http://stackoverflow.com/comment/90540330
score: 0
type: AnswerComment
type: Comment
has text: I can do it in two days.
comment on: http://stackoverflow.com/a/51787228

http://stackoverflow.com/comment/90257929
comment on: http://stackoverflow.com/q/51647037
score: 1
type: Comment
has text: when you `enumerate` through `f`, you're moving the file pointer. By the time you actually call `readlines` the filepointer points at the end of the file, so there is nothing left to read. Your loop does nothing anyway, so just remove it.
type: QuestionComment

http://stackoverflow.com/a/65174202
answers question: http://stackoverflow.com/q/51706256
has comment: http://stackoverflow.com/comment/123793985
downvote count: 0
has comment: http://stackoverflow.com/comment/117007219
has body: Well, Here is a workaround! Hope it works! text_element = driver_trader.find_element_by_xpath('xpath') text = '⚪' driver.execute_script("arguments[0].innerHTML = '{}'".format(text),text_element) text_element .send_keys('.') text_element .send_keys(Keys.BACKSPACE)
type: Answer
upvote count: 10
score: 10

http://stackoverflow.com/a/51785528
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51765234
has body: After you computed your distance, choose n and run: n = 5 outliers = [x[0] for x in sorted(enumerate(distances), key=lambda x: sum(x[1]**2)**0.5, reverse=True)[:n]] Now, outliers hold the index of the data points in Data which are furthest from their centroids. for outlier in outliers: print(Data[outlier])

http://stackoverflow.com/comment/90358621
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51697727
has text: Well as I'm sure you know, the *regular* way would be to load everything into one big numpy array and train the model from that. Since the size of your data makes that impossible, you are forced to use a generator to feed the data into your network. However I'm not aware of any easy way of doing so; what I would suggest involves creating your own custom generator, which unfortunately requires a significant amount of coding and debugging. If you're interested I could write an answer giving you some pointers on how to do so.... Maybe someone has some better idea.

http://stackoverflow.com/comment/90520219
has text: I want it to be within one line.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51781293

http://stackoverflow.com/comment/90528236
has text: @mrWiga What is the actual question here? How to be more lucky? You should not ignore such warnings until you need to upgrade. And even now, it makes a lot of sense to fix your code using Pandas 0.18.0 in order not to run into other (ignored?) incompatibility issues.
comment on: http://stackoverflow.com/q/51785209
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51722810
upvote count: 2
has comment: http://stackoverflow.com/comment/90425849
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51722790
score: 2
has body: The input shape is only defined on your very first layer. From this link Guide to Sequential modelling The model needs to know what input shape it should expect. For this reason, the first layer in a Sequential model (and only the first, because following layers can do automatic shape inference) needs to receive information about its input shape. There are several possible ways to do this:

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

http://stackoverflow.com/a/51646774
answers question: http://stackoverflow.com/q/51646529
upvote count: 5
downvote count: 0
has body: In Python 3.5+ we can get away with the following, ignoring problems from additional key clashes. k = 'Name' merged_lst = [{**a, **b} for a in lst_1 for b in lst_2 if a[k]==b[k]] The {**a, **b} is a neat way to unpack the two dictionaries being considered into a combined dictionary (I believe on a clash it uses the value from b instead of a). This is the only step that requires 3.5+. In Python 2.x with string keys a similar construct is dict(a, **b), though Guido frowns on it heavily. Other options are more verbose. Python list comprehensions allow you to easily iterate through what is effectively the cartesian product of lst_1 and lst_2 by using for twice. We only care about dictionaries with the same 'Name', hence the a[k]==b[k] bit. If you are allowed to clobber any of the dictionaries in lst_1 or lst_2, approaches involving dict.update() are probably faster. They might be anyway, though the syntax isn't as nice I don't think.
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90257654
has comment: http://stackoverflow.com/comment/90257904
has comment: http://stackoverflow.com/comment/90257626
has comment: http://stackoverflow.com/comment/90257759
has comment: http://stackoverflow.com/comment/90257477
type: Answer
accepted answer of: http://stackoverflow.com/q/51646529
has comment: http://stackoverflow.com/comment/90257687

http://stackoverflow.com/comment/90341537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51689860
score: 0
has text: So, the true question is: how to find the sum of `'9,7,4'`? (If you can do that, you can do the rest.) `split` the string, convert each fragment to an `int`, apply `sum`, convert back to a `str`ing.

http://stackoverflow.com/comment/121937974
comment on: http://stackoverflow.com/a/68992343
score: 0
type: AnswerComment
has text: I don't think this has much to do with the question (if they were missing the -dev package then they'd get errors at the C compiling stage)
type: Comment

http://stackoverflow.com/comment/90533599
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51787721
has text: Rkesh thank you so much! This is EXACTLY what I wanted!
type: AnswerComment

http://stackoverflow.com/q/51713512
type: UnansweredQuestion
has title: How to make Keras automatically load custom metrics
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90391006
has body: I'm using Keras with Cern ROOT and its analysis package TMVA. The way it works is that I use Keras to initialize the NN, then save it to a file, then TMVA loads that file in. The problem is that I am using custom metrics when setting up the neural network, and when doing this, Keras wants you to do something like models.load_model(model_path, custom_objects={"my_object":my_object}) Unfortunately, the way that TMVA takes arguments requires that I only supply the filename of the model file being used. However, based on the error messages that I am getting, it is clear that it is simply using Keras to load the model in. My question is, how do I force Keras to automatically load my custom objects in without having to use the above line, as this is incompatible with the package I'm trying to use.
tagged with: tensorflow
type: Question
tagged with: root-framework
has comment: http://stackoverflow.com/comment/90388652
score: 0
tagged with: keras

http://stackoverflow.com/q/51763182
has answer: http://stackoverflow.com/a/51763766
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90485987
type: Question
answer count: 2
tagged with: pyqt4
has body: I want to dynamically create and populate QTableWidgets on PyQt4. My goal is to display different sets of data on separated tables (placed on different tabs in a QTabWidget). The data sets names and their number are not predictable, I cannot pre-create the tables/tabs in Qt Designer. I did not find any other post about this matter, except for reproducing existing widgets (mostly QPushButtons but I apologize if this problem has already been brought up. As you can see on the picture below, I was able to create the tabs, give them a name dynamically (here let’s say tab_1, tab_2 and tab_3) and add widgets to them. However, when I try to populate the tables it turns out that I am populating the same table in my different tabs (the tables in each tab are referred as the same QTableWidget). Function: for i,s in enumerate(dataSets): tab_name = str(s) tab = QWidget() self.tabWidget.addTab(tab, tab_name) layout = QVBoxLayout() label_1=QLabel() spacerItem1 = QtGui.QSpacerItem(20, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) label_1.setText(u"Data set:") # Up to here, it looks like everything works fine self.Table_1="Table_%s" % str(i) #Table_1, Table_2, Table_3, ... self.Table_1 = QtGui.QTableWidget() self.Table_1.setMaximumSize(QtCore.QSize(16777215, 150)) self.Table_1.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.Table_1.setObjectName(_fromUtf8(str(self.Table_1))) self.Table_1.setColumnCount(0) self.Table_1.setRowCount(0) layout.addSpacing(20) layout.addWidget(label_1) layout.addWidget(self.Table_1) self.populateTable_1() self.tabWidget.setLayout(layout) The problem comes from these two lines as the name associated with the QtGui.QTableWidget() is self.Table_1 and not its value. self.Table_1="Table_%s" % str(i) #Table_1, Table_2, Table_3, ... self.Table_1 = QtGui.QTableWidget() I tried setattr as well, but without any success, the tables are created but I get an error when I call self.Table_1 to populate it. Dear Python Gurus, I thank you in advance…
possible better answer: http://stackoverflow.com/a/51764349
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90485883
has answer: http://stackoverflow.com/a/51764349
accepted answer: http://stackoverflow.com/a/51763766
tagged with: python
has title: Dynamically create/populate QTableWidgets in PyQt4
tagged with: qtablewidget

http://stackoverflow.com/comment/90319965
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51677734
score: 0
has text: @PM2Ring. I am, actually. I have never used defaultdict myself in the wild. I'll add something to the answer about that.

http://stackoverflow.com/q/51682341
has comment: http://stackoverflow.com/comment/90327981
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/68654018
has comment: http://stackoverflow.com/comment/90328073
tagged with: cookies
upvote count: 8
tagged with: urllib
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90328205
has title: How to send cookies with urllib
has answer: http://stackoverflow.com/a/68654018
has comment: http://stackoverflow.com/comment/90327669
score: 8
tagged with: python-3.x
has body: I'm attempting to connect to a website that requires you to have a specific cookie to access it. For the sake of this question, we'll call the cookie 'required_cookie' and the value 'required_value'. This is my code: import urllib import http.cookiejar cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) opener.addheaders = [('required_cookie', 'required_value'), ('User-Agent', 'Mozilla/5.0')] urllib.request.install_opener(opener) req = Request('https://www.thewebsite.com/') webpage = urlopen(req).read() print(webpage) I'm new to urllib so please answer me as a beginner
tagged with: python
has answer: http://stackoverflow.com/a/51682831
accepted answer: http://stackoverflow.com/a/51682831
tagged with: http

http://stackoverflow.com/a/51648297
has comment: http://stackoverflow.com/comment/90302674
has comment: http://stackoverflow.com/comment/90303085
upvote count: 2
has body: Try this: df['countDetails'] = '' count_dict = {} for index, row in df.iterrows(): count_dict.setdefault(row['Alphabets'], 0) count_dict[row['Alphabets']] = row['Count'] k= map(lambda x:{'id':x,'count':count_dict[x]}, count_dict) df.at[ index, 'countDetails'] = k
has comment: http://stackoverflow.com/comment/90265510
downvote count: 0
answers question: http://stackoverflow.com/q/51645940
has comment: http://stackoverflow.com/comment/90296387
type: Answer
score: 2

http://stackoverflow.com/q/51651063
answer count: 1
has title: Dockerfile run scrapy crawl command in a folder
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51652321
has comment: http://stackoverflow.com/comment/90265724
tagged with: dockerfile
has comment: http://stackoverflow.com/comment/90265503
has comment: http://stackoverflow.com/comment/90265607
has comment: http://stackoverflow.com/comment/90265791
score: 3
downvote count: 0
tagged with: scrapy
has comment: http://stackoverflow.com/comment/90265766
type: Question
tagged with: docker
upvote count: 3
has body: I got a scrapy spider which can be run in terminal with scrapy crawl estate in the tutorial folder. How do I use the run command in Dockerfile to cd to the tutorial folder and run it? My Dockerfile without the RUN cd: FROM ubuntu:18.04 FROM python:3.6-onbuild RUN apt-get update &amp;&amp;apt-get upgrade -y&amp;&amp; apt-get install python-pip -y RUN pip install --upgrade pip RUN pip install scrapy WORKDIR /usr/local/bin COPY scrapy_estate/tutorial/tutorial ./ COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 80

http://stackoverflow.com/q/51654117
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90271569
duplicate of: http://stackoverflow.com/q/11709079
upvote count: 1
has comment: http://stackoverflow.com/comment/90271544
type: Question
accepted answer: http://stackoverflow.com/a/51654176
score: -1
has body: I have tried all the StackOverflow solutions for similar questions, and could`t find anything. I have this snippet of code and I need to extract the text between html tags, everything between > and &lt; . word = "div class="name"&gt; Text_I_Want_To_Extract &lt;/div&gt;" m = re.search('&gt;(.+)&lt;', word) print (m) I have tried various regex expressions but I failed. I always get empty result. I am guessing it is because I am extracting everything between > and &lt; symbols. Did anyone had this kind of problems with Python 3 ?
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/90271628
answer count: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/90271652
has title: Python 3 Regex extract part of string
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/159118
downvote count: 2
has answer: http://stackoverflow.com/a/51654176
tagged with: python
duplicate of: http://stackoverflow.com/q/159118

http://stackoverflow.com/q/51656964
downvote count: 1
linked to: http://stackoverflow.com/q/1504717
has comment: http://stackoverflow.com/comment/90277683
tagged with: immutability
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90278255
has comment: http://stackoverflow.com/comment/90277754
type: UnansweredQuestion
has title: How can identical strings be different objects in Python 3.5.3?
tagged with: python
has comment: http://stackoverflow.com/comment/90277692
has answer: http://stackoverflow.com/a/51657048
score: 2
has body: I'm setting up pytest for a flask app. In one of my tests, I make an assertion on a returned JSON data structure. res = flask_app.get("/api/list_databases") # type: flask.wrappers.Response assert res.json["status"] is "success" Note that status does not refer to the HTTP status code in this context. It's an application specific status attribute. This assertion fails when I run the test. AssertionError: assert 'success' is 'success' I know I am using reference equality testing here, which is not strictly necessary, but this error got me very curious. As in, how is this possible? If I do id(x) on both, I see they have different object id's. They are both instance of str (using type(x)). But from my (limited) understanding of Python, the following applies: All strings are made up of unicode codepoints. Before they become strings (e.g. when they are read from disk or network) they are bytes and must be parsed with a specified (or default?) character encoding to become str instances. As a result, once initialized, a string will be made up of unicode codepoints in whatever internal form the Python interpreter deems useful. This is different from Ruby, where a string exists together with encoding meta data. As such, you can have both ISO 8859-1 strings and UTF-8 strings side by side. Seeing as strings are "normalized" in this way, it is impossible for the string føøbar to have two different byte representations within the Python interpreter, even if it's read from two different text files, with different encodings. When the byte representation cannot differ, that means these two strings are backed by the exact same sequence of bytes. Strings in Python are immutable. Because of this, the Python interpreter will not create multiple instances of the same string. Instead, new references will point to the first str object. This is wrong. See answers. Strings may be interned in some cases, but that's a CPython optimization, not part of the language specification. Empirical evide…
has comment: http://stackoverflow.com/comment/90278288
type: Question
tagged with: string
has comment: http://stackoverflow.com/comment/90277801
has comment: http://stackoverflow.com/comment/90277861
favorite count: 0
upvote count: 3
duplicate of: http://stackoverflow.com/q/1504717
answer count: 1

http://stackoverflow.com/a/51711457
has comment: http://stackoverflow.com/comment/90385669
has comment: http://stackoverflow.com/comment/90385891
answers question: http://stackoverflow.com/q/51710706
has body: Seems like the length of x_train and y_train is not equal. Check their lengths. len(x_train) len(y_train)
score: 0
type: Answer

http://stackoverflow.com/comment/90285291
type: QuestionComment
has text: Can you share your python code?
comment on: http://stackoverflow.com/q/51660901
score: 0
type: Comment

http://stackoverflow.com/q/51717080
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/90395864
has comment: http://stackoverflow.com/comment/90395990
type: Question
has comment: http://stackoverflow.com/comment/90395460
has title: Most efficient way to add "show results within X miles of zip code" filter to website
downvote count: 0
has body: I am trying to add a "show results within X miles of zip code" filter to my django site. I am using a file with all US zip codes in the format ZIP,LATITUDE,LONGITUDE\n (https://gist.github.com/erichurst/7882666), I plan on having a function get the user entered zip code, get the lat and long of that zip code from this file and then run some calculations to find all zip codes within a certain distance. My question is about the most efficient way to do this. Is saving this long file as a .txt, storing it on a server and having my website access this file and run these commands on the fly when a user uses the filter the best way of doing this? Will this cause a long load time?
has comment: http://stackoverflow.com/comment/90396238
favorite count: 0
tagged with: python
score: 1
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/90395461
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90395792

http://stackoverflow.com/comment/90474314
type: QuestionComment
has text: why I cannot attach the image??
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51757428

http://stackoverflow.com/q/51662051
has answer: http://stackoverflow.com/a/51662408
type: Question
has comment: http://stackoverflow.com/comment/90288243
has body: I want to call a class attribute and append it to a list. Here is a simple script: class class_1(): def __init__(self): self.x = np.array([0, 0]) def update(self): self.x += 1 return self.x cl_1 = class_1() a = [] for i in range(3): y = cl_1.update() print(y) a.append(y) print(a) # output: [1 1] [2 2] [3 3] [array([3, 3]), array([3, 3]), array([3, 3])] but I expect [array([1, 1]), array([2, 2]), array([3, 3])] as the final value of list a. I checked that there is no problem with python numbers: class class_2(): def __init__(self): self.x = 0 def update(self): self.x += 1 return self.x cl_2 = class_2() a = [] for i in range(3): y = cl_2.update() print(y) a.append(y) print(a) #output 1 2 3 [1, 2, 3]
accepted answer: http://stackoverflow.com/a/51662408
has comment: http://stackoverflow.com/comment/90288050
has comment: http://stackoverflow.com/comment/90287923
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90287908
has comment: http://stackoverflow.com/comment/90288091
tagged with: python
has comment: http://stackoverflow.com/comment/90287906
has title: Python appending class attribute with numpy array type
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/90288273
has comment: http://stackoverflow.com/comment/90287988
has comment: http://stackoverflow.com/comment/90287807
upvote count: 1

http://stackoverflow.com/comment/112774691
comment on: http://stackoverflow.com/q/51793396
score: 0
has text: it seems 7zip is able to open general dll or pyd file and mapped them according to section categories (data, code) but they are still in binaries.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90298637
has text: I have a lot of attributes and I'm trying to avoid writing a lot of attribute initializations. Your suggestion is to write a lot of `if` statements instead. No, thank you.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51658365

http://stackoverflow.com/a/51726543
has comment: http://stackoverflow.com/comment/90418557
has comment: http://stackoverflow.com/comment/90416221
has comment: http://stackoverflow.com/comment/90418266
type: Answer
has body: Try to update pip to beta version pip install -U --pre pip If it does't help try using easy_install Another solution: run a new cmd.exe console chcp it will show the system default code, for example 936. open Lib/site-package/pip/compat/init.py around 75 line, change return s.decode('utf_8') to return s.decode('cp936') It's just a workaround from https://github.com/pypa/pip/issues/4251
score: 1
has comment: http://stackoverflow.com/comment/90417007
has comment: http://stackoverflow.com/comment/90417143
upvote count: 1
answers question: http://stackoverflow.com/q/51723751
downvote count: 0

http://stackoverflow.com/q/51662305
has title: JPEG2000 API for Python
has body: I am about to run a simulation in which I need to encode and decode image files with JPEG2000. I need an API that gives me flexibility to tune coding parameters and set output quality. Is there any API for Python to do so?
has comment: http://stackoverflow.com/comment/90288306
downvote count: 0
has comment: http://stackoverflow.com/comment/90288221
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: jpeg2000
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51724962
score: 0
has body: 7 CRM TRF 500509 23/01/2012 JEWEL-NANO-M 1,000.00 0.00 71,700.00 Dr. I want to extract the value 'CRM' only, but when i use 'TD' tag in beautifulsoup, it extracts all the other text also.
has comment: http://stackoverflow.com/comment/90410770
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/90410311
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/90410292
answer count: 0
has comment: http://stackoverflow.com/comment/90410166
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90410517
has title: Extracting a particular text from html tags using Python's BeautifulSoup library
has comment: http://stackoverflow.com/comment/90410208

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

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51679456
tags question: http://stackoverflow.com/q/51654961
tags question: http://stackoverflow.com/q/51696116
tags question: http://stackoverflow.com/q/51775331
tags question: http://stackoverflow.com/q/51762173
tags question: http://stackoverflow.com/q/51726827
tags question: http://stackoverflow.com/q/51787413
tags question: http://stackoverflow.com/q/51663042
tags question: http://stackoverflow.com/q/51747255
tags question: http://stackoverflow.com/q/51740689
tags question: http://stackoverflow.com/q/51686181
tags question: http://stackoverflow.com/q/51759862
tags question: http://stackoverflow.com/q/51717710
tags question: http://stackoverflow.com/q/51662950
tags question: http://stackoverflow.com/q/51697436
tags question: http://stackoverflow.com/q/51725642
tags question: http://stackoverflow.com/q/51740610
tags question: http://stackoverflow.com/q/51656477
tags question: http://stackoverflow.com/q/51717170
tags question: http://stackoverflow.com/q/51678994
tags question: http://stackoverflow.com/q/51712015
tags question: http://stackoverflow.com/q/51693536
tags question: http://stackoverflow.com/q/51791455
tags question: http://stackoverflow.com/q/51707288
tags question: http://stackoverflow.com/q/51710053
type: Tag
tags question: http://stackoverflow.com/q/51682594
tags question: http://stackoverflow.com/q/51692955
tags question: http://stackoverflow.com/q/51775268
tags question: http://stackoverflow.com/q/51772361
tags question: http://stackoverflow.com/q/51690580
tags question: http://stackoverflow.com/q/51717527
tags question: http://stackoverflow.com/q/51747086
tags question: http://stackoverflow.com/q/51663212
tags question: http://stackoverflow.com/q/51749817
tags question: http://stackoverflow.com/q/51653495
tags question: http://stackoverflow.com/q/51732253
tags question: http://stackoverflow.com/q/51762006
tags question: http://stackoverflow.com/q/51660571
tags question: http://stackoverflow.com/q/51643680
tags question: http://stackoverflow.com/q/51737750
tags question: http://stackoverflow.com/q/51640105
tags question: http://stackoverflow.com/q/51769824
tags question: http://stackoverflow.com/q/51684793
tags question: http://stackoverflow.com/q/51794560
tags question: http://stackoverflow.com/q/51660036
tags question: http://stackoverflow.com/q/51698918
tags question: http://stackoverflow.com/q/51729530
tags question: http://stackoverflow.com/q/51719205
tags question: http://stackoverflow.com/q/51768080
tags question: http://stackoverflow.com/q/51670846
tags question: http://stackoverflow.com/q/51700954
tags question: http://stackoverflow.com/q/51749388

http://stackoverflow.com/a/51708007
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/90377052
accepted answer of: http://stackoverflow.com/q/51707847
has body: For python 3.6: import random my_randoms = random.choices(range(1,100), k=10000) print(my_randoms) For older would still need to use loops: my_randoms = [random.randrange(100) for x in range(10000)]
has comment: http://stackoverflow.com/comment/90377378
answers question: http://stackoverflow.com/q/51707847
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/51647919
score: 1
answers question: http://stackoverflow.com/q/51647767
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90259556
has body: x = {"OMIM:614373": ["10280"], "OMIM:614370": ["6439", "1439", "6440", "21"], "OMIM:614371": ["30835"], "OMIM:614376": ["57728"]} for i,j in x.items(): for items in x[i]: print (i,items) this also can help you, same idea of arman's answer in general.

http://stackoverflow.com/comment/90280304
type: Comment
has text: No, it should be `list` as it is above. The `defaultdict` will call whatever that first arg is if the key doesn't exist, as in: `list()` and assign it as the value.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51658027

http://stackoverflow.com/a/51773477
upvote count: 2
type: Answer
has body: round(X) in Matlab rounds each element of X. If you feed it a vector, it returns a vector.
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51773314

http://stackoverflow.com/a/51778585
downvote count: 0
has comment: http://stackoverflow.com/comment/90515529
upvote count: 2
type: Answer
score: 2
has body: So long as we are giving alternatives, can also translate df.Grade.str.translate(str.maketrans({'%':''})).astype(float)
answers question: http://stackoverflow.com/q/51778480
has comment: http://stackoverflow.com/comment/90515509

http://stackoverflow.com/comment/90412624
score: 0
comment on: http://stackoverflow.com/q/51726029
type: Comment
type: QuestionComment
has text: I think this says it all. https://stackoverflow.com/questions/27697766/understanding-min-df-and-max-df-in-scikit-countvectorizer

http://stackoverflow.com/comment/90386751
score: 0
type: Comment
type: QuestionComment
has text: What did you do to get this error?
comment on: http://stackoverflow.com/q/51712642

voronoi
tags question: http://stackoverflow.com/q/51708955
tag name: voronoi
type: Tag

http://stackoverflow.com/a/51673935
type: Answer
has body: You forgot a closing bracket on this line list1.append(df1Lat.iloc[i]; Replace it with this: list1.append(df1Lat.iloc[i])
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51673847
accepted answer of: http://stackoverflow.com/q/51673847

http://stackoverflow.com/comment/90320972
comment on: http://stackoverflow.com/a/51678759
type: AnswerComment
score: 0
type: Comment
has text: Oh right, how could I output to a file everytime Zi0 changes? Is it my placement of the file writer that is wrong?

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51767548
tags question: http://stackoverflow.com/q/51701986
tags question: http://stackoverflow.com/q/51672962
tags question: http://stackoverflow.com/q/51657157
tags question: http://stackoverflow.com/q/51747177
tags question: http://stackoverflow.com/q/51768933
tags question: http://stackoverflow.com/q/51722119
tags question: http://stackoverflow.com/q/51750501
tags question: http://stackoverflow.com/q/51686198
tags question: http://stackoverflow.com/q/51764272
tags question: http://stackoverflow.com/q/51705314
tags question: http://stackoverflow.com/q/51711631
tags question: http://stackoverflow.com/q/51771935
tags question: http://stackoverflow.com/q/51687692
tags question: http://stackoverflow.com/q/51763182
tags question: http://stackoverflow.com/q/51784783
tags question: http://stackoverflow.com/q/51784292
tags question: http://stackoverflow.com/q/51733668
tags question: http://stackoverflow.com/q/51755187
tags question: http://stackoverflow.com/q/51652527
tags question: http://stackoverflow.com/q/51664300
tags question: http://stackoverflow.com/q/51700517
tags question: http://stackoverflow.com/q/51768266
tags question: http://stackoverflow.com/q/51658170
tags question: http://stackoverflow.com/q/51644685
tag name: pyqt
tags question: http://stackoverflow.com/q/51741851
tags question: http://stackoverflow.com/q/51714031
tags question: http://stackoverflow.com/q/51787219
tags question: http://stackoverflow.com/q/51720725
tags question: http://stackoverflow.com/q/51769828
tags question: http://stackoverflow.com/q/51686635
tags question: http://stackoverflow.com/q/51716606

http://stackoverflow.com/q/51707313
type: Question
tagged with: argparse
tagged with: path
has body: I have this script in python 3.7: pars = argparse.ArgumentParser(prog='copy dirs script', description="à copier MSRE localment:", epilog="Comme ça on copie les repertoires") pars.add_argument("-o", "--output", action='store_const', default=destination_file, const=destination_file1, help="the destination dirctory is the curently working dirctory") pars.add_argument("-a", "--arch", choices=("all", "i386", "x86_64"), type = lambda s : s.lower(), help="Targeted check architecture: 32b, 64b, All") pars.add_argument("-p", "--platform", choices=("all", "windows", "linux"), type = lambda s : s.lower(), help="Targeted check platform: Windows, Linux, All") args = pars.parse_args() I want to parse the output in the command line, for example: python script.py -o C:/Users/michael/Documents/install -a all -p windows I don't know how to store the output into a variable. How can I proceed?
tagged with: python
has title: parse a path like and an argument
answer count: 2
tagged with: file
downvote count: 3
has comment: http://stackoverflow.com/comment/90376307
has answer: http://stackoverflow.com/a/51707448
score: -3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51707433
upvote count: 0
has comment: http://stackoverflow.com/comment/90375390
favorite count: 0
accepted answer: http://stackoverflow.com/a/51707448
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51707433

http://stackoverflow.com/comment/90273587
has text: Someone else had written this code and I need to fix it. `userid` in the `UserRating` model should use ForeignKey, thats true. What about the others?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51654961
score: 0

http://stackoverflow.com/comment/90498906
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51770165
type: Comment
has text: I guess the transformation to pandas will potentially fail due to memory issues ... the reason why I started to use Dask ...

http://stackoverflow.com/comment/90546672
comment on: http://stackoverflow.com/q/51794529
type: QuestionComment
has text: `turtle.Turtle()` to instantiate a Turtle (what a phrase) - use parentheses ... turtle.Turtle is the class, not an instance of it
score: 1
type: Comment

python
tags question: http://stackoverflow.com/q/51784033
tags question: http://stackoverflow.com/q/51772115
tags question: http://stackoverflow.com/q/51783374
tags question: http://stackoverflow.com/q/51741320
tags question: http://stackoverflow.com/q/51780924
tags question: http://stackoverflow.com/q/51758611
tags question: http://stackoverflow.com/q/51642220
tags question: http://stackoverflow.com/q/51797718
tags question: http://stackoverflow.com/q/51797925
tags question: http://stackoverflow.com/q/51752903
tags question: http://stackoverflow.com/q/51742768
tags question: http://stackoverflow.com/q/51654726
tags question: http://stackoverflow.com/q/51717881
tags question: http://stackoverflow.com/q/51749914
tags question: http://stackoverflow.com/q/51737205
tags question: http://stackoverflow.com/q/51700754
tags question: http://stackoverflow.com/q/51692286
tags question: http://stackoverflow.com/q/51736714
tags question: http://stackoverflow.com/q/51749435
tags question: http://stackoverflow.com/q/51771415
tags question: http://stackoverflow.com/q/51767711
tags question: http://stackoverflow.com/q/51778765
tags question: http://stackoverflow.com/q/51665533
tags question: http://stackoverflow.com/q/51753343
tags question: http://stackoverflow.com/q/51692080
tags question: http://stackoverflow.com/q/51791804
tags question: http://stackoverflow.com/q/51788896
tags question: http://stackoverflow.com/q/51664719
tags question: http://stackoverflow.com/q/51697205
tags question: http://stackoverflow.com/q/51768254
tags question: http://stackoverflow.com/q/51744751
tags question: http://stackoverflow.com/q/51691299
tags question: http://stackoverflow.com/q/51695492
tags question: http://stackoverflow.com/q/51708565
tags question: http://stackoverflow.com/q/51758634
tags question: http://stackoverflow.com/q/51699867
tags question: http://stackoverflow.com/q/51658120
tags question: http://stackoverflow.com/q/51644921
tags question: http://stackoverflow.com/q/51662228
tags question: http://stackoverflow.com/q/51753549
tags question: http://stackoverflow.com/q/51715561
tags question: http://stackoverflow.com/q/51692985
tags question: http://stackoverflow.com/q/51776054
tags question: http://stackoverflow.com/q/51642951
tags question: http://stackoverflow.com/q/51776501
tags question: http://stackoverflow.com/q/51666361
tags question: http://stackoverflow.com/q/51657959
tags question: http://stackoverflow.com/q/51674644
tags question: http://stackoverflow.com/q/51698662
tags question: http://stackoverflow.com/q/51663438
tags question: http://stackoverflow.com/q/51797066
tags question: http://stackoverflow.com/q/51663071
tags question: http://stackoverflow.com/q/51769824
tags question: http://stackoverflow.com/q/51756712
tags question: http://stackoverflow.com/q/51646152
tags question: http://stackoverflow.com/q/51750762
tags question: http://stackoverflow.com/q/51736178
tags question: http://stackoverflow.com/q/51722090
tags question: http://stackoverflow.com/q/51793744
tags question: http://stackoverflow.com/q/51663651
tags question: http://stackoverflow.com/q/51766679
tags question: http://stackoverflow.com/q/51783527
tags question: http://stackoverflow.com/q/51739413
tags question: http://stackoverflow.com/q/51793009
tags question: http://stackoverflow.com/q/51715423
tags question: http://stackoverflow.com/q/51744409
tags question: http://stackoverflow.com/q/51743157
tags question: http://stackoverflow.com/q/51718472
tags question: http://stackoverflow.com/q/51793908
tags question: http://stackoverflow.com/q/51779151
tags question: http://stackoverflow.com/q/51786133
tags question: http://stackoverflow.com/q/51722266
tags question: http://stackoverflow.com/q/51695315
tags question: http://stackoverflow.com/q/51679311
tags question: http://stackoverflow.com/q/51695970
tags question: http://stackoverflow.com/q/51788344
tags question: http://stackoverflow.com/q/51746327
tags question: http://stackoverflow.com/q/51678830
tags question: http://stackoverflow.com/q/51686862
tags question: http://stackoverflow.com/q/51709034

http://stackoverflow.com/a/51678381
downvote count: 1
type: Answer
upvote count: 4
score: 3
has body: You say you will use scipy for clustering, so I assume that means you will use the function scipy.cluster.hierarchy.linkage. linkage accepts the distance data in "condensed" form, so you don't have to create the full symmetric distance matrix. (See, e.g., How does condensed distance matrix work? (pdist), for a discussion on the condensed form.) So all you have to do is get obj_distances.values() into a known order and pass that to linkage. That's what is done in the following snippet: from scipy.cluster.hierarchy import linkage, dendrogram obj_distances = { ('obj2', 'obj3'): 1.8, ('obj3', 'obj1'): 1.95, ('obj1', 'obj4'): 2.5, ('obj1', 'obj2'): 2.0, ('obj4', 'obj2'): 2.1, ('obj3', 'obj4'): 1.58, } # Put each key pair in a canonical order, so we know that if (a, b) is a key, # then a &lt; b. If this is already true, then the next three lines can be # replaced with # sorted_keys, distances = zip(*sorted(obj_distances.items())) # Note: we assume there are no keys where the two objects are the same. keys = [sorted(k) for k in obj_distances.keys()] values = obj_distances.values() sorted_keys, distances = zip(*sorted(zip(keys, values))) # linkage accepts the "condensed" format of the distances. Z = linkage(distances) # Optional: create a sorted list of the objects. labels = sorted(set([key[0] for key in sorted_keys] + [sorted_keys[-1][-1]])) dendrogram(Z, labels=labels) The dendrogram:
has comment: http://stackoverflow.com/comment/90339054
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51674401
answers question: http://stackoverflow.com/q/51674401

c++
tags question: http://stackoverflow.com/q/51649109
tags question: http://stackoverflow.com/q/51703614
tags question: http://stackoverflow.com/q/51682164
tags question: http://stackoverflow.com/q/51745946
tags question: http://stackoverflow.com/q/51681185
tags question: http://stackoverflow.com/q/51722309
type: Tag
tags question: http://stackoverflow.com/q/51648285
tags question: http://stackoverflow.com/q/51797066
tags question: http://stackoverflow.com/q/51727482
tags question: http://stackoverflow.com/q/51667821
tags question: http://stackoverflow.com/q/51729698
tags question: http://stackoverflow.com/q/51681667
tags question: http://stackoverflow.com/q/51729187
tags question: http://stackoverflow.com/q/51758076
tags question: http://stackoverflow.com/q/51762408
tags question: http://stackoverflow.com/q/51784448
tags question: http://stackoverflow.com/q/51793690
tags question: http://stackoverflow.com/q/51672869
tags question: http://stackoverflow.com/q/51641780
tags question: http://stackoverflow.com/q/51701318
tags question: http://stackoverflow.com/q/51656818
tag name: c++
tags question: http://stackoverflow.com/q/51769336
tags question: http://stackoverflow.com/q/51660614
tags question: http://stackoverflow.com/q/51784507

http://stackoverflow.com/comment/90415860
type: QuestionComment
has text: After each =, it goes to the line. The input and output files looks the same
comment on: http://stackoverflow.com/q/51726907
score: 0
type: Comment

http://stackoverflow.com/comment/90291436
comment on: http://stackoverflow.com/a/51663408
score: 0
has text: This makes a lot more sense to me, thank you very much! Last thing though, how would you go about saving this new `game_df` with our calculated features? Ideally like I had before in my code where I could just append each row to a list. The only thing that comes to mind for me is itterows, ha!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90288490
has text: which version of python are you using? as Mark says, it's most like a problem with your IDE
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51662299
type: AnswerComment

http://stackoverflow.com/comment/90489730
score: 3
has text: But two equal numbers/string are *not* per se the same object: for example `a = "foobar"; b = "foo"; b += "bar"; a is b` will return `False`.
type: QuestionComment
comment on: http://stackoverflow.com/q/51765551
type: Comment

http://stackoverflow.com/q/51764354
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/51764494
has answer: http://stackoverflow.com/a/51764614
possible better answer: http://stackoverflow.com/a/51764480
downvote count: 2
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51764494
has body: I have the following json: { "request": { "id": "123", "url": "/aa/bb/cc", "method": "GET", "timestamp": "2018-08-09T08:41:38.432Z" }, "response": { "status": { "code": 200, "message": "OK" }, "items": [ { "id": "aaa", "name": "w1" }, { "id": "bbb", "name": "w2" }, { "id": "ccc", "name": "w3" } ] } } I need to loop over items and print each name. I've tried the following code which doesn't work. response = requests.get(url) data = json.loads(response.content) for group in data['response']['items']: print data['response']['items'][group]['name'] When i replace group with 0 for example, I can access the first name: data['response']['items'][0]['name'] However, I don't know in advanced how many elements are in the array.
favorite count: 0
has comment: http://stackoverflow.com/comment/90487385
tagged with: python
has title: Extracting elements from json in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51764480
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/51645607
downvote count: 0
has comment: http://stackoverflow.com/comment/90255318
type: Answer
upvote count: 1
has body: Conversion to float is not very informative here. You can however convert the datetime object to a timestamp object. Considering that row[0] holds a datetime object, something like below should work: import time timestamp = time.mktime((row[0].timetuple()) timestamp would be a UTC timestamp generated from your datetime object. Update: Observed that row[0] holds a date in string format. &gt;&gt;&gt; import time &gt;&gt;&gt; ts = time.strptime("10/10/2018", "%m/%d/%Y") &gt;&gt;&gt; time.mktime(ts) &gt;&gt;&gt; 1539109800.0
score: 1
answers question: http://stackoverflow.com/q/51645542

http://stackoverflow.com/a/51744894
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90449686
type: Answer
has body: Select necessary observations and then apply aggregation: df[df.ID != df.Period].groupby('ID').sum() Output: Period Variable ID 1 2 12 2 3 18
has comment: http://stackoverflow.com/comment/90449553
answers question: http://stackoverflow.com/q/51744769
downvote count: 0

http://stackoverflow.com/a/51765627
has comment: http://stackoverflow.com/comment/90493362
has comment: http://stackoverflow.com/comment/90497737
score: 0
has body: Returns a dict-like {chosenric : timeseries} def get_variable(riclist): return {chosenric : ek.get_timeseries(rics=chosenric, start_date=2018-01-01, fields="CLOSE") for chosenric in riclist}
has comment: http://stackoverflow.com/comment/90498608
has comment: http://stackoverflow.com/comment/90494372
has comment: http://stackoverflow.com/comment/90494923
type: Answer
has comment: http://stackoverflow.com/comment/90495473
has comment: http://stackoverflow.com/comment/90496822
answers question: http://stackoverflow.com/q/51765436

http://stackoverflow.com/q/51728071
has comment: http://stackoverflow.com/comment/90418631
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90417606
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90417677
upvote count: 1
tagged with: tensorflow
has title: How can I log the IDs of the training samples with Keras model.fit?
has comment: http://stackoverflow.com/comment/90417210
type: Question
has body: I currently have reproducibility issues, although I set the seeds. I know that the model is initialized the same way (checked via inspection of model.save("initial.h5") with h5dump and meld). The next thing for me to check if the training samples are used in the same order. Hence I would like to log them. I train via model.fit(dataset['train']['X'], dataset['train']['y'], epochs=cfg['model']['nb_epochs'], batch_size=cfg['model']['batch_size'], validation_split=cfg['model']['validation_split'], callbacks=[checkpoint], class_weight=cw) I can also add dataset['train']['id']. I would like to get a txt file which contains the list of IDs being used, e.g. for a batch-size of 32, a training dataset length of 765 and 5 epochs I would expect 765 * 5 = 3825 lines in the txt file where each ID roughly appears 5 times and the first 32 elements are the IDs from the first batch. Is that possible?
tagged with: reproducible-research
has comment: http://stackoverflow.com/comment/90417584
has comment: http://stackoverflow.com/comment/90416866
linked to: http://stackoverflow.com/q/51715573
downvote count: 0
score: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90417084
has comment: http://stackoverflow.com/comment/90416839

http://stackoverflow.com/a/51699030
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90359620
answers question: http://stackoverflow.com/q/51699017
type: Answer
upvote count: 2
has body: You're out by 1, right? So change the index by 1: def getMonth(month): try: list_of_month_index0 = ['Jan', 'Feb','March','April','May','June','July','Aug','Sep','Oct','Nov','Dec'] if month &lt; 1 or month &gt; len(list_of_month_index0): return 'ERROR: out of range!' return list_of_month_index0[month - 1] except: return 'ERROR: invalid number!'
has comment: http://stackoverflow.com/comment/90360835
has comment: http://stackoverflow.com/comment/90359584

http://stackoverflow.com/q/51672327
has answer: http://stackoverflow.com/a/51688654
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63945053
score: 1
tagged with: scikit-image
tagged with: image-processing
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/63945053
upvote count: 1
has title: skimage peak local max finds multiple spots in close proximity due to image impurities
has body: I have an image that looks like this, with some larger impurities/overexposed spots. It generally doesn't matter if they're detected, as measurements are time resolved, so they'll be removed later on. However, I'm interested in as many as the small dots as possible - as fast as possible. skimage.feature.peak_local_max does a really good job, and is very easy to use on different data, because there's no need to play around much with intensity scaling. The problem is though, that large spots for some reason give very strong positives. import skimage.io import skimage.feature import skimage.morphology from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt def plotRoi(spots, img_ax, color, radius): patches = [] for spot in spots: y, x = spot c = plt.Circle((x, y), radius) patches.append(c) img_ax.add_collection(PatchCollection(patches, facecolors = "None", edgecolors = color, alpha = 0.3, linewidths = 1)) img = skimage.io.imread("/Path/to/img.png") img = img[:,:,0] fig, ax = plt.subplots() ax.imshow(img, cmap = "Greys") spots = skimage.feature.peak_local_max(img, min_distance = 0, exclude_border = True, num_peaks = 2000) plotRoi(spots, ax, "red", radius = 10) plt.show() And searching for thousands of spots in some images lead to a large number of local maxima being pretty much on top of each other. Is there a way to avoid this, e.g. by applying a filter on image loading, as I would prefer not to move to a slower type of peak fitting?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51688654
tagged with: python

http://stackoverflow.com/a/51694108
answers question: http://stackoverflow.com/q/51694073
has body: Use max to get item with largest value: lst = [('car crash killed', 95), ('car accident crash', 86), ('disaster police car', 45)] print(max(lst, key=lambda x: x[1])[0]) # car crash killed Now, to return all max value items, basically apply the same logic. Get max_value and return all items with the max_value using a list-comprehension like below: lst = [('car crash killed', 95), ('car accident crash', 95), ('disaster police car', 45)] max_value = max(lst, key=lambda x: x[1])[1] print([x[0] for x in lst if x[1] == max_value]) # ['car crash killed', 'car accident crash']
has comment: http://stackoverflow.com/comment/90349538
has comment: http://stackoverflow.com/comment/90349670
downvote count: 0
score: 2
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90349598

http://stackoverflow.com/comment/90457550
type: AnswerComment
has text: You mean like @piRSquared had? :)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51748395

http://stackoverflow.com/comment/90504030
has text: What is your expected output ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51772564
score: 0

pandas
tags question: http://stackoverflow.com/q/51752366
tags question: http://stackoverflow.com/q/51741786
tags question: http://stackoverflow.com/q/51720348
tags question: http://stackoverflow.com/q/51797259
tags question: http://stackoverflow.com/q/51790883
tags question: http://stackoverflow.com/q/51696579
tags question: http://stackoverflow.com/q/51795156
tags question: http://stackoverflow.com/q/51720306
tags question: http://stackoverflow.com/q/51667626
tags question: http://stackoverflow.com/q/51717535
tags question: http://stackoverflow.com/q/51712285
tags question: http://stackoverflow.com/q/51680548
tags question: http://stackoverflow.com/q/51705941
tags question: http://stackoverflow.com/q/51754608
tags question: http://stackoverflow.com/q/51744786
tags question: http://stackoverflow.com/q/51765983
tags question: http://stackoverflow.com/q/51753964
tags question: http://stackoverflow.com/q/51733456
tags question: http://stackoverflow.com/q/51711213
tags question: http://stackoverflow.com/q/51700754
tags question: http://stackoverflow.com/q/51721851
tags question: http://stackoverflow.com/q/51791707
tags question: http://stackoverflow.com/q/51753549
tags question: http://stackoverflow.com/q/51783225
tags question: http://stackoverflow.com/q/51773156
tags question: http://stackoverflow.com/q/51749235
tags question: http://stackoverflow.com/q/51768947
tags question: http://stackoverflow.com/q/51657853
tags question: http://stackoverflow.com/q/51658015
tags question: http://stackoverflow.com/q/51651243
tags question: http://stackoverflow.com/q/51767709
tags question: http://stackoverflow.com/q/51761498
tags question: http://stackoverflow.com/q/51707544
tags question: http://stackoverflow.com/q/51791736
tags question: http://stackoverflow.com/q/51707384
tags question: http://stackoverflow.com/q/51650634
tags question: http://stackoverflow.com/q/51783371
tags question: http://stackoverflow.com/q/51645195
tags question: http://stackoverflow.com/q/51642102
tags question: http://stackoverflow.com/q/51644467
tags question: http://stackoverflow.com/q/51769287
tags question: http://stackoverflow.com/q/51668808
tags question: http://stackoverflow.com/q/51691265
tags question: http://stackoverflow.com/q/51750164
tags question: http://stackoverflow.com/q/51705671
tags question: http://stackoverflow.com/q/51755504
tags question: http://stackoverflow.com/q/51797523
tags question: http://stackoverflow.com/q/51686216
tags question: http://stackoverflow.com/q/51762754
tags question: http://stackoverflow.com/q/51749143
tags question: http://stackoverflow.com/q/51787441
tags question: http://stackoverflow.com/q/51713702
tags question: http://stackoverflow.com/q/51795186
tags question: http://stackoverflow.com/q/51642699
tags question: http://stackoverflow.com/q/51656264
tags question: http://stackoverflow.com/q/51650166
tags question: http://stackoverflow.com/q/51752413
tags question: http://stackoverflow.com/q/51766031
tags question: http://stackoverflow.com/q/51787945
tags question: http://stackoverflow.com/q/51676783
tags question: http://stackoverflow.com/q/51723928
tags question: http://stackoverflow.com/q/51749872
tags question: http://stackoverflow.com/q/51757735
tags question: http://stackoverflow.com/q/51715782
tags question: http://stackoverflow.com/q/51689103
tags question: http://stackoverflow.com/q/51734215
tags question: http://stackoverflow.com/q/51797491
tags question: http://stackoverflow.com/q/51690079
tags question: http://stackoverflow.com/q/51662445
tags question: http://stackoverflow.com/q/51705502
tags question: http://stackoverflow.com/q/51792440
tags question: http://stackoverflow.com/q/51748650
tags question: http://stackoverflow.com/q/51697502
tags question: http://stackoverflow.com/q/51713340
tags question: http://stackoverflow.com/q/51789766
tags question: http://stackoverflow.com/q/51786633
tags question: http://stackoverflow.com/q/51723899
tags question: http://stackoverflow.com/q/51754737
tags question: http://stackoverflow.com/q/51798537
tags question: http://stackoverflow.com/q/51745439

http://stackoverflow.com/comment/90293201
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51664897
has text: @ktb That's not the only issue: if `printgraph` is to be an instance method, it needs `self` as a parameter, and then reference array as `self.array` (assuming that `array` would then become an attribute).
score: 0

http://stackoverflow.com/q/51755232
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51755313
tagged with: string
has comment: http://stackoverflow.com/comment/90470258
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/90470277
tagged with: python
has body: I've got a dictionary with keys as byte strings and values as byte strings and would like to print a cleaned up version of it. Here is an example pair: {b'cf1:c1': b'test-value'} I've tried doing json.dumps, but I get an error saying that TypeError: key b'cf1:c1' is not a string I've also tried pprint. Are there any libraries or easy ways to do this? Ideally the result would look like { 'cf1:c1': 'test-value' }
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90470306
has answer: http://stackoverflow.com/a/51755313
tagged with: pprint
has title: How to print a Python dict containing byte strings?

indexing
tags question: http://stackoverflow.com/q/51693929
tags question: http://stackoverflow.com/q/51661480
tags question: http://stackoverflow.com/q/51656851
tags question: http://stackoverflow.com/q/51699630
tags question: http://stackoverflow.com/q/51653170
type: Tag
tags question: http://stackoverflow.com/q/51752634
tags question: http://stackoverflow.com/q/51682648
tags question: http://stackoverflow.com/q/51705941
tags question: http://stackoverflow.com/q/51672594
tags question: http://stackoverflow.com/q/51737122
tags question: http://stackoverflow.com/q/51650855
tags question: http://stackoverflow.com/q/51773724
tags question: http://stackoverflow.com/q/51700469
tags question: http://stackoverflow.com/q/51765983
tag name: indexing
tags question: http://stackoverflow.com/q/51675388
tags question: http://stackoverflow.com/q/51773314
tags question: http://stackoverflow.com/q/51748631
tags question: http://stackoverflow.com/q/51745110
tags question: http://stackoverflow.com/q/51743156
tags question: http://stackoverflow.com/q/51697575
tags question: http://stackoverflow.com/q/51675723
tags question: http://stackoverflow.com/q/51676382
tags question: http://stackoverflow.com/q/51732396
tags question: http://stackoverflow.com/q/51708052
tags question: http://stackoverflow.com/q/51746802
tags question: http://stackoverflow.com/q/51679228

http://stackoverflow.com/comment/90244791
type: QuestionComment
comment on: http://stackoverflow.com/q/51640020
score: 0
type: Comment
has text: i got that error: NoneType' object is not callable I'm not sure why that error happens, maybe because I didn't specify the form_class, so the form_class return with None Value.

http://stackoverflow.com/a/51691876
has comment: http://stackoverflow.com/comment/90349348
has comment: http://stackoverflow.com/comment/90349151
has comment: http://stackoverflow.com/comment/90348971
has comment: http://stackoverflow.com/comment/90346513
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51691259
upvote count: 3
has comment: http://stackoverflow.com/comment/90348957
has body: A linear regression attempts to minimize the Mean Squared Error with an optimal hyperplane. Most data is not perfectly linear (including yours), so the predictions will not be perfect. However, they will have as low of an error as possible given the linearity constraint. In your example, there isn't much of a difference between 0.97 and 1.00. Consider the following linear regression in a smaller number of dimensions to make visualization easier. All the regression does is choose the line that fits the data best. That doesn't mean it goes through every point. When you use that line to make a prediction, it will be off by a little bit. The negative score (straight from the documentation) simply means that the model performs worse than if you did nothing but predict the average value of your data. Models can perform arbitrarily poorly. In your case, since a linear regression is able to learn such a constant model, this indicates overfitting to the training set (likely due to the small sample size). If you scored your train data instead you should get a non-negative answer, and probably one which is positive. Examining your model a little more closely, you'll notice that anything with a true value of 1 is predicted relatively closely due to the large class imbalance (you have almost twice as many 1's as everything else put together). The 2's are a little worse, and the 3's have a horrendous prediction. A linear model has a tough time making the huge jump from 1's and 2's to 3's for just a couple of points stuck in the middle of the rest of the point cloud.
downvote count: 0

http://stackoverflow.com/q/51673952
answer count: 1
has title: Compare cells from multiple data frames
has answer: http://stackoverflow.com/a/51674139
tagged with: python
type: AnsweredQuestion
score: 0
has body: I am unsure how to approach this utilizing Pandas. I am trying to compare each ID's value in one data frame to the other data frames. An example is below. Data Frame A Data Frame B Data Frame C ID Val ID Val ID Val 0 12345 10 0 12345 11 0 12345 11 1 23456 12 1 23456 12 1 23456 12 2 34567 13 2 34567 13 2 34567 13 3 45678 16 3 56789 12 Say there are three data frames (dfa, dfb, &amp; dfc) with each having IDs and values. ID 12345 has a value of 10, 11, and 11, so it would be ignored. ID 23456 has a value of 12 for all three data frames so it would get flagged in some way. Maybe printed that ID 23456 is the same. Moving forward, the same would apply for ID 34567 since it has the same values, but ID 45678 would be ignored since it doesn't exist in data frame B or data frame C. I've thought of some ways to do this, but it involves dictionaries and lists. I wanted to see if there was a way to better do this by continuing to utilize Pandas.
type: Question
accepted answer: http://stackoverflow.com/a/51674139
tagged with: pandas

http://stackoverflow.com/comment/90253759
type: QuestionComment
has text: At each step, you’re making two recursive calls, unless you’re below the lower bound. They have different args, so the memo cache won’t help. And each of those two calls makes two calls, and each of those makes two calls, and so on. So, unless you have some proof that this can only go log N steps before reaching the lower bound, instead of N steps, your code is `O(2**N)`, not `O(N**2)`.
score: 2
comment on: http://stackoverflow.com/q/51644831
type: Comment

http://stackoverflow.com/comment/90290699
score: 1
has text: That's not a positional argument, that's a keyword argument—the exact opposite kind.
type: QuestionComment
comment on: http://stackoverflow.com/q/51663651
type: Comment

http://stackoverflow.com/q/51656402
has body: my dataframe looks like: hours | cumulative value | value to add 1 1 1 2 2 1 3 3 3 4 6 1 What I want is, to append this dataframe like e.g.: 2-times (should be up to 50-times) and add its own values. It should look like: hours | cumulative value | value to add 1 1 1 2 2 1 3 3 3 4 6 1 #The first time 5 7 1 6 8 1 7 9 3 8 12 1 #The second time 9 13 1 10 14 1 11 15 3 12 18 1 And so on.. I am strugglin to find an optimal solution for that. Has anyone a good idea?
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51656787
has answer: http://stackoverflow.com/a/51656826
has answer: http://stackoverflow.com/a/51656784
has title: Appending pandas dataframe and adding its own values (python)
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51657204
accepted answer: http://stackoverflow.com/a/51657204
possible better answer: http://stackoverflow.com/a/51656784

http://stackoverflow.com/comment/90540274
type: Comment
has text: If I may add, if the row has less than 10 columns, then you can use `row.append(phone)`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51791383

http://stackoverflow.com/comment/90415682
score: 0
type: Comment
has text: Thank u wish u the best
type: AnswerComment
comment on: http://stackoverflow.com/a/51689857

http://stackoverflow.com/comment/139964776
type: AnswerComment
has text: You mean you want to input your user/password? For that you may better use selenium.
comment on: http://stackoverflow.com/a/72435895
type: Comment
score: 0

http://stackoverflow.com/comment/90379240
comment on: http://stackoverflow.com/q/51708980
score: 0
type: QuestionComment
type: Comment
has text: oh I did that in my initialisation- `self.zedTextureID_L = glGenTextures(1);` and `self.zedTextureID_R = glGenTextures(1);`

http://stackoverflow.com/comment/90381109
comment on: http://stackoverflow.com/q/51709652
type: Comment
type: QuestionComment
score: 1
has text: It looks like your lat / long coords are out of order. If that is the case, you'll have to use some sort of algorithm to "shrink wrap" your vertices. Most of the stuff I've seen on that is for skinning 3D point clouds into triangle or quad surfaces, but it should be extensible to 2D.

http://stackoverflow.com/q/51742743
has answer: http://stackoverflow.com/a/51743015
type: Question
score: 14
has answer: http://stackoverflow.com/a/51743129
has answer: http://stackoverflow.com/a/51742971
accepted answer: http://stackoverflow.com/a/51743054
linked to: http://stackoverflow.com/q/949098
has answer: http://stackoverflow.com/a/51743054
downvote count: 1
has answer: http://stackoverflow.com/a/51743052
duplicate of: http://stackoverflow.com/q/949098
favorite count: 0
has comment: http://stackoverflow.com/comment/90445540
answer count: 5
tagged with: python
upvote count: 15
has title: Is there a way to "fork" a list in two based on a condition
possible better answer: http://stackoverflow.com/a/51743015
has body: I have seen a pattern repeated a couple times in my team's code, it looks like this numbers = [1, 2, 3, 4] even_numbers = [n for n in numbers if n % 2 == 0] odd_numbers = [n for n in numbers if n % 2 != 0] I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this numbers = [1, 2, 3, 4] even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0) So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't. Is there something around python's standard library that achieves this?
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/51672097
type: Answer
answers question: http://stackoverflow.com/q/51671530
accepted answer of: http://stackoverflow.com/q/51671530
has comment: http://stackoverflow.com/comment/90310055
has comment: http://stackoverflow.com/comment/90307362
has body: This should work and is generalizable to other types than float: with open("data.txt") as infile: np.fromstring( infile.read().replace("[","").replace("]", ""), sep=" ").reshape(-1,3) Note: np.fromstring returns a 1d array, I added a reshaping assuming 3 columns.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/90545052
score: 1
comment on: http://stackoverflow.com/q/51793459
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow! Please edit your original post to add the text requested in the comment. Also, please avoid posting to external images, which when deleted, will render this post meaningless. The point of SO is to create a lasting encyclopedia of questions and answers, and to help people later who have similar issues. Thanks!

http://stackoverflow.com/a/51753471
type: Answer
score: 2
has body: Use the e-format type like this: '%.1E' % 2182869
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90466781
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51753433
has comment: http://stackoverflow.com/comment/90468486
answers question: http://stackoverflow.com/q/51753433

http://stackoverflow.com/q/51721654
has answer: http://stackoverflow.com/a/51721844
accepted answer: http://stackoverflow.com/a/51721844
type: Question
answer count: 1
has title: It says 'module' object has no type attribute when I'm trying to use event.type
score: 0
tagged with: python
tagged with: pygame
has body: It says this when I'm trying to use event.type. I have not used the event module before though, but it says in my book that it is supposed to work. I looked this up, on google and on stack overflow, but I didn't find anything like this (I used Javascript for the code snippet, because i didn't know how to get the code into python.) import pygame from pygame import * pygame.init() pygame.event.get() black = (0,0,0) white = (255,255,255) playercoords_a = (275,425) playercoords_b = (275,475) playercoords_c = (225,475) playercoords_d = (225,425) playertotalcoords = (playercoords_a, playercoords_b, playercoords_c, playercoords_d) windowSurface = pygame.display.set_mode((500, 500),0,32) windowSurface.fill(black) xmod = 0 ymod = 0 pygame.draw.polygon(windowSurface,white,((275,425),(275,475),(225,475),(225,425))) pygame.display.update() while True: if event == KEYDOWN: if event.key == K_LEFT: print('it works') windowSurface.fill((black,)) pygame.draw.polygon(windowSurface,white,((275 + xmod,425 + ymod),(275 + xmod,475 + ymod),(225 + xmod,475 + ymod),(225 + xmod,425 + ymod))) pygame.display.update() line 19, in if event.type == KEYDOWN: AttributeError: 'module' object has no attribute 'type'
type: AnsweredQuestion
tagged with: python-3.x

selenium
tags question: http://stackoverflow.com/q/51778832
tags question: http://stackoverflow.com/q/51693420
tags question: http://stackoverflow.com/q/51677024
tags question: http://stackoverflow.com/q/51651732
tags question: http://stackoverflow.com/q/51763519
tags question: http://stackoverflow.com/q/51732681
tags question: http://stackoverflow.com/q/51676804
tags question: http://stackoverflow.com/q/51666491
tags question: http://stackoverflow.com/q/51754978
tags question: http://stackoverflow.com/q/51705998
tags question: http://stackoverflow.com/q/51654287
tags question: http://stackoverflow.com/q/51717120
tags question: http://stackoverflow.com/q/51641546
tags question: http://stackoverflow.com/q/51726228
tags question: http://stackoverflow.com/q/51756925
tags question: http://stackoverflow.com/q/51686224
tags question: http://stackoverflow.com/q/51682386
tags question: http://stackoverflow.com/q/51702832
tags question: http://stackoverflow.com/q/51732570
tags question: http://stackoverflow.com/q/51679932
tags question: http://stackoverflow.com/q/51709267
tags question: http://stackoverflow.com/q/51723825
tags question: http://stackoverflow.com/q/51740517
tags question: http://stackoverflow.com/q/51642044
tags question: http://stackoverflow.com/q/51789088
tags question: http://stackoverflow.com/q/51739413
tags question: http://stackoverflow.com/q/51689617
tags question: http://stackoverflow.com/q/51796488
tags question: http://stackoverflow.com/q/51745994
tags question: http://stackoverflow.com/q/51726711
tags question: http://stackoverflow.com/q/51661710
tags question: http://stackoverflow.com/q/51709804
tags question: http://stackoverflow.com/q/51641703
tags question: http://stackoverflow.com/q/51748978
tags question: http://stackoverflow.com/q/51795743
tags question: http://stackoverflow.com/q/51695422
tags question: http://stackoverflow.com/q/51787475
tags question: http://stackoverflow.com/q/51706256
tags question: http://stackoverflow.com/q/51641540
tags question: http://stackoverflow.com/q/51776223
tags question: http://stackoverflow.com/q/51777361
tags question: http://stackoverflow.com/q/51666661
tag name: selenium
tags question: http://stackoverflow.com/q/51774569
tags question: http://stackoverflow.com/q/51681276
tags question: http://stackoverflow.com/q/51798576
tags question: http://stackoverflow.com/q/51729042
tags question: http://stackoverflow.com/q/51756066
tags question: http://stackoverflow.com/q/51771415
tags question: http://stackoverflow.com/q/51743859
tags question: http://stackoverflow.com/q/51774892
tags question: http://stackoverflow.com/q/51716262
tags question: http://stackoverflow.com/q/51757506
tags question: http://stackoverflow.com/q/51787152
tags question: http://stackoverflow.com/q/51747425
tags question: http://stackoverflow.com/q/51697746
tags question: http://stackoverflow.com/q/51730930
tags question: http://stackoverflow.com/q/51780885
tags question: http://stackoverflow.com/q/51646908
tags question: http://stackoverflow.com/q/51737769
tags question: http://stackoverflow.com/q/51715712
tags question: http://stackoverflow.com/q/51756089
tags question: http://stackoverflow.com/q/51697919
tags question: http://stackoverflow.com/q/51721185
tags question: http://stackoverflow.com/q/51700886
tags question: http://stackoverflow.com/q/51713416
tags question: http://stackoverflow.com/q/51760262
tags question: http://stackoverflow.com/q/51755916
tags question: http://stackoverflow.com/q/51706120
tags question: http://stackoverflow.com/q/51751248
tags question: http://stackoverflow.com/q/51647573
tags question: http://stackoverflow.com/q/51679235
tags question: http://stackoverflow.com/q/51673700
tags question: http://stackoverflow.com/q/51720039
tags question: http://stackoverflow.com/q/51755623
tags question: http://stackoverflow.com/q/51644941
tags question: http://stackoverflow.com/q/51642864
tags question: http://stackoverflow.com/q/51707070
tags question: http://stackoverflow.com/q/51690101
tags question: http://stackoverflow.com/q/51724472

http://stackoverflow.com/q/51690666
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has body: I came across this line of code ax = ax or plt.gca() It is line 29 here https://github.com/Santosh-Gupta/adjustText/blob/master/adjustText/init.py How exactly does this expression work?
favorite count: 0
possible better answer: http://stackoverflow.com/a/51690771
has title: Setting python variable with conditional statement
linked to: http://stackoverflow.com/q/47007680
has comment: http://stackoverflow.com/comment/90343112
tagged with: python
has answer: http://stackoverflow.com/a/51690743
accepted answer: http://stackoverflow.com/a/51690743
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90343338
type: Question
has answer: http://stackoverflow.com/a/51690771
has answer: http://stackoverflow.com/a/51690814

http://stackoverflow.com/comment/90419320
has text: https://imgur.com/a/8bygbUO that seems to work, although the last slash is a backslash, I don't know if that's a problem? But that'd mean that the issue lies in the last part "with open(path + file, 'r') as flower_file:". I hate that I'm so bad at this, I'm just trying to figure stuff out :(
comment on: http://stackoverflow.com/a/51724227
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51767387
has comment: http://stackoverflow.com/comment/90493634
answers question: http://stackoverflow.com/q/51767339
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51767339
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90493713
has comment: http://stackoverflow.com/comment/90493526
has body: Use planet_templates = [{"name": "templates/neptune.png", "width": 107, "height": 148}] for d in planet_templates: for key, value in d.items(): print("{0}: {1}".format(key, value)) Output: width: 107 name: templates/neptune.png height: 148

http://stackoverflow.com/comment/90460220
type: Comment
has text: You can't really handle it in Python in a sensible way. What you can do though is to run the python interpreter through GDB with your script. When the interpreter segfaults, GDB will stop all execution, and you can look into the various threads stacktraces to get a clue what goes wrong.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51750173

http://stackoverflow.com/q/51720624
upvote count: 1
type: Question
tagged with: ide
answer count: 1
downvote count: 0
favorite count: 0
has title: PyCharm code completion doesn't work for installed libraries
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90409016
tagged with: python
tagged with: pycharm
has body: I am using PyCharm community edition 2018.2. Code completion works fine but just for installed modules if I install external library code completion doesn't work for them. However I have no problem with running code based on them. I checked that my PyCharm is not in the 'PowerSafeMode'. I have created project both for main and local Python interpreter. In the IDE I also try to select installed libraries as a source. I tried this for PIL library and OpenCV library. Anyone has and idea what I might be missing or doing wrong?
score: 1
has answer: http://stackoverflow.com/a/51721491

http://stackoverflow.com/q/51754894
tagged with: text-analysis
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: text-analytics-api
score: 0
has answer: http://stackoverflow.com/a/51756633
tagged with: azure
has title: Microsoft Azure Text Analytics Coginitive Service Encoding Issue
answer count: 1
has comment: http://stackoverflow.com/comment/90471545
has comment: http://stackoverflow.com/comment/90472746
type: UnansweredQuestion
has body: In order to use their text analytics, Azure requires a json file/document that looks like this: document = { "documents" :[ {"id": "1", "language": "en", "text": "I had a wonderful experience! The rooms were wonderful and the staff was helpful."}, {"id": "2", "language": "en", "text": "I had a terrible time at the hotel. The staff was rude and the food was awful."}, {'id': '3', 'language': 'es', 'text': 'Los caminos que llevan hasta Monte Rainier son espectaculares y hermosos.'}, {'id': '4', 'language': 'es', 'text': 'La carretera estaba atascada. Había mucho tráfico el día de ayer.'}]} The issue I am getting at the moment is that the last record id: 4 is causing this error: b'{"code":"BadRequest","message":"Invalid request","innerError":{"code":"InvalidRequestBodyFormat","message":"Request body format is wrong. Make sure the json request is serialized correctly and there are no null members."}}' The formatting of the JSON is correct, it's straight from their site and it runs perfectly fine without the last record. I tested some more and then found out that the í and á are the ones throwing the error. To make sure, I even tested it out with English words like resumé or fiancé but still the same error. But that doesn't make sense since Spanish is one of the supported languages for the text analysis and the text language is even define as Spanish before it's processed. So my question is, am I missing something before passing my data through Azure? Am I suppose to convert, changing the encoding, or remove those characters or is this something that Azure's API should be able to handle? EDIT: A little more background, I followed the instructions provided on their site to set it up to work with python. It works perfectly except for what I mentioned.
tagged with: python

http://stackoverflow.com/comment/90801304
type: Comment
has text: Try and add this to your uwsgi config - `touch-reload = /path/to/file/vassal-foo.ini`. Then restart your uwsgi process and see if it works.
comment on: http://stackoverflow.com/q/51734383
score: 0
type: QuestionComment

http://stackoverflow.com/q/51653673
answer count: 3
has answer: http://stackoverflow.com/a/79255072
has title: Selenium - OSError: [WinError 6] The handle is invalid
has answer: http://stackoverflow.com/a/53484462
has answer: http://stackoverflow.com/a/51668434
possible better answer: http://stackoverflow.com/a/53484462
type: AnsweredQuestion
score: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51668434
tagged with: selenium-chromedriver
upvote count: 3
has body: I'm trying to keep my automated chrome windows open, but they close with this error: Traceback (most recent call last): File "C:\Users\Duma\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 841, in __del__ self._internal_poll(_deadstate=_maxsize) File "C:\Users\Duma\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1193, in _internal_poll if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: OSError: [WinError 6] The handle is invalid Using Selenium and my Python script looks like this: login_url='https://www.life4laptop.com/index.php?route=account/login' url='https://www.life4laptop.com/index.php?route=product/search&amp;search=samsung' list=[] driver=webdriver.Chrome(crm_path, chrome_options=options) driver.get(login_url) elem = driver.find_element_by_id("input-email") elem.clear() elem.send_keys(x['life4laptop']['username']) elem = driver.find_element_by_id("input-password") elem.clear() elem.send_keys(x['life4laptop']['password']) elem = driver.find_element_by_xpath("//form/input[@type='submit']") elem.click() driver.get(url) driver2=webdriver.Chrome(crm_path, chrome_options=options) driver2.get(login_url) elem = driver2.find_element_by_id("input-email") elem.clear() elem.send_keys(x['life4laptop']['username']) elem = driver2.find_element_by_id("input-password") elem.clear() elem.send_keys(x['life4laptop']['password']) elem = driver2.find_element_by_xpath("//form/input[@type='submit']") elem.click() driver2.get(url) #driver.close() #driver.quit() Any clues why, and how to get it working?

http://stackoverflow.com/comment/90266214
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51650428
has text: Duuuude! The forest for all the trees not seen! TY!

http://stackoverflow.com/comment/90272377
score: 0
type: Comment
has text: Are the discontinueities of fixed length or are there variably many 0 and 1 in between the single runs? Your pseudo-code suggests no, but then the practical runtime would be more like O(c*n) with c maybe close to 2. (Hint: you should stay away from plucking out each and every X1-list)
type: QuestionComment
comment on: http://stackoverflow.com/q/51650690

http://stackoverflow.com/q/51693420
has title: Format error in python Selenium package
accepted answer: http://stackoverflow.com/a/51694513
has body: I'm running on Linux Debian 9 and PyCharmwith web scraping purposes; I'm currently using Python 3.5 as interpreter. The script is the following: from selenium import webdriver import time import datetime from selenium.webdriver.common.keys import Keys Till here, the script works fine, by importing the packages properly; when I try to set the driver by running the following line: driver = webdriver.Firefox(executable_path='/home/quant/Desktop/DataDownload/venv/bin/geckodriver') I get the following error message, relative to a format problem: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/home/quant/Desktop/DataDownload/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 157, in __init__ self.service.start() File "/home/quant/Desktop/DataDownload/venv/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python3.5/subprocess.py", line 676, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child raise child_exception_type(errno_num, err_msg) OSError: [Errno 8] Exec format error Browsing on the web, I found that probably this problem comes out when the executable program has not been unzipped and made executable correctly; to do that, I followed the steps below, by running them on the terminal: (1).zip file download from the official repository in the github website: wget [here][1] (2) unzipped the file: cd /home/quant/Downloads tar -xvzf geckodriver-v0.21.0-arm7hf.tar.gz (3) made the file executable: chmod +x geckodriver (4) moved the file on the following path: mv geckodriver /home/quant/PycharmProject/DataDownloads/venv/bin/ Could someone help me to understand what's wrong, please? Thanks in advance all!!
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/90348334
has answer: http://stackoverflow.com/a/51694513
tagged with: geckodriver
tagged with: python
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/90348310
type: Question
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90382722
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51706885
has text: The coeffictients is [c,b,a], so it's working well enough since 1e-15 ~ 0. Look at how `X_poly` looks when printed
score: 1

http://stackoverflow.com/comment/90278004
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51650006
score: 0
has text: I added the info

http://stackoverflow.com/comment/90383669
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51710948
score: 1
has text: You can also use `inplace=True` for the changes to stick.

http://stackoverflow.com/comment/111102168
type: Comment
has text: This worked perfectly for me (MacOS). Thanks a ton!
comment on: http://stackoverflow.com/a/62741032
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90481762
type: Comment
comment on: http://stackoverflow.com/a/51761390
has text: Thankyou for the answer
type: AnswerComment
score: 0

http://stackoverflow.com/q/51732395
type: Question
has answer: http://stackoverflow.com/a/51732424
answer count: 2
tagged with: default-value
possible better answer: http://stackoverflow.com/a/51732424
has comment: http://stackoverflow.com/comment/90425545
score: 0
accepted answer: http://stackoverflow.com/a/51732433
has title: Default Parameters in Function Definition, Syntax problems.
tagged with: python
has body: I am having an issue finding a straightforward answer to a question that I have. I am coding a program that has some default values for certain parameters that do not end up being called by the user. My program is somewhat complicated so I decided to try a simplified problem. def mult(x = 1, y = 2, z = 3): ans = x * y * z print(ans) mult() In this quick program, the function call would result in 6. Which makes sense because it goes to the default values I provided. My question is, how can I call this function if, for example, I wanted to define y and not any other variable? What would be the correct syntax in that situation. My intuition was to call mult(x, 5, z) to indicate default values for x and z but a new value for y. I know that does not work and would like to know what the correct syntax would be.
has comment: http://stackoverflow.com/comment/90425572
type: AnsweredQuestion
tagged with: syntax
has answer: http://stackoverflow.com/a/51732433

http://stackoverflow.com/q/51742210
score: 0
answer count: 1
tagged with: pandas
has body: I have two dataframes: df1 shape = (101, 4825) df2 shape = (97, 5818) The first 4825 column names of df2 are the same as df1, and then increases by +1. However, at the end of both dataframes, there is a column named Group_number. I want to concatenate both the data frames so that the shape of the final dataframe is of shape (198,5818), i.e the final dataframe has all the rows of both the and NaN values for the df1 section (after the initial 4825 values). I tried pd.concat([df1,df2]) but the column Group_number gets mixed up.
tagged with: python
type: UnansweredQuestion
type: Question
has title: Concatenate two dataframes with different number of rows and columns
tagged with: dataframe
has answer: http://stackoverflow.com/a/51742814

http://stackoverflow.com/a/51655035
type: Answer
answers question: http://stackoverflow.com/q/51654012
downvote count: 0
has body: I was having fun with variations on Sven Marnach's answer defaultdict and count from collections import defaultdict from itertools import count c = defaultdict(lambda:count(1)) {f"{k}{['', next(c[k])][len(V) &gt; 1]}": v for k, V in data.items() for v in V} {'a1': 80, 'a2': 130, 'b': 64, 'c1': 58, 'c2': 80} enumerate {f"{k}{['', i][len(V) &gt; 1]}": v for k, V in data.items() for i, v in enumerate(V, 1)} {'a1': 80, 'a2': 130, 'b': 64, 'c1': 58, 'c2': 80}
score: 1
upvote count: 1

http://stackoverflow.com/q/51677943
has comment: http://stackoverflow.com/comment/90319133
tagged with: python
has answer: http://stackoverflow.com/a/51681122
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/663171
score: 1
tagged with: bit-manipulation
has comment: http://stackoverflow.com/comment/90319945
upvote count: 1
has answer: http://stackoverflow.com/a/51679315
accepted answer: http://stackoverflow.com/a/51679315
has comment: http://stackoverflow.com/comment/90319175
has comment: http://stackoverflow.com/comment/90319932
type: Question
has body: Suppose I have a large hex number, 0x1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF and I wanted to get bytes 10-20, from this hex number easily, how would I accomplish that? I know I can cut the data from bit shifting right by 10*8 times but I still have the significant bytes in my left over hex number.
possible better answer: http://stackoverflow.com/a/51681122
answer count: 2
has title: Python getting specific bytes in a large hex number
downvote count: 0
has comment: http://stackoverflow.com/comment/90319211
favorite count: 0
has comment: http://stackoverflow.com/comment/90319139
tagged with: byte

http://stackoverflow.com/a/51689142
downvote count: 0
answers question: http://stackoverflow.com/q/51688998
has comment: http://stackoverflow.com/comment/90340147
type: Answer
score: 1
upvote count: 1
has body: A fully general solution to this question would solve the halting problem, which has been mathematically proven impossible. For more particular cases, it can be done. For certain algorithms, if you know how much work must be done and you can periodically check how much of it has been done, then you can update the percentage. You can also estimate the time remaining based on how quickly the percentage is progressing, but this can often be inaccurate.

http://stackoverflow.com/comment/90373952
type: AnswerComment
has text: Yeah this is what I tried at first, but there is mismatch type error. str1 is not string but array (array of string), and this is why I thought about using explode but with no success either. Thanks
comment on: http://stackoverflow.com/a/51706618
type: Comment
score: 0

http://stackoverflow.com/comment/134652683
type: QuestionComment
comment on: http://stackoverflow.com/q/51698662
has text: what is the result of `pyenv versions`?
score: 0
type: Comment

http://stackoverflow.com/comment/90419159
type: QuestionComment
score: 2
has text: `list(zip(x, x[1:]))` ?
comment on: http://stackoverflow.com/q/51729217
type: Comment

http://stackoverflow.com/comment/90487571
comment on: http://stackoverflow.com/a/51742006
type: AnswerComment
score: 0
has text: That looks like it might be the wrong library since it's only a few months old, but people have been using the one I'm talking about for years. Heres an example from 2016: https://www.rhydolabz.com/wiki/?p=16325
type: Comment

http://stackoverflow.com/comment/90517113
comment on: http://stackoverflow.com/q/51779699
has text: where did you get your `json_data` from?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90510524
score: 1
type: QuestionComment
type: Comment
has text: Can you provide minimal table example please?
comment on: http://stackoverflow.com/q/51775745

http://stackoverflow.com/comment/90537222
has text: In which module do you import the signals? This module might be only executed in the process **sending** the task (thus emitting the `after_task_publish` signal), but not in the process **running** the task (emitting the `task_postrun` signal).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51789799
score: 0

http://stackoverflow.com/comment/90305260
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51671313
has text: How do you get this number `556111`? I think it should be `55611` = (333 * 334)/2

http://stackoverflow.com/a/51780739
downvote count: 0
answers question: http://stackoverflow.com/q/51780684
upvote count: 1
type: Answer
has body: You can define the format. created_at = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True) Change the format in which type you want. If you want change for all datetime then change in the setting file. REST_FRAMEWORK = { 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ", }
score: 1

http://stackoverflow.com/comment/90381664
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51709512
has text: Thanks a lot Bethany.
score: 0

http://stackoverflow.com/q/51699630
tagged with: python
has answer: http://stackoverflow.com/a/51699723
tagged with: indexing
tagged with: dataframe
type: Question
has title: Subsetting Hierarchical Index and Hierarchical column names in Pandas (with and without indices)
answer count: 2
has comment: http://stackoverflow.com/comment/90361222
has body: I am a beginner in Python and Pandas, and it has been 2 days since I opened Wes McKinney's book. So, this question might be a basic one. I am using Anaconda distribution (Python 3.6.6) and Pandas 0.21.0. I researched the following threads (https://pandas.pydata.org/pandas-docs/stable/advanced.html, xs function at https://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-xs, Select only one index of multiindex DataFrame, Selecting rows from pandas by subset of multiindex, and https://pandas.pydata.org/pandas-docs/stable/indexing.html) before posting this. All of them explain how to subset data.frame using either hierarchical index or hierarchical column, but not both. Here's the data. import pandas as pd import numpy as np from numpy import nan as NA #Hierarchical index for row and column data = pd.DataFrame(np.arange(36).reshape(6,6), index=[['a']*2+['b']*1+['c']*1+['d']*2, [1, 2, 3, 1, 3, 1]], columns = [['Title1']*3+['Title2']*3, ['A']*2+['B']*2+['C']*2]) data.index.names = ['key1','key2'] data.columns.names = ['state','color'] Here are my questions: Question:1 I'd like to access key1 = a, key2 = 1, state = Title1 (column), and color = A (column). After a few trial and errors, I found that this version works (I really don't know why this works--my hypothesis is that data.loc['a',1] gives an indexed dataframe, which is then subset...and so on): data.loc['a',1].loc['Title1'].loc['A'] Is there a better way to subset above? Question:2 How do I subset the data after deleting the indices? data_wo_index = data.reset_index() I'm relatively comfortable with data.table in R. So, I thought of using http://datascience-enthusiast.com/R/pandas_datatable.html to subset the data using my data.table knowledge. I tried one step at a time, but even the first step (i.e. subsetting key1 = a gave me an error: data_wo_index[data_wo_index['key1']=='a'] Exception: cannot handle a non-unique multi-index! I don't know why Pandas is still thinking that there is multi-index. I have …
linked to: http://stackoverflow.com/q/28140771
linked to: http://stackoverflow.com/q/22521414
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51699736
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90360814

http://stackoverflow.com/comment/131068840
comment on: http://stackoverflow.com/a/60866026
score: 1
has text: I still received this error after changing the environment back to base since anaconda was not in my default channels. Please see my answer for the solution to that if you still get this error message like I did.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51719309
answers question: http://stackoverflow.com/q/51717120
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90408987
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90409207
accepted answer of: http://stackoverflow.com/q/51717120
has body: You have forgot this: while True: # Scroll down to bottom browser.execute_script("window.scrollTo(0, document.body.scrollHeight)") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = browser.execute_script("return document.body.scrollHeight") # break condition if new_height == last_height: break last_height = new_height Also you have SCROLL_PAUSE_TIME = 0.5 it is not very much, and when number of posts to load becomes bigger, twitter slows down. You have to increase this pause. I would try SCROLL_PAUSE_TIME = 2 PS: it is not very effective to use hard coded pause. Instead you can try to locate spinner or whatever, when twitter loads new content and wait until spinner disappear. This would be more elegant.

http://stackoverflow.com/a/51728257
has comment: http://stackoverflow.com/comment/90417307
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51728070
score: 2
has body: I thought we should use rolmean = ts.rolling(window=12).mean() Instead of rolmean = pd.rolling_mean(ts, window=12) Since pd.rolling_mean is deprecated EDIT Just change rolmean = pd.rolling_mean(ts, window=12) rolstd = pd.rolling_std(ts, window=12) To rolmean = ts.rolling(window=12).mean() rolstd = ts.rolling(window=12).std() EDIT If you are talking about this line change it from df['priceModLogMA12'] = pd.rolling_mean(df.priceModLog, window = 5) To df['priceModLogMA12'] = df.priceModLog.rolling(window = 5).mean()
downvote count: 0

http://stackoverflow.com/q/51766916
upvote count: 1
answer count: 1
downvote count: 1
tagged with: template-engine
linked to: http://stackoverflow.com/q/32024551
favorite count: 0
has body: I have spent way too much time trying to figure this out. I have a dictionary like the following: {'asset_1': {'scenario_1':10%, 'scenario_2':-20%}, 'asset_2': {'scenario_1':-11%, 'scenario_2':30%}, 'asset_3': {'scenario_1':15%, 'scenario_2':22%}, 'asset_4': {'scenario_1':-13%, 'scenario_2':30%}} What I need now to do is loop through the each asset, and then through each scenario and fill this in, in the table. But I cannot access the outer loop's asset name in the innermost. I can access the index however, through {% set asset_loop = loop %}, and then say {{asset_loop.index}}, but this is not helpful, because I would have to know ahead of calling {{asset_loop.index}}, which index corresponds to which asset (so that I create a dictionary like the following: {0: {'scenario_1':...}, 1: {'scenario_1':,...},..}, but I cannot guarantee the order in the dictionary! This is what I have atm, which does not work, clearly, but shows what I want to achieve: {% for asset in (raw_results["risk_scenarios"].keys() | list) %} {% set asset_loop = loop %} {{asset}} weight {% for scenario in raw_results["risk_scenarios"][{{asset}}] %} {{raw_results["risk_scenarios"][{{asset}}][{{scenario}}]}} {% endfor %} {% endfor %}
duplicate of: http://stackoverflow.com/q/32024551
tagged with: python
type: AnsweredQuestion
has title: Looping through a nested dictionary (Jinja2, Flask)
tagged with: jinja2
type: Question
has answer: http://stackoverflow.com/a/51766979
accepted answer: http://stackoverflow.com/a/51766979
tagged with: flask
score: 0

http://stackoverflow.com/q/51674401
downvote count: 0
tagged with: scikit-learn
answer count: 3
has answer: http://stackoverflow.com/a/51674616
accepted answer: http://stackoverflow.com/a/51678381
favorite count: 0
has title: Convert distance pairs to distance matrix to use in hierarchical clustering
has comment: http://stackoverflow.com/comment/90317738
upvote count: 2
possible better answer: http://stackoverflow.com/a/51674616
has comment: http://stackoverflow.com/comment/90311976
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51674676
tagged with: hierarchical-clustering
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51678381
score: 2
has comment: http://stackoverflow.com/comment/90316400
linked to: http://stackoverflow.com/q/13079563
has body: I am trying to convert a dictionary to a distance matrix that I can then use as an input to hierarchical clustering: I have as an input: key: tuple of length 2 with the objects for which I have the distance value: the actual distance value for k,v in obj_distances.items(): print(k,v) and the result is : ('obj1', 'obj2') 2.0 ('obj3', 'obj4') 1.58 ('obj1','obj3') 1.95 ('obj2', 'obj3') 1.80 My question is how can I convert this into a distance matrix that I can later user for clustering in scipy?

http://stackoverflow.com/comment/90352509
type: QuestionComment
has text: what is `py -2`?
comment on: http://stackoverflow.com/q/51695492
score: 0
type: Comment

http://stackoverflow.com/comment/90444995
has text: @JHBonarius I was trying to but it said I couldn't accept an answer so fast? It's telling me I can accept in 2 mins
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51742430

http://stackoverflow.com/comment/90516478
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51779134
has text: Will you want to do this many times to different rows of the df or it will always start at the first row?

http://stackoverflow.com/comment/90533816
has text: The problem is that I can't rely on a specific color. This is a great starting point though! I'll play around with it a bit and see if I can modify it to work. Thank you!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51777589

http://stackoverflow.com/a/51784278
downvote count: 1
answers question: http://stackoverflow.com/q/51782224
has body: A modified version of ibarronds solution without using labmda and works with higher dimensions above 3: import numpy as np def myfunc(*J): return np.sqrt(np.prod(np.array(J))) myfunc2=np.vectorize(myfunc) D=(2,3,4,5) np.fromfunction(function=myfunc2 , shape=D) P.S. Unfortunately he has removed his answer so I copy it here for reference: creation_function = lambda *args: np.sqrt(np.prod(np.array([*args]), axis=0)) np.fromfunction(function=creation_function, shape=D)
score: -1
has comment: http://stackoverflow.com/comment/90525911
has comment: http://stackoverflow.com/comment/90526082
has comment: http://stackoverflow.com/comment/90525930
has comment: http://stackoverflow.com/comment/90525830
upvote count: 0
has comment: http://stackoverflow.com/comment/90525747
has comment: http://stackoverflow.com/comment/90526033
type: Answer
has comment: http://stackoverflow.com/comment/90525738
has comment: http://stackoverflow.com/comment/90525992
has comment: http://stackoverflow.com/comment/90525673
has comment: http://stackoverflow.com/comment/90525861

http://stackoverflow.com/comment/90532596
has text: The message indicates that it can find the `helpers` module, but it can't find `my_func` inside it. Do you have any other files named helper.py in your project directory or on your PATH?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51787702
score: 3

http://stackoverflow.com/a/51676778
type: AcceptedAnswer
has body: It sounds like you want a transpose in there too: m_3d = np.random.rand(2000, 140, 190) # break the 2000 dimension in two. Pick one: m_4d = m_3d.reshape((50, 40, 140, 190)) # move the dimensions to collapse to be adjacent # you might need to tweak this - you haven't given enough information to know # what order you want m_4d = m_4d.transpose((0, 2, 1, 3)) # collapse adjacent dimensions m_2d = m_4d.reshape((7000, 7600))
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51674782
downvote count: 0
answers question: http://stackoverflow.com/q/51674782
score: 1

http://stackoverflow.com/a/68869795
downvote count: 0
score: 1
has body: Alternatively, the 2-line solution could be def get_top_n(df, top_n): # find top_n largest entries by stock df = df.apply(lambda x: x.nlargest(top_n), axis=1) # convert dataframe NaN or float entries True and False, and then convert to 0 and 1 top_numbers = (df.notnull()).astype(np.int) return top_numbers
answers question: http://stackoverflow.com/q/51645934
upvote count: 1
type: Answer

http://stackoverflow.com/a/51768236
downvote count: 0
has body: Try this code if you still want to use threading: import threading import random import time x = [] start_time = time.time() def printit(): current_time = time.time() print(current_time - start_time) if current_time - start_time &gt; 60.0: return threading.Timer(3.0, printit).start() l = ['a', 'b', 'c', 'd'] secure_random = random.SystemRandom() x.append(secure_random.choice(l)) print(x) printit() I tested this code in Python 3.6 you may want to change the print() to print to make it work in Python 2
type: Answer
answers question: http://stackoverflow.com/q/51767783
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51767783
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51745679
has comment: http://stackoverflow.com/comment/90450961
linked to: http://stackoverflow.com/q/17383094
has answer: http://stackoverflow.com/a/51746054
type: Question
has answer: http://stackoverflow.com/a/51746086
has answer: http://stackoverflow.com/a/51745774
answer count: 3
tagged with: pandas
tagged with: python
tagged with: countif
type: UnansweredQuestion
score: 0
has body: Columns L,M,N of my dataframe are populated with 'true' and 'false' statements(1000 rows). I would like to create a new column 'count_false' that will return the number of times 'false' statement occurred in columns L,M and N. Any tips appreciated! Thank you.
has title: Python | count number of False statements in 3 rows

http://stackoverflow.com/a/51744978
answers question: http://stackoverflow.com/q/51744012
type: Answer
has comment: http://stackoverflow.com/comment/90452046
has comment: http://stackoverflow.com/comment/90451084
has comment: http://stackoverflow.com/comment/90450438
has comment: http://stackoverflow.com/comment/90453196
has comment: http://stackoverflow.com/comment/90453557
score: 0
has comment: http://stackoverflow.com/comment/90450409
has body: Use the Tkinter OptionMenu widget, and create a text variable to track the value of the selection. You can call .get() on the variable to find out what's selected. ie. s = tk.StringVar() tk.OptionMenu(window, s, c[0], c[1]... ) def function(x): # use x to find data ... button = tk.Button(window, text='Button', command= lambda x=s.get() : function(x) ) You need a button aswell, so keep the one you've got and the command should use .get() to get the dropdown selection, then you can use that info to find your data. The effbot docs are quite good for explaining how to use tkinter widgets.
has comment: http://stackoverflow.com/comment/90452418
has comment: http://stackoverflow.com/comment/90452447

http://stackoverflow.com/comment/90351824
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51695059
has text: Side-note: When opening a file for use with the `csv` module, you need to pass `newline=''` as an argument to `open`; specific newline formats are important to CSV formats, and `open` should not be translating them.
score: 0

http://stackoverflow.com/q/51752289
type: Question
has body: Here is what I tried first df = dd.from_pandas(pd.DataFrame(dict(x=np.random.normal(size=100), y = np.random.normal(size=100))), chunksize=40) cat = df.map_partitions( lambda d: np.digitize(d['x']+d['y'], [.3,.9]), meta=pd.Series([], dtype=int, name='x')) cat.to_hdf('/tmp/cat.h5', '/cat') This fails with cannot properly create the storer... I next tried to save cat.values instead: da.to_hdf5('/tmp/cat.h5', '/cat', cat.values) This fails with cannot convert float NaN to integer which I am guessing to be due to cat.values not having nan shape and chunksize values. How do I get both of these to work? Note the actual data would not fit in memory.
upvote count: 0
has title: How to save a dask series to hdf5
score: -1
accepted answer: http://stackoverflow.com/a/51773545
answer count: 1
favorite count: 0
tagged with: dask
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51773545
tagged with: hdf5

http://stackoverflow.com/q/51744642
upvote count: 2
has comment: http://stackoverflow.com/comment/90450011
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90449634
has comment: http://stackoverflow.com/comment/90449246
answer count: 1
tagged with: django-celery
has comment: http://stackoverflow.com/comment/90449338
has comment: http://stackoverflow.com/comment/90449357
tagged with: celery
has comment: http://stackoverflow.com/comment/90449892
has body: My current code: from celery.task.schedules import crontab from celery.decorators import task, periodic_task @periodic_task(run_every=crontab(hour=15, minute=55, day_of_week="wed")) def demo(): print("testing------------------------") Setting file: CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'amqp://guest:guest@localhost//') It's not working, am I missing something? Thanks In advance
has answer: http://stackoverflow.com/a/51747346
score: 2
has title: How to set periodic task on Django using celery?
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51747346
has comment: http://stackoverflow.com/comment/90449771
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/51693988
type: Question
tagged with: django-urls
accepted answer: http://stackoverflow.com/a/51694082
answer count: 2
has body: url('add/(?P&lt;journal_type&gt;C[DR])/$', add_bank_entry), how to convert this line to django 2.0 version path() pattern? What is does C[DR] do?
downvote count: 0
has title: how to convert regular expression of django 1.4 to django 2.0 style path?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51694082
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51694132
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/51694132

http://stackoverflow.com/a/51691864
has body: Best practice for Pytorch 0.4.0 is to write device agnostic code: That is, instead of using .cuda() or .cpu() you can simply use .to(torch.device("cpu")) A = A.to(dtype=torch.long, device=torch.device("cpu")) Note that .to() is not an "in-place" operation (see, e.g., this answer), thus you need to assign A.to(...) back into A.
answers question: http://stackoverflow.com/q/51664192
downvote count: 0
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/51659030
type: Answer
score: 1
has body: You should use tree.iterlinks() in your for loop: for i in tree.iterlinks(): print(i) Output: (&lt;Element style at 0x7f9e6e41ca48&gt;, None, '/images/nav_logo229.png', 1054) (&lt;Element link at 0x7f9e6e406db8&gt;, 'href', '/images/branding/product/ico/googleg_lodp.ico', 0) ...
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51658528
answers question: http://stackoverflow.com/q/51658528
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90299824
has comment: http://stackoverflow.com/comment/90297136

http://stackoverflow.com/a/51717027
type: Answer
score: 0
has body: You can try using regex. import re pattern = "Power Scheme GUID: ([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})\s+\(([a-zA-Z ]+)\)" mystr = "Existing Power Schemes (* Active)\n-----------------------------------\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (Balanced)\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (High performance)\nPower Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (Power saver) *" re.findall(pattern, mystr) # results: [('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Balanced'), ('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'High performance'), ('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Power saver')] Given a string and a pattern, you can find all the parts of the string that match your pattern. In this case, I created a pattern, and grouped (using paranthesis) the id part and the type part. The result is a list of tuples. Each tuple is a pattern match.
answers question: http://stackoverflow.com/q/51697784

http://stackoverflow.com/q/51678770
accepted answer: http://stackoverflow.com/a/51680246
has body: I have python script myscript.py that I compiled with pyinstaller with the following command: pyinstaller -F myscript.py . Now I get a file called myscript.exe . In my script, there are line that I wrote to get the path of this file using the following code: this_file = os.path.realpath(__file__) src = this_file filenameOnly, file_extension = os.path.splitext(src) exeFile = filenameOnly+'.exe' print ('exe file to check', exeFile) if os.path.exists(exeFile): src = exeFile print ('Binary file', src) But this works well only if the .exe file is having the same name as the initial .py file. If I rename the binary file, my script will not detect that change
answer count: 2
has answer: http://stackoverflow.com/a/51679039
favorite count: 0
possible better answer: http://stackoverflow.com/a/51679039
downvote count: 2
tagged with: python
tagged with: python-os
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51680246
has title: How to get python script file path that has been compiled in binary .exe?
linked to: http://stackoverflow.com/q/25984395
type: Question
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/4117530

http://stackoverflow.com/q/51733399
accepted answer: http://stackoverflow.com/a/51737649
linked to: http://stackoverflow.com/q/51679173
type: AnsweredQuestion
tagged with: statsmodels
score: 1
has comment: http://stackoverflow.com/comment/90443439
has body: sorry I am still fairly new to python and hoping someone can help me with a curve fitting issue... I have a MxN dataframe "data" where M is number of samples and N is number of variables (10). I have a Mx1 dependent variable "Fractions" which are a fraction between 0 and 1 that correspond to each sample. I know how to easily run a multiple linear regression between the independent variables N and and dependent variable Fractions, however, I wrapped the regression in a sigmoid regression to keep responses between 0 and 1. I was able to perform this like so... def sigmoid(x,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10): y = 1 / (1 + np.exp(- (b0 + b1*x[:,0] + b2*x[:,1] + b3*x[:,2] + b4*x[:,3] + b5*x[:,4] + b6 * x[:,5] + b7*x[:,6] + b8*x[:,7] + b9*x[:,8] + b10*x[:,9]))) return y popt, pcov = curve_fit(sigmoid,data,fractions) '''use coefficients from curve_fit to estimate new fraction from new 1xN data''' newFraction = sigmoid(newData, *popt) However, I would like to implement some sort of stepwise multiple regression for feature selection, preferably based on AIC. I have found these following methods using python... http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html https://planspace.org/20150423-forward_selection_with_statsmodels/ https://datascience.stackexchange.com/questions/24405/how-to-do-stepwise-regression-using-sklearn/24447#24447 But all of these methods rely on using a regression that involves a .fit() method. Is there a way to implement a model like above using a any of the .fit() methods like statsmodels or lmfit? I have also looked into Lasso-type methods, however, again can't figure out how to implement my function.
tagged with: scipy
type: Question
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90443976
has answer: http://stackoverflow.com/a/51737649
has title: python curve fitting with results summary
answer count: 1
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/90435088
favorite count: 0
has comment: http://stackoverflow.com/comment/90445140
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51798701
accepted answer: http://stackoverflow.com/a/51798965
tagged with: ipython
downvote count: 0
answer count: 1
tagged with: shell
score: 1
has title: How to input password to a shell command 'git push' from a Jupyter Notebook?
favorite count: 0
tagged with: linux
linked to: http://stackoverflow.com/q/44996933
tagged with: python
has body: I have the following code in a Jupyter Notebook's cell: !git push origin master which will ask my password for Github but the cell keeps on running as I can't find the way to input my password. For some reason, I want to push the code this way. I tried to follow the similar questions but nothing seems to be working in my case. Here's what I tried and it didn't work: import getpass import os password = getpass.getpass() command = "git -S push origin master " #can be any command but don't forget -S as it enables input from stdin os.system('echo %s | %s' % (password, command)) Here's the log for above: unknown option: -S usage: git [--version] [--help] [-C &lt;path&gt;] [-c &lt;name&gt;=&lt;value&gt;] [--exec-path[=&lt;path&gt;]] [--html-path] [--man-path] [--info-path] [-p | --paginate | --no-pager] [--no-replace-objects] [--bare] [--git-dir=&lt;path&gt;] [--work-tree=&lt;path&gt;] [--namespace=&lt;name&gt;] &lt;command&gt; [&lt;args&gt;]
tagged with: jupyter-notebook
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51798965
type: Question

http://stackoverflow.com/comment/90625236
has text: Should be fixed now. Apologies.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51781334
type: Comment

http://stackoverflow.com/comment/90514381
comment on: http://stackoverflow.com/q/51778079
score: 0
type: Comment
type: QuestionComment
has text: This question is a bit unintelligible. A clearer way to ask is to show some input and expected output.

http://stackoverflow.com/comment/90379127
comment on: http://stackoverflow.com/q/51708998
score: 1
has text: what about this? https://joytokey.net/en/
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90538853
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51790676
has text: Why are you placing that code inside the `foo` class definition at all?
score: 0

http://stackoverflow.com/q/51793396
duplicate of: http://stackoverflow.com/q/28958825
score: 2
favorite count: 0
answer count: 0
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/112774691
tagged with: cython
linked to: http://stackoverflow.com/q/35601229
has body: I'm trying to get the source code of a python program and have come to realize that is it likely Cython due to a ton of *.pyd files in the library.zip. I don't have experience with these; however I have noticed I can open this .pyd file in 7zip giving me the following files: my question is can any of these be decompiled into a python source? I cannot find anything regarding actually opening the PYD file with 7zip - there is a general thread about decompiling however it never mentions anywhere about the files found when you open it with 7zip.
duplicate of: http://stackoverflow.com/q/35601229
linked to: http://stackoverflow.com/q/28958825
downvote count: 0
type: UnansweredQuestion
has title: Opening PYD files with 7zip

http://stackoverflow.com/q/51645246
possible better answer: http://stackoverflow.com/a/51645621
type: Question
has answer: http://stackoverflow.com/a/51645621
type: AnsweredQuestion
tagged with: testing
tagged with: robotframework
has comment: http://stackoverflow.com/comment/90259088
has comment: http://stackoverflow.com/comment/90294236
has comment: http://stackoverflow.com/comment/90272400
score: -1
has answer: http://stackoverflow.com/a/54381675
answer count: 2
has body: I have tried installing Robot Framework with python 2.7 in Ubuntu 16.04. firstly I installed Python and then I installed pip after that I installed Robot Framework pip install robot framework and then selenium library pip install robotframework-selenium2library with pip. After that when I tried to install RIDE IDE using pip pip install robotframework-ride I am unable to install RIDE and I am getting an error like Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/robotframework_ride-1.5.2.1.dist-info' Consider using the --user option or check the permissions. I tried with the permission thing but I am still unable to solve the issue. I googled the solution but couldn't find an exact solution to this issue.
accepted answer: http://stackoverflow.com/a/54381675
favorite count: 0
has comment: http://stackoverflow.com/comment/90260893
linked to: http://stackoverflow.com/q/31512422
has comment: http://stackoverflow.com/comment/90254868
tagged with: python
has title: Install robot framework with python in Ubuntu 16.04
has comment: http://stackoverflow.com/comment/90254979
downvote count: 2
upvote count: 1
tagged with: pip

http://stackoverflow.com/comment/90546365
type: Comment
type: QuestionComment
has text: @piRSquared either first or last would be fine.
comment on: http://stackoverflow.com/q/51794147
score: 0

http://stackoverflow.com/a/51744142
type: Answer
has comment: http://stackoverflow.com/comment/90449103
answers question: http://stackoverflow.com/q/51743776
has body: def filter_function(input): words_to_be_filtered = ["rude", "words"] searched = map(lambda x: x in input, words_to_be_filtered) return reduce(lambda x,y: x or y, searched, False) inputs = ["something", "somethingrude", "sometwordshing"] print(filter(filter_function, inputs)) Function above gives the following result : ['somethingrude', 'sometwordshing']. I hope this works for you.
has comment: http://stackoverflow.com/comment/90453953
has comment: http://stackoverflow.com/comment/90449327
score: 0
has comment: http://stackoverflow.com/comment/90448609
has comment: http://stackoverflow.com/comment/90448767

http://stackoverflow.com/q/51792477
favorite count: 0
has title: tkinter run function in parent window when child window closes
tagged with: python
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90542601
score: 1
has answer: http://stackoverflow.com/a/51793859
answer count: 2
has body: I have a parent window in tkinter that opens a child window like this: def openChild(data): callChildFunc(data,"y") Button(dash, text="Open", command=partial(openChild, data)) This calls a function callChildFunc(data,fill) which takes input and saves it to a json file. The child window closes like this: def getInput(file): #bunch of commands to save data from input fields... childform.destroy() Button(childform, text="Save", command=partial(getInput, data)) I want to call a function in the parent window when the child window is destroyed. Is there any way for the parent window to detect when the child is destroyed, or a way to pass an argument from the destroyed window back to the parent?
has answer: http://stackoverflow.com/a/51828787
downvote count: 0

http://stackoverflow.com/q/51731420
has comment: http://stackoverflow.com/comment/90423677
possible better answer: http://stackoverflow.com/a/56229196
score: 2
tagged with: pycharm
downvote count: 0
has body: I have the newest PyCharm version (2018) and the latest Django version (2.1) and Python (3.6) When I want to import something in PyCharm from Django: from django.urls import url I get an error message under django stating: Unresolved reference 'django' I created a virtual environment and I ran a project on it, the most famous one (polls) and it ran very well. But now I noticed that I have this error, what is the solution? Thank you in advance.
accepted answer: http://stackoverflow.com/a/51739371
tagged with: django
has comment: http://stackoverflow.com/comment/90424436
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51739371
has comment: http://stackoverflow.com/comment/90424278
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/56229196
has comment: http://stackoverflow.com/comment/90428731
has comment: http://stackoverflow.com/comment/90423968
has comment: http://stackoverflow.com/comment/90425454
tagged with: virtualenv
favorite count: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/65937657
has title: PyCharm 2018 Python Unresolved Reference 'django' VirtualEnv

http://stackoverflow.com/a/69404694
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51745898
score: 1
has body: I came across same issue recently. Your DATABSE_URL env variable in file .local/.postgres needs to be : DATABASE_URL=postgres://username:password@{DB_SERVICE_NAME}:5432/marketing As you can see here in place of localhost use "postgres" if your docker-compose.yml has service name as postgres.
downvote count: 0

http://stackoverflow.com/q/51778590
has answer: http://stackoverflow.com/a/51778692
score: 1
type: Question
has body: I understand this may be a very simple question, however I'm new to python and I'm unsure how to manipulate pandas data frames very well. Lets say as an example data: Job Skill RelationType Director Manage staff essential Director Manage staff optional Target Lets say as an example data: Job Skill RelationType Director Manage staff essential Director Manage staff essential Ideally I want to write a function that when the RelationType is different but the Skill is the same it overwrite and replace by in this case for the essential. So for the same job a essential skill will be always more important than the optional. Solved df['RelationType'] = df.groupby(['Jobs', 'Skill'])['RelationType'].transform('min')
tagged with: data-manipulation
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51778692
tagged with: pandas
has comment: http://stackoverflow.com/comment/90515386
favorite count: 0
has title: Data manipulation in pandas - python
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/96536902
has text: That’s interesting idea, I’ll give it a try. Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/54882795
type: Comment
score: 0

http://stackoverflow.com/comment/90448400
comment on: http://stackoverflow.com/q/51742453
type: QuestionComment
type: Comment
has text: I have written a process file in python and able to read input files content and writing to output file but when i run process file again same data is appending to output file without proper check. same content shouldn't be append
score: 0

http://stackoverflow.com/comment/90360725
type: Comment
has text: yes, that works. i am not sure, but does s mean the text file?
comment on: http://stackoverflow.com/a/51699144
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90390027
comment on: http://stackoverflow.com/q/51714244
has text: It's not clear what you want the result to be.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90521452
comment on: http://stackoverflow.com/a/51781893
type: Comment
has text: I suggest you update your question with the information about running the code in a Jupyter Notebook
score: 0
type: AnswerComment

http://stackoverflow.com/q/51743014
accepted answer: http://stackoverflow.com/a/51746212
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a dataframe containing a column type of categorical data, and I have a table (dictionary) of parameter values for each possible type, each entry of which looks like type1: [x1,x2,x3] I have working code looking like this: def foo(df): [x1,x2,x3] = parameters[df.type] return (* formula depending on x1,x2,x3,df.A,df.B *) df['new_variable'] = df.apply(lambda x: foo(x), axis = 1) Iterating through the rows like this (.apply(..., axis=1)) is of course very slow, and I'd like an efficient solution, but I don't know how to do the table-lookup in a neat manner. For instance, I can't just do df['new_variable'] = (* formula depending on parameters[df.type][0:3],df.A,df.B *) as that throws a TypeError: 'Series' objects are mutable, thus they cannot be hashed (I'm naively trying to use a Series as a key, which doesn't work). I suppose I could make new columns for the parameter values, but that seems inelegant somehow, and I'm sure there is a better way. What's the best way to do this? EDIT: I just realised I can get a column with the lists of parameters via df.type.map(parameters) but I can't access the entries of those lists, as the usual index-conventions don't seem to work. E.g. df.type.map(parameters).loc[:,2] gives an IndexingError: Too many indexers; basically pandas gets confused when having too many dimensions without sticking it all in a MultiIndex. Is there a way to get around this? EDIT2: a minimal example: df = pd.DataFrame([['dog',4],['dog',6],['cat',1],['cat',4]],columns = ['type','A']) parameters = {'dog': [1,2], 'cat': [3,-1]} def foo(x): [a,b]=parameters[x.type] return a * x.A + b df['new'] = df.apply(foo,axis=1) produces the desired output type A new 0 dog 4 6 1 dog 6 8 2 cat 1 2 3 cat 4 11
favorite count: 0
has answer: http://stackoverflow.com/a/51746212
tagged with: python
has title: Applying function whose parameters depend on values of a column
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: performance
tagged with: dataframe

http://stackoverflow.com/a/51688423
has comment: http://stackoverflow.com/comment/90338978
has body: getattr(AddEmployee, self.OtherClassMethod)(self) is probably wrong in class All_Contents_Page, which is not a subclass of AddEmployee. Probably AddEmployee.AddEmployee_ReturnAllData is trying to access the cursor self.c on the All_Contents_Page instance, which did not receive a c member during its initialization. It's not clear what your intent there is, so hard to suggest a fix. But that is the likely cause of the error you described.
answers question: http://stackoverflow.com/q/51688330
score: 0
has comment: http://stackoverflow.com/comment/90338830
type: Answer

http://stackoverflow.com/q/51750512
type: AnsweredQuestion
has title: Get index of a number from list
tagged with: list
possible better answer: http://stackoverflow.com/a/51750778
has answer: http://stackoverflow.com/a/51750778
type: Question
upvote count: 2
answer count: 2
has body: [('3604', 0.7113370895385742), ('63', 0.6787939071655273), ('6566', 0.6688929796218872), ('6406', 0.6664271354675293), ('15', 0.6614164113998413)] I want to get index of the first instance instead that is: [(log[3604], 0.7113370895385742), (log[63], 0.6787939071655273), (log[6566], 0.6688929796218872), (log[6406], 0.6664271354675293), (log[15], 0.6614164113998413)] So far I am doing this: new_sentence = "My Order".split(" ") sen2vec.docvecs.most_similar(positive=[sen2vec.infer_vector(new_sentence)],topn=5) to get the list. Any suggestions will help!
score: -2
has answer: http://stackoverflow.com/a/51750581
accepted answer: http://stackoverflow.com/a/51750581
favorite count: 0
has comment: http://stackoverflow.com/comment/90460958
tagged with: python
downvote count: 4

http://stackoverflow.com/q/51784589
upvote count: 1
type: Question
tagged with: opencv
has title: How to validate whether a marked feature is correctly tracking an object in a video by OpenCV?
has body: I want to validate the object detection(the green boxes) which I have marked, whether it's tracking that object only in a video. How do I check whether it's tracking that object only and not moved to any other object? say in this case How do I validate that the left car(black) is tracking correctly over the next set of frames along with another object(white car on the right side) edit: I have tried with finding contours and extracting particularly that object (the black car in this frame) and tried to extract features out of it, but that didn't work.
tagged with: contour
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90677715
has answer: http://stackoverflow.com/a/51786909
favorite count: 0
has comment: http://stackoverflow.com/comment/90654786
tagged with: python
tagged with: computer-vision
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/90256464
type: QuestionComment
has text: Thank you for a nice, consize, well written question following about all guidelines for new questions/on topic/mvce
score: 0
comment on: http://stackoverflow.com/q/51646231
type: Comment

http://stackoverflow.com/a/51738317
score: 0
has comment: http://stackoverflow.com/comment/90436958
has comment: http://stackoverflow.com/comment/90437033
upvote count: 1
has body: The solution by @paragbaxi is fine I would only add an condition to filter out the lines containing only "------". Like so: import csv lines_to_skip = 4 with open('data.csv', 'r') as f: reader = csv.reader(f, delimiter='|') for i in range(lines_to_skip): next(reader) #Skipping lines data = [] for line in reader: if line[0].find("---") != 0: #Check what position has symbol "---" if 0 then skip print(line) data.append(line) print("Last row:\n{}".format(data[-1])) print("Client ID:{} Domain:{}".format(data[-1][0].replace(" ",""),data[-1][4].replace(" ",""))) #replace() just removes unnecessary spaces Output: [' Client ID ', ' Client Type ', ' Service Type ', ' Status ', ' Trust Domain ', ' Data Instance Name ', ' Data Version ', ' Creation Time ', ' Last Update ', ' Scheduled Time ', ' '] [' REFRESH_ROUTINGTIER_ARTIFACTS_1465901168866 ', ' ROUTINGTIER_ARTIFACTS ', ' SYSTEM ', ' COMPLETED ', ' RRA Bulk Client ', ' soa_server1 ', ' 18.2.2.0.0 ', ' 2016-06-14 03:49:55 -07:00 ', ' 2016-06-14 03:49:57 -07:00 ', ' --- ', ' '] [' 500333443 ', ' CREATE ', ' [FA_GSI] ', ' COMPLETED ', ' holder ', ' soa_server1 ', ' 18.3.2.0.0 ', ' 2018-08-07 11:59:57 -07:00 ', ' 2018-08-07 12:04:37 -07:00 ', ' --- ', ' '] [' 500333446 ', ' CREATE ', ' [FA_GSI] ', ' COMPLETED ', ' holder-test ', ' soa_server1 ', ' 18.3.2.0.0 ', ' 2018-08-07 12:04:48 -07:00 ', ' 2018-08-07 12:08:52 -07:00 ', ' --- ', ' '] Last row: [' 500333446 ', ' CREATE ', ' [FA_GSI] ', ' COMPLETED ', ' holder-test ', ' soa_server1 ', ' 18.3.2.0.0 ', ' 2018-08-07 12:04:48 -07:00 ', ' 2018-08-07 12:08:52 -07:00 ', ' --- ', ' '] Client ID:500333446 Domain:holder-test Process finished with exit code 0
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/90437199
accepted answer of: http://stackoverflow.com/q/51738059
has comment: http://stackoverflow.com/comment/90551208
type: Answer
answers question: http://stackoverflow.com/q/51738059
has comment: http://stackoverflow.com/comment/90437237
has comment: http://stackoverflow.com/comment/90548775
has comment: http://stackoverflow.com/comment/90437177

http://stackoverflow.com/a/51756605
answers question: http://stackoverflow.com/q/51756552
type: AcceptedAnswer
has body: IIUC, This dictionary comprehension should do the trick : {k:v[0] for k,v in res.items()} {0: -1.6133319, 1: -1.278326, 2: -0.68584293, 3: -1.2741858, 4: -0.81194735}
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90472704
score: 1
accepted answer of: http://stackoverflow.com/q/51756552

file
tags question: http://stackoverflow.com/q/51773808
type: Tag
tags question: http://stackoverflow.com/q/51775775
tags question: http://stackoverflow.com/q/51653124
tag name: file
tags question: http://stackoverflow.com/q/51682092
tags question: http://stackoverflow.com/q/51743671
tags question: http://stackoverflow.com/q/51772318
tags question: http://stackoverflow.com/q/51700282
tags question: http://stackoverflow.com/q/51723749
tags question: http://stackoverflow.com/q/51744409
tags question: http://stackoverflow.com/q/51702365
tags question: http://stackoverflow.com/q/51778202
tags question: http://stackoverflow.com/q/51700590
tags question: http://stackoverflow.com/q/51654172
tags question: http://stackoverflow.com/q/51752883
tags question: http://stackoverflow.com/q/51690825
tags question: http://stackoverflow.com/q/51678557
tags question: http://stackoverflow.com/q/51705159
tags question: http://stackoverflow.com/q/51706138
tags question: http://stackoverflow.com/q/51655172
tags question: http://stackoverflow.com/q/51763854
tags question: http://stackoverflow.com/q/51709990
tags question: http://stackoverflow.com/q/51644119
tags question: http://stackoverflow.com/q/51699083
tags question: http://stackoverflow.com/q/51735493
tags question: http://stackoverflow.com/q/51788870
tags question: http://stackoverflow.com/q/51748318
tags question: http://stackoverflow.com/q/51707313
tags question: http://stackoverflow.com/q/51663516
tags question: http://stackoverflow.com/q/51786416

http://stackoverflow.com/a/51786370
type: Answer
downvote count: 0
score: 3
has body: You can use the ufuncs built right into numpy. The relevant methods would be: np.abs absolute value of every element in the array (you can also use the builtin abs, which calls np.abs for numpy arrays np.maximum pairwise calls to max np.hypot equivalent to np.sqrt(x**2, y**2) np.logical_and applys and pairwise to elements in an array. Then using the fact that you can use numpy arrays of booleans as indices, what you want would become: matches = np.logical_and(np.maximum(np.abs(x), np.abs(y)) &gt; 5, np.hypot(x, y) &lt; 10) result_x = x[matches] result_y = y[matches] Note, this code uses the numpy builtin functions, which are almost always (significantly) faster than Python loops, since the looping is done in C and not in Python.
upvote count: 3
answers question: http://stackoverflow.com/q/51786039

http://stackoverflow.com/q/51741897
has comment: http://stackoverflow.com/comment/90448004
has title: Compare two columns of a dataframe against 1 column of another dataframe and if matches print the row
type: Question
has body: I have two csv files read into 2 dataframes: df1: Aend Bend A B C D df2 node_name Alarm A alarm1 D alarm2 List =["NTP", "LOS"] I want to check for row1 in df1 if columns Aend or Bend matches with node_name in df2. If yes take the corresponding row from df2 and have to check the condition `if df2[Alarm] contains any value from List : print "YES" else: print "NO" Similarly check for row2 . What would be the best way to do this.
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51744793
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90449022

http://stackoverflow.com/comment/90378792
score: 0
has text: @sniperd Thank you for the suggestion. I'm trying different time delays and it has failed at least once with a 1 second delay. In case the time delay does not work, do you know if there is a way reconnect to the sql db automatically by setting it up inside the python code?
comment on: http://stackoverflow.com/q/51707677
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51705819
linked to: http://stackoverflow.com/q/4869589
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90372598
has comment: http://stackoverflow.com/comment/90373278
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90372433
has answer: http://stackoverflow.com/a/51707497
type: Question
has title: Compare list with dictionary (that contains wildcards), return values
answer count: 1
has body: I have a list that contains several strings and a dictionary with strings (that contain wildcards) as keys and integers as values. For example like this: list1 = ['i', 'like', 'tomatoes'] dict1 = {'tomato*':'3', 'shirt*':'7', 'snowboard*':'1'} I would like to go through list1 and see if there is a key in dict1 that (with the wildcard) matches the string from list1 and get the respective value from dict1. So in this case 3 for 'tomato*'. Is there a way to iterate over list1, see if one of the dict1 keys (with wildcards) matches with this particular string and return the value from dict1? I know I could iterate over dict1 and compare the keys with the elements in list1 this way. But in my case, the dict is very large and in addition, I have a lot of lists to go through. So it would take too much time to loop through the dictionary every time. I thought about turning the keys into a list as well and get wildcard matches with a list comprehension and fnmatch(), but the returned match wouldn't be able to find the value in the dict (because of the wildcard).
has comment: http://stackoverflow.com/comment/90372683
has comment: http://stackoverflow.com/comment/90372770
tagged with: wildcard
score: 0
has comment: http://stackoverflow.com/comment/90372485
accepted answer: http://stackoverflow.com/a/51707497
has comment: http://stackoverflow.com/comment/90373417
has comment: http://stackoverflow.com/comment/90372611
tagged with: python

http://stackoverflow.com/a/51661955
downvote count: 0
has body: Just to see if I could do it, this should find the invoice and the invoice number based on the following assumptions invoice is always present in the string The numbers that appear after invoice are the invoice numbers. I've put some garbage between invoice and the numbers just to ensure I'm able to extract them correctly. It won't take # or no or number. It will also ignore any numbers after it finds the first set of digits. I split str3 up, basically the loop is finding invoice and an digit. Once it finds a digit after invoice (str3 starts at invoice) def isInv(strn): leng = len('invoice') print(leng) pos = strn.find('invoice') strn = strn[pos:leng] if strn == 'invoice': return(1) return(0) def dig(strn): if strn.isdigit()==True: return(1) return(0) str1 = 'invoice' str2 = 'sold to invoice testing garbage 91058780 12345 wal-mart 12345673 corp' fullLen = len(str2) RelvLen = totalLen = str2.find(str1) str3 = str2[totalLen:fullLen] x = str3.split() finlLst = [] for t in x: itm = isInv(t) if itm &gt; 0: finlLst.append(t) itm = dig(t) if itm &gt; 0: finlLst.append(t) inv = finlLst[0] + " " + finlLst[1] print(inv)
type: Answer
has comment: http://stackoverflow.com/comment/90288504
has comment: http://stackoverflow.com/comment/90287542
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90287461
answers question: http://stackoverflow.com/q/51661686

http://stackoverflow.com/a/51793573
type: Answer
answers question: http://stackoverflow.com/q/51792627
has body: if you want to data first sort on length of string so you must change keys orders in your code and also you want your string sort in alphabetical order from tail so you must send characters from tail (x[::-1]) so finally you must change your key by key(len(x), x[::-1])
score: 0

http://stackoverflow.com/comment/90273450
has text: Furthermore like AKX says, it is no good practice to write `ids`, instead of using `ForeignKey`s. By using such keys, you can let the ORM make joins. Furthermore a reasonable database system will enforce that the `id`s match.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51654961

http://stackoverflow.com/comment/90915907
type: AnswerComment
score: 0
type: Comment
has text: @Bhargav added.
comment on: http://stackoverflow.com/a/51927812

http://stackoverflow.com/comment/90453909
score: 0
has text: Is frame non null and does it actually contain an image?
comment on: http://stackoverflow.com/q/51747056
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51698806
score: 0
has title: Euler angles of joints in a kinematic chain with constraints
tagged with: inverse-kinematics
tagged with: rotational-matrices
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I want to find the euler angles that allow the transformation from the image on th e left-hand side to the image on the right-hand side (see below). Joints A and B have a set of contraints: Local coordinate system XYZ given by the angles [0, 0, 20] (other joints may have different coordinate systems). I think this is always relative to the origin (I am reading from an .amc and .asf files) A direction D and a length L; Some joints only allow transformation in one or two axes; The points A and B are part of a kinematic chain. QUESTION: How to compute the rotation matrix that allow the transformation from A to A' taking into consideration their local coordinate system and the rotation constraints? Please Note I am not looking for an inverse kinematics algorithm, in the sense that I already have the joint angles between two segments. I am having trouble to understand how to deal with rotation restrictions, a local coordinate system and direction.
tagged with: opengl
has comment: http://stackoverflow.com/comment/90364119
has comment: http://stackoverflow.com/comment/90367555
type: Question
tagged with: kinematics

http://stackoverflow.com/q/51685330
has comment: http://stackoverflow.com/comment/90332786
has comment: http://stackoverflow.com/comment/90333696
has comment: http://stackoverflow.com/comment/90334481
has answer: http://stackoverflow.com/a/75608581
score: 9
has comment: http://stackoverflow.com/comment/97078713
linked to: http://stackoverflow.com/q/18619121
has comment: http://stackoverflow.com/comment/90333128
has answer: http://stackoverflow.com/a/52000037
tagged with: python
has answer: http://stackoverflow.com/a/57843404
tagged with: selenium-webdriver
tagged with: exit
upvote count: 9
tagged with: selenium
has comment: http://stackoverflow.com/comment/90335711
has comment: http://stackoverflow.com/comment/90333881
has comment: http://stackoverflow.com/comment/90381016
answer count: 4
has comment: http://stackoverflow.com/comment/97493299
downvote count: 0
has title: Python Selenium Detect when the browser is closed
has body: Right now, I use this as a way to detect when the user closes the browser: while True: try: # do stuff except WebDriverException: print 'User closed the browser' exit() But I found out that it is very unreliable and a very bad solution since WebDriverException catches a lot of exception (if not all) and most of them are not due to the user closing the browser. My question is: How to detect when the user closes the browser?
has comment: http://stackoverflow.com/comment/90333744
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73541679
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90333002
has comment: http://stackoverflow.com/comment/90333738

http://stackoverflow.com/a/51797129
score: 4
has comment: http://stackoverflow.com/comment/90551551
answers question: http://stackoverflow.com/q/51797066
has comment: http://stackoverflow.com/comment/90551417
has body: You cannot reliably solve this problem without building a full blown C parser, because there are strings, and nested comments, and the /* sequence can be easily inside the string, like printf( "/* is this a comment or what?" );, etc. Moreover, /* and */ sometimes are used to comment out parts of the code, sometimes quite large blocks, without commenting every line with //, are those code blocks the comments you want to get as your program output? Probably not... Here is a link that might get you going in the right direction: Complete C99 parser in pure Python
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/51748968
score: 1
possible better answer: http://stackoverflow.com/a/51749067
has answer: http://stackoverflow.com/a/51749067
has answer: http://stackoverflow.com/a/51749058
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51749058
downvote count: 0
has body: So, the 3rd party charges differently for certain limits values. Let's just say I'm cheap and don't wanna pay the full rate for unlimited access. The approach I've used is rather simple, I just call sleep for 3 seconds after processing each request (paid for the 20 calls per minute plan). Here is some clipped code for illustration: import requests import sqlite3 from time import sleep timetosleep = 3 conn = sqlite3.connection('db.db') c = conn.cursor() keys = [ "A BIG LIST, SOMETHING LIKE len == 80K" #working with 500 at a time ] def treatResponse(response): #series of validations, some regex and stuff returns "A TUPLE WITH DATA TO THE SQLITE DB" for key in keys: response = requests.get("API ADDRESS AND KEYS", {"auth":"auth"}) #if response is GREAT! yadayada c.execute( """INSERT INTO tbl(field1, field2) values(?, ?)""", treatResponse(response.json())) conn.commit() sleep(timetosleep) As the function used to treat the response is rather expensive, with a bunch of sequential regex calls, and the server may get a long time (relative to the limit/minute) to respond, it may be an overkill to wait 3 full seconds (or even to wait at all). Does anyone has a solution for timing each iteration? If this operation is done neatly, it could be used to reduce the sleep timer and improve performance by a lot. TIA
has title: Timming processing time to deal with requests per minute limits when interacting with 3rd party API
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51672488
type: Question
linked to: http://stackoverflow.com/q/15222754
has title: Calculate Aggregate Mode
score: 0
has answer: http://stackoverflow.com/a/51673052
answer count: 3
tagged with: pandas
has body: I have a dataframe : ID CATEGORY AMOUNT 1 T1 1000 2 T2 1500 3 T3 2000 4 T4 3000 5 T1 2000 6 T2 2500 7 T3 7000 8 T4 4000 9 T1 1000 10 T2 1500 11 T3 2000 12 T4 3000 I want to groupby category and then get the mode of each category: T1 1000 T2 1500 All the way to T4. When I run the below python code I get an error: df['AMOUNT'].groupby(df['CATEGORY']).mode() I get the below error AttributeError: Cannot access callable attribute 'mode' of 'SeriesGroupBy' objects, try using the 'apply' method
has answer: http://stackoverflow.com/a/51672737
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51672710
tagged with: python
duplicate of: http://stackoverflow.com/q/15222754

http://stackoverflow.com/q/51677734
tagged with: python
tagged with: dictionary
tagged with: list
has comment: http://stackoverflow.com/comment/90319891
has body: I want to create a dictionary where the keys are string and the values are the lists. Initially, all lists are empty. Then I want to append an int to a specific list using "append()." The result: the int is appended to ALL list in my dictionary. d = ['a', 'b', 'c'] my_d = dict.fromkeys(d, []) my_d['a'].append(4) print(my_d) {'a': [4], 'b': [4], 'c': [4]} I want it to be : {'a': [4], 'b': [], 'c': []} since I appended 4 to my_d['a'] only
type: Question
has comment: http://stackoverflow.com/comment/90319965
linked to: http://stackoverflow.com/q/8174723
has title: python dictionary: how does appending of items work?
has comment: http://stackoverflow.com/comment/90320118
duplicate of: http://stackoverflow.com/q/8174723
score: 0
has comment: http://stackoverflow.com/comment/90318743
tagged with: append
has comment: http://stackoverflow.com/comment/90319307
has comment: http://stackoverflow.com/comment/90319608
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90455798
has text: @PatrickHaugh, YES exactly
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51747854
type: Comment

http://stackoverflow.com/q/51763467
tagged with: python-3.x
score: 0
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51764025
has comment: http://stackoverflow.com/comment/137013414
has body: I write some code like from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): t = "!!!!!!" return render_template('hello.html', title=t) if __name__ == '__main__': app.run(debug=True) also i have hello.html template in templates folder TEST {{ title }} When I run it I get error File "webui-controller.py", line 9 return render_template('hello.html', title=t) But when I run without title argument (return render_template('hello.html')) it works fine. How can I solve it?
linked to: http://stackoverflow.com/q/45621722
type: AnsweredQuestion
has title: Flask render_template IndentationError
duplicate of: http://stackoverflow.com/q/45621722
has answer: http://stackoverflow.com/a/51764025
type: Question

3d
tags question: http://stackoverflow.com/q/51653965
type: Tag
tag name: 3d
tags question: http://stackoverflow.com/q/51769771

http://stackoverflow.com/q/51735093
type: Question
answer count: 2
score: 5
upvote count: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/52021987
has answer: http://stackoverflow.com/a/52021987
has body: My class looks like this class Foo(): x = attrib() y = attrib() f = Foo(x=1, y=2) My template looks like &lt;html&gt; &lt;body&gt; &lt;span&gt;{{x}}&lt;/span&gt; -&gt; instead of this I want to use foo.x &lt;span&gt;{{y}}&lt;/span&gt; -&gt; instead of this I want to use foo.y &lt;/body&gt; &lt;/html&gt; I use template.render(**attr.asdict(f)) to render it. Instead I want to just pass template.render(f) and use {{f.x}} and {{f.y}} Is there a way to do this? I keep running into the error vars = dict(*args, **kwargs) TypeError: 'Foo' object is not iterable
has answer: http://stackoverflow.com/a/52047503
favorite count: 0
has title: How to pass an object instance to a jinja html template
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52047503
tagged with: jinja2

http://stackoverflow.com/comment/115772453
score: 0
type: Comment
comment on: http://stackoverflow.com/a/55402987
has text: This is the source folder from the Step 1: https://digi.bib.uni-mannheim.de/tesseract/ . You might find there the newer versions of Tesseract OCR.
type: AnswerComment

http://stackoverflow.com/comment/90544449
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51793412
type: QuestionComment
has text: Just match the first parentheses, `r'\(([^()]*)\)'`

xlutils
tags question: http://stackoverflow.com/q/51742362
type: Tag
tag name: xlutils
tags question: http://stackoverflow.com/q/51680979

http://stackoverflow.com/comment/90401895
has text: btw. pip is allready on version 18
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51668485

http://stackoverflow.com/a/51660749
has comment: http://stackoverflow.com/comment/90285962
score: 1
has comment: http://stackoverflow.com/comment/90285028
answers question: http://stackoverflow.com/q/51660670
has comment: http://stackoverflow.com/comment/90284990
upvote count: 1
has body: You can apply a condition check to each row: df[df.col_1.apply(lambda x: 'no issue' in x)]
type: Answer
has comment: http://stackoverflow.com/comment/90284967
downvote count: 0

http://stackoverflow.com/comment/90310782
type: Comment
type: QuestionComment
has text: @jasonharper how would I initalize self.tempresult ? to None ?
comment on: http://stackoverflow.com/q/51673826
score: 0

http://stackoverflow.com/q/51662445
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51663408
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90288351
has comment: http://stackoverflow.com/comment/90288410
has comment: http://stackoverflow.com/comment/90288373
has comment: http://stackoverflow.com/comment/90288607
has title: Alternative to df.iterrows() for joining two Postgres tables and computing features
has comment: http://stackoverflow.com/comment/90288432
possible better answer: http://stackoverflow.com/a/51662697
tagged with: pandas
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51662697
downvote count: 0
has answer: http://stackoverflow.com/a/51663408
has body: I have a dataframe (game_df) and a Postgres table (team_stats_1970_2017). game_df consists of a few thousand rows with data like this... season_yr home_team visitor_team home_team_runs visitor_team_runs 0 2017 ARI SFG 6 5 1 2017 ARI SFG 4 8 2 2017 ARI SFG 8 6 3 2017 ARI SFG 9 3 4 2017 ARI CLE 7 3 5 2017 ARI CLE 11 2 6 2017 ATL LAD 2 3 team_stats_1970_2017 would have this corresponding data team season_yr r_per_g pa ab b_r b_h b2 b3 b_hr 0 ARI 2017 5.01 6224.0 5525 812 1405 314 39 220 1 ATL 2017 4.52 6216.0 5584 732 1467 289 26 165 2 CLE 2017 5.05 6234.0 5511 818 1449 333 29 212 3 LAD 2017 4.75 6191.0 5408 770 1347 312 20 221 4 SFG 2017 3.94 6137.0 5551 639 1382 290 28 128 As an example, for row 1 of game_df, the code selects the "ARI" and "SFG" data from team_stats_1970_2017 in Postgres and creates features from this. This is then repeated for the rest of the rows within game_df. I am currently using df.iterrows, but I am noticing it is quite slow as I am only testing a small piece of my data and it is still taking a while. Would anyone have a better/faster alternative for this? features = [] results = [] for index,row in game_df.iterrows(): import psycopg2 as pg2 connect = pg2.connect(login) cursor=connect.cursor() year, t1, t2, p1, p2 = row p1, p2 = map(int, [p1, p2]) feature1 = cursor.execute("SELECT * FROM team_stats_1970_2017 WHERE team = (%s) and season_yr = (%s)",(t1,year)) feature1 = list(cursor.fetchone()[2::]) feature2 = cursor.execute("SELECT * FROM team_stats_1970_2017 WHERE team = (%s) and season_yr = (%s)",(t2,year)) feature2 = list(cursor.fetchone()[2::]) feature = np.array(feature2) - np.array(feature1) ## Calculate result of game if (p2 - p1) &gt; 0: result = 1 else: result = 0 features.append(feature) results.append(result)
favorite count: 0
tagged with: python-3.x
tagged with: postgresql

http://stackoverflow.com/a/51742499
score: 12
answers question: http://stackoverflow.com/q/51737334
upvote count: 12
type: Answer
has body: You can monkeypatch file opening function and check whether a new file is written. Collect new files in a list. Afterwards, go through the list and remove the files. Example: # spam.py import pathlib import numpy def plain_write(): with open('spam.1', 'w') as f: f.write('eggs') def pathlib_write(): with pathlib.Path('spam.2').open('w') as f: f.write('eggs') def pathlib_write_text(): pathlib.Path('spam.3').write_text('eggs') def pathlib_write_bytes(): pathlib.Path('spam.3').write_bytes(b'eggs') def numpy_save(): numpy.save('spam.4', numpy.zeros([10, 10])) def numpy_savetxt(): numpy.savetxt('spam.5', numpy.zeros([10, 10])) tests Depending on what functions you test, monkeypatching builtins.open may not be enough: for example, to cleanup files written with pathlib, you need to additionally monkeypatch io.open. import builtins import io import os import pytest import spam def patch_open(open_func, files): def open_patched(path, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): if 'w' in mode and not os.path.isfile(path): files.append(path) return open_func(path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) return open_patched @pytest.fixture(autouse=True) def cleanup_files(monkeypatch): files = [] monkeypatch.setattr(builtins, 'open', patch_open(builtins.open, files)) monkeypatch.setattr(io, 'open', patch_open(io.open, files)) yield for file in files: os.remove(file) def test_plain_write(): assert spam.plain_write() is None def test_pathlib_write(): assert spam.pathlib_write() is None def test_pathlib_write_text(): assert spam.pathlib_write_text() is None def test_pathlib_write_bytes(): assert spam.pathlib_write_bytes() is None def test_numpy_save(): assert spam.numpy_save() is None def test_numpy_savetxt(): assert spam.numpy_savetxt() is None
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51737334

http://stackoverflow.com/a/51756620
has comment: http://stackoverflow.com/comment/90474267
type: AcceptedAnswer
has body: Python doesn't use {} for control constructs. Just remove the braces and the semicolons, and you'll be fine.
type: Answer
has comment: http://stackoverflow.com/comment/90472719
accepted answer of: http://stackoverflow.com/q/51756613
answers question: http://stackoverflow.com/q/51756613
score: 0
has comment: http://stackoverflow.com/comment/90472715

http://stackoverflow.com/q/51776981
tagged with: module
favorite count: 0
has comment: http://stackoverflow.com/comment/90512370
type: UnansweredQuestion
tagged with: package
has title: How does one handle multiple modules/packages in python?
has answer: http://stackoverflow.com/a/51777155
score: 10
upvote count: 10
tagged with: import
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90512777
has body: I've spent hours researching this problem, and I'm still baffled. Please find my ignorance charming. I'm building a python program that will allow me to pit two AIs against each other in a game of battleship. Here's my directory structure: . ├── ais_play_battleship │ ├── game.py │ ├── __init__.py │ ├── player.py │ └── ship.py ├── LICENSE ├── README.md └── tests └── ship_test.py 2 directories, 7 files Currently, I'm trying to write ship_test.py, but I cannot seem to import ais_play_battleship.ship. I get the dreaded "ModuleNotFoundError" Here's what my research has taught me about my problem: If you want to import python code from another directory, you should make that directory a package instead of a module. Therefore, I've placed an __init__.py file in the root of ais_play_battleship. Python will only search the directory python is launched from as well as the directory of the script you're running. Therefore, I've been trying to launch my tests by running python3 tests/ship_tests.py from the root directory. Here are my specific questions: Why is the error a "ModuleNotFound" error? Shouldn't it be "PackageNotFound"? Am I correct to make ais_play_battleship a package? How can I keep my tests in a separate directory and still use the code in ais_play_battleship? Please forgive me, as I'm not very good at asking questions on StackOverflow. Please tell me how I can improve.
has answer: http://stackoverflow.com/a/51790131
has answer: http://stackoverflow.com/a/67191361
answer count: 3
tagged with: python

http://stackoverflow.com/comment/90252653
type: QuestionComment
score: 0
has text: the `self._drones` is a dict with a key, supposed to be drone.id, if `add` change the drone.id, that is a serious flaw. same as changing a person's name, and try to find the person by name
type: Comment
comment on: http://stackoverflow.com/q/51643904

http://stackoverflow.com/q/51751483
has comment: http://stackoverflow.com/comment/90463140
has title: Tkinter - Accessing class value of checkbox
upvote count: 1
downvote count: 1
has body: I am trying to get a working example going of retrieving the text within a gui when a button is clicked in a tkinter GUI. I am using Python 36. How do I access the guiCheckState variable from within the button? from tkinter import * from tkinter import ttk import tkinter as tk class MyGUI(): def __init__(self, master): self.master = master self.printButton = Button(master, text="PRINT VALUE", width=17, command=Main.printButton, background='GREEN').grid(row=1,column=0,sticky="w") guiCheckState = IntVar(master) self.testCheck = Checkbutton(master, text="Max Price: ", variable=guiCheckState, background='#b3d0e8').grid(row=13,column=0,sticky="w") class Main(): def main(): root = Tk() root.geometry('300x300') root.configure(background='#b3d0e8') root.protocol("WM_DELETE_WINDOW", exit) gui = MyGUI(root) root.mainloop() def printButton(): print(MyGUI.guiCheckState) #AttributeError: type object 'MyGUI' has no attribute 'guiCheckState' Main.main() Thank you!!!
type: Question
has comment: http://stackoverflow.com/comment/90463059
score: 0
answer count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51753286
has answer: http://stackoverflow.com/a/51751598
tagged with: tkinter

http://stackoverflow.com/comment/112711214
type: AnswerComment
comment on: http://stackoverflow.com/a/51751514
score: 0
type: Comment
has text: @BryanOakley I suggest that you add a warning about the multiple bindings to your answer. I fell into the trap and would never have noticed it if I had not red the comments.

http://stackoverflow.com/q/51702122
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54386704
type: Question
answer count: 2
upvote count: 9
tagged with: event-loop
has body: What is the best method to have an asyncio event loop run in a Flask app? My main.py looks like this: if __name__ == '__main__': try: app.run(host='0.0.0.0', port=8000, debug=True) except: logging.critical('server: CRASHED: Got exception on main handler') logging.critical(traceback.format_exc()) raise To add the option of async tasks, I needed to create an event_loop before running the app, but even when stopping the app run, a background thread still hangs (observable in debugger) if __name__ == '__main__': try: app.event_loop = asyncio.get_event_loop() app.run(host='0.0.0.0', port=8000, debug=True) except: logging.critical('server: CRASHED: Got exception on main handler') logging.critical(traceback.format_exc()) raise finally: app.event_loop.stop() app.event_loop.run_until_complete(app.event_loop.shutdown_asyncgens()) app.event_loop.close() And using the following to create async tasks: def future_callback(fut): if fut.exception(): logging.error(fut.exception()) def fire_and_forget(func, *args, **kwargs): if callable(func): future = app.event_loop.run_in_executor(None, func, *args, **kwargs) future.add_done_callback(future_callback) else: raise TypeError('Task must be a callable') The only solution I could find was to add exit() at the end of the finally block, but I don't think its the correct solution.
has comment: http://stackoverflow.com/comment/90405863
tagged with: flask
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/54386704
tagged with: python-asyncio
downvote count: 0
possible better answer: http://stackoverflow.com/a/52948167
favorite count: 0
has answer: http://stackoverflow.com/a/52948167
score: 9
tagged with: python
has title: asyncio event_loop in a Flask app

django-rest-framework
tags question: http://stackoverflow.com/q/51759020
tags question: http://stackoverflow.com/q/51776014
tags question: http://stackoverflow.com/q/51639826
tags question: http://stackoverflow.com/q/51750876
tags question: http://stackoverflow.com/q/51728593
tags question: http://stackoverflow.com/q/51769255
tags question: http://stackoverflow.com/q/51798476
tags question: http://stackoverflow.com/q/51765035
tags question: http://stackoverflow.com/q/51726827
tags question: http://stackoverflow.com/q/51729973
tags question: http://stackoverflow.com/q/51761652
tags question: http://stackoverflow.com/q/51715256
tags question: http://stackoverflow.com/q/51710053
type: Tag
tags question: http://stackoverflow.com/q/51643547
tags question: http://stackoverflow.com/q/51713938
tags question: http://stackoverflow.com/q/51752001
tags question: http://stackoverflow.com/q/51704472
tags question: http://stackoverflow.com/q/51761077
tags question: http://stackoverflow.com/q/51717170
tags question: http://stackoverflow.com/q/51780684
tags question: http://stackoverflow.com/q/51677740
tags question: http://stackoverflow.com/q/51768708
tags question: http://stackoverflow.com/q/51719611
tags question: http://stackoverflow.com/q/51643680
tags question: http://stackoverflow.com/q/51715851
tags question: http://stackoverflow.com/q/51707016
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/51763488
tags question: http://stackoverflow.com/q/51745803
tags question: http://stackoverflow.com/q/51676351
tags question: http://stackoverflow.com/q/51684793
tags question: http://stackoverflow.com/q/51789273
tags question: http://stackoverflow.com/q/51709659
tags question: http://stackoverflow.com/q/51684467
tags question: http://stackoverflow.com/q/51735632
tags question: http://stackoverflow.com/q/51647889

http://stackoverflow.com/a/51721287
has body: Since Your urls.py looks follow. urlpatterns = [url(r'social-auth/', include('social_django.urls', namespace='social')) ] u have add callback URL in the Twitter App Configuration like follow. https://humbusy.tk/social-auth/complete/twitter/ http://humbusy.tk/social-auth/complete/twitter/
score: 0
accepted answer of: http://stackoverflow.com/q/51719623
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51719623
type: Answer

http://stackoverflow.com/q/51648284
has title: How to process data from DataTables Editor in Django?
score: 0
tagged with: datatables
answer count: 1
tagged with: ajax
has comment: http://stackoverflow.com/comment/90260184
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51648620
has comment: http://stackoverflow.com/comment/90260297
type: Question
tagged with: jquery-datatables-editor
has body: I'm trying to process data sent via DataTables Editor plugin in a Django view. The received request.POST looks like: {'action': 'edit', 'data[3115][row1]': 'value1', 'data[3115][row2]': 'value2', 'data[3115][row3]': 'value3', 'data[3115][row4]': 'value4', 'data[3115][row5]': 'value5'} where 3115 is the primary key of my model. Whats the intended approach in Django view to get PK and model.row1, model.row2, model.row3,... values from the POST data? The desired output would be something like result = { 'pk': 3115, 'row1': 'value1', 'row2': 'value2', 'row3': 'value3', 'row4': 'value4', 'row5': 'value5' }

http://stackoverflow.com/a/51722987
downvote count: 0
answers question: http://stackoverflow.com/q/51722218
accepted answer of: http://stackoverflow.com/q/51722218
score: 1
has comment: http://stackoverflow.com/comment/90406592
type: AcceptedAnswer
has body: Your first bit of code for store in inventory_list: print(store['serial_id']) is throwing an error because for k in dictionary iterates through the keys of a dictionary, setting each key as k. When you try to access store[x], you're telling python to access the character in position x of string store. However, you have used a string (serial_id), so python is telling you that it expects an integer. The second snippet for store in inventory_list.items(): print(store['serial_id']) makes the same error, but store in this case is a tuple of (key, value). The more common way to use this syntax is to access both keys and values, as follows: inventory_list = { 'store a': { 'apples': 10, 'bananas': 5, 'cows': 2 }, 'store b': { 'apples': 5, 'bananas': 10 } } for store, stuff in inventory_list.items(): print( store ) print( stuff ) returns store a {'apples': 10, 'bananas': 5, 'cows': 2} store b {'apples': 5, 'bananas': 10} If you want to iterate through the data within each of the nested dictionaries, do so as if you were accessing a top-level item, i.e. # using the same inventory list as before for k,v in inventory_list.items(): print("Inventory for store " + k) # v is a reference to a dictionary, so iterate through that for item, qtt in v.items(): print("Item: " + item + "; quantity: " + str(qtt)) Output: Inventory for store store a Item: apples; quantity: 10 Item: bananas; quantity: 5 Item: cows; quantity: 2 Inventory for store store b Item: apples; quantity: 5 Item: bananas; quantity: 10 If you want to access data in the nested dictionary directly, you can do so using by key: for k,v in inventory_list.items(): print(k + " has " + str(v['apples']) + ' apples in stock') Output: store a has 10 apples in stock store b has 5 apples in stock If you have a list of dictionaries, you can iterate through it using for x in list, where each x will be dictionary: inventory_list = [ { 'apples': 10, 'bananas': 5, 'cows': 2 }, { 'apples': 5, 'bananas': 10 }] for store in inventory_list: p…
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90406798

http://stackoverflow.com/q/51658153
favorite count: 0
possible better answer: http://stackoverflow.com/a/62872525
has answer: http://stackoverflow.com/a/65597914
score: 6
has answer: http://stackoverflow.com/a/62872525
tagged with: python
upvote count: 6
type: AnsweredQuestion
has title: Lemmatize a doc with spacy?
tagged with: spacy
has body: I have a spaCy doc that I would like to lemmatize. For example: import spacy nlp = spacy.load('en_core_web_lg') my_str = 'Python is the greatest language in the world' doc = nlp(my_str) How can I convert every token in the doc to its lemma?
has answer: http://stackoverflow.com/a/51658792
type: Question
tagged with: lemmatization
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51658792
tagged with: nlp

http://stackoverflow.com/q/51718690
upvote count: 1
type: Question
has body: Here's a sample of my code. def send_text(mobile_phone, msg): customer_id = "..." api_key = "..." phone_number = mobile_phone message = msg message_type = "ARN" messaging = MessagingClient(customer_id, api_key) response = messaging.message(phone_number, message, message_type) print(response, messaging.message(phone_number, message, message_type)) send_text(input('Enter your phone number:')(?)). I am not sure what to put in the second parameter. If I put a message in the second parameter then it give's me an error that says str isn't callable. If anyone can help me that would be great.
has title: I want to know how I should fill in the second parameter in order that I don't get str not callable error
has answer: http://stackoverflow.com/a/51718720
answer count: 2
has answer: http://stackoverflow.com/a/51718789
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1

http://stackoverflow.com/q/51712984
tagged with: python
has body: I am trying to scrape data off this url: https://www.apple.com/ca/shop/browse/home/specialdeals/mac/macbook_pro/13 I am trying to retrieve the line that says 8GB of 2133MHz LPDDR3 onboard memory or 16GB of 2133MHz LPDDR3 onboard memory in each container in containers = soup.findAll('tr', {'class': 'product'}) using BeautifulSoup. The problem is it has line breaks and multiple newlines around it, which makes it difficult for me to parse. How can I retrieve this?
type: AnsweredQuestion
score: 1
tagged with: web-scraping
upvote count: 1
has title: Web scraping data with line breaks
type: Question
linked to: http://stackoverflow.com/q/51755623
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51714156
tagged with: web
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/51714156

sql
tags question: http://stackoverflow.com/q/51670451
tags question: http://stackoverflow.com/q/51657923
tags question: http://stackoverflow.com/q/51775250
tags question: http://stackoverflow.com/q/51752005
tags question: http://stackoverflow.com/q/51661061
tags question: http://stackoverflow.com/q/51716348
tags question: http://stackoverflow.com/q/51678132
tags question: http://stackoverflow.com/q/51679270
tags question: http://stackoverflow.com/q/51749603
tags question: http://stackoverflow.com/q/51762785
tags question: http://stackoverflow.com/q/51743584
tags question: http://stackoverflow.com/q/51715089
tags question: http://stackoverflow.com/q/51643089
tags question: http://stackoverflow.com/q/51704754
tags question: http://stackoverflow.com/q/51734803
tags question: http://stackoverflow.com/q/51662547
tags question: http://stackoverflow.com/q/51643509
tags question: http://stackoverflow.com/q/51782946
tags question: http://stackoverflow.com/q/51648849
tags question: http://stackoverflow.com/q/51706011
tag name: sql
tags question: http://stackoverflow.com/q/51776595
type: Tag
tags question: http://stackoverflow.com/q/51765475
tags question: http://stackoverflow.com/q/51655478
tags question: http://stackoverflow.com/q/51767855
tags question: http://stackoverflow.com/q/51715851
tags question: http://stackoverflow.com/q/51739196
tags question: http://stackoverflow.com/q/51706803
tags question: http://stackoverflow.com/q/51702208
tags question: http://stackoverflow.com/q/51659046
tags question: http://stackoverflow.com/q/51707677
tags question: http://stackoverflow.com/q/51751194
tags question: http://stackoverflow.com/q/51759304
tags question: http://stackoverflow.com/q/51644478
tags question: http://stackoverflow.com/q/51676316
tags question: http://stackoverflow.com/q/51702199
tags question: http://stackoverflow.com/q/51663438
tags question: http://stackoverflow.com/q/51701258
tags question: http://stackoverflow.com/q/51746423
tags question: http://stackoverflow.com/q/51677027
tags question: http://stackoverflow.com/q/51726782
tags question: http://stackoverflow.com/q/51743530
tags question: http://stackoverflow.com/q/51733152
tags question: http://stackoverflow.com/q/51776507
tags question: http://stackoverflow.com/q/51776309
tags question: http://stackoverflow.com/q/51751943
tags question: http://stackoverflow.com/q/51732678
tags question: http://stackoverflow.com/q/51764038
tags question: http://stackoverflow.com/q/51777543
tags question: http://stackoverflow.com/q/51692704

http://stackoverflow.com/a/51736642
has body: Try python3 -m pip install pyTelegramBotAPI Probably pip installs the module to a different python version.
type: Answer
has comment: http://stackoverflow.com/comment/90454946
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51668485
upvote count: 2

http://stackoverflow.com/comment/90588861
comment on: http://stackoverflow.com/q/51791188
has text: The default for StatifiedKFold is `shuffle=False`, and `random_state` is only used when `shuffle=True`, so not sure whether this is causing the problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51797315
has body: You can use infer_datetime_format: pd.to_datetime("1-Sep-14",infer_datetime_format=True)# "%d-%m-%y") gives : Timestamp('2014-09-01 00:00:00') If you want to remove hour-minute-second, you can : pd.to_datetime("1-Sep-14",infer_datetime_format=True)# "%d-%m-%y").date() which gives : datetime.date(2014, 9, 1)
answers question: http://stackoverflow.com/q/51797198
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51797198
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90552336
score: 1
has comment: http://stackoverflow.com/comment/90551765
type: AcceptedAnswer

http://stackoverflow.com/q/51762615
tagged with: python
has title: How to streamline my code (+ split column issue)?
has comment: http://stackoverflow.com/comment/90527213
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90527189
has body: I hope some more experienced python'ers are able to help me towards a more streamline approach for my current code. WHAT I GOT/WANT: I am having a table looking like this: study id; rack position; box number; freeze-thaw cycles; new rack position; new box number; project code 24; A1; 10001; 1; A2; 11040; 1,2 25; B1; 10002; 0; A4; 11045; 1 26; C2; 10003; 0; A5; 13420; 2 which I want to parse into the following format (id = study id, count = freeze-thaw cycles - and where multiple project codes are separated and put in separate rows): id; field; count; value 24; rack position; 1; A1 24; box number; 1; 10001 24; new rack position; 1; A2 24; new box number; 1; 11040 24; project code; 1; 1 24; project code; 1; 2 25; rack position; 0; B1 25; box number; 0; 10002 25; new rack position; 0; A2 25; new box number; 0; 11040 25; project code; 0; 1 26; and so on... HOW FAR I GOT: # import pandas import pandas as pd # reading in the data df = pd.read_table('data.csv', delimiter=';') # rename "study id" and "freeze-thaw cycles" df = df.rename(columns={'study id': 'id', 'freeze-thaw cycles': 'count'}) # splitting "project code" df = df.join(df['project code'].str.split(',', 1, expand=True).rename(columns={0:'Project code1', 1:'Project code2'})) # remove "project code" df = df.drop('project code', 1) # Split the dataframe based on Project code1 and Project code2 df1 = df'box number', 'rack position', 'id', 'count', 'new box number', 'new Rack Position', 'Project code1' df2 = df'box number', 'rack position', 'id', 'count', 'new box number', 'new rack position', 'Project code2' # rename Project code1 and Project code2 to Project code df1 = df1.rename(columns={'Project code1': 'Project code'}) df2 = df2.rename(columns={'Project code2': 'Project code'}) # concatenate the dataframes based on "Project code" df = pd.concat([df1, df2], axis=0) #axis=0 for columns, axis=1 for rows # convert the data frame into the long format df = pd.melt(df, id_vars=['id', 'count'], var_name='field'…
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/18172851
tagged with: parsing
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90527429

http://stackoverflow.com/q/51702594
accepted answer: http://stackoverflow.com/a/51709884
tagged with: python
has comment: http://stackoverflow.com/comment/90366589
score: 1
upvote count: 1
has title: How to add acceleration to velocity?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51709884
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: I have an image called arrow. I want to shoot arrows when I press spacebar. I did it by calculating velx and vely by using an angle I already have. velx = math.cos(angle)*10 vely = math.sin(angle)*10 I added velx to the x-coordinate of my image and vely to y-coordinate of my image and I'm able to shoot arrows. Now, I want to accelerate vely by -9.8 . How do I do it?

http://stackoverflow.com/q/51650326
has comment: http://stackoverflow.com/comment/90264675
tagged with: python
tagged with: connection
tagged with: snmp
answer count: 0
tagged with: request
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90264611
has title: can i check connection without request and reply in real time
has comment: http://stackoverflow.com/comment/90264062
has body: as stated above, i want to check any connection between 2 device or more, i want to check their connectivity, but i do not want to use any thing that require request and reply, i know that you can use Simple Network Management Protocol trap, but Simple Network Management Protocol trap still need to add 1 more device in between, and that device will still use ping request and reply, is there something that i could do? to detect the connection, through some protocol, i had try Control Protocol and ping, but both require request and reply. thank you
has comment: http://stackoverflow.com/comment/90264912
tagged with: reply
type: UnansweredQuestion

http://stackoverflow.com/q/51747646
favorite count: 0
has title: tensorflow stopped and no error report
tagged with: python
downvote count: 0
type: UnansweredQuestion
has body: my python version is 3.6.5 CUDA version is 9.0 tensorflow version is 1.9.0 I'm a beginner. I build a CNN network and run it in python shell. But it doesn't work, and no error report, so I don't know what the problem is. Later, the python shell restart. Here is my code, hope somebody can help me. Thanks a lot! import numpy as np import tensorflow as tf #ms=readmnist.mnistset() from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) #parameters learning_rate = 0.01 num_steps = 200 batch_size = 16 display_step = 10 tf.reset_default_graph() x=tf.placeholder(tf.float32,[None,784]) y_=tf.placeholder(tf.float32,[None,10]) #def of objects class NN: def __init__(self): self.W={} self.b={} self.layer={} self.n=0 def creatNN(self,x,inputsize,outputsize): self.W[self.n]=tf.Variable(tf.random_normal([inputsize,outputsize],mean=0.0,stddev=0.2)) self.b[self.n]=tf.Variable(tf.random_normal([outputsize],mean=0.0,stddev=0.2)) self.layer[self.n] =tf.add(tf.matmul(x,self.W[self.n]),self.b[self.n]) self.n=self.n+1 return self.layer[self.n-1] class CNN: def __init__(self): self.wc={} self.bc={} self.layer={} self.clayer={} self.n=0 def creatCNN(self,x,strides=1,k=2,coresize=5,tsize=1,outputsize=32): self.wc[self.n]=tf.Variable(tf.random_normal([coresize,coresize,tsize,outputsize])) self.bc[self.n]=tf.Variable(tf.random_normal([outputsize])) self.layer[self.n]=tf.nn.conv2d(x, self.wc[self.n], strides=[1, strides, strides, 1], padding='SAME') self.layer[self.n]=tf.nn.bias_add(self.layer[self.n],self.bc[self.n]) self.layer[self.n]=tf.nn.relu(self.layer[self.n]) self.clayer[self.n]=tf.nn.max_pool(self.layer[self.n],ksize=[1,k,k,1],strides=[1,k,k,1],padding='SAME') self.n=self.n+1 return self.clayer[self.n-1] x_img = tf.reshape(x, [-1,28,28,1]) ''' construct the network ''' nn=NN() cnn=CNN() cnn1=cnn.creatCNN(x_img,1,2,5,1,32) cnn2=cnn.creatCNN(cnn1,1,2,5,32,64) tnn=tf.reshape(cnn2,[-1,7*7*64]) nn1=nn.creatNN(tnn,7*7*64,1024) nn…
tagged with: tensorflow
type: Question
score: 1
has answer: http://stackoverflow.com/a/51758313
upvote count: 1
answer count: 1

http://stackoverflow.com/a/51798309
score: 0
has comment: http://stackoverflow.com/comment/90557461
answers question: http://stackoverflow.com/q/51789605
type: Answer
has comment: http://stackoverflow.com/comment/90557125
has body: I believe you could store your queryset in a session and than retrieve it in another view. See Django: Passing a queryset to another view with HttpResponseRedirect for some hints.

http://stackoverflow.com/comment/90359872
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51699026
has text: That worked, thanks. If you want, you can answer the question so I can upvote it and designate it as the correct answer.

http://stackoverflow.com/q/51680468
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has body: I am trying to compare the differences in the csv. 1st csv: Device,Priority Device 1,High Device 2,Low Device 3,Medium Device 4,HIGH Device 5,Not Found 2nd CSV: Device,Group 1,Group 2,Group 3,FQDN Device 2,Operation group MEDIUM,Layer 1 group MEDIUM,Layer 2 group MEDIUM,Some FQDN Device 3,Operation group LOW,Layer 1 group LOW,Layer 2 group LOW,Some FQDN Device 1,Operation group HIGH,Layer 1 group HIGH,Layer 2 group HIGH,Some FQDN Device 4,Alerts,Alerts,Alerts,Some FQDN Device 5,Operation group LOW,Layer 1 group LOW, Layer 2 group LOW I want my Output csv file to be such that it should print only the changed updated priority from 1st csv and print them to their respective groups. The relevant groups are: Operation(Group 1) Layer 1 (Group 2) Layer 2(Group 3). Also, if the group is irrelevant for example, ALERTS or some other group then it should skip that iteration and should not print either the device or any info regarding it. This is how my output file should look like: Device,Group 1,Group 2,Group 3 Device 2,Operation group LOW,Layer 1 group LOW,Layer 2 group LOW Device 3,Operation group MEDIUM,Layer 1 group MEDIUM,Layer 2 group MEDIUM It skipped Device 4 because it had irrelevant group called ALERTS, skipped device 5 because priority wasn't mentioned in 1st csv and it also skipped Device 1 because the priority was same in 1st csv and 2nd csv. All the groups(rows) will have the same priority in 2nd csv, except for the group names which will be different.(Operation, Layer 1 and Layer 2) This is what I've tried so far: I have created 2 classes and I have created a dictionary that can lookup the group values if matched: d = { ('High', 'Operation group HIGH'): 'Operation group HIGH', ('High', 'Layer 1 group HIGH'): 'Layer 1 group HIGH', ('High', 'Layer 2 group HIGH'): 'Layer 2 group HIGH' } and later in my code I have put this, for now I am only testing to get the group 1: for group in groups: if device.1stcsvname == group.2ndcsvname: try: user = d[device.priorities, …
tagged with: python
type: AnsweredQuestion
has title: Compare data in csv and print changes based on dictionary lookup
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90384382
has answer: http://stackoverflow.com/a/51714554
accepted answer: http://stackoverflow.com/a/51714554
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/90247448
type: QuestionComment
comment on: http://stackoverflow.com/q/51641472
score: 0
has text: Steps 1-3 are relatively good. I could be nitpicky but I don't think any changes would improve what you have by much
type: Comment

http://stackoverflow.com/comment/90500729
type: QuestionComment
comment on: http://stackoverflow.com/q/51770915
score: 2
has text: Why not directly do `np.put(start_list, remove_list, 0)`. Why intermediate step?
type: Comment

urllib
tags question: http://stackoverflow.com/q/51668283
tags question: http://stackoverflow.com/q/51699802
tags question: http://stackoverflow.com/q/51796368
type: Tag
tags question: http://stackoverflow.com/q/51757421
tags question: http://stackoverflow.com/q/51771656
tag name: urllib
tags question: http://stackoverflow.com/q/51690465
tags question: http://stackoverflow.com/q/51784008
tags question: http://stackoverflow.com/q/51650428
tags question: http://stackoverflow.com/q/51732475
tags question: http://stackoverflow.com/q/51778764
tags question: http://stackoverflow.com/q/51660709
tags question: http://stackoverflow.com/q/51682341
tags question: http://stackoverflow.com/q/51778965
tags question: http://stackoverflow.com/q/51788716
tags question: http://stackoverflow.com/q/51725602
tags question: http://stackoverflow.com/q/51684985
tags question: http://stackoverflow.com/q/51676983

recursion
type: Tag
tags question: http://stackoverflow.com/q/51775140
tags question: http://stackoverflow.com/q/51670194
tags question: http://stackoverflow.com/q/51789062
tags question: http://stackoverflow.com/q/51733279
tags question: http://stackoverflow.com/q/51684284
tags question: http://stackoverflow.com/q/51717675
tag name: recursion
tags question: http://stackoverflow.com/q/51772318
tags question: http://stackoverflow.com/q/51717860
tags question: http://stackoverflow.com/q/51669178
tags question: http://stackoverflow.com/q/51690130
tags question: http://stackoverflow.com/q/51783374
tags question: http://stackoverflow.com/q/51740535
tags question: http://stackoverflow.com/q/51677828
tags question: http://stackoverflow.com/q/51788658
tags question: http://stackoverflow.com/q/51746218
tags question: http://stackoverflow.com/q/51718665

http://stackoverflow.com/a/51723906
accepted answer of: http://stackoverflow.com/q/51723380
answers question: http://stackoverflow.com/q/51723380
type: Answer
has comment: http://stackoverflow.com/comment/90603286
has comment: http://stackoverflow.com/comment/90409689
has comment: http://stackoverflow.com/comment/90409789
score: 1
has comment: http://stackoverflow.com/comment/90603985
has body: @Zero: Would adding the below to your code help ..?? :) df_new = df.reset_index().groupby('C1')['index'].agg(['min', 'max']).rename( columns={'min': 'start', 'max': 'end'}) df_new.reset_index().rename(columns={'C1':'Name'}) Edit: Maybe something like this..? I am still learning but there is no harm trying. :) labels = (df.C1 != df.C1.shift()).cumsum() df1 = pd.concat([df,labels],axis = 1,names = 'label') df1.columns = ['C1','label'] df_new = df1.reset_index().groupby(['label','C1']).agg(['min', 'max']).rename( columns={'min': 'start', 'max': 'end'}).reset_index().rename(columns={'C1':'Name'}) df_new
has comment: http://stackoverflow.com/comment/90482140
has comment: http://stackoverflow.com/comment/90627305
upvote count: 1
has comment: http://stackoverflow.com/comment/90409751
has comment: http://stackoverflow.com/comment/90482083
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51672957
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/51674135
tagged with: python
has body: I have a django music project with a site called Add-Album. I want only registered users to upload abums. When I added the limited access in views.py, I had to change the view from class-view to function-view. But then i got a problem. Everything worked fine, without the template. No forms showed up in the template(when it was class-view the showed up). My question is how can I include both limited access, and the models in same view? #Views.py # .... # My model and fields # model = Album # fields = ['artist', 'album_title', 'genre', 'album_logo'] # before this was a class view with the model and fields def AlbumCreate(request): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] if not request.user.is_authenticated: return redirect('{}?next={}'.format(settings.LOGIN_URL, request.path)) return render(request, 'Music/album_form.html') class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('Music:Music') # .... #models from django.db import models from django.urls import reverse class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=150) genre = models.CharField(max_length=30) album_logo = models.ImageField(upload_to='albumlogo/') def get_absolute_url(self): return reverse('Music:detail', kwargs={'pk': self.pk}) def __str__(self): return self.album_title + ' - ' + self.artist #urls.py #... url(r'album/(?P&lt;pk&gt;[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'), url(r'album/(?P&lt;pk&gt;[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), url(r'album/add/$', views.AlbumCreate, name='album-add'), #...
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51674135
has title: Django: How to include both limited access, and models in same view?

http://stackoverflow.com/comment/90314256
has text: Is there an other methodother than map() to convert all the elements of the list to int or float that you would like to suggest @DYZ
score: 0
comment on: http://stackoverflow.com/q/51675327
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51730321
answer count: 1
has title: Bokeh Dynamically Update xrange based on a ColumnDataSource
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51730840
tagged with: bokeh
type: Question
accepted answer: http://stackoverflow.com/a/51730840
has body: Is there a way to update the xaxis of a bar chart using a columndatasource object? I have a chart that updates the bars based off of what is selected, but I want the tick marks in the xaxis to only represent the values that are being displayed. So, I figured the best option would be to dynamically update the xrange as each new value is selected, similar to how the overall plot is changed based on this.
score: 0

http://stackoverflow.com/q/51672528
type: AnsweredQuestion
score: 1
has body: I'm following the steps to access the Google Tasks API found here, installed the libraries, copied the code for Python, executed the quickstart in my computer and it worked. After that I changed the code to write a task, Here is the code: from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file as oauth_file, client, tools # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/tasks' def main(): store = oauth_file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('tasks', 'v1', http=creds.authorize(Http())) tasklist_id = "theidofmygoogletasklist" task = { 'title': 'Study Python', 'notes': '', 'due': '' } # Call the Tasks API results = service.tasks().insert(tasklist=tasklist_id, body=task).execute() print(result['id']) if __name__ == '__main__': main() Note that I changed the SCOPE to write privilege But I'm getting an error saying "Insufficient Permission". How can I solve this problem?
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51747748
tagged with: python
has title: google tasks api Insufficient Permission
tagged with: google-apis-explorer
upvote count: 1
accepted answer: http://stackoverflow.com/a/51747748
tagged with: google-tasks-api

http://stackoverflow.com/a/51689986
accepted answer of: http://stackoverflow.com/q/51689736
has body: Use Example.objects.get(pk=instance.id) to get the old title from the database in the pre_save handler function: @receiver(pre_save, sender=Example, uid='...') def compare_title_changes(sender, instance, **kwargs): new_title = instance.title # this is the updated value old_title = Example.objects.get(pk=instance.id) # Compare the old and new titles here ... This trick was proposed here a long time ago. I've not tested it with the recent Django version. Please let me know whether it's still working.
type: AcceptedAnswer
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51689736
score: 5

http://stackoverflow.com/comment/90549651
comment on: http://stackoverflow.com/q/51793808
type: Comment
has text: @Prune that sounds weird to me, did you call the function with different node names? or was it always the same? I don't know why is that happening, for me is working fine and nobody else reported a similar problem yet
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90541285
score: 0
type: QuestionComment
has text: according to your rule M1 should be x, no?
comment on: http://stackoverflow.com/q/51791903
type: Comment

http://stackoverflow.com/comment/90447928
type: Comment
has text: Happy to hear problem solved , please mark this as answer , yup u can do it , declare new array for them and put them instead of "i" in for i in numb: writer.writerow([i,i,i])
comment on: http://stackoverflow.com/a/51743563
type: AnswerComment
score: 0

http://stackoverflow.com/q/51715082
score: 8
tagged with: big-o
type: AnsweredQuestion
downvote count: 1
type: Question
upvote count: 9
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/65210272
tagged with: execution-time
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90393571
linked to: http://stackoverflow.com/q/36489576
tagged with: pandas
has title: What is the running time (big "O" order) of pandas DataFrame.join?
tagged with: python
has body: This problem is more conceptual/theoretical (has to do with run times for very large datasets), so I apologize for not having a minimial example to show. I have a bunch of DataFrames from two different sensors that I need to eventually concatenate into two very large DataFrames from two different sensors (df_snsr1 and df_snsr2), and then left join into a single DataFrame. My data is such that I can also join first, then concat, or some combination. I am trying to figure out the most efficient way to do this. From reading this SO answer I know that pandas.concat allocates space for the concatenation of all of its dataframes, and if you do this in a loop it can lead to O(N**2) copying and some major slowdowns. Thus I am currently first building a big list of dataframes (loaded from files), concatenating them all at once, and then joining the two big dataframes: df_list = [] for file in my_pickle_files_snsr1: # O(M) loop over M files df_list.append(pd.read_pickle(file)) # O(1) append, M times df_snsr1 = pd.concat(df_list) # O(N) copies of N records # repeat for sensor 2 (df_snsr2) df_snsr1.join(df_snsr2, on=['some', 'columns']) # O(dunno, maybe bears?) I am unable to find anything about execution speed in the documentation on pandas.DataFrame.join. Is it O(N)? O(N**2)? My thought is that if it is similar order to pandas.concat, then it really doesn't matter what order I do the two operations in. If it is O(N**2), however, then it will likely be more efficient for me to join many small dataframes and then concatenate them rather than concat and then join. The overall operation takes long enough that it is worth-while for me to ask the question on here, so "run it and see" isn't going to work. Does anybody know what algorithm join is using and what its execution big-O order is? Or does anybody have any other suggestions on getting the most-efficient combination of join and concat?
has answer: http://stackoverflow.com/a/65210272

http://stackoverflow.com/a/51786065
accepted answer of: http://stackoverflow.com/q/51785824
has comment: http://stackoverflow.com/comment/90529537
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90529400
has body: This is one approach. Demo: from ast import literal_eval constants = ['(1,2)', '(1,5,1)', '1'] res = [] for i in constants: val = literal_eval(i) #Convert to python object if isinstance(val, tuple): #Check if element is tuple if len(val) == 3: #Check if no of elements in tuple == 3 val = list(val) val[1]+=1 res.extend(range(*val)) continue res.append(val) print(res) Output: [(1, 2), 1, 2, 3, 4, 5, 1]
has comment: http://stackoverflow.com/comment/90529345
has comment: http://stackoverflow.com/comment/90529466
answers question: http://stackoverflow.com/q/51785824
downvote count: 0
has comment: http://stackoverflow.com/comment/90529506
type: AcceptedAnswer
score: 1

http://stackoverflow.com/comment/90517017
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51775402
has text: @Evarsite Galios . I guess it's a live end point , the data changes if we change the query parameters. No problem :)

http://stackoverflow.com/comment/90412681
has text: What do you mean colorize by third ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51726081

http://stackoverflow.com/comment/90273473
type: QuestionComment
comment on: http://stackoverflow.com/q/51651627
has text: The locator you provided in your code isn't being found on the URL you provided. Please update your question with an example we can follow and an [mcve].
score: 0
type: Comment

http://stackoverflow.com/q/51756544
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/51762213
has answer: http://stackoverflow.com/a/51756665
score: 0
has body: I am having trouble trying to obtain a boolean array that indicates when an element in the second numpy array is also in the first array. The challenging part is that each array is made up of Latitude/Longitude pairs and I want to make sure that each Lat/Lon in secondcoords is also in firstcoords. So, this is like an intersection Here is what I have done thus far (with small example coordinates): firstlat = [0, 1, 5, 5] firstlon = [1, 0, 5, 4] secondlat = [0, 2, 0, 5] secondlon = [1, 2, 5, 5] firstcoords = numpy.array((firstlat, firstlon)) firstcoords = numpy.transpose(firstcoords) # gets lat/lon pair secondcoords = numpy.array((secondlat, secondlon)) secondcoords = numpy.transpose(secondcoords) a = numpy.isin(secondcoords, firstcoords) Wrong output: [[ True True] [False False] [ True True] [ True True]] Wanted output: True, False, False, True Numpy isin flattens the arguments so although firstcoords[0] = [0 1], it seems to be improperly comparing it "element by element". However, as I saw, each element comprises of both the [lat lon]; and the purpose to transpose it was to get the lat / lons in tuple or tuple-like form for easier comparison. So, how do I fix my approach or what other approaches would be feasible for this problem?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48178213
linked to: http://stackoverflow.com/q/8317022
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/16970982
has title: Comparing two numpy arrays: (x1, y1) and (x2, y2) to check whether elements intersect
has answer: http://stackoverflow.com/a/51756823
type: Question
has answer: http://stackoverflow.com/a/51756848

http://stackoverflow.com/comment/90391230
type: QuestionComment
has text: so instead should I put for i in M, for j in i...: and then eliminate the rows and columns that way?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51714914

http://stackoverflow.com/q/51671931
has answer: http://stackoverflow.com/a/55934231
has comment: http://stackoverflow.com/comment/90312075
type: Question
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90307586
upvote count: 1
tagged with: apache-spark-sql
has title: Apply describe with filter on column specific in pyspark
has body: I have a table in hive hive_tbl with columns 'col_1','col_2','col_3'. I have created a dataframe on top of above data. Now i am getting statistics of the columns specified using describe() i am getting the result as below. +-------+------------------+------------------+------------------+ |summary| col1 | col2 | col3 | +-------+------------------+------------------+------------------+ | count| 17547479| 17547479| 17547479| | mean|2.0946498354549963| 1.474746257282603|1943.9881619448768| | stddev|1.7921560893864912|1.2898177241581452| 40126.73218327477| | min| 0.0| 0.0| 0.0| | max| 99.0| 60.0| 1.6240624E8| +-------+------------------+------------------+------------------+ The above count is giving the count of the records in the entire table. But can we apply filter specific to columns when using describe i.e. i have some blanks/values to be ignored when getting the count for some column eg col_1 has record count with good values 549023. Can we get below result. +-------+------------------+------------------+------------------+ |summary| col1 | col2 | col3 | +-------+------------------+------------------+------------------+ | count| 549023 | 854049| 17547479| | mean|2.0946498354549963| 1.474746257282603|1943.9881619448768| | stddev|1.7921560893864912|1.2898177241581452| 40126.73218327477| | min| 0.0| 0.0| 0.0| | max| 99.0| 60.0| 1.6240624E8| +-------+------------------+------------------+------------------+
has comment: http://stackoverflow.com/comment/90307292
tagged with: pyspark
tagged with: dataframe
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51746996
tagged with: python-3.x
downvote count: 0
has title: Crawl and extract multiple elements
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51747428
tagged with: web-crawler
has body: I try to crawl information from a certain website to get data of several names from YouTube-Channels, their belonging country and their URLs. Right now it is possible to crawl information of the channel name and url. My goal is to extract the country of the certain YouTube Channel, however sometimes it is possible that this information is missing. Right now I am able to extract the URL of each channel and the channel name, but I have no idea how to extract the title of the headline such as: title="Romania". I tried to use regular expression, but the problem is that the title contains sometimes two times in the header. The following code demonstrates my current procedure: from bs4 import BeautifulSoup import re import requests for i in range(1, 300): url = "https://www.channelcrawler.com/eng/results/136630/page:%s" % i req = requests.get(url) data = req.text soup = BeautifulSoup(data, "html.parser") for link in soup.find_all('h4'): #for t in link.find_all('title'): print(link) row = str(link) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', row) print(urls) #print(link.text.strip()) print(link.get_text()) Output: Ford South Africa ['http://www.youtube.com/channel/UCWmSq95JfUZTv1-Jxmkk-Rw'] ... Nutz Rider ['http://www.youtube.com/channel/UCyfWjPOye4zFvEC_MkbJZ4w']
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51747428
favorite count: 0
tagged with: beautifulsoup
tagged with: python

http://stackoverflow.com/comment/90510651
type: QuestionComment
comment on: http://stackoverflow.com/q/51776024
has text: Do you mean you want to add modules that you installed with pip to PATH?
score: 0
type: Comment

http://stackoverflow.com/comment/90401346
type: Comment
comment on: http://stackoverflow.com/q/51719623
score: 0
has text: Try To Restart server once check or follow this [link](https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html)
type: QuestionComment

http://stackoverflow.com/comment/90497854
has text: As later in the code, I am exchanging the dictionary data between processors, I would like to see if the MPI code that I am writing is logically correct. For that I would want the results to be printed. I would like to point out that I didn't face such an issue while using C/C++ programming languages for MPI. So with python, I am trying to find a way to avoid interspersing of data while printing. Many thanks!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51765805

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

http://stackoverflow.com/q/51681164
has comment: http://stackoverflow.com/comment/90325645
tagged with: export-to-csv
possible better answer: http://stackoverflow.com/a/51681213
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/4706499
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90325463
has answer: http://stackoverflow.com/a/51681203
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I am currently conducting a data scraping project with Python 3 and am attempting to write the scraped data to a CSV file. My current process to do it is this: import csv outputFile = csv.writer(open('myFilepath', 'w')) outputFile.writerow(['header1', 'header2'...]) for each in data: scrapedData = scrap(each) outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...]) Once this script is finished, however, the CSV file is blank. If I just run: import csv outputFile = csv.writer(open('myFilepath', 'w')) outputFile.writerow(['header1', 'header2'...]) a CSV file is produced containing the headers: header1,header2,.. If I just scrape 1 in data, for example: outputFile.writerow(['header1', 'header2'...]) scrapedData = scrap(data[0]) outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...]) a CSV file will be created including both the headers and the data for data[0]: header1,header2,.. header1 data for data[0], header1 data for data[0] Why is this the case?
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/51681203
has title: Empty CSV file when writing lots of data
has answer: http://stackoverflow.com/a/51681213

http://stackoverflow.com/comment/90500043
comment on: http://stackoverflow.com/q/51769590
score: 0
type: QuestionComment
type: Comment
has text: it takes value as default then, it's returning execvalue instead of execNone

http://stackoverflow.com/q/51775268
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51775407
tagged with: django-models
has body: I have a Django model that makes use of some libraries which I would like to be able to override. For instance, when testing I'd like to pass a mock instead of having my model tightly coupled. I can do this in python, but for the life of me I can't figure out how to do it with a Django model. Here's a simplified example not using Django: import requests class APIClient: def __init__(self, **kwargs): self.http_lib = kwargs.get("http_lib", requests) def get_url(self, url): return self.http_lib.get(url) For regular use of this class I can still use requests but if I want to use a different library for some reason or if I want to test certain outcomes, I can invoke the class with client = APIClient(http_lib=MockRequests()) But how do I do that with a Django model? If I try to pass kwargs that aren't backed by a database field Django throws an error. Overriding __init__ is not considered a good practice either. Is there a way in Django to set and get a value that isn't backed by a database column?
type: Question
has title: inject library dependencies into django model
tagged with: dependency-injection
answer count: 1

http://stackoverflow.com/comment/90481850
has text: OK. I'm going to add an answer. Hope it's what you're after.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51741790

http://stackoverflow.com/a/51745141
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90930214
has body: Before moving on to automating any scenario, always write down the manual steps you would perform to execute the scenario. Manual steps for what you want to (which I understand from the question) is - 1) Go to site - https://services.wiltshire.gov.uk/PlanningGIS/LLPG/WeeklyList 2) Select first week option 3) Click search 4) Get the data from every page 5) Load the url again 6) Select second week option 7) Click search 8) Get the data from every page .. and so on. You are having a loop to select different weeks but inside each loop iteration for the week option, you also need to include a loop to iterate over all the pages. Since you are not doing that, your code is returning only the data from the first page. Another problem is with how you are locaing the 'Next' button - driver.find_element_by_xpath('//*[@id="form1"]/div[3]/a[4]').click() You are selecting the 4th &lt;a&gt; element which is ofcourse not robust because in different pages, the Next button's index will be different. Instead, use this better locator - driver.find_element_by_xpath("//a[contains(text(),'Next')]").click() Logic for creating loop which will iterate through pages - First you will need the number of pages. I did that by locating the &lt;a&gt; immediately before the "Next" button. As per the screenshot below, it is clear that the text of this element will be equal to the number of pages - - I did that using following code - number_of_pages = int(driver.find_element_by_xpath("//a[contains(text(),'Next')]/preceding-sibling::a[1]").text) Now once you have number of pages as number_of_pages, you only need to click "Next" button number_of_pages - 1 times! Final code for your main function- def main(): all_data = [] select = Select(driver.find_element_by_xpath("//select[@class='formitem' and @id='selWeek']")) list_options = select.options for item in range(len(list_options)): select = Select(driver.find_element_by_xpath("//select[@class='formitem' and @id='selWeek']")) select.select_by_index(str(it…
has comment: http://stackoverflow.com/comment/90450121
type: Answer
has comment: http://stackoverflow.com/comment/90450574
has comment: http://stackoverflow.com/comment/90450302
score: 8
has comment: http://stackoverflow.com/comment/90450441
has comment: http://stackoverflow.com/comment/104956471
answers question: http://stackoverflow.com/q/51743859
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51743859
has comment: http://stackoverflow.com/comment/90450082
upvote count: 8
has comment: http://stackoverflow.com/comment/90926261

http://stackoverflow.com/comment/90541332
has text: Just adding, [^!@#$%] this will mean the opposite of what you intend to since [^] means a not for things that follow. Always good to be explicit and escape meta-characters even when its not necessary.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51791295

http://stackoverflow.com/comment/90302109
score: 0
has text: hi Madhan Varadhodiyil, it still keep saying this: for d in c ['slot']: TypeError: list indices must be integers or slices, not str
comment on: http://stackoverflow.com/q/51669572
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90855412
score: 0
type: AnswerComment
type: Comment
has text: If ticks are (0,100) then you could set markerPos to be `random()*100` or for (1,100) you would need `random()*99+1`. The point is, the `markerPos` is set in whatever units the low/high tick marks have
comment on: http://stackoverflow.com/a/51952509

http://stackoverflow.com/comment/90306493
score: 0
has text: Moreover, the score 0.99 seems too high, and thats because you have resampled the data and then RandomizedSearchCV is splitting that into train and test, so its leaking the information of test data into the model. I would advise you to use a Pipeline with Sampling and XGB, so that data is split first into train and test and then only train data is resampled.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51671058

http://stackoverflow.com/comment/90368369
has text: Are you looking for [`numpy.diff`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html) ?
score: 0
comment on: http://stackoverflow.com/q/51703661
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90256432
type: QuestionComment
type: Comment
has text: @Sraw - Thanks again. I did follow that link and https://www.jetbrains.com/help/pycharm/ipython.html before posting. This didn't help to get rid of those red underlines in my `.py` file.
comment on: http://stackoverflow.com/q/51645855
score: 0

http://stackoverflow.com/q/51763941
linked to: http://stackoverflow.com/q/27905295
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90486657
duplicate of: http://stackoverflow.com/q/27905295
has answer: http://stackoverflow.com/a/51764016
upvote count: 1
answer count: 1
tagged with: dataframe
has title: Importing a CSV with grouped data into a Pandas data frame
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51764016
downvote count: 0
has comment: http://stackoverflow.com/comment/90487142
score: 1
has body: When I import my data file with Pandas I get following data frame: product feature_1 feature_2 0 a 11 12 1 NaN 13 14 2 NaN 15 16 3 NaN 17 18 4 NaN 19 20 5 b 21 22 6 NaN 23 24 7 NaN 25 26 8 c 27 28 9 NaN 29 30 10 NaN 31 32 What I need to do is to substitute the NaNs with the next non-NaN element above them so I get following data frame: product feature_1 feature_2 0 a 11 12 1 a 13 14 2 a 15 16 3 a 17 18 4 a 19 20 5 b 21 22 6 b 23 24 7 b 25 26 8 c 27 28 9 c 29 30 10 c 31 32 What I did (see gist for code and datafile): Import my data into a list of dicts iterate through the list and make the modifications import the list into a data frame How can I make this happen directly in Pandas without doing the list preprocessing beforehand ?
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51796195
tagged with: python
tagged with: praw
has comment: http://stackoverflow.com/comment/90549637
has answer: http://stackoverflow.com/a/51796232
accepted answer: http://stackoverflow.com/a/51796234
score: -3
upvote count: 1
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/90549671
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90549648
type: Question
downvote count: 4
linked to: http://stackoverflow.com/q/45621722
has body: So, I'm new to Python in all. I tried my hand at making a reddit bot, I fixed most errors. But this one kinda started beating my head in as I tried fixing it. print("String with \"best girl\" found in comment", str(comment.id)) IndentationError: unindent does not match any outer indentation level. And an arrow pointing to the last ) in the code. After researching a bit, I found no help. Again, I'm completely new to programming in all. My Code: import praw import config import time import os def bot_login(): print "Loggin in..." r = praw.Reddit(username = config.username, password = config.password, client_id = config.client_id, client_secret = config.client_secret, user_agent = "busterronitest's dog comment responder v0.1") print "Logged in!" return r def run_bot(r, comments_replied_to): print "Obtaining 25 comments..." for comment in r.subreddit('TheTempleOfOchako').comments(limit=10): if "best girl" or "Best girl" in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me(): print("String with \"best girl\" found in comment", str(comment.id)) comment.reply("We all know ochako is best girl, [Just look at her!](https://i.imgur.com/SuKe7l0.jpg) This action was performed by a bot, contact u/Monikas_Comin if you have any issues.") print("Replied to comment", str(comment.id)) comments_replied_to.append(comment.id) with open ("comments_replied_to.txt", "a") as f: f.write(comment.id + "\n") print "Sleeping for 10 seconds..." #Sleep for 10 seconds... time.sleep(10) def get_saved_comments(): if not os.path.isfile("comments_replied_to.txt"): comments_replied_to = [] else: with open("comments_replied_to.txt", "r") as f: comments_replied_to = f.read() comments_replied_to = comments_replied_to.split("\n") comments_replied_to = filter(None, comments_replied_to) return comments_replied_to r = bot_login() comments_replied_to = get_saved_comments() print comments_replied_to while True: run_bot(r, comments_replied_to)
has answer: http://stackoverflow.com/a/51796305
has comment: http://stackoverflow.com/comment/90549664
has answer: http://stackoverflow.com/a/51796234
favorite count: 0
possible better answer: http://stackoverflow.com/a/51796305
answer count: 3
has title: Error: unindent does not match any outer indentation level (Making a reddit bot)

http://stackoverflow.com/a/51684817
has comment: http://stackoverflow.com/comment/116572483
accepted answer of: http://stackoverflow.com/q/51683915
has comment: http://stackoverflow.com/comment/111996403
score: 12
type: Answer
answers question: http://stackoverflow.com/q/51683915
upvote count: 12
type: AcceptedAnswer
downvote count: 0
has body: The sigmoid activation produces outputs between zero and one, so if you use it as activation of your last layer(the output), the network's output will be between zero and one. output = Dense(3, activation="sigmoid")(dense)

http://stackoverflow.com/comment/90274321
comment on: http://stackoverflow.com/q/51654434
score: 0
type: Comment
has text: @DeepSpace if a variable doesn't have `__bool__` or `__len__` dunder methods it wiil allways be `True`, and this is not a desired outcome.
type: QuestionComment

http://stackoverflow.com/comment/90499221
has text: What happens if you change your `b` request to this: `b = request.args.get('basket', 'value')`? Does it output `value`?
type: Comment
comment on: http://stackoverflow.com/q/51769590
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90590797
comment on: http://stackoverflow.com/a/51728654
type: AnswerComment
score: 0
type: Comment
has text: No problem at all - super grateful for your answer and the info - I will just test out the code and then hopefully will be in a position to accept the answer :)

http://stackoverflow.com/comment/90344824
comment on: http://stackoverflow.com/a/51691346
score: 0
has text: You wrote in the question that you want the percentage of the outputs that are better than 50. 7/15 is 0.4666.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90487419
has text: Are you trying to detect a blue line, or are you trying to detect a car and then draw a blue line?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51764151
score: 0

http://stackoverflow.com/q/51676506
score: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/51676757
upvote count: 1
has title: Bar chart with label name and value on top in pandas
linked to: http://stackoverflow.com/q/25447700
possible better answer: http://stackoverflow.com/a/51676811
has body: I have two columns where i used groupby option create a df called output_duration_per_device such as output_duration_per_device=s3_dataset.groupby('DeviceType')['Output_media_duration'].sum().reset_index(name ='format_duration') output_duration_per_device DeviceType format_duration 0 Alchemist 8.166905e+06 1 CaptionMaker 1.310864e+07 2 Elemental 1.818089e+07 3 EncodingCloud 0.000000e+00 4 FfMpeg 5.258470e+07 5 FlipFactory 4.747456e+02 6 Rhozet 6.263442e+08 7 Tachyon 4.827463e+06 I can make a bar chat and find like this output_duration_per_device=s3_dataset.groupby('DeviceType')['Output_media_duration'].sum().reset_index(name ='Device_duration').plot(kind ='bar', figsize=(10,7), fontsize=13) output_duration_per_device.set_alpha(0.8) output_duration_per_device.set_title('DeviceType Output Media duration') output_duration_per_device.set_xlabel('DeviceType') plt.ylabel('Output_media_duration') which gives me but i want like below please help me
has answer: http://stackoverflow.com/a/51676811
duplicate of: http://stackoverflow.com/q/25447700
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51676757
downvote count: 0

http://stackoverflow.com/a/51689275
upvote count: 2
answers question: http://stackoverflow.com/q/51688989
has body: You can try CSS selectors built-in within BeautifulSoup. This will select all span whose ids are beginning with ContentPlaceHolder: soup.select('span[id^=ContentPlaceHolder]') Example: from bs4 import BeautifulSoup html = """0 1 2 3 xxx""" soup = BeautifulSoup(html, 'lxml') for s in soup.select('span[id^=ContentPlaceHolder]'): print(s.text) Prints: 0 1 2 3
downvote count: 0
type: Answer
score: 2

full-text-search
tags question: http://stackoverflow.com/q/51707642
tag name: full-text-search
type: Tag
tags question: http://stackoverflow.com/q/51699120

http://stackoverflow.com/a/51731406
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If the number of elements is small, simply looping over all elements should be no problem: import numpy as np a = [['A', 'B'], ['B', 'B'], ['B', 'C'], ['C', 'B'], ['B', 'A'], ['A', 'D'], ['D', 'D'], ['D', 'A'] ['A', 'B'], ['B', 'A'], ['A', 'D']] a = np.asarray(a) elems = np.unique(a) dim = len(elems) P = np.zeros((dim, dim)) for j, x_in in enumerate(elems): for k, x_out in enumerate(elems): P[j,k] = (a == [x_in, x_out]).all(axis=1).sum() if P[j,:].sum() &gt; 0: P[j,:] /= P[j,:].sum() Output: array([[0. , 0.5 , 0. , 0.5 ], [0.5 , 0.25, 0.25, 0. ], [0. , 1. , 0. , 0. ], [0.5 , 0. , 0. , 0.5 ]]) But you could also use the counter with a pre-allocated transition matrix, map the elements to indices, assign the counts as values, and normalize (last two steps just like I did).
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51731187
accepted answer of: http://stackoverflow.com/q/51731187

http://stackoverflow.com/a/51683307
type: Answer
has comment: http://stackoverflow.com/comment/90329322
upvote count: 1
answers question: http://stackoverflow.com/q/51683296
has comment: http://stackoverflow.com/comment/90329149
score: 1
has comment: http://stackoverflow.com/comment/90329162
type: AcceptedAnswer
downvote count: 0
has body: If same length of both DataFrames: df1.index = df2.index Or: df1= df1.set_index(df2.index)
has comment: http://stackoverflow.com/comment/90329343
has comment: http://stackoverflow.com/comment/90329249
accepted answer of: http://stackoverflow.com/q/51683296

http://stackoverflow.com/a/51700221
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: You can do it like this: In [24]: a['key'] = 1 In [25]: b['key'] = 1 In [27]: pd.merge(a, b, on='key').drop('key', axis=1) Out[27]: aa bb 0 1 4 1 1 5 2 2 4 3 2 5 4 3 4 5 3 5
score: 2
answers question: http://stackoverflow.com/q/51700173
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51700173

http://stackoverflow.com/a/51774500
has body: Miniconda is not a module indeed it is a variant of Anaconda python distribution, hence you could not import it. You could get further info about miniconda from the link below. https://conda.io/miniconda.html
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51774393
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90508450

http://stackoverflow.com/comment/127567714
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/72198690
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

http://stackoverflow.com/comment/90450405
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51744751
has text: @Ivar Would you like to have a look at the code and comment if possible?
type: Comment

http://stackoverflow.com/q/51697631
type: Question
linked to: http://stackoverflow.com/q/48276187
score: 1
has body: I saw a few posts to find duplicates in a directory and compress: here, here, and here, but none of these posts explain how to reverse the process. So after this process, you end up with file hashes, the file itself, and the position where they occur. In my case, I'm using the algorithm to find duplicates in a file. From a, say, 6 kB file, I reduce to 2 kB. When I try to reconstruct the file, the contents are the same, but the file size and comparison fail. Here's my code to reconstruct the file that I modified from a previous post: import pickle import hashlib with open(compressed, 'rb') as f, open(recovered, "wb") as fname: a_dict = pickle.load(f) # loads the compressed file a_list = [] for values_list in a_dict.values(): file_bytes = values_list.pop(0) for val in values_list: a_list .insert(val, file_bytes) result = tuple(a_list) pickle.dump(result, fname, protocol=pickle.HIGHEST_PROTOCOL) Where a_dict is a_dict = {'8a50b9f75b57104d89b58305d96045df':[b'\x94*\x08\x9d\xd8', 0, 1, 4, 6, 7], 'bff92f621cc65e2103305343a943c9a8':[b'\x85*\xe4\xf0\xd7', 2, 3, 5, 8, 9]} Again, the contents of the original file and the result are the same. But when I compare with Unix cmp file1 file2 or even when I hash the files again, the bytes are not the same.
upvote count: 2
linked to: http://stackoverflow.com/q/51690094
tagged with: arrays
answer count: 1
has answer: http://stackoverflow.com/a/51697675
linked to: http://stackoverflow.com/q/14956313
has title: Reverse process after finding duplicates
has comment: http://stackoverflow.com/comment/90357164
favorite count: 0
linked to: http://stackoverflow.com/q/748675
tagged with: python
linked to: http://stackoverflow.com/q/18724376
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90356756
downvote count: 1

http://stackoverflow.com/comment/90515397
type: QuestionComment
has text: Why is row `3` not `3 1` in your expected output?
comment on: http://stackoverflow.com/q/51778723
score: 0
type: Comment

http://stackoverflow.com/comment/90378005
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51707553
has text: This is correct. Is that what the code does? Just explain what the code does. Thanks
score: 0

http://stackoverflow.com/comment/90393266
has text: You should check whether there are now two copies of `psutil` in two different locations on `sys.path`. As long as the new version is the one in the earlier `sys.path` location, things should just work (and the reason is some variation of what's in my answer, although I don't know the Ubuntu 18.04 specific details). If the old version isn't there at all anymore, something different is going on.
score: 2
comment on: http://stackoverflow.com/q/51715599
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51756452
has body: If you can remove the erroneous exits, then you can achieve this by summing the entries and taking away the exits cumulatively and mapping the values (1,0) to (Long/Short, not long/not short): df['Long'] = (df['EntrySignal'] == 'LongEntry').cumsum() - (df['ExitSignal'] == 'LongExit').cumsum() df['Short'] = (df['EntrySignal'] == 'ShortEntry').cumsum() - (df['ExitSignal'] == 'ShortExit').cumsum() df['Long'] = df['Long'].map({1: 'Long', 0: ''}) df['Short'] = df['Short'].map({1: 'Short', 0: ''}) Note: with the erroneous entries the value will go below 0, and you will require more sophisticated logic.
type: Answer
answers question: http://stackoverflow.com/q/51754406
score: 0

http://stackoverflow.com/a/51686768
upvote count: 1
has comment: http://stackoverflow.com/comment/90336597
has comment: http://stackoverflow.com/comment/90336366
score: 1
has comment: http://stackoverflow.com/comment/90336740
accepted answer of: http://stackoverflow.com/q/51686618
has comment: http://stackoverflow.com/comment/90336226
has comment: http://stackoverflow.com/comment/90336395
has comment: http://stackoverflow.com/comment/90336261
has body: The problem is, .index does not return all the indices so, you will need something similar as mentioned in other question. stopword_pos_set = set() # creating set so that index is not added twice # I need to note the position of all the stopwords for later use for w in tokenized: if w.lower() in stop_words: indices = [i for i, x in enumerate(tokenized) if x == w] stopword_pos_set.update(indices) stopword_pos = list(stopword_pos_set) # convert to list In above, I created stopword_pos_set, so that same index are not added twice, it will just assign same value twice but when you print stopword_pos without set you will see duplicate values. One suggestion is, in above code, I changed it to if w.lower() in stop_words:, so that when you check for stopwords without case-sensitive, otherwise 'This' is not same as 'this'. Other suggestion is to use .update method to update with multiple items in stop_words set with stop_words.update([".", ","]) instead of .add multiple times. You can try as below: ex_text='This is an example list that has no special keywords to sum up the list, but it will do. Another list is a very special one this I like very much.' tokenized = word_tokenize(ex_text) stop_words = set(stopwords.words('english')) stop_words.update([".", ","]) #Since I do not need punctuation, I added . and , stopword_pos_set = set() # I need to note the position of all the stopwords for later use for w in tokenized: if w.lower() in stop_words: indices = [i for i, x in enumerate(tokenized) if x == w] stopword_pos_set.update(indices) stopword_pos = sorted(list(stopword_pos_set)) # set to list # Replacing stopwords with "QQQQQ" for i in range(len(stopword_pos)): tokenized[stopword_pos[i]] = 'QQQQQ' print(tokenized) print(stopword_pos)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51686618
type: Answer

http://stackoverflow.com/a/51769314
type: Answer
answers question: http://stackoverflow.com/q/51644481
has body: In https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html they define a little function to draw the circle. Use this example and modify it. import cv2 import numpy as np # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCLK: cv2.circle(img,(x,y),100,(255,0,0),-1) # Create a black image, a window and bind the function to window img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('image') cv2.setMouseCallback('image',draw_circle)#&lt;=====here while(1): cv2.imshow('image',img) if cv2.waitKey(20) &amp; 0xFF == 27: break cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/103529304
score: 0

http://stackoverflow.com/comment/90520382
type: Comment
score: 2
type: AnswerComment
has text: @ManishSingh Nowhere in your question have you said that the solution must be a one-liner. Which is good, because writing this in a single line is horrible. Don't ask us to write bad code. This answer is a good solution. Let go of your arbitrary requirements.
comment on: http://stackoverflow.com/a/51781293

http://stackoverflow.com/comment/90401481
type: Comment
has text: how ll i pass parameter from the html page syntax? i added <str:department> this yet i am getting error.--- Reverse for 'emp_pay_list' with arguments '('',)' not found. 1 pattern(s) tried: ['hrmsapp/list_of_employees/<str:department>$']---
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51719571

http://stackoverflow.com/comment/90279433
score: 2
comment on: http://stackoverflow.com/q/51656818
has text: @MarcGlisse, wow adding this option reduced computation time by a factor of 3 (now it is only 45-50 ms per loop). Taking into account, that multithreading was not used (there is a function in eigen that allows me to check it), I believe that unveils the mystery
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90280686
has text: There was another problem with `ut`, see my edit. Note that it is impossible to test your code, as it is not complete enough to run it, even in a reduced version. Consider creating a [mcve] if there are more bugs in your code.
comment on: http://stackoverflow.com/a/51652695
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51791896
has body: 1. I need to assign time as a Dimension to the xarray.DataSet object 2. I need to assign lat/lon as a Dimension I have downloaded vegetation health data from the NOAA FTP service here. The help documentation is here. There are 2030 weekly files so any help doing this in parallel is very much appreciated. In [0]: ls | wc -l 2030 The Problem: The major issue is that the data has come weekly, without a time dimension (except for a day number in the .nc global attributes and the year in the filename). For the file named 'VHP.G04.C07.NH.P1992014.VH.nc': In [1]: xr.open_dataset('VHP.G04.C07.NH.P1992014.VH.nc') Out[1]: &lt;xarray.Dataset&gt; Dimensions: (HEIGHT: 3616, WIDTH: 10000) Dimensions without coordinates: HEIGHT, WIDTH Data variables: VCI (HEIGHT, WIDTH) float32 ... TCI (HEIGHT, WIDTH) float32 ... VHI (HEIGHT, WIDTH) float32 ... QA (HEIGHT, WIDTH) float32 ... Attributes: VERSION: VH (vh.exe,version 1.3, March 21 2012) SATELLITE: NH INSTRUMENT: AVHRR CITATION_TO_DOCUMENTS: User Guide of Vegetation Health(VH) system (vers... CONTACT: NOAA/NESDIS/STAR/EMB PRODUCT_NAME: Vegetation Health PROJECTION: Plate_Carree DATE_BEGIN: 92 DATE_END: 98 TIME_BEGIN: 00:00 UTC (use day time data only) TIME_END: 23:59 UTC (use day time data only) ANCILLARY_FILES: FILE_CONFIGURE:vh.config_NN\nFILE_PRELAUNCH_CALI... CONFIGURE_FILE_CONTENT: [Options for vh.exe]\nDIR_Ancillary= ... YEAR: 1992 PERIOD_OF_YEAR: 14 DAYS_PER_PERIOD: 7 END_LATITUDE_RANGE: -55.152 START_LONGITUDE_RANGE: -180.0 START_LATITUDE_RANGE: 75.024 END_LONGITUDE_RANGE: 180.0 INPUT_FILES: 2 INPUT_FILENAMES: data/AVHRR_VHP/4km/VH/VHP.G04.C07.NH.P1992014.SM... The Question Therefore, I was hoping to use xarray to: Store time as a scalar dimension Convert HEIGHT and WIDTH to latitude and longitude dimensions Writing the resultant xarray.Dataset to a .nc file So I want something like this (but with cf-compliance): &lt;xarray.Dataset&gt; Dimensions: (latitude: 3616, longitude: 10000, time) Dimensions without coordinates: latitud…
answer count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90632897
type: UnansweredQuestion
tagged with: geocoding
has comment: http://stackoverflow.com/comment/90646206
tagged with: python-xarray
has title: Python assign time, latitude & longitude to `Dimensions` of xarray.DataSet from netcdf file
score: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90619460
has comment: http://stackoverflow.com/comment/90646764
tagged with: netcdf
downvote count: 1

http://stackoverflow.com/q/51696441
score: 1
accepted answer: http://stackoverflow.com/a/53156688
has comment: http://stackoverflow.com/comment/90354964
has body: Is it possible to put data labels (values) in pandas/matplotlib stacked area charts? In stacked bar plots, I use the below for label in yrplot.patches: yrplot.annotate(label.get_height(), (label.get_x()+label.get_width()/2.,label.get_y()+label.get_height()/2.), ha='center', va='center', xytext=(0, 1), textcoords='offset points') Below is how I am plotting the stacked area chart %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns yrplot = yrly_perc_df.plot(x='year', y=prod, kind='area', stacked=True, figsize=(15,10), color = areacolors) yrplot.set_ylabel('share') yrplot.legend(loc='center left', bbox_to_anchor=(1.0,0.5)) Any leads would be much appreciated. To state my want, it is something similar to this image but in a stacked area chart (data labels along the plot, similar to the first code in the question).
linked to: http://stackoverflow.com/q/31573869
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90354704
tagged with: matplotlib
has answer: http://stackoverflow.com/a/53156688
has comment: http://stackoverflow.com/comment/90354463
has title: Labels (annotate) in pandas area plot
has comment: http://stackoverflow.com/comment/90354635
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90354648
favorite count: 0
has comment: http://stackoverflow.com/comment/90354429
has comment: http://stackoverflow.com/comment/90354922
tagged with: python
has comment: http://stackoverflow.com/comment/90354500
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90354684
upvote count: 2

http://stackoverflow.com/a/51759321
type: Answer
answers question: http://stackoverflow.com/q/51759222
has body: Strings are immutable, so you can not "edit" single characters inside them bey indexing into them - thats what you are trying in your for x ..: for y: ... loop. To keep most of your code, you can change it to: def addBorder(picture): m=len(picture) #number of rows n=len(picture[0]) #num of columns newpic=[['*'*(n+2)]for y in range(m+2)] for idx,text in enumerate(picture): # get text and index here newpic[idx+1] = '*' + text+ '*' # change text in +1 row in target list return newpic print(addBorder( ["abc", "ded"])) Output: [['*****'], '*abc*', '*ded*', ['*****']] Changing more code: def addBorder(picture): # slightly more compley length computation, will work for ragged text as well maxL = max(len(x) for x in picture) patt = "*{:&lt;"+str(maxL)+"}*" # left justified by maxL , see link below rv = [] rv.append('*'*(maxL+2)) # top border for t in picture: rv.append(patt.format(t)) # text + adornment rv.append('*'*(maxL+2)) # bottom border return rv print(addBorder( ["abc", "defgh","i"])) Output: ['*******', '*abc *', '*defgh*', '*i *', '*******'] Link: string format mini language Your out of index error message is somewhat misleading - you are inside the bounds of your lists, but you are trying to manipulate the string - I would have thought a 'str' object does not support item assignment would be more appropriate here... Edit: see Azats answer for why your error occurs - I left text in so his post does not loose its reference.
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/51759222

http://stackoverflow.com/comment/90371245
type: Comment
has text: @ArnoldKlein I'm sorry, I dont understand. My current implementation also dont have hardcoded `power`. Its just that its a list of values now. You can specify `IrisDataManupulation(powers=[2])` and it will still work.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51702148

http://stackoverflow.com/comment/90259926
type: QuestionComment
score: 1
has text: What code do you use to get to those images?
comment on: http://stackoverflow.com/q/51647923
type: Comment

http://stackoverflow.com/q/51681592
has comment: http://stackoverflow.com/comment/90326220
favorite count: 0
has answer: http://stackoverflow.com/a/51681609
tagged with: pandas
has title: Pandas dataframe ranked by multiple columns (combination key)
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90326218
score: 1
has comment: http://stackoverflow.com/comment/90326360
tagged with: dataframe
tagged with: rank
type: Question
has body: Is there a pythonic way of sorting the dataframe described below by a combo key - first by ORD_DT_KEY then by ORD_TM_KEY and then by ORD_KEY; and store the rank in another column ORD_RANK? Code below does not work since it creates 3 separate ranks and throws an error when I try to assign it to single column. import pandas as pd #Read orders data stored in a pipe delimeted file df_raw_orders = pd.read_table("Dummy_order_data.txt", delimiter="|") print df_raw_orders.head() df_sorted_orders = df_raw_orders cols = ['ORD_DT_KEY','ORD_TM_KEY','ORD_KEY'] df_sorted_orders['ORD_RANK'] = df_sorted_orders[cols].rank(method='dense') Input data, Dummy_order_data.txt, is as below: ORD_KEY|ORD_DT_KEY|ORD_TM_KEY|QTY|SKU_KEY 10001|1|0|1|1 10001|1|0|1|2 10001|1|0|1|3 10002|2|0|1|1 10002|2|0|1|3 10003|3|0|1|4 10004|4|0|1|4 10004|4|0|1|5 10005|5|0|1|1 10006|6|0|1|1 10006|6|0|1|4 10007|7|0|1|3 10007|7|0|1|4 10008|8|0|1|5 10009|9|0|1|1 10009|9|0|1|4 10009|9|0|1|5 10010|10|0|2|1 10010|10|0|2|2 10010|10|0|2|3 10011|11|0|1|1 10011|11|0|1|3 10012|12|0|1|4 10012|12|0|1|5 10013|13|0|1|1 10014|14|0|2|1 10014|14|0|2|4 Required output: ORD_KEY ORD_DT_KEY ORD_TM_KEY SKU_KEY QTY ORD_RANK 10001 1 0 1 1 1 10001 1 0 2 1 1 10001 1 0 3 1 1 10002 2 0 1 1 2 10002 2 0 3 1 2 10003 3 0 4 1 3 10004 4 0 4 1 4 10004 4 0 5 1 4 10005 5 0 1 1 5 10006 6 0 1 1 6 10006 6 0 4 1 6 10007 7 0 3 1 7 10007 7 0 4 1 7 10008 8 0 5 1 8 10009 9 0 1 1 9 10009 9 0 4 1 9 10009 9 0 5 1 9 10010 10 0 1 2 10 10010 10 0 2 2 10 10010 10 0 3 2 10 10011 11 0 1 1 11 10011 11 0 3 1 11 10012 12 0 4 1 12 10012 12 0 5 1 12 10013 13 0 1 1 13 10014 14 0 1 2 14 10014 14 0 4 2 14
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90318612
has text: Hi, I think oversubscribe puts the same slots in the queue.
comment on: http://stackoverflow.com/q/51658008
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90589412
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51794274
type: QuestionComment
has text: @NilsWerner I used some parts of your code to update mine. My conv function seems to be ok, the only issue is I don't know how to populate `Omega` using this function.

http://stackoverflow.com/a/51740317
has comment: http://stackoverflow.com/comment/90440790
has body: May be you this help, import re st = "Mandzukic 18' (o.g.) Griezmann 38' (pen.) Pogba 59' Mbappe 65'; Perisic 28' Mandzukic 69'" re.findall(r'(\w\s*\w+)\s(\d+)', st) # Output as: [('Mandzukic', '18'), ('Griezmann', '38'), ('Pogba', '59'), ('Mbappe', '65'), ('Perisic', '28'), ('Mandzukic', '69')]
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51740218
type: Answer

xml-parsing
tags question: http://stackoverflow.com/q/51664292
tag name: xml-parsing
tags question: http://stackoverflow.com/q/51756049
type: Tag
tags question: http://stackoverflow.com/q/51750620
tags question: http://stackoverflow.com/q/51674660

http://stackoverflow.com/comment/90276867
type: Comment
type: QuestionComment
has text: can someone help please?
comment on: http://stackoverflow.com/q/51653193
score: 0

valueerror
tags question: http://stackoverflow.com/q/51708969
tags question: http://stackoverflow.com/q/51646342
tag name: valueerror
type: Tag
tags question: http://stackoverflow.com/q/51711688
tags question: http://stackoverflow.com/q/51751833

http://stackoverflow.com/a/51790508
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51790351
upvote count: 1
has body: cumprod df.assign(new_col=df.z.fillna(0).add(1).cumprod()) x y z new_col 0 NaN NaN NaN 1.0 1 1.0 2.0 3.0 4.0 2 2.0 3.0 4.0 20.0 3 2.0 1.0 3.0 80.0 Attempt to preserve dtype df.assign(new_col=df.z.fillna(0, downcast='infer').add(1).cumprod()) x y z new_col 0 NaN NaN NaN 1 1 1.0 2.0 3.0 4 2 2.0 3.0 4.0 20 3 2.0 1.0 3.0 80 With Numba The point of this is to show how to perform a linear path dependent calculation. Numba is very fast and if the calculation has a time complexity of O(N) then you don't have to be afraid of using this loop in Numba. If you don't have numba installed and don't want to install it, just remove the @njit decorator. from numba import njit @njit def f(a): out = np.zeros_like(a) out[0] = 1 for i, x in enumerate(a[1:], 1): out[i] = out[i-1] * (1 + x) return out df.assign(new_col=f(df.z.values)) x y z new_col 0 NaN NaN NaN 1.0 1 1.0 2.0 3.0 4.0 2 2.0 3.0 4.0 20.0 3 2.0 1.0 3.0 80.0 With int df.assign(new_col=f(df.z.fillna(0).astype(int).values)) x y z new_col 0 NaN NaN NaN 1 1 1.0 2.0 3.0 4 2 2.0 3.0 4.0 20 3 2.0 1.0 3.0 80

http://stackoverflow.com/comment/90301493
has text: You can get even more concise: `{k: dict(v) for k, v in myList}`
score: 2
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51669363

http://stackoverflow.com/comment/90419763
score: 0
type: AnswerComment
type: Comment
has text: print(len(pkt)) results in a 7
comment on: http://stackoverflow.com/a/51728715

http://stackoverflow.com/q/51677111
type: Question
tagged with: lstm
tagged with: deep-learning
upvote count: 1
tagged with: keras
favorite count: 0
has title: Understanding Conv2D and LSTM
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
answer count: 0
downvote count: 0
score: 1
has body: I am trying to predict next image. So I am using Conv2D and LSTM instead of ConvLSTM2D. The reason is I want to understand every step as I am a beginner. My questions are: 1) I wanted to write a generator method that will return X and y. I think the shape of X will be (number of samples, timesteps, height, width, channels) but I am not sure about the shape of y. (For example, if we want to predict temperature from a dataset, then in the generator method the shape of X will be (number of samples, timesteps, number of features) and the shape of y will be (number of samples,).) 2) In the network architecture, initially (in the Con2D part) the input shape will be 5D tensor (number of samples, timesteps, height, width, channels). Then in the LSTM part the input shape will be 3D tensor (number of samples, timesteps, heightwidthchannels). As I am predicting images, should I use Reshape(height, width, channels) at the end of the LSTM? Here is my code: model = Sequential() model.add(TimeDistributed(Convolution2D(128, (5, 5)), input_shape=(None, 512, 512, 1))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(128, (5, 5)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(256, (5, 5)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(256, (5, 5)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(512, (5, 5)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(512, (5, 5)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2)))) model.add(TimeDistributed(Convolution2D(512, (3, 3)))) model.add(Activation('relu')) model.add(TimeDistributed(MaxPooling2D(…

http://stackoverflow.com/q/51708634
favorite count: 0
has comment: http://stackoverflow.com/comment/90378466
upvote count: 3
has answer: http://stackoverflow.com/a/51708952
has answer: http://stackoverflow.com/a/51708783
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90378695
possible better answer: http://stackoverflow.com/a/51708783
has title: Tuple of tuples as argparse command line argument
answer count: 2
accepted answer: http://stackoverflow.com/a/51708952
downvote count: 0
has body: I need users to provide a list of lists of numbers as command line arguments. The current solution I'm adopting is here below, the question is whether there is a more pythonic or more standard way of doing it. Currently I'm accepting a comma-separated list of space-separated numbers from command line, like this: $ python foo.py --numbers '1 2 3, 4 5 6' and internally I do def list_of_lists(arg): return map(lambda l: map(float, l), map(str.split, a.split(','))) parser.add_argument('--numbers', type=list_of_lists) to transform the string "1 2 3, 4 5 6" into [[1,2,3],[4,5,6]].
tagged with: python

http://stackoverflow.com/comment/90398257
type: AnswerComment
comment on: http://stackoverflow.com/a/51683297
has text: In your question you wrote that you are able to extract the SMILES from a csv. Didn't you put them in a list? What did you do?
type: Comment
score: 0

http://stackoverflow.com/q/51778034
tagged with: python
has answer: http://stackoverflow.com/a/51778129
downvote count: 3
has title: Text based dungeon game python
has body: Can you guys run my code in Jupyter note and please tell me whats wrong with it? I don't seem to understand why it doesn't work like it should. Everytime I choose and item from inventory, it gives me game over. I want the code to print whenever the dragon defeated or not and the print statement to next room. import sys print("""Hello! Type 1 to Continue""") #ice sword - a #fire sword - b #electric sword - c inv = {'a':'Ice Sword'} #function to display the inventory def display(): print("type 1 to display your inventory\n") n = input() if int(n)==1: for i in inv: print(i +" - "+ inv[i]) sequence = ['c','a','b'] for i in range(0,4): #room-1 Fire dragon - ice sword win-firesword if i==0: print("You are in room-1 a FIRE DRAGON appears\n") display() print("choose your Item") x = input() if x == 'a' and i==0: print("The fire dragon is defeated proceed to next room\n") print("You have acquired a new Item 'Fire Sword'\n") inv['b'] = 'Fire Sword' else: print("---GAME OVER---") #room-2 Electric dragon - ice sword win-electric sword if i==1: print("You are in room-2 a ELECTRIC DRAGON appears\n") display() print("choose your Item") x = input() if x=='a' and i==1: print("The electric dragon is defeated you proceed next room\n") print("You have acquired a new Item 'Electric Sword'\n") inv['c'] = 'Electric Sword' else: print("---GAME OVER---") #room-3 Ice dragon - fire sword win-key if i==2: print("You are in room-3 a Ice dragon appears\n") display() print("choose your Item") x = input() if x=='b' and i==2: print("The Ice dragon is defeated you __ next room\n") print("You have acquired a new Item 'Key'\n") inv['d'] = 'Key' else: print("---GAME OVER---") #room-4 Dark beast Ganon specific order ([c a b]) if i==3: print("Use the key you won to enter the last room\n") display() print("choose your Item") x = input() if x=='d' and i==3: print("The Final boss DARK BEAST GANON appears\n") else: print("---GAME OVER---") #used the key and the boss appears print("to defeat this boss you need…
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/51778140
answer count: 2
upvote count: 0
tagged with: jupyter
favorite count: 0
type: UnansweredQuestion
score: -3

http://stackoverflow.com/a/51751412
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51751108
type: Answer
score: 2
upvote count: 2
has body: eigh is only for symmetric matrices and thus uses a faster (and different) algorithm. This is why it produces different results. There are an infinite number of eigenvectors for any given eigenvalue, so I don't think you need to be concerned. I've never used these methods and am just going off of my linear algebra knowledge and what I found about eigh and eig online, so please correct me if I'm wrong.
answers question: http://stackoverflow.com/q/51751108
type: AcceptedAnswer

http://stackoverflow.com/q/51740404
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/51750513
has answer: http://stackoverflow.com/a/51750513
tagged with: python
linked to: http://stackoverflow.com/q/48393253
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51741807
type: Question
tagged with: html-table
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51741807
has body: I'm trying to get the tables from a webpage using bs4 and getting them to csv using pandas. The webpage has two tables, I can get the first table, but only the header of second table gets scraped. Below is the code I've used tried out. from urllib2 import Request, urlopen from bs4 import BeautifulSoup from scrapelib import table_to_2d import pandas as pd ehurl = 'https://www.fpi.nsdl.co.in/web/Reports/Latest.aspx' hd = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1;WOW64;rv:46.0) Gecko/46.0 Firefox/46.0'} raq = Request(ehurl, headers=hd) resp = urlopen(raq) eh_page = resp.read() soup = BeautifulSoup(eh_page, "html.parser") i=1 for qeros in soup.findAll("table"): x = table_to_2d(qeros) df = pd.DataFrame(x) df.to_csv("fpi" + str(i) + ".csv", sep=",", header=False, index=False) i += 1 The function table_to_2d is taken from https://stackoverflow.com/a/48451104/2724299
has title: Scrape all tables from a webpage using python bs4

http://stackoverflow.com/q/51708287
has comment: http://stackoverflow.com/comment/90377682
has comment: http://stackoverflow.com/comment/90377745
type: Question
has comment: http://stackoverflow.com/comment/90377996
has comment: http://stackoverflow.com/comment/90379071
has comment: http://stackoverflow.com/comment/90377620
has comment: http://stackoverflow.com/comment/90378320
linked to: http://stackoverflow.com/q/30506069
tagged with: terminal
has body: I have just written a bunch of lines of code on the Python prompt at the terminal. Now, I want to save all those lines of code to a .py file. I am unable to find out how to do that. The only thing that I could find on StackOverflow was this answer but it shows only how to do it in an iPython notebook. I am not using an iPython notebook. I am running the code at the command line on the terminal. I tried to follow that answer (because just in case) and ran the %save magic command on the terminal but it gave a SyntaxError. So, how do save it? Thanks!
has answer: http://stackoverflow.com/a/51709129
has title: How to save code at the python prompt in the terminal to a local file
has comment: http://stackoverflow.com/comment/90378723
favorite count: 0
has answer: http://stackoverflow.com/a/61355244
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90377531
answer count: 4
score: 3
has answer: http://stackoverflow.com/a/51708652
has answer: http://stackoverflow.com/a/51709254
has comment: http://stackoverflow.com/comment/90377862
upvote count: 5

http://stackoverflow.com/comment/90453992
type: Comment
comment on: http://stackoverflow.com/a/51746154
has text: Totally overlooked repetitions. You're absolutely right.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90695179
score: 0
type: AnswerComment
type: Comment
has text: Are you sure you know what you are talking about? Have looked at the other answer? For me it is 100% ok if you just delete your answer, this it is not valid. At least I think it is not valid, but maybe I am wrong.
comment on: http://stackoverflow.com/a/51789197

http://stackoverflow.com/comment/90483250
has text: When I do as you suggested to print all the dates I get no error, but when I try to print only the most recent date I get No Attribute Error as above. It must be how I querying. This results in an error: `lines[0].date`
comment on: http://stackoverflow.com/a/51761328
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90310280
type: AnswerComment
comment on: http://stackoverflow.com/a/51673763
type: Comment
score: 0
has text: Not in a place where I can debug your code, but once you know what to look for, it should not be hard to find examples of how to do these things correctly.

http://stackoverflow.com/comment/90370329
type: QuestionComment
comment on: http://stackoverflow.com/q/51704472
has text: Is that is class which process data and resulted the [6, 6, 6] list
score: 0
type: Comment

http://stackoverflow.com/a/51750070
has comment: http://stackoverflow.com/comment/90460218
has comment: http://stackoverflow.com/comment/90460030
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90460020
type: Answer
score: 2
has body: Always use raw string for regex pattern. And 4th arg for re.sub is not flags. So make sure you specify the flags=re.IGNORECASE while invoking re.sub &gt;&gt;&gt; input_regex = r'Cooper S \(3doors\)' &gt;&gt;&gt; re.search(input_regex,input_text,re.IGNORECASE) &lt;re.Match object; span=(0, 17), match='cooper s (3doors)'&gt; &gt;&gt;&gt; re.sub(input_regex,subst_regex,input_text, flags=re.IGNORECASE) 'Cooper S Hardtop 2 Door'
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51749957
answers question: http://stackoverflow.com/q/51749957
upvote count: 2

http://stackoverflow.com/comment/90497215
score: 2
comment on: http://stackoverflow.com/q/51769239
type: Comment
type: QuestionComment
has text: Dicts are not ordered, so the exact json output is not guaranteed even for the same Python version.

http://stackoverflow.com/q/51658170
score: 0
tagged with: pyqt5
type: Question
has body: Morning/Afternoon/Evening I've hit a brick wall previously I was able to have a QLineEdit be able to give you autofill options such as: Autofill (Can't embedded images so its a link) Previously the values were sorted in a list and using QCompleter and QStringListModel this was possible. Having moved my form that was all QLineEdits to now just a QTableWidget. I want to achieve the same effect as previous with QLineEdit where if you type in the field labaled "Fittings" it will preform as previous. The values that were before stored in a List are now in a SQL DB. from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtSql import * import tkinter import sqlite3 import sys connection = sqlite3.connect("PriceList.db") # Getting Screen info root = tkinter.Tk() root.withdraw() def setup(uname): global user user = uname # Layout layout = QHBoxLayout() right_side = QGridLayout() right_side.setAlignment(Qt.AlignTop) left_side = QVBoxLayout() class QuotesWindow(QMainWindow): def __init__(self, *args, **kwargs): super(QuotesWindow, self).__init__(*args, **kwargs) # Window Settings self.setWindowTitle("Herpy - " + user) self.setWindowIcon(QIcon("icon.png")) self.showMaximized() # Right Side Enter Quote self.input_table() right_side.addWidget(self.tableWidget) # Mid Line mid_line = QFrame() mid_line.setFrameShape(QFrame.VLine) mid_line.setFrameShadow(QFrame.Sunken) # Left Side Details acc_bt = QPushButton("Account") left_side.addWidget(acc_bt) # Who who_box = QLineEdit() who_box.setPlaceholderText("Name") left_side.addWidget(who_box) # Street street_box = QLineEdit() street_box.setPlaceholderText("Street") left_side.addWidget(street_box) # Town town_box = QLineEdit() town_box.setPlaceholderText("Town") left_side.addWidget(town_box) # County county_box = QLineEdit() county_box.setPlaceholderText("County") left_side.addWidget(county_box) # Postcode postc_box = QLineEdit() postc_box.setPlaceholderText("Postcode") left_side.addWidget(postc_box) …
has title: Python - PyQt5 - AutoFill QTableWidget with SQL
linked to: http://stackoverflow.com/q/30017853
has comment: http://stackoverflow.com/comment/90281222
tagged with: pyqt
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90280499
answer count: 0

http://stackoverflow.com/q/51698569
tagged with: python
has comment: http://stackoverflow.com/comment/90358873
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90358779
has title: coinbase Pro python login error
possible better answer: http://stackoverflow.com/a/51996990
type: Question
has answer: http://stackoverflow.com/a/51996990
score: 0
answer count: 2
tagged with: coinbase-api
accepted answer: http://stackoverflow.com/a/51698714
has answer: http://stackoverflow.com/a/51698714
has body: I am using this simple code to login to CoinBase Pro account. secretKey = "xx" key = "yy" from coinbase.wallet.client import Client client = Client(key,secretKey) user = client.get_current_user() It is giving me the following error: Traceback (most recent call last): File "&lt;input&gt;", line 9, in &lt;module&gt; File "/Users/rishibhatt/venv/CoinBase/lib/python3.6/site- packages/coinbase/wallet/client.py", line 220, in get_current_user response = self._get('v2', 'user', params=params) File "/Users/rishibhatt/venv/CoinBase/lib/python3.6/site- packages/coinbase/wallet/client.py", line 129, in _get return self._request('get', *args, **kwargs) File "/Users/rishibhatt/venv/CoinBase/lib/python3.6/site- packages/coinbase/wallet/client.py", line 116, in _request return self._handle_response(response) File "/Users/rishibhatt/venv/CoinBase/lib/python3.6/site-packages/coinbase/wallet/client.py", line 125, in _handle_response raise build_api_error(response) coinbase.wallet.error.AuthenticationError: APIError(id=authentication_error): invalid api key I can't find any post related to this error. Can someone please explain the error or direct me to the correct post? PS: I generated the API keys just today.

http://stackoverflow.com/comment/90465386
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51752768
has text: Explicit is always better than implicit, not sure why you feel that way.
score: 0

http://stackoverflow.com/q/51783734
downvote count: 1
type: UnansweredQuestion
has body: I need to calculate prime numbers. I got the below code from a separate thread: for p in range(2, n+1): for i in range(2, p): if p % i == 0: break else: print p, However, when I run it myself I get: 3 5 5 5 7 7 7 7 7 9 11 11 11 11 11 11 11 11 11 13 13 13 13 13 13 13 13 13 13 13 15 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 21.... Some of which are obviously not primes. I'm on a challenge of Euler's Project that requires prime calculation; after a bit of thought I got to a piece of code similar to the above, but ran into the same problem, which is when I turned to the forum and took this. I'm wondering whether there's something up with the way that the modulus operator is functioning on my machine? Can anyone point me in the direction of where I'm going wrong?
has comment: http://stackoverflow.com/comment/90526714
favorite count: 0
has comment: http://stackoverflow.com/comment/90524604
has comment: http://stackoverflow.com/comment/90524654
type: Question
tagged with: python
tagged with: primes
answer count: 1
has title: Finding primes in Python (trouble with the modulus operator?)
score: 0
has answer: http://stackoverflow.com/a/51783786
has comment: http://stackoverflow.com/comment/90524919
upvote count: 1
has comment: http://stackoverflow.com/comment/90524621

http://stackoverflow.com/comment/97317449
score: 0
type: Comment
type: QuestionComment
has text: unfortunately no :(
comment on: http://stackoverflow.com/q/51671278

http://stackoverflow.com/comment/90428146
has text: Such an investment in time will pay off in the future though.
score: 0
comment on: http://stackoverflow.com/q/51731946
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90390579
type: Comment
has text: Actually, use neither of the above examples, instead use `return lastName + ',' + firstName` instead. Also, your `lastFirst` is potentially not even needed. It seems to me that this was overthought.
comment on: http://stackoverflow.com/q/51714585
score: 0
type: QuestionComment

http://stackoverflow.com/comment/97301789
score: 2
comment on: http://stackoverflow.com/a/51701040
type: AnswerComment
has text: So if this is in a 3rd party app you need to upgrade it? Are you SOL if that 3rd party app is not fixed for PEP 479?
type: Comment

http://stackoverflow.com/a/51704476
has comment: http://stackoverflow.com/comment/90370498
type: Answer
has body: I think you need: df.groupby(['col1', 'col2']).agg('size').unstack().plot(kind = 'bar', legend=True)
score: 3
accepted answer of: http://stackoverflow.com/q/51704243
upvote count: 3
answers question: http://stackoverflow.com/q/51704243
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90533295
comment on: http://stackoverflow.com/q/51787976
score: 0
type: Comment
type: QuestionComment
has text: Seems legit question!

http://stackoverflow.com/q/51759859
has comment: http://stackoverflow.com/comment/90479357
score: 27
has comment: http://stackoverflow.com/comment/90480069
answer count: 2
favorite count: 0
has title: How to move labels from bottom to top without adding "ticks"
tagged with: seaborn
tagged with: python
upvote count: 27
tagged with: heatmap
linked to: http://stackoverflow.com/q/14406214
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53304154
has comment: http://stackoverflow.com/comment/90478826
has comment: http://stackoverflow.com/comment/90480445
has comment: http://stackoverflow.com/comment/90480126
has answer: http://stackoverflow.com/a/51760629
tagged with: plot
type: Question
has body: How can I position xlabel on top of the plot using something else than "tick_top" - that adds a tick to the x label, and I don't want it. xlabel on the bottom with no tick: code: import numpy as np; np.random.seed(0) import matplotlib.pyplot as plt import seaborn as sns sns.set() uniform_data = np.random.rand(10, 12) ax = sns.heatmap(uniform_data, vmin=0, vmax=1) plt.yticks(rotation=0) plt.show() xlabel on top but with tick: code: import numpy as np; np.random.seed(0) import matplotlib.pyplot as plt import seaborn as sns sns.set() uniform_data = np.random.rand(10, 12) ax = sns.heatmap(uniform_data, vmin=0, vmax=1) plt.yticks(rotation=0) ax.xaxis.tick_top() # x axis on top ax.xaxis.set_label_position('top') plt.show()
tagged with: matplotlib

http://stackoverflow.com/comment/90319508
comment on: http://stackoverflow.com/q/51678121
has text: You are creating a new string in your loop and throwing it away. And in any case, strings are immutable in Python.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90553262
has text: If any of those answers below helped you out, please consider voting on/accepting one!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51719033
type: Comment

http://stackoverflow.com/q/51772905
has answer: http://stackoverflow.com/a/51772978
downvote count: 0
has title: Pandas bad escape %s" % escape, len(escape)
favorite count: 0
accepted answer: http://stackoverflow.com/a/51772978
tagged with: python
has answer: http://stackoverflow.com/a/66853594
has body: When executing the following line: df = df[df['Directory'].str.contains("C:\Windows\System32\Tasks")] I get the following error: File "/Users/patrickmaynard/Desktop/CSVparser/parse.py", line 80, in parseFoundFiles df = df[df['Directory'].str.contains("C:\Windows\System32\Tasks")] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/strings.py", line 1562, in contains regex=regex) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/strings.py", line 249, in str_contains regex = re.compile(pat, flags=flags) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 233, in compile return _compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 301, in _compile p = sre_compile.compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py", line 562, in compile p = sre_parse.parse(p, flags) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 856, in parse p = _parse_sub(source, pattern, flags &amp; SRE_FLAG_VERBOSE, False) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 415, in _parse_sub itemsappend(_parse(source, state, verbose)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 501, in _parse code = _escape(source, this, state) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 401, in _escape raise source.error("bad escape %s" % escape, len(escape)) sre_constants.error: bad escape \T at position 19 I have tried other file paths and they work just fine. I didn't include more code as I am certain that it has not effected this line. I believe this might be some weird glitch in pandas or regex, is this the case or have I made a mistake?
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/66853594
has comment: http://stackoverflow.com/comment/90504738
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90505109
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/90549205
type: AnswerComment
comment on: http://stackoverflow.com/a/51795908
type: Comment
has text: First, this is trying to solve a totally different problem from the one the OP asked about. Doing `line[0].strip(" \t")` won't affect an `IndexError` from `line[0]`.
score: 0

http://stackoverflow.com/q/51715290
possible better answer: http://stackoverflow.com/a/51715425
type: AnsweredQuestion
has title: Python: open a URL with accent
has answer: http://stackoverflow.com/a/51715340
has answer: http://stackoverflow.com/a/51715425
type: Question
tagged with: urllib2
has comment: http://stackoverflow.com/comment/90392131
accepted answer: http://stackoverflow.com/a/51715340
score: 0
answer count: 2
tagged with: utf-8
has comment: http://stackoverflow.com/comment/90392735
has body: In Python 2.7, I want to open a URL which contains accents (the link itself, not the page to which it's pointing). If I use the following: #!/usr/bin/env Python # -*- coding: utf-8 -*- import urllib2 test = "https://www.notifymydevice.com/push?ApiKey=K6HGFJJCCQE04G29OHSRBIXI&amp;PushTitle=Les%20accents%20:%20éèçà&amp;PushText=Messages%20éèçà&amp;" urllib2.urlopen(test) My accents are converted to gibberish (Ã, ¨, ©, etc rather than the éèà I expect). I've searched for that kind of issue and so I tried with urllib2.urlopen(test.encode('utf-8')) but Python throws an error in that case: File "test.py", line 10, in urllib2.urlopen(test.encode('utf8')) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 98: ordinal not in range(128)
tagged with: python

http://stackoverflow.com/q/51705206
accepted answer: http://stackoverflow.com/a/51708977
score: -3
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90372980
type: AnsweredQuestion
downvote count: 3
has body: I'm working on an image classification model for a multiclass problem. I get the model up and running, but when I try to predict/test the model, it appears only to be able to recognise 1 of 4 image types (it's the same class no matter how I change the model). My dataset per class is pretty small, but I do use imagegenerator to increase the amount of data. The model should be able to recognise the images with some added noise on the picture. My challenges can be boiled down to this: Small amount of data. I have &lt; 100 images per class. My model is not supposed to find specific figures, but more overall patterns in the picture (areas with a certain colour and such). Many of the pictures contain a lot of white and text. Do I need any image preprocessing to help the model. My model looks like this: model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(s1,s2,3), data_format = "channels_first")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(50, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(4, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy']) And has img size of 250,250, and batch size 16. Check acc and loss curves acc curve loss curve Do you guys have any advice? Thanks in advance!
has comment: http://stackoverflow.com/comment/90371599
type: Question
has answer: http://stackoverflow.com/a/51708977
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/90371620
upvote count: 0
has comment: http://stackoverflow.com/comment/90372623
tagged with: keras
tagged with: deep-learning
answer count: 1
has title: Keras Image Classification Problems
favorite count: 0

http://stackoverflow.com/a/51685828
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51684952
has body: I think you shouldn't create a new session directly with Tensorflow when using Keras. Instead, it is better to use the session implicitly created by Keras: import keras.backend as K sess = K.get_session() However, I think in this case you don't need to retrieve the session at all. You can easily use backend functions, like K.gradients() and K.function(), to achieve your aim.

http://stackoverflow.com/q/51760359
answer count: 2
tagged with: time
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51760487
tagged with: python
has answer: http://stackoverflow.com/a/51760460
has title: Python Time Module-import timex2?
type: Question
has body: I am newbie about python and I didnt understand some place from datatime topic. import time from time import time as my_timer Can u explain me why we use 2 time kind of import here?
score: 0

http://stackoverflow.com/comment/90347731
type: Comment
score: 1
has text: Excellent. Context is key here, and you've given it in your new question. thanks.
comment on: http://stackoverflow.com/a/51689040
type: AnswerComment

http://stackoverflow.com/comment/90387934
comment on: http://stackoverflow.com/q/51712916
score: 0
type: QuestionComment
has text: Please do the following: 1) Fix indentation as Python maintains syntax rules on tabs/spaces and 2) set up a [reproducible example](https://stackoverflow.com/q/20109391/1422451) (as we do not have any of your data).
type: Comment

http://stackoverflow.com/comment/90372215
comment on: http://stackoverflow.com/a/51705573
type: AnswerComment
has text: if I save a model with custom losses I will have to tell keras what they are when loading the same. So `import gse from somewhere` and then `load_model(model_file, custom_objects={'gse':gse}`. `custom_objects` dict...!
score: 0
type: Comment

http://stackoverflow.com/q/51676370
answer count: 2
has comment: http://stackoverflow.com/comment/90316055
has comment: http://stackoverflow.com/comment/90315941
favorite count: 0
linked to: http://stackoverflow.com/q/3748063
type: UnansweredQuestion
has body: Suppose a list in Python -> mylist: mylist = [] I want to now take input from users and update the values afterward in mylist: input1 = ["xyz","wyh",34] print mylist Output: "xyz","wyh",34 input2 = ["yo","hey",657] print mylist output: [["xyz","wyh",34],["yo","hey",657]] append() only works when list has some values already.
tagged with: python
tagged with: dictionary
upvote count: 0
tagged with: list
score: -5
has comment: http://stackoverflow.com/comment/90316411
has comment: http://stackoverflow.com/comment/90316023
has comment: http://stackoverflow.com/comment/90316336
type: Question
has comment: http://stackoverflow.com/comment/90315850
has comment: http://stackoverflow.com/comment/90316685
has answer: http://stackoverflow.com/a/51676413
has comment: http://stackoverflow.com/comment/90315888
downvote count: 5
has title: Is there a dict.update(sub_dict) function for list in Python? (When the list is empty)
has comment: http://stackoverflow.com/comment/90315934
has answer: http://stackoverflow.com/a/51676395

http://stackoverflow.com/comment/90345608
has text: @DYZ - thanks, I modified that slightly to get one working. Ended up `for i in list1:` , `T1.insert("end", i, 'recent')`. Still no line separations like I was shooting for, but I can look that up. Thanks.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51691835

http://stackoverflow.com/comment/90286130
has text: thank you so much that worked:) now I have a permission error. File "neweggwebscrape.py", line 57, in <module> f=open(filename,'w') PermissionError: [Errno 13] Permission denied: 'NeweggWebscrape.csv'
comment on: http://stackoverflow.com/a/51660653
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51715751
tagged with: network-programming
has title: Python - Create list of IPs based off starting IP
type: AnsweredQuestion
has body: I spent a few hours researching, and this has stumped me. Before I go down a new path, I'm looking for a best practice. I ultimately want a list of IPs (just the IPs) when given a starting IP, based off the quantity of items in a list. I've been using the ipaddress module; here's the nearest I've gotten.. import ipaddress IP_Start = 192.168.1.1 hostnames = [hostname1, hostname2, hostname3] list_of_ips = [] my_range = range(len(hostnames)) for ips in my_range: list_of_ips.append(ipaddress.ip_address(IP_Start) + my_range[ips]) print(list_of_ips) Output: list_of_ips = [IPv4Address('192.168.1.1'), IPv4Address('192.168.1.2'), IPv4Address('192.168.1.3')] For some reason, I cannot strip "IPv4Address(' ')" out of the list of strings; my output may not be a traditional list. When using str.replace, I get weird errors and figure replacing is probably not the best practice. I feel like if I ditch the ipaddress module, there would be a much simpler way of doing this. What would be a better way of doing this so my output is simply list_of_ips = [192.168.1.1, 192.168.1.2, 192.168.1.3]
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51715802
type: Question
tagged with: python
tagged with: ip-address
answer count: 2
possible better answer: http://stackoverflow.com/a/51715837
upvote count: 1
has answer: http://stackoverflow.com/a/51715837
accepted answer: http://stackoverflow.com/a/51715802

global
type: Tag
tags question: http://stackoverflow.com/q/51671587
tag name: global
tags question: http://stackoverflow.com/q/51767164
tags question: http://stackoverflow.com/q/51660429
tags question: http://stackoverflow.com/q/51643173

http://stackoverflow.com/comment/90301712
score: 0
type: Comment
type: QuestionComment
has text: @B001ᛦ Do you run it on Python 2.7?
comment on: http://stackoverflow.com/q/51669480

http://stackoverflow.com/q/51729909
favorite count: 0
has comment: http://stackoverflow.com/comment/90420681
has comment: http://stackoverflow.com/comment/90427082
tagged with: python
tagged with: generator
has comment: http://stackoverflow.com/comment/90427220
tagged with: list
has comment: http://stackoverflow.com/comment/90428771
answer count: 0
has comment: http://stackoverflow.com/comment/90428867
type: UnansweredQuestion
score: 1
upvote count: 1
has title: How to call a generator without creating list?
type: Question
has comment: http://stackoverflow.com/comment/90420617
has body: OK, really hope this isn't too basic of a question but I haven't been able to find an answer on this topic. Here goes. I've slightly modified the product function from itertools and it produces exactly what I want. However, I don't need the huge/complete output list, I just want to use its step output (z), do some math (not shown), and move on. The problem is the only way I can call this generator is by putting the output into a list via the last 2 lines of code, which in my mind basically defeats the purpose of a generator. I need this to get up to like 700 repeats, which will create millions of millions of lines that my memory obviously cannot/is not handling. If I just write a = product(range(2),repeat=30) or anything other than exactly how it's shown below I get an error or no output. I realize I'm most likely just not grasping the concept of generators but I keep searching and trying different things and not getting anywhere. If you have any ideas I'd really appreciate it. Thanks! def reduction(): def product(*args, **kwds): # product('ABCD', 'xy') --&gt; Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --&gt; 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] i=int() i=0 for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) z = list(tuple(prod)) i = i+1 print i a=list() a=list(product(range(2),repeat=30))
downvote count: 0

http://stackoverflow.com/a/51768808
accepted answer of: http://stackoverflow.com/q/51768755
answers question: http://stackoverflow.com/q/51768755
has body: Dictionaries in Python are implemented as hash tables, which are inherently unordered – or rather, they are ordered arbitrarily and may change their order upon any modification. This was changed in Python 3.7, where dictionaries keep their insertion order. But relying on this will make your code less portable. Use OrderedDict if you want to keep the ordering on all Python versions: from collections import OrderedDict OrderedDict(sorter(data))
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 5

http://stackoverflow.com/a/76123172
has body: In case someone is wondering how to pad a batch of images instead: def pad_images(images: np.ndarray, top=0, bottom=0, left=0, right=0, constant=0.0) -&gt; np.ndarray: assert len(images.shape) == 4, 'not a batch of images!' return np.pad(images, ((0, 0), (top, bottom), (left, right), (0, 0)), mode='constant', constant_values=constant) Example usage: # assuming `image_batch` has shape (B, H, W, C) pad_images(image_batch, top=1, bottom=1, constant=0.5)
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51650325
upvote count: 1

http://stackoverflow.com/comment/90542272
comment on: http://stackoverflow.com/a/51789104
score: 0
type: AnswerComment
has text: With your approach `sys.stdout.buffer.write("Hello")` does not work, but I need to redirect namely `sys.stdout.buffer`.
type: Comment

http://stackoverflow.com/q/51789010
has comment: http://stackoverflow.com/comment/90535332
accepted answer: http://stackoverflow.com/a/51789044
has title: Returning string in place of None without if statement
has comment: http://stackoverflow.com/comment/90535391
has comment: http://stackoverflow.com/comment/90535575
has comment: http://stackoverflow.com/comment/90535544
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51789122
has body: Is it possible to achieve the same outcome as the code below without making a temp variable and not using a if statement? I have tried multiple things but I am quite new to python. def get_value(dictionary, key): temp = dictionary.get(key) if temp = None: return "Sorry this item doesn't exist" else: return temp i.e. of what I am trying to achieve def get_value(dictionary, key): return dictionary.get(key) else return "Sorry this item doesn't exist"
has answer: http://stackoverflow.com/a/51789044
has comment: http://stackoverflow.com/comment/90535431
type: Question
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/51789122
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/90280628
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51658345
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html This might be useful
score: 0

http://stackoverflow.com/q/51684475
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90331680
tagged with: autoencoder
type: Question
has title: Keras: split to train and test after adding noise is not working
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90333260
has body: I built a denoising autoencoder for training and testing I had to split dataset(image) to train set and test set. If I split before adding noise its working but if I split after adding nosing its not working. I need to split after adding noise. what is the problem here train_size = int(images.shape[0]*0.8) x_train = images[0:train_size] x_test = images[train_size:] x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = np.reshape(x_train, (len(x_train), 64, 64, 1)) x_test = np.reshape(x_test, (len(x_test), 64, 64, 1)) noise_factor = 0.3 x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=2.0, size=x_train.shape) x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=2.0, size=x_test.shape) x_train_noisy = np.clip(x_train_noisy, 0., 1.) x_test_noisy = np.clip(x_test_noisy, 0., 1.) This is working noisy_set = images[0:].astype('float32') / 255. noisy_set = np.reshape(noisy_set, (len(noisy_set), 64, 64, 1)) noise_factor = 0.3 noisy_set = noisy_set + noise_factor * np.random.normal(loc=0.0, scale=2.0, size=noisy_set.shape) noisy_set = np.clip(noisy_set, 0., 1.) train_size = int(images.shape[0]*0.8) x_train = images[0:train_size] x_train_noisy = noisy_set[0:train_size] x_test = images[train_size:] x_test_noisy = noisy_set[train_size:] This is not working
tagged with: keras
answer count: 0

defaultdict
tags question: http://stackoverflow.com/q/51778873
type: Tag
tag name: defaultdict
tags question: http://stackoverflow.com/q/51715077
tags question: http://stackoverflow.com/q/51769187
tags question: http://stackoverflow.com/q/51779236
tags question: http://stackoverflow.com/q/51702626

http://stackoverflow.com/a/52297678
has comment: http://stackoverflow.com/comment/91547842
answers question: http://stackoverflow.com/q/51749426
has body: Load your Turtle file into a proper RDF Triple or Quad Store, and naturally benefit from the DBMS features and functionality.
accepted answer of: http://stackoverflow.com/q/51749426
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51665149
tagged with: python
has answer: http://stackoverflow.com/a/51665359
has body: I have a dict whose values are all lists, and I need to extract the first element of the list for a given key. I had been using var = varDict.get(key, 0) But now that the value is a list I need the same var which was the value and is now the first element of the list. I've tried a few variations, mostly involving putting square brackets in different places with varying numbers in them, my attempt's at slice notation and pulling it from the list the standard way, all of which resulted in either dict.get returning default everytime, or nothing. From researching, it seems like this isn't an issue people have really run into, I tried some of the answers to similar problems but none of them work with this combination of elements. I could also do this by adding an if statement and expanding this quite a bit, but as long as there is a built-in way to do this, which I would assume there is, I'd prefer to keep the code as neat and minimal as practical. Some Context In this particular situation a fuller snippet of my code is: varDict[key] = [vardict.get(key, 0) + step,item2,item3] As you can likely see here, my goal is to increment (or decrement depending on value of step) the int in the list/value associated with the key, overwriting the other two values of the list, and creating the key if it it doesn't already exist. Some Examples As moondra requested here are some examples of expected output: Starting with varDict as an empty dict: key = "test", step = 1, item2 = True, item3 = False Should result in: varDict = {"test": [1, True, False]} Then: key = "test", step = 1, item2 = False, item3 = False Results in: varDict = {"test": [2, False, False]} Then: key = "words", step = -1, item2 = False, item3 = False Results in: varDict = {"test": [2, False, False], "words": [-1, False, False]} I would like to note however that I'm looking for an answer to my question, not my situation, as answering my question could be of help to others who find this and have the same question, wherea…
has comment: http://stackoverflow.com/comment/90293641
has comment: http://stackoverflow.com/comment/90293540
has comment: http://stackoverflow.com/comment/90294193
has comment: http://stackoverflow.com/comment/90293676
has comment: http://stackoverflow.com/comment/90293582
has comment: http://stackoverflow.com/comment/90293524
type: Question
score: -2
has comment: http://stackoverflow.com/comment/90293498
has answer: http://stackoverflow.com/a/51665269
answer count: 2
has comment: http://stackoverflow.com/comment/90293541
downvote count: 3
upvote count: 1
favorite count: 0
tagged with: python-3.x
has title: Finding first element of list returned by dict.get
type: UnansweredQuestion

http://stackoverflow.com/comment/90384496
type: AnswerComment
comment on: http://stackoverflow.com/a/51711604
type: Comment
has text: You haven't explained what is wrong and how you fix it at all
score: 0

http://stackoverflow.com/q/51649746
type: AnsweredQuestion
score: 1
type: Question
tagged with: neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/51651640
has body: I want to check my loss values using MSE during the training process, how to fetching the loss values using MSE at each of iteration?., thank you. from sklearn.neural_network import MLPRegressor from sklearn.metrics import mean_absolute_error dataset = open_dataset("forex.csv") dataset_vector = [float(i[-1]) for i in dataset] normalized_dataset_vector = normalize_vector(dataset_vector) training_vector, validation_vector, testing_vector = split_dataset(training_size, validation_size, testing_size, normalized_dataset_vector) training_features = get_features(training_vector) training_fact = get_fact(training_vector) validation_features = get_features(validation_vector) validation_fact = get_fact(validation_vector) model = MLPRegressor(activation=activation, alpha=alpha, hidden_layer_sizes=(neural_net_structure[1],), max_iter=number_of_iteration, random_state=seed) model.fit(training_features, training_fact) pred = model.predict(training_features) err = mean_absolute_error(pred, validation_fact) print(err)
answer count: 1
tagged with: scikit-learn
has title: Fetching the loss values (MAE) per iteration using sklearn MLPRegressor
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51651640
upvote count: 1
tagged with: python
tagged with: artificial-intelligence

http://stackoverflow.com/comment/90330362
comment on: http://stackoverflow.com/q/51683877
type: Comment
type: QuestionComment
score: 1
has text: Possible duplicate of [What does python sys getsizeof for string return?](https://stackoverflow.com/questions/30255307/what-does-python-sys-getsizeof-for-string-return)

http://stackoverflow.com/q/51720780
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51720863
tagged with: python
tagged with: negative-number
has comment: http://stackoverflow.com/comment/90402134
has comment: http://stackoverflow.com/comment/90402195
accepted answer: http://stackoverflow.com/a/51720858
has comment: http://stackoverflow.com/comment/90402420
type: AnsweredQuestion
upvote count: 9
has body: What is the quickest way to check if the given pandas series contains a negative value. For example, for the series s below the answer is True. s = pd.Series([1,5,3,-1,7]) 0 1 1 5 2 3 3 -1 4 7 dtype: int64
has title: Quick way to check if the pandas series contains a negative value
type: Question
score: 9
tagged with: booleanquery
has answer: http://stackoverflow.com/a/51720858
downvote count: 0
has answer: http://stackoverflow.com/a/51720898
favorite count: 0
tagged with: series
possible better answer: http://stackoverflow.com/a/51720863

http://stackoverflow.com/comment/90475985
type: Comment
score: 0
has text: does `open('file.log', 'w').close()` work? Maybe there is a permissions issue?
type: QuestionComment
comment on: http://stackoverflow.com/q/51758303

http://stackoverflow.com/q/51735862
tagged with: anaconda
score: 0
has body: While trying to just run the example program on my Android phone, I got this error while running buildozer android debug deploy run. # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for android # Install platform # Apache ANT found at /Users/USER/.buildozer/android/platform/apache-ant-1.9.4 # Android SDK found at /Users/USER/.buildozer/android/platform/android-sdk-20 # Android NDK found at /Users/USER/.buildozer/android/platform/android-ndk-r9c # Check application requirements # Check garden requirements # Compile platform # Command failed: /Users/USER/miniconda3/envs/Kivy2New/bin/python -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/Users/USER/Desktop/TestKivy/.buildozer/android/platform/build # # Buildozer failed to execute the last command # If the error is not obvious, please raise the log_level to 2 # and retry the latest command. # In case of a bug report, please add a full log with log_level = 2 All with after just installing Kivy, Cython 0.19 and running buildozer init. The full log with level 2 here. I am running Anaconda on OSX with Python 2 (But same error occurs when on Python 3). Thanks!
has title: OSX Anaconda Python 2 Kivy Android Buildozer Command failed
answer count: 0
type: UnansweredQuestion
tagged with: conda
has comment: http://stackoverflow.com/comment/90432550
tagged with: android
tagged with: kivy
has comment: http://stackoverflow.com/comment/90432509
has comment: http://stackoverflow.com/comment/90434339
type: Question
tagged with: python

http://stackoverflow.com/a/51716842
type: Answer
has comment: http://stackoverflow.com/comment/90410797
accepted answer of: http://stackoverflow.com/q/51716333
upvote count: 1
has body: Solution - Using KivyMD MDDialog In the following example it is using KivyMD MDDialog as popup window. Snippet from kivymd.dialog import MDDialog from kivymd.label import MDLabel from kivy.metrics import dp class ExitPopup(MDDialog): def __init__(self, **kwargs): super(ExitPopup, self).__init__(**kwargs) content = MDLabel(font_style='Body1', theme_text_color='Secondary', text="Are you sure?", size_hint_y=None, valign='top') content.bind(texture_size=content.setter('size')) self.dialog = MDDialog(title="Close Application", content=content, size_hint=(.3, None), height=dp(200)) self.dialog.add_action_button("Close me!", action=lambda *x: self.dismiss_callback()) self.dialog.open() def dismiss_callback(self): self.dialog.dismiss() App.get_running_app().close_app() ... def stop(self, *largs): # Open the popup you want to open and declare callback if user pressed `Yes` ExitPopup() Output - KivyMD MDDialog Solution - Using Kivy Popup Please refer to step-by-step, snippet and example for details. Add import statement, from kivy.uix.button import Button Replace MDIconButton with Button Snippet def stop(self, *largs): # Open the popup you want to open and declare callback if user pressed `Yes` popup = ExitPopup(title="Are you sure?", content=Button(text='Close me!'), size=(400, 400), size_hint=(None, None) ) Example - Kivy Popup main.py # -*- coding: utf-8 -*- import os # Set virtual keyboard from kivy.app import App from kivy.config import Config from kivy.uix.popup import Popup from kivy.uix.button import Button Config.set('kivy', 'keyboard_mode', 'systemandmulti') from kivy.core.window import Window # Window.fullscreen = "auto" from kivy.lang import Builder from functools import partial from kivymd.list import BaseListItem from kivymd.material_resources import DEVICE_TYPE from kivymd.navigationdrawer import MDNavigationDrawer, NavigationDrawerHeaderBase from kivymd.theming import ThemeManager class HackedDemoNavDrawer(MDNavigationDrawer): # DO NOT USE def add_widget(self,…
has comment: http://stackoverflow.com/comment/90424907
score: 1
has comment: http://stackoverflow.com/comment/90578431
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90424734
answers question: http://stackoverflow.com/q/51716333
has comment: http://stackoverflow.com/comment/90560162

http://stackoverflow.com/q/51689620
has answer: http://stackoverflow.com/a/51787954
upvote count: 1
type: Question
has title: Parallelize loops using OpenCL in Python
accepted answer: http://stackoverflow.com/a/51787954
has body: I have a given dataset in the matrix y and I want to train different SOMs with it. The SOM is one-dimensional (a line), and its number of neurons varies. I train a SOM of size N=2 at first, and N=NMax at last, giving a total of NMax-2+1 SOMs. For each SOM, I want to store the weights once the training is over before moving on to the next SOM. The whole point of using PyOpenCL here is that each one of the outer loops is independent of the others. Namely, for each value of N, the script doesn't care about what happens when N takes other values. One could have the same result running the script NMax-2+1 times changing the value of N manually. With this in mind, I was hoping to be able to perform each one of these independent iterations at the same time using the GPU, so that the time spent reduces significantly. The increase in speed will be less than 1/(NMax-2+1) though, because each iteration is more expensive that the previous ones, as for larger values of N, more calculations are made. Is there a way to 'translate' this code to run on the GPU? I've never used OpenCL before, so let me know if this is too broad or silly so I can ask a more specific question. The code is self-contained, so feel free to try it out.The four constants declared at the beginning can be changed to whatever you like (given that NMax &gt; 1 and all the others are strictly positive). import numpy as np import time m = 3 # Dimension of datapoints num_points = 2000 # Number of datapoints iterMax = 150 # Maximum number of iterations NMax = 3 # Maximum number of neurons #%% np.random.seed(0) y = np.random.rand(num_points,m) # Generate always the same dataset sigma_0 = 5 # Initial value of width of the neighborhood function eta_0 = 1 # Initial value of learning rate w = list(range(NMax - 1)) wClusters = np.zeros((np.size(y,axis = 0),NMax - 1)) # Clusters for each N t_begin = time.clock() # Start time for N in range(NMax-1): # Number of neurons for this iteration w[N] = np.random.uniform(0,1,(N+2,np…
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: opencl
tagged with: gpu
tagged with: python
tagged with: pyopencl
tagged with: parallel-processing
type: AnsweredQuestion

http://stackoverflow.com/comment/106004228
comment on: http://stackoverflow.com/q/51734955
score: 0
type: QuestionComment
has text: Might it be something related to this issue: https://github.com/tensorflow/tensorflow/issues/36250 ?
type: Comment

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

http://stackoverflow.com/q/51733286
score: 0
answer count: 1
tagged with: lmfit
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
has body: I would like to know if in Python, and more precisely, in lmfit library, there is an option for fitting data by parts ? I would like to fit data defined in different ranges and then obtain a unique fit. Thank you
type: Question
has title: curve fitting by parts - lmfit Python
has answer: http://stackoverflow.com/a/51737575
accepted answer: http://stackoverflow.com/a/51737575

http://stackoverflow.com/q/51750396
upvote count: 3
has body: I want to know the specific difference between conda, pip and pip3. Specifically, in Anaconda (Python version=3.6), the package of “## + list” is not the same, and I do not find any problems with the alternate use of these installation tools. But I still don't know exactly where these packages are installed, and what's more important is whether they cause conflicts.
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90508931
linked to: http://stackoverflow.com/q/49158543
tagged with: anaconda
linked to: http://stackoverflow.com/q/20994716
has comment: http://stackoverflow.com/comment/90460927
tagged with: conda
linked to: http://stackoverflow.com/q/45471477
linked to: http://stackoverflow.com/q/45917541
has title: The difference of conda, pip and pip3 in anaconda
has comment: http://stackoverflow.com/comment/90508870
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/138309592
score: 0
type: QuestionComment
type: Comment
has text: **Check out this solution:** [Nested dictionary using values](https://stackoverflow.com/a/78452255/10495300)
comment on: http://stackoverflow.com/q/51643706

http://stackoverflow.com/comment/90714613
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51855021
has text: Hi. The code is not related to my problem. If you added "stream=stream.read()" after "stream = open(path, 'rb')" , it would be related to my problem.

http://stackoverflow.com/comment/126036418
comment on: http://stackoverflow.com/a/51739378
has text: Thanks, yeah I guess I would have to use metaclass approach for my use case
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51693773
tagged with: arima
tagged with: python
has title: TimeSeries Stationarity
tagged with: statsmodels
upvote count: 1
has answer: http://stackoverflow.com/a/60757621
has answer: http://stackoverflow.com/a/51693896
has comment: http://stackoverflow.com/comment/90696301
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
has body: I am working on python program for timeseries forecasting of number of events by date. For prediction I use ARIMA model. Now I have some results, but predicted values is not so good. First, I made my timeseries stationary. For this I used: check stationarity by Dickey-Fuller test(0,5), then used Box-Cox transformation and again check ed Dickey-Fuller value(0,3). Then I tried to find first order difference method. I didnt received good results. My question is how to deal with non-stationary time series. which methods should I use to make it stationary?

http://stackoverflow.com/a/51791309
has comment: http://stackoverflow.com/comment/90540267
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: This is because the file url mentioned in the instructions, you followed is invalid and so it returns following html code instead of expected tar.gz file: 301 Moved Permanently 301 Moved Permanently Solution Try below url: https://files.pythonhosted.org/packages/33/bc/fa0b5347139cd9564f0d44ebd2b147ac97c36b2403943dbee8a25fd74012/virtualenv-16.0.0.tar.gz You can refer from here: https://pypi.org/project/virtualenv/#files
upvote count: 2
has comment: http://stackoverflow.com/comment/90540177
accepted answer of: http://stackoverflow.com/q/51791128
answers question: http://stackoverflow.com/q/51791128

http://stackoverflow.com/comment/90347925
type: QuestionComment
comment on: http://stackoverflow.com/q/51693022
has text: Ingredients not in the preferences list get ignored.
score: 0
type: Comment

http://stackoverflow.com/comment/90419647
type: QuestionComment
score: 0
has text: @sP_ didn't get you. Are you saying that I shouldn't have any file named django in any of my apps? Well I don't have any.
comment on: http://stackoverflow.com/q/51729386
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/51648278
tags question: http://stackoverflow.com/q/51795310
tags question: http://stackoverflow.com/q/51699109
tags question: http://stackoverflow.com/q/51767175
tags question: http://stackoverflow.com/q/51732039
tags question: http://stackoverflow.com/q/51707026
tags question: http://stackoverflow.com/q/51753328
tags question: http://stackoverflow.com/q/51732525
tags question: http://stackoverflow.com/q/51743674
tags question: http://stackoverflow.com/q/51755160
tags question: http://stackoverflow.com/q/51663236
tags question: http://stackoverflow.com/q/51677728
tags question: http://stackoverflow.com/q/51714365
tags question: http://stackoverflow.com/q/51737993
tags question: http://stackoverflow.com/q/51773495
tags question: http://stackoverflow.com/q/51695149
tags question: http://stackoverflow.com/q/51748106
tags question: http://stackoverflow.com/q/51684594
tags question: http://stackoverflow.com/q/51747660
tags question: http://stackoverflow.com/q/51716189
tags question: http://stackoverflow.com/q/51755742
tags question: http://stackoverflow.com/q/51756330
tags question: http://stackoverflow.com/q/51652690
tags question: http://stackoverflow.com/q/51742446
tags question: http://stackoverflow.com/q/51711655
tags question: http://stackoverflow.com/q/51668059
tags question: http://stackoverflow.com/q/51780725
tags question: http://stackoverflow.com/q/51728071
tags question: http://stackoverflow.com/q/51777535
tags question: http://stackoverflow.com/q/51777232
tags question: http://stackoverflow.com/q/51710617
tags question: http://stackoverflow.com/q/51790721
tags question: http://stackoverflow.com/q/51677314
tags question: http://stackoverflow.com/q/51757355
tags question: http://stackoverflow.com/q/51718667
tags question: http://stackoverflow.com/q/51649945
tags question: http://stackoverflow.com/q/51645149
tags question: http://stackoverflow.com/q/51721889
tags question: http://stackoverflow.com/q/51749350
tags question: http://stackoverflow.com/q/51764358
tags question: http://stackoverflow.com/q/51673665
tags question: http://stackoverflow.com/q/51703508
tags question: http://stackoverflow.com/q/51743705
tags question: http://stackoverflow.com/q/51642951
tags question: http://stackoverflow.com/q/51734627
tags question: http://stackoverflow.com/q/51679311
tags question: http://stackoverflow.com/q/51724699
tags question: http://stackoverflow.com/q/51728551
tags question: http://stackoverflow.com/q/51754020
tags question: http://stackoverflow.com/q/51685934
tags question: http://stackoverflow.com/q/51672903
tags question: http://stackoverflow.com/q/51696575
tags question: http://stackoverflow.com/q/51794914
tags question: http://stackoverflow.com/q/51676257
tags question: http://stackoverflow.com/q/51724377
tags question: http://stackoverflow.com/q/51678609
tags question: http://stackoverflow.com/q/51794084
tags question: http://stackoverflow.com/q/51756173
tags question: http://stackoverflow.com/q/51684952
tags question: http://stackoverflow.com/q/51663348
tags question: http://stackoverflow.com/q/51691199
tags question: http://stackoverflow.com/q/51782385
tags question: http://stackoverflow.com/q/51674597
tags question: http://stackoverflow.com/q/51796338
tags question: http://stackoverflow.com/q/51748835
tags question: http://stackoverflow.com/q/51771039
tags question: http://stackoverflow.com/q/51662840
tags question: http://stackoverflow.com/q/51708902
tags question: http://stackoverflow.com/q/51654346
tags question: http://stackoverflow.com/q/51692086
tags question: http://stackoverflow.com/q/51692253
tags question: http://stackoverflow.com/q/51653638
tags question: http://stackoverflow.com/q/51662801
tags question: http://stackoverflow.com/q/51748514
tag name: tensorflow
tags question: http://stackoverflow.com/q/51715632
tags question: http://stackoverflow.com/q/51682492
tags question: http://stackoverflow.com/q/51683574
tags question: http://stackoverflow.com/q/51714299
tags question: http://stackoverflow.com/q/51747081

http://stackoverflow.com/comment/90318879
score: 0
type: AnswerComment
has text: Funny, I don't get that error. But try using `strip` to get rid of the trailing whitespace: `pd.to_numeric(df.Quantity.str.replace('Â','').str.strip())`
type: Comment
comment on: http://stackoverflow.com/a/51677760

http://stackoverflow.com/comment/90474233
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51757323
has text: after re-running the code I get:TypeError: Parameters to generic types must be types. Got {'time': '11:58 pm', 'temp': '27\xa0°F', 'weather': 'Partly cloudy.', 'wind': '21 mph', 'humidity': .

http://stackoverflow.com/a/52903322
upvote count: 1
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92718027
has body: The reason for the exception is that your remote function expects three arguments: self, rgx_patts, and phones, since that's how it was declared: @ray.remote def compile_file(self, rgx_patts, phones): Note that you only passed two arguments to it in your call: doc.compile_file.remote(rgx_patts, phones) The first argument is interpreted as being self, the second argument is interpreted as being rgx_patts, and there is no argument passed for phones, hence the exception. A possible workaround is to pass the object (doc, in your example) as your first argument, such that the call would become: doc.compile_file.remote(doc, rgx_patts, phones) Which looks a bit wonky, but I think it should work - and in fact it works for me in a similar scenario, although I can't test it for your case since your code sample is not self contained. If you go with this solution, and doc is the same very time, you might want to use ray.put() to serialize doc only once, instead of every time you call that method. To do that, you could do doc_id = ray.put(doc) (only once) and then replace doc with doc_id in the above code (doc_id is the object id for the serialized doc). Note that another solution is to convert your class into an Actor, which seems appropriate if your class has a "state" that needs to be stored in memory in between calls to the method.
answers question: http://stackoverflow.com/q/51673310

http://stackoverflow.com/q/51744409
has comment: http://stackoverflow.com/comment/90449840
has answer: http://stackoverflow.com/a/51744654
linked to: http://stackoverflow.com/q/5324107
has comment: http://stackoverflow.com/comment/90448736
tagged with: file
has comment: http://stackoverflow.com/comment/90449006
has comment: http://stackoverflow.com/comment/90449813
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51744812
possible better answer: http://stackoverflow.com/a/51744654
has comment: http://stackoverflow.com/comment/90449517
has comment: http://stackoverflow.com/comment/90448766
has comment: http://stackoverflow.com/comment/90448678
has comment: http://stackoverflow.com/comment/90449872
tagged with: rename
answer count: 2
has title: Renaming .png files python
has body: Beginner question: I am trying to rename .png files using: import os os.rename('x.png','y.png') The error I get is: WindowsError: [Error 2] The system cannot find the file specified. I am in the right directory, and so are the files.The strange this is, if I manually rename the file (for example to 'h.png') and use that variable name in the rename command, it does work. I am confused...
score: 0
has comment: http://stackoverflow.com/comment/90448805
has comment: http://stackoverflow.com/comment/90449548
has answer: http://stackoverflow.com/a/51744812
tagged with: python
has comment: http://stackoverflow.com/comment/90448829
has comment: http://stackoverflow.com/comment/90448613

http://stackoverflow.com/comment/90526116
has text: Just to clarify... Are you just trying to get the average value of the sensor readout over the past minute?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51781864
score: 1

http://stackoverflow.com/comment/90476096
comment on: http://stackoverflow.com/q/51758303
score: 0
type: Comment
type: QuestionComment
has text: when I try to add that and run it, the file is being overwritten by this: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

http://stackoverflow.com/q/51796611
has comment: http://stackoverflow.com/comment/90550332
has comment: http://stackoverflow.com/comment/90550415
has comment: http://stackoverflow.com/comment/90550333
has answer: http://stackoverflow.com/a/51796622
has body: I have the following program to find out the leap year year = int(input("Enter a year: ") if (year % 4 == 0) and (year % 100 == 0) and (year % 400 == 0): print("True") else: print("False") However, I'm getting following syntax error File "is_leap.py", line 2 if (year % 4) and (year % 100) and (year % 400): ^ I do not understand why it is showing syntax error in : P.S: I am newbie to Python and programming, and I knew there are solutions in online to figure out leap year. But I'm trying to figure this in my way. I'm trying to understand why it's showing this syntax error while the "if" condition should have : in Python.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90550312
favorite count: 0
score: -1
has title: Syntax error in Python 3.7: in line "if (year % 4) and (year % 100) and (year % 400):"
tagged with: python-3.x
type: Question
downvote count: 2
linked to: http://stackoverflow.com/q/32196628
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90552420
answer count: 1
accepted answer: http://stackoverflow.com/a/51796622

http://stackoverflow.com/a/51692983
answers question: http://stackoverflow.com/q/51692823
type: Answer
downvote count: 0
score: 1
has body: If indeed you are asking for one line per tuple, here's the code. fig = plt.figure() ax = fig.add_subplot(111) assert len(x) == len(y) for i in range(len(x)): plt.plot(x[i], y[i]) plt.show() giving you
upvote count: 1

http://stackoverflow.com/comment/90430240
type: Comment
has text: That's a whole different problem. I'd suggest asking a new question with specifics as to how you want the pie graph to look. But you can take a look at https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html, it might be enough for you to adapt the code above
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51717915

http://stackoverflow.com/q/51736396
has answer: http://stackoverflow.com/a/51736473
tagged with: python
has title: subplots in matplotlib give ValueError: not enough values to unpack
favorite count: 0
score: 8
upvote count: 8
has answer: http://stackoverflow.com/a/51736488
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51736488
linked to: http://stackoverflow.com/q/47029479
type: Question
answer count: 2
has body: The below code gives an error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-14-ea5c06641335&gt; in &lt;module&gt;() 14 values = usa.loc[: , "GDP Billions"] 15 ---&gt; 16 fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6)) 17 18 fig.suptitle('GDP Growth', fontsize=20) ValueError: not enough values to unpack (expected 4, got 2) If I change fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6)) to fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) and delete the corresponding code for ax3 and ax4 below, it works as desired. Not sure why it is not working as written. %matplotlib inline import matplotlib.pyplot as plt import matplotlib.ticker import numpy as np from numpy import array plt.style.use('seaborn-white') plt.rc('ytick', labelsize=14) plt.rc('xtick', labelsize=14) # Plot GDP/Year names = usa.loc[: , "Year"] values = usa.loc[: , "GDP Billions"] fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, figsize=(15, 6)) fig.suptitle('GDP Growth', fontsize=20) ax1.plot(names, values) ax1.xaxis.set_ticks(np.arange(0, 57, 8)) ax1.set_ylabel('GDP', fontsize=16) ax1.set_title('United States',fontsize=16) ax1.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax2.plot(names, values) ax2.xaxis.set_ticks(np.arange(0, 57, 8)) ax2.set_ylabel('Year', fontsize=16) ax2.set_title('China',fontsize=16) ax2.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax3.plot(names, values) ax3.xaxis.set_ticks(np.arange(0, 57, 8)) ax3.set_ylabel('GDP', fontsize=16) ax3.set_title('United States',fontsize=16) ax3.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax4.plot(names, values) ax4.xaxis.set_ticks(np.arange(0, 57, 8)) ax4.set_ylabel('Year', fontsize=16) ax4.set_title('China',fontsize=16) ax4.get_yaxis().set_major_formatter(matplotlib.tic…
downvote count: 0
possible better answer: http://stackoverflow.com/a/51736473

http://stackoverflow.com/comment/90326134
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51680538
type: Comment
has text: @T Burgis I consistently get that the second method, the vectorized method (calc_all_energies), is a little over 10x faster! If you have been playing with it more and have found more optimizations, please let me know.

ethereum
type: Tag
tags question: http://stackoverflow.com/q/51641761
tag name: ethereum
tags question: http://stackoverflow.com/q/51688655

http://stackoverflow.com/q/51796658
has comment: http://stackoverflow.com/comment/90550411
has comment: http://stackoverflow.com/comment/90550396
answer count: 1
duplicate of: http://stackoverflow.com/q/4289331
favorite count: 0
score: 0
has body: How do I split the string 'Notification id = 7427580 user-id = 1992' to obtain the Id numbers from the string only. For example: var NotificationID = 7427580 var UserID = 1992 Thanks in advance! Thanks for the fix: temp = 'Notification id = 7427580 user-id = 1992' for s in temp.split(): if (s.isdigit()): id_list.append(s) print(id_list[0]) print(id_list[1])
has title: Python: Split String by ID
has answer: http://stackoverflow.com/a/51796696
upvote count: 2
downvote count: 2
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51796696
linked to: http://stackoverflow.com/q/4289331
type: Question
tagged with: split

http://stackoverflow.com/comment/90420720
has text: `ValueError: invalid literal for float(): 1,000.000` there is clearly still a comma in one of your value.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51729908
type: AnswerComment

http://stackoverflow.com/comment/90381488
has text: I think the pattern `[a-z]+` . should work
type: QuestionComment
comment on: http://stackoverflow.com/q/51710087
type: Comment
score: 0

http://stackoverflow.com/q/51713293
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51715724
downvote count: 3
has comment: http://stackoverflow.com/comment/90388428
type: Question
has body: I'm trying to solve a problem in which two strings are given as arguments and the task is to determine if the first string contains all the elements necessary to make the second string. I thought I had a fairly straightforward solution by creating dictionaries from the two strings, where the keys are the characters in the strings and the values are their respective number of appearances. Here's the code: def scramble(s1, s2): s1dict = {x: s1.count(x) for x in s1} s2dict = {y: s2.count(y) for y in s2} s3dict = {k:s2dict[k] for k in s2dict and s1dict[k] &gt;= s2dict[k]} return s3dict == s2dict When I try to submit the solution into the web challenge interpreter, it says my code is timing out. I know that for large strings this solution is causing a lot of iteration...What approach can I take to make this more efficent?
has title: Are dict comprehensions inefficient...is there a faster way to compare to keys and values in two dicts?
possible better answer: http://stackoverflow.com/a/51714010
accepted answer: http://stackoverflow.com/a/51715724
has answer: http://stackoverflow.com/a/51714010
has comment: http://stackoverflow.com/comment/90387966
score: -1
answer count: 3
has answer: http://stackoverflow.com/a/76180516
favorite count: 0
has comment: http://stackoverflow.com/comment/90387968

http://stackoverflow.com/q/51743303
tagged with: arima
tagged with: python
has title: Forecasting future with Arima in Python (Key Error)
has body: Im trying to use predict() from statsmodels' Arima library, to make future predictions based on my arima model. I have date as my timeseries index (which i converted using pd.datetime) model = ARIMA(ts_log, order = (5, 1 ,2)) results_arima = model.fit(disp = -1) pred1 = results_arima.predict(start = '2017-12-29' , end = '2018-01-29') My timeseries ends at '2017-12-29' but I want to predict for a month ahead, as shown in the code. This is the error that I get: KeyError: "invalid literal for int() with base 10: '2017-12-29'" This is what my timeseries looks like:
upvote count: 1
tagged with: statsmodels
tagged with: time-series
has comment: http://stackoverflow.com/comment/90453247
tagged with: forecasting
type: UnansweredQuestion
downvote count: 0
answer count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90476903
has comment: http://stackoverflow.com/comment/90519978
type: Question

http://stackoverflow.com/comment/139854012
comment on: http://stackoverflow.com/a/62280907
type: AnswerComment
score: 0
type: Comment
has text: And what would be the safe approach for production if having same issue?

http://stackoverflow.com/comment/90357831
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51698182
score: 0
has text: Very cool, did not think of how indices would behave if I'm changing them!

http://stackoverflow.com/q/51653564
type: Question
has comment: http://stackoverflow.com/comment/90271021
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51653700
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90270584
has title: Calling a python class method from an instance of a class doesn't work as I expect
has body: I'm new to Python, and I think I'm trying to do something simple. However, I am confused with the results I am getting. I am declaring a class that has 2 class methods, add and remove, which in my simple example add or remove a client from a list class variable. Here's my code: Service.py from Client import Client class Service: clients = [] @classmethod def add(cls, client): cls.clients.append(client) @classmethod def remove(cls, client): if client in cls.clients: cls.clients.remove(client) if __name == '__main__' a = Client() b = Client() c = Client() Service.add(a) Service.add(b) Service.add(c) print(Service.clients) c.kill() print(Service.clients) Service.remove(c) print(Service.clients) Client.py class Client: def kill(self): from Service import Service Service.remove(self) I would expect calling c.kill() would remove the instance from the clients list. However, when I evaluate the clients list, it is showing 0 items. when I call Service.remove(c), it shows the correct list, and removes it as expected. I am not sure what I am missing here. If it matters, I am currently using PyCharm with my code running in a Virtualenv with Python 3.6.5.

http://stackoverflow.com/q/51778795
type: UnansweredQuestion
tagged with: exchange-server-2007
tagged with: smtplib
type: Question
tagged with: openssl
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51928780
upvote count: 8
has title: Login via starttls method from smtplib to old e-mail server
tagged with: starttls
tagged with: python
score: 8
has body: I use: Python 2.7.15, OpenSSL 1.1.0h (27 Mar 2018), MS Exchange 2007. My MS exchange allows to send login/pass only after STARTTLS. In python I try to connect to server like: from stmplib import SMTP conn = SMTP(server,port) conn.set_debuglevel(1) conn.starttls() conn.login(username, password) conn.quit() And finally I get error in starttls: /python2.7/ssl.py", line 847, in do_handshake self._sslobj.do_handshake() The problem is follow python try to establish connection with TLS v1.2 but Exchange only support TLS v.1.0. I tried ports 25 and 587. When I tried to connect and login to server by console openssl application it is work fine for both ports with TLS v.1.0: openssl s_client -connect sever:587 -starttls smtp -no_tls1_2 -no_tls1_1 -crlf Server answer: SSL handshake has read 1481 bytes and written 530 bytes --- New, TLSv1/SSLv3, Cipher is RC4-MD5 Server public key is 2048 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE No ALPN negotiated SSL-Session: Protocol : TLSv1 Cipher : RC4-MD5 Session-ID: xxxx Session-ID-ctx: Master-Key: xxxx Key-Arg : None PSK identity: None PSK identity hint: None SRP username: None Start Time: 1533874470 Timeout : 300 (sec) Verify return code: 21 (unable to verify the first certificate) --- 250 CHUNKING ehlo 250-xxxxxxx Hello [xxxx] 250-SIZE 26214400 250-PIPELINING 250-DSN 250-ENHANCEDSTATUSCODES 250-AUTH GSSAPI NTLM LOGIN 250-8BITMIME 250-BINARYMIME 250 CHUNKING ^C I try to inherits standard SMTP class to overload starttls method to use context option like: # show only changes to standard `starttls` method def starttls(self, keyfile=None, certfile=None, context=None): ... if context is None: context = ssl._create_stdlib_context(certfile=certfile, keyfile=keyfile) self.sock = context.wrap_socket(self.sock, server_hostname=self._hostname) ... And use this class in my script: context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.options |= ssl.OP_NO_TLSv1_2 | ssl.OP_NO_TLSv1_1 conn = mySMTP(server,port) conn.set_deb…

http://stackoverflow.com/comment/90380812
score: 0
type: Comment
has text: Man. I did not know applescript was still in carriage return land. Thanks. Do you know how to force applescript to convert captured/passed-on stdout to proper line breaks? Other than, I suppose, just wrapping it up in a bash script or something to always pipe it through to tr like in your example. :-)
comment on: http://stackoverflow.com/a/51699098
type: AnswerComment

http://stackoverflow.com/comment/90510974
has text: The best way is to **debug** your script, there is builtin tool for it called [`pdb`](https://docs.python.org/3/library/pdb.html), or in some fance IDEs debugger is also builtin and easy and fun to use.
comment on: http://stackoverflow.com/q/51776219
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90527952
type: QuestionComment
comment on: http://stackoverflow.com/q/51783527
score: 0
type: Comment
has text: Have a look at the tqdm python library. It's a non-tensorflow solution, but it's something that can get you close to the keras progress bar https://github.com/tqdm/tqdm

http://stackoverflow.com/a/51721979
score: 0
has comment: http://stackoverflow.com/comment/90404510
type: Answer
answers question: http://stackoverflow.com/q/51721790
has body: Use random.choice &gt;&gt;&gt; import random &gt;&gt;&gt; all_chars = lowerConsonants + upperConsonants + lowerVowels + upperVowels + numbers+ symbols &gt;&gt;&gt; ''.join([random.choice(all_chars) for i in range(10)]) 'W+8yB533$W'

http://stackoverflow.com/comment/90437186
comment on: http://stackoverflow.com/q/51738331
has text: Can you show us more of your code?
type: Comment
score: 1
type: QuestionComment

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

http://stackoverflow.com/q/51761012
accepted answer: http://stackoverflow.com/a/51761139
has title: Merge list item with previous list item
favorite count: 0
has body: I'm trying to merge list items with previous items if they don't contain a certain prefix, and adding a \n between said list items when doing so. prefix = '!' cmds = ['!test','hello','world','!echo','!embed','oh god'] output = ['!test\nhello\nworld','!echo','!embed\noh god'] I tried something like for i in list(range(0,len(cmds))): if not cmds[i+1].startswith(prefix): cmds[i] += cmds.pop(i+1) but always get the list index out of range error. My apologies if this is badly worded, or seems like an obvious fix, I'm fairly new to python/programming. Edit: I had managed to get it to work with prefix = '!' cmds = ['!test','hello','world','!echo','!embed','oh god'] print(list(range(0,len(cmds)))) for i in reversed(range(len(cmds))): if not cmds[i].startswith(prefix): cmds[i-1] += '\n'+cmds.pop(i) print(cmds) but your answers seem so much neater and efficient. Much thanks everyone
tagged with: python-3.x
upvote count: 8
has answer: http://stackoverflow.com/a/51761676
tagged with: python
tagged with: merge
answer count: 4
has answer: http://stackoverflow.com/a/51761139
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51761274
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90481248
possible better answer: http://stackoverflow.com/a/51761653
has answer: http://stackoverflow.com/a/51761653
score: 7

http://stackoverflow.com/q/51727255
has answer: http://stackoverflow.com/a/51727375
has comment: http://stackoverflow.com/comment/90416291
has comment: http://stackoverflow.com/comment/90415529
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51727606
has answer: http://stackoverflow.com/a/51728038
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/51727553
has title: Quadrupling list with one-liner
tagged with: python
has body: I can do it with long, ugly way: list_1 = ['AA','BB'] quadrupled = [] for i in list_1: quadrupled.append(i) quadrupled.append(i) quadrupled.append(i) quadrupled.append(i) Or shorter, using .extend(): for i in list_1: quadrupled.extend([i] * 4) But I'm wondering if I can do it using list comprehension. quadrupled = [([i] * 4) for i in list_1] gives me list of lists, but I want flat list. I know that readability of such one-liner might not be too good as it may require to use some nesting and it may be better to stick to .extend() but i'm just wondering if it's possible. I've seen the same for doubling, not quadrupling.
accepted answer: http://stackoverflow.com/a/51727375
has comment: http://stackoverflow.com/comment/90414995
has comment: http://stackoverflow.com/comment/90416387
possible better answer: http://stackoverflow.com/a/51727553
upvote count: 1
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90416088
has answer: http://stackoverflow.com/a/51727323

http://stackoverflow.com/a/51783823
upvote count: 1
type: AcceptedAnswer
has body: On line 8 you have: TypeError: Falscher Farbwert -1!____ (4 blank spaces at the end) You should replace it with: TypeError: Falscher Farbwert -1!
type: Answer
answers question: http://stackoverflow.com/q/51783148
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51783148

http://stackoverflow.com/q/51769509
has answer: http://stackoverflow.com/a/51770169
score: 0
has answer: http://stackoverflow.com/a/51769601
has comment: http://stackoverflow.com/comment/90497691
has title: How to install latest version of Python and python packages in CentOS without internet connection?
tagged with: centos
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51770197
has answer: http://stackoverflow.com/a/51770101
has answer: http://stackoverflow.com/a/51770197
tagged with: package
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/51770101
type: AnsweredQuestion
has body: I am using a computer with the high processing power. This computer is installed with CentOS and I want to install Python 3.6 along with Python packages. The problem I face is that I am not allowed to have an internet connection so I cannot download anything. What should I do?
tagged with: centos7
type: Question

http://stackoverflow.com/q/51746465
has answer: http://stackoverflow.com/a/51746617
has body: I want to add three columns to my Treeview and name them 'Varenavn','Antall','Best før'. I tried the following: self.tree = ttk.Treeview (height = 10, columns = 3) self.tree.grid (row = 4, column = 0, columnspan = 2) self.tree.heading ('#0', text = 'Varenavn', anchor = W) self.tree.heading ('#1', text = 'Antall', anchor = W) self.tree.heading ('#2', text = 'Best før', anchor = W) But I am getting: _tkinter.TclError: Column #2 out of range. If I change the last bit of code to: self.tree.heading ('#1', text = 'Best før', anchor = W) The code runs fine, but overwrites 'Antall' to 'Best før' in the second column. Any ideas would be greatly appreciated!
tagged with: tkinter
has answer: http://stackoverflow.com/a/67535909
tagged with: treeview
has answer: http://stackoverflow.com/a/57210056
has title: Tkinter - Adding multiple columns to a Treeview
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
upvote count: 1
possible better answer: http://stackoverflow.com/a/57210056
accepted answer: http://stackoverflow.com/a/51746617
favorite count: 0
answer count: 3
tagged with: python

http://stackoverflow.com/a/51784878
downvote count: 0
answers question: http://stackoverflow.com/q/51784855
has body: You can convert the type with .astype In [312]: df.columns = df.columns.astype(int) In [313]: df Out[313]: 2006 2007 2008 2009 0 foo foo bar bar 1 foo foo bar bar Or use .map and convert to string type. In [338]: df.columns.map('{:g}'.format) Out[338]: Index(['2006', '2007', '2008', '2009'], dtype='object') In [319]: df.columns.map(int) Out[319]: Int64Index([2006, 2007, 2008, 2009], dtype='int64')
score: 5
accepted answer of: http://stackoverflow.com/q/51784855
type: AcceptedAnswer
type: Answer
upvote count: 5

http://stackoverflow.com/comment/90495813
has text: Yesterday I was able to request without passing this parameter, By the way how can I get a google domain certificate ?
comment on: http://stackoverflow.com/a/51768580
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51746147
has comment: http://stackoverflow.com/comment/90462974
tagged with: python-2.7
has title: Tkinter: Why am I not able to run a code by double-clicking the file?
tagged with: python
favorite count: 0
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90462593
score: 2
downvote count: 0
has body: The code below runs properly, both by running on terminal and upon double-clicking the python file : from Tkinter import * root = Tk() im_fr = Label(root) im_fr.pack(expand = "yes") root.mainloop() But, the moment I use PhotoImage for displaying an image, it ceases to run by double clicking the file, nothing happens on a double-click. It runs only through terminal. The code is below: from Tkinter import * root = Tk() img = PhotoImage(file='img.png') im_fr = Label(root, image = img) im_fr.pack(expand = "yes") root.mainloop() #Runs well on terminal -&gt; python fi.py #Doesn't run on double-click, nothing happens All other Python files run well upon being double-clicked, it's just this one which refuses to. Using python 2.7 on Mint 18.3.
has comment: http://stackoverflow.com/comment/90463159
has comment: http://stackoverflow.com/comment/90465757
has comment: http://stackoverflow.com/comment/90462751
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90463376

http://stackoverflow.com/a/51752463
accepted answer of: http://stackoverflow.com/q/51752298
has body: Both read_csv and read_excel accept a na_values argument, which is described in the docs as follows: na_values : scalar, str, list-like, or dict, default None Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’. This means you can pass your extra values through when you read the file and it should be considerably faster. Basically, where you read the file do placeholders = ['N/A', 'N/a', 'n/a', 'NaN', 'none', '&lt;none&gt;', 'Unassigned', 'Not Reported', '- None -'] df = read_csv(filename, na_values=placeholders) Now that will read the file with NaN in the placeholder positions. To drop the rows containing these values, use dropna(): df = df.dropna(subset=[column]) # For a single column df = df.dropna() # for all rows containing nans df = df.dropna(how='all') # to drop only rows where all columns are nan
answers question: http://stackoverflow.com/q/51752298
type: Answer
has comment: http://stackoverflow.com/comment/90465085
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90464834
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51677760
accepted answer of: http://stackoverflow.com/q/51677679
has comment: http://stackoverflow.com/comment/90318879
has body: Method 1: You can use replace and to_numeric: df['Quantity'] = pd.to_numeric(df.Quantity.str.replace('Â','')) example: &gt;&gt;&gt; df Quantity data 0 0.1 Â 1 1 0.2 Â 2 df['Quantity'] = pd.to_numeric(df.Quantity.str.replace('Â','')) &gt;&gt;&gt; df Quantity data 0 0.1 1 1 0.2 2 Method 2: Alternatively, since your Â is always preceded by a space, you can use split and take the first item: df['Quantity'] = pd.to_numeric(df['Quantity'].str.split().str[0])
has comment: http://stackoverflow.com/comment/90318835
answers question: http://stackoverflow.com/q/51677679
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/90478049
type: QuestionComment
has text: I guess you want something like "notification" in your program right?
score: 0
comment on: http://stackoverflow.com/q/51759304
type: Comment

http://stackoverflow.com/a/51690285
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51690184
has body: Your solution is hard to follow and quite un-pythonic. Consider using the Python power tools: splitting, list comprehension, and joining. def process_madlib(mad_lib): # Split the string into words words = mad_lib.split() # Apply a transformation to each word transformed = [word_transformer(word) for word in words] # Join the transformed words return " ".join(transformed) The second line of the function body can be further rewritten as a mapping: transformed = map(word_transformer, words) Finally, the whole function could be implemented as a one-liner: def process_madlib(mad_lib): return " ".join(map(word_transformer, mad_lib.split()))
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90342590
has comment: http://stackoverflow.com/comment/90342876
type: Answer
answers question: http://stackoverflow.com/q/51690184
score: 1

http://stackoverflow.com/comment/90280997
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51658428
has text: @wpercy I am only an operations analyst and have to work with the data given to me. Essentially, what I am working with is Tissue which can be used one of two ways from the same source. Due to this, the single ID represents the source, the Product ID represents the two types of tissue possible from the source. Our analysis will provide the most detail at a Source level instead of the individual product types as we try and aggregate why a certain source caused a failure of one type but a passable quality for the other type.
type: Comment

http://stackoverflow.com/comment/90667333
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51703508
score: 1
has text: @Tejas I have managed to overcome the error. The package that you should be adding to `REQUIRED_PACKAGES` list in setup.py is `'absl-py>=0.1.0'`. Apart from that, download [this package](https://pypi.org/project/absl-py/#files) tar.gz file to `models/research/dist` . Install by running `pip install absl-py` . Then, when starting the job add `dist/avsl-0.4.0.tar.gz` to the variables passed to the `--packages` flag.

http://stackoverflow.com/a/51784805
upvote count: 6
has comment: http://stackoverflow.com/comment/90528170
type: Answer
has comment: http://stackoverflow.com/comment/90526709
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/51784775
has comment: http://stackoverflow.com/comment/90527338
has body: This is one approach. Using set Ex: string1 = "wana" string2 ="sana" string3 = "".join(set(string1) ^ set(string2)) print(string3) Output: sw
accepted answer of: http://stackoverflow.com/q/51784775
type: AcceptedAnswer

http://stackoverflow.com/a/51699419
has comment: http://stackoverflow.com/comment/90360285
downvote count: 0
has body: Chain two any and map (df&gt;55).any(1).mask((df.isnull()).any(1),np.nan).map({1:'Yes',0:'No'}) Out[405]: 0 Yes 1 NaN 2 Yes 3 No 4 NaN 5 No 6 No 7 NaN 8 Yes 9 Yes dtype: object Or using two np.where a=(df&gt;55).any(1) b=df.isnull().any(1) np.where(b,np.nan,np.where(a,'Yes','No')) Out[407]: array(['Yes', 'nan', 'Yes', 'No', 'nan', 'No', 'No', 'nan', 'Yes', 'Yes'], dtype='&lt;U32')
answers question: http://stackoverflow.com/q/51699376
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/90325167
comment on: http://stackoverflow.com/a/51664275
type: Comment
has text: @Yanpei No, you do not need to reset the graph. There is no such thing as reset the graph; you either use the same one, or create a new one.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51643985
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90252475
has answer: http://stackoverflow.com/a/51644232
downvote count: 1
type: Question
score: -1
upvote count: 0
answer count: 1
has title: Why this code shows wrong message (ignore the first XML element using python)
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
has body: I'm trying to ignore the first XML element using python and found one resolve here but this doesn't work for me. please look at this follow <?xml version="1.0" encoding="UTF-8" standalone="yes"?> some link some link 2 link i want to find I want to ignore only the first li element and print all. So i found this code import xml.etree.ElementTree as ET tree = ET.parse("C:\\ignore_first.xml") root = tree.getroot() ignore_first = root.findall('.//li[position()>1]') print(ignore_first) Where is wrong? this code shows SyntaxError: unsupported function. I don't think li[position()>1] is accepted in python.

http://stackoverflow.com/q/51644318
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51644389
accepted answer: http://stackoverflow.com/a/51655808
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python discord.py Installation
has answer: http://stackoverflow.com/a/51655808
has comment: http://stackoverflow.com/comment/90252742
has comment: http://stackoverflow.com/comment/90252817
has answer: http://stackoverflow.com/a/51644392
type: Question
duplicate of: http://stackoverflow.com/q/8548030
has answer: http://stackoverflow.com/a/51644389
upvote count: 2
answer count: 3
has body: Hi I have just installed python on my mac for the first time and am trying to make a discord bot, but when I run the command: pip install discord.py it displays This error: Can anyone please help me? Thanks ~Jake
downvote count: 1
linked to: http://stackoverflow.com/q/8548030
favorite count: 0

http://stackoverflow.com/a/51705395
has comment: http://stackoverflow.com/comment/90449879
answers question: http://stackoverflow.com/q/51705187
has body: Check out numpy's numpy.unique() function: import numpy as np test = np.array([[255,233,200], [23,66,122], [0,0,123], [233,200,255], [23,66,122]]) print(np.unique(test, axis=0, return_counts = True)) &gt;&gt;&gt; (array([[ 0, 0, 123], [ 23, 66, 122], [233, 200, 255], [255, 233, 200]]), array([1, 2, 1, 1])) You can collect the RGB numpy arrays in a 2D numpy array and then use the numpy.unique() funtion with the axis=0 parameter to traverse the arrays within. Optional parameter return_counts=True will also give you the number of occurences.
has comment: http://stackoverflow.com/comment/90384607
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 13
score: 13
accepted answer of: http://stackoverflow.com/q/51705187

http://stackoverflow.com/q/51652779
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 3
tagged with: ssl
type: Question
has body: the script import ldap ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) try: l = ldap.initialize('ldaps://ldapHost:ldapPort') ldap_base = "ou=XXX,o=XXX" query = "(cn=XXXXX)" result = l.search_s(ldap_base, ldap.SCOPE_SUBTREE, query) except ldap.LDAPError, e: print e returns with the following error: {'info': u'An unexpected TLS packet was received.', 'errno': 2, 'desc': u"Can't contact LDAP server"} Is there any other option I need to specify? Or using cert files is mandatory in this case? I can connect to the ldap server without specifying any cert files. versions: Python 2.7.13 python-ldap 3.1.0 Thanks!
upvote count: 3
tagged with: ldap
has title: Connecting with python-ldap to ldaps - An unexpected TLS packet was received
tagged with: python

http://stackoverflow.com/a/51653074
answers question: http://stackoverflow.com/q/51651732
type: AcceptedAnswer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51651732
has comment: http://stackoverflow.com/comment/90272887
has comment: http://stackoverflow.com/comment/90910219
type: Answer
downvote count: 0
score: 6
has body: This code works the way you want - elem = driver.find_element_by_id("mainCommentForm") text = "To type text here" for character in text: actions = ActionChains(driver) actions.move_to_element(elem) actions.click() actions.send_keys(character) print(character) actions.perform() time.sleep(random.uniform(0.2,0.5))

http://stackoverflow.com/q/51674751
upvote count: 20
has comment: http://stackoverflow.com/comment/90371274
linked to: http://stackoverflow.com/q/22190403
has comment: http://stackoverflow.com/comment/90371173
score: 20
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90314238
tagged with: python
has title: Using Requests library to make asynchronous requests with Python 3.7
has answer: http://stackoverflow.com/a/54677708
tagged with: grequests
has answer: http://stackoverflow.com/a/76323087
has body: I need to make asynchronous requests using the Requests library. In Python 3.7 if I try from requests import async I get SyntaxError: invalid syntax. async has become a reserved with in Python 3.7. How to I get around this situation?
tagged with: python-requests
has answer: http://stackoverflow.com/a/51674813
type: Question

http://stackoverflow.com/a/51755115
has body: import pandas as pd df = pd.read_excel('example.xlsx') df = df[df['A'] == df['B']] print (df.shape[0])
downvote count: 0
has comment: http://stackoverflow.com/comment/90473472
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51754578

flask
tags question: http://stackoverflow.com/q/51702154
tags question: http://stackoverflow.com/q/51675501
tags question: http://stackoverflow.com/q/51744718
tags question: http://stackoverflow.com/q/51797751
tags question: http://stackoverflow.com/q/51753645
tags question: http://stackoverflow.com/q/51765827
tags question: http://stackoverflow.com/q/51678585
tags question: http://stackoverflow.com/q/51660431
tags question: http://stackoverflow.com/q/51756351
tags question: http://stackoverflow.com/q/51785384
tags question: http://stackoverflow.com/q/51764453
tags question: http://stackoverflow.com/q/51733288
tags question: http://stackoverflow.com/q/51798277
tags question: http://stackoverflow.com/q/51769590
tags question: http://stackoverflow.com/q/51774703
tags question: http://stackoverflow.com/q/51696757
tags question: http://stackoverflow.com/q/51662722
tags question: http://stackoverflow.com/q/51783658
tags question: http://stackoverflow.com/q/51707419
tags question: http://stackoverflow.com/q/51747842
tags question: http://stackoverflow.com/q/51657959
tags question: http://stackoverflow.com/q/51719075
tags question: http://stackoverflow.com/q/51715438
tags question: http://stackoverflow.com/q/51774089
tags question: http://stackoverflow.com/q/51678132
tags question: http://stackoverflow.com/q/51681104
tags question: http://stackoverflow.com/q/51660889
tags question: http://stackoverflow.com/q/51795093
tags question: http://stackoverflow.com/q/51713844
tags question: http://stackoverflow.com/q/51700524
tags question: http://stackoverflow.com/q/51717955
tags question: http://stackoverflow.com/q/51649211
tags question: http://stackoverflow.com/q/51789909
tags question: http://stackoverflow.com/q/51791955
tags question: http://stackoverflow.com/q/51742163
tags question: http://stackoverflow.com/q/51657472
tags question: http://stackoverflow.com/q/51766208
tags question: http://stackoverflow.com/q/51670059
tags question: http://stackoverflow.com/q/51698417
tags question: http://stackoverflow.com/q/51735051
tags question: http://stackoverflow.com/q/51700053
tags question: http://stackoverflow.com/q/51679230
tags question: http://stackoverflow.com/q/51706339
tags question: http://stackoverflow.com/q/51737806
tags question: http://stackoverflow.com/q/51692771
tags question: http://stackoverflow.com/q/51711374
tags question: http://stackoverflow.com/q/51702861
tags question: http://stackoverflow.com/q/51669892
tags question: http://stackoverflow.com/q/51702122
tags question: http://stackoverflow.com/q/51649710
tags question: http://stackoverflow.com/q/51643669
tags question: http://stackoverflow.com/q/51782730
tags question: http://stackoverflow.com/q/51702747
tags question: http://stackoverflow.com/q/51733419
tags question: http://stackoverflow.com/q/51728645
tags question: http://stackoverflow.com/q/51789475
tags question: http://stackoverflow.com/q/51787558
tags question: http://stackoverflow.com/q/51640866
tags question: http://stackoverflow.com/q/51714919
tags question: http://stackoverflow.com/q/51697402
tags question: http://stackoverflow.com/q/51657950
tags question: http://stackoverflow.com/q/51715469
tags question: http://stackoverflow.com/q/51768850
tags question: http://stackoverflow.com/q/51665087
type: Tag
tags question: http://stackoverflow.com/q/51773879
tags question: http://stackoverflow.com/q/51665856
tags question: http://stackoverflow.com/q/51755139
tags question: http://stackoverflow.com/q/51760948
tags question: http://stackoverflow.com/q/51715736
tags question: http://stackoverflow.com/q/51740541
tags question: http://stackoverflow.com/q/51650933
tags question: http://stackoverflow.com/q/51786792
tags question: http://stackoverflow.com/q/51765498
tags question: http://stackoverflow.com/q/51685322
tags question: http://stackoverflow.com/q/51726922
tags question: http://stackoverflow.com/q/51795945
tags question: http://stackoverflow.com/q/51721881
tags question: http://stackoverflow.com/q/51762461
tags question: http://stackoverflow.com/q/51767830

http://stackoverflow.com/a/51781489
has body: Using enumerate Ex: d = {'namelist': [{'name':"John",'age':23,'country':'USA'}, {'name':"Mary",'age':12,'country':'Italy'}, {'name':"Susan",'age':32,'country':'UK'}]} d["namelist"] = [{k+"_"+str(i): v for k,v in value.items()} for i , value in enumerate(d["namelist"], 1)] print(d) Output: {'namelist': [{'age_1': 23, 'country_1': 'USA', 'name_1': 'John'}, {'age_2': 12, 'country_2': 'Italy', 'name_2': 'Mary'}, {'age_3': 32, 'country_3': 'UK', 'name_3': 'Susan'}]}
score: 0
answers question: http://stackoverflow.com/q/51781254
type: Answer

http://stackoverflow.com/q/51675033
favorite count: 0
has comment: http://stackoverflow.com/comment/90313030
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90312994
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51675076
tagged with: python
upvote count: 1
downvote count: 7
type: Question
has answer: http://stackoverflow.com/a/51675213
has comment: http://stackoverflow.com/comment/90313094
has body: I was messing around and wanted to see if I could get this simple program to work. I want to check the user input against my list and output whether or not it is in the list. How I have it setup up currently it will return for the 0 index but not the other two. What am I doing wrong? print("Check to See if You are Registered:") name = input("Please Enter Your Name:") check_name = ["lisa", "jim", "betty"] if name == check_name[0]: print("Welcome lisa") if name == check_name[1]: print("Welcome jim") elif name == check_name[2]: print("Welcome betty") pass else: print("Sorry, Looks like you are not in the system") pass
has answer: http://stackoverflow.com/a/51675301
answer count: 3
has title: New to Python, need some direction on checking user input against a list
score: -6

http://stackoverflow.com/comment/131159675
type: AnswerComment
comment on: http://stackoverflow.com/a/69138513
score: 0
type: Comment
has text: @arst3k Thanks for the comment. The error is due to the implementation with `set` which remove all duplicates characters. I will figure out an different implementation

http://stackoverflow.com/comment/90249709
type: Comment
type: QuestionComment
has text: Python 3.6.3 |Anaconda custom (64-bit), pandas 0.20.3'
comment on: http://stackoverflow.com/q/51642556
score: 0

http://stackoverflow.com/q/51759798
accepted answer: http://stackoverflow.com/a/51760010
has body: I have a test.txt file that has right now 2 lines not False == True not True == True I'm trying to import that to my function so that it will display the text with an input and then actually do the Boolean calculation and then do it again for each line. It's working for the input on line 6 but line 7 doesn't work which I know why, I just don't know how to do what I'm trying to do... def calc (read): line = read.readline() if line: lines = line.strip() input(f"Does {lines}?&gt;") print(f"{lines}") return calc(boolfile) boolfile = open("test.txt") calc(boolfile)
has comment: http://stackoverflow.com/comment/90478781
tagged with: python
has title: How to import line from txt file and make it a variable value python?
has comment: http://stackoverflow.com/comment/90478937
answer count: 2
has comment: http://stackoverflow.com/comment/90478760
has answer: http://stackoverflow.com/a/51760005
has comment: http://stackoverflow.com/comment/90478945
has answer: http://stackoverflow.com/a/51760010
has comment: http://stackoverflow.com/comment/90478738
possible better answer: http://stackoverflow.com/a/51760005
downvote count: 4
type: AnsweredQuestion
upvote count: 0
score: -4
favorite count: 0
tagged with: python-3.7
type: Question

http://stackoverflow.com/q/51642600
has body: Trying to solve it in 2 days in a row. I have this only script on my html page: function show() { $.ajax({ url: "index.py", cache: false, contentType: "application/x-www-form-urlencoded;charset=windows-1251", success: function(html){ $("#content").html(html); } }); } function parse() { $.ajax({ url: "parser.py", cache: false, }); } setInterval(show(),1000); setInterval(parse(),10000); &lt;/script&gt; It's deployed on VPS with uWSGI+nginx. The trouble is: on server, when sending ajax requests (index.py, parser.py) with loading the page it сauses calling all js scripts (including bootstrap and jquery in &lt;head&gt;) again and again without delay. But on local python http cgi server it works absolutely fine. May be this happens because of wsgi.py content? def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '''%ENTIRE HTML CODE OF THE PAGE%'''
has comment: http://stackoverflow.com/comment/90249835
tagged with: ajax
has comment: http://stackoverflow.com/comment/90250237
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90250181
tagged with: uwsgi
type: Question
has comment: http://stackoverflow.com/comment/90250320
tagged with: javascript
score: 0
has title: Continuous scripts reloading on uWSGI

http://stackoverflow.com/comment/90476859
has text: So if there are 10 categories you just want to split them into 5 random groups of 2?
score: 0
comment on: http://stackoverflow.com/q/51741790
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90432546
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51735513
type: AnswerComment
has text: @Tissuebox It works approximating the round function, yes, but it is not differentiable mathematically speaking. Please read the formal definition of being differentiable.

http://stackoverflow.com/q/51668608
score: 1
has answer: http://stackoverflow.com/a/51668692
favorite count: 0
accepted answer: http://stackoverflow.com/a/51668649
has body: I'm confused how to access class variables while in methods. For example, what are the ways that the compare method below can use the class variable COURSES? I got it to work by adding self before calling COURSES (self.COURSES.items()), but is that correct? I feel like it is bad practice and I'm missing something, but I can't seem to find the answer. Thanks, everyone. class Example: COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "input", "exceptions", "integers", } def compare(self, arg): intersection_list = [] for key, value in COURSES.items(): if value &amp; arg: intersection_list.append(key) return intersection_list
possible better answer: http://stackoverflow.com/a/51668692
has comment: http://stackoverflow.com/comment/90299931
tagged with: python
linked to: http://stackoverflow.com/q/707380
has title: How do methods within a class access class constant variables?
type: AnsweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90299906
has answer: http://stackoverflow.com/a/51668649
answer count: 2
downvote count: 0

http://stackoverflow.com/q/51683877
linked to: http://stackoverflow.com/q/30255307
has comment: http://stackoverflow.com/comment/90330362
type: Question
tagged with: memory
has title: Why does empty string show a size of 49 in python?
upvote count: 1
answer count: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51683909
score: 0
downvote count: 1
tagged with: python
tagged with: python-3.x
has body: import sys s = "" print(sys.getsizeof(s)) output : 49 What is the reason for this?
type: UnansweredQuestion

http://stackoverflow.com/comment/90384265
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51710856
has text: Hello, thanks for answering, if I tried it as "Reports / Reportes_enviados_20180806.xls" but also gives me the following error "No such file or directory: 'Reportes / Reportes_enviados_20180806.xls" and verified the permissions of the folder, and have permissions for everything, do you think the library is badly installed?
score: 0

http://stackoverflow.com/comment/90490598
has text: Are you seriously suggesting that someone "Wait until Python 3.8"? Completely unrealistic IMO.
comment on: http://stackoverflow.com/a/51765018
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51773208
tagged with: conv-neural-network
downvote count: 0
tagged with: pytorch
type: Question
score: 18
has title: pytorch skip connection in a sequential model
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/51783329
favorite count: 0
accepted answer: http://stackoverflow.com/a/51783329
tagged with: sequential
upvote count: 18
tagged with: python
has body: I am trying to wrap my head around skip connections in a sequential model. With the functional API I would be doing something as easy as (quick example, maybe not be 100% syntactically correct but should get the idea): x1 = self.conv1(inp) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.deconv4(x) x = self.deconv3(x) x = self.deconv2(x) x = torch.cat((x, x1), 1)) x = self.deconv1(x) I am now using a sequential model and trying to do something similar, create a skip connection that brings the activations of the first conv layer all the way to the last convTranspose. I have taken a look at the U-net architecture implemented here and it's a bit confusing, it does something like this: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up Isn't this just adding layers to the sequential model well, sequentially? There is the down conv which is followed by submodule (which recursively adds inner layers) and then concatenated to up which is the upconv layer. I am probably missing something important on how the Sequential API works, but how does the code snipped from U-NET actually implements the skip?
type: AnsweredQuestion

http://stackoverflow.com/a/51761823
has body: Swiping a bit from @AGN above c = np.zeros_like(a, dtype = b.dtype) c[a] = b
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51757511
score: 1
upvote count: 1

http://stackoverflow.com/comment/90532986
comment on: http://stackoverflow.com/a/51781009
type: AnswerComment
score: 0
type: Comment
has text: That looks pretty much right, but when I run it I get this: 'AttributeError: 'bytes' object has no attribute 'findAll''

http://stackoverflow.com/a/51733802
has body: # delete the last character MAIN_txt.delete(len(MAIN_txt.get())-1)
accepted answer of: http://stackoverflow.com/q/51733663
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51733663
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51699222
has comment: http://stackoverflow.com/comment/90359856
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51699290
favorite count: 0
accepted answer: http://stackoverflow.com/a/51699290
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90359866
has title: Get TypeError when call the function from second time
score: 1
type: Question
has body: My problem is the error message only happen after I call the function second time numLen, phoneMask = numberLen(3) TypeError: 'NoneType' object is not iterable Here is my code. If I type in correct extension, for example 71023 at first time I run the script, there is no problem. If I typed wrong extension at first time and typed in correct one the second time, it return the typeerror message and I can see numberlen(i) returned none. Thank you in advance. import sys def numAssign(t): maskList = ['02694406XX', '02693710XX'] extList = ['706XX', '710XX'] i = 0 while i &lt; len(extList) : if t != extList[i] : i = i + 1 else : return True, maskList[i] print('''The extension you entered is not in the indial range.''') return False, ' ' def numberLen(i): t = input('Please enter the extnsion : ') T = len(t) isNum = t.isdecimal() patternConvert = t[0:3] + 'XX' if T == 5 and isNum == True : valid, mask = numAssign(patternConvert) print(mask) print(i) if valid == True: print(numAssign(patternConvert)) return True, mask else : if i == 0 : print('''The number you entered was not valid. It has to be 5 digits.''') else : print('Please try again') print(i) numberLen(i-1) else : if i == 0 : print('Your entering is invalid, we will terminiate the programe') exit() else : numberLen(i-1) if __name__ == '__main__': numLen, phoneMask = numberLen(3) print(phoneMask)enter code here

http://stackoverflow.com/comment/131273183
comment on: http://stackoverflow.com/a/74308173
score: 0
type: AnswerComment
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33099657)
type: Comment

http://stackoverflow.com/comment/90340845
type: Comment
has text: There are limited situations where a try/except with a pass are used.. not ideal, I agree.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51689457

http://stackoverflow.com/q/51791935
accepted answer: http://stackoverflow.com/a/51792140
tagged with: keras
favorite count: 0
has body: UPDATE sdcbr points out in their answer that K.ones_like(T)*a works for generating a similar tensor to the once specified above, the key point being it has the correct batch_size. To clarify with another example, another tensor I need looks like C = [ [a1 a2 ... an] [a1 a2 ... an] ... [a1 a2 ... an] ] The case here is that given vector [a1 a2 ... an] is concatenated with itself to return a tensor that has the same batch_size as T. Original Question I am looking for a way to construct a tensor in Keras which has the same batch_size of another tensor T. An example would be A = [ [a a ... a a] [a a ... a a] ... [a a ... a a] ] where a is repeated n times across the second dim and batch_size(T) across the first dim. If T has a defined batch_size, then the following snippet works just fine A = K.constant(np.array([[a]*n]*T.shape[0])) However, if T is a placeholder then T.shape[0] is None. It would be possible to feed the tensor in as an input, but that seems inelegant and leaves more room for user error. How would I go about generating a tensor of this form?
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90541619
has comment: http://stackoverflow.com/comment/90542449
type: AnsweredQuestion
tagged with: tensor
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51792140
possible better answer: http://stackoverflow.com/a/53854622
has answer: http://stackoverflow.com/a/53854622
answer count: 2
has title: Keras: Construct a full tensor of the same batch size as a given tensor
downvote count: 0

django
tags question: http://stackoverflow.com/q/51749148
tags question: http://stackoverflow.com/q/51762389
tags question: http://stackoverflow.com/q/51708625
tags question: http://stackoverflow.com/q/51746452
tags question: http://stackoverflow.com/q/51719381
tags question: http://stackoverflow.com/q/51765035
tags question: http://stackoverflow.com/q/51656477
tags question: http://stackoverflow.com/q/51693988
tags question: http://stackoverflow.com/q/51721056
tags question: http://stackoverflow.com/q/51639801
tags question: http://stackoverflow.com/q/51750732
tags question: http://stackoverflow.com/q/51647374
tags question: http://stackoverflow.com/q/51712719
tags question: http://stackoverflow.com/q/51678994
tags question: http://stackoverflow.com/q/51726827
tags question: http://stackoverflow.com/q/51729973
tags question: http://stackoverflow.com/q/51672142
tags question: http://stackoverflow.com/q/51732587
tags question: http://stackoverflow.com/q/51782128
tags question: http://stackoverflow.com/q/51720089
tags question: http://stackoverflow.com/q/51783922
tags question: http://stackoverflow.com/q/51761703
tags question: http://stackoverflow.com/q/51689736
tags question: http://stackoverflow.com/q/51653316
tags question: http://stackoverflow.com/q/51774372
tags question: http://stackoverflow.com/q/51712015
tags question: http://stackoverflow.com/q/51786190
tags question: http://stackoverflow.com/q/51761652
tags question: http://stackoverflow.com/q/51791632
tags question: http://stackoverflow.com/q/51693536
tags question: http://stackoverflow.com/q/51673687
tags question: http://stackoverflow.com/q/51791455
tags question: http://stackoverflow.com/q/51715256
tags question: http://stackoverflow.com/q/51745325
tags question: http://stackoverflow.com/q/51710053
tags question: http://stackoverflow.com/q/51648284
tags question: http://stackoverflow.com/q/51699997
tags question: http://stackoverflow.com/q/51643573
tags question: http://stackoverflow.com/q/51769505
tags question: http://stackoverflow.com/q/51795074
tags question: http://stackoverflow.com/q/51781841
tags question: http://stackoverflow.com/q/51663042
type: Tag
tags question: http://stackoverflow.com/q/51645447
tags question: http://stackoverflow.com/q/51692392
tags question: http://stackoverflow.com/q/51672111
tags question: http://stackoverflow.com/q/51656174
tags question: http://stackoverflow.com/q/51747255
tags question: http://stackoverflow.com/q/51709822
tags question: http://stackoverflow.com/q/51643547
tags question: http://stackoverflow.com/q/51724903
tags question: http://stackoverflow.com/q/51792774
tags question: http://stackoverflow.com/q/51713938
tags question: http://stackoverflow.com/q/51682594
tags question: http://stackoverflow.com/q/51777567
tags question: http://stackoverflow.com/q/51752001
tags question: http://stackoverflow.com/q/51695434
tags question: http://stackoverflow.com/q/51644119
tags question: http://stackoverflow.com/q/51690898
tags question: http://stackoverflow.com/q/51772361
tags question: http://stackoverflow.com/q/51753072
tags question: http://stackoverflow.com/q/51759519
tags question: http://stackoverflow.com/q/51735066
tags question: http://stackoverflow.com/q/51790935
tags question: http://stackoverflow.com/q/51729386
tags question: http://stackoverflow.com/q/51640059
tags question: http://stackoverflow.com/q/51711562
tags question: http://stackoverflow.com/q/51745898
tags question: http://stackoverflow.com/q/51695678
tags question: http://stackoverflow.com/q/51724084
tags question: http://stackoverflow.com/q/51704472
tags question: http://stackoverflow.com/q/51695999
tags question: http://stackoverflow.com/q/51702078
tags question: http://stackoverflow.com/q/51761077
tags question: http://stackoverflow.com/q/51748727
tags question: http://stackoverflow.com/q/51697436
tags question: http://stackoverflow.com/q/51725642
tags question: http://stackoverflow.com/q/51787553
tags question: http://stackoverflow.com/q/51725832
tags question: http://stackoverflow.com/q/51641243

http://stackoverflow.com/a/51755175
has comment: http://stackoverflow.com/comment/90470078
score: -1
answers question: http://stackoverflow.com/q/51755131
has comment: http://stackoverflow.com/comment/90470068
upvote count: 0
has comment: http://stackoverflow.com/comment/90470138
type: Answer
has comment: http://stackoverflow.com/comment/90469985
downvote count: 1
has body: You can use any and all: dict_list1 = [{'k1':1, 'k2':2}, {'k1':3, 'k2':4}] dict_list2 = [{'k1':1, 'k2':2, 'k3':10}, {'k1':3, 'k2':4, 'k3':10}] v = [any(all(c in i and i[c] == k for c, k in b.items()) for i in dict_list2)\ for b in dict_list1] Output: [True, True]

http://stackoverflow.com/q/51687223
score: 7
has body: I am trying to copy elements of a doc from one doc file to other. The text part is easy, the images is where it gets tricky. Attaching an image to explain the structure of the doc: Just some text and 1 image. from docx import Document import io doc = Document('/Users/neha/Desktop/testing.docx') new_doc = Document() for elem in doc.element.body: new_doc.element.body.append(elem) new_doc.save('/Users/neha/Desktop/out.docx') This gets me the whole structure of the doc in the new_doc but the image is still blank. Image below: Good thing is I have the blank image in the right place so I thought of getting the byte level data from the previous image and insert it in the new doc. Here is how I extended the above code: from docx import Document import io doc = Document('/Users/neha/Desktop/testing.docx') new_doc = Document() for elem in doc.element.body: new_doc.element.body.append(elem) im = doc.inline_shapes[0] blip = im._inline.graphic.graphicData.pic.blipFill.blip rId = blip.embed doc_part = doc.part image_part = doc_part.related_parts[rId] bytes = image_part._blob #Here I get the byte level data for the image im2 = new_doc.inline_shapes[0] blip2 = im2._inline.graphic.graphicData.pic.blipFill.blip rId2 = blip2.embed document_part2 = new_doc.part document_part2.related_parts[rId2]._blob = bytes new_doc.save('/Users/neha/Desktop/out.docx') But the image still shows empty in the new_doc. What should I do from here?
linked to: http://stackoverflow.com/q/116139
has answer: http://stackoverflow.com/a/73398694
has answer: http://stackoverflow.com/a/51753321
accepted answer: http://stackoverflow.com/a/51802850
favorite count: 0
possible better answer: http://stackoverflow.com/a/51753321
upvote count: 8
answer count: 3
has title: Copying .docx and preserving images
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/docx
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51802850
has comment: http://stackoverflow.com/comment/90466692

http://stackoverflow.com/comment/90435531
has text: If that is the case, then the test case can simply do a `chdir()` before calling the function, to have the function put the files into the chdir'ed directory. Right?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51737334

http://stackoverflow.com/q/51726032
has comment: http://stackoverflow.com/comment/90440496
answer count: 0
favorite count: 0
type: Question
tagged with: facebook
tagged with: django
tagged with: python
has title: Django Social Auth Facebook Valid URL callback
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90412292
has comment: http://stackoverflow.com/comment/90440345
downvote count: 1
has body: Since facebook does not allow URL requests from insecure (http) site to access it . I added http://example.com/oauth/complete/twitter/ and same for google they worked just fine . Now i tried to do same for facebook . I have the ssl certificate for the my site. I referred some questions here but it left me more confused . in my settings.py : AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) my urls.py urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('account.urls')), url(r'^oauth/', include('social_django.urls', namespace='social')) ] i have added https://example.com/oauth/complete/facebook/ in facebook's app but after i clicked on login with facebook it show invalid url .
tagged with: ssl
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90412466
has comment: http://stackoverflow.com/comment/90412297

http://stackoverflow.com/comment/90385470
type: Comment
type: QuestionComment
has text: Note: `gen2` is *not a generator*. It is a regular function, and the PEP 479 changes do not apply to it. Add a `yield` expression to make it a generator.
score: 3
comment on: http://stackoverflow.com/q/51712065

http://stackoverflow.com/comment/90550522
has text: That's because you ran the command wrong. Run it exactly as I wrote it, don't split it in two commands. And don't add stuff, there should be no `sudo` in it.
comment on: http://stackoverflow.com/q/51756910
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90310757
type: AnswerComment
score: 0
type: Comment
has text: Thanks @@AdriVelaz but I'm getting this error `Traceback (most recent call last): File "<stdin>", line 8, in <module> AttributeError: 'nt.stat_result' object has no attribute 'mtime'`
comment on: http://stackoverflow.com/a/51665107

http://stackoverflow.com/comment/132944774
score: 0
type: Comment
type: QuestionComment
has text: Does the link help? https://stackoverflow.com/questions/68462443/efficient-block-bootstrap-of-integer-sequences
comment on: http://stackoverflow.com/q/51641223

http://stackoverflow.com/q/51770056
type: Question
tagged with: python-3.6
has answer: http://stackoverflow.com/a/57127547
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
tagged with: easygui
has title: Python 3.6 open a message box using Tkinter and continue with the script
has body: I have a script that runs a program and then begins a while True loop. I want to open a message box using easyGUI (that simplifies tkinter, so essentially, I want to open a message box using tkinter) and then enter into the while loop. When the message box is dismissed, I want to break from the loop and then kill the program. My question is, how do I achieve this? Current script (section of): import subprocess, easygui from time import sleep f = open("file.txt", "w") notOpen = True while True: if notOpen == True: subprocess.Popen("program.exe", shell=True, stdout=open(os.devnull, 'wb')) easygui.msgbox("\nRunning!", "FSRP engine") notOpen = False f.write("1=") f.flush() sleep(5) f.write("2=") f.flush() sleep(5) f.write("3") f.flush() sleep(5)
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/57127547
type: AnsweredQuestion

http://stackoverflow.com/q/51678991
tagged with: multiprocessing
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/51550131
accepted answer: http://stackoverflow.com/a/51681951
has comment: http://stackoverflow.com/comment/90321366
has body: Using multiprocessing.Pipe I create two multiprocessing.Connection objects, for one of which I read the file descriptor/handle through Conection.fileno() and then pass it as a command line argument to another process. I believe this is similar to how multiprocessing spawns child-processes. In a child process, I'm creating a multiprocessing.Connection object by reading the handle from a command line argument, and then communicate between two processes. This works well on my mac but for some reason calling the Connection.poll method on windows results in the following error: IOError: [Errno 10038] An operation was attempted on something that is not a socket What is the cause of the difference? Why there's no mention of that in polls documentation? A simple code example could be something like: In father.py: c1, c2 = multiprocessing.Pipe() subprocess.Popen(['child.py', str(c1.fileno())]) In child.py: c1 = multiprocessing.Connection(int(sys.argv[1])) c1.poll(1) For additional details, this question and answer of mine describe what I'm trying to achieve and how I ended up doing that.
tagged with: python
has title: Why cannot I poll() on a multiprocessing.Connection object on Windows?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51681951
score: 0
has comment: http://stackoverflow.com/comment/90321548

http://stackoverflow.com/q/51795971
has body: I'd like to delete an entire row of a Pandas DataFrame if that row has a particular entry in one of its columns. Here's a simplified example of what I'm trying to do. In the DataFrame below, I'd like to get rid of rows 'b' and 'd' because they have unwanted entries in column 'C': unwanted_df = pd.DataFrame({'A' : ['aA', 'bA', 'cA', 'dA'], 'B' : ['aB', 'bB', 'cB', 'dB'], 'C' : ['aC', 'unwanted_1', 'cC', 'unwanted_2'], 'D' : ['aD', 'bD', 'cD', 'dD']}, index = ['a','b','c','d']) unwanted_df Here's what that DataFrame looks like: Original DataFrame I tried defining a new DataFrame with the dropped rows using Boolean operators like so: dropped_unwanted_df = \ unwanted_df.drop(unwanted_df[(unwanted_df['C'] == 'unwanted_1') | (unwanted_df['C'] == 'unwanted_2')], axis = 1) However, the output is not what's expected. dropped_unwanted_df Here's what I get: Unexpected Output I wrote another little code that produces what I would have expected: expected_df = pd.DataFrame({'A' : ['aA', 'cA'], 'B' : ['aB', 'cB'], 'C' : ['aC', 'cC'], 'D' : ['aD', 'cD']}, index = ['a','c']) expected_df This is the output I would've liked: Expected Output
has answer: http://stackoverflow.com/a/51796053
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: dataframe
answer count: 2
downvote count: 0
has title: Python Pandas DataFrames: Dropping entire rows if one entry is unwanted
has answer: http://stackoverflow.com/a/51795987
favorite count: 0
tagged with: pandas
tagged with: python

python-3.x
tags question: http://stackoverflow.com/q/51668735
tags question: http://stackoverflow.com/q/51765660
tags question: http://stackoverflow.com/q/51658015
tags question: http://stackoverflow.com/q/51651243
tags question: http://stackoverflow.com/q/51676044
tags question: http://stackoverflow.com/q/51697398
tags question: http://stackoverflow.com/q/51769639
tags question: http://stackoverflow.com/q/51770972
tags question: http://stackoverflow.com/q/51657864
tags question: http://stackoverflow.com/q/51735207
tags question: http://stackoverflow.com/q/51712065
tags question: http://stackoverflow.com/q/51689035
tags question: http://stackoverflow.com/q/51720345
tags question: http://stackoverflow.com/q/51745342
tags question: http://stackoverflow.com/q/51696558
tags question: http://stackoverflow.com/q/51667086
tags question: http://stackoverflow.com/q/51691980
tags question: http://stackoverflow.com/q/51685658
tags question: http://stackoverflow.com/q/51686797
tags question: http://stackoverflow.com/q/51727061
tags question: http://stackoverflow.com/q/51699383
tags question: http://stackoverflow.com/q/51776983
tags question: http://stackoverflow.com/q/51702503
tags question: http://stackoverflow.com/q/51654117
tags question: http://stackoverflow.com/q/51658919
tags question: http://stackoverflow.com/q/51746423
tags question: http://stackoverflow.com/q/51668808
tags question: http://stackoverflow.com/q/51646529
tags question: http://stackoverflow.com/q/51708044
tags question: http://stackoverflow.com/q/51720829
tags question: http://stackoverflow.com/q/51724039
tags question: http://stackoverflow.com/q/51735918
tags question: http://stackoverflow.com/q/51769171
tags question: http://stackoverflow.com/q/51707266
tags question: http://stackoverflow.com/q/51762886
tags question: http://stackoverflow.com/q/51661377
tags question: http://stackoverflow.com/q/51757506
tags question: http://stackoverflow.com/q/51677027
tags question: http://stackoverflow.com/q/51658531
tags question: http://stackoverflow.com/q/51749548
tags question: http://stackoverflow.com/q/51685765
tags question: http://stackoverflow.com/q/51726782
tags question: http://stackoverflow.com/q/51740003
tags question: http://stackoverflow.com/q/51752046
tags question: http://stackoverflow.com/q/51678763
tags question: http://stackoverflow.com/q/51689594
tags question: http://stackoverflow.com/q/51766963
tags question: http://stackoverflow.com/q/51775126
tags question: http://stackoverflow.com/q/51705975
tags question: http://stackoverflow.com/q/51690799
tags question: http://stackoverflow.com/q/51698528
tags question: http://stackoverflow.com/q/51788823
tags question: http://stackoverflow.com/q/51640995
tags question: http://stackoverflow.com/q/51677539
tags question: http://stackoverflow.com/q/51732000
tags question: http://stackoverflow.com/q/51745310
tags question: http://stackoverflow.com/q/51788550
tags question: http://stackoverflow.com/q/51682341
tags question: http://stackoverflow.com/q/51662445
tags question: http://stackoverflow.com/q/51751847
tags question: http://stackoverflow.com/q/51790447
tags question: http://stackoverflow.com/q/51737396
tags question: http://stackoverflow.com/q/51748650
tags question: http://stackoverflow.com/q/51788990
tags question: http://stackoverflow.com/q/51713340
tags question: http://stackoverflow.com/q/51788811
tags question: http://stackoverflow.com/q/51793808
tags question: http://stackoverflow.com/q/51659479
tags question: http://stackoverflow.com/q/51798537
tags question: http://stackoverflow.com/q/51716954
tags question: http://stackoverflow.com/q/51656758
tags question: http://stackoverflow.com/q/51701548
tags question: http://stackoverflow.com/q/51678021
tags question: http://stackoverflow.com/q/51655214
tags question: http://stackoverflow.com/q/51767175
tags question: http://stackoverflow.com/q/51795087
tags question: http://stackoverflow.com/q/51758636
tags question: http://stackoverflow.com/q/51685860
tags question: http://stackoverflow.com/q/51772859
tags question: http://stackoverflow.com/q/51792119

http://stackoverflow.com/comment/90402134
score: 0
type: Comment
has text: `(s<0).sum()>0` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/51720780

http://stackoverflow.com/q/51740424
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90441300
score: 0
tagged with: pandas
answer count: 1
has title: Pandas dataframe currency to numeric
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I know there is other similar topics, but I have tried all of them and did not succeed. I am reading in a dataframa of which one column('Gross') is full of currencies (like $2,553.00) This is how I read in the dataframe: columns=['Client','year','month','traffic','Source','Leads','Sold','Gross'] return pd.read_csv(filename,thousands=',',decimal=".", index_col='Client',parse_dates=True,encoding = "ISO-8859-1",usecols=columns) I have now tried several ways to convert the currency column to floats in order to do calculations with them, for example the following: data = data.apply(lambda x: x.str.replace(',','.')) data['Gross'] = data['Gross'].fillna(0.0).str.replace(r'[$,-]', '').astype('float') which gives me the following error: Traceback (most recent call last): File "C:\Users\Laila\Desktop\tool5.py", line 136, in &lt;module&gt; data=getData() File "C:\Users\Laila\Desktop\tool5.py", line 123, in getData data = data.apply(lambda x: x.str.replace(',','.')) File "C:\Users\Laila\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\frame.py", line 4877, in apply ignore_failures=ignore_failures) File "C:\Users\Laila\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\frame.py", line 4973, in _apply_standard results[i] = func(v) File "C:\Users\Laila\Desktop\tool5.py", line 123, in &lt;lambda&gt; data = data.apply(lambda x: x.str.replace(',','.')) File "C:\Users\Laila\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\generic.py", line 3610, in __getattr__ return object.__getattribute__(self, name) File "C:\Users\Laila\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\accessor.py", line 54, in __get__ return self.construct_accessor(instance) File "C:\Users\Laila\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\strings.py", line 1910, in _make_accessor raise AttributeError("Can only use .str accessor with string " AttributeError: ('Can only use .str accessor with string v…
has answer: http://stackoverflow.com/a/51740678
accepted answer: http://stackoverflow.com/a/51740678
tagged with: dataframe

http://stackoverflow.com/comment/90287807
has text: This is a duplicate that has been asked a million times over (no reflection on you OP), but I can't seem to find a good hammer candidate.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51662051
score: 0

python-imaging-library
tags question: http://stackoverflow.com/q/51764560
tags question: http://stackoverflow.com/q/51676447
tags question: http://stackoverflow.com/q/51710999
tags question: http://stackoverflow.com/q/51694887
tags question: http://stackoverflow.com/q/51763488
tags question: http://stackoverflow.com/q/51681486
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/51725809
tags question: http://stackoverflow.com/q/51702670
type: Tag
tags question: http://stackoverflow.com/q/51786794
tags question: http://stackoverflow.com/q/51733298
tags question: http://stackoverflow.com/q/51773168
tags question: http://stackoverflow.com/q/51774020
tags question: http://stackoverflow.com/q/51789970
tags question: http://stackoverflow.com/q/51663567
tags question: http://stackoverflow.com/q/51736536
tags question: http://stackoverflow.com/q/51776679
tags question: http://stackoverflow.com/q/51775170
tags question: http://stackoverflow.com/q/51754561

http://stackoverflow.com/comment/90447610
type: Comment
has text: `df` is your input dataframe, as in your question. This is the only input for my logic. Everything else is derived.
comment on: http://stackoverflow.com/a/51743304
type: AnswerComment
score: 0

http://stackoverflow.com/a/51708952
answers question: http://stackoverflow.com/q/51708634
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/51708634
has comment: http://stackoverflow.com/comment/90380547
type: Answer
has body: What you have is fine. If I were writing it, I'd use commas and semicolons as delimiters (being strict about it: no whitespace allowed), and use a list comprehension for parsing: def list_of_lists(arg): return [float(x.split(',')) for x in arg.split(';')] but that's really just cosmetic. The next question is: how much verification do you want to do in list_of_lists? Right now, this simple version assumes that the string is in exactly the format you want. You can add more logic to catch errors, raising argparse.ArgumentTypeError to signal incorrect values.
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/90380016

http://stackoverflow.com/a/51745349
has body: How about something like: import os import pandas as pd DATA_DIR = '/path/to/csv_file_dir/' all_companies_df = pd.DataFrame() for _company_fn in os.listdir(DATA_DIR): _company_df = pd.read_csv(DATA_DIR + _company_fn) _company_df.set_index('Quarter End', inplace=True) _company_name = _company_fn.split('_')[0] _company_df.columns = \ pd.MultiIndex.from_product([[_company_name], _company_df.columns.tolist()]) all_companies_df = pd.concat((all_companies_df, _company_df), axis=1)
has comment: http://stackoverflow.com/comment/90454051
has comment: http://stackoverflow.com/comment/90465028
has comment: http://stackoverflow.com/comment/90455874
accepted answer of: http://stackoverflow.com/q/51745110
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90482022
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51745110
has comment: http://stackoverflow.com/comment/90454341
has comment: http://stackoverflow.com/comment/90456097
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90465319
type: QuestionComment
comment on: http://stackoverflow.com/q/51752634
type: Comment
has text: @RoryDaulton: Yes. When I do type(D), type(c), it gives numpy.ndarray
score: 0

http://stackoverflow.com/comment/90536090
comment on: http://stackoverflow.com/a/51777451
score: 0
type: AnswerComment
has text: thanks. But, I have more than 1000 records. @jwood74
type: Comment

http://stackoverflow.com/q/51640505
tagged with: python-dataclasses
tagged with: attributes
favorite count: 0
has comment: http://stackoverflow.com/comment/90249942
possible better answer: http://stackoverflow.com/a/51678459
has answer: http://stackoverflow.com/a/76933035
has comment: http://stackoverflow.com/comment/90248982
has answer: http://stackoverflow.com/a/51678459
has comment: http://stackoverflow.com/comment/90247397
accepted answer: http://stackoverflow.com/a/51641747
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 16
has comment: http://stackoverflow.com/comment/90249070
downvote count: 1
has body: I'm trying to port our namedtuple classes into dataclass in Python 3.6 using the backport package. However, I noticed when mocking dataclass classes, you cannot use the "spec" keyword anymore. I assume it's because the dataclass code is auto generated. from dataclasses import dataclass import mock @dataclass class A: aaa: str bbb: int m = mock.Mock(spec=A) m.aaa And this is the error I get: AttributeError: Mock object has no attribute 'aaa' Any idea if there's any way to automatically set all the attributes from original object to the mock object? I have lots of data classes with a lot of data. It's going to be really tedious if I try to manually set the values one by one.
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/90245518
tagged with: mocking
has title: How to use spec when mocking data classes in Python
has answer: http://stackoverflow.com/a/51641747
has answer: http://stackoverflow.com/a/76385481

http://stackoverflow.com/comment/90248887
comment on: http://stackoverflow.com/q/51642064
has text: for fc in arcpy.SoilData(): arcpy.AddField_management(in_table="Soil_Data", field_name="CODE", \ field_type="INTEGER") fieldName = {CODE [1:10]}
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90360041
has text: @bazza1988 yes for sure exposing a function to change it would work. What I wasn’t sure of is when you needed to change the level. I’m having trouble thinking of a case where you couldn’t simply use info level to log “I started up properly”, if you always want to see that message for example. And then use debug level for abt true debugging things. Then just if you’re having trouble, run at debug level, otherwise run at info level.
comment on: http://stackoverflow.com/a/51699199
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51703391
has answer: http://stackoverflow.com/a/51707019
has title: AsyncResult returns None if task completed successfully
favorite count: 0
tagged with: redis
tagged with: python
type: AnsweredQuestion
has body: I'm currently working on a system where i have a processing component that uses celery to distribute tasks to workers and a backend where you can check the status of longer running tasks. I followed this example and everything works as expected. You can schedule tasks and while the task is running, you can see its status. However after the task is complete, it only works if the task finished with an error. If the task finished with success, AsyncResult returns a None type while the tombstone is still alive, which to my best knowledge is undocumented behaviour. After the tombstone has expired and the task_id is no longer known to celery, it once again returns a PENDING status, which is expected. I'm using redis as result backend, if that makes any difference. Any ideas why i'm getting a None type return for successful tasks?
score: 1
upvote count: 1
tagged with: celery
type: Question
accepted answer: http://stackoverflow.com/a/51707019
downvote count: 0
answer count: 1

http://stackoverflow.com/a/51655363
has comment: http://stackoverflow.com/comment/90274947
has comment: http://stackoverflow.com/comment/90274810
answers question: http://stackoverflow.com/q/51655212
type: Answer
has comment: http://stackoverflow.com/comment/90275019
has comment: http://stackoverflow.com/comment/90275216
has comment: http://stackoverflow.com/comment/90275310
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90274565
has comment: http://stackoverflow.com/comment/90275356
upvote count: 2
has comment: http://stackoverflow.com/comment/90274425
has body: Finding empty directories is a lot easier with os.walk: import os print([root for root, dirs, files in os.walk('/') if not files and not dirs]) Or if you prefer to print the files line by line: import os for root, dirs, files in os.walk('/'): if not files and not dirs: print(root)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90274355
accepted answer of: http://stackoverflow.com/q/51655212

http://stackoverflow.com/comment/90291879
comment on: http://stackoverflow.com/q/51663834
type: Comment
has text: @kevinkayaks No, they are not. If I set xdata=np.linspace(0, 1000, 1000), I find it a straight line. In fact, as x goes to infinity, y should be close to c.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51689670
has comment: http://stackoverflow.com/comment/90344487
score: 6
has body: You should change default program for .py files from pycharm to "python"
has comment: http://stackoverflow.com/comment/90341544
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90351209
accepted answer of: http://stackoverflow.com/q/51689573
type: Answer
answers question: http://stackoverflow.com/q/51689573
upvote count: 6

http://stackoverflow.com/q/51689573
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/66546565
has title: manage.py runserver opens up pycharm instead of running server
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90340958
has answer: http://stackoverflow.com/a/66546565
tagged with: pycharm
has body: I'm pretty new to coding in general and could really use someones help with this! I installed django via CMD on my WIN 10 computer and when I run the server it works. D:\Python\Python37-32\website&gt;manage.py runserver 8080 Performing system checks... System check identified no issues (0 silenced). August 04, 2018 - 15:32:59 Django version 2.1, using settings 'website.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. However... I than downloaded Pycharm Community edition on my computer and instead of the server starting, it just opens up the pycharm ide and the server doesnt run. The interpreter looks fine as well. D:\Python\Python37-32\website&gt;manage.py runserver 8080 D:\Python\Python37-32\website&gt;
has answer: http://stackoverflow.com/a/51689670
type: Question
tagged with: intellij-idea
score: 4
linked to: http://stackoverflow.com/q/2640971
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/51689670
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90340966

http://stackoverflow.com/q/51734545
tagged with: python
has title: How to iterate through the digits of a number without having it under the form of a string in Python?
type: AnsweredQuestion
has body: I've seen a couple posts explaning how to iterate through the digits of a number in Python, but they all turn the number into a string before iterating through it... For example: n=578 print d for d in str(n) How can I do this without the conversion into a string?
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51734607
has comment: http://stackoverflow.com/comment/90429968
accepted answer: http://stackoverflow.com/a/51734607
tagged with: iteration
answer count: 1
score: 1
favorite count: 0
downvote count: 2

http://stackoverflow.com/q/51707357
favorite count: 0
has title: Selenium, Python- Clicking behind an element
has answer: http://stackoverflow.com/a/51707492
has body: I'm trying to click a log in button with selenium (chrome driver, --headless). The problem is that there is a element in front of the log in button. Is there a way to click the button even if an element is in the way? My Python script looks something like this: pirkciau_driver=webdriver.Chrome(crm_path, chrome_options=options) pirkciau_driver.get(login_url) elem = pirkciau_driver.find_element_by_id("email") elem.clear() elem.send_keys(x['pirkciau']['username']) elem = pirkciau_driver.find_element_by_id("passwd") elem.clear() elem.send_keys(x['pirkciau']['password']) elem = pirkciau_driver.find_element_by_id("SubmitLogin") elem.click()
tagged with: python
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/7794087
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90375710
accepted answer: http://stackoverflow.com/a/51707429
type: Question
linked to: http://stackoverflow.com/q/41632230
possible better answer: http://stackoverflow.com/a/51707492
has answer: http://stackoverflow.com/a/51707465
has answer: http://stackoverflow.com/a/51707429
has comment: http://stackoverflow.com/comment/90375500
score: 0
answer count: 3
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/90360053
score: 0
type: AnswerComment
type: Comment
has text: Sounds great please let me know how it works out for you if at all! :)
comment on: http://stackoverflow.com/a/51689168

http://stackoverflow.com/comment/90474755
type: QuestionComment
type: Comment
has text: It sounds like the modules you're using are reading in the entire sheet but missing the conditional formatting. That would explain my they are not correctly writing them back out again. Have you considered trying xlsxwriter instead? See https://xlsxwriter.readthedocs.io/
score: 0
comment on: http://stackoverflow.com/q/51742362

http://stackoverflow.com/comment/90440118
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51736054
type: Comment
has text: I installed API 26,27,28 and the newest version of the building tool. In buildozer.spec i set android.api = 26 and get this error: Check that aidl cam be executed --> Search for Aidl --> Run 'home/dennis/.buildozer/android/platform/android-sdk-20/build-tools/28.0.2/aidl' --> CWD None --> Aidl cannot be executed ..... do you have a solution for that ?

http://stackoverflow.com/q/51705595
linked to: http://stackoverflow.com/q/20109391
upvote count: 3
has answer: http://stackoverflow.com/a/51705766
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51705766
type: Question
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90372625
downvote count: 0
has body: Below I have a DataFrame showing how each vehicle (Vehicle_ID) will visit the different places (place_id) in a particular sequence (Pos_in_route). place_id Lat Lon Vehicle_ID Pos_in_route 0 51.4457678 -0.45613 0 0 1 52.497911 -1.903832 0 1 2 52.332395 -1.346753 0 2 0 51.4457678 -0.45613 0 3 0 51.4457678 -0.45613 1 0 4 52.110728 -0.463547 1 1 3 52.276323 -1.579845 1 2 5 52.423667 -0.609697 1 3 0 51.4457678 -0.45613 1 4 Now I am trying to add another two columns to show the GPS coordinates of the prior place visited (prior_lat, prior_lon), according to the column (Pos_in_route). If there is no prior position of place it will be itself (i.e. place_id = 0) place_id Lat Lon Vehicle_ID Pos_in_route prior_lat prior_lon 0 51.4457678 -0.45613 0 0 51.4457678 -0.45613 1 52.497911 -1.903832 0 1 51.4457678 -0.45613 2 52.332395 -1.346753 0 2 52.497911 -1.903832 0 51.4457678 -0.45613 0 3 52.332395 -1.346753 0 51.4457678 -0.45613 1 0 51.4457678 -0.45613 4 52.110728 -0.463547 1 1 51.4457678 -0.45613 3 52.276323 -1.579845 1 2 52.110728 -0.463547 5 52.423667 -0.609697 1 3 52.276323 -1.579845 0 51.4457678 -0.45613 1 4 52.423667 -0.609697 This is a small part of my program but it's very hard for me to show the complete codes. Maybe there is a simple way to add the last two columns at the end of my program?
favorite count: 0
possible better answer: http://stackoverflow.com/a/51705748
has answer: http://stackoverflow.com/a/51705748
has title: Pandas -- Map values from one column to another column
tagged with: python

http://stackoverflow.com/comment/90436733
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51738186
type: Comment
has text: I'm not familiar with Docker, but maybe you should add pip to your Dockerfile, so Docker knows how to install Pip when recreating your image?

pip
tags question: http://stackoverflow.com/q/51651236
tags question: http://stackoverflow.com/q/51714885
tags question: http://stackoverflow.com/q/51773066
tags question: http://stackoverflow.com/q/51704466
tags question: http://stackoverflow.com/q/51659427
tags question: http://stackoverflow.com/q/51709681
tags question: http://stackoverflow.com/q/51754381
tags question: http://stackoverflow.com/q/51770268
tags question: http://stackoverflow.com/q/51694205
tags question: http://stackoverflow.com/q/51686456
tags question: http://stackoverflow.com/q/51756910
tags question: http://stackoverflow.com/q/51794827
tags question: http://stackoverflow.com/q/51648534
tags question: http://stackoverflow.com/q/51692229
tags question: http://stackoverflow.com/q/51789374
tags question: http://stackoverflow.com/q/51715599
tags question: http://stackoverflow.com/q/51673214
tags question: http://stackoverflow.com/q/51743789
tags question: http://stackoverflow.com/q/51701051
tags question: http://stackoverflow.com/q/51715784
tags question: http://stackoverflow.com/q/51767675
tags question: http://stackoverflow.com/q/51769336
tags question: http://stackoverflow.com/q/51662776
tag name: pip
tags question: http://stackoverflow.com/q/51688655
tags question: http://stackoverflow.com/q/51641367
tags question: http://stackoverflow.com/q/51654726
tags question: http://stackoverflow.com/q/51699886
tags question: http://stackoverflow.com/q/51751223
tags question: http://stackoverflow.com/q/51776103
tags question: http://stackoverflow.com/q/51646558
tags question: http://stackoverflow.com/q/51643451
tags question: http://stackoverflow.com/q/51758197
tags question: http://stackoverflow.com/q/51642944
tags question: http://stackoverflow.com/q/51644402
tags question: http://stackoverflow.com/q/51733027
tags question: http://stackoverflow.com/q/51732582
tags question: http://stackoverflow.com/q/51668485
tags question: http://stackoverflow.com/q/51697323
tags question: http://stackoverflow.com/q/51657865
tags question: http://stackoverflow.com/q/51748058
tags question: http://stackoverflow.com/q/51745894
tags question: http://stackoverflow.com/q/51796155
tags question: http://stackoverflow.com/q/51795199
tags question: http://stackoverflow.com/q/51738186
tags question: http://stackoverflow.com/q/51756108
tags question: http://stackoverflow.com/q/51714684
tags question: http://stackoverflow.com/q/51720909
tags question: http://stackoverflow.com/q/51748121
tags question: http://stackoverflow.com/q/51641650
tags question: http://stackoverflow.com/q/51777918
type: Tag
tags question: http://stackoverflow.com/q/51738505
tags question: http://stackoverflow.com/q/51714524
tags question: http://stackoverflow.com/q/51704003
tags question: http://stackoverflow.com/q/51657805
tags question: http://stackoverflow.com/q/51695434
tags question: http://stackoverflow.com/q/51641690
tags question: http://stackoverflow.com/q/51645246
tags question: http://stackoverflow.com/q/51715424
tags question: http://stackoverflow.com/q/51771656
tags question: http://stackoverflow.com/q/51763405
tags question: http://stackoverflow.com/q/51785602
tags question: http://stackoverflow.com/q/51640667
tags question: http://stackoverflow.com/q/51710290
tags question: http://stackoverflow.com/q/51717507
tags question: http://stackoverflow.com/q/51716115
tags question: http://stackoverflow.com/q/51651515
tags question: http://stackoverflow.com/q/51714605
tags question: http://stackoverflow.com/q/51697141
tags question: http://stackoverflow.com/q/51758754

http://stackoverflow.com/comment/90286492
type: AnswerComment
has text: I quite agree. If you're headed there yourself, at least look up one set of physiology research. Coat patterning in many animals (tiger stripes, leopard spots, etc.) results from the interactions of color-coding chemical signals that resonate over a surface model of the animal. Once the researches understood the mechanism, they could model it with a sheet-metal cutout (like a tiger-skin rug) and vibrations from the physically critical points of the body. Put granules on the sheet start the vibration, and you get the coat patterning in the lab.
type: Comment
comment on: http://stackoverflow.com/a/51659896
score: 1

http://stackoverflow.com/comment/90473710
has text: h is the output you get for a single input of the unrolled input sequence. So `h.shape = [batch_size, h_dim]`
type: AnswerComment
comment on: http://stackoverflow.com/a/51756833
score: 0
type: Comment

http://stackoverflow.com/a/51690691
score: 2
downvote count: 0
has body: Taken from jasonharper... &lt;Enter&gt; is whenever the mouse enters the widget &lt;Return&gt; is the actual enter button
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51690173
answers question: http://stackoverflow.com/q/51690173
type: Answer

http://stackoverflow.com/a/51675553
score: 0
has body: using sample, you can do it this way: #create a dataframe like yours df = pd.DataFrame({'tag':['a']*1500 + ['b']*3250 + ['c']*320 + ['d']*260,'col1':range(5330)}) min_size = df.groupby('tag').count().min()[0] #here it's 260 max_plus = 50 df_sample = (df.groupby('tag',as_index=False) .apply(lambda x: x.sample(min(len(x), min_size + np.random.randint(max_plus,size=1)))) .reset_index(drop=True)) # this is not mandatory, it depends of your needs and then for example with my try: print (df_sample.groupby('tag').count()) Out[292]: col1 tag a 270 b 299 c 287 d 260
type: Answer
answers question: http://stackoverflow.com/q/51672398

http://stackoverflow.com/q/51742139
accepted answer: http://stackoverflow.com/a/51742502
type: Question
tagged with: python
has title: Fix parameters of a class
tagged with: oop
has comment: http://stackoverflow.com/comment/90444725
score: 0
has answer: http://stackoverflow.com/a/51742541
answer count: 3
has answer: http://stackoverflow.com/a/51742422
has answer: http://stackoverflow.com/a/51742502
tagged with: object
possible better answer: http://stackoverflow.com/a/51742541
has body: I have a class that takes in three different objective types. Let's assume the class name is BaseEstimator and it accepts three modes- 'obj_1', 'obj_2' and 'obj_3' for the objective parameter. Now I want to create three classes, one for each of the objective types. These classes will by default pass in each of the objective type. so for example FixedEstimator_Obj1 will have objective = 'obj_1'. I understand I can do this by doing something like this in the __init__ function of the FixedEstimator_Obj1 class: class FixedEstimator_Obj1: def __init__(self): self.base_estimator = BaseEstimator(objective='obj_1') The issue with this approach is that when I want to access an attribute or a use a method of the BaseEstimator, I'll have to access it through the base_estimator like so fe_obj1 = FixedEstimator_Obj1() fe_obj1.base_estimator.some_method() What I am looking for is a way that will allow me to write the above as fe_obj1.some_method() How do I this?
type: AnsweredQuestion

http://stackoverflow.com/q/51736643
type: UnansweredQuestion
upvote count: 1
type: Question
has body: In Java, it is possible to write code like this: int number = 1; while((number++)&lt;10){ System.out.println(number); } I tried doing the same in Python, but got a syntax error. Is there any similar feature in Python where the value of a variable can be modified within a conditional expression?
score: 1
tagged with: java
tagged with: control-structure
has answer: http://stackoverflow.com/a/51736659
has comment: http://stackoverflow.com/comment/90434229
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90436358
has comment: http://stackoverflow.com/comment/90434251
has title: Modifying variable within conditional expression in Python
linked to: http://stackoverflow.com/q/3654830
favorite count: 0
tagged with: increment
tagged with: python

http://stackoverflow.com/q/51640672
has body: I have docker image with bash and python scripts inside it: 1) entrypoint.sh (this script runs python file); 2) parser.py When developers run a container, they can pass env variables with prefix like MYPREFIX_*. docker run name -e MYPREFIX_1=true -e MYPREFIX_DEMO=100 ... There are more than 100 possible keys, they change from time to time (depending on remote configuration file). I'd like to pass all variables to the bash script and then to the python script. I can't define all variables inside Dockerfile (keys can change). I also can't use env_file. Are there any suggestions? Content of entrypoint: /usr/bin/python3 "/var/hocon-parser.py" /usr/bin/curl -sLo /var/waves.jar "https://github.com/wavesplatform/Waves/releases/download/v$WAVES_VERSION/waves-all-$WAVES_VERSION.jar" /usr/bin/java -jar /var/waves.jar /waves-config.conf
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51654696
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90247819
tagged with: docker
tagged with: environment-variables
has comment: http://stackoverflow.com/comment/90249442
downvote count: 0
has title: Get all Docker env variables in python script inside a container
answer count: 1
has comment: http://stackoverflow.com/comment/90248106
has comment: http://stackoverflow.com/comment/90245989

http://stackoverflow.com/comment/90502907
has text: Do you want to avoid querying `Parent` at the same time, or is eager loading an ok solution?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51771062

aws-lambda
tags question: http://stackoverflow.com/q/51676317
type: Tag
tags question: http://stackoverflow.com/q/51737239
tags question: http://stackoverflow.com/q/51721079
tags question: http://stackoverflow.com/q/51680179
tag name: aws-lambda
tags question: http://stackoverflow.com/q/51679863
tags question: http://stackoverflow.com/q/51702716
tags question: http://stackoverflow.com/q/51691812
tags question: http://stackoverflow.com/q/51695467
tags question: http://stackoverflow.com/q/51703107
tags question: http://stackoverflow.com/q/51750492
tags question: http://stackoverflow.com/q/51774759
tags question: http://stackoverflow.com/q/51644377
tags question: http://stackoverflow.com/q/51738406
tags question: http://stackoverflow.com/q/51783578

http://stackoverflow.com/a/53453830
has body: You can update your urllib3 using pip install --upgrade --ignore-installed urllib3
downvote count: 0
type: Answer
upvote count: 9
has comment: http://stackoverflow.com/comment/110262374
answers question: http://stackoverflow.com/q/51686224
score: 9

http://stackoverflow.com/comment/90461284
has text: `i` is just an arbitrary variable name, it doesn't affect what's going on. You can call it `banana` and it all works the same.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51748786

http://stackoverflow.com/a/51793849
upvote count: 1
score: 1
has body: You can convert a string to a list of ascii values with ord. values = [ord(c) for c in data] Although, depending on what you want to do, you might not even need to cast your data as a list since a str is already iterable. Instead, iterate over your characters and recover their value. Here is a simplified example. dt = '\xa0\x1e\x03\x00\x02\xfe' for x in map(ord, dt): print(x) Output 160 30 3 0 2 254
downvote count: 0
has comment: http://stackoverflow.com/comment/90548641
type: Answer
answers question: http://stackoverflow.com/q/51793633

http://stackoverflow.com/comment/111164374
has text: https://stackoverflow.com/questions/62857682/how-to-skip-tests-based-on-condition-in-pytest#comment111156247_62857682
comment on: http://stackoverflow.com/a/51762407
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90504416
has text: If I understand correctly, you create circular reference between TempFile and tempfile._TemporaryFileWrapper
type: Comment
comment on: http://stackoverflow.com/a/51766897
score: 0
type: AnswerComment

http://stackoverflow.com/q/51770237
accepted answer: http://stackoverflow.com/a/51771504
score: 1
has body: I'm learning django for building my website. I learned how to create models, views, but now I have some question relative to admin interface. So I have tis code: from django.db import models class AudioBook(models.Model): titolo=models.CharField(max_length=250) capitoli=models.ManyToManyField('Chapters') class Chapters(models.Model): capitolo=models.CharField(max_length=250) Now, when I add a new audiobook I can see chapters previously added to others audiobooks. This is bad. I want only the chapters taht belong to this audiobook, so, when I add a new one, the list must be empty. I tried some things: adding limit_choices_to = models.Q(audiobook__titolo=titolo), but it doesn't work. In command line I can retrieve these info by adding filters on Chapters object, but I can reproduce this situation in admin interface. Any idea? I searched on google but I didn't find anything that helps me. Germano
upvote count: 1
has comment: http://stackoverflow.com/comment/90539120
type: Question
has title: Python django admin: How can I show only items belonging to specific model in an admin page?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51771504
favorite count: 0
has comment: http://stackoverflow.com/comment/90499132
tagged with: django
tagged with: python
type: AnsweredQuestion

checkbox
tags question: http://stackoverflow.com/q/51704745
tag name: checkbox
type: Tag

http://stackoverflow.com/a/51692938
answers question: http://stackoverflow.com/q/51692893
upvote count: 1
has body: Use a positive lookbehind: sent = "Sales to two of the segment's customers, The Home Depot and Lowe's Home Improvement Warehouse, accounted for greater than 10% of the Corporation's consolidated sales for 2004, 2003, and 2002." regex_ = re.compile(r"(?&lt;=Sales to two of the segment's customers, The )Home Depot") print(regex_.search(sent).span()) Output: (45, 55)
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/90249257
comment on: http://stackoverflow.com/q/51640122
score: 0
type: Comment
type: QuestionComment
has text: What is not specific enough about this?

http://stackoverflow.com/q/51677024
has body: The goal is to write csv files for each Invoice from a webpage. I'm trying to do this with a webscraper, mainly using selenium Each Invoice has its own number, date, close_date, amount, and list of Records Each Record in an Invoice has its own id, description, storage, weight, price, and quantity I was able to successfully print out to the console all of the data I need. Like so: Going to: https://thewebsite/thing/my_account.whatever?is=checkout#invoices/429807/paid-invoices Extracting... ------------------------------ ID: 30795 Description: YOGURT, BLUEBERRY, LOW FAT, DANNON Storage: 35 Degree Cooler Weight: 110 Price: $0.00 Quantity: 22 ------------------------------ ID: 86546 Description: SWEET POTATOES, P/L Storage: 55 Degree Cooler Weight: 240 Price: $0.00 Quantity: 6 ------------------------------ ID: 36446 Description: PINEAPPLE, FRESH, P/L Storage: 55 Degree Cooler Weight: 560 Price: $0.00 Quantity: 20 I did this with these: class myRecord(object): id = "" description = "" storage = "" weight = "" price = "" quantity = "" def _init_(self, id, description, storage, weight, price, quantity): self.id = id self.description = description self.storage = storage self.weight = weight self.price = price self.quantity = quantity class myInvoice(object): number = "" date = "" close_date = "" amount = "" def _init_(self, number, date, close_date, amount, formatted_records_list = None): self.number = number self.date = date self.close_date = close_date self.amount = amount if formatted_records_list is None: self.formatted_records_list = [] else: self.formatted_records_list = formatted_records_list I assigned values to each attribute from html elements like this (I'll just use the "number" attribute as an example) invoice_number_list = [] invoice_number_list = browser.find_elements_by_class_name("tranid") i = 0 for invoice_link in invoice_link_list: #invoice links are basically urls to each invoice invoice = myInvoice() invoice.number = invoice_number_list[i].get_attribut…
linked to: http://stackoverflow.com/q/44813122
type: Question
has answer: http://stackoverflow.com/a/51677593
has title: Python: How do I store and retrieve dynamic data in a namedtuple to write to a csv? Should I just use object attributes instead?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: namedtuple
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/comment/90505415
has text: `\s` means whitespace character. `\S` means non-whitespace character.
comment on: http://stackoverflow.com/a/51772978
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51736677
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: randomly select from dictionary of a dictionary in python
has comment: http://stackoverflow.com/comment/90443772
upvote count: 1
downvote count: 1
type: Question
has body: I have defined dictionary of dictionary of the form: my_dict = { "my_key1": {"key_1": value_1, "key_2": value_2}, "my_key2": {"key_1": value_1, "key_2": value_2, "key_3": value_3}, "my_key3": {"key_1": value_1, "key_2": value_2, "key_3": value_3, , "key_4": value_4}, "my_key4": {"key_1": value_1, "key_2": value_2} } I want to randomly select one "value" for each my_key. I tried below which didn't work: for key in my_dict: # randomly select from the sub-dictionary rand = random.sample(list(param[key]), 1) # get value at that randomVal net[key] = param[key][rand] Is there any other way to randomly select the values for each key. Thanks in advance!
score: 0
has answer: http://stackoverflow.com/a/51736695
answer count: 1
has comment: http://stackoverflow.com/comment/90434278
favorite count: 0

http://stackoverflow.com/a/51783126
type: AcceptedAnswer
has body: Here I tried this using replace, time.sleep and extend and I have just modified your code only: import requests from bs4 import BeautifulSoup url = 'https://www.wunderground.com/weather/us/ca/montara' def scrap_weather(url): page = requests.get(url) page.text soup = BeautifulSoup(page.text, 'html.parser') #read wind speed montara_wSpeed = [] montara_wSpeed_elem = soup.find_all(class_='wind-speed') for item in montara_wSpeed_elem: montara_wSpeed.append(item.text.replace("\n","")) # read wind direction montara_wCompass = [] montara_wCompass_elem = soup.find_all(class_='wind-compass') for item in montara_wCompass_elem: montara_wCompass.append(item.text.replace("\n","")) #read wind station montara_station = [] montara_station_elem = soup.find_all(class_='station-nav') for item in montara_station_elem: montara_station.append(item.text.replace("\n"," ")) #create dataframe montara_array = [] for station, windCompass, windSpeed in zip(montara_station, montara_wCompass, montara_wSpeed): montara_array.append({'Station': station, 'Wind Direction': windCompass, 'Wind Speed': windSpeed}) return montara_array n_times = 3 #df_new = pd.DataFrame(columns = ["Station", "Wind Direction", "Wind Speed"]) for i in range(n_times): montara_array = scrap_weather(url) if i == 0: data = montara_array else: montara_array.extend(data) print(montara_array) time.sleep(600) data = pd.DataFrame(montara_array)
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51782044
upvote count: 1
answers question: http://stackoverflow.com/q/51782044

http://stackoverflow.com/comment/90265202
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51650460
has text: It goes into infinite loop.

http://stackoverflow.com/comment/90436476
comment on: http://stackoverflow.com/q/51738043
score: 0
type: Comment
type: QuestionComment
has text: You want to delete tags or show the values in the tag?

http://stackoverflow.com/a/51692306
has comment: http://stackoverflow.com/comment/90346638
has comment: http://stackoverflow.com/comment/90346176
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51692286
has body: You can use a simple for loop like this for k,v in fruits.items(): print(k, v) Output apple 100 banana 2 mango 42 To print in descending order: for k,v in sorted(fruits.items(), key=lambda x: x[1], reverse=True): print(k,v) Output: apple 100 mango 42 banana 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90346310
has comment: http://stackoverflow.com/comment/90346221
score: 4
has comment: http://stackoverflow.com/comment/90346152

http://stackoverflow.com/q/51695453
tagged with: python
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51759272
has title: Dynamically generate list of protobuf rpc commands in python
has answer: http://stackoverflow.com/a/51758532
tagged with: grpc
score: 1
type: Question
has body: Could you give me advice, how could one get list of possible grpc calls (and objects using in calling) in python? More precisely, say I have a protobuf: service MyService { rpc Command1(Command1Request) returns (Command1Response); rpc Command2(Command2Request) returns (Command2Response); ... rpc CommandX(CommandXRequest) returns (CommandXResponse); } message Command1Request { uint64 param1 = 2; } What I want is to generate protobuf using console utility. I have argparse and want to be able to dynamically generate list of commands for my utility: my_utility --Command1 --param1 &lt;value&gt; my_utility --Command2 --param2 &lt;value&gt; ... Right now I use dir() method to get list of objects and because of this have fixed the special naming convention for my protobuf: If I have "Command2Response" my object for call is "Command2Request" and method for invoke request is "Command2". Are there more correct method to get list of possible calls (naming convention too prone to human errors)?
upvote count: 1
has answer: http://stackoverflow.com/a/51777033
favorite count: 0
tagged with: protocol-buffers
answer count: 3

http://stackoverflow.com/a/51726821
downvote count: 0
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51725616
answers question: http://stackoverflow.com/q/51725616
has body: You are missing the the position of the 'Value' within each group. We can create it with groupby.cumcount df.set_index( ['group_id', df.groupby('group_id').cumcount() + 1] ).Value.unstack().add_prefix('Value_').reset_index() group_id Value_1 Value_2 Value_3 0 1 23 28 32 1 12 35 23 42
type: AcceptedAnswer

http://stackoverflow.com/q/51644576
score: 2
tagged with: flask-restful
duplicate of: http://stackoverflow.com/q/45274152
type: Question
downvote count: 0
tagged with: flask-sqlalchemy
linked to: http://stackoverflow.com/q/45274152
has title: flask, sqlalchemy KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
favorite count: 0
has body: I made some api system with flask-restful. Also use flask-sqlalchemy for communicate with MySQL. My code structure is here. app.py - api - __init.py - auth.py - db - __init__.py - db.py [app.py] from flask import Flask from flask_restful import Resource, Api, reqparse from api.auth import Register from db.db import db, User app = Flask(__name__) api = Api(app) db.create_all() api.add_resource(Register, '/register') if __name__ == '__main__': app.run(debug=True) [/api/auth.py] from flask_restful import Resource, reqparse import jwt from db.db import User, db parser = reqparse.RequestParser() class Register(Resource): def post(self): parser.add_argument('userid') parser.add_argument('userpw') args = parser.parse_args() if args['userid'] is not None and args['userpw'] is not None: user = User( userid=args['userid'], userpw=args['userpw'] ) db.session.add(user) db.session.commit() return {'status':'true', 'result':'register success'} else: return {'status':'false', 'result':'register fail'} [/db/db.py] from flask_sqlalchemy import SQLAlchemy from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://id:pw@localhost/db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class User(db.Model): no = db.Column(db.Integer, primary_key=True) userid = db.Column(db.String(30), unique=True, nullable=False) userpw = db.Column(db.String(30), nullable=False) is_admin = db.Column(db.Boolean, default=False) When I connect to /register with userid and userpw parameter, it throw error. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_…
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http
tags question: http://stackoverflow.com/q/51784825
tags question: http://stackoverflow.com/q/51653660
tags question: http://stackoverflow.com/q/51660709
tags question: http://stackoverflow.com/q/51778965
tag name: http
tags question: http://stackoverflow.com/q/51740232
tags question: http://stackoverflow.com/q/51657562
tags question: http://stackoverflow.com/q/51726923
type: Tag
tags question: http://stackoverflow.com/q/51668057
tags question: http://stackoverflow.com/q/51682341
tags question: http://stackoverflow.com/q/51677248

http://stackoverflow.com/comment/90394383
has text: Thank you David, I tried the exact code given in the documentation (https://mpi4py.scipy.org/docs/usrman/tutorial.html). But yes, now I'm gonna make four "requests" and "wait" them all post all sends and receives. Any suggestion on how can I gather and scatter the dictionary. Do I need to define the datatype? Or can I simply write **if rank == 0: data = comm.gather(data, root=0)**
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51714108

http://stackoverflow.com/comment/90407837
type: AnswerComment
comment on: http://stackoverflow.com/a/51723482
type: Comment
has text: Yea thank you that removed all the code error now when I run it i get driver.switch_to_window(driver.window_handles[1]) IndexError: list index out of range
score: 0

http://stackoverflow.com/q/51776454
favorite count: 0
answer count: 5
tagged with: python
upvote count: 4
type: AnsweredQuestion
has title: Replace multiple substrings of Pandas Series at once
possible better answer: http://stackoverflow.com/a/51776490
accepted answer: http://stackoverflow.com/a/51776576
has body: I have a Pandas Series of golf scores with multiple substring replacements I would like to make simultaneously: Replace '+' with '' (i.e. nothing) Replace 'E' with '0' In a dictionary, I suppose this would look like: reps = {'+' : '', 'E' : '0'} I have tried pandas.Series.str.replace, but that only seems to accept one argument. What I've done so far is this: series = series.str.replace('+', '') series = series.str.replace('E', '0') This works, but is obviously poor form. How can I do this in one line, with any number of edits?
has answer: http://stackoverflow.com/a/51777134
type: Question
has answer: http://stackoverflow.com/a/51776523
has answer: http://stackoverflow.com/a/51776576
score: 4
tagged with: series
tagged with: replace
has answer: http://stackoverflow.com/a/51776560
tagged with: pandas
has answer: http://stackoverflow.com/a/51776490
downvote count: 0
tagged with: string

http://stackoverflow.com/comment/90589572
has text: @ibarrond: Sure, if needs be
comment on: http://stackoverflow.com/q/51785355
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51673970
tagged with: latex
tagged with: python
has title: matplotlibrc and latex package setup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51674262
upvote count: 1
type: Question
tagged with: configuration
score: 1
tagged with: matplotlib
has body: How do I set latex package options in python? I am trying to setup siunitx. I don't understand how to set options. This also applies to the matplotlibrc directly. The following does not work. import matplotlib as mpl mpl.rc('text', usetex=True) mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single,range-phrase={-}]{siunitx}' ## using the following instead of the previous line works... # mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single]{siunitx},\sisetup{range-phrase={-}}' import numpy as np import matplotlib.pyplot as plt x=np.linspace(1,100,1) y=x fig=plt.figure() ax=fig.add_subplot(111) ax.plot(x,y,label=r'\SIrange{0}{1}{\metre\per\second}') ax.legend(loc=0) Since the code snippet works, I would suggest that it is due to the use of the comma. I tried \, or ',' without luck. I tried it on Mac in a jupyter notebook. In the default matplotlibrc it says #text.latex.preamble : ## IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES ## AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP ## IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO. ## preamble is a comma separated list of LaTeX statements ## that are included in the LaTeX document preamble. ## An example: ## text.latex.preamble : \usepackage{bm},\usepackage{euler} ## The following packages are always loaded with usetex, so ## beware of package collisions: color, geometry, graphicx, ## type1cm, textcomp. Adobe Postscript (PSSNFS) font packages ## may also be loaded, depending on your font settings Unfortunately I cannot find any information on the proper usage of this option besides what is specified in the comments... Any ideas?
answer count: 1
downvote count: 0
tagged with: configuration-files
favorite count: 0

http://stackoverflow.com/q/51701383
answer count: 2
possible better answer: http://stackoverflow.com/a/51701822
has answer: http://stackoverflow.com/a/51701684
accepted answer: http://stackoverflow.com/a/51701684
tagged with: multiple-columns
has title: Apply a function across multiple Columns in Pandas
tagged with: python
tagged with: list
has body: I have the following pandas dataframe df= SlNo A B C D1 D2 D3 1 1 2 3 21 32 32 2 2 1 3 21 22 33 1 1 2 3 21 32 32 2 2 1 3 21 22 33 1 1 2 3 21 32 32 2 2 1 3 21 22 33 1 1 2 3 21 32 32 2 2 1 3 21 22 33 Here D1, D2, D3 represent dependent variables and A, B,C the causal variables. The following is the output expected SlNo A B C D1 D2 D3 RD1 RD2 RD3 1 1 2 3 21 32 32 25 23 21 2 2 1 3 21 22 33 23 24 27 1 1 2 3 21 32 32 23 21 26 2 2 1 3 21 22 33 25 27 21 1 1 2 3 21 32 32 24 22 21 2 2 1 3 21 22 33 24 23 26 1 1 2 3 21 32 32 25 26 28 2 2 1 3 21 22 33 21 25 26 RD1, RD2, RD3 refer to three columns generated by randomforest algorithm. from sklearn.ensmeble import RandomForestClassifier Y=df[D1] X=df[A, B,C] clf = RandomForestClassifier(n_jobs=2, random_state=0) clf.fit(X, Y) df[RD1]=clf.fit(X, Y) Since I have many columns, is it possible to apply this function across multiple columns- D1, D2, D3 simultaneously and generate columnns RD1, RD2, RD3.
has answer: http://stackoverflow.com/a/51701822
type: Question
type: AnsweredQuestion
tagged with: apply
score: 0

http://stackoverflow.com/comment/90379233
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51708658
has text: Thanks, was a perfect answer, very helpful!! You also helped me in the movement of the cars so thank you very much :)
type: AnswerComment

http://stackoverflow.com/comment/90493419
has text: i will edit the code with the other code parts.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51754074

http://stackoverflow.com/comment/90376790
score: 0
type: AnswerComment
has text: then just use the 3rd line from my example where i create an variable output, that should work for you
type: Comment
comment on: http://stackoverflow.com/a/51707448

http://stackoverflow.com/comment/90472728
type: QuestionComment
has text: It will generally tell you what the syntax errors are as well.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51756613

http://stackoverflow.com/comment/90553719
type: QuestionComment
comment on: http://stackoverflow.com/q/51797957
has text: I fixed the variable in my Post. Ofc it was named wrong. The issue stands: using "quit()" and "exit()" wont stop the code from writing into the file! Thats a behaviour I would not expect!
score: 0
type: Comment

http://stackoverflow.com/a/51771905
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51771812
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51771812
has comment: http://stackoverflow.com/comment/90521576
has body: A note about the following solution: You have overlapping conditions in your requirements, for example, it is possible for V2 to not be null, but also for V1 to start with QS or 1111 (which occurs in row 3), so you will need to set up your np.select in the order that you want to prioritize those conditions. Using np.select: c1 = df.V1.isnull() &amp; df.V2.isnull() c2 = df.V2.notnull() c3 = df.V1.str.contains(r'^QS|^1111').fillna(False) df.assign(V3=np.select([c1, c2, c3], ['UNLISTED', 'LISTED', 'UNLISTED'], 'LISTED')) Output: id V1 V2 V3 0 1 NaN NaN UNLISTED 1 2 QSINTSTK NaN UNLISTED 2 3 1111GHGKJKIUH 122354H LISTED 3 4 FGHKLIH 123456K LISTED 4 5 FDUL12 237899M LISTED 5 6 VHKIOY3 784236A LISTED 6 7 NaN NaN UNLISTED

http://stackoverflow.com/q/51783267
type: Question
tagged with: numpy
tagged with: dataframe
has title: Getting previous row based using conditional shift
has answer: http://stackoverflow.com/a/51783318
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I am converting an XML into a dataframe which looks something this: I want the page number tag which is in the pageflag column to be copied for all the text boxes in that page which in this case would be pageflag value in row 1 copied into row 9,10 and 11 For this purpose i am using Dataframe.shift using a condition something like this: df['pageflag'] = np.where(df['pageflag']==0,df['pageflag'].shift(1),df['pageflag']) It should be based on this condition so as to avoid the shift for rows which already have a value like in this case it is row 13 where a new page attribute is present. The issue i am facing is that the shift occurs only for one row after the page number tag which in my case is row 9.row 10 and 11 will still have the value zero which is not what i was expecting. This can be achieved using a for loop as below: for i in range(1, len(df)): if df['pageflag'][i] == 0: df['pageflag'][i] = df['pageflag'][i - 1] else: df['pageflag'][i] = df['pageflag'][i] but this is something i want to avoid due to performance issues for large dataframes. Any suggestions on how this can be achieved in the most efficient way?
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/comment/90420568
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51729908
has text: well now its File "/home/antonp/workspace/odoo-9.0/openerp/osv/fields.py", line 362, in _symbol_set_float result = __builtin__.float(x or 0.0) ValueError: invalid literal for float(): 1,000.000

http://stackoverflow.com/q/51784680
upvote count: 4
downvote count: 0
score: 4
has title: How to iterate through a folder of images and print images inline in Jupyter notebook with Python 3.6
has answer: http://stackoverflow.com/a/51784821
answer count: 3
has body: My following code iterates through a list of files &amp; prints each image "inline" in a Jupyter Notebook with the filename. from IPython.display import Image, display listOfImageNames = ["0/IMG_1118.JPG","0/IMG_1179.JPG"] for imageName in listOfImageNames: display(Image(filename=imageName)) print(imageName) However, I want to achieve the same output, but iterate through a folder of images, without having to reference each image file in the code. I have been battling with this one- can anyone point me in the right direction?
favorite count: 0
tagged with: jupyter-notebook
tagged with: python
has answer: http://stackoverflow.com/a/51785001
accepted answer: http://stackoverflow.com/a/51784821
has answer: http://stackoverflow.com/a/69101247
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51785001
tagged with: loops
tagged with: image
type: Question

http://stackoverflow.com/comment/90410430
comment on: http://stackoverflow.com/a/51725105
score: 2
type: AnswerComment
type: Comment
has text: `''` and `'^'` are exactly equivalent.

http://stackoverflow.com/comment/90474735
has text: @ Ajax1234 this is my notebook, I attached the error messages I am getting now: https://drive.google.com/open?id=1WS72xVIEN4M1xXmpxiR6pl0oAfKwxdFs
comment on: http://stackoverflow.com/a/51757323
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51707152
accepted answer of: http://stackoverflow.com/q/51707002
score: 0
type: AcceptedAnswer
type: Answer
has body: You can reshape: import tensorflow as tf D3 = tf.constant([ [[1,2],[3,4]] , [[1,2],[3,4]] ]) D2 = tf.reshape(D3, shape=(4,2)) with tf.Session() as sess: print(D2.eval()) gives [[1 2] [3 4] [1 2] [3 4]] which corresponds to your numpy example. Alternatively, you can split, then concat: D3_split = tf.split(D3, axis=-1, num_or_size_splits=2) D2_bis = tf.squeeze(tf.concat(D3_split, axis=0))
answers question: http://stackoverflow.com/q/51707002

http://stackoverflow.com/q/51653495
has body: I want to display dropdown choices for certain fields. I have a model workorder and i created a model form. I created a file choices.py and defined the created choices in the model and also at forms.py but I don't know the html code to display the choices. I'm a beginner so would appreciate any help. This is my code: The field I'm trying to make dropdowns is WO_Type_ID. models.py from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models from multiselectfield import MultiSelectField from MMS.choices import * class Workorder(models.Model): WO_ID = models.BigIntegerField(primary_key=True) WO_DateDefWO = models.DateField() WO_DateSched = models.DateField(blank=True, null=True) WO_DateFinished = models.DateField(blank=True, null=True) WO_ST_ID_Sign = models.BigIntegerField(blank=True, null=True) WO_Status_ID = models.BigIntegerField(blank=True, null=True) WO_Type_ID = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) WO_Comments = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ID = models.BigIntegerField(blank=True, null=True) WO_Nav_Kons_ID = models.CharField(max_length=12, blank=True, null=True) WO_Nav_Name = models.CharField(max_length=254, blank=True, null=True) WO_Nav_CustAdr = models.CharField(max_length=254, blank=True, null=True) WO_Nav_Debt = models.FloatField(blank=True, null=True) WO_Nav_PropCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_DepCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_PhoneNo = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ReasonCompl = models.CharField(max_length=254, blank=True, null=True) WO_NightShift = models.BooleanField(default=False) WO_Priority = models.BigIntegerField(blank=True, null=True) WO_RE_ID = models.BigIntegerField(blank=True, null=True) WO_MapUrl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.WO_ID views.py from django.…
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51654159
upvote count: 1
type: Question
type: AnsweredQuestion
has title: Dropdown list html code
tagged with: django-models
has answer: http://stackoverflow.com/a/51654159
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51699083
tagged with: text
type: AnsweredQuestion
has body: Okay, so I have this text file: hello there hello print hello there print lolol this is what I want to do in Python(down below in pseudo-code): when print statement found: print next five letters(not including space); This is the result I want: &gt;&gt;&gt;[hello, lolol] How do I solve this problem in python?
tagged with: file
type: Question
has answer: http://stackoverflow.com/a/51699144
tagged with: substring
score: 0
answer count: 2
has title: How to find all the substrings in a .txt file in Python
possible better answer: http://stackoverflow.com/a/51699144
has comment: http://stackoverflow.com/comment/90359694
has comment: http://stackoverflow.com/comment/90359640
has answer: http://stackoverflow.com/a/51699145
accepted answer: http://stackoverflow.com/a/51699145
tagged with: python

http://stackoverflow.com/comment/90482317
type: AnswerComment
has text: yeah I did now it says it cannot import choice from random
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51761390

http://stackoverflow.com/q/51790721
has comment: http://stackoverflow.com/comment/90545216
favorite count: 0
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90715157
upvote count: 1
tagged with: python
has body: I followed (sentdex's Youtube video) to create a TensorFlow program and it worked well. I started to tweak some parameters(converting all float32 to float 16 to try to make it faster) in it and got errors. So I tried to debug it with Pycharm. Then I discovered that during debug, even if I was pausing on one line and there was no other process running at the same time, python2.7 keeps occupying more and more memory until it hits 100% and my computer freezes. Is it that TensorFlow should not be debugged this way? Or is it that something else is wrong? import tensorflow as tf import time import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) n_node_hl1 = 500 n_node_hl2 = 500 n_node_hl3 = 500 n_classes = 10 batch_size = 100 x = tf.placeholder(tf.float16, [None, 784]) y = tf.placeholder(tf.float16) def neural_network_model(data): hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,, n_node_hl1], dtype=tf.float16)), 'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))} hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl1, n_node_hl2], dtype=tf.float16)), 'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))} hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl2, n_node_hl3], dtype=tf.float16)), 'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))} output_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl3, n_classes], dtype=tf.float16)), 'bias': tf.Variable(tf.random_normal([n_classes], dtype=tf.float16))} l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['bias']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['bias']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['bias']) l3 = tf.nn.relu(l3) output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['bias']) return output …
linked to: http://stackoverflow.com/q/51167542
answer count: 0
score: 1
tagged with: tensorflow
type: Question
tagged with: debugging
has title: Why does pycharm occupies more and more memory while debugging a TensorFlow program?
has comment: http://stackoverflow.com/comment/90539458
downvote count: 0

http://stackoverflow.com/a/51679252
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51679027
has body: I don't actually think this is something that's necessary to explicitly check -- just write your code as normal, and constantly run mypy against it. If you end up accidentally introducing an inconsistency while refactoring some code, mypy will inform you about those mismatches. So, if you have code that does metric_doubler(my_mean, something) and change the definition of Metric without also changing my_mean, mypy will complain about that function call. (This is one of the benefits of static typing! If everything is typed, you can refactor more fearlessly since your tooling can detect mistakes and mismatches for you -- you often don't need to put in any extra work beyond adding types.) If you want to make absolutely sure everything matches, you could perhaps add a few extra unit tests. E.g. maybe add a unit test that looks like: def test_my_mean() -&gt; None: assert metric_doubler(my_mean, something) == something_else Then, run mypy against both your full codebase and your tests. Or even more simply: def expects_metric(x: Metric) -&gt; None: pass def test_my_mean() -&gt; None: expect_metric(my_mean) I think the first form (where you bundle a runtime check along with static checks) is more useful though.
score: 1

http://stackoverflow.com/comment/90487630
type: QuestionComment
has text: Try checking out [string templates](https://docs.python.org/3/library/string.html#template-strings). They're incredibly useful for getting input such as customer information.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51764409

http://stackoverflow.com/q/51765035
linked to: http://stackoverflow.com/q/49936101
answer count: 1
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
tagged with: python-3.x
has body: I'm using Django REST throttling to block the user after 5 login attempts. I'm using the code from this post to block the user. Now I want to add a feature where an admin can reset blocked users, meaning to remove a blocked user from the blocked list. How can I remove the user from Django Blocked list? Thanks In advance
type: Question
has answer: http://stackoverflow.com/a/53151867
tagged with: django
has title: How to remove user from Django Blocked list (User blocked by Django throttle)?
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/53151867

http://stackoverflow.com/comment/90266715
comment on: http://stackoverflow.com/a/51650623
type: Comment
score: 0
has text: I am using python 2.7 , I am getting this error AttributeError: 'module' object has no attribute 'quote'
type: AnswerComment

http://stackoverflow.com/comment/90356439
type: Comment
has text: I got it working, again thank you for the response I look forward to use the knowledge I gained from your version in the future. It's not so much of a hack job anymore haha
comment on: http://stackoverflow.com/a/51681397
score: 0
type: AnswerComment

http://stackoverflow.com/q/51716904
tagged with: variable-assignment
tagged with: python
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1228299
has comment: http://stackoverflow.com/comment/90424586
has body: As a starting programmer I am currently working on a hangman project, in which the given letters must return every time. Therefore I would like to work with a list that returns with the by the player given letters. However, this gives me the following issue: File "Hangman.py", line 65, in &lt;module&gt; word_blank[i] = guess TypeError: 'str' object does not support item assignment This is for the following part of my code: while game_on == 'yes': answer = select_word(selection) if answer != 'error123': word_blank = answer_form(answer) break # start guessing letters count = 1 guesses = [] while count &lt;= 10: print(f'\n\nYour guess count:\t{count}') print(f'Your guesses:\t\t{guesses}') guess = input('Guess a letter: ').lower() count += 1 guesses.append(guess) for i in range(0, len(answer)): if answer[i] == guess: word_blank[i] = guess break print(' '.join(word_blank)) print('\n\nGame over..') With answer form being: def answer_form(answer): word_blank = [] word_blank.extend(answer) for i in range(0, len(word_blank)): word_blank[i] = '_' return(' '.join(word_blank)) I have checked various answers on Stack Overflow already, but unfortunately I cannot relate these well to my personal code. I felt the solution in this link came close, but unfortunately it has been without results. How should I improve my code to get rid of the error, while being able to stay within the loop to add all the guessed letters to word_blank[i]?
has title: String object does not support item assignment
downvote count: 1
linked to: http://stackoverflow.com/q/10631473
has answer: http://stackoverflow.com/a/51732507
linked to: http://stackoverflow.com/q/8056130
score: -1
type: Question
has comment: http://stackoverflow.com/comment/90424531
upvote count: 0
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/90395034
has comment: http://stackoverflow.com/comment/90395029

http://stackoverflow.com/q/51657853
downvote count: 0
score: 4
favorite count: 0
tagged with: pandas
has title: Search entire excel sheet with Pandas for word(s)
type: UnansweredQuestion
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/51658019
linked to: http://stackoverflow.com/q/26640129
has body: I am trying to essentially replicate the Find function (control-f) in Python with Pandas. I want to search and entire sheet (all rows and columns) to see if any of the cells on the sheet contain a word and then print out the row in which the word was found. I'd like to do this across multiple sheets as well. I've imported the sheet: pdTestDataframe = pd.read_excel(TestFile, sheet_name="Sheet Name", keep_default_na= False, na_values=[""]) And tried to create a list of columns that I could index into the values of all of the cells but it's still excluding many of the cells in the sheet. The attempted code is below. columnsList = [] for i, data in enumerate(pdTestDataframe.columns): columnList.append(pdTestDataframe.columns[i]) for j, data1 in enumerate(pdTestDataframe.index): print(pdTestDataframe[columnList[i]][j]) I want to make sure that no matter the formatting of the excel sheet, all cells with data inside can be searched for the word(s). Would love any help I can get!
type: Question
upvote count: 4
answer count: 1

http://stackoverflow.com/q/51781785
tagged with: python
answer count: 0
tagged with: pytest
has comment: http://stackoverflow.com/comment/90527691
score: 1
has title: How can I write this in a different way so that the fixture is not called always?
upvote count: 1
has comment: http://stackoverflow.com/comment/90525484
type: Question
has comment: http://stackoverflow.com/comment/90525644
has body: My test suite has a fixture shared by all tests. @pytest.fixture(scope="session") def foo_fixture(): data = get_data() if not data: pytest.fail('ERROR: Could not get data', pytrace=False) Then I have a lot of tests which basically boil down to: def test_foo(foo_fixture): assert something, pytest.fail('ERROR: ...', pytrace=False) def test_bar(foo_fixture): assert something, pytest.fail('ERROR: ...', pytrace=False) The issue I'm seeing is that whenever get_data() returns nothing, the fixture is called by every test. Why do I know this? Because the output is: ____________________________________________________________________ ERROR at setup of test_foo ____________________________________________________________________ ERROR: Could not get data ____________________________________________________________________ ERROR at setup of test_bar____________________________________________________________________ ERROR: Could not get data As you can see, I'm setting the fixture with scope="session", so it should run only once. I think the problem here is the pytest.fail. I guess it's ending the session, so that's why the fixture is called all the times. So, how could I write this in a different way so that the fixture is called only once? When get_data() actually returns something, I can notice the fixture is running only once due to tests duration. But as I said, when there is no data, it runs for every test, and the problem is that get_data() does many requests to different APIs, so I want to run it just once for lowering tests duration.
downvote count: 0
has comment: http://stackoverflow.com/comment/90528735
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90531500
type: UnansweredQuestion

http://stackoverflow.com/comment/90348530
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51693532
has text: @jpmc26 Sorry =)
score: 0

python-2.7
tags question: http://stackoverflow.com/q/51678854
tags question: http://stackoverflow.com/q/51720348
tags question: http://stackoverflow.com/q/51783628
tags question: http://stackoverflow.com/q/51699162
tags question: http://stackoverflow.com/q/51746147
tags question: http://stackoverflow.com/q/51737205
tags question: http://stackoverflow.com/q/51753343
tags question: http://stackoverflow.com/q/51666361
tags question: http://stackoverflow.com/q/51750762
tags question: http://stackoverflow.com/q/51771588
tags question: http://stackoverflow.com/q/51770972
tags question: http://stackoverflow.com/q/51673938
tags question: http://stackoverflow.com/q/51740310
tags question: http://stackoverflow.com/q/51751847
tags question: http://stackoverflow.com/q/51705067
tags question: http://stackoverflow.com/q/51737396
tags question: http://stackoverflow.com/q/51713340
tags question: http://stackoverflow.com/q/51655361
tags question: http://stackoverflow.com/q/51734041
tags question: http://stackoverflow.com/q/51678021
tags question: http://stackoverflow.com/q/51731426
tags question: http://stackoverflow.com/q/51704073
tags question: http://stackoverflow.com/q/51757366
tags question: http://stackoverflow.com/q/51657638
tags question: http://stackoverflow.com/q/51725481
tags question: http://stackoverflow.com/q/51774634
tags question: http://stackoverflow.com/q/51659879
tags question: http://stackoverflow.com/q/51675577
tags question: http://stackoverflow.com/q/51652269
tags question: http://stackoverflow.com/q/51688998
tags question: http://stackoverflow.com/q/51685377
tags question: http://stackoverflow.com/q/51756641
tags question: http://stackoverflow.com/q/51747854
tags question: http://stackoverflow.com/q/51692736
tags question: http://stackoverflow.com/q/51689127
tags question: http://stackoverflow.com/q/51787922
tags question: http://stackoverflow.com/q/51752073
tags question: http://stackoverflow.com/q/51758674
tags question: http://stackoverflow.com/q/51710854
tags question: http://stackoverflow.com/q/51771831
tags question: http://stackoverflow.com/q/51674782
tags question: http://stackoverflow.com/q/51646924
tags question: http://stackoverflow.com/q/51645940
tags question: http://stackoverflow.com/q/51784198
tags question: http://stackoverflow.com/q/51779199
tags question: http://stackoverflow.com/q/51764757
tags question: http://stackoverflow.com/q/51703568
tags question: http://stackoverflow.com/q/51650109
tags question: http://stackoverflow.com/q/51761404
tags question: http://stackoverflow.com/q/51725602
tags question: http://stackoverflow.com/q/51741536
tags question: http://stackoverflow.com/q/51770268
tags question: http://stackoverflow.com/q/51723451
tags question: http://stackoverflow.com/q/51750492
tags question: http://stackoverflow.com/q/51780097
tags question: http://stackoverflow.com/q/51695492
tags question: http://stackoverflow.com/q/51758697
tags question: http://stackoverflow.com/q/51765974
tags question: http://stackoverflow.com/q/51746255
tags question: http://stackoverflow.com/q/51783883
tags question: http://stackoverflow.com/q/51646558
tags question: http://stackoverflow.com/q/51732824
tags question: http://stackoverflow.com/q/51730186
tags question: http://stackoverflow.com/q/51655172
tags question: http://stackoverflow.com/q/51768009
tags question: http://stackoverflow.com/q/51719838
tags question: http://stackoverflow.com/q/51780284
tags question: http://stackoverflow.com/q/51709572
tags question: http://stackoverflow.com/q/51774047
tags question: http://stackoverflow.com/q/51788074
tags question: http://stackoverflow.com/q/51675067
tags question: http://stackoverflow.com/q/51665571
tags question: http://stackoverflow.com/q/51710667
tags question: http://stackoverflow.com/q/51763141
tags question: http://stackoverflow.com/q/51773088
tags question: http://stackoverflow.com/q/51648785
tags question: http://stackoverflow.com/q/51738813
tags question: http://stackoverflow.com/q/51712256
tags question: http://stackoverflow.com/q/51769239
tags question: http://stackoverflow.com/q/51757619

http://stackoverflow.com/q/51758674
possible better answer: http://stackoverflow.com/a/51758836
has comment: http://stackoverflow.com/comment/90476791
has comment: http://stackoverflow.com/comment/90510346
has answer: http://stackoverflow.com/a/51758836
tagged with: python
has answer: http://stackoverflow.com/a/51775985
has comment: http://stackoverflow.com/comment/90477052
has comment: http://stackoverflow.com/comment/90510351
downvote count: 1
type: AnsweredQuestion
has body: How to traverse through dictionary by summing up the values of the keys until it reaches 50 and then write those keys to files. For example: fruits={'mangoes':10,'banana':20,'orange':20,'grapes':40,'apple':10,'strawberry':20,'cherry':30} The output should be multiple bags with batch of "maximum 50" fruits. In this example: bag1: mangoes, banana, orange bag2: grapes, apple bag3: strawberry, cherry
accepted answer: http://stackoverflow.com/a/51775985
score: -1
type: Question
tagged with: python-2.7
answer count: 2
has title: Traverse dictionary keys by summing up values
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90476804

http://stackoverflow.com/q/51789864
has title: Twitter Streaming - Find Top 10 trending topics | PySpark
tagged with: pyspark
has body: Am doing a project to find top 10 trending topics or hashtags on Twitter. Am creating a class with the code below: class TweetsListener(StreamListener): def __init__(self, csocket): self.client_socket = csocket def on_data(self, data): try: msg = json.loads( data ) print(msg['user']['screen_name'].encode('utf-8')) return True except BaseException as e: print("Error on_data: %s" % str(e)) return True def on_error(self, status): print(status) return True Below is the code for sending data: def sendData(c_socket): auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) twitter_stream = Stream(auth, TweetsListener(c_socket)) twitter_stream.filter(track=['india'] Here twitter_stream.filter is filtering messages with tag India. I want to get all the messages from Twitter. In short, I do not want a filter to be applied. Is there a way to do the same? Any help appreciated. - P.S : Novice in Spark streaming and PySpark
score: 0
tagged with: apache-spark
answer count: 1
favorite count: 0
tagged with: python
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52107791
accepted answer: http://stackoverflow.com/a/52107791
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/90447009
has text: Thats `filter(variable__startswith='_A')`.
comment on: http://stackoverflow.com/q/51743530
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51701529
score: 0
type: Answer
has body: Try this pattern: +(\d+(\.\d+)?) +. Explanation: pattern will match number preceeded and followed by one or more spaces (+). It will match numbers with optional decimal part ((\.\d+)?), which will become second capturing group in a match (but you won't need it anyway). In every match, first capturing group \1 will be your number. Demo
answers question: http://stackoverflow.com/q/51701290

http://stackoverflow.com/comment/90492505
comment on: http://stackoverflow.com/a/51758999
score: 0
type: Comment
has text: I now got it working, thanks! Is it now possible to also communicate with the RPi via Bluetooth (RPi and Smartphone) or would that use the serial port which is already being used by the Arduino / RPi communication?
type: AnswerComment

http://stackoverflow.com/a/51789220
has comment: http://stackoverflow.com/comment/90545708
answers question: http://stackoverflow.com/q/51774703
has comment: http://stackoverflow.com/comment/90545701
type: Answer
has body: That sounds like you do not have flask installed. You may for example pip install flask to the particular python version that you are trying to run your flask app with.
score: 0

http://stackoverflow.com/comment/90543914
type: Comment
has text: Unless you have a reason that compels you to use Theano specifically, I would strongly recommend using some other library. Theano is no longer under development.
comment on: http://stackoverflow.com/q/51791933
score: 0
type: QuestionComment

http://stackoverflow.com/q/51733620
tagged with: python
answer count: 1
tagged with: excel
has comment: http://stackoverflow.com/comment/90429068
has title: Using Python loop for next i rows in dataframe
has body: I'm a new Python user (making the shift from VBA) and am having trouble figuring out Python's loop function. I have a dataframe df, and I want to create a column of variables based on some condition being met in another column, based on a loop. Something like the below: cycle = 5 dummy = 1 for i = 1 to cycle if df["high"].iloc[i] &gt;= df["exit"].iloc[i] and df["low"].iloc[i] &lt;= df["exit"].iloc[i] then df["signal"] = dummy break elif i = cycle df["signal"] = cycle + 1 break else: dummy = dummy + 1 next i Basically trying to find in which column over the next columns up to the cycle variable are the conditions in the if statement met, and if they're never met, assign cycle + 1. So df["signal"] will be a column of numbers ranging 1 -> (cycle + 1). Also, there are some NaN values in df["exit"], not sure how that affects the loop. I've found fairly extensive documentation on row iterations on the site, I feel like this is close to where I need to get to, but can't figure out how to adapt it. Thanks for any advice! EDIT: INCLUDED DATA SAMPLE FROM EXCEL CELLS BELOW: high low EXIT test signal/(OUTPUT COLUMN) 4 3 4 1 1 2 2 2 1 1 2 3 5 0 6 4 3 1 0 5 2 5 2 0 4 5 5 1 0 3 3 1 5 0 2 5 1 5 1 1 1 1 4 0 0 EDIT 2: FURTHER CLARIFICATION AROUND SCRIPT Once the condition df["high"].iloc[i] &gt;= df["exit"].iloc[i] and df["low"].iloc[i] &lt;= df["exit"].iloc[i] is met in the loop, it should terminate for that particular instance/row. EDIT 3: EXPECTED OUTPUT The expected output is the df["signal"] column - it is the first instance in the loop where the condition df["high"].iloc[i] &gt;= df["exit"].iloc[i] and df["low"].iloc[i] &lt;= df["exit"].iloc[i] is met in any given row. The output in df["signal"] is effectively i from the loop, or the given iteration.
score: 0
has comment: http://stackoverflow.com/comment/90428737
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90428981
has comment: http://stackoverflow.com/comment/90428269
has comment: http://stackoverflow.com/comment/90429159
accepted answer: http://stackoverflow.com/a/51734938
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90427999
has comment: http://stackoverflow.com/comment/90428523
has comment: http://stackoverflow.com/comment/90428709
has comment: http://stackoverflow.com/comment/90428734
type: Question
has answer: http://stackoverflow.com/a/51734938
has comment: http://stackoverflow.com/comment/90428121
linked to: http://stackoverflow.com/q/27471215
has comment: http://stackoverflow.com/comment/90428332

http://stackoverflow.com/comment/90297375
comment on: http://stackoverflow.com/q/51646568
score: 0
type: Comment
type: QuestionComment
has text: There have been many improvements released for the Cloud Vision API over time, including optimizations to the image processing behavior. [This documentation](https://cloud.google.com/vision/docs/supported-files) describes the image types that should be supported. If some of the image types are being rejected, this is an issue that we should investigate further. Can you provide the image that is generating the error? I can already see the code, that is the other useful part to reproduce the error.

http://stackoverflow.com/q/51682521
has title: Can't fit Poisson to histogram in
answer count: 1
has comment: http://stackoverflow.com/comment/90344952
has comment: http://stackoverflow.com/comment/90354366
has comment: http://stackoverflow.com/comment/90344929
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90356384
has comment: http://stackoverflow.com/comment/90340040
has comment: http://stackoverflow.com/comment/90329010
tagged with: distribution
has comment: http://stackoverflow.com/comment/90357043
has comment: http://stackoverflow.com/comment/90340964
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/90328806
has comment: http://stackoverflow.com/comment/90345077
has comment: http://stackoverflow.com/comment/90355393
has comment: http://stackoverflow.com/comment/90339540
tagged with: poisson
has answer: http://stackoverflow.com/a/51687553
has comment: http://stackoverflow.com/comment/90329034
score: 0
has body: I've looked at a bunch of examples on here and tried using snippets of other codes, but they're not working for me. I have 4 data sets, but I'll include just one here. My professor told me that the data appeared to be Poisson distributed, so I am trying to fit a Poisson to a histogram of the data. Here is my code: ######## Poisson fit ######## import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.special import factorial data = data59[4] entries,bin_edges,patches = plt.hist(data59[4],60,[1,10],normed=True) bin_middles = 0.5*(bin_edges[1:]+bin_edges[:-1]) def poisson(k, lamb): return np.exp(-lamb)*(lamb**k)/factorial(k) popt,pcov = curve_fit(poisson,bin_middles,entries) x = np.linspace(1,10,100) plt.plot(x,poisson(x,*popt)) plt.show() I tried plotting other distributions on top of the histogram like normal and Rayleigh using scipy.stats instead of curve_fit. Those kind of worked only because they have a scale parameter, which scipy.stats.poisson doesn't. The distribution for this comes out looking exactly the same as the curve_fit. I'm not sure how to resolve this issue. Perhaps the data is not even Poisson distributed! Thanks for helping!! Update: The data is IceCube data from the TXS 0506+056 blazar. I used SkyDrive to get a URL for the file. I hope it works. The first column is the modified Julian day and the last column is the log of the energy proxy. I am using the last column. I have null and alternative hypotheses surrounding this data and am using maximum likelihood estimation (from a certain distribution, Poisson in my first case) to analyze the data. Also, here is where I got the data: https://icecube.wisc.edu/science/data/TXS0506_point_source
has comment: http://stackoverflow.com/comment/90355126

http://stackoverflow.com/comment/90501242
type: QuestionComment
type: Comment
score: 1
has text: Please post your code as text, not an image
comment on: http://stackoverflow.com/q/51771182

http://stackoverflow.com/comment/90478920
type: QuestionComment
has text: label_list[0].shape is: (2,).
comment on: http://stackoverflow.com/q/51755160
score: 0
type: Comment

http://stackoverflow.com/comment/90354855
comment on: http://stackoverflow.com/q/51669362
score: 0
type: Comment
type: QuestionComment
has text: Created a python issue. See https://bugs.python.org/issue34338

http://stackoverflow.com/comment/90524052
has text: When I add in `def handle_focus_in(_): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='black') def handle_focus_out(_): full_name_entry.delete(0, tk.END) full_name_entry.config(fg='grey') full_name_entry.insert(0, "Example: Joe Bloggs") def handle_enter(txt): print(full_name_entry.get()) handle_focus_out('dummy')` I get `/inventory_collector2.py", line 233 def handle_focus_in(_): ^ IndentationError: unexpected indent`
type: Comment
comment on: http://stackoverflow.com/a/51781808
score: 0
type: AnswerComment

http://stackoverflow.com/a/54937479
has body: askopenfilename doesn't work in windows from tkinter import * #from tkFileDialog import askopenfilename import tkinter.filedialog def callback(): name= tkinter.filedialog.askopenfilenames() print (name) errmsg = 'Error!' Button(text='File Open', command=callback).pack(fill=X) mainloop()
score: -1
upvote count: 0
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/51662441

http://stackoverflow.com/a/51772883
has comment: http://stackoverflow.com/comment/90506216
has body: # let big_dict be the big list you start with output_dict = {} for key, value in big_dict.items(): # break the list into two lists, for those with third value greater # and those with third value lesser/equal higher_tuples = [i for i in value if i[2] &gt; i[0]] lower_tuples = [i for i in value if i[2] &lt;= i[0]] # Get the values from that list with high_closest = min(higher_tuples, key=lambda x: x[2] - x[0]) low_closest = min(lower_tuples, key=lambda x: x[0] - x[2]) # bind them into an output output_duct[key] = [high_closest, low_closest] If you wanted you could bind it all together in one really big one-liner: output_dict = {key: [min([i for i in value if i[2] &gt; i[0]], key=lambda a: a[2] - a[0]), min([j for j in value if j[0] &lt;= j[2]], key=lambda b: b[0] - b[2])] for key, value in big_dict.items()}
type: Answer
has comment: http://stackoverflow.com/comment/90504596
score: 1
answers question: http://stackoverflow.com/q/51772724
upvote count: 1
has comment: http://stackoverflow.com/comment/90504625
downvote count: 0

http://stackoverflow.com/a/51709810
has body: Assuming you're on *nix-like system: just run pkill python in a new terminal to kill all python processes of your user. You can run: ps ax to find the exact process you want to kill then kill -9 &lt;the PID of your process&gt; To start a new tty you can press ctrl + F4 then log in If you're on windows: ctrl+alt+del to the task manager then seek your python process and kill it
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51709371
downvote count: 0

http://stackoverflow.com/q/51793808
has comment: http://stackoverflow.com/comment/90546273
possible better answer: http://stackoverflow.com/a/51794138
favorite count: 0
has body: i have the folowwing network graph: import networkx as nx net = nx.Graph() node_list = ["Gur","Qing","Samantha","Jorge","Lakshmi","Jack","John","Jill"] edge_list = [("Gur","Qing",{"relation":"work"}), ("Gur","Jorge", {"relation":"family"}), ("Samantha","Qing", {"relation":"family"}), ("Jack","Qing", {"relation":"work"}), ("Jorge","Lakshmi", {"relation":"work"}), ("Jorge","Samantha",{"relation":"family"}), ("Samantha","John", {"relation":"family"}), ("Lakshmi","Jack", {"relation":"family"}), ("Jack","Jill", {"relation":"charity"}), ("Jill","John",{"relation":"family"})] net.add_nodes_from(node_list) net.add_edges_from(edge_list) I want to build a function that given a network, a node name, and a relationship type, returns a list of the people to which the given person is directly connected. This is the function i got so far: def get_relations(graph,node,relationship): if relationship == 'charity': charity = [ (v) for (u,v,d) in net.edges( data = True) if d["relation"]=="charity"] return list(set(charity)) else: if relationship == 'work': work = [ (v) for (u,v,d) in net.edges( data = True) if d["relation"]=="work"] return list(set(work)) else: if relationship == 'family': family = [(v) for (u,v,d) in net.edges( data = True) if d["relation"]=="family"] return list(set(family)) else: return None calling the function like this: get_connections(net, 'John', 'family') yields this output: ['Gur', 'Samantha', 'John', 'Lakshmi'] This is not what i need though, i would like it to return only those people which are directly connected to John, or whatever the node is, with a direct path, not indirect ones. Calling the function in the same way should yield this as the correct output: ['John', 'Jill', 'Samantha', 'Qing', 'Jorge', 'Gur'] Code attempt: def get_relations(graph,node,relationship): if relationship not in {'charity', 'work', 'family'}: return None relation_net = nx.Graph([(u,v,d) for (u, v, d) in net.edges( data = True) if d["relation"] == relationship]) relation_subnet…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90546317
has answer: http://stackoverflow.com/a/51794138
accepted answer: http://stackoverflow.com/a/51830985
tagged with: python
has comment: http://stackoverflow.com/comment/90613939
tagged with: network-analysis
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90606104
has comment: http://stackoverflow.com/comment/90546575
has comment: http://stackoverflow.com/comment/90549651
downvote count: 1
type: Question
has title: Getting direct edge connections in a network graph
tagged with: networkx
has comment: http://stackoverflow.com/comment/90546121
tagged with: graph
has comment: http://stackoverflow.com/comment/90549642
upvote count: 0
has answer: http://stackoverflow.com/a/51848580
has comment: http://stackoverflow.com/comment/90545527
has answer: http://stackoverflow.com/a/51830985
has comment: http://stackoverflow.com/comment/90546126
has comment: http://stackoverflow.com/comment/90545568
has comment: http://stackoverflow.com/comment/90546280
score: -1
has comment: http://stackoverflow.com/comment/90545912
has comment: http://stackoverflow.com/comment/90546203
answer count: 3
has comment: http://stackoverflow.com/comment/90545810
has comment: http://stackoverflow.com/comment/90545990

http://stackoverflow.com/comment/90262378
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51649467
has text: it worked fine. Thank you very much!
type: Comment

http://stackoverflow.com/q/51736793
has body: What I need the code to do: Copy all rows under Columns A - D from 'NewData.xlsx' and update all rows under columns A - D in a copy of 'template.xlsx' called 'updated.xlsx'. What the code actually does: It (successfully!) creates a new template sheet called 'NEW_DATA' in an updated template file called 'updated.xlsx' and writes the data.... ALL IN ONE CELL. (I need to transfer a large quantity of GPS data into an existing table for work - in case anyone is curious why I am doing this.) Unlike previous questions I've read, I do not want to modify the number of columns or rows when updating the data, I do not want to paste the data into a new tab, I do not want to copy the whole worksheet or xlsx file and I don't want to append the data below existing data. import openpyxl import pandas as pd # create variable df containing updated data in excel DataAsXlsx = r'C:\Users\...\NewData.xlsx' xl_workbook = pd.ExcelFile(DataAsXlsx) # Load the excel workbook df = xl_workbook.parse("Sheet") # Parse the sheet into a dataframe #Reads template xlsx, creates template sheet 'NEW_DATA' template = openpyxl.load_workbook(r'C:\Users\...\template.xlsx') template.sheetnames sheet1 = template.worksheets[0] sheet1.title = 'NEW_DATA' sheet1 = template['NEW_DATA'] #^^^everything above this line works^^^ #Code below attempts to copy rows AND columns from NewData.xlsx and paste to sheet 'NEW_DATA' in updated.xlsx for row in range(1, sheet1.max_row+1): cell = sheet1.cell(row=row, column=1) if cell.value is not None: cell.value = str(df) #This pastes ALL DATA into ColA of sheet 'NEW_DATA' in updated.xlsx template.save('updated.xlsx') Here is what NewData.xlsx looks like in Excel: For the purposes of debugging, template.xlsx can be any existing excel file. I've already read : Update rows and column using openpyxl from python and it helped with iterating over the template file BUT it uses hard coded data "(c)" and this logic does not transfer to what I need. I've read almost every question on here…
linked to: http://stackoverflow.com/q/51739488
has comment: http://stackoverflow.com/comment/90463131
upvote count: 2
has title: Python Copy specific rows and columns and update existing template file
tagged with: pandas
has answer: http://stackoverflow.com/a/51741025
answer count: 1
accepted answer: http://stackoverflow.com/a/51741025
linked to: http://stackoverflow.com/q/49848360
favorite count: 0
has comment: http://stackoverflow.com/comment/90438374
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: openpyxl
tagged with: excel
type: Question

http://stackoverflow.com/q/51790447
answer count: 3
has answer: http://stackoverflow.com/a/57925800
has answer: http://stackoverflow.com/a/51849458
tagged with: python
tagged with: python-3.x
has body: I installed the ROS package for Crazyflie, I wanted to run a simple script but when I type sudo python3 execute_trajectory.py , it gives me an error of no module named rospy. This is the package: https://github.com/whoenig/crazyflie_ros and the file is in crazyflie_demo/scripts. Also I'm using Ubuntu 16.04 and ROS Kinect and I tried to run a Python3 script without ROS and everything works well. This is my CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(crazyflie_demo) ## Find catkin macros and libraries ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) ## is used, also find other catkin packages find_package(catkin REQUIRED COMPONENTS roscpp ) ## System dependencies are found with CMake's conventions # find_package(Boost REQUIRED COMPONENTS system) ## Uncomment this if the package has a setup.py. This macro ensures ## modules and global scripts declared therein get installed ## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html # catkin_python_setup() ################################################ ## Declare ROS messages, services and actions ## ################################################ ## To declare and build messages, services or actions from within this ## package, follow these steps: ## * Let MSG_DEP_SET be the set of packages whose message types you use in ## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...). ## * In the file package.xml: ## * add a build_depend and a run_depend tag for each package in MSG_DEP_SET ## * If MSG_DEP_SET isn't empty the following dependencies might have been ## pulled in transitively but can be declared for certainty nonetheless: ## * add a build_depend tag for "message_generation" ## * add a run_depend tag for "message_runtime" ## * In this file (CMakeLists.txt): ## * add "message_generation" and every package in MSG_DEP_SET to ## find_package(catkin REQUIRED COMPONENTS ...) ## * add "message_runtime" and every package in MSG_DEP_SET to ## catkin_packag…
has answer: http://stackoverflow.com/a/51793665
has comment: http://stackoverflow.com/comment/96147619
upvote count: 7
has title: ImportError: No module named 'rospy'
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51849458
score: 7
has comment: http://stackoverflow.com/comment/90539541
tagged with: crazyflie
tagged with: ros
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/57925800
tagged with: rospy

http://stackoverflow.com/q/51710087
possible better answer: http://stackoverflow.com/a/51712978
score: 1
has comment: http://stackoverflow.com/comment/90381918
has comment: http://stackoverflow.com/comment/90381390
has answer: http://stackoverflow.com/a/51712978
downvote count: 1
has title: Find all lowercase words in a sentence
type: Question
has comment: http://stackoverflow.com/comment/90381473
has answer: http://stackoverflow.com/a/51710237
has comment: http://stackoverflow.com/comment/90381511
answer count: 3
has comment: http://stackoverflow.com/comment/90381469
accepted answer: http://stackoverflow.com/a/51710237
has comment: http://stackoverflow.com/comment/90381540
has comment: http://stackoverflow.com/comment/90432372
has comment: http://stackoverflow.com/comment/90381449
has comment: http://stackoverflow.com/comment/90381588
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51710280
has body: I have to to find all lowercase words in a sentence using Python. I've thought about using regular expression as follows: import re re.findall(r'\b[^A-Z()\s\d]+\b', 'A word, TWO words') It works except for the case in which I have, for instance, Aword. How can I solve it? In general, the regex should match the following cases: Aword --&gt; output: word A word --&gt; output: word A word word --&gt; output [word, word] A(word) AND A pers --&gt; output [word, pers] AwordWOrd --&gt; output [word, rd]
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90381488
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90381894

plot
tags question: http://stackoverflow.com/q/51672643
tags question: http://stackoverflow.com/q/51719201
tags question: http://stackoverflow.com/q/51794943
tags question: http://stackoverflow.com/q/51685807
tags question: http://stackoverflow.com/q/51712916
tags question: http://stackoverflow.com/q/51700295
tags question: http://stackoverflow.com/q/51685200
tags question: http://stackoverflow.com/q/51733677
tags question: http://stackoverflow.com/q/51690775
tags question: http://stackoverflow.com/q/51761032
tag name: plot
tags question: http://stackoverflow.com/q/51665438
tags question: http://stackoverflow.com/q/51741963
tags question: http://stackoverflow.com/q/51678219
tags question: http://stackoverflow.com/q/51759859
tags question: http://stackoverflow.com/q/51721918
tags question: http://stackoverflow.com/q/51690690
tags question: http://stackoverflow.com/q/51675927
tags question: http://stackoverflow.com/q/51738372
tags question: http://stackoverflow.com/q/51754469
tags question: http://stackoverflow.com/q/51660998
tags question: http://stackoverflow.com/q/51784529
tags question: http://stackoverflow.com/q/51688755
tags question: http://stackoverflow.com/q/51794904
tags question: http://stackoverflow.com/q/51726188
tags question: http://stackoverflow.com/q/51734780
tags question: http://stackoverflow.com/q/51747539
tags question: http://stackoverflow.com/q/51695911
tags question: http://stackoverflow.com/q/51751297
type: Tag
tags question: http://stackoverflow.com/q/51778168
tags question: http://stackoverflow.com/q/51646249
tags question: http://stackoverflow.com/q/51736740
tags question: http://stackoverflow.com/q/51653965
tags question: http://stackoverflow.com/q/51705314
tags question: http://stackoverflow.com/q/51717199
tags question: http://stackoverflow.com/q/51667240
tags question: http://stackoverflow.com/q/51683771
tags question: http://stackoverflow.com/q/51672938
tags question: http://stackoverflow.com/q/51768756
tags question: http://stackoverflow.com/q/51780513

http://stackoverflow.com/a/51720465
score: 1
upvote count: 1
has body: You can simply use a try-excep expression in order to find out whether your name exist in the dictionary or not. If it exist there you can then return all the values of the respective value: def get_nested_item(tree, check_on): try: sub_dict = tree[check_on] except KeyError: print("No result") return else: return sub_dict.values() Also note that about checking the existence of your name in dictionary what you're ding here is a membership checking at following line: if check_con in fi_name: Which will not check for equality but checks if check_con appears within the dictionary keys. However if this is what you want you have to loop over your items and find the intended one. But also note that this may have multiple answers or in other words there may be multiple keys matching your criteria which contradicts with the whole purpose of using a dictionary. Demo: In [11]: get_nested_item(tree, "George") Out[11]: dict_values([{'Mickey'}]) In [12]: get_nested_item(tree, "Luke") Out[12]: dict_values([{'The Chancellor'}]) In [13]: get_nested_item(tree, "Sarah") No result
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51720345
has comment: http://stackoverflow.com/comment/90401881

scikit-learn
tags question: http://stackoverflow.com/q/51677314
tags question: http://stackoverflow.com/q/51793647
tags question: http://stackoverflow.com/q/51649746
tags question: http://stackoverflow.com/q/51761031
tags question: http://stackoverflow.com/q/51660001
tags question: http://stackoverflow.com/q/51772935
tags question: http://stackoverflow.com/q/51735011
tags question: http://stackoverflow.com/q/51648253
tags question: http://stackoverflow.com/q/51663071
tags question: http://stackoverflow.com/q/51694076
tags question: http://stackoverflow.com/q/51668808
tags question: http://stackoverflow.com/q/51785048
tags question: http://stackoverflow.com/q/51671058
tags question: http://stackoverflow.com/q/51766963
tags question: http://stackoverflow.com/q/51758480
tags question: http://stackoverflow.com/q/51797306
tags question: http://stackoverflow.com/q/51659383
tags question: http://stackoverflow.com/q/51720720
tags question: http://stackoverflow.com/q/51678388
tags question: http://stackoverflow.com/q/51697502
tags question: http://stackoverflow.com/q/51655597
tags question: http://stackoverflow.com/q/51718734
tags question: http://stackoverflow.com/q/51730559
tags question: http://stackoverflow.com/q/51704532
tags question: http://stackoverflow.com/q/51712106
tags question: http://stackoverflow.com/q/51677828
tags question: http://stackoverflow.com/q/51755742
tags question: http://stackoverflow.com/q/51651266
tags question: http://stackoverflow.com/q/51694637
tags question: http://stackoverflow.com/q/51709377
tags question: http://stackoverflow.com/q/51733399
tags question: http://stackoverflow.com/q/51722840
tags question: http://stackoverflow.com/q/51703661
tags question: http://stackoverflow.com/q/51770274
tags question: http://stackoverflow.com/q/51794928
tags question: http://stackoverflow.com/q/51681972
tags question: http://stackoverflow.com/q/51765234
tags question: http://stackoverflow.com/q/51698624
tags question: http://stackoverflow.com/q/51722280
tags question: http://stackoverflow.com/q/51779042
tags question: http://stackoverflow.com/q/51775903
tags question: http://stackoverflow.com/q/51691259
tags question: http://stackoverflow.com/q/51762514
tags question: http://stackoverflow.com/q/51758409
tags question: http://stackoverflow.com/q/51682470
tags question: http://stackoverflow.com/q/51707968
tags question: http://stackoverflow.com/q/51795062
tags question: http://stackoverflow.com/q/51654280
tags question: http://stackoverflow.com/q/51652093
tags question: http://stackoverflow.com/q/51690364
tags question: http://stackoverflow.com/q/51662473
tags question: http://stackoverflow.com/q/51755095
tags question: http://stackoverflow.com/q/51753852
tags question: http://stackoverflow.com/q/51791188
tag name: scikit-learn
tags question: http://stackoverflow.com/q/51645273
tags question: http://stackoverflow.com/q/51695322
tags question: http://stackoverflow.com/q/51708715
type: Tag
tags question: http://stackoverflow.com/q/51741605
tags question: http://stackoverflow.com/q/51773231
tags question: http://stackoverflow.com/q/51685322
tags question: http://stackoverflow.com/q/51695769
tags question: http://stackoverflow.com/q/51665654
tags question: http://stackoverflow.com/q/51752222
tags question: http://stackoverflow.com/q/51717846
tags question: http://stackoverflow.com/q/51689145
tags question: http://stackoverflow.com/q/51717943
tags question: http://stackoverflow.com/q/51765325
tags question: http://stackoverflow.com/q/51681572
tags question: http://stackoverflow.com/q/51696150
tags question: http://stackoverflow.com/q/51798540
tags question: http://stackoverflow.com/q/51688568
tags question: http://stackoverflow.com/q/51729524
tags question: http://stackoverflow.com/q/51674401
tags question: http://stackoverflow.com/q/51726062
tags question: http://stackoverflow.com/q/51685584
tags question: http://stackoverflow.com/q/51715923
tags question: http://stackoverflow.com/q/51798708
tags question: http://stackoverflow.com/q/51776145

http://stackoverflow.com/comment/90561665
comment on: http://stackoverflow.com/q/51775918
type: Comment
type: QuestionComment
score: 0
has text: Things that I tried subprocess.call(['hdfs', 'dfs', '-copyFromLocal', '/u/data/abc.csv', 'hdfs://user/hive/warehouse/class.db/abc.csv'], shell=True) Error : No alias specified and no default alias found. 1 2nd try: shutil.copy('/user/adam/data//abc.csv', 'hdfs://user/hive/warehouse/class.db/class/abc.csv')

http://stackoverflow.com/comment/90557449
type: Comment
comment on: http://stackoverflow.com/q/51789823
type: QuestionComment
score: 0
has text: You think that defaultdicts are faster than numpy arrays? because i thought numpys are written in c or something.. you mean how many times I add data to my array? with some real data it would be: 320 * 120000 = 38.4 million times..

http://stackoverflow.com/comment/90494363
comment on: http://stackoverflow.com/a/51767886
has text: `return [0 if x[0] != 'U' else 1 for x in p]`
score: 0
type: AnswerComment
type: Comment

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/51693427

http://stackoverflow.com/q/51794615
score: 0
has comment: http://stackoverflow.com/comment/90547433
has title: python regular expression end of match in different conditions
has comment: http://stackoverflow.com/comment/90546860
has comment: http://stackoverflow.com/comment/90547055
has body: Currently, I am using two regular expressions to get data from string, like as below: match = re.match('(\d+(\.\d+)*)(.*)[Xx](.*)(\d+(\.\d+)*)|', '12 x 13.5|1 - 3 acres') The number I want to get is 12 and 13.5. In other situation, the string don't have |, it is just empty after the number. I use this to match: match = re.match('(\d+(\.\d+)*)(.*)[Xx](.*)(\d+(\.\d+)*)$', '12 x 13.5') What I want is to use one regular expression to match both of two conditions, how should I do? update: I get number by: match.group(1) match.group(4)+match.group(5)
has comment: http://stackoverflow.com/comment/90547467
has comment: http://stackoverflow.com/comment/90546970
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90547067
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90546844
has comment: http://stackoverflow.com/comment/90547660

http://stackoverflow.com/a/59018580
has body: Don't need to use kwargs To create a typewriter effect, just follow the code below. def anything(str): for letter in str: sys.stdout.write(letter) sys.stdout.flush() time.sleep(0.5) anything("That is my sample text.") The code I've written gives a 0.5 second waiting time between every letter in the string, and only takes six lines of code.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51641456

http://stackoverflow.com/comment/90326546
has text: Thank you for this edit. Even though it worked, I didn't exactly understand all of the terms you used, (like what AJAX is, or how you got that api, or even what an api is, haha) but I'm still very new to this and that tells me where to focus my learning. Any recommendations of where I can learn some of these terms and practices?
type: Comment
comment on: http://stackoverflow.com/a/51663111
score: 0
type: AnswerComment

http://stackoverflow.com/q/51794156
tagged with: python
type: AnsweredQuestion
has title: How can I "upload and deploy" to Elastic Beanstalk from the command line?
upvote count: 2
has answer: http://stackoverflow.com/a/51794418
type: Question
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51794418
tagged with: amazon-web-services
tagged with: amazon-elastic-beanstalk
favorite count: 0
has body: To start, apologies if this is a foolish question -- I'm relatively new to AWS and none of my googling has been fruitful thus far. I have a server that I deploy through elastic beanstalk. Currently I do it relatively manually (docker build, push, zip folder and click upload and deploy and the elastic beanstalk page with the zip I just made. I'm writing a script to simplify this. Everything seems to be working, but I can't figure out how to do the upload and deploy step programmatically. Just to be very explicit, this is the button I'm referring to: Is there a way I can do this bit using python? Any help is appreciated.

http://stackoverflow.com/q/51720044
type: Question
type: AnsweredQuestion
tagged with: falconframework
has title: How to pass variable from middleware to resource in falcon?
possible better answer: http://stackoverflow.com/a/71309436
answer count: 2
has answer: http://stackoverflow.com/a/71309436
downvote count: 0
has answer: http://stackoverflow.com/a/52459016
favorite count: 0
accepted answer: http://stackoverflow.com/a/52459016
has body: I'm using Falcon, I need pass variable from middleware to resource, how can I do that? main.py app = falcon.API(middleware=[ AuthMiddleware() ]) app.add_route('/', Resource()) and auth class AuthMiddleware(object): def process_request(self, req, resp): self.vvv = True and resource class Resource(object): def __init__(self): self.vvv = False def on_get(self, req, resp): logging.info(self.vvv) #vvv is always False why self.vvv is always false? I have changed it in middleware to true.
tagged with: python
upvote count: 6
score: 6

http://stackoverflow.com/q/51681200
score: 1
type: Question
has comment: http://stackoverflow.com/comment/107025104
downvote count: 0
has comment: http://stackoverflow.com/comment/90325743
favorite count: 0
has comment: http://stackoverflow.com/comment/90325548
has comment: http://stackoverflow.com/comment/90325798
has body: I am using Selenium to automate some tasks, and one problem I often find is working with system panels at different resolutions. I am looking for a way to get to the buttons on a system panel, independently from the resolution. My assumption is that the panel appear always in the same position; independently from the resolution, so if I can get a way to translate the resolution coordinates, to something more absolute, I may be able to click that button, no matter the resolution. If I use percentage as way to find the coordinates, instead of pixels, would that solve my problem? Something like this: read resolution (example: 1920x1080) on 1920x1080, my button is located at points x=920 and y=180 transform the values from pixels to percentages, using val = 100*(position/resolution) for X and Y values Once I have the percentage position, if I go to a different computer that use a resolution like 1024x768, I can convert back that percentage value in a pixel value, using position = (val/100)*resolution, for X and Y values At this point, I have the values of X and Y to move the mouse to that specific point, which should be in the same general area of where the button I want to press is located. Is this feasible or is it a waste of time, since the percentage is not a feasible value? In which case, how could I work around the problem?
answer count: 0
has title: Percentage of screen size as way to find a consistent point on screen, independently from the resolution
type: UnansweredQuestion
tagged with: selenium
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90257417
has text: Is it safe to assume that each list only has one occurrence of each `'Name'`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51646529
type: Comment

http://stackoverflow.com/comment/90359897
has text: You can access the current index by `df.index`. Refer to https://stackoverflow.com/questions/18022845/pandas-index-column-title-or-name
comment on: http://stackoverflow.com/q/51699094
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51728648
favorite count: 0
accepted answer: http://stackoverflow.com/a/51820566
has title: How do masked values affect the metrics in Keras?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 7
tagged with: tensorflow
type: Question
tagged with: keras
tagged with: metrics
upvote count: 7
has body: If I look into keras metric I see that the values of y_true and y_predict are "just" compared at the end of each epoch for categorical_accuracy: def categorical_accuracy(y_true, y_pred): return K.cast(K.equal(K.argmax(y_true, axis=-1), K.argmax(y_pred, axis=-1)), K.floatx()) How are masked values handled? If I understood correctly, masking prohibits the masked values to influence the training, but it still produces predictions for the masked values. Thereby, it does, in my opinion, influence the metric. More explanation on how it influences the metric: In the padding/masking process, I set the padded/masked values in y_true to an unused class e.g. class 0. If now argmax() is looking for a max value in the one-hot encoded y_true, it will just return 0 as the total (masked) row is the same. I do not have a class 0, as it is my masking value/class, and thereby the y_pred and y_true certainly have different values creating a reduced accuracy. Is this somehow already thought of in the Keras metric and I oversaw it? Otherwise, I would have to create a custom metric or callback creating a similar metric to categorical_accuracy with the addition that all masked values are eliminated in y_pred and y_true before comparison.
answer count: 1
has answer: http://stackoverflow.com/a/51820566

http://stackoverflow.com/a/51734607
answers question: http://stackoverflow.com/q/51734545
type: Answer
score: 4
upvote count: 4
has body: 10**int(log(n, 10)) is basically 10*, such that it is the same length as n. The floor division of n by that will give us the leading digit, while the modulo % gives us the rest of the number. from math import log def digits(n): if n &lt; 0: yield '-' n = -1 * n elif n == 0: yield 0 return xp = int(log(n, 10).real) factor = 10**xp while n: yield int(n/factor) n = n % factor try: xp, old_xp = int(log(n, 10).real), xp except ValueError: for _ in range(xp): yield 0 return factor = 10**xp for _ in range(1, old_xp-xp): yield 0 for x in digits(12345): print(x) prints 1 2 3 4 5 Edit: I switched to this version, which is much less readable, but more robust. This version correctly handles negative and zero values, as well as trailing and internal 0 digits.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51734545

http://stackoverflow.com/a/51658786
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/90281250
has comment: http://stackoverflow.com/comment/90282084
type: Answer
has comment: http://stackoverflow.com/comment/90282058
downvote count: 1
answers question: http://stackoverflow.com/q/51658729
has body: One-liner using list comprehension: new_list = [x for x in original_list if (x['label'] in label_list)] which iterates over all elements of original_list, and compiles those for which (x['label'] in label_list) is true into a new list.

http://stackoverflow.com/comment/90374843
comment on: http://stackoverflow.com/q/51707077
has text: You can use cron jobs for that: https://stackoverflow.com/questions/11774925/how-to-run-a-python-file-using-cron-jobs
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51679825
score: 1
has comment: http://stackoverflow.com/comment/90323001
has body: You need to change line 10 to: with open (os.path.join(self.destdir, destination), 'w') as outfile: In your case Python looks for testdir inside GetNums first and, if it cannot find it there, it will look for this name in the module. It does not magically use tesdir from __init__. The name self stands for the instance you will create later. So in __init__ you essentially set mysinstance.testdir and later in GetNums you can access with mysinstance.testdir. self is just the placeholder for mysinstance, i.e the instance you create later. You can read the detail in the documentation.
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51679658
answers question: http://stackoverflow.com/q/51679658
has comment: http://stackoverflow.com/comment/90323149
downvote count: 0
has comment: http://stackoverflow.com/comment/90323328
type: AcceptedAnswer

http://stackoverflow.com/q/51706730
favorite count: 0
tagged with: python
downvote count: 1
has title: Tensorflow, Keras: Tensor normalization by axis
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51706980
score: -1
tagged with: tensorflow
type: Question
upvote count: 0
tagged with: keras
has body: Assume we have images Tensor A with shape (None, 200, 200, 1). where None is the batch size, and (200, 200, 1) is the image size. How to perform normalization (0 to 1) on each image (not using for iteration)? That is: A[0] = (A[0] - A[0].min()) / (A[0].max() - A[0].min()) A[1] = (A[1] - A[1].min()) / (A[1].max() - A[1].min()) ... A[n] = (A[n] - A[n].min()) / (A[n].max() - A[n].min()) if I just directly use A = (A - A.min()) / (A.max() - A.min()), it will normalize all the images by the global max and min. I wish to normalize each image with their own max and min. In other words, how to achieve a max or min operation, that results in a shape of: (None, 1, 1, 1), where each (1, 1, 1) contains the max or min of each image.
accepted answer: http://stackoverflow.com/a/51706980
answer count: 1

http://stackoverflow.com/comment/90284410
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51660389
has text: but your answer just covers a single aspect, i am facing the problem both ways meaning that when i increase the email_id's in the message["To"] section and pass just a single one in sendmail() the email goes to all in the headers section , but then why does interchanging the arguments(number of email_ids) create the same behaviour, isn't that a bit ambiguous?
type: AnswerComment

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

http://stackoverflow.com/a/58952573
score: 4
has body: Create hook-grpc.py in the hooks folder (\Lib\site - packages\PyInstaller\hooks) and put the following code. from PyInstaller.utils.hooks import collect_data_files datas = collect_data_files ( 'grpc' ) If this doesn't work, then go to \Lib\site - packages\PyInstaller\hooks and add the following code to hook-google.cloud.py file. datas += copy_metadata ( 'google-cloud-firestore' )
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/123293729
downvote count: 0
answers question: http://stackoverflow.com/q/51745571

http://stackoverflow.com/q/51758975
has title: Retrieve image from sqlite3 and display in Kivy image widget - ValueError
upvote count: 3
has body: REQUIREMENT I'm trying to retrieve an image from Database and set this image to kivy image widget, this operation throws a ValueError, unsure of the cause. Welcome any inputs. Database: Sqlite3 Table name: Users Columns: UserID, UserName, UserImage def populate_fields(self): # NEW # Code retrieves text data and display in textinput fields here. # STEP 1: RETRIEVE IMAGE connection = sqlite3.connect("demo.db") with connection: cursor = connection.cursor() cursor.execute("SELECT UserImage from Users where UserID=?",self.data_items[columns[0]]['text'] ) image = cursor.fetchone() data = io.BytesIO(image[0]) #STEP 2: SET OUTPUT TO IMAGE WIDGET self.image.source = data # ---&gt; triggers an Error ERROR TRACEBACK: self.image.source = data File "kivy\weakproxy.pyx", line 33, in kivy.weakproxy.WeakProxy.__setattr__ (kivy\weakproxy.c:1471) File "kivy\properties.pyx", line 478, in kivy.properties.Property.__set__ (kivy\properties.c:5572) File "kivy\properties.pyx", line 513, in kivy.properties.Property.set (kivy\properties.c:6352) File "kivy\properties.pyx", line 504, in kivy.properties.Property.set (kivy\properties.c:6173) File "kivy\properties.pyx", line 676, in kivy.properties.StringProperty.check (kivy\properties.c:8613) ValueError: Image.source accept only str
tagged with: image
downvote count: 0
has answer: http://stackoverflow.com/a/58509775
type: Question
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/58509775
tagged with: sqlite
tagged with: kivy
favorite count: 0
tagged with: kivy-language
has answer: http://stackoverflow.com/a/51791453
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51791453

http://stackoverflow.com/q/51740517
tagged with: selenium
tagged with: firefox-headless
type: Question
linked to: http://stackoverflow.com/q/5370762
upvote count: 2
has body: I was wondering how to run hidden Firefox window when testing a page in Selenium and came across this solution. It says that I can run Firefox in headless mode like this: from selenium import webdriver import os os.environ['MOZ_HEADLESS'] = '1' driver = webdriver.Firefox() driver.get("https://www.google.com/") driver.close() But it earned no votes whatsoever. It seems like people think it is a wrong answer. Why? Also, in official documentation I found that it can be done like this: from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.add_argument('-headless') driver = webdriver.Firefox(options=options) driver.get("https://www.google.com/") driver.close() Can someone explain the difference between the two ways?
tagged with: firefox
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90441126
has answer: http://stackoverflow.com/a/51740848
accepted answer: http://stackoverflow.com/a/51740848
tagged with: python
score: 2
type: AnsweredQuestion
has title: The right way to run Firefox in headless mode (Selenium, Python)

http://stackoverflow.com/comment/90538579
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51790470
has text: Also, what is your question? "kinda stumped me" is not a problem description. StackOverflow is not a coding, design, or tutorial service.
score: 0

http://stackoverflow.com/comment/90433839
type: QuestionComment
comment on: http://stackoverflow.com/q/51736487
has text: @Ywapom that not the information i am trying to get the infor i am interested in is on the player's profile under statistics
score: 0
type: Comment

http://stackoverflow.com/comment/90279870
comment on: http://stackoverflow.com/a/51657878
type: AnswerComment
score: 0
type: Comment
has text: Here is what the entire base.html looks as. index.html and everything else is inheriting from this file, shouldn't they also inherit context ? https://pastebin.com/KXbAQy61

http://stackoverflow.com/comment/90537916
type: AnswerComment
has text: thanks, I immediately tried thinking this was exactly what I needed but for some weird reason it only gets the text of the element and not the html. I tried it on a bunch of elements but it doesn't seem to capture the html code. Does it work on your end?
type: Comment
comment on: http://stackoverflow.com/a/51789490
score: 0

http://stackoverflow.com/q/51774703
tagged with: debian
has answer: http://stackoverflow.com/a/51789220
has comment: http://stackoverflow.com/comment/90570886
linked to: http://stackoverflow.com/q/28688306
type: Question
score: 0
tagged with: apache
answer count: 1
has title: python 3.5 Flask install on apache 2.4
has body: I have Google Cloud with Debian 9. There are python 2.7a and 3.5. 3.5 I did as default. I have apache where is PHP and I need to keep it there. I installed libapache2-mod-python configured virtual host and pure python file return me a correct result. I installed Flask framework and it throws an exception that ImportError: No module named Flask It's my first time with Flask and in general with python in web. For all examples I see mod_wsgi but I can't install it with libapache2-mod-python. My questions are: Does it's possible to run Flash with libapache2-mod-python module? If no, then does mod_wsgi has no conflict with PHP apache module? Thanks for any hints.
tagged with: flask
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51769636
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90497946
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51770105
has title: Give a variable varying value for each item in a string?
type: Question
accepted answer: http://stackoverflow.com/a/51770105
has body: So I'm making a simplified Enigma-style code where each character is changed into another, but the encoding changes after each character. What I have so far is: message = input("Message?") message = message.lower() state1 = int(input("State 1?")) code1 = [] code2 = [] for character in message: number = ord(character) + state1 if number &gt;= 123: number = number -26 code1.append(number) print (code1) for character in code1: word = chr(character) code2.append(word) print (code2) So if state1 = 1, "abc" will become "bcd", however I want state1 to increase by one for each character so that "abc" would become "bdf" (a+1=b, b+2=d, c+3=f). I'm aware that there are other (perhaps better) ways of achieving what I have so far, but this is what I best understand. Is there a way to achieve my goal this way, or do I need a different approach?

http://stackoverflow.com/q/51677462
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51677515
upvote count: 0
tagged with: cmd
favorite count: 0
has title: Process multiple files via command line
type: Question
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90318244
downvote count: 2
has body: I want to run a Python Script to process multiple images: Currently I'm using a simple command line to process a single image python script.py --input C:\Users\file1.png --output C:\Users\file1_output.png
answer count: 1
has comment: http://stackoverflow.com/comment/90318400

http://stackoverflow.com/a/51700026
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51699975
score: 1
has body: Try opening the file in binary mode - open("forMatMul_ref.f90", "rb") - it will give you raw bytes for the source code (which seems to be what it expects) rather than decoding to a string. This is probably a side-effect of them porting legacy python 2 code to run in python 3, otherwise a string object would seemingly be an appropriate representation for source code. If you are interested, this post describes what changed with strings between Python 2 and 3: https://timothybramlett.com/Strings_Bytes_and_Unicode_in_Python_2_and_3.html
type: Answer
has comment: http://stackoverflow.com/comment/90362442
upvote count: 1
has comment: http://stackoverflow.com/comment/90361511
answers question: http://stackoverflow.com/q/51699975

http://stackoverflow.com/a/51802191
score: 14
downvote count: 0
type: Answer
upvote count: 14
has body: If you're using numpy, then don't use the math module. Numpy as all of the math functions built in but they work on numpy arrays far better. We can calculate nu at all of our b, d values with the aid of a meshgrid. A meshgrid can take 2 1D arrays, and return 2 2D arrays such that every index in the arrays corresponds to a unique pair of elements from the original 1D arrays. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np b = np.arange(0.2, 3.2, 0.2) d = np.arange(0.1, 1.0, 0.1) B, D = np.meshgrid(b, d) nu = np.sqrt( 1 + (2*D*B)**2 ) / np.sqrt( (1-B**2)**2 + (2*D*B)**2) fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(B, D, nu) plt.xlabel('b') plt.ylabel('d') plt.show() This produces: Additionally, 3D plots tend to block seeing all of the data (because a spike hides things behind it). I would recommend a pcolormesh or a contourf plot. In the later case the last 6 lines become: plt.contourf(B, D, nu) plt.colorbar() plt.xlabel('b') plt.ylabel('d') plt.show() which produces:
answers question: http://stackoverflow.com/q/51765184

http://stackoverflow.com/q/51679291
has comment: http://stackoverflow.com/comment/90321835
has comment: http://stackoverflow.com/comment/90322249
score: 0
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90321861
has answer: http://stackoverflow.com/a/51679468
answer count: 1
accepted answer: http://stackoverflow.com/a/51679468
has comment: http://stackoverflow.com/comment/90322138
tagged with: python
has comment: http://stackoverflow.com/comment/90321802
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90321969
has title: Foreach loop with additional behavior for one specific iteration
has comment: http://stackoverflow.com/comment/90321807
type: Question
has body: I'm iterating over a list with a foreach loop and I want to do some additional stuff to exactly one of the x that I iterate over (specifically cryoTemp in the code below). I could add this functionality with a simple if statement in the body of the loop, but it sets off a subconscious "bad code" alarm in my head, as the if statement will be evaluated on every iteration, even though it will only evaluate to true once. Is there a smarter, perhaps more "Pythonic" way to do this? for p in self.params: &lt; get parameter p from server &gt; &lt; parse response &gt; log_in_redis_and_mysql(p, value) # log cooling rate based on cryoTemp value if p == 'cryoTemp': self.pastCryoTemps.append(value) # calculate average of queue when it fills up then remove the oldest (first) element if (len(self.pastCryoTemps) == 4): differences = [] for i in range(len(self.pastCryoTemps) - 1): differences.append(-(self.pastCryoTemps[i] - self.pastCryoTemps[i + 1])) average = sum(differences) / len(differences) log_in_redis_and_mysql('cooling_rate', average) self.pastCryoTemps.pop(0)
linked to: http://stackoverflow.com/q/2401785

http://stackoverflow.com/q/51685126
linked to: http://stackoverflow.com/q/34592172
has comment: http://stackoverflow.com/comment/90332706
has comment: http://stackoverflow.com/comment/90332319
has body: There are some cases where I get a number appended to the variable scope (even if I set reuse=True) Let's say I do something like: import tensorflow as tf with tf.Session() as session: graph = tf.Graph() with graph.as_default(): with tf.variable_scope("Foo", reuse=True): tf.placeholder(dtype=tf.float64, name="A") # Do something else here.. with tf.variable_scope("Foo", reuse=True): tf.placeholder(dtype=tf.float64, name="B") writer = tf.summary.FileWriter('/tmp/tf', graph=graph) writer.flush() Why do I see (tensorboard) two groupings (Foo, Foo_1): I would like A and B to be placed in the same grouping but still keep the two with statements separate. I think a key difference with other existing questions is that I am asking: How do I do this?
duplicate of: http://stackoverflow.com/q/34592172
has comment: http://stackoverflow.com/comment/90332758
favorite count: 0
has comment: http://stackoverflow.com/comment/90332342
has comment: http://stackoverflow.com/comment/90332669
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/90332470
has title: Variable scopes get a number appended
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90332675
has comment: http://stackoverflow.com/comment/90332685
has comment: http://stackoverflow.com/comment/90332332

http://stackoverflow.com/a/51792187
type: Answer
has body: Provided you have access to AAPT (standard android sdk built-tool), the following should give you the information. aapt dump badging myApk.apk | grep versionName Alternatively, if you don't want to use grep and you want to seek through the massive dump of data on your own, just use aapt dump badging myApk.apk and traverse the string until you find the info you're looking for. Using SDK 27.0.3, the following is the return of the above command with grep: package: name='com.example.myapk' versionCode='49' versionName='1.2.3' platformBuildVersionName='' For executing this command in python, use the subprocess module: https://docs.python.org/3/library/subprocess.html
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51790545
downvote count: 0

http://stackoverflow.com/comment/90358029
has text: Can you post a sample of your data? `df.head().to_dict()` helps
score: 0
comment on: http://stackoverflow.com/q/51698291
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51712819
tagged with: desktop
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51712856
has title: Displaying an image from Desktop Path
type: Question
tagged with: python
has body: #!/usr/bin/python from os import listdir from PIL import Image as PImage def loadImages(path): # return array of images imagesList = listdir(path) loadedImages = [] for image in imagesList: img = PImage.open(path + image) loadedImages.append(img) return loadedImages path = r"C:\Users\Aidan\Desktop\APDR_PDhh_epi5new.bmp" # your images in an array imgs = loadImages(path) for img in imgs: # you can show every image img.show() NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\Aidan\Desktop\APDR_PDhh_epi5new.bmp' Above is the error. I have the bitmap file named "APDR_PDhh_epi5new.bmp" on my desktop and I am getting an error. What am I doing wrong?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51712856
tagged with: reader
tagged with: image

http://stackoverflow.com/a/51737950
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51737866
answers question: http://stackoverflow.com/q/51737866
type: Answer
has body: You could format within your format print("Income {:&gt;8} pays Flat tax {:&gt;9} and Current tax {:&gt;9}".format('${:,d}'.format(income), '${:.2f}'.format(tax), '${:.2f}'.format(curr_tax))) Which gives Income $10,000 pays Flat tax $0.00 and Current tax $0.00 Income $50,000 pays Flat tax $780.00 and Current tax $0.00

http://stackoverflow.com/comment/90392598
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51714787
type: QuestionComment
has text: I guess a simple no that is not possible or it is possible if you use <software> with other <software> would be enough to get me started. These are too many words for a search engine but if I can get hints at what I should possibly be looking at then I can narrow my research. Its more about can I combine these things rather than why I want it.

http://stackoverflow.com/q/51788625
score: 1
has body: I wish to create an NxN numpy array where only everything above the main diagonal is filled. The way it is filled is that the main diagonal (k=0) is filled with gamma**0, the k=1 diagonal is filled with gamma**1, the k=2 diagonal is filled with gamma**2 etc... gamma = 0.9 dim = 4 M = np.zeros((dim,dim)) for i in range(dim)[::-1]: M += np.diagflat([gamma**(dim-i-1)]*(i+1),dim-i-1) print(M) This correctly gives array([[ 1. , 0.9 , 0.81 , 0.729], [ 0. , 1. , 0.9 , 0.81 ], [ 0. , 0. , 1. , 0.9 ], [ 0. , 0. , 0. , 1. ]]) I wanted to ask if there were any more simpler or elegant ways of handling this or something different. I will be handling with multidimensial arrays frequently and I wanted to be inspired by different tools and approaches.
type: Question
tagged with: numpy
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51788766
accepted answer: http://stackoverflow.com/a/51788766
favorite count: 0
tagged with: multidimensional-array
tagged with: matrix
has title: Numpy adding values to diagonals
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90322598
has text: I don't like adding code to `__init__.py`, personal preference. It can make it hard to figure out where things are due to the forwarded imports. It can be nice if you're developing an API that other python devs are going to consume just to shorten names. Other than that, i'd recommend avoiding it. It throws beginners for a loop when they do `import mypackage; mypackage.doStuff()`, and in reality `doStuff()` is 700 layers deep in a directory hierarchy instead of in the first layer as expected. They'll eventually come to you bc they cant figure out where the module actually lives on the filesys.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51679103

http://stackoverflow.com/q/51667792
has title: How to sort a text file to find anagrams in O(MN) time complexity where M is the max number of characters and N is the number of words?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/55404000
type: Question
has answer: http://stackoverflow.com/a/55404000
tagged with: sorting
tagged with: counting-sort
tagged with: radix-sort
has comment: http://stackoverflow.com/comment/90309237
upvote count: 1
answer count: 1
favorite count: 0
has body: Hi I'm new to Python and I want to find groups of anagrams in a file in linear time.Anagrams are basically two or more words which consists of the same alphabet but in different arrangements. First I read all the words into a list. Apparently, I can use radix sort to sort each word by column and the radix sort should use a stable counting sort. But I don't know exactly what my counting sort should do? Should I write a counting sort function that takes a word and sorts it by alphabetical order? Then call it in radix sort? Can someone give me a clearer idea on how to approach this problem?Any help will be appreciated thanks!

http://stackoverflow.com/comment/101120182
has text: 1 yr later, I understand; I was just naive about how writing to terminal works. Thanks.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51657549

http://stackoverflow.com/a/51650363
downvote count: 0
answers question: http://stackoverflow.com/q/51650097
accepted answer of: http://stackoverflow.com/q/51650097
score: 1
has comment: http://stackoverflow.com/comment/90264833
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90265721
has body: re.findall returns a list of strings - i.e. all matches found in the text given to it. &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall(r'Typ: (.*?);', 'Typ: foobar;') ['foobar'] To include it again at the end, you can join all the matches together: fn.write(text + ''.join(run) + "\n") If you only want one match, you can use re.search instead: &gt;&gt;&gt; re.search(r'Typ: (.*?);', 'Typ: foobar;').group(1) 'foobar' It works with your example: &gt;&gt;&gt; re.search(r'Typ: (.*?);', 'Typ: Mehrfamilienhaus;').group(1) 'Mehrfamilienhaus' But since re.search will give None if there isn't a match, you can check that you get a proper match before attempting to retrieve the group (as you do in your findall above): result = re.search(r'Typ: (.*?);', 'Typ: Mehrfamilienhaus;') run = result.group(1) if result else '0'
type: Answer

http://stackoverflow.com/comment/90393571
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51715082
has text: While I am also interested in the answer to your question, I recommend taking a look at the [solution](http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.read_csv) that dask provides for exactly this problem (i.e. reading lots of files into one DataFrame). It doesn't really support reading lots of pickle files but csv, parquet, hdf and many other file types are really easy to read in this way. `import dask.dataframe as dd; df_snsr1 = dd.read_csv(list_of_csv_files_or_path_regex); df_snsr1 = df_snsr1.compute()`

http://stackoverflow.com/a/51642627
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51640816
has body: You might want to try something like strCommand = sprintf('python speakObject.py %s', label); system(strCommand);
type: Answer
answers question: http://stackoverflow.com/q/51640816

http://stackoverflow.com/comment/90621222
score: 0
type: AnswerComment
type: Comment
has text: There are constructs where your regexp can remove too much/too little. For example, someone could use a custom tag ` regular html formatted with CSS ` and you'll begin removing there all the way to some script at the end of the document. Or with CDATA constructs, there can be a ` ` inside the script that will be ignored by the HTML parser. Then your regexp will remove too little, and you'll have script garbage in your text.
comment on: http://stackoverflow.com/a/51800448

http://stackoverflow.com/a/51778921
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51778873
type: Answer
has comment: http://stackoverflow.com/comment/90515916
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90516149
has comment: http://stackoverflow.com/comment/90515864
has comment: http://stackoverflow.com/comment/90516133
accepted answer of: http://stackoverflow.com/q/51778873
has comment: http://stackoverflow.com/comment/90515960
has body: You are missing self in the len() call in push(): def push(self, e): if len(c[self.current_stack]) + 1 &gt; self.size: ##### ^ You need: def push(self, e): if len(self.c[self.current_stack]) + 1 &gt; self.size: ##### You must have another c in the environment that you are referencing that is never being added to - so is constantly the same size. And there are a couple of similar errors in pop(), e.g.: def pop(self): if self.current_stack &gt; 0 and len(c[self.current_stack]) == 1 : ^ Note: def __repr__(): should return a str not actually print(), e.g.: def __repr__(self): return repr(self.c) With those fixes you get the expected output: defaultdict(&lt;class 'list'&gt;, {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 2: [20]})

http://stackoverflow.com/q/51782044
tagged with: dataframe
has title: Web Scraping : Updating/ adding to a dataframe using pandas
has comment: http://stackoverflow.com/comment/90521735
type: Question
answer count: 1
has body: I am creating a web scraping program using python, pandas, and BeautifulSoup. I want it to request wind information from a weather station every 10 minutes. This data is to be stored in an array containing 72 indexes (24 hours). Up to this point I have managed to create a messy dataframe with current conditions. I have 3 questions, the third question might exceed my abilities at this time. 1: How to exclude '/n' from my data while parsing? 2: How to update every 10 minutes and add to array 3: How to push/pop data from array, displaying most recent data at front of array. (I have read about push and pop, and this may be something I can research in the future.) This is the first bit of code I have personally written, so please excuse me. I have inserted my code below, and here's a link of an image displaying my output. import pandas as pd import requests from bs4 import BeautifulSoup url = 'https://www.wunderground.com/weather/us/ca/montara' page = requests.get(url) page.text soup = BeautifulSoup(page.text, 'html.parser') #read wind speed montara_wSpeed = [] montara_wSpeed_elem = soup.find_all(class_='wind-speed') for item in montara_wSpeed_elem: montara_wSpeed.append(item.text) #read wind direction montara_wCompass = [] montara_wCompass_elem = soup.find_all(class_='wind-compass') for item in montara_wCompass_elem: montara_wCompass.append(item.text) #read wind station montara_station = [] montara_station_elem = soup.find_all(class_='station-nav') for item in montara_station_elem: montara_station.append(item.text) #create dataframe montara_array = [] for station, windCompass, windSpeed in zip(montara_station, montara_wCompass, montara_wSpeed): montara_array.append({'Station': station, 'Wind Direction': windCompass, 'Wind Speed': windSpeed}) df = pd.DataFrame(montara_array) df
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/51783126
has comment: http://stackoverflow.com/comment/90540218
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51783126
has comment: http://stackoverflow.com/comment/90521755
tagged with: web-scraping
type: AnsweredQuestion

http://stackoverflow.com/q/51697672
type: AnsweredQuestion
has body: Could I please get help with converting my date and time, dataː 01/01/2012 01:00 into something like 2012-01-01 01:00:00ʔ I have tried doing datetime = [datetime.datetime(2012, 1, 1, 1, 0, 0) + datetime.timedelta(hours=i) for i in range(9)] dates=[datetime.strptime('%Y-%m-%d %H:%M:%S') for x in datetime] This returns the errorː AttributeError: 'list' object has no attribute 'strptime' My datetime's in my csv file look like thisː 01/01/2012 01:00 01/01/2012 02:00 01/01/2012 03:00 01/01/2012 04:00 01/01/2012 05:00 01/01/2012 06:00 01/01/2012 07:00 01/01/2012 08:00 01/01/2012 09:00 I believe this must be very straight forward but i can't seem to get my head around this. help with this will be appreciated
has comment: http://stackoverflow.com/comment/90356820
has answer: http://stackoverflow.com/a/51697690
answer count: 1
linked to: http://stackoverflow.com/q/2158347
score: 0
tagged with: datetime
tagged with: python
has title: How to convert timestamp (datetime.datetime(2012, 1, 1, 1, 0) into 2012-01-01 01:00:00
favorite count: 0
accepted answer: http://stackoverflow.com/a/51697690
has comment: http://stackoverflow.com/comment/90356834
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90357439
type: Question

http://stackoverflow.com/comment/90396441
type: AnswerComment
comment on: http://stackoverflow.com/a/51717550
type: Comment
has text: right, though, aren't we then averaging the averages as `counts` joined the `gb.agg()` call?
score: 0

http://stackoverflow.com/comment/90285902
has text: Upgrading code from python2 to python3 sounds like the exact usecase for the tool 2to3.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51658120

http://stackoverflow.com/a/51689392
score: 2
downvote count: 0
has body: The issue is, as noted in the comments, due to int32 limits. The proper dtype isn't being inferred, leading to the loss of information. This should be resolved with an upcoming release of fiona (which geopandas uses for reading/writing files), which will improve how int types are handled (https://github.com/Toblerity/Fiona/pull/564). In the meantime, you can use schema = gpd.io.file.infer_schema(gdf) schema['properties']['int_column'] = 'int:18' gdf.to_file('gdf.shp', schema=schema)
upvote count: 2
answers question: http://stackoverflow.com/q/51688660
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51688660
type: Answer

http://stackoverflow.com/a/67562815
has body: from django import forms from .models import Dforms class Forms(forms.ModelForm): class Meta: model = Dforms fields = &quot;__all__&quot;
score: 0
has comment: http://stackoverflow.com/comment/119419581
type: Answer
answers question: http://stackoverflow.com/q/51734479
has comment: http://stackoverflow.com/comment/119420280

http://stackoverflow.com/q/51756925
tagged with: css-selectors
upvote count: 1
has answer: http://stackoverflow.com/a/51758299
has title: How to find the href attribute of the videos on twitch through selenium and python?
downvote count: 1
favorite count: 0
tagged with: webdriverwait
has comment: http://stackoverflow.com/comment/90475441
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90474170
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51784609
accepted answer: http://stackoverflow.com/a/51784609
has comment: http://stackoverflow.com/comment/90475029
tagged with: selenium
has comment: http://stackoverflow.com/comment/90473532
type: Question
has comment: http://stackoverflow.com/comment/90511889
has body: I'm trying to find the twitch video IDs of all videos for a specific user. So for example on this page https://www.twitch.tv/dyrus/videos/all So here we have all videos linked, but its not quite so simple as to just scrape the html and find the links since they are generated dynamically it seems. So I heard about selenium and did something like this: from selenium import webdriver # Change path here obviously driver = webdriver.Chrome('C:/Users/Jason/Downloads/chromedriver') driver.get('https://www.twitch.tv/dyrus/videos/all') link_element = driver.find_elements_by_xpath("//*[@href]") for link in link_element: print(link.get_attribute('href')) driver.close() This returns me a bunch of links on the page but not the videos, they lie "deeper" I think, any input? Thanks in advance
score: 0
possible better answer: http://stackoverflow.com/a/51758299
answer count: 2

http://stackoverflow.com/a/51722158
downvote count: 0
score: 1
has body: You can align indices and then combine_first. Since this method doesn't let you specify columns, you can recover 'C' values from df1 in a separate step. # align indices df1 = df1.set_index('key') df2 = df2.set_index('key') # combine dataframes preference to df2 res = df2.combine_first(df1).astype(int) # recover C values from df1 res['C'].update(df1['C']) # elevate index to series res = res.reset_index() print(res) key A B C 0 k1 4 5 2 1 k2 1 2 3 2 k3 2 3 5 3 k4 2 3 6
upvote count: 1
answers question: http://stackoverflow.com/q/51721851
type: Answer

http://stackoverflow.com/q/51697516
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/53550801
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has title: IOPub data rate exceeded in Jupyter notebook (Version 5.4.0)
tagged with: jupyter
linked to: http://stackoverflow.com/q/43288550
tagged with: jupyter-notebook
has body: I am running into an issue where when I read a txt file, the following message is generated : IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_data_rate_limit`. Current values: NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec) NotebookApp.rate_limit_window=3.0 (secs) I tried to follow the instructions provided in this Stack Overflow post here: IOPub data rate exceeded when viewing image in Jupyter notebook However, I can't get past the first step of generating a config file via the Command Line. When I try to call Jupyter Notebook in the command line as a part of step 1, the command line doesn't recommend it. I tried calling Jupyter Notebook from within the file directory in which it sits. I confirmed it is the right directory by verifying the last modified date. Can anyone point me in the right direction? Thanks

http://stackoverflow.com/q/51752600
has body: Need to get the min and max values of each index in the sublists of a list. If my list is [[1, 2], [4, 1], [2, 2], [1, 6], [5, 3]], I do the following: xmin = min(i[0] for i in mylist) ymin = min(i[1] for i in mylist) xmax = max(i[0] for i in mylist) ymax = max(i[1] for i in mylist) # Results: xmin = 1 xmax = 5 ymin = 1 ymax = 6 While very explicit in what I am doing with those 4 lines, is there a way to get it in tuple unpack?
has comment: http://stackoverflow.com/comment/110820390
upvote count: 1
possible better answer: http://stackoverflow.com/a/51752768
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51752688
type: Question
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/4002796
has comment: http://stackoverflow.com/comment/90465311
has title: Min and Max of each index in sublists
accepted answer: http://stackoverflow.com/a/51752688
score: 1
has answer: http://stackoverflow.com/a/51752768
favorite count: 0
has comment: http://stackoverflow.com/comment/90465369

http://stackoverflow.com/comment/90415372
score: 0
type: Comment
has text: This answers the question but in practice I need to search for all the "Appendix I" in a book, so there is a lot of paragraphs, etc. between two adjacent "Appendix I"s, in which case this answer doesn't really work.
comment on: http://stackoverflow.com/a/51687376
type: AnswerComment

http://stackoverflow.com/comment/90406286
type: Comment
type: QuestionComment
has text: but having a QTableWidget on the item would no longer make it possible to use that signal.
comment on: http://stackoverflow.com/q/51722119
score: 0

http://stackoverflow.com/comment/90472933
type: AnswerComment
comment on: http://stackoverflow.com/a/51739765
type: Comment
score: 0
has text: i notice if you do not maximize the window your code will not work why is that just curious?

http://stackoverflow.com/comment/90585574
score: 0
type: Comment
type: QuestionComment
has text: @QuangHoang That worked...Awesome!! thanks again!
comment on: http://stackoverflow.com/q/51784719

http://stackoverflow.com/comment/90281917
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51658976
has text: @novawaly - Can youvadd expected output?

http://stackoverflow.com/q/51750663
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90481418
has comment: http://stackoverflow.com/comment/90498130
type: Question
has body: I have a list of html files and I'm trying to put them together into an animation in python. I've tried doing this: htims = [list_of_html_images] %matplotlib notebook import matplotlib.pyplot as plt import matplotlib.animation as animation ani = animation.ArtistAnimation(fig, htims, repeat_delay=1000) But when I try to save it, I get an error: ValueError: the output must be of type htm or html and the plt.show() command gives me nothing. Is there a good way to make animations out of HTML images in python?
downvote count: 0
has title: make animation out of html file in python
favorite count: 0
tagged with: animation
tagged with: python
has comment: http://stackoverflow.com/comment/90471454
answer count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/51666955
has comment: http://stackoverflow.com/comment/90296921
tagged with: pandas
has answer: http://stackoverflow.com/a/51668764
tagged with: python
accepted answer: http://stackoverflow.com/a/51668764
has comment: http://stackoverflow.com/comment/90296951
type: Question
type: AnsweredQuestion
has body: I'm trying to get the 15 most relevant item for each users but every functions i tried took an eternity. (more than 6 hours i shutdown it after that ...) I have 418 unique users, 3718 unique items. U2tfifd dict has as well 418 entry and there is 32645 words in tfidf_feature_names. Shape of my interactions_full_df is (40733, 3) i tried : def index_tfidf_users(user_id) : return [users for users in U2tfifd[user_id].flatten().tolist()] def get_relevant_items(user_id): return sorted(zip(tfidf_feature_names, index_tfidf_users(user_id)), key=lambda x: -x[1])[:15] def get_tfidf_token(user_id) : return [words for words, values in get_relevant_items(user_id)] then interactions_full_df["tags"] = interactions_full_df["user_id"].apply(lambda x : get_tfidf_token(x)) or def get_tfidf_token(user_id) : tags = [] v = sorted(zip(tfidf_feature_names, U2tfifd[user_id].flatten().tolist()), key=lambda x: -x[1])[:15] for words, values in v : tags.append(words) return tags or def get_tfidf_token(user_id) : v = sorted(zip(tfidf_feature_names, U2tfifd[user_id].flatten().tolist()), key=lambda x: -x[1])[:15] tags = [words for words in v] return tags U2tfifd is a dict with keys = user_id, values = an array
tagged with: list-comprehension
has title: speed up function based on list comprehension
answer count: 1
score: 0

http://stackoverflow.com/comment/90492136
comment on: http://stackoverflow.com/q/51766069
score: 0
type: Comment
type: QuestionComment
has text: `df['Terms'].replace('\s*,'',regex=True)`.

http://stackoverflow.com/comment/90444826
type: Comment
comment on: http://stackoverflow.com/a/51720650
has text: `type({"The Chancellor"}) ` and ` `type({"Luke"}) ` ` , everything shows as set ,
type: AnswerComment
score: 0

http://stackoverflow.com/q/51770942
has comment: http://stackoverflow.com/comment/90500977
upvote count: 3
has answer: http://stackoverflow.com/a/51771389
answer count: 1
has body: I'm trying to get the file path from user input. i have used the below syntax import pandas as pd path = input("Enter the path of your file:") sheetname = input("Enter the sheet name:") path_1 = ("r'"+path+"'") df1 = pd.read_excel(path_1, sheet_name = sheetname) but am getting "OSError: [Errno 22] Invalid argument" error Could someone help me out to get it done
downvote count: 1
has comment: http://stackoverflow.com/comment/90500853
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90501383
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90536334
score: 2
type: Question
has title: Getting file path from user input in Python3
has comment: http://stackoverflow.com/comment/90536013

http://stackoverflow.com/comment/125370166
type: Comment
score: 1
type: AnswerComment
has text: +1 for showing an approach using a parameterized query than the formatted string based approach. For e.g., see here about parameterized queries: https://pynative.com/python-sqlite-insert-into-table/
comment on: http://stackoverflow.com/a/56284749

http://stackoverflow.com/a/51772425
type: Answer
accepted answer of: http://stackoverflow.com/q/51772331
answers question: http://stackoverflow.com/q/51772331
score: 3
has body: As stated in the documentation: Help on built-in function readlines: readlines(hint=-1, /) method of _io.TextIOWrapper instance Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. Once you have consumed all lines, the next call to readlines will be empty. Change your function to store the result in a temporary variable: with open(os.path.join(root, file)) as fRead: lines = fRead.readlines() line_3 = lines[3] line_4 = lines[4] print line_3 print line_4
downvote count: 0
has comment: http://stackoverflow.com/comment/90503759
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/51736050
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/159118
tagged with: apache-spark-2.0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51740692
has body: I have a record which is like "_row"\n"&lt;BR&gt;Datetime:2018.06.30^ Name:ABC^ Se:4^ Machine:XXXXXXX^ InnerTrace:^ AdditionalInfo:^ &lt;ER&gt; I would want to remove everything before in each record. Is there an easy way to do this with spark dataframe import pyspark.sql.functions as f data.select(f.regexp_replace(pattern='\n&lt;BR&gt;',replacement="&lt;BR&gt;",str="row") something like this? What should the pattern be?
accepted answer: http://stackoverflow.com/a/51740692
score: 1
upvote count: 1
has title: PySpark 2 - Regex replace everything before
type: Question
tagged with: pyspark
tagged with: apache-spark
answer count: 1

http://stackoverflow.com/comment/90278020
has text: i.e. `image_generator = image_datagen.flow(imgs_train, seed=seed, batch_size=btc_s, subset='training')` `mask_generator = image_datagen.flow(imgs_mask_train, seed=seed, subset='training') train_generator = zip(image_generator, mask_generator) model.fit_generator(train_generator, steps_per_epoch=50, shuffle=True, epochs=20)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51657016
score: 0

http://stackoverflow.com/q/51713634
has title: Tkinter - loop a funcion while updating it in the GUI
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51714537
favorite count: 0
has body: How do I loop a function that displays a value in my window? So I have this function from telethon to get all the new messages from telegram: def get_message(): for message in client.iter_messages('@snoopdoggystyledogg', limit=10): msg_history = utils.get_display_name(message.sender), message.message return msg_history And I have this to display it: messages = Text(root) messages.insert(INSERT, '') messages.insert(INSERT, get_message()) messages.pack() But the problem is that the messages doesn't get updated if I'm not reopening the app.. Any idea how to make it loop and update it on my chat screen?
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/51714537
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90390304
has comment: http://stackoverflow.com/comment/90388690

http://stackoverflow.com/a/51640637
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51640610
has body: stateNames = [] for i statesAbbrv: for k, v in statesDict.iteritems(): if stateDict[k] == stateAbbrv[i]: stateNames.append(stateDict(k)) print stateNames You need to add iteritems() to make the dictionary iterable on python 2.7.
score: 0
type: Answer

http://stackoverflow.com/a/51640139
downvote count: 0
score: 1
has body: A csv.DictWriter requires a dictionary for writing. If your ent object doesn't have a to_dict() method, you will have to make one. for ent in doc.ents: if ent.label_ == 'PERSON': d = {'Character':ent.text, 'begin':ent.start_char, 'end':ent.end_char,'Label':ent.label_} cf.writerow(d)
type: Answer
answers question: http://stackoverflow.com/q/51639941
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51639941
type: AcceptedAnswer

http://stackoverflow.com/comment/90364248
type: QuestionComment
score: 1
has text: You mena `pd['url']=unique_id`?
comment on: http://stackoverflow.com/q/51701548
type: Comment

http://stackoverflow.com/a/51784073
answers question: http://stackoverflow.com/q/51783883
type: Answer
has body: It's good to try something yourself first, the ask on SO - you learn much more that way. I would try: import os from shutil import copyfile folder_path = '*folder path*' os.chdir(folder_path) for file in os.listdir(folder_path) year = file[3:7] month = file[7:9] final_path = folder_path + '/' + year + '&gt;' + month + '/' + file + .jpg' copyfile(file, final_path) Just replace the paths in ** with whatever you need. This way you slice the file name and get year and month from it (characters from 3 to 6 and 7,8), then copyfile to a path consisting of both year and month that you sliced.
score: 0

http://stackoverflow.com/a/56765286
has body: This would be easier to understand if you work with excel on java. Excel cell have properties which define them as active or inactive. If you enter a value to a cell then delete the value, the cell still remains active. max_row returns the row number of the last active cell, hence you get 10 rather than 7 even if the sheet now have data only till row 7 it may once have data till 10. Manually you can clear the cell (Editing->Clear->Clear All) for the cell in excel making it inactive again. Not sure how to do the same via code in python.
type: Answer
answers question: http://stackoverflow.com/q/51747535
score: 0

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

http://stackoverflow.com/comment/90270723
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51652641
type: Comment
has text: Well in that case you will have to elaborate more clearly what you want.

http://stackoverflow.com/comment/90447552
type: Comment
type: QuestionComment
has text: Seems to be the best way forward. Let me dig into flask_sqlalchemy group by to see if I can get it to group by date
comment on: http://stackoverflow.com/q/51743584
score: 0

http://stackoverflow.com/comment/90389904
has text: Add `flags=re.MULTILINE` because of using start of line pattern `^`.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51699242
type: Comment

http://stackoverflow.com/a/51748395
has comment: http://stackoverflow.com/comment/90458481
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/90457240
has comment: http://stackoverflow.com/comment/90457141
has comment: http://stackoverflow.com/comment/90457475
has comment: http://stackoverflow.com/comment/90457562
has comment: http://stackoverflow.com/comment/90456821
answers question: http://stackoverflow.com/q/51748201
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90457280
accepted answer of: http://stackoverflow.com/q/51748201
has comment: http://stackoverflow.com/comment/90457821
has comment: http://stackoverflow.com/comment/90457520
has comment: http://stackoverflow.com/comment/90457798
has comment: http://stackoverflow.com/comment/90458415
type: Answer
has comment: http://stackoverflow.com/comment/90456996
has comment: http://stackoverflow.com/comment/90457550
has comment: http://stackoverflow.com/comment/90458389
has body: np.where You can specify regex=False and na=False as parameters to pd.Series.str.contains so that only rows where your condition is met are updated: df['name'] = np.where(df['code'].str.contains('-CUT', regex=False, na=False), df['name'].str[:-4], df['name']) regex=False isn't strictly necessary for this criterion, but it should improve performance. na=False ensures any type which cannot be processed via str methods returns False. pd.DataFrame.loc Alternatively, you can use pd.DataFrame.loc. This seems more natural than specifying an "unchanged" series as a final argument to np.where: mask = df['code'].str.contains('-CUT', regex=False, na=False) df.loc[mask, 'name'] = df['name'].str[:-4]

http://stackoverflow.com/comment/90488588
score: 1
comment on: http://stackoverflow.com/a/51749637
type: AnswerComment
type: Comment
has text: You can transform your current for loop (`for img in img_list`) into a generator that yields images one at a time. Then you train the network with `fit_generator()` instead of with `fit()`. This way, you directly feed the images one by one to the network instead of collecting them in a `np array` first (which is not possible because of the varying sizes). For some boilerplate code on how to train an CNN with a generator, you can look [here](https://github.com/sdcubber/Keras-Sequence-boilerplate/blob/master/Keras-Sequence.ipynb).

http://stackoverflow.com/comment/90412794
comment on: http://stackoverflow.com/a/51725234
has text: I have checked that no truncation. Also tried plt.tight_layout() but same output
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90437478
has text: To my limited understanding, it is a better way in the way ZdaR has explained: for each row, you have only one column, which has multiple sub-elements. When it comes to points, this approach is more intuitive to me because the number of rows indicate number of points in that dimension. So, if you wanted to have multiple planes, you can still have (x,n,y) where n is the number of planes. So, it helps in extending things from one plane to multiple ones. I am also new to OpenCV, so I might be slightly wrong. It's better to do the reshape to make it consistent with the rest of the library.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51724120

http://stackoverflow.com/comment/90430732
comment on: http://stackoverflow.com/a/51734355
type: Comment
has text: Unsure what you mean by next line; but, you may want to look into python's escape characters like \n, which forces output to a new line. It looks like `warnings.formatwarning(message, category, filename, lineno[, line])` supports output to a newline. https://docs.python.org/2/library/warnings.html
score: 0
type: AnswerComment

http://stackoverflow.com/a/73499715
has body: The emoji.get_emoji_regexp() is outdated. If you want to remove emoji from strings, you can use emoji.replace_emoji() as shown in the examples below. import emoji def remove_emoji(string): return emoji.replace_emoji(string, '') Visit https://carpedm20.github.io/emoji/docs/api.html#emoji.replace_emoji
downvote count: 0
answers question: http://stackoverflow.com/q/51784964
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90292966
score: 0
type: Comment
type: QuestionComment
has text: Thanks for your advice. I'm pretty new here.
comment on: http://stackoverflow.com/q/51664659

http://stackoverflow.com/a/51692327
has comment: http://stackoverflow.com/comment/90346333
has comment: http://stackoverflow.com/comment/90346227
has comment: http://stackoverflow.com/comment/90346281
has comment: http://stackoverflow.com/comment/90346188
has comment: http://stackoverflow.com/comment/90366309
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51691980
has body: Approach #1 Most intutive one would be with np.add.at for those repeated indices - np.add.at(result, [-y_mapping, x_mapping], values) Approach #2 We need to perform binned summations owing to the possible repeated nature of x,y indices. Hence, another way could be to use NumPy's binned summation func : np.bincount and have an implementation like so - # Get linear index equivalents off the x and y indices into result array m,n = result.shape out_dtype = result.dtype lidx = ((-y_mapping)%m)*n + x_mapping # Get binned summations off values based on linear index as bins binned_sums = np.bincount(lidx, values, minlength=m*n) # Finally add into result array result += binned_sums.astype(result.dtype).reshape(m,n) If you are always starting off with a zeros array for result, the last step could be made more performant with - result = binned_sums.astype(out_dtype).reshape(m,n)
answers question: http://stackoverflow.com/q/51691980
has comment: http://stackoverflow.com/comment/90366431
has comment: http://stackoverflow.com/comment/90346512
has comment: http://stackoverflow.com/comment/93896045
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90366285
type: Answer
has comment: http://stackoverflow.com/comment/90368112

http://stackoverflow.com/comment/90384987
type: Comment
type: QuestionComment
has text: How did you extract the `vbaProject.bin`? Did you use `vba_extract.py`
score: 3
comment on: http://stackoverflow.com/q/51711527

http://stackoverflow.com/comment/90295753
has text: It can be a substring
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51666374

http://stackoverflow.com/comment/93373775
score: 0
type: Comment
has text: On Xubuntu 14.04.5, even after upgrading pip to v18.1 when I run the command `pip install urllib3` I get still `Requirement already satisfied: urllib3 in /usr/lib/python2.7/dist-packages (1.7.1)`. The library is Not upgraded. See my [new stackoverflow thread](https://stackoverflow.com/questions/53199623/typeerror-urlopen-got-multiple-values-for-keyword-argument-body-while-tryin). So I am still stuck with the problem.
comment on: http://stackoverflow.com/a/51707029
type: AnswerComment

http://stackoverflow.com/comment/90503646
has text: What or where is the error you are getting?
comment on: http://stackoverflow.com/q/51772361
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90375351
type: Comment
has text: thanks for reply,it's showing like Error:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51707198

http://stackoverflow.com/comment/90497129
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51769171
has text: Why not wirte a function that take a string and a time_interval as parameters, which then loops throgh all letters and prints them with a timeout?

http://stackoverflow.com/q/51700954
accepted answer: http://stackoverflow.com/a/51701012
upvote count: 12
possible better answer: http://stackoverflow.com/a/51703794
downvote count: 0
has answer: http://stackoverflow.com/a/51703794
tagged with: ajax
answer count: 3
tagged with: python
favorite count: 0
has body: I have given {% csrf_token %} inside the form. Do I have to give another {% csrf_token %} inside the AJAX $.ajax({ .......... )} ? {% csrf_token %} {{ form.as_p }} Sign up
tagged with: django
has answer: http://stackoverflow.com/a/58688307
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/51701012
tagged with: django-models
type: Question
score: 12
has title: Django csrf token for Ajax

http://stackoverflow.com/q/51699001
tagged with: python
type: AnsweredQuestion
tagged with: tokenize
possible better answer: http://stackoverflow.com/a/51713440
has answer: http://stackoverflow.com/a/51713440
has body: I am working to create a text classification code but I having problems in encoding documents using the tokenizer. 1) I started by fitting a tokenizer on my document as in here: vocabulary_size = 20000 tokenizer = Tokenizer(num_words= vocabulary_size, filters='') tokenizer.fit_on_texts(df['data']) 2) Then I wanted to check if my data is fitted correctly so I converted into sequence as in here: sequences = tokenizer.texts_to_sequences(df['data']) data = pad_sequences(sequences, maxlen= num_words) print(data) which gave me fine output. i.e. encoded words into numbers [[ 9628 1743 29 ... 161 52 250] [14948 1 70 ... 31 108 78] [ 2207 1071 155 ... 37607 37608 215] ... [ 145 74 947 ... 1 76 21] [ 95 11045 1244 ... 693 693 144] [ 11 133 61 ... 87 57 24]] Now, I wanted to convert a text into a sequence using the same method. Like this: sequences = tokenizer.texts_to_sequences("physics is nice ") text = pad_sequences(sequences, maxlen=num_words) print(text) it gave me weird output: [[ 0 0 0 0 0 0 0 0 0 394] [ 0 0 0 0 0 0 0 0 0 3136] [ 0 0 0 0 0 0 0 0 0 1383] [ 0 0 0 0 0 0 0 0 0 507] [ 0 0 0 0 0 0 0 0 0 1] [ 0 0 0 0 0 0 0 0 0 1261] [ 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 1114] [ 0 0 0 0 0 0 0 0 0 1] [ 0 0 0 0 0 0 0 0 0 1261] [ 0 0 0 0 0 0 0 0 0 753]] According to Keras documentation (Keras): texts_to_sequences(texts) Arguments: texts: list of texts to turn to sequences. Return: list of sequences (one per text input). is it not supposed to encode each word to its corresponding number? then pad the text if it shorter than 50 to 50? Where is the mistake ?
type: Question
accepted answer: http://stackoverflow.com/a/55294888
score: 9
has answer: http://stackoverflow.com/a/56584862
upvote count: 9
answer count: 6
tagged with: keras
tagged with: deep-learning
has answer: http://stackoverflow.com/a/60229349
downvote count: 0
has title: tokenizer.texts_to_sequences Keras Tokenizer gives almost all zeros
tagged with: nlp
favorite count: 0
has answer: http://stackoverflow.com/a/55294888
has answer: http://stackoverflow.com/a/61974600
has answer: http://stackoverflow.com/a/59545233

http://stackoverflow.com/comment/90426417
comment on: http://stackoverflow.com/q/51732577
type: Comment
type: QuestionComment
has text: That didnt not work, i still have multiple lines
score: 0

http://stackoverflow.com/a/51709942
answers question: http://stackoverflow.com/q/51709814
upvote count: 1
has body: The split() in your case breaks in an array of element by the space (one element of array = one word). Looping through it it the solution text = 'je ne suis pas une table' not_shortword = {'n', 'pas', 'ne'} rep = ' '.join(shortword for shortword in text.split() if len(shortword ) &gt;= 4 or shortword in not_shortword) print(rep) #returns : "ne suis pas table"
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51737763
type: Question
tagged with: python
tagged with: tkinter
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51738667
has comment: http://stackoverflow.com/comment/90436399
has body: I created a code in Python to present a Guess game of numbers between 1 and 100. I wanted to implement this game in a graphical interface, using the Tkinter module. I had an idea, I created a code using tkinter, but after that I crashed. My question is, how to "merge" the two codes that were created into one, to create this graphical interface? Tkinter part. from tkinter import * import random i = Tk() i.title('Guess Game') i.geometry("400x200") texto = Label(i, text = "Welcome to the Guess Game") texto.pack() texto = Label(i, text = "You have 10 chances to hit the number I'm thinking") texto.pack() texto = Label(i, text = "This is a value between 1 and 100. So, come on!") texto.pack() form = Entry(i, width=3) form.pack() b = Button(i, text ="Execute", fg= "green") b.pack() i.mainloop() Second part import random n = random.randrange(1, 101) nrepete = [] estado1 = 7 # início estado2 = 7 def SetStatus(tentativa): global estado2 if abs(n - palpite) == 1: estado2 = 6 # Very Fucking Hot if abs(n - palpite) == 2 or abs(n - palpite) == 3: estado2 = 5 # Very Hot if abs(n - palpite) &gt;= 4 and abs(n - palpite) &lt;= 6: estado2 = 4 # Hot if abs(n - palpite) &gt;= 7 and abs(n - palpite) &lt;= 9: estado2 = 3 # Warm if abs(n - palpite) &gt;= 10 and abs(n - palpite) &lt;= 15: estado2 = 2 # Cold if abs(n - palpite) &gt;= 16 and abs(n - palpite) &lt;= 25: estado2 = 1 # Very Cold if abs(n - palpite) &gt;= 26: estado2 = 0 # Freezing def FornecerPista(): if estado1 == 7: if estado2 == 0: print('Freezing!') if estado2 == 1: print('Very cold!') if estado2 == 2: print('Cold!') if estado2 == 3: print('Warm!') if estado2 == 4: print('Hot!') if estado2 == 5: print('Very hot!') if estado2 == 6: print('Very fucking hot!') if estado1 - estado2 == 0: if estado2 == 0: print('Seu palpite continua congelando!') if estado2 == 1: print('Seu palpite continua muito frio!') if estado2 == 2: print('Seu palpite continua frio!') if estado2 == 3: print('Seu palpite continua morno!') if estado2 == 4: print…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90436546
has title: Guessing Game - Tkinter Module
has answer: http://stackoverflow.com/a/51738667

http://stackoverflow.com/q/51734479
upvote count: 11
tagged with: django
has answer: http://stackoverflow.com/a/79099534
has comment: http://stackoverflow.com/comment/90429895
type: Question
has answer: http://stackoverflow.com/a/67562815
answer count: 8
has answer: http://stackoverflow.com/a/51734761
has answer: http://stackoverflow.com/a/58155218
has title: django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited
has answer: http://stackoverflow.com/a/62448755
has comment: http://stackoverflow.com/comment/90429910
has answer: http://stackoverflow.com/a/72517517
has body: (ll_env) brads-MacBook-Pro:learning_log $ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d417d08> Traceback (most recent call last): File "/learning_log/ll_env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/learning_log/ll_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/learning_log/ll_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 396, in check for pattern in self.url_patterns: File "/learning_log/ll_env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/learning_log/ll_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/learning_log/ll_env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/learning_log/ll_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_…
has answer: http://stackoverflow.com/a/68627729
downvote count: 0
has answer: http://stackoverflow.com/a/51734654
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 11

http://stackoverflow.com/q/51685807
tagged with: python
has body: I have plotted the following scatter matrix using pandas _ = scatter_matrix(data, figsize=(20,20), diagonal='kde') As you can see, the top left axis scale (for CAC) is unlike the other plots, and not being rounded to 2 decimal places. Is there a way to fix this?
type: UnansweredQuestion
tagged with: plot
type: Question
has title: Fix axis scale in Pandas Scatter Matrix Plot
has answer: http://stackoverflow.com/a/52668622
answer count: 1
score: 0
tagged with: pandas

http://stackoverflow.com/comment/90352551
comment on: http://stackoverflow.com/q/51695492
has text: miniconda or Anaconda is better tool to manage multiple virtualenv
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51729145
answers question: http://stackoverflow.com/q/51728783
type: Answer
score: 1
has body: Here's one way: import numpy as np src = np.array([[2, 9, 0, 2, 4], [0, 1, 8, 8, 0], [1, 0, 3, 0, 0], [0, 0, 0, 0, 7]]) # Masked indices of non-zero positions idx = np.arange(len(src))[:, np.newaxis] * (src != 0) # Sort to and pick valid indices at the end idx = np.sort(idx, axis=0)[-2:] # Get values trg = src[idx, np.arange(src.shape[1])] print(trg) Output: [[2 9 8 2 4] [1 1 3 8 7]]
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/51694132
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51693988
has body: From Django documentation for url url(regex, view, kwargs=None, name=None) This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release. Key difference between path and re_path is that path uses route without regex You can use re_path for complex regex calls and use just path for simpler lookups So, you can use re_path('add/(?P&lt;journal_type&gt;C[DR])/$', add_bank_entry), instead of url('add/(?P&lt;journal_type&gt;C[DR])/$', add_bank_entry), if the regex is working fine with url()
upvote count: 1
type: Answer

http://stackoverflow.com/q/51780844
tagged with: python
has comment: http://stackoverflow.com/comment/90519579
tagged with: list
has comment: http://stackoverflow.com/comment/90519816
downvote count: 2
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90519867
upvote count: 0
score: -2
has title: compare elements between two lists and print in series
has body: &gt;&gt;&gt; a = [1, 2, 3, 4, 5] &gt;&gt;&gt; b = [9, 8, 3, 6, 5] &gt;&gt;&gt; set(a) &amp; set(b) {3,5} I am using this code to find matching elements between the lists a and b, but I want to return list b if the elements of a match list b and output should be in the form of series.
has answer: http://stackoverflow.com/a/51781323
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: series
has comment: http://stackoverflow.com/comment/90519819
type: UnansweredQuestion

http://stackoverflow.com/comment/90465601
type: QuestionComment
comment on: http://stackoverflow.com/q/51752885
score: 1
has text: Please post the lists as code so that users can copy and paste it to try it out
type: Comment

http://stackoverflow.com/comment/90246347
has text: Yes, we need to know how you're trying to install this. If you aren't, give it a try using: `pip install pyaudio`. Or, here's a pre-built package that you can try: http://people.csail.mit.edu/hubert/pyaudio/packages/pyaudio-0.2.8.py27.exe
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51640667
type: QuestionComment

win32gui
type: Tag
tags question: http://stackoverflow.com/q/51694887
tag name: win32gui
tags question: http://stackoverflow.com/q/51736536

http://stackoverflow.com/a/51761274
score: 1
upvote count: 1
downvote count: 0
has body: You can do it with list comprehension "also". In [1]: cmds = ['!test','hello','world','!echo','!embed','oh god'] In [2]: prefix = '!' In [3]: inds = [i for i, x in enumerate(cmds) if prefix in x] In [4]: inds.append(len(cmds)) In [5]: lens = list(zip(inds, inds[1:])) # [(0, 3), (3, 4), (4, 6)] In [6]: ["\n".join(cmds[a:b]) for a, b in lens] Out[6]: ['!test\nhello\nworld', '!echo', '!embed\noh god']
type: Answer
answers question: http://stackoverflow.com/q/51761012

http://stackoverflow.com/comment/90366073
type: Comment
score: 0
has text: after reading the file you can do something like this`df2['data'] = [np.array(i) for i in df2.data]`. I dont think its possible while reading the file.
type: QuestionComment
comment on: http://stackoverflow.com/q/51702034

http://stackoverflow.com/comment/116572483
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51684817
has text: Using sigmoid is not good for regression as it is more biased towards 0 and 1 than the middle values (only good for classification). One should use an activation function like relu and restrict it to be less than 1.
type: AnswerComment

http://stackoverflow.com/a/51798449
has comment: http://stackoverflow.com/comment/90613582
type: AcceptedAnswer
has body: You can also use the DataFrame.append() function: df2=df2.append(df1'Name', 'OrderNo', 'Phone'.iloc[0]) df2 Name OrderNo Phone 0 Sanjay 23 555-1212
answers question: http://stackoverflow.com/q/51797491
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51797491
downvote count: 0
score: 1

http://stackoverflow.com/comment/127784977
comment on: http://stackoverflow.com/a/66443030
type: Comment
has text: I was following the same (amazing) tutorial. I'd changed the module name to "bloggy" in order to disambiguate `app`. So my import is `from bloggy import models` and viola table has been created.
score: 2
type: AnswerComment

http://stackoverflow.com/a/51762407
downvote count: 0
has comment: http://stackoverflow.com/comment/90496820
type: Answer
answers question: http://stackoverflow.com/q/51760917
has comment: http://stackoverflow.com/comment/111164374
has comment: http://stackoverflow.com/comment/111164368
score: 2
has comment: http://stackoverflow.com/comment/90483845
has comment: http://stackoverflow.com/comment/90488395
upvote count: 2
has comment: http://stackoverflow.com/comment/90487190
has body: First, according to Conventions for Python test discovery, the class name should starts with Test: From those files, collect test items: test_ prefixed test functions or methods outside of class test_ prefixed test functions or methods inside Test prefixed test classes (without an __init__ method) class Test...: Second, func_fixture in @pytest.mark.skipif("func_fixture=='fail'") is a function, not a return value of the function call. (I don't know how to use fixture value inpytest.mark.skipif(..); See this answer to see how to use fixture in expression for skipif). import pytest @pytest.fixture def func_fixture(): return 'fail' skip_by_fixture = pytest.mark.skipif("func_fixture() == 'fail'") class TestSetting: @skip_by_fixture def test_setting_value(self): print("Hello I am in testcase")
has comment: http://stackoverflow.com/comment/90486504
has comment: http://stackoverflow.com/comment/90484030

http://stackoverflow.com/comment/90394768
type: AnswerComment
has text: @Nicolas That question doesn't make sense. A `u'…'` string is a Unicode string, not a UTF-8 string. `u'\xe9'` is the Unicode string whose only character is Unicode character number `0xe9`, aka `U+00E9`, aka `é`. A UTF-8 string is _not_ a Unicode string, it's a byte string, just like a Latin-1 string or any other kind of byte string. The Unicode string `u'\xe9'` encodes to UTF-8 as the byte string `'\xc3\xa9'`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51715425

http://stackoverflow.com/comment/90516281
has text: Isn't it just an attribute of `user`, e.g. `user.mail_nickname`?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51779199
type: QuestionComment

http://stackoverflow.com/q/51684658
has title: Retain entry field in Python Tkinter
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51684787
type: AnsweredQuestion
tagged with: tkinter
upvote count: 3
accepted answer: http://stackoverflow.com/a/51684787
type: Question
has body: I have a pop up text entry field as part of my GUI asking for two entries #1 Filepath #2 Item (these reference an excel sheet) The filepath will rarely change but the ability to change it when needed is still required Is it possible to retain the filepath in the entry field so it dosnt require typing each and every time? i.e after closing and re opening the entry field still contains C:\*\*\*\*\*\somthing.xlsx. master = Tk() master.title("Entry Field") Label(master, text="Filepath: ").grid(row=0) Label(master, text="Item Number: ").grid(row=1) e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) def entry_field(): print("Filepath: %s" % (e1.get())) print("Item No: %s" % (e2.get())) Button(master, text = 'Accept', command = entry_field).grid(row=3, column=1, sticky=W, pady=4) root.mainloop()
score: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90468894
type: Comment
comment on: http://stackoverflow.com/q/51754338
has text: @Strawberry any other thoughts? Maybe something can be done through Python? :)
score: 0
type: QuestionComment

http://stackoverflow.com/a/60325485
has comment: http://stackoverflow.com/comment/110921107
has body: I was getting the following error when trying to update boto3 in my conda environment: PackageNotInstalledError: Package is not installed in prefix. prefix: /usr/local/anaconda3/envs/myfoldername package name: boto3 This was after having already just done: conda install anaconda, conda update -n root conda and conda update --all However, I did finally succeed in updating boto3, by specifying the version number as follows: conda install boto3=1.12
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51712693
type: Answer
score: 4

http://stackoverflow.com/comment/90291875
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51664093
has text: Yeah, I see your point. I've added the `+` inside the capturing group for the number though.

http://stackoverflow.com/q/51695664
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90352879
possible better answer: http://stackoverflow.com/a/51696056
type: Question
has comment: http://stackoverflow.com/comment/90352853
has answer: http://stackoverflow.com/a/51695937
has body: I'm trying to create error handler in python, python will check the file and if the file contains more than 95000 lines, it will stop and print an error message. Is it an easy way to make this? This is solution I found: def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 And then something like, if i > 95000 print 'Error'
has comment: http://stackoverflow.com/comment/90352911
has comment: http://stackoverflow.com/comment/90353006
tagged with: python-2.7
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90353226
has answer: http://stackoverflow.com/a/51696056
has comment: http://stackoverflow.com/comment/90353320
has comment: http://stackoverflow.com/comment/90352955
has comment: http://stackoverflow.com/comment/90352752
tagged with: python
has title: Python | If file contain more than X lines, exit and print message
has answer: http://stackoverflow.com/a/51702643
accepted answer: http://stackoverflow.com/a/51702643
type: AnsweredQuestion

http://stackoverflow.com/q/51763870
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/26762100
type: UnansweredQuestion
tagged with: python
has title: Python Pandas : how to reconstrut categorical feature from stacked dummy features?
has body: My dataframe is the following : Files attr_1 attr_2 attr_3 file_1 X X X file_2 X file_3 X X I want to transform it to : Files attr file_1 attr_1 file_1 attr_2 file_1 attr_3 file_2 attr_2 file_3 attr_1 file_3 attr_3 The closest I found was this question : Reconstruct a categorical variable from dummies in pandas However for me to use the stack() method I need to already have one line per file/attribute, ie the following : Files attr_1 attr_2 attr_3 file_1 X file_1 X file_1 X file_2 X file_3 X file_3 X which is not my case unfortunately. What is the cleanest way to achieve this ?
type: Question
tagged with: dummy-variable
has answer: http://stackoverflow.com/a/51764213
score: 0

http://stackoverflow.com/comment/90543144
type: AnswerComment
has text: (and others) I've accepted this answer because 1) it is 0.5 sec faster than the one-liner answer and 2) it is easier to debug - thanks again!
comment on: http://stackoverflow.com/a/51791074
type: Comment
score: 1

http://stackoverflow.com/comment/90333737
score: 0
type: AnswerComment
type: Comment
has text: could I somehow just remove the commas in the td's, just to make it easier on Excel???
comment on: http://stackoverflow.com/a/51685653

http://stackoverflow.com/comment/90517175
type: AnswerComment
comment on: http://stackoverflow.com/a/51770105
score: 0
type: Comment
has text: @Imbalance, Yes, thats exactly how that loop runs.

http://stackoverflow.com/q/51668057
tagged with: http
type: Question
has comment: http://stackoverflow.com/comment/90299213
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/90298978
has comment: http://stackoverflow.com/comment/90299016
accepted answer: http://stackoverflow.com/a/51668378
has comment: http://stackoverflow.com/comment/90298869
answer count: 1
favorite count: 0
has title: using urllib in python 3
tagged with: python-3.x
has body: I have been coding a webcrawler in python 3, and everything seems to be working. So I decided to use urllib to get the source code of the pages I am going to crawl. But I get a name error that says: name 'urlib' is not defined here is my python code: def get_url(url): from urllib.request import urlopen source = urllib.request.urlopen(url) return source def getNextTarget(page): startLink = page.find("&lt;a href=") if startLink == -1: return None, 0 startQuote = page.find('"', startLink) endQuote = page.find('"', startQuote + 1) url = page[startQuote + 1 : endQuote] return url, endQuote def findAllLinks(page): while True: url, endpos = getNextTarget(page) if url: print(url) page = page[endpos:] else: break findAllLinks(get_url("https://xkcd.com/")) Sorry if this question has already been asked. Thank you for your help in advance. P.S: the main prblem is with the get_url() function.
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37369901
has answer: http://stackoverflow.com/a/51668378
downvote count: 1

http://stackoverflow.com/comment/90466235
comment on: http://stackoverflow.com/a/51751967
type: AnswerComment
type: Comment
has text: @Liamdaniel Generator Expressions, List Comprehensions, and Dictionary Comprehensions. https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions https://www.python.org/dev/peps/pep-0289/
score: 0

http://stackoverflow.com/comment/90252617
comment on: http://stackoverflow.com/q/51643904
type: QuestionComment
score: 0
has text: cause when I run the code, "test_add_raiseException_true" function doesn't show if the exception has been raised
type: Comment

http://stackoverflow.com/q/51660187
has title: Python 2.7: 2 lists with duplicate value into a dictionary
tagged with: duplicates
score: 0
answer count: 2
has body: If I have 2 lists: fruits = ["apple","apple","oranges","watermelon","apple"] val = ["a","b","c","d","e"] Each index of val corresponds to the index of fruits So if I want a dictionary with: dict { "apple" : ["a","b","e"], "oranges": ["c"], "watermelon": ["d"] } What is the simplest way to achieve this?
has answer: http://stackoverflow.com/a/51660227
favorite count: 0
duplicate of: http://stackoverflow.com/q/960733
has comment: http://stackoverflow.com/comment/90283963
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90283896
has comment: http://stackoverflow.com/comment/90284033
tagged with: list
has answer: http://stackoverflow.com/a/51660234
downvote count: 2
linked to: http://stackoverflow.com/q/960733
type: Question

http://stackoverflow.com/comment/109371835
has text: This was an issue I had, thanks for this, it is to do with flask mixing up a package and a module import of the same name at different points
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51783300

http://stackoverflow.com/comment/90281193
has text: Okay, I will attempt to do something with template tags now, I will take reference from django documentation. Will report back if it fails or I still have not understood.
comment on: http://stackoverflow.com/a/51657878
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51654950
has answer: http://stackoverflow.com/a/51655022
tagged with: python
accepted answer: http://stackoverflow.com/a/51655077
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90273344
score: 1
possible better answer: http://stackoverflow.com/a/51655062
upvote count: 1
has answer: http://stackoverflow.com/a/51655062
type: Question
has title: A function to list all divisors of an integer
has body: I'm practicing the basics of Python and I had a exercise of doing a function that asks for the user for a number and the function will return him all the divisors of that number so I done this def divisor_generator(): integer = raw_input("Enter a number:") integer = int(integer) list = [] for divisors in range(integer+1): if divisors%integer == 0: list.append(divisors) print list and for example the output for the integer 50 was [50, 0] I really want to keep it simple and I don't understand what is not good about it, I searched for so many answers but none of them was on my level of understanding. Why is my function not working as expected?
has answer: http://stackoverflow.com/a/51655077
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/90273538
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90328615
type: Comment
has text: When changing the scale in the second example you can resize the picture but you can also use cv2.resize(img, (target_width, target_height))
comment on: http://stackoverflow.com/a/51682979
type: AnswerComment
score: 0

http://stackoverflow.com/q/51658015
has body: I use something like the following to update my dataframe df.loc[(df['Message'].str.contains('hello', case=False)),'SomeSeries'] = 'SomeUpdate' But I might want to update when my series contains 'hello' or 'bicycle' or 'monday', etc. Obviously, I could iterate over a list but I'm wondering if there is a way to do that in a single line? I would like something like watchlist = ['hello','bicycle','monday'] df.loc[(df['Message'].str.contains(watchlist, case=False)),'SomeSeries'] = 'SomeUpdate'
tagged with: pandas
score: 3
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51658111
type: Question
tagged with: dataframe
upvote count: 4
has comment: http://stackoverflow.com/comment/90279844
has title: Pandas str.contains over a list?

http://stackoverflow.com/q/51664615
has comment: http://stackoverflow.com/comment/90292651
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51682290
has comment: http://stackoverflow.com/comment/90292772
linked to: http://stackoverflow.com/q/45731683
score: 0
has comment: http://stackoverflow.com/comment/90292712
has comment: http://stackoverflow.com/comment/90292741
has body: There are a lot of questions asked on this topic but none have helped me. I am trying to connect Gunicorn to /tmp/gunicorn.sock but I keep on getting operation not permitted. My gunicorn.conf.py looks like: import multiprocessing # bind = '127.0.0.1:5000' bind = 'unix:/tmp/gunicorn.sock' backlog = 2048 preload_app = True max_requests = 2048 max_requests_jitter = 128 workers = multiprocessing.cpu_count() * 2 + 1 worker_connections = 1000 timeout = 60 keepalive = 2 errorlog = '-' loglevel = 'debug' accesslog = '-' access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' def when_ready(server): open('/tmp/app-initialized', 'w').close() and my logs are: [2018-08-03 02:34:40 +0000] [116] [INFO] Starting gunicorn 19.9.0 [2018-08-03 02:34:40 +0000] [116] [DEBUG] connection to /tmp/gunicorn.sock failed: [Errno 1] Operation not permitted [2018-08-03 02:34:40 +0000] [116] [ERROR] Retrying in 1 second. [2018-08-03 02:34:41 +0000] [116] [DEBUG] connection to /tmp/gunicorn.sock failed: [Errno 1] Operation not permitted [2018-08-03 02:34:41 +0000] [116] [ERROR] Retrying in 1 second. [2018-08-03 02:34:42 +0000] [116] [DEBUG] connection to /tmp/gunicorn.sock failed: [Errno 1] Operation not permitted [2018-08-03 02:34:42 +0000] [116] [ERROR] Retrying in 1 second. [2018-08-03 02:34:43 +0000] [116] [DEBUG] connection to /tmp/gunicorn.sock failed: [Errno 1] Operation not permitted [2018-08-03 02:34:43 +0000] [116] [ERROR] Retrying in 1 second. [2018-08-03 02:34:44 +0000] [116] [DEBUG] connection to /tmp/gunicorn.sock failed: [Errno 1] Operation not permitted [2018-08-03 02:34:44 +0000] [116] [ERROR] Retrying in 1 second. [2018-08-03 02:34:45 +0000] [116] [ERROR] Can't connect to /tmp/gunicorn.sock This looks like a permission error for the user, but that shouldn't be a problem because gunicorn is running as root /opt/app # ps aux | grep gunicorn 123 root 0:00 grep gunicorn I have also tried creating a user and a group as addgroup -S appgroup &amp;&amp; adduser …
has title: Gunicorn not able to connect to sock file on Alpine
answer count: 1
has comment: http://stackoverflow.com/comment/90292752
accepted answer: http://stackoverflow.com/a/51682290
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/90292786
has comment: http://stackoverflow.com/comment/90292802
tagged with: python

http://stackoverflow.com/q/51700305
answer count: 1
tagged with: variables
has title: Running an if statement against a variable set as None.
favorite count: 0
tagged with: python-3.x
has body: Might just be too new this to accurately find what I am looking. I have a variable I preset to None globally to update the value of var1 from func1. If that first function was not ran to update Var1 from None, is there a method to do an if statement on the None variable, to do some action if it is confirmed it is still set to None. I have tried ==, != "1", and many other familiars, but not finding a way through. Here is an example with tkinter: import tkinter as tkinter from tkinter import Frame import tkinter.filedialog as filedialog root = tkinter.Tk() class Stupid_app(Frame): def __init__(self, master=None): Frame.__init__(self, master, bd=2) Var1 = None def func1(): global Var1 Var1 = tkinter.filedialog.askopenfilename() # Open file to get path label.config(text=Var1) # Updates the label print(Var1) return Var1 def func2(): global Var1 if Var1 is not None: print("var is not none") else: quit() Button1 = tkinter.Button(root, text="Get Path", command=func1) Button1.pack() label = tkinter.Label(root, text="^^Select File ^^") label.pack() Button2 = tkinter.Button(root, text="Run a Fuction", command=func2) Button2.pack() app = Stupid_app(root) root.update() root.mainloop() Rather setting globals, presetting variable as a string, it seems to always return NameError: name 'var1' is not defined on line 22 that contains the if statement if var1 is "":. Ive also tried setting the variable inside and outside the function with "a", or simliar. I have read on several location this is not possible, nor is it possible to use None in this manner, but I do not see any alternatives. Any assistance is appreciated, thanks.
tagged with: python
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51700334
downvote count: 1
tagged with: nonetype
score: -1
type: Question
upvote count: 0

http://stackoverflow.com/q/51786133
downvote count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51786285
has comment: http://stackoverflow.com/comment/90529272
has title: Efficient multiplying matrices with different shapes in numpy
type: AnsweredQuestion
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/90529246
tagged with: arrays
has comment: http://stackoverflow.com/comment/90529438
possible better answer: http://stackoverflow.com/a/51786285
has answer: http://stackoverflow.com/a/62290316
has answer: http://stackoverflow.com/a/51786223
has answer: http://stackoverflow.com/a/51786241
accepted answer: http://stackoverflow.com/a/51786241
has body: I have two matrices A and B: &gt;&gt;&gt;A [[1,1,1] [1,1,1]] &gt;&gt;&gt;B [2, 3] I want to multiply them efficiently to get such result: &gt;&gt;&gt; A*B [[2,2,2] [3,3,3]] I am looking for a more efficient solution than iterate in a loop. Can anyone help?
has comment: http://stackoverflow.com/comment/90529359
has answer: http://stackoverflow.com/a/51786609
favorite count: 0
tagged with: python-3.x
score: 2

http://stackoverflow.com/comment/90537042
comment on: http://stackoverflow.com/q/51789766
score: 0
type: QuestionComment
has text: Why not just check if a number is negative or not? `x/x.sum()` will ever only be negative if `x < 0` or `x.sum() < 0`? You wouldn't even need a `lambda` function. You could replace all the negative values in the Dataframe with `None` and set rows whose sum is < 0 to `None` as well.
type: Comment

http://stackoverflow.com/comment/90378237
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51707677
has text: you probably want to put a `sleep` command in so it pauses between each connection for a few seconds. The DBA might have code that kills anything that appears to be hammering the database.
score: 0

http://stackoverflow.com/comment/90429677
comment on: http://stackoverflow.com/q/51733797
type: Comment
score: 0
has text: what did you configure for hdfs? https://community.hortonworks.com/questions/85757/how-to-add-the-hadoop-and-yarn-configuration-file.html
type: QuestionComment

http://stackoverflow.com/comment/90567596
type: Comment
has text: @skrx I don't agree with it. I am sure that you have not tested my code. If you add a `print` statement in the main loop , then you will see it printing until a button isn't pressed.
score: 0
comment on: http://stackoverflow.com/a/51797485
type: AnswerComment

http://stackoverflow.com/a/51702767
has body: Yes you can. First, you must create a mask of the color range to change, and the answer for that is the inRange function of OpenCV. Then, via numpy, you can say where the mask is not 0 paint them in my image red. This is the code for that: import numpy as np import cv2 # load image and set the bounds img = cv2.imread("D:\\debug\\HLS.png") lower =(255, 55, 0) # lower bound for each channel upper = (255, 255, 10) # upper bound for each channel # create the mask and use it to change the colors mask = cv2.inRange(img, lower, upper) img[mask != 0] = [0,0,255] # display it cv2.imshow("frame", img) cv2.waitKey(0) If you want actually to get a range of colors (e.g. all blue colors) it is better to use HLS or HSV color spaces.
has comment: http://stackoverflow.com/comment/137737998
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/137672439
upvote count: 9
has comment: http://stackoverflow.com/comment/90393793
type: Answer
accepted answer of: http://stackoverflow.com/q/51699025
has comment: http://stackoverflow.com/comment/90402260
downvote count: 0
answers question: http://stackoverflow.com/q/51699025
score: 9

http://stackoverflow.com/a/51796205
score: 1
has comment: http://stackoverflow.com/comment/90549633
has body: Split the string at '.' and then take the last element of the split (using index [-1]). If this is 'csv' then it is a csv file. for i in data_files: if i.split('.')[-1].lower() == 'csv': # It is a CSV file else: # Not a CSV
upvote count: 1
answers question: http://stackoverflow.com/q/51796154
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90536193
comment on: http://stackoverflow.com/a/51789058
has text: I have tried upgrading and downgrading pymongo a few times. My DB is 80GB, and this problem happens in different ranges of queries. Schema is always fixed in the range of the query. Also, dumping and restoring works with mongodump and mongorestore. I really need here something out of the box. Something related to my operational system (Windows 10 Home unfortunatelly) or that this happens because of some indexing I've done, or some configuration of mongo server or... I dont know. Your code is pretty much the same as mine and have the same problem in my enviroment. BTW I'm running pymongo 3.7.1
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51730380
has comment: http://stackoverflow.com/comment/90421940
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51712256
score: 1
has body: Generalizing a bit, you want to perform some operation with a time limit. If the operation finishes before the time limit is reached, all is well. If not, you want the operation to be interrupted, and execution to pass on to whatever comes next. This suggests that we want to set up a try ... except structure, with the exception being raised after a certain amount of time has passed. This question doesn’t specify a platform. I can’t provide code for Windows. This question and this other question seem useful for that. Under Unix, we set up a signal handler function that raises the exception; tell Python to call that function when the SIGALRM signal is received; and set a timer that will send that signal when it times out. See example code below. #!/usr/bin/env python2 import signal from time import sleep # only needed for testing timelimit_seconds = 3 # Must be an integer # Custom exception for the timeout class TimeoutException(Exception): pass # Handler function to be called when SIGALRM is received def sigalrm_handler(signum, frame): # We get signal! raise TimeoutException() # Function that takes too long for bananas and oranges def mix(f): if 'n' in f: sleep(20) else: sleep(0.5) fruits = ['apple', 'banana', 'grape', 'strawberry', 'orange'] for f in fruits: # Set up signal handler for SIGALRM, saving previous value old_handler = signal.signal(signal.SIGALRM, sigalrm_handler) # Start timer signal.alarm(timelimit_seconds) try: mix(f) print f, 'was mixed' except TimeoutException: print f, 'took too long to mix' finally: # Turn off timer signal.alarm(0) # Restore handler to previous value signal.signal(signal.SIGALRM, old_handler)
accepted answer of: http://stackoverflow.com/q/51712256
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51735366
has comment: http://stackoverflow.com/comment/90431829
has answer: http://stackoverflow.com/a/51735556
has body: B1, B2,B3 -232.34 -48.48 -260.77 -233.1 -49.48 -253.6 -232.44 -50.81 -250.25 -233.02 -51.42 -248.88 -232.47 -51.95 -248.06 -232.17 -52.25 -247.59 -232.6 -52.83 -245.82 -232.29 -53.63 -243.98 -231.65 -53.24 -243.76 o1,o2,o3 -302.07 -1.73 -280.1 -302.13 -3.37 -273.02 -303.13 -4.92 -269.74 -302.69 -4.85 -268.32 -303.03 -5.61 -267.45 -302.55 -5.2 -267.22 -302.6 -5.91 -266.01 -302.46 -6.41 -264.79 -302.59 -7.4 -264.96 import numpy as np # Convert your arrays to numpy arrays B1 = np.asarray(B1) B2 = np.asarray(B2) B3 = np.asarray(B3) o1 = np.asarray(o1) o2 = np.asarray(o2) o3 = np.asarray(o3) # Find the distance in a single, vectorized operation force = np.sqrt(np.sum(((B1-o1)**2, (B2-o2)**2, (B3-o3)**2), axis=0)) print(force) print(B1,B2,B3,o1,o2,o3) #87.08173861378742 is the result of force #-231.65 -53.24 -243.76 -302.59 -7.4 -264.96 is the result for B1,B2,B3,o1,o2,o3 #the code only uses last data set for the force calculation. It should use all the data The data type of B1-o3 changed from &lt;class 'numpy.float64'&gt; to &lt;class 'numpy.ndarray'&gt; after the code runs. I wan to calculate the distances between the two point (O and B). each points comes from 3D system. I think there is something wrong about my data type, but I couldn't find it.
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90431985
has title: Calculate distance between two points from two lists
linked to: http://stackoverflow.com/q/51676404
has comment: http://stackoverflow.com/comment/90431528
tagged with: distance
score: 0
tagged with: types
has comment: http://stackoverflow.com/comment/90432028
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90431917
tagged with: python
has answer: http://stackoverflow.com/a/51735645

http://stackoverflow.com/comment/90562708
type: Comment
comment on: http://stackoverflow.com/q/51791599
score: 0
has text: i am using python 3
type: QuestionComment

http://stackoverflow.com/q/51797718
has comment: http://stackoverflow.com/comment/90552397
downvote count: 2
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/90552771
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90556787
has answer: http://stackoverflow.com/a/51797801
type: Question
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/1712227
answer count: 1
has title: Python lambda : Reducing typing and invocation
tagged with: python-3.6
favorite count: 0
accepted answer: http://stackoverflow.com/a/51797801
has comment: http://stackoverflow.com/comment/90567687
has body: I have written the following code to find the area of triangle in terms of its three sides a, b and c: s = lambda a, b, c : (a + b + c)/2 area_tri = lambda a, b, c : (s(a,b,c) * (s(a,b,c)-a) * (s(a,b,c)-b) * \ (s(a,b,c)-c)) ** 0.5 area_tri(1, 2, 3) Output: 7.3484692283495345 I have two questions. First, how to reduce the repeated typing of s(a,b,c) in the lambda function for area_tri? Secondly, conjoined to the first question, how to reduce the number of invocations to lambda s in area_tri?

http://stackoverflow.com/q/51640881
has answer: http://stackoverflow.com/a/51641453
upvote count: 2
duplicate of: http://stackoverflow.com/q/7978144
type: UnansweredQuestion
tagged with: python
has body: I want to do something like: list = [1,2,3] valstring = "one: {}, two: {}, three: {}".format(list) print(valstring) result: one: 1, two: 2, three: 3 Is something like this possible? I know I can achieve a similar result by using .format(list[0], list[1], list[2]) but I have a long list so I'd prefer not to.
has answer: http://stackoverflow.com/a/51640922
score: 2
tagged with: string.format
tagged with: list
has title: Is there a way to insert a list into the .format method in python?
type: Question
linked to: http://stackoverflow.com/q/7978144
answer count: 2
tagged with: printing
has comment: http://stackoverflow.com/comment/90246209
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90352711
score: 0
type: Comment
type: QuestionComment
has text: Can you post a small sample of your dataframe, as well as a desired output? There is a much better way to do this than iterrows.
comment on: http://stackoverflow.com/q/51695651

http://stackoverflow.com/comment/90379799
type: QuestionComment
comment on: http://stackoverflow.com/q/51707773
score: 0
has text: @xdze2 That's *exactly* the case. Thanks a lot for spotting that! Can you add this as an answer, I'll then accept the answer.
type: Comment

http://stackoverflow.com/a/51661944
accepted answer of: http://stackoverflow.com/q/51661686
answers question: http://stackoverflow.com/q/51661686
type: AcceptedAnswer
downvote count: 0
has body: I would use fuzzy match algorithms e.g. from fuzzywuzzy import fuzz a = 'invoice#' b = 'sold to wal-mart corp invoice no 91058780' for word in b.split(): print(a, word, '--&gt;',fuzz.partial_ratio(word,a)) get_word = [word for word in b.split() if fuzz.partial_ratio(word,a)&gt;98] print(get_word) as you can see below on jupyter notebook, it gets the value we are after. Will this work?
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/90340405
has text: @JakeWalter Which examples? The docs say C extensions don’t work. There are open issues asking for specific modules to be added because C extensions don’t work. I’m not making this up to make your life harder, and arguing with me isn’t going to make your code start working.
comment on: http://stackoverflow.com/a/51679635
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51648340
has body: Try this in one line: a = '''XXX f,d,c,e DDD f,d,c,g ZZZ f,d,h,g KKK c,c,d,d''' {k:v.split(',') for k,v in {l.split()[0]:l.split()[1] for l in a.split('\n')}.items()} the out put: {'XXX': ['f', 'd', 'c', 'e'], 'DDD': ['f', 'd', 'c', 'g'], 'ZZZ': ['f', 'd', 'h', 'g'], 'KKK': ['c', 'c', 'd', 'd']}
upvote count: 2
answers question: http://stackoverflow.com/q/51648189
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90441685
type: AnswerComment
comment on: http://stackoverflow.com/a/51739772
score: 0
type: Comment
has text: @qwww cell.coordinate returns value like 'A1' ,then sheet1['A1'].value is the value of cell A1

http://stackoverflow.com/q/51661893
has title: Pandas Python conditional
upvote count: 3
tagged with: pandas
answer count: 5
has answer: http://stackoverflow.com/a/51681414
has body: d = [{'Number':'0001', 'Name':'A','Course':'Eng','Score':81 },{'Number':'0001', 'Name':'A','Course':'Geo','Score':75}, {'Number':'0002', 'Name':'B','Course':'Eng','Score': 76} , {'Number':'0002', 'Name':'B','Course':'Geo','Score':90 }, {'Number':'0003', 'Name':'C','Course':'Eng','Score':81 },{'Number':'0003', 'Name':'C','Course':'Geo','Score':100, }, {'Number':'0003', 'Name':'C','Course':'Bio','Score':90 }] data = pd.DataFrame(d, index=[1,2,3,4,5,6,7]) data Course Name Number Score 1 Eng A 0001 81 2 Geo A 0001 75 3 Eng B 0002 76 4 Geo B 0002 90 5 Eng C 0003 81 6 Geo C 0003 100 7 Bio C 0003 90 what I want is return only name C because C is the only one who score over 80 on every subject
downvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51661991
score: 3
has answer: http://stackoverflow.com/a/51662017
type: Question
has answer: http://stackoverflow.com/a/51661990
has answer: http://stackoverflow.com/a/51661930
favorite count: 0

http://stackoverflow.com/q/51731348
answer count: 1
accepted answer: http://stackoverflow.com/a/51733159
favorite count: 0
linked to: http://stackoverflow.com/q/51724335
has body: I have two classes GeoFence and Worker. The class GeoFence has an attribute risk_level that is assigned randomly to all objects of this class. I want to access this attribute risk_level from the class Worker. In particular, when I check the collision between the objects of these two classes (see the function update in Worker), I want to print the risk_level of particular geofence that the worker collides with. Below I provide my code, but it fails with the error message: AttributeError: 'Group' object has no attribute 'risk_level' So, I understand that it's necessary to access objects of the group, because the group itself does not have the attribute risk_level. But how can I do it? import pygame class GeoFence(pygame.sprite.Sprite): def __init__(self, rect, risk_level, *groups): # we set a _layer attribute before adding this sprite to the sprite groups self._layer = 1 pygame.sprite.Sprite.__init__(self, groups) self.image = pygame.surface.Surface((rect.width, rect.height)) self.image.fill(GREEN) self.rect = rect self.risk_level = risk_level class Worker(pygame.sprite.Sprite): # we introduce to possible states: RUNNING and IDLE RUNNING = 0 IDLE = 1 NUMBER_OF_ACCIDENTS = 0 def __init__(self, image_running, image_idle, location, *groups): # each state has it's own image self.images = { Worker.RUNNING: pygame.transform.scale(get_image(image_running), (45, 45)), Worker.IDLE: pygame.transform.scale(get_image(image_idle), (20, 45)) } # we set a _layer attribute before adding this sprite to the sprite groups # we want the workers on top self._layer = 2 pygame.sprite.Sprite.__init__(self, groups) # let's keep track of the state and how long we are in this state already self.state = Worker.IDLE self.ticks_in_state = 0 self.image = self.images[self.state] self.rect = self.image.get_rect(topleft=location) self.direction = pygame.math.Vector2(0, 0) self.speed = random.randint(1, 3) self.set_random_direction() def set_random_direction(self): # random new direction or standing st…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90427110
tagged with: python
tagged with: pygame
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51733159
type: Question
has title: How to access attributes of the group's object? AttributeError: 'Group' object has no attribute 'risk_level'
score: 0
has comment: http://stackoverflow.com/comment/90424763

http://stackoverflow.com/a/51766357
downvote count: 0
answers question: http://stackoverflow.com/q/51766289
score: 4
accepted answer of: http://stackoverflow.com/q/51766289
type: Answer
has comment: http://stackoverflow.com/comment/90491230
upvote count: 4
has comment: http://stackoverflow.com/comment/90491335
has body: IIUC: In [24]: df['day_hour'] = df['day'].astype(str)+df['hour'].astype(str) In [27]: wd.groupby(['day_hour'],as_index=False)['number'].sum() Out[27]: day_hour number 0 2018010110 19 1 2018010111 8 2 2018010112 78
type: AcceptedAnswer

http://stackoverflow.com/q/51771665
tagged with: python
has title: Other ways to drop a row in pandas based on specific value
type: UnansweredQuestion
has body: I am trying to delete rows from a pandas df that are equal to 0, i only need that specific row's 0's to be deleted as other rows with a 0 value are ok. i have been trying different variations of code that i will list here to no affect. Anyone know why its not working or working incorrectly? i have tried using: df = df[df.Columnname != 0] and df = df['df.Columnname != 0'] i have tried changing the 0 values to NaN then dropping the NaNs like this: columns = ['columnname'] df = df.replace('0', pd.np.nan).dropna(axis=0, how='any', subset=columns)) I've also tried different variations that i have found here in these forums to no affect. Any help is greatly appreciated! Thanks in advance.
has comment: http://stackoverflow.com/comment/90502551
has comment: http://stackoverflow.com/comment/90502097
type: Question
has answer: http://stackoverflow.com/a/51771815
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/90537137
tagged with: pandas

http://stackoverflow.com/comment/90303935
score: 0
has text: You need to put it in pandas data frame?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51670198

http://stackoverflow.com/comment/90262160
score: 0
has text: Im supposed to read the data in the dict and get the top 10 price and room_id. How do I go about linking it?
comment on: http://stackoverflow.com/a/51648993
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51735066
accepted answer: http://stackoverflow.com/a/51735498
has comment: http://stackoverflow.com/comment/90431069
has body: Background I have model C inherits B In C, it has just normal charField, nullBooleanField and foreign keys. class C(B): uid = UUIDField(unique=True) x = models.ForeignKey(X, to_field='uid') y = models.ForeignKey(Y, to_field='uid', null=True) z = models.TextField() u = models.ForeignKey(U, null=True) foo = models.NullBooleanField(default=False) In B, it has bunch of dateField like below class B(models.Model): date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) date_deactivated = models.DateTimeField(null=True, blank=True) active = models.BooleanField(default=True, db_index=True, help_text='Set to false if the instance is deleted.') class Meta: abstract = True None of those classes has meta order specified. The problem When I was in a shell_plus, I assigned C.objects.all() to a variable called cs, then I can see cs[0], cs[1], cs[2] and cs[3]. There are only 4 records. Now I want to change one nullBooleanField to false/true. I did cs[1].foo = true and cs[1].save() I would expect 4 records are in the same order as when I fetched them and the second record's foo field is updated. The actual result is, for some reasons, the second record is moved to the back of the list, and it doesn't remember my changes. For example, in the beginning, 4 records are R1, R2, R3, R4 and R2.foo is false. After the assigning foo to true for the second record as I describe above, the result is R1, R3, R4, R2 and R2.foo is still false. The workaround seems to be assigning cs[1] to a variable first then change the variable. It would be nice the know why. Is there anything in Django that can cause queryset result to be rearranged? Edit does each queryset[index] cause a database hit?
has title: Django queryset indexing shuffle around and doesn't remember my changes
downvote count: 0
has comment: http://stackoverflow.com/comment/90430993
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90431505
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90430976
has answer: http://stackoverflow.com/a/51735498
has comment: http://stackoverflow.com/comment/90430996
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90431023
has comment: http://stackoverflow.com/comment/90431089
has comment: http://stackoverflow.com/comment/90431306
type: Question
answer count: 1
tagged with: database

http://stackoverflow.com/a/51709057
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51708969
has body: Have a look at the tuple in ** **, maybe that's the reason # 3rd row elif(i == 2 and j == 0): if(actions == UP): return (i-1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j,0.1),**(i,j+1,1,0.1)** elif(actions == LEFT): return (i,j,0.8),(i-1,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i-1,j,0.1),(i,j,0.1) elif (i == 2 and j == 1): if(actions == UP): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i,j,0.1)
has comment: http://stackoverflow.com/comment/90379621
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/90379852
answers question: http://stackoverflow.com/q/51708969
score: 5
has comment: http://stackoverflow.com/comment/90379311
type: AcceptedAnswer

http://stackoverflow.com/comment/90339087
comment on: http://stackoverflow.com/a/51688611
score: 1
type: AnswerComment
has text: This is going to save me a lot of time
type: Comment

http://stackoverflow.com/comment/100419642
comment on: http://stackoverflow.com/q/51790382
type: Comment
type: QuestionComment
score: 0
has text: @oliver I'm not sure but if I remember correctly my partitions were completely skewed, having all the data on one partition and only a negligible number of data on the rest. Hence the non-parallelism.

http://stackoverflow.com/comment/90498477
comment on: http://stackoverflow.com/q/51743407
score: 0
has text: Thanks that's something similar to what I'm doing, it seems to be working so far, I will edit the post with the solution.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51710667
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Values updating automatically inside the for loop
score: 1
tagged with: loops
has body: I was trying to implement the value iteration algorithm. I have a grid grid = [[0, 0, 0, +1], [0, "W", 0, -1], [0, 0, 0, 0]] An actionlist actlist = {UP:1, DOWN:2, LEFT:3, RIGHT:4} And a reward function reward = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] I wrote a function T, which returns tuple of 3 tuples. def T(i,j,actions): if(i == 0 and j == 0): if(actions == UP): return (i,i,0.8),(i,i,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i+1,j,0.8),(i,j,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j,0.8),(i,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,i,0.1),(i+1,j,0.1) elif (i == 0 and j == 1): if(actions == UP): return (i,i,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i,j,0.1) elif(i == 0 and j == 2): if(actions == UP): return (i,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == DOWN): return(i+1,j,0.8),(i,j-1,0.1),(i,j+1,0.1) elif(actions == LEFT): return (i,j-1,0.8),(i,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j+1,0.8),(i,j,0.1),(i+1,j,0.1) elif(i == 0 and j == 3): if(actions == UP): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == DOWN): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == LEFT): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) elif(actions == RIGHT): return (-1,-1,0.8),(-1,-1,0.1),(-1,-1,0.1) # 2nd row elif (i == 1 and j == 0): if(actions == UP): return (i-1,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == DOWN): return (i+1,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == LEFT): return (i,j,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(actions == RIGHT): return (i,j,0.8),(i-1,j,0.1),(i+1,j,0.1) elif(i == 1 and j ==1): if(actions == UP): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == DOWN): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == LEFT): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif(actions == RIGHT): return (i,j,0.8),(i,j,0.1),(i,j,0.1) elif (i == 1…
type: Question
has answer: http://stackoverflow.com/a/51710862
has answer: http://stackoverflow.com/a/51710800
tagged with: python-2.7
answer count: 2
tagged with: while-loop
possible better answer: http://stackoverflow.com/a/51710862
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51710800

http://stackoverflow.com/comment/90302877
has text: @AI. cf my anwer.
score: 0
comment on: http://stackoverflow.com/q/51669831
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90343322
comment on: http://stackoverflow.com/a/51688087
score: 0
type: Comment
has text: Holy Yeaah! Thanks!
type: AnswerComment

http://stackoverflow.com/comment/90275872
type: QuestionComment
score: 2
has text: Not sure what your desired output is. A dict like `{'A': {'list1': ['X'], 'list2': [1.0]}, 'B': {'list1': ...}, ...}` maybe?
type: Comment
comment on: http://stackoverflow.com/q/51656077

http://stackoverflow.com/comment/90470717
type: Comment
type: QuestionComment
has text: `pandas.DataFrame.merge`???
comment on: http://stackoverflow.com/q/51755504
score: 0

http://stackoverflow.com/comment/90888681
comment on: http://stackoverflow.com/a/51770117
has text: No necessary, use `df.columns = df.columns.map('_'.join)`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90531872
has text: Have a search for "EAFP" or "duck typing" if you're interested :)
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51787099

http://stackoverflow.com/a/51788165
type: Answer
has body: replace s = socket.socket with s = socket.socket() Basically you need to use the socket object not the instance class definition
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51788085
downvote count: 0

http://stackoverflow.com/q/51797066
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51797207
type: Question
answer count: 2
has body: I am working on a project that require that I should extract comments from C++ source code irrespective of where it is located. It can be of single line or multiple line comment. I have the following as data input in txt file, which was read into the program. /* this is a comment in C. This comment syntax is guaranteed to work on every compiler */ and // This is also a comment in C. but it might present portability challenges Fortran ! This is a comment in Fortran C++ // This is single Line Comment in C++ /* This is multi line comment. in C++ */ My task is to extract the human readable comment part excluding the comment tag, Hence using python and regular expression,below is my implementation, I have this function in my python code: def cplusComment(self,content): for comment in re.findall(r'\/\*((.*?)|(\n))*\/', content, re.S): yield comment The above function is been call in this section of the code here: def commentdata(self, content): for con in content.read(): for k in self.cplusComment(con): print(k, 'what is this k meant for') my output is empty list of this format: ('', '', '') and what I am expecting should be this is a comment in C. This comment syntax is guaranteed to work on every compiler This is also a comment in C. but it might present portability challenges This is multi line comment in C++ I will appreciate if i can be guide to the right direction
accepted answer: http://stackoverflow.com/a/51797207
tagged with: regex
favorite count: 0
tagged with: c++
upvote count: 2
has title: Extracting C++ comment in source code with Python and Regular Expression
downvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51797129
has answer: http://stackoverflow.com/a/51797129

http://stackoverflow.com/comment/90421472
has text: Oh I see, I guess I didn't realize that you need to reconstruct the model and redefine variables when restoring the graph. Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/51679504
score: 0
type: Comment

http://stackoverflow.com/comment/107567824
type: Comment
has text: As to the unexpected behavior of ElementTree I was was among the ones fooled by it once. As to the matter at hand, if you'd like to suppress it [see this comment of mine](https://stackoverflow.com/questions/2828953/silence-the-stdout-of-a-function-in-python-without-trashing-sys-stdout-and-resto#comment107567752_28321717)
type: AnswerComment
comment on: http://stackoverflow.com/a/51645756
score: 0

http://stackoverflow.com/comment/90317317
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51656942
has text: thanks for your answer! As I read networkx documentation I saw that I need to use some javascript to achieve the things I wrote (especially the online graph editing). Can I make without js or if I can't, which one do you recommend? d3.js, vis.js, sigma js? Thx
score: 0

http://stackoverflow.com/a/51775154
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51775126
answers question: http://stackoverflow.com/q/51775126
upvote count: 9
has body: yes, with ast.literal_eval which is safe since it only evaluates literals. &gt;&gt;&gt; import ast &gt;&gt;&gt; stringAsByte = "b'a'" &gt;&gt;&gt; ast.literal_eval(stringAsByte) b'a'
score: 9
type: AcceptedAnswer

http://stackoverflow.com/q/51797321
duplicate of: http://stackoverflow.com/q/36268749
has title: Delete elements from python array with given index of elements as list
linked to: http://stackoverflow.com/q/11847491
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90551677
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/38647439
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51797432
downvote count: 0
possible better answer: http://stackoverflow.com/a/51797391
has comment: http://stackoverflow.com/comment/90552102
score: 1
has answer: http://stackoverflow.com/a/51797391
duplicate of: http://stackoverflow.com/q/11847491
has answer: http://stackoverflow.com/a/51797341
accepted answer: http://stackoverflow.com/a/51797341
type: Question
has body: I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4] del_list = [0, 4, 11] desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9] Here is what I have done x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4] index_list = [0, 4, 11] for element in index_list: del x[element] print(x) I get this error. I can figure out that because of deleting elements the list shortens and the index goes out of range. But i am not sure how to do it Traceback (most recent call last): IndexError: list assignment index out of range

http://stackoverflow.com/q/51725436
type: Question
downvote count: 0
tagged with: amazon-ec2
answer count: 1
score: 1
favorite count: 0
tagged with: apache-spark
tagged with: python
has title: Python can not access S3 bucket through EC2 instance
linked to: http://stackoverflow.com/q/44629156
has comment: http://stackoverflow.com/comment/90434115
has answer: http://stackoverflow.com/a/51756057
has comment: http://stackoverflow.com/comment/90450421
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90460245
tagged with: amazon-s3
tagged with: pyspark
has body: I have an Amazon EC2 instance running which has IAM policy that is open to invoke any resources which is proven by invoking a public S3 bucket. But, if I create one S3 bucket myself(mybucket with some .csv files) and provide a bucket policy { "Id": "Policy112324099371", "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt3309232", "Action": "s3:*", "Effect": "Allow", "Resource": "arn:aws:s3:::mybucket/*", "Principal": { "AWS": "*" } } ] } to be invoked by the EC2 user, I am getting the below error. com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 400, AWS Service: Amazon S3, AWS Request ID: &lt;REQUEST ID&gt;, AWS Error Code: null, AWS Error Message: Bad Request, S3 Extended Request ID: &lt;EXTENDED REQUEST ID&gt; at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:798) at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:421) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:232) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3528) at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031) at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994) at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373) at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:350) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:348) at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241) at scala.collecti…

http://stackoverflow.com/q/51697982
tagged with: kivy
type: AnsweredQuestion
tagged with: kivy-language
has answer: http://stackoverflow.com/a/51700006
upvote count: 1
accepted answer: http://stackoverflow.com/a/51713913
type: Question
score: 1
has body: I am learning kivy now... I am developing my 1st app for a friend, a very simple one. But I am facing this error: Whenever I click "create account", the named 'Login(Screen)' loads blank. None of the widgets that I have created on my kivy file shows. here are the codes: ========================================================================== python file: from kivy.app import App from kivy.uix.screenmanager import Screen, ScreenManager class Gerenciador(ScreenManager): pass class BoasVindas(Screen): pass class Login(Screen): def logar(self, usuario, senha): print("usuario={0}, senha={1}".format(usuario, senha)) class Resultado(Screen): pass class LoginApp(App): def build(self): return Gerenciador() LoginApp().run() ======================================================================== kivy file: &lt;Gerenciador&gt;: BoasVindas: name: 'boasvindas' BoxLayout: orientation:'vertical' Label: text:'Faça o seu Login ou crie uma nova conta' Button: text:'Login' Button: text:'Criar nova conta' on_release:root.current='login' Login: name: 'login' BoxLayout: TextInput: id:usuario hint_text:'Usuário' multiline: False TextInput: id:senha hint_text:'Senha' multiline: False password: True Button: id:'btn' text:'Ok' on_press: self.parent.parent.logar(usuario.text, senha.text) on_release:root.current='boasvindas' ========================================================================= Any ideas on what I am missing? The first screen loads perfectly. If I swap the order, Login screen loads well. But the second screen is blank, no matter what content. as long as it is the second screen to load, it returns blank. Thank you!
has answer: http://stackoverflow.com/a/51713913
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51700006
favorite count: 0
has title: Python + Kivy (second screen is loading blank)
tagged with: python

http://stackoverflow.com/comment/90512111
comment on: http://stackoverflow.com/a/51759307
type: AnswerComment
score: 0
type: Comment
has text: Please vote and accept the answer if it helped. Personally I think a box or violin plot would be better :) but I can see what they were trying to do.

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/51698624
tags question: http://stackoverflow.com/q/51708356
tags question: http://stackoverflow.com/q/51790943

http://stackoverflow.com/a/51723228
upvote count: 1
has comment: http://stackoverflow.com/comment/90407114
has comment: http://stackoverflow.com/comment/90407162
downvote count: 0
has body: Not sure this is the most straightforward way to do it but this is what I can think of: import pandas as pd from io import StringIO s = """cid pid purl tid turl sid surl c1 p1 urlp1 t1 urlt1 s1 urls1 c1 p1 urlp1 t1 urlt1 s2 urls2 c1 p1 urlp1 t1 urlt1 s3 urls3 c2 p2 urlp2 t2 urlt2 s5 urls5 c2 p2 urlp2 t2 urlt2 s6 urls6""" df = pd.read_table(StringIO(s), sep='\\s+', header=0) df2 = df.set_index('cid') df3 = pd.concat([df2'pid', 'purl'.rename(columns={'pid': 'uid', 'purl': 'url'}), df2'tid', 'turl'.rename(columns={'tid': 'uid', 'turl': 'url'}), df2'sid', 'surl'.rename(columns={'sid': 'uid', 'surl': 'url'})], axis=0) result = df3.drop_duplicates().sort_index().reset_index() print(result) Output: cid uid url 0 c1 p1 urlp1 1 c1 t1 urlt1 2 c1 s1 urls1 3 c1 s2 urls2 4 c1 s3 urls3 5 c2 p2 urlp2 6 c2 t2 urlt2 7 c2 s5 urls5 8 c2 s6 urls6
type: Answer
answers question: http://stackoverflow.com/q/51722864
score: 1

http://stackoverflow.com/comment/90534056
comment on: http://stackoverflow.com/q/51788397
has text: `OrderedDict` or use a function to sort over keys and print them individually. But as another note, why do you care if a dictionary has an order?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51724846
has comment: http://stackoverflow.com/comment/90410376
score: -1
tagged with: numpy
has answer: http://stackoverflow.com/a/51724889
has comment: http://stackoverflow.com/comment/90409993
answer count: 1
has body: I am using the following code: import numpy as np a = np.array([1,2], [3,4]) print(a) While executing, i am getting the following error: TypeError: data type not understood while using 2D numpy array in python What could be the cause of this error?
favorite count: 0
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90409922
upvote count: 0
type: UnansweredQuestion
has title: Getting the following error..TypeError: data type not understood while using 2D numpy array in python
type: Question

http://stackoverflow.com/q/51794987
tagged with: python-3.x
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51795011
accepted answer: http://stackoverflow.com/a/51795032
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51795011
has title: calculate the weekday information based on date information
has answer: http://stackoverflow.com/a/51795032
has body: In a dataframe created using Pandas, there is one column, i.e., 'date', storing the value of date, i.e., 2012-10-8, how can I create another column, each entry of which stores the weekdays for the corresponding date entry. In other words, I would like to have two columns date weekday 2012-10-8 Tuesday The weekday entry need to be computed based on the date column.
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/90249680
type: QuestionComment
type: Comment
score: 1
has text: works fine on my side too
comment on: http://stackoverflow.com/q/51642556

http://stackoverflow.com/comment/91187437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51722083
has text: It's also possible to login using requests but you need to inspect the exact POST the site makes when doing so. Probably you also need to extract a crsf-token on the login-page and use this in your payload/header. Without the exact site it's hard to say what is needed. It's very much site dependant...
score: 0

http://stackoverflow.com/a/51779758
downvote count: 0
has comment: http://stackoverflow.com/comment/90518465
accepted answer of: http://stackoverflow.com/q/51779699
has body: You need to decode the json first import json print(json.loads(json_data)["export"]) Should work better, I think.
answers question: http://stackoverflow.com/q/51779699
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90518861
has comment: http://stackoverflow.com/comment/90517854
has comment: http://stackoverflow.com/comment/90518672
has comment: http://stackoverflow.com/comment/90517598
has comment: http://stackoverflow.com/comment/90517345
has comment: http://stackoverflow.com/comment/90518214
has comment: http://stackoverflow.com/comment/90518099
type: AcceptedAnswer

http://stackoverflow.com/comment/90246444
type: Comment
type: QuestionComment
has text: A solution could be to match letters of the word? Like if you're trying to find 'John' in the string then split the string into a list, and iterate until you find J, then check for o, h and n..
score: 0
comment on: http://stackoverflow.com/q/51640978

http://stackoverflow.com/a/51788887
downvote count: 0
score: 1
has body: Ok. So after discussion in comments, this is your problem statement. You want to pass the columns feat_1, feat_2 along with the tfidf of text column to your ml model. So the only thing you need to do is this: # Feature Union Pipeline pipeline = FeatureUnion([('text', Pipeline([('selector', ItemSelector(key='text')), ('tfidf', TfidfVectorizer(max_df=0.5)), ])), ('non_text', ItemSelector(key=['feat_1', 'feat_2'])) ]) tfidf = pipeline.fit_transform(test_df) The default ItemSelector can be used to select multiple features at once which will be appended to the last of the tfidf data return from text part of feature Union.
upvote count: 1
has comment: http://stackoverflow.com/comment/90600612
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51776145
answers question: http://stackoverflow.com/q/51776145
type: Answer

http://stackoverflow.com/comment/90361511
type: Comment
has text: Thanks for your answer. I change to open the file in binary mode. After that, the file can be read, while a new error appears.
comment on: http://stackoverflow.com/a/51700026
score: 0
type: AnswerComment

http://stackoverflow.com/a/51750535
has comment: http://stackoverflow.com/comment/90461745
has comment: http://stackoverflow.com/comment/90461053
has comment: http://stackoverflow.com/comment/90461323
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51750436
type: Answer
has body: Use In [99]: df.A.astype(str) + df.B Out[99]: 0 2a 1 1b 2 3c 3 4d dtype: object Alternative, with apply, which could be slow. In [106]: df.apply(lambda x: '{A}{B}'.format(**x), axis=1) Out[106]: 0 2a 1 1b 2 3c 3 4d dtype: object @JonClements has a nice alternative with format_map In [124]: df.apply('{A}{B}'.format_map, axis=1) Out[124]: 0 2a 1 1b 2 3c 3 4d dtype: object
score: 4
has comment: http://stackoverflow.com/comment/90461464

http://stackoverflow.com/q/51711588
type: AnsweredQuestion
tagged with: tkinter
downvote count: 2
type: Question
has title: What does frame.__init__ do? - tkinter
accepted answer: http://stackoverflow.com/a/51711847
tagged with: oop
score: -2
tagged with: class
has body: I am watching Sentdex's Tkinter tutorial and there are some related problems that arise: Basic Class Questions that I'm just new to: How come Frame follows after the declaration of the Window class (sorry for a basic class question)? How is self.pack working without specifying what to pack? What does frame.__init__ contribute to this code? The code is this: from tkinter import * class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master, bg='LightBlue') self.master = master self.init_window() def init_window(self): self.master.title("GUI") self.master.geometry('400x400') self.pack(fill=BOTH, expand=1) quitButton = Button(self, text='Quit') quitButton.place(x=0, y=0) root = Tk() app = Window(root) root.mainloop() Thanks in advance!
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51711876
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51711876
has answer: http://stackoverflow.com/a/51711847
tagged with: python

http://stackoverflow.com/comment/92260768
comment on: http://stackoverflow.com/a/51676787
type: Comment
has text: OK, finally got it: it was a simple format error. The file had an extra new line at the end which messed with the data extraction. Stupid to spend so much time on such a simple mistake, but I guess you learn something every time...
score: 0
type: AnswerComment

http://stackoverflow.com/a/51731253
type: Answer
has comment: http://stackoverflow.com/comment/90428022
has comment: http://stackoverflow.com/comment/90443103
score: 1
has comment: http://stackoverflow.com/comment/90441853
upvote count: 1
answers question: http://stackoverflow.com/q/51730930
downvote count: 0
has body: Search by geckodriver and then kill your gecko processes. netstat -tlp | egrep '(firefo|vnc|gecko)' It comes something like this: 0 0 localhost:9090 *:* LISTEN 11970/geckodriver

http://stackoverflow.com/comment/90593506
comment on: http://stackoverflow.com/a/51655970
score: 1
type: AnswerComment
has text: How is this a user error? Sure, there's nothing for the model to learn, but the fact that the library throws exceptions like this makes it unnecessarily hard to embed in a large automated application. It would be much more user-friendly if it just built a model which predicted that same constant class. Instead we have to catch these exceptions and put in workarounds in our code for no good reason. Is this an edge case? Sure. But the problem is still not ill-defined, it's just super easy.
type: Comment

http://stackoverflow.com/q/51660998
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51919700
accepted answer: http://stackoverflow.com/a/51919700
has comment: http://stackoverflow.com/comment/90285507
tagged with: python
has comment: http://stackoverflow.com/comment/90330169
has title: Plotly python scatterplot y axis not ordering
has body: Plotly.py is having issues with the y axis. Data is not ordered. Even in the csv file the data is sorted in ascending order. https://i.sstatic.net/SUOL3.png import plotly import plotly.plotly as py import plotly.graph_objs as go import pandas as pd import numpy as np import math #What is the filename filename = 'output.csv' #What is the X Value? xvalue = 'total_students' #What is the Y Value? yvalue = 'realcount' #What is the plot title? PlotTitle = 'total_students' filename = input("What is the filename? (WITH .CSV) ") xvalue = input("What is the X value? ") yvalue = input("What is the y Value? ") PlotTitle = input("What is the title of this chart? ") esc1 = pd.read_csv('output.csv', encoding='cp1252') def random_color(): rgbl=[255,0,0] random.shuffle(rgbl) return tuple(rgbl) esc1 = go.Scatter( x = esc1[xvalue], y = esc1[yvalue], name = 'School', mode = 'markers', marker = dict( size = 10, sizemode='area', sizeref=1, color = 'rgba(66, 134, 244, .8)' ) ) data = [esc1] layout = dict(title = 'Total Student Scatter', yaxis = dict(zeroline = True, title=yvalue), xaxis = dict(zeroline = True, title=xvalue) ) #fig = dict(data=data, layout=layout) #py.iplot(fig, filename='styled-scatter') plotly.offline.plot({ "data": data, "layout": layout },filename=PlotTitle+'.html', auto_open=False) print("Finished") Jeeze stack-overflow has a ton of quality control. I have to keep adding details so i hope this helps.
tagged with: plot
type: AnsweredQuestion
tagged with: plotly
has comment: http://stackoverflow.com/comment/90285445
has comment: http://stackoverflow.com/comment/90285613
type: Question
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/51788344
has answer: http://stackoverflow.com/a/52649180
tagged with: python
accepted answer: http://stackoverflow.com/a/51788645
tagged with: opencv
type: AnsweredQuestion
tagged with: pca
score: 1
upvote count: 1
has title: Computing eigen values and eigen vectors using PCACompute2
type: Question
has answer: http://stackoverflow.com/a/51788645
answer count: 2
has body: Im using the following code to compute eigen vectors together with eigen values. mean, eigenvectors, eigenvalues = cv2.PCACompute2(data_pts, mean) but why am i getting the following error? AttributeError: module 'cv2' has no attribute 'PCACompute2' I have installed opencv-contrib-python though using pip but still the error persists. Is there any ways to find eigen values apart from PCACompute2?
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/52649180

http://stackoverflow.com/comment/90406743
type: Comment
comment on: http://stackoverflow.com/a/51722702
has text: I would not say it is bad practice. You can also the checking function and some `if` conditions to really check for the version number. It might be even clearer to use `h5py` just if the version in `get_matfile_version()` is `2`. Who knows what else might raise a `NotImplementedError` :) It just depends on if you want to use `get_matfile_version()` and sneak preview the file.
type: AnswerComment
score: 0

pyyaml
tags question: http://stackoverflow.com/q/51654379
tag name: pyyaml
tags question: http://stackoverflow.com/q/51789905
tags question: http://stackoverflow.com/q/51783818
type: Tag

http://stackoverflow.com/q/51659453
score: 1
type: Question
has title: Writing a CSV file with Python
has answer: http://stackoverflow.com/a/51659580
answer count: 3
has answer: http://stackoverflow.com/a/51660475
has answer: http://stackoverflow.com/a/51659703
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I am trying to save in a CVS file some information using Python. When I run it, it looks like it works but when I go to the file nothing comes out This is my code: dic = {"name": "jason", "name": "mike"} file = "names.csv" cvs = open(file, "a") column = "name,name2\n" cvs.write(column) for key in dic.keys(): name = key name2 = dic[key] fil = name + "," + name2 + "\n" cvs.write(fil)
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90359336
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51698925
has text: "I keep getting errors" is insufficient description
type: Comment

http://stackoverflow.com/a/51677466
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51677308
answers question: http://stackoverflow.com/q/51677308
score: 1
has body: Both works. But, the confusion comes from the fact that 'auth.user' was used before the add of AUTH_USER_MODEL in Django 1.5. Now, in your code I would actually recommend to use neither. instead follow Django recommendation and use settings.AUTH_USER_MODEL user = models.ForeignKey(settings.AUTH_USER_MODEL) or user = models.OneToOneField(settings.AUTH_USER_MODEL) This will avoid that your code will stop working in projects where the AUTH_USER_MODEL setting has been changed to a different user model.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/99772256
comment on: http://stackoverflow.com/a/56597859
type: AnswerComment
score: 0
has text: Well, it's better than nothing.
type: Comment

http://stackoverflow.com/a/51679342
answers question: http://stackoverflow.com/q/51678972
has body: You could do this: @patch.object(requests, 'post') def test_service_post(mock_request_post): data = {'number': 0000, 'user_id': 0, 'name': 'john'} def res(): r = requests.Response() r.status_code = 200 def json_func(): return data r.json = json_func return r mock_request_post.return_value = res() assert data == service_post(data) Test then passed for me when I ran it locally. Be aware that Mock is a mini-smell. I used to be a big fan of Mock. As I've grown as a dev, though, I really try to avoid it. It can trick you into some really bad design, and they can be really hard to maintain (especially since you're modifying your Mock to hold return values). Mock can also create a false sense of security (your test will continue to pass even if the web services changes dramatically, so you might explode in prod). I don't think you really need it here. Two alternatives: You could hit whatever service you're trying to hit, and serialize (save) that response out with pickle, and store to disk (save it in your test suite). Then have your unit test read it back in and use the actual response object. You'd still have to patch over requests.post, but at least the return values will be lined up for you and you won't have to add or modify them as your needs/application grows. Just hit the web. Forget the patch entirely: just do the POST in your test and check the response. Of course, this might be slow, and will only work if you have internet. And you'll get goofy purists who will tell you to never to do this in a unit test. Maybe move it to an integration test if you run into one of those puristy people. But seriously, there's no substitute for doing what you're actually going to do in prod. The upside to doing this is that if the web service changes, then you'll know about it right away and can fix your code. Downside is it can slow down your test suite, and it's a potentially unreliable test (if the webservice is down, your test will fail...but it might actually be good to know …
type: Answer
upvote count: 22
has comment: http://stackoverflow.com/comment/131256242
has comment: http://stackoverflow.com/comment/90393151
accepted answer of: http://stackoverflow.com/q/51678972
downvote count: 0
has comment: http://stackoverflow.com/comment/90344236
has comment: http://stackoverflow.com/comment/115245017
has comment: http://stackoverflow.com/comment/90378156
score: 22
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98874769

http://stackoverflow.com/q/51739163
tagged with: ssh
has body: I use ~/.ssh/config to manage hosts that I need to interact with frequently. Sometimes I would like to access the aliases from that file in scripts that do not use ssh directly, ie if I have a .ssh/config with Host host1 User user1 Hostname server1.somewhere.net I would like to be able to say something like sshcfg['host1'].Hostname to get server1.somewhere.net in scripting languages, particularly Python and something sensible in Bash. I would prefer to do this with standard tools/libraries if possible. I would also prefer the tools to autodetect the the current configuration from the environment rather than have to be explicitly pointed at a configuration file. I do not know if there is a way to have alternate configs in ssh but if there is I would like a way to autodetect the currently active one. Otherwise just defaulting to "~/.ssh/config" would do.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90438402
has answer: http://stackoverflow.com/a/51739164
has answer: http://stackoverflow.com/a/75330623
has title: Accessing ~/.ssh/config aliases from bash and python
type: Question
answer count: 2
score: 0
tagged with: bash
tagged with: ssh-config

http://stackoverflow.com/comment/90258442
score: 0
type: AnswerComment
has text: thanky http://www.zamaninternational.org/news.php?n=72%27%20/*!UNION*/%20/*!SELECT*/%201,2,3,4,5,6,7,8,9,10,11,12,13,14--+ run :)
type: Comment
comment on: http://stackoverflow.com/a/51646935

http://stackoverflow.com/a/51776659
has comment: http://stackoverflow.com/comment/90512222
has comment: http://stackoverflow.com/comment/90511774
has comment: http://stackoverflow.com/comment/90511969
has comment: http://stackoverflow.com/comment/90512053
has comment: http://stackoverflow.com/comment/90511995
has comment: http://stackoverflow.com/comment/90512113
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90511780
has comment: http://stackoverflow.com/comment/90513172
answers question: http://stackoverflow.com/q/51776572
has comment: http://stackoverflow.com/comment/90511849
has comment: http://stackoverflow.com/comment/90512136
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/90512004
upvote count: 6
has body: The problem is that your inner most reduce function, the one acting on your sublists, is always turning the second argument to _: lambda a, b: strxo(a) + strxo(b) So, on the last element of that reduce, b is __, which gets turned into _! You want to map strxo onto everything first, and then reduce using concatenation. So you want something like this: reduce(lambda x, y: x + "\n" + y, map(lambda l: reduce(lambda a, b: a + b, map(strxo, l)), board)) Note, I removed the unecessary call to list. But more importantly, stop using reduce and the concatenation operator to join strings! It is unnecessarily verbose, and it is inefficient to boot (it will have quadratic time complexity). Instead, use: joinstr = ''.join Which is a perfectly fine function. Functional programming doesn't mean "use map and reduce everywhere possible". So, here's some good functional programming: joinstr = ''.join join_newline = '\n'.join def board_str(board): return join_newline(map(lambda l: joinstr(map(strxo,l)), board)) Better yet, you should just use list comprehensions, which are eminently functional constructs (Python stole them from Haskell, btw). It is frequently more readable than map + lambda: def board_string(board): return join_newline([joinstr(map(strxo, l)) for l in board])
accepted answer of: http://stackoverflow.com/q/51776572
has comment: http://stackoverflow.com/comment/90511927
has comment: http://stackoverflow.com/comment/90512044

http://stackoverflow.com/comment/90336226
score: 0
type: Comment
has text: I would expect the ´stopword_pos´ list to be in ascending order, but that isn't the case. Here's the output: [0, 1, 23, 2, 5, 6, 7, 10, 12, 13, 15, 16, 17, 18, 19, 20, 33, 1, 23, 24, 25, 31, 28, 29, 25, 31, 20, 33]
type: AnswerComment
comment on: http://stackoverflow.com/a/51686768

http://stackoverflow.com/a/51743821
has body: Django's queries don't seem to support LIKE out of the box (which is kind of weird). You can translate your LIKE expression to a regular expression and use __regex: .filter(variable__regex='.A.*') (Another, more advanced way would be to write the LIKE lookup class yourself and register it on CharField.)
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51743530
answers question: http://stackoverflow.com/q/51743530

http://stackoverflow.com/q/51685244
tagged with: queue
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90332678
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/51686542
has answer: http://stackoverflow.com/a/51686542
has comment: http://stackoverflow.com/comment/90332731
score: 0
tagged with: multithreading
answer count: 2
has answer: http://stackoverflow.com/a/51685370
has title: How to run two threads simultaneously while sharing their values?
accepted answer: http://stackoverflow.com/a/51685370
has body: I need to run two threads. The first one is a sensor, the second one is motor. I need to run those two threads in parallel with two different delay times and I need to communicate between them. This is my try code. here the motor thread runs only once and print This is the code from queue import Queue from threading import Thread import time def sensor(numbers,q): for n in numbers: q.put(n*n) print (n*n) time.sleep(1) # Add some delay here def motor(): a=q.get() if (a&lt;10): print("good") time.sleep(2) # Add some delay here else: print ("bad") time.sleep(2) # Add some delay here if __name__=="__main__": numbers = [1,2,3,4,5,6,7,8] q= Queue() p= Thread(target=sensor , args = (numbers,q)) r= Thread(target = motor) p.start() r.start() ` this is the results i got 1 good 4 9 16 25 36 49 64 i need to get good or bad comment after each number.

http://stackoverflow.com/comment/90355003
has text: Also: calling `fp.readline()` twice means you skip every second line.
score: 1
comment on: http://stackoverflow.com/q/51696770
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90315484
has text: Go to the code layout part on this link: https://legacy.python.org/dev/peps/pep-0008/ and check `# Aligned with opening delimiter.`
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51675862

http://stackoverflow.com/q/51745894
has answer: http://stackoverflow.com/a/55069871
tagged with: command-prompt
has title: No module named 'pip._internal'; 'pip' is not a package
duplicate of: http://stackoverflow.com/q/49940813
type: Question
upvote count: 4
answer count: 2
downvote count: 0
score: 4
favorite count: 0
has body: I am new to using python, and am wanting to be able to install packages for python using pip. I am having trouble running pip on my windows computer. When typing in "pip --version" into command prompt I get: ModuleNotFoundError: No module named 'pip._internal'; 'pip' is not a package I have added the scripts folder to the PATH environment variable as shown on the picture in this link Environment variables photo (Stack overflow does not allow embedded pictures if you are new) This is the contents of my scripts directory where pip is present: Directory of C:\Users\....\AppData\Local\Programs\Python\Python37-32\Scripts [.] [..] easy_install-3.7.exe easy_install.exe pip-script.py pip.exe pip.exe.manifest pip3 pip3-script.py pip3.7-script.py pip3.7.exe pip3.7.exe.manifest pip3.exe pip3.exe.manifest wheel.exe Any help on this would be appreciated
has answer: http://stackoverflow.com/a/51746074
tagged with: python
tagged with: python-3.x
linked to: http://stackoverflow.com/q/49940813
type: UnansweredQuestion
tagged with: package
tagged with: pip

http://stackoverflow.com/q/51651757
has body: I'm making an API call that fetches me something like Session #1 - ABC Session #2 - DEF Session #3 - PQR I want to render only the values after the hyphen (ABC, DEF, PQR) on a page. Logically, remove all the characters upto the nth character(hyphen, in this case). How do I do that, though?
score: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51651813
has title: display only a certain word in a string

http://stackoverflow.com/q/51667881
has comment: http://stackoverflow.com/comment/90301819
has answer: http://stackoverflow.com/a/51800547
has body: I am trying to load a data set of 1.000.000 images into memory. As standard numpy arrays (uint8) all images combined fill around 100 GB of RAM, but I need to get this down to &lt; 50 GB while still being able to quickly read the images back into numpy (that's the whole point of keeping everything in memory). Lossless compression like blosc only reduces file size by around 10%, so I went to JPEG compression. Minimum example: import io from PIL import Image numpy_array = (255 * np.random.rand(256, 256, 3)).astype(np.uint8) image = Image.fromarray(numpy_array) output = io.BytesIO() image.save(output, format='JPEG') At runtime I am reading the images with: [np.array(Image.open(output)) for _ in range(1000)] JPEG compression is very effective (&lt; 10 GB), but the time it takes to read 1000 images back into numpy array is around 2.3 seconds, which seriously hurts the performance of my experiments. I am searching for suggestions that give a better trade-off between compression and read-speed.
type: Question
tagged with: performance
has title: Lossy compression of numpy array (image, uint8) in memory
upvote count: 5
has comment: http://stackoverflow.com/comment/90300209
tagged with: numpy
score: 5
has comment: http://stackoverflow.com/comment/90300572
has comment: http://stackoverflow.com/comment/90358209
accepted answer: http://stackoverflow.com/a/51800547
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90300702
tagged with: image-compression
type: AnsweredQuestion
tagged with: compression

http://stackoverflow.com/q/51737967
has answer: http://stackoverflow.com/a/51741930
has title: Making lines of code run at certain times - Python 3
tagged with: python
has comment: http://stackoverflow.com/comment/90437027
has answer: http://stackoverflow.com/a/51757537
tagged with: tkinter
downvote count: 2
has body: I am making a code in Python for my teacher and I need help with making the code run at specified times. Right now, I am just trying to make the code run before implementing the simple features into the program... I want the code to run at each class time. I can't get this to work. Below is the basic code. import datetime from datetime import date import calendar while True: my_date = date.today() day=calendar.day_name[my_date.weekday()] time_now = datetime.datetime.now() if day == 'Monday': if time_now.hour &gt;= 9 and time_now.minute &gt;= 10: if time_now.hour &gt;= 10 and time_now.minute &gt;= 30: if time_now.hour &gt;= 11 and time_now.minute &gt;= 30: if time_now.hour &gt;= 13 and time_now.minute &gt;= 10: if time_now.hour &gt;= 14 and time_now.minute &gt;= 5: #period 5 else: #period 4 else: #period 3 else: #period 2 else: #period 1 else: continue #not in range Below here is my current code which I am happy with - instead I want to replace the drop down menu with an automated class selector. I would recommend running this so you can see what I mean. import tkinter as tk # python 3 from tkinter import font as tkfont # python 3 import math from tkinter import StringVar from tkinter import * import random #import Tkinter as tk # python 2 #import tkFont as tkfont # python 2 radius=0 radiususe=0 class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo, PageThree, PageFour, PageFive, PageSix, PageSeven): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of th…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90437159
accepted answer: http://stackoverflow.com/a/51757537
type: Question
answer count: 2
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90436894
favorite count: 0
has comment: http://stackoverflow.com/comment/90436362
possible better answer: http://stackoverflow.com/a/51741930

http://stackoverflow.com/comment/90386044
type: QuestionComment
score: 1
has text: Did you try just `Workbook("Reportes_enviados_20180806.xlsx")`? with no folder specified at all? I highly doubt the library is installed improperly.
comment on: http://stackoverflow.com/q/51710856
type: Comment

http://stackoverflow.com/comment/90449293
has text: If you open the page the 302 is pointing to, what do you see?
comment on: http://stackoverflow.com/q/51744766
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90510062
comment on: http://stackoverflow.com/q/51775775
score: 1
has text: If you do fopen on a file which doesnt exist, it will create it. You can delete it at the end of your program
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90839396
has text: Can it be done using 'OPENCV' ? Does Python 3 support 'OpenCV' ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51721986
score: 0

http://stackoverflow.com/q/51672803
accepted answer: http://stackoverflow.com/a/51676510
has comment: http://stackoverflow.com/comment/137307205
type: Question
tagged with: network-programming
downvote count: 0
tagged with: ssl
has body: In python, we can specify some TLS context options. For example, this code from the documentation here: client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.options |= ssl.OP_NO_TLSv1 client_context.options |= ssl.OP_NO_TLSv1_1 I do not get this symbol |=. I read what it means but don't get why we use it here? why don't we use = ? Should I use |= to set any option? strangely, I find some examples also int he documentation use &amp;=: ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) ctx.options &amp;= ~ssl.OP_NO_SSLv3 I need to specify another option. I jsut need to disable session ticket which is from this option: ssl.OP_NO_TICKET If I have context ctx, how to set ssl.OP_NO_TICKET? Should I use = or |= or &amp;=? please explain.
answer count: 1
tagged with: tls1.2
has answer: http://stackoverflow.com/a/51676510
favorite count: 0
tagged with: sockets
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: How to change a TLS context option
score: 1

http://stackoverflow.com/a/51662940
answers question: http://stackoverflow.com/q/51662866
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90292356
has body: You almost certainly don't want one to spawn a thread per file. To the extent that threading gives you a benefit (and you're not just saturating your disk I/O bandwidth anyhow), you should probably just use a thread pool (e.g. concurrent.futures.ThreadPoolExecutor) with a fixed number of threads. This will limit the number of files open at once. In fact this case is given as an example in the Python docs: https://docs.python.org/dev/library/concurrent.futures.html#concurrent.futures.Executor.shutdown Adapting this to your use: with ThreadPoolExecutor(max_workers=4) as e: for x in files: if os.path.isfile(x): e.submit(copy_file_to_directory, x, directory)
upvote count: 3
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51662866
has comment: http://stackoverflow.com/comment/90338129

http://stackoverflow.com/a/51895668
has body: import pandas as pd import xml.etree.ElementTree as ET def getMetrics(file_name): tree = ET.parse(file_name) root = tree.getroot() result = [] for measure in root.iter('measure'): #Get all 'measure' tag node = measure.attrib["measure"].split("-")[0].strip() #Get Node for measurement in measure: #Get Metrics Information if "timestamp" in measurement.attrib: result.append(dict(node=node, timestamp=measurement.attrib.get("timestamp"), max=measurement.attrib["max"], count=measurement.attrib["count"])) return result df = pd.DataFrame(getMetrics(filename), columns=["timestamp", "max", "count", "node"]) #Form Dataframe print(df) df.to_csv("Your_Output.csv") #Write to CSV.
score: 0
answers question: http://stackoverflow.com/q/51750726
type: Answer

http://stackoverflow.com/a/51747218
has body: You can't have a DatetimeIndex that contains non-datetime things. My recommendation is to place the rows labeled ['Id', 'Name', 'Organization'] into a MultiIndex column object. df = df.T.set_index(['Id', 'Name', 'Organization']).T df = df.set_index(pd.to_datetime(df.index)) df Id 1 2 3 4 5 Name Lewis Alexander Scott Anderson Paul Ashworth Daniel Bachman Bernard Baumohl Organization Nomura Securities International Bank of the West Capital Economics Deloitte LP Economic Outlook Group 2018-12-01 3.25 3.19 3.25 3.2 3.1 2019-12-01 3 3.47 2.5 3.5 3.6 2020-12-01 2.88 2.6 2.25 3.7 4.2 2019-06-01 3.25 3.5 3 3.4 3.35 2020-06-01 3 3.1 2.25 3.6 3.9 You can create an abomination of an index that is of mixed type. If it wasn't obvious, I really advise against this. If you care enough about the type of your index to try and convert it to Datetime then you shouldn't do this. df.set_index(df.index.map(lambda x: pd.to_datetime(x, errors='ignore'))) 0 1 2 3 4 2018-12-01 00:00:00 3.25 3.19 3.25 3.2 3.1 2019-12-01 00:00:00 3 3.47 2.5 3.5 3.6 2020-12-01 00:00:00 2.88 2.6 2.25 3.7 4.2 Id 1 2 3 4 5 2019-06-01 00:00:00 3.25 3.5 3 3.4 3.35 2020-06-01 00:00:00 3 3.1 2.25 3.6 3.9 Name Lewis Alexander Scott Anderson Paul Ashworth Daniel Bachman Bernard Baumohl Organization Nomura Securities International Bank of the West Capital Economics Deloitte LP Economic Outlook Group
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/51746802
upvote count: 4
answers question: http://stackoverflow.com/q/51746802
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/100121986
type: Comment
has text: Eagerly waiting for the v2 documents as I have a similar requirement
comment on: http://stackoverflow.com/a/52960174
score: 0
type: AnswerComment

http://stackoverflow.com/q/51776103
has comment: http://stackoverflow.com/comment/90511700
tagged with: python
tagged with: easy-install
has comment: http://stackoverflow.com/comment/90512993
type: UnansweredQuestion
tagged with: pip
type: Question
tagged with: python-dateutil
has answer: http://stackoverflow.com/a/53266794
has answer: http://stackoverflow.com/a/51957181
has body: I'm facing this issue while trying to use pandas package. I have installed numpy 1.9.0 and installed dateutil 2.5.0 using the command pip install python-dateutil==2.5.0. Still I see this error. Is there any other way to install dateutil? And this is related only to pandas package Traceback (most recent call last): import pandas as pd File "/Users/xyz/Library/Python/2.7/lib/python/site-packages/pandas/init.py", line 23, in from pandas.compat.numpy import * File "/Users/xyz/Library/Python/2.7/lib/python/site-packages/pandas/compat/init.py", line 422, in raise ImportError('dateutil 2.5.0 is the minimum required version') ImportError: dateutil 2.5.0 is the minimum required version
has comment: http://stackoverflow.com/comment/90578768
answer count: 3
has answer: http://stackoverflow.com/a/67074002
score: 0
has title: ImportError: dateutil 2.5.0 is the minimum required version
tagged with: pandas

http://stackoverflow.com/q/51675716
has answer: http://stackoverflow.com/a/51675794
type: UnansweredQuestion
tagged with: python
has body: Hello to all of you from bs4 import BeautifulSoup as b data = """ This is string 1 This is string 2 Another String 1 """ bsObj = b(data, 'html.parser') print(bsObj.find('span', 'string')) Now I want to parse the "Another String 1" only but when I'm run the code, The result is "This is string 1". If I change the find into findAll it prints string1 from div.hello1 and div.hello2 but I only want is the span in div.hello2
type: Question
has answer: http://stackoverflow.com/a/51675905
has title: Parsing a same tag with same class in BS4
score: 0
answer count: 2
tagged with: beautifulsoup

http://stackoverflow.com/a/51697892
has comment: http://stackoverflow.com/comment/90364935
type: Answer
answers question: http://stackoverflow.com/q/51697205
has body: Actually, there is a way but highly inefficient since it requires iterating over all of the existing Sessions. You can use signals to catch post_save of Session model and then delete all of the existing Sessions of this user except the new one (I am not sure if this is what you want, because it will delete all of the sessions, not just the cleared one) . from django.contrib.sessions.models import Session from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Session) def save_session(sender, instance, **kwargs): user_id = instance.get_decoded().get('_auth_user_id') # Get all sessions excluding current session sessions = Session.objects.exclude(session_key=instance.session_key) # Iterate over all sessions and decode them for session in sessions: session_user_id = session.get_decoded().get('_auth_user_id') # If the session belongs to user, delete it if session_user_id == user_id: session.delete()
score: 0
has comment: http://stackoverflow.com/comment/90358245

http://stackoverflow.com/q/51700673
tagged with: pandas
upvote count: 1
has body: I have pandas df with say, 100 rows, 4 columns. I want to calculate mean in specific columns("Value") every 5 rows and select last data(Fifth) of another column("Date") to keep in new dataframe. How can I do that? My dataframe that looks like this : &gt;&gt;df Date Product Location Value 0 12-08-2018 A S1 1.313 1 12-08-2018 B S1 3.089 2 12-08-2018 C S1 1.890 3 12-08-2018 D S1 3.136 4* 12-08-2018 E S1 3.258 5 13-08-2018 F S1 3.113 6 13-08-2018 G S1 2.651 7 13-08-2018 H S1 2.135 8 13-08-2018 I S1 1.555 9* 14-08-2018 J S1 2.009 10 14-08-2018 K S1 1.757 11 14-08-2018 L S1 1.808 12 14-08-2018 M S1 1.511 13 15-08-2018 N S1 2.265 14* 15-08-2018 O S1 2.356 and I would like to turn it into new dataframe looks like this : &gt;&gt; new_df Date Value 0 12-08-2018 2.5372 1 14-08-2018 2.2926 2 15-08-2018 1.9394 Can you help me out? Note : I add * for easy to observe at every 5 rows.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90362830
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: Calculate mean every 5 rows specific column and select last data (fifth) of another column in pandas dataframe
has comment: http://stackoverflow.com/comment/90363032
has answer: http://stackoverflow.com/a/51700687
accepted answer: http://stackoverflow.com/a/51700687
tagged with: dataframe
tagged with: python-2.7

http://stackoverflow.com/a/51794255
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51793856
has body: I'm assuming this is a DiGraph. In that case, first find the edges you want to remove. Then remove them. to_remove = [(v,u) for v,u in G.edges() if not G.has_edge(u,v)] G.remove_edges_from(to_remove) The list to_remove has all those edges in G for which G does not have the opposite edge (it is a list comprehension).
answers question: http://stackoverflow.com/q/51793856
type: Answer

http://stackoverflow.com/a/51686038
has comment: http://stackoverflow.com/comment/90337162
has comment: http://stackoverflow.com/comment/90337762
has comment: http://stackoverflow.com/comment/90337545
upvote count: 3
has comment: http://stackoverflow.com/comment/90337396
answers question: http://stackoverflow.com/q/51685809
type: Answer
has comment: http://stackoverflow.com/comment/90337508
has comment: http://stackoverflow.com/comment/90334238
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90336943
has body: You can use the dataframe .astype() method to change the dtypes. Use a dict to target specific columns and their intended types. import numpy as np # Create data frame and clean data... types = {'A': np.int64, 'B': np.int64, 'C': np.str} df = df.astype(types) df.dtypes A int64 B int64 C object dtype: object EDIT: If I understand you correctly, you want the dtypes of data frame after you've cleaned it. In that case, you can do the following: # Implicitly convert numeric types; see the 'convert_objects' # documentation for other supported types df = df.convert_objects(convert_numeric=True) df.apply(pd.api.types.infer_dtype) A integer B integer C string dtype: object Or, for a dict: dict(df.apply(pd.api.types.infer_dtype)) {'A': 'integer', 'B': 'integer', 'C': 'string'} Note: I'm using pandas 0.23.3. EDIT 2: Per your request here is the full code I'm using. I've simplified it as well, so that no inference is necessary. from io import StringIO txt = '''A B C 1Â 2Â abcÂ 2Â 5Â defÂ''' df = pd.read_table(StringIO(txt), sep = '\s{1,}', engine='python') df = df.applymap(lambda x: x.strip('Â')) df = df.convert_objects(convert_numeric=True) df.dtypes A int64 B int64 C object dtype: object
has comment: http://stackoverflow.com/comment/90336799
has comment: http://stackoverflow.com/comment/90337480
has comment: http://stackoverflow.com/comment/90336631

http://stackoverflow.com/q/51666830
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90296603
has body: I have accidentally overwritten a file called file.pkl. The variable data was None and now the file has zero bytes. Can I somehow restore the original content of the file? The Python process is still running in a jupyter notebook. I use Ubuntu. Code which I used to overwrite the file: with open('file.pkl', 'wb') as fp: pickle.dump(data, fp)
type: UnansweredQuestion
has title: Recover file that was overwritten with python
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51666918

http://stackoverflow.com/q/51643995
type: AnsweredQuestion
score: 2
type: Question
tagged with: matplotlib
has title: Print text above the errorbar cap with pyplot
upvote count: 2
has comment: http://stackoverflow.com/comment/90252139
accepted answer: http://stackoverflow.com/a/51644026
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51644026
has comment: http://stackoverflow.com/comment/90252149
has body: I'm currently working on a somewhat simple bar graph, but I want to add the mean and standard deviation text above the corresponding bars. The problem is that the bars in my graph aren't remotely the same size, so I can't use the rectangle object to define height. Doing so results in an image like this: Of course, this is completely unacceptable, so I've been trying to find a way to do the same thing, except with the caps of the error bars. My current code is this: bar = plt.bar(names, means, yerr=sterr, capsize=5, color=colors) plt.yticks(np.arange(0,0.35,step=0.05)) plt.ylabel('Percentage of appearance') plt.xlabel('Pot in question') # Add numbers in plot for i, rectangle in enumerate(bar): height = rectangle.get_height() plt.text(rectangle.get_x() + rectangle.get_width()/2, height+0.01, '$\mu=$%s \n $\sigma=$%s' % (str(round(height,3))[1:], str(round(sterr[i],3))[1:]), ha='center', va='bottom') plt.show() The new code would replace the rectangles in the for loop with the caps of the error bar plot. Moving on to my attempt, I opened up the BarContainer object object and found this: {'patches': [&lt;matplotlib.patches.Rectangle object at 0x0000020C44BB8CF8&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BB8FD0&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BC6390&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BC66D8&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BC6A20&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BC6DA0&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BD4160&gt;, &lt;matplotlib.patches.Rectangle object at 0x0000020C44BD44E0&gt;], 'errorbar': &lt;ErrorbarContainer object of 3 artists&gt;, 'eventson': False, '_oid': 0, '_propobservers': {}, '_remove_method': &lt;function _AxesBase.add_container.&lt;locals&gt;.&lt;lambda&gt; at 0x0000020C3F71EF28&gt;, '_label': '_container1'} This has an ErrorbarContainer object, so I tried opening that up which showed this: {'lines': (None, …
tagged with: python

http://stackoverflow.com/comment/90323328
type: AnswerComment
score: 0
type: Comment
has text: Thanks again. This looks better than the one I was looking at on programiz.
comment on: http://stackoverflow.com/a/51679825

http://stackoverflow.com/q/51643696
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90281145
type: AnsweredQuestion
has body: I have my csv files in the same folder. I want to get only the data in the 5th column from all my csv files and write the data into a single file. But there are blank lines in my csv files. https://drive.google.com/file/d/1SospIppACOrLeKPU_9OknnDLnDpatIqE/view?usp=sharing How can I keep the blanks with pandas.read_csv command? Many thanks!
tagged with: loops
downvote count: 1
has title: Extract one specific column with blank lines from multiple csv files and merge into one
type: Question
has answer: http://stackoverflow.com/a/51643751
score: -1
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/51643751
favorite count: 0
possible better answer: http://stackoverflow.com/a/51643745
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51643745
tagged with: pandas

http://stackoverflow.com/q/51665048
tagged with: python
tagged with: pass-by-value
has comment: http://stackoverflow.com/comment/90326465
tagged with: immutability
has comment: http://stackoverflow.com/comment/90293637
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: pass-by-reference
downvote count: 1
linked to: http://stackoverflow.com/q/986006
type: Question
has title: How is the behavior of local/global mutable object different from immutable object in python?
has comment: http://stackoverflow.com/comment/90293598
duplicate of: http://stackoverflow.com/q/534375
duplicate of: http://stackoverflow.com/q/986006
duplicate of: http://stackoverflow.com/q/23029727
duplicate of: http://stackoverflow.com/q/13771088
has body: Scenario 1 : Mutable object like list def a(l): l[0] = 1 print("\nValue of l = {0} in a()".format(l)) def b(l): l = l + [9] print("\nValue of l = {0} in b()".format(l)) l = [0] a(l) print("\nValue of l = {0} after executing a()".format(l)) b(l) print("\nValue of l = {0} after executing b()".format(l)) Output Value of l = [1] in a() Value of l = [1] after executing a() Value of l = [1, 9] in b() Value of l = [1] after executing b() Questions In the context of mutable objects, why is the modification done to l in b() not visible in global scope whereas it happens for a()? Scenario 2 : Immutable object like integer def a(l): l = 1 print("\nValue of l = {0} in a()".format(l)) def b(l): l = l + 9 print("\nValue of l = {0} in b()".format(l)) l = 0 a(l) print("\nValue of l = {0} after executing a()".format(l)) b(l) print("\nValue of l = {0} after executing b()".format(l)) Output Value of l = 1 in a() Value of l = 0 after executing a() Value of l = 9 in b() Value of l = 0 after executing b() Questions In the context of immutable objects, why is the modification done to l in both a() and b() not visible in the global scope? I checked with many folks and they couldnt explain this. Can someone explain the fundamental concepts used in this example?
tagged with: global-variables
has comment: http://stackoverflow.com/comment/90293394
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/90293500
has comment: http://stackoverflow.com/comment/90293325
has comment: http://stackoverflow.com/comment/90293468
has comment: http://stackoverflow.com/comment/90293385

http://stackoverflow.com/a/51694295
type: Answer
upvote count: 0
has body: I am going to speculate a little bit here so maybe I'm just wrong but I'm going to assume you've got running a command prompt, you install CUDA, you update the env.var PATH adding the CUDA paths and you forgot to restart the command prompt. If it's so, the process where you run Python won't have PATH env.var updated? To make sure about this one, just do python -c 'import os; print(os.environ["PATH"])' and confirm it. If PATH is ok on the command prompt process, recheck again the CUDA directories, search cudart64_90.dll and make sure the path where that file lives has been added correctly to PATH. And if the previous step failed, well, I'd say your best chance is opening the Tensorflow file where that dll is being loaded and make some debugging there.
score: -1
answers question: http://stackoverflow.com/q/51693792
downvote count: 1

http://stackoverflow.com/q/51684546
downvote count: 0
answer count: 1
has body: I have a 3D plot of a disk. Now I would like to plot the surface in color depending on values which are stored in an array. E.g. the radius of the disk is 300mm. The array could like: arr = np.array([[ 114.28, 14], [ 128.57, 16], [ 142.85,19], [ 157.13,20], [ 171.41,21], [ 185.69,22], [ 199.97,24], [ 214.25,27], [ 228.53,29], [ 242.81,30], [ 257.09,31], [ 271.37,34], [ 288.65,35], [ 299.93,36], [ 300,38]]) It means for radius = 114.28 I have the value 14. I would like to plot a circle at radius 114.28 in a color (e.g. blue). Second radius is 128.57. For the radius 128.57 the value 16 is assigned. That means I would like to plot a circle in another color e.g. orange on the surface of the plot and so on. I tried to solve this problem with contourplot (thanks to bazingaa). It looks exactly as I want it to. Unfortunately I just realized that this is not really the solution to my problem. Maybe I should explain what I'm trying to achieve. I want to show how certain parameters, such as speed, are distributed along the disc. In this case the contourplot would also correct, as the speed increases towards the outside. But it can also happen that parameters have to be visualized which do not always increase towards the outside continuously. I tried this scenario and simply made a value in the middle of the array smaller than the value before it (I changed the value 27 to 14 from arr) and nothing happens in the contourplot except that the legend changes. Maybe contourplot is not the right approach after all? Maybe I have to draw individual circles and assign colors to them and interpolate between the circles to fill the gaps. import numpy as np import matplotlib as mlp import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d ri = 100 ra = 300 h=20 # input xy coordinates xy = np.array([[ri,0],[ra,0],[ra,h],[ri,h],[ri,0]]) # radial component is x values of input r = xy[:,0] # angular component is one revolution of 30 steps phi = np.linspace(0, 2*np.pi, 2000) …
favorite count: 0
tagged with: python-3.x
has title: matplotlib: assign color to a radius
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90340714
score: 6
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51689707
tagged with: matplotlib
type: Question
tagged with: contourf
has comment: http://stackoverflow.com/comment/90332376
tagged with: contour

http://stackoverflow.com/q/51747086
type: UnansweredQuestion
tagged with: django-forms
type: Question
has title: Django form validation : TypeError at /student/home conversion from dict to Decimal is not supported
has comment: http://stackoverflow.com/comment/90455882
tagged with: django-models
upvote count: 2
has body: I have a decimalfield in my model current_CGPA = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=4) I am using Modelform to validate my form class StudentAcademicsForm(ModelForm): class Meta: model = Student fields = ['current_CGPA'] I have used custom template for form rendering CGPA upto previous semester {{form.current_CGPA.errors}} When i submit the request and validates form (like this) user = request.user student = Student.objects.get(user=user) if request.method == 'POST': form = StudentAcademicsForm(request.POST, instance=student) if form.is_valid(): form.save() else: form = StudentAcademicsForm() this error occurs: TypeError at /student/home conversion from dict to Decimal is not supported On going through stacktrace i found that get_attr() method on my field 'current_CGPA' returns all attributes of POST in the format { 'current_CGPA':3,... } I think its expected to return only the value '3' But this is something done by django built-in code So is it a bug? Has anyone used DecimalField before? If so then please correct me if I have done something wo Stacktrace is shown below: Environment: Request Method: POST Request URL: http://localhost:8000/student/home Django Version: 2.0 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'gep_app.apps.GepAppConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Traceback: File "/usr/local/lib/python3.7/site-packages/django/core…
has comment: http://stackoverflow.com/comment/90455864
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90453976
score: 2
tagged with: django-views
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/90356612
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51691508
type: AnswerComment
has text: @MGB.py I think I found the problem, will update my answer soon

http://stackoverflow.com/q/51784529
has comment: http://stackoverflow.com/comment/90526556
tagged with: python
linked to: http://stackoverflow.com/q/61797760
tagged with: plot
has comment: http://stackoverflow.com/comment/90526443
has comment: http://stackoverflow.com/comment/90526080
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/109400871
has answer: http://stackoverflow.com/a/62967486
accepted answer: http://stackoverflow.com/a/62967486
type: Question
has body: I am using sns.distplot with hist=True and kde=True. This works fine but for some datasets (e.g. if they contain only discrete values) the kernel density estimation line is zig-zagging which looks very odd given that the histogram underneath is smooth. A manual adjustment of the kde bandwidth should fix this but how can I set this for sns.distplot? The documentation does not say anything and the "bw" parameter that works for sns.kdeplot does not exist. How can I stop it from zig-zagging?
tagged with: kernel-density
has title: How can I hand a to bandwidth for the kde to seaborn's distplot?
score: 0
has comment: http://stackoverflow.com/comment/90526209
answer count: 1
tagged with: seaborn

http://stackoverflow.com/comment/110262374
type: Comment
score: 0
type: AnswerComment
has text: Don't forget `pip3` for Python 3.
comment on: http://stackoverflow.com/a/53453830

http://stackoverflow.com/a/51850511
answers question: http://stackoverflow.com/q/51777367
has body: Have you considered this library? I think it will do the job for you! https://pypi.org/project/uritemplate/
score: 0
type: Answer

http://stackoverflow.com/a/55777345
has body: The crash is actually caused by hidinput not handling the ctrl key correctly. I have fixed this in hidinput and will try to do a PR for it once I figure out how to also not have the keycodes go through to the shell that I started kivy from.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51675262

http://stackoverflow.com/a/51753643
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51732824
downvote count: 0
has body: import numpy as np import array import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D num_lon = 128 num_lat = 754 tmpfile = "180523_WT_striatum_#1.dat" fileobj = open(tmpfile, mode='rb') fileobj.seek(1020) binvalues = array.array('f') # 'f' stands for float 4 bytes # It would be 'd' for float 8 bytes size binvalues.read(fileobj, 128 * 128 ) data = np.array(binvalues) data = np.reshape(data, (128,128)) L = np.array([[i for i in range(128)]for j in range(754)]) fileobj.close() fig = plt.figure() ax = fig.gca(projection='3d') for i in range(len(data)): ax.plot(L[i], data[i], i) plt.show()
type: Answer

http://stackoverflow.com/comment/90537401
type: AnswerComment
comment on: http://stackoverflow.com/a/51648578
type: Comment
has text: I note that setting those cells without data to NAN is more convenient
score: 0

http://stackoverflow.com/q/51738505
has title: Python not showing up in Command Prompt after first input
score: -1
type: Question
has answer: http://stackoverflow.com/a/51738566
answer count: 2
accepted answer: http://stackoverflow.com/a/51738594
upvote count: 0
has comment: http://stackoverflow.com/comment/90437390
possible better answer: http://stackoverflow.com/a/51738566
favorite count: 0
tagged with: python-2.7
has body: I'm currently trying to install a package on python that can only be installed on Python 3. I have both 3.6 and 2.7. I'm on a Windows machine. Whenever I type "python" into a newly opened command prompt it returns python 2.7. Then whenever I type "python" it says Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'python' is not defined I believe python 3.6 is set as an environment variable on my path. Can someone offer some advice on how to switch these over? I've read py.exe from python 3's installion should switch between python 2 and 3, but I do not see how I am supposed to run that command other than clicking on it in my File Explorer and that does nothing.
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90437319
has answer: http://stackoverflow.com/a/51738594
tagged with: pip
linked to: http://stackoverflow.com/q/5087831
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/90354463
score: 0
comment on: http://stackoverflow.com/q/51696441
type: Comment
type: QuestionComment
has text: I want the yearly percentage values on the chart, like in bar charts' annotate. Is it possible in area charts?

http://stackoverflow.com/a/51714698
has comment: http://stackoverflow.com/comment/124556934
accepted answer of: http://stackoverflow.com/q/51697727
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/124572139
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51697727
type: Answer
has body: What you need to do is to implement a generator, to feed the data little by little to your model. Keras, does have a TimeseriesGenerator, but I don't think you can use it as it requires you to first load the whole dataset in memory. Thankfully, keras has a generator for images (called ImageDataGenerator), which we will use to base our custom generator off of. First two words on how it works. You have two main classes the ImageDataGenerator class (which mostly deals with any preprocessing you want to perform on each image) and the DirectoryIterator class, which actually does all the work. The latter is what we will modify to get what we want. What it essentially does is: Inherits from keras.preprocessing.image.Iterator, which implements many methods that initialize and generate an array called index_array that contains the indices of the images that are used in each batch. This array is changed in each iteration, while the data it draws from are shuffled in each epoch. We will build our generator upon this, to maintain its functionality. Searches for all images under a directory; the labels are deduced from the directory structure. It stores the path to each image and its label in two class variable called filenames and classes respectively. We will use these same variables to store the locations of the timeseries and their classes. It has a method called _get_batches_of_transformed_samples() that accepts an index_array, loads the images whose indices correspond to those of the array and returns a batch of these images and one containing their classes. What I'd suggest you do is: Write a script that structures your timeseries data like how you are supposed to structure images when using the ImageDataGenerator. This involves creating a directory for each class and placing each timeseries separatly inside this directory. While this probably will require more storage than your current option, the data won't be loaded in memory while training the model. Get acquainted on…

http://stackoverflow.com/a/51684435
has body: I dont know whats the problem there, but I get this with requests package. install requests package with pip : pip install requests then do this: resp = requests.get('http://www.bom.gov.au/fwo/IDV60701/IDV60701.95936.json') print resp.json
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51684384
answers question: http://stackoverflow.com/q/51684384
type: Answer
has comment: http://stackoverflow.com/comment/90348839
score: 0

http://stackoverflow.com/comment/90383629
type: QuestionComment
has text: What is the desired output and its shape?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51710676

http://stackoverflow.com/comment/90341849
has text: After a hard reboot on my Windows 7 machine it seems like everything is back to normal now.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51689035

http://stackoverflow.com/comment/90405299
score: 0
type: Comment
type: QuestionComment
has text: *"it doesn't fit my project"* - why and/or how not? Could you give some context to the problem you're trying to solve?
comment on: http://stackoverflow.com/q/51722449

http://stackoverflow.com/q/51778764
has answer: http://stackoverflow.com/a/55995809
has answer: http://stackoverflow.com/a/58347960
upvote count: 23
tagged with: urllib
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90516195
has answer: http://stackoverflow.com/a/64991518
has answer: http://stackoverflow.com/a/67376339
has answer: http://stackoverflow.com/a/55336269
possible better answer: http://stackoverflow.com/a/64991518
has comment: http://stackoverflow.com/comment/90515584
tagged with: urllib3
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/90515914
has answer: http://stackoverflow.com/a/52376686
favorite count: 0
score: 23
has title: Obnoxious CryptographyDeprecationWarning because of missing hmac.compare_time function everywhere
tagged with: python
has comment: http://stackoverflow.com/comment/90516001
has answer: http://stackoverflow.com/a/52347146
accepted answer: http://stackoverflow.com/a/52376686
has body: Things were running along fine until one of my projects started printing this everywhere, at the top of every execution, at least once: local/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py:26: CryptographyDeprecationWarning: Support for your Python version is deprecated. The next version of cryptography will remove support. Please upgrade to a 2.7.x release that supports hmac.compare_digest as soon as possible. I have no idea why it started and it's disrupting the applications'/tools' output, especially when it's being captured and consumed by other tools. Like many difficulties throughout time, I'm fairly certain it is related to urllib and, by association, requests. Worse, I have so many projects and cross-dependencies that I can't possibly update all of the imports and branches with the call to warnings.filterwarnings() to suppress the warning. I have Python 2.7.6 . Apparently this goes away in 2.7.7 . Only, I have some systems that have 2.7.6 where I do not see the warnings. So, something may or may not be disabling them in one version and I might've inadvertently replaced it with another version. My Ubuntu, Python, urllib, requests (with the security option), cryptography, and hmac are all identical versions/builds on systems that do print the warning and systems that do not. There appears to be no relevant warnings or announcements online and it seems like any related project is static/stable by this point (even though 'hmac' can be installed via PIP, it hasn't changed in eight years).
linked to: http://stackoverflow.com/q/54861026
tagged with: python-requests

http://stackoverflow.com/comment/90537541
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51789766
score: 0
has text: What does "if cell is same at total" mean?

http://stackoverflow.com/a/51641307
has body: While the command= parameter on a Button determines which function to call, it won't pass any parameter. So the function you put there must be a function that doesn't have any argument. The way to solve this is to fetch the user input from inside your function, instead of having it as a parameter: def build_main(): name = manager_name_entry.get() df_manager = df_main[df_main['Employee'].str.contains(name)] Now that means the function must have a way to refer to the entry itself - usually we do that by making everything part of a class, so that you can store those objects that are useful in other functions as attributes of the class instance: self.manager_name_entry = tkinter.Entry() ... then later ... def build_main(self): # a method name = self.manager_name_entry.get() df_manager = df_main[df_main['Employee'].str.contains(name)]
has comment: http://stackoverflow.com/comment/90248041
has comment: http://stackoverflow.com/comment/90247964
accepted answer of: http://stackoverflow.com/q/51641188
score: 0
answers question: http://stackoverflow.com/q/51641188
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90247821
type: Answer

http://stackoverflow.com/comment/90464470
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51752211
has text: Are you sure that the index you point to is ALWAYS in the format you expect it to be? Please provide the format of the CSV file

http://stackoverflow.com/comment/90413706
has text: I don't understand the objection. My code does the exact same thing as the code you're trying to `exec` -- retrieving a member from a module (named in the variable `chart_type`) from the module named `module_name`, and storing it under the name `drawing_class`. Have you actually tried it?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51658120
type: Comment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/51756712
type: Tag
tags question: http://stackoverflow.com/q/51779042
tags question: http://stackoverflow.com/q/51796531
tags question: http://stackoverflow.com/q/51774047
tags question: http://stackoverflow.com/q/51751040
tags question: http://stackoverflow.com/q/51646231
tags question: http://stackoverflow.com/q/51695495
tag name: csv
tags question: http://stackoverflow.com/q/51778614
tags question: http://stackoverflow.com/q/51660998
tags question: http://stackoverflow.com/q/51742698
tags question: http://stackoverflow.com/q/51793530
tags question: http://stackoverflow.com/q/51673963
tags question: http://stackoverflow.com/q/51644941
tags question: http://stackoverflow.com/q/51670504
tags question: http://stackoverflow.com/q/51751023
tags question: http://stackoverflow.com/q/51764219
tags question: http://stackoverflow.com/q/51676669
tags question: http://stackoverflow.com/q/51656948
tags question: http://stackoverflow.com/q/51721802
tags question: http://stackoverflow.com/q/51700452
tags question: http://stackoverflow.com/q/51749613
tags question: http://stackoverflow.com/q/51768081
tags question: http://stackoverflow.com/q/51768418
tags question: http://stackoverflow.com/q/51750855
tags question: http://stackoverflow.com/q/51643389
tags question: http://stackoverflow.com/q/51730456
tags question: http://stackoverflow.com/q/51681164
tags question: http://stackoverflow.com/q/51709412
tags question: http://stackoverflow.com/q/51713123
tags question: http://stackoverflow.com/q/51640880
tags question: http://stackoverflow.com/q/51728089
tags question: http://stackoverflow.com/q/51657192
tags question: http://stackoverflow.com/q/51680468
tags question: http://stackoverflow.com/q/51674730
tags question: http://stackoverflow.com/q/51677024
tags question: http://stackoverflow.com/q/51678110
tags question: http://stackoverflow.com/q/51746376
tags question: http://stackoverflow.com/q/51691265
tags question: http://stackoverflow.com/q/51738838
tags question: http://stackoverflow.com/q/51763717
tags question: http://stackoverflow.com/q/51748908
tags question: http://stackoverflow.com/q/51771182
tags question: http://stackoverflow.com/q/51762615
tags question: http://stackoverflow.com/q/51713791
tags question: http://stackoverflow.com/q/51786416
tags question: http://stackoverflow.com/q/51639941
tags question: http://stackoverflow.com/q/51743671
tags question: http://stackoverflow.com/q/51784072
tags question: http://stackoverflow.com/q/51671427
tags question: http://stackoverflow.com/q/51659737
tags question: http://stackoverflow.com/q/51643696
tags question: http://stackoverflow.com/q/51645542
tags question: http://stackoverflow.com/q/51653419
tags question: http://stackoverflow.com/q/51745485
tags question: http://stackoverflow.com/q/51676316
tags question: http://stackoverflow.com/q/51681659
tags question: http://stackoverflow.com/q/51763627
tags question: http://stackoverflow.com/q/51795156
tags question: http://stackoverflow.com/q/51744751
tags question: http://stackoverflow.com/q/51783225
tags question: http://stackoverflow.com/q/51686494
tags question: http://stackoverflow.com/q/51713916
tags question: http://stackoverflow.com/q/51731389
tags question: http://stackoverflow.com/q/51795186
tags question: http://stackoverflow.com/q/51759005
tags question: http://stackoverflow.com/q/51793885
tags question: http://stackoverflow.com/q/51705502
tags question: http://stackoverflow.com/q/51660471
tags question: http://stackoverflow.com/q/51765879
tags question: http://stackoverflow.com/q/51712489
tags question: http://stackoverflow.com/q/51700215
tags question: http://stackoverflow.com/q/51745110
tags question: http://stackoverflow.com/q/51711256
tags question: http://stackoverflow.com/q/51791299
tags question: http://stackoverflow.com/q/51648879
tags question: http://stackoverflow.com/q/51764038
tags question: http://stackoverflow.com/q/51751960
tags question: http://stackoverflow.com/q/51662838

http://stackoverflow.com/comment/90460527
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51750164
has text: can you include the output you expect?
score: 0

http://stackoverflow.com/comment/90521824
type: Comment
has text: Doesn't look like it. "CompleteValue, Datum = UebergabeWert()" is the line giving the error. It implicitly tries to unpack a tuple (a,b) returned by UebergabeWert(), but in this case the function returned None instead.
type: QuestionComment
comment on: http://stackoverflow.com/q/51781864
score: 1

http://stackoverflow.com/a/51665906
answers question: http://stackoverflow.com/q/51656394
score: 1
upvote count: 1
has body: With partition(): s='srting=123d*gss6agn' s,separator,remainder=s.partition("=") print(s) Out: 'srting' (No exception if '=' is missing.) Just playing: import re re.sub(r"(?&lt;==).*",lambda m: m[0][::-1],s) Out: 'srting=nga6ssg*d321' (?&lt;==) lookbehind ?&lt;= for'='; so '=' isn't captured for replacing; sub's 2nd arg can be a function, too, which got the match object, here 'm'.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51782021
tagged with: data-augmentation
upvote count: 14
downvote count: 1
has answer: http://stackoverflow.com/a/73350500
type: Question
has body: How to use different data augmentation (transforms) for different Subsets in PyTorch? For instance: train, test = torch.utils.data.random_split(dataset, [80000, 2000]) train and test will have the same transforms as dataset. How to use custom transforms for these subsets?
has answer: http://stackoverflow.com/a/51782022
has answer: http://stackoverflow.com/a/59612875
tagged with: deep-learning
answer count: 4
favorite count: 0
has title: How to use different data augmentation for Subsets in PyTorch
tagged with: pytorch
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59615584
score: 13
tagged with: python

http://stackoverflow.com/comment/90271062
type: AnswerComment
has text: I understand that it uses circular imports, but I would still expect that the clients class variable would not have multiple instances.
type: Comment
comment on: http://stackoverflow.com/a/51653700
score: 0

http://stackoverflow.com/a/51759440
type: Answer
has body: I tried to download the data through the URL, and it does take a very long time. I recommend you to download through wget and then process it. The script itself seems fine.
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/51759314
downvote count: 1

http://stackoverflow.com/a/51680952
has body: I would suggest adding an insert trigger similar to the following: create trigger insert_refcode after insert on Table_name begin update Table_name set reference_code = printf('P-%04d', id+999) where rowid=new.rowid; end
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90326623
accepted answer of: http://stackoverflow.com/q/51680083
answers question: http://stackoverflow.com/q/51680083
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90287066
type: Comment
comment on: http://stackoverflow.com/a/51643751
has text: No problem, glad it helped! For future reference - the [`pandas documentation`](https://pandas.pydata.org/pandas-docs/stable/index.html) is really good, you can find a lot of examples there!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90543911
score: 1
has text: This should help you: https://github.com/jupyterlab/jupyterlab/issues/4934
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51790200

http://stackoverflow.com/comment/90545838
comment on: http://stackoverflow.com/q/51793928
type: QuestionComment
has text: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 0
type: Comment

http://stackoverflow.com/q/51774796
tagged with: apache-spark
has title: how to convert dictionary to data frame in PySpark
linked to: http://stackoverflow.com/q/51554921
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51786639
accepted answer: http://stackoverflow.com/a/51786639
has body: Input I have: {'A': '1', 'B': '1'} Output I need: +----+----+ |A |B | +----+----+ | 1| 2| +----+----+ Code I have tried is below - which is not working. v = {'A': '1', 'B': '2'} rdd = sc.parallelize(v.values()) df = spark.createDataFrame(rdd, list(v.keys())) df.show()
score: 2
type: AnsweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/51554921
type: Question
upvote count: 2
tagged with: pyspark
answer count: 1

http://stackoverflow.com/q/51766530
type: Question
tagged with: anagram
has answer: http://stackoverflow.com/a/51767125
tagged with: binary-search
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51767125
upvote count: 2
has title: Given an input string how to search for all the anagrams in O(k logN + W) time where W is the output size and k is the max characters in the string?
tagged with: python
has body: I am trying to write a program that given an input string by the user finds all anagrams available in a list? The O(klogN + W ) time complexity does not include time complexity for sorting. My approach is to first sort each word alphabetically then sort the list alphabetically. For example, a list like this: ['act',bad','cat','tac']... will become ['act','act','act','bad'] To meet the O(klogN) time complexity I decided to use a binary search. But I'm not sure how to really go about it? This is my current code so far but it only appends the first anagram of the word to anagramList? def binarySearch(arr, lower, upper, target): anagramList=[] if upper &gt;= lower: mid = lower + ((upper - lower) // 2) if areAnagrams(arr[mid],target): anagramList.append(arr[mid]) elif arr[mid] &gt; target: return binarySearch(arr, lower, mid - 1, target) else: return binarySearch(arr, mid + 1, upper, target) return anagramList areAnagrams check if 2 strings are anagrams of each other.
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/51781963
downvote count: 0
has comment: http://stackoverflow.com/comment/90523310
accepted answer of: http://stackoverflow.com/q/51781843
answers question: http://stackoverflow.com/q/51781843
upvote count: 6
type: AcceptedAnswer
has body: The grayscale image has just a single channel and the colour image has 3 or 4 channels (BGR or BGRA). Once you have the pixel coordinates, the pixel value in the grayscale image will be an intensity value or you can get the BGR values from that pixel in the original image. That is, img_gray[y][x] will return an intensity value in the range 0-255, and img_rgb[y][x] will return a list of [B, G, R (, A)] values, each of which will have intensity values in the range 0-255. Thus the value returned when you call e.g. img_gray[10][50] or print(img_gray[10][50]) is the pixel value at x=50, y=10. Similarly the value returned when you call e.g. img_rgb[10][50] is the pixel value at x=50, y=10, but calling it in this way will return the list of pixel values for that location e.g. [93 238 27] for RGB or [93 238 27 255] for RGBA. To get just the B, G or R value you would call img_rgb[10][50][chan] where for chan, B=0, G=1, R=2.
score: 6
type: Answer

http://stackoverflow.com/a/51728297
score: 0
type: AcceptedAnswer
type: Answer
has body: To add a delay of 10 seconds in Powershell, use sleep 10 The correct loop structure as per the requirement would be: for($i=0;$i -le 72;$i++){ python pythonFile.py $arg sleep 10 }
accepted answer of: http://stackoverflow.com/q/51727784
answers question: http://stackoverflow.com/q/51727784

http://stackoverflow.com/a/51797298
answers question: http://stackoverflow.com/q/51797189
downvote count: 0
has comment: http://stackoverflow.com/comment/138879775
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/118569586
score: 112
has comment: http://stackoverflow.com/comment/118320027
type: Answer
has comment: http://stackoverflow.com/comment/117458811
upvote count: 112
accepted answer of: http://stackoverflow.com/q/51797189
has body: From the docs: Uninstalling pyenv The simplicity of pyenv makes it easy to temporarily disable it, or uninstall from the system. To disable Pyenv managing your Python versions, simply remove the pyenv init line from your shell startup configuration. This will remove Pyenv shims directory from PATH, and future invocations like python will execute the system Python version, as before Pyenv. pyenv will still be accessible on the command line, but your Python apps won't be affected by version switching. To completely uninstall pyenv, perform step (1) and then remove its root directory. This will delete all Python versions that were installed under $(pyenv root)/versions/ directory: rm -rf $(pyenv root) If you've installed Pyenv using a package manager, as a final step perform the Pyenv package removal. For instance, for Homebrew: brew uninstall pyenv

http://stackoverflow.com/comment/90551279
type: QuestionComment
score: 0
has text: To make an async call (call an async function) from a sync function running inside the event loop, such as `connection_made`, use `loop.create_task(async_function(args...))`. You won't be able to see the result because `connection_made` must return as soon as possible to allow the event loop to proceed.
type: Comment
comment on: http://stackoverflow.com/q/51778812

seaborn
tags question: http://stackoverflow.com/q/51731351
tags question: http://stackoverflow.com/q/51794136
tags question: http://stackoverflow.com/q/51666784
tag name: seaborn
tags question: http://stackoverflow.com/q/51772467
tags question: http://stackoverflow.com/q/51712916
tags question: http://stackoverflow.com/q/51762938
tags question: http://stackoverflow.com/q/51777034
tags question: http://stackoverflow.com/q/51741963
tags question: http://stackoverflow.com/q/51765493
tags question: http://stackoverflow.com/q/51761786
tags question: http://stackoverflow.com/q/51759859
tags question: http://stackoverflow.com/q/51722468
tags question: http://stackoverflow.com/q/51737946
tags question: http://stackoverflow.com/q/51784529
tags question: http://stackoverflow.com/q/51732867
tags question: http://stackoverflow.com/q/51694935
tags question: http://stackoverflow.com/q/51726599
tags question: http://stackoverflow.com/q/51716063
type: Tag
tags question: http://stackoverflow.com/q/51743690
tags question: http://stackoverflow.com/q/51709697
tags question: http://stackoverflow.com/q/51646249

dictionary
tags question: http://stackoverflow.com/q/51686216
tags question: http://stackoverflow.com/q/51790555
tags question: http://stackoverflow.com/q/51748908
tags question: http://stackoverflow.com/q/51788550
tags question: http://stackoverflow.com/q/51652175
tags question: http://stackoverflow.com/q/51676006
tags question: http://stackoverflow.com/q/51776672
tags question: http://stackoverflow.com/q/51767011
tags question: http://stackoverflow.com/q/51648189
tags question: http://stackoverflow.com/q/51788397
tags question: http://stackoverflow.com/q/51639984
tags question: http://stackoverflow.com/q/51696185
tags question: http://stackoverflow.com/q/51645249
tags question: http://stackoverflow.com/q/51752529
tags question: http://stackoverflow.com/q/51679881
tags question: http://stackoverflow.com/q/51648879
tags question: http://stackoverflow.com/q/51744093
tags question: http://stackoverflow.com/q/51768972
tags question: http://stackoverflow.com/q/51689948
tags question: http://stackoverflow.com/q/51676052
tags question: http://stackoverflow.com/q/51779255
tags question: http://stackoverflow.com/q/51654012
tags question: http://stackoverflow.com/q/51706302
tags question: http://stackoverflow.com/q/51682634
tags question: http://stackoverflow.com/q/51775708
tags question: http://stackoverflow.com/q/51668261
tags question: http://stackoverflow.com/q/51689114
tags question: http://stackoverflow.com/q/51721110
tags question: http://stackoverflow.com/q/51660187
tags question: http://stackoverflow.com/q/51669304
tags question: http://stackoverflow.com/q/51783374
tags question: http://stackoverflow.com/q/51692286
tags question: http://stackoverflow.com/q/51658919
tags question: http://stackoverflow.com/q/51677489
tags question: http://stackoverflow.com/q/51788720
tags question: http://stackoverflow.com/q/51663796
tags question: http://stackoverflow.com/q/51711660
tags question: http://stackoverflow.com/q/51691169
tags question: http://stackoverflow.com/q/51749872
tags question: http://stackoverflow.com/q/51743607
tags question: http://stackoverflow.com/q/51752231
tags question: http://stackoverflow.com/q/51705932
tags question: http://stackoverflow.com/q/51751074
tags question: http://stackoverflow.com/q/51652591
tags question: http://stackoverflow.com/q/51740535
tags question: http://stackoverflow.com/q/51725481
tags question: http://stackoverflow.com/q/51768755
tags question: http://stackoverflow.com/q/51695495
tags question: http://stackoverflow.com/q/51776571
tags question: http://stackoverflow.com/q/51764789
tags question: http://stackoverflow.com/q/51714253
tags question: http://stackoverflow.com/q/51751929
tags question: http://stackoverflow.com/q/51647767
tags question: http://stackoverflow.com/q/51649572
tags question: http://stackoverflow.com/q/51789010
tag name: dictionary
tags question: http://stackoverflow.com/q/51771831
tags question: http://stackoverflow.com/q/51758370
tags question: http://stackoverflow.com/q/51676896
tags question: http://stackoverflow.com/q/51666933
tags question: http://stackoverflow.com/q/51778413
tags question: http://stackoverflow.com/q/51685988
tags question: http://stackoverflow.com/q/51719225
tags question: http://stackoverflow.com/q/51706855
tags question: http://stackoverflow.com/q/51788658
tags question: http://stackoverflow.com/q/51747902
tags question: http://stackoverflow.com/q/51736677
tags question: http://stackoverflow.com/q/51656077
tags question: http://stackoverflow.com/q/51669643
tags question: http://stackoverflow.com/q/51764219
tags question: http://stackoverflow.com/q/51688936
tags question: http://stackoverflow.com/q/51657764
tags question: http://stackoverflow.com/q/51753809
tags question: http://stackoverflow.com/q/51640610
tags question: http://stackoverflow.com/q/51764048
tags question: http://stackoverflow.com/q/51679677
tags question: http://stackoverflow.com/q/51756552
tags question: http://stackoverflow.com/q/51774445
tags question: http://stackoverflow.com/q/51791644
tags question: http://stackoverflow.com/q/51652937

http://stackoverflow.com/q/51783787
upvote count: 2
accepted answer: http://stackoverflow.com/a/51784644
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51784644
has answer: http://stackoverflow.com/a/51784670
answer count: 2
has comment: http://stackoverflow.com/comment/90524849
downvote count: 0
tagged with: button
has body: I am new to tkinter and also rather new to python so I decided to build a "Synthesizer" using tkinter as practice. It's working so far but I can't figure out how to make the keyboard look like an actual piano keyboard, i.e. the black keys are missing. Is there a way to shape buttons in tkinter so i can squeeze the black keys in between or perhaps overlay the black key above the white ones? My code so far: from tkinter import * from functools import partial import pygame pygame.mixer.init() #directory name where sounds are direc='/Users/nol975/Desktop/tiny-piano00/Piano-' listofnames=['A4','A5','D#4','D#5','C1','F#5','C3','C4','C5','C6','F#4'] listofkeys=[direc+x+'.wav' for x in listofnames] def clicked(a): (pygame.mixer.Sound(listofkeys[a]).play()) #**********GUI********** root=Tk() root.title('My cool synth') #keyboard synthframe=Frame(root).pack(side= BOTTOM, anchor='n') for i in range(len(listofnames)): Button(synthframe,text=listofnames[i], command=partial(clicked,i)).pack(side=LEFT, fill=BOTH, expand=1) #Menu bar on top menu = Menu(root) root.config(menu=menu) submenu = Menu(menu) menu.add_cascade(label='File', menu=submenu) submenu.add_command(label='Quit', command=root.destroy) root.mainloop() also, if I my code so far is sloppy I'd appreciate corrections/feedback
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Python 3.x tkinter: Buttons of specific shapes or Button overlay
possible better answer: http://stackoverflow.com/a/51784670
score: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90524768

http://stackoverflow.com/comment/90381071
has text: Why is `"je"` not in the final output? Don't you want to delete _words whose `length == 3` and are `not in not_shortword` list_?
score: 1
comment on: http://stackoverflow.com/q/51709814
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51652093
has body: I am seeking your suggestions for a problem I have suddenly stumbled upon. I am using sci-kit nearest neighbor methods for finding the nearest neighbors. For calculating distance, I am using an user-defined distance function- looked like this: def HVDM(a, b): print("a:", a[0], ",", a[1], ",", a[2], ",", a[3], ",", a[4], ",", a[5], ",", a[6], ",", a[7]) print("b:", b[0], ",", b[1], ",", b[2], ",", b[3], ",", b[4], ",", b[5], ",", b[6], ",", b[7]) return 0 To hold the data I am using pandas dataframe and numpy array. My dataset has eight attributes, that are being passed and the values of the first attribute are just 0,1 and 2. Below I have given some samples from my dataset: [ 0.0 , 0.455 , 0.365 , 0.095 , 0.514 , 0.2245 , 0.10099999999999999 ,0.15] [ 0.0 , 0.35 , 0.265 , 0.09 , 0.2255 , 0.0995 , 0.0485 , 0.07 ] [ 1.0 , 0.53 , 0.42 , 0.135 , 0.677 , 0.2565 , 0.1415 , 0.21 ] [ 0.0 , 0.44 , 0.365 , 0.125 , 0.516 , 0.2155 , 0.114 , 0.155 ] [ 2.0 , 0.33 , 0.255 , 0.08 , 0.205 , 0.0895 , 0.0395 , 0.055 ] Problem is when I tried to see, how these values are passed to the distance function, I have found some mismatch. Especially in case of the first passed parameter "a", where clearly the first attribute is changed but for the second parameter "b"- the first attribute is unchanged. Below I have given some passed samples: a: [ 0.9554704333253531 , 0.5239920995930099 , 0.407881254488869 , 0.1395163993296614 , 0.82874215944458 , 0.35936748862820106 , 0.18059360785252604 , 0.23883085946851795 ] b: [ 2.0 , 0.25 , 0.185 , 0.065 , 0.071 , 0.027000000000000003 , 0.0185 , 0.0225 ] a: [ 0.9554704333253531 , 0.5239920995930099 , 0.407881254488869 , 0.1395163993296614 , 0.82874215944458 , 0.35936748862820106 , 0.18059360785252604 , 0.23883085946851795 ] b: [ 2.0 , 0.2 , 0.145 , 0.05 , 0.036000000000000004 , 0.0125 , 0.008 , 0.011000000000000001 ] a: [ 0.9554704333253531 , 0.5239920995930099 , 0.407881254488869 , 0.1395163993296614 , 0.82874215944458 , 0.35936748862820106 , 0.1805936078…
has comment: http://stackoverflow.com/comment/90267903
has comment: http://stackoverflow.com/comment/90277362
tagged with: pandas
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: knn
has answer: http://stackoverflow.com/a/51655094
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90272236
has comment: http://stackoverflow.com/comment/90276426
tagged with: python
tagged with: nearest-neighbor
downvote count: 2
has title: Sci-kit Learn KNN user-defined distance matric: mis-match between the actual value and the value passed
has comment: http://stackoverflow.com/comment/90268337
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90268870

http://stackoverflow.com/a/51658792
has body: Each token has a number of attributes, you can iterate through the doc to access them. For example: [token.lemma_ for token in doc] If you want to reconstruct the sentence you could use: ' '.join([token.lemma_ for token in doc]) For a full list of token attributes see: https://spacy.io/api/token#attributes
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51658153
score: 7
answers question: http://stackoverflow.com/q/51658153
has comment: http://stackoverflow.com/comment/125837261
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90361785
has comment: http://stackoverflow.com/comment/90281694
type: Answer

http://stackoverflow.com/a/51673006
answers question: http://stackoverflow.com/q/51672709
type: Answer
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/107333920
has comment: http://stackoverflow.com/comment/107328143
upvote count: 8
has body: Just use dict-like to_replace: df['edjefe'].replace({'no': 0, 'yes': 1})

http://stackoverflow.com/q/51702154
has answer: http://stackoverflow.com/a/51743318
upvote count: 1
has comment: http://stackoverflow.com/comment/90422088
type: Question
has title: How to decode the flask response with message pack?
tagged with: msgpack
tagged with: flask
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm using message pack to encode the flask response before sending it to the UI. In order to do that I'm overriding the flask response class from flask import Flask, Response, jsonify, make_response import msgpack import json class FlaskResponse(Response): @classmethod def force_type(cls, rv, environ=None): if isinstance(rv, dict): rv = jsonify(rv) msgData = super(FlaskResponse, cls).force_type(rv, environ) print "msgData" print msgpack.packb(json.loads(msgData.data)) return jsonify((msgpack.packb(json.loads(msgData.data)))) I'm getting the error UnicodeDecodeError: 'utf8' codec can't decode byte 0x83 in position 0: invalid start byte Any suggestion what I'm doing wrong here?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90421781
score: 1

http://stackoverflow.com/comment/90467840
type: Comment
type: QuestionComment
has text: That's what I thought but thanks for confirming!!
comment on: http://stackoverflow.com/q/51716331
score: 0

http://stackoverflow.com/comment/90396231
has text: Possible duplicate of [When would you use reduce() instead of sum()?](https://stackoverflow.com/questions/33772092/when-would-you-use-reduce-instead-of-sum)
score: 0
comment on: http://stackoverflow.com/q/51717509
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90515903
type: Comment
type: QuestionComment
score: 0
has text: Agree with @AChampion The output for me is also `2100.0`
comment on: http://stackoverflow.com/q/51778992

http://stackoverflow.com/q/51709918
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90380973
has body: I am trying to read the text values from the following JSON file. https://www.ted.com//talks/marina_abramovic_an_art_made_of_trust_vulnerability_and_connection/transcript.json?language=en I want to print whatever there is in "text" key. I am trying this code but not getting the results : import json import urllib url = "https://www.ted.com//talks/marina_abramovic_an_art_made_of_trust_vulnerability_and_connection/transcript.json?language=en" response = urllib.urlopen(url) data = json.loads(response.read()) def iterate(data): for key, value in data.items(): if isinstance(value, dict): print(value) iterate(value) continue iterate(data)
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: How to read a particular value ("text") from the following JSON file using Python 2.7?
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51710101
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90381077
accepted answer: http://stackoverflow.com/a/51710101

http://stackoverflow.com/comment/90446018
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51723177
has text: Trying what you suggested, using sf.readfile it seems that something changed, as now dBs look different. Still, they have weird values, as they are all negative. Frequencies did not changed... which is strange, because I reviewed the values in local vars and the frequencies array max val is 8000 https://i.imgur.com/zkruQYh.png

http://stackoverflow.com/q/51722531
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51723787
has title: Pandas bar plot with both categorical and numerical data
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51723787
favorite count: 0
has body: I have a pandas dataframe named 'data' with data similar to the following table. I want to plot them in python as bar plots. Name X Y Z Activity AAA1 0.0 0.0 2.0 Low AAA2 0.0 2.0 6.0 Medium AAA3 1.0 2.0 3.0 High AAA4 2.0 1.0 4.0 High What I tried is, with a bit of setting color and style, sns.set(style="white", context="talk", palette="husl") data.plot.bar(x='Name', width=.8) While this plots a bar diagram showing X, Y, and Z for each Name (9 bars in total), I cannot figure out a way of showing the 'Activity' corresponding to each 'Name' in the bar diagrams. It will be nice if I can somehow show this categorical column graphically, either by color or by some style, on the top of the bar charts. I am using Python 3.7.0 with Pandas 0.23.3, matplotlib 2.2.2, and seaborn version 0.9.0 .
tagged with: python
score: 2

http://stackoverflow.com/comment/90403411
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51700198
has text: @WebQube do you have different license_key in stage?

http://stackoverflow.com/comment/90273218
score: 0
type: Comment
type: QuestionComment
has text: OK, thanks for updating. What JSON Schema do you have so far? `mysql` at the root level is not a valid schema keyword.
comment on: http://stackoverflow.com/q/51650938

http://stackoverflow.com/q/51793856
type: Question
has body: Suppose I have edges between [(1,2),(2,1),(1,3)], how can I remove (1,3) since it is not bidrectional like the edge between 1 and 2?
has title: Networkx: How to remove single direction edges?
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51798664
accepted answer: http://stackoverflow.com/a/51794255
tagged with: python
has answer: http://stackoverflow.com/a/51794255
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51798664
tagged with: networkx

http://stackoverflow.com/a/51722715
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51720962
has body: There's two major problems in your code. The first is that you keep making new widgets every time self.show() or self.menu_changed() is called, the second is that you set the tracing of the variable inside your self.show() function, which is therefore executed many times. I rearranged your code, only creating new widgets and setting the trace in the self.add() function. This way you don't create more widgets than necessary. The only "problem" with this is that I use a StringVar for the Checkbutton/Entry even when you have a Boolean or Integer selected, so all values are converted to strings. I also added a print button to print out all current values. import tkinter as tk import tkinter.ttk as ttk from functools import partial class MyWindow(ttk.Frame): def __init__(self, parent): ttk.Frame.__init__(self, parent) self.lines = [] self.add_button = ttk.Button(self, text="+", command=self.add, width=3) self.print_button = ttk.Button(self, text="Print", command=self.print_values) self.place(x=10, y=10, anchor=tk.NW) self.add() def show(self): for widget in self.children.values(): widget.grid_forget() x = 0 for line in self.lines: line[2].grid(row=x, column=0) if line[0].get() == "bool": line[3].grid(row=x, column=1) else: line[4].grid(row=x, column=1) x += 1 self.add_button.grid(row=x, column=0) self.print_button.grid(row=x, column=1) def add(self): line = [tk.StringVar(value="bool"), tk.StringVar(value="1")] line.append(ttk.OptionMenu(self, line[0], line[0].get(), *["bool", "int", "string"])) line.append(ttk.Checkbutton(self, variable=line[1])) line.append(ttk.Entry(self, textvariable=line[1])) line[0].trace("w", partial(self.menu_changed, line=line)) self.lines.append(line) self.show() def menu_changed(self, *_, line): if line[0].get() == "bool": line[1].set("1") elif line[0].get() == "int": line[1].set("0") elif line[0].get() == "string": line[1].set("") self.show() def print_values(self): print("Current values:") for line in self.lines: print(line[1].get()) root = t…
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51720962

http://stackoverflow.com/comment/90292820
has text: @Patwie I considered this but I'm modifying someone else's code and modifying the graph construction may introduce errors. In my case, putting the loading of data first is easier to do.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51649945
score: 0

http://stackoverflow.com/q/51658206
has body: I'm playing with Python multiprocessing. But it wouldn't work on my system. I ran the example code I found on multiprocessing page. But it just hangs there and the CPU usage is 0%. What do I do to make it work? Thanks a lot! https://docs.python.org/2/library/multiprocessing.html from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': p = Pool(5) print(p.map(f, [1, 2, 3])) update: just tried to run the same code in command line and get the following error message. Error Message
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90280142
linked to: http://stackoverflow.com/q/45719956
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90281033
has comment: http://stackoverflow.com/comment/90280683
has title: Python Multiprocessing wouldn't Work
score: 1
has comment: http://stackoverflow.com/comment/90280127
type: Question
downvote count: 0

http://stackoverflow.com/comment/90274876
has text: Try to find the export button in HTLM and then "click" (()button = browser.find_element_by_name("button") button.click()), https://stackoverflow.com/questions/25415405/downloading-an-excel-file-from-the-web-in-python -this answer and other random things I found in youtube.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51655494
score: 0

http://stackoverflow.com/a/56339403
type: Answer
score: 1
upvote count: 1
has body: For a more complex case where A needs to be divided in sections where only some parts are trainable and others can have arbitrary values, the easiest thing to do would be to build the individual sections and then concatenate them together. For example I needed weight matrix A of arbitrary size that (for size 4x4) looks like this (4 distinct sections of 2x2): # [[0., 0., -0.2, 0.], # [0., 0., 0., -0.2], # [0.35, 0., train, train], # [0., 0.35, train, train]] Code to make this: n_neurons = 3 zero_quarter = tf.zeros((n_neurons, n_neurons)) # upper left quarter are zeros neg_diag = tf.diag(tf.ones(n_neurons) * -0.2) # upper right is negative diag pos_diag = tf.diag(tf.ones(n_neurons) * 0.35) # lower left is positive diag # lower right quarter is trainable randomly initialized vars train_quarter = tf.get_variable(name='TrainableWeights', shape=[n_neurons, n_neurons]) weights_row0 = tf.concat([zero_quarter, neg_diag], axis=1) weights_row1 = tf.concat([pos_diag, train_quarter], axis=1) weights = tf.concat([weights_row0, weights_row1], axis=0) sess = tf.Session() sess.run(tf.global_variables_initializer()) print(sess.run(weights)) And the result is: [[ 0. 0. 0. -0.2 0. 0. ] [ 0. 0. 0. 0. -0.2 0. ] [ 0. 0. 0. 0. 0. -0.2 ] [ 0.35 0. 0. -0.61401606 0.39812732 0.72078323] [ 0. 0.35 0. -0.34560132 0.40494204 0.36660933] [ 0. 0. 0.35 0.34820676 0.5112138 -0.97605824]] where only the bottom right 3x3 section is trainable.
answers question: http://stackoverflow.com/q/51745580
downvote count: 0

http://stackoverflow.com/a/52611617
score: 2
answers question: http://stackoverflow.com/q/51715687
has comment: http://stackoverflow.com/comment/105228366
has comment: http://stackoverflow.com/comment/92377438
accepted answer of: http://stackoverflow.com/q/51715687
type: AcceptedAnswer
downvote count: 0
has body: The PythonInterpreter.initialize() method should only be called once. It is called twice in your program and the second time, sys.argv is not updated. A way around this is to use pyscript.py as a module and call the function defined in the module. Replace interp.execfile("pyscript.py"); with something like this: interp.exec("from pyscript import pyscript"); PyObject func = interp.get("pyscript"); func.__call__(new PyString(start), new PyString(end), new PyString(subject));
type: Answer
has comment: http://stackoverflow.com/comment/105231038
upvote count: 2

http://stackoverflow.com/q/51705464
has answer: http://stackoverflow.com/a/51705573
tagged with: loss-function
possible better answer: http://stackoverflow.com/a/51705559
has answer: http://stackoverflow.com/a/75082681
has answer: http://stackoverflow.com/a/51705559
linked to: http://stackoverflow.com/q/51557383
has title: Keras/Tensorflow: Combined Loss function for single output
downvote count: 0
has comment: http://stackoverflow.com/comment/128502945
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90372335
accepted answer: http://stackoverflow.com/a/51705573
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/62171770
score: 11
linked to: http://stackoverflow.com/q/62861773
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51705576
has comment: http://stackoverflow.com/comment/111214924
tagged with: tensorflow
type: Question
has body: I have only one output for my model, but I would like to combine two different loss functions: def get_model(): # create the model here model = Model(inputs=image, outputs=output) alpha = 0.2 model.compile(loss=[mse, gse], loss_weights=[1-alpha, alpha] , ...) but it complains that I need to have two outputs because I defined two losses: ValueError: When passing a list as loss, it should have one entry per model outputs. The model has 1 outputs, but you passed loss=[&lt;function mse at 0x0000024D7E1FB378&gt;, &lt;function gse at 0x0000024D7E1FB510&gt;] Can I possibly write my final loss function without having to create another loss function (because that would restrict me from changing the alpha outside the loss function)? How do I do something like (1-alpha)*mse + alpha*gse? Update: Both my loss functions are equivalent to the function signature of any builtin keras loss function, takes in y_true and y_pred and gives a tensor back for loss (which can be reduced to a scalar using K.mean()), but I believe, how these loss functions are defined shouldn't affect the answer as long as they return valid losses. def gse(y_true, y_pred): # some tensor operation on y_pred and y_true return K.mean(K.square(y_pred - y_true), axis=-1)

http://stackoverflow.com/q/51694827
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90351141
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51696270
answer count: 1
has comment: http://stackoverflow.com/comment/90351845
linked to: http://stackoverflow.com/q/4700614
has comment: http://stackoverflow.com/comment/90351047
has comment: http://stackoverflow.com/comment/90351158
favorite count: 0
has title: matplotlib nice plot , who knows the scheme used?
tagged with: python
tagged with: color-scheme
has body: May somebody know which is the scheme of color used in this post for the example plot ? this blue magenta, green ? which kind of style it is ?? EDIT ah ok I thought that was a known schemes
upvote count: 2
has comment: http://stackoverflow.com/comment/90351012
accepted answer: http://stackoverflow.com/a/51696270
downvote count: 1
type: Question

http://stackoverflow.com/comment/90517585
type: AnswerComment
type: Comment
has text: Okay but if I append the sorted character to the anagram would it take O(N^2) worst case time complexity?Can it be O(n)?
comment on: http://stackoverflow.com/a/51767125
score: 0

http://stackoverflow.com/q/51691522
tagged with: python
score: 0
answer count: 1
tagged with: numpy
type: UnansweredQuestion
has title: Set the last element equal to the first element in a multidimensional numpy array
has comment: http://stackoverflow.com/comment/90344724
has answer: http://stackoverflow.com/a/51691560
has body: For example I have an array: [[[[1 2][3 4]]][[[1 2][3 4]]]] How would I set 4 equal to 1? I used array[-1][-1][-1][-1] = array[0][0][0][0] but I got an error because of it later on. Is there a more general way of doing this?
has comment: http://stackoverflow.com/comment/90344714
type: Question

http://stackoverflow.com/a/51699812
answers question: http://stackoverflow.com/q/51699767
score: 0
type: Answer
has body: It is hard to answer without a look at the directory from which you are extracting your filenames.One possible reason could be the number of csv files could be less than or equal to the number of json files. If that is the case your zip function wont work as expected. the length of the lists should be equal, else the elements in the longer list is truncated. Could that be the case? a = [1,2,3] b = [1,2] for i in zip(a,b): print(i) #(1, 1) #(2, 2)

loops
tags question: http://stackoverflow.com/q/51741056
tags question: http://stackoverflow.com/q/51688584
tags question: http://stackoverflow.com/q/51774885
tags question: http://stackoverflow.com/q/51640114
tags question: http://stackoverflow.com/q/51765436
tags question: http://stackoverflow.com/q/51710667
tags question: http://stackoverflow.com/q/51762200
tags question: http://stackoverflow.com/q/51719941
tags question: http://stackoverflow.com/q/51784680
tags question: http://stackoverflow.com/q/51721230
tags question: http://stackoverflow.com/q/51644273
tags question: http://stackoverflow.com/q/51678557
tags question: http://stackoverflow.com/q/51724583
tags question: http://stackoverflow.com/q/51713341
tags question: http://stackoverflow.com/q/51655172
tags question: http://stackoverflow.com/q/51686340
type: Tag
tags question: http://stackoverflow.com/q/51775140
tags question: http://stackoverflow.com/q/51737178
tags question: http://stackoverflow.com/q/51758563
tags question: http://stackoverflow.com/q/51728873
tags question: http://stackoverflow.com/q/51727784
tags question: http://stackoverflow.com/q/51651659
tags question: http://stackoverflow.com/q/51757710
tags question: http://stackoverflow.com/q/51741054
tags question: http://stackoverflow.com/q/51707384
tags question: http://stackoverflow.com/q/51717924
tags question: http://stackoverflow.com/q/51681527
tags question: http://stackoverflow.com/q/51772877
tags question: http://stackoverflow.com/q/51642064
tag name: loops
tags question: http://stackoverflow.com/q/51668240
tags question: http://stackoverflow.com/q/51643696
tags question: http://stackoverflow.com/q/51750077
tags question: http://stackoverflow.com/q/51653771
tags question: http://stackoverflow.com/q/51678854
tags question: http://stackoverflow.com/q/51681457
tags question: http://stackoverflow.com/q/51790470
tags question: http://stackoverflow.com/q/51712836
tags question: http://stackoverflow.com/q/51678763
tags question: http://stackoverflow.com/q/51680213
tags question: http://stackoverflow.com/q/51683170
tags question: http://stackoverflow.com/q/51662181
tags question: http://stackoverflow.com/q/51781908
tags question: http://stackoverflow.com/q/51668502
tags question: http://stackoverflow.com/q/51781985
tags question: http://stackoverflow.com/q/51689247
tags question: http://stackoverflow.com/q/51791299
tags question: http://stackoverflow.com/q/51695331
tags question: http://stackoverflow.com/q/51779199
tags question: http://stackoverflow.com/q/51716093

http://stackoverflow.com/q/51780524
answer count: 1
linked to: http://stackoverflow.com/q/20449427
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90518611
has title: What is wrong in below code?
has answer: http://stackoverflow.com/a/51780598
has comment: http://stackoverflow.com/comment/90518791
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/90520666
score: -1
has comment: http://stackoverflow.com/comment/90518582
has comment: http://stackoverflow.com/comment/90518590
has comment: http://stackoverflow.com/comment/90518657
upvote count: 0
has body: Program to find whether the given number is present in given list of numbers in python. What is wrong in below code? It never prints "number is present". import sys a = [1,2,3,4,5,6,7,8] each = 1 s = raw_input("eneter a number ") for each in range(0,len(a)): if s == a[each]: print "number is present" sys.exit() elif each == len(a): print "not present" else: continue

http://stackoverflow.com/q/51660176
tagged with: python
type: AnsweredQuestion
has title: Add ID tags to HTML tags using Python (BeautifulSoup?)
has answer: http://stackoverflow.com/a/51661285
accepted answer: http://stackoverflow.com/a/51661285
type: Question
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has body: I have an HTML file that contains certain tags, and I need to add ID numbers to each tag in the format id="rule_1", id="rule_1.1", id="rule_1.2", id="rule_1.2.1", etc. For example, current HTML is: TEXT TEXT TEXT TEXT I need that HTML to look like this: TEXT TEXT TEXT TEXT I can write these in manually, but I was hoping to use an existing HTML parser library. Is it possible to do with BeautifulSoup, or another module? I tried something like this: from bs4 import BeautifulSoup as html_parser with open('outputs/HTML/{}.html'.format(deal), 'r') as read_file: html_source = read_file.read() soup = html_parser(html_source, 'html.parser') html_tags = soup.find_all(['div', 'p', 'span', 'ul', 'li']) for each_tag in html_tags: each_tag.attrs['id'] = html_tags.index(each_tag) with open('outputs/HTML/{}-id.html'.format(deal), 'w') as save_file: save_file.write(str(soup)) But this just adds id="1", id="2", and so on. How can I have it staggered like 1, 1.1, 1.1.1, and so on?

http://stackoverflow.com/comment/90290085
has text: As I said in the question, my usual advice is to make sure the virtual environment is to activate the virtual environment, then just use `python`. For a Python 3 virtual environment, this will use Python 3. I remember another user having similar problems with `py -3` when following the MDN guide, but I couldn't find the question when I searched for it today. I don't use Python on Windows, so I don't know why `python3` and `py -3` are not working for you, or whether there's a good reason for the MDN guide to recommend `py -3`.
comment on: http://stackoverflow.com/a/51654647
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51642920
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52247825
has title: pygal plotting dates on the x-axis
tagged with: python
has answer: http://stackoverflow.com/a/55971527
score: 2
downvote count: 0
tagged with: pygal
type: AnsweredQuestion
has body: (Note: I am mostly new at Python so my code is more functional than elegant, or so I hope it becomes functional.) Using Python 3.6 and pygal 2 I am attempting to read in json formated data from a storage array's REST API. I want to pull out the latency values (read, write, total) and create a scatter plot showing the values. I started with the pygal docs about plotting dates, here. The timestamps in json are all in epoch milliseconds. So as I read them in, I have to divide to make them work with datetime library. Sample json data section: [ 1532908042508, { "latency.total": 1.09258, "partialBlocksRatio.total": 18.58528, "iops.read": 5984.2, "latency.read": 1.1011, "iops.write": 2181.4, "throughput.read": 1461.03762, "throughput.write": 105.14331, "throughput.total": 1566.18092, "iops.total": 8165.6, "latency.write": 1.06919 } ], My issue is once I get the data is how to feed it into pygal. I start with defining the chart (taken from the pygal doc example) I pull the data, convert the epoch milliseconds to seconds, create the time string to be in the format needed (Y, m, d, H, M, S) and put that list in a list. Next load the latency data into a list. When all the data is loaded, I add to pygal and attempt to render to a file. if key.lower() == 'history': for key2, historyData in value: epochSec = key2 / 1000.0 # The key for each history entry is epoch time in milliseconds. Time functions in Python # appear to want seconds. So the division is needed. timeStamp = [datetime.fromtimestamp(epochSec).strftime('%Y, %m, %d, %H, %M, %S')] # Create the list format used for pygal timeStamps.append(timeStamp) #print(timeStamp) for key3 in historyData: if key3.lower() == 'latency.read': perfHistory.append(historyData[key3]) for stamp in timeStamps: #print(stamp[0]) xy_dateLine.add("", datetime(int(stamp[0])),perfHistory) xy_dateLine.render_to_file('scatter4-1.svc') the error is Traceback (most recent call last): File "C:/Users/../python/XIO_DataPlotting5.py", line 57, in xy_dateL…
tagged with: python-datetime
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/52247825
favorite count: 0
accepted answer: http://stackoverflow.com/a/55971527

http://stackoverflow.com/q/51714942
answer count: 1
favorite count: 0
has body: i want to get specific data from a website. The url of the website is https://www.bullmarketbrokers.com/Cotizaciones/Acciones. I want to get 'P.Compra' value for 'Producto'. I know how to use BeatifulSoup to get the html code. But i don't know how to extract the information.
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51715020
accepted answer: http://stackoverflow.com/a/51715020
has comment: http://stackoverflow.com/comment/90391364
has title: Get specific data from website using python
score: -1
upvote count: 0

http://stackoverflow.com/q/51782085
has comment: http://stackoverflow.com/comment/90521995
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90521909
accepted answer: http://stackoverflow.com/a/51782147
favorite count: 0
type: Question
answer count: 2
tagged with: python
score: 0
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/51783865
has answer: http://stackoverflow.com/a/51782147
has answer: http://stackoverflow.com/a/51783865
has body: I have a pandas data frame of dimensions (7096, 94), each index has a name. I want to reorder the columns with that list of positions/locations : [92, 57, 73, 81, 62, 64, 18, 93, 63, 89, 56, 72, 78, 26, 28, 79, 40, 54, 55, 53, 27, 21, 70, 25, 51, 7, 36, 23, 15, 59, 71, 0, 5, 91, 39, 67, 90, 77, 86, 2, 61, 69, 82, 46, 47, 45, 85, 75, 83, 6, 88, 65, 34, 52, 4, 8, 29, 38, 35, 33, 60, 84, 80, 49, 24, 13, 3, 14, 12, 68, 16, 17, 41, 31, 10, 87, 32, 11, 20, 76, 43, 66, 48, 37, 44, 74, 42, 22, 58, 1, 19, 50, 30, 9]
has title: How to reorder columns according to a list of new positions

http://stackoverflow.com/q/51715931
has title: Installed Docker on Mac but can't find the command
has answer: http://stackoverflow.com/a/51715993
answer count: 2
favorite count: 0
has body: On My mac I ran: pip install docker And it seems successfully: Installing collected packages: websocket-client, docker-pycreds, docker Successfully installed docker-3.4.1 docker-pycreds-0.3.0 websocket-client-0.48.0 However, when I run the 'docker' at the terminal, it can't find it: $ docker -bash: docker: command not found Then I run: $ whereis docker It shows nothing. So how do I get docker to run? Thanks.
has answer: http://stackoverflow.com/a/51715991
tagged with: python
accepted answer: http://stackoverflow.com/a/51715993
upvote count: 11
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51715991
downvote count: 1
has comment: http://stackoverflow.com/comment/127013280
type: Question
score: 10
has comment: http://stackoverflow.com/comment/90393254
has comment: http://stackoverflow.com/comment/90393218
tagged with: docker
linked to: http://stackoverflow.com/q/64009138

http://stackoverflow.com/a/75215157
answers question: http://stackoverflow.com/q/51755722
type: Answer
has body: I was having this issue and in my case it was because the package was being installed as .egg, you can circumvent that installing with pip install -e foo_package
score: 0

http://stackoverflow.com/comment/90556400
has text: The recipe you're using doesn't provide access to the individual elements of the matrix the way you'd like. Look at everything in the recipe's `MatrixTests` as well as the all the examples shown in the "Sample usage": section. The class' own code only accesses entire rows at once, i.e. `ret[x] = row`, which do go through the class' `__setitem__` method. Another way to say this is that the `item` argument passed to `__setitem__()` is an entire row. Also note that the `idx` argument is a row index and each row is simply as list, which have their own `__setitem__` method.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51794208

http://stackoverflow.com/q/51682470
tagged with: machine-learning
type: Question
has body: I have a dataset of reviews which has a class label of positive/negative. I am applying Decision Tree to that reviews dataset. Firstly, I am converting into a Bag of words. Here sorted_data['Text'] is reviews and final_counts is a sparse matrix. I am splitting the data into train and test dataset. X_tr, X_test, y_tr, y_test = cross_validation.train_test_split(sorted_data['Text'], labels, test_size=0.3, random_state=0) # BOW count_vect = CountVectorizer() count_vect.fit(X_tr.values) final_counts = count_vect.transfrom(X_tr.values) applying the Decision Tree algorithm as follows # instantiate learning model k = optimal_k # Applying the vectors of train data on the test data optimal_lambda = 15 final_counts_x_test = count_vect.transform(X_test.values) bow_reg_optimal = DecisionTreeClassifier(max_depth=optimal_lambda,random_state=0) # fitting the model bow_reg_optimal.fit(final_counts, y_tr) # predict the response pred = bow_reg_optimal.predict(final_counts_x_test) # evaluate accuracy acc = accuracy_score(y_test, pred) * 100 print('\nThe accuracy of the Decision Tree for depth = %f is %f%%' % (optimal_lambda, acc)) bow_reg_optimal is a decision tree classifier. Could anyone tell how to get the feature importance using the decision tree classifier?
upvote count: 2
answer count: 1
tagged with: scikit-learn
tagged with: decision-tree
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51682482
accepted answer: http://stackoverflow.com/a/51682482
tagged with: sklearn-pandas
score: 2
has title: How to get feature importance in Decision Tree?
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/51663652
has body: As found in official python docs: group = 'group_user' def my_func(group): set_permission(**{group: 'write'}) # it works like set_permission(group_user='write') print_permission(group) my_func(group) # prints -&gt; 'group_user': 'write' group = 'group_admin' my_func(group) # prints -&gt; 'group_admin': 'write' and 'real life' from models import User, Project import mommy def create_instance_of_repetable_model(model, model_field): mommy.make(model, **{model_field: 'write'})
answers question: http://stackoverflow.com/q/51663651
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90290717

http://stackoverflow.com/comment/90516771
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51756910
has text: The `/path/to/jdk/` should be `/usr/lib/jvm/java-11-openjdk-amd64` in your case. It's the root of JDK installation. `bin/java` is just the path to java executable.

http://stackoverflow.com/comment/90535030
has text: Would you show your _folder_ structure?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51782761
type: Comment

http://stackoverflow.com/comment/90428470
type: Comment
type: QuestionComment
has text: Can you please give an example ?
comment on: http://stackoverflow.com/q/51733315
score: 0

http://stackoverflow.com/q/51674486
has answer: http://stackoverflow.com/a/51674542
type: UnansweredQuestion
tagged with: python
score: 3
has title: Python click module is_flag not working as expected
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90311909
has body: According to click documentation there are two ways to specific a boolean flag. The "on/off" method: @click.option('--shout/--no-shout', default=False) and the "is_flag" method: @click.option('--shout', is_flag=True) I am not getting this behavior. First the code. import click @click.command() @click.option('--one/--no-one', default=False, help='on/off') @click.option('--two', is_flag=False, help='is_flag') def foo(one, two): print(one, two) if __name__ == '__main__': foo() The session below shows that the second option, "two", is a string argument not a boolean flag. $ python foo.py --help Usage: foo.py [OPTIONS] Options: --one / --no-one on/off --two TEXT is_flag --help Show this message and exit. $ python foo.py --two Error: --two option requires an argument $ python foo.py --two a False a $ python foo.py --one True None $ python foo.py --no-one False None Am I using this incorrectly? I am using click 6.7 and: $ python --version Python 3.5.3 :: Anaconda 4.4.0 (x86_64) $ uname -a Darwin tardis 16.7.0 Darwin Kernel Version 16.7.0: Fri Apr 27 17:59:46 PDT 2018; root:xnu-3789.73.13~1/RELEASE_X86_64 x86_64
downvote count: 1
upvote count: 4
favorite count: 0

http://stackoverflow.com/a/51680813
downvote count: 0
upvote count: 2
has body: Use str.split() to split the fields into a list of separate strings. Then convert the list to a tuple: &gt;&gt;&gt; '21345 CSEE 21000 James Frank Smith'.split() ['21345', 'CSEE', '21000', 'James', 'Frank', 'Smith'] &gt;&gt;&gt; t = tuple('21345 CSEE 21000 James Frank Smith'.split()) &gt;&gt;&gt; t ('21345', 'CSEE', '21000', 'James', 'Frank', 'Smith') Now you have a tuple with 6 items. I'm not sure how you will handle splitting of the first name(s) and surname, but this should point you in the right direction.
answers question: http://stackoverflow.com/q/51680727
type: Answer
score: 2

http://stackoverflow.com/q/51690724
has answer: http://stackoverflow.com/a/51690737
tagged with: python
tagged with: list
linked to: http://stackoverflow.com/q/4978787
type: Question
has title: Python: How do I convert each character in a string to a list?
score: 0
answer count: 1
has body: Say I have a string like this: '0123456789' can I convert that into a list like this? ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Thanks in advance! I've been searching for a while, but haven't found precisely what I want, so I asked a question.
tagged with: string
duplicate of: http://stackoverflow.com/q/4978787
has comment: http://stackoverflow.com/comment/90343518
has comment: http://stackoverflow.com/comment/90343234
has comment: http://stackoverflow.com/comment/90343259
has comment: http://stackoverflow.com/comment/90343237
type: UnansweredQuestion

http://stackoverflow.com/comment/90262317
type: AnswerComment
comment on: http://stackoverflow.com/a/51648993
type: Comment
has text: Im trying to retrieve the price with room_id from the data_list which contains thousands of rows. the sample list I shown was 1 row of it
score: 0

http://stackoverflow.com/a/51741039
answers question: http://stackoverflow.com/q/51740051
has body: Put the access or id token obtained from the Cognito user pool in the Authentication header when making an API Gateway request
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/90507381
score: 0
has text: i believe both expanding and rolling will pass the `.values` slice of whatever the index split is
comment on: http://stackoverflow.com/q/51774318
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51645531
tagged with: python
has title: Error displaying video stream using Opencv on raspberry pi
has comment: http://stackoverflow.com/comment/90255047
tagged with: opencv
type: Question
tagged with: raspberry-pi
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/52462621
tagged with: raspberry-pi3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I'm trying to access a live video feed from my Raspberry Pi with a PiCam attached. I have enabled the camera in the interface settings and even tested it by snapping some pictures and videos using the PiCam library. However, OpenCV is giving me troubles. I installed open CV following this tutorial (shoutout to Adrian Rosenbrock). Check out the screenshot below for the code and the error message. I'm running everything from within a virtual environment with OpenCV installed, like Adrian suggests. Code and error message VIDEOIO ERROR: V4L: can't open camera by index 0 From what I've read from other problems people have had, this error is sometimes resolved by playing with the index value. If i change the index value to -1 or 1, like most solutions suggest, i either get the same thing or a slightly different "can't access camera" error. I'm relatively new to OpenCV and RPi so I might just be missing something simple. Any suggestion is much appreciated, thanks!
type: UnansweredQuestion

http://stackoverflow.com/a/51663183
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90289836
has comment: http://stackoverflow.com/comment/90289759
has comment: http://stackoverflow.com/comment/90318254
has comment: http://stackoverflow.com/comment/90290637
has body: If I follow, you just want to turn the array into a list? list(temp) will give you a list
answers question: http://stackoverflow.com/q/51663167
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90318214

http://stackoverflow.com/comment/90379706
comment on: http://stackoverflow.com/a/51697882
score: 0
type: AnswerComment
type: Comment
has text: and with `(?:xlink:href\=\")([^\"]*.jpg)`? : I added `.jpg` because it matched also `<use xlink:href="#f0_f"`... and I don't know if you want to include the `?q=` parts

http://stackoverflow.com/comment/90341661
has text: Do not convert to 1 bit B/W, use grayscale ('L" IINM).
type: QuestionComment
comment on: http://stackoverflow.com/q/51688973
type: Comment
score: 0

http://stackoverflow.com/q/51679581
score: 0
answer count: 2
has body: I'm trying to create a script that will bring up a vpn connection. I modeled my script from this question and it works fine for my purposes but I find that as soon as I close the script the vpn connection is interrupted. When using the "-b" option I get the following at the end of my child.read(): Established DTLS connection (using GnuTLS). Ciphersuite (DTLS0.9)-(RSA)-(AES-256-CBC)-(SHA1).\r\nSSL operation canceled\r\nUser detached from session (SIGHUP); exiting.\r\n' Here is my code: import os, sys, subprocess, time, re, pexpect import signal def signal_handler(sig, frame): print("sigHUUUUUP") sys.exit child = pexpect.spawn('sudo openconnect -b --script /etc/vpnc/vpnc-script remote.host') child.expect('.*') child.sendline('yes') child.expect('.*') child.sendline('ipsec') child.expect('.*') child.sendline('username') child.expect('.*') child.sendline('password') signal.signal(signal.SIGHUP, signal_handler) time.sleep(15) I have a strong preference to remain in python but I'm open to other ways of running openconnect and feeding it the expected passwords. Mainly looking for a way to have the vpn setup without needing to run the script continuously. I've tried using ignore_sighup=True and that doesn't work.
linked to: http://stackoverflow.com/q/35159066
tagged with: python-3.x
tagged with: pexpect
has comment: http://stackoverflow.com/comment/90326247
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90383931
has title: using pexpect and openconnect to bring up a vpn connection
has answer: http://stackoverflow.com/a/51734751
has answer: http://stackoverflow.com/a/79166463
type: Question

http://stackoverflow.com/comment/90292712
comment on: http://stackoverflow.com/q/51664615
has text: Vaguely, this? https://stackoverflow.com/questions/45731683/docker-pull-operation-not-permitted
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51759882
tagged with: python
tagged with: artificial-intelligence
has answer: http://stackoverflow.com/a/51861681
has title: Pytorch Convolutional Layer returning Nan
tagged with: pytorch
score: 0
type: UnansweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/90479304
type: Question
answer count: 1
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90479273
has body: so I am using a convolutional layer as the first layer of a neural network for deep reinforcement learning to get the spatial features out of a simulation I built. The simulation gives different maps that are of different lengths and heights to process. If I understand convolutional networks, this should not matter since the channel size is kept constant. In between the convolutional network and the fully connected layers there is a spatial pyramid pooling layer so that the varying image sizes does not matter. Also the spatial data is pretty sparse. Usually it is able to go through a few states and sometimes a few episodes before the first convolutional layer spits out all Nans. Even when I fix the map size this happens. I do not know where the problem lies, where can the problem lie?
has comment: http://stackoverflow.com/comment/90479200

http://stackoverflow.com/comment/90457621
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51739832
has text: @MadPhysicist your comment isn't useful. care to explain?

http://stackoverflow.com/comment/90458262
comment on: http://stackoverflow.com/a/51749045
type: AnswerComment
score: 0
type: Comment
has text: I appreciate the approach but note that _namedtuples_ are not handled well by the default _json_ serializer (they are serialized as lists, not as dictionaries).

http://stackoverflow.com/comment/90529211
type: QuestionComment
has text: @ZainPatel, the dicts are formed from a product and its variants, because both instances of Finish have the same value, they can be combined into a single entry in the compiled_list
score: 0
comment on: http://stackoverflow.com/q/51785355
type: Comment

http://stackoverflow.com/a/51797896
type: Answer
has body: Check your function call. First parameter you use (train-images) is not defined in your code. Tested version of your code: from __future__ import print_function import os from urllib import request SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' def maybe_download(filename, work_directory): if not os.path.exists(work_directory): os.mkdir(work_directory) filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): filepath, _ = request.urlretrieve(SOURCE_URL + filename, filepath) statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') print(filepath) return filepath #function call maybe_download("train-images-idx3-ubyte.gz","./samples") exit(0) In your case python tries to interpret train-image as variable name. In case you want use it as file name you should wrap it with quotes. Please notice if you use python3 as you specified in tags then fix urlencode imports before usage. Also you can check http://yann.lecun.com/exdb/mnist/train-image with your browser. It returns 404 as train-image does not exists. But there are several zipped archives with training sets. You can check correct URLs via browser: http://yann.lecun.com/exdb/mnist. You can try to use some IDE (like: pycharm) for your development. It highlights some kind of mentioned problems.
has comment: http://stackoverflow.com/comment/90552764
score: 0
accepted answer of: http://stackoverflow.com/q/51797855
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51797855
has comment: http://stackoverflow.com/comment/90552829

http://stackoverflow.com/q/51659551
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51662920
tagged with: javascript
has title: How to use bitwise operators on raw binary data in JavaScript for a CRC check?
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7695450
has body: I'm porting a CRC check function made in Python to JavaScript and I'm struggling a bit. Here is the working Python code: from BitVector import BitVector # BitVector==3.4.8 def compute_crc(message): message = message.deep_copy() generator = BitVector(bitstring='1111111111111010000001001') crc_length = len(generator) - 1 content_length = len(message) - crc_length assert content_length &gt;= 0 for i in range(content_length): if message[i]: message[i:i + len(generator)] ^= generator return message[-crc_length:] adsb_hex = "8D4840D6202CC371C32CE0576098" adsb_crc = compute_crc(BitVector(hexstring = adsb_hex)) if int(adsb_crc) != 0: print 'Bad' else: print 'Good' Here is my (bad) JavaScript code: function BinToDec(binStr) { var regexp = /^[01]+$/ if (!regexp.test(binStr)) { return false; } var result = parseInt(binStr, 2); if (isNaN(result)) { return false; } return result; } function StrToBinArray(binStr) { var result = new Array(); for (var i = 0; i &lt; binStr.length; i++) { result[i] = binStr[i] === '0' ? 0 : 1; } return result; } function TestCRC(adsbBinStr) { var genStr = '1111111111111010000001001'; var generatorInt = BinToDec(genStr); var generator = StrToBinArray(genStr); var crcLength = generator.length - 1; var contentLength = adsbBinStr.length - crcLength; if (contentLength &lt; 0) { return false; } var adsbBin = StrToBinArray(adsbBinStr); for (var i = 0; i &lt;= contentLength; i++) { if (adsbBin[i]) { var currSlice = adsbBin.slice(i, i + generator.length); var currSliceInt = BinToDec(BinArrayToStr(currSlice)); var currCheck = currSliceInt ^ generatorInt; var currCheckBin = currCheck.toString(2); for (var j = 0; j &lt;= currCheckBin.length; j++) { adsbBin[i + j] = currCheckBin[j]; } } } return BinToDec(BinArrayToStr(adsbBin.slice(contentLength + 2))) === 0; } TestCRC('1000110101001000010000001101011000100000001011001100001101110001110000110010110011100000010101110110000010011000'); If it helps here is the CRC check as pseudocode: GENERATOR = 1111111111111010000…
has answer: http://stackoverflow.com/a/51662920
tagged with: crc
tagged with: python
has comment: http://stackoverflow.com/comment/90288786
tagged with: bit-manipulation

http://stackoverflow.com/a/51653363
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Device memory is reserved when you instantiate a tf.Session. If you need to reserve device memory early on, you could start by creating a session, and then proceed normally to construct your graph. Although it is common in "raw" tensorflow to create the graph first then instantiate a session, it is nonetheless allowed to proceed differently, and it is actually common in the Keras world where one would often start a script with import tensorflow as tf sess = tf.Session() from keras import backend as K K.set_session(sess) ...
accepted answer of: http://stackoverflow.com/q/51649945
answers question: http://stackoverflow.com/q/51649945

http://stackoverflow.com/comment/90388609
type: Comment
comment on: http://stackoverflow.com/a/51712094
type: AnswerComment
has text: Thanks for your help !!! But,BogoSort is taking a lot of time.
score: 0

http://stackoverflow.com/q/51790883
tagged with: pandas
has body: I'm new to python. I've looked at previous threads like this and this. I have a Series of dates and times that created this way: tp1=[] for f in files: ### files is the variable that has all the files I need to read in this loop t=f[-19:-5] ### these characters in the filename correspond to the date and time tp1.append(datetime.strptime(t,"%Y%m%d%H%M%S")) time_p1_cr=pd.to_datetime(pd.Series(tp1), format='%Y-%m-%d %H:%M:%S') tp1 looks like: [datetime.datetime(2018, 8, 1, 16, 6, 39), datetime.datetime(2018, 8, 2, 17, 16, 37), datetime.datetime(2018, 8, 3, 10, 53, 46), datetime.datetime(2018, 8, 3, 17, 14, 39), datetime.datetime(2018, 8, 4, 11, 21, 36), datetime.datetime(2018, 8, 4, 17, 27, 54), and so on. time_p1_cr looks like : 0 2018-08-01 16:06:39 1 2018-08-02 17:16:37 2 2018-08-03 10:53:46 3 2018-08-03 17:14:39 and so on. I need to find the successive differences between the elements of the list. I basically need the time difference. I can't do t2=tp1[1:] t3=tp1[:-1] t4=t3-t2 because t2, and t3 are lists and I can't subtract lists. So, I tried test1=time_p1_cr[1:] test2=time_p1_cr[:-1] test3=test1.subtract(test2) according to this. But test3 turns out to be test3 0 NaT 1 0 days 2 0 days 3 0 days 4 0 days 5 0 days 6 0 days 7 0 days and so on. How can I get the time difference between the successive elements?
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51790933
tagged with: datetime
linked to: http://stackoverflow.com/q/34428678
tagged with: python
linked to: http://stackoverflow.com/q/35878175
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
has title: Finding datetime difference between lists in python
type: Question
has answer: http://stackoverflow.com/a/51790933

http://stackoverflow.com/a/67078185
type: Answer
answers question: http://stackoverflow.com/q/51661560
has body: You might already find your answer, but to others who stumble upon this thread: Try this, no need to import typing: dict[dict] it will be displayed in docstring as: Dict[dict] In the case of your example: def do_somthing(dict_of_dicts): &quot;&quot;&quot; :type dict_of_dicts: dict[Any, dict] &quot;&quot;&quot; for key, value in dict_of_dicts.items(): for key2, value2 in value.items(): print('Key')
score: 0

http://stackoverflow.com/q/51733152
has answer: http://stackoverflow.com/a/51750741
has comment: http://stackoverflow.com/comment/90427101
has comment: http://stackoverflow.com/comment/90427448
score: 2
type: AnsweredQuestion
tagged with: sql
downvote count: 0
has comment: http://stackoverflow.com/comment/90456235
has comment: http://stackoverflow.com/comment/90428357
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: postgresql
has body: I'm trying to download a JSON file from a Postgres Server on R Studio, however, the fromJSON() method from the rjsonio package only works when the file is 1) on a local directory or 2) on a URL. Does anyone know a way to perform this on R Studio or on Python?
accepted answer: http://stackoverflow.com/a/51750741
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90461208
upvote count: 2
linked to: http://stackoverflow.com/q/5963269
has comment: http://stackoverflow.com/comment/90426988
answer count: 1
has comment: http://stackoverflow.com/comment/90429695
has title: Downloading JSON file from Postgres Server on R Studio

http://stackoverflow.com/q/51664732
tagged with: python-3.x
has body: I am just a beginner at Python. I am trying to scrape data from a site and have managed to write the below code. However, I am not sure how to proceed ahead as I am unable to get the href tags so that I can go to each listing &amp; get the data. I am also not very well aware of HTML Tags, so I suspect that I have not identified the tags properly. Here is my code : import requests from bs4 import BeautifulSoup urls = [] for i in range(1,5): pages = "https://directory.singaporefintech.org/?p={0}&amp;category=0&amp;zoom=15&amp;is_mile=0&amp;directory_radius=0&amp;view=list&amp;hide_searchbox=0&amp;hide_nav=0&amp;hide_nav_views=0&amp;hide_pager=0&amp;featured_only=0&amp;feature=1&amp;perpage=20&amp;sort=random".format(i) urls.append(pages) Data = [] for info in urls: page = requests.get(info) soup = BeautifulSoup(page.content, 'html.parser') links = soup.find_all('a', attrs ={'class' :'sabai-directory-title'}) hrefs = [link['href'] for link in links] The above code is producing hrefs as a blank list. Any help would be highly appreciated!! Thanks!!!
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/51669799
has title: Web Scraping through Python BeautifulSoup
type: Question
score: 1
answer count: 3
has answer: http://stackoverflow.com/a/51664851
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has answer: http://stackoverflow.com/a/51664993

http://stackoverflow.com/a/51758424
answers question: http://stackoverflow.com/q/51758370
has comment: http://stackoverflow.com/comment/90476140
type: Answer
has comment: http://stackoverflow.com/comment/90476148
has comment: http://stackoverflow.com/comment/90479178
has comment: http://stackoverflow.com/comment/90476513
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90476167
has comment: http://stackoverflow.com/comment/90476248
has comment: http://stackoverflow.com/comment/90478420
has body: First, yes, strings don't have an append method. You can see a list of all the methods in the docs, or by typing help(str) in the interactive interpreter, or even just printing out dir(str). The reason strings don't have an append method is that they're immutable—you cannot change a string value. You can only create a brand-new string value, e.g., by adding two strings together: &gt;&gt;&gt; 'abc' + 'def' 'abcdef' However, you can still use augmented assignment on a variable or other target holding a string value: &gt;&gt;&gt; s = 'abc' &gt;&gt;&gt; s += 'def' 'abcdef' This doesn't change the value 'abc', it makes a brand-new 'abcdef' value and assigns that to s. But that's fine for you. So, if you want to update a dict value that's a string, you can do the same: &gt;&gt;&gt; d = {'abc': 'def'} &gt;&gt;&gt; d['abc'] += 'ghi' &gt;&gt;&gt; d {'abc': 'defghi'} But really, you don't seem to want to append to a string in the first place; what you want is to have a dict with lists of strings for the values. So, just create it that way in the first place: files = { 'Input.txt': ['Randy'], 'Code.py': ['Stan'], 'Output.txt': ['Randy'] } … and now the rest of your code will work. Or, maybe, you wanted files to be a dict with (single) string values, and only final to be a dict with lists of string values. In that case, instead of this: final.update({files.get(j):i}) … do this: final.update({files.get(j): [i]}) Since I can't figure out what your code is intended to do, I don't know which fix you want. But I do know that, if you want to append to the values in final, those values have to be lists (of strings), not strings. Meanwhile, this line of code is overcomplicated for no obvious reason: final.update({files.get(j):i}) If you just want to replace a value in a dict, just assign to it: final[files.get(j)] = i Or, since it seems like you're expecting j will always be in files, why are you even using get? final[files[j]] = i Finally, you have at least one other major problem: on…
has comment: http://stackoverflow.com/comment/90476184
has comment: http://stackoverflow.com/comment/90479590
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90478464
accepted answer of: http://stackoverflow.com/q/51758370
has comment: http://stackoverflow.com/comment/90476413
has comment: http://stackoverflow.com/comment/90476217

http://stackoverflow.com/a/51642994
score: 0
type: Answer
has body: You can use requests and bs4 libraries to scrap a website. For example: a) I will count how many links are in a site: b) i will extract href value for each link import requests, bs4 my_request = requests.get('https://www.bellezaculichi.com') # request one page my_request.raise_for_status() # check for error my_html = bs4.BeautifulSoup(my_request.text) # parse site my_links = my_html.select('a') #stores all links in list my_links total_links = len(my_links) # how many links do i found print(total_links) # show how many links for i in range(total_links): my_links[i]["href"] With bs4 you can count any element in a web page. You can count how many divs, p or a With bs4 you can count any element by ID in a web page. With bs4 you can count any element by CLASS in a web page. With bs4 you can count any element by ATTRIBUTE in a web page.
answers question: http://stackoverflow.com/q/51642133

http://stackoverflow.com/q/51685988
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90333953
has body: I have a dictionary that has dataframes in values, something like this - dict = {'demand': demand_df, 'supply':supply_df, 'prod': prod_df} then, I have a list like this - list = ['demand', 'supply', 'prod'] I want to create individual dataframes objects using a loop, resulting in below - demand = demand_df supply = supply_df prod = prod_df My try - for i in list: i = dict[i] This obviously is giving an error. How do I correct it?
linked to: http://stackoverflow.com/q/18837262
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51689040
has comment: http://stackoverflow.com/comment/90333961
has comment: http://stackoverflow.com/comment/90334219
type: Question
has comment: http://stackoverflow.com/comment/90334030
has comment: http://stackoverflow.com/comment/90334089
linked to: http://stackoverflow.com/q/51686216
linked to: http://stackoverflow.com/q/1933451
tagged with: pandas
has title: Creating dataframe objects from a dictionary using 'for' loop
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90334061
type: UnansweredQuestion

http://stackoverflow.com/q/51780513
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: plot
tagged with: binning
score: 1
tagged with: matplotlib
type: Question
has body: I have 3 data matrices that I am trying to plot in the same figure. My code to do this is below, and I had to make the dataframes quite long in order to show the issue more clearly: import numpy as np import pandas as pd import matplotlib.pyplot as plt profile_features = ['Col1'] question_features = ['Col2'] fig = plt.figure(figsize=(10,5)) count = 1 for pf in profile_features: for qf in question_features: data1 = pd.DataFrame(columns=['Col1', 'Col2']) data1['Col1'] = [0, 2, 1, 1, -1, 0, -2, 0, 0, 0, 0, -2, 0, 0, 0, 0, 1, -1, 1, 0, 1, -1, 1, 0, -1, 1, 2, 1, -2, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 1, 0, 0, -1, -1, -1, -2, 1, -2, -1, 0, 0, -2, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, -2, 1, -1, 0, 1, -1, 0, 0, 1, -1, 0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 2, 0, 0, 0, -2, 2, -1, 1, -2, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -2, -1, 0, -1, 0, 1, -1, -1, -2, 0, -2, 0, 1, 0, -1, 1, 0, 0, 0, -2, -1, -2, -2, 0, 0, 1, 0, 0, 0, 1, 0, 0, -2, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 1, 1, 0, 1, -1, -1, 0, 0, 0, 0, -2, 1, 1, 0, 0, 0, 0, 0, 0, 2, 1, 1, 0, 2, -1, -2, 0, 0, 0, 1, 0, 1, 0, 0, -1, 0, 0, 1, 1, 0, -2, 0, 1, -1, -2, 0, 1, 0, 1, 0, 0, 1, -1, 0, 0, 0, 0, 2, 0, 0, 1, 0, 1, 1, 1, 1, -2, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, -2, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, -2, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, -2, 0, 0, 0, 0, -1, 1, -2, 1, 0, -1, 0, 0, -2, 2, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 2, -2, -1, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, -2, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, -2, -2, 0, 1, -1, 0, 0, 1, 0, 1, -2, 0, 0, 0, -1, 0, 0, 0, -2, 0, -2, 0, -1, 0, 1, 1, -2, 1, 0, -2, 0, 0, 1, -2, -1, -2, -1, 0, 0, 1, 0, -1, 0, 0, 0, -2, -2, -1, 0, 0, -1, -1, 0, 1, -2, 0, 1, 0, 0, 0, 0, 0, -1, 1, 0, 0, -1, 0, 1, 0, 0, 0, 2, -1, 0, -1, -1, -1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 1, 0, 1, 0, 2, -2, 2, 2, -2,…
upvote count: 1
downvote count: 0
has title: How do I make the x-axis consistent when plotting multiple subplots in the same figure in matplotlib (or seaborn)?
favorite count: 0

http://stackoverflow.com/comment/90298378
type: Comment
type: QuestionComment
has text: @Miki I also assumed this was the case, however when printing the values of the array they all happened to be in the range of 0.0 to 90.0.
comment on: http://stackoverflow.com/q/51667520
score: 0

http://stackoverflow.com/q/51702078
tagged with: django
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/90365697
score: 2
has title: Can not run unit test from PyCharm in Django project
type: Question
downvote count: 0
has body: Whenever I try to test some existing (and working) unit tests in my Django project with PyCharm pro, I get the following error: File "/home/user/pycharm-2018.2/helpers/pycharm/django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) TypeError: run_tests() takes exactly 2 arguments (12 given) The way unit tests are executed seems to be hardcoded in PyCharm helpers. The project is based on Django 1.9. Could that explain the incompatibility of the test runner? Or did I miss something in setup?
tagged with: python
favorite count: 0
answer count: 0
tagged with: pycharm
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/90397236
has text: Hmm interesting. Maybe try `pip freeze` and `conda list` to see what you have in respective Python? Pandas should be installed when you installed Anaconda.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51700206

http://stackoverflow.com/q/51668283
tagged with: python
has answer: http://stackoverflow.com/a/51668319
accepted answer: http://stackoverflow.com/a/51668319
type: AnsweredQuestion
type: Question
tagged with: urllib
has body: I am having trouble getting the output. I am getting unordered sentences as output and I need them alphabetically sorted. import sys import os from urllib.request import Request from urllib.request import urlopen from urllib.error import URLError import json def getMovieTitles(variable): # variable = raw_input() var = str(variable) for i in range(0, 10): page = str(1) url = "https://jsonmock.hackerrank.com/api/movies/search/?Title=%s&amp;page=%s" % (var, page) # while(int(page)&lt;int(page)+1): response = urlopen(url).read().decode('UTF-8') data = json.loads(response) # response2 = urllib2.urlopen(url2) # data = json.loads(response.content.decode('utf-8')) # data = json.loads(response.json()) print (data['data'][i]['Title']) for i in range(0,3): page = str(2) url = "https://jsonmock.hackerrank.com/api/movies/search/?Title=%s&amp;page=%s" % (var, page) # while(int(page)&lt;int(page)+1): response = urlopen(url).read().decode('UTF-8') data = json.loads(response) print (data['data'][i]['Title']) # print data2['data'][i]['Title'] getMovieTitles("spiderman") #output: Italian Spiderman Superman, Spiderman or Batman Spiderman Spiderman Fighting, Flying and Driving: The Stunts of Spiderman 3 Spiderman and Grandma The Amazing Spiderman T4 Premiere Special Amazing Spiderman Syndrome Hollywood's Master Storytellers: Spiderman Live Spiderman 5 They Call Me Spiderman The Death of Spiderman Spiderman in Cannes #ouput required: Amazin Spiderman Syndrome Fighting, Flying and Driving: The Stunts of Spiderman 3 Hollywood's Master Storytellers: Spiderman Live ....... and so on NOTICE THE FIRST LETTER IN OUTPUT REQUIRED SECTION as its alphabetically ordered
score: 0
answer count: 1
has title: how to print sorted multiple sentences alphabetically in python?
has comment: http://stackoverflow.com/comment/90299710

fedora
tags question: http://stackoverflow.com/q/51694562
tag name: fedora
type: Tag

http://stackoverflow.com/q/51691363
tagged with: asterisk
has body: I'm trying to run these lines of code in atom and python3.6 : from pycall import CallFile, Call, Application import sys def call(): c = Call('SIP/200') a = Application('Playback', 'hello-world') cf = CallFile(c, a) cf.spool() if __name__ == '__main__': call() But I receive this error: Traceback (most recent call last): File "/home/pd/gits/voiphone/main.py", line 12, in &lt;module&gt; call() File "/home/pd/gits/voiphone/main.py", line 9, in call cf.spool() File "/home/pd/telephonerelayEnv/lib/python3.6/site-packages/pycall/callfile.py", line 135, in spool self.writefile() File "/home/pd/telephonerelayEnv/lib/python3.6/site-packages/pycall/callfile.py", line 123, in writefile f.write(self.contents) File "/home/pd/telephonerelayEnv/lib/python3.6/site-packages/pycall/callfile.py", line 118, in contents return '\n'.join(self.buildfile()) File "/home/pd/telephonerelayEnv/lib/python3.6/site-packages/pycall/callfile.py", line 100, in buildfile raise ValidationError pycall.errors.ValidationError I would appreciate if you help me solving my problem. thank you in advance
tagged with: pycall
has answer: http://stackoverflow.com/a/51828146
tagged with: voip
tagged with: python-sip
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has title: Pycall throws ValidationError
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51828146
tagged with: python
answer count: 1

http://stackoverflow.com/q/51658697
score: 1
has answer: http://stackoverflow.com/a/51658750
tagged with: python-2.7
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/37980821
tagged with: string
has comment: http://stackoverflow.com/comment/90280977
favorite count: 0
tagged with: python
has body: when executing the command in python str="BANANA" print(str.count("ANA")) give answer as 1. but real answer would be 2. how to solve this
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/37980821
type: Question
has title: getting error while using count in string "BANANA" to find "ANA" as substring using str.count() inbuild function of python

http://stackoverflow.com/comment/90280274
type: AnswerComment
type: Comment
has text: For `state_info = defaultdict(list)` is `list` suppose to be `county_list`? It throws a `TypeError: first argument must be callable or None` error otherwise.
comment on: http://stackoverflow.com/a/51658027
score: 0

http://stackoverflow.com/q/51706714
tagged with: gradient-descent
type: UnansweredQuestion
tagged with: python
tagged with: linear-regression
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/51707861
has comment: http://stackoverflow.com/comment/90375987
score: 0
answer count: 1
has body: X_train is already normalized using StandardScaler() and also the categorical columns have been converted into one hot encodings. X_train.shape=(32000, 37) I am using the following code to compute the value of w using gradient descent w = np.zeros(len(X_train.columns)) learning_rate = 0.001 for t in range(1000): Yhat = X.dot(w) delta = Yhat - Y_train w = w - learning_rate*X_train.T.dot(delta) My w vector blows up (i.e. increases very fast) and and every entry of w becomes NaN. I tried reducing the number of epochs to 10, 15, 20, etc., and what I found is every element of w is diverging instead of converging. I tried using normal equations and the w is indeed coming up fine in that case (line breaks added for readability): w_found_using_normal_eqns = [ 3.53175449e-14 1.27924991e-14 -5.42441539e-14 9.91098366e-16 -2.31752259e-14 -6.21205773e-13 1.66139358e-13 2.72739782e-13 -1.65076881e-13 -1.25280166e-14 -1.98905983e-14 3.78837632e-13 -1.39424696e-12 -6.48511452e-15 1.58136412e-14 1.39778439e-12 -1.06142667e-14 3.00624557e-14 -1.70159700e-15 -6.91500349e-15 -4.04842208e-15 2.37516654e-16 3.25211677e+01 -2.86074823e+01 -2.86074823e+01 -2.86074823e+01 -2.86074823e+01 -2.86074823e+01 -2.86074823e+01 -2.86074823e+01 3.55024823e+01 3.55024823e+01 3.55024823e+01 3.55024823e+01 3.55024823e+01 3.55024823e+01 3.55024823e+01] The r^2 error is 1 if I use normal equations to solve for w.
has title: What is wrong with this gradient descent algorithm?

http://stackoverflow.com/comment/90289836
has text: Without knowing what `data` looks like, this question is ambiguous as it is. For all we know, data is a collection of 4 values and `data[3]` is just a simple integer or otherwise that is being appended to `temp`. Until more details are added/terminology corrected, this is somewhat of a toss up
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51663183
type: Comment

http://stackoverflow.com/a/51654453
answers question: http://stackoverflow.com/q/51653316
has comment: http://stackoverflow.com/comment/90280882
has comment: http://stackoverflow.com/comment/90279971
score: 0
has body: There is a comment sign in front of ssl = on in your file, so the default value ssl = off is used. To enable SSL, you need a certificate and a key as well, see the documentation.
has comment: http://stackoverflow.com/comment/90279959
has comment: http://stackoverflow.com/comment/90279562
has comment: http://stackoverflow.com/comment/90273034
type: Answer
has comment: http://stackoverflow.com/comment/90279535
has comment: http://stackoverflow.com/comment/90279715
has comment: http://stackoverflow.com/comment/90295831

pygobject
type: Tag
tags question: http://stackoverflow.com/q/51731082
tags question: http://stackoverflow.com/q/51640478
tag name: pygobject

http://stackoverflow.com/q/51743933
upvote count: 1
has answer: http://stackoverflow.com/a/69526706
type: Question
has body: I have implemented an OPC UA Client in Python by accessing Anonymously to the OPC UA Server, But now when it comes to the encryption I founded out that Python OPC UA Package don't support/allow Basic 256sha256 in which OPC Foundation finds the others Obsolete or no longer considered secure. https://opcfoundation.org/UA/SecurityPolicy/#Basic256 http://documentation.unified-automation.com/uasdkhp/1.0.0/html/_l2_ua_discovery_connect.html I am using this packages: from opcua import Client from opcua import ua in which the connection doesn't allow its security policy... client.set_security_string("Basic256Sha256,SignAndEncrypt,certificate-example.der,private-key-example.pem") Does anyone knows any other way to implementwith PYTHON an OPC UA Client with Basic256Sha256 Security Policy since on the links before it says that the others are no longer considered secure (Basic128Rsa15) or used.
has title: Python OPC UA Client Security Policy (basic 256sha256)?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: client-certificates
tagged with: protocols
type: UnansweredQuestion
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/107965374
tagged with: opc-ua
score: 1

http://stackoverflow.com/comment/90490872
type: Comment
score: 1
has text: It seems like there is no 1:1 substitute
type: AnswerComment
comment on: http://stackoverflow.com/a/51765707

http://stackoverflow.com/comment/90395492
score: 0
type: Comment
has text: Looks like an overkill for something as simple as: `kwargs['syle'] = kwargs['style'] | wx.BORDER_NONE if 'style' in kwargs else wx.BORDER_NONE` before passing to the `super().__init__(..)`. Or may be I'm missing something
comment on: http://stackoverflow.com/a/51717070
type: AnswerComment

http://stackoverflow.com/a/51751514
has body: It works as expected if I close using the cross in the top right, but not if I close with my function that calls .destroy() , can anyone explain to me why this isn't working as intended? Perhaps I have missed something ? loginMaster.protocol("WM_DELETE_WINDOW", self.checkLogin) only tells tkinter what to do when the window manager destroys the window. When you call some function which calls destroy(), that doesn't involve the window manager and therefore your callback is not called. If you want something to happen when the window is destroyed, you should bind to the &lt;Destroy&gt; event.
has comment: http://stackoverflow.com/comment/112711214
answers question: http://stackoverflow.com/q/51749757
has comment: http://stackoverflow.com/comment/90464694
accepted answer of: http://stackoverflow.com/q/51749757
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90464752
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51707681
has body: I'm trying to compile my script into an exe file using PyInstaller, but I get the error ImportError with no details or specifics. Just ImportError. The following is the entire terminal output C:\Users\vk2458\AppData\Local\Continuum\anaconda3\Scripts&gt;pyinstaller C:\Users\vk2458\PycharmProjects\untitled\Excelmagic.py 101 INFO: PyInstaller: 3.1 101 INFO: Python: 3.5.5 102 INFO: Platform: Windows-7-6.1.7601-SP1 105 INFO: wrote C:\Users\vk2458\AppData\Local\Continuum\anaconda3\Scripts\Excelmagic.spec 108 INFO: UPX is not available. 111 INFO: Extending PYTHONPATH with paths ['C:\\Users\\vk2458\\PycharmProjects\\untitled', 'C:\\Users\\vk2458\\AppData\\Local\\Continuum\\anaconda3\\Scripts'] 111 INFO: checking Analysis 111 INFO: Building Analysis because out00-Analysis.toc is non existent 111 INFO: Initializing module dependency graph... 116 INFO: Initializing module graph hooks... 121 INFO: Analyzing base_library.zip ... 5046 INFO: running Analysis out00-Analysis.toc 5049 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\users\vk2458\appdata\local\continuum\anaconda3\python.exe 5559 INFO: Analyzing C:\Users\vk2458\PycharmProjects\untitled\Excelmagic.py 6190 INFO: Processing pre-find module path hook distutils 7421 INFO: Processing pre-safe import module hook six.moves 11625 INFO: Processing pre-find module path hook site 11626 INFO: site: retargeting to fake-dir 'c:\\users\\vk2458\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\PyInstaller\\fake-modules' 69940 INFO: Processing pre-safe import module hook win32com 118851 INFO: Looking for import hooks ... 118855 INFO: Processing hook hook-scipy.sparse.csgraph.py 118858 INFO: Processing hook hook-sqlite3.py 118864 INFO: Processing hook hook-win32com.py 119122 INFO: Processing hook hook-IPython.py 126273 INFO: Processing hook hook-scipy.special._ufuncs.py 126274 INFO: Processing hook hook-pycparser.py 126519 INFO: Processing hook hook-PyQt5.QtSvg.py 126520 I…
type: Question
has title: Pyinstaller ImportError without no details when compiling
has comment: http://stackoverflow.com/comment/90376588
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90376237
favorite count: 0
tagged with: python-3.x
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51709469
tagged with: pyqt5

http://stackoverflow.com/comment/90818737
comment on: http://stackoverflow.com/a/51927483
type: Comment
has text: Both. Looks like you installed Python to some custom directory. I prefer to install it to a folder like: `C:\Python36\`. So every time I see where all versions are and able to uninstall it. And preferable way is to use mostly python from virtualenv, not root.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90550578
type: AnswerComment
score: 0
has text: @DYZ Which statement do you mean?
type: Comment
comment on: http://stackoverflow.com/a/51788983

http://stackoverflow.com/comment/90416088
has text: Why don't you use `answer = [list_1[0]]*4 + [list_1[1]]*4 `
type: Comment
comment on: http://stackoverflow.com/q/51727255
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90438143
score: 0
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177606/discussion-between-nazar-khan-and-durjoy).
type: Comment
comment on: http://stackoverflow.com/q/51738554

http://stackoverflow.com/q/51692037
downvote count: 0
favorite count: 0
tagged with: python-3.7
tagged with: python
has body: I want to put an image in the second window using tkinter, in the first window the code works good, but the second window shows nothing. In this part I import necessary modules: from tkinter import filedialog, Tk, Frame, Label, PhotoImage, Button from PIL import Image from tkinter import* import tkinter as tk Then create the principal window: raiz = Tk() raiz.title("ventana") Then I create the frame and put the image in the frame: miFrame = Frame() miFrame.pack() miFrame.config(width="1400", heigh=("1200")) fondo=tk.PhotoImage(file="fondoF.png") fondo=fondo.subsample(1,1) label=tk.Label(miFrame,image=fondo) label.place(x=0,y=0,relwidth=1.0,relheight=1.0) Then a button that will call the second window function: btn3 = Button(raiz, text="boton") btn3.place(x=500, y=500) btn3.config(command=abrirventana2) Here we have the function which opens the second window and here (I guess) is where I want to put the image. This part also has two buttons named mih which does nothing in the meantime and ok which calls the function to close the second window: def abrirventana2(): raiz.deiconify() ventana2=tk.Toplevel() ventana2.geometry('500x500') ventana2.title("ventana2") ventana2.configure(background="white") fondov=tk.PhotoImage(file="xxx.gif") label1=tk.Label(ventana2,image=fondov) label1.place(x=50,y=50,relwidth=5.0,relheight=5.0) mensaje=tk.Label(ventana2,text="funciona") mensaje.pack(padx=5,pady=5,ipadx=5,ipady=5,fill=tk.X) boton1=tk.Button(ventana2,text='mih') boton1.pack(side=tk.TOP) boton2=tk.Button(ventana2,text='ok',command=ventana2.destroy) boton2.pack(side=tk.TOP) Function to close the second window: def cerrarventana2(): ventana.destroy() I use the mainloop to keep the window open raiz.mainloop() Note: I had already tried creating a frame in the second window, but it didn't work.
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
type: Question
has title: How to put image in another window in tkinter?
score: 1
has answer: http://stackoverflow.com/a/51694319
tagged with: image
answer count: 1

http://stackoverflow.com/a/51724187
score: 0
has body: I think your current solution is better than coming up with a function each time. It is a good solution. Here is a generic solution for a generic key. You'd make your version using the Cipher.random_range method I've stuck on. import random class Cipher: def __init__(self, key): """ key is a dict of unique values (i.e. bijection) """ if len(set(key.values())) != len(key): raise ValueError('key values are not unique') self._encoder = key.copy() self._decoder = {v: k for k, v in key.items()} @classmethod def random_range(cls, max): lst = list(range(max)) random.shuffle(lst) return cls(dict(enumerate(lst))) def encode(self, num): return self._encoder[num] def decode(self, num): return self._decoder[num]
answers question: http://stackoverflow.com/q/51723241
type: Answer

http://stackoverflow.com/q/51721956
has comment: http://stackoverflow.com/comment/90440238
type: Question
has comment: http://stackoverflow.com/comment/90440220
has title: python3.6 PEXPECT is not writing logs to a logfile
has answer: http://stackoverflow.com/a/51723415
tagged with: pexpect
score: 0
has comment: http://stackoverflow.com/comment/90440199
answer count: 1
has body: I am trying to log pexpect logs to a file. The code was working in python2.7 but logs not getting printed in python3.6 import pexpect child = pexpect.spawn("telnet IP") fout = open("abc.txt", "wb"): child.logfile = fout child.sendlines("somecommand)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90440215
tagged with: python

http://stackoverflow.com/q/51788422
downvote count: 0
has comment: http://stackoverflow.com/comment/90534494
possible better answer: http://stackoverflow.com/a/51788711
has comment: http://stackoverflow.com/comment/90534348
favorite count: 0
has answer: http://stackoverflow.com/a/51788711
answer count: 3
has comment: http://stackoverflow.com/comment/90547867
has answer: http://stackoverflow.com/a/51788651
has comment: http://stackoverflow.com/comment/90534369
has comment: http://stackoverflow.com/comment/90534451
has comment: http://stackoverflow.com/comment/90534321
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90534198
accepted answer: http://stackoverflow.com/a/51788651
type: AnsweredQuestion
score: 3
has body: Consider the following zone definitions for a value x: 'A' : x &lt; 1 'B' : 1 &lt;= x &lt; 10 'C' : 10 &lt;= x &lt; 112 'D' : 112 &lt;= x I am looking for an efficient way to determine the zone for given values of x. I came up with: borders = (1, 10, 112) tst_values = (.2, 2, 22, 222) for x in tst_values: z = next((i for b, i in zip(borders, 'ABC') if x &lt; b), 'D') print(f" * Value {x:3g} is in zone '{z}'.") # The output is: # * Value 0.2 is in zone 'A'. # * Value 2 is in zone 'B'. # * Value 22 is in zone 'C'. # * Value 222 is in zone 'D'. What are the best practices for solving such a problem, especially if the number of zones, i.e., len(borders) is large. borders may contain an arbitrary list of (increasing) floats. Update Rephrased question a little bit to address comments.
type: Question
tagged with: numpy
has title: How to efficiently determine the interval a given value is in?
has answer: http://stackoverflow.com/a/51788791

state
tag name: state
tags question: http://stackoverflow.com/q/51645244
type: Tag

http://stackoverflow.com/q/51691149
has comment: http://stackoverflow.com/comment/90344020
has comment: http://stackoverflow.com/comment/90344030
upvote count: 2
tagged with: boolean
has comment: http://stackoverflow.com/comment/90344040
has title: var == False or if not var
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/9798407
has body: var = False if not var: do_thing() or var = False if var == False: do_thing() What is the difference between the two?(If there is one) Is one fast than the either?
tagged with: boolean-expression
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/37103705
type: Question
duplicate of: http://stackoverflow.com/q/37103705
has comment: http://stackoverflow.com/comment/90344053
linked to: http://stackoverflow.com/q/36936065
has answer: http://stackoverflow.com/a/51691171
accepted answer: http://stackoverflow.com/a/51691171

http://stackoverflow.com/q/51668165
tagged with: string
favorite count: 0
tagged with: string-literals
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90325175
type: UnansweredQuestion
tagged with: string-formatting
has comment: http://stackoverflow.com/comment/90299044
tagged with: python
has comment: http://stackoverflow.com/comment/90299134
score: 1
upvote count: 1
has body: name = 'John' #basic method print('Hello, his name is ' + name) #.format method print('Hello, his name is {}'.format(name)) #f-string literal method print(f'Hello, his name is {name}') All are viable ways to concatenate and outputs the same thing, but why would I choose one over the other?
has comment: http://stackoverflow.com/comment/90299433
linked to: http://stackoverflow.com/q/13451989
linked to: http://stackoverflow.com/q/5082452
type: Question
has title: What are the advantages of these different string-formatting calls?
has answer: http://stackoverflow.com/a/51668209
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90395986
has text: Not worked, can you please test before write? It's more helpful. I've read about a type inside __import__() called fromlist: __import__(..., fromlist="...")
type: AnswerComment
comment on: http://stackoverflow.com/a/51691811
score: 0
type: Comment

http://stackoverflow.com/q/51741963
tagged with: python
has comment: http://stackoverflow.com/comment/90443878
tagged with: plot
has comment: http://stackoverflow.com/comment/90444295
type: Question
has answer: http://stackoverflow.com/a/51742247
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90444900
has body: I have a groupby object to which I applied value_counts(normalize=True) which yields the following series: Category Reason 25-39 year old Money 0.20 Time 0.10 Interest 0.70 40-54 year old Money 0.50 Time 0.20 Interest 0.30 55+ year old Money 0.70 Time 0.10 Interest 0.20 And I would like to make a bar chart, where x = category, y = values (shown above), and the "Reason" column being used as hue. See quick example in paint below:
has title: Plot pandas groupby object
tagged with: seaborn
type: UnansweredQuestion

http://stackoverflow.com/comment/90517285
has text: @Bakuriu I already use json.loads
score: 0
comment on: http://stackoverflow.com/q/51779699
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90373044
type: AnswerComment
type: Comment
has text: Not working, error message `AttributeError: 'float' object has no attribute 'lower'`
comment on: http://stackoverflow.com/a/51706068
score: 0

http://stackoverflow.com/comment/90323145
type: QuestionComment
has text: Welcome to Stack Overflow! Please read why [a screenshot of code is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Paste the code and properly format it instead.
score: 0
comment on: http://stackoverflow.com/q/51679235
type: Comment

http://stackoverflow.com/q/51676128
type: Question
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/63926261
favorite count: 0
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/90317621
has body: Every time I code something that has direction in it, I always have to make 4 different instances of the code, one for each direction, which makes code hard to maintain and develop. My example below is one example, and I would like to know if I could reduce it to 1 instance. Each instance is very similar, with just very minute differences, how do I combine them all into one? #This is a simcity sort of remake where everything is split into tiles(48x48) #I am storing the grid in a 2d numpy array, called grid #This triggers on mouse release #startX amd #startY are where you clicked the mouse down coords = pygame.mouse.get_pos() finishX = int(coords[0]/TILESIZE) finishY = int(coords[1]/TILESIZE) try: if abs(startX - finishX) &lt; abs(startY - finishY): #If it is verticle rather then horizontal if startY &gt; finishY: #If it's going up for i in range(abs(startY - finishY+1)): #Loop through entire length if grid[startX, startY-i] == 'g': #If the tile is grass/free (For plots) if tileType == 'r' or tileType == 'c' or tileType == 'i': #If it's a plot if grid[startX-1, startY-i] == 't' or grid[startX, startY-i-1] == 't' or grid[startX+1, startY-i] == 't' or grid[startX, startY-i+1] == 't': #If it has a neighbouring road grid[startX, startY-i] = tileType elif tileType == 't': #If it's a road if cash &gt;= roadCost: #If you can afford a road cash -= roadCost #Decrease cash by said road cost grid[startX, startY-i] = tileType #Set that tile to the new one else: text = "Not enough money to build more road!" # This sets it for the next function displayText(window, text) #Will display text at the bottom of the screen else: if tileType == 'g': #If it's the demolish tool, setting the tile to grass if grid[startX, startY-i] == 't': cash += roadCost/2 #Increase Cash by the cost of a road/2 grid[startX, startY-i] = 'g' #Set the ground to grass else: #If it's going down for i in range(abs(startY - finishY)+1): if grid[startX, startY+i] == 'g': if tileType == 'r' or tileType == 'c' or til…
duplicate of: http://stackoverflow.com/q/63926261
upvote count: 1
downvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90315409
has title: Reducing directional code
tagged with: numpy
has comment: http://stackoverflow.com/comment/90315384
has comment: http://stackoverflow.com/comment/90315532
has comment: http://stackoverflow.com/comment/90320623
tagged with: python-3.7

http://stackoverflow.com/comment/90312497
has text: My output looks like this. ------------------ ------------------ ------------------ ------------------ ------------------ ------------------ ------------------ ------------------ ------------------ ------------------ -----------hg------ -----w------------ . The output is supposed to display the symbols of each element in the correct place as in the Periodic Table and. Since I only have two elements in the library it should show. Hg and W in their correct places.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51674141

http://stackoverflow.com/a/51710440
accepted answer of: http://stackoverflow.com/q/51710341
score: 1
answers question: http://stackoverflow.com/q/51710341
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90382103
has comment: http://stackoverflow.com/comment/90382127
type: Answer
has body: So your issue is that you check the first line of the 'login.txt' file, and exit if it doesn't match. You could do something like this: for line in lines: if line.split(":")[0] == username and line.split(":")[1] == password: print("Welcome back %s" % (username)) while True: message = raw_input("") else: sys.exit() By moving the else one indent back, you create a for/else loop, which will run the else code if no lines in the file matched.
upvote count: 1

http://stackoverflow.com/comment/90257626
type: Comment
comment on: http://stackoverflow.com/a/51646774
score: 0
type: AnswerComment
has text: @schwobaseggl That could definitely be a problem, but I'm curious how you came up with `O(m+n)`? Is that average case? In my scratch work the best solution I've found is `O(m*log(m)+n*log(n))` worst case. What's the best algorithm to use for time complexity here?

http://stackoverflow.com/comment/90455831
has text: `get_date` is going to have to return *some object* that has the rest of the methods you want to use. You could have the `__str__` of the Date object use the default representation, then have each of the other methods return other specific formatting.
score: 1
comment on: http://stackoverflow.com/q/51748004
type: Comment
type: QuestionComment

pyinstaller
tags question: http://stackoverflow.com/q/51791938
tags question: http://stackoverflow.com/q/51707681
type: Tag
tags question: http://stackoverflow.com/q/51745571
tags question: http://stackoverflow.com/q/51747177
tags question: http://stackoverflow.com/q/51697707
tag name: pyinstaller
tags question: http://stackoverflow.com/q/51787641
tags question: http://stackoverflow.com/q/51787811
tags question: http://stackoverflow.com/q/51715595
tags question: http://stackoverflow.com/q/51657864
tags question: http://stackoverflow.com/q/51653339
tags question: http://stackoverflow.com/q/51759233
tags question: http://stackoverflow.com/q/51793459
tags question: http://stackoverflow.com/q/51662773
tags question: http://stackoverflow.com/q/51776025
tags question: http://stackoverflow.com/q/51721252
tags question: http://stackoverflow.com/q/51711276
tags question: http://stackoverflow.com/q/51700784
tags question: http://stackoverflow.com/q/51640995
tags question: http://stackoverflow.com/q/51756641

http://stackoverflow.com/q/51710105
has answer: http://stackoverflow.com/a/51710255
tagged with: python
has answer: http://stackoverflow.com/a/51710773
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51710305
upvote count: 2
has body: I have a text that I'm splitting into a list of sentences, and I want to find the subject of each sentence. For example, if the text is 'Dogs are great. They are so awesome', they have to be splitted into the two sentences 'Dogs are great.' and 'They are so awesome'. Then I use a for loop to find what the subject of each sentence is, whether it is 'cats' or 'dogs'. sentence_list=['Dogs are great', 'They are so awesome'] for sentence in sentence_list: if 'Dog' in sentence: subject= 'Dog' elif 'Cat' in sentence: subject='Cat' Because 'They' is used as a replacement for one of these, I want to set the subject for that sentence to the same as the last sentence. So in this example, the subject would be 'Dog' for both sentences.
has comment: http://stackoverflow.com/comment/90381445
score: 2
type: AnsweredQuestion
has title: How do I set a value to be the same as in the last item?
accepted answer: http://stackoverflow.com/a/51710773
type: Question
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90382034
has comment: http://stackoverflow.com/comment/90381597
possible better answer: http://stackoverflow.com/a/51710255

http://stackoverflow.com/q/51722280
type: Question
has title: python - How to read table with chunksize and names
has body: how can i read data from a csv with chnunksize and names? I tried this: sms = pd.read_table('demodata.csv', header=None, names=['label', 'good']) X = sms.label.tolist() y = sms.good.tolist() and it worked totaly fine. But if try this, i'll get an error: sms = pd.read_table('demodata.csv', chunksize=100, header=None, names=['label', 'good']) X = sms.label.tolist() y = sms.good.tolist() And i get this error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-18-e3f35149ab7f&gt; in &lt;module&gt;() ----&gt; 1 X = sms.label.tolist() 2 y = sms.good.tolist() AttributeError: 'TextFileReader' object has no attribute 'label' Why does it work in the first but not in the second place?
score: 0
has comment: http://stackoverflow.com/comment/90410468
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90405090
has comment: http://stackoverflow.com/comment/90405590
answer count: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51729465
tagged with: python
type: AnsweredQuestion
has title: Scikit-Image Questions (specifically re: `blob_log`)
type: Question
has comment: http://stackoverflow.com/comment/90434842
has body: I'm trying to use blob detection in scikit-image. blob_log is supposed to return an array of either Nx3 for a 2D image, or an Nx4 for a 3D image (?) The first two values in a 2D image are the (x, y, sigma) and in 3D are (p, x, y sigma) I'm attempting to load this image into my code which looks like it has quite a few observable blobs &amp; it is a 2D image. I've got a few questions: (1) the blob_log is returning a Nx4 array which means its loading it as a 3D image. When I try to print it, it looks like its just a bunch of empty arrays which I don't understand how because when I plt.show() it is a 2D image. (2) If N is the number of blobs it has calculated, then it is only giving me less than 10% of the total images - I believe this is due to the fact that the image is on a white background making it more difficult for the blob_log to notice - is that correct? (3) I don't understand how the for loop at the end of the Blob documentation works? How is it plotting the circles over the image? I'm sorry if this is an elementary question, but its frustrating me because I think that would help me with some of the other things I was wondering about. Attempts to figure out what is going on: (1) Loading data.coins() and printing it gives me a nice array of values which I assume are the 2D, it still doesn't explain why the image I want to load isn't being recognized as 2D. (2) I tried to load the data.coins() which should be an obviously provided image with circular images and fooled around with the sigma and threshold settings, I'm getting a variety of different values depending on the settings - is there a good way of figuring out which are the best without having to fool around with the settings until I get one that works? Due to the length of my code and my question, below is just the applicable parts, but my entire code can be found here from skimage import data, feature, exposure, io import matplotlib import matplotlib.pyplot as plt img = data.coins() #img = io.imread('gf…
accepted answer: http://stackoverflow.com/a/51737106
tagged with: scikit-image
tagged with: image-processing
tagged with: image
score: 0
has answer: http://stackoverflow.com/a/51737106
answer count: 1
tagged with: arrays

http://stackoverflow.com/q/51662933
has comment: http://stackoverflow.com/comment/90289504
favorite count: 0
type: UnansweredQuestion
has title: Why does datetime.fromtimestamp(time / 1e3) results in java.util.GregorianCalendar?
tagged with: python
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51671940
type: Question
tagged with: pyspark
has comment: http://stackoverflow.com/comment/90289350
answer count: 1
downvote count: 0
has body: I have a Spark job which has a UDF like this: def checkTimeRange(etime): date = datetime.datetime.fromtimestamp(etime / 1e3) if datetime.datetime(2018, 7, 26, 8, 00, 00) &lt; date &lt; datetime.datetime(2018, 7, 25, 9, 00, 00): return True else: return False I check whether the event time falls within a range and return True or False accordingly. The etime is of type int (Example: 1532609527000) but looks like date is of format: |java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="US/Pacific-New",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=US/Pacific-New,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2018,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=26,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=5,HOUR_OF_DAY=5,MINUTE=52,SECOND=7,MILLISECOND=0,ZONE_OFFSET=?,DST_OFFSET=?] How do I fix this?

mpi4py
tags question: http://stackoverflow.com/q/51747452
tags question: http://stackoverflow.com/q/51765805
tag name: mpi4py
tags question: http://stackoverflow.com/q/51714108
type: Tag
tags question: http://stackoverflow.com/q/51658008

http://stackoverflow.com/comment/90387555
has text: You are using sockets wrongly. `recv` gets one to 4096 bytes, not messages. Why don't you use http?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51713001

http://stackoverflow.com/q/51692672
answer count: 3
tagged with: data-visualization
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51700283
has answer: http://stackoverflow.com/a/51693370
upvote count: 1
possible better answer: http://stackoverflow.com/a/51693370
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51693442
score: 1
tagged with: plotly
has comment: http://stackoverflow.com/comment/90349823
type: Question
accepted answer: http://stackoverflow.com/a/51693442
has comment: http://stackoverflow.com/comment/90354817
has body: I want to integrate my jupyter notebook with my website, where I have written the code to fetch real-time data from MySQL server and do real-time visualisation using plotly. But every time I'm having to run all the cells of my Kernel. Is there a way I can automate the running of the Jupyter notebook cells periodically say everyday 1 hour?
linked to: http://stackoverflow.com/q/31984196
downvote count: 0
has title: How to automate running of Jupyter Notebook cells periodically
favorite count: 0
tagged with: sql-server

filesplitting
type: Tag
tag name: filesplitting
tags question: http://stackoverflow.com/q/51737962

http://stackoverflow.com/comment/90387188
comment on: http://stackoverflow.com/a/51712683
type: Comment
has text: @novawaly I personally think my second solution (the mask) is more straightforward, so I would recommend using that.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51780221
has comment: http://stackoverflow.com/comment/90518665
has answer: http://stackoverflow.com/a/51780586
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51780543
possible better answer: http://stackoverflow.com/a/51780586
type: Question
has body: I have a dataframe df where there are 3 columns id code status 1 US Y 2 IN Y 3 UK Y 4 CN Y 5 KR Y I want to update column status to N where code not in ("US", "UK") I tried using this but failed df.loc[df['code'] not in ("US","UK"),["status"]] ='N'
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51780543
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/30631841
has title: check and update column based on multiple values
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/51763148
answers question: http://stackoverflow.com/q/51762528
has body: As @alkanen already commented the value you pass to tensor1d is an array of arrays. ([[val],[val]]). As I understood the values form.value.X are already floats so you can simply make a float array out of them like [form.value.p, form.value.glu, ...] and then pass this to tf.tensor1d(). And the second thing is, that predict and fit take tensors or arrays of tensors(Reference) as parameters to allow for batching, so you would just call it like this.model.predict([x]).
type: Answer
score: 0

http://stackoverflow.com/q/51710804
tagged with: numpy
answer count: 2
upvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51710977
type: AnsweredQuestion
has title: Error while trying to display only certain colour pixels of an image that is captured
has body: I am trying to convert all the pixels of a captured image, that are not in the color yellow to white. The error message that I am getting is: if jmg[i,j]!=[255,255,0]: valueError: the truth value of an array with more than one element is ambiguous. use a.any() or a.all() Below is my code: import cv2 import picamera import numpy import time from matplotlib import pyplot as plt print("ready") with picamera.PiCamera() as camera: camera.resolution=(400,400) time.sleep(1) camera.capture("/home/pi/rowdy.jpg") print("Done") yellow=[255,255,0] img=cv2.imread("/home/pi/rowdy.jpg",1) jmg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) for i in numpy.arange(399): for j in numpy.arange(399): if jmg[i,j]!=[255,255,0]: jmg[i,j]=[255,255,255] plt.imshow(jmg) plt.xticks([]),plt.yticks([]) plt.show()
possible better answer: http://stackoverflow.com/a/51711462
downvote count: 1
has comment: http://stackoverflow.com/comment/90384210
type: Question
has answer: http://stackoverflow.com/a/51711462
tagged with: opencv
accepted answer: http://stackoverflow.com/a/51710977
score: -1

http://stackoverflow.com/q/51744314
has comment: http://stackoverflow.com/comment/90448735
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90448727
tagged with: pandas
tagged with: string
has title: Slicing the year from a year-mm-dd row in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/90448406
has comment: http://stackoverflow.com/comment/90448871
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51744592
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51744662
tagged with: slice
has body: I am trying to slice a large object-type column in a pandas dataframe. All the dates in this column are on a "year-mm-dd" format and I would like first to replace it with only the "year" value and then convert it to a numeric column. I tried to do the following : for i in range(len(df.index)): df.age[i]=df.age[i][:4] I directly get a warning and an error like this: /home/nbuser/anaconda3_501/lib/python3.6/site-packages/ipykernel/__main__.py:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy from ipykernel import kernelapp as app --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-262-b01a66467d00&gt; in &lt;module&gt;() 1 for i in range(len(df.index)): ----&gt; 2 df.age[i]=df.age[i][:4] IndexError: invalid index to scalar variable. What I wanted to do if it worked, was then to convert this column from object to a numeric column by using: df['age'] = pd.to_numeric(df['age']) By putting a .to_dict prompt, I get : Input : df['age'].to_dict() Output: {0: '1966-04-08', 1: '1965-05-14', 2: '1965-08-12', 3: '1968-02-15', 4: '1968-08-08', ...} I cut the rest as there are more than 16000 values Plus, when I get the dtype I get : Input: df['age'].dtype Output: dtype('O') Thank you in advance for your help!
type: Question
linked to: http://stackoverflow.com/q/31797249
answer count: 2

http://stackoverflow.com/q/51719616
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51719696
score: -1
favorite count: 0
has body: i am going though one python script and found this line for passing arguments. I want to know what is the need to repeat same arguments with -daily and --daily parser.add_argument("-daily", "--daily", action="store_true", default=False)
tagged with: python
type: AnsweredQuestion
has title: hyphen in python argument parser
has answer: http://stackoverflow.com/a/51719696
downvote count: 1
type: Question

pivot-table
tags question: http://stackoverflow.com/q/51749448
tag name: pivot-table
tags question: http://stackoverflow.com/q/51693871
tags question: http://stackoverflow.com/q/51677160
tags question: http://stackoverflow.com/q/51732854
tags question: http://stackoverflow.com/q/51698989
type: Tag

http://stackoverflow.com/comment/90543288
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51791933
has text: Sorry, would you mind formatting the error as code please? It will make it much easier to read.
score: 0

http://stackoverflow.com/comment/90781863
has text: Thanks smci. I rebuilt the program as you said. And clearly I found that I am totally not understand the 'class' function and the question is so stupid. But again, thanks very much to point out my problem. I should read more the docs.
comment on: http://stackoverflow.com/a/51692451
score: 0
type: AnswerComment
type: Comment

mysql-connect
tag name: mysql-connect
type: Tag
tags question: http://stackoverflow.com/q/51713202

http://stackoverflow.com/comment/90330496
comment on: http://stackoverflow.com/a/51667108
has text: No. Your code also not working. sorry 'mode = logger.error' was typing mistake, actually I coded 'mode = logging.error' in my program. I'm passing the mode from config file is that a problem?, when I comment out logger.setLevel(mode) it is working,in default logging.warning mode.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51774930
answers question: http://stackoverflow.com/q/51774831
has comment: http://stackoverflow.com/comment/90508814
has comment: http://stackoverflow.com/comment/90517354
has body: The pycharm is using a python from a .../venv/... folder while what you type in the cmd does not. Make sure to use the same python version for both. One way would be to go to: File->Settings->Project->Project Interpreter and change to the python that you have installed the module for
has comment: http://stackoverflow.com/comment/90508600
has comment: http://stackoverflow.com/comment/90544199
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90509326
accepted answer of: http://stackoverflow.com/q/51774831
type: Answer

http://stackoverflow.com/a/51777707
score: 0
has comment: http://stackoverflow.com/comment/90513898
has body: You can use a simple function, or just directly print the variable. Assuming you make an object from the class tech called tech_obj: tech_obj = tech() print(tech_obj.w) or you could make a function: def weight(self): print(self.w)
has comment: http://stackoverflow.com/comment/90513699
has comment: http://stackoverflow.com/comment/90513803
has comment: http://stackoverflow.com/comment/90513922
has comment: http://stackoverflow.com/comment/90513814
type: Answer
has comment: http://stackoverflow.com/comment/90513752
answers question: http://stackoverflow.com/q/51777687
has comment: http://stackoverflow.com/comment/90513731
has comment: http://stackoverflow.com/comment/90513661
has comment: http://stackoverflow.com/comment/90513652
has comment: http://stackoverflow.com/comment/90513681

object-detection
tags question: http://stackoverflow.com/q/51742805
tags question: http://stackoverflow.com/q/51665533
tag name: object-detection
tags question: http://stackoverflow.com/q/51703508
tags question: http://stackoverflow.com/q/51676257
tags question: http://stackoverflow.com/q/51649833
tags question: http://stackoverflow.com/q/51647333
type: Tag
tags question: http://stackoverflow.com/q/51738546
tags question: http://stackoverflow.com/q/51656728
tags question: http://stackoverflow.com/q/51788811
tags question: http://stackoverflow.com/q/51743674
tags question: http://stackoverflow.com/q/51754968

http://stackoverflow.com/q/51720962
tagged with: tkinter
score: 0
possible better answer: http://stackoverflow.com/a/51725856
has answer: http://stackoverflow.com/a/51722715
type: AnsweredQuestion
tagged with: optionmenu
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51722715
tagged with: ttk
has body: I want to write a code generator in python and asking the user to select by an ttk.OptionMenu the type of variable. Right behind this OptionMenu the user has to define the value inside a ttk.Checkbutton if it is a boolean type or an entry if it is an integer or string and define a value. The GUI looks like the following: If I want to change the type to int or string the ttk.Checkbutton in behind should change to an ttk.Entry, but the program does crash because it can't allocate any more menus [_tkinter.TclError: No more menus can be allocated.]. I dont know what to do and found no solution. I am connecting my checkbutton by trace with a function that gets called all the time the optionmenu has changed. Here is my simple coding example: import tkinter as tk import tkinter.ttk as ttk from functools import partial class MyWindow(ttk.Frame): def __init__(self, parent): ttk.Frame.__init__(self, parent) line = [tk.StringVar(value="bool"), tk.BooleanVar(value=True)] self.vars = [line] self.show() def show(self): for widget in self.children.values(): widget.grid_forget() x = 0 for var in self.vars: ttk.OptionMenu(self, var[0], var[0].get(), *["bool", "int", "string"]).grid(row=x, column=0) var[0].trace("w", partial(self.menu_changed, line=var)) if var[0].get() == "bool": ttk.Checkbutton(self, variable=var[1].get()).grid(row=x, column=1) else: ttk.Entry(self, textvariable=var[1].get()).grid(row=x, column=1) x += 1 ttk.Button(self, text="+", command=self.add, width=3).grid(row=x, column=0) self.place(x=10, y=10, anchor=tk.NW) def add(self): line = [tk.StringVar(value="bool"), tk.BooleanVar(value=True)] self.vars.append(line) self.show() def menu_changed(self, *_, line): if line[0].get() == "bool": line[1] = tk.BooleanVar(value=True) elif line[0].get() == "int": line[1] = tk.IntVar(value=0) elif line[0].get() == "string": line[1] = tk.StringVar() self.show() root = tk.Tk() window = MyWindow(root) root.mainloop() I hope you do have any idea what's wrong. Thanks in advance.
has title: tkinter OptionMenu in combination with trace throws "TclError: No more menus can be allocated"
tagged with: python
has answer: http://stackoverflow.com/a/51725856

http://stackoverflow.com/q/51656146
favorite count: 0
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/51656259
has answer: http://stackoverflow.com/a/51656225
tagged with: python
has body: For example, the following, the first parameter should be restricted to a string, and the second parameter should be a function. However, this is wrong syntax for both. Anyone can help suggest the correct syntax to impose the type restriction? def GetArg(msg:String, converter:lambda, default): print("{}, the default is '{}':".format(msg, default)) return converter(stdin.readline().strip()) It gives error Traceback (most recent call last): File "E:/stdin_ext.py", line 4, in &lt;module&gt; def GetArg(msg:String, converter, default:String): NameError: name 'String' is not defined and File "E:/stdin_ext.py", line 4 def GetArg(msg:String, converter:lambda, default:String): ^ SyntaxError: invalid syntax
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
answer count: 2
has title: How to restrict a parameter of python function must be string or a function like lambda expression

http://stackoverflow.com/comment/90300651
comment on: http://stackoverflow.com/q/51668931
type: Comment
type: QuestionComment
has text: I don't think you should define your function there, move it to another scope (proably global)
score: 4

http://stackoverflow.com/comment/90334596
score: 0
type: AnswerComment
type: Comment
has text: another question I would have, is how do you limit the shift only for na in the extra_columns?
comment on: http://stackoverflow.com/a/51669633

http://stackoverflow.com/q/51712500
has title: Create dataframe from itertools product
accepted answer: http://stackoverflow.com/a/51712573
has comment: http://stackoverflow.com/comment/90386647
favorite count: 0
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90386945
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90386900
has comment: http://stackoverflow.com/comment/90393973
score: 1
upvote count: 3
has answer: http://stackoverflow.com/a/51712573
type: Question
tagged with: numpy
has body: I have two lists: a = [1,2,3] b = [4,5,6] I want to create a dataframe whereby each combination of (a,b) generates a dataframe X and I pick out the max value of X, with the resulting output rows/columns with the elements in a and b. df=[] for i, j in itertools.product(a, b): X = do_something(i,j) ## this is a dataframe x_value = X.max() df.append(i,j,x_value) df=pd.DataFrame(df, columns=['a', 'b', 'x_value']) The output dataframe should have columns as a, rows as b, and values as x_value. 1 2 3 4 5 6
has answer: http://stackoverflow.com/a/51712602
tagged with: python-itertools
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51712581
has answer: http://stackoverflow.com/a/51718875
has answer: http://stackoverflow.com/a/51712581
tagged with: pandas

http://stackoverflow.com/a/51642537
answers question: http://stackoverflow.com/q/51642034
has comment: http://stackoverflow.com/comment/90272124
downvote count: 0
has comment: http://stackoverflow.com/comment/90283206
upvote count: 2
type: Answer
has body: If you call GET /folder you should get an array of sheets that contain the sheet ids, like this: { "id": 7116448184199044, "name": "Projects", "permalink": "https://app.smartsheet.com/b/home?lx=B0_lvAtnWygeMrWr4Rfoa", "sheets": [ { "id": 4509918431602564, "name": "Project Timeline", "accessLevel": "OWNER", "permalink": "https://app.smartsheet.com/b/home?lx=uWicCItTmkbxJwpCfQ5wiwW", "createdAt": "2015-06-05T20:05:29Z", "modifiedAt": "2015-06-05T20:05:43Z" } ] }
score: 2

http://stackoverflow.com/comment/90401849
score: 0
has text: The question is somewhat misleading, as the core of the queston is not about Base64 at all. It's more about determining the encoding of a text string where the fact it was decoded from Base64 or comes from elsewhere is irrelevant.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51720010

http://stackoverflow.com/a/51646849
has comment: http://stackoverflow.com/comment/90259229
score: 1
has comment: http://stackoverflow.com/comment/90259551
downvote count: 0
answers question: http://stackoverflow.com/q/51646627
has comment: http://stackoverflow.com/comment/90259250
type: Answer
has body: You can use BeautifulSoup to navigate XML: from bs4 import BeautifulSoup data = """ 1 abc def 2 fhi jklmn """ soup = BeautifulSoup(data, 'xml') text = input('Please input your text : ') t = soup.find(lambda t: False if t.name != 'text' else text in t.string) if t: number = t.findPrevious('number').text.strip() print('Text {} found, the number is {}'.format(text, number)) else: print('Text {} not found'.format(text)) This will input user for a string and tries to find the string in tags. If it is found, it will print value contained in . Example: Please input your text : abc Text abc found, the number is 1 EDIT: For searching all tags for given string, not just change the find() function to: t = soup.find(lambda t: False if not t.string else text in t.string)
upvote count: 1

http://stackoverflow.com/comment/90297029
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51666361
type: Comment
has text: The topic is clear. There are no risks. But yes, it _is_ considered bad practice. And we suspect that it's unnecessary, or at least that there's a better way to deal with your real problem, which is why we continue to ask why you want to do this.

http://stackoverflow.com/a/51661332
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51661280
score: 5
has body: I've answered my own question. The solution was just the string 'd' as a parameter, whereas I was trying 'day','days', etc. Hope this helps someone in need.

http://stackoverflow.com/q/51674701
tagged with: dictionary-comprehension
answer count: 1
has title: Get values for (almost) matching keys in 2 dictionaries and join them
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/51674845
favorite count: 0
tagged with: python-3.x
has body: So I want to get values for (almost) matching keys in 2 dictionaries and join them. I tried: dict3 = {key:dict1[key].strip() for key in dict2.keys() if key.partition('__')[0] in dict1} ...but I dont get any results because it's not finding any matches, my dicts are below, I know i'm close but I'm missing something: dict1: { "h1__display-3": "", "h1__display-3_text-white_text-center": "", "h1__mt-4": "", "h1__mt-5": "", "h1__mt-5_kakabum": "", "h1__my-4": "", "h2__card-title": "", "h2__mt-4": "", "h2__my-4": "" } dict2: { "h1": " [] ", "h2": " [] " } Desired outcome: { "h1": " [] ", "h1__display-3": " [] ", "h1__display-3_text-white_text-center": " [] ", "h1__mt-4": " [] ", "h1__mt-5": " [] ", "h1__mt-5_kakabum": " [] ", "h1__my-4": " [] ", "h2": " [] ", "h2__card-title": " [] ", "h2__mt-4": " [] ", "h2__my-4": " [] " } I was hoping that running the first line of code would work, but I dont think i have the syntax right.
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51674845
type: Question

http://stackoverflow.com/q/51691980
tagged with: python
has answer: http://stackoverflow.com/a/51692110
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Numpy : Grouping/ binning values based on associations
type: Question
tagged with: numpy
tagged with: numpy-ndarray
answer count: 2
has answer: http://stackoverflow.com/a/51692327
accepted answer: http://stackoverflow.com/a/51692327
has body: Forgive me for a vague title. I honestly don't know which title will suit this question. If you have a better title, let's change it so that it will be apt for the problem at hand. The problem. Let's say result is a 2D array and values is a 1D array. values holds some values associated with each element in result. The mapping of an element in values to result is stored in x_mapping and y_mapping. A position in result can be associated with different values. Now, I have to find the sum of the values grouped by associations. An example for better clarification. result array: [[0, 0], [0, 0], [0, 0], [0, 0]] values array: [ 1., 2., 3., 4., 5., 6., 7., 8.] Note: Here result and values have the same number of elements. But it might not be the case. There is no relation between the sizes at all. x_mapping and y_mapping have mappings from 1D values to 2D result. The sizes of x_mapping, y_mapping and values will be the same. x_mapping - [0, 1, 0, 0, 0, 0, 0, 0] y_mapping - [0, 3, 2, 2, 0, 3, 2, 1] Here, 1st value(values[0]) have x as 0 and y as 0(x_mapping[0] and y_mappping[0]) and hence associated with result[0, 0]. If we are counting the number of associations, then element value at result[0,0] will be 2 as 1st value and 5th value are associated with result[0, 0]. If we are taking the sum, the result[0, 0] = value[0] + value[4] which is 6. Current solution # Initialisation. No connection with the solution. result = np.zeros([4,2], dtype=np.int16) values = np.linspace(start=1, stop=8, num=8) y_mapping = np.random.randint(low=0, high=values.shape[0], size=values.shape[0]) x_mapping = np.random.randint(low=0, high=values.shape[1], size=values.shape[0]) # Summing the values associated with x,y (current solution.) for i in range(values.size): x = x_mapping[i] y = y_mapping[i] result[-y, x] = result[-y, x] + values[i] The result, [[6, 0], [ 6, 2], [14, 0], [ 8, 0]] Failed solution; But why? test_result = np.zeros_like(result) test_result[-y_mapping, x_mapping] = test_result[-y_…
possible better answer: http://stackoverflow.com/a/51692110
tagged with: array-broadcasting
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/53513497
tagged with: python-3.x

http://stackoverflow.com/a/51715984
has comment: http://stackoverflow.com/comment/90426189
downvote count: 0
has comment: http://stackoverflow.com/comment/90427560
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51715928
upvote count: 1
has body: I think this should work; locals gets you a dict of all of the local variables (in this case, all variables in the function). def get_curl_params(url=None, headers=None, post=None, curl_proxy=None, curl_success=None, should_use_cookies=False, should_follow_location=False, should_include_referer=False, custom_request='Get', should_verify_ssl=False, head=None, timeout_limit=60, site_rate_limit_seconds=None): kwargs = locals() # if you can pass everything to init, this would be nice curl_params = CurlParameters(**kwargs) # otherwise, you can do this: for name, val in kwargs.items(): setattr(curl_params, name, val) return curl_params

http://stackoverflow.com/a/51796959
type: Answer
accepted answer of: http://stackoverflow.com/q/51796846
answers question: http://stackoverflow.com/q/51796846
score: 0
has body: You were close. Try this: import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [ 4, 5, 2], 'c': [2, 4, 5]}) print(df) df = df[[x for _, x in sorted(zip(df.iloc[-1], df.columns), reverse=True)]] print(df) Starting DataFrame: a b c 0 1 4 2 1 2 5 4 2 3 2 5 Columns sorted by the values in the bottom row, in descending order: c a b 0 2 1 4 1 4 2 5 2 5 3 2
type: AcceptedAnswer

http://stackoverflow.com/comment/90405490
has text: I edit it again in another question.
type: Comment
comment on: http://stackoverflow.com/q/51716404
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90325364
has text: By the way, I think `data` is probably a `bytes` here—you get it from calling `read` on something (presumably a file open in binary mode, or a `BytesIO` or something that acts like a file open in binary mode). But that's fine; a `bytes` is a sequence of values from 0 to 255, just like a list of those values.
comment on: http://stackoverflow.com/q/51680235
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51691822
score: 0
answers question: http://stackoverflow.com/q/51691768
has body: You will need to check if the puzzle is solved, and use the returned value to decide what to do: You must check rows, the columns and the 9 3x3 blocks; I don't think the sum of rows is enough class puzzle(): def __init__(self, puzzle): self.board = [row[:] for row in puzzle] def is_solved(self)-&gt; bool: compare_to = list(range(10)) is_solved = True for row in self.board: is_solved = is_solved and (sorted(row) == compare_to) if not is_solved: return False for idx in range(10): column = [row[idx] for row in self.board] is_solved = is_solved and (sorted(column) == compare_to) if not is_solved: return False # check the blocks here return is_solved
type: Answer

http://stackoverflow.com/comment/90428608
type: Comment
comment on: http://stackoverflow.com/a/51731803
has text: A variable can't be a key in a dictionary, but multiple keys can share the same value. `for word in ['hi', 'hello', 'howdy', 'good morning']: keywords[word] = 'Hello! How can I help you?'`
type: AnswerComment
score: 0

http://stackoverflow.com/a/51698904
downvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51696404
answers question: http://stackoverflow.com/q/51696404
score: 0
has body: You should be able to do aggregation on xyz.keyword field even without any special mapping. If you are not interested in search hits just add "size": 0 property on the top level of your query.
type: Answer
upvote count: 1

http://stackoverflow.com/a/51752511
score: 2
has comment: http://stackoverflow.com/comment/90525908
upvote count: 2
answers question: http://stackoverflow.com/q/51751965
downvote count: 0
has body: Simple and quick way to draw an x on the plot of yours could be to use plt.scatter. You can make use of the x marker to put the x in the center of the circle you have. Check the following code, it draws the x in the center of the leftmost circle. The coordinates you need to provide for the marker are the same relative coordinates you pass to create the circle. import matplotlib.pyplot as plt f = plt.figure(figsize=(6, 6)) ax = f.add_subplot(111) box = ax.get_position() axColor = plt.axes([box.x0 + 0.05, box.y0 + 0.05, 0.6, 0.6], projection='polar') axColor.set_yticks([]) axColor.set_xticks([]) axColor.set_rlim(0, 50) circle = plt.Circle((0., 0.), 10, transform=axColor.transData._b, edgecolor='k', facecolor='None', linewidth=2) axColor.add_artist(circle) circle = plt.Circle((0., 0.), 3, transform=axColor.transData._b, color='k', linewidth=2) axColor.add_artist(circle) circle = plt.Circle((-0.02, 0.9), 0.1, transform=axColor.transAxes, edgecolor='k', facecolor='None', linewidth=2, clip_on=False) axColor.add_artist(circle) mymarker = plt.scatter(-0.02, 0.9, s=300, c='red', transform=axColor.transAxes, marker='x', clip_on=False) axColor.add_artist(mymarker) f.savefig('plot_with_x.png') I also attached the image here. You can adjust the size of the marker by adjusting the value of s and change the color with c. Hope this helps.
type: Answer
has comment: http://stackoverflow.com/comment/90543092

http://stackoverflow.com/a/51796102
answers question: http://stackoverflow.com/q/51795743
score: 0
has comment: http://stackoverflow.com/comment/90554051
type: Answer
has body: The dropdown you are trying to click is not actually a SELECT element so you can't use the Select class. The SELECT you are trying to click is just a backing element but it's invisible so you can't interact with it. To make this work, you will need to click the dropdown element to expose the options and then click the desired option. driver.find_element_by_css_selector("#s2id_ddlEstado &gt; a").click() driver.find_element_by_xpath("//ul[@id='select2-results-1']/li[.='MG']").click() This is untested code, so you may need to add a wait...

http://stackoverflow.com/comment/90485319
type: Comment
type: QuestionComment
score: 0
has text: Your tempfile is destroyed as soon as you leave its context manager, hence the error.
comment on: http://stackoverflow.com/q/51734728

http://stackoverflow.com/a/51756157
has comment: http://stackoverflow.com/comment/90502431
answers question: http://stackoverflow.com/q/51752883
score: 0
type: Answer
has body: you are running your processes asynchronously. You cannot expect that these independent processes process/finish their task in any expected order.

http://stackoverflow.com/q/51772066
has body: I was recently experimenting with monkey patching built in types (Yes I know this is a terrible idea---trust me, this is for educational purposes only). I discovered that there is an odd distinction between lambda expressions and functions declared with def. Take a look at this iPython session: In [1]: %load_ext cython In [2]: %%cython ...: from cpython.object cimport PyObject_GenericSetAttr ...: def feet_to_meters(feet): ...: ...: """Converts feet to meters""" ...: ...: return feet / 3.28084 ...: ...: PyObject_GenericSetAttr(int, 'feet_to_meters', feet_to_meters) In [3]: (20).feet_to_meters() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-3-63ba776af1c9&gt; in &lt;module&gt;() ----&gt; 1 (20).feet_to_meters() TypeError: feet_to_meters() takes exactly one argument (0 given) Now, if I wrap feet_to_meters with a lambda, everything works! In [4]: %%cython ...: from cpython.object cimport PyObject_GenericSetAttr ...: def feet_to_meters(feet): ...: ...: """Converts feet to meters""" ...: ...: return feet / 3.28084 ...: ...: PyObject_GenericSetAttr(int, 'feet_to_meters', lambda x: feet_to_meters(x)) In [5]: (20).feet_to_meters() Out[5]: 6.095999804928006 What is going on with this?
tagged with: python
has comment: http://stackoverflow.com/comment/90504866
has answer: http://stackoverflow.com/a/51794949
tagged with: cpython
upvote count: 1
linked to: http://stackoverflow.com/q/20981789
type: AnsweredQuestion
score: 1
tagged with: cython
type: Question
accepted answer: http://stackoverflow.com/a/51794949
has comment: http://stackoverflow.com/comment/90504304
has comment: http://stackoverflow.com/comment/90504076
downvote count: 0
answer count: 1
favorite count: 0
has title: Why does `PyObject_GenericSetAttr` behave differently with lambdas than named functions

http://stackoverflow.com/comment/90282400
comment on: http://stackoverflow.com/q/51659140
score: 0
has text: You get six numbers and you use them to reach a target, you can use as many or as few as you need.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90429093
type: Comment
type: QuestionComment
has text: while adding and using append function and using [a[b]] in a second parameter i'm expecting the array to add values in it..The second parameter in append is for adding values in an array
comment on: http://stackoverflow.com/q/51733904
score: 0

http://stackoverflow.com/comment/90469250
score: 1
has text: Which of the two examples calls functions in an arbitrary order?
comment on: http://stackoverflow.com/a/51754751
type: AnswerComment
type: Comment

popen
tags question: http://stackoverflow.com/q/51660091
type: Tag
tags question: http://stackoverflow.com/q/51645873
tags question: http://stackoverflow.com/q/51706019
tag name: popen

http://stackoverflow.com/a/51677515
score: 0
has body: Since the argument being passed into your program is a string, you could just comma separate the different file paths and then split them in the program with .split() Or another option is to specify a folder path where all the image files are located, and then use glob.glob('path/*.png') to get a list of all files with the .png extension.
type: Answer
answers question: http://stackoverflow.com/q/51677462

dataframe
tags question: http://stackoverflow.com/q/51695651
tags question: http://stackoverflow.com/q/51664495
tags question: http://stackoverflow.com/q/51768543
tags question: http://stackoverflow.com/q/51702138
tags question: http://stackoverflow.com/q/51687702
tags question: http://stackoverflow.com/q/51695171
tags question: http://stackoverflow.com/q/51740214
tags question: http://stackoverflow.com/q/51690414
tags question: http://stackoverflow.com/q/51681592
tags question: http://stackoverflow.com/q/51793878
tags question: http://stackoverflow.com/q/51661561
tags question: http://stackoverflow.com/q/51744314
tags question: http://stackoverflow.com/q/51783267
tags question: http://stackoverflow.com/q/51690288
tags question: http://stackoverflow.com/q/51660420
tags question: http://stackoverflow.com/q/51722546
tags question: http://stackoverflow.com/q/51702899
tags question: http://stackoverflow.com/q/51739438
tags question: http://stackoverflow.com/q/51768103
tags question: http://stackoverflow.com/q/51710907
tags question: http://stackoverflow.com/q/51770740
tags question: http://stackoverflow.com/q/51770458
tags question: http://stackoverflow.com/q/51683170
tags question: http://stackoverflow.com/q/51653878
tags question: http://stackoverflow.com/q/51748631
tags question: http://stackoverflow.com/q/51733223
tags question: http://stackoverflow.com/q/51778614
tags question: http://stackoverflow.com/q/51743354
tags question: http://stackoverflow.com/q/51782824
tags question: http://stackoverflow.com/q/51733620
tags question: http://stackoverflow.com/q/51790351
tags question: http://stackoverflow.com/q/51641558
tags question: http://stackoverflow.com/q/51664482
tags question: http://stackoverflow.com/q/51771812
tags question: http://stackoverflow.com/q/51743156
tags question: http://stackoverflow.com/q/51699597
tags question: http://stackoverflow.com/q/51728054
tags question: http://stackoverflow.com/q/51700673
tags question: http://stackoverflow.com/q/51755927
tags question: http://stackoverflow.com/q/51780221
tags question: http://stackoverflow.com/q/51668104
tags question: http://stackoverflow.com/q/51741865
tags question: http://stackoverflow.com/q/51758417
tags question: http://stackoverflow.com/q/51661480
tags question: http://stackoverflow.com/q/51793364
tags question: http://stackoverflow.com/q/51761308
tags question: http://stackoverflow.com/q/51775895
tags question: http://stackoverflow.com/q/51641981
tags question: http://stackoverflow.com/q/51709244
tags question: http://stackoverflow.com/q/51658428
tags question: http://stackoverflow.com/q/51684832
tags question: http://stackoverflow.com/q/51676382
tags question: http://stackoverflow.com/q/51687318
tags question: http://stackoverflow.com/q/51678823
tags question: http://stackoverflow.com/q/51666933
tags question: http://stackoverflow.com/q/51784855
tags question: http://stackoverflow.com/q/51740502
tags question: http://stackoverflow.com/q/51665244
tags question: http://stackoverflow.com/q/51705734
tags question: http://stackoverflow.com/q/51781561
tags question: http://stackoverflow.com/q/51741897
tags question: http://stackoverflow.com/q/51784495
tags question: http://stackoverflow.com/q/51699630
tags question: http://stackoverflow.com/q/51796886
tags question: http://stackoverflow.com/q/51648409
tags question: http://stackoverflow.com/q/51690941
tags question: http://stackoverflow.com/q/51644442
tags question: http://stackoverflow.com/q/51769472
tags question: http://stackoverflow.com/q/51680205
tags question: http://stackoverflow.com/q/51748201
tags question: http://stackoverflow.com/q/51774318
tags question: http://stackoverflow.com/q/51764219
tags question: http://stackoverflow.com/q/51679840
tags question: http://stackoverflow.com/q/51717268
tags question: http://stackoverflow.com/q/51701531
tags question: http://stackoverflow.com/q/51723424
tags question: http://stackoverflow.com/q/51669232
tags question: http://stackoverflow.com/q/51640114
tags question: http://stackoverflow.com/q/51721923
tags question: http://stackoverflow.com/q/51658345

http://stackoverflow.com/comment/90477818
type: Comment
score: 0
type: AnswerComment
has text: Thanks a lot this fixed it perfectly!
comment on: http://stackoverflow.com/a/51746728

http://stackoverflow.com/a/51651653
type: Answer
has body: In schemes function, you set color['nb'] to a list. In Standard.setparams function, you put this list into self.parameters['scheme'] then you call DefaultPlot.setparams In DefaultPlot.setparams you call BasePlot.schemes(v) with v equal to this list In BasePlot.schemes you call return color[style] with style equal to this list, which cannot work (style should be a string)
answers question: http://stackoverflow.com/q/51650408
score: 0

http://stackoverflow.com/q/51657427
has answer: http://stackoverflow.com/a/51658278
favorite count: 0
has body: I'm trying to get the rowcount of a database table before and after having inserted a new row into the table. At a basic level I want to take tthe rowcount, insert a row, then take the rowcount again (i.e. it should be 1 more). However, the second call of cursor.rowcount always returns the same number as the first cursor.rowcount call. My code: from mysql.connector import MySQLConnection, Error from single_api_insert import insert def query_insert(): try: con = MySQLConnection(host='localhost', database='test', user='root', password='') if con.is_connected(): print('Connected to database') cursor = con.cursor() cursor.execute("select * from testapi") row = cursor.fetchall() print(cursor.rowcount) insert(2, 'mk', 'km') print(cursor.rowcount) except Error: print(Error) finally: cursor.close() con.close() if __name__ == '__main__': query_insert() The insert method inserts a row into my table testapi. With an empty table this should print Connected to database 0 1 but the rowcount does not increase to 1. Is there a better way to do this or a way to solve rowcount not working correctly the second time? Thanks
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
type: Question
has title: Python/MySQL: using cursor.rowcount before and after inserting a row
upvote count: 1
tagged with: mysql-python
answer count: 1

http://stackoverflow.com/a/51730840
has comment: http://stackoverflow.com/comment/90424280
has comment: http://stackoverflow.com/comment/90424360
score: 0
has comment: http://stackoverflow.com/comment/90424512
has body: No, FactorRange objects are only configurable by setting the factors property of the range. It is not possible to link the factors property to a CDS directly. (Factor ranges support multi-level hierarchical levels, and that does not map naturally to CDS columns.) However, you can change the value of factors to whatever you need, in a CustomJS callback, or Python callback (if are making a Bokeh server application).
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90424399
has comment: http://stackoverflow.com/comment/90424478
type: Answer
accepted answer of: http://stackoverflow.com/q/51730321
answers question: http://stackoverflow.com/q/51730321

http://stackoverflow.com/q/51797189
favorite count: 0
has answer: http://stackoverflow.com/a/51797223
answer count: 3
has title: how to uninstall pyenv(installed by homebrew) on Mac
tagged with: pyenv
tagged with: macos
has body: I used to install pyenv by homebrew to manage versions of python, but now, I want to use anaconda.But I don't know how to uninstall pyenv.Please tell me.
accepted answer: http://stackoverflow.com/a/51797298
tagged with: homebrew
score: 58
tagged with: python
has answer: http://stackoverflow.com/a/58908094
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51797298
downvote count: 0
possible better answer: http://stackoverflow.com/a/51797223
type: Question
upvote count: 58

http://stackoverflow.com/a/51697476
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51696639
has body: .apply can indeed be used here, with a custom function (that needs a reference to the whole dataframe df). def get_hit_first(row): # Get a temporary view on the subsequent rows temp = df.loc[row.name:].iloc[1:] # Find the first row matching the criteria head = temp[(temp.High &gt;= row['High-Target'])|(temp.Low &lt;= row['Low-Target'])]\ .head(1) if len(head) &gt; 0: if head.iloc[0].High &gt;= row['High-Target']: return 'HIGH' else: return 'LOW' df['Hit First'] = df.apply(get_hit_first, axis=1) It is probably not the most optimal solution though, as the comparisons are executed on all subsequent rows.
downvote count: 0

http://stackoverflow.com/comment/90472982
comment on: http://stackoverflow.com/q/51756727
score: 0
has text: Please, format your code and define `template_out` variable.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90274238
type: AnswerComment
has text: Just for curiosity sake, but why do you need this? What is the difference with the presented solutions?
type: Comment
comment on: http://stackoverflow.com/a/51655117
score: 0

http://stackoverflow.com/a/51723038
type: Answer
has body: Ok, it looks like plt.pcolor inverted my array y. So used the following code to correct it: # inverse y y = y[::-1] Now my image looks right.
answers question: http://stackoverflow.com/q/51720829
accepted answer of: http://stackoverflow.com/q/51720829
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/51773120
has body: Taking a shot here, you can use .loc[:, cols] to slice only columns that matter, and .agg in axis 1 to perform your logic df.loc[:, df.columns.str.startswith('dog')].agg(function, 1) For a simple sum, for example, this can be df.loc[:, df.columns.str.startswith('dog')].agg(sum, 1) # or sum(1)
answers question: http://stackoverflow.com/q/51772956
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51772956
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90361278
has text: what line is throwing the error?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51699923
score: 0

http://stackoverflow.com/comment/90295169
has text: Thanks again Amadan. I learned something new again. `re.DOTALL` is great. I was about to use `r'{(\n?.*)}'`, but `re.DOTALL` is cleaner. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51664486
type: AnswerComment

http://stackoverflow.com/comment/90469977
comment on: http://stackoverflow.com/q/51755013
score: 0
has text: ah ok. I think I might know a way, one sec
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90327229
type: QuestionComment
has text: Also, what does "dies" mean here? What actually happens? Does it just exit without a message? Raise an exception? Segfault? And there isn't any code that reads a second line, so where does this dying actually happen?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51682092

http://stackoverflow.com/a/51766254
has body: Or: l=['root pts/3 100.121.17.73 Tue Aug 7 14:22 - 14:23 (00:00) '] print(' '.join(l[0].split()[-6:][:-1])) Output: Aug 7 14:22 - 14:23
type: Answer
answers question: http://stackoverflow.com/q/51765943
score: 0

http://stackoverflow.com/q/51743417
tagged with: python-3.x
has title: Pygame's colliderect isn't noticing collisions
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51744755
accepted answer: http://stackoverflow.com/a/51744755
type: Question
has body: Before this I used the code to say 'every button press it moves' but now I have changed it to 'when you press the button it moves in one direction until further instructions', but now the colliderect doesn't work. It worked before, and I'm still new to pygame. I have found a few similar issues but I think I've done what the people asking the questions have done. Any help at all is accepted. import pygame, sys, random from pygame.locals import * from time import sleep pygame.init() def render(): windowSurface.fill(black) player = pygame.Rect(225 + xmod,450 - ymod,30,30) pygame.draw.rect(windowSurface,white,player) pygame.draw.rect(windowSurface,white,wall_1) pygame.draw.rect(windowSurface,white,wall_2) pygame.display.update() black = (0,0,0) white = (255,255,255) windowSurface = pygame.display.set_mode((500, 500),0,32) windowSurface.fill(black) xmod = 0 ymod = 0 direction = 'none' player = pygame.Rect(225 + xmod,450 - ymod,30,30) wall_1 = pygame.Rect(0,225,250,50) wall_2 = pygame.Rect(300,250,200,50) render() while True: render() for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_LEFT: direction = 'left' if event.key == K_RIGHT: direction = 'right' if event.key == K_UP: direction = 'up' if event.key == K_DOWN: direction = 'down' if event.type == QUIT: pygame.quit() sys.exit() if player.colliderect(wall_1) or player.colliderect(wall_2): xmod = 0 ymod = 0 player = pygame.Rect(225 + xmod,450 - ymod,30,30) render() print('again') if direction == 'left': xmod -= 1 sleep(0.004) if direction == 'right': xmod += 1 sleep(0.004) if direction == 'up': ymod += 1 sleep(0.004) if direction == 'down': ymod -= 1 sleep(0.004)
upvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51782790
answers question: http://stackoverflow.com/q/51782558
accepted answer of: http://stackoverflow.com/q/51782558
has body: Here is a solution using scipy.signal.convolve2d : import scipy import numpy as np # Input matrix, can be left as boolean matrix = np.array([[True, False, False], [False, True, False], [False, False, False]]) # Our dougnut filter W = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) # Single convolve res = convolve2d(matrix, W, 'same') We get the exact result: res array([[1, 2, 1], [2, 1, 1], [1, 1, 1]])
has comment: http://stackoverflow.com/comment/90523338
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/90523677
has comment: http://stackoverflow.com/comment/90524643
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90269121
comment on: http://stackoverflow.com/a/51651976
score: 0
type: AnswerComment
type: Comment
has text: I fixed this. I installed the packages with sudo privileges and tried to run without it and that's the problem. When I provided sudo privileges it worked.

http://stackoverflow.com/comment/90332596
score: 0
type: QuestionComment
type: Comment
has text: I tried (4,1) and (1,4), both of them are error. I have no idea of that.
comment on: http://stackoverflow.com/q/51685117

http://stackoverflow.com/comment/90343585
type: Comment
comment on: http://stackoverflow.com/a/51690822
has text: This has the problem of recomputing this every time rather than treating them like static variables in Java (which is usually one of the motivations for using class-level variables). Also, this means you must instantiate a `Planet` object in order to use these variables instead of `Planet.ATMOSPHERE_GASES`
score: 0
type: AnswerComment

http://stackoverflow.com/q/51774445
tagged with: python
tagged with: memory-efficient
tagged with: dictionary
score: 3
has answer: http://stackoverflow.com/a/51775032
downvote count: 0
has comment: http://stackoverflow.com/comment/90507756
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/327311
has answer: http://stackoverflow.com/a/51775340
has comment: http://stackoverflow.com/comment/90507633
has body: I'm new to posting here, so I hope I provide enough detail. I'm trying to find out if key selection effects the efficiency of dictionaries in Python. Some comparisons I'm thinking of are: numbers vs strings (e.g. would my_dict[20] be faster than my_dict['twenty']) len of strings (e.g. would my_dict['a'] be faster than my_dict['abcdefg']) mixing key types within a dictionary, for instance using numbers, strings, and/or tuples (e.g. would my_dict = {0: 'zero', 2: 'two'} perform faster than {0: 'zero', 'two': 2}) I haven't been able to find this topic from a google search, so I thought maybe someone here might know.
upvote count: 3
linked to: http://stackoverflow.com/q/11162201
has comment: http://stackoverflow.com/comment/90508260
tagged with: processing-efficiency
has title: Efficient keys for dictionaries
tagged with: key
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51673635
has answer: http://stackoverflow.com/a/51673803
type: Question
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51673717
favorite count: 0
possible better answer: http://stackoverflow.com/a/51673724
has comment: http://stackoverflow.com/comment/90310289
has answer: http://stackoverflow.com/a/51673724
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51673717
score: 0
has comment: http://stackoverflow.com/comment/90310156
has title: Assign a function as a class method
upvote count: 1
has body: I want to pass only valid parameters to a function ("read_excel") I tried the following code but getting an error... import pandas as pd expected_keys=['io', 'sheet_name','header', 'names', 'index_col', 'usecols', 'squeeze', 'dtype', 'engine', 'converters', 'true_values', 'false_values', 'skiprows', 'nrows', 'na_values', 'parse_dates', 'date_parser', 'thousands', 'comment', 'skipfooter', 'convert_float'] def safe_read_excel(self, *args, **kwargs): if set(kwargs.keys()).difference(set(expected_keys)): raise ValueError('invalid parameter found') return self.read_excel(f_name, *args, **kwargs) pd.safe_read_excel = safe_read_excel When I use the default "read_excel" method a dataframe is created... df= pd.read_excel('sales_summary.xlsx', header=0) But my custom method throws an error... df= pd.safe_read_excel('sales_summary.xlsx', header=0) AttributeError: 'str' object has no attribute 'read_excel' How do I assign my function as pandas method?

http://stackoverflow.com/comment/113535936
score: 1
comment on: http://stackoverflow.com/a/57457530
type: AnswerComment
has text: Clean and simple! Wondering why this is not the selected answer.
type: Comment

http://stackoverflow.com/comment/90518454
has text: Thanks. I'll ask you one more question. Do you know how to save 20 pictures in one field?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51780092
type: Comment

http://stackoverflow.com/comment/90536252
has text: @mad_1 Do you want to edit your answer for the primary key to be 'scheduleId' so that i can mark it as correct?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51769244

http://stackoverflow.com/q/51671313
possible better answer: http://stackoverflow.com/a/51671721
has title: Combine numpy subarrays of varying dimensions
has answer: http://stackoverflow.com/a/51671721
tagged with: python
type: AnsweredQuestion
has body: I have a nested numpy array (dtype=object), it contains 333 arrays that increase consistently from size 52x1 to size 52x333 I would like to effectively extract and concatenate these arrays so that I have a single 52x55611 array I imagine this may be straightforward but my attempts using numpy.reshape have been unsuccesful
has answer: http://stackoverflow.com/a/51671871
type: Question
tagged with: numpy
tagged with: numpy-ndarray
score: 0
has comment: http://stackoverflow.com/comment/90305260
answer count: 2
accepted answer: http://stackoverflow.com/a/51671871

http://stackoverflow.com/q/51716345
favorite count: 0
has body: from random import randint as random names = ['Ninja','xXx_leet1337_xXx','robert87','nic0','y2ih8','roxky','Wierdio','a3rt','BeastyBoy','bobby'] active_players = names deaths = (' shotgunned ', ' sniped ', ' ran over ', ' rifled ') def findDeath(): current_death = deaths[random(0,3) while len(active_players) &gt;= 2: findDeath() if current_death = ' sniped ': sniper_length = str(random(5,100))+ 'm' print(active_players[random(0,9)]+' '+current_death+'from '+sniper_length) else: print(active_players) Output: File "..\Playground\", line 11 while len(active_players) >= 2: ^ SyntaxError: invalid syntax Why?
has title: Why does this code output a syntax error? (python)
has comment: http://stackoverflow.com/comment/90393960
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/51716358
accepted answer: http://stackoverflow.com/a/51716358
type: AnsweredQuestion
downvote count: 3
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/90488151
type: Comment
has text: @Anthony soup.findall returns a list. get_text should be applied to each element of the list, not the list itself. See my answer for more details.
score: 0
comment on: http://stackoverflow.com/q/51764239
type: QuestionComment

http://stackoverflow.com/comment/90553066
type: QuestionComment
has text: You only need the number of rectangles, or do you also need to enumerate them?
comment on: http://stackoverflow.com/q/51798058
score: 1
type: Comment

http://stackoverflow.com/q/51724583
tagged with: iterable
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51724723
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/51724701
has answer: http://stackoverflow.com/a/51724637
tagged with: loops
has title: Assigning elements to a lists within a list
type: Question
has body: I am running Python3.6 and am working with lists which contain other lists within it. list_array = [[1,0,1,0,2,2], [1,1,2,0,1,2], [2,2,2,1,0,1]] I would like to modify the list called list_array be deleting all the entries with value 2 within the sub lists. The code I used for this is for k in list_array: k = [x for x in k if x!=2] However, this code doesn't modify list_array. Why isn't it possible to replace the elements in the lists within list_array this way?
possible better answer: http://stackoverflow.com/a/51724701
has comment: http://stackoverflow.com/comment/90409503
answer count: 3
accepted answer: http://stackoverflow.com/a/51724637
downvote count: 0
has comment: http://stackoverflow.com/comment/90409430
favorite count: 0

http://stackoverflow.com/a/51762039
score: 6
has body: With &gt;&gt;&gt; elements = [[(0, 0, 0), 337.94174378689814], [(0, 0, 1), 339.92776762374007], [(0, 0, 2), 338.78632729456444], [(0, 1, 0), 344.85997106879347], [(0, 1, 1), 331.6819890120493], [0, 0]] we can write a list comprehension &gt;&gt;&gt; [element for element in elements if element != [0,0]] or (IMO more readable) with predicate def is_valid(element): return element != [0, 0] we can use filter built-in like # wrapping in ``list`` because in Python3 ``filter`` returns iterator &gt;&gt;&gt; list(filter(is_valid, elements)) [[(0, 0, 0), 337.94174378689814], [(0, 0, 1), 339.92776762374007], [(0, 0, 2), 338.78632729456444], [(0, 1, 0), 344.85997106879347], [(0, 1, 1), 331.6819890120493]]
downvote count: 0
answers question: http://stackoverflow.com/q/51761784
upvote count: 6
type: Answer

http://stackoverflow.com/q/51688660
type: Question
accepted answer: http://stackoverflow.com/a/51689392
has comment: http://stackoverflow.com/comment/90339127
has body: I have a GeoDataFrame with a column of float values and I want to transform them in int values, then overwrite the shapefile. import numpy as np import pandas as pd import geopandas as gpd gdf=gpd.read_file(r'.\folder\gdf.shp') This gdf has a column of float values, float_column: gdf["float_column"] 0 1.307500e+12 1 1.307500e+12 2 1.307500e+12 3 1.307500e+12 4 1.307500e+12 5 1.307500e+12 6 1.307500e+12 7 1.307500e+12 8 1.307500e+12 9 1.307500e+12 Then I apply a transformation: gdf["int_column"]=[int(x) for x in gdf["float_column"]] Which has these values (right transformation): gdf["int_column"] 0 1307500192816 1 1307500170116 2 1307500012418 3 1307500152317 4 1307500141816 5 1307500093417 6 1307500055117 7 1307500081117 8 1307500107717 9 1307500096916 10 1307500213815 Then I save the gdf: gdf.to_file(r".\folder\gdf.shp",driver='ESRI Shapefile',crs_wkt=prj) And when I cross-check the result int_column has these values: gdf_try=gpd.read_file(r'.\folder\gdf.shp') gdf_try["int_column"] 0 2147483647 1 2147483647 2 2147483647 3 2147483647 4 2147483647 5 2147483647 6 2147483647 7 2147483647 8 2147483647 9 2147483647 Which seems totally crazy! Did I miss something very stupid??
tagged with: numpy
has comment: http://stackoverflow.com/comment/90339355
score: 0
tagged with: pandas
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90339401
has answer: http://stackoverflow.com/a/51689392
tagged with: geopandas
has title: GeoPandas .to_file gives wrong column?
tagged with: python
has comment: http://stackoverflow.com/comment/90339393
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90339375
has comment: http://stackoverflow.com/comment/90339428

http://stackoverflow.com/comment/90352117
type: AnswerComment
type: Comment
has text: You know what, I think I understand what you are saying now. Because etree.pyx right?
comment on: http://stackoverflow.com/a/51679635
score: 0

http://stackoverflow.com/comment/90495878
has text: @DietrichEpp Code review does not accept neither code that is not working, nor code that is simplified for the purpose of demonstrating a specific behaviour. This question has a clear problem (code hangs) that can be addressed on SO.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51756938

http://stackoverflow.com/q/51721881
has title: Fetch all user's input ( input ) in .aiml file and append it on a list
score: 0
has comment: http://stackoverflow.com/comment/90405450
answer count: 1
accepted answer: http://stackoverflow.com/a/51723722
has body: Currently my task is to get all the user's input inside the .aiml file, and append it to a list using Python3. Below is the code: topic.aiml <?xml version = "1.0" encoding = "UTF-8"?> HELLO ALICE Hello User HOW ARE YOU I'm fine WHAT ARE YOU DOING Coding WHERE YOU FROM Manila test.py @extract.route('/') def index_page(): folder = 'templates/topic.aiml' data_set = [] with open(folder, 'r') as myfile: data = myfile.read().replace('\n', '') return data Return value is: HELLO ALICE HOW ARE YOU WHAT ARE YOU DOING WHERE YOU FROM, which is correct. But I don't know how will I append it to data_set I'm just to new to this kind of task that the team gave to me. Much appreciated if someone know how to manipulate this one. Thanks! Below is the result. Return value from topic.aiml
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90434018
type: Question
has answer: http://stackoverflow.com/a/51723722
tagged with: aiml
tagged with: flask
favorite count: 0

http://stackoverflow.com/comment/90513567
comment on: http://stackoverflow.com/a/51757878
score: 0
type: AnswerComment
has text: @SuperUser_15: Since `img` is jsut an array of numbers by using `pd.DataFrame(img)` it will by default be a single column. Using `[img]` instead means that your values are now in the first position of a two dim array and it will become a row in the dataframe. You could try adding more arrays and see that more rows are added. Finally, the last one is a three dim array and will put all values in the (0,0) position of the dataframe.
type: Comment

http://stackoverflow.com/comment/90363535
type: Comment
type: QuestionComment
has text: @PatrickArtner these json commit ids are in descending format like latest(first dict) are recently commit and below are the old commits in a serial order.
score: 0
comment on: http://stackoverflow.com/q/51700973

http://stackoverflow.com/q/51725921
has answer: http://stackoverflow.com/a/51726102
has answer: http://stackoverflow.com/a/51728565
has body: How do you determine if a list contains either 3 even or 3 odd values all next to each other? Example lists (True, False, True): [2, 1, 3, 5] [2, 1, 2, 5] [2, 4, 2, 5] Closest code: evenOdd = [] while True: try: n = int(input()) evenOdd.append(n) except: break for x in evenOdd: if x % 2 == 0: print("True")
has answer: http://stackoverflow.com/a/51733100
has answer: http://stackoverflow.com/a/51726172
has answer: http://stackoverflow.com/a/51726083
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/90412118
tagged with: python
has answer: http://stackoverflow.com/a/51726291
answer count: 10
upvote count: 4
tagged with: python-3.x
tagged with: list
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51726377
has title: How to determine if a list contains either 3 even or 3 odd values next to each other?
has answer: http://stackoverflow.com/a/51726159
has answer: http://stackoverflow.com/a/51726583
type: Question
has answer: http://stackoverflow.com/a/51726143

http://stackoverflow.com/comment/90487633
has text: added the first 20 datapoints and the graph image and link if image does not work
comment on: http://stackoverflow.com/q/51762514
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51765159
has comment: http://stackoverflow.com/comment/90489118
downvote count: 0
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51765116
type: Answer
has body: You can get the type of the object, to then initialize another object if type(event) == Event1 or type(event) == Event2: new_event = type(event)(some_id) As a side note, I generally prefer isinstance if isinstance(event, (Event1, Event2)): new_event = type(event)(some_id)

http://stackoverflow.com/q/51681081
upvote count: 1
has comment: http://stackoverflow.com/comment/90326742
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51684499
type: UnansweredQuestion
tagged with: python
has body: Okay, output maybe isn't clear if you don't know the language. Here is example: 0 1 2 3 4 x = ['text1','text2','text3' ,'text4','text5'] - scrapped_sentence[-30+position:position+30], where position is taken from re.finditer y = [ '-' , '-' ,['text1'], '-' ,['text2']] - texts from re.findall out=[ '-' , '-' , text1 , '-' , 'text2'] - scrapped sentence Problem: I'm trying to figure out the code that would replace one list with another on places that are not minuses. List of indexes of the first list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] List of indexes of the second list: [37, 39, 41, 42, 43, 50, 63, 69] First list: ['gospodarcze: gospodarcze ', 'parking: parkingo', 'parking: parkingo', 'garaż: garaże', 'garaż: garaże', 'garaż: garaże', 'garaż: garaże', 'ogród: ogród.', 'ogród: ogród.', 'ogrod: ,ogrode', 'ogrod: ,ogrode', 'remon: remont', 'aneks: anekse', 'aneks: anekse', 'zabudow: zabudowi', 'zabudow: zabudowi'] In first list there will be more characters (sentences +/-60 chars.). Here is short (+/1 char.) for better view. Second list: ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ['gospodarcze'], '-', ['parking', 'parking'], '-', ['garaż', 'garaż', 'garaż', 'garaż'], ['ogród', 'ogród'], ['ogrod', 'ogrod'], '-', '-', '-', '-', '-', '-', ['remon'], '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ['aneks', 'aneks'], '-', '-', '-', '-', '-', ['zabudow', 'zabudow'], '-', '-', '-', '-', '-', '-', '-', '-'] Desired output is overlaping the list. I know it is kind of impossible right now, because First list should have some nested values such as 'parking: parkingo', 'parking: parkingo. Still working on it. ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 'gospodarcze: gos…
tagged with: list
has comment: http://stackoverflow.com/comment/90325834
has title: Replacing values in the list (lists overlap)
downvote count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90325588
has comment: http://stackoverflow.com/comment/90331117

http://stackoverflow.com/comment/90548521
type: QuestionComment
type: Comment
has text: Please post a [mcve] in your question
score: 0
comment on: http://stackoverflow.com/q/51795486

http://stackoverflow.com/comment/90472719
comment on: http://stackoverflow.com/a/51756620
type: Comment
has text: It doesn't use semicolons either, and depending on the version of Python, there should also be no parentheses after the `print` statement.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51786223
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51786133
has body: your question is defying the rules of mathematics. Matrix A and B cannot be multiplied together because the number of columns in A does not equal the number of rows in B. In this case, the multiplication of these two matrices is not defined
has comment: http://stackoverflow.com/comment/90530479
has comment: http://stackoverflow.com/comment/90529441

http://stackoverflow.com/a/51760092
answers question: http://stackoverflow.com/q/51759721
accepted answer of: http://stackoverflow.com/q/51759721
type: Answer
upvote count: 6
score: 6
type: AcceptedAnswer
downvote count: 0
has body: Maybe the regex module is the way to go &gt;&gt;&gt; s = 'test\x06\x06\x06\x06' &gt;&gt;&gt; s1 = 'test2\x04\x04\x04\x04' &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub('[^A-Za-z0-9]+', '', s) 'test' &gt;&gt;&gt; re.sub('[^A-Za-z0-9]+', '', s1) 'test2'

http://stackoverflow.com/q/51724021
answer count: 1
favorite count: 0
tagged with: ajax
has title: Jquery, Ajax (failed) net::ERR_CONNECTION_REFUSED
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51726730
upvote count: 1
tagged with: google-chrome
has body: I'm getting (failed) net::ERR_CONNECTION_REFUSED after i reload my page and execute the script first time, after that it works just fine. Any ideas why? I won't post the whole script of my python and jquery because it will be too long(~1200 lines combined), rather I will post the parts that are responsible for the request to happen. Python: class testHTTPServer_RequestHandler(BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.send_header('Content-type','application/json; charset=utf-8') self.send_header('Access-Control-Allow-Origin', 'http://localhost') self.end_headers() content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) parsed_q = urlparse(self.path) parsed_b = urlparse(body.decode("utf-8")) search_info = urllib.parse.parse_qs(parsed_q.query) user_info = urllib.parse.parse_qs(parsed_b.path) luk = ''.join(search_info['search']) wer = ''.join(search_info['parde']) user_id = ''.join(user_info['user']) self.wfile.write(bytes(where_to(luk, wer, user_id), "utf8")) return def do_GET(self): print ("get request...") self.send_response(200) self.send_header('Content-type','text/html; charset=utf-8') self.send_header('Access-Control-Allow-Origin', '*') self.end_headers() message = "Nothing to see here." self.wfile.write(bytes(message, "utf8")) return Jquery or Ajax: else{ $(".peenum").html(""); $(".cont_row").html(""); $('.progress-bar').css({"width": "0%"}) var dat = Cookies.get() $(".where").each(function(){ var url = 'http://localhost:8081/?search='+$("#enter_look_for").val()+'&amp;parde='+$(this).val(); $.ajax({ url: url, method: "POST", data: dat, success: pajiehali }); }); } If this information isn't enough feel free to ask, I'll post all of my code if that's what it takes to figure it out.
has comment: http://stackoverflow.com/comment/90409655
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90410123
score: 1
accepted answer: http://stackoverflow.com/a/51726730
type: Question
tagged with: firefox
has comment: http://stackoverflow.com/comment/90408923
downvote count: 0

django-views
tags question: http://stackoverflow.com/q/51682774
tags question: http://stackoverflow.com/q/51644960
tags question: http://stackoverflow.com/q/51709984
tags question: http://stackoverflow.com/q/51688125
tags question: http://stackoverflow.com/q/51700954
tags question: http://stackoverflow.com/q/51779319
tags question: http://stackoverflow.com/q/51677078
tags question: http://stackoverflow.com/q/51696116
tags question: http://stackoverflow.com/q/51770468
tags question: http://stackoverflow.com/q/51775331
tags question: http://stackoverflow.com/q/51710854
tag name: django-views
tags question: http://stackoverflow.com/q/51663042
type: Tag
tags question: http://stackoverflow.com/q/51759862
tags question: http://stackoverflow.com/q/51790935
tags question: http://stackoverflow.com/q/51725642
tags question: http://stackoverflow.com/q/51758845
tags question: http://stackoverflow.com/q/51660571
tags question: http://stackoverflow.com/q/51772361
tags question: http://stackoverflow.com/q/51674127
tags question: http://stackoverflow.com/q/51690580
tags question: http://stackoverflow.com/q/51664603
tags question: http://stackoverflow.com/q/51735871
tags question: http://stackoverflow.com/q/51747086
tags question: http://stackoverflow.com/q/51755692
tags question: http://stackoverflow.com/q/51772237
tags question: http://stackoverflow.com/q/51643680
tags question: http://stackoverflow.com/q/51795121

http://stackoverflow.com/q/51655373
has answer: http://stackoverflow.com/a/51660436
score: 0
answer count: 1
tagged with: zabbix
type: UnansweredQuestion
tagged with: python
has title: pyzabbix get hostid from hostname
type: Question
has body: I'm just starting to use pyzabbix. I'm wanting to find a specific host's ID from it's name. All the examples I read about do something like this, where the desired host_id is the first element [0] in a filtered (by host) list of hosts: host_name = 'ci-dev' host_id = zapi.host.get({"filter":{"host":host_name}})[0]["hostid"] However, when I view the list of host with host_id = zapi.host.get({"filter":{"host":host_name}}), the first element is not the host I'm looking for. Regardless of which host I'm filtering for, the first host in the list of hosts is always our Zabbix server. The host I'm filtering for is usually way down the list. What am I going wrong?

http://stackoverflow.com/q/51742596
type: Question
has comment: http://stackoverflow.com/comment/90445253
has title: Sphinx doc struggling with import typing
has comment: http://stackoverflow.com/comment/90449632
score: 0
has comment: http://stackoverflow.com/comment/90489560
answer count: 1
has comment: http://stackoverflow.com/comment/90448189
linked to: http://stackoverflow.com/q/9002901
tagged with: python
has body: today, I setup a simple sphinx job for my python project. When I hit "make html" it crashes with the following messages: WARNING: autodoc: failed to import module 'myname.mymodule'; the following exception was raised: cannot import name 'MyClass' I deleted line by line and now, if I remove from typing import Tuple in front of myname.mymodule, sphinx does the docu with errors (can't find Tuple) of course. I can easily attach the log, referenced by sphinx, but the only intresting in it is this: while not self.fetch_token().match([OP, '='], NEWLINE, COMMENT): AttributeError: 'NoneType' object has no attribute 'match' Does sphinx has a problem with typing? Or is there something broken with my imports ?
tagged with: python-typing
has comment: http://stackoverflow.com/comment/90487174
has comment: http://stackoverflow.com/comment/90487204
has answer: http://stackoverflow.com/a/51839821
tagged with: python-sphinx
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90487143

http://stackoverflow.com/comment/90308285
score: 0
comment on: http://stackoverflow.com/q/51672288
type: Comment
type: QuestionComment
has text: So the closest you're going to get is to use what chepner first suggested and make `Person` iterable, so you can do stuff like `name, age = p` or `t = tuple(p)`, or `seq = [*p]`. Etc.

http://stackoverflow.com/q/51790676
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51790809
has comment: http://stackoverflow.com/comment/90539245
favorite count: 0
has answer: http://stackoverflow.com/a/51790864
type: Question
has comment: http://stackoverflow.com/comment/90538915
answer count: 2
has body: I want to have an object of a class within a class, because I need to pass it to a method, similarly to the example below. I would like the example below to print out 1, or fooObj.fooNum, but I keep getting a NameError: name 'foo' is not defined. class bar: def fooDef(self, fooObj): print fooObj.fooNum class foo: fooNum = 1 b = bar() f = foo() b.fooDef(f)
linked to: http://stackoverflow.com/q/12179271
tagged with: python
has comment: http://stackoverflow.com/comment/90539082
tagged with: object
has title: Create an object of the same class within the class
has comment: http://stackoverflow.com/comment/90538932
downvote count: 3
has comment: http://stackoverflow.com/comment/90538853
has comment: http://stackoverflow.com/comment/90538931
upvote count: 0
linked to: http://stackoverflow.com/q/2546608
type: UnansweredQuestion
score: -3
tagged with: class
has comment: http://stackoverflow.com/comment/90538998

http://stackoverflow.com/a/51789157
has comment: http://stackoverflow.com/comment/90539361
answers question: http://stackoverflow.com/q/51788990
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: def dict_unzip(lst): for x in lst: yield reversed(x.split(' ', 1)) my_dict = dict(dict_unzip(my_list)) But since it's Python3 things are notably simpler actually: my_dict = dict(map(lambda s: reversed(s.split(' ', 1)), my_list)) Or even my_dict = dict(reversed(s.split(' ', 1)) for s in my_list)
type: Answer
accepted answer of: http://stackoverflow.com/q/51788990

keras
tags question: http://stackoverflow.com/q/51643987
tags question: http://stackoverflow.com/q/51684475
tags question: http://stackoverflow.com/q/51682648
tags question: http://stackoverflow.com/q/51760851
tags question: http://stackoverflow.com/q/51713512
tags question: http://stackoverflow.com/q/51684041
tags question: http://stackoverflow.com/q/51751131
tags question: http://stackoverflow.com/q/51772853
tags question: http://stackoverflow.com/q/51775966
tags question: http://stackoverflow.com/q/51682118
tags question: http://stackoverflow.com/q/51656000
tags question: http://stackoverflow.com/q/51655941
tags question: http://stackoverflow.com/q/51764642
tags question: http://stackoverflow.com/q/51659198
tags question: http://stackoverflow.com/q/51705464
tags question: http://stackoverflow.com/q/51697695
tags question: http://stackoverflow.com/q/51699514
tags question: http://stackoverflow.com/q/51657456
tags question: http://stackoverflow.com/q/51755271
tags question: http://stackoverflow.com/q/51678213
tags question: http://stackoverflow.com/q/51791935
tags question: http://stackoverflow.com/q/51705206
tags question: http://stackoverflow.com/q/51739016
tags question: http://stackoverflow.com/q/51734955
tags question: http://stackoverflow.com/q/51794398
tags question: http://stackoverflow.com/q/51767167
tags question: http://stackoverflow.com/q/51746179
tags question: http://stackoverflow.com/q/51669382
tags question: http://stackoverflow.com/q/51753328
tags question: http://stackoverflow.com/q/51762528
tags question: http://stackoverflow.com/q/51798708
tags question: http://stackoverflow.com/q/51751163
tags question: http://stackoverflow.com/q/51700351
tags question: http://stackoverflow.com/q/51755160
tags question: http://stackoverflow.com/q/51731207
tags question: http://stackoverflow.com/q/51695149
tags question: http://stackoverflow.com/q/51748106
tags question: http://stackoverflow.com/q/51728071
tags question: http://stackoverflow.com/q/51706730
tags question: http://stackoverflow.com/q/51732258
tags question: http://stackoverflow.com/q/51776922
tags question: http://stackoverflow.com/q/51730484
tags question: http://stackoverflow.com/q/51722790
tags question: http://stackoverflow.com/q/51677314
tags question: http://stackoverflow.com/q/51757355
tags question: http://stackoverflow.com/q/51645149
tags question: http://stackoverflow.com/q/51699867
tags question: http://stackoverflow.com/q/51783527
tags question: http://stackoverflow.com/q/51679311
tags question: http://stackoverflow.com/q/51746327
tags question: http://stackoverflow.com/q/51731419
tags question: http://stackoverflow.com/q/51724699
tags question: http://stackoverflow.com/q/51711832
tags question: http://stackoverflow.com/q/51751252
tags question: http://stackoverflow.com/q/51672903
tags question: http://stackoverflow.com/q/51785432
tags question: http://stackoverflow.com/q/51720720
tags question: http://stackoverflow.com/q/51750347
tags question: http://stackoverflow.com/q/51696613
tags question: http://stackoverflow.com/q/51684952
tags question: http://stackoverflow.com/q/51755320
tags question: http://stackoverflow.com/q/51663348
tags question: http://stackoverflow.com/q/51732525
tags question: http://stackoverflow.com/q/51641921
tags question: http://stackoverflow.com/q/51772307
tags question: http://stackoverflow.com/q/51748514
tags question: http://stackoverflow.com/q/51737993
tags question: http://stackoverflow.com/q/51716189
tags question: http://stackoverflow.com/q/51718396
tags question: http://stackoverflow.com/q/51699001
tags question: http://stackoverflow.com/q/51652690
tags question: http://stackoverflow.com/q/51697727
tags question: http://stackoverflow.com/q/51728648
tags question: http://stackoverflow.com/q/51701120
tags question: http://stackoverflow.com/q/51696464
tags question: http://stackoverflow.com/q/51677111
tags question: http://stackoverflow.com/q/51748305
tags question: http://stackoverflow.com/q/51657476
tags question: http://stackoverflow.com/q/51735090
tags question: http://stackoverflow.com/q/51649109

http://stackoverflow.com/a/51661515
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51660901
type: Answer
answers question: http://stackoverflow.com/q/51660901
has body: You don't need to escape the % instances in the string that is to the right of the % in the generation of the query so: match = r"%exam\%ple%" # Use r string to avoid having to double \s query = """ SELECT * FROM table WHERE name LIKE "%s" """ % (match) print(query) # as a check Results in: SELECT * FROM table WHERE name LIKE "%exam\%ple%" Also note that you can effectively escape, i.e. make literal, % characters by doubling them, i.e. %d = insert number but %%d = insert "%d" however you will need to double for each % operation that you are performing. A better alternative would be to use the string format command which is available in both python 3.4+ any python 2.7. This uses {} as a marker for insertion points, (it is classed as a mini-language), and will not touch your % signs. In [2]: "{} == {}".format(1,2) Out[2]: '1 == 2' In [3]: match = r"%exam\%ple%" # Use r string to avoid having to double \s In [4]: query = """ ...: SELECT * ...: FROM table ...: WHERE name LIKE "{}" ...: """.format(match) In [5]: print(query) SELECT * FROM table WHERE name LIKE "%exam\%ple%"
has comment: http://stackoverflow.com/comment/90539353
has comment: http://stackoverflow.com/comment/90550680
has comment: http://stackoverflow.com/comment/90544454
has comment: http://stackoverflow.com/comment/90545591

http://stackoverflow.com/q/51672398
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90309786
has comment: http://stackoverflow.com/comment/90307609
has comment: http://stackoverflow.com/comment/90308816
answer count: 1
has comment: http://stackoverflow.com/comment/90311601
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90311508
has comment: http://stackoverflow.com/comment/90308528
has title: Randomly dropping rows with a condition using pandas
has answer: http://stackoverflow.com/a/51675553
type: Question
has comment: http://stackoverflow.com/comment/90309877
has body: I have a dataset that is unbalanced such as: tag #elements a 1500 b 3250 c 320 d 260 It causes overfitting. I want to eleminate some of the rows that have certain name randomly so my dataset will be more balanced. For example after elemination I want something like this; tag #elements a 300 b 300 c 300 d 260 But, I appriciate it, if possible to eleminate them randomly between some range such as lowest number of elements (260 in our case), plus 50 or so (I don't know the right way to perform it.). So, after elemination number of elements will be something like this: tag #elements a 307 b 286 c 275 d 260 Please note that, these numbers corresponds to the number of tags. Length of dataset is 5330 in total. I want to reduce it. Thanks in advance.

http://stackoverflow.com/comment/91313777
score: 0
has text: in the latest version of the code I can locate (serial delete of what doesn't work!) im getting error "'list' object has no attribute 'T'". The document corpus (X) is a list with word vectors. vector_norms = np.array([np.sqrt(np.sum(np.square(v))) for v in dfCorpusWV]) X = (dfCorpusWV.T / vector_norms).T
type: AnswerComment
comment on: http://stackoverflow.com/a/51652111
type: Comment

http://stackoverflow.com/comment/90295825
comment on: http://stackoverflow.com/q/51665568
has text: A nicer idiom than stepping integer k through separate lists `x_move, y_move` is to directly do `for (x_move, y_move) in ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)):`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51697061
tagged with: batch-rename
has body: I have a set of files, not necessarily of the same extension. These files were created by a Python script that iterates over some files (say x.jpg, y.jpg, and z.jpg), and then numbers them with zero-padding so that the numbers are of length 7 characters (in this example, the filenames become 0000001 - x.jpg, 0000002 - y.jpg, and 0000003 - z.jpg). I now need a script (any language is fine, but Bash/zsh is preferred), that will increment these numbers by an argument. Thereby renaming all the files in the directory. For example, I'd like to call the program as (assuming a Shell script): ./rename.sh 5 The numbers in the final filenames should be padded to length 7, and it's guaranteed that there's no file initially whose number is 9999999. So the resulting files should be 0000006 - x.jpg, 0000007.jpg, 0000008.jpg. It's guaranteed that all the files initially are incremental; that is, there are no gaps in the numbers. I can't seem to do this easily at all in Bash, and it seems kind of like a chore even in Python. What's the best way to do this? Edit: Okay so here are my efforts so far. I think the leading 0s are a problem, so I removed them using rename: rename 's/^0*//' * Now with just the numbers left, I'd ideally use a loop, something like this, but I'm not exactly familiar with the syntax and why this is wrong: for file in "(*) - (*)" ; do mv "${file}" "$(($1+5)) - ${2}" ; done The 5 there is just hard-coded, but I guess changing that to the first argument shouldn't be too big a deal. I can then use another loop to add the 0s back.
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90355662
accepted answer: http://stackoverflow.com/a/51697189
score: 0
has comment: http://stackoverflow.com/comment/90355486
has comment: http://stackoverflow.com/comment/90355666
has title: How to increment number with leading zeros in filename
has comment: http://stackoverflow.com/comment/90355597
tagged with: bash
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90355596
has comment: http://stackoverflow.com/comment/90355625
has comment: http://stackoverflow.com/comment/90355609
has answer: http://stackoverflow.com/a/51697189

http://stackoverflow.com/a/51728844
has body: You can use functools.reduce with operator.getitem for this: a = [[[1,2],[3,4]], [[5,6],[7,8]]] from functools import reduce from operator import getitem def foo(L, idx, var): reduce(getitem, idx[:-1], L)[idx[-1]] = var foo(a, [0,0,0], 'one') print(a) [[['one', 2], [3, 4]], [[5, 6], [7, 8]]]
type: Answer
accepted answer of: http://stackoverflow.com/q/51728719
score: 4
answers question: http://stackoverflow.com/q/51728719
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90418518

http://stackoverflow.com/comment/90423204
type: QuestionComment
score: 0
type: Comment
has text: Note that there are parentheses around your path; that doesn't seem to be correct.
comment on: http://stackoverflow.com/q/51731220

http://stackoverflow.com/a/51779373
has body: python2 &gt;&gt;&gt; import ipaddress &gt;&gt;&gt; print ipaddress.ip_network(u'192.168.0.1/0.0.0.15', strict=False).netmask 255.255.255.240 python3 &gt;&gt;&gt; import ipaddress &gt;&gt;&gt; print(ipaddress.ip_network('192.168.0.1/0.0.0.15', strict=False).netmask) 255.255.255.240
type: Answer
answers question: http://stackoverflow.com/q/51773707
score: 0

http://stackoverflow.com/comment/90442811
type: QuestionComment
has text: There is a comma at the end of the `get_object_or_404`, so you wrap the result in a *singleton* tuple.
comment on: http://stackoverflow.com/q/51741398
score: 0
type: Comment

http://stackoverflow.com/comment/90380384
comment on: http://stackoverflow.com/q/51709572
type: QuestionComment
type: Comment
has text: [`__len__()` should return a single integer](https://docs.python.org/3/reference/datamodel.html#object.__len__). what are you trying to achieve?
score: 7

http://stackoverflow.com/q/51762534
answer count: 2
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90484149
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/78503336
upvote count: 1
has answer: http://stackoverflow.com/a/51765087
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/90484686
downvote count: 0
has title: SQLAlchemy reverse ordered query
has body: What the best way to reverse ordered query? Can I do it only with sql/sqlalchemy? For example if I have rows with ids: [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10] I want to fetch rows after id 5 with limit 3 in order like that [8, 7, 6] For now it works with: Comment.query.filter(Comment.id &gt; 5).order_by(Post.id.asc()).limit(3) I got list with ids [6, 7, 8] and after I use list.reverse() in Python to get list with order [8,7,6] This doesn't work: Comment.query.filter(Comment.id &gt; 5).order_by(Post.id.desc()).limit(3) it will give list with ids [10,9,8]
tagged with: flask-sqlalchemy
tagged with: postgresql

featuretools
tag name: featuretools
type: Tag
tags question: http://stackoverflow.com/q/51715923

http://stackoverflow.com/q/51720280
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Is it possible to constrain an (abstract) base method only on the return type but keep the parameters flexible?
has comment: http://stackoverflow.com/comment/90401496
type: Question
tagged with: mypy
has answer: http://stackoverflow.com/a/51724793
has body: Is it possible to constrain an (abstract) base method only on the return type but keep the arguments of that method entirely flexible for children to implement in any way they want? E.g. import abc class Mother(abc.ABC): @abc.abstractmethod def foo(self) -&gt; int: pass class Child(Mother): def foo(self, val: int) -&gt; int: return val * 2 This raises: $ mypy inheritance.py inheritance.py:12: error: Signature of "foo" incompatible with supertype "Mother" Because Child implements foo with an argument val that isn't defined in the foo method of Mother. The only way I see is to make Mother generic over some container type that foo would accept but what I really want is to be as flexible in Child as I want so that I can use any number of parameters and really be only constraint in the return type of the method.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90404591
tagged with: inheritance
favorite count: 0
accepted answer: http://stackoverflow.com/a/51724793
tagged with: python

http://stackoverflow.com/comment/90360977
type: QuestionComment
score: 0
has text: @StephenRauch - how would you loop through every file in the dir if I remove listdir,do you mind being more specific?
comment on: http://stackoverflow.com/q/51699751
type: Comment

http://stackoverflow.com/a/51760010
downvote count: 0
has comment: http://stackoverflow.com/comment/90479361
accepted answer of: http://stackoverflow.com/q/51759798
score: 1
has body: f-strings can only evaluate expressions that are literally in your source code, inside the f-string. If you want to evaluate a string containing the representation of an expression as if it were source code, you need to use eval. There are a whole host of reasons why eval is almost always a bad idea (tl;dr: anyone who can change the input you pass to eval can get you to run any code they want). But if that's really what you want to do, that's the way to do it: if line: lines = line.strip() input(f"Does {lines}?&gt;") print(eval(lines)) If you want to do something safer, the only thing you can do is parse and interpret the code as something safer than "any Python expression". That's not as hard as it sounds (especially since, if your language is an exact subset of Python, you can just use the ast module to do the parsing, and you only have to write the interpreter part), but it's not exactly a one-liner.
has comment: http://stackoverflow.com/comment/90479550
answers question: http://stackoverflow.com/q/51759798
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51793860
type: Answer
score: 1
has body: I could not reproduce the error, so I'll admit some of this is guesswork. I suspect chmod -R 755 /home/alex/.astropy will resolve the issue. If /home/alex/.astropy doesn't exist, create it first: mkdir /home/alex/.astropy. After you execute these commands in your shell, try the import again.
upvote count: 1
has comment: http://stackoverflow.com/comment/90653293
downvote count: 0
answers question: http://stackoverflow.com/q/51793714

regression
tags question: http://stackoverflow.com/q/51703845
tags question: http://stackoverflow.com/q/51660001
tags question: http://stackoverflow.com/q/51660648
tags question: http://stackoverflow.com/q/51718734
tag name: regression
type: Tag
tags question: http://stackoverflow.com/q/51665236
tags question: http://stackoverflow.com/q/51732577

http://stackoverflow.com/comment/90469925
type: Comment
type: QuestionComment
has text: Not really since this as about variable assignment not dict access
comment on: http://stackoverflow.com/q/51755013
score: 0

http://stackoverflow.com/comment/90565024
comment on: http://stackoverflow.com/q/51792139
score: 0
has text: It looks like @cdlane added those tags for you this time. In the future, click the 'edit' button and add those tags, just like the two your added initially (ie, [graphics] and [defaults])
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90441365
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51740541
has text: this may help you, ```json_name = request.args.get('jsonname', default = '', type = str)```
score: 0

http://stackoverflow.com/q/51686130
tagged with: temporary-files
has answer: http://stackoverflow.com/a/70174744
has body: I have created a temporary directory in python where I am saving a bunch of .png files for later use. My code seemingly works fine up until the point where I need to access those .png files - when I do so, I get the following error: TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory The error is thrown when I pass the temporary directory in os.path.join: import os import tempfile t_dir = tempfile.TemporaryDirectory() os.path.join (t_dir, 'sample.png') Traceback (most recent call last): File "&lt;ipython-input-32-47ee4fce12c7&gt;", line 1, in &lt;module&gt; os.path.join (t_dir, 'sample.png') File "C:\Users\donna\Anaconda3\lib\ntpath.py", line 75, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory However, using gettempdir() seems to work fine. import os import tempfile t_dir = tempfile.gettempdir() os.path.join (t_dir, 'sample.png') The python docs suggests tempfile.TemporaryDirectory works using the same rules as tempfile.mkdtemp() (https://docs.python.org/3.6/library/tempfile.html#tempfile.TemporaryDirectory), and I would think tempfile.TemporaryDirectory is the preferred method for python 3.x. Any ideas why this throws an error or if one of these methods is preferred over the other for this use case?
score: 12
type: Question
answer count: 2
upvote count: 12
has title: Reading from a temporary directory in python: TypeError: expected str, bytes or os.PathLike object, not TemporaryDirectory
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/54358146
tagged with: windows
type: UnansweredQuestion
tagged with: python
tagged with: filepath

http://stackoverflow.com/a/51718377
type: Answer
score: 0
has body: I don't think it is possible because the current working directory is an attribute of a process. This means it cannot be changed by another program, such as your python script.
answers question: http://stackoverflow.com/q/51718334

http://stackoverflow.com/comment/118683485
comment on: http://stackoverflow.com/a/51673969
score: 57
type: Comment
type: AnswerComment
has text: FWIW, dataclasses can also be immutable, hashable, iterable and comparable. The `dataclass()` decorator accepts a kwarg `frozen=True`.

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51788574
type: Tag

http://stackoverflow.com/a/51654313
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90272838
type: Answer
answers question: http://stackoverflow.com/q/51647923
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51647923
has comment: http://stackoverflow.com/comment/90272161
has comment: http://stackoverflow.com/comment/90293094
upvote count: 2
has body: In TeX math mode it is standard to display mathematical expressions with a dedicated math font (usually the italic version of the font you use). Matplotlib seems to mimic this behaviour. In TeX (or LaTeX) you can get the old font back by using the mathrm command, which appears to work also in matplotlib, like so: import matplotlib as mlp,numpy as np mlp.rc('font',family='Times New Roman') import matplotlib.pyplot as plt fig,axes = plt.subplots(1,2); axes[0].set_xlabel('N$_{sou}$=20',fontsize=20) axes[0].set_title('normal math mode') axes[1].set_xlabel('N$_\mathrm{sou}$=20', fontsize=20) axes[1].set_title('using \mathrm') plt.show()

http://stackoverflow.com/q/51686489
accepted answer: http://stackoverflow.com/a/51686513
tagged with: machine-learning
downvote count: 1
has answer: http://stackoverflow.com/a/51686543
upvote count: 0
possible better answer: http://stackoverflow.com/a/51686543
has title: Fill missing value
tagged with: data-science
has comment: http://stackoverflow.com/comment/90335135
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51686513
has body: I have a data sets which has column with missing value 2439. But the missing value is such that for specific index has some missing value and some fill value as shown below (Compare column 'Item_Identifier' and 'Item_Weight') If carefully seen for specific item_identifier, there missing value in item_weight. Like this there many more Item_Identifier which missing value. Is there any way using python we fill missing value for only item_weight as same.
favorite count: 0
score: -1
linked to: http://stackoverflow.com/q/944700
type: Question
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90335108

http://stackoverflow.com/comment/90267709
type: QuestionComment
has text: @TobiasBrösamle Thank you for your questions. I've updated my code to hopefully help with the understanding.
comment on: http://stackoverflow.com/q/51651281
score: 0
type: Comment

http://stackoverflow.com/comment/90524570
has text: Yes, your multiplying the 9 fist integers together which is 9! wich is 3628800. More info [link](https://www.wikiwand.com/en/Factorial)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51782326

http://stackoverflow.com/comment/90359584
comment on: http://stackoverflow.com/a/51699030
score: 0
type: AnswerComment
type: Comment
has text: Hi Alex, That gives me "Dec" when I call getMonth(0). It needs to be 'ERROR: out of range!'

http://stackoverflow.com/a/73438409
answers question: http://stackoverflow.com/q/51717720
type: Answer
has body: hello I recommend that you first send this validation before sending the reset so you avoid headaches reinicioNGINX = subprocess.getoutput(['nginx -t']) if 'nginx: the configuration file /etc/nginx/nginx.conf syntax is ok' in reinicioNGINX: _command_restart else: _command_avoid_restart
score: 0

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/51644831

http://stackoverflow.com/comment/90363346
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51701087
has text: [use of global keyword](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python)
score: 0

http://stackoverflow.com/q/51767758
upvote count: 1
downvote count: 1
has body: I have a tensor x of type tf.float32 and I would like to apply softmax over all entries. Unfortunately, the built-in function can apply softmax along a specified axis only. The solution I thought of: e = tf.exp(x) softmaxed = e / tf.reduce_sum(e) does not work - if x has too big entries (e.g. 100), then e cannot be calculated properly.
tagged with: tensorflow
type: Question
answer count: 1
has title: TensorFlow: Softmax applied to each entry
favorite count: 0
has answer: http://stackoverflow.com/a/51770760
tagged with: python
accepted answer: http://stackoverflow.com/a/51770760
type: AnsweredQuestion
score: 0
tagged with: softmax

http://stackoverflow.com/comment/90476707
type: Comment
score: 1
has text: Yes, sure, give me a sec.
type: AnswerComment
comment on: http://stackoverflow.com/a/51758635

http://stackoverflow.com/a/51699071
has body: I am not sure what your expected output is but if you want to find the mean of the closest size on the dates that have more than one transaction you could do something like this. If you are looking for something else please provide an expected output: df = pd.read_clipboard() # find the diff on the size column and backfill the NaN values df['diff'] = df.groupby('date')['size'].diff().fillna(method='bfill') # group by date and use the lambda function to find the min diff df2 = df.groupby(['date']).apply(lambda x: x[x['diff'] == x['diff'].min()]) # find the mean of price df2.groupby('date')['price'].mean() date 2018-08-01 232.5 2018-08-02 220.0 Name: price, dtype: float64
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51698240

http://stackoverflow.com/comment/90380213
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51709199
type: Comment
has text: @necko How so? Doesn't it work same as accept_invite or? Should I make another question?

http://stackoverflow.com/comment/90361415
type: Comment
has text: Thank you once again. Final q: While I haven't run benchmarks between `pandas` and `data.table`, from your experience, will `pandas` be slower than `data.table` in R?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51699723

http://stackoverflow.com/comment/90266650
comment on: http://stackoverflow.com/q/51648849
score: 0
has text: There is no `COPY` statement in `MySQL`, so inserting is probably your only choice. Another _slightly_ wonky solution might be altering the table names (essentially making your staging table your production table, and production table your staging table).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51748311
answer count: 0
has comment: http://stackoverflow.com/comment/90458076
type: Question
tagged with: python-asyncio
tagged with: aiopg
tagged with: python
tagged with: aiohttp
score: 0
has comment: http://stackoverflow.com/comment/90505662
has body: I have an application that loops through batches of URL:s from a Postgres table, downloads the URL, runs a processing function on each download and saves back the result of the processing to the table. I have written it using aiopg and aiohttp to get it to run asynchronously. In simplified form it looks like: import asyncio import aiopg from aiohttp import ClientSession, TCPConnector BATCH_SIZE = 100 dsn = "dbname=events user={} password={} host={}".format(DB_USER, DB_PASSWORD, DB_HOST) async def run(): async with ClientSession(connector=TCPConnector(ssl=False, limit=100)) as session: async with aiopg.create_pool(dsn) as pool: while True: count = await run_batch(session, pool) if count == 0: break async def run_batch(session, db_pool): tasks = [] async for url in get_batch(db_pool): task = asyncio.ensure_future(process_url(url, session, db_pool)) tasks.append(task) await asyncio.gather(*tasks) async def get_batch(db_pool): sql = "SELECT id, url FROM db.urls ... LIMIT %s" async with db_pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute(sql, (BATCH_SIZE,)) for row in cur: yield row async def process_url(url, session, db_pool): async with session.get(url, timeout=15) as response: body = await response.read() data = process_body(body) await save_data(db_pool, data) async def process_body(body): ... return data async def save_data(db_pool, data): sql = "UPDATE db.urls ..." async with db_pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute(sql, (data,)) But something is wrong. The script runs slower and slower the longer it goes, also with more and more exceptions thrown from call to session.get. My guess is that there is something wrong with how I use the Postgres connection but I cannot figure out what's wrong. Any help would be much appreciated!
type: UnansweredQuestion
has title: How to use aiopg together with aiohttp

http://stackoverflow.com/a/51764647
type: Answer
has comment: http://stackoverflow.com/comment/90490879
upvote count: 3
score: 3
has body: You can use str.join() to print text with linebreaks: from bs4 import BeautifulSoup import requests r = requests.get('https://automatetheboringstuff.com/chapter11/') soup = BeautifulSoup(r.text, 'lxml') print('\n'.join(strong.text for strong in soup.select('strong.literal'))) Prints: import webbrowser webbrowser.open('http://inventwithpython.com/') pyperclip else: # Get address from clipboard. address = pyperclip.paste() webbrowser.open('https://www.google.com/maps/place/' + address) import requests import requests ...and so on.
accepted answer of: http://stackoverflow.com/q/51764239
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51764239
downvote count: 0
has comment: http://stackoverflow.com/comment/90493425

http://stackoverflow.com/comment/90413485
type: AnswerComment
comment on: http://stackoverflow.com/a/51726585
type: Comment
has text: But how to open browser now?
score: 0

http://stackoverflow.com/q/51664225
score: 5
has comment: http://stackoverflow.com/comment/91192947
answer count: 1
has title: PyCharm: regex string intentions for function arguments
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/90633195
has comment: http://stackoverflow.com/comment/95526392
has comment: http://stackoverflow.com/comment/90617305
tagged with: python
tagged with: regex
has body: I have a function that takes a string argument that will be compiled into a regular expression, like so: class Pattern: def __init__(self, pattern, **kwargs) -> None: self.re = re.compile(pattern) self.extras = dict(**kwargs) ... more methods ... When I initialize a Pattern object, I'd love for PyCharm (actually, I'm using IntelliJ IDEA with the Python plugin, but I think that's essentially the same platform) to know that my pattern argument string should conform to Python's regular expression syntax, and can be syntax-highlighted, just like when using re.compile(pattern): # This won't be recognized as a regex intention: p1 = Pattern(r'^(?P<site>[A-Z]{4}).(?P<unit>\d{4})') # But this will: p2 = re.compile(r'^(?P<site>[A-Z]{4}).(?P<unit>\d{4})') Is there any way to give the IDE a hint here, that whatever is passed as the pattern argument to Pattern should have regex syntax? Ideally in some kind of hint comment or type hint that I could put in the code so it would work for other developers too. I do know that: I could create a plugin for this - in my case that would probably be vast overkill. I can do "Inject language or reference" on an ad-hoc basis for any particular call to Pattern(...) - but that's temporary, it's tedious when there are a lot of such calls, and it doesn't help other developers read the code more easily. Edit: This question is the direct analog of "Can one automatically get Intellij's regex assistance for one's own regex parameters", but for Python instead of Java. The IntelliLang solution in that answer seems to be only applicable to editing Java or XML files.
has answer: http://stackoverflow.com/a/52149407
linked to: http://stackoverflow.com/q/37009549
has comment: http://stackoverflow.com/comment/91174337
tagged with: pycharm
downvote count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/51704718
has comment: http://stackoverflow.com/comment/90371953
accepted answer of: http://stackoverflow.com/q/51704532
type: AcceptedAnswer
downvote count: 0
has body: As the documentation says, you have to pass a matrix with n_samples (3) and n_features (1). So your input X in the form [[1,2,3]] needs the inner vector in a vertical position. After **T: array([[ 1], [ 4], [16]]) This is what happens under the hood: https://machinelearningmastery.com/solve-linear-regression-using-linear-algebra/
has comment: http://stackoverflow.com/comment/90371697
has comment: http://stackoverflow.com/comment/90371487
type: Answer
has comment: http://stackoverflow.com/comment/90371400
has comment: http://stackoverflow.com/comment/90371042
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90370629
answers question: http://stackoverflow.com/q/51704532

http://stackoverflow.com/q/51731291
has body: I am using pycharm all code are run and show below in window expect Functions. When I write code run and debug it is not showing output. I write that code on pycharm: def exponent(base, power): result=1 for index in range(power): result=result * base return result print(exponent(4,9)) but it give me in below window: C:\Users\Rameen\exponent\venv\Scripts\python.exe C:/Users/Rameen/exponent/exponent.py Process finished with exit code 0 it does not give any error and output both. when i debug this it show : C:\Users\Rameen\exponent\venv\Scripts\python.exe "C:\Users\Rameen\AppData\Roaming\JetBrains\PyCharm Community Edition 2018.2\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 61607 --file C:/Users/Rameen/exponent/exponent.py pydev debugger: process 1292 is connecting Connected to pydev debugger (build 182.3684.100) Process finished with exit code 0
accepted answer: http://stackoverflow.com/a/51731343
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51731343
tagged with: pycharm
tagged with: python
type: AnsweredQuestion
has title: output is not showing for functions
has comment: http://stackoverflow.com/comment/90423350
type: Question
has comment: http://stackoverflow.com/comment/90423536
has comment: http://stackoverflow.com/comment/90423559

http://stackoverflow.com/comment/90547070
type: AnswerComment
has text: I am not sure I follow, could you please clarify? What do you mean by your comment?
type: Comment
comment on: http://stackoverflow.com/a/51794680
score: 0

http://stackoverflow.com/comment/91251031
has text: @KNP this is SO, not a Pydoop help page. If you think you have found an issue with the installation process, pleas open a ticket at https://github.com/crs4/pydoop/issues
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51670038
type: AnswerComment

http://stackoverflow.com/comment/90273997
score: 0
has text: @AKX I do believe I am editing only one copy of "base.html" Should I also include the part of my settings.py file showing the template related configurations ?
comment on: http://stackoverflow.com/q/51654924
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51664200
downvote count: 0
has comment: http://stackoverflow.com/comment/90312483
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51663687
has body: Other than the first element *[@id="mw-content-text"], all the rest of the elements in your XPath should be the immediate children of the ones before them. By using // you're selecting elements of any depth within the parent, which is not what you want. Change all but the first //s to / and it should work as intended: for elem in tree.xpath('//*[@id="mw-content-text"]/table[14]/tr[3]/td/table/tr/td'): print(etree.tostring(elem, pretty_print=True))
answers question: http://stackoverflow.com/q/51663687
type: Answer
has comment: http://stackoverflow.com/comment/90359898

http://stackoverflow.com/comment/90352613
score: 1
comment on: http://stackoverflow.com/q/51695422
type: Comment
type: QuestionComment
has text: [@Andersson] Sorry, Andersson. I am not familiar with stackoverflow. So all code can't show to a code style. I don't understand why code are showed above. Please understand.

http://stackoverflow.com/q/51768254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51935251
type: Question
tagged with: bitbucket
answer count: 2
tagged with: bitbucket-api
has title: Extract list of Sources (branches) from Bitbucket using Python
score: 0
accepted answer: http://stackoverflow.com/a/51935251
has body: I'm new to python and trying to update someone else's code. I need to pull a list of Sources (branches) from Bitbucket to allow user selection from that list. The existing code successfully used URL requests to retrieve lists from Bitbucket for both Projects and Repositories but I can't find a way to access the Source location to change from the default "Master" to a user selected branch. For reference, this excerpt of code worked to extract the Repositories information: @app.route("/initial3" , methods=['GET', 'POST']) def initial3(): selected_git_project = str(request.form.get('git_project')) selected_git_repository = str(request.form.get('git_information')) #checkbox_all_selection = str(request.form.get('checkbox_all')) confluence_information = [str(request.form.get('confluence_information'))] selected_page = request.form.get('page_id') returnlistsearch = [] url = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+selected_git_project+'/repos/'+selected_git_repository+'/files?limit=1000' resources_json = requests.get(url, auth=(git_user, git_password)).json() resources_json_dump = (json.dumps(resources_json, indent=4, sort_keys=False)) decoded = json.loads(resources_json_dump) for x in decoded['values']: if '.robot' in x: location=os.path.dirname(x) if location!='': returnlistsearch.append(location) returnlistsearch =remove_duplicated(returnlistsearch) return render_template('initial3.html',git_repository=selected_git_repository,git_project=selected_git_project ,git_information=returnlistsearch) I thought I could reuse the same code but with a modified URL (some references on docs.atlassian seemed to indicate that would work): url = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+selected_git_project+'/repos/'+selected_git_repository+'/files?limit=1000' Any suggestions would be much appreciated - My first look EVER at python was two days ago.
possible better answer: http://stackoverflow.com/a/51768758
tagged with: python
has answer: http://stackoverflow.com/a/51768758

http://stackoverflow.com/comment/90469008
type: QuestionComment
comment on: http://stackoverflow.com/q/51754592
score: 0
type: Comment
has text: is the first row's `count(label_1)` count of label 1 just in column `month_1`?

http://stackoverflow.com/comment/90493564
type: Comment
has text: I can't believe that I missed it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51766288

http://stackoverflow.com/comment/90248483
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51640880
type: Comment
has text: Trying to run your sample code gives `KeyError: 'group'`

http://stackoverflow.com/a/51742898
type: Answer
answers question: http://stackoverflow.com/q/51742085
score: 2
has comment: http://stackoverflow.com/comment/90497589
has comment: http://stackoverflow.com/comment/90446331
has comment: http://stackoverflow.com/comment/90447780
downvote count: 0
has body: Try: foo('{} left'.format(N-n)) That should do the job. This is a very simple example of the power of Python string formating. Here is a suggested method for doing what you want, based on your revised problem definition, but it is definitely non-trivial. It is based on modifying the Python abstract syntax tree for the function foo. The following steps will be necessary: This step is only needed if you only have bytecode for the foo function. Find a third party decompiler that will generate Python source code Generate the source code for the foo function. Parse the source code with ast.parse(). Find the spot in the function where N and n are reliably usable. If there is already a print statement that you can override, replace it with your code, otherwise insert your print statement into the tree. Compile the AST using ast.compile(). Use the resulting function object in place of the original function. You will need a very strong use case for this as it is going to be a lot of learning and work. Without the actual foo function there is little more that I can offer.
upvote count: 2
has comment: http://stackoverflow.com/comment/90446200

http://stackoverflow.com/a/51645946
has comment: http://stackoverflow.com/comment/90256522
has comment: http://stackoverflow.com/comment/90256361
type: Answer
has comment: http://stackoverflow.com/comment/90262236
has comment: http://stackoverflow.com/comment/90256438
has comment: http://stackoverflow.com/comment/90262123
has body: Add i variable, because iterrows return indices with Series for each row: for i, row in df.iterrows(): top_numbers = row.nlargest(top_n).sum() General solution with numpy.argsort for positions in descending order, then compare and convert boolean array to integers: def get_top_n(df, top_n): if top_n &gt; len(df.columns): raise ValueError("Value is higher as number of columns") elif not isinstance(top_n, int): raise ValueError("Value is not integer") else: arr = ((-df.values).argsort(axis=1) &lt; top_n).astype(int) df1 = pd.DataFrame(arr, index=df.index, columns=df.columns) return (df1) df1 = get_top_n(df, 2) print (df1) A B C 0 1 1 0 1 1 1 0 df1 = get_top_n(df, 1) print (df1) A B C 0 1 0 0 1 0 1 0 EDIT: Solution with iterrows is possible, but not recommended, because slow: top_n = 2 for i, row in df.iterrows(): top = row.nlargest(top_n).index df.loc[i] = 0 df.loc[i, top] = 1 print (df) A B C 0 1 1 0 1 1 1 0
has comment: http://stackoverflow.com/comment/90262384
has comment: http://stackoverflow.com/comment/90258880
answers question: http://stackoverflow.com/q/51645934
has comment: http://stackoverflow.com/comment/90262587
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/51645934
downvote count: 0
has comment: http://stackoverflow.com/comment/90262342
has comment: http://stackoverflow.com/comment/90292456
has comment: http://stackoverflow.com/comment/109516870
has comment: http://stackoverflow.com/comment/90262548
has comment: http://stackoverflow.com/comment/90256318
has comment: http://stackoverflow.com/comment/90255992
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90256410

http://stackoverflow.com/q/51755411
upvote count: 1
type: Question
has title: Bokeh not interpreting correct scale with SQL data
tagged with: bokeh
has body: Explored lots of various solutions here but not finding one that works. I'm using sqlite and pandas to read data from a SQL database, but Bokeh doesn't like the date. I've tried conversions to datetime, unixepoch, etc. and they all seem to yield the same result. EDIT: Here's the full code: from os.path import dirname, join import pandas as pd import pandas.io.sql as psql import numpy as np import sqlite3 import os from math import pi from bokeh.plotting import figure, output_file, show from bokeh.io import output_notebook, curdoc from bokeh.models import ColumnDataSource, Div, DatetimeTickFormatter from bokeh.models.widgets import Slider, Select, RadioButtonGroup from bokeh.layouts import layout, widgetbox import warnings import datetime warnings.filterwarnings('ignore') ## Set up the SQL Connection conn = sqlite3.connect('/Users/&lt;&gt;/Documents/python_scripts/reptool/reptool_db') c = conn.cursor() ## Run the SQL proj = pd.read_sql( """ SELECT CASE WHEN df is null THEN ds ELSE df END AS 'projdate', CASE WHEN yhat is null THEN y ELSE yhat END AS 'projvol', strftime('%Y',ds) as 'year' FROM forecast LEFT JOIN actuals ON forecast.ds = actuals.df """, con=conn) # HTML index page and inline CSS stylesheet desc = Div(text=open("/Users/&lt;&gt;/Documents/python_scripts/reptool/description.html").read(), width=800) ## Rename Columns and create list sets proj.rename(columns={'projdate': 'x', 'projvol': 'y'}, inplace=True) x=list(proj['x']) y=list(proj['y']) # proj['projdate'] = [datetime.datetime.strptime(x, "%Y-%m-%d").date() for x in proj['projdate']] # Create input controls radio_button_group = RadioButtonGroup( labels=["Actuals", "Forecast","FY Projection"], active=0) min_year = Slider(title="Period Start", start=2012, end=2018, value=2013, step=1) max_year = Slider(title="Period End", start=2012, end=2018, value=2017, step=1) ## Declare systemic source source = ColumnDataSource(data=dict(x=[], y=[], year=[])) ## Bokeh tools TOOLS="pan,wheel_zoom,box_zoom,reset,xbox_se…
has answer: http://stackoverflow.com/a/51757457
tagged with: sqlite
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51789649
answer count: 3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51771693

http://stackoverflow.com/comment/90293154
score: 0
has text: what's the URL to the page that has the a tag you reference?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51664851

http://stackoverflow.com/comment/90356574
has text: Can you show your output? It looks fine for me when I try it.
comment on: http://stackoverflow.com/q/51697575
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90793750
has text: I'm still confused, actually. I just want to obtain the number of microseconds between epoch and right now. Note, no timezones involved. What is the correct way to do that?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51756295

http://stackoverflow.com/comment/90411130
has text: The only way I can think of is to combine the data into one table and allow blank or allow null. Other than that, I think it's not possible even using raw SQL.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51719611

http://stackoverflow.com/comment/94945949
score: 0
type: QuestionComment
has text: If you post a link to the data, I can run it though my zunzun.com online surface fitter's "function finder" and see if it turns up any candidate z=f(x,y) 3D surface equations - the site has hundreds of surface equations for the search.
type: Comment
comment on: http://stackoverflow.com/q/51659957

http://stackoverflow.com/q/51675818
type: Question
has title: Proper indentation for the second line of a multiline code with parentheses
has comment: http://stackoverflow.com/comment/90315169
answer count: 2
tagged with: indentation
tagged with: pep8
downvote count: 0
has answer: http://stackoverflow.com/a/51676112
linked to: http://stackoverflow.com/q/2504411
favorite count: 0
has body: What is the recommended standard indentation for the second line of a multiline Python code with parentheses/commas? No indentation: plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet', vmin=-100, vmax=0, origin='lowest', aspect='auto') 4 spaces indentation: plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet', vmin=-100, vmax=0, origin='lowest', aspect='auto') Identation up to the (: plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet', vmin=-100, vmax=0, origin='lowest', aspect='auto') Another solution? This is linked: Proper indentation for Python multiline strings but here the question is specific to multiline with parentheses / commas, and not strings.
has answer: http://stackoverflow.com/a/51675862
tagged with: multiline
tagged with: python
tagged with: parentheses
score: 2
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/51690799
duplicate of: http://stackoverflow.com/q/13905741
tagged with: variables
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51690940
linked to: http://stackoverflow.com/q/625083
has title: Why is a NameError raised when using a list compression at the class level?
tagged with: python
has comment: http://stackoverflow.com/comment/90343500
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90343426
upvote count: 3
has comment: http://stackoverflow.com/comment/90343468
type: Question
possible better answer: http://stackoverflow.com/a/51690822
score: 3
has comment: http://stackoverflow.com/comment/90343399
has answer: http://stackoverflow.com/a/51690940
has answer: http://stackoverflow.com/a/51690822
has comment: http://stackoverflow.com/comment/90346241
has body: I get interesting for me trouble in my code. ... class Planet: ATMOSPHERE_GASES = { 'N2':(67.59, 28.0134), 'O2':(28.04, 31.9988), 'CO2':(0.0114, 44.00995), 'CH4':(0.00015, 16.04303), 'Ar':(1.105, 39.948), 'Ne':(1.003, 20.179), 'He':(0.719, 4.0026), 'Kr':(0.45, 83.80), 'H2':(0.001, 2.01594), 'Xe':(0.23, 131.30)} ATMOSPHERE_GASES['Other'] = tuple([100-sum([x[0] for x in ATMOSPHERE_GASES.values()]), sum([x[1] for x in ATMOSPHERE_GASES.values()])/len(ATMOSPHERE_GASES.values())]) ATMOSPHERE_GASES_MOLAR_MASS = sum([sum(ATMOSPHERE_GASES[x]) for x in ATMOSPHERE_GASES.keys()])/100 ... ATMOSPHERE_GASES_MOLAR_MASS give error NameError("name 'ATMOSPHERE_GASES' is not defined",) I check indented block, tabs and some other reasons, try to rewrite this part, but nothing. But without class it works! Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\ptvsd_launcher.py", line 111, in &lt;module&gt; vspd.debug(filename, port_num, debug_id, debug_options, run_as) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\debugger.py", line 36, in debug run(address, filename, *args, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\_main.py", line 47, in run_file run(argv, addr, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\_main.py", line 98, in _run _pydevd.main() File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\pydevd\pydevd.py", line 1628, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\pydevd\pydevd.py", line 103…
tagged with: class
answer count: 2
tagged with: function
downvote count: 0

http://stackoverflow.com/a/51660057
has body: From the builtins docs: The value of __builtins__ is normally either this module [builtins] or the value of this module's __dict__ attribute To fix your error: &gt;&gt;&gt; print(eval('x+1',{'__builtins__': {'x': x}})) To specify a few built-in methods, provide it to __builtins__ &gt;&gt;&gt; print(eval('min(1,2)',{'__builtins__': {'min': min}})) However, limiting __builtins__ is still not safe: see https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51659933
answers question: http://stackoverflow.com/q/51659933
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/90283726

http://stackoverflow.com/comment/90325493
type: QuestionComment
has text: @MattMessersmith Agreed which is why I noted in the question that I don't think using `__init__.py` was a good option. I'm just not sure what the standard is.
comment on: http://stackoverflow.com/q/51679103
score: 0
type: Comment

http://stackoverflow.com/a/51706775
has body: For loading model efficiently, make it global and load it into another function, so that you don't have to load it again and again. After making it global, it will be accessible in main function: def load_model(): global model json_file = open('model.json', 'r') model_json = json_file.read() model = model_from_json(model_json) model.load_weights("model.h5") model._make_predict_function()
type: Answer
answers question: http://stackoverflow.com/q/51679636
score: 0

http://stackoverflow.com/a/51793448
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51793379
score: 0
has body: If they are all formatted similarly to the three fruit example you gave, you can simply do a string.split(".")[0] on each filename you encounter: import os for image in images: fruit = image.split(".")[0] if not os.path.isdir(fruit): os.mkdir(fruit) os.rename(os.path.join(fruit, image))

http://stackoverflow.com/a/51665948
upvote count: 6
has body: Have a look at the docs for insert and flatten: They both return new arrays (copies). So you need to write X = np.insert(a, [0, 0], toAppend) in order for X to contain the extended array. I also don't think you need the preceding X.flatten(). Instead of inserting into a numpy array (which is expensive), you should consider just building a nested list and only convert it once at the end.
score: 6
answers question: http://stackoverflow.com/q/51665905
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51665905

http://stackoverflow.com/comment/90381083
comment on: http://stackoverflow.com/a/51709835
type: Comment
score: 2
type: AnswerComment
has text: You can **not** use `len()` to return anything different from a positive integer. Nothing more to say...

http://stackoverflow.com/q/51791903
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90541285
type: Question
possible better answer: http://stackoverflow.com/a/51792171
has answer: http://stackoverflow.com/a/51792018
accepted answer: http://stackoverflow.com/a/51792018
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51792171
has body: I have a bunch of records, each labeled with a cluster value. Original dataframe, df: +-------------+---------+ | measurement | cluster | +-------------+---------+ | M1 | 6 | | M2 | 6 | | M3 | 6 | | M4 | 12 | | M5 | 12 | | M6 | 12 | | M7 | 2 | | M8 | 9 | | M9 | 9 | | M10 | 9 | | M11 | 9 | +-------------+---------+ How can I rename the clusters to a new number based on whether the current cluster value is equal to the prior and next one while assigning to "x" rows whose cluster values do not equal to the prior or next one? Desired df: +-------------+---------+-------------+ | measurement | cluster | new_cluster | +-------------+---------+-------------+ | M1 | 6 | 1 | | M2 | 6 | 1 | | M3 | 6 | 1 | | M4 | 12 | 2 | | M5 | 12 | 2 | | M6 | 12 | 2 | | M7 | 2 | x | | M8 | 9 | 3 | | M9 | 9 | 3 | | M10 | 9 | 3 | | M11 | 9 | 3 | +-------------+---------+-------------+
has title: How can I increase a counter based on a condition for a Pandas dataframe?
favorite count: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/51723844
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90409065
has comment: http://stackoverflow.com/comment/90410251
type: Question
has answer: http://stackoverflow.com/a/76804104
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90409490
upvote count: 1
tagged with: django-debug-toolbar
answer count: 1
has title: Django debug toolbar works only in admin interface
has comment: http://stackoverflow.com/comment/90408496
type: UnansweredQuestion
has body: I've did all the steps which are described in the docs and got the toolbar in admin site. However, I can't get it work in the project frontend side. Here is my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ... ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INTERNAL_IPS = ('127.0.0.1', 'localhost',) I've googled a lot already and non of the proposed solution are not working for me: workaround that shows toolbar even if debug=False, playing with different parameters like INTERCEPT_REDIRECTS=False/True, specifying JQUERY_URL since there is a local jquery which is used by frontend. I've asked for help from frontend dev, but he can't understand why there is no any configs for client side. Frontend is using nodes.js and listens on 3000 port than forwards to localhost:8081. Django version 1.10, django-debug-toolbar 1.9.1.

http://stackoverflow.com/comment/90463313
type: QuestionComment
comment on: http://stackoverflow.com/q/51751674
score: 0
has text: What error? You mean when you have to kill it? Or when the process you ran with `Popen` returns an error code?
type: Comment

http://stackoverflow.com/comment/90549253
score: 1
comment on: http://stackoverflow.com/q/51795890
has text: The real question is: why do you have this file? Did you generate it by calling `str` on some NumPy arrays and writing the result to a file or something? If so, can you change your code to not do that, and instead write something that's actually meant to be parsed, like JSON or `np.savetxt`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51661723
answers question: http://stackoverflow.com/q/51661522
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90286970
type: Answer
has comment: http://stackoverflow.com/comment/90287179
has body: first this is testing twice too much and also testing if one object collides with itself: for i in list1: for j in list1: if collide(i, j): i.kill() j.kill() This loops exactly len(list1)**2 times. a very simple way to divide the number of tests by 2 (and avoiding testing against itself): for i,obj1 in enumerate(list1): for j in range(i+1,len(list1)): obj2 = list1[j] if collide(obj1,obj2): obj1.kill() obj2.kill() It takes advantage of the fact that collide(obj1,obj2) is the same as collide(obj2,obj1). At this point, you probably want to break out the inner loop since obj1 is now dead. But that depends on what you want to do. If an accurate collision test is expensive, you could consider a rougher check (distance, rectangle boundary, any quick method), so you can discard items which are too far away from each other without performing the "expensive" test.
has comment: http://stackoverflow.com/comment/90286987
has comment: http://stackoverflow.com/comment/90287009
upvote count: 1
has comment: http://stackoverflow.com/comment/90287045
has comment: http://stackoverflow.com/comment/90286885
score: 1
accepted answer of: http://stackoverflow.com/q/51661522
has comment: http://stackoverflow.com/comment/90286940

http://stackoverflow.com/q/51758720
possible better answer: http://stackoverflow.com/a/51758829
score: 0
answer count: 2
tagged with: operating-system
accepted answer: http://stackoverflow.com/a/51758854
tagged with: python
type: AnsweredQuestion
has body: I have a image dataset archived in tree structure, where the name of different level of folders are the labels of these images, for example /Label1 /Label2 /image1 /image2 /Label3 /image3 /Label4 /image4 /image5 Then how could I count number of images in each end folder. In the above example, I want to know how many images are there in folder /Label1/Label2, /Label1/Label3 and Label4. I checked out the function os.walk(), but it seems that there is no easy way to count number of files in each individual end folder. Could anyone help me, thank you in advance.
type: Question
has answer: http://stackoverflow.com/a/51758829
has answer: http://stackoverflow.com/a/51758854
tagged with: filesystems
has title: Count number of files in end directories using Python

http://stackoverflow.com/q/51667240
tagged with: matplotlib
has title: How to save figures in a folder with Jupyter Notebook when the plots are produced with an external function that I don't want to modify?
type: Question
has comment: http://stackoverflow.com/comment/90300858
score: 2
linked to: http://stackoverflow.com/q/9622163
answer count: 1
has comment: http://stackoverflow.com/comment/90297654
favorite count: 0
has comment: http://stackoverflow.com/comment/90297819
tagged with: python
tagged with: jupyter
has comment: http://stackoverflow.com/comment/90297434
has comment: http://stackoverflow.com/comment/90297491
has comment: http://stackoverflow.com/comment/90297727
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51667648
upvote count: 3
type: UnansweredQuestion
has body: I want to save figures plotted by a function that I don't want to have to touch (because it is an external function, and also because if tomorrow I don't want to save them and just display on the console, I don't want to have to edit the source code again and again). Is it possible to save the figures into a folder from ipython? Whether the figures are plotted in iPython or not is not a concern. I just want to be able to save them in a folder automatically, as they are a lot in number. I have tried most of the solutions mentioned here, but they don't work - they just save a blank image file. import matplotlib.pyplot as pl fig = pl.figure() external_function(parameters) # this function plots a figure fig.savefig(r'path\to\folder\image.png') # saves a blank image.png into the folder
downvote count: 1
tagged with: plot

http://stackoverflow.com/comment/90256251
comment on: http://stackoverflow.com/q/51646185
type: QuestionComment
has text: one more tip, if you got gimp2 - it got scripted filters, my guess is one would create "paper like" textures. inspect the layers of it (or steal parts) and apply those as translucent png to your picture - maybe use the mug stain as well ;o)
type: Comment
score: 1

http://stackoverflow.com/q/51698240
has comment: http://stackoverflow.com/comment/90360056
has comment: http://stackoverflow.com/comment/90360560
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90359962
has comment: http://stackoverflow.com/comment/90360147
tagged with: dataframe
type: Question
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51699071
downvote count: 0
has comment: http://stackoverflow.com/comment/90361431
favorite count: 0
has answer: http://stackoverflow.com/a/51699495
accepted answer: http://stackoverflow.com/a/51699495
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90360248
upvote count: 2
possible better answer: http://stackoverflow.com/a/51699071
has body: I have a dataframe with ~3 million rows, which looks like: date size price 0 2018-08-01 100 220 1 2018-08-01 110 245 2 2018-08-01 125 250 3 2018-08-02 110 210 4 2018-08-02 120 230 5 2018-08-02 150 260 6 2018-08-03 115 200 For each row, it is a transaction of a item. We have the date of the transaction, size and price of the item. Now I would like to add a column called avg_price, such that the avg_price of a transaction/row is the average of k transactions on the last day that have the closest sizes as this one(very similar to the idea of k nearest neighbors). For example, when k = 2, the avg_price of the last row above should be (210+230)/2=220 because the 2 closest transactions come with sizes 110 and 120, with corresponding prices 210 and 230. The expected output should be: date size price avg_price 0 2018-08-01 100 220 NA 1 2018-08-01 110 245 NA 2 2018-08-01 125 250 NA 3 2018-08-02 110 210 (220+245)/2 4 2018-08-02 120 230 (245+250)/2 5 2018-08-02 150 260 (245+250)/2 6 2018-08-03 115 200 (210+230)/2 I wrote a for loop to iterate over each rows, first pick out all transactions on the last day, then sort by difference in size and calculate the average of the first k items. However, as expected this is extremely slow. Could anyone point out a more "vectorized" approach? Thanks. Updates: number of transactions per day is not fixed, and around ~300.
has comment: http://stackoverflow.com/comment/90360059
has comment: http://stackoverflow.com/comment/90360117
has title: Pandas dataframe iterate over rows without for loops

http://stackoverflow.com/comment/90382576
has text: No field in the database is something I can not encode. Trying to encode that field still throws the error as it gets thrown during retrieving the field. It seems to have broken some data during the migration.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51709917

http://stackoverflow.com/comment/90903958
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51738439
type: Comment
has text: oh! good idea. I'll give that a try. I'd already tried using jquery's .extend() method but it wasn't great. Merging in `crawl` would be much cleaner. Cheers!

http://stackoverflow.com/comment/90437950
comment on: http://stackoverflow.com/q/51738309
score: 0
type: Comment
type: QuestionComment
has text: @blhsing Getting the right order while printing the D.__mro__ but get not getting the constructor call of class C

http://stackoverflow.com/q/51789376
has body: I have an unstructured file which I need to parse using Python. After carrying out some initial manipulation whilst retrieving the file, the data is in a following format (the titles are simply dummies, they can be anything e.g. INDEX LENGTH, WIDTH etc.) data = [ [" title1-a", "title2-a", "title3-a", " title4-a"], ["title1-b ", " title2-b", "title3-b ", "title4-b"], ["title3-c", " title4-c "], ["title1-a ", " title5-a"], ["title1-b", " title5-b"], ["title5-c "] ] The above data is a dummy. The real data set looks like below real = [ ['TIME', 'YEARS', 'WWPR', 'WWPR', 'WWPR', 'WWPR', 'WOPR', 'WOPR', 'WOPR', 'WOPR'], ['DAYS', 'YEARS', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY'], ['P1', 'P2', 'P3', 'P4', 'P1', 'P2', 'P3', 'P4'], ['TIME', 'WWIR'], ['DAYS', 'STB/DAY'], ['I1'] ] Note, each title is a concatination of three lists! So, real = [[ ['TIME', 'YEARS', 'WWPR', 'WWPR', 'WWPR', 'WWPR', 'WOPR', 'WOPR', 'WOPR', 'WOPR'], ['DAYS', 'YEARS', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY', 'STB/DAY'], ['P1', 'P2', 'P3', 'P4', 'P1', 'P2', 'P3', 'P4']],[ ['TIME', 'WWIR'], ['DAYS', 'STB/DAY'], ['I1'] ]] The real data would be parsed to achieve following strings TIME DAYS YEARS YEARS WWPR STB/DAY P1 WWPR STB/DAY P2 WWPR STB/DAY P3 WWPR STB/DAY P4 WOPR STB/DAY P1 WOPR STB/DAY P2 WOPR STB/DAY P3 WOPR STB/DAY P4 WWIR STB/DAY I1 The objectives are as follows Concatinate associated title entries; The order of titles MUST be preserved; No duplication allowed; Minimize copy operation where possible; Based on the dummy data, the desired output would look like the one below output = [ "title1-a title1-b", "title2-a title2-b", "title3-a title3-b title3-c", "title4-a title4-b title4-c", "title5-a title5-b title5-c" ] I have developed a solution. This said, there must be a cleaner and more efficient way. Hence, I would be keen to investigate alternative solutions. Following is code I developed to get the above data i…
answer count: 2
has answer: http://stackoverflow.com/a/51789477
upvote count: 1
favorite count: 0
tagged with: python
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51789494
type: Question
score: 1
tagged with: data-manipulation
has title: Data Manipulation using Python
has comment: http://stackoverflow.com/comment/90543100

http://stackoverflow.com/a/51689884
downvote count: 0
has body: I don't believe this can be done with a single regexp. But it's straightforward with a nested loop: import re test = "wddddd" # need to compile the tail regexp to get a version of # `finditer` that allows specifying a start index tailre = re.compile("(d)") for wg in re.finditer("(w)", test): start = wg.start(1) for dg in tailre.finditer(test, wg.end(1)): end = dg.end(1) print(test[start : end], "at", (start, end)) That displays: wd at (0, 2) wdd at (0, 3) wddd at (0, 4) wdddd at (0, 5) wddddd at (0, 6) With test = "worldworldworld" instead: world at (0, 5) worldworld at (0, 10) worldworldworld at (0, 15) world at (5, 10) worldworld at (5, 15) world at (10, 15)
has comment: http://stackoverflow.com/comment/90341638
answers question: http://stackoverflow.com/q/51689418
score: 4
accepted answer of: http://stackoverflow.com/q/51689418
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90342386
type: Answer
upvote count: 4

http://stackoverflow.com/comment/90288576
score: 1
has text: What is `forwhom` in your code?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51662544

http://stackoverflow.com/comment/90460975
score: 0
has text: @Onyambu - The answer need not be always as a column. It can also be in the form of a new dataframe or just a print statement - calculating and just streaming the output using print. I have already provided how the output should look like
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51750164

http://stackoverflow.com/comment/90254662
has text: Thank you. I use shell=True and the previous error disappear. But new error occured: 'dld_tool' is not recognized as an internal or external command, operable program or batch file.
type: Comment
comment on: http://stackoverflow.com/a/51645210
type: AnswerComment
score: 0

numpy
tags question: http://stackoverflow.com/q/51711531
tags question: http://stackoverflow.com/q/51711607
tags question: http://stackoverflow.com/q/51694496
tags question: http://stackoverflow.com/q/51768789
tags question: http://stackoverflow.com/q/51767723
tags question: http://stackoverflow.com/q/51757511
tags question: http://stackoverflow.com/q/51779406
tags question: http://stackoverflow.com/q/51705187
tags question: http://stackoverflow.com/q/51765983
tags question: http://stackoverflow.com/q/51648253
tags question: http://stackoverflow.com/q/51737205
tags question: http://stackoverflow.com/q/51791707
tags question: http://stackoverflow.com/q/51756544
tags question: http://stackoverflow.com/q/51736178
tags question: http://stackoverflow.com/q/51786133
tags question: http://stackoverflow.com/q/51769198
tags question: http://stackoverflow.com/q/51665905
tags question: http://stackoverflow.com/q/51675388
tags question: http://stackoverflow.com/q/51671313
tags question: http://stackoverflow.com/q/51720829
tags question: http://stackoverflow.com/q/51733255
tags question: http://stackoverflow.com/q/51752413
tags question: http://stackoverflow.com/q/51700295
tags question: http://stackoverflow.com/q/51692229
tags question: http://stackoverflow.com/q/51699494
tags question: http://stackoverflow.com/q/51736293
tags question: http://stackoverflow.com/q/51733298
tags question: http://stackoverflow.com/q/51705067
tags question: http://stackoverflow.com/q/51720097
tags question: http://stackoverflow.com/q/51748650
tags question: http://stackoverflow.com/q/51673388
tags question: http://stackoverflow.com/q/51788492
tags question: http://stackoverflow.com/q/51734193
tags question: http://stackoverflow.com/q/51716954
tags question: http://stackoverflow.com/q/51687602
tags question: http://stackoverflow.com/q/51731815
tags question: http://stackoverflow.com/q/51702622
tags question: http://stackoverflow.com/q/51711962
tags question: http://stackoverflow.com/q/51780844
tags question: http://stackoverflow.com/q/51681486
tags question: http://stackoverflow.com/q/51672325
tags question: http://stackoverflow.com/q/51798462
tags question: http://stackoverflow.com/q/51787868
tags question: http://stackoverflow.com/q/51747903
tags question: http://stackoverflow.com/q/51789821
tags question: http://stackoverflow.com/q/51700637
tags question: http://stackoverflow.com/q/51692253
tags question: http://stackoverflow.com/q/51748904
tags question: http://stackoverflow.com/q/51641558
tags question: http://stackoverflow.com/q/51764143
tags question: http://stackoverflow.com/q/51643687
tags question: http://stackoverflow.com/q/51650896
tags question: http://stackoverflow.com/q/51658976
tags question: http://stackoverflow.com/q/51736770
tags question: http://stackoverflow.com/q/51757043
tags question: http://stackoverflow.com/q/51698989
tags question: http://stackoverflow.com/q/51658801
tags question: http://stackoverflow.com/q/51693017
tags question: http://stackoverflow.com/q/51695747
tags question: http://stackoverflow.com/q/51791933
tags question: http://stackoverflow.com/q/51729849
tags question: http://stackoverflow.com/q/51697727
tags question: http://stackoverflow.com/q/51720631
tags question: http://stackoverflow.com/q/51694376
tags question: http://stackoverflow.com/q/51795002
tags question: http://stackoverflow.com/q/51776809
tags question: http://stackoverflow.com/q/51782885
tags question: http://stackoverflow.com/q/51699975
tags question: http://stackoverflow.com/q/51737996
tags question: http://stackoverflow.com/q/51643654
tags question: http://stackoverflow.com/q/51736172
tags question: http://stackoverflow.com/q/51795224
tags question: http://stackoverflow.com/q/51715173
tags question: http://stackoverflow.com/q/51715182
tags question: http://stackoverflow.com/q/51749888
tags question: http://stackoverflow.com/q/51772001
tags question: http://stackoverflow.com/q/51653193
tags question: http://stackoverflow.com/q/51703661
tags question: http://stackoverflow.com/q/51699315
tags question: http://stackoverflow.com/q/51774605

http://stackoverflow.com/comment/90428709
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga, thanks, the df["signal"] column is the output. So this is effectively checking the first occurrence over the next 5 rows of data the conditions df[high] > df[break] and df[low] < df[break] is met.
score: 0
comment on: http://stackoverflow.com/q/51733620

http://stackoverflow.com/comment/90462904
type: Comment
has text: Thank you. The triple quotes worked. I actually didn't have a space in my original code (my bad), but it still wasn't working. I actually don't want a new line in the standard output. I just want to continue writing the statement on the next line in the IDE because it would get too long.
comment on: http://stackoverflow.com/a/51751011
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90274055
comment on: http://stackoverflow.com/q/51650938
score: 0
type: Comment
type: QuestionComment
has text: Well, actually no. It would be really helpful if you could be more descriptive. Thanks already. @Relequestual

countvectorizer
type: Tag
tag name: countvectorizer
tags question: http://stackoverflow.com/q/51645273

http://stackoverflow.com/q/51790382
has body: I am running Python Spark on local to run an example found on Spark website. I generated a random dataFrame to have a bigger sample to make performance tests. I have set my SparkSession and SparkContext like this: spark = SparkSession.builder \ .master("local[*]") \ .appName("KMeansParallel") \ .getOrCreate() sc = spark.sparkContext But the program does not seem to run on parallel processes as suggested here. I see on task manager that only 10-25% of processor is used which leads me to think that Python is stuck on one core (by GIL?). What do I do wrong? I tried to change some parameters on SparkSession: .config("spark.executor.instances", 7) \ .config("spark.executor.cores", 3) \ .config("spark.default.parallelism", 7) \ .config("spark.driver.memory", "15g") \ I am running with 16GB memory, 4 cores, 8 logical processors. I leave some ressources for OS as advised here (even if local might be different from YARN configuration). Complete code : from pyspark.sql import SparkSession, Row from pyspark import SparkContext from pyspark.ml.linalg import Vectors from pyspark.ml.clustering import KMeans from pyspark.ml.evaluation import ClusteringEvaluator import numpy as np import math import time def gaussianMixture(sc, spark, nPoints, nGaussian, gaussianVariance): """ Returns a dataframe with &lt;nPoints&gt; points generated randomly around &lt;nGaussian&gt; centers by a normal distribution N(&lt;a center chosen randomly&gt;, &lt;gaussianVariance&gt;) """ #Generating centers meanPointsNumpy = np.random.rand(nGaussian, 2) def geneRandomChoice(nGaussian, nPoints): for i in range(nPoints): yield (i, np.random.choice(nGaussian, 1)) #Generating points in a numpy ndarray dataNumpy = np.array([ [t[0], np.random.normal(loc = meanPointsNumpy[t[1],0], scale = math.sqrt(gaussianVariance)), np.random.normal(loc = meanPointsNumpy[t[1],1], scale = math.sqrt(gaussianVariance))] for t in geneRandomChoice(nGaussian, nPoints) ]) #Converting ndarray to RDD then to dataFrame dataRDD = sc \ .p…
type: UnansweredQuestion
has title: Python Spark local parallelism
downvote count: 1
score: 3
has answer: http://stackoverflow.com/a/51791398
has comment: http://stackoverflow.com/comment/90538234
has comment: http://stackoverflow.com/comment/100419785
has comment: http://stackoverflow.com/comment/100395804
type: Question
upvote count: 4
tagged with: apache-spark
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/100419642
tagged with: python
has comment: http://stackoverflow.com/comment/90588822
linked to: http://stackoverflow.com/q/38036528

http://stackoverflow.com/q/51696940
has body: I am having much trouble trying to read in a large excel file (.xlsx), and write some of its tabs/sheets to a smaller excel file. In one class, I get return a dict of dataframes. The key is the respective sheet/tab that the dataframe came from, type string. The value is the actual dataframe, with all of its original columns, type DataFrame. In this class, I extract certain dataframes from the original excel file. I am able to print out my key:value pairs after extracting the dataframes of my choice, and it all looks fine. However, I believe that my real problem is writing the actual data to 1 excel file. I only get the first dataframe, without the sheet name that it came from (it becomes the default 'Sheet1'), and nothing else. Here is the code that writes my dict to an excel file: def frames_to_excel(self, df_dict, path): """Write dictionary of dataframes to separate sheets, within 1 file.""" writer = pd.ExcelWriter(path, engine='xlsxwriter') for tab_name, dframe in df_dict.items(): dframe.to_excel(writer, sheet_name=tab_name) writer.save() - "path" is the select output path to write the whole dict to a xlsx fle. - "df_dict" is the dict of dataframes.
score: 4
has answer: http://stackoverflow.com/a/51697422
answer count: 1
tagged with: excel
has title: How to write a dict of dataframes to one excel file in Pandas? Key is sheet name, Value is the dataframe
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90355283
upvote count: 4
has comment: http://stackoverflow.com/comment/90355377
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90423772
accepted answer: http://stackoverflow.com/a/51697422
downvote count: 0
favorite count: 0
type: Question
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/90469611
has text: I got it working, thanks a lot for your help! You're the best :D
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51753319

http://stackoverflow.com/a/51762187
has body: You don't need to actually save the numbers again on int_in_string and fl_in_string, so you could use two simple counters int_in_string = 0 fl_in_string = 0 for i in out: if isinstance(eval(str(i)), int): int_in_string += 1 elif isinstance(eval(str(i)), float): fl_in_string += 1
score: 0
answers question: http://stackoverflow.com/q/51762067
type: Answer

http://stackoverflow.com/comment/90297158
type: Comment
comment on: http://stackoverflow.com/a/51664162
score: 0
has text: @Anon, question was for Python 2, as print with parentheses would have given a different error in bash. But I'll add that to answer, cheers.
type: AnswerComment

http://stackoverflow.com/a/56239993
type: Answer
answers question: http://stackoverflow.com/q/51755139
score: 0
has body: I had the same error. What I did was to create a folder named flaskr and then move the __init__.py file into it (that is move the __init__.py into flaskr folder).

http://stackoverflow.com/comment/90293222
type: AnswerComment
comment on: http://stackoverflow.com/a/51664851
score: 0
type: Comment
has text: Oh i see - what you need to do is first get the div with that class and then get the a tags you need and extract the href. The "sabai-directory-title" class is not in an "a" element/tag, but in a div element. It also seems like the base URL you have set as the "pages" variable that you append to urls may be incorrect as it's different than the link you provide in your comment below (https://directory.singaporefintech.org/ has div elements with the "sabai-directory-title" class).

http://stackoverflow.com/a/56415888
type: Answer
has comment: http://stackoverflow.com/comment/117089531
has body: Earlier answer misses some deeper "group in group" cases. Group shapes may contain many levels of shapes, including group shapes. Thus, in many real life cases there is a need to do a recursive search among the group shapes. The previous answer parses only some of these (down to second layer of group shapes). But even that layer group shape may in turn contain further groups. So we need an iterative search strategy. This is best shown by reusing above code, keeping the first part: from pptx.shapes.group import GroupShape from pptx import Presentation for eachfile in files: prs = Presentation(eachfile) textrun=[] for slide in prs.slides: for shape in slide.shapes: then we need to replace the "for text in GroupShape.shapes:" test with a call for the recursive part: textrun=checkrecursivelyfortext(slide.shapes,textrun) and also insert a new recursive function definition of the function (like after the import statement). To make comparison easier, the inserted function is using the same code as above, only adding the recursive part: def checkrecursivelyfortext(shpthissetofshapes,textrun): for shape in shpthissetofshapes: if shape.shape_type == MSO_SHAPE_TYPE.GROUP: textrun=checkrecursivelyfortext(shape.shapes,textrun) else: if hasattr(shape, "text"): print(shape.text) textrun.append(shape.text) return textrun
upvote count: 4
answers question: http://stackoverflow.com/q/51701626
downvote count: 0
score: 4

http://stackoverflow.com/comment/90764682
has text: your virtualenv binary is likely belonged to another python installation, use `virtualenv -v venv` to check the detail.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51644402
score: 0

http://stackoverflow.com/comment/90342772
has text: First of all, you didn't say what is not working
score: 0
comment on: http://stackoverflow.com/q/51690430
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51717006
has body: You have "many" things to do, so you can put that dict in a list, or a dict. You cannot put that in a set beacuse it has to be hashable. If you chose a dict, you have to chose a "key" for each element, right? You can read about "data structures" here . Let's try list : thingsToDo = [] newThingToDo = { 'Item': 'I need a haircut', 'DueDate': 'Right now', 'Status': 'Done' } thingsToDo.append(newThingToDo) Using a dict would allow you to order your tasks, but I'm not sure it is your question. Let's try ordering your tasks by adding a number. thingsToDo = {} newThingToDo = { 'Item': 'I need a haircut', 'DueDate': 'Right now', 'Status': 'Done' } thingsToDo[5] = newThingToDo So your haircut is task number 5. If you choose the dict way, your code could look like this : # -*- coding: utf-8 -*- thingsToDo = {} while True: n = int(input("How many tasks do you want to add?")) for i in range(n): item = input("What do you need to do? ") duedate = input("When do you need to do it by? ") status = "Not done." newThingToDo = { 'Item': item, 'DueDate': duedate, 'Status': status } thingsToDo[i] = newThingToDo print(thingsToDo)
has comment: http://stackoverflow.com/comment/90452817
score: 0
has comment: http://stackoverflow.com/comment/90395524
type: Answer
has comment: http://stackoverflow.com/comment/90452301
answers question: http://stackoverflow.com/q/51716854

http://stackoverflow.com/a/52597076
downvote count: 0
type: Answer
score: 9
upvote count: 9
has body: This is not an error. Tensorflow is running just fine. It's a warning saying that Tensorflow is NOT taking advantage of some of the advanced instructions available on your CPU because its binary was compiled not to use these instructions (so it could run on older CPUs). Your options are: Ignore it. Silence it (see the other answer). Build the Tensorflow from source. The #3 may make sense if you expect to perform a lot of computations on CPU: it could somewhat improve the performance. However, it would take time and effort, so I would not recommend it for a beginner: just use Tensorflow as-is. P.S. b'Hello, TensorFlow!' is fine too. See: The print of string constant is always attached with 'b' inTensorFlow
answers question: http://stackoverflow.com/q/51681727

http://stackoverflow.com/q/51642535
has comment: http://stackoverflow.com/comment/90249663
type: Question
has comment: http://stackoverflow.com/comment/90249719
upvote count: 1
tagged with: button
favorite count: 0
has title: python toggle-able function by a button
type: UnansweredQuestion
has body: I am messing around python, and made this simple thing that works on my pc that opens up discord logs in and messages something. I want this to run in the background and make it toggle-able by a button, all tho i have no idea how to do it since i started learning only today! # log in as dave the goat and message dog dave the dog # positions for my icons below # 20, 137 chrome # 307, 48 search bar # 1674, 105 open discord web # 687, 685 login # 681, 517 click on email # 915, 578 click on the right email # 220, 310 click on dog # 654, 1034 click on message import pyautogui import time pyautogui.click(20, 137) # click on chrome time.sleep(0.7) pyautogui.click(307, 48) # click on search bar pyautogui.typewrite("discord.com") pyautogui.typewrite(["enter"]) time.sleep(0.5) pyautogui.click(1674, 105) time.sleep(0.7) pyautogui.click(687, 685) time.sleep(3.9) pyautogui.click(220, 310) pyautogui.click(654, 1034) pyautogui.typewrite("Dave the goat says hello") pyautogui.typewrite(["enter"])
tagged with: python
has comment: http://stackoverflow.com/comment/90249811
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/comment/90473165
comment on: http://stackoverflow.com/q/51755160
type: Comment
type: QuestionComment
has text: That yields the following error trace: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
score: 0

http://stackoverflow.com/comment/90461917
type: AnswerComment
has text: Right now i cannot try on pc, but i guess you should try something like `ffill` with `df['date']) + timedelta(days=1))`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51748498

http://stackoverflow.com/a/51721411
answers question: http://stackoverflow.com/q/51699523
upvote count: 1
has body: You need to include cudnn in your environment variables(if on windows), if you need to run tensorflow-gpu.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90395491
type: Comment
comment on: http://stackoverflow.com/a/51700041
has text: Python is at usr/bin/Python
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90381069
comment on: http://stackoverflow.com/a/51709735
has text: It seems that `pip` replaces `_` with `-`: https://stackoverflow.com/a/19131777/4352108, so this whole thing should not be a problem anyway. :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51762646
type: Question
has comment: http://stackoverflow.com/comment/90484713
has comment: http://stackoverflow.com/comment/90494000
has comment: http://stackoverflow.com/comment/90484513
has body: I would like to create a simple py script for validation list of parameters with specified value. For example: param1 - value1 param2 - value2 param3 - value3 Params can be printed from console in randomly sequence. Value will be always the same. Should I create a list of params and assign the values for them? How to start? What is the best method for newbie?
tagged with: python
has comment: http://stackoverflow.com/comment/90488939
has title: Compare list of parameters with values
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90495200
has comment: http://stackoverflow.com/comment/90489702

http://stackoverflow.com/q/51792903
has body: I've properly converted my year column into a datetime index, however the month and date are inaccurate and unneeded seeing my dataset only includes year. I've used the format parameter to set year only, however it's still showing as "%Y-%M-%D" format. Original data: index song year artist genre 0 0 ego-remix 2009 beyonce knowles Pop 1 1 shes-tell-me 2009 save Rock 2 2 hello 2009 yta Pop 3 3 the rock 2009 term R&amp;B 4 4 black-culture 2009 hughey Country conducted a few more scrubbing techniques with the above code. Then here are example rows from my dataframe code: clean_df.index = pd.to_datetime(clean_df['year'], format='%Y') clean_df = clean_df.drop(['index', 'year'], 1) clean_df.sort_index(inplace=True) clean_df.head() year song artist genre 1970-01-01 hey now caravan Rock 1970-01-01 show me abc Rock 1970-01-01 hey now xyz Pop 1970-01-01 tell me foxy R&amp;B 1970-01-01 move up curtis R&amp;B Is there any other method to be used to set index as annual only?
has answer: http://stackoverflow.com/a/51793044
accepted answer: http://stackoverflow.com/a/51793044
downvote count: 1
favorite count: 0
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/69789810
type: AnsweredQuestion
score: 3
type: Question
has title: use only year for datetime index - pandas dataframe
tagged with: datetime-format
possible better answer: http://stackoverflow.com/a/69789810
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/51678854
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51678898
has comment: http://stackoverflow.com/comment/90321032
has comment: http://stackoverflow.com/comment/90320938
tagged with: python
possible better answer: http://stackoverflow.com/a/51678946
has answer: http://stackoverflow.com/a/51678946
type: AnsweredQuestion
has title: "\r\n" also not writing to next line
has body: I am just following a simple Python script to write to a text file. The suggetsed method; adding "\n" to the end didn't work. It is printing within a loopAs I am using Windows, I also tried "\r\n." Still it only prints the last item. I have tried moving everything inside and outside the loop (starting with path and ending with file.close() but no go. What's going on here? #Assign variables to the shapefiles park = "Parks_sd.shp" school = "Schools_sd.shp" sewer = "Sewer_Main_sd.shp" #Create a list of shapefile variables shapeList = [park, school, sewer] path = r"C:/EsriTraining/PythEveryone/CreatingScripts/SanDiegoUpd.txt" open(path, 'w') for shp in shapeList: shp = shp.replace("sd", "SD") print shp file = open(path, 'w') file.write(shp + "\r\n") file.close()
tagged with: file-writing
tagged with: loops
has answer: http://stackoverflow.com/a/51678898
type: Question
has comment: http://stackoverflow.com/comment/90320937
tagged with: python-2.7

http://stackoverflow.com/q/51688239
tagged with: printing
has comment: http://stackoverflow.com/comment/90338608
has answer: http://stackoverflow.com/a/51688411
tagged with: variables
type: UnansweredQuestion
tagged with: python
has title: Variable with other variables always prints to same line python
has body: Why does a variable holding other variables print to just one line, even with explicitly listing sep and end? var1 = 123 var2 = ("foo", "678) var3 = 456 var4 = var1, var2, var3 print(var4) # Or sep="\n" Or end="\n" print("var1 is ", var1, var2, var3) Results either which way I seem to run this is: (123, 'foo', 456) 123 foo 456 *Update - Ican do a work around like this, but callign on this multiple times is redundant. print("var1 is: ", var1, "\nvar2 is: ", var2, "\nvar3 is: ", var3) # Results were var1 is: 123 var2 is: foo var3 is: 456 Without being able to store the new lines into a variable, I have to relist this method at every point, which is redundant. Using print(*var4, sep='\n') Breaks apart var2 (which is actually a dict on my script), resulting in output like: 123 foo 1 foo 2 var3
type: Question
has answer: http://stackoverflow.com/a/51688405
score: 0
answer count: 2

http://stackoverflow.com/comment/90451971
comment on: http://stackoverflow.com/a/51741663
type: Comment
score: 0
type: AnswerComment
has text: Same as above, my combined ~ 8 million, so it crash

http://stackoverflow.com/comment/90536448
type: Comment
comment on: http://stackoverflow.com/a/51789477
has text: oops i just realized that i missed the concatenation part
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90289677
has text: @MatthewMankiewicz When you connected it to a monitor, are you running a text framebuffer, or are you running an X11 GUI?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51662312
type: Comment

http://stackoverflow.com/comment/90248942
has text: this does seem to work for my basic test case! Let me play with it a bit more to confirm. thanks!!
type: AnswerComment
comment on: http://stackoverflow.com/a/51642115
score: 0
type: Comment

http://stackoverflow.com/comment/90485536
type: AnswerComment
type: Comment
has text: I am trying `last_oee = Test.objects.latest('oee')` with error: `no such column: Test.id`
comment on: http://stackoverflow.com/a/51761328
score: 0

http://stackoverflow.com/comment/90348260
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51692704
has text: @LukaszSzozda The parameter is as string, is giving error is in the spacing of the string, I already checked the type

http://stackoverflow.com/comment/90436313
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51717955
has text: The jinja runs ar the server. At that time there is no checkbox selecione. You can use javascript to do this on client side.
score: 0

http://stackoverflow.com/q/51658123
score: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90279894
has answer: http://stackoverflow.com/a/51658224
has title: Python : getting error: TypeError: argument of type 'int' is not iterable
has comment: http://stackoverflow.com/comment/90280019
answer count: 1
has comment: http://stackoverflow.com/comment/90279921
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90279901
has body: from sys import exit def gold_room(): print ("how much gold you need)") amount = int(input("amount:")) if 0 in amount or 1 in amount: print(amount) gold_room() Output how much gold you need) amount:1 line 8, in gold_room if 0 in amount or 1 in amount: TypeError: argument of type 'int' is not iterable Process finished with exit code 1 Why am I getting this error?

http://stackoverflow.com/a/51682365
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: The 0.2 cutoff is just a coincidence. What's really going on here is float rounding. float values can't represent most fractions exactly; they just give you the closest 52-bit binary fraction to the number you wanted. Which leads to rounding errors. If you add 1/2 to 0 twice, you get exactly 1. If you add 1/3 to 0 three times, you get a number a tiny bit larger than 1, but 1 is actually the closest binary fraction to that number. If you add 1/4 to 0 four times, you get exactly 1. If you add 1/5 to 0 five times, you get a number a tiny bit larger than 1. If you add 1/6 to 0 six times, you get a number a tiny bit smaller than 1. If you add 1/7 to 0 seven times, you get a number a tiny bit smaller than 1. If you add 1/8 to 0 four times, you get exactly 1. So, 1/3 is fine because it happens to round to 1 anyway; 1/5 is fine, because when x is a tiny bit larger than 1, x &lt; 1 is false, and your loop stops. But 1/6 and 1/7 are not fine, because when x is a tiny bit smaller than 1, x &lt; 1 is still true, so your loop goes one time too many. The simplest fix is to use isclose: while not math.isclose(x, 1): … although that will mean an infinite loop if x isn't pretty close to a unary fraction. Of course your method doesn't work for such values, but it might be nice to get an error or an incorrect result instead of waiting until the end of the universe. So you might want to do something a little more clever, like: while x &lt; 0.999999: A nicer fix, at the cost of some speed, is to use the Fraction type for w and x instead of float. You can still leave y as a float, so your calculations won't eat up all of your memory and time building fractions with ridiculous denominators when you're just looking for an approximation: import fractions x = 0 y = 2.0 w = fractions.Fraction(1, 6) while x &lt; 1: dydx = 1 - 2*x + y deltaY = dydx*w y = y + deltaY x += w print(x,y) Now you'll get: 1 5.521626371742112 But the best option is probably to just keep track of the fact that w is 1/6,…
answers question: http://stackoverflow.com/q/51682303
accepted answer of: http://stackoverflow.com/q/51682303
type: Answer
score: 4

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/51704472
tags question: http://stackoverflow.com/q/51686990

http://stackoverflow.com/a/51721803
upvote count: 3
answers question: http://stackoverflow.com/q/51720968
score: 3
has body: Assuming you have a model as, class MyModel(models.Model): # other fields presentation = models.FileField(upload_to='some/place/') and in your signals, import mimetypes def mail_business_plan(sender, instance, created, **kwargs): if created: ctx = {"ctx": instance} from_email = 'info@some_email.in' subject = 'Business Plan by' + instance.company_name message = get_template('email/business_team.html').render(ctx) to = ['some_email@gmail.com'] mail = EmailMessage(subject, message, to=to, from_email=from_email) content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here &lt;&lt;&lt; mail.attach_file(instance.presentation, instance.presentation.read(), content_type) # &lt;&lt;&lt; change is here also return mail.send() Reference: mimetypes.guess_type()
downvote count: 0
type: Answer

heroku
tags question: http://stackoverflow.com/q/51655018
tags question: http://stackoverflow.com/q/51793817
tags question: http://stackoverflow.com/q/51756650
tags question: http://stackoverflow.com/q/51738274
tags question: http://stackoverflow.com/q/51695744
tags question: http://stackoverflow.com/q/51716168
tags question: http://stackoverflow.com/q/51684413
type: Tag
tags question: http://stackoverflow.com/q/51679928
tags question: http://stackoverflow.com/q/51791955
tags question: http://stackoverflow.com/q/51775331
tag name: heroku
tags question: http://stackoverflow.com/q/51786190

http://stackoverflow.com/q/51797491
accepted answer: http://stackoverflow.com/a/51798449
tagged with: dataframe
has title: using iterrows(), insert a subset of columns from a single row of a dataframe as a new row in another dataframe
answer count: 2
tagged with: for-loop
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51798449
favorite count: 0
possible better answer: http://stackoverflow.com/a/51797627
tagged with: python
type: AnsweredQuestion
has body: I need to select 3 columns from a single row of a 6-column dataframe and append it to another dataframe that has only 3 columns. import pandas import numpy df1 = pd.DataFrame({'Name':['Sanjay','Robin','Hugo'], 'Email':['s@email.com','r@email.com','h@email.com'], 'OrderNo':[23,234,66], 'Address':['234 West Ave','45 Oak Street','Rt. 3443 FM290'], 'Phone':['555-1212','555-3322','555-6655'], 'Age':[34,23,65]}) df2 = pd.DataFrame(columns = ['Name', 'OrderNo', 'Phone']) for index, row in df1.iterrows(): if index == 0: df2 = df2.append(row[0,2,4]) #df2 = df2.append(row['Name','OrderNo','Phone']) &lt;------also threw key error print(df2) Here's what I was hoping to see: Name OrderNo Phone 0 Sanjay 23 555-1212 Here's the output from this exercise: Traceback (most recent call last): File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3109, in get_value return libindex.get_value_box(s, key) File "pandas/_libs/index.pyx", line 55, in pandas._libs.index.get_value_box File "pandas/_libs/index.pyx", line 63, in pandas._libs.index.get_value_box TypeError: 'tuple' object cannot be interpreted as an integer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 15, in &lt;module&gt; File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/series.py", line 766, in __getitem__ result = self.index.get_value(self, key) File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3117, in get_value raise e1 File "/Users/Joe/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3103, in get_value tz=getattr(series.dtype, 'tz', None)) File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine…
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51797627
tagged with: row
score: 1

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/51744668
tags question: http://stackoverflow.com/q/51707009
tags question: http://stackoverflow.com/q/51730947
tags question: http://stackoverflow.com/q/51664323
tags question: http://stackoverflow.com/q/51667473
type: Tag
tags question: http://stackoverflow.com/q/51660134
tags question: http://stackoverflow.com/q/51664292
tags question: http://stackoverflow.com/q/51653954
tags question: http://stackoverflow.com/q/51646627
tags question: http://stackoverflow.com/q/51735794
tags question: http://stackoverflow.com/q/51679188
tags question: http://stackoverflow.com/q/51710542
tags question: http://stackoverflow.com/q/51643985
tags question: http://stackoverflow.com/q/51658126
tags question: http://stackoverflow.com/q/51715352
tags question: http://stackoverflow.com/q/51769008
tag name: xml
tags question: http://stackoverflow.com/q/51756106
tags question: http://stackoverflow.com/q/51756049
tags question: http://stackoverflow.com/q/51710027
tags question: http://stackoverflow.com/q/51747250
tags question: http://stackoverflow.com/q/51703566
tags question: http://stackoverflow.com/q/51655130
tags question: http://stackoverflow.com/q/51750959
tags question: http://stackoverflow.com/q/51657574
tags question: http://stackoverflow.com/q/51660316
tags question: http://stackoverflow.com/q/51704628
tags question: http://stackoverflow.com/q/51671304
tags question: http://stackoverflow.com/q/51689111
tags question: http://stackoverflow.com/q/51721750
tags question: http://stackoverflow.com/q/51760142
tags question: http://stackoverflow.com/q/51750620
tags question: http://stackoverflow.com/q/51777141

expected-condition
tags question: http://stackoverflow.com/q/51641546
type: Tag
tag name: expected-condition

http://stackoverflow.com/q/51665098
type: Question
has title: celery: chord and group in chain not working correctly
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am doing same tasks that needs to reuse the result computed by previous tasks. More specifically, I have three models, and there are two steps of, the first step is clean and segment raw data, the second tasks are two different kind of tokenizations. Two of the model share the same tokenizer, and the third one requires the result computed by the second tokenizer. Hence I first need to clean and segment the raw input, which are later relay to the tokenizers, and one of the tokenized result are fed to two models, and the other one are to be fed to the last model. Lastly, I need to combine the result. However, I can't seem to make the tasks to work. Model prediction tasks were run, but they can't be all passed to the last combining task. I simply the task as the following. @app.route('test', methods = ['GET']) def test(): result = test_chain_group.delay(10) result = [v for v in result.collect()] return str(result) @shared_task def test_chain_group(num): header = [(add.s(5) | group([add.s(6), mul.s(9)])), (mul.s(5)|add.s(3))] chord_r = chord(header, aggr.s()) chain_r = (add.s(7)|chord_r) result = chain_r(num) return result @shared_task def add(a,b): return a+b @shared_task def mul(a,b): return a*b @shared_task def aggr1(data): return data Though the worker computed 28, 198, 88 correctly, but only 28 and 198 were passed to aggr1. Also the flask app didn't wait for the result to come back before returning something to the client.
answer count: 0
score: 1
tagged with: celery

http://stackoverflow.com/comment/90391671
score: 1
comment on: http://stackoverflow.com/q/51687355
has text: @FarNorth I tested your code and indeed yes, it **does exit when using Multiprocessing**. However, it does not exist when run without Multiprocessing.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51771656
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90502341
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90502504
tagged with: pip
has comment: http://stackoverflow.com/comment/90502500
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/14149422
score: 1
has title: can't install urllib3, having proxy in between using pip?
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/90502014
has body: Basically I am trying to install urllib3 but I am countering below error: `C:\Python 3.7\Scripts&gt;pip3.7.exe install urllib3 Collecting urllib3 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x03285170&gt;, 'Connection to pypi.org timed ou t. (connect timeout=15)')': /simple/urllib3/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x00D3E2B0&gt;, 'Connection to pypi.org timed ou t. (connect timeout=15)')': /simple/urllib3/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x032AB610&gt;, 'Connection to pypi.org timed ou t. (connect timeout=15)')': /simple/urllib3/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x032AB670&gt;, 'Connection to pypi.org timed ou t. (connect timeout=15)')': /simple/urllib3/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection .VerifiedHTTPSConnection object at 0x032AB5F0&gt;, 'Connection to pypi.org timed ou t. (connect timeout=15)')': /simple/urllib3/ pip3.7.exe install urllib3 Could not find a version that satisfies the requirement urllib3 (from versions: ) No matching distribution found for urllib3 I Tried: pip3.7.exe install urllib3 and pip install urllib3 both are having the same issue FYI: I am located behind a proxy. All replies are much appreciated
has comment: http://stackoverflow.com/comment/90504985
has answer: http://stackoverflow.com/a/51772004
has comment: http://stackoverflow.com/comment/90502362
tagged with: urllib3

http://stackoverflow.com/q/51786179
has title: How can I copy multiple files between buckets using the API
type: AnsweredQuestion
tagged with: python
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51787129
has body: I am using the Google Cloud Storage package for Python to copy a bunch of files from one bucket to another. Basic code is: from google.cloud.storage.client import Client def copy_bucket_content (client:Client, source_bucket_name, destination_bucket_name, source_dir): source_bucket = client.get_bucket(source_bucket_name) destination_bucket = client.get_bucket(destination_bucket_name) blobs_to_copy = [blob for blob in source_bucket.list_blobs() if blob.name.startswith(source_dir)] source_bucket. for blob in blobs_to_copy: print ("copying {blob}".format(blob=blob.name)) source_bucket.copy_blob(blob, destination_bucket, blob.name) When I pass a source_dir that has many blobs in it the script fails at runtime with: File "/Users/jamiet/.virtualenvs/hive-data-copy-biEl4iRK/lib/python3.6/site-packages/google/cloud/_http.py", line 293, in api_request raise exceptions.from_http_response(response) google.api_core.exceptions.InternalServerError: 500 POST https://www.googleapis.com/storage/v1/b/path/to/blob/copyTo/b/path/to/blob: Backend Error This invariably occurs after transferring between 50 and 80 blobs (it doesn't fail at the same point each time). I am assuming that I'm hitting some sort of API request limit. Would that be the case? If so, how do I get around this? I suppose lifting the restriction would be one way but better would be able to issue just one call to the REST API rather than looping over all the blobs and copying them one at a time. I searched around the GCS python package but didn't find anything that might help. I assume there's a better way of accomplishing this but I don't know what it is, can anyone help?
tagged with: google-cloud-storage
accepted answer: http://stackoverflow.com/a/51787129

http://stackoverflow.com/q/51644167
type: UnansweredQuestion
tagged with: web-scraping
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51644297
has body: I cant get his for loop to be read and take the listing of items it just prints nothing at all and skips the whole loop import requests import re from bs4 import BeautifulSoup maxPages = 10 keyword = "ps4" costMax = 0 costMin = 0 def tradeSpiderGS(maxPages): page = 1 while page &lt;= maxPages: print(page) #creating url for soup if page &lt;= 1: url = 'https://www.gamestop.com/browse?nav=16k-3-'+ keyword +',28zu0' else: url = 'https://www.gamestop.com/browse?nav=16k-3-' + keyword + ',2b'+ str(page *12) + ',28zu0' #creating soup object srcCode = requests.get(url) plainTxt = srcCode.text soup = BeautifulSoup(plainTxt,"html.parser") #this for loop is not being read supposed to grab links on gs website for links in soup.find_all('a', {'class': 'ats-product-title-lnk'}): href = links.get('href') trueHref = 'https://www.gamestop.com/' + href print(trueHref) page += 1 tradeSpiderGS(maxPages)
tagged with: beautifulsoup
score: 0
tagged with: python
has title: My for loop isnt being read on my scraper of gamestop
tagged with: python-3.x

http://stackoverflow.com/comment/90309710
has text: I'm pretty sure this functionality doesn't exist. I don't see any way to create a link like this, or for a Discord bot to see information about the invite you used to join a server. What you *can* do is have private channels for your various roles, and then use links to invite members to those channels. Your bot can easily assign a role to anyone who posts in a particular channel.
score: 1
comment on: http://stackoverflow.com/q/51662220
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90276588
has text: Would you happen to know how I could do a different function if in the `categories` list, two or more of the keys in `my_dict` values as opposed to each individual function?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51655850
type: Comment

http://stackoverflow.com/a/51681420
type: Answer
has comment: http://stackoverflow.com/comment/90327886
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51681243
downvote count: 0
has body: Try this: batch['doc_tok']=batch['doc_tok'].long().cpu() batch['query_tok']=batch['query_tok'].long().cpu()

http://stackoverflow.com/comment/122207043
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/55555605
type: Comment
has text: I know this answer is pretty old, but now you don't need the from_data or from_dict function. the message.embeds[0] is a discord.Embed object

http://stackoverflow.com/comment/90416372
score: 0
comment on: http://stackoverflow.com/a/51725853
has text: For some reason, this did not work with my dataset as the output using this was not in proper order and all messed up. However @piRSquared solution worked flawlessly
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51748972
has body: As is officially written here ImageDataGenerator is a batches Generator of tensor image data with real-time data augmentation. The data will be looped over (in batches). This means that will on the fly apply transformations to batch of images randomly. For instance: train_datagen = ImageDataGenerator( rescale=1./255, #scale images from integers 0-255 to floats 0-1. shear_range=0.2, zoom_range=0.2, # zoom in or out in images horizontal_flip=True) #horizontal flip of images At every new epoch new random transformations will be applied and in this way we train with a little different set of images each time. Obtaining more data is not always achievable or possible, using ImageDataGenerator is helpful this way.
upvote count: 9
answers question: http://stackoverflow.com/q/51748514
score: 8
has comment: http://stackoverflow.com/comment/100724593
has comment: http://stackoverflow.com/comment/105387212
type: Answer
downvote count: 1

http://stackoverflow.com/comment/90303780
comment on: http://stackoverflow.com/q/51670625
has text: Also check this one https://matthew-brett.github.io/teaching/global_scope.html
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90356521
has text: @user2009020 they are not. When you say `array` in Python, that usually means a `numpy.ndarray` object, or even an `array.array` object.
comment on: http://stackoverflow.com/q/51697299
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90537605
has text: Can you provide an example of your DAG code, 2 minutes for a DAG import is extremely slow and it is likely you are doing something resource intensive in your top-level DAG code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51743225
score: 0

http://stackoverflow.com/comment/90308798
comment on: http://stackoverflow.com/q/51671602
score: 1
type: Comment
type: QuestionComment
has text: I didn't downvote, but you have the reasons why it was filtered right there. You know exactly why it was treated as such, so fix it. You have a few hypotheses for how you could make it better, so implement them and see if that helps

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/51747842
tags question: http://stackoverflow.com/q/51738286
tags question: http://stackoverflow.com/q/51752599
tags question: http://stackoverflow.com/q/51794326
type: Tag
tags question: http://stackoverflow.com/q/51664813

http://stackoverflow.com/q/51791197
has comment: http://stackoverflow.com/comment/90540027
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51791268
tagged with: python
score: 2
downvote count: 0
has body: Is there a way to split a string in a pandas dataframe column like coordinates(gDNA) chr10:g.89711916T&gt;A into tab separated fields chr\start\ref\alt chr10\t89711916\tT\tA in pandas. So far I've tried df'chr','others' = df['coordinates(gDNA)'].str.split(':',expand=True) and extracted the first part, but not sure what to do for the rest
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51791491
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51791317
favorite count: 0
has title: splitting string a multiple delimiters

http://stackoverflow.com/q/51758845
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90482298
has comment: http://stackoverflow.com/comment/90512754
tagged with: django-views
has body: AIM In general, the application displays location data for specific Twitter hashtags. For instance, if the User enters "python". The application searches Twitter for recent tweets containing the hashtag "python" and, where possible, displays location data for those tweets. Currently, the location data is displayed as a dict, which is achieved through the def display_locations(self) function in Models.py. Now, I am attempting to display that data on a histogram. I have written the draw_histogram() function in Views.py below but I get the error stated below. I suspect that an effective solution may be to call the method: Hashtag.display_locations in the function: draw_histogram(), but I am not sure. I have two, alternate, questions: In draw_histogram() in Views.py, how to set country_list to achieve the aim? Perhaps it is more appropriate to include the draw_histogram() function as a method in the class SearchResultsView(generic.ListView)? If so, how do I do so? ERROR Exception Type: TypeError Exception Value: draw_histogram() missing 1 required positional argument: 'self' CODE Models.py class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) locations = models.ManyToManyField(Location, blank=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Creates a frequency dict of the locations attached to the Hashtag model """ country_list = list(self.locations.values_list('country', flat=True).all()) for country in country_list: location_freq = {i:country_list.count(i) for i in set(country_list)} return location_freq Views.py class SearchResultsView(generic.ListView): """ Generic class-based view listing search results of locations """ model = Hashtag template_name = 'mapping_twitter/results.html' def get_queryset(self, **kwargs): """ Restrict the results to the search_text entered on the…
has comment: http://stackoverflow.com/comment/90476911
tagged with: matplotlib
type: Question
has title: How to display a histogram from a queryset in django
has comment: http://stackoverflow.com/comment/90477079
score: 0
answer count: 0

http://stackoverflow.com/a/51705979
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51705871
accepted answer of: http://stackoverflow.com/q/51705871
upvote count: 2
type: AcceptedAnswer
has body: You cannot use the except statement outside of a try: ... except: ... code block. https://docs.python.org/3/tutorial/errors.html#handling-exceptions So you would rephrase your code as while True: try: if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time() : print ("Pin 18 High") else: print ("Pin 18 Low") except KeyboardInterrupt: pass print("Error..... Quiting.....") raise sys.exit() which I haven't tried but essentially wraps the if statement with a try clause, and any KeyboardInterrupt would be captured by the except statement.

http://stackoverflow.com/q/51720869
possible better answer: http://stackoverflow.com/a/52378507
type: Question
has body: I am new to Python and have decided to have some exercise in TestDome. Below is the Code to an easy question from that website but because it does not print the result as it should, I get zero as a score. class IceCreamMachine: all={} def __init__(self, ingredients, toppings): self.ingredients = ingredients self.toppings = toppings def scoops(self): for i in range(0,len(self.ingredients)): for j in range(0,len(self.toppings)): print ([self.ingredients[i],self.toppings[j]]) machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"]) print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']] Can anybody give a Hint how to fix it?
has answer: http://stackoverflow.com/a/52378507
downvote count: 0
has answer: http://stackoverflow.com/a/51720942
answer count: 3
has answer: http://stackoverflow.com/a/56303852
favorite count: 0
upvote count: 1
tagged with: python
tagged with: collections
accepted answer: http://stackoverflow.com/a/51720942
type: AnsweredQuestion
has title: Print Strings in Python (TestDome)
score: 1

http://stackoverflow.com/comment/90888666
type: Comment
has text: It is creating multi index.i have different question can I ask
type: AnswerComment
comment on: http://stackoverflow.com/a/51770117
score: 0

http://stackoverflow.com/comment/90315585
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51665107
type: Comment
has text: Just one more thing, how does this variable `lastest_none_empty[0]` get the value? I'm confused here

http://stackoverflow.com/comment/90342276
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51690051
score: 0
has text: @LevZakharov I think I have a subquadratic time solution to this problem using suffix trees that would work in linear time as long as m is bounded. Can you check what I have and see whether this works?

http://stackoverflow.com/a/77706181
score: 0
answers question: http://stackoverflow.com/q/51723928
has body: An extension of the cumsum strategy from @gyx-hh was able to solve the issue for me df['samplegroup'] = df.sample(frac=1).groupby('city').cumcount() df['samplegroup'] = ((df['samplegroup'] + df.groupby('city').ngroup()) % 3) grouped = df.groupby(['samplegroup']) list(grouped) [(0, day city temperature windspeed event samplegroup 5 2017-01-06 new york 33 5 Sunny 0 7 2017-01-08 new york 23 7 Rain 0 9 2017-01-02 mumbai 85 12 Fog 0 12 2017-01-05 mumbai 89 7 Sunny 0 15 2017-01-08 mumbai 89 8 Rain 0 18 2017-01-03 paris 54 8 Cloudy 0 20 2017-01-05 paris 43 20 Sunny 0 22 2017-01-07 paris 40 14 Rain 0), (1, day city temperature windspeed event samplegroup 0 2017-01-01 new york 32 6 Rain 1 3 2017-01-04 new york 33 7 Sunny 1 4 2017-01-05 new york 31 7 Rain 1 8 2017-01-01 mumbai 90 5 Sunny 1 10 2017-01-03 mumbai 87 15 Fog 1 13 2017-01-06 mumbai 80 10 Fog 1 16 2017-01-01 paris 45 20 Sunny 1 17 2017-01-02 paris 50 13 Cloudy 1 21 2017-01-06 paris 48 4 Cloudy 1), (2, day city temperature windspeed event samplegroup 1 2017-01-02 new york 36 7 Sunny 2 2 2017-01-03 new york 28 12 Snow 2 6 2017-01-07 new york 27 12 Rain 2 11 2017-01-04 mumbai 92 5 Rain 2 14 2017-01-07 mumbai 85 9 Sunny 2 19 2017-01-04 paris 42 10 Cloudy 2 23 2017-01-08 paris 42 15 Cloudy 2 24 2017-01-09 paris 53 8 Sunny 2)]
type: Answer
has comment: http://stackoverflow.com/comment/136993770

http://stackoverflow.com/comment/106135688
type: AnswerComment
has text: @atjw94 I don't have anything in the source code, but you could use this: `y[x.index(kn.knee)]` -- feel free to open an issue or a pull request on GitHub if you think it would be a useful feature :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52577880

orm
tags question: http://stackoverflow.com/q/51749817
tag name: orm
type: Tag
tags question: http://stackoverflow.com/q/51659080

http://stackoverflow.com/q/51687502
favorite count: 0
has body: I'm trying to apply the following formula to my data: <img src="https://latex.codecogs.com/gif.latex?%5Cinline%20M%28t%29%3D%5Cint_%7B0%7D%5E%7Bt%7Df%28%5Ctau%20%29G%28t-%5Ctau%29d%5Ctau%3D%5Cint_%7B0%7D%5E%7Bt%7Df%28%5Ctau%20%29%5BA%5Cfrac%7B%5Clambda%20_%7Bbi%7D%7D%7B%5Clambda%20_%7Bbi%7D-%5Clambda%20_%7Bpb%7D%7D%28e%5E%7B-%5Clambda%20_%7Bpb%7D%28t-%5Ctau%29%7D-e%5E%7B-%5Clambda%20_%7Bbi%7D%28t-%5Ctau%29%7D%29+Be%5E%7B-%5Clambda%20_%7Bbi%7D%28t-%5Ctau%29%7D%5Dd%5Ctau" alt="M(t)=\int_{0}^{t}f(\tau&space;)G(t-\tau)d\tau=\int_{0}^{t}f(\tau&space;)[A\frac{\lambda&space;_{bi}}{\lambda&space;_{bi}-\lambda&space;_{pb}}(e^{-\lambda&space;_{pb}(t-\tau)}-e^{-\lambda&space;_{bi}(t-\tau)})+Be^{-\lambda&space;_{bi}(t-\tau)}]d\tau"> where A = 0.3, B=1, lambda_pb = 0.000431062, lambda_bi = 0.000580525. For time t, I have: t=np.array([0, 900, 1800, 2700, 3600, 4500, 5400, 6300, 7200, 8100]) and f(t): f=np.array([ 0., 0., 0.00555556, 0., 0., 0., 0., 0., 0., 0.]) For G(t): G=np.array([ 1., 0.69255058, 0.47822256, 0.32940846, 0.22642738, 0.15536312, 0.10643991, 0.07282715, 0.04977304, 0.03398402]) Then I'm convolving G(t) and f(t) using the following code: import numpy as np from numpy import convolve convolution=np.convolve(f, G)[:len(t)]*(t[1]-t[0]) I obtain the following plot : For t < tau, I obtain the curve in red. However, this is not correct, since for t < tau, G(t-tau)=0 (causality principle). Hence, I would like to obtain the black curve (vertical increase at t=tau). Can anyone tell me how to improve my code to do that and only account for the response function G(t-tau) for t>tau? Maybe using a step function?
tagged with: convolution
tagged with: python
type: AnsweredQuestion
has title: Convolution of step function and exponential decay
has answer: http://stackoverflow.com/a/51718000
upvote count: 1
type: Question
tagged with: numpy
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51718000
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/91347497
has text: i am still getting the error after i upgrade from python 2.7 to 3.7. Any suggestion what i can do? just started python last week
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51957181

http://stackoverflow.com/a/62924439
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51783300
has comment: http://stackoverflow.com/comment/111275638
has body: I encountered the same problem following Miguel Grinberg tutorial. I solved this my adding from app.models import User, Post to migrations/env.py
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/51794907
has body: Try this command python -m pip &lt;action&gt;
answers question: http://stackoverflow.com/q/51794827
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51774253
has comment: http://stackoverflow.com/comment/90507607
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51774540
downvote count: 0
has comment: http://stackoverflow.com/comment/90507206
accepted answer: http://stackoverflow.com/a/51774540
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90507500
has comment: http://stackoverflow.com/comment/90507655
type: AnsweredQuestion
score: 1
type: Question
has body: My input is a filename, some examples: /some/file/path/thefooisgood.txt /some/file/path/thisfooisalsogood.txt /some/file/path/thisfooalsohasbar.txt I want to find/allow all filenames/paths that contain the substring foo so long as the string doesn't also have the substring bar in it. Substring bar may appear anywhere in the file path, doesn't always necessarily come after foo and may sometimes be in the path name, not just the filename. Same goes for foo. I can't seem to get it right.
has title: Regex: Allow a string that contains "foo" but not if that same string also contains "bar"

http://stackoverflow.com/a/51676510
downvote count: 0
has body: Each option is, in fact, a flag among many possible ones, so you need to compose them using bitwise AND (&amp;) and bitwise OR (|) operations. It is done like that because these options are not mutually excluding each other, you need to compose a final value by picking various options that you combine together. So each one has a value being a power of 2, which means it is a bit being 1 at some specific position, and the final value then encodes if each specific separate flag is either on or off. So you need bitwise operators to manage them and construct the final value you want. See: In [8]: print ssl.OP_NO_TLSv1, bin(ssl.OP_NO_TLSv1) 67108864 0b100000000000000000000000000 In [9]: print ssl.OP_NO_TLSv1_1, bin(ssl.OP_NO_TLSv1_1) 268435456 0b10000000000000000000000000000 In [13]: print ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1, bin(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) 335544320 0b10100000000000000000000000000 In [14]: print ssl.OP_NO_TLSv1 &amp; ssl.OP_NO_TLSv1_1, bin(ssl.OP_NO_TLSv1 &amp; ssl.OP_NO_TLSv1_1) 0 0b0 You see that if you want both of these options, you need to flip both bits to 1, and hence need an OR (|) otherwise with an AND (&amp;) since each value has only one bit set to 1, at a different position each time, you are guaranteed to always get 0 as a result, which means no feature at all, so certainly not what you need. In short, in cases like that to compose values, you will never use AND (&amp;). Now, about &amp;= ~: ~ is the bitwise negation, so it is useful to remove some options while keeping other options that are already set. ctx.options &amp;= ~ssl.OP_NO_SSLv3 This construct makes you flip to 0 the bit related to ssl.OP_NO_SSLv3 in the final value. See: In [34]: ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) In [37]: print ctx.options, bin(ctx.options) 2197816319 0b10000011000000000000001111111111 In [38]: print bin(ssl.OP_NO_SSLv3) 0b10000000000000000000000000 In [40]: print ctx.options &amp; ~ssl.OP_NO_SSLv3 2164261887 In [41]: print ctx.options &amp; ~ssl…
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51672803
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51672803
type: Answer

http://stackoverflow.com/comment/90485959
has text: this is the formatted json that we use for development
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51763581

http://stackoverflow.com/q/51665438
score: 1
favorite count: 0
has title: Energy Spectrogram with non-evenly spaced values on Python
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: plot
answer count: 0
has body: I'm trying to plot a time-frequency-energy distribution plot (basically a spectogram); however, in my case I have the arrays with values for frequency and energy already determined (so there's no need to use the spectrogram function in matplotlib and my the thing I'm working with is already sampled so time is just the number of points in the array). Here's a very basic example of what these arrays might look like: time = [0, 1, 2, 3, 4, 5] freq = [ [ 5, 8, 10, 13, 19, 21] , [1.3, 3.4, 8.9, 18.3, 45.4, 43.9] ] amp = [ [ 2.3 , 4.7, 9.1 , 10.3, 3.2, 1.2], [7.4 , 1.1 , 4.5 , 6.6, 8.9 , 6.7] ] in my actual implementation my time array would be really big (like 216,000 points long) and so my frequency and amplitude arrays would be an array of N (I set N = 2 in the basic example above) arrays of 216,000 points long. Note that the values in frequency and amplitude aren't evenly spaced so I don't think I can do a meshgrid or surface plot (pretty sure meshgrid breaks with too many points). Let me know if I should provide more information.
tagged with: matplotlib
type: Question
downvote count: 0
tagged with: spectrogram

http://stackoverflow.com/q/51783148
has comment: http://stackoverflow.com/comment/90523776
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90523935
accepted answer: http://stackoverflow.com/a/51783823
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90523896
has comment: http://stackoverflow.com/comment/90524113
has body: I have a python module containing (amongst other functions) this piece of code: def check_color_range(*argv): """ Abbreviated documentation and other tests. &gt;&gt;&gt; check_color_range(23, -1, 99, 10000) Traceback (most recent call last): ... TypeError: Falscher Farbwert -1! """ for c in argv: if c &lt; 0 or c &gt; 255: raise TypeError('Falscher Farbwert ' + str(c) + '!') When I run this using doctest like so: python -m doctest -v demo.py, I get the following output: Trying: check_color_range(23, -1, 99, 10000) Expecting: Traceback (most recent call last): ... TypeError: Falscher Farbwert -1! ********************************************************************** File "C:\az\code_camp_python\src\EigeneProgramme\Tag3\arcade_base\demo.py", line 5, in demo.check_color_range Failed example: check_color_range(23, -1, 99, 10000) Expected: Traceback (most recent call last): ... TypeError: Falscher Farbwert -1! Got: Traceback (most recent call last): File "C:\az\miniconda3\envs\py37\lib\doctest.py", line 1329, in __run compileflags, 1), test.globs) File "&lt;doctest demo.check_color_range[0]&gt;", line 1, in &lt;module&gt; check_color_range(23, -1, 99, 10000) File "C:\az\code_camp_python\src\EigeneProgramme\Tag3\arcade_base\demo.py", line 12, in check_color_range raise TypeError('Falscher Farbwert ' + str(c) + '!') TypeError: Falscher Farbwert -1! 1 items had no tests: demo ********************************************************************** 1 items had failures: 1 of 1 in demo.check_color_range 1 tests in 2 items. 0 passed and 1 failed. ***Test Failed*** 1 failures. For me the expected and the actual Errors look the same, but I may be missing something. I already compared whitespace etc., which seems to be the same. I then tried to paste the complete Traceback from the "Got:" section into the testcase - and I'm still get the failed test, so I guess I must be doing something wrong. I'd be very happy, if you could give me a heads-up.
answer count: 1
downvote count: 0
tagged with: doctest
has answer: http://stackoverflow.com/a/51783823
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90523737
has title: Python 3/Doctest: Exception is not evaluated as expected result

http://stackoverflow.com/q/51700723
has answer: http://stackoverflow.com/a/51710107
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has title: Regex recursion and multiple replacements
has answer: http://stackoverflow.com/a/51701619
has body: I have come across a challenge with regex and could use some assistance. Currently working on a script to update syntax on the source file for plugins by using regex. Situation: Without looping a regex search until no match, I am attempting to declare multiple variables as int within functions, since the old syntax did not require it. For example this is the old code, followed by what I then want it to become void Split(const char[] variable, test1, char[] variable2, test2, test3) { void Split(const char[] variable, int test1, char[] variable2, int test2, int test3) { I have a regex to match a single instance of it here: (^\w.*?)(\(|, )([\w_\&amp;]+)(, |\)) I could then replace with: \1\2int \3\4
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90363537

http://stackoverflow.com/a/51754996
upvote count: 1
answers question: http://stackoverflow.com/q/51753017
downvote count: 0
type: Answer
has body: personal guess is to use some algorithm to detect the grayscale change. The grayscale variation around the scratch should be bigger than the variation in other area. Sobel and Scharr Derivatives could be an option. This is a link to python-openCV about image gradient. You can first crop out the fruit with coutour application
score: 1

http://stackoverflow.com/q/51763627
downvote count: 2
possible better answer: http://stackoverflow.com/a/51763805
has comment: http://stackoverflow.com/comment/90486051
type: Question
has title: How to fetch input from the csv file in python
has answer: http://stackoverflow.com/a/51763808
accepted answer: http://stackoverflow.com/a/51763762
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90488495
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -2
answer count: 4
has answer: http://stackoverflow.com/a/51763805
has answer: http://stackoverflow.com/a/51764877
type: AnsweredQuestion
has body: I have a csv (input.csv) file as shown below: VM IP Naa_Dev Datastore vm1 xx.xx.xx.x1 naa.ab1234 ds1 vm2 xx.xx.xx.x2 naa.ac1234 ds1 vm3 xx.xx.xx.x3 naa.ad1234 ds2 I want to use this csv file as an input file for my python script. Here in this file, first line i.e. (VM IP Naa_Dev Datastore) is the column heading and each value is separated by space. So my question is how we can use this csv file for input values in python so if I need to search in python script that what is the value of vm1 IP then it should pickup xx.xx.xx.x1 or same way if I am looking for VM which has naa.ac1234 Naa_Dev should take vm2. I am using Python version 2.7.8 Any help is much appreciated. Thanks
has answer: http://stackoverflow.com/a/51763762

http://stackoverflow.com/comment/90341358
has text: `[00 = {str} '1 \tname1\t3'` doesn't look like valid python syntax to me. Please fix it to be a [mcve].
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51689790

http://stackoverflow.com/comment/90531311
score: 0
type: Comment
type: QuestionComment
has text: I edited my question with detailed stack trace.. does this work?
comment on: http://stackoverflow.com/q/51786862

http://stackoverflow.com/comment/90520801
type: AnswerComment
type: Comment
has text: @Aran-Fey, you guys are still stuck on the concepts of C-language which was introduced in 1972. Python is built to do complex task so lets make the most out of it.
comment on: http://stackoverflow.com/a/51781293
score: 0

http://stackoverflow.com/comment/90252915
type: Comment
comment on: http://stackoverflow.com/q/51644402
score: 0
has text: Where are you running the command to reinstall `pip`? And where is the message appearing? `pip` may need to be updated in your venv, but you're trying to update in another enviornment
type: QuestionComment

foreground
tags question: http://stackoverflow.com/q/51797925
type: Tag
tag name: foreground

http://stackoverflow.com/comment/90281674
score: 0
comment on: http://stackoverflow.com/q/51658729
type: Comment
type: QuestionComment
has text: Try using the answer given below with the modification I wrote in the comments.

http://stackoverflow.com/comment/90542625
type: Comment
comment on: http://stackoverflow.com/a/51792085
score: 0
type: AnswerComment
has text: Yeah, but I want to save the state of the array `b` between consecutive calls to `closed(10)`, quite much like in a generator. I'll ask a followup question next week. :) Thanks alot for your help!

http://stackoverflow.com/a/51696911
score: 3
answers question: http://stackoverflow.com/q/51644278
accepted answer of: http://stackoverflow.com/q/51644278
type: AcceptedAnswer
downvote count: 0
has body: I found the answer myself and the answer is Yes, it is possible to have multiple custom matchers when using VCR.py It's actually similar to how the VCRPY docs show using a single custom matcher. Below is a general structure on how it can be done: def vcr_matcher_1(r1, r2): # logic for matching r1 and r2 requests def vcr_matcher_2(r1, r2): # logic for matching r1 and r2 requests In your recording code, you can use something like: custom_vcr = vcr.VCR() custom_vcr.register_matcher('vcr_matcher_1', vcr_matcher_1) custom_vcr.register_matcher('vcr_matcher_2', vcr_matcher_2) with custom_vcr.use_cassette('cassette_name.yml', match_on = ['method', 'scheme', 'host', 'port', 'vcr_matcher_1', 'vcr_matcher_2']): The above example also shows you can mix your custom matchers with default provided matchers by VCR.py Ref: http://vcrpy.readthedocs.io/en/latest/advanced.html#register-your-own-request-matcher
type: Answer
upvote count: 3

http://stackoverflow.com/comment/90548365
type: QuestionComment
has text: But I don't know what good that would do for you. A `Cmd` isn't going to call anything but the `do_*` functions. And, after a command is entered, it's going to look for `complete_*` functions to complete the arguments, and if your `complete_*` functions don't have matching `do_*` functions nothing is going to work.
score: 0
comment on: http://stackoverflow.com/q/51795382
type: Comment

kivy
tags question: http://stackoverflow.com/q/51762848
tags question: http://stackoverflow.com/q/51728720
tags question: http://stackoverflow.com/q/51797204
type: Tag
tags question: http://stackoverflow.com/q/51761130
tags question: http://stackoverflow.com/q/51668784
tags question: http://stackoverflow.com/q/51651253
tags question: http://stackoverflow.com/q/51732319
tags question: http://stackoverflow.com/q/51789540
tags question: http://stackoverflow.com/q/51787177
tags question: http://stackoverflow.com/q/51719374
tags question: http://stackoverflow.com/q/51653962
tags question: http://stackoverflow.com/q/51753641
tags question: http://stackoverflow.com/q/51793700
tags question: http://stackoverflow.com/q/51684097
tags question: http://stackoverflow.com/q/51697115
tags question: http://stackoverflow.com/q/51758975
tags question: http://stackoverflow.com/q/51679570
tags question: http://stackoverflow.com/q/51675262
tags question: http://stackoverflow.com/q/51766655
tags question: http://stackoverflow.com/q/51687169
tags question: http://stackoverflow.com/q/51798287
tags question: http://stackoverflow.com/q/51781916
tags question: http://stackoverflow.com/q/51659510
tags question: http://stackoverflow.com/q/51731647
tags question: http://stackoverflow.com/q/51735862
tags question: http://stackoverflow.com/q/51697982
tag name: kivy
tags question: http://stackoverflow.com/q/51756641
tags question: http://stackoverflow.com/q/51751001
tags question: http://stackoverflow.com/q/51641456
tags question: http://stackoverflow.com/q/51684939
tags question: http://stackoverflow.com/q/51695725
tags question: http://stackoverflow.com/q/51701737
tags question: http://stackoverflow.com/q/51716333
tags question: http://stackoverflow.com/q/51713984
tags question: http://stackoverflow.com/q/51652937
tags question: http://stackoverflow.com/q/51727669
tags question: http://stackoverflow.com/q/51676947
tags question: http://stackoverflow.com/q/51716272
tags question: http://stackoverflow.com/q/51704814
tags question: http://stackoverflow.com/q/51676248
tags question: http://stackoverflow.com/q/51759951

http://stackoverflow.com/q/51737993
score: 1
has answer: http://stackoverflow.com/a/51738117
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/51738117
answer count: 1
tagged with: python
has body: I am trying to use a neural network to approximate the log-normal distribution pdf (just as an exercise). However, model.predict() always returns 1. Here is my code import tensorflow as tf import numpy as np from scipy.stats import lognorm from tensorflow import keras mu = 5 sig =1 data = np.linspace(0,600,10000) labels =lognorm.pdf(data,sig,0,np.exp(mu)) model = keras.Sequential() model.add(keras.layers.Dense(64,input_shape=(1,),activation='sigmoid')) model.add(keras.layers.Dense(64, activation='sigmoid')) model.add(keras.layers.Dense(1, activation='softmax')) model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss='mse', metrics=['accuracy']) model.fit(data, labels, epochs=1) # Now test x = np.random.lognormal(mu, sig, 100) y =lognorm.pdf(x,sig,0,np.exp(mu)) score = model.evaluate(x, y) # score = [0.9951245284080505, 0.0] # Now try prediction newx = np.linspace(600,1000,50) newy = model.predict(newx) score2 = model.evaluate(newx, newy) # score2 = [0.0, 1.0] score2 is 0, but it shouldn't be. Would someone help me find where I did wrong?
tagged with: prediction
tagged with: machine-learning
upvote count: 1
has title: Errors in making predictions using keras
type: AnsweredQuestion

http://stackoverflow.com/comment/90312560
type: AnswerComment
has text: Thanks, that fixed that error, but I believe what is missing is that your solution formats it to a new list and removes the necessary `<Cell R30C4 '*Value*'>` format that is required for me to push this back to a Google Sheet with the `gspread` library. If you look back to my question I set each individual forecast value to the `.value` property of `cell` (`cell.value = forecast`). Any ideas of what to modify? the `forecasting_range[i]?`
type: Comment
comment on: http://stackoverflow.com/a/51661647
score: 0

http://stackoverflow.com/comment/90482003
has text: Don't forget to put `r` in front of the windows paths like `r"C:\Users\qeee11\Downloads\"`
type: QuestionComment
comment on: http://stackoverflow.com/q/51761408
score: 0
type: Comment

http://stackoverflow.com/a/51644668
answers question: http://stackoverflow.com/q/51644606
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51644606
type: Answer
downvote count: 0
score: 1
has body: You should create the zip file with the root path joined so that the zip file will be created where the JSON file is, and when writing the JSON file into the zip file, use the writestr method instead of write so that you can name the file with the path name you want, which in this case is just the file name with no path name at all: for root, dirs, files in os.walk(path, topdown=True): print('This is root: ', root) for file in files: zf = zipfile.ZipFile(os.path.join(root, '{}.zip'.format(file[:-5])), 'w', zipfile.ZIP_DEFLATED) zf.writestr(file, open(os.path.join(root, file)).read()) zf.close()
upvote count: 1

http://stackoverflow.com/a/51684616
has comment: http://stackoverflow.com/comment/90332653
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90332280
has comment: http://stackoverflow.com/comment/121028535
has comment: http://stackoverflow.com/comment/90332435
has comment: http://stackoverflow.com/comment/90332388
has comment: http://stackoverflow.com/comment/90332875
score: 5
has body: Q: How do wait for the user to click the button? In this case , you can introduce WebDriverWait which is explicit wait in selenium. You can try with this code : from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.ID, 'submitID'))) Q. How do I then click OK on the dialog box? In this case first you would have to switch the focus of your web driver to the alert and then you can click on it. alert = browser.switch_to.alert alert.accept() print("alert accepted") UPDATE 1: When you are performing the click operation then there is one alert gets popped up. You can extract the text from the alert using this code : alert = browser.switch_to.alert msg_from_alert = alert.text alert.accept() Now You can simply match it with your expected message which is already known to you. expected_msg = "some msg from alert" from collections import Counter Counter(msg_from_alert) == Counter(expected_msg) True
has comment: http://stackoverflow.com/comment/90332155
type: Answer
has comment: http://stackoverflow.com/comment/90332932
has comment: http://stackoverflow.com/comment/90332521
has comment: http://stackoverflow.com/comment/117279853
has comment: http://stackoverflow.com/comment/90332214
accepted answer of: http://stackoverflow.com/q/51681276
upvote count: 5
has comment: http://stackoverflow.com/comment/121028328
answers question: http://stackoverflow.com/q/51681276
has comment: http://stackoverflow.com/comment/90332820
has comment: http://stackoverflow.com/comment/121028172

http://stackoverflow.com/q/51688822
type: Question
upvote count: 4
answer count: 3
downvote count: 0
favorite count: 0
has body: Can anybody help me please? I am new to machine learning Studio. I am using free azure machine learning studio workspace trying to use in cell run all got the following error. ValueError Traceback (most recent call last) &lt;ipython-input-1-17afe06b8f16&gt; in &lt;module&gt;() 1 from azureml import Workspace 2 ----&gt; 3 ws = Workspace() 4 ds = ws.datasets['Lemonadecsv.csv'] home/nbuser/anaconda3_23/lib/python3.4/site-packages/azureml/__init__.py in __init__(self, workspace_id, authorization_token, endpoint) 883 endpoint = https://studio.azureml.net 884 """ --&gt; 885 workspace_id, authorization_token, endpoint, management_endpoint = _get_workspace_info(workspace_id, authorization_token, endpoint, None) 886 887 _not_none_or_empty('workspace_id', workspace_id) /home/nbuser/anaconda3_23/lib/python3.4/site-packages/azureml/__init__.py in _get_workspace_info(workspace_id, authorization_token, endpoint, management_endpoint) 849 850 if workspace_id is None: --&gt; 851 raise ValueError('workspace_id not provided and not available via config') 852 if authorization_token is None: 853 raise ValueError('authorization_token not provided and not available via config') ValueError: workspace_id not provided and not available via config 5 frame = ds.to_dataframe()
has answer: http://stackoverflow.com/a/52219756
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51693935
score: 4
has answer: http://stackoverflow.com/a/51769425
has title: can't Explore Data in a Jupyter Notebook using python 3 azure machine learning studio

http://stackoverflow.com/comment/90474347
has text: I'm with @cricket_007. I don't think the extra `% i` is needed after `racadm_command`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51757402

http://stackoverflow.com/q/51663212
tagged with: django-models
has title: How to check if value occurs in a field of a model list in Django?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/29587382
tagged with: django
has body: I have a list of Django models, I want to check if a string value occurs somewhere in a specific field for ANY model in the list. Please see the example below: class something: animals = [] #type: list[Animals] def does_atleast_one_animal_make_that_sound(animal_sound): if animal_sound in ...# for each animal in animals, turn animal.sound into a list print('One of the animals in the list makes this sound') else: print('No animal makes this sound') How would I correctly write the part of the function with the "..."?
has answer: http://stackoverflow.com/a/51663400
type: Question

http://stackoverflow.com/comment/90455459
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51747015
has text: Thank you for your answer, the problem is that I want to do it for all store ids so it needs to loop all stores, so final df should also include them ,any ideas?

http://stackoverflow.com/comment/90268537
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51652397
type: Comment
has text: If all your sub-dicts have only one item, you should flatten them all first. Make it a list of tuples, e.g. `[(554862122, 55110385224, 'PR 26', 2), (5242699687, 55110385289, 'CO 109', 6), ...]`.

http://stackoverflow.com/comment/90386124
type: QuestionComment
comment on: http://stackoverflow.com/q/51711860
has text: I have added the image of previous project and also the code of current project runserver. please let me know if you need more information
score: 0
type: Comment

http://stackoverflow.com/q/51739195
has answer: http://stackoverflow.com/a/51793036
tagged with: git
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90438737
has comment: http://stackoverflow.com/comment/90438570
type: Question
has comment: http://stackoverflow.com/comment/90438593
tagged with: gitlab-ci-runner
tagged with: gitlab-ci
has title: How can I get GitLab CI/CD jobs to push to external repositories?
has body: I've been having issues getting Gitlab CI/CD to push new changes to the current repository. Apparently, this can not be done as of now. So now, I am attempting to see if it can push to other repositories. This is what I'm trying to do: Clone another repo into mine let's call mine Router) let's call the other Rinner) Modify Rinner in some way Commit and Push only the changes to Rinner Then remove Rinner from Router I'm trying to test this out in Python, and currently have this: os.system('mkdir temp'); os.chdir('temp'); os.system('git clone git@gitlab.com/path/Rinner.git'); os.chdir('Rinner'); os.system('echo "Hello World!" &gt; hello.txt'); os.system('git add -A'); os.system('git commit -m "Running a test..."'); os.system('git push --force'); os.chdir('..'); os.chdir('..'); os.system('rm -rf temp'); On my local machine, it works perfect fine. On my GitLab CI/CD job, I get the following result. Cloning into 'Rinner'... Host key verification failed. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. How can I go about getting past this when it operates on GitLab CI/CD?
has comment: http://stackoverflow.com/comment/90438882
has comment: http://stackoverflow.com/comment/90438765
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90438773
tagged with: gitlab
has comment: http://stackoverflow.com/comment/90438790
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51744571
has comment: http://stackoverflow.com/comment/90449060
has answer: http://stackoverflow.com/a/51744892
accepted answer: http://stackoverflow.com/a/51744892
has comment: http://stackoverflow.com/comment/90449866
downvote count: 5
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90448952
favorite count: 0
has comment: http://stackoverflow.com/comment/90448928
has title: Missing something in import statement?
tagged with: python
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/90449814
has body: What exactly am I missing there? The path is: "projectname" -> django-project -> xyz_core- > management -> commands -> mail_handling.py and my import statement says: from xyz_core.management.commands import mail_handling but it still gives me an error that it's unresolved and unused (unused definitely not true). ErrorMessage: Unused import statement Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items. Unresolved reference 'management' Inspection info: This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items Solution: from xyz_core.management.commands.mail_handling import *
type: Question

http://stackoverflow.com/a/51766436
answers question: http://stackoverflow.com/q/51765983
has body: This returns the dataframe with the columns removed df.drop(list(df)[2:5], axis=1)
downvote count: 0
type: Answer
score: 11
upvote count: 11

http://stackoverflow.com/comment/90594578
type: Comment
comment on: http://stackoverflow.com/q/51794274
type: QuestionComment
has text: @NilsWerner Thanks for the comment and sorry if my post it not clear enough. I tried my best to be as clear as possible. If you help me know which part is missing or what is not clear I will edit the post.
score: 0

http://stackoverflow.com/a/51760164
has body: The page seems to blocklist Tor Ip addressees, so we can circumvent this by going through another site, e.g. W3 validator, that is showing source to us: https://validator.w3.org/nu/?showsource=yes&amp;doc=https%3A%2F%2Fwww.totallylegal.com%2Fsearchjobs%2F We're still using TOR, but letting other site to fetch the site for us (and their IP isn't blocked): from bs4 import BeautifulSoup import requests proxies = { 'http': 'http://&lt;YOUR PROXY ADDRESS&gt;:&lt;YOUR PROXY PORT&gt;', 'https': 'http://&lt;YOUR PROXY ADDRESS&gt;:&lt;YOUR PROXY PORT&gt;', } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36', 'accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } r = requests.get('https://validator.w3.org/nu/?showsource=yes&amp;doc=https%3A%2F%2Fwww.totallylegal.com%2Fsearchjobs%2F', proxies=proxies, headers=headers) soup = BeautifulSoup(r.text, 'lxml') source_code = '' for code in soup.select('ol.source &gt; li &gt; code'): if 'class' in code.attrs and 'lf' in code.attrs['class']: source_code += '\n' else: source_code += code.text soup2 = BeautifulSoup(source_code, 'lxml') for li in soup2.select('li.lister__item h3'): print(li.text) print('-' * 80) Prints: Corporate Partner -------------------------------------------------------------------------------- Personal Injury Paralegal -------------------------------------------------------------------------------- Healthcare Regulatory Lawyer - London -------------------------------------------------------------------------------- Company Secretary and Corporate Governance -------------------------------------------------------------------------------- Junior FCPA/Compliance Associate, Beijing - 14612/TTL -------------------------------------------------------------------------------- International Project Manager, Shanghai - 14611/TTL ----------------------------------------------------------…
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51757608
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90480066
answers question: http://stackoverflow.com/q/51757608

http://stackoverflow.com/comment/90490565
comment on: http://stackoverflow.com/a/51749952
has text: also, removing the first item has a hit since the remaining items need to be shifted in memory afaik (though that's pretty efficient actually)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51697936
has body: You might want to consider writing your own generator (making use of Keras' Sequence object to allow for multiprocessing) instead of modifying the ImageDataGenerator code. From the Keras docs: class CIFAR10Sequence(Sequence): def __init__(self, x_set, y_set, batch_size): self.x, self.y = x_set, y_set self.batch_size = batch_size def __len__(self): return int(np.ceil(len(self.x) / float(self.batch_size))) def __getitem__(self, idx): batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size] batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size] return np.array([ resize(imread(file_name), (200, 200)) for file_name in batch_x]), np.array(batch_y) You could have your labels, paths to the images, and paths to the text files in a single pandas dataframe and modify the __getitem__ method from above to have your generator yield all three of them simultaneously: one list of numpy arraysX which contains all the inputs, one numpy array Y which contains the outputs.
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90357269
score: 2
answers question: http://stackoverflow.com/q/51697695

http://stackoverflow.com/comment/90340131
type: AnswerComment
has text: Can you post expected output?
type: Comment
comment on: http://stackoverflow.com/a/51688754
score: 0

http://stackoverflow.com/comment/90424823
has text: You're missing a parentheses at the end of your 3rd line.
comment on: http://stackoverflow.com/q/51731972
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90527203
comment on: http://stackoverflow.com/a/51783672
type: AnswerComment
type: Comment
score: 0
has text: Amazing ! Thanks a lot ImportanceOfBeingErnest ! Exactly what I was looking for !

http://stackoverflow.com/q/51698186
tagged with: arrays
downvote count: 0
has title: how to convert a binary numpy array to decimal?
duplicate of: http://stackoverflow.com/q/15505514
favorite count: 0
tagged with: python
has body: I want to convert binary numpy array to decimal. Is there a similar function to this numpy.binary_repr that works the other way around? x = array([ 1., 1., 0., 1., 0., 0., 0., 1., 0.]) I know I can do this: int("110100010",2) = 418 But here I need to extract the elements of the array and put them into string? Is there an easier way? if not, then how can I extract the elements of the array and create a string out of them?
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/15505514
has answer: http://stackoverflow.com/a/51698201
answer count: 1

http://stackoverflow.com/comment/90279365
comment on: http://stackoverflow.com/q/51654924
type: Comment
type: QuestionComment
has text: But something has to call the view. If you don't have a URL pointing at it, then nothing will call it.
score: 0

http://stackoverflow.com/comment/128382512
type: Comment
has text: in one line, to get just the correlations, it's `df.values[np.triu_indices(len(df), 1)]`. this assumes `df` is a square dataframe of correlations. see my answer below.
comment on: http://stackoverflow.com/q/51774479
score: 0
type: QuestionComment

http://stackoverflow.com/q/51652567
has title: Union more than two table in sql through Python.
has comment: http://stackoverflow.com/comment/90268582
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51654525
has body: I am trying to perform union over more than two tables using following query but I am getting syntax error. "CREATE TABLE IF NOT EXISTS Xi(SELECT * FROM X UNION SELECT * FROM Y UNION SELECT * FROM Z UNION SELECT * FROM W)" I have also tried Insert but still getting some error. Can someone please help me resolve this problem?
linked to: http://stackoverflow.com/q/44007310
type: UnansweredQuestion
tagged with: phpmyadmin
tagged with: python
linked to: http://stackoverflow.com/q/11882610
tagged with: mysql
type: Question

http://stackoverflow.com/a/51644798
score: 1
upvote count: 1
has body: Since the csvfile is a _io.TextIOWrapper object, you have to use .read() method instead of getvalue() as, def send_results_by_email(to, filename=FILENAME): """Send an email with the NPS data attached""" with open(filename, 'r') as csvfile: now = datetime.now().strftime("%m-%d-%Y %H:%M") email_message = EmailMessage( subject=f"NPS data (collected {now})", body=f"Script run with the following settings module: '{settings.SETTINGS_MODULE}'", to=to, attachments=[('nps.csv', csvfile.read(), 'text/csv')]) email_message.send() print(f"Email sent to {to}!")
answers question: http://stackoverflow.com/q/51644454
downvote count: 0
type: Answer

http://stackoverflow.com/a/51670122
score: 1
accepted answer of: http://stackoverflow.com/q/51669962
upvote count: 1
has body: You can use the fuzzywuzzy module to calculate the fuzzy score between two items on the same row and then iterate over the rows. Or if your dataset is very long this could probably be vectorized. The link below got me going with fuzzywuzzy last week: https://marcobonzanini.com/2015/02/25/fuzzy-string-matching-in-python/
answers question: http://stackoverflow.com/q/51669962
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51708902
tagged with: tensorflow
type: Question
has body: I'm working with 4 dimensional tensors and need to do a couple of calculations that work like the following example. Take A to be a tensor with shape (6,64,64,64). I want to use the function tf.where to obtain the voxels of each (64,64,64) volume that has a value larger than 0.75. The only way I have managed to do this is like this: X = tf.convert_to_tensor([tf.where(A[i,:,:,:] &gt; 0.75) for i in range(A.shape[0])] This seems to be a very crude solution. Is there a better way to achieve this?
has title: Correct way to vectorise tensorflow step
score: 1
has answer: http://stackoverflow.com/a/51710562
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90380840
tagged with: python
accepted answer: http://stackoverflow.com/a/51710562
type: AnsweredQuestion
tagged with: python-3.x
tagged with: tensor
upvote count: 1
tagged with: vectorization

http://stackoverflow.com/comment/90475029
score: 0
has text: the href values appear to be links to pages that show each video
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51756925

http://stackoverflow.com/comment/90358602
type: Comment
type: QuestionComment
has text: @bobblebubble that works! If you post it as an answer i will accept it. Could you give me some hints on how you it works - especially the first part of the regex looks quite strange to me :)
comment on: http://stackoverflow.com/q/51697213
score: 0

http://stackoverflow.com/a/51778770
type: Answer
answers question: http://stackoverflow.com/q/51772115
has comment: http://stackoverflow.com/comment/90544854
has comment: http://stackoverflow.com/comment/90544862
has comment: http://stackoverflow.com/comment/90545118
has body: Pressing enter after entering the code should be sufficient. What is the problem you encounter? (After you enter the code, you'll need to execute additional code to access Drive as described in the linked article.) !mkdir -p drive !google-drive-ocamlfuse drive
has comment: http://stackoverflow.com/comment/90544808
has comment: http://stackoverflow.com/comment/90539547
score: 0
has comment: http://stackoverflow.com/comment/90541000

http://stackoverflow.com/comment/90527991
score: 0
type: Comment
type: QuestionComment
has text: It's for the `run` command, for testing purposes I'd remove all `pip install` commands from the Dockerfile and I'd try to test it inside a container by running commands manually.
comment on: http://stackoverflow.com/q/51784475

http://stackoverflow.com/q/51774605
has comment: http://stackoverflow.com/comment/90507905
has title: Creating Matrix(array) where each element itself is a matrix
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90508010
downvote count: 0
has body: I have four mxn matrices. From those matrices I want to create a mxn matrix of matrices such that each element of new matrix would be a 2x2 matrix taking respective elements from each matrix. So far I can think of stacking all four matrices and then reshape each element along z axis and replace it. I believe there is more elegant solution to this. Sample input: $$ \begin{bmatrix} A_{11} &amp; A_{12}\\ A_{21} &amp; A_{22} \end{bmatrix} , \begin{bmatrix} B_{11} &amp; B_{12}\\ B_{21} &amp; B_{22} \end{bmatrix} , \begin{bmatrix} C_{11} &amp; C_{12}\\ C_{21} &amp; C_{22} \end{bmatrix} , \begin{bmatrix} D_{11} &amp; D_{12}\\ D_{21} &amp; D_{22} \end{bmatrix} $$ Expected output: $$ \begin{bmatrix} \begin{bmatrix} A_{11} &amp; B_{11}\\ C_{11} &amp; D_{11} \end{bmatrix} &amp; \begin{bmatrix} A_{12} &amp; B_{12}\\ C_{12} &amp; D_{12} \end{bmatrix}\\ \begin{bmatrix} A_{21} &amp; B_{21}\\ C_{21} &amp; D_{21} \end{bmatrix} &amp; \begin{bmatrix} A_{22} &amp; B_{12}\\ C_{22} &amp; D_{22} \end{bmatrix} \end{bmatrix $$
has comment: http://stackoverflow.com/comment/90507956
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51775558
has comment: http://stackoverflow.com/comment/90508137
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51775558
upvote count: 1
possible better answer: http://stackoverflow.com/a/51774903
type: Question
has answer: http://stackoverflow.com/a/51774903

http://stackoverflow.com/comment/90315216
has text: After I use `text.translate(string.punctuation)` it seems to turn my `\n`s into `+`s
comment on: http://stackoverflow.com/q/51676027
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51704247
answer count: 1
tagged with: tensorflow
tagged with: loaddata
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has body: I am trying to load a .txt file on a non GPU machine. The .txt file was dumped on a GPU machine: with open("Data/all_rewards.txt", "wb") as f: pickle.dump(all_rewards, f) The file contains just text data, no network models or anything else. On a GPU machine, I have no trouble loading the data: with open("all_rewards.txt", 'rb') as f: losses = pickle.load(f) On a non GPU machine however, I get the error: AssertionError('Torch not compiled with CUDA enabled',) Since Torch uses pickle too to load models, I have tried to load the data with : losses = torch.load("all_rewards.txt", map_location='cpu') but that didn´t work. Could you help me plaese? EDIT: Somehow this problem solved itself magically. I have reinstalled pickle, which did not solve the problem initially but now it works...
has title: Load .txt file with pickle on non GPU machine
tagged with: pytorch
has answer: http://stackoverflow.com/a/51704404
has comment: http://stackoverflow.com/comment/136765370
tagged with: pickle
upvote count: 1

http://stackoverflow.com/comment/90482445
has text: so it return `DatetimeIndex` from `read_csv`
type: AnswerComment
comment on: http://stackoverflow.com/a/51761265
score: 0
type: Comment

http://stackoverflow.com/a/51720858
has comment: http://stackoverflow.com/comment/90416403
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/137272014
has body: Use any &gt;&gt;&gt; s = pd.Series([1,5,3,-1,7]) &gt;&gt;&gt; any(s&lt;0) True
has comment: http://stackoverflow.com/comment/90417975
type: Answer
has comment: http://stackoverflow.com/comment/90402386
score: 19
downvote count: 0
has comment: http://stackoverflow.com/comment/90417687
answers question: http://stackoverflow.com/q/51720780
upvote count: 19
accepted answer of: http://stackoverflow.com/q/51720780

http://stackoverflow.com/a/75705599
has body: I got many attempt for ModuleNotFoundError: No Module named **** when i wanna use dirsearch I solved it with: sudo pip3 install dirsearch Collecting dirsearch Downloading dirsearch-0.4.3.post1-py3-none-any.whl (139 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.0/140.0 kB 3.4 MB/s eta 0:00:00 Collecting Jinja2&gt;=3.0.0 Downloading Jinja2-3.1.2-py3-none-any.whl (133 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 133.1/133.1 kB 14.6 MB/s eta 0:00:00 Collecting PySocks&gt;=1.7.1 Downloading PySocks-1.7.1-py3-none-any.whl (16 kB) Collecting beautifulsoup4&gt;=4.8.0 Downloading beautifulsoup4-4.11.2-py3-none-any.whl (129 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 129.4/129.4 kB 6.8 MB/s eta 0:00:00 Requirement already satisfied: certifi&gt;=2017.4.17 in ./.pyenv/versions/3.11.2/lib/python3.11/site-packages (from dirsearch) (2022.12.7) Requirement already satisfied: cffi&gt;=1.14.0 in ./.pyenv/versions/3.11.2/lib/python3.11/site-packages (from dirsearch) (1.15.1) Requirement already satisfied: chardet&gt;=3.0.2 in ./.pyenv/versions/3.11.2/lib/python3.11/site-packages (from dirsearch) (5.1.0) Collecting charset-normalizer~=2.0.0 Downloading charset_normalizer-2.0.12-py3-none-any.whl (39 kB) Collecting colorama&gt;=0.4.4 Using cached colorama-0.4.6-py2.py3-none-any.whl (25 kB) Requirement already satisfied: cryptography&gt;=2.8 in ./.pyenv/versions/3.11.2/lib/python3.11/site-packages (from dirsearch) (39.0.2) Collecting defusedxml&gt;=0.7.0 Downloading defusedxml-0.7.1-py2.py3-none-any.whl (25 kB) Requirement already satisfied: idna&gt;=2.5 in ./.pyenv/versions/3.11.2/lib/python3.11/site-packages (from dirsearch) (3.4) Collecting markupsafe&gt;=2.0.0 Downloading MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (27 kB) Collecting ntlm-auth&gt;=1.5.0 Downloading ntlm_auth-1.5.0-py2.py3-none-any.whl (29 kB) Collecting pyopenssl&gt;=21.0.0 Downloading pyOpenSSL-23.0.0-py3-none-any.whl (57 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 57.3/57.3 kB 18…
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51775462
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/51652584
has comment: http://stackoverflow.com/comment/90268788
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90268789
has comment: http://stackoverflow.com/comment/90270546
has comment: http://stackoverflow.com/comment/90271384
has body: This fragment of code raises errors. while True: data = s.recv(1024) js = json.loads(data) print js &gt; Traceback (most recent call last): File "test.py", line 10, in &lt;module&gt; js = json.loads(data) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 367, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 9 column 3 - line 9 column 4 (char 303 - 304) Here is the json: {"B49":{ "Time":1533208501.720, "PacketID":2358, "Loss":0, "RSSI":-57, "*****":[50.4,49.8,49.8,51,51.7,49.1,49.8,49.8,50.1,48.5], "*****":[-10.1,-9.8,-9.8,-7.9,-11.4,-9.2,-9.8,-10.1,-9.5,-9.2], "*****":[-23.6,-21.2,-21.3,-20.9,-20.5,-22.4,-23.8,-23.4,-21.5,-23.9] }} I don't understand because when I try type(data) I get type&lt;str&gt; which means that I am passing a string argument as this method requires.
type: UnansweredQuestion
has title: json.loads raises two errors
tagged with: python
has answer: http://stackoverflow.com/a/51653684
has comment: http://stackoverflow.com/comment/90268455
type: Question
has answer: http://stackoverflow.com/a/51668090
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/51778068
score: 1
answers question: http://stackoverflow.com/q/51777914
has body: No for loop or list comprehension required. Use diff Input: from io import StringIO import pandas as pd import numpy as np df = pd.read_table(StringIO("""vehicle, timestamp, mode x,1970-01-19 01:24:59.973, 0 x,1970-01-19 01:25:59.973, 2 x,1970-01-19 01:26:59.973, 2 x,1970-01-19 01:27:59.973, 0 x,1970-01-19 01:28:59.973, 2 x,1970-01-19 01:29:59.973, 0 x,1970-01-19 01:30:59.973, 0 x,1970-01-19 01:31:59.973, 2 x,1970-01-19 01:32:59.973, 0""".replace(', ', ',')), sep=',', engine='python') Adding new column 'changes' and fill with 1 when diff is -2: df.loc[(df['mode'].diff() == -2) &amp; (df['mode'] == 0), 'changes'] = 1 Output: vehicle timestamp mode changes 0 x 1970-01-19 01:24:59.973 0 NaN 1 x 1970-01-19 01:25:59.973 2 NaN 2 x 1970-01-19 01:26:59.973 2 NaN 3 x 1970-01-19 01:27:59.973 0 1.0 4 x 1970-01-19 01:28:59.973 2 NaN 5 x 1970-01-19 01:29:59.973 0 1.0 6 x 1970-01-19 01:30:59.973 0 NaN 7 x 1970-01-19 01:31:59.973 2 NaN 8 x 1970-01-19 01:32:59.973 0 1.0
has comment: http://stackoverflow.com/comment/90514880
downvote count: 0
has comment: http://stackoverflow.com/comment/90515003
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90319947
score: 0
has text: can anyone give me an example of using argparse instead?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51643262

http://stackoverflow.com/q/51771588
has answer: http://stackoverflow.com/a/51771620
favorite count: 0
tagged with: python-3.x
upvote count: 1
has comment: http://stackoverflow.com/comment/90502079
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51771620
type: Question
downvote count: 0
tagged with: python-2.7
has body: I have a directory with pictures that have names like this: v1-001.png v1-002.png ..... I want of list the names in order (V1--001 V1-002 V1--003 V1--004) but I have this v1--00900 v1--002 v1--0034 V1--0020 V1--001 this is my code: import os path="." for current_dir, dir_names, file_names in os.walk(path): for file_name in file_names: in_file = os.path.join(current_dir, file_name) print(in_file)
answer count: 1
has title: Get names in a directory in order in python
tagged with: python

http://stackoverflow.com/q/51685285
score: -1
answer count: 2
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/90332705
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51685620
tagged with: python
has title: how to find a row value which contains every possible values of another column in pandas
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/51685685
possible better answer: http://stackoverflow.com/a/51685620
has body: Let's say I have a pandas DataFrame with IDs, months and statuses. There are several rows for each ID, each representing a month and the status in the given month. I want to find the IDs which have all the possible statuses. How do I do this? import pandas as pd df=pd.DataFrame({'ID':[11, 11, 12, 12], 'Month':[1, 2, 1, 2], 'Status':['a', 'a', 'a', 'b']}) print(df) ID Month Status 0 11 1 a 1 11 2 a 2 12 1 a 3 12 2 b I wish to find the code that outputs 12, since that is the ID that contains all possible status values ('a' and 'b' in this case)
type: Question
has answer: http://stackoverflow.com/a/51685685

http://stackoverflow.com/comment/90414094
type: Comment
has text: it works.... :)
comment on: http://stackoverflow.com/a/51726920
score: 0
type: AnswerComment

http://stackoverflow.com/q/51704517
has body: Prerequisite This is a question derived from this post. So, some of the introduction of the problem will be similar to that post. Problem Let's say result is a 2D array and values is a 1D array. values holds some values associated with each element in result. The mapping of an element in values to result is stored in x_mapping and y_mapping. A position in result can be associated with different values. Now, I have to find the minimum and maximum of the values grouped by associations. An example for better clarification. min_result array: [[0, 0], [0, 0], [0, 0], [0, 0]] max_result array: [[0, 0], [0, 0], [0, 0], [0, 0]] values array: [ 1., 2., 3., 4., 5., 6., 7., 8.] Note: Here result arrays and values have the same number of elements. But it might not be the case. There is no relation between the sizes at all. x_mapping and y_mapping have mappings from 1D values to 2D result(both min and max). The sizes of x_mapping, y_mapping and values will be the same. x_mapping - [0, 1, 0, 0, 0, 0, 0, 0] y_mapping - [0, 3, 2, 2, 0, 3, 2, 1] Here, 1st value(values[0]) and 5th value(values[4]) have x as 0 and y as 0(x_mapping[0] and y_mappping[0]) and hence associated with result[0, 0]. If we compute the minimum and maximum from this group, we will have 1 and 5 as results respectively. So, min_result[0, 0] will have 1 and max_result[0, 0] will have 5. Note that if there is no association at all then the default value for result will be zero. Current working solution x_mapping = np.array([0, 1, 0, 0, 0, 0, 0, 0]) y_mapping = np.array([0, 3, 2, 2, 0, 3, 2, 1]) values = np.array([ 1., 2., 3., 4., 5., 6., 7., 8.], dtype=np.float32) max_result = np.zeros([4, 2], dtype=np.float32) min_result = np.zeros([4, 2], dtype=np.float32) min_result[-y_mapping, x_mapping] = values # randomly initialising from values for i in range(values.size): x = x_mapping[i] y = y_mapping[i] # maximum if values[i] &gt; max_result[-y, x]: max_result[-y, x] = values[i] # minimum if values[i] &lt; min_result[-y, …
upvote count: 3
tagged with: python
downvote count: 0
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51704831
accepted answer: http://stackoverflow.com/a/51704831
has title: Numpy: Finding minimum and maximum values from associations through binning
linked to: http://stackoverflow.com/q/53513497
tagged with: numpy
tagged with: array-broadcasting
answer count: 1
tagged with: numpy-ufunc
favorite count: 0
linked to: http://stackoverflow.com/q/51691980

http://stackoverflow.com/comment/90376419
type: Comment
type: QuestionComment
has text: @UCProgrammer see my answer for my ideas. Also, environment variables usually work better as separate single values that you connect inside your context.
comment on: http://stackoverflow.com/q/51706855
score: 0

http://stackoverflow.com/comment/90506073
has text: @SagarDawda running pip -V returns `pip 18.0 from /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip (python 2.7)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51768009

http://stackoverflow.com/q/51689455
type: Question
answer count: 1
tagged with: python-3.x
score: 0
type: UnansweredQuestion
tagged with: cartesian-product
tagged with: output
tagged with: python
has body: I need to create a Cartesian product with user input. I have done that but the out put needs to have commas. I am just having a hard time getting that. So if you input 1,2 in ListA and 3,4 in ListB the outcome should be (1,3), (1,4), (2,3), (2,4). Currently the output is as follows. ['1,3', '1,4', '2,3', '2,4']. I am sure I am missing something very simple, I just keep missing it. Thank you for any insight. ListA = input("Enter up to 10 numbers seperated by commas:") numbers = list(map(str, ListA.split(","))) print(ListA) ListB = input("Enter up to 10 numbers seperated by commas:") numbers = list(map(str, ListB.split(","))) print(ListB) import itertools AxB = [] for i in itertools.product(ListA.split(","), ListB.split(",")): AxB.append(",".join(map(str, i))) print(AxB)
has title: Creating commas around my product output
has answer: http://stackoverflow.com/a/51689482

http://stackoverflow.com/comment/90534517
type: QuestionComment
score: 0
has text: You could dynamically put together a list or an array and use that for slicing.
comment on: http://stackoverflow.com/q/51788492
type: Comment

http://stackoverflow.com/comment/121114214
comment on: http://stackoverflow.com/a/51703667
has text: @jezrael how can I use a condition for the update? For example, I want to update the row if the col B = 8 or 9.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51732176
has body: Use BorderImage and change the source. There is no attribute, background_color for ProgressBar. It uses BorderImages. The first BorderImage (e.g. blue.png) acts as a rail/track whereby the second BorderImage (e.g. red.png) runs on the rail/track. test.kv #:kivy 1.11.0 &lt;Rootwidget&gt;: ProgressBar: id: pb max: 1000 canvas: BorderImage: border: (12, 12, 12, 12) pos: self.x, self.center_y - 12 size: self.width, 24 source: 'blue.png' BorderImage: border: [int(min(self.width * (self.value / float(self.max)) if self.max else 0, 12))] * 4 pos: self.x, self.center_y - 12 size: self.width * (self.value / float(self.max)) if self.max else 0, 24 source: 'red.png' Output
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51719374
accepted answer of: http://stackoverflow.com/q/51719374
type: Answer
has comment: http://stackoverflow.com/comment/90458811
has comment: http://stackoverflow.com/comment/90437273
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/comment/90535465
type: AnswerComment
type: Comment
has text: No libraries, no built-in functions. Read the question carefully. I'm aware of the Counter.
score: 0
comment on: http://stackoverflow.com/a/51789051

http://stackoverflow.com/comment/90276498
type: Comment
type: QuestionComment
has text: Do you also want the remove the equals sign?
score: 0
comment on: http://stackoverflow.com/q/51656394

multilabel-classification
tags question: http://stackoverflow.com/q/51715587
tag name: multilabel-classification
type: Tag

http://stackoverflow.com/q/51676219
accepted answer: http://stackoverflow.com/a/51676285
type: Question
has body: I'm trying to sort an array by another array that has matching indexes but in a different order. In: array1 Out: array([123, 323, 142, 532, 563, 256]) In: array2 Out: array([323, 563, 256, 142, 123, 532]) I'm not sure what to do to make array2 get reordered to be in the same order as array1. So I would like for the end product to look like this: In: array1 Out: array([123, 323, 142, 532, 563, 256]) In: array2 Out: array([123, 323, 142, 532, 563, 256]) Any help is much appreciated!
answer count: 1
downvote count: 1
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/51676285
has title: Sort numpy array by order of matching values of another array
tagged with: python
upvote count: 0
type: AnsweredQuestion
score: -1

http://stackoverflow.com/comment/90332342
has text: The `tf.get_variable` or `tf.Variable` call you're using inside the 2 `tf.variable_scope`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51685126
score: 0

http://stackoverflow.com/a/51699563
accepted answer of: http://stackoverflow.com/q/51699527
has comment: http://stackoverflow.com/comment/90360677
answers question: http://stackoverflow.com/q/51699527
type: Answer
upvote count: 2
downvote count: 2
score: 0
has body: The following expression will do (since 30 is 6 and 10's lowest common denominator): [n for n in range(1, 301) if n % 30 == 0]
type: AcceptedAnswer

http://stackoverflow.com/a/51713921
has body: Someone asked the same question a while ago: Pretty Printing a pandas dataframe I will suggest you, to take a look on the last answer and also just try in your tabulate function: tablefmt='psql'
answers question: http://stackoverflow.com/q/51713702
score: 0
type: Answer

http://stackoverflow.com/comment/90423434
comment on: http://stackoverflow.com/a/51730471
type: Comment
has text: See above - current code and traceback added to original question.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51719075
has title: Logging format for Flask on PythonAnywhere
tagged with: pythonanywhere
favorite count: 0
has comment: http://stackoverflow.com/comment/90410057
tagged with: python
upvote count: 4
tagged with: logging
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51729211
accepted answer: http://stackoverflow.com/a/51729211
type: Question
tagged with: wsgi
score: 4
tagged with: flask
has body: I'm running a Flask web app on PythonAnywhere. The access logs xyz.pythonanywhere.com.access.log have the format: 12.34.167.189 - - [07/Aug/2018:04:33:46 +0000] "GET /foo/bar?id=abc HTTP/1.1" 200 117942 "-" "-" "12.34.167.189" response-time=0.041 I'm trying to get rid of the IPs. All approaches modifying or overriding the logger didn't work. The following lines successfully effect the logging on my local machine: import logging from werkzeug.serving import WSGIRequestHandler logger = logging.getLogger('werkzeug') WSGIRequestHandler.log = lambda self, type, msg, *args: getattr(logger, type)(msg % args) On PythonAnywhere, however, Flask is started differently from /var/www/xyz_pythonanywhere_com_wsgi.py. The logging format didn't change. So, how can I configure the WSGI logging?
answer count: 1

http://stackoverflow.com/a/51768605
has body: Problem is groupby.apply return DataFrame, not DataFrameGroupBy object: grouped = df.loc[~exact_rows].groupby('id').apply( lambda g: g.sort_values('date', ascending=True)) print (grouped) type id date code id 8242 2 fuzzy 8242 2017-11-01 122 3 fuzzy 8242 2017-11-01 122 So solution for sorting values per groups is use DataFrame.sort_values by 2 columns before groupby('id'): exact_rows = df['type'] != 'fuzzy' grouped = df.loc[~exact_rows].sort_values(['id','date'], ascending=True).groupby('id') a = np.where(grouped['code'].transform('nunique') == 1, 20, 0) print (a) [20 20]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51768543
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51768543
type: AcceptedAnswer

http://stackoverflow.com/comment/90446646
type: QuestionComment
comment on: http://stackoverflow.com/q/51739531
type: Comment
has text: Updated P0_T :)
score: 0

http://stackoverflow.com/q/51781019
accepted answer: http://stackoverflow.com/a/51781121
type: Question
has comment: http://stackoverflow.com/comment/90520832
has body: I have following pandas dataframe with date column as object ID Date Volume 0 13-02-2018 00:06 85 1 13-02-2018 00:10 70 2 13-02-2018 00:11 100 3 2018-02-13 06:30 123 4 02-13-2018 07:56 100 I want to convert it to following one format ID Date Volume 0 2018-02-13 00:06 85 1 2018-02-13 00:10 70 2 2018-02-13 00:11 100 3 2018-02-13 06:30 123 4 2018-02-13 07:56 100 I am trying to achieve this by following command df['Date'] = df.date.apply(lambda x: pd.to_datetime(x).strftime('%Y-%m-%d %H:%M')[0]) But it throws an error. How can I do it in pandas?
has comment: http://stackoverflow.com/comment/90520639
answer count: 2
tagged with: pandas
downvote count: 0
has title: how to convert multiple date formats in one format in pandas
has comment: http://stackoverflow.com/comment/90519794
favorite count: 0
has answer: http://stackoverflow.com/a/51781121
has comment: http://stackoverflow.com/comment/90520414
has comment: http://stackoverflow.com/comment/90519952
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51781377
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90519992
score: 6
has comment: http://stackoverflow.com/comment/90520460
possible better answer: http://stackoverflow.com/a/51781377

http://stackoverflow.com/comment/90470324
type: AnswerComment
score: 0
type: Comment
has text: printing is not returning. The code executes but data doesn't go upstream to the caller. But it's not possible that adding a print makes the code fail... unless tests are scanning standard output.
comment on: http://stackoverflow.com/a/51754993

http://stackoverflow.com/q/51745678
favorite count: 0
has answer: http://stackoverflow.com/a/51746007
accepted answer: http://stackoverflow.com/a/51745781
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: list
downvote count: 2
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51745781
tagged with: sorting
has title: How do I sort this array in Python?
answer count: 3
possible better answer: http://stackoverflow.com/a/51745817
has body: I have this array: [14, 'S', 12, 'D', 8, 'S', 9, 'S', 10, 'D'] I want to sort it in descending order (numbers), but at the same time keep the number with the following letter together. So the result should look like this: [14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S'] How can I do this? I tried to do it this way (five_cards_num is the name of the array): for j in range(4): max = five_cards_num[j] max_color = five_cards_num[j+1] for i in range(j, 5): if (five_cards_num[2*i] &gt; max): max = five_cards_num[2*i] max_color = five_cards_num[2*i+1] five_cards_num[2*i] = five_cards_num[j] five_cards_num[2*i+1] = five_cards_num[j+1] five_cards_num[j] = max five_cards_num[j+1] = max_color But I get error: TypeError: '>' not supported between instances of 'int' and 'str' Thank you in advance.
tagged with: arrays
has answer: http://stackoverflow.com/a/51745817

http://stackoverflow.com/q/51726307
tagged with: python-3.x
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/24768222
has body: I have several photos of documents and I need to determine whether the documents have been changed. So this task consist of two parts: 1. Text shifting. Detect that special text was shifted: Pay attention to inscription: TEST TEXT HERE has a gap (at the S letter). And the second task: similar shift of the background image like this: MY QUESTION: are some methods to detect the same shifts? They can be horizontal and vertical. I always know the test inscription (in the first task) and I always have ornament sample in good quality. And I have a set of photos which I need to check. My workaround. 1. First idea: superimpose correct inscription at each photo and check pixels colours around it - if there are a lot of red pixels, there is a shift. So I can go for text but can't for image. 2. About image I thought about Fourier Transformations. If there is a gap at the image there is function jump at the same coordinate. But I don't know some realizations of this method. First of all I know, that this type of questions is too broad for SO. How to detect a shift between images But I found similar already, so hope it will not be closed! Second remark - I'm opened for any algorithms - both classical and machine learning.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90443180
has answer: http://stackoverflow.com/a/51742217
accepted answer: http://stackoverflow.com/a/51742217
has comment: http://stackoverflow.com/comment/90413159
has title: How to detect that PART of an image was shifted?
tagged with: image-processing
has comment: http://stackoverflow.com/comment/90439537
type: Question
score: 0
answer count: 1
tagged with: edge-detection

http://stackoverflow.com/a/51738869
score: 0
accepted answer of: http://stackoverflow.com/q/51738699
answers question: http://stackoverflow.com/q/51738699
type: Answer
upvote count: 1
has body: &gt;&gt;&gt; def solution(lst): ... dex = len(lst) - 1 ... while dex &gt;= 0: ... yield lst[dex] ... dex -= 1 ... &gt;&gt;&gt; nums = solution([1, 2, 3, 4]) &gt;&gt;&gt; next(nums) 4 &gt;&gt;&gt; next(nums) 3 &gt;&gt;&gt; next(nums) 2 &gt;&gt;&gt; next(nums) 1 &gt;&gt;&gt; next(nums) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; StopIteration
downvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90481069
comment on: http://stackoverflow.com/q/51751223
score: 0
type: Comment
type: QuestionComment
has text: @holger thanks for your comment, I'm asking for a direct comparison between pipsi and gem, not a recommendation, is there an error in my ruby terminology? it sounds like the answer to my question is simply "no" (but the hint about a possible solution is welcome )

http://stackoverflow.com/comment/90545072
type: AnswerComment
has text: Makes sense. It's a good answer.
type: Comment
comment on: http://stackoverflow.com/a/51793645
score: 0

http://stackoverflow.com/q/51756108
upvote count: 2
has comment: http://stackoverflow.com/comment/93819077
tagged with: machine-learning
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/90503401
answer count: 3
possible better answer: http://stackoverflow.com/a/54618526
has answer: http://stackoverflow.com/a/51756370
downvote count: 1
has answer: http://stackoverflow.com/a/54618526
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90476893
has body: I was trying to run a machine learning code based on Keras/TensorFlow. When running in tensorflow environment, I encounter the following error: from keras_applications.mobilenet import relu6 ImportError: cannot import name 'relu6' How can I solve it?
has title: ImportError: cannot import name 'relu6'
tagged with: keras
has answer: http://stackoverflow.com/a/67070235
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51756370
score: 1
favorite count: 0

http://stackoverflow.com/comment/90352627
score: 1
comment on: http://stackoverflow.com/q/51695477
has text: Try to put some print statements in your code to see what exactly is None
type: Comment
type: QuestionComment

gmail
type: Tag
tags question: http://stackoverflow.com/q/51767566
tags question: http://stackoverflow.com/q/51756066
tags question: http://stackoverflow.com/q/51644769
tags question: http://stackoverflow.com/q/51760850
tag name: gmail

http://stackoverflow.com/q/51789012
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90536885
favorite count: 0
has title: Translate md5 hash generator in python into R
tagged with: hash
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: md5
has body: I am trying to use private APIs of Cryptopia. In order to use private API, Base64 encoded MD5 hash of the post parameters is needed. I found a python code from https://github.com/thebotguys/cryptopia-api-python/blob/master/cryptopia_api.py While translating the code into R, the md5 hash generator got me in trouble. The hash results from python and R are different. Please fill me in how to fix. Python: post_parameters = {'Currency': 'BTC'} post_data = json.dumps(post_parameters) md5 = hashlib.md5() jsonparams = post_data.encode('utf-8') md5.update(jsonparams) rcb64 = base64.b64encode(md5.digest()).decode('utf-8') R: post_parameters &lt;- list("Currency" = "BTC") post_data &lt;- jsonlite::toJSON(post_parameters, auto_unbox=T) jsonparams &lt;- stri_enc_toutf8(post_data, is_unknown_8bit = FALSE, validate = FALSE) rcb64 &lt;- base64encode(digest(jsonparams, algo="md5", raw=T) Instead of the last row, I tried this, but it also made another result. rcb64 &lt;- base64encode(charToRaw(digest(jsonparams, algo="md5")))
type: Question
has answer: http://stackoverflow.com/a/51790187
accepted answer: http://stackoverflow.com/a/51790187
tagged with: http://stackoverflow.com/tag/r
tagged with: api

http://stackoverflow.com/q/51687392
answer count: 0
type: UnansweredQuestion
tagged with: python-3.6
tagged with: console
downvote count: 0
score: 1
favorite count: 0
tagged with: terminal
type: Question
has comment: http://stackoverflow.com/comment/90340053
tagged with: python
has comment: http://stackoverflow.com/comment/90340011
has comment: http://stackoverflow.com/comment/90343168
has comment: http://stackoverflow.com/comment/90339623
has title: Import package using user input -- Python v3.6
has body: Uhm, this is my first question that I do in Stack Overflow, so let's just go to the point. :) I'm creating a program with Python v3.6 and it is a like terminal, my plan is do like the programming languages(C#: "console.write"). The commands will be stored in a folder called "lib" and it will have folders to separate the commands, so the thing will be just like this: ------------------------------------------------------------------------------------------------------------------------------------ lib- console- write.py see.py main.py ------------------------------------------------------------------------------------------------------------------------------------ So, as you can see there's the folder "lib", inside it has the folder "console" and inside the folder has 2 files "write.py" and "see.py". My mission is when the terminal starts the user type a command like: "$ console.write Hello World", doing that the program will separate the "console" from "write" creating a list ["console", "write"]. Now the terminal will see if "console" is a folder, if it exists so the terminal will check if "write"+".py" is a file, if so it will import the file and pass the args "Hello World", the basic structure that the command needs is two lines: "class exec:" and "def main(args):": class exec: def main(args): # The rest of the command here. print(args) With everything allright the terminal will import the file and execute the class "exec" and execute the def "main" passing all the arguments to it resulting in: $ console.write Hello World Hello World $ The same to "see.py": $ console.see /home/user/documents/file.txt This is a file that contains some text, really interesting. $ Thx if someone help me. ;) Have a good day!
upvote count: 1

http://stackoverflow.com/comment/90412638
type: AnswerComment
comment on: http://stackoverflow.com/a/51703047
score: 0
has text: It's a Pycharm BUG "Package management doesn't work with pip 10.0 " [BUG Link](https://youtrack.jetbrains.com/issue/PY-29395). Please recreate the virtual environment from the scratch, it may work. [Solutions at Pycharm support](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000168364-Pycharm-Virenv-AttributeError-module-pip-has-no-attribute-main-occured-)
type: Comment

http://stackoverflow.com/comment/90545857
type: QuestionComment
has text: @barny, ...given as the old one implements (well, used to implement) the API used by the OP's code, it seems pretty clear-cut. If someone says they're having a problem with `requests` or `numpy`, we don't bother looking at whether there's a separate library with the same name unless there's actually evidence to that effect.
comment on: http://stackoverflow.com/q/51791466
score: 0
type: Comment

http://stackoverflow.com/comment/90379419
has text: Side question: if all your function does is act like a table, why don't you use a dictionary?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51708969

http://stackoverflow.com/a/51761321
type: Answer
accepted answer of: http://stackoverflow.com/q/51760829
upvote count: 3
has body: You have to convert length to an integer after reading the user input. Otherwise you are comparing an integer with a string, which is never going to be equal. Hence you get in infinite loop. length = int(input('# input length of password in integers | '))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90481853
downvote count: 0
answers question: http://stackoverflow.com/q/51760829
score: 3

http://stackoverflow.com/comment/90560732
type: Comment
comment on: http://stackoverflow.com/a/51778581
score: 0
type: AnswerComment
has text: You can define a `class App(tk.Frame)` (that inherits from Frame) that contains an `AlertPanel ` Frame for your buttons. You can probably use it directly, with only alterations needed to attach the correct actions to your buttons, and some cosmetic changes to the aspect of the buttons.

http://stackoverflow.com/comment/90332008
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51684698
has text: @lenik Just reread your comment again ... I thought the OP was only looking for one match. I'll edit my answer in case the OP wanted multiple matches.
type: Comment

http://stackoverflow.com/a/51762291
has comment: http://stackoverflow.com/comment/90485119
has body: I didn't encounter errors that you've mentioned. Have you dropped in both columns into Values? import matplotlib.pyplot as plt plt.plot(dataset['Date'], dataset['Value']) plt.show() UPDATED with M query: let Source = Csv.Document(File.Contents("C:\your-directory..\timerseries.csv"),[Delimiter=",", Columns=2, Encoding=1252, QuoteStyle=QuoteStyle.None]), #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Date", type date}, {"Value", Int64.Type}}) in #"Changed Type"
has comment: http://stackoverflow.com/comment/90630183
has comment: http://stackoverflow.com/comment/90488512
type: Answer
has comment: http://stackoverflow.com/comment/90489112
has comment: http://stackoverflow.com/comment/90484032
upvote count: 2
has comment: http://stackoverflow.com/comment/90533374
accepted answer of: http://stackoverflow.com/q/51761926
score: 2
answers question: http://stackoverflow.com/q/51761926
has comment: http://stackoverflow.com/comment/90632797
has comment: http://stackoverflow.com/comment/90486244
has comment: http://stackoverflow.com/comment/90532808
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90484388
has comment: http://stackoverflow.com/comment/90665043

http://stackoverflow.com/q/51650338
tagged with: fabric
tagged with: python
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/104940374
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51873062
has comment: http://stackoverflow.com/comment/92611666
has comment: http://stackoverflow.com/comment/92507971
has comment: http://stackoverflow.com/comment/91019542
score: 2
downvote count: 0
has body: I have a very basic problem with the fabric library, after I installed it on my mac via pip. $ pip install fabric (I already tried it with sudo. Makes no difference) Installation worked fine I think. $ fab -V Fabric 2.2.2 Paramiko 2.4.1 Invoke 1.1.1 But if I follow the fabric tutorial (http://docs.fabfile.org/en/1.14/tutorial.html), and try the very first step -creating the fabfile.py with the hello task- It always fails with: $ fab hello No idea what 'hello' is! I am in the right directory and the file exits. I followed exactly the steps given in the tutorial. Does anybody have a clue what the problem might be? I wasn't able to find a solution anywhere online.
favorite count: 0
has comment: http://stackoverflow.com/comment/92527022
has title: fabric practically not working after installation on Mac OS 10.13.5
type: Question

http://stackoverflow.com/q/51768588
tagged with: qt5
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Stop window from jumping with movemouseEvent
score: 0
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/51769088
has body: I have a widget where I want to be able to move the window using the mouse from anywhere inside the widget, except for inside a qcombobox or qlineedit or qpushbutton. The mousePressEvent and mouseMoveEvent defined in the Wizard init page makes this work. The problem is that when a combobox is clicked, the widget can jump to any location in the screen or the qcombobox and comboboxlist become separated. This happens randomly and the results are random. It can move a few centimeters in any direction or to the bottom left of the screen, bottom right, etc etc. It only seems to happen when clicking a combo box. How can I disable the movemouseevent for comboboxes and linedits? import sys from PyQt5.QtCore import Qt, QPoint, QIODevice, QDateTime, QSize, QObject, QProcess, pyqtSignal, QThread, QEvent, QTimer, QBasicTimer from PyQt5.QtWidgets import QStyle, QWidget, QMainWindow, QCompleter, QProgressBar, QFileDialog, QApplication, qApp, QLineEdit, QLabel, QComboBox, QWizard, QWizardPage, QPushButton, QVBoxLayout, QShortcut, QMessageBox, QDesktopWidget, QHBoxLayout from PyQt5.QtGui import QPainter, QFont, QIcon, QPixmap, QPalette, QLinearGradient, QColor, QBrush, QCursor class Wizard(QWizard): # Initilisation of the UI and Wizard def __init__(self, parent=None): super(Wizard, self).__init__(parent) self.addPage(EnterCode(self)) #mos position self.oldPos = self.pos() def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QPoint(event.globalPos() - self.oldPos) print(delta) self.move(self.x() + delta.x(), self.y() + delta.y()) # if obj != self.comboBox: self.oldPos = event.globalPos() class EnterCode(QWizardPage): """ Sensor Code Entry """ def __init__(self, parent=None): super(EnterCode, self).__init__(parent) # Spacer Label self.spacer = QLabel() self._five_digit = QLineEdit(self) self.code_combo = QComboBox(self) self.label1 = QLabel() self.lineedit1 = QLineEdit(self) self.lineedit2 =QLineEdit(self) self.lineedit3 = QLineEdi…

http://stackoverflow.com/a/51734419
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51728645
has body: Looks like Flask-WhooshAlchemy is not ready for Python3, if we look at the code on github, we find this relevant part: if not isinstance(query, unicode): query = unicode(query) results = self._whoosh_searcher(query, limit, fields, or_) Now, this refers to the unicode built-in type, which is no longer available in Python3, see this exercise in the interpreter, Python2: Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; unicode &lt;type 'unicode'&gt; And doing the same in Python3, we find we get the error you are experiencing: Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; unicode Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'unicode' is not defined
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90441648
answers question: http://stackoverflow.com/q/51728645
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90479672
has text: Probably the best solution full stop.
comment on: http://stackoverflow.com/a/51757536
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51784864
upvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
score: 1
type: Question
has title: Changing tf.Variable value in Estimator SessionRunHook
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51789632
tagged with: python
accepted answer: http://stackoverflow.com/a/51789632
favorite count: 0
has body: I have a tf.Estimator whose model_fn contains a tf.Variable initialized to 1.0. I would like to change the variable value at every epoch based on the accuracy on the dev set. I implemented a SessionRunHook to achieve this, but when I try to change the value I receive the following error: raise RuntimeError("Graph is finalized and cannot be modified.") This is the code for the Hook: class DynamicWeightingHook(tf.train.SessionRunHook): def __init__(self, epoch_size, gamma_value): self.gamma = gamma_value self.epoch_size = epoch_size self.steps = 0 def before_run(self, run_context): self.steps += 1 def after_run(self, run_context, run_values): if self.steps % epoch_size == 0: # epoch with tf.variable_scope("lambda_scope", reuse=True): lambda_tensor = tf.get_variable("lambda_value") tf.assign(lambda_tensor, self.gamma_value) self.gamma_value += 0.1 I understand the Graph is finalized when I run the hook, but I would like to know if there's any other way to change a variable value in the model_fn graph with the Estimator API during training.

http://stackoverflow.com/comment/90280607
type: QuestionComment
type: Comment
has text: @n.m. This entirely depends on your BLAS implementation. Essentially, this benchmark compares Eigen's matrix multiplication with the BLAS used by numpy.
score: 0
comment on: http://stackoverflow.com/q/51656818

http://stackoverflow.com/comment/90331447
type: AnswerComment
has text: Where I was making a mistake?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51684628

http://stackoverflow.com/q/51658801
tagged with: python
has comment: http://stackoverflow.com/comment/90281344
answer count: 0
has comment: http://stackoverflow.com/comment/90281874
tagged with: flood-fill
type: Question
tagged with: numpy
has body: I am trying to make an algorithm in python where a random element in an (300,300,3) nd numpy image array is picked and is changed to white. Then the surrounding pixels have a 99 percent probability of being changed to white and the ones surrounding those have a 98 percent chance of being turned white and so on and so forth. I am trying to use a floodfill algorithm to achieve this but it gives me a recursion error. Any suggestions? import numpy as np import random def addHoles(a): randX = random.randint(0,299) randY = random.randint(0,299) floodfill(a,randX,randY,100) def prob(n): rand = random.randint(0,101) if rand &lt; n: return True else: return False def floodfill(a,x,y,n): white = [255,255,255] if(x == 299 or y == 299 or x == 0 or y == 0): return if(prob(n)): a[x,y] = white floodfill(a, x+1, y, n-1) floodfill(a, x-1, y, n-1) floodfill(a, x, y+1, n-1) floodfill(a, x, y-1, n-1)
has title: Floofill Error Python
has comment: http://stackoverflow.com/comment/90281921
has comment: http://stackoverflow.com/comment/90281819
has comment: http://stackoverflow.com/comment/90281496
tagged with: image
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90281735

http://stackoverflow.com/comment/90370531
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51704178
has text: Your solution worked for me! Thank you very much. I really appreciate for your help.

http://stackoverflow.com/comment/90412771
has text: It seems like the OP means `x[IX(0,i)] = b==1 ? -x[IX(1,i)] : x[IX(1,i)];` but they switched some symbols and ended up with nonsense.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51725926

http://stackoverflow.com/comment/90526209
score: 0
comment on: http://stackoverflow.com/q/51784529
type: Comment
type: QuestionComment
has text: Because it does not have the "hist=True" option

http://stackoverflow.com/comment/90322735
score: 1
type: AnswerComment
has text: I like this the most.. Cleanest and easy to understand!
type: Comment
comment on: http://stackoverflow.com/a/51679724

http://stackoverflow.com/q/51678153
tagged with: machine-learning
type: Question
accepted answer: http://stackoverflow.com/a/51812911
tagged with: relu
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90336663
answer count: 1
has comment: http://stackoverflow.com/comment/90326228
has answer: http://stackoverflow.com/a/51812911
tagged with: python
has body: I'm trying to implement the backpropagation with ReLU as the activation function. If I am not mistaken the derivative of that function is 1 for x > 0 and 0 for x &lt; 0. Using this derivative the network does not learn at all. Searching for other examples I found that most ignore the 1 for X > 0 part and just leave it at x, which leads to much better results. I wonder why that is the case. To make sure I there are no other mistakes, here is the code for training a 1 input, 1 output no hidden Neuron Network. I use the mean squared error as a error function import random x = random.uniform(0, 1) y = random.uniform(0, 1) w = random.uniform(0, 1) lr = 0.1 for i in range(500): z = x * w yP = z if yP &lt; 0: yP = 0 loss = (yP - y)**2 print(i, loss) grad_y=2.0*(yP - y) grad_z = grad_y if z &lt; 0: grad_z = 0 else : grad_z = grad_y grad_w = grad_z * x w -= lr * grad_w Please note that is it unlikely it has to do with the size of the network I also tested on a network with 1000 input Neurons, 1 hidden Layer with 100 Neurons and 10 Output Neurons. I used a batch size of 64 and 500 epochs. It had the same problem.
type: AnsweredQuestion
has title: Using the Proper ReLU derivative prevents learning

http://stackoverflow.com/comment/90553847
type: Comment
type: QuestionComment
has text: @UmeshKonduru You usually *only* pass class instances (ie objects). Classes themselves can be passed, but it is used not so often -- usually when you try to process different kinds of objects the same way.
score: 0
comment on: http://stackoverflow.com/q/51798366

http://stackoverflow.com/q/51680332
has body: I came across this post, which detailed how to incorporate a ggplot object into a matplotlib grid. The process involves first generating a ggplot object, getting the current figure, and then building more subplots onto the existing figure with the state-based API. I wanted to replicate this using the object-oriented API in order to make this more extensible. import ggplot as gp import matplotlib.pyplot as plt g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price') + gp.xlab('carat') g.make() f1 = plt.gcf() g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat') + gp.xlab('price') g.make() f2 = plt.gcf() (fig, axes) = plt.subplots(1,2, figsize=(20,10)) axes[0] = f1.axes[0] axes[0].set_title('Price vs. Carat') axes[1] = f2.axes[0] axes[1].set_title('Carat vs. Price') fig.show() However, when this is executed, the output comes out blank: My motivation for this post extends beyond just the ggplot library, as ideally I'd like to create grids using graphics from several different libraries like seaborn or bokeh too. What is the best way to extract an axis from a graph and add it onto a matplotlib figure grid using the object-oriented API? EDIT: As @ImportanceOfBeingErnest suggested, I tried a different method: import ggplot as gp import matplotlib.pyplot as plt g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price')+ gp.xlab('carat') g.make() f1 = plt.gcf() g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat')+ gp.xlab('price') g.make() f2 = plt.gcf() plt.show() def add_axis(fig, ggFig, pos): ggAxis = ggFig.axes[0] ggAxis.remove() ggAxis.figure = fig fig.axes.append(ggAxis) fig.add_axes(ggAxis) dummy = fig.axes[pos] ggAxis.set_position(dummy.get_position()) dummy.remove() plt.close(ggFig) (fig, axes) = plt.subplots(1,2, figsize=(20,10)) add_axis(fig, f2, 1) add_axis(fig, f1, 0) fig.show() Oddly enough…
answer count: 2
linked to: http://stackoverflow.com/q/42899779
tagged with: data-visualization
tagged with: python
possible better answer: http://stackoverflow.com/a/51680971
has title: Set matplotlib axis to other figure's axis using object-oriented interface
linked to: http://stackoverflow.com/q/35042255
has answer: http://stackoverflow.com/a/51680971
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90325487
score: 0
has answer: http://stackoverflow.com/a/51680499
linked to: http://stackoverflow.com/q/6309472
type: Question
tagged with: ggplot2
accepted answer: http://stackoverflow.com/a/51680499
tagged with: matplotlib

http://stackoverflow.com/a/51793034
answers question: http://stackoverflow.com/q/51792964
type: Answer
score: 11
upvote count: 11
downvote count: 0
has body: While @pault 's answer addresses your question, I think it isn't super readable. If you have a couple of variables only, pythons mantra dictate a straightforward, explicit way: if len(x) == 1: f(x) elif len(y) == 1: f(y) elif len(z) == 1: f(z) Otherwise, if you have a list, a for loop is readable and efficient: for l in ls: if len(l) == 1: f(l) break

emscripten
tags question: http://stackoverflow.com/q/51784307
tag name: emscripten
type: Tag

http://stackoverflow.com/a/51687459
answers question: http://stackoverflow.com/q/51686929
has comment: http://stackoverflow.com/comment/90337557
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/90344269
has comment: http://stackoverflow.com/comment/90336975
upvote count: 3
has comment: http://stackoverflow.com/comment/90336972
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51686929
has body: Perhaps it is not an optimal solution, but it does the work on this small dataframe: EDIT added checking for company names, assuming that we removed punctuation df = pd.DataFrame({"company": ['A', 'A', 'A', 'B', 'B'], "address": ['16D Bayberry Rd, New Bedford, MA, 02740, USA', 'MA, USA', 'USA', 'New Bedford, MA, USA', 'MA, USA']}) # Splitting addresses by column and making sets from every address to use "issubset" later addresses = list(df['address'].apply(lambda x: set(x.split(', '))).values) companies = list(df['company'].values) rows_to_drop = [] # Storing row indexes to drop here # Iterating by every address for i, (address, company) in enumerate(zip(addresses, companies)): # Iteraing by the remaining addresses rem_addr = addresses[:i] + addresses[(i + 1):] rem_comp = companies[:i] + companies[(i + 1):] for other_addr, other_comp in zip(rem_addr, rem_comp): # If address is a subset of another address, add it to drop if address.issubset(other_addr) and company == other_comp: rows_to_drop.append(i) break df = df.drop(rows_to_drop) print(df) company address 0 A 16D Bayberry Rd, New Bedford, MA, 02740, USA 3 B New Bedford, MA, USA
type: Answer

http://stackoverflow.com/a/51689534
downvote count: 0
score: 1
has body: I got a turnaround solution that to save the path as a bookmark of a web in chrome tag and whenever I enter the root of jupyter notebook. I know it's stupid but it did work... I have tried your answers above but not really work. Thanks.
upvote count: 1
answers question: http://stackoverflow.com/q/51686191
type: Answer

http://stackoverflow.com/comment/90411582
type: Comment
type: QuestionComment
has text: @DebanjanB, I just gave I little bit more information that may be necessary. I am convinced, however, that the solution which would make those errors disappear is one, therefore, there should be one question, on my opinion.
comment on: http://stackoverflow.com/q/51724472
score: 0

http://stackoverflow.com/comment/90457871
type: Comment
has text: Those class attrs need to be referenced with `self` so just use `self.content` etc
type: QuestionComment
comment on: http://stackoverflow.com/q/51748941
score: 0

svd
type: Tag
tags question: http://stackoverflow.com/q/51787135
tag name: svd

http://stackoverflow.com/comment/90335986
type: QuestionComment
comment on: http://stackoverflow.com/q/51686797
has text: I mean format your expected *output* correctly. Currently `rusage` is written as a variable, not as the key to a dict.
score: 0
type: Comment

http://stackoverflow.com/a/51707061
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90377382
has comment: http://stackoverflow.com/comment/90375992
has body: You can still use with syntax in the interactive console, however a context is based on 2 magic methods __enter__ and __exit__, so you can just use them: class MyCtx(object): def __init__(self, f): self.f = f def __enter__(self): print("Enter") return self.f def __exit__(*args, **kwargs): print("Exit") def foo(): print("Hello") usually you do: with MyCtx(foo) as f: f() Same as: ctx = MyCtx(foo) f = ctx.__enter__() f() ctx.__exit__() Here you have the live example Remember that contexts __exit__ method are used for managing errors within the context, so most of them have a signature of __exit__(exception_type, exception_value, traceback), if you dont need to handle it for the tests, just give it some None values: __exit__(None, None, None)
type: Answer
has comment: http://stackoverflow.com/comment/90377115
has comment: http://stackoverflow.com/comment/90377203
score: 21
upvote count: 21
has comment: http://stackoverflow.com/comment/90375172
has comment: http://stackoverflow.com/comment/90375906
accepted answer of: http://stackoverflow.com/q/51706836
answers question: http://stackoverflow.com/q/51706836

http://stackoverflow.com/q/51781149
downvote count: 1
has answer: http://stackoverflow.com/a/51781280
tagged with: string
has answer: http://stackoverflow.com/a/51836539
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/90520302
has answer: http://stackoverflow.com/a/51781398
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69138513
tagged with: python
has body: Imagine we have following list of strings: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] The output of our program should group each set of anagram and return them all together as a list as following: Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] My current solution finds the first set of anagrams but fails to detect the other two and instead, duplicates the first groups into the list: class Solution(object): def groupAnagrams(self, strs): allResults=[] results=[] temp='' for s in strs: temp=s[1:]+s[:1] for i in range(0,len(strs)): if temp==strs[i]: results.append(strs[i]) allResults.append(results) return allResults and the output is: [["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"],["ate","eat","tea"]] How to fix this issue? EDIT: I have fixed the duplication in appending by appending the results into allResults outside of second loop: class Solution(object): def groupAnagrams(self, strs): allResults=[] results=[] temp='' for s in strs: temp=s[1:]+s[:1] for i in range(0,len(strs)): if temp==strs[i]: results.append(strs[i]) allResults.append(results) print(results) return allResults Yet, it does not detect the other two sets of anagrams.
has comment: http://stackoverflow.com/comment/90520780
tagged with: list
has comment: http://stackoverflow.com/comment/90520566
has answer: http://stackoverflow.com/a/51781334
has answer: http://stackoverflow.com/a/51781382
type: Question
tagged with: anagram
has title: Anagrams in Python using lists
score: -1
answer count: 6
has comment: http://stackoverflow.com/comment/90520752
has comment: http://stackoverflow.com/comment/90520648

http://stackoverflow.com/comment/90390924
score: 1
type: QuestionComment
has text: @ntrme: Are these `id`s being `print`ed in the same process? In the CPython reference interpreter, `0` is a singleton (implementation detail), so even if you did something weird that causes `value` to be redefined in two places, the `id` would match *unless* you had separate processes involved (and even then, I think it would only occur if you were using `subprocess` or `multiprocessing` on Windows, where the workers are made via spawn, not fork). Alternatively, is any of your code assigning to `definer.value`? If so, the `id` would change after the assignment.
type: Comment
comment on: http://stackoverflow.com/q/51714337

http://stackoverflow.com/a/51667308
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51667176
has body: You can use the split function a = ['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87'] x = list(i.split(',')[0] for i in a) y = list(i.split(',')[1] for i in a) print(x) #['46', '91', '46', '137', '54', '99', '91', '91'] print(y) #['101', '86', '100', '64', '53', '31', '85', '87']

http://stackoverflow.com/comment/90358615
comment on: http://stackoverflow.com/a/51694319
type: Comment
has text: THANKS A LOT, now is working really well. I'm new here, how can i give you points or something like that? :v
score: 0
type: AnswerComment

http://stackoverflow.com/q/51706777
tagged with: python
has body: I'd like to do something like the following (obviously with a proper condition rather than just True): a = {1:1} print({2:2, **a if True else 1:0}) however, it doesn't work: $ python3 test2.py File "test2.py", line 2 print({2:2, **a if True else 1:0}) ^ SyntaxError: invalid syntax It also doesn't work if I put the dictionary unpacking in parens (I thought maybe there was a precedence issue between the unpacking and the ternary expression): $ python3 test2.py File "test2.py", line 2 print({2:2, (**a) if True else 1:0}) ^ SyntaxError: invalid syntax In the end, I had to apply the unpacking to the whole ternary expression, and use a temporary dictionary for the default: a = {1:1} print({2:2, **(a if True else {1:0})}) (which gives the output {2: 2, 1: 1}) Why can a ternary expression not contain a dictionary unpacking?
has comment: http://stackoverflow.com/comment/90374949
downvote count: 0
linked to: http://stackoverflow.com/q/19525530
has comment: http://stackoverflow.com/comment/90374269
type: Question
has answer: http://stackoverflow.com/a/51707221
answer count: 1
tagged with: iterable-unpacking
score: 4
has title: Dictionary unpacking doesn't work in one arm of a ternary expression
favorite count: 0
upvote count: 4
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/126607778
has text: The odd thing is that if I add the -1, it gets me to one pixel below the height and width of the original, and if I don't, it gets me to one pixel above the height and width of the original. Very confusing! I still don't know how to get to the actually correct size, now.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51745109
type: AnswerComment

http://stackoverflow.com/comment/90392168
has text: .... `while 1 != 0`? Why would you write that? Just use `while True:`... Anyway you can probably try to vectorize the operations to generate up to `N` random numbers at a time... Create a vector with `N` random values for `r1`, same with `r2`, `r3` and `r4`. Then compute `L1` (which will be an `N` element vector). Then select the rows of `L1` according to that condition and compute `X` which will have `<= N` elements. To create the random vectors use the `size` parameter as mentioned by Warren.
comment on: http://stackoverflow.com/q/51715173
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90409719
score: 1
has text: Ok I will make it as an answer for future reference.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51724039

http://stackoverflow.com/a/51678309
type: Answer
answers question: http://stackoverflow.com/q/51677887
upvote count: 5
downvote count: 0
score: 5
type: AcceptedAnswer
has body: A comment pointed out that if the slit is uneven, the result can't be a array, at least not one that has the same dtype. At best it would be an object dtype. But lets consider the case of equal length subarrays: In [124]: x = np.arange(10) In [125]: np.split(x,2) Out[125]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])] In [126]: np.array(_) # make an array from that Out[126]: array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) But we can get the same array without split - just reshape: In [127]: x.reshape(2,-1) Out[127]: array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) Now look at the code for split. It just passes the task to array_split. Ignoring the details about alternative axes, it just does sub_arys = [] for i in range(Nsections): # st and end from `div_points sub_arys.append(sary[st:end]) return sub_arys In other words, it just steps through array and returns successive slices. Those (often) are views of the original. So split is not that sophisticate a function. You could generate such a list of subarrays yourself without a lot of numpy expertise. Another point. Documentation notes that split can be reversed with an appropriate stack. concatenate (and family) takes a list of arrays. If give an array of arrays, or a higher dim array, it effectively iterates on the first dimension, e.g. concatenate(arr) =&gt; concatenate(list(arr)).
accepted answer of: http://stackoverflow.com/q/51677887

http://stackoverflow.com/q/51651812
type: Question
tagged with: python-import
answer count: 2
accepted answer: http://stackoverflow.com/a/51651976
tagged with: importerror
score: 0
has answer: http://stackoverflow.com/a/51651976
has body: First of all I searched my problem and didn't find any solution. I imported SimPy in my Python script as "import simpy" and I assured that SimPy installed on my system via pip but nevertheless it couldn't be imported. I also added the picture shows output of pip list and result of my try to run script. import simpy def car(env): while True: print('Start parking at %d' % env.now) parking_duration = 5 yield env.timeout(parking_duration) print('Start driving at %d' % env.now) trip_duration = 2 yield env.timeout(trip_duration) def main(): env = simpy.Environment() env.process(car(env)) env.run(until=15) if __name__ == '__main__': main() Terminal output:
possible better answer: http://stackoverflow.com/a/51661370
has answer: http://stackoverflow.com/a/51661370
has title: Can't Import SimPy
tagged with: python
has comment: http://stackoverflow.com/comment/90268280
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90268389
has comment: http://stackoverflow.com/comment/90267064
has comment: http://stackoverflow.com/comment/90268909
has comment: http://stackoverflow.com/comment/90268689
tagged with: simpy

http://stackoverflow.com/q/51654726
has answer: http://stackoverflow.com/a/57246611
has answer: http://stackoverflow.com/a/51903686
type: Question
tagged with: windows-10
score: 0
answer count: 3
has body: When I run the command pip install pyswisseph to install the python extension of the swiss ephemeris, its giving errors. C:\WINDOWS\system32&gt;pip install pyswisseph Collecting pyswisseph Using cached https://files.pythonhosted.org/packages/09/27/10ad652fa0e07fc89890142a6f900725e26cf02a24d8fd724015e08707b5/pyswisseph-2.00.00-2.tar.bz2 Building wheels for collected packages: pyswisseph Running setup.py bdist_wheel for pyswisseph ... error Complete output from command c:\users\narayana\appdata\local\programs\python\python37\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Narayana\\AppData\\Local\\Temp\\pip-install-wlypji8s\\pyswisseph\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Narayana\AppData\Local\Temp\pip-wheel-f31zjcrt --python-tag cp37: Searching system libswe... pkg-config not found Using internal libswe c:\users\narayana\appdata\local\programs\python\python37\lib\site-packages\setuptools\dist.py:398: UserWarning: Normalizing '2.00.00-2' to '2.0.0.post2' normalized_version, running bdist_wheel running build running build_ext building 'swisseph' extension creating build creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\libswe creating build\temp.win-amd64-3.7\Release\swephelp C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.13.26128\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ilibswe -Iswephelp -Ic:\users\narayana\appdata\local\programs\python\python37\include -Ic:\users\narayana\appdata\local\programs\python\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.13.26128\include" /Tcpyswisseph.c /Fobuild\temp.win-amd64-3.7\Release\pyswisseph.obj -std=gnu99 cl : Command line warning D9002 : ignoring unknown option '-std=gnu99' pyswisseph.c c:\users\narayana\appdata\lo…
tagged with: python
accepted answer: http://stackoverflow.com/a/57246611
has answer: http://stackoverflow.com/a/51654794
tagged with: pip
has title: pip install pyswisseph giving error on windows 10
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51654794

http://stackoverflow.com/q/51724472
type: UnansweredQuestion
downvote count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/90415121
has comment: http://stackoverflow.com/comment/90410348
type: Question
score: -2
upvote count: 0
has comment: http://stackoverflow.com/comment/90410824
answer count: 1
has comment: http://stackoverflow.com/comment/90411582
has body: OS: Ubuntu I am following step 2.5 of this tutorial: 1) I downloaded selenium server standalone of two versions:selenium-server-standalone-2.50.1.jar and selenium-server-standalone-3.13.0.jar. 2) I created a file named test_selenium_server.py: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME) driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.OPERA) driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS) I installed chromedriver and geckodriver. When I run java -jar selenium-server-standalone-2.50.1.jar and then python test_selenium_server.py, I get an error like: Traceback (most recent call last): File "test_selenium_server.py", line 12, in &lt;module&gt; desired_capabilities=DesiredCapabilities.OPERA) ... selenium.common.exceptions.WebDriverException: Message: The best matching driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver can't create a new driver instance for Capabilities [{browserName=opera, version=, platform=ANY}] Build info: version: '2.50.1', revision: 'd7fc91b', time: '2016-01-29 19:08:26' System info: host: 'AMDC2763', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-30-generic', java.version: '1.8.0_181' Driver info: driver.version: unknown ... And when I run java -jar selenium-server-standalone-3.13.0.jar and then python test_selenium_server.py, I get an error like: Traceback (most recent call last): File "test_selenium_server.py", line 12, in &lt;module&gt; desired_capabilities=DesiredCapabilities.OPERA) ... selenium.common.exceptions.SessionNotCreatedException: Message: Unable to create new service: OperaDriverService Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32…
favorite count: 0
has comment: http://stackoverflow.com/comment/90411208
has comment: http://stackoverflow.com/comment/90411140
has answer: http://stackoverflow.com/a/51725967
has comment: http://stackoverflow.com/comment/90411386
tagged with: opera
tagged with: python
has title: selenium.common.exceptions.SessionNotCreatedException: Message: Unable to create new service: OperaDriverService
tagged with: selenium-webdriver

http://stackoverflow.com/comment/90508450
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51774500
has text: See comments above
type: AnswerComment

http://stackoverflow.com/comment/90370176
type: QuestionComment
has text: I guess that in this specific case you are fitting `y` as a linear function of `x^2` and not a linear function of `x`. I advise you to look at feature engineering in machine learning if this is confusing.
comment on: http://stackoverflow.com/q/51704532
score: 0
type: Comment

http://stackoverflow.com/a/55555605
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/122207043
has body: To get the first Embed of your message, as you said that would be a dict(): embedFromMessage = uzenet.embeds[0] To transfer the dict() into an discord.Embed object: embed = discord.Embed.from_data(embedFromMessage)
type: Answer
accepted answer of: http://stackoverflow.com/q/51688392
answers question: http://stackoverflow.com/q/51688392
upvote count: 5

http://stackoverflow.com/comment/90542380
has text: Not strings, they do not support `-`, oops.
comment on: http://stackoverflow.com/a/51792085
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51660842
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51660271
has body: The first approach gives you a probability mass function. The second gives you a probability density - hence the name probability density function (pdf). Hence both are correct, they just show something different. If you evaluate the pdf over a larger range (e.g. 10 times the standard deviation), it will look much like an expected gaussian curve. import pandas as pd import scipy.stats as stats import numpy as np import matplotlib.pyplot as plt dict = {'id': ['a','b','c','d'], 'testers_time': [10, 30, 15, None], 'stage_1_to_2_time': [30, None, 30, None], 'activated_time' : [40, None, 45, None],'stage_2_to_3_time' : [30, None, None, None],'engaged_time' : [70, None, None, None]} df = pd.DataFrame(dict, columns=['id', 'testers_time', 'stage_1_to_2_time', 'activated_time', 'stage_2_to_3_time', 'engaged_time']) df= df.dropna(subset=['testers_time']).sort_values('testers_time') mean = np.mean(df['testers_time']) std = np.std(df['testers_time']) x = np.linspace(mean - 5*std, mean + 5*std) fit = stats.norm.pdf(x, mean, std) print(fit) plt.plot(x, fit, marker='.', linestyle='-') plt.hist(df['testers_time'], normed='true') plt.show()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51660271
type: Answer

http://stackoverflow.com/q/51681833
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90326834
tagged with: compare
has title: Storing and Comparing Multiple Attributes in Python
tagged with: python
tagged with: dictionary
has body: I'm trying to build a Survivor game that will allow me to compare stored characters against one another individually and as members of a tribe. I can sort of do it with one attribute, but can not figure out the best way to expand it to multiple attributes. Example: TribeAStr = {'John': 50, 'Tyler': 55, 'Joe': 90, 'Bob': 55} # check who is the strongest Survivor $ strongest = max(TribeAStr, key=TribeAStr.get) #Remove him from TribeA del TribeAStr[strongest] #Check how strong the Tribe is as a whole $ tribeastrength = sum(TribeAStr.values()) What I'd like to do is have each Survivor house their own attribues, and then use their names as a key that can then be pulled into similar scenarios as above. Something like this: class Survivor: def __init__(self, name, str=None, int=None, cha=None, luk=None): self.name = name self.str = strength self.int = intelligence self.cha = charisma self.luk = luck TribeA = {} John = Survivor{'John', 50, 40, 55, 20} Bob= Survivor{'Bob', 55, 40, 80, 25} Joe= Survivor{'Joe', 60, 10, 65, 10} Tyler= Survivor{'Tyler', 56, 30, 15, 25} TribeA.update('John', 'Bob', 'Joe', 'Tyler') # check who is the strongest Survivor $ strongest = max(Survivor, Survivor.str) for Survivor in TribeA Any advice?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51681918
has answer: http://stackoverflow.com/a/51681892
tagged with: class
type: Question
has comment: http://stackoverflow.com/comment/90326821
has answer: http://stackoverflow.com/a/51681917

http://stackoverflow.com/comment/90505930
score: 0
comment on: http://stackoverflow.com/q/51769590
has text: Interesting. Not sure what mistake you did. Ever flask application that I've written has used request.args, or request.form to get the data. I'm glad you at least figured out something.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51659651
tagged with: python
has body: I am learning about VGG, and I was struck by the following performance graph: My question is this: Looking at the graph, it seems that first there is rapid growth, which then gradually slows down. This makes sense to me, since it becomes more difficult to improve a model the smaller the loss is. However, there are also three sudden drops around the 50, 75, and 100 epoch mark. I am curious as to why all the models experience this drop and rebound at the same time? What is causing it? Thank you in advance for any help.
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
tagged with: performance
tagged with: statistics
score: 0
accepted answer: http://stackoverflow.com/a/51659896
answer count: 1
favorite count: 0
has title: Strange pattern in convolutional neural network performance
has answer: http://stackoverflow.com/a/51659896

http://stackoverflow.com/comment/90935871
type: Comment
type: QuestionComment
has text: @Maksim pretty certain that the issue here is that the version of pip packaged with [virtualenv](https://pypi.org/project/virtualenv/) is outdated.
comment on: http://stackoverflow.com/q/51644402
score: 0

http://stackoverflow.com/a/51677805
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90319355
has body: Use python sockets. Specifically, copy the 'echo client' code from here: https://docs.python.org/3/library/socket.html#example with your host/port.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51677665
answers question: http://stackoverflow.com/q/51677665

http://stackoverflow.com/comment/90479223
type: AnswerComment
comment on: http://stackoverflow.com/a/51745367
score: 0
type: Comment
has text: Thank you.. I accept this answer as it is giving what I wanted. But was not exactly what I thought, still it is giving me idea or suggestion which is a silver lining on the dark cloud.

http://stackoverflow.com/q/51762032
has body: I am using struct.pack to return me a bytes object. However, it is inconsistent. print(struct.pack('BbbB', 0x1B, -2, 1, 0)) #returns b'\x1b\xfe\x01\x00' GOOD print(struct.pack('BbbB', 0x0F, -2, 1, 0)) #returns b'\x0f\xfe\x01\x00' GOOD print(struct.pack('BbbB', 0x0C, -2, 1, 0)) #returns b'\x0c\xfe\x01\x00' GOOD print(struct.pack('BbbB', 0x35, -2, 1, 0)) #returns b'5\xfe\x01\x00' ??? print(struct.pack('BbbB', 0x21, -2, 1, 0)) #returns b'!\xfe\x01\x00' ??? If I look at ASCII character chart, I can see why it became "5" and "!" in the last two examples, but shouldnt it have returned me b'\0x35\xfe\x01\x00' and b'\0x21\xfe\x01\x00' instead of the above result? What am I missing here? I am using Python 3.7.0.
type: AnsweredQuestion
type: Question
answer count: 2
has title: Python struct.pack is not consistent
has answer: http://stackoverflow.com/a/51762355
accepted answer: http://stackoverflow.com/a/51762188
score: 0
tagged with: python-3.7
tagged with: byte
tagged with: struct.pack
tagged with: python
possible better answer: http://stackoverflow.com/a/51762355
has answer: http://stackoverflow.com/a/51762188

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/51729023
tags question: http://stackoverflow.com/q/51676274

http://stackoverflow.com/comment/90349362
score: 0
has text: What do you expect? A mean value ? Max value ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51694002

http://stackoverflow.com/a/51750586
has body: This might be sloppy but it's the best way I could figure out how to do this splitprice_pt1 = pricedata.str.split(r'\bon\b', expand=True)[0] #split the numbers on the 'on' text and selecting the first part split_KE_Date = pricedata.str.split(r'\bon\b', expand=True)[1] #split the numbers on the 'on' text and selecting the second part split_KE_Price = splitprice_pt1.str.split(r'^([^,]*,[^,]{3})', expand=True)[0] #split the numbers on the 3 digits after comma and selecting the first part range_KE_Price = splitprice_pt1.str.split(r'^([^,]*,[^,]{3})', expand=True)[1] #split the numbers on the 3 digits after comma and selecting the second part
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51742351
type: Answer
answers question: http://stackoverflow.com/q/51742351

http://stackoverflow.com/comment/90245682
type: QuestionComment
has text: Edited my post, hope you can better understand the problem I am facing... @roganjosh
score: 0
comment on: http://stackoverflow.com/q/51640114
type: Comment

http://stackoverflow.com/comment/90398956
type: Comment
has text: is it the best pythonic way of doing it... i know tricks, but need a perfect pythonic way of it
comment on: http://stackoverflow.com/a/51719059
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90332611
type: QuestionComment
has text: Another duplicates https://stackoverflow.com/questions/10973766/understanding-the-map-function and https://stackoverflow.com/questions/16750493/python-map-function-iteration and https://stackoverflow.com/questions/47998941/is-the-python-map-function-a-value-returning-function and related https://stackoverflow.com/questions/245792/when-is-not-a-good-time-to-use-python-generators
score: 0
comment on: http://stackoverflow.com/q/51671132
type: Comment

http://stackoverflow.com/q/51791374
has body: I am trying to scrape product name and its links from amazon root links root1.csv: https://www.amazon.com.au/s/gp/search/ref=sr_nr_p_85_0?fst=as%3Aoff&amp;rh=n%3A4851510051%2Cp_4%3AThe+Gro+Company%2Cp_6%3AANEGB3WVEVKZB%2Cp_85%3A5444100051&amp;bbn=4851510051&amp;ie=UTF8&amp;qid=1530074038&amp;rnid=5444099051 https://www.amazon.com.au/s/gp/search/ref=sr_nr_p_6_0?fst=as%3Aoff&amp;rh=n%3A4851510051%2Cp_4%3AES+Kids%2Cp_85%3A5444100051%2Cp_6%3AANEGB3WVEVKZB&amp;bbn=4851510051&amp;ie=UTF8&amp;qid=1530074169&amp;rnid=4910514051 My script is: below from urllib.request import urlopen import requests from bs4 import BeautifulSoup import re from io import StringIO from selenium import webdriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.firefox.options import Options from selenium.common.exceptions import NoSuchElementException import csv import time import os data = open("input/root1.csv", encoding='utf-8', errors='ignore').read() dataFile = StringIO(data) csvReader = csv.reader(dataFile) for row in csvReader: data = [] myurl = row[0] f = open('output/product_links1.csv', 'a', newline='', encoding='utf-8') writer = csv.writer(f) source_code = requests.get(myurl) plain_text = source_code.text soup = BeautifulSoup(plain_text, 'lxml') agent = {'User-Agent': 'Magic Browser'} req1 = requests.get(myurl, headers=agent) soup2 = BeautifulSoup(req1.content, "html.parser") headers = { # 'cookie': '_ga=GA1.3.1576298877.1530030143; _gid=GA1.3.898834.1530030143; __lc.visitor_id.8904714=S1530030142.7515ce042a; sid_customer_0b4ee=8afef780e801184c0fb0e6eb689b52ca-1-C; roadblocked_at=1530030165529; nocache=1; lc_sso8904714=1530112813205; lc_window_state=minimized', 'accept-encoding': 'text */*', 'accept-language': 'en-US,en;q=0.9', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.3…
upvote count: 0
has title: How to stop while loop when it reaches last page
answer count: 1
has comment: http://stackoverflow.com/comment/90540431
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51792151
has comment: http://stackoverflow.com/comment/90540300
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51792151
tagged with: web-scraping
downvote count: 1
type: Question

http://stackoverflow.com/comment/90320765
type: Comment
has text: @the_it_crowd are you sure bs4 package is installed in `/anaconda3/lib/python3.6/site-packages/`? Did you import bs4 **after** you added path to `sys.path`? It should work. Try to print `sys.path` when you run the script from terminal and compare it when you run it from cron.
type: AnswerComment
comment on: http://stackoverflow.com/a/51678310
score: 0

http://stackoverflow.com/q/51755742
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51768445
has comment: http://stackoverflow.com/comment/90487232
has title: Massively worse performance in Tensorflow compared to Scikit-Learn for Logistic Regression
upvote count: 3
linked to: http://stackoverflow.com/q/29831489
answer count: 1
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/90473795
tagged with: python
has body: I’m trying to implement a logistic regression classifier on a numerical dataset. I was having trouble getting good accuracy and loss with a model I built in Tensorflow, so to check it wasn’t something in the data, I tried using scikit-learn’s own LogisticRegression, and got massively better results. The difference is so big that I suspect I’m doing something really basic wrong on the .tf side... Data preprocessing: dt = pd.read_csv('data.csv', header=0) npArray = np.array(dt) xvals = npArray[:,1:].astype(float) yvals = npArray[:,0] x_proc = preprocessing.scale(xvals) XTrain, XTest, yTrain, yTest = train_test_split(x_proc, yvals, random_state=1) If I now do Logistic Regression with sklearn: log_reg = LogisticRegression(class_weight='balanced') log_reg.fit(XTrain, yTrain) yPred = log_reg.predict(XTest) print (metrics.classification_report(yTest, yPred)) print ("Overall Accuracy:", round(metrics.accuracy_score(yTest, yPred),2)) ...I get the following confusion matrix: precision recall f1-score support 1 1.00 0.98 0.99 52 2 0.96 1.00 0.98 52 3 0.98 0.96 0.97 51 4 0.98 0.97 0.97 58 5 1.00 0.95 0.97 37 6 0.93 1.00 0.96 65 7 1.00 0.95 0.97 41 8 0.94 0.98 0.96 50 9 1.00 0.98 0.99 45 10 1.00 0.98 0.99 49 avg/total 0.98 0.98 0.98 500 Overall Accuracy: 0.98 Great stuff, right? Here's the Tensorflow code instead from the same point right after the split: yTrain.resize(len(yTrain),10) #the labels are scores between 1 and 10 yTest.resize(len(yTest),10) tf.reset_default_graph() X = tf.placeholder(tf.float32, [None, 8], name="input") Y = tf.placeholder(tf.float32, [None, 10]) W = tf.Variable(tf.zeros([8, 10])) b = tf.Variable(tf.zeros([10])) out = (tf.matmul(X, W) + b) pred = tf.nn.softmax(out, name="output") learning_rate = 0.001 training_epochs = 100 batch_size = 200 display_step = 1 L2_LOSS = 0.01 l2 = L2_LOSS * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) # Minimize error using cross entropy cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(lo…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51768445
linked to: http://stackoverflow.com/q/33640581
score: 3

http://stackoverflow.com/a/51753479
answers question: http://stackoverflow.com/q/51694459
score: 0
accepted answer of: http://stackoverflow.com/q/51694459
type: AcceptedAnswer
has body: After going through the give inputs and outputs by the OP i understood that OP wants to count the number of primes which can completely divide the prod (product of element) and give remainder as 0. Input 1 by OP - g = 1*2*3*4 and distinct prime divisor of g are 2 and 3. Total count of distinct prime divisor = 2 Input 2 by OP - g = 96*98*5*41*80 and distinct prime divisor of g are 2,3,5,7 and 41. Total count of distinct prime divisor = 5 Code for the above problem - class Solution: # @param A : list of integers # @return an integer def prime(self,num): if(num==1): return 0 for i in range(2,(num//2+1)): if(num%i==0): return 0 return num def solve(self, A): prod = 1 tot = 0 for i in range(0,len(A)): prod = prod*A[i] for i in range(1,(prod//2+1)): pr = self.prime(i) if(pr): #77145600 print("Prime :",pr) if(prod%pr==0): tot = tot+1 return tot A = [96,98,5,41,80] print(Solution().solve(A)) But for this code, the response time is very high. For this input - 96,98,5,41,80 the response time was more than 5 hours. Can anyone provide a better solution for it? I found a better solution then the above mentioned by me - Updated new code - # Python Program to find the prime number def prime(num): if(num==1): return 0 for i in range(2,(num//2+1)): if(num%i==0): return 0 return num # Python Program to find the factors of a number def findFactors(x): # This function takes a number and finds the factors total = 0 for i in range(1, x + 1): if x % i == 0: if(prime(i)!=0): print("Prime : ",prime(i)) total+=1 print("Total : ",total) return total # change this value for a different result. num = 77145600 findFactors(num) The findFactors function first finds the factors of given number and then by using prime function I am checking whether the found factor is prime or not. If it is a prime number then I am incrementing the total by 1. Execution time is 45 seconds on my system.
has comment: http://stackoverflow.com/comment/90481142
type: Answer

http://stackoverflow.com/a/51765197
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51765116
has body: if type(event) in (Event1,Event2): new_event = type(event)(something) Make it easier to check weather type(event) is Event1 or Event2
type: Answer

http://stackoverflow.com/a/51761073
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: Both + and - can be used as unary or binary operators. In your case they are used as unary operators. return + operand is the same as return operand. We are used to see them in the form of return +operand or return -operand.
answers question: http://stackoverflow.com/q/51760986

http://stackoverflow.com/q/51733298
answer count: 2
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90427420
favorite count: 0
has answer: http://stackoverflow.com/a/65327432
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90429543
tagged with: python
has answer: http://stackoverflow.com/a/51735273
has body: I have a Pandas dataframe with 3 columns (x, y, d) and about 200, 000 rows. x and y are integers, denoting the position of the grid. d denotes point density of the grid. There are about 90 rows missing (not included in the df), all of which has a d of 0. I want to plot the dataframe into a 501 * 501 pixel and each pixel's color is determined by its corresponding d. I was able to do it using numpy, matplotlib, and PIL, the image looks like this: gray scale heat map. However, the runtime is about 16s. I wonder is there anyway to improve the performance? The code is as following: #read csv from HDFS to a pandas df conf = SparkConf().setAppName("Read_CSV") sqlContext = sql.SQLContext(sc) df = sqlContext.read.csv("hdfs://localhost:9000/density/output/*", header=True, sep=",").toDF("x", "y", "d").toPandas() def tuples(a): return (a, a, a) #lerps the density to a gray scale color df['d'] = (df['d'] / 600 * 255).astype(int) df['d'] = df['d'].apply(tuples) #creates a 501 * 501 white image img = Image.new( 'RGB', (501,501), "white") pixels = img.load() #goes through the df and colors the pixels for i in range(len(df['x'])): pixels[df['x'][i], df['y'][i]] = df['d'][i] imgplot = plt.imshow(img, origin='lower', vmin=0, vmax=600) The last step, iterating through the dataframe and coloring the pixels is the most time consuming (~16s), are there any alternatives that I can use? Thank you very much. UPDATE: In my code, instead of using [] operator, I used .at[] for indexing the pandas dataframe. The runtime is improved by 100% (~8s). However, I would still love to know how to improve it further.
tagged with: python-imaging-library
has title: What's a more efficient way to convert pandas dataframe to a bit map?
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
tagged with: numpy

http://stackoverflow.com/comment/90439526
type: Comment
has text: Are you on MAC or Linux? What OS are you on?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51727080

http://stackoverflow.com/comment/127051266
has text: For quarter you can do something like this: `SELECT datetime(DATE('2022-07-01'), printf('-%d month', (strftime('%m', DATE('2022-07-01')) - 1) % 3 + 1));`
comment on: http://stackoverflow.com/a/51666243
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51754112
upvote count: 1
type: Answer
downvote count: 0
has body: if you wanted to check all nested keys, you could create a loop function that checks the type of your looked up data and iterates over it if it is another dictionary, like def print_nested_keys(d): for k in d.keys(): print(k) if type(d[k]) == dict: print('nested dict detected - recursing...') print_nested_keys(d[k]) here, whenever one of the keys in your dictionary points to another dictionary, you call the function recursively to read through the lower-level dictionary keys. of course, you could always append the keys that you find in a list to return by your function in the end, if you want such a list.
answers question: http://stackoverflow.com/q/51753809
score: 1

http://stackoverflow.com/q/51778534
has answer: http://stackoverflow.com/a/51778572
has body: I've been learning neural networks from Michael Nielsen's http://neuralnetworksanddeeplearning.com/chap1.html. In the section below to update the weights and biases def update_mini_batch(self, mini_batch, eta): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) #Zero vectors nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): if test_data: n_test = len(test_data) n = len(training_data) for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] #### for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if test_data: print "Epoch {0}: {1} / {2}".format( j, self.evaluate(test_data), n_test) else: print "Epoch {0} complete".format(j) what is the need to introduce nabla_b and nabla_w zero vectors? when they're simply being added to the dnb and dnw which are numpy arrays themselves. Isn't 0 + something = something. What is the need for zero vector here for a single training example? As a test I removed the zero vector and had dnb and dnw by itself and I failed to see any significant difference in the training. Thank you.
type: Question
type: AnsweredQuestion
score: 3
has title: How does gradient descent weight/bias update work here?
tagged with: numpy
downvote count: 0
answer count: 1
tagged with: neural-network
favorite count: 0
upvote count: 3
tagged with: gradient-descent
accepted answer: http://stackoverflow.com/a/51778572
tagged with: python

http://stackoverflow.com/comment/90297173
comment on: http://stackoverflow.com/a/51666728
score: 0
type: AnswerComment
has text: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="019a8673-60aa-4b9f-825a-00b01ad36507"] This error pops up when I run it
type: Comment

http://stackoverflow.com/comment/90378283
has text: You put your string into `parseString` function which return a [_Document_](https://docs.python.org/3/library/xml.dom.minidom.html#xml.dom.minidom.parseString). Then you open your file in write mode and use `writexml` method on the _Document node_ and specify indent and addindent (_The `addindent` parameter is the incremental indentation to use for subnodes of the current one_)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51707553
type: Comment

http://stackoverflow.com/a/59986736
downvote count: 0
has body: This is how I solved the problem in my case: Import the Migrate model: from flask_migrate import Migrate Initiate Migrate class: migrate = Migrate(app, db) Comment db.create_all() Drop your database now =&gt; DROP DATABASE db_name; Create it again =&gt; CREATE DATABSE db_name OWNER owner_name; Export you flask entry file =&gt; export FLASK_APP=name_app.py Run flask db migrate Note: The 6th step should be used in case you get this error: Error: Could not locate a Flask application Hope this will help someone.
type: Answer
answers question: http://stackoverflow.com/q/51783300
has comment: http://stackoverflow.com/comment/118684872
upvote count: 12
score: 12

logging
tags question: http://stackoverflow.com/q/51710522
tags question: http://stackoverflow.com/q/51701662
tags question: http://stackoverflow.com/q/51737378
tags question: http://stackoverflow.com/q/51757004
tags question: http://stackoverflow.com/q/51734784
tags question: http://stackoverflow.com/q/51793604
tag name: logging
tags question: http://stackoverflow.com/q/51777830
tags question: http://stackoverflow.com/q/51678585
tags question: http://stackoverflow.com/q/51660431
tags question: http://stackoverflow.com/q/51698157
tags question: http://stackoverflow.com/q/51741536
tags question: http://stackoverflow.com/q/51724999
tags question: http://stackoverflow.com/q/51662409
tags question: http://stackoverflow.com/q/51719075
tags question: http://stackoverflow.com/q/51768850
tags question: http://stackoverflow.com/q/51721895
tags question: http://stackoverflow.com/q/51752447
tags question: http://stackoverflow.com/q/51707126
tags question: http://stackoverflow.com/q/51793723
tags question: http://stackoverflow.com/q/51783818
type: Tag
tags question: http://stackoverflow.com/q/51665352
tags question: http://stackoverflow.com/q/51658345

http://stackoverflow.com/a/51728032
answers question: http://stackoverflow.com/q/51689594
type: Answer
upvote count: 6
has body: Equivalent of Python 2.7 round() when rounding to an integer (one-parameter): import math def py2round(x): if x &gt;= 0.0: return math.floor(x + 0.5) else: return math.ceil(x - 0.5) Another option that is more succinct but more expensive for scalar values: def py2round(x): return int(math.copysign(math.floor(abs(x) + 0.5), x)) It is however much more performant for large vectors if math is replaced with numpy (but very slow for scalars): import numpy as np def py2round(x): return np.copysign(np.floor(abs(x) + 0.5), x).astype(int)
downvote count: 1
score: 5

http://stackoverflow.com/comment/90538747
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51790340
type: AnswerComment
has text: No problem will figure it out. Thank you so much for your response, it's really helpful. - @OlivierMelançon

http://stackoverflow.com/a/51748128
score: 11
has body: With zip we can achieve this. &gt;&gt;&gt; i_max = 5 &gt;&gt;&gt; j_max = 7 &gt;&gt;&gt; for i, j in zip(range(0, i_max), range(0, j_max)): ... print str(i) + ", " + str(j) ... 0, 0 1, 1 2, 2 3, 3 4, 4
accepted answer of: http://stackoverflow.com/q/51747961
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51747961
has comment: http://stackoverflow.com/comment/90456099
has comment: http://stackoverflow.com/comment/90456149
type: Answer
upvote count: 11

http://stackoverflow.com/a/51652587
type: Answer
answers question: http://stackoverflow.com/q/51652586
score: 2
upvote count: 2
has body: import hashlib import io class Sha256File: def __init__(self, fo, hashvalue): self._fo = fo self.hashvalue = hashvalue def __enter__(self): self._m = hashlib.sha256() return self def read(self, size=-1): b = self._fo.read(size) self._m.update(b) return b def __iter__(self): return self def __next__(self): b = self.read() if b == b'': raise StopIteration return b def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: assert self._m.hexdigest() == self.hashvalue self._fo.close() hashvalue = '5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03' with Sha256File(io.BytesIO(b'hello\n'), hashvalue) as f: for line in f: print(line)
downvote count: 0

http://stackoverflow.com/comment/90502098
score: 0
has text: @pguardiario I want to use the covenant functions provide by bs4 to deal with DOM tree, but it cannot execute xpath.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51748942

http://stackoverflow.com/comment/90403609
type: AnswerComment
type: Comment
has text: I increase the epoches from 10 to 50, the test accuracy reaches 85%.
comment on: http://stackoverflow.com/a/51719550
score: 0

http://stackoverflow.com/comment/108700763
score: 0
type: QuestionComment
type: Comment
has text: _I created a conda environment called tensorflow running Python 3.5, activated it and ran pip install --ignore-installed --upgrade tensorflow to install tensorflow._ Don't use pip in a Conda environment unless absolutely necessary, see for example https://www.anaconda.com/using-pip-in-a-conda-environment
comment on: http://stackoverflow.com/q/51753825

http://stackoverflow.com/comment/90474531
type: QuestionComment
type: Comment
has text: besides removing `%i` in `Popen`, have you tried using f-strings (literal string interpolation)?
comment on: http://stackoverflow.com/q/51757402
score: 0

http://stackoverflow.com/comment/90344098
score: 0
type: AnswerComment
has text: @lenik My idea is to get the longest lowest, which means the longest sequence with the lowest numbers in the array... the priority is the length
comment on: http://stackoverflow.com/a/51682637
type: Comment

http://stackoverflow.com/q/51793690
tagged with: c++
answer count: 0
type: UnansweredQuestion
has title: Call c++ template function from cython
tagged with: python
score: 1
tagged with: cython
type: Question
has comment: http://stackoverflow.com/comment/90551796
linked to: http://stackoverflow.com/q/41190519
upvote count: 1
downvote count: 0
favorite count: 0
has body: Currently, I am learning how to call c++ template function from Cython. I have a .h file named 'cos_doubles.h' The file is as follows: #ifndef _COS_DOUBLES_H #define _COS_DOUBLES_H #include &lt;math.h&gt; template &lt;typename T, int ACCURACY&gt; void cos_doubles(T * in_array, T * out_array, int size) { int i; for(i=0;i&lt;size;i++){ out_array[i] = in_array[i] * 2; } } #endif Indeed the variable ACCURACY does nothing. Now, I want to define a template function in cython that use this cos_doubles function, but only has the typename T as a template. In other words, I want to give the variable ACCURACY a value in my cython code. My .pyx code is some thing like the following # import both numpy and the Cython declarations for numpy import numpy as np cimport numpy as np cimport cython # if you want to use the Numpy-C-API from Cython # (not strictly necessary for this example) np.import_array() # cdefine the signature of our c function cdef extern from "cos_doubles.h": void cos_doubles[T](T* in_array, T* out_array, int size) I know this code has errors, because I did not define the variable of ACCURACY in void cos_doubles[T](T* in_array, T* out_array, int size). But I do not know the gramma how to set it. For example, I want to let ACCURACY = 4. Can anyone tell me how to do this ? One solution I already have is cdef void cos_doubles1 "cos_doubles&lt;double, 4&gt;"(double * in_array, double * out_array, int size) cdef void cos_doubles2 "cos_doubles&lt;int, 4&gt;"(int * in_array, int * out_array, int size) but I do not define two different functions. Is there any better solution?

http://stackoverflow.com/comment/90341692
type: Comment
type: QuestionComment
has text: @Bazingaa That gives you an NxN matrix filled with zeroes. Same as student's.
score: 0
comment on: http://stackoverflow.com/q/51689901

http://stackoverflow.com/q/51678591
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51679336
has answer: http://stackoverflow.com/a/51679336
has body: back again with another question. Preface: built a GUI with Qt Designer, a search button, parsing csv data, and building my TableWidget with the found data. I have a file that has two results that are similar, for instance, one location is labeled Reddit (North) and Reddit (South). If I search for Reddit, only the first result shows, but when I press the Search button again, it only shows the first find, not the second. Question: How do I stop the csv reader at the first match, fill in the table with the data it found from the first hit, then hit the search button again to clear the first hit and display the second hit? def search(self): self.table_search.setRowCount(6) self.table_search.setColumnCount(1) self.table_search.verticalHeader().setDefaultSectionSize(20) self.table_search.verticalHeader().setVisible(True) self.table_search.setVerticalHeaderLabels([ 'Location ID:', 'Location Name:', 'Cost Center:', 'Street Address:', 'City:', 'State:'] ) # taking input from a PyQt line edit box search = self.lineedit_locsearch.text() search_string = search.strip().upper() # stripping white space from the string # containers for specific data from the csv file locid = '' locname = '' loccost = '' locaddress = '' loccity = '' locstate = '' with open('data/loc.csv', "r") as locdata: reader = csv.reader(locdata) for row in reader: for field in row: if field == search_string: locid = row[0] locname = row[1] loccost = row[2] locaddress = row[3] loccity = row[4] locstate = row[5] locdata.close() self.table_locsearch.setItem(0, 0, QtWidgets.QTableWidgetItem(locid)) self.table_locsearch.setItem(1, 0, QtWidgets.QTableWidgetItem(locname)) self.table_locsearch.setItem(2, 0, QtWidgets.QTableWidgetItem(loccost)) self.table_locsearch.setItem(3, 0, QtWidgets.QTableWidgetItem(locaddress)) self.table_locsearch.setItem(4, 0, QtWidgets.QTableWidgetItem(loccity)) self.table_locsearch.setItem(5, 0, QtWidgets.QTableWidgetItem(locstate))
score: 0
has title: Python CSV Reader search string found matches
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51679241
accepted answer: http://stackoverflow.com/a/51679241

http://stackoverflow.com/q/51702899
has title: Alpha Vantage stockinfo only collects 4 dfs properly formatted, not 6
tagged with: python
has body: I can get 4 tickers of stockinfo from Alpha Vantage before the rest of the DataFrames are not getting the stockinfo I ask for. So my resulting concatenated df gets interpreted as Nonetype (because the 4 first dfs are formatted differently than the last 2). This is not my problem. The fact that I only get 4 of my requests is... If I can fix that - the resulting concatenated df will be intact. My code import pandas as pd import datetime import requests from alpha_vantage.timeseries import TimeSeries import time tickers = [] def alvan_csv(stocklist): api_key = 'demo' # For use with Alpha Vantage stock-info retrieval. for ticker in stocklist: #data=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&amp;symbol=%s&amp;apikey={}'.format(api_key) %(ticker)) df = pd.read_csv('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&amp;datatype=csv&amp;symbol=%s&amp;apikey={}'.format(api_key) %(ticker))#, index_col = 0) &amp;outputsize=full df['ticker'] = ticker tickers.append(df) # concatenate all the dfs df = pd.concat(tickers) print('\ndata before json parsing for === %s ===\n%s' %(ticker,df)) df['adj_close'] = df['adjusted_close'] del df['adjusted_close'] df['date'] = df['timestamp'] del df['timestamp'] df = df'date','ticker','adj_close','volume','dividend_amount','split_coefficient','open','high','low' # df=df.sort_values(['ticker','date'], inplace=True) time.sleep(20.3) print('\ndata after col reshaping for === %s ===\n%s' %(ticker,df)) return df if __name__ == '__main__': stocklist = ['vws.co','nflx','mmm','abt','msft','aapl'] df = alvan_csv(stocklist) NB. Please note that to use the Alpha Vantage API, you need a free API-Key which you may optain here: https://www.alphavantage.co/support/#api-key Replace the demo API Key with your API Key to make this code work. Any ideas as to get this to work?
has answer: http://stackoverflow.com/a/52023884
accepted answer: http://stackoverflow.com/a/52023884
tagged with: alpha-vantage
type: AnsweredQuestion
tagged with: stockquotes
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/90366718
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/51712693
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/60866026
has comment: http://stackoverflow.com/comment/90961785
answer count: 16
tagged with: conda
has body: conda update conda >> successful conda update anaconda >> gives me error saying package is not installed in prefix. I have single installation of Python distribution on my system. How do I solve this issue? (base) C:\Users\asukumari&gt;conda info active environment : base active env location : C:\Users\asukumari\AppData\Local\Continuum\anaconda3 shell level : 1 user config file : C:\Users\asukumari\.condarc populated config files : C:\Users\asukumari\.condarc conda version : 4.5.9 conda-build version : 3.4.1 python version : 3.6.4.final.0 base environment : C:\Users\asukumari\AppData\Local\Continuum\anaconda3 (writable) channel URLs : https://repo.anaconda.com/pkgs/main/win-64 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/free/win-64 https://repo.anaconda.com/pkgs/free/noarch https://repo.anaconda.com/pkgs/r/win-64 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/pro/win-64 https://repo.anaconda.com/pkgs/pro/noarch https://repo.anaconda.com/pkgs/msys2/win-64 https://repo.anaconda.com/pkgs/msys2/noarch package cache : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\pkgs C:\Users\asukumari\AppData\Local\conda\conda\pkgs envs directories : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\envs C:\Users\asukumari\AppData\Local\conda\conda\envs C:\Users\asukumari\.conda\envs platform : win-64 user-agent : conda/4.5.9 requests/2.18.4 CPython/3.6.4 Windows/10 Windows/10.0.16299 administrator : False netrc file : None offline mode : False
has answer: http://stackoverflow.com/a/78925189
has answer: http://stackoverflow.com/a/70806093
has answer: http://stackoverflow.com/a/74380232
linked to: http://stackoverflow.com/q/77617946
has comment: http://stackoverflow.com/comment/90632082
favorite count: 0
score: 95
tagged with: python-3.x
has answer: http://stackoverflow.com/a/71085376
has answer: http://stackoverflow.com/a/60371514
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/60325485
has answer: http://stackoverflow.com/a/77369848
has answer: http://stackoverflow.com/a/78130182
accepted answer: http://stackoverflow.com/a/56758687
has comment: http://stackoverflow.com/comment/90642720
has comment: http://stackoverflow.com/comment/124263322
has comment: http://stackoverflow.com/comment/131290537
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/76095493
has answer: http://stackoverflow.com/a/79537381
possible better answer: http://stackoverflow.com/a/53637013
has comment: http://stackoverflow.com/comment/131309157
has answer: http://stackoverflow.com/a/74238190
has answer: http://stackoverflow.com/a/59133861
has answer: http://stackoverflow.com/a/53637013
has title: PackageNotInstalledError: Package is not installed in prefix
has answer: http://stackoverflow.com/a/79021439
has answer: http://stackoverflow.com/a/56758687
upvote count: 95

http://stackoverflow.com/comment/90449447
type: Comment
type: QuestionComment
has text: That complicates workflow. Instead of `python foo.py` user would have to think about pip.
comment on: http://stackoverflow.com/q/51743789
score: 0

http://stackoverflow.com/q/51700452
score: 1
favorite count: 0
tagged with: python-3.x
has body: My dataset looks like this, Col1 Col2 Col3 A 10 x1 B 100 x2 C 1000 x3 This is what I want my output to look like, Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 A 10 x1 Empty Empty Empty Empty Empty Empty B 100 x2 Empty Empty Empty Empty Empty Empty C 1000 x3 Empty Empty Empty Empty Empty Empty A 10 x1 B 100 x2 Empty Empty Empty B 100 x2 C 1000 x3 Empty Empty Empty A 10 x1 B 100 x2 C 1000 x3 I can get the various combinations of A,B,C with itertools.combinations but how do I get this table?
accepted answer: http://stackoverflow.com/a/51700509
tagged with: python
type: AnsweredQuestion
has title: Pandas combinations with format
upvote count: 1
type: Question
tagged with: python-itertools
downvote count: 0
has answer: http://stackoverflow.com/a/51700509
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

matplotlib
tags question: http://stackoverflow.com/q/51657157
tags question: http://stackoverflow.com/q/51787097
tags question: http://stackoverflow.com/q/51654037
tags question: http://stackoverflow.com/q/51658832
tags question: http://stackoverflow.com/q/51733904
tags question: http://stackoverflow.com/q/51765184
tags question: http://stackoverflow.com/q/51738460
tags question: http://stackoverflow.com/q/51734218
tags question: http://stackoverflow.com/q/51785007
tags question: http://stackoverflow.com/q/51675940
tags question: http://stackoverflow.com/q/51713123
tags question: http://stackoverflow.com/q/51641022
tags question: http://stackoverflow.com/q/51730950
tags question: http://stackoverflow.com/q/51741786
tags question: http://stackoverflow.com/q/51674388
tags question: http://stackoverflow.com/q/51669135
tags question: http://stackoverflow.com/q/51761210
tags question: http://stackoverflow.com/q/51666784
tags question: http://stackoverflow.com/q/51779728
tags question: http://stackoverflow.com/q/51751965
tags question: http://stackoverflow.com/q/51746400
tags question: http://stackoverflow.com/q/51695911
tags question: http://stackoverflow.com/q/51705314
tags question: http://stackoverflow.com/q/51680405
tags question: http://stackoverflow.com/q/51733742
tags question: http://stackoverflow.com/q/51758845
tags question: http://stackoverflow.com/q/51732577
tags question: http://stackoverflow.com/q/51784604
tags question: http://stackoverflow.com/q/51726978
tag name: matplotlib
tags question: http://stackoverflow.com/q/51667240
tags question: http://stackoverflow.com/q/51749208
tags question: http://stackoverflow.com/q/51696441
tags question: http://stackoverflow.com/q/51685078
tags question: http://stackoverflow.com/q/51750663
tags question: http://stackoverflow.com/q/51796490
tags question: http://stackoverflow.com/q/51692299
tags question: http://stackoverflow.com/q/51672938
tags question: http://stackoverflow.com/q/51726081
tags question: http://stackoverflow.com/q/51687502
tags question: http://stackoverflow.com/q/51741591
tags question: http://stackoverflow.com/q/51743483
tags question: http://stackoverflow.com/q/51687305
tags question: http://stackoverflow.com/q/51692823
tags question: http://stackoverflow.com/q/51713305
tags question: http://stackoverflow.com/q/51731351
tags question: http://stackoverflow.com/q/51685993
tags question: http://stackoverflow.com/q/51788767
tags question: http://stackoverflow.com/q/51780513
tags question: http://stackoverflow.com/q/51790062
tags question: http://stackoverflow.com/q/51742886
tags question: http://stackoverflow.com/q/51703845
tags question: http://stackoverflow.com/q/51649816
tags question: http://stackoverflow.com/q/51672643
tags question: http://stackoverflow.com/q/51647923
tags question: http://stackoverflow.com/q/51777217
tags question: http://stackoverflow.com/q/51717881
tags question: http://stackoverflow.com/q/51737205
tags question: http://stackoverflow.com/q/51734973
tags question: http://stackoverflow.com/q/51642660
tags question: http://stackoverflow.com/q/51791042
tags question: http://stackoverflow.com/q/51709652
tags question: http://stackoverflow.com/q/51784854
tags question: http://stackoverflow.com/q/51716914
tags question: http://stackoverflow.com/q/51660271
tags question: http://stackoverflow.com/q/51720829
tags question: http://stackoverflow.com/q/51751954
tags question: http://stackoverflow.com/q/51658392
tags question: http://stackoverflow.com/q/51712916
tags question: http://stackoverflow.com/q/51766031
tags question: http://stackoverflow.com/q/51667449
tags question: http://stackoverflow.com/q/51685200
tags question: http://stackoverflow.com/q/51742468
tags question: http://stackoverflow.com/q/51663834
tags question: http://stackoverflow.com/q/51795521
tags question: http://stackoverflow.com/q/51752085
tags question: http://stackoverflow.com/q/51733298
tags question: http://stackoverflow.com/q/51794078
tags question: http://stackoverflow.com/q/51759921
tags question: http://stackoverflow.com/q/51787812

http://stackoverflow.com/q/51678077
tagged with: beautifulsoup
has title: Cron with beautifulsoup not running
type: Question
tagged with: cron
has comment: http://stackoverflow.com/comment/90323605
tagged with: python
accepted answer: http://stackoverflow.com/a/51678310
score: 0
answer count: 1
has body: Python file runs properly when executed from terminal. Gives error "ImportError: No module named bs4" when run with cron. I'm running python3.6 from /anaconda3/lib/python3.6 python3.6 &gt;&gt;&gt; from crontab import CronTab &gt;&gt;&gt; cron = CronTab(user=True) &gt;&gt;&gt; job = cron.new(command='python /Users/X/Y/Z/Hello.py') &gt;&gt;&gt; job.minute.every(1) &gt;&gt;&gt; cron.write() Hello.py calls beautifulsoup from bs4, which is in /anaconda3/lib/python3.6/site-packages/bs4/ Cron details are: X-Cron-Env: &lt;SHELL=/bin/sh&gt; X-Cron-Env: &lt;PATH=/usr/bin:/bin&gt;
has answer: http://stackoverflow.com/a/51678310
type: AnsweredQuestion

http://stackoverflow.com/comment/90319139
has text: It's simple mathematics: `index = (pos*2)` with base pos = 1. So first byte is `pos=1` and hence `index=2` in a zero-based array.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51677943

http://stackoverflow.com/comment/90473782
score: 0
type: AnswerComment
has text: I'm using Python 3.6.4
comment on: http://stackoverflow.com/a/51753442
type: Comment

http://stackoverflow.com/a/52128093
has comment: http://stackoverflow.com/comment/104254983
downvote count: 0
has comment: http://stackoverflow.com/comment/115563687
has comment: http://stackoverflow.com/comment/109064010
type: Answer
upvote count: 13
score: 13
has comment: http://stackoverflow.com/comment/95287198
has comment: http://stackoverflow.com/comment/97964547
has body: Use it like this: pytesseract.image_to_string(img, config='-c preserve_interword_spaces=1')
answers question: http://stackoverflow.com/q/51668339

http://stackoverflow.com/comment/90331530
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51684295
has text: I did not know that about `&` and `|` with numpy, thank you @PM2Ring
score: 0

http://stackoverflow.com/comment/90426913
type: Comment
score: 1
has text: Damn my eyes! Nevertheless that information is already included in the answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/51732593

http://stackoverflow.com/q/51665542
has answer: http://stackoverflow.com/a/51666749
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51665640
type: Question
possible better answer: http://stackoverflow.com/a/51665687
has answer: http://stackoverflow.com/a/51665687
has answer: http://stackoverflow.com/a/51665933
has body: I have two lists- master.txt and a subset of it, child.txt. I want to print the edges in master.txt which are NOT there in child.txt master.txt A B B C D F child.txt B A C B E F output: D F I have written a sample code file1 = open("master.txt", "r") file2 = open("child.txt", "r") probe_id = file1.readlines() loc_names = file2.readlines()` #flag=0 for i in probe_id: i=i.rstrip() probe_info=i.split("\t") probe_info[0]=probe_info[0].strip() probe_info[1]=probe_info[1].strip() flag=0 for j in loc_names: j=j.strip() loc_names=j.split("\t") loc_names[0]=loc_names[0].strip() loc_names[1]=loc_names[1].strip() #throwing index out of range error if (probe_info[0]==loc_names[0] and probe_info[1]==loc_names[1]) or (probe_info[0]==loc_names[1] and probe_info[1]==loc_names[0]): flag=1 if flag==0: print i As of now, I am getting index out of range when I am splitting the smaller file. Kindly help. Also, if there is any other faster technique to do the same thing, pls let me know. Thanks
downvote count: 0
tagged with: awk
favorite count: 0
has answer: http://stackoverflow.com/a/51665640
has comment: http://stackoverflow.com/comment/90294861
has title: Comparing two network edge lists
answer count: 5
has answer: http://stackoverflow.com/a/51665835
tagged with: python
has comment: http://stackoverflow.com/comment/90294483

http://stackoverflow.com/q/51729964
has comment: http://stackoverflow.com/comment/90420649
tagged with: python
has comment: http://stackoverflow.com/comment/90420622
type: AnsweredQuestion
has body: So I just started learning python and I picked up a book that is written in python 2 but I am using python3.6 to compile. So I am not very familiar with the differences. When I wrote this movies={} for line in open (path+'/u.item'): (id,title)=line.split('|')[0:2] movies[id]=title I get this error (id,title)=line.split('|')[0:2] TypeError: list indices must be integers or slices, not float I'm not quite sure what (id,title)=line.split("|")[0:2] is doing. Please help me understand.
type: Question
score: 4
has comment: http://stackoverflow.com/comment/90421091
upvote count: 4
tagged with: python-2.7
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90420845
has comment: http://stackoverflow.com/comment/90420762
has answer: http://stackoverflow.com/a/51730283
accepted answer: http://stackoverflow.com/a/51730283
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90420970
has title: What does (id,title)=line.split('|')[0:2] do?

http://stackoverflow.com/comment/90467419
type: QuestionComment
score: 3
has text: Why do you think it is supposed to return nested keys? `dict.keys()` method doesn't do that.
comment on: http://stackoverflow.com/q/51753809
type: Comment

http://stackoverflow.com/q/51758428
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51758575
type: AnsweredQuestion
score: 2
has body: I want to insert multiple records using json like this: posts = [{ "title": "First Post", "user_id": 1 }, { "title": "Second Post", "user_id": 2 }] How do you save posts like this way?: post = Post(title=posts.title, user_id=posts.user_id) db.session.add(post) db.session.commit() I am using flask 1.0.2 and Python 3.6.6.
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/51758575
has title: How to insert multiple records using JSON in SQLAlchemy
tagged with: python-3.6
answer count: 1
downvote count: 0
tagged with: flask-sqlalchemy

http://stackoverflow.com/q/51656951
has answer: http://stackoverflow.com/a/51660194
favorite count: 0
type: Question
has title: jupyter-notebook's top toolbar doesn't work
score: -2
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/90277744
downvote count: 2
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90277742
upvote count: 0
has body: I push that buttons but anything happened. I downloaded jupyter notebook again, but still it is not working.
type: UnansweredQuestion

http://stackoverflow.com/q/51641651
has title: Linking Mulit User Profile Together
has answer: http://stackoverflow.com/a/51642117
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/51642117
type: AnsweredQuestion
has body: So i have this Accounts where I have two types of users example: intern, and HR Supervisor. So my models is class User(AbstractUser): is_intern = models.BooleanField(default=True) class InternProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='intern_profile') bio = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) SuperVisor= models.ForeignKey(HRProfile, null=True, related_name='employee') class HRProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='hr_profile') company_name = models.CharField(max_length=100, blank=True) website = models.CharField(max_length=100, blank=True) Now lets suppose i have two HR managers name Alice and Bob. Both Alice and Bob have three interns underneath them working, lets say Sam, David, Katty works under Alice and Drake, Taylor and Nik works under Bob. Now I want to Bob to see only his intern and Alice can only see her intern not other way round, so guys i m new and learning django any advice related to this , cause i cant able to find the way around this. Thank you
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/comment/90344018
comment on: http://stackoverflow.com/q/51690935
has text: Low cyclomatic complexity is not necessarily related with code length. If you are trying to reduce the code length by using one-letter variable names, please don't, that makes your code hard to read. Instead of using comments all over the place try to come up with good names.
score: 4
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51747403
favorite count: 0
score: 4
has answer: http://stackoverflow.com/a/51747525
has title: How to write to stdout after redirecting FD
has comment: http://stackoverflow.com/comment/90455108
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51747525
tagged with: stdout
upvote count: 4
has comment: http://stackoverflow.com/comment/90454868
has body: Please take a look at this python code below. so = open('/tmp/test.log', 'a+') os.dup2(so.fileno(), sys.stdout.fileno()) After executing that piece of code I would like to still have possibility to print something on standard stdout. I already tried: print('Foo\n', file=sys.__stdout__) As according to documentation could be a way to go. sys.__stdin__ sys.__stdout__ sys.__stderr__ These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected. But it's not in that case. Its still logging to my test.log file. Python version: 3.4.8 Any help would be greatly appreciated.
downvote count: 0
has comment: http://stackoverflow.com/comment/90454827
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/q/51729136
has answer: http://stackoverflow.com/a/51730099
tagged with: python
tagged with: regex
type: AnsweredQuestion
type: Question
has title: Parsing an IP adress in a logfile in python 3
has body: I'm quite new to python and I'm trying to (using python 3) go through a number of large custom log files to extract parameters from certain GET requests an try to collect some statistics from them. I got kind of far but I got stuck with two questions that me and my colleague could not figure out why they were giving us such headache. I will post the two questions separately to not confuse you. My log file looks like this: 80 172.23.131.149 "2018-07-05 13:08:25 860" "POST /bios/servlet/bios.servlets.sso.WaffleLoginServlet HTTP/1.1" 401 5 891 891 "-" "Java/1.8.0_171" 8080 172.23.131.251 "2018-07-05 13:08:26 594" "HEAD /bios/servlet/bios.servlets.web.Ping?level=3 HTTP/1.0" 200 - 1953 1953 "-" "-" 8080 172.23.131.252 "2018-07-05 13:08:26 594" "HEAD /bios/servlet/bios.servlets.web.Ping?level=3 HTTP/1.0" 200 - 953 953 "-" "-" 80 172.23.131.149 "2018-07-05 13:08:28 188" "GET /bios/wms/app/baggis/web/WMS_STHLM_STOCKHOLMSKARTA_HYBRID_INTERN?TILED=TRUE&amp;SERVICE=WMS&amp;VERSION=1.1.1&amp;REQUEST=GetMap&amp;FORMAT=image%2Fpng&amp;TRANSPARENT=false&amp;LAYERS=p_1002095&amp;SRS=EPSG%3A3011&amp;STYLES=&amp;r=n2q&amp;WIDTH=256&amp;HEIGHT=256&amp;BBOX=156240.234375%2C6576777.34375%2C156269.53125%2C6576806.640625 HTTP/1.1" 200 133210 3547 3516 "http://tkkarta3.stockholm.se/astolmap/v3/kopplet/tkkarta.htm" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" 80 172.23.131.149 "2018-07-05 13:08:28 188" "GET /bios/wms/app/baggis/web/WMS_STHLM_STOCKHOLMSKARTA_HYBRID_INTERN?TILED=TRUE&amp;SERVICE=WMS&amp;VERSION=1.1.1&amp;REQUEST=GetMap&amp;FORMAT=image%2Fpng&amp;TRANSPARENT=false&amp;LAYERS=p_1002095&amp;SRS=EPSG%3A3011&amp;STYLES=&amp;r=n2q&amp;WIDTH=256&amp;HEIGHT=256&amp;BBOX=156240.234375%2C6576748.046875%2C156269.53125%2C6576777.34375 HTTP/1.1" 200 108066 3547 3532 "http://tkkarta3.stockholm.se/astolmap/v3/kopplet/tkkarta.htm" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133…
possible better answer: http://stackoverflow.com/a/51730099
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90419133
tagged with: parsing
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51729921
accepted answer: http://stackoverflow.com/a/51729921

http://stackoverflow.com/q/51766367
has answer: http://stackoverflow.com/a/51767448
accepted answer: http://stackoverflow.com/a/51767448
type: AnsweredQuestion
has body: I am trying to parse out a database with certain definitions. A definition is essentially a string with IDs and relationships between them. For example: (A,((B,C) (D,E))) F where a space means AND and a comma means OR. Based on the definitions I want to make lists of possible combinations. In this example the possible combinations would be: [A,F] [B,D,F] [B,E,F] [C,D,F] [C,E,F] I tried filtering out groups between parentheses using regular expresssions and to make a tree structure that would fit F as the root and make leafs based on the other possibilities, but it failed especially on more complex examples. One of the most complex examples will be: (K01647,K05942) (K01681,K01682) (K00031,K00030) (K00164+K00658+K00382,K00174+K00175-K00177-K00176) (K01902+K01903,K01899+K01900,K18118) (K00234+K00235+K00236+K00237,K00239+K00240+K00241-(K00242,K18859,K18860),K00244+K00245+K00246-K00247) (K01676,K01679,K01677+K01678) (K00026,K00025,K00024,K00116) Any suggestions would be greatly appreciated.
has comment: http://stackoverflow.com/comment/90517920
has comment: http://stackoverflow.com/comment/90492025
type: Question
has comment: http://stackoverflow.com/comment/90493168
has comment: http://stackoverflow.com/comment/90493908
has comment: http://stackoverflow.com/comment/90492114
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: string
favorite count: 0
tagged with: parsing
has title: Parsing complex strings
has comment: http://stackoverflow.com/comment/90493453
tagged with: python
has comment: http://stackoverflow.com/comment/90491762

http://stackoverflow.com/q/51726577
tagged with: pandas
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90413512
favorite count: 0
has body: I downloaded the pandas package to my computer using the pip install. When I try to import pandas as pd into Pycharm I get the following error message: ModuleNotFoundError: No module named 'pandas' I know I have downloaded the package, but how do I get Pycharm to recognize that I have downloaded the package?
tagged with: pycharm
type: UnansweredQuestion
score: -4
has title: Downloaded Pandas, but getting error when importing into Pycharm
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/90413509
upvote count: 0
has answer: http://stackoverflow.com/a/51726763

http://stackoverflow.com/q/51795002
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51795606
has title: Appending to a specific row in a numpy array
has body: I am trying to append a number to a particular row of a 2D numpy array. I did the following but it doesn't work right: onspiketimes=np.array([[] for i in range(9)]) neurs = [3, 4, 8, 2] onspiketimes[neurs]=2 &gt;&gt;&gt; onspiketimes array([], shape=(9, 0), dtype=float64) As you can see that nothing got appended,onspiketimes still remains empty. However I could do this with list of lists as below: &gt;&gt;&gt; onspiketimes= [[] for i in range(9)] &gt;&gt;&gt; for items in neurs: onspiketimes[items].append(2) &gt;&gt;&gt; for items in neurs: onspiketimes[items].append(3) &gt;&gt;&gt; onspiketimes [[], [], [2, 3], [2, 3], [2, 3], [], [], [], [2, 3]] This is a contrived example, I can't really compare numpy and lists here but in my real applications for loops will really effect the speedup. I was hoping to solve this using array slicing in numpy.
has answer: http://stackoverflow.com/a/51795623
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90547584
downvote count: 0
has comment: http://stackoverflow.com/comment/90547622
score: 1
has comment: http://stackoverflow.com/comment/90547653
favorite count: 0
has comment: http://stackoverflow.com/comment/90547848
has comment: http://stackoverflow.com/comment/90547544
type: UnansweredQuestion

http://stackoverflow.com/q/51711953
has answer: http://stackoverflow.com/a/51714192
accepted answer: http://stackoverflow.com/a/51713978
favorite count: 0
tagged with: dask
upvote count: 2
has comment: http://stackoverflow.com/comment/90389196
tagged with: python
score: 2
type: AnsweredQuestion
has title: Creating Dask delays with Lock. Error: _thread._local has no execution_state
type: Question
has answer: http://stackoverflow.com/a/51713978
linked to: http://stackoverflow.com/q/51696684
answer count: 2
has comment: http://stackoverflow.com/comment/90388726
has body: I want to create a Dask array with multiple blocks. Each block is from a function that reads a file. To avoid reading multiple files from the hard disk at the same time, I follow the answer here and use a lock. But creating the dealays give the following error: AttributeError: '_thread._local' object has no attribute 'execution_state' Test: import numpy as np import dask import distributed def make_test_data(): n = 2 m = 3 x = np.arange(n * m, dtype=np.int).reshape(n, m) np.save('0.npy', x) np.save('1.npy', x) shape = (n, m) return shape @dask.delayed def load_numpy(lock, fn): lock.acquire() out = np.load(fn) lock.release() return out def make_delayed(): # np.load is a function that reads a file # and returns a numpy array. read_lock = distributed.Lock('numpy-read') return [load_numpy(read_lock, '%d.npy' % i) for i in range(2)] def main(): shape = make_test_data() ds = make_delayed() main() Complete error message: Traceback (most recent call last): File "&lt;...&gt;/site-packages/distributed/worker.py", line 2536, in get_worker return thread_state.execution_state['worker'] AttributeError: '_thread._local' object has no attribute 'execution_state' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test_lock.py", line 32, in &lt;module&gt; main() File "test_lock.py", line 30, in main ds = make_delayed() File "test_lock.py", line 25, in make_delayed read_lock = distributed.Lock('numpy-read') File "&lt;...&gt;/site-packages/distributed/lock.py", line 92, in __init__ self.client = client or _get_global_client() or get_worker().client File "&lt;...&gt;/site-packages/distributed/worker.py", line 2542, in get_worker raise ValueError("No workers found") ValueError: No workers found
downvote count: 0
possible better answer: http://stackoverflow.com/a/51714192

http://stackoverflow.com/comment/90377276
has text: you need a constructor
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51708044

http://stackoverflow.com/a/51786440
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51786324
upvote count: 1
has body: Your solution is good actually, with a slight (big!) detail of efficiency: Use 1&lt;&lt;i (bitwise shift) instead of 2**i So, to copy you, consider the following : def two_powers(num): return set(1 &lt;&lt; i for i, j in enumerate(bin(num)[-1: 1: -1]) if j == '1') print two_powers(42)

http://stackoverflow.com/comment/90320184
type: Comment
has text: I edited and tested your loop. Try this version out - replace the stubs with your actual data.
comment on: http://stackoverflow.com/a/51644990
type: AnswerComment
score: 0

http://stackoverflow.com/a/51751033
upvote count: 1
downvote count: 1
has body: Wouldn't my_arr = array[:,1,1,1] do the trick much more efficiently?
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51750872
answers question: http://stackoverflow.com/q/51750872

similarity
tags question: http://stackoverflow.com/q/51681659
tags question: http://stackoverflow.com/q/51651934
tags question: http://stackoverflow.com/q/51785335
tag name: similarity
type: Tag

http://stackoverflow.com/a/51735300
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51734958
type: Answer
accepted answer of: http://stackoverflow.com/q/51734958
has body: Not exactly sure what you're asking, but if you mean to have lists 1, 2, ..., n then an integer i and you want to get the i'th list, simply have a list of lists and index the outer list with the integer i (in your case called band). l = [data_w1, data_w2, data_w3] list_to_operate_on = l[band] func(list_to_operate_on)

http://stackoverflow.com/q/51758417
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/51758587
tagged with: pandas
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51758587
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51758486
has comment: http://stackoverflow.com/comment/90476124
type: Question
has title: Python Selecting and Adding row values of columns in dataframe to create an aggregated dataframe
has answer: http://stackoverflow.com/a/51758486
tagged with: dataframe
has body: I need to process my dataframe in Python such that I add the numeric values of numeric columns that lie between 2 rows of the dataframe. The dataframe can be created using df = pd.DataFrame(np.array([['a',0,1,0,0,0,0,'i'], ['b',1,0,0,0,0,0,'j'], ['c',0,0,1,0,0,0,'k'], ['None',0,0,0,1,0,0,'l'], ['e',0,0,0,0,1,0,'m'], ['f',0,1,0,0,0,0,'n'], ['None',0,0,0,1,0,0,'o'], ['h',0,0,0,0,1,0,'p']]), columns=[0,1,2,3,4,5,6,7], index=[0,1,2,3,4,5,6,7]) I need to add all rows that occur before the 'None' entries and move the aggregated row to a new dataframe that should look like:
score: -1

http://stackoverflow.com/comment/90504708
score: 0
has text: No, because I'm just rebinding the name. `TempFile` subclasses whatever class `tempfile._TemporaryFileWrapper` *used* to reference.
type: Comment
comment on: http://stackoverflow.com/a/51766897
type: AnswerComment

http://stackoverflow.com/q/51691563
has answer: http://stackoverflow.com/a/73042517
answer count: 16
has comment: http://stackoverflow.com/comment/90346450
has answer: http://stackoverflow.com/a/64249410
has answer: http://stackoverflow.com/a/72431312
has answer: http://stackoverflow.com/a/63952018
has answer: http://stackoverflow.com/a/78928939
downvote count: 0
has answer: http://stackoverflow.com/a/51701698
possible better answer: http://stackoverflow.com/a/55272357
favorite count: 0
has comment: http://stackoverflow.com/comment/90346653
has answer: http://stackoverflow.com/a/78579884
linked to: http://stackoverflow.com/q/55780923
upvote count: 97
tagged with: python
has answer: http://stackoverflow.com/a/68868647
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72056576
has comment: http://stackoverflow.com/comment/90345971
has answer: http://stackoverflow.com/a/66092315
tagged with: pytorch
has answer: http://stackoverflow.com/a/72195341
has answer: http://stackoverflow.com/a/78560173
has comment: http://stackoverflow.com/comment/90346497
has answer: http://stackoverflow.com/a/55272357
has body: THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generated/../generic/THCTensorMathPointwise.cu line=265 error=59 : device-side assert triggered Traceback (most recent call last): File "main.py", line 109, in <module> train(loader_train, model, criterion, optimizer) File "main.py", line 54, in train optimizer.step() File "/usr/local/anaconda35/lib/python3.6/site-packages/torch/optim/sgd.py", line 93, in step d_p.add_(weight_decay, p.data) RuntimeError: cuda runtime error (59) : device-side assert triggered at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generated/../generic/THCTensorMathPointwise.cu:265 How do I resolve this error?
type: Question
has comment: http://stackoverflow.com/comment/90346591
score: 97
has answer: http://stackoverflow.com/a/76325734
has comment: http://stackoverflow.com/comment/106932165
has answer: http://stackoverflow.com/a/77971703
has answer: http://stackoverflow.com/a/72662286
has title: CUDA runtime error (59) : device-side assert triggered
accepted answer: http://stackoverflow.com/a/51701698

http://stackoverflow.com/a/51696335
has body: Erosion is a rather costly operation. You can try scipy's implementation. I'm not sure how it is implemented. If you end up using it, please get back with a performance update :).
answers question: http://stackoverflow.com/q/51695747
score: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51695747

http://stackoverflow.com/a/51770697
answers question: http://stackoverflow.com/q/51711450
has body: All detector/descriptor classes have methods to get the features or descriptors only. But you can't combine all extractors with all descriptors. Descriptors may need some Special Infos provided by the feature detector. The find-object program (https://introlab.github.io/find-object/) is a nice testbed for testing detector/descriptor pairs.
score: 0
type: Answer

http://stackoverflow.com/comment/90450216
type: Comment
has text: Yes. I've added in my edit what I mean. Also, I'm still getting the `TypeError: unsupported type for timedelta hours component: IntegerField` on your `save()` function.
comment on: http://stackoverflow.com/a/51745203
type: AnswerComment
score: 0

http://stackoverflow.com/q/51753887
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/51754526
has body: I have a simple timeseries of daily observations over 2 years. I basically want to plot the daily date for each month of the series (looking daily seasonality that occurs each month). For example: I'd expect a series on the chart for each month. Is there a way to split the dataframe easily to do this? I'm trying to avoid doing this for each month/year... df['JUN-2016'] = data[df['date'].month==12 &amp; df['date'].year==2016] A sample of the dataframe: DATE 2015-01-05 2.7483 2015-01-06 2.7400 2015-01-07 2.7250 2015-01-08 2.7350 2015-01-09 2.7350 2015-01-12 2.7350 2015-01-13 2.7450 2015-01-14 2.7450 2015-01-15 2.7350 2015-01-16 2.7183 2015-01-19 2.7300 2015-01-20 2.7150 2015-01-21 2.7150 2015-01-22 2.6550 2015-01-23 2.6500 2015-01-27 2.6450 2015-01-28 2.6350 2015-01-29 2.6100 2015-01-30 2.5600 2015-02-02 2.4783 2015-02-03 2.4700
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90467520
tagged with: python
score: -2
has title: Pandas - TimeSeries to Monthly series plot
linked to: http://stackoverflow.com/q/20109391
downvote count: 2
has comment: http://stackoverflow.com/comment/90467610
has comment: http://stackoverflow.com/comment/90467711
answer count: 1
has comment: http://stackoverflow.com/comment/90467676
has answer: http://stackoverflow.com/a/51754526
has comment: http://stackoverflow.com/comment/90467565

http://stackoverflow.com/comment/90394354
type: Comment
type: QuestionComment
has text: Are you sharing your Kivy App from local machine with Kivy Buildozer VM?
comment on: http://stackoverflow.com/q/51716272
score: 0

http://stackoverflow.com/q/51731605
tagged with: python
has comment: http://stackoverflow.com/comment/90424384
answer count: 0
has comment: http://stackoverflow.com/comment/90424120
has comment: http://stackoverflow.com/comment/90424107
tagged with: adjacency-matrix
type: Question
tagged with: numpy
has title: Convert meshgrid points into adjacency matrix in python
score: 0
has body: I am converting mesh-grid points (2D Maze) into Adjacency matrix which I will use later to find the shortest path between the given coordinates. Please have a look into my code: import numpy as np import numpy.matlib #for matrices def cutblocks(xv,yv,allBlocks): x_new,y_new = np.copy(xv), np.copy(yv) ori_x,ori_y = xv[0][0], yv[0][0] for block in allBlocks: block = sorted(block) block_xmin = np.min((block[0][0], block[2][0])) block_xmax = np.max((block[0][0], block[2][0])) block_ymin = np.min((block[0][1], block[1][1])) block_ymax = np.max((block[0][1], block[1][1])) rx_min, rx_max = int((block_xmin-ori_x)/stepSize)+1, int((block_xmax-ori_x)/stepSize)+1 ry_min, ry_max = int((block_ymin-ori_y)/stepSize)+1, int((block_ymax-ori_y)/stepSize)+1 for i in range(rx_min,rx_max): for j in range(ry_min,ry_max): x_new[j][i] = np.nan for i in range(ry_min,ry_max): for j in range(rx_min,rx_max): y_new[i][j] = np.nan return x_new, y_new stepSize = 0.2 ##Blocks that should be disabled allBlocks = [[(139.6, 93.6), (143.6, 93.6), (143.6, 97.6), (139.6, 97.6)], [(154.2, 93.4), (158.2, 93.4), (158.2, 97.4), (154.2, 97.4)], [(139.2, 77.8), (143.2, 77.8), (143.2, 81.8), (139.2, 81.8)], [(154.2, 77.8), (158.2, 77.8), (158.2, 81.8), (154.2, 81.8)], [(139.79999999999998, 86.4), (142.6, 86.4), (142.6, 88.0), (139.79999999999998, 88.0)], [(154.79999999999998, 87.2), (157.6, 87.2), (157.6, 88.8), (154.79999999999998, 88.8)]] x = np.arange(136.0, 161.0, stepSize) y = np.arange(75.0, 101.0, stepSize) xv, yv = np.meshgrid(x, y) xv, yv = cutblocks(xv,yv,allBlocks) MazeSize = xv.shape[0]*xv.shape[1] adj = np.matlib.zeros((MazeSize,MazeSize)) #initialize AdjacencyMatrix #make 1 whenever there is a connection between neighboring coordinates mazeR, mazeC = 0,0 for row in range(xv.shape[0]): for col in range(xv.shape[1]): if xv[row][col]&gt;0 and col+1&lt;xv.shape[1] and round(np.abs(xv[row][col] - xv[row][col+1]),2) == stepSize: adj[mazeR,mazeC+1] = 1 break mazeC = mazeC+1 mazeR = mazeR+1 This code gen…
has comment: http://stackoverflow.com/comment/90424515
has comment: http://stackoverflow.com/comment/90424477
type: UnansweredQuestion

http://stackoverflow.com/q/51791707
tagged with: numpy
has comment: http://stackoverflow.com/comment/90541157
has comment: http://stackoverflow.com/comment/90542534
score: 0
tagged with: pandas
tagged with: types
has comment: http://stackoverflow.com/comment/90551805
answer count: 1
has comment: http://stackoverflow.com/comment/90553153
has comment: http://stackoverflow.com/comment/90553086
has title: Strange behavior of numpy astype for record
tagged with: python
has comment: http://stackoverflow.com/comment/90551889
type: AnsweredQuestion
has body: I am using numpy's .astype() method to convert the data types, however, it gives the strange result, Suppose the following code: import pandas as pd import numpy as np import sys df = pd.DataFrame(0.1, 2, 'a', columns=["a1", "a2", "str"]) arr = df.to_records(index=False) dtype1 = [('a1', np.float32), ('a2', np.int32), ('str', '|S2')] dtype2 = [('a2', np.int32), ('a1', np.float32), ('str', '|S2')] arr1 = arr.astype(dtype1) arr2 = arr.astype(dtype2) print(arr1) print(arr2) print(arr) print(sys.version) print(np.__version__) print(pd.__version__) I have test it on different python version, and gives me the different result. The newer version gives me the unexpected result: [(0.1, 2, b'a')] [(0, 2., b'a')] [(0.1, 2, 'a')] 3.6.5 |Anaconda custom (64-bit)| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] 1.15.0 0.23.4 While the older version give the correct result: [(0.10000000149011612, 2, 'a') (0.10000000149011612, 2, 'b')] [(2, 0.10000000149011612, 'a') (2, 0.10000000149011612, 'b')] [(0.1, 2L, 'a') (0.1, 2L, 'b')] 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] 1.11.1 0.20.3 Can someone tell me what is going on?
has answer: http://stackoverflow.com/a/51800614
accepted answer: http://stackoverflow.com/a/51800614
has comment: http://stackoverflow.com/comment/90549503
has comment: http://stackoverflow.com/comment/90549508
has comment: http://stackoverflow.com/comment/90552017
type: Question

http://stackoverflow.com/comment/90461368
comment on: http://stackoverflow.com/q/51750599
has text: @rahlf23 hi i tried posting my code... but there was indentation error. I will try to fix that later. I followed the Time Series with LSTM code on this website: http://dacatay.com/data-science/part-6-time-series-prediction-neural-networks-python/ Yes , lags=3 Thanks for the reply,
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/131168437
comment on: http://stackoverflow.com/a/69138513
has text: @arst3k mmm yes, it makes sense... just didn't see it:) I didn't remember why I come out with that answer so I preferred to restart a look at the problem from another prospective. Nice trick your comment!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90254606
comment on: http://stackoverflow.com/q/51644467
score: 0
type: QuestionComment
type: Comment
has text: [Why does it take so long to create a SparseDataFrame (Python pandas)?](https://stackoverflow.com/questions/41369868/why-does-it-take-so-long-to-create-a-sparsedataframe-python-pandas). Back then I deduced that a sparse dataframe consists of individual sparse series - one per column. In your case that's 1000s of series.

http://stackoverflow.com/a/52882937
downvote count: 0
score: 9
type: Answer
answers question: http://stackoverflow.com/q/51727441
upvote count: 9
has body: Use dump_to/load_from (marshmallow 2) or data_key (marshmallow 3): class TemporalExtentSchema(Schema): # Marshmallow 2 t_from = fields.String(required=True, dump_to='from', load_from='from') # Marshmallow 3 t_from = fields.String(required=True, data_key='from') to = fields.String(required=True)

django-queryset
tags question: http://stackoverflow.com/q/51722146
tags question: http://stackoverflow.com/q/51662224
tag name: django-queryset
tags question: http://stackoverflow.com/q/51733545
tags question: http://stackoverflow.com/q/51789688
tags question: http://stackoverflow.com/q/51769505
type: Tag
tags question: http://stackoverflow.com/q/51677657
tags question: http://stackoverflow.com/q/51749817

http://stackoverflow.com/q/51678572
score: 0
has comment: http://stackoverflow.com/comment/90320673
upvote count: 1
has comment: http://stackoverflow.com/comment/90320396
possible better answer: http://stackoverflow.com/a/51678607
has comment: http://stackoverflow.com/comment/90320483
downvote count: 1
has answer: http://stackoverflow.com/a/51678607
has body: x=3 y=x ans=0 while( y != 0 ): ans = ans + x y = y - 1 ans = ans*x print( str(ans) ) There is no output on screen. And no error is showing up. Just shown in image.
favorite count: 0
has comment: http://stackoverflow.com/comment/90320903
has comment: http://stackoverflow.com/comment/90320411
has comment: http://stackoverflow.com/comment/90320932
tagged with: python
has answer: http://stackoverflow.com/a/51678897
accepted answer: http://stackoverflow.com/a/51678897
has comment: http://stackoverflow.com/comment/90320434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90320703
has title: Can anyone help me in this python code for finding Cube
has comment: http://stackoverflow.com/comment/90320829
type: Question
has comment: http://stackoverflow.com/comment/90320748
answer count: 2
has comment: http://stackoverflow.com/comment/90320397
has comment: http://stackoverflow.com/comment/90320515
has comment: http://stackoverflow.com/comment/90320567
has comment: http://stackoverflow.com/comment/90320531

http://stackoverflow.com/comment/90504647
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51772806
has text: @PatrickHaugh Thanks for your help. I will try to do that.
type: Comment

http://stackoverflow.com/comment/90492006
score: 0
type: Comment
type: QuestionComment
has text: Just FYI, unless Python is a requirement here, this is a very simple operation that does not require Python, you can do it straight in a Linux shell. Use "head" to get the first N lines, use > to extract the output to a new file. Example: "head -n 6 > output.txt"
comment on: http://stackoverflow.com/q/51766469

http://stackoverflow.com/comment/90485554
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51761404
has text: is the cycle actually the line number? or many lines could have the same cycle? and do you always know the last written cycle, or do you want to read it from the file before adding the new data?

http://stackoverflow.com/q/51746797
answer count: 2
has answer: http://stackoverflow.com/a/51750671
score: -1
has answer: http://stackoverflow.com/a/51751667
tagged with: pandas
downvote count: 1
has title: Find that start date and end dates are available using python pandas
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
has body: I am having a dataframe like this year end id start 1949 1954.0 ABc 1949.0 1950 1954.0 ABc 1949.0 1951 1954.0 ABc 1949.0 1952 1954.0 ABc 1949.0 1953 1954.0 ABc 1949.0 1954 1954.0 ABc 1949.0 1950 1954.0 xyz 1949.0 1951 1954.0 xyz 1949.0 1952 1954.0 xyz 1949.0 1953 1954.0 xyz 1949.0 1954 1954.0 xyz 1949.0 1949 1954.0 cde 1949.0 1950 1954.0 cde 1949.0 1951 1954.0 cde 1949.0 1952 1954.0 cde 1949.0 1953 1954.0 cde 1949.0 I have to find the missing year for that id the output should be like this year end id start 1949 1954 xyz 1949 1954 1954 cde 1949 We have to check whether the start and end for that id is available or not. How can i achieve this.
type: Question

http://stackoverflow.com/comment/90366232
comment on: http://stackoverflow.com/q/51702498
score: 0
type: Comment
type: QuestionComment
has text: Try `r=requests.post(html, data=payload)`

http://stackoverflow.com/q/51755824
answer count: 1
tagged with: raspberry-pi3
tagged with: python
type: AnsweredQuestion
has title: Error importing pandas on Raspberry Pi
type: Question
accepted answer: http://stackoverflow.com/a/51756182
score: 0
has answer: http://stackoverflow.com/a/51756182
tagged with: raspberry-pi
tagged with: pandas
has body: I am trying to work with pandas on the Raspberry Pi, but it seems that Python is not recognizing that I have the module installed and is saying that pandas does not exist, despite the fact that I have used: pip install pandas as well as: sudo apt-get install python-pandas I would appreciate it if someone could let me know what is causing this strange error. UPDATE: Here is the error: Traceback (most recent call last): File "/home/pi/Desktop/NeuralNetwork.py", line 4, in &lt;module&gt; import pandas as pd ImportError: No module named 'pandas'

http://stackoverflow.com/a/54832113
upvote count: 4
answers question: http://stackoverflow.com/q/51648534
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/105063477
type: Answer
has body: I had a very similar pipeline that I was running right after setting up Docker agents on my Jenkins system, so I thought my setup was wrong. Using the comments in your thread, I cooked up this solution: First, you'll need to be root inside your container, so change your agent declaration to be similar to this: agent { docker { image "python:3.7" args '--user 0:0' } } Now I was able to use pip install! However, subsequent runs of the job would try to run git clean and fail since the built files inside the container were created by root. To fix that, I ran the clean command inside the container as my last step: steps { sh 'git clean -fdx' } Update: I found a problem where a failed build wouldn't clean up and killed all of the builds after it. To fix this, I put the clean action as a post-build task that always runs: post { cleanup { cleanWs() } }

multi-gpu
type: Tag
tag name: multi-gpu
tags question: http://stackoverflow.com/q/51699514

http://stackoverflow.com/a/51738091
downvote count: 0
answers question: http://stackoverflow.com/q/51737962
has comment: http://stackoverflow.com/comment/90436908
type: Answer
has comment: http://stackoverflow.com/comment/90436693
has comment: http://stackoverflow.com/comment/90436681
has comment: http://stackoverflow.com/comment/90436641
score: 1
upvote count: 1
has body: You can use pandas and some math operations to replicate your groups. n, r = df.shape[0] // 4, df.shape[0] % 4 df['group'] = [1,2,3,4]*n + [1,2,3,4][:r] day city temperature windspeed event group 0 2017-01-01 new york 32 6 Rain 1 1 2017-01-02 new york 36 7 Sunny 2 2 2017-01-03 new york 28 12 Snow 3 3 2017-01-04 new york 33 7 Sunny 4 4 2017-01-05 new york 31 7 Rain 1 5 2017-01-06 new york 33 5 Sunny 2 6 2017-01-07 new york 27 12 Rain 3 7 2017-01-08 new york 23 7 Rain 4 8 2017-01-01 mumbai 90 5 Sunny 1 9 2017-01-02 mumbai 85 12 Fog 2 10 2017-01-03 mumbai 87 15 Fog 3 11 2017-01-04 mumbai 92 5 Rain 4 12 2017-01-05 mumbai 89 7 Sunny 1 13 2017-01-06 mumbai 80 10 Fog 2 14 2017-01-07 mumbai 85 9 Sunny 3 15 2017-01-08 mumbai 89 8 Rain 4 16 2017-01-01 paris 45 20 Sunny 1 17 2017-01-02 paris 50 13 Cloudy 2 18 2017-01-03 paris 54 8 Cloudy 3 19 2017-01-04 paris 42 10 Cloudy 4 20 2017-01-05 paris 43 20 Sunny 1 21 2017-01-06 paris 48 4 Cloudy 2 22 2017-01-07 paris 40 14 Rain 3 23 2017-01-08 paris 42 15 Cloudy 4 24 2017-01-09 paris 53 8 Sunny 1

http://stackoverflow.com/q/51730381
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90513152
has comment: http://stackoverflow.com/comment/114722618
tagged with: python
linked to: http://stackoverflow.com/q/64888172
has comment: http://stackoverflow.com/comment/90423989
has title: CGI and Content-Type: text/html
answer count: 0
has body: I print some text after my CGI script finishes. As I understand the following line is compulsory: print('Content-type: text/html\n\n') apparently for the server to know that it must output HTML? However, what solution would you suggest to make it invisible on the output page? even if after that print i add: print(" ") ... print(" ") the content type is printed after the html tag like regular text EDIT. full code: #!/usr/bin/python3 import cgi import cgitb import sys import subprocess import os import threading import myModule cgitb.enable() form = cgi.FieldStorage() a1= form['a1'].value a2=form['a2'].value a3=form['a3'].value print('Content-type: text/html\n\n') print(' ') pid=os.fork() if(pid==0): print(' ') infoMsg=myModule.myFun(a1,a2,a3) print(' ') else: exit()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90422081
tagged with: cgi

http://stackoverflow.com/a/51793044
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51792903
has comment: http://stackoverflow.com/comment/90544098
answers question: http://stackoverflow.com/q/51792903
has comment: http://stackoverflow.com/comment/90544348
has comment: http://stackoverflow.com/comment/90544603
upvote count: 2
type: AcceptedAnswer
has body: You were close clean_df.index = pd.to_datetime(clean_df['year'], format='%Y-%m-%d').year It's hard to provide the actual correct format needed because I don't have your original data, but you just need to transform to date object and then call the year parameter
has comment: http://stackoverflow.com/comment/90544128
type: Answer

http://stackoverflow.com/q/51792916
has title: What is the parameter "size" means in gensim.model.Word2Vec(sentence, size)?
type: UnansweredQuestion
tagged with: word-embedding
tagged with: word2vec
tagged with: python
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51793603
tagged with: gensim
tagged with: nlp
has body: I have just been started learning about word embeddings and gensim and I tried this code . In this article during the visualisation it says we need PCA to convert high-dimensional vectors into low-dimensions. Now we have a parameter "size" in Word2Vec method, so why can't we set that size equals to 2 rather using PCA. So, I tried to do this and compare both graphs (one with 100 size and other with 2 as size) and got very different result. Now I am confused that what this "size" depicts? How the size of vectors affect this? This is what I got when I used 100 as size. This is what I got when I used 2 as size.

http://stackoverflow.com/comment/90348702
type: QuestionComment
has text: Then I have no idea what is wrong. You should create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Right now it's way too much code for anyone to help you.
comment on: http://stackoverflow.com/q/51692086
score: 0
type: Comment

http://stackoverflow.com/comment/90612731
type: Comment
has text: This is an example code but I had a similar case with two `QiMessaging` services. Thank you for the advice. I will organize the common logic in helpers. What do you mean by "different services": different services packed in one application or different services as different application? If the applications are different - how do you manage to import the common libraries?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51814113

http://stackoverflow.com/comment/90431325
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51734061
has text: @claudiadast congratulations
score: 0

http://stackoverflow.com/comment/133420699
type: Comment
comment on: http://stackoverflow.com/a/51783778
has text: Don't use `| safe` with `url_for` as it potentially allows for XSS: https://stackoverflow.com/a/39246205/3812928
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90398183
type: AnswerComment
comment on: http://stackoverflow.com/a/51718371
score: 0
type: Comment
has text: I modify the while loop as you suggested.. Am I correct? thanks

http://stackoverflow.com/q/51715784
has title: How to know what to import into the Python Interpreter in order to use installed python library
tagged with: python
has body: I have installed a python library called PyRadiomics by doing: pip install pyradiomics When I do pip freeze | grep pyra in the command prompt, I see pyradiomics==2.0.0 clearly showing that the library was installed. When I start a python interpreter and do import pyradiomics, it does not work. I realized that I need to do import radiomics. I just happened to figure this out by luck. How is someone supposed to know how to import a library into their python script after installing it using pip. It seems that currently, you could install a library with pip install some_name and have to do import some_other_name in your Python code. I have been using Python for a while but never came across this before which lead me to assume that some_name is always the same as some_other_name but I found out that this is not the case. How is someone supposed to know what that other name is after installing a library called some_name
upvote count: 5
tagged with: installation
tagged with: pip
type: AnsweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/7184375
type: Question
score: 5
answer count: 1
has answer: http://stackoverflow.com/a/51716170
accepted answer: http://stackoverflow.com/a/51716170
favorite count: 0
linked to: http://stackoverflow.com/q/7184375

http://stackoverflow.com/q/51697205
has title: Remove session data in database-backed session in django after clearing browser history
tagged with: django-sessions
has answer: http://stackoverflow.com/a/51697892
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90356012
tagged with: web-frameworks
has body: After i clear my browser history the session key and data that was added to the table django_session (session engine is database-backed by mysql) for the session remains and for subsequent requests a new 'session key' is added. In a situation where users clear their history frequently this table will grow inadvertently. Using clearsessions command doesn't remove the rows because the expiry date has not yet been reached. How do i overcome this issue if the expiry date is large? Is there some setting wrongly set up?
type: Question
tagged with: django
tagged with: python
answer count: 1
score: 0

http://stackoverflow.com/comment/90573045
comment on: http://stackoverflow.com/a/51790601
type: Comment
score: 0
type: AnswerComment
has text: Thanks for all the answers, this really helps.

http://stackoverflow.com/a/51670032
has comment: http://stackoverflow.com/comment/90303046
type: Answer
has body: The fact you see the same id for both lambda definitions is an implemetation detail - the first lambda is collected immediatly (since there's no reference to it), so the id is free for reuse and happens to be indeed reused for the second one. And no, Python is not C and activeley prevents any direct memory access. Note that the fact that CPython's objects ids are memory addresses is also an implementation detail - it's not part of the language definition, and other implementation (Jhython for example) are free to use something else for object ids. If you want to use a lambda (actually a function - lambda is only syntactic sugar and yields a function object just like a regular def statement) then you have to have a reference to it (as a variable, as a function parameter - which is actually a variable -, as an element from a collection, as an attribute from an object etc). Note that this isn't specific to functions either, Python functions are objects (hint: everything you can put on a LHS in Python is an object) and the above stands true for all objects. I wonder if I can give an object a name according to its address in memory to call or use What do you think foo = lambda x: x*2 is doing ? It "gives an object a name" (or more exactly "binds an object to a name") so you can use it later, and the binding (internally) relies on the object's id / memory address / etc to access the object. If you hope to understand Python you first need to stop thinking in C concepts and learn Python concepts.
score: 0
accepted answer of: http://stackoverflow.com/q/51669831
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51669831

http://stackoverflow.com/comment/90404584
comment on: http://stackoverflow.com/a/51722076
has text: No, then the picture turns 90 degrees
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51741646
has comment: http://stackoverflow.com/comment/90472179
has body: This very much looks like a timing issue with your queue. If the call to onConnected happens too quickly after onConnecting has been called, onConnected clears the event before onConnecting -> _connecting sets it. This is how I stripped down your class to run and test it (I removed all the LED ring stuff and added print statements to onConnected and _run) import time, threading, queue class NeoPixels: def __init__(self): self._running = True self._queue = queue.Queue() self._animation = threading.Event() threading.Thread(target=self._run) def onStart(self): self._running = True self._animation.clear() self._queue.put(self._start) def onConnecting(self): self._animation.clear() self._queue.put(self._connecting) def onConnected(self): print("called onConnected") self._animation.clear() self._queue.put(self._connected) def _run(self): while self._running: func = self._queue.get() print("now running {}".format(func.__qualname__)) func() def _start(self): time.sleep(.5) def _connecting(self): self._animation.set() while self._animation.is_set(): for i in range(5): time.sleep(20 / 1000.0) print('done') def _connected(self): for i in range(1): print("connected") time.sleep(1) And here's how I run it: leds = NeoPixels() leds.onStart() leds.onConnecting() leds.onConnected() Here's the output: called onConnected now running NeoPixels._start now running NeoPixels._connecting As you can see, onConnected is called and clears the event before _run even fetched _start from the queue and processed it. So when onConnecting is executed, _connecting sets the event and since nothing clears it after that, it keeps running indefinitely. So, changing onConnected to wait for the queue to clear, like so: def onConnected(self): while not self._queue.empty(): time.sleep(.1) print("called onConnected") self._animation.clear() self._queue.put(self._connected) will lead to the following output: now running NeoPixels._start now running NeoPixels._connecting called onConnected done now running Neo…
type: Answer
has comment: http://stackoverflow.com/comment/90449041
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51736512
has comment: http://stackoverflow.com/comment/90455045
accepted answer of: http://stackoverflow.com/q/51736512
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90317793
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51668259
has text: I was only looking for the button ;-) and there is something in the documentation, eg [here](https://www.odoo.com/documentation/11.0/reference/guidelines.html). Nice to know everything is solved now :-)
score: 0

http://stackoverflow.com/comment/90308821
has text: I can not register an arrangement in a field in odoo, because what I want is that element I have in my arrangement X = [1,2,3,4] that the days are created one by one in the cycle for that creates to create the registry in the data saes, if you observe it is a dictionary and there is a key called Day because there I must place each element of the arrangement example 1 or 4 where 1 or 4 are the day. Do you understand better?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51659704

http://stackoverflow.com/comment/90380104
comment on: http://stackoverflow.com/a/51707553
type: AnswerComment
score: 0
type: Comment
has text: Instead of `tree` try `tree.getroot()`

http://stackoverflow.com/q/51761032
tagged with: data-visualization
tagged with: python
has comment: http://stackoverflow.com/comment/90492432
has comment: http://stackoverflow.com/comment/90481770
answer count: 0
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/90481827
score: 0
tagged with: deep-learning
has body: I would really appreciate any advice about plotting the evaluation accuracy curve of several models for comparison. Assuming I have 6 different versions of a model and within each version I have two variations. Normally plotting the evaluation accuracy of these models would look something like this: Line plot of evaluation accuracy over N iterations. It's cluttered and can hardly convey the information. I could clean it up more but it would still be cluttered. Or I could seperate them but would get several plots instead. Does it make sense to use box whiskers like this? Box whisker plot of evaluation accuracy over N iterations. If not, how would someone go about plotting several models for comparison while keeping it clear and simple? Thanks in advance!
tagged with: visualization
has title: Plotting evaluation curve, does box whisker plot makes any sense?
type: UnansweredQuestion

http://stackoverflow.com/comment/90506894
type: QuestionComment
type: Comment
has text: Could you give us an idea of the kind of file names you're inputting? You're probably not correctly inputting the absolute path
comment on: http://stackoverflow.com/q/51774047
score: 0

http://stackoverflow.com/comment/90498909
score: 0
comment on: http://stackoverflow.com/q/51754073
has text: I'm sorry I have no idea, but Google app script uses javascript and you deploy the scripts from within the Google app script editor Check out https://developers.google.com/apps-script/
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51762908
type: AnsweredQuestion
downvote count: 0
tagged with: dsl
score: 6
has title: Can I use JetBrains MPS in a web application?
type: Question
has answer: http://stackoverflow.com/a/51763074
upvote count: 6
tagged with: flask
tagged with: jetbrains-ide
tagged with: mps
answer count: 2
has answer: http://stackoverflow.com/a/51779632
accepted answer: http://stackoverflow.com/a/51779632
favorite count: 0
possible better answer: http://stackoverflow.com/a/51763074
tagged with: python
has body: I am developing a small web application with Flask. This application needs a DSL, which can express the content of .pdf files. I have developed a DSL with JetBrains MPS but now I'm not sure how to use it in my web application. Is it possible? Or should I consider to switch to another DSL or make my DSL directly in Python.

http://stackoverflow.com/comment/90459103
type: Comment
type: AnswerComment
has text: Well, maybe using `slim` may help you as well. Can you please check this link: https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb especially the loading pre-trained model Inception.
comment on: http://stackoverflow.com/a/51718688
score: 0

http://stackoverflow.com/q/51690071
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I'm trying to run a jango site, static files are working, media is not loaded from the media folder, if the picture in static files is visible. The folder is listed correctly, pycharm gives a fall in the folder setings.py STATIC_ROOT = '/home/static/' STATIC_URL = '/static/' # MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_ROOT = '/home/media/' MEDIA_URL = '/media/' urls.py if settings.DEBUG: import debug_toolbar # Server statics and uploaded media urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Allow error pages to be tested urlpatterns += [ url(r'^403$', handler403), url(r'^404$', handler404), url(r'^500$', handler500), url(r'^__debug__/', include(debug_toolbar.urls)), ] I use django oscar, this can be the cause of the problem?
type: Question
possible better answer: http://stackoverflow.com/a/51690160
has answer: http://stackoverflow.com/a/51690160
has answer: http://stackoverflow.com/a/51690484
linked to: http://stackoverflow.com/q/2928738
answer count: 3
has title: Django media not loading, static files working
upvote count: 1
accepted answer: http://stackoverflow.com/a/51690326
favorite count: 0
tagged with: django
has answer: http://stackoverflow.com/a/51690326
tagged with: python
has comment: http://stackoverflow.com/comment/90342248

http://stackoverflow.com/a/51660940
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51643332
type: Answer
has body: I didn't get exactly what I wanted, but this what I can come up with so far to build off of from bs4 import BeautifulSoup import requests from lxml import html, cssselect import csv link = "https://www.sec.gov/Archives/edgar/data/320193/000032019318000100/a10-qq320186302018.htm" response = requests.get(link) soup = BeautifulSoup(response.text, 'html.parser') str_soup = str(soup) doc = html.document_fromstring(str_soup) with open('AAPL_financials.csv', 'w') as csvfile: writer = csv.writer(csvfile) for col in doc.cssselect('tr'): row = [] for text in col.cssselect('font'): if text.text == None: continue value = text.text.strip() if value == "": continue if value == "$": continue if value == "%": continue if value == ")": continue if value[0] == "(": value = value.replace("(", "-")) row.append(value) writer.writerow(row)
score: 0
accepted answer of: http://stackoverflow.com/q/51643332

http://stackoverflow.com/q/51781841
linked to: http://stackoverflow.com/q/502501
score: 1
has answer: http://stackoverflow.com/a/51782271
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90521647
has title: Delete a post in Django
has answer: http://stackoverflow.com/a/51782160
answer count: 3
favorite count: 0
has body: I new to django and I am trying to make a web application. I have this page page image and I want to delete one post when I press the delete button. How can I do that? This is my modal for 'Post' : class Post(models.Model): created_date = models.DateTimeField() title = models.CharField(max_length=100) profile_image = models.ImageField(upload_to='poze', blank=True, null=True) text = models.CharField(max_length=1000, default='Nimic', blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) I've been looking for delete methods, but I've always found form-only methods and I don't use form. Thank you.
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51782132
tagged with: django
tagged with: python

http://stackoverflow.com/q/51657959
has comment: http://stackoverflow.com/comment/90643628
has body: Is there any way to sort the Namespace entries after they've been added to the Api? I'm following the documentation, and the flow (AFAIK) appears to be: a) Create the API: api = Api(version="1.0", title="MahApi", description="Mah Nice Little API", doc="/swagger-ui", strict_slashes=False) b) Define namespaces: ns = Namespace("sample_namespace", description="sample module api", path='/sample_one') ... @ns.route('/test1', endpoint='sample_ns_test1') class TestApi(Resource): def get(self): df = mah_service.get_some_data() return jsonify(json.loads(df.to_json(orient='records'))) c) Add namespaces to the API: api.add_namespace(mah_sample_ns) Where I'm facing an issue (albeit it's a cosmetic yet annoying one) is that the namespaces are not being sorted in any way. It seems that I will need to sort the namespaces myself, manually, in code. Is there a more clever, pythonic way to get swagger to sort the namespaces?
type: Question
has comment: http://stackoverflow.com/comment/90642789
has title: Flask-restplus: any way to sort the namespaces in swagger?
has answer: http://stackoverflow.com/a/65585051
has comment: http://stackoverflow.com/comment/90671780
has comment: http://stackoverflow.com/comment/90281676
score: 4
tagged with: flask
upvote count: 4
tagged with: flask-restplus
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90643483
has comment: http://stackoverflow.com/comment/90642670
linked to: http://stackoverflow.com/q/24951268

http://stackoverflow.com/comment/90252268
score: 0
has text: I have closed it, i don't know why it shows a python running
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51643987

http://stackoverflow.com/q/51772473
tagged with: dictionary
has body: I struggled with this yesterday afternoon and think I have come up with a clever solution but looking for feedback on how to improve it. The scenario: I am running ffprobe on media files and getting back the JSON dictionary from ffprobe and storing it in a MongoDB collection linked to the mongo document for the file. The problem: Some media file types give back key names in the JSON that are incompatible with the BSON documents in Mongo. For example, the following perfectly valid JSON cannot be stored in Mongo as is due to the keys in the tags dictionary: "format": { "filename": "ToS-4k-1920_CMO_freezeframe6308.mov", "nb_streams": 2, "nb_programs": 0, "format_name": "mov,mp4,m4a,3gp,3g2,mj2", "format_long_name": "QuickTime / MOV", "start_time": "0.000000", "duration": "738.941667", "size": "14542021084", "bit_rate": "157436200", "probe_score": 100, "tags": { "major_brand": "qt ", "minor_version": "537199360", "compatible_brands": "qt ", "creation_time": "2018-01-15T18:07:07.000000Z", "com.apple.quicktime.player.movie.audio.gain": "1.000000", "com.apple.quicktime.player.movie.audio.treble": "0.000000", "com.apple.quicktime.player.movie.audio.bass": "0.000000", "com.apple.quicktime.player.movie.audio.balance": "0.000000", "com.apple.quicktime.player.movie.audio.pitchshift": "0.000000", "com.apple.quicktime.player.movie.audio.mute": "", "com.apple.quicktime.player.movie.visual.brightness": "0.000000", "com.apple.quicktime.player.movie.visual.color": "1.000000", "com.apple.quicktime.player.movie.visual.tint": "0.000000", "com.apple.quicktime.player.movie.visual.contrast": "1.000000", "com.apple.quicktime.player.version": "7.6.6 (7.6.6)", "com.apple.quicktime.version": "7.7.3 (2943.14) 0x7738000 (Mac OS X, 10.11.6, 15G18013)" } } The solution? I wrote a recursive function to parse the dictionary updating the keys but it is bad mojo to update a dictionary you are iterating in so I tricked the system by getting a list of all the keys and interating through that so that I c…
score: 0
tagged with: http://stackoverflow.com/tag/json
tagged with: ffprobe
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/90503847
has answer: http://stackoverflow.com/a/51773060
answer count: 1
has title: How to update the key names in place in a complex Python dictionary
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51674813
type: Answer
has comment: http://stackoverflow.com/comment/120901116
upvote count: 6
answers question: http://stackoverflow.com/q/51674751
has comment: http://stackoverflow.com/comment/120873542
has comment: http://stackoverflow.com/comment/121031988
downvote count: 1
score: 5
has comment: http://stackoverflow.com/comment/90313666
has body: You can use asyncio to make asynchronous requests. Here is an example: import asyncio import requests async def main(): loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( None, requests.get, 'http://example.org/' ) for i in range(20) ] for response in await asyncio.gather(*futures): pass loop = asyncio.get_event_loop() loop.run_until_complete(main())
has comment: http://stackoverflow.com/comment/120948824
has comment: http://stackoverflow.com/comment/90371208
has comment: http://stackoverflow.com/comment/90377677
has comment: http://stackoverflow.com/comment/103307531

regex
tags question: http://stackoverflow.com/q/51763696
tags question: http://stackoverflow.com/q/51679605
tags question: http://stackoverflow.com/q/51640868
tags question: http://stackoverflow.com/q/51762816
tags question: http://stackoverflow.com/q/51643853
tags question: http://stackoverflow.com/q/51739940
tags question: http://stackoverflow.com/q/51689418
tags question: http://stackoverflow.com/q/51731972
tags question: http://stackoverflow.com/q/51794615
tags question: http://stackoverflow.com/q/51690718
tags question: http://stackoverflow.com/q/51715783
tags question: http://stackoverflow.com/q/51696579
tags question: http://stackoverflow.com/q/51710087
tags question: http://stackoverflow.com/q/51694375
tags question: http://stackoverflow.com/q/51657210
tags question: http://stackoverflow.com/q/51697213
tags question: http://stackoverflow.com/q/51708212
tags question: http://stackoverflow.com/q/51685002
tags question: http://stackoverflow.com/q/51789435
tags question: http://stackoverflow.com/q/51685744
tag name: regex
tags question: http://stackoverflow.com/q/51642012
tags question: http://stackoverflow.com/q/51711321
tags question: http://stackoverflow.com/q/51654117
tags question: http://stackoverflow.com/q/51759520
tags question: http://stackoverflow.com/q/51752581
tags question: http://stackoverflow.com/q/51645157
tags question: http://stackoverflow.com/q/51656394
tags question: http://stackoverflow.com/q/51768463
tags question: http://stackoverflow.com/q/51791240
tags question: http://stackoverflow.com/q/51793677
tags question: http://stackoverflow.com/q/51736281
tags question: http://stackoverflow.com/q/51649789
tags question: http://stackoverflow.com/q/51796154
tags question: http://stackoverflow.com/q/51777395
tags question: http://stackoverflow.com/q/51644378
tags question: http://stackoverflow.com/q/51742351
tags question: http://stackoverflow.com/q/51706710
tags question: http://stackoverflow.com/q/51661686
tags question: http://stackoverflow.com/q/51730850
tags question: http://stackoverflow.com/q/51746791
tags question: http://stackoverflow.com/q/51747158
tags question: http://stackoverflow.com/q/51648244
tags question: http://stackoverflow.com/q/51733659
tags question: http://stackoverflow.com/q/51781505
tags question: http://stackoverflow.com/q/51687342
tags question: http://stackoverflow.com/q/51713273
tags question: http://stackoverflow.com/q/51700700
tags question: http://stackoverflow.com/q/51674960
tags question: http://stackoverflow.com/q/51783628
tags question: http://stackoverflow.com/q/51707642
tags question: http://stackoverflow.com/q/51746426
tags question: http://stackoverflow.com/q/51742768
tags question: http://stackoverflow.com/q/51797066
tags question: http://stackoverflow.com/q/51681281
tags question: http://stackoverflow.com/q/51697171
tags question: http://stackoverflow.com/q/51749886
tags question: http://stackoverflow.com/q/51777582
tags question: http://stackoverflow.com/q/51686797
tags question: http://stackoverflow.com/q/51686658
tags question: http://stackoverflow.com/q/51784964
tags question: http://stackoverflow.com/q/51711826
tags question: http://stackoverflow.com/q/51716554
tags question: http://stackoverflow.com/q/51733496
tags question: http://stackoverflow.com/q/51691040
tags question: http://stackoverflow.com/q/51716134
tags question: http://stackoverflow.com/q/51777179
tags question: http://stackoverflow.com/q/51731946
tags question: http://stackoverflow.com/q/51775817
tags question: http://stackoverflow.com/q/51781509
tags question: http://stackoverflow.com/q/51659430
tags question: http://stackoverflow.com/q/51693934
tags question: http://stackoverflow.com/q/51746290
tags question: http://stackoverflow.com/q/51650097
tags question: http://stackoverflow.com/q/51793412
tags question: http://stackoverflow.com/q/51753067
tags question: http://stackoverflow.com/q/51777409
tags question: http://stackoverflow.com/q/51664061
tags question: http://stackoverflow.com/q/51664555
tags question: http://stackoverflow.com/q/51791564

http://stackoverflow.com/comment/90509144
type: Comment
type: QuestionComment
has text: @pault I am doing this within pyspark and this file is going to be used to load the data to a Hive table.
score: 0
comment on: http://stackoverflow.com/q/51774634

http://stackoverflow.com/comment/90331471
type: Comment
comment on: http://stackoverflow.com/q/51684594
score: 0
type: QuestionComment
has text: @joaquin I know, which is why I said that it's 'worth noting' :) (as it's still useful information for users who stumble upon this question)

http://stackoverflow.com/comment/114935950
has text: I had tried reverse-engineering the whole thing in order to crack that code and arrive at just such a solution but got nowhere. This is useful to know.
comment on: http://stackoverflow.com/a/64991518
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90436547
has text: you run on local PC , scrapy spider container , postgre container , scrapy-splash container are working fine ?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51738063

http://stackoverflow.com/comment/90391758
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51714880
has text: This doesn't answer the question. OPs concept should work - Open an instance of Excel, Open a file (which happens to be a csv, but that doesn't matter), inject some vba code into it, run that vba (although that bit might be missing), SaveAs the file (that's where it might fall down, if not SaveAs'd an Excel file)

http://stackoverflow.com/q/51667350
answer count: 1
has answer: http://stackoverflow.com/a/51670184
upvote count: 1
favorite count: 0
has body: class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return True if head.next == None: return True slow = head fast = head if fast.next.next == None: return fast.val == fast.next.val length = 1 lenPtr = head while lenPtr.next != None: length += 1 lenPtr = lenPtr.next while fast != None and fast.next != None: slow = slow.next fast = fast.next.next if length % 2 == 0: # even rev = self.reverse(slow) else: rev = self.reverse(slow.next) slow = None print(rev.val, head.val, head.next.val) return rev == head def reverse(self, head): if head.next == None: print('return head', head.val) return head tempHead = head while head.next != None: temp = head.next head.next = head.next.next temp.next = tempHead tempHead = temp return tempHead Here is my solution for a coding interview question that finds whether a linked list is a palindrome. My strategy is just to find the midpoint of the linked list by using two pointers with different speed and reverse the second half of the list and then compare with the first half. After I debugged, the problem is that the first half of the linked list does not remove the last node when it's an odd-length list. For example, if an input is 1-&gt;0-&gt;1-&gt;None, the second half will end up being 1-&gt;None and the first half should be 1-&gt;None too since I did slow = None after getting the reversed second half. However, it seems like it still has the 0 node even after setting slow = None. This is very weird because head.next == slow returns true when I try to debug it. What can possibly be the issue?
type: UnansweredQuestion
tagged with: python
has title: Checking whether a linked list is palindrome. Cannot find the issue
tagged with: linked-list
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/51489385
type: Question

http://stackoverflow.com/comment/90521203
score: 0
comment on: http://stackoverflow.com/q/51781729
has text: I also ran this in Jupyter Notebook and it worked flawlessly
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90465752
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51752925
has text: Is your entire file actually valid json? Or is only each line valid json?

http://stackoverflow.com/q/51732256
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51732271
linked to: http://stackoverflow.com/q/45184549
favorite count: 0
upvote count: 2
has title: Alternative to using np.where with list to yield a series instead of an ndarray to be more amenable to converting into a dataframe?
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/51732271
type: Question
has body: Is there an alternative to use np.where with a list so that I can work with a series instead of an ndarray? animal = ['Buffalo', 'Gazelle'] df.one = np.where(df.one.isin(animal),'Herding Animal', df.one)
tagged with: comparison
has comment: http://stackoverflow.com/comment/90463263
score: 0

http://stackoverflow.com/comment/90392917
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51715736
has text: Can you expand on what your aim is?
type: Comment

http://stackoverflow.com/q/51784615
tagged with: input
has body: i need to read a file in python. My Problem is, that the file has an alternating amount of columns and that there are comments at the end of each line. I want to get rid of the comments while I read the file and save the data in a array or something like that. I Have absolutely no idea how to do that. Can anyone of you help me? This is how the file looks like: 2.0 # mass -2.0 2.0 1999 # xMin xMax nPoint 1 5 # first and last eigenvalue to print linear # interpolation type 2 # nr. of interpolation points and xy declarations -2.0 0.0 2.0 0.0
has answer: http://stackoverflow.com/a/51788757
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90526330
possible better answer: http://stackoverflow.com/a/51784868
linked to: http://stackoverflow.com/q/1706198
has answer: http://stackoverflow.com/a/51784868
tagged with: comments
has answer: http://stackoverflow.com/a/51784917
has comment: http://stackoverflow.com/comment/90526359
type: Question
has answer: http://stackoverflow.com/a/51785386
has comment: http://stackoverflow.com/comment/90526299
accepted answer: http://stackoverflow.com/a/51788757
has title: Reading a file with without comments in python
has comment: http://stackoverflow.com/comment/90526410
tagged with: python
answer count: 4
score: 0
has comment: http://stackoverflow.com/comment/90526240

http://stackoverflow.com/comment/90342297
score: 0
type: Comment
has text: @michelle Sure! But using `enumerate` is the neat & Pythonic way to do it. You can also do it with `for gamenum in range(4):`. See if you can figure it out. You could also do it with a `while` loop, like you were trying to do before, but that's the messiest way.
type: AnswerComment
comment on: http://stackoverflow.com/a/51683695

http://stackoverflow.com/comment/90444942
score: 0
has text: Sorry for the delay. Unfortunately, I get an `IndexError: index 3 is out of bounds for axis 0 with size 3` even when applying your code to the example.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51736389

http://stackoverflow.com/comment/90283176
comment on: http://stackoverflow.com/a/51659571
type: AnswerComment
has text: Seems like you might need something like `compact_results.loc[compact_results.Trade != 'Flat', 'ExitTime'] = df.reindex(ids)['Date_Time'].values`
type: Comment
score: 1

http://stackoverflow.com/comment/90446865
type: AnswerComment
has text: I think that I found why is plotting those axis values (161x157). It seems to be the shape of both spectrogram and dBS vars, so it IS a printing problem more than an implementation problem. The only thing left now is to find the correct printing values in order to obtain the desired plot
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51723177

http://stackoverflow.com/comment/90512005
comment on: http://stackoverflow.com/a/51773252
type: AnswerComment
has text: Yet it worked for other dictionaries that had that same thing, but it considered only the first index, and ignored the rest, no matter how many came after for one key. Hmm...so what could it be?
score: 0
type: Comment

http://stackoverflow.com/comment/90889389
has text: https://stackoverflow.com/questions/51969476/how-to-compare-two-dataframes-on-a-column-and-replace-with-other-column-value
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51770117
type: Comment

http://stackoverflow.com/comment/90307102
has text: This might help: https://stackoverflow.com/questions/14969739/python-del-statement
score: 0
comment on: http://stackoverflow.com/q/51672142
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90387728
score: 0
type: Comment
has text: @HahaMuntz: in case a queryset is necessary, then you can not do this. Then you probably better add an extra `foo` field to the database, and update it regularly with the calculations.
comment on: http://stackoverflow.com/a/51710164
type: AnswerComment

http://stackoverflow.com/a/51790752
accepted answer of: http://stackoverflow.com/q/51788308
has comment: http://stackoverflow.com/comment/90554317
score: 0
type: AcceptedAnswer
has body: In the branch tdd you've named the file travis.yml while it must be .travis.yml. Rename, commit and push. In other branches you don't have .travis.yml at all. Add .travis.yml to all branches you want to build.
type: Answer
answers question: http://stackoverflow.com/q/51788308
has comment: http://stackoverflow.com/comment/90553410

http://stackoverflow.com/a/51714090
has comment: http://stackoverflow.com/comment/90390282
answers question: http://stackoverflow.com/q/51713955
score: 0
has body: You will need to install python3-dev on ubuntu (in addition to unixodbc-dev) and it did work. Please ensure you've installed these: $ sudo apt-get install python3-dev $ sudo apt-get install unixodbc-dev FYI : Python 2.x users, will need python-dev instead.
has comment: http://stackoverflow.com/comment/90392159
type: Answer

http://stackoverflow.com/comment/90317058
has text: [4, 5, 2] are consecutive with their index values [4, 5, 2] their index is 0, 1, 2 if u need any clarity, please ask.
comment on: http://stackoverflow.com/q/51676842
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51677027
has answer: http://stackoverflow.com/a/51678011
has answer: http://stackoverflow.com/a/51677253
has title: How to implement Try and Except into my code so it automatically restarts when connection to database fails?
has comment: http://stackoverflow.com/comment/90317774
type: Question
has comment: http://stackoverflow.com/comment/90318742
answer count: 2
has comment: http://stackoverflow.com/comment/90318828
tagged with: postgresql
score: 0
tagged with: try-except
tagged with: sql
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90319107
tagged with: python
has comment: http://stackoverflow.com/comment/90318799
has comment: http://stackoverflow.com/comment/90319172
has body: I have a python script that pulls sql queries from a database but unfortunately the database has performance issue and sometime kills my script. Since my script is using a list of 20,000 arguments from a text file it will take my script a while to run and it will fail many times. As a result I would like to implement try and except into my script so it will automatically continue retrying even when the connection to the database is lost momentarily. The error message I get is cannot connect to database which I know isn't true since my script works without the try and except statements. My code is below and I would greatly appreciate your assistance! Code from __future__ import print_function try: import psycopg2 except ImportError: raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n') sys.exit(1) import re import sys import json import pprint outfilepath = "crtsh_output/crtsh_flat_file" DB_HOST = 'crt.sh' DB_NAME = 'certwatch' DB_USER = 'guest' def connect_to_db(): filepath = 'forager.txt' with open(filepath) as fp: try: for cnt, domain_name in enumerate(fp): print("Line {}: {}".format(cnt, domain_name)) print(domain_name) domain_name = domain_name.rstrip() conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) cursor = conn.cursor() cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_k$ FROM certificate c, certificate_identity ci WHERE c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) = lower(%s) AND x509_notAfter(c.certificate) &gt; statement_timestamp()''',(domain_name,)) unique_domains = cursor.fetchall() pprint.pprint(unique_domains) outfilepath = "crtsh1" + ".json" with open(outfilepath, 'a') as outfile: outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False)) except: print("\n\033…

http://stackoverflow.com/q/51713202
tagged with: mysql-connector
tagged with: mysql-connect
type: Question
has title: Can't create temporary tables through Python (Mysql.Connector)
tagged with: mysql-python
downvote count: 0
answer count: 1
has body: I have a query of the following format, DROP TABLE X; CREATE TEMPORARY TABLE IF NOT EXISTS X (SELECT * FROM TABLE); SELECT A,B,C FROM X; However, if I run this in Python using mysql connector. I get the following message, 'No result set to fetch from'. My understanding is that it only executes the first DROP TABLE X; and returns. Is there another way to achieve this?. I've also tried using multi=True but that didn't work either. Thanks in advance
has answer: http://stackoverflow.com/a/54489840
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: mysql-connector-python
score: 2
upvote count: 2

http://stackoverflow.com/q/51693536
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51694579
score: 1
accepted answer: http://stackoverflow.com/a/51694579
tagged with: django-models
has body: I using a nested model in a Django project. The following snippet code is models.py: from django.db import models from django.db.models.deletion import CASCADE class Model_(models.Model): name = models.CharField(max_length=50, default="This is a model") frequently = models.FloatField(default=1.0) def __str__(self): return self.name class SubModel(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=8, default='0x') model_ = models.ForeignKey(Model_, on_delete=CASCADE) def __str__(self): return self.name class Metadata(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=100) sub_model = models.ForeignKey(SubModel, on_delete=CASCADE) This is my admin.py script: from django.contrib import admin from nested_inline.admin import NestedTabularInline, NestedStackedInline,\ NestedModelAdmin from &lt;djano-application-name&gt;.models import Model_, SubModel, Metadata class MetadataAdmin(NestedTabularInline): model = Metadata extra = 1 class SubModelAdmin(NestedStackedInline): model = SubModel inlines = [MetadataAdmin] extra = 1 class Model_Admin(NestedModelAdmin): model = Model_ inlines = [SubModelAdmin] list_display = ['name'] admin.site.register(Model_, Model_Admin) Question: What is the difference between NestedStackedInline and NestedTabularInline in admin.py script? [NOTE]: Versions: Python 2.7 and Django 1.11
upvote count: 1
answer count: 1
has title: Difference between NestedStackedInline and NestedTabularInline
tagged with: python
favorite count: 0
downvote count: 0
tagged with: django
type: Question

http://stackoverflow.com/comment/90456223
type: Comment
comment on: http://stackoverflow.com/q/51747535
type: QuestionComment
has text: yes, when I print the cell's value I get "None"
score: 0

http://stackoverflow.com/comment/90393409
comment on: http://stackoverflow.com/q/51715988
has text: Each cell yes, that's correct.
score: 0
type: Comment
type: QuestionComment

parsing
tags question: http://stackoverflow.com/q/51688127
tags question: http://stackoverflow.com/q/51656193
tags question: http://stackoverflow.com/q/51704509
tag name: parsing
tags question: http://stackoverflow.com/q/51676669
tags question: http://stackoverflow.com/q/51726531
tags question: http://stackoverflow.com/q/51684312
tags question: http://stackoverflow.com/q/51643332
tags question: http://stackoverflow.com/q/51790924
tags question: http://stackoverflow.com/q/51788359
tags question: http://stackoverflow.com/q/51769008
tags question: http://stackoverflow.com/q/51729136
tags question: http://stackoverflow.com/q/51756106
tags question: http://stackoverflow.com/q/51762615
tags question: http://stackoverflow.com/q/51766367
tags question: http://stackoverflow.com/q/51676994
type: Tag
tags question: http://stackoverflow.com/q/51667938
tags question: http://stackoverflow.com/q/51780630
tags question: http://stackoverflow.com/q/51751934
tags question: http://stackoverflow.com/q/51688720
tags question: http://stackoverflow.com/q/51704784
tags question: http://stackoverflow.com/q/51765515
tags question: http://stackoverflow.com/q/51683243
tags question: http://stackoverflow.com/q/51733754
tags question: http://stackoverflow.com/q/51681873
tags question: http://stackoverflow.com/q/51731804
tags question: http://stackoverflow.com/q/51727061

http://stackoverflow.com/a/51742814
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51742210
has body: This could happening because of index problem as well. Use arg "ignore_index": pd.concat([df1,df2], ignore_index=True) or you can test by using "keys" argument so that you will know which observation is of which original data frame: pd.concat([df1,df2], ignore_index=True, keys=['a', 'b'])

http://stackoverflow.com/comment/90349820
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51691178
has text: Which is too slow, `a.tolist()`, or making the Series from that list?
score: 0

http://stackoverflow.com/comment/90532952
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51787868
has text: Clone the array. Order the cloned array. Remove all elements from nth position. Remove in order the elements from original array that arent on new array.

http://stackoverflow.com/q/51660429
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: module
has body: I have created 3 file namely config.ipynb , update.ipynb and main.ipynb in same directory. I am using Jupyter notebook environment. The same code works fine with spyder environment under .py file format. config.ipynb :- config module a = 0 b = "empty" The module config.py stores global variables of a and b. update.ipynb :- update module import config config.a = 10 config.b = "alphabet" In update.py file, we import the config.py module and modify the values of a and b. main.ipynb :- import config import update print(config.a) print(config.b) Similarly, in main.py file we import both config.py and update.py module. Finally, we print and test the values of global variables whether they are changed or not. And I got this error :- ModuleNotFoundError: No module named 'config' I am predicting that the answer will be 10 alphabet
has title: Module : - Share a global Variable Across Python Modules
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90284949
downvote count: 0
tagged with: global

http://stackoverflow.com/q/51736105
has title: Python DBAPI cursor fetchmany in a generator is closed too early
type: Question
has comment: http://stackoverflow.com/comment/90444128
score: 0
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/90501571
tagged with: generator
answer count: 0
type: UnansweredQuestion
tagged with: python-db-api
has body: import dbapi2 conn = dbapi2.connect("db", autocommit=True) def fetch_generator(): cursor = conn.cursor() for res in cursor.execute('select * from table'): yield res def generator_1(): for x in fetch_generator(): yield x def generator_2(): for x in generator_1(): yield x if __name__ == '__main__': for x in generator_2(): print(x) This throws an error at for x in fetch_generator() Error: dbapi2.InterfaceError: Attempted to use a closed cursor Why is the cursor closing with the chain of generators? Is is a scope issue and are context managers one solution? How do I keep the cursor from having del or close called on it automatically -- somewhere not sure when -- and keep it open.

http://stackoverflow.com/q/51663279
linked to: http://stackoverflow.com/q/16720541
has answer: http://stackoverflow.com/a/51666107
downvote count: 1
type: Question
tagged with: text-parsing
has answer: http://stackoverflow.com/a/51667099
score: -1
has body: Currently I have a program that accepts a text file as a setting parameter. The format of the text file is like so: What I would like to do in Python is to be able to parse the file. I want to read each line and check if it contains a specific string and if the line contains it, be able to append/update in place a user input text right into the end of that line. For example, the "PRIMER_PRODUCT_SIZE_RANGE=" (highlighted) is found in the text file and I want to update it from "PRIMER_PRODUCT_SIZE_RANGE=100-300" to read for example "PRIMER_PRODUCT_SIZE_RANGE=500-1000". I want to be able to do this for several of the parameters (that I have chosen for my needs). A few tools I've looked into would include fileinput module, doing a regular file open/write (which I can't do in place editing apparently), and a module I found called the in_place module. Some preliminary code I have using the in_place module: def SettingFileParser(filepath): with in_place.InPlaceText(filepath) as text_file: for line in text_file: if 'PRIMER_PRODUCT_SIZE_RANGE=' in line: text_file.write("idk what to put here") I'm a noob programmer to preface so any help or guidance in the right direction would be appreciated.
answer count: 3
possible better answer: http://stackoverflow.com/a/51666107
favorite count: 0
has answer: http://stackoverflow.com/a/51664430
accepted answer: http://stackoverflow.com/a/51664430
tagged with: python
has comment: http://stackoverflow.com/comment/90292341
has title: How would update a line in a text file if it contains a certain string with user input in Python?
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/90359127
comment on: http://stackoverflow.com/q/51698805
type: QuestionComment
type: Comment
has text: Can you give some example input and output? "Every tenth (non-zero) value" is ambiguous and also something completely different from what your code is doing. You may find this helpful: [How to loop through 2D numpy array using x and y coordinates without getting out of bounds error?](https://stackoverflow.com/q/30499857)
score: 0

http://stackoverflow.com/a/51675520
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51655729
has body: It sounds like what you're really asking is "how do I convert a json document to my own Python class". The role of a client library (for Cloudant) is to abstract away the boiler plate HTTP and json encoding stuff, and leave you with nice method calls and a native (in Python a dict) representation of a json document. In Python especially, given its superb requests library and slick json handling, most people probably wouldn't bother using a specific client library, even. Converting a dict to a class of your own making shouldn't be hard, or requiring a library. Python 3.7: from dataclasses import dataclass @dataclass class Employee: name: str department: str code: int and import requests from employee import Employee doc = requests.get("https://acc.cloudant.com/employees/bobthebuilder").json() employee = Employee( name=doc.get("name", "n/a") department=doc.get("department", "n/a") code=doc.get("code", "n/a") )
answers question: http://stackoverflow.com/q/51655729
has comment: http://stackoverflow.com/comment/90325428
type: Answer
has comment: http://stackoverflow.com/comment/90340776
score: 2

http://stackoverflow.com/comment/90345069
score: 5
comment on: http://stackoverflow.com/a/51689353
has text: Oh, thank you. Problem solved with `from skimage.util import montage2d`. Should have read the release notes.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90481084
comment on: http://stackoverflow.com/q/51760670
type: Comment
has text: Try to add `type="http", auth="public", ...` to your decorator and tell us if it works then?
type: QuestionComment
score: 0

http://stackoverflow.com/q/51659963
tagged with: python
has comment: http://stackoverflow.com/comment/90286301
has title: Not being able to call a particular column after grouping data week-wise in Pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/90283702
has body: I tried to convert daily data to weekly data in Pandas, but when I want to perform calculations with a particular column from the grouped data frame, I cannot do so. This is my code: df_w['Date'] = pd.to_datetime(df_w['Date']) df_w.set_index('Date', inplace=True) df_w.sort_index(inplace=True) def take_first(array_like): return array_like[0] def take_last(array_like): return array_like[-1] output_w = df_w.resample('W', # Weekly resample how={'Date2': take_first, 'Open': take_first, 'High': 'max', 'Low': 'min', 'Close': take_last, 'Volume': 'sum'}, loffset=pd.offsets.timedelta(days=-6)) # to put the labels to Monday df_w = output_w'Date2','Open', 'High', 'Low', 'Close', 'Volume' df_w[ 'EMA_40' ] = df_w['Close'].ewm( span = 40, adjust=False ).mean() This is the error message: df_w[ 'EMA_40' ] = df_w['Close'].ewm( span = 40, adjust=False ).mean() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/window.py", line 2178, in mean return self._apply('ewma', **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/window.py", line 2149, in _apply values = self._prep_values(b.values) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/window.py", line 219, in _prep_values dtype=values.dtype)) NotImplementedError: ops for EWM for this dtype datetime64[ns] are not implemented I realized that I'm making a mistake while grouping the data, since, upon printing the new 'Close', instead of a column being printed, the entire data frame of Open, High, Low, and Close is being printed. While printing df_w and df_w[ 'Close' ], this is the output: index close ... Open Low High Date ... 2014-07-28 1008 2014-08-01 41.41 ... 41.12 41.0200 41.7300 2014-08-04 1003 2014-08-08 41.44 ... 40.79 40.7800 41.4600 2014-08-11 998 2014-08-15 41.97 ... 41.84 41.7400 42.2200 2014-08-18 993 2014-08-22 42.45 ... 42.75 42.2100 42.7500 Is there a way to rectify this? I …
has comment: http://stackoverflow.com/comment/90283440
score: 0
upvote count: 1
tagged with: resampling
has comment: http://stackoverflow.com/comment/90285774
downvote count: 1
has comment: http://stackoverflow.com/comment/90283545
has comment: http://stackoverflow.com/comment/90284175
tagged with: quantitative-finance
has comment: http://stackoverflow.com/comment/90284387
has comment: http://stackoverflow.com/comment/90286498
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90285676
type: Question
tagged with: pandas
tagged with: grouping

http://stackoverflow.com/comment/90376950
type: Comment
type: QuestionComment
has text: I fix it, but this mistake was caused by writing code in stackoverflow ;) Then I don't have this mistake in my real code and it doesn't work.
comment on: http://stackoverflow.com/q/51707986
score: 0

http://stackoverflow.com/comment/90459889
type: Comment
type: QuestionComment
score: 0
has text: @Laurent H. Happy to use US/UK spelling with -ize, but I'm Australian and -ise is [acceptable spelling here](https://en.wikipedia.org/wiki/Macquarie_Dictionary#preferred_spellings)
comment on: http://stackoverflow.com/q/51749631

http://stackoverflow.com/a/51754026
answers question: http://stackoverflow.com/q/51753964
has comment: http://stackoverflow.com/comment/90467877
type: Answer
has comment: http://stackoverflow.com/comment/90467861
has comment: http://stackoverflow.com/comment/90467823
has comment: http://stackoverflow.com/comment/90468193
has body: You can sort by multiple columns. Just put both columns in the list. duplicates = duplicates.sort_values(['Last Name', 'Address Type'], ascending = True)
score: 0

http://stackoverflow.com/comment/90322591
comment on: http://stackoverflow.com/q/51679658
score: 0
type: Comment
type: QuestionComment
has text: `self.destdir`. Also, you are allowing for destdir to be passed to the initializer, but never using it?

http://stackoverflow.com/q/51707213
has title: Make code uncaseSensitive, Python, Discord Bot
type: Question
has answer: http://stackoverflow.com/a/51707602
tagged with: discord.py
tagged with: bots
score: 1
has body: How can i make this code icaseSensitive? I have tried bot = commands.Bot(command_prefix=';', case_insensitive=True Is the code i have here on the rewrite branch? I know how on async def on_message but have heard it is not that smart to use async def on_message Code: import discord from discord.ext import commands from discord.ext.commands import Bot import asyncio bot = commands.Bot(command_prefix=';', case_insensitive=True) @bot.command(pass_context=True) @commands.has_role("Admin") async def info(ctx, user: discord.Member): embed = discord.Embed(title="{}'s info:".format(user.name), description="Here is his description. Bounty is around 1000 Dubloons", color=0x00ff00) embed.add_field(name="Navn", value=user.name, inline=True) embed.add_field(name="ID", value=user.id, inline=True) embed.add_field(name="Status", value=user.status, inline=True) embed.add_field(name="Høyeste rolle", value=user.top_role) embed.add_field(name="Ble med", value=user.joined_at) embed.set_thumbnail(url=user.avatar_url) await bot.say(embed=embed) edit: from itertools import product def aliases(info): return [''.join(item) for item in product(*((c.lower(), c.upper()) for c in info))] @bot.command(pass_context=True, aliases=aliases('info')) @commands.has_role("Admin") async def info(ctx, user: discord.Member): embed = discord.Embed(title="{}'s info:".format(user.name), description="Here is his description. Bounty is around 1000 Dubloons", color=0x00ff00) embed.add_field(name="Navn", value=user.name, inline=True) embed.add_field(name="ID", value=user.id, inline=True) embed.add_field(name="Status", value=user.status, inline=True) embed.add_field(name="Høyeste rolle", value=user.top_role) embed.add_field(name="Ble med", value=user.joined_at) embed.set_footer(text="© Solmester123456 // Thomas") embed.set_thumbnail(url=user.avatar_url) await bot.say(embed=embed)
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
tagged with: discord
accepted answer: http://stackoverflow.com/a/51707602
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90364442
comment on: http://stackoverflow.com/a/51701092
has text: this is returning the same value again and again. [{'823feb2': 'Merge pull request #1160'}, {'823feb2': 'Merge pull request #1160'}]
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51732160
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90486130
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51722840
answers question: http://stackoverflow.com/q/51722840
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90489661
has comment: http://stackoverflow.com/comment/90429105
has comment: http://stackoverflow.com/comment/90429214
has body: There are some internal reasons why split decisions in trees prefer a &lt;= relation (rather than equality, even if the latter might seem to make more sense for a human reader), but such representation details should not pose any difficulty in the interpretation, which is what you are asking about here. So, practically speaking: children &lt;= 3.5 means less than four children (assuming variable is integer) MaritalStatus_M &lt;= 0.5 for a binary variable means MaritalStatus_M==0 (i.e. not married) Sales Reason_Price&lt;=0.5 for a binary variable means Sales Reason_Price==0 Tenure_Months&lt;= 0.5 means Tenure_Months==0 (assuming variable is integer)

http://stackoverflow.com/a/51738206
has body: The convention to structure unittests is like this: Hold all tests in tests directory. test module will be named as test_modulea.py with class TestClassA nosetests -vw tests to run all tests.
answers question: http://stackoverflow.com/q/51737662
score: 0
type: Answer

http://stackoverflow.com/q/51691265
possible better answer: http://stackoverflow.com/a/51691383
upvote count: 0
downvote count: 3
accepted answer: http://stackoverflow.com/a/51691346
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51691346
has answer: http://stackoverflow.com/a/51691383
has comment: http://stackoverflow.com/comment/90344323
answer count: 2
tagged with: pandas
has title: dictionary column operation counter
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has body: ‘fruit_classifier.csv’​ ​ is​ ​ a ​ ​ CSV​ ​ file​ ​ which​ ​ is​ ​ the​ ​ output​ ​ of​ ​ a ​ ​ program​ ​ which​ ​ classifies​ ​ images​ ​ into different​ ​ kind​ ​ of​ ​ fruits.​ ​ Each​ ​ classification​ ​ is​ ​ scored​ ​ in​ ​ terms​ ​ of​ ​ percentage.​ ​ For​ ​ example,​ ​ image ‘a.jpg’​ ​ has​ ​ ​ a ​ ​ 99.18%​ ​ chance​ ​ it​ ​ is​ ​ a ​ ​ Pear,​ ​ 0.15%​ ​ chance​ ​ it​ ​ is​ ​ an​ ​ orange​ ​ etc. he​ ​ first​ ​ new​ ​ row​ ​ to​ ​ be​ ​ added​ ​ must​ ​ show​ ​ the​ ​ percentage​ ​ of​ ​ images,​ ​ for​ ​ each​ ​ type​ ​ of​ ​ fruit, where​ ​ the​ ​ detection​ ​ value​ ​ was​ ​ greater​ ​ than​ ​ 50%.​ ​ i.e.​ ​ if​ ​ out​ ​ of​ ​ 15​ ​ images,​ ​ if​ ​ Apples​ ​ had​ ​ 6 ​ ​ images where​ ​ the​ ​ detection​ ​ value​ ​ was​ ​ greater​ ​ than​ ​ 50%,​ ​ you​ ​ need​ ​ to​ ​ display​ ​ 6*100/15​ ​ = ​ ​ 40%​ ​ for Apples. thanks in advance hope hear from you soon i am new in python and i don't get idea how to handle each column in csv seprately
score: -3
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/51783056
score: 1
answers question: http://stackoverflow.com/q/51777072
has body: The embedding layer can only be used as the first layer in a model as the documentation states, so something like this: inputs = Input(shape=(timesteps, input_dim)) embedded = Embedding(vocab_size, embedding_size, mask_zero=True, ...))(inputs) encoded = LSTM(latent_dim)(embedded) We should firstly tokenize the text, embedding it with pre-trained vector, right? Yes, this is the default option. You only train your own embeddings if you have a sufficiently large enough corpus otherwise GloVe are often used. There is a Keras example that uses GloVe and the internal Tokenizer to pass text into a model with Embedding layer. For decoding, you will need a Dense layer but using TimeDistributed is optional with version 2. By default Dense will apply the kernel to every timestep of your 3D tensor you pass: decoded = RepeatVector(timesteps)(encoded) decoded = LSTM(input_dim, return_sequences=True)(decoded) decoded = Dense(vocab_size, activation='softmax')(decoded) # (batch_size, timesteps, vocab_size) It's worth noting that taking the top N most frequent words will speed up training, otherwise that softmax will become very costly to compute. The Keras example also takes a limited number of words and every other word is mapped to a special UNKnown token.
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90541743
accepted answer of: http://stackoverflow.com/q/51777072

http://stackoverflow.com/a/51677151
answers question: http://stackoverflow.com/q/51676842
accepted answer of: http://stackoverflow.com/q/51676842
has comment: http://stackoverflow.com/comment/90318300
score: 0
type: AcceptedAnswer
has body: Just keep a "max list" and update it as you go. maxList = [] currList = [] lst = [4,5,2,19,3,8,9] n = 8 for x in lst: if x &lt; n: currList.append(x) if len(currList) &gt; len(maxList): maxList = currList else: currList = [] I'm pretty sure that will work
type: Answer

http://stackoverflow.com/a/51747165
score: 0
has comment: http://stackoverflow.com/comment/90458059
type: Answer
has comment: http://stackoverflow.com/comment/90479486
has body: A reactor does multiplexing in a single process and a single thread. It does not launch multiple threads for you automatically. reactor.run() is expected to run until the entire program shuts down. No application code comes after that, typically. Perhaps you want to launch multiple processes, but you'll need to use another library such as concurrent.futures or multiprocessing or Twisted's spawnProcess().
answers question: http://stackoverflow.com/q/51746788

http://stackoverflow.com/comment/90271349
type: QuestionComment
comment on: http://stackoverflow.com/q/51640882
has text: @Water Malone check please the second picture look to from . import views , it takes import as a module not the ( . ). i guess that is the problem and i dont know how to solve it can you help please??
score: 0
type: Comment

http://stackoverflow.com/comment/90264209
comment on: http://stackoverflow.com/a/51643356
type: Comment
has text: Thanks, but this code is part of a software plugin, so therefore I can't add any more drivers / components to the code.
type: AnswerComment
score: 0

subtraction
tags question: http://stackoverflow.com/q/51714025
tags question: http://stackoverflow.com/q/51688179
tags question: http://stackoverflow.com/q/51646101
tag name: subtraction
type: Tag

http://stackoverflow.com/q/51722323
tagged with: python
possible better answer: http://stackoverflow.com/a/51731697
accepted answer: http://stackoverflow.com/a/51732804
has answer: http://stackoverflow.com/a/68992343
has comment: http://stackoverflow.com/comment/90405565
type: AnsweredQuestion
tagged with: compiler-errors
downvote count: 2
has answer: http://stackoverflow.com/a/51731697
tagged with: cython
upvote count: 7
has answer: http://stackoverflow.com/a/51732804
has body: I haven't been able to find much about this, but when attempting to compile one of my python scripts with cython, it gives me this error: Error compiling Cython file: ------------------------------------------------------------ ... import traceback #line:24 import bcrypt #line:25 Y =str (os .path .dirname (os .path .abspath (__file__ )))#line:28 IH =open #line:29 IA =str #line:30 IK =print #line:31 ^ ------------------------------------------------------------ headlessobfu.pyx:29:4: Expected an identifier or literal Traceback (most recent call last): File "setup.py", line 5, in &lt;module&gt; ext_modules = cythonize("headlessobfu.pyx") File "C:\Users\justi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Cython\Build\Dependencies.py", line 1026, in cythonize cythonize_one(*args) File "C:\Users\justi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Cython\Build\Dependencies.py", line 1146, in cythonize_one raise CompileError(None, pyx_file) Cython.Compiler.Errors.CompileError: headlessobfu.pyx I haven't been able to find the exact cause of this error. I was able to get simple scripts to compile just fine. The python runs just fine on it's own. Is it a problem with my python formatting? Here is the command line argument I am running: py setup.py build_ext --inplace If anyone has a solution please let me know. Thanks.
type: Question
has title: Cython compiler error
has comment: http://stackoverflow.com/comment/90405718
has comment: http://stackoverflow.com/comment/90405469
answer count: 3
score: 5
favorite count: 0
has comment: http://stackoverflow.com/comment/90421777
has comment: http://stackoverflow.com/comment/90407325

http://stackoverflow.com/a/51646771
type: Answer
has body: stateNames = [statesDict.get(i) for i in statesAbbrv]
score: 0
answers question: http://stackoverflow.com/q/51640610

http://stackoverflow.com/comment/90449799
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51745035
has text: Probably can also create the groupby once and then `group.sum() - group.first()` as well...
score: 3

http://stackoverflow.com/a/51792085
has comment: http://stackoverflow.com/comment/90542380
has body: You can just define the wrap on the fly: def fun(a, b, c, d): # raw function print(a + b + c - d) def closed(d): fun(5,6,7,d) closed(10) You can use this with lambda, but @juanpa points out you should not if there is no reason to. The above code will result in 8. This method by the way is not Python specific, most languages would support this. But if you need a closure in a sense that it relies on the wrapper variables, than no, and there is good reason not to. This will create essentially a non-working function, that relies on wrapping. In this case using a class maybe better: class fun: def __init__(self,*args): #Can use specific things, not just *args. self.args = args #Or meaningful names def __call__(self,a, b, c, d): # raw function print(a + b + c - d,self.args) def closed(d): fun("some",3,"more",['args'])(5,6,7,d) closed(10) or using *args/**kwargs directly and passing extra variables through that. Otherwise I am not familiar with a "inner function" construct that only works after wrapping.
score: 2
has comment: http://stackoverflow.com/comment/90543821
has comment: http://stackoverflow.com/comment/90544670
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90541797
has comment: http://stackoverflow.com/comment/90543695
has comment: http://stackoverflow.com/comment/90541733
has comment: http://stackoverflow.com/comment/90542625
type: Answer
has comment: http://stackoverflow.com/comment/90543804
upvote count: 2
has comment: http://stackoverflow.com/comment/90541829
accepted answer of: http://stackoverflow.com/q/51792030
has comment: http://stackoverflow.com/comment/90542356
answers question: http://stackoverflow.com/q/51792030
has comment: http://stackoverflow.com/comment/90541758
has comment: http://stackoverflow.com/comment/90542246
has comment: http://stackoverflow.com/comment/90541749

http://stackoverflow.com/comment/90563999
has text: Happy to upload what I have, but it doesn't work so I don't know how much help that will be, especially if the solution is easy!
comment on: http://stackoverflow.com/q/51796531
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51643820
has answer: http://stackoverflow.com/a/51643906
score: -2
tagged with: compilation
has comment: http://stackoverflow.com/comment/90251896
upvote count: 0
answer count: 1
has title: Python Code not working - why?
favorite count: 0
has body: I am trying to learn Python and tried to run a code from https://github.com/joelgrus/data-science-from-scratch/blob/master/code/statistics.py However the code runs neither in Python nor in Ipython. First it says, there is no module named linear_algebra, I am using is Anaconda3, at least I don't know which equivalent would be the correct one. Second the code does not accept the lines from "print" ~ around line 115, it always says SyntaxError: Invalid Syntax. I've seen a similar question like 2-3 times when searching, but the answers could help me any further.....can someone explain, why the code isn't working or how I have to change it to use it?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90253238
tagged with: python
downvote count: 2
has comment: http://stackoverflow.com/comment/90251921
type: Question

http://stackoverflow.com/a/51683936
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51683574
downvote count: 0
has body: To wrap this up. As @user2906838 pointed out the problem was that I was inside anaconda virtural environment before I ran tmux. When I exited the environment before running tmux and entered the environment inside of tmux everything worked as usual.

http://stackoverflow.com/a/51703047
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/90412638
answers question: http://stackoverflow.com/q/51699886
has comment: http://stackoverflow.com/comment/90398304
has body: Apparently, you installed Pandas for python2 by pip. For python3, you need to use pip3. However, it doesn't matter regarding your problem. Probably, you don't choose the right project interpreter. For Pycharm, it supports the system python(2 and 3), as well as the virtual environment. You may install the Pandas module in system python, but use the virtual environment as default. Simple solution Make sure you select the interpreter you want (system or virtualenv); Check package list, if there is Pandas module; If yes, refresh the project list; If not, simply click + to search Pandas and install it to your project interpreter.

http://stackoverflow.com/a/51770460
answers question: http://stackoverflow.com/q/51768996
type: Answer
upvote count: 1
has body: Maybe not the most elegant way, but it should answer your question: fig, (empty, quarter, half, three_quarters, full) = plt.subplots(nrows=1, ncols=5, figsize=(18, 3)) empty.pie([100], colors = ['white'], wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'black' }) quarter.pie([75, 25], colors = ['white', 'black'], startangle=90, wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'black' }) half.pie([50, 50], colors = ['white', 'black'], startangle=90, wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'black' }) three_quarters.pie([25, 75], colors = ['white', 'black'], startangle=90, wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'black' }) full.pie([100], colors = ['black'], wedgeprops = { 'linewidth' : 1, 'edgecolor' : 'black' } )
score: 1
downvote count: 0

http://stackoverflow.com/comment/90391157
type: Comment
has text: it doesn't return the true value and it takes 5 seconds it's too slow and doesn't return the exact value
comment on: http://stackoverflow.com/a/51714672
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90528384
has text: @ascii_walker: for the full skin-tone modifier list, see https://www.unicode.org/emoji/charts/full-emoji-modifiers.html; you'd have to separately create a regex for the [5 tone component codepoints](https://www.unicode.org/emoji/charts/full-emoji-modifiers.html#component).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51785357
type: Comment

http://stackoverflow.com/a/54913163
score: -1
has body: You should make sure that Z doesn't contain any negative value! test if you have negative values: print len([_ for _ in z if _ &lt; 0])
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/96626057
answers question: http://stackoverflow.com/q/51792598
downvote count: 1

http://stackoverflow.com/a/51763143
answers question: http://stackoverflow.com/q/51762067
score: 0
type: Answer
has body: Assuming regex is NOT a must. st = '2.00 00 DBEL 215 Frox Lyxo 2.000 2.00' s = [i.isdigit() for i in st.split(' ') if not(i.isalpha())] print('no of int : ', s.count(True), 'no of float : ', s.count(False))

http://stackoverflow.com/q/51667852
has answer: http://stackoverflow.com/a/51962035
has title: Text-Classification RNN - LSTM - Error checking target
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51723828
tagged with: machine-learning
tagged with: text-classification
type: Question
has comment: http://stackoverflow.com/comment/90321082
tagged with: recurrent-neural-network
tagged with: lstm
score: 0
answer count: 2
has body: i'm developing a LSTM - RNN text classification with Keras This is my Code. import numpy as np import csv import keras import sklearn import gensim import random import scipy from keras.preprocessing import text from keras.preprocessing import sequence from keras.preprocessing.text import Tokenizer from keras.models import Sequential from keras.layers.core import Dense , Dropout , Activation , Flatten from keras.layers.convolutional import Convolution1D, MaxPooling1D from keras.layers import Embedding , LSTM from sklearn import preprocessing from sklearn.base import BaseEstimator from sklearn.svm import LinearSVC , SVC from sklearn.naive_bayes import MultinomialNB from gensim.models.word2vec import Word2Vec from gensim.models.doc2vec import Doc2Vec , TaggedDocument # size of the word embeddings embeddings_dim = 300 # maximum number of words to consider in the representations max_features = 30000 # maximum length of a sentence max_sent_len = 50 # percentage of the data used for model training percent = 0.75 # number of classes num_classes = 2 print ("") print ("Reading pre-trained word embeddings...") embeddings = dict( ) embeddings = gensim.models.KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin.gz" , binary=True) print ("Reading text data for classification and building representations...") data = [ ( row["sentence"] , row["label"] ) for row in csv.DictReader(open("test-data.txt"), delimiter='\t', quoting=csv.QUOTE_NONE) ] random.shuffle( data ) train_size = int(len(data) * percent) train_texts = [ txt.lower() for ( txt, label ) in data[0:train_size] ] test_texts = [ txt.lower() for ( txt, label ) in data[train_size:-1] ] train_labels = [ label for ( txt , label ) in data[0:train_size] ] test_labels = [ label for ( txt , label ) in data[train_size:-1] ] num_classes = len( set( train_labels + test_labels ) ) tokenizer = Tokenizer(num_words=max_features, filters='!"#$%&amp;()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~\t\n', lower=True, split=" ") tokenizer.fi…
has comment: http://stackoverflow.com/comment/90303801

http://stackoverflow.com/comment/90320638
score: 1
type: QuestionComment
has text: How exactly did you run this? You didn't show the command line you were actually using.
comment on: http://stackoverflow.com/q/51678520
type: Comment

http://stackoverflow.com/comment/90478567
type: QuestionComment
comment on: http://stackoverflow.com/q/51759721
type: Comment
score: 0
has text: What's special about `\x04`? What about `\x20`?

http://stackoverflow.com/a/51792824
downvote count: 2
answers question: http://stackoverflow.com/q/51785340
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/90547072
has comment: http://stackoverflow.com/comment/90546934
score: -2
has body: #!/usr/bin/env perl # unique_random.pl : get N non-repeating random numbers from list use strict; use warnings; use feature qw(say); use Tie::File; use List::Util qw(shuffle); # get the number of values to print from command line my $n = shift @ARGV; $n = defined($n) ? int($n) : 10; if ($n &lt; 1 or $n &gt; 100) { # sanity check $n = 10; } # persistent file of shuffled numbers tied to an array my $file = 'random_numbers.txt'; tie my @numbers, 'Tie::File', $file or die "Can't tie $file"; # initialize the array if it's empty or not full enough if ( scalar(@numbers) &lt;= $n ) { @numbers = shuffle (1000 .. 99999); # all 4 and 5 digit numbers } # get the first $n numbers and delete them from the array for ( 1 .. $n ) { say shift @numbers; } We could play Perl golf and make this more compact, but I went for legibility here.
has comment: http://stackoverflow.com/comment/90565132

http://stackoverflow.com/comment/90387968
has text: Dict comprehensions aren't inherently inefficient, your *algorithm* is: `{x: s1.count(x) for x in s1}` is needlessly inefficient. Instead of a linear time operation you are getting a quadratic time operation because .count is linear on the length of s1. Also, `{k:s2dict[k] for k in s2dict and s1dict[k] >= s2dict[k]}` is not doing what you think it is doing... what are you trying to do with `and` there?
type: QuestionComment
comment on: http://stackoverflow.com/q/51713293
type: Comment
score: 0

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51697982
tags question: http://stackoverflow.com/q/51704814
tags question: http://stackoverflow.com/q/51761130
tags question: http://stackoverflow.com/q/51668784
tag name: kivy-language
tags question: http://stackoverflow.com/q/51684097
tags question: http://stackoverflow.com/q/51758975
tags question: http://stackoverflow.com/q/51798287
tags question: http://stackoverflow.com/q/51716333

http://stackoverflow.com/q/51743396
has comment: http://stackoverflow.com/comment/90446849
type: Question
tagged with: html-table
has comment: http://stackoverflow.com/comment/90517140
answer count: 1
downvote count: 0
has title: Getting AttributeError: 'Series' object has no attribute 'to_html'?
favorite count: 0
has body: My code looks something like this where i am trying to make a table of column "Supplier" and "Discount" Discount_By_Suppliers = data.groupby(["Supplier"])["Discount"].sum() Top_20_suppliers = Discount_By_Suppliers.nlargest(25) print(Top_20_suppliers) Top_20_suppliers.to_html('index.html') what i am doing wrong? please help.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/67506340
score: 3
upvote count: 3

http://stackoverflow.com/a/51734885
answers question: http://stackoverflow.com/q/51734814
score: 2
downvote count: 0
type: Answer
has body: One way purely in pandas would be to create a MultiIndex from product, then convert it to a dataframe: &gt;&gt;&gt; df1 0 0 drug1 1 drug2 2 drug3 &gt;&gt;&gt; df2 0 0 disease1 1 disease2 2 disease3 df3 = (pd.MultiIndex.from_product([df1[0],df2[0]]) .to_frame() .reset_index(drop=True)) &gt;&gt;&gt; df3 0 1 0 drug1 disease1 1 drug1 disease2 2 drug1 disease3 3 drug2 disease1 4 drug2 disease2 5 drug2 disease3 6 drug3 disease1 7 drug3 disease2 8 drug3 disease3
upvote count: 2

http://stackoverflow.com/a/51733590
upvote count: 4
has comment: http://stackoverflow.com/comment/113332046
downvote count: 0
has comment: http://stackoverflow.com/comment/90431277
accepted answer of: http://stackoverflow.com/q/51733545
answers question: http://stackoverflow.com/q/51733545
has comment: http://stackoverflow.com/comment/90430507
type: AcceptedAnswer
has body: Yes, you can "unpack" an iterable into position parameters in Python, by using a single asterisk (*) in the function call, like: value_fields = ('name', 'other_model__title') model.objects.all().values(*value_fields) # ^ asterisk If you call a function f(..) with an iterable xs like f(*xs), then Python will call it like f(x1, x2, xn) (with xi an individual element of the xs iterable). Since you stored the parameters in a tuple (a tuple is an iterable), it will thus call the .values(..) function with .values('name', 'other_model__title')). By using two asterisks (like f(**some_dict)), you can unpack dictionary-like objects into named parameters.
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/90430575

http://stackoverflow.com/comment/90292574
has text: Can you please add the `views.py`?
comment on: http://stackoverflow.com/q/51664603
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51641669
has body: Make a list of pairs, (difference, number) for each element in B. For each item in A, compute its difference with each item in B and if that difference is smaller than the stored one, replace the stored data. A = (762.859793, 763.544183, 764.272883, 766.190053, 767.108693, 767.123893, 768.933893, 770.619013, 771.375173, 771.522083, 774.9478730000001, 775.138843, 775.463863, 776.332693, 776.466303, 777.650083, 778.3751129999999, 781.922783, 782.592033, 784.224423, 784.779903, 785.2743429999999, 787.098133, 787.8258030000001, 787.8593030000001, 788.194393, 790.939383, 791.379753, 793.572803, 796.093073, 796.720693, 796.852473, 798.519643, 800.145803, 800.758723, 801.239613, 801.332453, 801.819333, 805.290823, 806.404353, 807.995663, 808.683403, 810.0645030000001, 810.695673, 810.7933929999999, 811.150203, 814.270803, 814.706783, 815.6527629999999, 819.127253, 819.820733, 821.030753, 821.166193, 823.111683, 824.637013, 826.707083, 826.997243, 827.441463, 828.529713, 830.364193, 831.241203, 831.2571929999999, 832.635243, 832.9749730000001, 834.222713, 837.932063, 838.250483, 838.695363, 840.0615730000001, 841.246143, 841.300043, 841.5062230000001, 844.7620730000001, 845.1879230000001, 846.261283, 847.139523, 849.0279429999999, 850.5646929999999, 850.726553, 851.8736529999999, 853.9559830000001, 854.171933, 857.674983, 858.035633, 858.327443, 858.9393230000001, 859.365103, 860.0646929999999, 861.035573, 861.496883, 864.127743, 866.558833, 867.0207429999999, 868.135673, 869.329093, 870.5860529999999, 871.1149230000001, 871.691343, 872.156483, 875.2681230000001, 875.921803, 876.6624029999999, 879.2358929999999, 879.7697029999999, 880.6190730000001, 882.563473, 883.1651529999999, 883.6522130000001, 884.311393, 886.585383, 888.0967929999999, 889.6549630000001, 890.564143, 891.0488230000001, 892.887933, 893.3944630000001, 896.817743, 897.9441429999999, 898.577573, 898.681813, 900.280573, 901.308643, 903.324453, 905.128653, 905.9143029999999, 906.190423, 906.641533, 907.232963…
has comment: http://stackoverflow.com/comment/90248008
has comment: http://stackoverflow.com/comment/90248369
has comment: http://stackoverflow.com/comment/90248917
has comment: http://stackoverflow.com/comment/90248125
has comment: http://stackoverflow.com/comment/90248430
score: 0
answers question: http://stackoverflow.com/q/51641518
has comment: http://stackoverflow.com/comment/90247975
type: Answer

http://stackoverflow.com/comment/90298837
comment on: http://stackoverflow.com/q/51667999
type: Comment
score: 0
type: QuestionComment
has text: When you typing '2' it means that your val before casting to int equals "'2'". It's not an integer.

http://stackoverflow.com/a/51665199
answers question: http://stackoverflow.com/q/51652313
type: AcceptedAnswer
type: Answer
has body: The problem where the things would stick together is simple, even though you always checked for collision, the time where it would actually recognise it would be when the circles would be past touching but slightly into each other. The circles now bounce and move a little. However they have not moved enough to completely to not be touching, this mean the bounce again and it goes in a loop. I made code that fixes this, but you have to change the bounce function and use your code, as mine is not that perfect, but functional. import pygame pygame.init() import random import numpy HEIGHT = 500 WIDTH = 500 NUM_BALLS = 2 #setup win = pygame.display.set_mode((WIDTH,HEIGHT)) pygame.display.set_caption("Simulation") class Particle(object): def __init__(self, x, y , radius): self.x = x self.y = y self.radius = radius self.xvel = random.randint(1,5) self.yvel = random.randint(1,5) self.colideCheck = [] def Draw_circle(self): pygame.draw.circle(win, (255,0,0), (int(self.x), int(self.y)), self.radius) def redrawGameWindow(): win.fill((0,0,0)) for ball in balls: ball.Draw_circle() pygame.display.update() def bounce(v1,v2, mass1 = 1, mass2 = 1): #i Tried my own bouncing mechanism, but doesn't work completly well, add yours here multi1 = mass1/(mass1+mass2) multi2 = mass2/(mass1+mass2) deltaV2 = (multi1*v1[0]-multi2*v2[0],multi1*v1[1]-multi2*v2[1]) deltaV1 = (multi2*v2[0]-multi1*v1[0],multi2*v2[1]-multi1*v1[1]) print("preVelocities:",v1,v2) return deltaV1,deltaV2 def checkCollide(circ1Cord,circ1Rad,circ2Cord,circ2Rad): tryDist = circ1Rad+circ2Rad actualDist = dist(circ1Cord,circ2Cord) if dist(circ1Cord,circ2Cord) &lt;= tryDist: return True return False def dist(pt1,pt2): dX = pt1[0]-pt2[0] dY = pt1[1]-pt2[1] return (dX**2 + dY**2)**0.5 balls = [] for turn in range(NUM_BALLS): balls.append(Particle(random.randint(60,WIDTH-60),random.randint(60,HEIGHT-60),60)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False for ball in balls: if (ball.…
score: 0
accepted answer of: http://stackoverflow.com/q/51652313

http://stackoverflow.com/comment/90341919
comment on: http://stackoverflow.com/q/51690051
score: 1
has text: You can't do it in linear time, as you need to find all the even elements, and then for each group of m elements you need to find the amount of relevant groups.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51653771
has title: Check for multiple integer values in dictionary where dictionary values are lists of integers
tagged with: python
has answer: http://stackoverflow.com/a/51654536
tagged with: dictionary
has answer: http://stackoverflow.com/a/51653956
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51654118
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/51653891
has answer: http://stackoverflow.com/a/51655518
answer count: 6
has answer: http://stackoverflow.com/a/51653936
has body: I have a dictionary like this. {1: [1], 2: [1, 2], 3: [1, 2, 3], 19: [1, 2, 19], 4: [1, 2, 3, 4], 23: [1, 2, 3, 23], 20: [1, 2, 19, 20], 5: [1, 2, 3, 4, 5], 24: [1, 2, 3, 23, 24], 21: [1, 2, 19, 20, 21], 6: [1, 2, 3, 4, 5, 6], 25: [1, 2, 3, 23, 24, 25], 22: [1, 2, 19, 20, 21, 22], 7: [1, 2, 3, 4, 5, 6, 7], 26: [1, 2, 3, 4, 5, 6, 26], 8: [1, 2, 3, 4, 5, 6, 7, 8], 27: [1, 2, 3, 4, 5, 6, 26, 27], 9: [1, 2, 3, 4, 5, 6, 7, 8, 9], 28: [1, 2, 3, 4, 5, 6, 26, 27, 28], 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 29: [1, 2, 3, 4, 5, 6, 26, 27, 28, 29], 11: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 30: [1, 2, 3, 4, 5, 6, 26, 27, 28, 29, 30], 12: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 31: [1, 2, 3, 4, 5, 6, 26, 27, 28, 29, 30, 31], 13: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 32: [1, 2, 3, 4, 5, 6, 26, 27, 28, 29, 30, 31, 32], 14: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 33: [1, 2, 3, 4, 5, 6, 26, 27, 28, 29, 30, 31, 32, 33], 15: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 16: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 17: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], 18: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]} I want to know in how many of the values, [2,3] are present. Similarly, I want to do it for other pairs like [3,4], [4,5] etc.
possible better answer: http://stackoverflow.com/a/51653891
score: 0
accepted answer: http://stackoverflow.com/a/51654118

http://stackoverflow.com/a/51685086
has comment: http://stackoverflow.com/comment/90333855
has body: Then why not store all the crawlers in a dict from the beginning? As an example: from Scripts_mart.wat_ver2 import crawler_watsons from Scripts_mart.cosmed_ver1 import crawler_cosmed from Scripts_mart.pxmart_ver1 import crawler_pxmart class MartCrawler(): def __init__(self, *args): self.crawlers = {} for crawler in args: # use some introspection to get the name of the classes. # The names should be "crawler_watsons", etc self.crawlers[crawler.__name__] = crawler() def crawler_testing(self): result_pack = {} for name, crawler in self.crawlers.items(): result_back[name] = crawler.run_before_insert() return result_back martCrawler = MartCrawler(crawler_watsons, crawler_cosmed, crawler_pxmart) Just have in mind that the names in your dict will be the actual names of the imported classes, not 'wat', 'pos' and 'pxm'. But if this is a problem you can use some string manipulation and/or regexes to fix it. For example you could replace crawler.__name__ with crawler.__name__[8:11]
has comment: http://stackoverflow.com/comment/90332250
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90334004
has comment: http://stackoverflow.com/comment/90336535
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51684920
answers question: http://stackoverflow.com/q/51684920
has comment: http://stackoverflow.com/comment/90334192
score: 1
has comment: http://stackoverflow.com/comment/90334416

http://stackoverflow.com/comment/130128598
comment on: http://stackoverflow.com/a/51698883
has text: Webargs 6.x and later no longer support searching multiple locations in the same `@use_args` or `@use_kwargs` decorator. Instead, the above answer needs to be modified to use multiple `@use_args()` calls. `@use_args({'username': fields.Str(...)}, location='view_args'); @use_args({'page': fields.Int(...)}, location-'query'); def(get...)`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51705941
answer count: 2
accepted answer: http://stackoverflow.com/a/51706745
downvote count: 0
possible better answer: http://stackoverflow.com/a/51706180
has answer: http://stackoverflow.com/a/51706180
tagged with: pandas
favorite count: 0
tagged with: python-3.x
has body: Regarding the following Pandas dataframe, idx = pd.MultiIndex.from_product([['A001', 'B001','C001'], ['0', '1', '2']], names=['ID', 'Entries']) col = ['A', 'B'] df = pd.DataFrame('-', idx, col) df.loc['A001', 'A'] = [10,10,10] df.loc['A001', 'B'] = [90,84,70] df.loc['B001', 'A'] = [10,20,30] df.loc['B001', 'B'] = [70,86,67] df.loc['C001', 'A'] = [20,20,20] df.loc['C001', 'B'] = [98,81,72] df.loc['D001', 'A'] = [20,20,10] df.loc['D001', 'B'] = [68,71,92] #df is a dataframe df I am interested to know the Ids which include the all the values from a set or list in their 'A' column. Let's define a list with values as [10,20]. In this case, I should get locations 'B001' and 'D001' as the answer since both these locations have the values mentioned the list in their 'A' column . Further can you suggest a faster implementation since I have to work on really big data set.
has title: Efficient and faster implementation of finding and matching unique values in a pandas dataframe
has answer: http://stackoverflow.com/a/51706745
tagged with: python
tagged with: indexing
type: AnsweredQuestion
tagged with: performance
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/90474345
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51757274
has text: As always in machine learning, there is no clear and 100% safe answer as it depends a lot on the data. But it could be because the learning rate. What learning rate are you employing? Do you use a callback like LearningRateSchedule or ReduceLROnPlateau?

http://stackoverflow.com/q/51778992
has comment: http://stackoverflow.com/comment/90515846
has comment: http://stackoverflow.com/comment/90516018
has comment: http://stackoverflow.com/comment/90515946
favorite count: 0
has comment: http://stackoverflow.com/comment/90517392
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90515860
has comment: http://stackoverflow.com/comment/90515988
has title: TypeError: __init__() missing 2 required positional arguments. Why is _init()_ missing arguments when it's there?
tagged with: oop
has answer: http://stackoverflow.com/a/56686782
type: Question
has body: class Vehicle: def __init__(self,vehicle_cost,vehicle_type): self.__vehicle_id =None self.__vehicle_type=vehicle_type self.__vehicle_cost=vehicle_cost self.__premium_amount=None def set_vehicle_id(self,vehicle_id): self.__vehicle_id=vehicle_id def get_vehicle_id(self): return self.__vehicle_id def set_vehicle_type(self,vehicle_type): self.__vehicle_type=vehicle_type def get_vehicle_type(self): return self.__vehicle_type def set_vehicle_cost(self,vehicle_cost): self.__vehicle_cost=vehicle_cost def get_vehicle_cost(self): return self.__vehicle_cost def set_premium_amount(self,premium_amount): self.__premium_amount=premium_amount def get_premium_amount(self): return self.__premium_amount def display_vehicle_details(self): print("Vehicle Id is",self.__vehicle_id) print("Vehicle Type is",self.__vehicle_type) print("Vehicle Cost is",self.__vehicle_cost) def calculate_premium(self): if(self.__vehicle_type =="Two Wheeler"): self.__premium_amount=self.__vehicle_cost-self.__vehicle_cost*0.98 print(self.__premium_amount) elif(self.__vehicle_type =="Four Wheeler"): self.__premium_amount=self.__vehicle_cost-self.__vehicle_cost*0.94 print(self.__premium_amount) else: print("Error: Wrong Vehicle type") obj=Vehicle(105000, "Two Wheeler") obj.calculate_premium()
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51781684
score: -1
has comment: http://stackoverflow.com/comment/90515903
tagged with: typeerror

http://stackoverflow.com/comment/91048727
type: Comment
comment on: http://stackoverflow.com/a/51769666
has text: Im getting the following error - `FieldError: Cannot resolve keyword 'userbanktransaction_set' into field. Choices are: created, email, first_name, id, is_active, is_admin, is_member, last_login, last_name, logentry, password, payment, paymentdata, pledge, updated, useralert, userbanktransaction, userchapter, userfinance, username, userprofile, userschool`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90526281
has text: You could have it as an optional parameter to your `__init__` function: `def __init__(self, loc, x, y, init_size=5)`. If not specified, then init_size will be 5. If you want a city with a different size, you can create it with `City(loc, x,y, init_size=<whatever>`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51783617

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/51648172
tag name: directed-acyclic-graphs

http://stackoverflow.com/q/51651236
downvote count: 2
tagged with: pip
linked to: http://stackoverflow.com/q/26610461
duplicate of: http://stackoverflow.com/q/26610461
has comment: http://stackoverflow.com/comment/90268067
has comment: http://stackoverflow.com/comment/90265694
has comment: http://stackoverflow.com/comment/90265954
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90265716
answer count: 1
has body: I have installed textract, python-docx, docx using pip. pip install textract The packages were successfully installed. I was able to see them when I execute pip list But when I try to import these packages it shows an import error suggesting that the module does not exist. import textract Traceback (most recent call last): File "", line 1, in ImportError: No module named textract I am using a Linux system. What exactly is the issue and how can I start solving it?
has comment: http://stackoverflow.com/comment/90265777
has title: Pip installed package shows error on import
has answer: http://stackoverflow.com/a/51651816
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90266324
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51643505
has answer: http://stackoverflow.com/a/51643806
type: Question
has answer: http://stackoverflow.com/a/51643589
downvote count: 0
has body: Here is my dataset: Unique_ID No_of_Filings Req_1 Req_2 Req_3 Req_4 RCONF045 3 Blue Red White Violet RCONF046 3 Blue Red White Brown RCONF047 3 Blue Red White Brown RCONF048 3 Black Yellow Green N/A RCONF051 4 Black Yellow Green N/A RCONF052 4 Black Brown Green Orange I've extracted the unique values from the last 4 columns (Req_1 through Req_4) by the following: pd.unique(df1"Req_1","Req_2","Req_3","Req_4".values.ravel("K")) Out[20]: array(['Blue', 'Black', 'Red', 'Yellow', 'Brown', 'White', 'Green', 'Violet', nan, 'Orange'], dtype=object) Here's what I need for the output. Frequency = how many times it shows up in the last four columns (e.g. Yellow only shows up twice) and Number of Filings = sum(No_of_Filings if the requirement is in that row). For example, Blue is in the first three rows, so that's 3 + 3 + 3 = 9 and Brown is in the second, third, and sixth row, so it's 3 + 3 + 4 = 10 Requirements Frequency Number of Filings Blue 3 9 Black 3 11 Red 3 9 Brown 3 10 White 3 9 Green 3 11 Yellow 2 7 N/A 2 7 Violet 1 3 Orange 1 4 How can I create those two columns in my newly-created dataframe above using pandas? Thanks
possible better answer: http://stackoverflow.com/a/51643589
tagged with: pandas
has answer: http://stackoverflow.com/a/51643595
favorite count: 0
has title: Counting unique values in columns - pandas Python
has answer: http://stackoverflow.com/a/51643583
tagged with: python
accepted answer: http://stackoverflow.com/a/51643583
answer count: 4
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/51765849
score: 6
tagged with: python
has title: Elasticsearch query date range does not work
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90490244
downvote count: 0
has comment: http://stackoverflow.com/comment/90490288
type: Question
has body: I am trying to query ElasticSearch to get a result between two timestamps. A typical record looks like { "_index": "cost-2018.08.09", "_type": "log", "_id": "asdasdasxsa-sdsds", "_score": 4.281278, "_source": { "index": "cost-2018.08.09", "app_group": "shop", "timestamp": "2018-08-09T00:00:04.349692" } } And the query I use to retrieve every shop from app_group between 2 timestamps: GET /cost-2018.08.09/_search?q=app_group:shop { "query": { "range": { "timestamp": { "gte": "2018-08-09 04:00:04", "lt": "2018-08-09 04:30:06" } } } Only returns every shop, but does not check for any timestamp. What's weird, is that even if I include error on purpose on the query: GET /cost-2018.08.09/_search?q=app_group:shop { "query": { "range": { "timestamp": { "gte": "2018-08-asdadsx09 04:00:04", "lt": "2018-08-09asdasd 04:30:06" } } } I got the exact same answer. Like it does not take the query into consideration. Some notes: In Python, my code looks like: result = es_client.search(index='cost-2018.07.26', q='app_group:shop', filter_path=['hits.hits._source'], body={ "query": { "range": { "timestamp": { "gte": "2018-08-09 04:00:04", "lt": "2018-08-09 04:30:06" } } } }) The timestamp field of the record is indeed interpreted as a date and not a String. What do I miss?
upvote count: 6
has comment: http://stackoverflow.com/comment/90490286
has answer: http://stackoverflow.com/a/51861519
accepted answer: http://stackoverflow.com/a/51861519
tagged with: elasticsearch
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90490491

http://stackoverflow.com/comment/90442053
type: Comment
has text: And what happens with this code (apart from an error that `char` is not defined)?
comment on: http://stackoverflow.com/q/51739663
score: 0
type: QuestionComment

http://stackoverflow.com/q/51772493
has answer: http://stackoverflow.com/a/59635707
has answer: http://stackoverflow.com/a/75068743
answer count: 3
downvote count: 0
has body: I'm new to Granger Causality and would appreciate any advice on understanding/interpreting the results of the python statsmodels output. I've constructed two data sets (sine functions shifted in time with noise added) and put them in a "data" matrix with signal 1 as the first column and signal 2 as the second. I then ran the tests using: granger_test_result = sm.tsa.stattools.grangercausalitytests(data, maxlag=40, verbose=True)` The results showed that the optimal lag (in terms of the highest F test value) were for a lag of 1. Granger Causality ('number of lags (no zero)', 1) ssr based F test: F=96.6366 , p=0.0000 , df_denom=995, df_num=1 ssr based chi2 test: chi2=96.9280 , p=0.0000 , df=1 likelihood ratio test: chi2=92.5052 , p=0.0000 , df=1 parameter F test: F=96.6366 , p=0.0000 , df_denom=995, df_num=1 However, the lag that seems to best describe the optimal overlap of the data is around 25 (in the figure below, signal 1 has been shifted to the right by 25 points): Granger Causality ('number of lags (no zero)', 25) ssr based F test: F=4.1891 , p=0.0000 , df_denom=923, df_num=25 ssr based chi2 test: chi2=110.5149, p=0.0000 , df=25 likelihood ratio test: chi2=104.6823, p=0.0000 , df=25 parameter F test: F=4.1891 , p=0.0000 , df_denom=923, df_num=25 I'm clearly misinterpreting something here. Why wouldn't the predicted lag match up with the shift in the data? Also, can anyone explain to me why the p-values are so small as to be negligible for most lag values? They only begin to show up as non-zero for lags greater than 30. Thanks for any help you can give.
has comment: http://stackoverflow.com/comment/138133584
score: 24
favorite count: 0
type: UnansweredQuestion
has title: Understanding output from statsmodels grangercausalitytests
tagged with: python
tagged with: statsmodels
tagged with: causality
has comment: http://stackoverflow.com/comment/99134503
has answer: http://stackoverflow.com/a/56360565
upvote count: 24
type: Question
tagged with: time-series

http://stackoverflow.com/q/51782932
linked to: http://stackoverflow.com/q/41518920
answer count: 2
has comment: http://stackoverflow.com/comment/90523389
possible better answer: http://stackoverflow.com/a/51783062
has answer: http://stackoverflow.com/a/51783062
has body: I have a Series 8 [11820] 9 [11820] 10 [11820] 11 [11820] 12 [11820] 27 [10599] 28 [10599] 29 [10599] 31 [661, 10599] 32 [661, 10599] 33 [7322] 34 [0] 37 [661] 39 [661] 40 [661] 49 [0, 661, 662, 663] I want to filter this Series with something like points[points.isin([0])] to get 34 [0] 49 [0, 661, 662, 663] but as a result I get 0 Features.
score: 0
has comment: http://stackoverflow.com/comment/90523468
tagged with: pandas
has answer: http://stackoverflow.com/a/51783035
tagged with: series
has title: Python Pandas Series.isin doesn't work
has comment: http://stackoverflow.com/comment/90523289
accepted answer: http://stackoverflow.com/a/51783035
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/90315821
type: QuestionComment
has text: Looks like your desired JSON got cutoff. Can you update?
comment on: http://stackoverflow.com/q/51676052
score: 0
type: Comment

http://stackoverflow.com/comment/90422265
type: Comment
has text: What is the dimension of your data? is it a 3D shape, a 2D curve?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51730532

http://stackoverflow.com/comment/90294171
score: 0
type: Comment
type: QuestionComment
has text: @ktb can you please explain more what do you mean about moving the data into the python application ?
comment on: http://stackoverflow.com/q/51665254

http://stackoverflow.com/comment/90421272
comment on: http://stackoverflow.com/a/51729454
type: Comment
has text: @ImranRashid, Let's replace `AdamOptimizer` with simple `GradientDescentOptimizer`, we know TensorFlow compute gradient using computing graph and autodiff method. Provided `loss = tf.reduce_mean(y-x)` derive `grad_w = mean(x)=4.88` all the time and `w_new = w_old - lr * grad_w`. If you print `w` you will get 0.49512 0.49024 0.48536 0.48048 0.4756 0.47072 ...
type: AnswerComment
score: 1

http://stackoverflow.com/q/51743705
score: 3
tagged with: tensorboard
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/51745367
tagged with: tensorflow
has title: Tensorboard not giving all the variables output for Visualization Python
upvote count: 3
accepted answer: http://stackoverflow.com/a/51745367
downvote count: 0
has body: Here are the variables that I have initialized for the tensorflow training, validation and testing. index_in_epoch = 0; perm_array = np.arange(x_train.shape[0]) np.random.shuffle(perm_array) # function to get the next batch def get_next_batch(batch_size): global index_in_epoch, x_train, perm_array start = index_in_epoch index_in_epoch += batch_size if index_in_epoch &gt; x_train.shape[0]: np.random.shuffle(perm_array) # shuffle permutation array start = 0 # start next epoch index_in_epoch = batch_size end = index_in_epoch return x_train[perm_array[start:end]], y_train[perm_array[start:end]] # parameters n_steps = seq_len-1 n_inputs = x_train.shape[2]#4 n_neurons = 200 n_outputs = y_train.shape[1]#4 n_layers = 2 learning_rate = 0.001 batch_size = 50 n_epochs = 100#200 train_set_size = x_train.shape[0] test_set_size = x_test.shape[0] tf.reset_default_graph() X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None, n_outputs]) # use LSTM Cell with peephole connections layers = [tf.contrib.rnn.LSTMCell(num_units=n_neurons, activation=tf.nn.leaky_relu, use_peepholes = True) for layer in range(n_layers)] multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers) rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32) stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons]) stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs) outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs]) outputs = outputs[:,n_steps-1,:] # keep only last output of sequence loss = tf.reduce_mean(tf.square(outputs - y)) # loss function = mean squared error optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) This is the way I am training and validating the model and also collecting the values to get displayed via tensorboard: saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for iteration in range(int(n_epochs*train_set_s…
tagged with: visualization
type: AnsweredQuestion

http://stackoverflow.com/comment/90275648
score: 0
has text: @Lisa check my comment on Wen's answer
comment on: http://stackoverflow.com/q/51655623
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51712444
answers question: http://stackoverflow.com/q/51706302
has body: ast library consumes lots of memory (refer this link) and I would suggest avoid using that while converting a simple string of dictionary format into python dictionary. Instead we can try python's builtin eval function to overcome latency due to imported modules. As some discussions suggest eval is extremely dangerous while dealing with strings which are sensitive. Example: eval('os.system("rm -rf /")'). But if we are very sure that that the csv content will not carry such sensitive commands we can make use of eval without worrying. with open('input.csv', encoding='utf-8') as fd: csv_reader = csv.DictReader(fd, delimiter=';') for row in csv_reader: # Convert dictionary in string format to python format row['alias'] = eval(row['alias']) # Filter empty dictionaries if not bool(row['alias']): continue known_as_list = [aliases for values in row['alias'].values() for aliases in values] print(known_as_list) Output C:\Python34\python.exe c:\so\51712444\eval_demo.py ['Adolf Muller'] ['Müller-Emmert', 'Adolf Muller-Emmert']
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51706302

http://stackoverflow.com/comment/90372589
comment on: http://stackoverflow.com/q/51705871
score: 0
type: Comment
type: QuestionComment
has text: `except` is not something you can just add to other statements. It's a syntax error because `except` can only be used when there is a `try:` block *first* to connect it to.

http://stackoverflow.com/comment/90339898
has text: Hi @ImportanceOfBeingErnest this works, thank you :-) I'm not sure I understand though - please can you explain, or point me to the right section of the docs? I don't find matplotlib particularly user friendly, unfortunately. Thanks for your help!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51685078
score: 0

http://stackoverflow.com/comment/90385471
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177507/discussion-between-tie-24-and-t-ray).
comment on: http://stackoverflow.com/q/51710392
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51715173
has body: I'm currently writing a simple program in python to simulate 1 + 1 dimensional SU(2) yang mills theory. For the case of SU(2) there exists a particular heatbath algorithm for updating the Link variables. In order to implement this algorithm however I need to generate a random real number X such that X is distributed according to P(x) = sqrt(1-X^2)*e^(k*X), where k is a real number from negative infinity to infinity. Fortunately there exists an algorithm to generate X's according to said distribution. Using my limited skills in python I implemented such an algorithm. Here is the code. I'm only using numpy here. def algorithm(k): count = 0 while 1 != 0: r1,r2,r3,r4 = np.random.uniform(low=0,high=1),np.random.uniform(low=0,high=1),np.random.uniform(low=0,high=1),np.random.uniform(low=0,high=1) L1 = -1/(2*k)*(np.log(r1)+np.log(r3)*np.cos(2*np.pi*r2)**2) if r4**2 &lt;= 1 - L1: X = 1 -2*L1 break else: count = count + 1 continue print(count) return X Basically, if we take three uniformly distributed random numbers in the intervals 0 to 1 we can generate a random variable l1 which is a function of the three random numbers. We accept this value L1 if 1 - L1 is greater than or equal to a fourth random number squared (uniformly distributed in the interval 0 to 1). Else we loop back to the beginning and do it all over again. We do this until we accept a value of L1. After we accept L1 we compute X as being 1 - 2*L1. This algorithm ensures that X follows the required distribution. In my program I'm going to have to generate an two dimensional array of X's. This is quite slow in my current implementation. So here's my question; is there a simpler way to do this using any preset numpy packages? If such a method doesn't exist, is there a way to vectorize this function to generate a two dimensional lattice of random X's without simply iterating it with a for loop?
answer count: 1
has comment: http://stackoverflow.com/comment/90392168
tagged with: mathematical-lattices
type: UnansweredQuestion
tagged with: physics
tagged with: python
has answer: http://stackoverflow.com/a/51715500
has title: Lattice su(2) gauge theory and random number generation in python
type: Question
has comment: http://stackoverflow.com/comment/90391805
tagged with: algorithm
tagged with: numpy
score: 0

fiware-orion
tags question: http://stackoverflow.com/q/51676088
type: Tag
tag name: fiware-orion

http://stackoverflow.com/q/51710999
tagged with: tuples
has comment: http://stackoverflow.com/comment/90383408
type: Question
has comment: http://stackoverflow.com/comment/90383390
tagged with: argument-unpacking
tagged with: python
has title: new style getargs format but argument is not a tuple error callng floodfill
tagged with: python-imaging-library
score: 0
has comment: http://stackoverflow.com/comment/90384172
type: UnansweredQuestion
has body: I am not sure what is going on. This thing worked before and now it dosn't. def generate_unity_texture(self, monKey_data): width, height = self.texture_image.size eye_position = (int(0.88 * width), int(0.88 * height)) ImageDraw.floodfill(unity_texture_copy, xy=eye_position , value=monKey_data['eye_color']) return unity_texture_copy and I get SystemError: new style getargs format but argument is not a tuple. The problem is in pixel[x, y] = value and it is mentioned that the problamatic line of code is PIL\ImageDraw.py", line 349, in floodfill This is a tuple. I even tried to replace middle with (int(middle[0]), int(middle[1]) but got the same result. In the documentation xy is: xy – Seed position (a 2-item coordinate tuple). Which is exactly what I did. Any suggestions?
answer count: 0
has comment: http://stackoverflow.com/comment/90383848

http://stackoverflow.com/comment/90471412
type: QuestionComment
type: Comment
has text: @Novel: you don't have to call `pack_forget()`. A widget can only be in one place at a time, so when it's added to a new place it's automatically removed from the old.
comment on: http://stackoverflow.com/q/51753750
score: 0

http://stackoverflow.com/a/51737796
answers question: http://stackoverflow.com/q/51737538
downvote count: 0
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/90475680
has body: As an aside, given you're starting this project, and are already using the rewrite documentation, make sure you're using the rewrite version. There are some questions on here about how to make sure, and how to get it if you're not, but it's better documented and easier to use. My answers below assume you are using discord.py-rewrite Message.reactions is a list of Reactions. You could get a mapping of reactions to their counts with {react.emoji: react.count for react in message.reactions} You could react to the message immediately after posting it: @bot.command() async def poll(ctx, *, text): message = await ctx.send(text) for emoji in ('', ''): await message.add_reaction(emoji) You can use Message.pin: await message.pin() I'm not sure what you mean by "user tags". Do you mean roles? I would write your command as @bot.command() async def create_poll(ctx, text, *emojis: discord.Emoji): msg = await ctx.send(text) for emoji in emojis: await msg.add_reaction(emoji) Note that this will only work for custom emoji, the ones you have added to your own server (This is because discord.py treats unicode emoji and custom emoji differently.) This would accept commands like !create_poll "Vote in the Primary!" :obamaemoji: :hillaryemoji: assuming those two emoji were on the server you send the command in. With the new commands.Greedy converter, I would rewrite the above command like so: @bot.command() async def create_poll(ctx, emojis: Greedy[Emoji], *, text): msg = await ctx.send(text) for emoji in emojis: await msg.add_reaction(emoji) So invocation would be a little more natural, without the quotes: !create_poll :obamaemoji: :hillaryemoji: Vote in the Primary!
has comment: http://stackoverflow.com/comment/90494791

http://stackoverflow.com/q/51784292
tagged with: python
tagged with: pyqtchart
has body: I have a PyQt Chart but the X axis displays the data horizontally. How can I display the labels on the X axis Vertically? My desired outcome is this (Excuse the poor photoshop skills!!) from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtChart import * #https://doc.qt.io/qt-5/qtcharts-datetimeaxis-example.html if __name__ == '__main__': import sys if True: a = QApplication(sys.argv) x = ['2018-07-01 13:06:38', '2018-07-01 12:46:38', '2018-07-01 12:36:38', '2018-07-01 12:26:38', '2018-07-01 12:16:38', '2018-07-01 12:06:38', '2018-07-01 11:56:38', '2018-07-01 11:46:38', '2018-07-01 11:36:38', '2018-07-01 11:26:38', '2018-07-01 10:56:38', '2018-07-01 10:46:38', '2018-07-01 10:36:38'] y = [23.5, 20.8, 28.0, 28.1, 28.0, 27.8, 27.3, 27.2, 25.7, 24.7, 25.0, 25.0, 24.9] num_ticks = 10 time_len = 'Time' # Chart Type series = QLineSeries() for t, val in zip(x, y): series.append(QDateTime.fromString( t, "yyyy-MM-dd hh:mm:ss").toMSecsSinceEpoch(), val) # Create Chart and set General Chart setting chart = QChart() chart.addSeries(series) #Title Font size font = QFont("Sans Serif", ) font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle("Temperature in Celcius For Device:") chart.setAnimationOptions(QChart.SeriesAnimations) palette = QPalette() palette.setColor(QPalette.Text, Qt.red) chart.setPalette(palette) # Chart Background backgroundGradient = QLinearGradient(0, 0, 0, 400) backgroundGradient.setColorAt(0.0, QColor('#50a1dc')) backgroundGradient.setColorAt(1.0, QColor('#00a1de')) chart.setBackgroundBrush(backgroundGradient) #Plot area background plotAreaGradient = QLinearGradient(0, 100, 0, 400) plotAreaGradient.setColorAt(0.0, QColor('#f1f1f1')) plotAreaGradient.setColorAt(1.0, QColor('#ffffff')) chart.setPlotAreaBackgroundBrush(plotAreaGradient) chart.setPlotAreaBackgroundVisible(True) # X Axis Settings axisX = QDateTimeAxis() axisX.setTickCount(num_ticks) # https://doc.qt.io/qt-5/qdatetime.html#toString-2 axisX.setFormat(…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90527467
upvote count: 3
tagged with: pyqt5
has answer: http://stackoverflow.com/a/51784779
has title: Display X labels vertically
type: Question
score: 3
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90528051
answer count: 1
accepted answer: http://stackoverflow.com/a/51784779
downvote count: 0
has comment: http://stackoverflow.com/comment/90526172
has comment: http://stackoverflow.com/comment/90527408
favorite count: 0

http://stackoverflow.com/q/51700886
tagged with: web-scraping
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 1
has body: I want to click a button which is actually a div tag. I am unable to click on it. from selenium import webdriver url = "https://www.qoo10.sg/item/LAPTOP-SCREEN-PROTECTOR-SCREEN-GUARD-FOR-13-14-15-INCHES-2ND/410235318" driver = webdriver.Firefox() driver.get(url) elem = driver.find_element_by_class_name('selectArea').click() when i run this program i go this error selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view.
tagged with: selenium
accepted answer: http://stackoverflow.com/a/51700955
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51700942
possible better answer: http://stackoverflow.com/a/51700942
favorite count: 0
has answer: http://stackoverflow.com/a/51700955
upvote count: 2
has title: unable to click the div button using selenium

http://stackoverflow.com/q/51652937
downvote count: 0
has body: I've made some classic Python3 functions, in a file, using dictionaries as arguments. I'd like to use this file as a library, and use the functions in a kivy widget. So here's what my code does : #all kivy imports import myLib class MyGame(Widget): myDict = DictProperty({1:0, 2:0, 3:0}) def addStuff(self, id): self.myDict[id]+= 1 def myNotWorkingFunction(self): number = myLib.getNumberFromDict(self.myDict) self.text = "The result is "+str(number) It doesn't work like that. If I don't use myLib.getNumberFromDict, and set number = 3, it's fine. myLib.getNumberFromDict works well with python dict, as I used it before trying to make the kivy app. I have this in the kivy log : stderr: Exception KeyError: ('', ) in 'kivy.properties.observable_dict_dispatch' ignored
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51666700
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51666700
tagged with: python
tagged with: kivy
tagged with: dictionary
tagged with: properties
has title: How to get a python dict from kivy dictProperty?
tagged with: python-3.x

http://stackoverflow.com/comment/90535515
score: 1
comment on: http://stackoverflow.com/q/51788990
has text: Please post an example case of input and desired output.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51691175
answer count: 1
has body: This question occurred to me when I was doing 173. Binary Search Tree Iterator on leetcode: class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.root = root def next(self): """ :rtype: int """ self.point = self.root while self.point.left: self.point = self.point.left #self.point = self.point.left #self.point.val = 1000 self.point = None And then when I ran: root = TreeNode(0) root.left = TreeNode(1) root.right = TreeNode(2) iterat.next() iterat.root.left.val I was expecting None, but it returned 1 anyway. Is there any explanation?
favorite count: 0
has comment: http://stackoverflow.com/comment/90344583
has comment: http://stackoverflow.com/comment/90656139
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51853668
downvote count: 1
has title: Why tree iteration is not properly working in python class
type: Question
accepted answer: http://stackoverflow.com/a/51853668
score: -1
tagged with: class
upvote count: 0

http://stackoverflow.com/q/51776572
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90512017
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90511711
tagged with: python
accepted answer: http://stackoverflow.com/a/51776659
tagged with: off-by-one
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90511740
type: Question
has comment: http://stackoverflow.com/comment/90511750
tagged with: arrays
has body: Sorry for the vague title, but I really have no idea what's going on here. from functools import reduce arr = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] def strxo(n): if (n == -1): return "X" elif (n == 1): return "O" else: return "_" def prboard(board): print(reduce(lambda x, y: x + "\n" + y, list(map(lambda l: reduce(lambda a, b: strxo(a) + strxo(b), l), board)))) prboard(arr) Desired output: ___ ___ ___ Real output: __ __ __ And when I change the final else on strxo to return str(n) instead of return "_" I get: 000 000 000 Which is what I would expect and the shape I want, but I want to replace those zeroes. What is causing this?
has answer: http://stackoverflow.com/a/51776659
has title: Python weirdness involving map and reduce
tagged with: functional-programming

http://stackoverflow.com/comment/90486127
type: QuestionComment
comment on: http://stackoverflow.com/q/51761687
score: 0
has text: You will have to use `$gte` or `$lte` with date...
type: Comment

http://stackoverflow.com/comment/90550315
type: QuestionComment
has text: Is your data purely numerical?
comment on: http://stackoverflow.com/q/51796291
score: 1
type: Comment

http://stackoverflow.com/q/51713001
possible better answer: http://stackoverflow.com/a/51716010
tagged with: telnet
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/51735659
has comment: http://stackoverflow.com/comment/90387640
has title: How to convert socket data to json object or to Dictionary with Python 3
has answer: http://stackoverflow.com/a/51716010
score: 0
has answer: http://stackoverflow.com/a/51735659
answer count: 2
has comment: http://stackoverflow.com/comment/90390215
has comment: http://stackoverflow.com/comment/90389728
has comment: http://stackoverflow.com/comment/90389171
has body: So I am trying to convert data from socket to json object. below is my python code that gets data from socket server. import socket HOST = "myHOST" PORT = myPORT with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((myHOST, myPORT)) s.sendall(b" ") buffer_size = 4096 print("Received: ") while True: data = s.recv(buffer_size) print(repr(data)) s.close() I am getting this data as an output: Received: b'2018-08-06T17:35:45.0612|power|ON|mode|MANUAL|execution|READY|Xact|215.13|Yact|331.34|Zact|22.16|Xcom|0.00|Ycom|0.00|Zcom|0.00|path_feedrate|0.00|line|0|Block|0|program|Plate 1_imported_dxf.ORD\n' b'2018-08-06T17:35:45.0612|comms|NORMAL||||\n2018-08-06T17:35:45.0612|Sspeed|0.00\n' And now I want to convert it to formatted json object so that i can later use it on my html with javascript. I tried to create json object within my while loop by: import socket import json HOST = "myHOST" PORT = myPORT with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((myHOST, myPORT)) s.sendall(b" ") buffer_size = 4096 print("Received: ") while True: data = s.recv(buffer_size) print(repr(data)) json_obj = json.loads(data) print(type(json_obj)) print(json_obj.get("power").get("mode")) s.close() But i cant make it to work. I also tried to use json.dumps but no success. Please help guys! I also tried to make a dictionary but no success, getting error: ValueError: too many values to unpack (expected 2). Below is the snippet for my dictionary try: while True: data = s.recv(buffer_size).decode("utf-8") print(data) d = {} for pair in data.replace(' ', '').split(', '): k, v = pair.split('|') d[k] = int(v) print(d) I want the answer to have key value pairs.
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/90387529
has comment: http://stackoverflow.com/comment/90387555

http://stackoverflow.com/comment/90285256
score: 0
type: Comment
type: QuestionComment
has text: Empty columns have a width of 0 (by default), so it does not matter how many you put in. Use `pack(side=RIGHT)` to place things on the right side.
comment on: http://stackoverflow.com/q/51660869

http://stackoverflow.com/comment/90248008
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51641669
has text: <ipython-input-187-b954c3c003b0> in <module>() 3 for i, ((curr_diff, _), b) in enumerate(zip(stored, arr2)): 4 diff = abs(a-b) ----> 5 if diff < curr_diff: 6 stored[i] = (diff, a) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
score: 0

http://stackoverflow.com/q/51690357
score: 1
tagged with: string
favorite count: 0
type: Question
tagged with: python
has title: Is there any way to convert a multiple ASCII characters into a string of numbers?
has comment: http://stackoverflow.com/comment/90342668
has comment: http://stackoverflow.com/comment/90342488
upvote count: 1
has body: I have a string of characters ascst = 'abc' and I want to know how to convert it into a string of numbers '097098099' in the output, every 3 letters is an Ascii character. 097 being a, 098 being b, 099 being c. Is there any easy way to do this?
duplicate of: http://stackoverflow.com/q/8452961
type: UnansweredQuestion
tagged with: ascii
has comment: http://stackoverflow.com/comment/90342474
downvote count: 0
answer count: 0

http://stackoverflow.com/a/51714173
type: Answer
has body: Your question isn't very clear, but this might work: df['count'] = df['unigrams'].map(lambda x: len(x))
answers question: http://stackoverflow.com/q/51714019
score: 0

http://stackoverflow.com/comment/90355666
type: QuestionComment
comment on: http://stackoverflow.com/q/51697061
score: 0
type: Comment
has text: Oh, you mean filename conflicts in case there's say, `001 - x.jpg` and `006 - x.jpg` initially? Right, I didn't think about that honestly. Okay, so I strip the leading 0s, go backwards, incrementing the numbers, and then add the 0s, am I on the right track?

http://stackoverflow.com/a/52311893
upvote count: 5
answers question: http://stackoverflow.com/q/51706256
has comment: http://stackoverflow.com/comment/98848404
score: 4
downvote count: 1
has body: You can not do it directly. You need to do this via javascript. Once Javascript has been formatted properly, you need to notify listeners. Before that, you need to find the unicode of any emoji you want to use. To get codepoint of any emoji, this website can be used: https://emojipedia.org/ Search for any emoji and at the bottom of the page, there will be the codepoint for it. To convert codepoint to unicode for javascript, use following website: https://r12a.github.io/app-conversion/ Type the codepoint and copy the value in javascript box of it. Once, you have it, use JavaScript as follows: JS_ADD_TEXT_TO_INPUT = """ var elm = arguments[0], txt = arguments[1]; elm.value += txt; elm.dispatchEvent(new Event('change')); """ elem = driver.find_element_by_id('&lt;Id of your webelement&gt;') text = u'\u2764' driver.execute_script(JS_ADD_TEXT_TO_INPUT, elem, text) 2764 is unicode for heart emoji. Hope this helps for any kind of emoticons you want to insert to your whatsapp! Edit: For more complex emoticons: You need to add multiple unicodes like Emoji for family : \uD83D\uDC6A
type: Answer
has comment: http://stackoverflow.com/comment/116659528

http://stackoverflow.com/comment/100880983
score: 0
type: Comment
has text: How do you use this? What do i need to install to get KMeansClusterer?
type: AnswerComment
comment on: http://stackoverflow.com/a/52578160

http://stackoverflow.com/a/51747461
has comment: http://stackoverflow.com/comment/90454815
has comment: http://stackoverflow.com/comment/90454676
has body: cond_1 = df['age'] &lt; 25 cond_2 = df['Gender'] == 1 df['group'] = np.where(cond_1 &amp; cond_2, 1, 0) It will assign 1 where both conditions are satisfied and 0 everywhere else. Taking into account your comments, this method doesn't have to be binary. You can include as many conditions as you need and you can substitute the 1 for any int or str you want. Moreover, you can change the 0 to np.nan.
has comment: http://stackoverflow.com/comment/90454976
answers question: http://stackoverflow.com/q/51747326
has comment: http://stackoverflow.com/comment/90454929
upvote count: 1
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/51737631
has comment: http://stackoverflow.com/comment/90513482
has comment: http://stackoverflow.com/comment/90474161
score: 0
has body: You can use something like this: from tkinter import * import random class RollMachine(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.first = self.second = self.third = None self.stake = 0 self.intro = """Panther's Den Slot Machine. Welcome to my den! You can win by rolling Ocelots, Jaguars, Boas, Caimans, Macaws or Tapirs. You can also with big with three Ibis. You'll lose a coin for anything else, and if you roll three Scorpions say good bye to 500 coins Good luck kit!""" self.ITEMS = ["OCELOT", "MACAW", "JAGUAR", "IBIS", "CAIMAN", "BOA", "SCORPION", "TAPIR", "CONDOR", "BAMBOO", "FROG"] self.makeWidgets() self.pack() def makeWidgets(self): nameLabel = Label(self, text="PANTHER DEN", font=('Cambria', 60)) nameLabel.pack() self.lbl = Label(self, text=self.intro, background='seagreen', font=('Cambria', 12)) self.lbl.pack() self.lbl2 = Label(self, text="Enter the stake") self.lbl2.pack() self.stake_input = Entry(self) self.stake_input.pack() Button(self, text="Play", command=self.play).pack() Button(self, text="Quit", command=self.quit_play).pack() Button(self, text="Exit", command=self.quit).pack() def play(self): if self.stake == 0: self.stake = int(self.stake_input.get()) self.first = self.spin() self.second = self.spin() self.third = self.spin() self.score() def spin(self): randomnumber = random.randint(0, 10) return self.ITEMS[randomnumber] def score(self): if((self.first == "OCELOT") and (self.second != "MACAW")): win = 5 elif((self.first == "JAGUAR") and (self.second == "JAGUAR") and (self.third != "JAGUAR")): win = 8 elif((self.first == "BOA") and (self.second == "BOA") and (self.third == "BOA")): win = 10 elif((self.first == "CAIMAN") and (self.second == "CAIMAN") and ((self.third == "CAIMAN") or (self.third == "BOA"))): win = 8 elif((self.first == "MACAW") and (self.second == "IBIS") and ((self.third == "MACAW"))): win = 15 elif((self.first == "TAPIR") and (self.second == "TAPIR") and ((self.third == "TAPIR"))): win = 20 elif((sel…
type: Answer
has comment: http://stackoverflow.com/comment/90513926
answers question: http://stackoverflow.com/q/51735566

http://stackoverflow.com/q/51717943
answer count: 1
tagged with: scikit-learn
favorite count: 0
has title: Sklearn neural network issue
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: machine-learning
type: Question
has body: I'm doing some practice neural networks and am stuck on one issue. My network is not predicting the right result, even though it says the training score is 97%. Here is my code: # Import `datasets` from `sklearn` from sklearn import datasets import pandas as pd from sklearn.model_selection import train_test_split # Import `train_test_split` from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier # Load in the `digits` data from sklearn.preprocessing import scale iris = datasets.load_iris() # split the data up - 3/4 for training, 1/4 for testing data_train, data_test, name_train, name_test = train_test_split(iris.data, iris.target, test_size=0.25, random_state=0) # Number of training features # n_samples, n_features = data_train.shape scaler = StandardScaler() scaler.fit(data_train) params_train_scaled = scaler.transform(data_train) params_test_scaled = scaler.transform(data_test) # 1 hidden layer, same size as the input layer mlp = MLPClassifier( solver='lbfgs', hidden_layer_sizes=(iris.data.shape[1], ), random_state=0) mlp.fit(params_train_scaled, name_train) print(name_train) print('Train score: %.3g' % mlp.score(params_train_scaled, name_train)) print('Test Score: %.3g' % mlp.score(params_test_scaled, name_test)) print test_val = [[5.1, 3.5, 1.4, 0.2]] print(mlp.predict(test_val)) My thought is it is how I scale the training and testing data, but I am not sure... The output I am getting is: Train score: 1 Test Score: 0.974 However, the predicted value should be 0, not 1. Thanks for any help.
has answer: http://stackoverflow.com/a/51718116
accepted answer: http://stackoverflow.com/a/51718116
upvote count: 3

http://stackoverflow.com/comment/90330740
score: 1
comment on: http://stackoverflow.com/q/51684046
type: Comment
type: QuestionComment
has text: We (probably) don't need to see the original function that creates `output`. But we do need you to make the code you've shown us unambiguous and self-consistent. You keep calling `output` an array, but it looks like a list. And according to the code you just added, `output` _is_ a list, not an array.

http://stackoverflow.com/comment/90360059
comment on: http://stackoverflow.com/q/51698240
has text: @RafaelC Because we only count the averages on the last day.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90465810
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51751327
has text: Thank you, I was interested in a more dynamic way to solve.

http://stackoverflow.com/comment/90520462
has text: @Bendebaria 's Pattern for GET and POST routes is actually a method to implement Flask Routes , Unfortunately since the searchForm is created outside , an error occurs. However calling the functions is a good option. Thank You
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51779969

http://stackoverflow.com/comment/90316919
type: QuestionComment
has text: I already debugged and ensured that it was working but it simply comes to the response and does nothing...
score: 0
comment on: http://stackoverflow.com/q/51675844
type: Comment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/51697374
tags question: http://stackoverflow.com/q/51771235
tag name: google-oauth

http://stackoverflow.com/q/51798251
has title: Query an existing socket's address family in Python
type: Question
has answer: http://stackoverflow.com/a/51803947
has answer: http://stackoverflow.com/a/51799456
has answer: http://stackoverflow.com/a/51799329
score: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51799329
tagged with: linux
accepted answer: http://stackoverflow.com/a/51803947
tagged with: sockets
has answer: http://stackoverflow.com/a/51806229
has body: I'm passing a socket file descriptor using a UNIX domain socket to a Python 3 program. I would like to query the socket and determine its address family. In this answer the getsockname system call is used to achieve the same result in C. However, Python's socket.getsockname function doesn't return the address family, instead assuming the caller already knows it. Furthermore, it only works on sockets, not on file descriptors, and creating a socket object from a file descriptor requires passing the address family as well. Is there a way to query the address family from Python? EDIT: I want to emphasize that I am looking for the address family of an already open socket, for which I have the file descriptor.
tagged with: python
linked to: http://stackoverflow.com/q/513298
answer count: 4
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/51778408
has comment: http://stackoverflow.com/comment/90515033
has body: Try doing __init__: class InfoSpider(scrapy.Spider): def __init__(self): self.name = 'info' self.allowed_domains = ['isbn.szmesoft.com'] self.isbns = list(set(pd.read_csv('E:/books.csv')['ISBN'])) self.url = 'http://isbn.szmesoft.com/isbn/query?isbn=' self.start_urls = [url + isbn for isbn in isbns[:3]] Then when you call it do self. before it
answers question: http://stackoverflow.com/q/51778393
has comment: http://stackoverflow.com/comment/90515931
has comment: http://stackoverflow.com/comment/90515940
has comment: http://stackoverflow.com/comment/90516802
has comment: http://stackoverflow.com/comment/90515888
has comment: http://stackoverflow.com/comment/90515020
has comment: http://stackoverflow.com/comment/90515868
has comment: http://stackoverflow.com/comment/90516007
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90515991
has comment: http://stackoverflow.com/comment/90515797

http://stackoverflow.com/q/51662213
has answer: http://stackoverflow.com/a/63653539
favorite count: 0
has comment: http://stackoverflow.com/comment/90288072
has answer: http://stackoverflow.com/a/74260445
tagged with: linux
has title: Cant get pyperclip to use copy and paste modules on python3
answer count: 5
has comment: http://stackoverflow.com/comment/90288006
tagged with: python
has answer: http://stackoverflow.com/a/51662312
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56561204
has answer: http://stackoverflow.com/a/51662295
score: 13
type: Question
possible better answer: http://stackoverflow.com/a/56561204
has body: Specs: Python3.5 Latest Pyperclip Both xclip and python3-pyqt4 installed using ssh(Putty) to connect to headleass raspberry pi 2 model B using Latest Raspian Stretch Light Error: pyperclip.copy('Hello world!') File "/usr/local/lib/python3.5/dist-packages/pyperclip/__init__.py", line 612, in lazy_load_stub_copy return copy(text) File "/usr/local/lib/python3.5/dist-packages/pyperclip/__init__.py", line 297, in __call__ raise PyperclipException(EXCEPT_MSG) pyperclip.PyperclipException: Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error I have also tried uninstalling and reinstalling both the module and clipboard programs. ive searched for 2 hours looking for an answer and used all of them and they didn't work. I admit i am a noob but it SHOULD'NT be this hard for me to do this.
tagged with: raspberry-pi
downvote count: 0
accepted answer: http://stackoverflow.com/a/51662312

http://stackoverflow.com/comment/90541736
type: AnswerComment
score: 0
has text: Okay, so this is a csv being imported into a csv. I need a list inserted into a csv
type: Comment
comment on: http://stackoverflow.com/a/51791761

http://stackoverflow.com/q/51754268
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51764128
type: Question
score: 12
tagged with: numpy
upvote count: 12
answer count: 1
downvote count: 0
tagged with: optimization
has body: So I have been trying to optimize some code that calculates a statistical error metric from some array data. The metric is called the Continuous Rank Probability Score (CRPS). I have been using Numba to try to speed up the double for loop required in this calculation, but I have been having an issue with the numpy.vstack function. From what I understand from the docs here, the vstack() function should be supported, but when I run the following code I get an error. def crps_hersbach_numba(obs, fcst_ens, remove_neg=False, remove_zero=False): """Calculate the the continuous ranked probability score (CRPS) as per equation 25-27 in Hersbach et al. (2000) Parameters ---------- obs: 1D ndarry Array of observations for each start date fcst_ens: 2D ndarray Array of ensemble forecast of dimension n x M, where n = number of start dates and M = number of ensemble members. remove_neg: bool If True, when a negative value is found at the i-th position in the observed OR ensemble array, the i-th value of the observed AND ensemble array are removed before the computation. remove_zero: bool If true, when a zero value is found at the i-th position in the observed OR ensemble array, the i-th value of the observed AND ensemble array are removed before the computation. Returns ------- dict Dictionary contains a number of *experimental* outputs including: - ["crps"] 1D ndarray of crps values per n start dates. - ["crpsMean1"] arithmetic mean of crps values. - ["crpsMean2"] mean crps using eqn. 28 in Hersbach (2000). Notes ----- **NaN and inf treatment:** If any value in obs or fcst_ens is NaN or inf, then the corresponding row in both fcst_ens (for all ensemble members) and in obs will be deleted. References ---------- - Hersbach, H. (2000) Decomposition of the Continuous Ranked Porbability Score for Ensemble Prediction Systems, Weather and Forecasting, 15, 559-570. """ # Treating the Data obs, fcst_ens = treat_data(obs, fcst_ens, remove_neg=remove_neg, remove_zero=remove_zero) # Set para…
has answer: http://stackoverflow.com/a/51764128
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90498517
tagged with: python-3.x
tagged with: numba
has title: Using numpy.vstack in numba

http://stackoverflow.com/comment/90310145
score: 1
comment on: http://stackoverflow.com/q/51673388
type: QuestionComment
has text: Got it (That makes things a tad bit more difficult but understood)
type: Comment

http://stackoverflow.com/a/51691335
upvote count: 3
has comment: http://stackoverflow.com/comment/124219611
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90349599
has body: Try this, pip install rcssmin --install-option="--without-c-extensions" pip install rjsmin --install-option="--without-c-extensions" pip install django-compressor --upgrade This solution works well, but it works much slower without the c extensions. So better solution is, Intstall C++ dependencies , size of 1.1GB
type: Answer
answers question: http://stackoverflow.com/q/51690898

http://stackoverflow.com/comment/90496291
type: Comment
comment on: http://stackoverflow.com/q/51768789
score: 0
type: QuestionComment
has text: You want `df.remove = np.where((pd.isnull(aws.to_group1)) & (pd.isnull(aws.to_group2)), True, np.nan)` you can't compare with `NaN` directly using `==`

http://stackoverflow.com/a/73224931
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51687362
has body: Just found this blog post about Grid.js. It makes it possible to edit table cells directly on a page without extra Edit links.
upvote count: 1
score: 1

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/51639976
tag name: encoder-decoder

printers
tag name: printers
type: Tag
tags question: http://stackoverflow.com/q/51752666

http://stackoverflow.com/comment/90314358
has text: Sort of. It is answering the question if value of `VWAP` is derived same way
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51675175

http://stackoverflow.com/comment/90278492
type: Comment
type: QuestionComment
has text: thanks, I opened a question on that forum
comment on: http://stackoverflow.com/q/51656750
score: 0

http://stackoverflow.com/a/51712492
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51712338
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51712338
has body: You could sort it by locating the 1's and 0's. Something like: list_ones = np.where(Array[0] == 1) list_zeros = np.where(Array[0] == 0) Then Array[list_ones,:,:,:] will contain all elements corresponding to a one and Array[list_zeros,:,:,:] will correspond to all elements corresponding to a zero. Then you can just put first_term = Array[list_ones,:,:,:] second_term = Array[list_zeros,:,:,:] And sum as appropriate. Would this work for your purpose?

http://stackoverflow.com/comment/90538633
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51743225
has text: Actually the DAG code is very easy, it is just a creating a DAG with a for loop to create about 20 branches of 7 tasks each. But there is nothing else querying something or loading a file for example. When I do python mydag.py it executes in 1-2s.
score: 0

http://stackoverflow.com/a/51735513
answers question: http://stackoverflow.com/q/51733311
has comment: http://stackoverflow.com/comment/90434813
has comment: http://stackoverflow.com/comment/90432563
has comment: http://stackoverflow.com/comment/90432597
has comment: http://stackoverflow.com/comment/90437360
score: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/90463901
has comment: http://stackoverflow.com/comment/90432483
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/90432686
has comment: http://stackoverflow.com/comment/90431888
has comment: http://stackoverflow.com/comment/90435773
has comment: http://stackoverflow.com/comment/90437160
has comment: http://stackoverflow.com/comment/90432443
type: Answer
has comment: http://stackoverflow.com/comment/90432632
accepted answer of: http://stackoverflow.com/q/51733311
has comment: http://stackoverflow.com/comment/90432546
has body: If you'd like to approximate round on the real line, you can do something like the following: def approx_round(x, steepness=1): floor_part = tf.floor(x) remainder = tf.mod(x, 1) return floor_part + tf.sigmoid(steepness*(remainder - 0.5)) There are, in fact, ways to register your own gradients in Tensorflow (see, for example, this question). However, I am not as familiar on achieving this part, as I don't use Keras/TensorFlow that often. In terms of a function that would give you the gradient of this approximation, it would be the following: def approx_round_grad(x, steepness=1): remainder = tf.mod(x, 1) sig = tf.sigmoid(steepness*(remainder - 0.5)) return sig*(1 - sig) To be clear, this approximation assumes you're using a "steep enough" steepness parameter, since the sigmoid function doesn't go to exactly 0 or 1, except in the limit of large arguments. To do something like the half sin approximation, you could use the following: def approx_round_sin(x, width=0.1): if width &gt; 1 or width &lt;= 0: raise ValueError('Width must be between zero (exclusive) and one (inclusive)') floor_part = tf.floor(x) remainder = tf.mod(x, 1) return (floor_part + clipped_sin(remainder, width)) def clipped_sin(x, width): half_width = width/2 sin_part = (1 + tf.sin(np.pi*((x-0.5)/width)))/2 whole = sin_part*tf.cast(tf.abs(x - 0.5) &lt; half_width, tf.float32) whole += tf.cast(x &gt; 0.5 + half_width, tf.float32) return whole def approx_round_grad_sin(x, width=0.1): if width &gt; 1 or width &lt;= 0: raise ValueError('Width must be between zero (exclusive) and one (inclusive)') remainder = tf.mod(x, 1) return clipped_cos(remainder, width) def clipped_cos(x, width): half_width = width/2 cos_part = np.pi*tf.cos(np.pi*((x-0.5)/width))/(2*width) return cos_part*tf.cast(tf.abs(x - 0.5) &lt; half_width, dtype=tf.float32)

http://stackoverflow.com/comment/90290476
score: 0
type: QuestionComment
has text: From the [docs](https://docs.python.org/3/reference/expressions.html#slicings): "If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items". So this would basically result in trying to use a tuple of three slices as a key/index (not an int). But really the question is, what exactly is it that you are trying to say/get?
comment on: http://stackoverflow.com/q/51663321
type: Comment

http://stackoverflow.com/comment/90528175
has text: why not just "⟷⇳⤚"?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51784633
type: Comment

http://stackoverflow.com/comment/90343700
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51690950
has text: @DYZ tmp_t is a variable that is generated _after_ the list comprehension (the list comprehension is where the ValueError is being raised). I've removed the information about it now because it isn't needed for my actual question. Sorry about the confusion.

http://stackoverflow.com/a/51679671
score: 0
type: Answer
has body: The modulo operator, %, has a well-defined behaviour. It yields the remainder after division by a number. It is used in the expression form of a % b, returning a value c The definition creates an interesting property, used in the code provided by your question, of "wrapping" values into a well-defined range. The code in question uses this in a loop to ensure that data_index is wrapped within the range of 0 to len(data) - 1. As it goes out of bounds, it just continues appending data[data_index] from 0. Here's an example of modulo's cyclic behaviour: for i in range(10): print(str(i) + ' % 3 =', i % 3) Which prints: 0 % 3 = 0 1 % 3 = 1 2 % 3 = 2 3 % 3 = 0 4 % 3 = 1 5 % 3 = 2 6 % 3 = 0 7 % 3 = 1 8 % 3 = 2 9 % 3 = 0
answers question: http://stackoverflow.com/q/51679228

http://stackoverflow.com/q/51687658
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51687747
accepted answer: http://stackoverflow.com/a/51687747
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51687807
has comment: http://stackoverflow.com/comment/90444047
score: 1
has answer: http://stackoverflow.com/a/51688162
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51687952
tagged with: algorithm
has title: Find the index in the string where count(symbols) in left half=count(symbols) in right half?
linked to: http://stackoverflow.com/q/5131538
has body: Given a string, say s="##$$$#", how can I find the index where the number of "#" symbols before the index is equal to the number of "$" symbols after the index? Example: if s="##$$$#", then the output would be 2. Explanation: before index 2 we have 2 "#" symbols and after index 2 we have 2 "$" symbols I tried finding the mid index first and count the symbols(# and $) on both the sides,if they are equal then print the mid index else increment the mid and proceed the same way.. But I'm not able to get the logic correctly.
has comment: http://stackoverflow.com/comment/90337267
possible better answer: http://stackoverflow.com/a/51687807
type: Question
upvote count: 2
downvote count: 1

http://stackoverflow.com/q/51764738
tagged with: matlab
has comment: http://stackoverflow.com/comment/90492367
tagged with: mathematical-optimization
answer count: 0
has title: Translating MATLAB's `fminsearch` with its constraints to scipy's `minimize`
has comment: http://stackoverflow.com/comment/90565192
has comment: http://stackoverflow.com/comment/90490233
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/90565205
has body: I want to maximize the log likelihood function of GARCH model, I am using fminsearch in MATLAB to minimize the negative log likelihood function, there are two constraints in this problem. I tried to use the fmin or minimize functions (from scipy) but I think the way of translating the constraints is incorrect. Below is my attempt in python 3.6: def computeNegLLH(parameters): sigma2 = np.zeros(len(returns)); omega = parameters[0]; alpha = parameters[1]; beta = parameters[2]; sigma2[1] = parameters[3]; # parameters restrictions: omega&gt;0; alpha,beta&gt;=0; alpha + beta &gt;= 1 if (omega&lt;=0 or min(alpha,beta)&lt;0 or alpha + beta &gt;= 1 or sigma2[0]&lt;=0): negLLH = sys.maxsize; sys.exit(); # calculate squared returns returns2 = returns**2; for t in range(1,len(returns)): sigma2[t]= omega + alpha*returns2[t-1] + beta*sigma2[t-1]; # calculate (-1)xLogLikelihood for a GARCH(1,1) process with parameters negLLH = 0.5*sum(log(sigma2) + returns2/sigma2); return negLLH result = minimize(fun = computeNegLLH, x0 = startingValues, method = 'Nelder- Mead', options = {'xtol': 1e-8}) My MATLAB code: function param = calibrate_GARCH(returns, startingValues) % computes maximum likelhood estimates for a GARCH(1,1) process give % timeseries "returns" using fminsearch function options = optimset('TolX',1e-12,'MaxFunEvals',3000,'Maxiter',3000, 'Display','off','LargeScale','off'); param = fminsearch(@(param)computeNegLLH(param,returns), startingValues, options); end function negLLH = computeNegLLH(param,returns) % param for the given timeseries returns sigma2 = zeros(size(returns)); omega = param(1); alpha = param(2); beta = param(3); sigma2(1) = param(4); % parameter restrictions: omega&gt;0 alpha,beta&gt;=0 % ensure that GARCH(1,1) process is covariance-stationary if omega&lt;=0 || min(alpha,beta)&lt;0 || alpha + beta &gt;= 1 || sigma2(1)&lt;=0; negLLH = intmax; return; end % calculate squared returns returns2 = returns.^2; for t=2:length(returns) sigma2(t)= omega + alpha*returns2…
score: 0
has comment: http://stackoverflow.com/comment/90491380
tagged with: minimization
has comment: http://stackoverflow.com/comment/90489497
has comment: http://stackoverflow.com/comment/90491496
has comment: http://stackoverflow.com/comment/90490825
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90491270
tagged with: python

http://stackoverflow.com/comment/90326962
type: Comment
score: 1
has text: That’s not what being hashable achieves. Access to list elements is also O(1).
comment on: http://stackoverflow.com/q/51681966
type: QuestionComment

http://stackoverflow.com/q/51711651
tagged with: tensorflow
type: Question
upvote count: 4
answer count: 1
downvote count: 0
score: 4
tagged with: lstm
has answer: http://stackoverflow.com/a/51729801
has body: I would like to pass 2 tensors with different dimensions to a tf.nn.dynamic_rnn. I am having difficulty because the dimensions do not match. I am open to suggestions for the best way to do this. These tensors are batches from a tf.data.Dataset I have 2 tensors of shape: tensor 1: (?, ?, 1024) tensor 2: (?, ?, 128) The first dimension is the batch size, the second dimension is the number of timesteps and the third dimension is the number of features to input at each timestep. Currently, I have an issue that the number of timesteps for each dimension do not match. Not only that but they are inconsistent in size across samples (for some samples tensor 1 has 71 timesteps, sometimes it may have 74 or 77). Is the best solution to dynamically pad the number of timesteps in the shorter tensor for each sample? If so, how would I do this? Below is a code segment to show what I would like to do: #Get the next batch from my tf.data.Dataset video_id, label, rgb, audio = my_iter.get_next() print (rgb.shape) #(?, ?, 1024) print (audio.shape) #(?, ?, 128) lstm_layer = tf.contrib.rnn.BasicLSTMCell(lstm_size) #This instruction throws an InvalidArgumentError, I have shown the output below this code concatenated_features = tf.concat([rgb, audio], 2) print (concatenated_features.shape) #(?, ?, 1152) outputs,_= tf.nn.dynamic_rnn(lstm_layer, concatenated_features, dtype="float32") with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(num_epochs): sess.run(my_iter.initializer) for j in range(num_steps): my_outputs = sess.run(outputs) The error upon calling tf.concat in a session: InvalidArgumentError (see above for traceback): ConcatOp : Dimensions of inputs should match: shape[0] = [52,77,1024] vs. shape[1] = [52,101,128]
tagged with: tensorflow-datasets
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: How can one pass two 3D tensors with only one common dimension (batch size) to a dynamic_lstm?
accepted answer: http://stackoverflow.com/a/51729801

http://stackoverflow.com/q/51663157
has answer: http://stackoverflow.com/a/51680558
type: Question
score: -1
answer count: 2
upvote count: 1
favorite count: 0
has title: Python 3.7 - Why am I receiving error for " in the following print with f command?
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: Beginner here! Code I am working with is: my_name = 'Fake A. Name' my_age = 20 # This is my real age my_height = 72 # This is in inches my_weight = 150 # Lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Blonde' print(f "Let's talk about {my_name}.") Error Message: print(f "Let'\s talk about {my_name}.") ^ SyntaxError: invalid syntax I am working through LPTHW (learn python the hard way) and despite following exact copy, am still receiving this error. I've tried searching through pythons rules but I am not finding much of a definite reason.
has answer: http://stackoverflow.com/a/51663218

http://stackoverflow.com/comment/90338733
type: QuestionComment
score: 0
has text: @LIXuhong removing `tf.reset_default_graph()` worked.
type: Comment
comment on: http://stackoverflow.com/q/51685701

http://stackoverflow.com/a/51702839
score: 0
type: Answer
has body: This has nothing to do with MultinomialNB. It can handle multiple columns fine. The problem is TfidfVectorizer. TfidfVectorizer only works on a an iterable of single dimension (single column of your dataframe) and will not do any kind of check on the shape or type of the input data. It will only do this: for doc in raw_documents: ... ... When you pass a dataframe to it (be it a single column or multiple columns), for doc in raw_documents:, on a dataframe will only output the column names and not actual data. The data you pass in X has three columns, so only those columns are used as documents, and hence the error ValueError: Found input variables with inconsistent numbers of samples: [3, 100] because your y will have 100 length, and your X (even though it has length 100, but due to tfidfvectorizer it will only now have 3 length). So to solve this, you have two options: 1) You need to do individual tf-idf vectorization for each text column (Text, Text_Two) and then combine the resultant matrices to form the feature matrix to be used with MultinomialNB. 2) You can combine the two text columns into a single column as @âńōŋŷxmoůŜ has suggested and then do tf-idf on that single column. Both options will result in different feature vectors, so you need to first understand what each one does and choose what you want.
answers question: http://stackoverflow.com/q/51697502

http://stackoverflow.com/q/51686929
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/90337130
type: AnsweredQuestion
downvote count: 0
has body: Suppose I have a dataframe df as:- index company url address 0 A . www.abc.contact.com 16D Bayberry Rd, New Bedford, MA, 02740, USA 1 A . www.abc.contact.com . MA, USA 2 A . www.abc.about.com . USA 3 B . www.pqr.com . New Bedford, MA, USA 4 B. www.pqr.com/about . MA, USA I want to remove all the rows from the dataframe where address is subset of another address and company is same. Eg, I want these two rows out of above 5 rows. index company url address 0 A . www.abc.contact.com 16D Bayberry Rd, New Bedford, MA, 02740, USA 3 B . www.pqr.com . New Bedford, MA, USA
type: Question
has answer: http://stackoverflow.com/a/51687459
accepted answer: http://stackoverflow.com/a/51687459
score: 5
has comment: http://stackoverflow.com/comment/90336448
tagged with: pandas
has title: How to remove rows based on a column value where some row's column value are subset of another?
has comment: http://stackoverflow.com/comment/90336900
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90491399
comment on: http://stackoverflow.com/q/51766387
score: 1
has text: Yep! Just take a look at the documentation for further information. The [memory management](https://docs.python.org/3/c-api/memory.html) page goes in depth about each aspect of how Python interacts with memory.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90430312
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51734690
has text: I get an error saying `NameError: name 'element' is not defined`
type: AnswerComment

http://stackoverflow.com/comment/90447177
type: AnswerComment
comment on: http://stackoverflow.com/a/51743378
type: Comment
has text: No, not overriding anything
score: 0

http://stackoverflow.com/q/51749783
answer count: 0
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/2903617
type: Question
has title: start, exit, try again buttons
upvote count: 1
has body: created this game called snake.I was wondering if anyone can help me create a window before the game opens, which contains the start button, exit button and instructions manual so that when i click start, the game starts and when I click exit, the game is terminated. I would also like a try again button that loops the game when the player loses the game, and a quit button which terminates the program. Here is the code for my snake game from tkinter import* import random #Globals WIDTH = 800 HEIGHT = 600 SEG_SIZE = 20 IN_GAME = True #Helper Functions def create_block(): """ Creates an apple to be eaten """ global BLOCK posx = SEG_SIZE * random.randint(1, (WIDTH-SEG_SIZE) / SEG_SIZE) posy = SEG_SIZE * random.randint(1, (HEIGHT-SEG_SIZE) / SEG_SIZE) BLOCK = c.create_oval(posx, posy, posx+SEG_SIZE, posy+SEG_SIZE, fill="blue") def main(): """ Handles game process """ global IN_GAME if IN_GAME: s.move() head_coords = c.coords(s.segments[-1].instance) x1, y1, x2, y2 = head_coords #Collision with borders if x2 &gt; WIDTH or x1 &lt; 0 or y1 &lt; 0 or y2 &gt; HEIGHT: IN_GAME = False #Eating apples elif head_coords == c.coords(BLOCK): s.add_segment() c.delete(BLOCK) create_block() #Self-eating else: for index in range(len(s.segments)-1): if head_coords == c.coords(s.segments[index].instance): IN_GAME = False root.after(100, main) # NOT IN_GAME -&gt; stop game and print message else: c.create_text(WIDTH/2, HEIGHT/2, text="GAME OVER!", font="Arial 40", fill="blue") class Segment(object): """ Single snake segment """ def __init__(self, x, y): self.instance = c.create_rectangle(x, y, x+SEG_SIZE, y+SEG_SIZE, fill="black") class Snake(object): """ Simple Snake class """ def __init__(self, segments): self.segments = segments #possible moves self.mapping = {"Down": (0, 1), "Right": (1, 0), "Up": (0, -1), "Left": (-1, 0)} #initial movement direction self.vector = self.mapping["Right"] def move(self): """ Moves the snake with the specified vector """ for index in range(len(self.segments…
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90462582
has comment: http://stackoverflow.com/comment/90459801
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90254390
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51644564
has text: where is the bag object created? are you hitting the database for updated value?

http://stackoverflow.com/a/51797704
has body: You need to iterate over each element in the list, and the determine if your word is in the list. You can define a function to handle this: def word_check(my_list, word): for i in range(0, len(my_list)): if word in my_list[i]: return i return False list = ['this is ', 'a simple ', 'list of things.'] word_check(list, 'simple') The function will return the index of the word if found, else it will return false.
type: Answer
answers question: http://stackoverflow.com/q/51797311
score: 0

http://stackoverflow.com/comment/90615666
type: Comment
comment on: http://stackoverflow.com/q/51669589
score: 0
type: QuestionComment
has text: Feel free to open an issue on the extension at https://github.com/Microsoft/vscode-python/issues to help debug this farther.

http://stackoverflow.com/comment/90354684
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51696441
has text: The title of you question should not say 'area plot' then. What you want is a bar plot.
score: 0

http://stackoverflow.com/q/51684203
has body: How should I do to use the python api to perform this query: db.collection.find( { field: value }, { array: {$slice: count } } ); When I use the projection operators, I can not use the include specifications at the same time. How can I do simply to access the specific filed without any other fields which might have a large amounts of data.
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: PyMongo: How to use the projection operators - $slice - in find() in PyMongo
has comment: http://stackoverflow.com/comment/90333844
score: 1
tagged with: pymongo
upvote count: 1
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/51684334

http://stackoverflow.com/comment/90462386
has text: It would help if you reduced your code down a bit more. If the problem is with a `Toplevel` and `WM_DELETE_WINDOW`, we don't need much more than that. Also, you import something called `User` which seems completely unnecessary to solve this problem.
score: 0
comment on: http://stackoverflow.com/q/51749757
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51656000
has answer: http://stackoverflow.com/a/57798754
score: 3
has title: Can I augment images and masks in Keras just using flow() instead of flow_from_directory?
tagged with: python
has answer: http://stackoverflow.com/a/52375589
has body: I've been trying to train a CNN using Keras with data augmentation applied to a series of images and their segmentation masks. The online example says that in order to do this, I should create two separate generators using flow_from_directory() and then zip them. But instead can I just have two numpy arrays for the images and masks, use the flow() function and instead do this: # Create image generator data_gen_args = dict(rotation_range=5, width_shift_range=0.1, height_shift_range=0.1, validation_split=0.2) image_datagen = ImageDataGenerator(**data_gen_args) seed = 1 # Create training and validation generators including masks train_generator = image_datagen.flow(images, masks, seed=seed, subset='training') val_train_generator = image_datagen.flow(images, masks, seed=seed, subset='validation') # Train model model.fit_generator(train_generator, steps_per_epoch=50, validation_data = val_train_generator, validation_steps = 10, shuffle=True, epochs=20) And if not, why not? It seems that if I run through the generator, I can only output the images and not the masks as well so I'm concerned it's not doing what I'd like it to.
upvote count: 3
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51657016
tagged with: deep-learning
answer count: 3
downvote count: 0
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/51737614
favorite count: 0
has title: Xgboost (GPU) crashing while predicting
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51737831
type: Question
has body: I am using XGBoost GPU version in Python and it crashes whenever I try to run .predict. It works for a smaller data set but for my current problem it is not working. train_final.shape, test_final.shape ((631761, 174), (421175, 174)) params = { 'objective': 'multi:softmax', 'eval_metric': 'mlogloss', 'eta': 0.1, 'max_depth': 6, 'nthread': 4, 'alpha':0, 'num_class': 5, 'random_state': 42, 'tree_method': 'gpu_hist', 'silent': True } GPU Stats: GTX 1070, 6 GB RAM: 32 GB Could someone please help me understand why is this happening?
accepted answer: http://stackoverflow.com/a/51737831
score: 2
answer count: 1
downvote count: 0
tagged with: xgboost

http://stackoverflow.com/q/51782385
downvote count: 1
tagged with: tensorflow
has title: How does transposed convolution work with same padding in tensorflow
type: Question
has body: I have been looking at Transposed Convolution with same padding and strides of 2 and something doesn't make sense to me. Given an input of width and height of 3x3, the output will have a shape 6x6. From what I have read, convolution transposed is just convolution. So input like 1 2 3 4 5 6 7 8 9 will be transformed to the following matrix then convolved on with strides of 1 1 0 2 0 3 0 0 0 0 0 4 0 5 0 6 0 0 0 0 0 7 0 8 0 9 Thus the output should have a shape of 5x5, where did the extra column come from ? .
upvote count: 5
has comment: http://stackoverflow.com/comment/90531883
linked to: http://stackoverflow.com/q/50683039
score: 4
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90530279
favorite count: 0
has comment: http://stackoverflow.com/comment/90530674
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90530105
answer count: 0

http://stackoverflow.com/q/51760801
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90480948
type: Question
has comment: http://stackoverflow.com/comment/90483969
has comment: http://stackoverflow.com/comment/90483795
score: 0
has comment: http://stackoverflow.com/comment/90480909
upvote count: 1
favorite count: 0
has body: I am using tensorflow in jupyter notebook. I have some data which i have trained. Data is in the following form 0 0 1 0 2 0 3 0 4 0 Now i am predicting values which are in this form after using linear classifier [{'class_ids': array([1], dtype=int64), 'classes': array([b'1'], dtype=object), 'logits': array([ -0.88531315, 12.51075077, -14.0423975 , 2.56915855], dtype=float32), 'probabilities': array([ 1.52104417e-06, 9.99950290e-01, 2.93827636e-12, 4.81282150e-05], dtype=float32)}, {'class_ids': array([3], dtype=int64), 'classes': array([b'3'], dtype=object), 'logits': array([ 6.42214537, 21.82447243, -13.30796623, 23.08537292], dtype=float32), 'probabilities': array([ 4.51742359e-08, 2.20818907e-01, 1.21958252e-16, 7.79181063e-01], dtype=float32)}, {'class_ids': array([2], dtype=int64), 'classes': array([b'2'], dtype=object), 'logits': array([ 27.05874252, -58.91906357, 48.28507996, -113.13697052], dtype=float32), 'probabilities': array([ 6.04670480e-10, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], dtype=float32)}, Now i want to plot them on graph. Problem is that i can not do that due to this error TypeError: float() argument must be a string or a number, not 'dict' How can i resolve this. This is the code i am using pred_inpuy_func = tf.estimator.inputs.pandas_input_fn(x=testCal, batch_size=10, num_epochs=1, shuffle=False) predictions = model.predict(pred_inpuy_func) Latest_Pred = list(predictions) import matplotlib.pyplot as pt %matplotlib inline pt.plot(y_test,my_pred,".")
has comment: http://stackoverflow.com/comment/90480832
has comment: http://stackoverflow.com/comment/90483701
type: UnansweredQuestion
has title: How to Plot Input and predicted data on graph in tensorflow jupyter notebook
tagged with: python
has comment: http://stackoverflow.com/comment/90483941
answer count: 0
has comment: http://stackoverflow.com/comment/90480751
tagged with: machine-learning
downvote count: 1

http://stackoverflow.com/comment/90439639
type: QuestionComment
has text: What have you tried so far? Please include a [mcve] of your problem. A code block defining what an "idea" object should look like would be a good start, but anything that you've attempted to try and solve this would also help us steer you in the right direction.
type: Comment
comment on: http://stackoverflow.com/q/51739732
score: 1

http://stackoverflow.com/q/51713955
tagged with: python-3.x
has body: I have a VM with Ubuntu 18.04.1. python3 --version says 3.6.5. I installed pip without any failure (seems like). Then I tried to install steem-python with pip install steem but I get a failure, which looks like: bla bla bla ... ^~~~~~~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for scrypt Running setup.py clean for scrypt ... ^~~~~~~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-0iqf8q/scrypt/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-1dMD0Y-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-build-0iqf8q/scrypt/ Now I'm out of ideas. Can anybody help me to fix this? How can I install it? My goal is to interact with the steem blockchain.
upvote count: 2
type: UnansweredQuestion
tagged with: steemit
tagged with: python
has answer: http://stackoverflow.com/a/51714090
score: 1
downvote count: 1
type: Question
has title: How to Resolve 'Error while installing steem-python'
tagged with: ubuntu
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51710617
type: Question
tagged with: ubuntu-16.04
has title: TensorFlow environment is not activated
has comment: http://stackoverflow.com/comment/90383004
has comment: http://stackoverflow.com/comment/90384294
has comment: http://stackoverflow.com/comment/90382760
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90383272
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90382483
has body: I am having a problem with setting up tensorflow environment for good. I have installed all the required packages and Jupyter Notebook runs seamlessly without any problems. However there is one slight problem for which I could not figure out a solution so far. In fact, I am able to run tensorflow environment only if I excecute this command line $source activate tensorflow each time I would like to run $jupyter notebook. The following is where my tensorflow environment is created using anaconda : $ ls /home/user/.conda/envs/ tensorflow $ which jupyter /home/user/.conda/envs/tensorflow/bin/jupyter How could I please solve this issue once for good?
has comment: http://stackoverflow.com/comment/90383124
tagged with: tensorflow

http://stackoverflow.com/q/51765879
has body: I'm developing a website that consists of different songs. These songs contain different attributes, one of them is a midi file that I upload through the fileField field of django. When I add a song with these attributes using a form, I call a script that generates a csv file with midi attribute information. The problem is that I would like to assign this resulting csv file directly to another Filefield, i.e. when I create the form, this csv is assigned to a fileField, just after submitting the form. I'd like to know if somebody could please help me with this. If you need any code or something else let me know. Here's my code at forms.py. With this form, I add a new song with the following atributes. class FormCancion(forms.ModelForm): class Meta: model = Cancion fields= ['titulo','creacion','midi','dificultad','nota_pad_verde','nota_pad_gris','nota_pad_azul','nota_pad_amarillo','nota_pad_rojo'] views.py code. This view is used to call the form that will add the new song. def crearCancion(request): cancion=Cancion() if request.method=="POST": formulario=FormCancion(request.POST,request.FILES,instance=cancion) if formulario.is_valid(): formulario.save() subprocess.call(['python', '/home/josema/MEGA/Universidad/Universidad/PROYECTO/MIDIPIRCUSSION/MIDIPIRCUSSION_APP/static/MIDIPIRCUSSION_APP/parser.py', '/home/josema/MEGA/Universidad/Universidad/PROYECTO/MIDIPIRCUSSION/media/'+str(cancion.midi)]) return redirect('/ListadoCanciones/') else: formulario=FormCancion() context={'formulario':formulario} return render(request,"nuevaCancion.html",context) My models.py code. The only model field that I need to add is the csv file. I'd like to add it automatically after I submit the form. class Cancion(models.Model): titulo=models.CharField(max_length=60) creacion=models.DateField(default=timezone.now) avanzado="Avanzado" intermedio="Intermedio" principiante="Principiante" dificultades=((avanzado, 'Avanzado'), (intermedio, 'Intermedio'), (principiante, 'Principiante')) dificulta…
has comment: http://stackoverflow.com/comment/90490743
linked to: http://stackoverflow.com/q/7514964
type: Question
has comment: http://stackoverflow.com/comment/90524463
accepted answer: http://stackoverflow.com/a/51767623
tagged with: django
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90490615
has title: assign resulting csv file to django model
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51767623
tagged with: midi

http://stackoverflow.com/comment/90541530
type: Comment
score: 0
type: AnswerComment
has text: side question, how did you load the data? using pd.read_clipboard?
comment on: http://stackoverflow.com/a/51792018

http://stackoverflow.com/a/51711375
has comment: http://stackoverflow.com/comment/90384315
has body: Clean up any trailing whitespace so that things group properly. Filter your DataFrame, and then apply groupby + size df['category'] = df.category.str.strip() df['user_uid'] = df.user_uid.str.strip() df[df.event_type == 'post'].groupby(['user_uid', 'category']).size() Output: user_uid category 11 like 2 42 share 1 dtype: int64
type: Answer
accepted answer of: http://stackoverflow.com/q/51711306
has comment: http://stackoverflow.com/comment/90384418
answers question: http://stackoverflow.com/q/51711306
has comment: http://stackoverflow.com/comment/90384522
has comment: http://stackoverflow.com/comment/90384704
score: 5
has comment: http://stackoverflow.com/comment/90384855
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/90384741
has comment: http://stackoverflow.com/comment/90384817
has comment: http://stackoverflow.com/comment/90384738
has comment: http://stackoverflow.com/comment/90384749

http://stackoverflow.com/q/51793998
has title: Cannot download article using newspaper3k
tagged with: python
tagged with: python-newspaper
has comment: http://stackoverflow.com/comment/90546366
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/78673482
type: Question
has body: I have even tried the commands in pypi.org but no article is getting downloaded. from newspaper import Article url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/' article = Article(url) article.download() article.html article.html only gives empty sting ' '. when i try article.parse() it gives error * You must download() an article first! I have tried workaround while article.download_state == ArticleDownloadState.NOT_STARTED: # Raise exception if article download state does not change after 10 seconds if slept &gt; 9: raise ArticleException('Download never started') sleep(1) slept += 1 still unable to solve the issue.
has comment: http://stackoverflow.com/comment/90561492
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/53253497
favorite count: 0

http://stackoverflow.com/comment/90426988
has text: Side note: I suggest you use [`jsonlite`](https://cran.r-project.org/web/packages/jsonlite/index.html) instead of [`RJSONIO`](https://cran.r-project.org/web/packages/RJSONIO/index.html); the former was updated last year, the latter over four years ago.
type: Comment
comment on: http://stackoverflow.com/q/51733152
score: 0
type: QuestionComment

http://stackoverflow.com/q/51747822
accepted answer: http://stackoverflow.com/a/51751867
type: Question
upvote count: 4
downvote count: 0
score: 4
tagged with: azure-cognitive-services
has answer: http://stackoverflow.com/a/51751867
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: How to use normalized coordinates in a rectangle for OpenCV
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: I'm using the Microsoft Custom Vision service for object detection with the Python SDK. I'm able to make predictions and I'm trying to use the bounding box information that comes back from the prediction to overlay a rectangle on the image using OpenCV. However, I'm not sure how to exactly calculate from the normalized coordinates that come back from the Custom Vision service to the point vertexes that the OpenCV rectangle function takes in. Here's an example of what comes back from the service as bounding box: {'left': 0.146396145, 'top': 0.0305180848, 'width': 0.373975337, 'height': 0.570280433} Currently, I'm doing these calculations below. The x and y values look like they're being calculated correctly, but I'm not sure how to calculate the second vertex. The image shape was resized to (400, 400). for pred in predictions: x = int(pred.bounding_box.left * img.shape[0]) y = int(pred.bounding_box.top * img.shape[1]) width = int(pred.bounding_box.width * img.shape[0]) height = int(pred.bounding_box.height * img.shape[1]) img = cv2.rectangle(img, (x,y), (width,height), (0,0,255), 2) And here is the resulting image from the above code: The first box looks like it's not going far enough, whereas the second box looks like it produced a rectangle going the opposite way of where it should. Does anyone know how to calculate these correctly from normalized coordinates?

http://stackoverflow.com/comment/90375751
comment on: http://stackoverflow.com/q/51669073
score: 0
type: Comment
type: QuestionComment
has text: Its right there in your screenshot. `import error: cannot import self`. That error is very specifically telling you that no method exist called `self()` inside of `openApplications.py`. Unless you want to show more of that py file there is nothing else we can do to help.

http://stackoverflow.com/q/51750164
downvote count: 0
has answer: http://stackoverflow.com/a/51751337
score: 1
has title: How to loop through columns of a pandas DataFrame
favorite count: 0
has comment: http://stackoverflow.com/comment/90460494
has comment: http://stackoverflow.com/comment/90461180
has comment: http://stackoverflow.com/comment/90460205
possible better answer: http://stackoverflow.com/a/51751337
has comment: http://stackoverflow.com/comment/90460399
tagged with: datetime
has comment: http://stackoverflow.com/comment/90460719
tagged with: python
has answer: http://stackoverflow.com/a/51751419
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90460812
upvote count: 1
accepted answer: http://stackoverflow.com/a/51751419
linked to: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/110397786
type: Question
has comment: http://stackoverflow.com/comment/90460975
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90460777
duplicate of: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/90460675
has comment: http://stackoverflow.com/comment/90461014
has body: I have a CSV file with thousands of rows. The file has 3 columns Date, Time and Value. I want to first loop through the date column and then the time column then add the value between two particular time. Is there any function in Pandas to achieve this? Below is my sample CSV. The dates are not continuous but they are in ascending order. Date Time Value 29-Jan-18 11:00 10 29-Jan-18 12:00 11 29-Jan-18 13:00 12 29-Jan-18 14:00 13 31-Jan-18 11:00 90 31-Jan-18 12:00 91 31-Jan-18 13:00 92 31-Jan-18 14:00 93 I am looking for output as "For 29-Jan-18 and for time 11 to 13, the sum of the values is 33." Not exactly 11-12 but there is a series. The calculation will be done for 9-10,10-11,11-13,13-15 but in the CSV file, every hour is present.
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90460527
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90460745

http://stackoverflow.com/q/51661327
tagged with: python
has comment: http://stackoverflow.com/comment/90286469
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51661618
tagged with: linked-list
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/51661618
type: Question
has answer: http://stackoverflow.com/a/51661752
tagged with: data-structures
answer count: 3
downvote count: 0
has body: I am trying to add elements to end of my linked list and do not see that happening. It always seem to add None to the end of the linked list. I am not sure why this happens and I am guessing this has to do something with someone my .next setup incorrectly. I am using python to implement my linked list. Can someone please help me with this Below is my Node class class Node: def __init__(self): self.data = None self.next = None def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next def set_next(self, node): self.next = node And here is my linked list class with insert methods class SingleyLinkedList: def __init__(self): self.head = Node() def insertAtHead(self, data): currentNode = self.head newNode = Node() newNode.set_data(data) if currentNode != None: newNode.set_next(currentNode) self.head = newNode print("Inserted ", data, " at the head") else: self.head.set_next(newNode) def insertAtEnd(self, data): currentNode = self.head new_node = Node() new_node.set_data(data) while currentNode.get_next() != None: currentNode = currentNode.next currentNode.set_next(new_node) print("Inserted ", data, " at end") def printNode(self): print("\nPrinting the nodes") currentNode = self.head while currentNode.next != None: print(currentNode.data, " --> ", end="") currentNode = currentNode.next print(" NULL \n") s = SingleyLinkedList() s.insertAtHead(5) s.printNode() s.insertAtHead(10) s.printNode() s.insertAtHead(1) s.printNode() s.insertAtEnd(20) s.printNode() I get the below result, Inserted 5 at the head Printing the nodes 5 --> NULL Inserted 10 at the head Printing the nodes 10 --> 5 --> NULL Inserted 1 at the head Printing the nodes 1 --> 10 --> 5 --> NULL Inserted 20 at end Printing the nodes 1 --> 10 --> 5 --> None --> NULL
has comment: http://stackoverflow.com/comment/90286286
favorite count: 0
accepted answer: http://stackoverflow.com/a/51661752
has answer: http://stackoverflow.com/a/51662011
has title: Add items to end of Linked List gives strange result

http://stackoverflow.com/q/51648253
possible better answer: http://stackoverflow.com/a/51648407
tagged with: python
has answer: http://stackoverflow.com/a/51648542
score: 2
type: AnsweredQuestion
has title: Python reshaping a np 4D array into a 2D array. Kaggle Image data
upvote count: 2
tagged with: kaggle
type: Question
accepted answer: http://stackoverflow.com/a/51648542
tagged with: numpy
answer count: 2
downvote count: 0
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51648407
has body: I am trying to convert a 4D array into a 2D array for the use of sklearn SVM model but it gives me issues when I try to use the data in the model. So i get the data split into the train and test data and then convert it into a np array like so. #Train data npXt = np.array(x_train) npYt = np.array(y_train) #Eval test data npXT = np.array(x_test) npYT = np.array(y_test) Then I look at the shape like so npXt.shape Which gives me this, (28709, 48, 48, 1) I try to change it by doing this; npXt.transpose((28709, 48, 48, 1)).reshape(np.prod(npXt.shape[:2]),-1) But gives this error. AxisError Traceback (most recent call last) &lt;ipython-input-8-2682876229f4&gt; in &lt;module&gt;() ----&gt; 1 npXt.transpose((28709, 48, 48, 1)).reshape(np.prod(npXt.shape[:2]),-1) AxisError: axis 28709 is out of bounds for array of dimension 4 What am I doing wrong here? Thanks for any help with this UPDATE: Thank you for all the suggestions: I tried it and there is a error like this: ValueError: bad input shape (28709, 7) So here is what I have fixed to get to this. What I think is the problem is that I am not reshaping the array right currently. So I download the data like this and this works fine: x_train, y_train, x_test, y_test = aiu.getKaggleData(file,numClass) Which gives this as the result: Creating Testing and Training datasets Filling datasets Transforming data to fit model's needs Normalizing traing/testing datasets Reshaping data 28709 train samples 3589 test samples I expect this and this worked with another model that I built. Next I build the SVM model like so: clf = SVC(C=0.01, kernel='linear', decision_function_shape='ovo', probability=True) Then convert the train and test data into np arrays like this #Train data npXt = np.array(x_train) npYt = np.array(y_train) #Eval test data npXT = np.array(x_test) npYT = np.array(y_test) Then using what has been suggested my_array = np.ones((28709, 48, 48, 1)) newXTrain = np.transpose( my_array ).reshape(np.prod(npXt.shape[:2]),-1) print…
favorite count: 0

http://stackoverflow.com/q/51794744
has comment: http://stackoverflow.com/comment/90547490
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90547438
downvote count: 1
upvote count: 23
type: Question
has answer: http://stackoverflow.com/a/51794822
has answer: http://stackoverflow.com/a/51794989
score: 22
possible better answer: http://stackoverflow.com/a/51794822
linked to: http://stackoverflow.com/q/45147100
has title: dropping empty columns in pandas 0.23+
answer count: 2
tagged with: pandas
duplicate of: http://stackoverflow.com/q/45147100
accepted answer: http://stackoverflow.com/a/51794989
has comment: http://stackoverflow.com/comment/90547806
has body: In earlier versions of pandas, you could drop empty columns simply with: df.dropna(axis='columns') However, dropna has been depreciated in later builds. How would one now drop multiple (without specifically indexing) empty columns from a dataframe?
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51723207
accepted answer of: http://stackoverflow.com/q/51722864
type: Answer
score: 3
upvote count: 3
has body: One manual solution is to use a list comprehension. The steps are: Set your index to the key column cid. Calculate the length of your list comprehension loop from the number of columns. Use concat with your list of dataframes and rename columns via pipe [add other formatting if required]. Finally, reset_index (to elevate the index to a series) and drop_duplicates. Here's a demo: df = df.set_index('cid') def formatter(df): df.columns = ['uid', 'url'] return df n = int(len(df.columns) / 2) L = [df.iloc[:, 2*i:2*(i+1)].pipe(formatter) for i in range(n)] res = pd.concat(L, axis=0).reset_index().drop_duplicates() print(res) cid uid url 0 c1 p1 urlp1 3 c2 p2 urlp2 5 c1 t1 urlt1 8 c2 t2 urlt2 10 c1 s1 urls1 11 c1 s2 urls2 12 c1 s3 urls3 13 c2 s5 urls5 14 c2 s6 urls6
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51722864

http://stackoverflow.com/a/51676445
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51676390
has body: It is dependent on the particular model. Some methods have analytical solutions, like Linear-, Ridge- and Kernel Ridge regression. Some methods like neural networks use numerical solvers. In some cases the documentation has details on the exact methods used, or have options to set it yourself.
downvote count: 0
score: 1

http://stackoverflow.com/comment/90381531
comment on: http://stackoverflow.com/q/51699287
type: QuestionComment
type: Comment
score: 0
has text: Thank you! I tried and I can `stat` the file. What will happen if I have a long complicated name?

http://stackoverflow.com/q/51693871
type: AnsweredQuestion
has title: python pandas create a list group by value
type: Question
has answer: http://stackoverflow.com/a/51694298
has body: I have a dataframe in python: pID sID time 0 2133 152414 2018-06-16 1 1721 152912 2018-06-17 2 2264 152912 2018-06-18 I want to create a new table with sID as the key and list of pID: pID time 152414 2133 2018-06-16 152912 1721 2018-06-17 2264 2018-06-18 What is the best way to do it without iterating over all the dataframe? I tried: df.pivot(index='sID', columns=['pID', 'time']) But got: ValueError: all arrays must be same length For these table of 3 rows Thanks!
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90349689
tagged with: pivot-table
accepted answer: http://stackoverflow.com/a/51694298
tagged with: data-munging
tagged with: python

http://stackoverflow.com/q/51640866
type: AnsweredQuestion
has body: I want to pass both form data as well as list value in flask. But the form data does not come in the output. I am new to python. Sorry if my question sounds too stupid! Here is the flask code from flask import Flask from flask import render_template,request app = Flask(__name__) @app.route('/') def my_form(): return render_template('a.html') @app.route('/', methods=['GET', 'POST']) def my_form_post(): result = request.form['username'] list1=['Who is the president of India?','Who is the captain of Team India?','In which year was Mahatma Gandhi born?']; return render_template('welcome.html', result=result, lis=list1) if __name__ == '__main__': app.run(debug=True) Here is the html code: Welcome! Welcome to the quiz {{result.username}} {{lis[0]}} Here is the form page: Welcome! Welcome to the quiz. Please Enter your name to proceed! Name: I get the output as: Welcome to the quiz Who is the president of India? Why does the name entered does not come in output? However, if I just change this line code return render_template('welcome.html', result=result) I get the output as Welcome to the quiz xyz. So why can't I pass multiple variables in render_template()?
has title: Passing form data as well as list value into HTML Page using flask
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/51642193
tagged with: flask
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51642193

http://stackoverflow.com/comment/90290790
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51656381
has text: Thanks, I think it's almost there. Now its in the Citation container, but its at the same level as Citeinfo, when it should be a child of Citeinfo. Also, the new elements are all on one line, how would I get pubdate on one, and othercit on another?
type: Comment

http://stackoverflow.com/comment/90340834
score: 0
type: Comment
has text: _Should_, but the broad statement "typically wont leave pass..." is not correct.
comment on: http://stackoverflow.com/a/51689457
type: AnswerComment

http://stackoverflow.com/q/51690079
has answer: http://stackoverflow.com/a/51690575
has answer: http://stackoverflow.com/a/51690266
tagged with: pandas
has title: Using fsolve to find the price necessary for two averages to intersect in Python
tagged with: python
type: AnsweredQuestion
tagged with: scipy
type: Question
possible better answer: http://stackoverflow.com/a/51690266
accepted answer: http://stackoverflow.com/a/51690575
has body: I'm trying to create a function in Python to solve for the value needed for two moving averages, across two datasets of differing lengths, to be equal. For example, the datasets 5 2 34 54 5 Average = 14 and 7 4 11 5 56 7 8 Average = 20 I want to solve for some number X that sets them both equal to the same average. I believe the fsolve function in scipy can do this easily, but the catch is that I want to do this using something analogous to pandas' .rolling function, so that this formula can be applied on a rolling dataset moving through thousands of rows of data. So, I'm envisioning some function like the below, though obviously it doesn't work. To clarify, count_ variables have a + 1 because I'm envisioning only looking at a the trailing set of data that is -1 of the actual average set I'm looking to find. Any help is much appreciated, thank you! def equations(short_ma, long_ma, p): sum_short = short_ma.sum() sum_long = long_ma.sum() count_short = short_ma.count() + 1 count_long = long_ma.count() + 1 ptv, eq_var = p return (((sum_short + ptv) / count_short) - eq_var, ((sum_long + ptv) / count_long) - eq_var) def rolling_equations(ptv, eq_var): ptv, eq_var = fsolve(equations, (1,1)) return ptv
score: 0
answer count: 2

algorithm
tags question: http://stackoverflow.com/q/51650690
tags question: http://stackoverflow.com/q/51723241
tag name: algorithm
tags question: http://stackoverflow.com/q/51795961
tags question: http://stackoverflow.com/q/51759995
tags question: http://stackoverflow.com/q/51695322
tags question: http://stackoverflow.com/q/51718642
tags question: http://stackoverflow.com/q/51713789
tags question: http://stackoverflow.com/q/51738851
tags question: http://stackoverflow.com/q/51717675
tags question: http://stackoverflow.com/q/51716398
tags question: http://stackoverflow.com/q/51717860
tags question: http://stackoverflow.com/q/51771003
tags question: http://stackoverflow.com/q/51657128
tags question: http://stackoverflow.com/q/51659140
tags question: http://stackoverflow.com/q/51751698
type: Tag
tags question: http://stackoverflow.com/q/51772023
tags question: http://stackoverflow.com/q/51695748
tags question: http://stackoverflow.com/q/51773034
tags question: http://stackoverflow.com/q/51690935
tags question: http://stackoverflow.com/q/51687658
tags question: http://stackoverflow.com/q/51690051
tags question: http://stackoverflow.com/q/51715173
tags question: http://stackoverflow.com/q/51681499
tags question: http://stackoverflow.com/q/51643317
tags question: http://stackoverflow.com/q/51798058
tags question: http://stackoverflow.com/q/51746218
tags question: http://stackoverflow.com/q/51712467

http://stackoverflow.com/a/51729726
upvote count: 1
answers question: http://stackoverflow.com/q/51729434
has comment: http://stackoverflow.com/comment/90421269
has body: 1st 'nan' is not NaN, if we want to use fillna we need replace df.column_1=df.column_1.replace('nan',np.nan).fillna(df.column_2) or we just using np.where df.column_1=np.where(df.column_1=='nan',df.column_2,df.column_1)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51729434
has comment: http://stackoverflow.com/comment/90421300
type: Answer
has comment: http://stackoverflow.com/comment/90420737
score: 1

http://stackoverflow.com/comment/90417448
has text: I solved the warning and single graph issue, now its producing like what you have shown, I am exploring further how it could be related. please revert once you get time to look at my code.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51725678

http://stackoverflow.com/comment/90307185
type: Comment
has text: You can't do it only with your SQLite, guess you need to use [cron](https://en.wikipedia.org/wiki/Cron).
score: 0
comment on: http://stackoverflow.com/q/51672141
type: QuestionComment

http://stackoverflow.com/a/51751517
accepted answer of: http://stackoverflow.com/q/51751491
has comment: http://stackoverflow.com/comment/90463091
answers question: http://stackoverflow.com/q/51751491
upvote count: 5
has body: Use the following regex: df[~df.NAME.str.contains('Z{2,}')] 'Z{2,}' means 2 or more occurences of Z
has comment: http://stackoverflow.com/comment/90463184
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90463048
score: 5
type: Answer

http://stackoverflow.com/comment/90310045
comment on: http://stackoverflow.com/q/51673388
score: 0
type: Comment
type: QuestionComment
has text: One more question for you @ead: If the string contains a castable float, do you want it to be casted?

http://stackoverflow.com/comment/90315904
type: AnswerComment
score: 4
type: Comment
comment on: http://stackoverflow.com/a/51676395
has text: talk about low effort answers -_-

http://stackoverflow.com/comment/90429953
type: Comment
score: 0
has text: Well, my point was simply that if `Foo` has any methods, like `Foo.doStuff` you'll end up with a bunch of bound methods.
type: AnswerComment
comment on: http://stackoverflow.com/a/51734064

http://stackoverflow.com/q/51759304
tagged with: connection
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90478471
has answer: http://stackoverflow.com/a/51759339
tagged with: database
type: Question
has comment: http://stackoverflow.com/comment/90478049
score: 2
downvote count: 0
favorite count: 0
tagged with: sql-server
tagged with: sql
has title: Is there any way mssql can notify my python application when any table or row has been updated?
answer count: 1
has body: I dont have much knowledge in dbs, but wanted to know if there is any technique by which when i update or insert a specific entry in a table, it should notify my python application to which i can then listen whats updated and then update that particular row, in the data stored in session or some temporary storage. I need to send data filter and sort calls again n again, so i dont want to fetch whole data from sql, so i decided to keep it local, nd process it from there. But i was worried if in the mean time the db updates, and i could have been passing the same old data to filter requests. Any suggestions?
tagged with: python

http://stackoverflow.com/q/51657549
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90279047
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/101120182
upvote count: 1
has body: I found a solution to this little issue, however I'm still wondering why it occurred in the first place. In my code, I (think I) have a main thread as well as another thread. From the function dealing with the main thread, if the received input is "", then a function (function_a) that acquires a/the lock is called. Here is my code: import time import threading class Some_Class: def __init__(self): self.lock = threading.Lock() def function_a(self): self.lock.acquire() print("function_A called") self.lock.release() def function_b(self): self.lock.acquire() print("function_B called") self.lock.release() some_class = Some_Class() def main_thread(): while True: if input() == "": some_class.function_a() time.sleep(0.5) # &lt;----- def thread(): while True: some_class.function_b() time.sleep(0.5) def main(): threading.Thread(target=thread).start() main_thread() if __name__ == "__main__": main() So the issue goes away when i remove the time.sleep(0.5) in the main_thread() function. However, I still don't understand why when there is the time.sleep(0.5) in the main_thread() function, function_a is called for a while after the user holds the enter key for a few seconds. Could someone explain the reason(s) for this phenomenon? Thanks. Edit: If I was being unclear regarding my question: When there's no time.sleep() in the the main_function(), function_a stops printing as soon as enter is no longer pressed. But when time.sleep() is there, function_a continues to print for a while. I was wondering why it does that...
has comment: http://stackoverflow.com/comment/101097037
type: Question
has comment: http://stackoverflow.com/comment/90279037
score: 1
has comment: http://stackoverflow.com/comment/90279307
downvote count: 0
has title: Function with lock.aquire() called when its condition is no longer met
favorite count: 0

http://stackoverflow.com/comment/90349342
type: Comment
has text: @ReutSharabani , I believe the solution still works , I tried my_list_3 = [2,2,4,5] and I got [11, 11, 9, 8]
comment on: http://stackoverflow.com/a/51693953
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90442210
type: Comment
has text: It is still using the default json and not the one from the url
comment on: http://stackoverflow.com/a/51740847
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90405467
comment on: http://stackoverflow.com/q/51722449
type: QuestionComment
type: Comment
has text: You can't have it both ways, either you have a flatter namespace from which to import (and Python loads both modules for you in the process), or you have a bushy namespace and get to import individual modules. Python imports are cheap however, so **why do you care**?
score: 0

http://stackoverflow.com/comment/90410682
score: 1
has text: @Lily, OK, this is a bit involved. I can't see a simple solution. Maybe un-accept this answer and make your question clearer with a more representative example.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51724813

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/51749631

http://stackoverflow.com/q/51656477
has answer: http://stackoverflow.com/a/51656674
has title: Django with MySQL backend - group by time range
favorite count: 0
has comment: http://stackoverflow.com/comment/90467340
tagged with: django
tagged with: python
has body: I've got this simple model: models.py class Ping(models.Model): online = models.BooleanField() created = models.DateTimeField(db_index=True, default=timezone.now) def __str__(self): return f'{self.online}, {self.created}' It gives me the following results: mysql [lab]&gt; SELECT * FROM myapp_ping; +----+--------+----------------------------+ | id | online | created | +----+--------+----------------------------+ | 1 | 1 | 2018-08-02 13:34:09.435292 | | 2 | 1 | 2018-08-02 13:35:09.520200 | | 3 | 0 | 2018-08-02 13:36:09.540638 | | 4 | 0 | 2018-08-02 13:37:10.529783 | | 5 | 1 | 2018-08-02 13:38:09.779012 | | 6 | 1 | 2018-08-02 13:39:09.650365 | | 7 | 1 | 2018-08-02 13:40:09.625543 | | 8 | 1 | 2018-08-02 13:41:09.892196 | | 9 | 1 | 2018-08-02 13:42:09.802186 | | 10 | 1 | 2018-08-02 13:43:09.864551 | | 11 | 1 | 2018-08-02 13:44:09.960962 | | 12 | 1 | 2018-08-02 13:45:09.891947 | | 13 | 0 | 2018-08-02 13:46:09.141727 | | 14 | 0 | 2018-08-02 13:47:09.142030 | | 15 | 0 | 2018-08-02 13:48:09.160942 | | 16 | 0 | 2018-08-02 13:49:09.152879 | | 17 | 0 | 2018-08-02 13:50:09.280246 | | 18 | 1 | 2018-08-02 13:51:09.363184 | | 19 | 1 | 2018-08-02 13:52:09.405863 | | 20 | 1 | 2018-08-02 13:53:09.403251 | +----+--------+----------------------------+ 20 rows in set (0.00 sec) Is there a way to get an output similar to this (the ranges in which online has been false): Downtime: from | to | duration 2018-08-02 13:36:09 | 2018-08-02 13:37:10 | 1 minute and 1 second 2018-08-02 13:46:09 | 2018-08-02 13:50:09 | 4 minutes and 0 seconds I'm not sure if this can be done with Django ORM or it will need a raw MySQL query to use something like CASE orIF statements? Update: Wed 8 Aug 15:13:15 UTC 2018 So I've got a proof of concept for both solutions from @AKX answer: models.py class PingManager(models.Manager): def downtime_python(self): queryset = super().get_queryset().filter(created__gt=timezone.now() - timezone.timedelta(days=30)) offline = False ret = [] for entry in queryset: if not entry.on…
has comment: http://stackoverflow.com/comment/90469999
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51656674
tagged with: mysql
has comment: http://stackoverflow.com/comment/90276725
possible better answer: http://stackoverflow.com/a/51657040
has answer: http://stackoverflow.com/a/51657040
type: Question
upvote count: 4
answer count: 2
downvote count: 0
tagged with: django-models
score: 4
has comment: http://stackoverflow.com/comment/90481199

http://stackoverflow.com/comment/90544473
type: Comment
type: QuestionComment
score: 0
has text: Hi tried I get this :(base) C:\Users\Kevin Boss>pip install "tornado>=5.0" Collecting tornado>=5.0 Using cached https://files.pythonhosted.org/packages/8b/d6/4e4a9282a3fb8555dca2369e827bd844c7f2d1a59c5790d3bfd97eb66206/tornado-5.1-cp36-cp36m-win_amd64.whl Installing collected packages: tornado Found existing installation: tornado 4.5.1 Cannot uninstall 'tornado'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
comment on: http://stackoverflow.com/q/51790200

http://stackoverflow.com/q/51739732
has comment: http://stackoverflow.com/comment/90475751
has answer: http://stackoverflow.com/a/51760473
tagged with: tagging
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90439625
linked to: http://stackoverflow.com/q/3538322
has comment: http://stackoverflow.com/comment/90439639
has answer: http://stackoverflow.com/a/51739832
has body: Please give me a hint about how is it better to code a Python application which helps to organise ideas by tags. Add a new idea: Input 1: the idea Input 2: corresponding tags Search for the idea: Input 1: one or multiple tags As far as I understood, it's necessary to create an array with ideas and an array with tags. But how to connect them? For example, idea number 3 corresponds to tags number 1 and 2. So the question is: how to link these two arrays in the most simple and elegant way?
type: UnansweredQuestion
has title: Python app to organise ideas by tags
tagged with: logic
type: Question
tagged with: python

http://stackoverflow.com/comment/90329385
type: QuestionComment
has text: It returns a new `Chain` whose path is the current path plus the extra bit. Your step 7 is wrong. The path doesn't somehow go back to being empty.
comment on: http://stackoverflow.com/q/51683408
score: 1
type: Comment

http://stackoverflow.com/q/51715851
has title: Python Django Shell AttributeError: 'Article' object has no attribute 'title'
has comment: http://stackoverflow.com/comment/90393298
tagged with: python
has body: I am new in django please help to find out this problem. I am trying to get hello world from DB but it's not working. Have a look in my windows power shell as administration windows. I have a app articles in my django project and there I have changed the models models file and made a basic class Article with title, date and body field . Also has a function str Article model is below from django.db import models # Create your models here. # A MODEL IS REPRESENTED BY CLASS class Article(models.Model): title : models.CharField(max_length=100) slug : models.SlugField() body : models.TextField() date : models.DateTimeField(auto_now_add=True) # ADD IN THUMNAILL LETTER def __str__(self): return self.title Command Prompt Windows PowerShell &gt;&gt;&gt; from articles.models import Article &gt;&gt;&gt; Article &lt;class 'articles.models.Article'&gt; &gt;&gt;&gt; Article.objects.all() &lt;QuerySet [&lt;Article: Article object (1)&gt;, &lt;Article: Article object (2)&gt;]&gt; &gt;&gt;&gt; article = Article() &gt;&gt;&gt; article &lt;Article: Article object (None)&gt; &gt;&gt;&gt; article.title = "hello world" &gt;&gt;&gt; article.title 'hello world' &gt;&gt;&gt; article.save() &gt;&gt;&gt; Article.objects.all() &lt;QuerySet [&lt;Article: Article object (1)&gt;, &lt;Article: Article object (2)&gt;, &lt;Article: Article object (3)&gt;]&gt; &gt;&gt;&gt; Article.objects.all()[0].title Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'Article' object has no attribute 'title'
has answer: http://stackoverflow.com/a/51718062
tagged with: django
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90393108
has comment: http://stackoverflow.com/comment/90393156
score: 0
tagged with: sql
answer count: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90340870
type: Comment
has text: @eDen "How it is working" is that your `return` statement is ending the entire function.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51689457

http://stackoverflow.com/q/51762200
score: 1
possible better answer: http://stackoverflow.com/a/51763300
has body: I am currently trying this to change the values of a panda column depending on another columns value. No problem so far but I would like to iterate through both columns in order to set my tables as in the example below: I have a panda table like this: id id2 1 0 1 0 1 0 2 0 2 0 2 0 ... I would like to get something like this: id id2 1 1 1 2 1 3 2 1 2 2 2 3 ... So I somehow have to check the value of the id column and depending on it change the values of id2. So far I only have that: n=1 m=50 df.loc[df.id==n, 'id2'] = m This gives me the following output, but is not quite what I am trying to do: id id2 1 50 1 50 1 50 2 50 2 50 2 50 I am new to programming and all the loops I tried failed. I would be very thankful if anyone could explain me how to do it!
type: Question
has answer: http://stackoverflow.com/a/51763150
has comment: http://stackoverflow.com/comment/90484338
answer count: 2
tagged with: iterator
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51763300
tagged with: python
favorite count: 0
downvote count: 0
has title: Looping through pandas table, changing value by condition on other column
tagged with: loops
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51763150

http://stackoverflow.com/q/51736172
has answer: http://stackoverflow.com/a/51832254
tagged with: numpy-ufunc
favorite count: 0
tagged with: dask
type: Question
accepted answer: http://stackoverflow.com/a/51832254
score: 5
tagged with: python
has body: In the xarray documentation for the function apply_ufunc it says: dask: ‘forbidden’, ‘allowed’ or ‘parallelized’, optional How to handle applying to objects containing lazy data in the form of dask arrays: ‘forbidden’ (default): raise an error if a dask array is encountered. ‘allowed’: pass dask arrays directly on to func. ‘parallelized’: automatically parallelize func if any of the inputs are a dask array. If used, the output_dtypes argument must also be provided. Multiple output arguments are not yet supported. and in the documentation's page on Parallel Computing then there is a note: For the majority of NumPy functions that are already wrapped by dask, it’s usually a better idea to use the pre-existing dask.array function, by using either a pre-existing xarray methods or apply_ufunc() with dask='allowed'. Dask can often have a more efficient implementation that makes use of the specialized structure of a problem, unlike the generic speedups offered by dask='parallelized'. However, I'm still not clear as to what the difference between these two options is. Does allowed still operate on chunks one by one to lower memory usage? Will allowed still parallelize if the applied ufunc only uses dask operations? Why does parallelized require you to give more information about the ufunc outputs (i.e. the arguments output_dtypes, output_sizes) than allowed does?
answer count: 1
has title: What's the difference between dask=parallelized and dask=allowed in xarray's apply_ufunc?
upvote count: 5
tagged with: python-xarray
tagged with: numpy
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51712338
has title: Equation calculations with 4D arrays
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90386089
type: Question
tagged with: numpy
upvote count: 0
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/51712492
favorite count: 0
tagged with: multidimensional-array
has body: Basically I have over 1000 3D arrays with the shape (100,100,1000). So some pretty large arrays, which I need to use in some calculations. The great thing about python and Numpy is that instead of interations, calculations on each element and such can be done very quickly. For example, I can make a sum of each index for each 3D array almost instant. The result is one large array with the sum of each index for each array. In principle, that is ALMOST what I want to do, however, there is a bit of a problem. What I need to do is use an equation that looks like this: So as stated, I have around 1000 3D arrays. In total, the shape of this total array is (1000, 100, 100, 1000). For each of the 1000 I also have a list going from 1 to 1000 that corresponds to the 1000 3D arrays, and each index of that list contains either a 1 or a 0. If it has a 1 that entire 3D array of that index should go in the first term of the equation, and if 0, it goes into the other. I am however very much in doubt about how I am going to do this without turning to some kind of looping that might destroy the speed of the calculations by a great deal.
accepted answer: http://stackoverflow.com/a/51712492
downvote count: 2
tagged with: python

http://stackoverflow.com/a/78503336
type: Answer
downvote count: 1
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/138398583
answers question: http://stackoverflow.com/q/51762534
has body: I use sqlalchemy for my project too, and i found a way to easily reverse a query. Ordering by negative id worked for me. Comment.query.filter(Comment.id &gt; 5).order_by(-Post.id.asc()).limit(3) If -Post.id.asc() is an integer or a float, this should work. I hope that helps EDIT: If you want [8, 7, 6] instead of [10, 9, 8], just move the method order_by() so that you first do a limit and then order what you get. Its easy, come on Comment.query.filter(Comment.id &gt; 5).limit(3).order_by(-Post.id.asc())

http://stackoverflow.com/q/51794208
accepted answer: http://stackoverflow.com/a/51794372
has comment: http://stackoverflow.com/comment/90557081
tagged with: python
has comment: http://stackoverflow.com/comment/90546098
possible better answer: http://stackoverflow.com/a/51794263
has comment: http://stackoverflow.com/comment/90546074
has comment: http://stackoverflow.com/comment/90556400
downvote count: 1
has answer: http://stackoverflow.com/a/51794263
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51794372
tagged with: oop
has comment: http://stackoverflow.com/comment/90546089
has body: I have a matrix class similar to here: class Matrix(object): def __init__(self, m, n, init=True): if init: self.rows = [[0]*n for x in range(m)] else: self.rows = [] self.m = m self.n = n def __setitem__(self, idx, item): self.rows[idx] = item print("HERE") ... I would like to set an element to a value of 2: my_mat = 0000 my_mat = 0000 0000 -&gt; 0200 0000 0000 0000 0000 and in my main() I set the element like this: from matrix import Matrix def main(): # Create matrix my_mat = Matrix(4,3) # Set element my_mat[1][1] = 2 print(my_mat) if __name__ == "__main__": main() The __setitem__ definition requires 3 args, (one which is self, that is provided automatically). So, id and item are needed. I have tried a number of different combinations to set an element of the matrix. When I try to set the element (above), "HERE" isn't printed. It appears that I'm not accessing the __setitem__ method at all. How do I set an element using the __setitem__ def? Syntax and examples would be appreciated. I have tried variations like: my_mat(1,1) = 2 my_mat(1,1,2) my_mat([1,1],2) .... but all fail.
score: -1
linked to: http://stackoverflow.com/q/16248012
answer count: 2
has comment: http://stackoverflow.com/comment/90547702
upvote count: 0
tagged with: matrix
favorite count: 0
has title: How to access the __setitem__ definition | Syntax & Examples?

http://stackoverflow.com/comment/90349363
comment on: http://stackoverflow.com/a/51693953
score: 0
type: AnswerComment
type: Comment
has text: @AhamedMoosa I've expanded my answer to address whatever you may have meant.

http://stackoverflow.com/comment/90485534
comment on: http://stackoverflow.com/q/51751934
type: Comment
type: QuestionComment
score: 0
has text: In response to your last comment they can contain both files and directories... added an explanation to the output format. How should the structure look if this is the case?

http://stackoverflow.com/comment/90263040
comment on: http://stackoverflow.com/q/51649572
has text: This line throws an error because the type of c is list, and .keys() is a function of dictionary. The elements of c are dictionaries, i.e, c[0].keys() will not throw an error.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90460853
comment on: http://stackoverflow.com/q/51749603
type: Comment
has text: @bedford Depends on your Linux distribution. Ask a system administrator. If you don't have a log entry, how do you know that the kernel killed the backend?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90517392
comment on: http://stackoverflow.com/q/51778992
score: 0
has text: Just a hint: Python is not Java. You don't have to write setters and getters for everything. Iff you need special behaviour, use a `property`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90537940
comment on: http://stackoverflow.com/q/51790199
has text: What form is your number in? Note that if it's a float, your representation is not guaranteed to have the exact value that you expect.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51748058
has answer: http://stackoverflow.com/a/51914498
accepted answer: http://stackoverflow.com/a/51914498
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 16
favorite count: 0
possible better answer: http://stackoverflow.com/a/51811225
has answer: http://stackoverflow.com/a/51811225
answer count: 3
has body: I'm trying to setup a local directory with packages that can be reused for installation on a machine without an internet connection but I'm having problems with some of the packages. I first download the packages with pip download -r requirements.txt -d my_packages --no-binary :all: And then I try to install them with pip install -r requirements.txt --no-index -f my_packages One of the packages I'm having trouble installing is elasticsearch-dsl==6.1.0: pip install -r requirements --no-index -f my_packages Looking in links: my_packages Collecting elasticsearch-dsl==6.1.0 Collecting six (from elasticsearch-dsl==6.1.0) Collecting python-dateutil (from elasticsearch-dsl==6.1.0) Installing build dependencies ... error Complete output from command /Users/Oskar/.pyenv/versions/2.7.15/envs/no_internet/bin/python2.7 -m pip install --ignore-installed --no-user --prefix /private/var/folders/36/t0_t6_td2f560t2j0149vjmw0000gn/T/pip-build-env-moib0N --no-warn-script-location --no-binary :none: --only-binary :none: --no-index --find-links my_packages -- setuptools wheel: Looking in links: my_packages Collecting setuptools Could not find a version that satisfies the requirement setuptools (from versions: ) No matching distribution found for setuptools Sure, setuptools I can manually install but there is more packages than that which is required for all the other packages. django-guardian==1.4.9 is another example which requires pytest-runner which for some reason is not downloaded with pip download
has answer: http://stackoverflow.com/a/51811419
has title: All dependencies are not downloaded with "pip download"
tagged with: package
score: 16
tagged with: pip
tagged with: python

http://stackoverflow.com/a/52820641
has body: You can use itertools.cycle to alternate between a remainder of 0 and 1, and use itertools.groupby to group odd-even sequences: from itertools import groupby, cycle l = [1,2,3,4,5,10,6,7,8,20,25,30,40] r = cycle((0, 1)) print(max(sum(1 for i in g) for _, g in groupby(l, key=lambda n: n % 2 == next(r)))) This outputs: 6 (since the longest odd-even sequence is 1,2,3,4,5,10)
score: 0
answers question: http://stackoverflow.com/q/51737789
type: Answer

http://stackoverflow.com/comment/90534058
score: 2
comment on: http://stackoverflow.com/q/51788397
has text: https://docs.python.org/3/library/pprint.html says, "Dictionaries are sorted by key before the display is computed." Doesn't make it sound like it's optional.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51748865
type: AnsweredQuestion
score: 3
tagged with: sqlalchemy
type: Question
has body: Suppose I have a model that conceptually should just be a dictionary from one simple type to another for a parent. I've tried to implement custom collection class but it seems that it isn't the right approach, because a custom collection should take something of type L1 as an argument when it adds it to collection. But the interface I want is Root(children={'a': 'a'}) class L1(Base): __tablename__ = 'l1s' id = sa.Column(sa.Integer, primary_key=True) parent_id = sa.Column(sa.Integer, sa.ForeignKey('roots.id')) name = sa.Column(sa.String, unique=True) value = sa.Column(sa.String) class Root(Base): __tablename__ = 'roots' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String, unique=True) children = relationship('L1', backref='parent', collection_class=partial(AsSimpleDict, L1, 'name', 'value'))
accepted answer: http://stackoverflow.com/a/51750275
downvote count: 0
favorite count: 0
answer count: 1
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/51750275
has title: How to use Dict[str, str] as a relationship property in sqlalchemy

http://stackoverflow.com/comment/90312442
comment on: http://stackoverflow.com/a/51673417
type: Comment
has text: @scharette I suspect that it would be possible to modify the behaviour of `t` (without making a full on interpreter), after all `t` is still looked-up in the appropriate name-space and if not defined this will throw a `NameError` (no actual good use cases for this though)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90520973
type: AnswerComment
type: Comment
has text: sorry, missed a part of your question. Edited
comment on: http://stackoverflow.com/a/51781708
score: 0

http://stackoverflow.com/comment/90530941
has text: [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/953482) may be of interest to you.
comment on: http://stackoverflow.com/q/51786872
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/51728921
type: Answer
has body: From your original code, one counter is enough. But lists are zero indexed for x in range(len1): dict1[teams[x]] = ratings[x]
score: 0
answers question: http://stackoverflow.com/q/51728799

http://stackoverflow.com/q/51774819
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51775246
type: Question
tagged with: api
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51775246
favorite count: 0
has body: i am creatin a project which includes integrating some major Video Network in Python.. My Main Objective is to make people search public videos by input keywords. I have done foe Youtube and now i want something similar with Vimeo but i don't get any idea on how there URI Request works.. As for Youtube i used the below codes to make a video search through the API.. import requests def browse_video_by_keyword(search , pageToken): _KEY = 'AIzaSyAlpM2iiTfLFUvEs3dR5IsHKX-wOJzh_uo' url = 'https://www.googleapis.com/youtube/v3/search?key={api_key}&amp;part=snippet,id&amp;pageToken={page}&amp;maxResults=24&amp;q={keyword}' request = requests.get(url.format(api_key=_KEY , keyword=search , page=pageToken)) res = request.json() return res["items"]; I Need someone to give me idea on how i can do something similar to this for Vimeo API.. I have search through very where i can but no get any idea.. Any Help would be appreciated. Thanks In advance..
tagged with: python
type: AnsweredQuestion
has title: How to integrate Vimeo API to Search Public Videos by keywords in python
tagged with: vimeo

http://stackoverflow.com/a/51701372
accepted answer of: http://stackoverflow.com/q/51701247
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51701247
has body: I just resolved the issue by upgrading my tensorflow to 1.9.0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/51665563
has answer: http://stackoverflow.com/a/51677946
type: UnansweredQuestion
tagged with: python
has body: I'm trying to install the cli for aws elastic beanstalk using conda install -c davidbgonzalez awsebcli but I keep running into this error: /Users/deepak/.local/lib/python2.7/site-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.23) or chardet (3.0.4) doesn't match a supported version! RequestsDependencyWarning) Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - awsebcli - urllib3 Use "conda info &lt;package&gt;" to see the dependencies for each package. Now this error appeared for many libraries- not just urllib3; but for each of those I was able to resolve by using either conda uninstall or pip install --upgrade. However, for urllib3, if I uninstall, the conda command itself doesn't work, as it says requests package not found, and if I update urllib3- it makes no difference, the conflict remains and I cant move forward with my awsebcli installation. Help? PS: I use a MacOS with conda 4.5.9 installation with python 2.7.14. I tried a pip install awsebcli- and it installed properly, but I'm not able to locate the executable and thus not sure how to include it into the '$PATH' variable. So, I'm guessing I need to use conda install as that is the main python I use everywhere. UPDATE: this is the result of conda info urllib3 /Users/deepak/.local/lib/python2.7/site-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.23) or chardet (3.0.4) doesn't match a supported version! RequestsDependencyWarning) urllib3 1.21.1 py27_0 --------------------- file name : urllib3-1.21.1-py27_0.tar.bz2 name : urllib3 version : 1.21.1 build string: py27_0 build number: 0 channel : https://repo.anaconda.com/pkgs/free/osx-64 size : 151 KB arch : x86_64 constrains : () date : 2017-06-21 license : MIT license_family: MIT md5 : 57332c18a93a2d82131212d52a0bafbf platform : darwin subdir : osx-64 url : https://repo.anaconda.com/pkgs/free/osx-64/urllib3-1.21.1-py27_0.tar.bz2 dependencies: certifi cryp…
type: Question
has title: Resolving conflict with urllib3 to install AWS elastic beanstalk CLI using anaconda on Macos?
tagged with: conda
score: 0
answer count: 1
tagged with: macos
tagged with: amazon-elastic-beanstalk

http://stackoverflow.com/a/51746055
answers question: http://stackoverflow.com/q/51745898
has comment: http://stackoverflow.com/comment/121373981
score: 3
upvote count: 4
has comment: http://stackoverflow.com/comment/90452285
has comment: http://stackoverflow.com/comment/90453412
has body: Add export before your variables in .myfilename. export POSTGRES_HOST=postgres export POSTGRES_PORT=5432 export POSTGRES_DB=marketing export POSTGRES_USER=username export POSTGRES_PASSWORD=password export DATABASE_URL=postgres://username:password@localhost:5432/marketing Then do source .myfilename
type: Answer
downvote count: 1

http://stackoverflow.com/q/51747591
has answer: http://stackoverflow.com/a/51747922
has answer: http://stackoverflow.com/a/51749187
type: Question
possible better answer: http://stackoverflow.com/a/51748010
has answer: http://stackoverflow.com/a/51748010
accepted answer: http://stackoverflow.com/a/51749187
score: 0
answer count: 3
tagged with: pandas
has title: Match word (starting with plus symbol) in pandas data frames
tagged with: python
has body: I have two pandas data frames. I would like to find matching strings in one specific column ("keyword") exist in both data frames. keyword adGroup goal6Value adCost [aaaa] (not set) 0 0.0 +bb +bb (not set) 0 0.0 +cc +cc (not set) 2072 0.0 [dddd] (not set) 0 0.0 The second data frame: keyword status Max Min [aaaa] (not set) 0.1 0.0 +bb +bb (not set) 0.2 0.0 +ff +ff (not set) 0.1 0.0 [gggg] (not set) 0.3 0.0 I would like the output to return all columns if the keyword is available in both data frames (keyword column). The output should look like this: keyword status Max Min adGroup goal6Value adCost [aaaa] (not set) 0.1 0.0 (not set) 0 0.0 +bb +bb (not set) 0.2 0.0 (not set) 0 0.0 I have changed the data type for keyword column into string for both data frames. I have tried these options: pd.merge(df1, df2, on='keyword') and df1.set_index('keyword').join(df2.set_index('keyword')) However, both options only matched the keyword with brackets and did not return the keywords starting with a plus symbol even when they are available in both data frames. Is there a way to match the keyword with the plus symbol as well in pandas?
type: AnsweredQuestion

http://stackoverflow.com/a/51768974
type: Answer
answers question: http://stackoverflow.com/q/51768947
accepted answer of: http://stackoverflow.com/q/51768947
score: 5
upvote count: 5
downvote count: 0
has body: You can use numpy.where with cumsum of boolean mask: m = df['B']=='yes' df['C'] = np.where(m, m.cumsum(), 0) Another solution is count boolean mask created by filtering and then add 0 values by reindex: m = df['B']=='yes' df['C'] = m[m].cumsum().reindex(df.index, fill_value=0) print (df) A B C 0 Tony no 0 1 Mike yes 1 2 Jen no 0 3 Anna yes 2 Performance (in real data should be different, best check it first): np.random.seed(123) N = 10000 L = ['yes','no'] df = pd.DataFrame({'B': np.random.choice(L, N)}) print (df) In [150]: %%timeit ...: m = df['B']=='yes' ...: df['C'] = np.where(m, m.cumsum(), 0) ...: 1.57 ms ± 34.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [151]: %%timeit ...: m = df['B']=='yes' ...: df['C'] = m[m].cumsum().reindex(df.index, fill_value=0) ...: 2.53 ms ± 54.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [152]: %%timeit ...: df['C'] = df.groupby('B').cumcount() + 1 ...: df['C'].where(df['B'] == 'yes', 0, inplace=True) 4.49 ms ± 27.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
type: AcceptedAnswer

http://stackoverflow.com/q/51714244
has comment: http://stackoverflow.com/comment/90389945
has body: df = pd.Series([["26"], ["81", "15", "27"], ["50"], ["8"], ["81", "15"], ["10"], ["81"]]).to_frame(name='itemsets') itemsets 0 [26] 1 [81, 15, 27] 2 [50] 3 [8] 4 [81, 15] 5 [10] 6 [81] rule = [["81"],["15"]] i tried this but it's to slow because the dataset has 9 million lines, so i look for an efficient solution to perform this code with this solution it takes more than 4 seconds, is that a way to convert the dataframe to a numpy array or everything that performs this code ? def support(rule): rule = rule[0] + rule[1] support = 0 support = sum([set(rule)&lt;=set(row) for row in df]) return support/SIZE when i try it on the largest dataset which contains 9 million transactions the result is : support(rule) 0.001039247773829178 the idea is to count the number of occurence of a non strict subset in a dataframe
type: UnansweredQuestion
tagged with: python
has title: calculate support of a rule in large dataset
has comment: http://stackoverflow.com/comment/90390202
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51714672
type: Question
has comment: http://stackoverflow.com/comment/90390880
has comment: http://stackoverflow.com/comment/90390027
tagged with: optimization
tagged with: numpy
score: 0
tagged with: pandas
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/90390638
favorite count: 0

http://stackoverflow.com/comment/90476551
type: Comment
comment on: http://stackoverflow.com/a/51758562
has text: Documentation of `numpy.where` does not specify the order of substitution, evaluation of the condition, that of x, and that of y arguments, i.e., whether "You're applying `where` *after* you apply `log10`".
type: AnswerComment
score: 0

http://stackoverflow.com/q/51735632
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: I'm running a docker container where I've installed, via pip, django rest framework v3.8.2. I updated my code to from rest_framework.decorators import action. Doing this causes an the import error. I've tried docker-compose restart, docker-compose down, docker-compose up -d. None of those seem to be picking up the correct DRF. I've run docker exec -it &lt;container_id&gt; bash and pip freeze and it spits out djangorestframework==3.8.2 What could I be missing? Any help would be great! Thanks in advance.
has title: Import error for action for the rest_framework.decorators
has answer: http://stackoverflow.com/a/51738671
type: Question
accepted answer: http://stackoverflow.com/a/51738671
tagged with: django-rest-framework
tagged with: docker
score: 0

http://stackoverflow.com/comment/90480980
comment on: http://stackoverflow.com/q/51760130
type: Comment
type: QuestionComment
has text: Well I'm sure your code could help me with the implementation of some other code of mine, so I'd be thankful if you'd share it. For this example however, I'd like to stick with the .txt-methode. I am constantly reading out data, about 50 times/second
score: 0

http://stackoverflow.com/q/51644145
score: 1
accepted answer: http://stackoverflow.com/a/51644157
favorite count: 0
type: Question
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
tagged with: python-3.x
upvote count: 1
answer count: 1
has title: Problems transforming a pandas dataframe
has answer: http://stackoverflow.com/a/51644157
tagged with: dataframe
has body: I have troubles converting a pandas dataframe into the format i need in order to analyze it further. The current data is derived from a survey where we asked people to order preferred means of communication (1=highest,4=lowest). Every row is a respondee. The current dataframe: A B C D 0 1 2 4 3 1 2 3 1 4 2 2 1 4 3 3 2 1 4 3 4 1 3 4 2 ... For data analysis i want to transform this into the following dataframe, where every row is a different means of communication and the columns are the counts how often a person ranked it in that spot. 1st 2d 3th 4th A 2 3 0 0 B 2 1 2 0 C 1 0 0 4 D 0 1 3 1 I have tried apply defined functions on the original dataframe, i have tried to apply .groupby function or .T on the dataframe with I don't seem to come closer to the result I actually want. This is the function I wrote but I can't figure out how to apply it correctly to give me the desired result. def count_values_rank(column,rank): total_count_n1 = 0 for i in column: if i == rank: total_count_n1 += 1 return total_count_n1 Running this piece of code on a single column of my dataframe get's the desired results but having troubles to actually write it so i can apply it to the dataframe and get the result I am looking for. The below line of code would return 2. count_values_rank(df.iloc[:,0],'1') It is probably a really obvious solution but having troubles seeing the easiest way to solve this. Thanks alot!
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90503768
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51772331
has text: Awesome! thanks for explaining how the readlines() func works!

http://stackoverflow.com/comment/90520798
type: AnswerComment
comment on: http://stackoverflow.com/a/51781493
type: Comment
has text: b = data['channel']['field1'] print (b) b = data['feeds'][0]['field1'] print (b)
score: 0

http://stackoverflow.com/comment/90322771
has text: The StandardScaler has an `inverse_transform` method. See [here](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler.inverse_transform) :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51678534

http://stackoverflow.com/a/51690057
has body: The answer to your first question is this link .getting start Cgi programmin The answer to your second question: You should use multi-threaded programming. If you have sample function in module test2 ... #in test1.py import threading import test2 T1 = threading.Thread(test2.sample(object)) T1.start() Answer your third question: Then you can either make a folder in your site's path where your cgi files will live, or configure certain directories to handle certain file types as cgi scripts. This is described well in the apache2 doc above, but essentially you to make all files in a cgi folder be executed, you would use this conf: Options ExecCGI SetHandler cgi-script and to allow .py files to be executed as scripts in a particular folder you would use this conf: &lt;Directory /srv/www/yoursite/public_html&gt; Options +ExecCGI AddHandler cgi-script .py &lt;/Directory&gt; Once you have that, if you're running python 3, you can make a python script like this one, and stick it in whichever folder is configured for cgi: #!/usr/bin/env python # -*- coding: UTF-8 -*-# enable debugging import cgitb cgitb.enable() print("Content-Type: text/html;charset=utf-8") print() print("Hello World!")
score: 0
has comment: http://stackoverflow.com/comment/90342074
type: Answer
answers question: http://stackoverflow.com/q/51689867

http://stackoverflow.com/q/51679648
tagged with: python-3.7
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/54407925
accepted answer: http://stackoverflow.com/a/51680475
has body: here is my feature matching code from an Opencv tutorial import numpy as np import cv2 as cv import matplotlib.pyplot as plt img1 = cv.imread('roblox.jpg',0) # queryImage img2 = cv.imread('bloxro.jpg',0) # trainImage orb = cv.ORB_create() kp1, des1 = orb.detectAndCompute(img1,None) kp2, des2 = orb.detectAndCompute(img2,None) bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True) matches = bf.match(des1,des2) matches = sorted(matches, key = lambda x:x.distance) img3 = cv.drawMatches(img1,kp1,img2,kp2,matches[:10], flags=2) plt.imshow(img3),plt.show() when it is run i get this error message Traceback (most recent call last): File "C:\Users\Blake\Desktop\Python3.7\opencvtests.py", line 19, in &lt;module&gt; img3 = cv.drawMatches(img1,kp1,img2,kp2,matches[:10], flags=2) TypeError: drawMatches() missing required argument 'outImg' (pos 6)
has answer: http://stackoverflow.com/a/54407925
has title: Can't figure out what 'outImg' in opencv
tagged with: opencv
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51680475
answer count: 2

http://stackoverflow.com/comment/90433791
has text: Your approach is right. But please post such questions [here](https://codereview.stackexchange.com).
comment on: http://stackoverflow.com/q/51736556
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90455722
score: 0
type: AnswerComment
has text: No they are different. And same store can have different start and end dates as these are aggregated values for some time and within longer period of time, store has multiple rows.
type: Comment
comment on: http://stackoverflow.com/a/51747017

http://stackoverflow.com/comment/90435062
type: Comment
has text: The Code is quite messy please [see here](https://pastebin.com/jYyAVCHY) I though this would work (I get a ValueError: Setting Array element with sequence) but in the documentation they have a `y, x, r = blob` which I think negates this?
type: AnswerComment
comment on: http://stackoverflow.com/a/51737106
score: 0

http://stackoverflow.com/a/65766649
type: Answer
has body: Regarding the two issues you mentioned in your question, both of them result from one line in your code which is labels = ['{}-{}'.format(i + 1, j) for i, j in zip(bins[:-1], bins[1:])] The gab resulted from i+1, also the digits resulted from computer approximation in the same line. Therefore, modify it to labels = [f'{i:.1f}-{j:.1f}' for i, j in zip(bins[:-1], bins[1:])] in which we make an approximation to one digit. and no need for labels[0] = '{}-{}'.format(bins[0], bins[1])
score: 0
answers question: http://stackoverflow.com/q/51777825

http://stackoverflow.com/comment/90245883
type: AnswerComment
comment on: http://stackoverflow.com/a/51640253
type: Comment
has text: On my end this seems to be just making the entire column the first population number. 123.456 every number all the way down.
score: 0

http://stackoverflow.com/comment/90285840
score: 0
type: Comment
has text: The problem is, lets says first_animal is defined, but second_animal is None. This technique still throws an errors, because it tried to evaluate second_animal.sound (Which will obviously throw an error if second_animal = None). The decorator seems like what I want, but instead of first_animal.sound == second_animal.sound throwing an error, I just want to be false and print ("No they don't")
type: AnswerComment
comment on: http://stackoverflow.com/a/51645024

http://stackoverflow.com/q/51655753
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51658648
has title: How to return ndarray in python3 ctypes?
tagged with: python
has body: I have a c++ function: double* hiho() { double *res = new double[10]; return res; } together with from numpy.ctypeslib import ndpointer mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,)) When calling the function, I get the following error: ValueError: '&lt;P' is not a valid PEP 3118 buffer format string I use Python 3.6.2 What am I doing wrong?
score: 1
upvote count: 1
type: Question
tagged with: ctypes
has answer: http://stackoverflow.com/a/60162912
answer count: 2
downvote count: 0
favorite count: 0
tagged with: multidimensional-array

http://stackoverflow.com/q/51741605
has answer: http://stackoverflow.com/a/68535114
has comment: http://stackoverflow.com/comment/90443506
has answer: http://stackoverflow.com/a/64145149
type: Question
tagged with: normalization
upvote count: 6
has title: Standardize dataset containing too large values
answer count: 3
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90445799
has answer: http://stackoverflow.com/a/51744034
favorite count: 0
linked to: http://stackoverflow.com/q/14463277
has body: I standardize features to mean=0 and sd=1 using preprocessing.scale astype('float64'). I got the following warning: UserWarning: Numerical issues were encountered when centering the data and might not be solved. Dataset may contain too large values. You may need to prescale your features. warnings.warn("Numerical issues were encountered " Here is a sample of the dataset: col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12 col13 0 327 143.04 123.66 101.71 89.36575914 0.668110013 84.13713837 588.103818 633.6584113 525.5505746 132.966095 13.05099964 131.7220566 1 1010 188.98 176.78 137.33 89.36575914 0.620949984 40.52060699 1413.802012 3705.255352 1641.459378 106.3353716 7.69299984 472.4249759 2 1485 166.67 141.72 111.07 98.91169739 0.979290009 100 3580.441388 4327.644518 3242.16829 111.2140427 13.05300045 1164.119187 3 78 54.27 83.01 161.74 95.0061264 0.968744297 100 35644.07894 37765.71684 15667.95157 106.3043671 7.448999882 850.651571 4 591 132.86 121.22 108.13 103.231369 1.039739966 100 9348.743837 10699.19772 7144.242782 101.7313309 8.788999557 1382.113557 5 562 134.98 141.72 141.15 89.36575914 0.968744297 100 3046.147835 3710.575743 2716.801411 106.3353716 18.26099968 1076.131188 6 1030 110.83 79.08 50.87 89.36575914 0.952409983 97.35466766 11348.70932 11928.21847 7637.253514 102.3456802 9.793620323 1164.119187 7 534 109.06 109.14 106.12 89.36575914 0.968744297 100 43007.67453 54008.70819 29971.03064 106.3353716 5.602000237 1164.119187 What is prescaling ? An what are my options to do so ?
type: UnansweredQuestion
score: 6
tagged with: python
downvote count: 0
tagged with: scaling

http://stackoverflow.com/a/51644990
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90272209
has comment: http://stackoverflow.com/comment/90279713
has comment: http://stackoverflow.com/comment/90280855
has comment: http://stackoverflow.com/comment/90320184
accepted answer of: http://stackoverflow.com/q/51644736
upvote count: 1
type: AcceptedAnswer
has body: It's not clear to me whether you're trying to write multiple sheets in one Excel file. If so, the problem may be that you're re-writing the same sheet called 'Reports' four times. Also, here are some basics to try. Put the df.to_excel() after pd.ExcelWriter(). Then remove from the for loop the last four lines. Finally, put writer.save() after the for loop ends. (This was not very clear for me when I first learned them, too. See more examples at this link.) Edit: here's fully executing code (with stub data). One of of the keys was to enable multiple writes to the worksheet using writer.sheets['Reports'] = worksheet - see this explanation. dummy_df = pd.DataFrame([[10,np.NaN],[12,42],[16,np.NaN],[20,3],[25,16],[30,1],[40,19],[60,99]],columns=['legacy_id', 'b']) writer = pd.ExcelWriter('reportTemplate.xlsx', engine='xlsxwriter') workbook = writer.book worksheet = workbook.add_worksheet('Reports') writer.sheets['Reports'] = worksheet # enable multiple writes to sheet # REPORT TITLE worksheet.write('D2','Daily In-Store Report') reportTimes = ['Day','Week','Period','Quarter','Year'] cityList = ['ontario','bayshore','ottawa','limeridge','oshawa','scarborough','sherway','massonville','gatineau', 'quebec','anjou','dix30','Fairview','laval','mtltrust','stbruno','gcapitale','stefoy','rivieres','chicoutimi','sherbrooke','canada'] # LOOP THROUGH FILES rowNb = 4 for time in reportTimes: # TITLE tableTitle = time + ' report as of ...' worksheet.write('A'+str(rowNb),tableTitle) rowNb += 1 headRow, secondHead = "dummy head row", "dummy second head" #I don't have your createHeadings(time) worksheet.write_row('B' + str(rowNb), headRow) worksheet.write_row('B' + str(rowNb), secondHead) rowNb += 2 df = dummy_df.copy(deep=True) # pd.read_csv('fy_' + time.lower() + '.csv') df.set_index('legacy_id',inplace=True) df = df.reindex(cityList) #print(df) df.to_excel(writer,sheet_name='Reports', startrow = rowNb) rowNb += df.shape[0] #gives row count writer.save()
answers question: http://stackoverflow.com/q/51644736
has comment: http://stackoverflow.com/comment/90393007
type: Answer

http://stackoverflow.com/q/51704175
tagged with: sparkle
tagged with: python
tagged with: auto-update
has title: How can i integrate sparkle updater framework with my python application built with pyinstaller
upvote count: 10
answer count: 0
type: UnansweredQuestion
has body: We are developing a python application which will be installed as a process on mac (There is no UI for this app, It just installs and starts the process). I came across sparkle framework which is used by most of the apps on mac for auto updates. But i see that the framework is written in C. The distributable that we give the customers is a mpkg. Is there any way to update the application with sparkle by integrating it in python application? Are there any alternatives that i can look for? Is it possible to write a separate updater application in xcode that will update my app (python app)?
downvote count: 0
score: 10
favorite count: 0
type: Question

http://stackoverflow.com/a/51677659
has body: How about this: links = open('links.txt', 'r') links_data = links.read() links.close() keys = open('keys.txt', 'r') keys_data = keys.read() keys.close() keys_split = keys_data.split() for url in keys_split: if url in links_data: print(url) Just make sure that links.txt and keys.txt are in the current working directory and everything should work fine. I'm assuming your URLs will always be space-delimited.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90318736
accepted answer of: http://stackoverflow.com/q/51677550
score: 1
answers question: http://stackoverflow.com/q/51677550
has comment: http://stackoverflow.com/comment/90318729
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51718797
has comment: http://stackoverflow.com/comment/90398951
has comment: http://stackoverflow.com/comment/90398742
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: pyside2
has comment: http://stackoverflow.com/comment/90398696
has comment: http://stackoverflow.com/comment/90398782
type: Question
has title: Can't set transparency of QWindow after shown once while opaque
has body: I have a window I'm trying to make transparent after being shown once while opaque. However, doesn't go transparent even if I hide and show again. This is what I get: But I want it like this: (transparent against background) If I run WA_TranslucentBackground first, before .show() it creates a nice transparent button as expected. Here is an example code which shows a floating button when you run it import sys from PySide2 import QtCore, QtWidgets, QtGui class TransparentWindow(QtWidgets.QMainWindow): def __init__(self): super(TransparentWindow, self).__init__() self.setCentralWidget(QtWidgets.QWidget(self)) self.mainLayout = QtWidgets.QVBoxLayout() self.centralWidget().setLayout(self.mainLayout) self.mainLayout.addWidget(QtWidgets.QPushButton("Hello World", parent=self)) self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint) self.show() # If I move this under '.setAttribute()' it works self.setAttribute(QtCore.Qt.WA_TranslucentBackground) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) demo = TransparentWindow() sys.exit(app.exec_()) I've tried hiding and reshowing, 'setAutoFillBackground()' and 'WA_NoSystemBackground' attribute, but I cant seem to get it to work. Anybody have any idea how to set the transparency after it has been shown as opaque? Using versions QtCore: 5.9.6, Pyside2: 5.9.0a1.dev1528389443

http://stackoverflow.com/comment/90299457
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51656096
has text: @HeadOverFeet - So need `df['date'] = pd.to_datetime(df['date'])` as first step.

http://stackoverflow.com/comment/90961785
score: 0
comment on: http://stackoverflow.com/q/51712693
has text: @jalazbe That dint solve it either. I am unable to figure out what to do.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51795780
has answer: http://stackoverflow.com/a/51798670
has comment: http://stackoverflow.com/comment/90548981
has answer: http://stackoverflow.com/a/51795892
has comment: http://stackoverflow.com/comment/90549150
has comment: http://stackoverflow.com/comment/90549027
has title: Calling a python function
has comment: http://stackoverflow.com/comment/90548971
favorite count: 0
score: -1
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has body: I am trying to make a python library that allows me to make custom tkinter widgets that are more aesthetically pleasing than the built-in ones. However, I have run into a problem while defining a few functions. The problem stems from the difference between functions like append() and str(). While the append function works as follows... somelist = ['a', 'b', 'c'] somelist.append('d') The str() function works like this... somenumber = 99 somenumber_text = str(some_number) You 'call upon' the append function by (1) stating the list that you are modifying (somelist), (2) adding a period, and (3) actually naming the append funtion itself (append()). Meanwhile you 'call upon' the str function by placing a positional argument (somenumber) within its argument area. I have no idea why there is this difference, and more importantly if there is a way to specify which method to use to 'call upon' a function that I define myself? Thanks...
has comment: http://stackoverflow.com/comment/90548963
has comment: http://stackoverflow.com/comment/90549016
type: Question
answer count: 2
tagged with: function

http://stackoverflow.com/q/51720406
score: 10
has title: Error while installing debian packages programmitically using apt_pkg
has comment: http://stackoverflow.com/comment/90746436
tagged with: linux
tagged with: package-managers
downvote count: 0
answer count: 1
tagged with: debian
has comment: http://stackoverflow.com/comment/90779262
has comment: http://stackoverflow.com/comment/90740071
favorite count: 0
has comment: http://stackoverflow.com/comment/90779254
type: UnansweredQuestion
tagged with: apt
tagged with: python
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/90689823
has body: I've built some debian packages and put them on my host. I want to install these packages in a python script. So I've written the install function using apt_pkg as follows : #!/usr/bin/env python # -*- coding: utf-8 -*- import apt import apt_pkg import sys class my_pkg_manager: def __init__(self): apt_pkg.init() self.cache = apt_pkg.Cache() self.sources = apt_pkg.SourceList() self.pkg_records = apt_pkg.PackageRecords(self.cache) self.depcache = apt_pkg.DepCache(self.cache) self.pkg_manager = apt_pkg.PackageManager(self.depcache) self.fetcher = apt_pkg.Acquire() def find_my_package(self): for pkg in self.cache.packages: if len(pkg.version_list)&gt;0: package_site = pkg.version_list[0].file_list[0][0].site if package_site == 'my_host_address.com': if pkg.name == 'my_pkg_name': return pkg return None def install_package(self, pkg): self.depcache.mark_install(pkg) self.sources.read_main_list() self.pkg_manager.get_archives(self.fetcher, self.sources, self.pkg_records) log_file = open('install_log','w') res = self.pkg_manager.do_install(log_file.fileno()) if res == self.pkg_manager.RESULT_COMPLETED: print('result completed!') elif res == self.pkg_manager.RESULT_INCOMPLETE: print('result incomplete!') else: print('result failed!') def run(self): my_pkg = self.find_my_package() if my_pkg != None: self.install_package(my_pkg) else: print('Can't find package!') if __name__ == '__main__': my_package_manager = my_pkg_manager() my_package_manager.run() If I use apt-get install, packages will be installed without any problem, but with this script the following error occurs : res = self.pkg_manager.do_install(log_file.fileno()) apt_pkg.Error: E:Internal Error, Pathname to install is not absolute 'myPackage_1.0.0_all.deb' I've placed .deb file and Packages.gz in a directory named 'debian' in my host and added the following line to my sources.list : deb http://my_host_address.com debian/ I don't know what is wrong with my script?
has answer: http://stackoverflow.com/a/51900674

http://stackoverflow.com/q/51720110
has body: I am trying to select an area of an image to do some analysis on that specific area of the image. However, when I searched online, I am only able to find guides on how to select a rectangular area. I need to select an area that is drawn using my mouse. An example of such area is included bellow. Would anyone be able to recommend to me some key words or libraries to search to help me with this or links to guides that do something similar? Also, I am not sure if it is necessary information but the analysis I am trying to do on the region of interest is to Find a ratio of amount of white to black pixels in that specific area.
has comment: http://stackoverflow.com/comment/90401163
accepted answer: http://stackoverflow.com/a/51720809
tagged with: python
has comment: http://stackoverflow.com/comment/90401399
has title: Using python to select an area of an Image
type: AnsweredQuestion
tagged with: image-processing
type: Question
upvote count: 4
downvote count: 0
answer count: 1
score: 4
has answer: http://stackoverflow.com/a/51720809
linked to: http://stackoverflow.com/q/36294025
has comment: http://stackoverflow.com/comment/90401091
tagged with: roi
has comment: http://stackoverflow.com/comment/90401591
favorite count: 0

http://stackoverflow.com/a/51682465
score: 1
has body: A bit simpler approach, that gives the required result: import re result = [] for i in data.split('\n') : # data -- is your original text if re.search( r'^\d\d\.\d\d\.\d\d\d\d', i) is None : result[-1] += '\n' + i else : result.append(i) Assuming data has your original text, the result: [ "08.04.2018 15:50:14, Vlada: Ey, hello there.\n\nhows it going?\nEverything fine?\n", "08.04.2018 15:53:30, Other: Meh\ncould have been better.\n", "08.04.2018 15:55:20, Vlada: ok" ]
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51681281

http://stackoverflow.com/q/51710027
linked to: http://stackoverflow.com/q/51707009
type: Question
has comment: http://stackoverflow.com/comment/90381764
duplicate of: http://stackoverflow.com/q/51707009
downvote count: 0
tagged with: elementtree
has title: Read a non formatted xml and export it again formatted?
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has body: Here is the code but the exported xml appears formatted in a single line. import xml.etree.ElementTree as ET import os sampleXML = """<?xml version="1.0" encoding="ASCII"?> <CODE_OK>510</CODE_OK> 13/08/2018 """ tree = ET.ElementTree(ET.fromstring(sampleXML)) for folder in os.listdir("YourPath"): #Iterate the dir tree.find("CODE_OK").text = folder #Update dir name in XML tree.write(open(os.path.join(r"Path", folder, "newxml.xml"), "wb")) #Write to XML Is it possible to either turn this code to something that does exactly what this does and exports it normally formatted or to read somehow the exported xml and export it again normally formatted. Thank you.
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/90442241
has text: Also it gives me an error if I try def action(): I have to def action(jsonname):
comment on: http://stackoverflow.com/q/51740541
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51661116
has answer: http://stackoverflow.com/a/51661329
linked to: http://stackoverflow.com/q/311627
has comment: http://stackoverflow.com/comment/90285863
has comment: http://stackoverflow.com/comment/90285743
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51661316
type: Question
has body: def send_email(status,message): yag.send(to=TO_EMAIL,subject="Test Subject: {}".format(status),contents=message) logging.info("Mail Sent!") How do I add the current date DDMM format just before the subject line like: 0308 Test Subject ? Yagmail Package. Thanks in advance.
answer count: 2
tagged with: yagmail
score: 0
has title: Add Date to the subject
accepted answer: http://stackoverflow.com/a/51661316
tagged with: python
possible better answer: http://stackoverflow.com/a/51661329

http://stackoverflow.com/a/51749045
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90458262
has comment: http://stackoverflow.com/comment/90459437
answers question: http://stackoverflow.com/q/51748908
upvote count: 2
has body: There are several options available to you. Probably the simplest, conceptually, would be a dictionary keyed to a tuple (id, year), with the values as tuples (variable1, variable2), or as a dict, eg &gt;&gt;&gt; {(1, 1990): {'v1': 'x', 'v2': 'y'}} {(1, 1990): {'v1': 'x', 'v2': 'y'}} I would consider creating an object to represent this data, though, since it's likely that the problem and your requirements will become more complex as you go along, and an object allows you to define methods to address new requirements as they arise. An intermediate solution would be a namedtuple, of which a quick example follows: &gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Machine = namedtuple("Machine", ['id', 'year', 'variable1', 'variable2']) &gt;&gt;&gt; Machine(1, 1990, 'x', 'y') Machine(id=1, year=1990, variable1='x', variable2='y') &gt;&gt;&gt; machines = [Machine(1, 1990, 'x', 'y'), Machine(1, 1991, 'a', 'b'), Machine(2, 2000, 'a', 'b')] &gt;&gt;&gt; machines_dict = {(m.id, m.year): m for m in machines} &gt;&gt;&gt; machines_dict[(2, 2000)] Machine(id=2, year=2000, variable1='a', variable2='b') &gt;&gt;&gt; (see the documentation for more info on this) Note that namedtuples do not play well with json serializers, so I still incline towards a simple object which knows how to emit a dict of its data, suitable for serializing. What I mean by "an object which knows how to emit a dict of its data" would normally just mean that the object has a method which produces a dict of the appropriate keys and shape, for example def to_dict(self): return {"ID": self.id, "year": self.year, "vars": (self.v1, self.v2)} However, you want something a little fancier, you want to summarize the data across instances. This will require taking a list of objects (or of data blobs) and doing a little parsing to group by id and list instances by year. Something like: @staticmethod def machines_to_dict(machines): machines_by_id = defaultdict(list) for m in machines: machines_by_id[m.id].ap…
has comment: http://stackoverflow.com/comment/90459802
accepted answer of: http://stackoverflow.com/q/51748908
has comment: http://stackoverflow.com/comment/90458367
has comment: http://stackoverflow.com/comment/90458981
has comment: http://stackoverflow.com/comment/90458659
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90459062

http://stackoverflow.com/comment/90312088
type: Comment
has text: Have you tried to encode them in `utf-8` directly instead ? (eg. `title.encode("utf-8")`)
comment on: http://stackoverflow.com/q/51674134
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90425043
comment on: http://stackoverflow.com/q/51731434
type: Comment
type: QuestionComment
has text: It works, but why i need use requests if I use "os" library for proxy?
score: 0

http://stackoverflow.com/a/51685296
has comment: http://stackoverflow.com/comment/90335864
has body: Here is a way to do it using datetime.strptime from datetime import datetime def IsNumber(s): try: int(s) return True except ValueError: return False def ConvertToDatetime(date): date=date.split(" ") #split by space if(IsNumber(date[0])): #is of the form dd month year if(len(date[1])==3): #if month is for form Jan,Feb... datetime_object = datetime.strptime(" ".join(date), '%d %b %Y') else: #if month is for form January ,February ... datetime_object = datetime.strptime(" ".join(date), '%d %B %Y') else: #is of the form month date year if(len(date[0])==3): #if month is for form Jan,Feb... datetime_object = datetime.strptime(" ".join(date), '%b %d %Y') else: #if month is for form January ,February ... datetime_object = datetime.strptime(" ".join(date), '%B %d %Y') return datetime_object You can add more cases based on the documentation and the format An example for the two in your question are : ConvertToDatetime("30 Jan 2018") 2018-01-30 00:00:00 ConvertToDatetime("January 30 2018") 2018-01-30 00:00:00
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51684954
upvote count: 1
answers question: http://stackoverflow.com/q/51684954

http://stackoverflow.com/comment/90476184
type: AnswerComment
score: 0
type: Comment
has text: @lonesome No, it appends to dictionaries whose values are lists. Your values are strings. That's exactly the difference the second section of my answer explains.
comment on: http://stackoverflow.com/a/51758424

http://stackoverflow.com/comment/90388172
type: Comment
comment on: http://stackoverflow.com/a/51702348
has text: Sorry, can't help with that. My solution was to abandon Windows entirely and it was one of the best decisions I've made.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51750046
has answer: http://stackoverflow.com/a/51750337
downvote count: 3
type: Question
upvote count: 0
answer count: 1
has body: I'm trying to print the output of a script. But for this I must use many prints. Is there any way to have all the topics without making all the prints? import pandas import mglearn import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation dataset = pandas.read_csv('text.csv', encoding = 'utf-8') comments = dataset['comments'] comments_list = remove_small_words.values.tolist() vector = CountVectorizer() X = vector.fit_transform(comments_list) lda = LatentDirichletAllocation(n_components = 30, learning_method = "batch", max_iter = 25, random_state = 0) document_topics = lda.fit_transform(X) sorting = np.argsort(lda.components_, axis = 1)[:, ::-1] feature_names = np.array(vector.get_feature_names()) topics = mglearn.tools.print_topics(topics = range(30), feature_names = feature_names, sorting = sorting, topics_per_chunk = 5, n_words = 10) print(topics) print("Topic 0:") docs = np.argsort(document_topics[:, 0])[::-1] for i in docs[:]: print(" ".join(comments_list[i].encode('utf-8').split(",")[:2]) + "\n") print() print() print("Topic 1:") docs = np.argsort(document_topics[:, 1])[::-1] for i in docs[:]: print(" ".join(comments_list[i].encode('utf-8').split(",")[:2]) + "\n") print() print() ... print("Topic 40:") docs = np.argsort(document_topics[:, 40])[::-1] for i in docs[:]: print(" ".join(comments_list[i].encode('utf-8').split(",")[:2]) + "\n") print() print() Instead of printing, for example, 40 times, could I just loop to print everything? To print these 40 topics, I need 240 lines of code. Imagine if I need to print 100... I have this output and I would like to keep it: Topic 0: blabla blabla Topic 1: blabla blabla Topic 3: blabla blabla ...
has comment: http://stackoverflow.com/comment/90460051
favorite count: 0
has comment: http://stackoverflow.com/comment/90460018
accepted answer: http://stackoverflow.com/a/51750337
has title: Replace many prints for just one loop
tagged with: python-3.x
score: -3
has comment: http://stackoverflow.com/comment/90460530
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51677662
has answer: http://stackoverflow.com/a/51678593
type: Question
score: 0
has title: Scrapy not able to go to next page
answer count: 1
has body: I am learning how to use Scrappy and am trying to make a crawler that scrapes website link and text from it. My crawler works for http://quotes.toscrape.com/ and http://books.toscrape.com/ but not for real life examples like https://pypi.org/project/wikipedia/ or Wikipedia. I am not able to understand what is causing this. Please help me MyCode import scrapy from scrapy.crawler import CrawlerRunner from scrapy.utils.project import get_project_settings from twisted.internet import reactor from scrapy.utils.log import configure_logging class firstSpider(scrapy.Spider): name = "htmlcrawler" start_urls = [ 'https://pypi.org/project/wikipedia/', ] def parse(self, response): val1=response.css("p.text::text").extract_first() val2=response.css("span.text::text").extract_first() val3=response.css("pre.text::text").extract_first() text = str("" if val3 is None else val3) + str("" if val2 is None else val2)+str("" if val1 is None else val1) NEXT_PAGE_SELECTOR = '.next a ::attr(href)' next_page = response.css(NEXT_PAGE_SELECTOR).extract_first() print(next_page) if next_page: next_page = response.urljoin(next_page) yield{'html':next_page,'text':text} yield scrapy.Request(next_page, callback=self.parse) def run(): settings = get_project_settings() settings.set('FEED_FORMAT', 'json') settings.set('FEED_URI', 'result.json') settings.set('Depth_Limit',60) settings.set('DOWNLOAD_DELAY',2) settings.set('DUPEFILTER_CLASS','scrapy.dupefilters.BaseDupeFilter') configure_logging() runner = CrawlerRunner(settings) runner.crawl(firstSpider) d = runner.join() d.addBoth(lambda _: reactor.stop()) reactor.run() if __name__=="__main__": run() I am running scrappy from Atom Hydrogen. Edit I changed the dupe filter class and tried to make some changes to my link gatherer from https://blog.siliconstraits.vn/building-web-crawler-scrapy/ but it still isnt working .
tagged with: python
accepted answer: http://stackoverflow.com/a/51678593
type: AnsweredQuestion
tagged with: web-scraping
tagged with: scrapy

http://stackoverflow.com/comment/90383921
type: QuestionComment
comment on: http://stackoverflow.com/q/51710907
score: 0
has text: Cleaner or recommended way.
type: Comment

http://stackoverflow.com/q/51783527
has title: How do i print ETA in tensorflow as I do in Keras with verbose
answer count: 0
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90527952
has comment: http://stackoverflow.com/comment/90525998
upvote count: 1
has comment: http://stackoverflow.com/comment/90527837
tagged with: keras
favorite count: 0
has body: I need to have the the estimated time it will take to train my model in Tensorflow with each epoch . In keras when i predict the classes with verbose , I get something like this : Epoch 1/70 17800/34960 [==============&gt;...............] - ETA: 22s - loss: 7.3802 - acc: 0.0631 34960/34960 [==============================] - 44s 1ms/step - loss: 7.1693 - acc: 0.0641 Epoch 2/70 34960/34960 [==============================] - 42s 1ms/step - loss: 6.7803 - acc: 0.0646 Epoch 3/70 34960/34960 [==============================] - 43s 1ms/step - loss: 6.6338 - acc: 0.0678 Epoch 4/70 5200/34960 [===&gt;..........................] - ETA: 36s - loss: 6.3998 - acc: 0.0737 34960/34960 [==============================] - 43s 1ms/step - loss: 6.4653 - acc: 0.0753 Epoch 5/70 34960/34960 [==============================] - 43s How can I get same type of info in Tensorflow only . When i print (tf.logging.set_verbosity(tf.logging.INFO), it gives 'None'
type: UnansweredQuestion
tagged with: epoch
tagged with: python

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/51763381

http://stackoverflow.com/comment/90466432
score: 0
comment on: http://stackoverflow.com/q/51753067
type: Comment
type: QuestionComment
has text: @anubhava Surely *"Does python have an equivalent of \Q and \E"* is a different question than *"How do I escape a regex in python"*?

http://stackoverflow.com/comment/90424946
type: Comment
type: QuestionComment
score: 1
has text: https://regex101.com/ helps me often
comment on: http://stackoverflow.com/q/51731946

http://stackoverflow.com/a/51726377
answers question: http://stackoverflow.com/q/51725921
type: Answer
has body: Tried a simple way to do it. Maintain two flags for even and odd. If you find an even, increment the even flag and reset the odd flag, and vice versa. As soon as one flag's value becomes 3, you know you have found three in succession. evenodd = [] while True: try: n = int(input()) evenodd.append(n) except: break evenflag = 0 oddflag = 0 print(evenodd) for number in evenodd: if number % 2 == 0: evenflag += 1 oddflag = 0 else: oddflag += 1 evenflag = 0 if evenflag == 3: print("Found 3 consecutive even numbers") break elif oddflag == 3: print ("Found three consecutive odd numbers") break
score: 0

http://stackoverflow.com/comment/90552848
type: Comment
comment on: http://stackoverflow.com/q/51797957
type: QuestionComment
has text: In spyder, there may be a residual `read` variable already defined from previous runs @Aran-Fey - The OP should restart the kernel and run the program with a clean kernel.
score: 0

http://stackoverflow.com/a/51782949
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51782243
answers question: http://stackoverflow.com/q/51782243
downvote count: 0
score: 1
has body: You can decode your bytes using the unicode_escape encoding, then convert the resulting string back to bytes by encoding it with latin1, which is a one to one encoding between bytes and characters: b'abc\\xe5\\xe6'.decode('unicode_escape').encode('latin1') # b'abc\xe5\xe6' And in the opposite direction: b'abc\xe5\xe6'.decode('latin-1').encode('unicode_escape') # b'abc\\xe5\\xe6'
upvote count: 1

http://stackoverflow.com/comment/104493479
type: Comment
comment on: http://stackoverflow.com/a/51719987
score: 0
type: AnswerComment
has text: You can just remove the environment directory.

http://stackoverflow.com/q/51791342
answer count: 1
favorite count: 0
upvote count: 5
has title: What does cv2.resize() do if input width and height same as resize input and width?
tagged with: python
accepted answer: http://stackoverflow.com/a/51791513
tagged with: opencv
type: AnsweredQuestion
downvote count: 0
has body: I like fast, compact code so I have a question about this: def loader(input_path, new_img_width, new_img_height): input_image = tifffile.imread(input_path) input_image = cv2.resize(input_image, (new_img_width, new_img_height), interpolation=cv2.INTER_NEAREST) return input_image Do I need to add a conditional statement before the call to cv2.resize for the case where new_img_width and new_img_height are the same as in input_image or this conditional statement already in the cv2.resize code? I don't want spend cycles resizing the image unless it's necessary.
has answer: http://stackoverflow.com/a/51791513
type: Question
score: 5

http://stackoverflow.com/comment/90446652
type: QuestionComment
has text: @Vikas Damodar I have added sample o/p so can you guide me please. Thankyou
score: 0
comment on: http://stackoverflow.com/q/51742698
type: Comment

http://stackoverflow.com/comment/90384788
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51706279
has text: Yes, I understand that map and filter - are the best here. But I do not want to significally change this piece of code.
score: 0

http://stackoverflow.com/q/51734955
has comment: http://stackoverflow.com/comment/90470333
upvote count: 2
tagged with: python-2.7
has title: Keras metrics with TF backend vs tensorflow metrics
answer count: 1
tagged with: keras
has body: When Keras 2.x removed certain metrics, the changelog said it did so because they were "Batch-based" and therefore not always accurate. What is meant by this? Do the corresponding metrics included in tensorflow suffer from the same drawbacks? For example: precision and recall metrics.
favorite count: 0
tagged with: python
tagged with: keras-2
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90463704
downvote count: 0
accepted answer: http://stackoverflow.com/a/51772402
has comment: http://stackoverflow.com/comment/106004228
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51772402

arrays
tags question: http://stackoverflow.com/q/51677995
tags question: http://stackoverflow.com/q/51690616
tags question: http://stackoverflow.com/q/51750872
tags question: http://stackoverflow.com/q/51694663
tags question: http://stackoverflow.com/q/51641518
tags question: http://stackoverflow.com/q/51770481
tags question: http://stackoverflow.com/q/51685584
tags question: http://stackoverflow.com/q/51671530
tags question: http://stackoverflow.com/q/51708532
tags question: http://stackoverflow.com/q/51766851
tags question: http://stackoverflow.com/q/51659369
type: Tag
tags question: http://stackoverflow.com/q/51689724
tags question: http://stackoverflow.com/q/51744613
tags question: http://stackoverflow.com/q/51750855
tags question: http://stackoverflow.com/q/51679898
tags question: http://stackoverflow.com/q/51730643
tags question: http://stackoverflow.com/q/51745678
tags question: http://stackoverflow.com/q/51659370
tags question: http://stackoverflow.com/q/51693022
tags question: http://stackoverflow.com/q/51699220
tags question: http://stackoverflow.com/q/51664659
tags question: http://stackoverflow.com/q/51699015
tags question: http://stackoverflow.com/q/51785824
tags question: http://stackoverflow.com/q/51739531
tags question: http://stackoverflow.com/q/51738331
tags question: http://stackoverflow.com/q/51794364
tags question: http://stackoverflow.com/q/51748939
tags question: http://stackoverflow.com/q/51756544
tags question: http://stackoverflow.com/q/51668189
tags question: http://stackoverflow.com/q/51701334
tags question: http://stackoverflow.com/q/51756897
tags question: http://stackoverflow.com/q/51717236
tags question: http://stackoverflow.com/q/51769198
tags question: http://stackoverflow.com/q/51791736
tags question: http://stackoverflow.com/q/51665905
tags question: http://stackoverflow.com/q/51776983
tags question: http://stackoverflow.com/q/51736293
tags question: http://stackoverflow.com/q/51705067
tags question: http://stackoverflow.com/q/51649186
tags question: http://stackoverflow.com/q/51676464
tags question: http://stackoverflow.com/q/51662181
tags question: http://stackoverflow.com/q/51669476
tags question: http://stackoverflow.com/q/51761345
tags question: http://stackoverflow.com/q/51697631
tags question: http://stackoverflow.com/q/51702229
tags question: http://stackoverflow.com/q/51642321
tags question: http://stackoverflow.com/q/51737245
tags question: http://stackoverflow.com/q/51698130
tags question: http://stackoverflow.com/q/51711607
tags question: http://stackoverflow.com/q/51694496
tags question: http://stackoverflow.com/q/51767723
tags question: http://stackoverflow.com/q/51676842
tags question: http://stackoverflow.com/q/51786133
tag name: arrays
tags question: http://stackoverflow.com/q/51733255
tags question: http://stackoverflow.com/q/51785988
tags question: http://stackoverflow.com/q/51716954
tags question: http://stackoverflow.com/q/51731815
tags question: http://stackoverflow.com/q/51772307
tags question: http://stackoverflow.com/q/51684239
tags question: http://stackoverflow.com/q/51766102
tags question: http://stackoverflow.com/q/51733677
tags question: http://stackoverflow.com/q/51778202
tags question: http://stackoverflow.com/q/51757867
tags question: http://stackoverflow.com/q/51710234
tags question: http://stackoverflow.com/q/51699558
tags question: http://stackoverflow.com/q/51698805
tags question: http://stackoverflow.com/q/51776572
tags question: http://stackoverflow.com/q/51694376
tags question: http://stackoverflow.com/q/51782885
tags question: http://stackoverflow.com/q/51643654
tags question: http://stackoverflow.com/q/51660247
tags question: http://stackoverflow.com/q/51690051
tags question: http://stackoverflow.com/q/51678219
tags question: http://stackoverflow.com/q/51676365
tags question: http://stackoverflow.com/q/51653193
tags question: http://stackoverflow.com/q/51729465
tags question: http://stackoverflow.com/q/51729217
tags question: http://stackoverflow.com/q/51679569

http://stackoverflow.com/q/51770458
type: Question
has body: I have around 300 log files in a directory and each log file contains around 3300000 lines. I need to read through each file line by line and count how many hostnames that appear on each line.I wrote basic code for that task. but it takes more than 1 hour to run and takes lots of memory as well. how can improve this code to make it run faster? import pandas as pd import gzip directory=os.fsdecode("/home/scratch/mdsadmin/publisher_report/2018-07-25")#folder with 300 log files listi=os.listdir(directory)#converting the logfiles into a list for file in listi:#taking eaching log file in the list tt=os.path.join(directory,file)# joining log file name along with the directory path with gzip.open(tt,'rt') as f: #unzipping the log file rows=[]#clearing the list after every loop for line in f: #reading each line in the file s=len(line.split('|')) a=line.split('|')[s-3] b=a.split('/')[0] #slicing just the hostname out of each line in the log file if len(b.split('.'))==None: '' else: b=b.split('.')[0] rows.append(b) # appending it to a list df_temp= pd.DataFrame(columns=['hostname'],data=rows) #append list to the dataframe after every file is read df_final=df_final.append(df_temp,ignore_index=True) #appending above dataframe to a new one to avoid overwriting del df_temp #deleting temp dataframe to clear memory df_rows1=df_rows1.groupby(["serverMonitoringAppCode"]).size().reset_index(name="Topic_Count") #doing the count Sample log lines tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokpa22**.sx.sx.com/16604/#001b0001|244/5664|2344|455 tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokdd333**.sc.sc.com/16604/#001b0001|7632663/2344|342344|23244 Desired output
has comment: http://stackoverflow.com/comment/90499983
has comment: http://stackoverflow.com/comment/90501637
tagged with: dataframe
score: 0
has title: Reading set of large log files line by line and count how many hostnames appear on each line
type: UnansweredQuestion
tagged with: python
tagged with: large-files
answer count: 0

http://stackoverflow.com/comment/92718027
has text: See also the related [GitHub issue](https://github.com/ray-project/ray/issues/2554)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52903322
score: 0

http://stackoverflow.com/comment/90373262
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51706263
type: AnswerComment
has text: So, do exactly what the other two answers say, but with one more loop over all items..?

http://stackoverflow.com/a/51787985
upvote count: 5
has comment: http://stackoverflow.com/comment/90599058
type: Answer
has comment: http://stackoverflow.com/comment/90638103
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51787219
answers question: http://stackoverflow.com/q/51787219
score: 5
has body: QTableWidget has a preset model that can not be replaced so using QSortFilterProxyModel would be impossible, so you should use QTableView, a possible solution to your main problem that is filtering is to use only QSqlQueryModel and make the filter using the LIKE command. from PyQt5 import QtWidgets, QtSql def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName("baza.db") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it.\n\n" "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel) return False return True class Widget(QtWidgets.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) lay = QtWidgets.QVBoxLayout(self) lineEdit = QtWidgets.QLineEdit() tableView = QtWidgets.QTableView() lay.addWidget(lineEdit) lay.addWidget(tableView) lineEdit.textChanged.connect(self.onTextChanged) self.model = QtSql.QSqlQueryModel() tableView.setModel(self.model) self.onTextChanged("") def onTextChanged(self, text): query = QtSql.QSqlQuery() query.prepare("SELECT * FROM Zaposleni WHERE Ime LIKE ?") query.addBindValue("{}%".format(text)) query.exec_() self.model.setQuery(query) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) if not createConnection(): sys.exit(-1) w = Widget() w.show() sys.exit(app.exec_()) In the previous example, we want the word to start with the text of the QLineEdit, if you want to find if it contains the word you must replace it with: query.addBindValue("%{}%".format(text)) If you still want to use QSortFilterProxyModel you can see the following example: from PyQt5 import QtCore, QtWidgets, QtSql def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName("baza.db") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to esta…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90638247

http://stackoverflow.com/comment/90291908
has text: What's the expected output for `'namespace P {a; b;}'`? `'a; b;'` seems correct to me as it is what's inside the curly brackets.
comment on: http://stackoverflow.com/q/51664240
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/90390209
type: QuestionComment
comment on: http://stackoverflow.com/q/51714080
type: Comment
has text: Adding to @kindall: The important part here is that this has nothing to do with `multiprocessing`; this wouldn't work if you just did `foo(x, 2)` with no `multiprocessing` involved at all.
score: 1

http://stackoverflow.com/q/51656958
tagged with: pandas
has comment: http://stackoverflow.com/comment/90278172
has title: ValueError: No Results DataFrame - Pandas
has comment: http://stackoverflow.com/comment/90277739
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90278093
answer count: 0
has comment: http://stackoverflow.com/comment/90278333
type: Question
has comment: http://stackoverflow.com/comment/90278430
has body: Here's my code. import os import pandas as pd file='Requirements Upload.xlsx' x1=pd.ExcelFile(file) df=x1.parse('Requirements Mapping') agg_df = (df.fillna('N/A').set_index(['Unique_ID', 'No_of_Filings']) .stack() .reset_index('No_of_Filings') .groupby(0) .agg(['sum', 'size']) .reset_index()) writer=pd.ExcelWriter("Requirements Output.xlsx",engine="xlsxwriter") agg_df.to_excel(writer,"Requirements Mapping Output") writer.save() Here's my data: Unique_ID No_of_Filings Req_1 Req_2 Req_3 Req_4 RCONF045 3 Blue Yellow RCONF046 3 Blue Yellow RCONF047 3 Blue Yellow RCONF048 3 Green Brown RCONF051 3 Green Purple Orange Black RCONF052 3 Green Purple Orange Blue When I run the code, my error is "ValueError: no results", but I can't understand why. Are the blank cells causing a problem? EDIT: I have added "NA" to all my blank cells, but I still receive the same error. SECOND EDIT: My source document was pulling these fields using a formula. I blew out the formula to upload into Python, but when I had my dataframe printed, it carried forward those empty fields (even though there was no formula in my upload file). I deleted those rows and now it works! Unique_ID No_of_Filings Req_1 Req_2 Req_3 Req_4 0 RCONF045 3.0 Blue Yellow NaN NaN 1 RCONF046 3.0 Blue Yellow NaN NaN 2 RCONF047 3.0 Blue Yellow NaN NaN 3 RCONF048 3.0 Green Brown NaN NaN 4 RCONF051 3.0 Green Purple Orange Black 5 RCONF052 3.0 Green Purple Orange Blue 6 NaN NaN NaN NaN NaN NaN 7 NaN NaN NaN NaN NaN NaN 8 NaN NaN NaN NaN NaN NaN 9 NaN NaN NaN NaN NaN NaN 10 NaN NaN NaN NaN NaN NaN Thanks!
has comment: http://stackoverflow.com/comment/90277755
score: 0

http://stackoverflow.com/comment/90288611
has text: @DYZ I have edited my question to show what I have done, that method and it is giving me that error.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51659737
score: 0

http://stackoverflow.com/a/51716940
answers question: http://stackoverflow.com/q/51716916
upvote count: 20
has body: Try this instead: def lcm(x, y): from fractions import gcd # or can import gcd from `math` in Python 3 return x * y // gcd(x, y)
has comment: http://stackoverflow.com/comment/113822250
type: Answer
has comment: http://stackoverflow.com/comment/105366031
downvote count: 3
has comment: http://stackoverflow.com/comment/114708755
has comment: http://stackoverflow.com/comment/105302562
score: 17
has comment: http://stackoverflow.com/comment/105302887

http://stackoverflow.com/comment/90494773
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51767999
has text: Yes, I realise that it works with `iloc` but I want to understand why does it not work without it. I should be able to select from a series without `iloc`, correct?

http://stackoverflow.com/a/51778012
answers question: http://stackoverflow.com/q/51777914
type: Answer
has body: This should work: import pandas as pd import numpy as np columns = ["vehicle", 'timestamp', 'mode'] rows = [["x","1970-01-19 01:24:59.973", 0], ["x","1970-01-19 01:25:59.973", 2], ["x","1970-01-19 01:26:59.973", 2], ["x","1970-01-19 01:27:59.973", 0], ["x","1970-01-19 01:28:59.973", 2], ["x","1970-01-19 01:29:59.973", 0], ["x","1970-01-19 01:30:59.973", 0], ["x","1970-01-19 01:31:59.973", 2], ["x","1970-01-19 01:32:59.973", 0]] df = pd.DataFrame(rows, columns=columns) df['changes'] = [np.nan] + [1 if prev == 2 and cur == 0 else np.nan for prev, cur in zip(df['mode'], df['mode'][1:])] print(df) This outputs: vehicle timestamp mode changes 0 x 1970-01-19 01:24:59.973 0 NaN 1 x 1970-01-19 01:25:59.973 2 NaN 2 x 1970-01-19 01:26:59.973 2 NaN 3 x 1970-01-19 01:27:59.973 0 1.0 4 x 1970-01-19 01:28:59.973 2 NaN 5 x 1970-01-19 01:29:59.973 0 1.0 6 x 1970-01-19 01:30:59.973 0 NaN 7 x 1970-01-19 01:31:59.973 2 NaN 8 x 1970-01-19 01:32:59.973 0 1.0 as desired
score: 0

http://stackoverflow.com/comment/90541148
comment on: http://stackoverflow.com/a/51778270
type: AnswerComment
score: 0
type: Comment
has text: also in the project directory there is the file db.sqlite3, and in settings this is the setup DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I dont think I did any other changes to setup to the database

http://stackoverflow.com/comment/90375013
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51706815
has text: @ng.newbie checkout my updated answer, python will simply run the code if you define a decorator

http://stackoverflow.com/a/51737249
answers question: http://stackoverflow.com/q/51737078
downvote count: 0
has comment: http://stackoverflow.com/comment/90435330
score: 24
has comment: http://stackoverflow.com/comment/90435178
has comment: http://stackoverflow.com/comment/90435157
has body: Parameters that can be either a thing or an iterable or things are a code smell. It’s even worse when the thing is a string, because a string is an iterable, and even a sequence (so your test for isinstance(names, Iterable) would do the wrong thing). The Python stdlib does have a few such cases—most infamously, str.__mod__—but most of those err in the other direction, explicitly requiring a tuple rather than any iterable, and most of them are considered to be mistakes, or at least things that wouldn’t be added to the language today. Sometimes it is still the best answer, but the smell should make you think before doing it. I don’t know exactly what your use case is, but I suspect this will be a lot nicer: def spam(*names): namestr = ','.join(names) dostuff(namestr) Now the user can call it like this: spam('eggs') spam('eggs', 'cheese', 'beans') Or, if they happen to have a list, it’s still easy: spam(*ingredients) If that’s not appropriate, another option is keywords, maybe even keyword-only params: def spam(*, name=None, names=None): if name and names: raise TypeError('Not both!') if not names: names = [name] But if the best design really is a string or a (non-string) iterable of strings, or a string or a tuple of strings, the standard way to do that is type switching. It may look a bit ugly, but it calls attention to the fact that you’re doing exactly what you’re doing, and it does it in the most idiomatic way. def spam(names): if isinstance(names, str): names = [names] dostuff(names)
type: AcceptedAnswer
upvote count: 24
accepted answer of: http://stackoverflow.com/q/51737078
type: Answer
has comment: http://stackoverflow.com/comment/90435312

http://stackoverflow.com/a/57329830
type: Answer
has body: You would need to write your own import class that can use in memory data (tar or zipfile for eg). See https://docs.python.org/3/library/importlib.html
answers question: http://stackoverflow.com/q/51689699
score: 0

http://stackoverflow.com/comment/90379563
score: 0
type: AnswerComment
has text: TypeError: object of type 'ElementTree' has no len()
comment on: http://stackoverflow.com/a/51707553
type: Comment

http://stackoverflow.com/a/51688606
type: Answer
has comment: http://stackoverflow.com/comment/90339156
answers question: http://stackoverflow.com/q/51688453
has body: Just a list comprehension, iterating over both the lists x1 and x2 is enough &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; res = [(a,b) for a in x1 for b in x2] &gt;&gt;&gt; pprint(res) [(1, 'string0'), (1, 'string1'), (1, 'string3'), (10, 'string0'), (10, 'string1'), (10, 'string3'), (20, 'string0'), (20, 'string1'), (20, 'string3'), (23, 'string0'), (23, 'string1'), (23, 'string3'), (12, 'string0'), (12, 'string1'), (12, 'string3')]
score: 0

http://stackoverflow.com/q/51709267
tagged with: webdriver
type: Question
accepted answer: http://stackoverflow.com/a/51757851
has body: I’m trying to add a few methods to WebElements that I use frequently. I figured out how to make it work, but now my assert statements fail. Here is what I have. How do I get my assert to work? def is_below(self, above_element): below = self.location['y'] above = above_element.location['y'] self.assertLess(above, below) WebElement.is_below = WebElement_is_below In reality, this is all the logic I am trying to figure out: class ModifiedTestCase(TestCase): def is_below(self, above_element): below = self.location['y'] above = above_element.location['y'] self.assertLess(above, below) WebElement.is_below = WebElement_is_below class SeleniumTest(ModifiedTestCase): def test_web_page(self): above_element = self.find_element() below_element = self.find_element() below_element.is_below(above_element) The error I get is “WebElement has no attribute assertIn”. I know I can pass it a driver argument, but that defeats some of the simplicity.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Python Selenium Webdriver add method to Webelements/ custom 'assert' statement
tagged with: python
has answer: http://stackoverflow.com/a/51757851
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
tagged with: selenium
upvote count: 1

http://stackoverflow.com/q/51707002
score: 0
has body: Let say I have a 3D tensor representing several 2D matrices: 3D_tensor = tf.random_uniform([N0, N1, N2], 1, -1)) I want to stack vertically these 2D matrices such that the resulting 2D tensor would be of dimensions [N0+N1, N2]. WHat is the best way to do that ? The numpy process would be the following one: 3D = np.array([ [[1,2],[3,4]] , [[1,2],[3,4]] ]) # 3D.shape = (2,2,2) 2D = np.vstack(3D) # D2.shape = (4,2)
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51707152
tagged with: python
type: AnsweredQuestion
upvote count: 1
has title: Tensorflow: best way to vertically stack matrices?
downvote count: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51707152

http://stackoverflow.com/comment/90325645
has text: You have to close the file after you finished writing into it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51681164

http://stackoverflow.com/comment/90430682
has text: of a simple keras model? Otherwise I dont know what code you are looking for, I wanted a differentiable rouding-like function, I dont know what code you are looking for
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51733311
score: 0

http://stackoverflow.com/q/51704940
has body: What would you say the time-complexity of the foo function is (relative to n)? DIGIT_FACTORIAL = [1] for x in range(1, 10): DIGIT_FACTORIAL.append(DIGIT_FACTORIAL[x-1]*x) def digit_factorial(x): return DIGIT_FACTORIAL[x] def foo(number_of_digits): n = 10**number_of_digits i = n//9 while i != sum(digit_factorial(int(x)) for x in str(i)) and i &lt; n: i += 1 if i &lt; n: return i return None
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51710653
has comment: http://stackoverflow.com/comment/90387883
has comment: http://stackoverflow.com/comment/90392808
tagged with: asymptotic-complexity
accepted answer: http://stackoverflow.com/a/51710653
type: AnsweredQuestion
tagged with: time-complexity
has title: Factorial digits sum puzzle, time complexity survey
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90384277
tagged with: python

http://stackoverflow.com/comment/90515693
comment on: http://stackoverflow.com/a/51778507
has text: that's why I am very confused
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51678855
downvote count: 0
answers question: http://stackoverflow.com/q/51678520
type: Answer
has body: Seems like you may be running it from the IDE without giving any command line arguments. I see you are using pycharm, so check this post about passing in command line arguments to pycharm runs: Pycharm and sys.argv arguments
upvote count: 1
score: 1

http://stackoverflow.com/q/51692253
score: 2
upvote count: 2
tagged with: tensorflow
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/57957877
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90346397
answer count: 2
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/90346316
favorite count: 0
has title: TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'
linked to: http://stackoverflow.com/q/40666316
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90346341
has answer: http://stackoverflow.com/a/57956654
tagged with: python
has body: Hope you guys are in good health. Respected members I am working on Cifar10 dataset and getting TypeError: unsupported operand type(s) for /: 'Dimension' and 'int' I use same algorithm for mnist dataset(GreyScale) but their is no error. But now I am using same algorithm of tensorflow for training on Cifar10(rgb). Is this error occurs because of (rgb) dataset?I am sharing my code please have a look Thank you Code layer1_neuron=500 layer2_neuron=500 layer3_neuron=500 number_of_class=10 batch_size=200 #my neural network def neural_network(x_train): hidden_layer_1={ 'weights':tf.Variable(tf.random_normal([3072,layer1_neuron])), 'biases': tf.Variable(tf.random_normal([layer1_neuron])) } hidden_layer_2={ 'weights':tf.Variable(tf.random_normal([layer1_neuron,layer2_neuron])), 'biases':tf.Variable(tf.random_normal([layer2_neuron])) } hidden_layer_3={ 'weights':tf.Variable(tf.random_normal([layer2_neuron,layer3_neuron])), 'biases':tf.Variable(tf.random_normal([layer3_neuron])) } output={ 'weights':tf.Variable(tf.random_normal([layer3_neuron,number_of_class])), 'biases':tf.Variable(tf.random_normal([number_of_class])) } l1=tf.add(tf.matmul(x_train,hidden_layer_1['weights']),hidden_layer_1['biases']) l1=tf.nn.relu(l1) l2=tf.add(tf.matmul(l1,hidden_layer_2['weights']),hidden_layer_2['biases']) l2=tf.nn.relu(l2) l3=tf.add(tf.matmul(l2,hidden_layer_3['weights']),hidden_layer_3['biases']) l3=tf.nn.relu(l3) output=tf.add(tf.matmul(l3,output['weights']),output['biases']) return output # for splitting out batches of data class Dataset: def __init__(self,data): self._index_in_epoch = 0 self._epochs_completed = 0 self._data = data self._num_examples = data.shape[0] pass @property def data(self): return self._data def next_batch(self,batch_size,shuffle = True): start = self._index_in_epoch if start == 0 and self._epochs_completed == 0: idx = np.arange(0, self._num_examples) # get all possible indexes np.random.shuffle(idx) # shuffle indexe self._data = self.data[idx] # get list of `num`…

http://stackoverflow.com/q/51735140
has answer: http://stackoverflow.com/a/55168927
upvote count: 4
has answer: http://stackoverflow.com/a/72565805
downvote count: 0
linked to: http://stackoverflow.com/q/5909012
has comment: http://stackoverflow.com/comment/90448955
has comment: http://stackoverflow.com/comment/90451444
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/94459620
score: 4
has comment: http://stackoverflow.com/comment/90439803
has body: I created a simple batch file to activate an Environment and then run spyder. @echo off call activate env spyder.exe exit Now the problem is that the CMD remains open after the execution and it's attached to spyder meaning that if I close it Spyder exits as well with the following message. forrtl: error (200): program aborting due to window-CLOSE event Image PC Routine Line Source libifcoremd.dll 00007FF8D20694C4 Unknown Unknown Unknown KERNELBASE.dll 00007FF917927EDD Unknown Unknown Unknown KERNEL32.DLL 00007FF918D91FE4 Unknown Unknown Unknown ntdll.dll 00007FF91ACECB31 Unknown Unknown Unknown QObject::~QObject: Timers cannot be stopped from another thread I actually tried the following code as well, after suggestions from here and other similar posts. The only difference now is that cmd closes but another window stays open in its place. The icon of the new window is not the cmd icon. @echo off call activate env start spyder.exe exit Furthermore, I tried cmd "/c activate env &amp;&amp; start spyder" which has the same result as the first batch cmd "/c activate env &amp;&amp; spyder &amp;&amp; exit" which exits before it does anything and cmd "/c activate env &amp;&amp; start spyder &amp;&amp; exit" which has the same result as the second batch Does anyone have a solution to that? Thanks
tagged with: batch-file
answer count: 2
has comment: http://stackoverflow.com/comment/90431181
favorite count: 0
has title: batch file to activate env and run spyder. CMD remains open
has comment: http://stackoverflow.com/comment/90433639
type: UnansweredQuestion
tagged with: spyder
tagged with: python

http://stackoverflow.com/q/51757922
has answer: http://stackoverflow.com/a/51757952
answer count: 1
tagged with: django-manage.py
score: 0
has body: I am trying to run a one time management command to pre-populate a db. Here is the model: class ZipCode(models.Model): zip_code = models.CharField(max_length=7) latitude = models.DecimalField(decimal_places=6, max_digits =12) longitude = models.DecimalField(decimal_places=6, max_digits =12) and here is the management command: from django.core.management.base import BaseCommand from core.models import ZipCode class Command(BaseCommand): def populate_db(self): zip_code_object = ZipCode(zip_code='10566', latitude = 10.2, longitude= 43.4) #test data to see if I could get it working ZipCode.save(self) def handle(self, *args, **options): self.populate_db() But when I run python3.6 manage.py populate_zip_code_db it returns File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save for field in self._meta.concrete_fields: AttributeError: 'Command' object has no attribute '_meta' Does anyone know how to get this working? I just discovered management commands so I am clueless.
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51757952
has title: Command object has no attribute meta, Django management commands
type: Question
tagged with: django-managers
tagged with: django-management-command

http://stackoverflow.com/comment/90446471
type: Comment
type: QuestionComment
score: 2
has text: https://stackoverflow.com/questions/9427163/remove-duplicate-dict-in-list-in-python
comment on: http://stackoverflow.com/q/51743175

http://stackoverflow.com/q/51769472
has answer: http://stackoverflow.com/a/51769622
favorite count: 0
has comment: http://stackoverflow.com/comment/90498092
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51769580
tagged with: python
has title: Simultaneously fill missing values in related columns in pandas dataframe
linked to: http://stackoverflow.com/q/51754475
score: 2
upvote count: 2
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51769654
tagged with: dataframe
has answer: http://stackoverflow.com/a/51769580
answer count: 3
tagged with: pandas
has body: I have a dataframe with two columns State and Code, with missing values in each. import pandas as pd df = pd.DataFrame([['Alabama', 'AL'], ['Alaska', 'AK'], ['Arizona', 'AZ'], ['Arkansas', 'AR'], ['Iowa','IA'],['Hawaii','HI'], ['Idaho', 'ID'], ['Alabama', ''], ['', 'IA'], ['Alaska',''], ['', 'AZ']], columns=['State', 'Code']) Missing values State Code 7 Alabama 8 IA 9 Alaska 10 AZ What I've tried state_code_dict = { 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'Iowa':'IA', 'Hawaii':'HI', 'Idaho': 'ID', } def state_code(x): if (x['Code'] == ''): return state_code_dict[x['State']] else: return x['Code'] df['Code'] = df.apply(lambda x: state_code(x), axis=1) This sets the missing values in Code. I need to update this function for setting State as well. I'm looking to simplify this. Required output State Code 7 Alabama AL 8 Iowa IA 9 Alaska AK 10 Arizona AZ
possible better answer: http://stackoverflow.com/a/51769622
downvote count: 0

http://stackoverflow.com/comment/90255598
comment on: http://stackoverflow.com/q/51645694
score: 0
type: Comment
type: QuestionComment
has text: Maybe you meant 'perfectly round'?

http://stackoverflow.com/comment/90484198
type: AnswerComment
score: 0
type: Comment
has text: @Chubaka yes, triple quotes is the Python syntax for multiline strings: https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string/10660443#10660443
comment on: http://stackoverflow.com/a/51743039

http://stackoverflow.com/comment/90477749
type: Comment
comment on: http://stackoverflow.com/q/51759222
has text: are you trying to mutate `str` inside of `newpic`?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90464622
type: AnswerComment
has text: The example with verbosity was just to demonstrate how you can bind the log level to command line argument; I didn't want to introduce a new argument just for that.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51745839

http://stackoverflow.com/comment/90476522
has text: Thanks for opening me up to this service. I took a look briefly and it seemed overkill for what I"m trying to do. This led me to looking into "Alerts" and "Action Group", which does exactly what I need. I set up an Alert for VM startup/shutdown and attach it to a webhook which POST to a URL. Very neat.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51756600
type: Comment

http://stackoverflow.com/comment/90406747
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51710776
score: 1
has text: Wow, thanks you! So much effort put into your answer, I'm glad that there's people like you out there! Not only is your code working perfectly, but also do I think I just got a little better programmer by understanding it :))

http://stackoverflow.com/comment/90295464
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51666099
has text: ok, so are they all connected?? I mean those 3 grey boxes are related? um.. I have an error 'KeyError: 'Date'

http://stackoverflow.com/comment/90357661
type: Comment
has text: Indeed. I'm not sure if this is required by pylint though.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51698110

http://stackoverflow.com/q/51705179
has comment: http://stackoverflow.com/comment/90371879
answer count: 1
has title: ValueError in tensorflow,,,
has comment: http://stackoverflow.com/comment/90372012
favorite count: 0
has body: Value Error: Cannot feed value of shape (7800, 28, 28, 1) for Tensor 'Placeholder:0', which has shape '(1, 28, 28, ?)' My Placeholder is looks like this: x1_image = tf.placeholder(tf.float32, [1, Size, Size, None]) How do I convert (7800, 28, 28, 1) into (1, 28, 28, 7800) in tensor flow ?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51705674
score: 0
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90372642

http://stackoverflow.com/comment/90317147
has text: The encoding of your file must be different from mine. Try opening the CSVs with 'rt' and 'wt' to not use bytes
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51676313
type: Comment

http://stackoverflow.com/comment/90419212
score: 0
has text: @Jean-FrançoisFabre, Agreed, I don't know where to find the dup :(.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51729217

http://stackoverflow.com/comment/90523750
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/51783225
has text: Please can you edit your post with your raw data, code to recreate your df, the desired output, any errors, and your code. Links to images are counter-productive on SO
type: Comment

http://stackoverflow.com/q/51678981
tagged with: python
has comment: http://stackoverflow.com/comment/90321446
answer count: 0
duplicate of: http://stackoverflow.com/q/45227604
score: 1
upvote count: 1
type: Question
tagged with: ggplot2
has comment: http://stackoverflow.com/comment/90321468
has title: ggplot to R - dataframe R
has comment: http://stackoverflow.com/comment/90321838
linked to: http://stackoverflow.com/q/45227604
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90321574
has comment: http://stackoverflow.com/comment/90321976
has body: We are trying to convert our application that builds on shiny to Django . We have our custom library for analytics written in R and we have integrated it in our Django using rpy2 library. Now this is the situation, Our library returns ggplot2 instance for plotting graphs. We can't change that library and have to use it for analytics purpose. So what we want is to convert that ggplot2 instance into R - data frame so then we can convert it in Json and sent to our front end to plot graphs. So is there a way to do this . Is it somehow possible to convert ggplot2 instance to data frame in R ?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90321490
has comment: http://stackoverflow.com/comment/90321553
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90321811
tagged with: django

http://stackoverflow.com/comment/90370798
score: 1
comment on: http://stackoverflow.com/q/51704898
has text: The `or` is correct. Within a lambda expression, you have to write plain python code. Note also that if NB_line and NB2_line are different, your condition will always be true.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90462097
has text: How do you use MSS via RDP? Could you post a screenshot to have an idea of the result?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51749574

http://stackoverflow.com/a/51679669
upvote count: 1
answers question: http://stackoverflow.com/q/51679569
type: AcceptedAnswer
downvote count: 0
has body: If I understood the question correctly you can just use set and any: any(set(lst2) &lt;= set(x) for x in lst1) where set(lst2) &lt;= set(x) checks if lst2 is sublist of x.
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51679569

http://stackoverflow.com/comment/90476292
type: Comment
type: QuestionComment
has text: Now I don't get that error. It shows me the code now. You can see the code I put in the question. Can you please tell me what else you need.
comment on: http://stackoverflow.com/q/51755652
score: 0

http://stackoverflow.com/a/51740406
type: Answer
score: 0
has body: You can use re.findall to find all the matches of a pattern. As for optionally matching a second word in your second sample input, you can put the word in a group with a ? to make it optional: import re for s in "Mandzukic 18' (o.g.) Griezmann 38' (pen.) Pogba 59' Mbappe 65'; Perisic 28' Mandzukic 69", "Samuel Umtiti 51'": print(re.findall(r'(?:\w+\s+)?\w+\s+\d+', s)) This outputs: ['Mandzukic 18', 'Griezmann 38', 'Pogba 59', 'Mbappe 65', 'Perisic 28', 'Mandzukic 69'] ['Samuel Umtiti 51']
answers question: http://stackoverflow.com/q/51740218

dayofweek
type: Tag
tags question: http://stackoverflow.com/q/51732396
tag name: dayofweek

http://stackoverflow.com/a/51762078
downvote count: 0
type: Answer
has body: Printing repr(Exon(BioSequence('abcde', 10), 10)) is enough to explain the problem: it gives "'[BioSequence abcde (s: 10, e: 15)]'" As the __str__ special method has been overriden, the conversion of a BioSequence to a plain string gives this detailed description. As a consequence, the str subobject of Exon(Exon(BioSequence('abcde', 10), 10) is not 'abcde' but '[BioSequence abcde (s: 10, e: 15)]'. This explains why the last comparison fails. My advice is that you do not want to override __str__ is a subclass of str. You have two possible paths here: override __repr__ in your subclasses instead of __str__. It makes sense, because the str part of the subclasses shall be the simple string. When you want the detailed description, just use repr do not use inheritance but delegation. In this pattern, a BioSequence is not a str but only has a str member. This should give you a greater flexibility, but requires more boiler plate code.
score: 2
answers question: http://stackoverflow.com/q/51761227
upvote count: 2

http://stackoverflow.com/a/51646752
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90296750
score: 1
has comment: http://stackoverflow.com/comment/90302106
upvote count: 1
answers question: http://stackoverflow.com/q/51643831
has body: You could run the mibbuild.py --destination-format json tool over all your MIBs. You will get one JSON document for each of your MIB files. The JSON documents will look like this: "coldStart": { "name": "coldStart", "oid": "1.3.6.1.6.3.1.1.5.1", "class": "notificationtype", "status": "current" }, From here you can load JSON into Python, create a new dict like {json[key]['oid']: key for key in json} which you could use for looking up TRAP names by OID. If your collection of MIBs is changing and needs constant updates, you can build the above procedure into your application by calling pysmi functions. EDIT: If you need to resolve whatever TRAP OID into its MIB name, you can grab as many MIBs as you can find on the Internet and run the above procedure over them. However you still may not be able to resolve all TRAP OIDs you encounter in the wild. It is more typical to have MIBs for all the devices your software is managing. The default for the mibdump tool is to pull requested MIBs from http://mibs.snmplabs.com/asn1/ site.
has comment: http://stackoverflow.com/comment/90279644
has comment: http://stackoverflow.com/comment/90260755
accepted answer of: http://stackoverflow.com/q/51643831
has comment: http://stackoverflow.com/comment/90261010

http://stackoverflow.com/comment/90499063
comment on: http://stackoverflow.com/a/51765018
type: AnswerComment
score: 0
has text: Thank you, python future option also very interesting to know.
type: Comment

http://stackoverflow.com/q/51753750
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90471412
accepted answer: http://stackoverflow.com/a/51755975
has body: I'm starting to get to know Tkinter but i'm stuck at a point as i'm experimenting and practicing; i couldn't figure out how to move tkinter elements such as Frame or Labels from one tab to another in Tkinter Notebook. A resourceful link or an answer concerning my problem would be very helpful! P.S: It's my first time asking a question so apologies if i did something wrong.
has comment: http://stackoverflow.com/comment/90558508
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90467637
has comment: http://stackoverflow.com/comment/90558503
has comment: http://stackoverflow.com/comment/90558483
has answer: http://stackoverflow.com/a/51755975
type: Question
score: 0
answer count: 1
tagged with: tkinter-canvas
has comment: http://stackoverflow.com/comment/90469984
tagged with: python
has title: How to move labels from one tab to another in notebook tkinter?
tagged with: python-3.x

http://stackoverflow.com/q/51754592
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has body: I have a series looking like this: month_1 | month_2 | ... | month_X user_1 | label_1 | label_2 | ... | label_2 user_2 | label_2 | label_3 | ... | label_4 .... user_X | label_4 | label_1 | ... | label_55 I want to convert this into a table looking like this: month_1 | label_1 | count(label_1) month_1 | label_2 | count(label_2) ... month_x | label_x | count(label_x) where count(label_x) is number of occurrences of the label in the column. I tried various Pandas aggregation functions, but they all seem to need the column names to be specified explicitly, which is not something I can do given how many there are.
type: Question
has title: How to aggregate count of each unique value per column as a row indexed by column header?
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/90469008
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51755793
has comment: http://stackoverflow.com/comment/91041823

http://stackoverflow.com/comment/90506842
has text: Thanks and It's really helpful!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51738201

http://stackoverflow.com/a/51863456
type: Answer
upvote count: 2
score: 2
has body: So it looks like referencing the label with literal_column solves the issue. Bear in mind that this will only work with MySQL Query(Model.name, subQuery.label('total')) \ .filter(Model.country == some_country) \ -group_by(Model.skill) \ -having(literal_column('total') &gt; some_total)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51793704
answers question: http://stackoverflow.com/q/51793704

http://stackoverflow.com/comment/90270653
has text: With `state='disabled'`, the Text truly is disabled - programmatic changes are disallowed just as well as manual typing. You have to momentarily enable it before inserting your text, then disable it again.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/51653603
type: QuestionComment

http://stackoverflow.com/a/51664467
has body: It doesn't get stuck at self.transport.write("MESSAGE %s\n" % msg) it actually fails there. Transport.write only accepts bytes. Encode the string and it should work. class Greeter(Protocol): def sendMessage(self, msg): print('sending message') self.transport.write(("MESSAGE %s\n" % msg).encode('utf8')) print('message sent')
has comment: http://stackoverflow.com/comment/108752604
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51662414
accepted answer of: http://stackoverflow.com/q/51662414
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51757017
downvote count: 1
has body: https://pythonhosted.org/javabridge/installation.html#dependencies: The Javabridge requires Python 2.6 or above, NumPy, the Java Development Kit (JDK), and a C compiler. sudo apt install python2.7 python-numpy openjdk-8-jdk gcc
score: 0
has comment: http://stackoverflow.com/comment/90498653
type: Answer
answers question: http://stackoverflow.com/q/51756910
has comment: http://stackoverflow.com/comment/90473439
upvote count: 1

http://stackoverflow.com/a/51707268
downvote count: 0
has comment: http://stackoverflow.com/comment/90410776
has comment: http://stackoverflow.com/comment/90419282
answers question: http://stackoverflow.com/q/51707077
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90410090
upvote count: 2
has comment: http://stackoverflow.com/comment/90405448
has comment: http://stackoverflow.com/comment/90421594
has body: If you have to use python, one possible way (adapted slightly from this thread which has other good information) is to use a massive sleep statement. #!/usr/bin/python3 import time def hello(): print("Hello, World") while True: hello() time.sleep(3*24*60*60) Here is a more complete code snippet. I tested it for shorter intervals (not 3 days) but it should probably work import numpy as np import time import datetime def function_to_call_periodically(): print("Hello World") # specify the interval and the time (3 days and at 11h00) # The code below assumes the interval is more than a day desired_time_delta_in_seconds = 3*24*60*60 # 3 days desired_time_minutes = 00 desired_time_hours = 11 # set the starting time the code will run every 3 days from this date (at the specified time) start_date = datetime.datetime(2018, 8, 7) # year, month date (hours, minutes, seconds will all be zero) start_stamp = start_date.timestamp() # if the scripts gets restarted we need to figure out when the next scheduled function call is # so we need to nkow when we started curr_time = datetime.datetime.now() curr_stamp = curr_time.timestamp() last_interval = (curr_stamp - start_stamp) // desired_time_delta_in_seconds # Loop forever while(True): # sleep so we don't use up all the servers processing power just checking the time time.sleep(5) # get the current time and see how many whole intervals have elapsed curr_time = datetime.datetime.now() curr_stamp = curr_time.timestamp() num_intervals = (curr_stamp - start_stamp) // desired_time_delta_in_seconds # python 3 integer division # if at least another interval has elapsed and it is currently the time for the next call # then call the function and update the interval count so we don't call it again if (num_intervals &gt; last_interval) and (curr_time.hour &gt;= desired_time_hours) and (curr_time.minute &gt;= desired_time_minutes): print("Calling scheduled function at ", curr_time) last_interval = num_intervals function_to_call_periodically()
has comment: http://stackoverflow.com/comment/90406153

http://stackoverflow.com/comment/90490743
score: 0
comment on: http://stackoverflow.com/q/51765879
type: Comment
type: QuestionComment
has text: Did you check this https://stackoverflow.com/questions/7514964/django-how-to-create-a-file-and-save-it-to-a-models-filefield ? I think it is what you want

http://stackoverflow.com/q/51694515
score: 0
has comment: http://stackoverflow.com/comment/90379712
tagged with: python
has comment: http://stackoverflow.com/comment/90356293
has answer: http://stackoverflow.com/a/51709630
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90353820
type: AnsweredQuestion
has title: confusing SQLite3 Error
accepted answer: http://stackoverflow.com/a/51709630
has comment: http://stackoverflow.com/comment/90350506
type: Question
linked to: http://stackoverflow.com/q/21142531
has comment: http://stackoverflow.com/comment/90356226
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/90350592
has body: Ive made a database in python with SQLite3 and im trying to add some data but im currently getting the error You did not supply a value for binding 1.. Ive made the exact same database (with different values) before but did not get this error, what am i doing wrong here? This is the database with the error: def Add_User_Data(self): self.c.execute("INSERT INTO Employees VALUES (:ID, :FirstName, :Surname, :DOB, :Age, :Gender)", {'ID: ': self.AddEmployee.ID.get(), 'FirstName: ':self.AddEmployee.FirstName.get(), 'Surname: ':self.AddEmployee.Surname.get(), 'DOB: ':self.AddEmployee.DOB.get(), 'Age: ':self.AddEmployee.Age.get(), 'Gender: ':self.AddEmployee.Gender.get()}) self.conn.commit() And this is the old one that did not get an error. def addEmployees(self): self.c.execute("INSERT INTO Employees VALUES (:FirstName, :Surname, :Age, :Postcode, :Wage, :Email, :Hours)", {'FirstName': 'aa', 'Surname':"Jan" , 'Age':"21" , 'Postcode':"UB5 7T3" , 'Wage':"1220000" , 'Email':"s@gmail.com" , 'Hours':"230"}) self.conn.commit() -------------------------------------------------------- Answer ---------------------------------------------------------------- So i fixed the problem by changing the layout to this and it worked: self.params = (self.AddEmployee.ID.get(), self.AddEmployee.FirstName.get(), self.AddEmployee.Surname.get(), self.AddEmployee.DOB.get(), self.AddEmployee.Age.get(), self.AddEmployee.Gender.get()) self.c.execute("INSERT INTO Employees VALUES (?, ?, ?, ?, ?, ? )", self.params) self.conn.commit() I found the solution at: sqlite3.OperationalError: no such column: Thank you to everyone that has replied and tried to help!

http://stackoverflow.com/comment/90337948
type: AnswerComment
has text: Thanks a lot ! That works. The only thing missing is the date labels though
type: Comment
comment on: http://stackoverflow.com/a/51687889
score: 0

http://stackoverflow.com/comment/90561280
comment on: http://stackoverflow.com/a/51800448
type: AnswerComment
score: 0
type: Comment
has text: Yeah that is what I was thinking, I will take a look at Cython. Thanks

http://stackoverflow.com/a/51768309
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51767077
downvote count: 0
score: 1
has body: It seems like python-robotframework is first available in the Sumo release, but not in Rocko. (You can easily search for packages here: http://layers.openembedded.org/layerindex/branch/master/recipes/?q=robotframework) So your options are either backporting the recipe to Rocko or upgrading to Sumo. By the way: You have to add the meta-python layer to your bblayers.conf if you haven't already done this.

http://stackoverflow.com/q/51759995
tagged with: python
has title: python class attribute update issue
has answer: http://stackoverflow.com/a/51760115
tagged with: python-3.x
has body: I wrote a small program to print out all permutations of an array - say input is [1,2,3]. I am using backtracking to generate the solution. My problem is that I can see the result getting updated to the desirable value (based on logs which print class attribute result) but it is not returned. The answer returned in-fact is [[],[],[],[],[],[]] – which is what I do not understand. class Solution: def __init__(self): self.result = [] def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ c = self.permuteHelper(nums, []) print("finally, result:", self.result) return self.result def permuteHelper(self, nums, chosen): print("permuteHelper: nums", nums, "chosen:", chosen) if len(nums) == 0: print("returning:", chosen) self.result.append(chosen) print("result:", self.result) return self.result index = 0 for n in nums: nums.pop(index) chosen.append(n) c = self.permuteHelper(nums, chosen) nums.insert(index, n) chosen.remove(n) index+=1 Here is the output that I am getting: permuteHelper: nums [1, 2, 3] chosen: [] permuteHelper: nums [2, 3] chosen: [1] permuteHelper: nums [3] chosen: [1, 2] permuteHelper: nums [] chosen: [1, 2, 3] returning: [1, 2, 3] result: [[1, 2, 3]] permuteHelper: nums [2] chosen: [1, 3] permuteHelper: nums [] chosen: [1, 3, 2] returning: [1, 3, 2] result: [[1, 3, 2], [1, 3, 2]] permuteHelper: nums [1, 3] chosen: [2] permuteHelper: nums [3] chosen: [2, 1] permuteHelper: nums [] chosen: [2, 1, 3] returning: [2, 1, 3] result: [[2, 1, 3], [2, 1, 3], [2, 1, 3]] permuteHelper: nums [1] chosen: [2, 3] permuteHelper: nums [] chosen: [2, 3, 1] returning: [2, 3, 1] result: [[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]] permuteHelper: nums [1, 2] chosen: [3] permuteHelper: nums [2] chosen: [3, 1] permuteHelper: nums [] chosen: [3, 1, 2] returning: [3, 1, 2] result: [[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]] permuteHelper: nums [1] chosen: [3, 2] permuteHelper: nums [] chosen: [3, 2, 1] returning: [3, 2, 1] result: [[3, 2, 1], [3, …
upvote count: 1
tagged with: backtracking
linked to: http://stackoverflow.com/q/986006
type: AnsweredQuestion
tagged with: algorithm
score: 1
accepted answer: http://stackoverflow.com/a/51760115
type: Question
downvote count: 0
favorite count: 0
answer count: 1

http://stackoverflow.com/comment/90505092
type: Comment
has text: I'm not following your description of events. Can you post some code and its output?
score: 2
comment on: http://stackoverflow.com/q/51773139
type: QuestionComment

http://stackoverflow.com/a/51737805
downvote count: 0
score: 1
has body: You should use the split method. So do 'cat, dog, mouse, elephant'.split(', ') this will give you ['cat', 'dog', 'mouse', 'elephant'] The ', ' means the string should be split every time there is a comma and then a space. The list is not needed, but if you absolutely have to use the list then do listExample[0].split(', ') to get the string out of the list and then split it. For more information see this
answers question: http://stackoverflow.com/q/51737762
upvote count: 1
type: Answer

http://stackoverflow.com/comment/90429280
type: Comment
comment on: http://stackoverflow.com/a/51732636
has text: I didn't even think of when it ends on a weekend. Hmm, I'll have to update my answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90450981
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51745601
has text: I think this is a different question. The dupe explains the second example, but I think the interesting question here is why the first example is different.

http://stackoverflow.com/q/51793431
answer count: 1
has title: MongoDB inserting null every 2nd time when I use .append
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51794182
tagged with: pymongo
has body: I'm getting an error where the first time I run this code, it works 100% properly but every 2nd time after that it behaves weirdly. For some reason, the value "warnings" becomes null instead of [{"warning": "Text1", "time": datetime.datetime(2018, 8, 10, 20, 2, 22, 103589)}, {"warning": "Text2", "time": datetime.datetime(2018, 8, 10, 20, 2, 50, 815495)}] I'm using pymongo and MongoDB atlas. This is my code: result = db.memberscol.find_one({"guild": ctx.guild.id, "user": user.id}) if result is None or result["warnings"] is None or len(result["warnings"]) == 0: warnings = [{"warning": warning, "time": datetime.datetime.utcnow()}] else: warnings = result["warnings"].append({"warning": warning, "time": datetime.datetime.utcnow()}) db.memberscol.replace_one({"guild": ctx.guild.id, "user": user.id}, {"guild": ctx.guild.id, "user": user.id, "warnings": warnings}, True) I would really appreciate it if someone could help me with this. Thanks.
type: Question
tagged with: mongodb
score: 0

http://stackoverflow.com/a/51696026
score: 1
answers question: http://stackoverflow.com/q/51695894
upvote count: 1
has body: this is your solution def strlength (string): lengthstring = len(string) return (lengthstring) string = input("enter the string: ") try: string = int(string) print("please enter the string not integer") except : print(strlength(string))
downvote count: 0
type: Answer

http://stackoverflow.com/q/51692003
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90395843
has comment: http://stackoverflow.com/comment/90353651
has comment: http://stackoverflow.com/comment/90422824
type: UnansweredQuestion
has body: I have a numpy array which is basically a data column from excel sheet. This data is acquired through low-pass 10 Hz filter DAS but due to some ambiguity it contains square wave like artifacts. The data now has to be filtered at 0.4 Hz Highpass Butterworth filter, which I do through scipy.signal. But after applying Highpass fiter, the square wave like artifacts change into spikes. When applying scipy.median to it I am not able to successfully filter the spikes. What should I try? The following pic shows the original data. Following pic shows highpass filter of 0.4 Hz applied followed by median filter of order 3 Even a median filter of order 51 is not useful.
has comment: http://stackoverflow.com/comment/90353178
tagged with: python
has comment: http://stackoverflow.com/comment/90453252
has title: Removing square wave like artifacts from numpy array
has answer: http://stackoverflow.com/a/51775669
has comment: http://stackoverflow.com/comment/90345757
upvote count: 2
has comment: http://stackoverflow.com/comment/90345770
tagged with: scipy
has comment: http://stackoverflow.com/comment/90351242
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90433179
has comment: http://stackoverflow.com/comment/90375586
score: 2

http://stackoverflow.com/comment/97465256
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/55336269
has text: I'm just trying to mitigate the chance that observers would think this might be Paramiko specific. Anything that is throwing the warning is doing so due to the issue in the cryptography package that they're all using.

http://stackoverflow.com/a/51747026
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51746567
has body: This code will extract all models by reading the whole file using regex to extract the modeltext and the modelnumber as tuple creating dictionary entries for the resulting tuples writing all models as single files You can adjust it to only write one number. Write demo data: code = """MODEL 0 ..0... ..0... ..0... ENDMDL MODEL 1 ..1... ..1.. ..1... ENDMDL """ with open("f.txt" , "w") as w: w.write(code) Read and parse demo data: import re with open("f.txt", "r") as r: allModels = r.read() allM = {} # the regex captures as few as possible things between # MODEL and ENDMDL and captures the first number after # MODEL as your modelnumber. for m in re.findall(r"(MODEL\s+(\d+).+?ENDMDL)",allModels,re.DOTALL): # create a dictionary entry for each found match-tuple allM[int(m[1])] = m[0] print(allM) for k in allM: with open("model_{}.txt".format(k),"w") as w: w.write(allM[k]) Output (of the dict): {0: 'MODEL 0\n..0...\n..0...\n..0...\nENDMDL', 1: 'MODEL 1\n..1...\n..1..\n..1...\nENDMDL'}

http://stackoverflow.com/comment/90448955
comment on: http://stackoverflow.com/q/51735140
score: 0
has text: I edit it! thank you for the suggestion.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51772877
type: Question
has body: I've got 2 ranges for which I want to get the overlap. And in a second step remove that overlap from the first range. Currently the ranges are saved in a list, that has the form of (start value, end value). So Range 1 be: (5230,7585) And Range 2 be: (6752,6988) Is this best possible solution for this, to create variables in which I call the range function like this and compare these like descriped elsewhere (How to find range overlap in python?) x = range(5230,7585) y = range(6752,6988) xs = set(x) xs.intersection(y) Actually I got >30.000 entry in both type of ranges. I am interested in finding the ranges from List 2 (or Ranges 2) that overlap with these of List 1 (Ranges 1). The intersections of List 2 with List 1 shall then be removed from List 1. So that List 1 Look like this List1 = [...,[5230,6752], [6988,7585], ...] I tried to do it with a lot of for loops and if statements but it soon got really confusing and unclear. I can post my code this far, however I am not sure that this would help. Is there a library or built-in function that can realize this task better (than manually via for-if-statements). What is the most pythonic way to remove the intersection. would it be? xintrm = xs.difference(y) Best Regards, Edit 1: Hey thanks @ the moderator. I am having trouble with transfering the solutions suggested in the other thread to my situation. Since I dont have just one range in which I want to finde the intervals but instead I have multiple ranges to search for intercepts
tagged with: intersection
linked to: http://stackoverflow.com/q/6821156
has comment: http://stackoverflow.com/comment/90505031
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/18399677
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/18399677
has comment: http://stackoverflow.com/comment/90508375
tagged with: list
answer count: 0
has title: Python removing intersection from list 2 out of list 1
tagged with: loops

http://stackoverflow.com/a/51788228
answers question: http://stackoverflow.com/q/51788074
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: Both self.w in the project function should be self._w.
has comment: http://stackoverflow.com/comment/90533961

amazon-s3
tags question: http://stackoverflow.com/q/51657351
tags question: http://stackoverflow.com/q/51738406
tags question: http://stackoverflow.com/q/51759237
tags question: http://stackoverflow.com/q/51660664
type: Tag
tags question: http://stackoverflow.com/q/51716222
tag name: amazon-s3
tags question: http://stackoverflow.com/q/51758593
tags question: http://stackoverflow.com/q/51725436

http://stackoverflow.com/q/51740197
has title: Odoo10 : How can I automatically get the value for partner when customer number is given?
tagged with: postgresql
tagged with: odoo-10
tagged with: python
has comment: http://stackoverflow.com/comment/90441063
type: UnansweredQuestion
upvote count: 1
has body: I am creating a module something like call log. In that i need to search the customer number and get the Partner information or have to link the partner automatically. the following are the codes, somebody please help me. class model_call(models.Model): _inherit = 'res.partner' _name = 'model.call' _description = 'call logs' """ *************** Base Fields ******************* """ name = fields.Char(string='Topic') customer_number = fields.Char(string='Customer Number', track_visiility='onchange', onchange='get_partner(customer_number)') #------------------------------------------------- # apis #------------------------------------------------- @api.onchange('customer_number') def get_partner(self, customer_number): if customer_number: customer = self.env['res.partner'].search([('customer_number', '=', record.phone)]) return customer #------------------------------------------------------ customer = fields.Many2one('res.partner', string='Customer', track_visibility='onchange',index=True, help="Linked partner (optional). Usually created when converting the lead.",)
has comment: http://stackoverflow.com/comment/90442877
tagged with: odoo
score: 1
has comment: http://stackoverflow.com/comment/90443114
type: Question
has comment: http://stackoverflow.com/comment/90442895
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51740605
favorite count: 0

http://stackoverflow.com/q/51750967
type: UnansweredQuestion
tagged with: io
has comment: http://stackoverflow.com/comment/90482469
tagged with: python
has comment: http://stackoverflow.com/comment/90482537
has answer: http://stackoverflow.com/a/51751124
has answer: http://stackoverflow.com/a/51751047
has body: I'm trying to control a relay board (USB RLY08) using a section of python code I found online (https://github.com/jkesanen/usbrly08/blob/master/usbrly08.py). It is currently returning an error which I'm not sure about. Does anyone have any ideas? I'm not actually needing all the code and instead just wanting to turn a single relay on and off. Thanks.
type: Question
has title: Controlling I/O Module using python code
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51751048

http://stackoverflow.com/comment/90305435
type: Comment
score: 3
has text: See [When should I use a Map instead of a For Loop?](//stackoverflow.com/q/1975250).
type: QuestionComment
comment on: http://stackoverflow.com/q/51671132

http://stackoverflow.com/q/51726827
type: Question
accepted answer: http://stackoverflow.com/a/51727038
downvote count: 0
tagged with: django-rest-framework
has title: Auto add new model_field on request in Django || DRF
has comment: http://stackoverflow.com/comment/90417559
answer count: 1
tagged with: python
has body: I have a simple REST-API project. Here is my models: class Human(Model): height = IntegerField() And I have a serializer for that: class HumanSerializer(ModelSerializer): id = IntegerField(read_only=True) height = IntegerField(required=True) Very clear and simple! But! What I want is to be able to add additional fields to my Human model, and automatically migrate those changes to the database, and add a new field to serializer that would be related to the new model field. For example, lets say that the client want to add a new field called "weight". So a developer won't do anything, because the backend will automatically receive that request, will automatically create a new field to Human model, automatically create a new field to serializer, and automatically create a migration.py file related to those changes. Is there a way to achieve that ? What is the best way to do that ?
favorite count: 0
has comment: http://stackoverflow.com/comment/90413988
tagged with: django
has answer: http://stackoverflow.com/a/51727038
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: django-models

http://stackoverflow.com/q/51727785
has body: I have lighttpd web server running on my Windows 7 pc using port 80. My web app calls python cgi scripts. I am trying to configure VScode to debug these python scripts when I click a button on one of my html pages. For example: http://localhost/cgi-bin/instantlight.py?Input=&amp;lightColor=blue In my launch.json file I have: { "name": "Python: Attach", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "${workspaceFolder}", "port": 80, "secret": "my_secret", "host": "localhost" } When I launch the debugger and click a button, my breakpoint is never hit. After a minute or two I get the error message "Debug adapter process has terminated unexpectedly" What am I missing?
type: Question
tagged with: python
answer count: 1
score: 0
tagged with: cgi
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/51773337
type: UnansweredQuestion
has title: VScode: How to debug a python 2.7 cgi script?

http://stackoverflow.com/comment/90467077
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51667352
has text: I've never come across append_entry and prefer setattr since it feels more basic pythonic. And in this case it allows automatic validation with the imported validators.

http://stackoverflow.com/q/51659321
type: AnsweredQuestion
tagged with: sum
has title: how to use annotate to sum up all rows and get the avg? django
has answer: http://stackoverflow.com/a/51659705
accepted answer: http://stackoverflow.com/a/51659705
tagged with: average
type: Question
has body: I was googling about this and there is a simplier way which uses Cast but then thing is I believe that's for django 2.0 that mine is django 1.9 I found a post and I tried it, it doesn't really work for me though. Let's say I have a model with value and max fields. I want to get the sum of all value and max then divide them to get the average. What I did just gets one row and return the avg of the row, can someone let me know what I have been doing wrong here? model_calcuation = Model.objects.filter().annotate( sum_score=Sum('value', output_field=FloatField()), sum_max=Sum('max', output_field=FloatField()) ).annotate( avg=F('sum_score') / F('sum_max') ) Thanks in advance for any help
upvote count: 1
answer count: 1
favorite count: 0
score: 0
tagged with: python
tagged with: django
downvote count: 1

http://stackoverflow.com/q/51785007
has comment: http://stackoverflow.com/comment/90528572
has comment: http://stackoverflow.com/comment/90527206
tagged with: slider
tagged with: python
has title: Matplotlib dynamic plot with a slider
has comment: http://stackoverflow.com/comment/90528466
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51786182
linked to: http://stackoverflow.com/q/31001713
has comment: http://stackoverflow.com/comment/90528293
type: Question
has comment: http://stackoverflow.com/comment/90528129
has comment: http://stackoverflow.com/comment/90528528
has comment: http://stackoverflow.com/comment/90527413
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90527765
accepted answer: http://stackoverflow.com/a/51786182
score: 0
answer count: 1
has body: I'm not too used to matplotlib dynamic plots, and thus I have some difficulties to create a desired plot. I'm trying to plot N timelines (not too much, less say less than 5) of the same large size (800k points). I would like to use a slider to represent this. import numpy as np from matplotlib import pyplot as plt from matplotlib.widgets import Slider plt.ioff() timelines = [np.random.randint(-2, 5, size = 800000), np.random.randint(-2, 5, size = 800000), np.random.randint(-2, 5, size = 800000)] timelines_labels = ["label1", "label2", "label3"] def slide_plot(timelines, timelines_labels): f, ax = plt.subplots(len(timelines), 1, sharex = True, figsize = (20, 10)) def update(pos, ax = ax, timelines = timelines): for k, a in enumerate(ax): a.axis([pos,pos+80,-max(timelines[k])-1, max(timelines[k])+1]) f.canvas.draw_idle() f.subplots_adjust(bottom=0.25) plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) t = np.arange(0.0, len(timelines[0]), 1) for k, a in enumerate(ax): a.plot(t, timelines[k], lw = 0.55, label=timelines_labels[k]) a.legend(loc="upper right") a.axis([0, 160000, -max(timelines[k])-1, max(timelines[k])+1]) ax[-1].set_xticks(np.arange(0.0, len(timelines[0])+80000, 80000)) axpos = plt.axes([0.2, 0.1, 0.65, 0.03]) spos = Slider(axpos, 'Time (ms)', valmin =0, valmax=800000, valinit=0) spos.on_changed(update) plt.show() slide_plot(timelines, timelines_labels) As you see, since my plots are sharing the X-axis, I'm taking out the xticks labels (will do the same with the xticks later) from all the axis except the bottom one. Then I create the variable t which is just the time, I feel like it is useless, and ax[k].plot(timelines[k]) would be enough. I do some more formatting by setting one tick every 80000 points. And finally, I got the slider. Obviously, the update function does not work. I do not know the correct syntax, nor the right way to achieve this. Thanks :) EDIT: By placing the argument ax = ax and timelines = timelines it seems to start …

http://stackoverflow.com/comment/90461099
has text: You should really post your code inside your question and format it properly instead of just posting an image. People are much more inclined to help you that way.
comment on: http://stackoverflow.com/q/51750599
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/51784507
has title: I have a document with a unique alphabet, how can I translate it?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9452108
has answer: http://stackoverflow.com/a/51784598
accepted answer: http://stackoverflow.com/a/51784598
tagged with: document
type: Question
possible better answer: http://stackoverflow.com/a/51784633
upvote count: 2
score: 0
answer count: 2
has body: I have a document filled with weird characters, but I have the counterpart of the letters in another document. Eg. ⟷ = a ⇳ = b ⤚ = c etc... I think that I can do this by using a dictionary, and a simple swap algorythm, but I'm still a newbie in programming. Do you think that's a good idea? How can I translate the whole text (preferably using Python or C++), without having to use MS Word's built in "swap" tool?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51784633
tagged with: c++
tagged with: translate
downvote count: 2
duplicate of: http://stackoverflow.com/q/9452108

http://stackoverflow.com/q/51762043
tagged with: python
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51763050
has title: what's the best way to clean CSV and load to mysql
downvote count: 1
linked to: http://stackoverflow.com/q/34383000
score: -1
type: Question
has body: Please let me know what's the best way to clean CSV and load to mysql I am working on loading a couple of different CSVs to mysql database but the CSVs have some anomalies. note: using pandas read_csv for loading to df and to_sql to load to mysql I am trying to remove all characters like &lt;$ , &quot; **&gt; from csv, getting data into dataframe with pd.read_csv and within the dataframe trying to do df[col].replace('$','').. does not work on some values unable to find out why. There is no error as such but simply does not remove these characters. Also the intention is to remove these special characters so accurate data types can be found using SQLalchemy function below. for col in df.columns: df[col]=(df[col].replace('$','')) df[col]=(df[col].replace(',','')) For finding datatype I am using SQL Alchemy as per below: pandas to_sql all columns as nvarchar
answer count: 1
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/51678593
accepted answer of: http://stackoverflow.com/q/51677662
type: Answer
has comment: http://stackoverflow.com/comment/90332114
has body: It's crawling, but stops because you are sending requests for the same page (#content). Scrapy has DupeFilter enabled by default.
has comment: http://stackoverflow.com/comment/90326348
has comment: http://stackoverflow.com/comment/90330918
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51677662
has comment: http://stackoverflow.com/comment/90331607

http://stackoverflow.com/q/51697816
has body: I am trying to do spatial rainfall correlations between rainfall time series and the SST. My code is as follows #'OND_rainfall_index_list' is a list of 27 (1990-2016) values of spatially averaged rainfall in eastern Africa #trial_x is a (27,48,80) multidimensional array of SST (time, lat,lon) in the Indian Ocean corr = np.zeros((27,48,80)) corr.shape for m in range(48): for n in range(80): corr[m,n]=stats.pearsonr(OND_rainfall_index_list, trial_x[:,m,n])[0] OND_rainfall_index_list is a list of 27 values of spatially averaged rainfall in eastern Africa whereas trial_x is a multidimensional array of SST. I am trying to initialize a matrix which I can then fill with correlation values. I would like to end up with a matrix of the same size as trial_x but with correlation values instead. How can I go about this? At the moment I get the following error when I run the loop. &gt; IndexError: index 48 is out of bounds for axis 1 with size 48
downvote count: 1
type: AnsweredQuestion
has title: How to fill 3D matrix with correlation values using a loop?
score: -1
type: Question
has answer: http://stackoverflow.com/a/51697910
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51697910
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51651281
tagged with: while-loop
has comment: http://stackoverflow.com/comment/90278601
tagged with: python
has comment: http://stackoverflow.com/comment/90266450
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90267709
answer count: 0
type: UnansweredQuestion
has body: I'm writing a script to receive data over a serial communication line from an MCU connected to a pressure sensor. The idea is that I would continuously poll the MCU for pressure information in one loop and gather data in another. I would like to be able to stop the data collection once the pressure is no longer constant. There are two while loops, one that polls the MCU and one that gathers data, but I need them to run concurrently so that the polling loop can provide the condition to the collection loop to stop. #Loop that polls MCU def poll(serial_data): data = serial_data while data_in: _, pressure = Get_data(data, 2000) difference = np.diff(pressure[:,1]) if (all(i&lt;1000 for i in difference) and all(i&gt;-1000 for i in difference)): print('Pressure constant. Start collecting.') return True else: print('Pressure is not constant.') #break 2nd loop on this condition return False def some_other_function(serial_data): input = "" data = serial_data #Loop to continously gather data while (poll(data) == True): # I realise this line probably isn't correct input_bytes = serial_data.read() input_string = str(input_bytes,'utf-8') input += input_string # Want to break 1st loop now that data collection has stopped I have been looking into multi-processing for doing this but am unsure of how to implement it so that one loop will depend on the other.
has comment: http://stackoverflow.com/comment/90267441
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/90273136
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/90266340
has comment: http://stackoverflow.com/comment/90275549
has title: Break one loop based on the condition of another - Python
has comment: http://stackoverflow.com/comment/90301687
score: 0

http://stackoverflow.com/comment/90250922
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51643262
has text: As a side note: Are you writing this script for learning purposes, or because you need a tool that can do those things? Because tools like `df` and `du` already exist for what you want unless you're on Windows, and if you are… I'm pretty sure there's something even if I don't know what it is (maybe part of Mark Russinovich's sysinternals stuff?). But if you're doing this to learn how to use `walk` and `listdir` and `stat` and so on, then it's a perfectly reasonable project (although I'd suggest learning `scandir`—and also `argparse` instead of `getopt`).

http://stackoverflow.com/a/51660430
has comment: http://stackoverflow.com/comment/90286607
accepted answer of: http://stackoverflow.com/q/51659976
has comment: http://stackoverflow.com/comment/90287841
answers question: http://stackoverflow.com/q/51659976
has comment: http://stackoverflow.com/comment/90288083
type: Answer
downvote count: 0
score: 1
has body: If I see it right, you're currently appending every element in order of it's appearance to the list outline_list. But obviously you don't have 1, but instead 3 types of distinct data: chapter__title chapter__exercise.name chapter__exercise.link Each title can have multiple exercises, which are always a pair of name and link. Since you also want to keep the data in this structure for your text-file, you can come up with any structure that represents this hierarchy. An example: from urllib.request import urlopen from bs4 import BeautifulSoup from collections import OrderedDict url = 'https://www.datacamp.com/courses/experimental-design-in-r' html = urlopen(url) soup = BeautifulSoup(html, 'lxml') lesson_outline = soup.find_all(['h4', 'li']) # Using OrderedDict assures that the order of the result will be the same as in the source chapters = OrderedDict() # {chapter: [(lesson_name, lesson_link), ...], ...} for item in lesson_outline: attributes = item.attrs try: class_type = attributes['class'][0] if class_type == 'chapter__title': chapter = item.text.strip() chapters[chapter] = [] if class_type == 'chapter__exercise': lesson_name = item.find('h5').text lesson_link = item.find('a').attrs['href'] chapters[chapter].append((lesson_name, lesson_link)) except KeyError: pass From there it should be easy to write your text file: for chapter, lessons in chapters.items(): # write chapter title for lesson_name, lesson_link in lessons: # write lesson
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51689007
upvote count: 2
answers question: http://stackoverflow.com/q/51688755
has body: You need to unstack sex column to get two more columns: M and F. Dirty example: &gt;&gt;&gt; df_ = df.set_index(['year', 'noc', 'sex']).unstack().reset_index() &gt;&gt;&gt; df_.columns = [''.join(col).strip() for col in df_.columns.values] Then you can use seaborn: &gt;&gt;&gt; sb.scatterplot(x='sumM', y='sumF', hue='year', data=df)
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/51729267
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90419451
score: 0
downvote count: 1
type: Answer
has body: Given a list x with n items, you need to create a new list with n-1 items, each item is a pair of items that follow each other. It's easy to do with running over the items of the list from the first item until the second to last, and create a list for every one of those items with that item (x[i]) and the one that comes after him (x[i+1]) result = [[x[i], x[i+1]] for i in range(len(x)-1)] And for the more generic case: offset = 2 sublist_size = 3 result = [[x[i + n] for n in range(sublist_size)] for i in range(0, len(x) - sublist_size, offset)]
accepted answer of: http://stackoverflow.com/q/51729217
has comment: http://stackoverflow.com/comment/90421755
answers question: http://stackoverflow.com/q/51729217
upvote count: 1
has comment: http://stackoverflow.com/comment/90419904

http://stackoverflow.com/comment/114380653
type: Comment
comment on: http://stackoverflow.com/a/51701698
score: 15
type: AnswerComment
has text: To add to this, once you get a more accurate stack trace and locate where the issue is, you can move your tensors to CPU. Moving the tensors to CPU will give much more detailed errors. Combining `CUDA_LAUNCH_BLOCKING=1` with moving the tensors to CPU was the only way I was able to solve a problem I spent 3 days on.

http://stackoverflow.com/comment/94709839
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51737367
has text: `(visits=F('visits') + 1)` you've this code in your answer i'm wondering why F what it does can you explain please?

http://stackoverflow.com/comment/90381183
type: Comment
has text: So everything works awesome, thank you so much! and i'm sure you are busy but would you mind explaining some of the functionality. I understand the command and calling a discord.Member and that doesn't confuse me, but I do not 100% understand the line split? I am definitely going to also do some research myself though
comment on: http://stackoverflow.com/a/51709405
score: 0
type: AnswerComment

http://stackoverflow.com/q/51733698
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90429826
type: Question
has answer: http://stackoverflow.com/a/51734726
has comment: http://stackoverflow.com/comment/90428263
accepted answer: http://stackoverflow.com/a/51734841
has answer: http://stackoverflow.com/a/51734802
has title: How do I format JSON's with multiple of the same keys with python?
has comment: http://stackoverflow.com/comment/90428760
has body: I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program: import subprocess import json p = subprocess.Popen(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./TestScript\";", "&amp;NSV"], stdout=subprocess.PIPE) (output, err) = p.communicate() data = json.loads(output) for mNull in data: del mNull['Scope'] del mNull['Path'] del mNull['Options'] del mNull['ClassPath'] del mNull['Properties'] del mNull['SystemProperties'] del mNull['Qualifiers'] del mNull['Site'] del mNull['Container'] del mNull['PSComputerName'] del mNull['__GENUS'] del mNull['__CLASS'] del mNull['__SUPERCLASS'] del mNull['__DYNASTY'] del mNull['__RELPATH'] del mNull['__PROPERTY_COUNT'] del mNull['__DERIVATION'] del mNull['__SERVER'] del mNull['__NAMESPACE'] del mNull['__PATH'] fdata = json.dumps(data,indent=2) print(fdata) Now here is the resulting JSON: [ { "Name": "Memory", "SensorType": "Load", "Value": 53.3276978 }, { "Name": "CPU Core #2", "SensorType": "Temperature", "Value": 69 }, { "Name": "Used Space", "SensorType": "Load", "Value": 93.12801 }, { "Name": "CPU Core #1", "SensorType": "Temperature", "Value": 66 }, { "Name": "CPU DRAM", "SensorType": "Power", "Value": 1.05141532 }, { "Name": "CPU Core #2", "SensorType": "Load", "Value": 60.15625 }, { "Name": "CPU Package", "SensorType": "Power", "Value": 15.2162886 }, { "Name": "Bus Speed", "SensorType": "Clock", "Value": 100.000031 }, { "Name": "CPU Total", "SensorType": "Load", "Value": 57.421875 }, { "Name": "CPU Package", "SensorType": "Temperature", "Value": 69 }, { "Name": "CPU Core #2", "SensorType": "Clock", "Value": 2700.00073 }, { "Name": "Temperature", "SensorType": "Temperature", "Value": 41 }, { "Name": "Used Memory", "SensorType": "Data", "Value": 4.21539…
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51735030
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90428500
answer count: 5
has comment: http://stackoverflow.com/comment/90428717
has answer: http://stackoverflow.com/a/51734690
has answer: http://stackoverflow.com/a/51734841
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51734690
score: 1

http://stackoverflow.com/comment/90446705
comment on: http://stackoverflow.com/q/51743354
type: Comment
type: QuestionComment
has text: Welcome to SO. Please provide a **[mcve]**. This means no links/images, just text.
score: 0

http://stackoverflow.com/comment/90493833
type: Comment
score: 1
has text: I got caught out on the need to define the end of the list slice (the 0 in `[-n:0]`) but think i understand now. Thanks again!
comment on: http://stackoverflow.com/a/51767407
type: AnswerComment

http://stackoverflow.com/q/51777942
upvote count: 1
accepted answer: http://stackoverflow.com/a/51777971
downvote count: 1
type: Question
type: AnsweredQuestion
has body: I am learning python , and I am running below code : df1 = pd.DataFrame( [['A',20,30],['B',30,40]],index=['A1','B1'],columns = ['a','b','c']) df1.loc['A1':'B1',['a':'b']] #edit to df1 to make easier for answerers It is giving syntax error : invalid syntax (at ':' after 'a') Whats wrong with this?
has comment: http://stackoverflow.com/comment/90514092
answer count: 1
favorite count: 0
score: 0
has title: Python - invalid syntax error
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51777971

http://stackoverflow.com/q/51746423
has comment: http://stackoverflow.com/comment/90455263
downvote count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90457650
has comment: http://stackoverflow.com/comment/90458289
tagged with: sql
has comment: http://stackoverflow.com/comment/90456937
has comment: http://stackoverflow.com/comment/90457905
has comment: http://stackoverflow.com/comment/90464721
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90456184
has comment: http://stackoverflow.com/comment/90457162
has answer: http://stackoverflow.com/a/57170955
score: 1
tagged with: pagination
has title: How to do pagination in postgres sql?
has body: I have a python script that I am using using to make sql queries. The problem is that my VM only has 2GBs of RAM and some of the sql queries are too RAM intensive and therefore the kernel automatically kills the script. How can I make this code more RAM efficient? I would like to implement pagination in my postgres sql code. How would I do that? Does anyone know an easy implementation of that? I would greatly appreciate your help! Updated Code from __future__ import print_function try: import psycopg2 except ImportError: raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n') sys.exit(1) import re import sys import json import pprint import time outfilepath = "crtsh_output/crtsh_flat_file" DB_HOST = 'crt.sh' DB_NAME = 'certwatch' DB_USER = 'guest' # DELAY = 0 def connect_to_db(): start = 0 offset = 10 flag = True while flag: filepath = 'forager.txt' with open(filepath) as fp: unique_domains = '' try: conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) cursor = conn.cursor() cursor.itersize = 10000 for cnt, domain_name in enumerate(fp): print("Line {}: {}".format(cnt, domain_name)) print(domain_name) domain_name = domain_name.rstrip() cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_keyAlgorithm(c.certificate), x509_keySize(c.certificate), x509_publicKeyMD5(c.certificate), x509_publicKey(c.certificate), x509_rsaModulus(c.certificate), x509_serialNumber(c.certificate), x509_signatureHashAlgorithm(c.certificate), x509_signatureKeyAlgorithm(c.certificate), x509_subjectName(c.certificate), x509_name(c.certificate), x509_name_print(c.certificate), x509_commonName(c.certificate), x509_subjectKeyIdentifier(c.certificate), x509_extKeyUsages(c.certificate), x509_certPolicies(c.certificate), x509_canIssueCerts(c.certificate), x509_getPathLenConstraint(c.certificate),…
has comment: http://stackoverflow.com/comment/90464396
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51746560

http://stackoverflow.com/comment/90365931
score: 1
comment on: http://stackoverflow.com/q/51702434
type: Comment
has text: pandas is overkill here. The csv module (included in standard distributions would be enough)
type: QuestionComment

http://stackoverflow.com/q/51726228
score: 0
has body: I've tried implementing the page object model in Python. I have two questions: Why does the browser launch thrice during the test execution? Is it because of the fact that I'm making new page objects in each of the tests verify_login_failure and verify_login_success? This could be because my driver.get() is wrongly placed in my BasePage class. Please advise. Where shall I call driver.quit() in order to end the test suite execution gracefully after all the tests are completed? Here's my code: # Basepage.py from selenium import webdriver class BasePage(object): def __init__(self): self.driver = webdriver.Chrome( executable_path="chromedriver_mac") self.driver.get("http://automationpractice.com/index.php?controller=authentication&amp;back=my-account") self.driver.implicitly_wait(5) # LoginPage.py from selenium.webdriver.common.by import By from page_object.pages.BasePage import BasePage class Login(BasePage): email = (By.ID, "email") password = (By.ID, "passwd") sign_in_btn = (By.ID, "SubmitLogin") failure_message = (By.XPATH, "//li[contains(text(),'Authentication failed.')]") def set_email(self, email): email_element = self.driver.find_element(*Login.email) email_element.clear() email_element.send_keys(email) def set_password(self, password): password_element = self.driver.find_element(*Login.password) password_element.clear() password_element.send_keys(password) def click_sign_in_btn(self): sign_in_element = self.driver.find_element(*Login.sign_in_btn) sign_in_element.click() def is_failure_message_displayed(self): failure_message_element = self.driver.find_element(*Login.failure_message) return failure_message_element.is_displayed() def login(self, email, password): self.set_email(email) self.set_password(password) self.click_sign_in_btn() # MyAccountPage.py from selenium.webdriver.common.by import By from page_object.pages.BasePage import BasePage class MyAccount(BasePage): my_account_text = (By.XPATH, "LoginPage.py") def is_my_account_text_displayed(self): my_acco…
answer count: 2
has answer: http://stackoverflow.com/a/51796630
tagged with: python
has comment: http://stackoverflow.com/comment/90417051
type: AnsweredQuestion
has title: Queries regarding page object model with Python
accepted answer: http://stackoverflow.com/a/51796630
tagged with: selenium
possible better answer: http://stackoverflow.com/a/51727584
type: Question
tagged with: pageobjects
has answer: http://stackoverflow.com/a/51727584

http://stackoverflow.com/q/51643389
score: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I want this output written via CSV ['https://www.lendingclub.com/loans/personal-loans' '6.16% to 35.89%'] ['https://www.lendingclub.com/loans/personal-loans' '1% to 6%'] ['https://www.marcus.com/us/en/personal-loans' '6.99% to 24.99%'] ['https://www.marcus.com/us/en/personal-loans' '6.99% to 24.99%'] ['https://www.marcus.com/us/en/personal-loans' '6.99% to 24.99%'] ['https://www.marcus.com/us/en/personal-loans' '6.99% to 24.99%'] ['https://www.marcus.com/us/en/personal-loans' '6.99% to 24.99%'] ['https://www.discover.com/personal-loans/' '6.99% to 24.99%'] However when I run the code to write the output to CSV I only get the last line written to the CSV file: ['https://www.discover.com/personal-loans/' '6.99% to 24.99%'] Could it be because my printed output is not comma separated? I attempted to circumvent having to put a comma in there by using a space as the delimiter. Let me know your thoughts. Would love some help on this because I am having the hardest time reshaping this collected data. plcompetitors = ['https://www.lendingclub.com/loans/personal-loans', 'https://www.marcus.com/us/en/personal-loans', 'https://www.discover.com/personal-loans/'] #cycle through links in array until it finds APR rates/fixed or variable using regex for link in plcompetitors: cdate = datetime.date.today() l = r.get(link) l.encoding = 'utf-8' data = l.text soup = bs(data, 'html.parser') #captures Discover's rate perfectly but catches too much for lightstream/prosper paragraph = soup.find_all(text=re.compile('[0-9]%')) for n in paragraph: matches = re.findall('(?i)\d+(?:\.\d+)?%\s*(?:to|-)\s*\d+(?:\.\d+)?%', n.string) try: irate = str(matches[0]) array = np.asarray(irate) array2 = np.append(link,irate) array2 = np.asarray(array2) print(array2) #with open('test.csv', "w") as csv_file: # writer = csv.writer(csv_file, delimiter=' ') # for line in test: # writer.writerow(line) except IndexError: pass
tagged with: python
has answer: http://stackoverflow.com/a/51643997
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51643714
type: Question
type: AnsweredQuestion
has title: Writing Printed Output to CSV - Numpy
possible better answer: http://stackoverflow.com/a/51643714
accepted answer: http://stackoverflow.com/a/51643997
tagged with: numpy
answer count: 2

http://stackoverflow.com/q/51734627
has body: I have a problem on making forecasting model(lstm) model now with tensorflow. I try to use embedding_lookup with multiple categorical columns. This is my data (shape[100, 12, 16]) [[[1, 1, 1, 7, 1, -1, 26, 9], [1, 5, 2, -5, 2, 20, 25, 8], [1, 4, 3, 1, 1, 32, 1, 7], ...]] for forecasting, each row has multiple features, and I changed these features to categorical data(0, 1, 2...). after then, I'd like to use embedding layer for each columns and then concat all for using as an input data to LSTM. How can I use embedding layer and concat each others? This is my code def get_var(self, name='', shape=None, dtype=tf.float32): return tf.get_variable(name, shape, dtype=dtype, initializer=self.initializer) def get_embedding(self, data='', name='', shape=[], dtype=tf.float32): return tf.nn.embedding_lookup(self.get_var(name=name, shape=shape), data) emb_concat = self.get_embedding(tf.cast(data[:,:, 0], 'int32'), name='emb_ap2id'+type, shape=[3, 2]) emb = self.get_embedding(tf.cast(data[:,:, 1], 'int32'), name='emb_month'+type, shape=[12, 11]) emb_concat = tf.concat(emb_concat, emb, axis=2) It isn't working and I got an error msg. result img
answer count: 0
type: UnansweredQuestion
tagged with: embedding-lookup
tagged with: tensorflow
type: Question
has title: Using tf.nn.embedding_lookup with multiple columns
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/90651705
has comment: http://stackoverflow.com/comment/90430032
tagged with: python
has comment: http://stackoverflow.com/comment/90430226

oitnb
tag name: oitnb
type: Tag
tags question: http://stackoverflow.com/q/51683391

http://stackoverflow.com/comment/90435134
has text: @Rushabh Mehta, This is nothing like that question? Could you please take another look. Your flag is blocking my question
comment on: http://stackoverflow.com/q/51737156
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51756338
score: -2
downvote count: 2
has body: You're probably missing the __init__.py file in the directory containing your class file. What is __init__.py for?
has comment: http://stackoverflow.com/comment/90472433
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51756290

http://stackoverflow.com/q/51677631
answer count: 1
tagged with: python
favorite count: 0
has body: I am able to get the output/predictions of all layers as suggested in Keras Docs: how-can-i-obtain-the-output-of-an-intermediate-layer def get_output_of_all_layers(model, test_input): output_of_all_layers = [] for count, layer in enumerate(model.layers): # skip the input layer if count == 0: continue intermediate_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer.name).output) intermediate_output = intermediate_layer_model.predict(test_input)[0] output_of_all_layers.append(intermediate_output) return np.array(output_of_all_layers) But this is incredible slower and takes more than a minute (clocked at ~65s, in 6700HQ with GTX1070, that's ridiculously high, inference happens in less than a second...!) for models with about 50 layers. I guess this is because it is building a model every single time, load the model into the memory, pass inputs and get outputs. Clearly, you can't get the output of the last layer without getting results from the other layers, how do I save them all like above without having to create redundant models (or in a faster, more efficient way)? Update: I also noticed that this does NOT utilize my GPU, this means all the conv layers are being executed by the CPU? Why wouldn't it use my GPU for this? I reckon it's gonna take way less if it used my GPU. How do I do it more efficiently?
upvote count: 3
tagged with: output
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90318880
has answer: http://stackoverflow.com/a/51678174
tagged with: tensorflow
has title: Keras/Tensorflow: Get predictions or output of all layers efficiently
type: Question
downvote count: 0
tagged with: keras
accepted answer: http://stackoverflow.com/a/51678174
tagged with: layer
score: 3

http://stackoverflow.com/comment/90401186
has text: Yes. This worked. But can you post it as answer?
score: 0
comment on: http://stackoverflow.com/q/51700700
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51796280
has answer: http://stackoverflow.com/a/51796300
answer count: 3
has answer: http://stackoverflow.com/a/51796331
has answer: http://stackoverflow.com/a/51796330
has title: Convert negation text to text in python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
score: 3
has body: I have a lot of data which contain the word "not". For example : "not good". I want to convert "not good" to "notgood" (without a space). How can I convert all of the "not"s in the data, erasing the space after "not". For example in the below list: 1. I am not beautiful → I am notbeautiful 2. She is not good to be a teacher → She is notgood to be a teacher 3. If I choose A, I think it's not bad decision → If I choose A, I think it's notbad decision
tagged with: data-science
upvote count: 4

http://stackoverflow.com/comment/90484093
type: QuestionComment
has text: it returns : MuhammetAliözTÜ as I said, my name contains Ö and Ü thats why I just reinstalled to another folder in D: but that didn't fix the issue too
comment on: http://stackoverflow.com/q/51762389
score: 0
type: Comment

http://stackoverflow.com/a/51714574
upvote count: 2
answers question: http://stackoverflow.com/q/51714489
type: Answer
score: 2
downvote count: 0
has body: You can catch multiple exceptions in a single line; final_dict["short_title"] = article_as_dict["short_title"] try: final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"] except (IndexError, KeyError) as e: final_dict["picture_url"] = None

http://stackoverflow.com/q/51689617
downvote count: 1
has comment: http://stackoverflow.com/comment/90341290
type: Question
has answer: http://stackoverflow.com/a/51691751
linked to: http://stackoverflow.com/q/48369043
has answer: http://stackoverflow.com/a/51692691
score: 0
answer count: 3
favorite count: 0
tagged with: xpath
has body: I am having not luck getting a button click on a webpage. in python coding using selenium on chrome browser. I have found the xpath in chrome inspect. chrome inspect xpath: NOTE Which is a looks to be a dynamic path after exportbutton-xxxx-btnInnerEl. //*[@id="exportbutton-1102-btnInnerEl"] I have tried 10 different xpath formats and not getting any closer to getting button selected to run report on website. My test case is just to get button pressed on this page to export some date. Here is buttonn element in html Export Tickets Run Error output from python in order: submit_button = driver.find_elements_by_xpath('//*[contains(@id,’exportbutton’)]') run errors in python submit_button = driver.find_elements_by_xpath('//*[contains(@id,’exportbutton’)]') return self.find_elements(by=By.XPATH, value=xpath) 'value': value})['value'] self.error_handler.check_response(response) raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //*[contains(@id,’exportbutton’)] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(@id,’exportbutton’)]' is not a valid XPath expression. (Session info: chrome=67.0.3396.99) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64) Thanks
has answer: http://stackoverflow.com/a/51706133
tagged with: invalidselectorexception
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium
has title: InvalidSelectorException while locating submit button through Selenium and Python

http://stackoverflow.com/a/51642500
downvote count: 0
answers question: http://stackoverflow.com/q/51641395
type: Answer
has body: People already provided much shorter (and efficient) solutions. I am just posting here my attempt just to show one more way and logic to approach the problem using list comprehension. def find_which_range(value, ranges): if value &lt;= min(ranges): c = 0 elif value &gt;= max(ranges): c = len(ranges) else: c = [i+1 for i in range(len(ranges)-1) if ranges[i] &lt;= value &lt;= ranges[i+1]][0] return c value = -9 i = find_which_range(value, ranges)
score: 1
upvote count: 1

mouseevent
tags question: http://stackoverflow.com/q/51666604
type: Tag
tag name: mouseevent

http://stackoverflow.com/comment/90327721
type: QuestionComment
comment on: http://stackoverflow.com/q/51682386
has text: Is it possible to give us url of the page ?
score: 0
type: Comment

http://stackoverflow.com/q/51680761
score: 0
has title: How to access a somehow fixed local variable of a function coming from another .py file in Python?
has comment: http://stackoverflow.com/comment/90326794
has body: So I have two files: test.py and test2.py Let's say I want to access the local variable of a function that belongs to another .py file, and have it display on the .py file I am working on. For example: I want my file test2.py to only display the variable three which belongs to the secondmain() function inside the program test.py Assuming that the variable three is a fixed local variable for test.py (meaning that making it global variable by putting it outside its function might break the code) ehat should I do to make it happen? Is it even a possibility? test.py file: import test2 def main(): &lt;-- able to access two = '2' print("the letter " + two) def secondmain(): three = '3' &lt;-- wants to access print("toying") print("dancing") print("testing") print(main()) test2.py file: import test print('testing something') test.main() # accessing the main() function of test.py # accessing second main but wants to JUST access its variable three. # test.secondmain().three???
has comment: http://stackoverflow.com/comment/90325467
has comment: http://stackoverflow.com/comment/90325026
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10139866
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90324866
has comment: http://stackoverflow.com/comment/90325623

http://stackoverflow.com/q/51757735
upvote count: 3
tagged with: pandas
tagged with: python-3.x
type: UnansweredQuestion
has title: How to read excels merged header cells in pandas properly
tagged with: python
linked to: http://stackoverflow.com/q/41251922
tagged with: excel
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90475141
has answer: http://stackoverflow.com/a/51757852
type: Question
answer count: 1
favorite count: 0
has body: How to read excels merged header cells as shown below in Pandas such that Frequency header can show up like Frequency_1, Frequency_2, Frequency_3 I am currently reading it as data = (pandas.read_excel(excelfilename, sheetname, header)).values while data read is correct but I end-up with header as ['Frequency' nan nan]
duplicate of: http://stackoverflow.com/q/41251922

http://stackoverflow.com/comment/90453206
comment on: http://stackoverflow.com/a/51746560
score: 0
type: AnswerComment
type: Comment
has text: @Ajay_Gupta Thank you again for your response! What exactly do you mean by this being pseudo code?

http://stackoverflow.com/a/51705799
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51702570
has body: Make sure that you have all files and directory that have before in initial project root directory. also check .gitignore file in the repository
answers question: http://stackoverflow.com/q/51702570

http://stackoverflow.com/comment/90456017
type: QuestionComment
comment on: http://stackoverflow.com/q/51746726
has text: Could you gives more details about the mathematical definition of the integration with complex bounds? I don't think the formula `exp(-t)/t` is actually used for the complex case, I am trying to make sense of the [Incomplete_gamma_function](https://en.wikipedia.org/wiki/Incomplete_gamma_function). `quad` will not work with complex argument: an integration path have to be defined (or an area) on the complex plane...
score: 0
type: Comment

http://stackoverflow.com/a/51772106
upvote count: 2
has body: You should change batch.clear() to batch = []. That is because .clear() clear the list and all the variables that point that list become [], on other way batch = [] just create a new list and assign it to batch
downvote count: 0
answers question: http://stackoverflow.com/q/51771859
type: Answer
score: 2

http://stackoverflow.com/a/51787687
has body: You could do In [384]: date = df.index.get_level_values('Date') In [385]: firstweek = date.to_frame().groupby(date.strftime('%Y-%m')).min()['Date'] In [386]: df[date.isin(firstweek)] Out[386]: Col Date Thing 2018-01-07 A 10 B 11 2018-02-04 I 18 J 19 2018-03-04 G 26 H 27 Details In [387]: date.to_frame().groupby(date.strftime('%Y-%m')).min() Out[387]: Date 2018-01 2018-01-07 2018-02 2018-02-04 2018-03 2018-03-04 Alternative. In [400]: fweek = df.assign(dt=date).resample('M', level='Date')['dt'].min() In [401]: df[date.isin(fweek)] Out[401]: Col Date Thing 2018-01-07 A 10 B 11 2018-02-04 I 18 J 19 2018-03-04 G 26 H 27
upvote count: 1
has comment: http://stackoverflow.com/comment/90532740
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51787441
has comment: http://stackoverflow.com/comment/90532772
answers question: http://stackoverflow.com/q/51787441
has comment: http://stackoverflow.com/comment/90532557
type: Answer
score: 1

pyqt4
tags question: http://stackoverflow.com/q/51722119
tags question: http://stackoverflow.com/q/51770282
tags question: http://stackoverflow.com/q/51763182
tags question: http://stackoverflow.com/q/51791042
type: Tag
tags question: http://stackoverflow.com/q/51690775
tags question: http://stackoverflow.com/q/51664300
tags question: http://stackoverflow.com/q/51741851
tags question: http://stackoverflow.com/q/51767548
tags question: http://stackoverflow.com/q/51687692
tag name: pyqt4

http://stackoverflow.com/a/51674999
answers question: http://stackoverflow.com/q/51674903
type: Answer
upvote count: 2
score: 2
has body: I believe this is because Python is using a native version of JSON scanner, so you can't use the Python debugger. See json/scanner.py: try: from _json import make_scanner as c_make_scanner except ImportError: c_make_scanner = None If the C / native version is not available, a fallback version written in Python is used instead (also defined in the file linked above).
downvote count: 0

http://stackoverflow.com/comment/90423856
type: AnswerComment
comment on: http://stackoverflow.com/a/51731489
has text: You should use `isinstance` (it supports inheritance correctly, for example), the OP's problem with using the correct tool is still unclear.
type: Comment
score: 2

http://stackoverflow.com/q/51721561
has comment: http://stackoverflow.com/comment/90403650
possible better answer: http://stackoverflow.com/a/51722252
has answer: http://stackoverflow.com/a/51723392
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/62688786
linked to: http://stackoverflow.com/q/1769403
has comment: http://stackoverflow.com/comment/90403655
type: Question
accepted answer: http://stackoverflow.com/a/51723392
score: 3
has body: I have 4 classes with several methods in each of them. I need these methods to use some class variables as arguments, eg. class Orange: def __init__(self,banana): self.banana = banana def apple(self,fruit=self.banana): return something I already found out that this does not work as method arguments are defined when function is created, not when it is called, so i found a workaround here: def apple(self,fruit=None): if fruit is None: fruit = self.banana But the problem is, that i have about 50 arguments (no in each method, but summary from all methods of all classes) and using this method, i would get about one hundred new lines of code and that seems to me like very "dirty" workaround... isnt there any easier way how to reach that?
tagged with: function
has comment: http://stackoverflow.com/comment/90403713
tagged with: class
has comment: http://stackoverflow.com/comment/90403842
answer count: 3
has answer: http://stackoverflow.com/a/51722252
downvote count: 0
has title: self is not defined in class method argument
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/67726016
score: 1
upvote count: 1
has body: To save everything into a single file one needs to pass single_file=True as df.to_csv(r'C:\Bla\SubFolder\*.csv', single_file = True)
answers question: http://stackoverflow.com/q/51768081
downvote count: 0
type: Answer

http://stackoverflow.com/q/51642660
score: 2
type: AnsweredQuestion
tagged with: matplotlib
type: Question
upvote count: 2
tagged with: openstreetmap
tagged with: cartopy
has title: Unable to retrieve map tiles at high zoom level (i.e. zoomed out) with Matplotlib/Cartopy/Python
answer count: 1
favorite count: 0
tagged with: python
downvote count: 0
has body: I am creating a mapping application with Python and Cartopy, and attempting to use open-source map tiles for backgrounds, to have more options than the default Cartopy map. It works perfectly for maps that are zoomed in fairly close, but when I try to get a view from a higher elevation, something fails. If I have the zoom set to 11, it works. If I set it to 12, it hangs indefinitely and gives no traceback. Same result with both the OSM and Stamen map servers. Here is a short, self-contained example (note that a line or two may be artifacts from the various ways I've tried this) import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt def custom_background(source_point): source_point = source_point.split(" ") source_point = (float(source_point[0]), float(source_point[1])) dx = 1.5 dy = 1.5 lon_min, lon_max = source_point[0]-dx, source_point[0]+dx lat_min, lat_max = source_point[1]-dy, source_point[1]+dy zoom = 7 map_url = "https://www.openstreetmap.org/#map={}/{}/{}".format(zoom,source_point[0],source_point[1]) tile = cimgt.OSM(url=map_url) tile = cimgt.StamenTerrain() ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([lat_min, lat_max, lon_min, lon_max]) ax.add_image(tile, zoom) #~ ax.add_image(tile) return ax custom_background("45.068466 -66.45477") plt.savefig("tile.png") the result, with zoom = 7: but if I were to change zoom to say, 14, the program will not complete no matter how long I allow it to run. The url parameter that is passed to cimgt.OSM() is optional. I get the same result with or without it. (See: https://scitools.org.uk/cartopy/docs/v0.16/cartopy/io/img_tiles.html#cartopy.io.img_tiles.OSM) Am I missing something here? Any help would be appreciated, thank you.
has answer: http://stackoverflow.com/a/51648598
accepted answer: http://stackoverflow.com/a/51648598
tagged with: gis

http://stackoverflow.com/a/51693137
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51693024
upvote count: 1
answers question: http://stackoverflow.com/q/51693024
type: AcceptedAnswer
downvote count: 0
has body: You can use any() and check if any neighbour is in your watch_list: adjacent = [] for i in source: if any(x in watch_list for x in list(nx.all_neighbors(G, i))): adjacent.append('Y') else: adjacent.append('N') print(adjacent) Result: ['Y', 'Y', 'Y', 'N', 'Y', 'Y', 'Y', 'Y']

http://stackoverflow.com/comment/90297975
comment on: http://stackoverflow.com/q/51667585
score: 0
type: Comment
type: QuestionComment
has text: Please add a minimal example so that we may reproduce your error.

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/51736907

http://stackoverflow.com/q/51726978
has body: I'm trying to learn how I can stretch the width of my plot both when showing (plt.show()) it and saving (plt.savefig) it. More precisely, the plot has two y-axes that I have written as follows: fig , ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(x,y) ax2.plot(x,y2) plt.show() Now the question is, how can I specify the size of the plot, e.g., how do we stretch the width/height? When using plt.show() and the plot appears, I can manually take one corner and resize the box however desired, but that manually customised size will not be the saved one.
has answer: http://stackoverflow.com/a/51727132
score: 1
upvote count: 1
type: Question
tagged with: matplotlib
tagged with: figure
accepted answer: http://stackoverflow.com/a/51727132
linked to: http://stackoverflow.com/q/332289
has title: Stretching figure size in a double-y plot
duplicate of: http://stackoverflow.com/q/332289
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90331514
has text: @Neil - Your `list comprehension` loop by columns names, in my sample `A, B, C, D, E`, so it cannot work.
type: Comment
comment on: http://stackoverflow.com/a/51684628
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90512967
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51776808
score: 0
has text: It seems this is related to how buttons work, as whenever i pass it through the query string by itself it does not ignore the value.

http://stackoverflow.com/comment/90497813
type: AnswerComment
score: 0
has text: Thanks Kostadin Slavov but Kurdish is not supported from django,there is no po file for kurdish.Wenn i add the LANGUAGE_CODE = 'ku' and run the manage.py makemessages receive some error. raise ValueError('invalid token in plural form: %s' % value) ValueError: invalid token in plural form: EXPRESSION
type: Comment
comment on: http://stackoverflow.com/a/51766611

http://stackoverflow.com/a/51779519
has body: Please consider to delete the line 3 in the first snippet. That has overwritten your dd whose type is defaultdict.
answers question: http://stackoverflow.com/q/51779236
upvote count: 1
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/114708755
comment on: http://stackoverflow.com/a/51716940
type: Comment
score: 2
has text: @TimPeters I've understood that the module level `__all__` is intended to advertise public names, and some extra names in containing scopes doesn't really harm anything. As for "why not", the style guide does say *Imports are always put at the top of the file* but I think the more important reason is for code to be up-front about their dependencies. That makes browsing a large code-base easier, and during testing it means mocking/patching a dependency from the module namespace is simpler.
type: AnswerComment

http://stackoverflow.com/q/51702859
has body: I'm getting an errors VIDEOIO ERROR: V4L2: Pixel format of incoming image is unsupported by OpenCV Unable to stop the stream: Device or resource busy VIDEOIO ERROR: V4L: can't open camera by index 0 when trying to run a code import time import datetime import cv2 import boto3 rekog = boto3.client('rekognition') video = cv2.VideoCapture(0) class VideoCamera(object): def __init__(self): # Using OpenCV to capture from device 0. If you have trouble capturing # from a webcam, comment the line below out and use a video file # instead. # self.video = cv2.VideoCapture(0) # If you decide to use video.mp4, you must have this file in the folder # as the main.py. # self.video = cv2.VideoCapture('video.mp4') print('camera loaded') def __del__(self): self.video.release() def get_frame(self): # success, image = self.video.read() success, image = video.read() overlay = image.copy() overlayTxt = image.copy() h, w = image.shape[:2] regImg = cv2.resize(image, (int(0.2 * w), int(0.2 * h))) _, newjpeg = cv2.imencode('.jpg', regImg) imgbytes = newjpeg.tobytes() t0 = time.time() resp = rekog.detect_labels(Image={'Bytes': imgbytes}) cv2.rectangle(overlay, (10, 10), (300, 50 + 50 * len(resp['Labels'])), (0, 0, 0), -1) alpha = 0.3 cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image) cnt = 1 now = str(datetime.datetime.now()) cv2.putText(image, now, (20, 40 * cnt), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) cnt = cnt + 1 for label in resp['Labels']: outTxt = label['Name'] + ' (' + str(int(label['Confidence'])) + '%)' cv2.putText(image, outTxt, (20, 40 * cnt), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 1) cnt = cnt + 1 # We are using Motion JPEG, but OpenCV defaults to capture raw images, # so we must encode it into JPEG in order to correctly display the # video stream. ret, jpeg = cv2.imencode('.jpg', image) t0 = time.time() resp = rekog.detect_labels(Image={'Bytes': imgbytes}) print("{} ---> {}".format((time.time() - t0), resp["Labels"])) return jpeg.tobytes() camera is w…
type: UnansweredQuestion
type: Question
tagged with: opencv
has title: opencv-python camera read erroes
answer count: 1
has answer: http://stackoverflow.com/a/52903248
score: 0
tagged with: python

http://stackoverflow.com/q/51748625
downvote count: 2
has comment: http://stackoverflow.com/comment/90895493
tagged with: python
answer count: 1
tagged with: phase
has comment: http://stackoverflow.com/comment/90457153
score: 0
tagged with: unwrap
type: UnansweredQuestion
has title: Python Numpy Unwrap function does not work as intended
has answer: http://stackoverflow.com/a/51972513
tagged with: ads
favorite count: 0
has body: I went through an ordeal with numpy.unwrap() function and came to realize it does not work as intended. Comparing the function to ADS unwrap function proved this. I'm sure it works when working with radians. But when working in degrees, it does not. Even when passing a discount with a conversion to degrees, it's output is no where correct. So be aware of this if you are using this function intended with degrees. I am currently seeking a solution.
tagged with: degrees
type: Question
upvote count: 2

http://stackoverflow.com/q/51731301
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/90423752
tagged with: python
accepted answer: http://stackoverflow.com/a/51731489
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90423367
linked to: http://stackoverflow.com/q/16151402
downvote count: 1
type: Question
has body: I have a mixture of datetime.datetime and datetime.time objects so I cannot use isinstance because isinstance throws an error if the object is datetime.datetime. So I need to use the type function. If I have the following: &gt;&gt;&gt;type(tim1) &lt;class 'datetime.datetime'&gt; Then how do I get: assert type(tim1) == '&lt;class "datetime.datetime"&gt; to output True.?
upvote count: 0
has comment: http://stackoverflow.com/comment/90423885
has answer: http://stackoverflow.com/a/51731489
has title: How do you use the type function to return a boolean value in Python
has comment: http://stackoverflow.com/comment/90423425
has comment: http://stackoverflow.com/comment/90423897
answer count: 1
has comment: http://stackoverflow.com/comment/90423796

http://stackoverflow.com/comment/90359082
has text: An easy mistake to make. In general parlance for embedded systems, code you write and compile on a "development machine" runs on a "target". Go ahead and accept your own answer, so people will see that the question has an accepted answer. And welcome to StackOverflow.
comment on: http://stackoverflow.com/a/51689440
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51729287
type: Answer
has body: You can use a slice of the list after the first element and do this with zip &gt;&gt;&gt; x=["A", "B", "B", "C", "B", "A", "D", "D", "A", "B", "A", "D"] &gt;&gt;&gt; [list(a) for a in zip(x,x[1:])] [['A', 'B'], ['B', 'B'], ['B', 'C'], ['C', 'B'], ['B', 'A'], ['A', 'D'], ['D', 'D'], ['D', 'A'], ['A', 'B'], ['B', 'A'], ['A', 'D']]
has comment: http://stackoverflow.com/comment/90419500
answers question: http://stackoverflow.com/q/51729217
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/51671049
type: AcceptedAnswer
has body: Here you have and example that produces 10%....100% without the need for the if series target_percent = 10 total_size = 1000 for bytes_so_far in range(1, 1000): percent = float(bytes_so_far) / total_size percent = round(percent*100) if percent &gt;= target_percent: print("%0.0f%%\r" % (percent)) target_percent += 10 you get: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% This can be organized inside a function: def get_percent(bytes_so_far, total_size, status): percent = float(bytes_so_far) / total_size percent = round(percent*100) if percent &gt;= status: print("%0.0f%%\r" % (percent)) status += 10 return status If we mock a repeated call to this function: size = 1000 status = 10 for bytes_so_far in range(1, 1000): status = get_percent(bytes_so_far, size, status) we get again: 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
type: Answer
has comment: http://stackoverflow.com/comment/90305621
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90330809
answers question: http://stackoverflow.com/q/51670873
has comment: http://stackoverflow.com/comment/90306457
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51670873

http://stackoverflow.com/comment/90366538
type: Comment
type: QuestionComment
score: 0
has text: Have you tried using [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/)?
comment on: http://stackoverflow.com/q/51702533

http://stackoverflow.com/q/51646226
score: -1
has comment: http://stackoverflow.com/comment/90256971
has comment: http://stackoverflow.com/comment/90256244
has answer: http://stackoverflow.com/a/51678844
downvote count: 2
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a string that looks something like this - ((COL1==VAL1)+(COL2==VAL2)) I want to convert this to following format: ((a.col1 == 'VAL1') &amp; (a.col2 == 'VAL2')) Another example - From: ((COL1==VAL1)|(COL2==VAL2/A)) TO: ((a.col1 == 'VAL1') | (a.col2 == 'VAL2/A')) can someone help please? Code: word = Word(alphas + alphanums + "+-_&lt;&gt; ") open = Literal('(') close = Literal(')') single_quote = Literal('\'') and_ = Literal('+') equal = Literal('=') comma = Literal(',') or_ = Literal('|') right_hand_value = word left_hand_value = word func = OneOrMore(open) + left_hand_value + OneOrMore(equal) + right_hand_value + OneOrMore(close) results = func.parseString(string) This kind of works only for one expression: (a.col1 == 'VAL1'). but I want this to handle multiple expressions.
has comment: http://stackoverflow.com/comment/90256982
type: UnansweredQuestion
has title: pyparsing - String parsing to generate Where clause
tagged with: python
tagged with: pyparsing
type: Question

http://stackoverflow.com/a/51679484
upvote count: 5
has comment: http://stackoverflow.com/comment/90322211
has body: After performing tr=utf_string.encode('utf8'), tr is a bytes object. Methods on bytes objects expect bytes arguments, not str arguments. So you need to make the arguments to replace bytes literals, using the b prefix (you don't need the r prefix here; it's not a regex, and there are no backslashes in it in any event): tr = tr.replace(b',', b'')
downvote count: 0
has comment: http://stackoverflow.com/comment/90322294
type: Answer
answers question: http://stackoverflow.com/q/51679457
score: 5

http://stackoverflow.com/a/51692973
has comment: http://stackoverflow.com/comment/90347384
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51692893
has body: If you want to get the position of the text in parentheses, you need to specify that you're matching the first group as an argument to span(): sent = "Sales to two of the segment's customers, The Home Depot and Lowe's Home Improvement Warehouse, accounted for greater than 10% of the Corporation's consolidated sales for 2004, 2003, and 2002." regex_ = re.compile("Sales to two of the segment's customers, The (Home Depot) regex_.search(sent).span(1) See the python documentation on match objects and span.
score: 2
downvote count: 0

http://stackoverflow.com/q/51744613
tagged with: numpy
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
has title: NumPy setdiff1d with tolerance - Comparing a numpy array to another and saving only the unique values - outside of a tolerance
accepted answer: http://stackoverflow.com/a/51747164
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 3
type: Question
score: 3
has body: I have two numpy arrays: A= [ 3.8357 3.2450] B= [ 5.6132 3.2415 3.6086 3.5666 3.8769 4.3587] I want to compare A to B and only keep the value in A that is unique - outside of a +/-0.04 tolerance (i.e. A=[3.8357]). Any ideas as to how I can do this?
has answer: http://stackoverflow.com/a/51747164

http://stackoverflow.com/comment/95136349
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51716364
has text: Urgh, this is probably the new link flags, will fix - - can you make an issue on https://github.com/deadsnakes/issues

http://stackoverflow.com/q/51701737
tagged with: python
has comment: http://stackoverflow.com/comment/90402430
type: Question
upvote count: 0
score: -2
has body: The following code permanently crashes with "Segmentation fault (core dumped)". It seems that setting the text in the TextInput makes the application crash. Can anyone confirm the error? What does the error message mean? I use threading, because I wanted the user to perform some actions on the screen and the application should wait for the result before going on. Edit: If there was something like a "goto" statement (o.k. sorry for that ;-)) I would like to jump to the line with comment # further commands and proceed there with the main flow. import sys import threading from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import StringProperty, ObjectProperty, BooleanProperty Builder.load_string(""" &lt;MyWordRecorderScreen&gt;: id: TheWordRecorderScreen my_text_input: TheTextInput my_record_button: TheRecordButton BoxLayout: orientation: 'vertical' spacing: 10 MyTextInput: id: TheTextInput my_screen: TheWordRecorderScreen # removing the following statement makes the app work but useless text: "Example" RecordButton: id: TheRecordButton text: "Record" my_screen: TheWordRecorderScreen size_hint: (0.2, 0.15) """) class MyTextInput(TextInput): pass class RecordButton(Button): my_screen = ObjectProperty(None) class MyWordRecorderScreen(Screen): my_record_button = ObjectProperty(None) my_text_input = ObjectProperty(None) class MyScreenSequence(): def __init__(self,my_screenmanager): self.sm=my_screenmanager def do_job(self): self.CurrentScreen = MyWordRecorderScreen() self.sm.switch_to(self.CurrentScreen) def ApplicationFlow(MyScreenManager, *largs): sm = MyScreenManager screen_terminated=threading.Condition() screen_terminated.acquire() # subroutine will use screen_terminated.notify_all() once result is available MSS=MyScreenSequence(my_screenmanager=sm) t2 = threading.Thread(t…
has comment: http://stackoverflow.com/comment/90380110
has comment: http://stackoverflow.com/comment/90364656
has comment: http://stackoverflow.com/comment/90402124
answer count: 1
tagged with: kivy
favorite count: 0
has title: Kivy app permanently crashes with "Segmentation fault (core dumped)"
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90402862
downvote count: 2
has answer: http://stackoverflow.com/a/51728014

http://stackoverflow.com/comment/90485978
comment on: http://stackoverflow.com/q/51763581
score: 1
has text: That is not valid JSON. Do you mean `{"message": "// System...", "category": "Poor..."}`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/101537475
type: Comment
has text: Thank you. It worked. I had created and env and I got this error resolved with the command conda update --all. Cheers
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/53637013

http://stackoverflow.com/a/51752698
has body: First, to do what you want is trivial. When you import a module, there’s only a single instance of that module object shared by anyone else who imports it,1 and that module object’s attributes are just the module’s globals. So: # script.py import cheese import eggs cheese.beans = 10 eggs.dostuff() # eggs.py import cheese print(cheese.beans) print(cheese.ham) # cheese.py ham = 20 If you run script.py, it will print 10, then 20. You do of course have to be careful with top-level module code, which gets run in the order the modules are first imported (which can be tricky to work out),2 and with code in the script (which should never be imported as a module by anyone else)3, but otherwise, it just works, without needing any special getter and setter functions. (If you do for some reason need getter and setter functions, the same getattr and setattr that work for any object work just fine on module objects.) And now, how does logging do its magic? Simple; it just stores a dict in its globals. Since there’s only one instance of the module, there’s only one instance of its globals, and therefore only one instance of the dict. 1. If you want to know how that works under the covers… When you execute import cheese, what Python does (by default, assuming you haven't installed any weird import hooks) is: first, is there a sys.modules['cheese']? If not, find the spec for cheese, use it to find a loader, use the loader to load the code, exec the code, and store the result as sys.modules['cheese']. Then just return sys.modules['cheese']. This is why each module only gets its top-level code run once, no matter how many times you import it, and it's also why everyone who imports it shares the same copy of the module object. 2. Your example just works with my_module.my_value = 42 and print(my_module.myvalue)—if foo gets imported before bar. But if bar gets imported first, it will get an AttributeError, because obviously nobody has set my_module.my_value yet. 3. The main reason is tha…
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51752447
answers question: http://stackoverflow.com/q/51752447
has comment: http://stackoverflow.com/comment/90481819
type: Answer
upvote count: 1
score: 1

ttk
tags question: http://stackoverflow.com/q/51783460
tags question: http://stackoverflow.com/q/51762835
type: Tag
tags question: http://stackoverflow.com/q/51720962
tag name: ttk

http://stackoverflow.com/comment/90299411
comment on: http://stackoverflow.com/q/51668214
score: 0
type: QuestionComment
type: Comment
has text: try this `sudo curl https://bootstrap.pypa.io/get-pip.py | python` then `pip install -r requirements.txt`

http://stackoverflow.com/q/51777495
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51777750
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping
upvote count: 1
tagged with: python-requests
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51777750
tagged with: .aspxauth
has title: Logging into website and scraping data
has comment: http://stackoverflow.com/comment/90513202
score: 0
has body: The website I am trying to log in to is https://realitysportsonline.com/RSOLanding.aspx. I can't seem to get the login to work since the process is a little different to a typical site that has a login specific page. I haven't got any errors, but the log in action doesn't work, which then causes the main to redirect to the homepage. import requests url = "https://realitysportsonline.com/RSOLanding.aspx" main = "https://realitysportsonline.com/SetLineup_Contracts.aspx?leagueId=3000&amp;viewingTeam=1" data = {"username": "", "password": "", "vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-3d vc_btn3-color-danger" : "Log In"} header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'Referer': 'https://realitysportsonline.com/RSOLanding.aspx', 'Host': 'realitysportsonline.com', 'Connection': 'keep-alive', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'} s = requests.session() s.get(url) r = s.post(url, data, headers=header) page = requests.get(main)
answer count: 1

hdf5storage
tags question: http://stackoverflow.com/q/51670371
tag name: hdf5storage
type: Tag

http://stackoverflow.com/q/51679898
has answer: http://stackoverflow.com/a/51681149
score: 1
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90323127
has answer: http://stackoverflow.com/a/51680538
tagged with: arrays
downvote count: 0
has body: Energy calculations in molecular simulation are inherently full of "for" loops. Traditionally coordinates for each atom/molecule were stored in arrays. arrays are fairly straightforward to vectorize, but structures are nice to code with. Treating molecules as individual objects, each with their own coordinates, and other properties, is very convenient and much clearer as far as book-keeping goes. I am using Python version 3.6 My problem is that I cannot figure out how to vectorize calculations when I am using an array of objects... it seems that a for loop cannot be avoided. Is it necessary for me to use arrays in order to take advantage of numpy and vectorize my code? Here is a python example which utilizes arrays (line 121 of the code), and shows a fast (numpy) and slow ( 'normal') python energy calculation. https://github.com/Allen-Tildesley/examples/blob/master/python_examples/mc_lj_module.py The calculation is much faster using the numpy accelerated method because it is vectorized. How would I vectorize an energy calculation if I was not using arrays, but an array of objects, each with their own coordinates? This seems to necessitate using the slower for loop. Here is a simple example code with a working slow version of the for loop, and an attempted vectorization that doesn't work: import numpy as np import time class Mol: num = 0 def __init__(self, r): Mol.num += 1 self.r = np.empty((3),dtype=np.float_) self.r[0] = r[0] self.r[1] = r[1] self.r[2] = r[2] """ Alot more useful things go in here in practice""" ################################################ # # # Main Program # # # ################################################ L = 5.0 # Length of simulation box (arbitrary) r_cut_box_sq = L/2 # arbitrary cutoff - required mol_list=[] nmol = 1000 # number of molecules part = 1 # arbitrary molecule to interact with rest of molecules """ make 1000 molecules (1 atom per molecule), give random coordinates """ for i in range(nmol): r = np.random.rand(3) * L mol_list…
has comment: http://stackoverflow.com/comment/90323062
tagged with: python
has comment: http://stackoverflow.com/comment/90323032
favorite count: 0
accepted answer: http://stackoverflow.com/a/51680538
upvote count: 1
has title: Structuring a list of objects in python for vectorization: Can a list of structures(objects) be vectorized, or are explicit arrays required
tagged with: vectorization
has comment: http://stackoverflow.com/comment/90324207
possible better answer: http://stackoverflow.com/a/51681149
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90323078

http://stackoverflow.com/comment/90473650
type: QuestionComment
comment on: http://stackoverflow.com/q/51756910
score: 0
has text: So you set `JAVA_HOME`, but the error with `javabridge` still remains?
type: Comment

http://stackoverflow.com/comment/90343923
type: AnswerComment
comment on: http://stackoverflow.com/a/51691111
type: Comment
has text: If I enter all even numbers this will not work, you need to change `if user_input is None:` to `if largest_odd is None:`
score: 0

http://stackoverflow.com/q/51700053
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51700116
tagged with: werkzeug
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
duplicate of: http://stackoverflow.com/q/46280558
has title: Flask werkzeug.exceptions.BadRequestKeyError
has comment: http://stackoverflow.com/comment/90361550
type: Question
has body: I've tried several different flask apps and get the following error every time. werkzeug.exceptions.BadRequestKeyError werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'name' I can't figure out why. It must be something with my setup because the same thing is happening in different applications. I set up a very simple model with minimal code to demonstrate. If I remove the name key I get the same error with the number1 key. And I can't find anything on what this error even means. app.py from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flow.sqlite3' db = SQLAlchemy(app) from routes import * if __name__ == '__main__': # db.drop_all() db.create_all() app.run() routes.py from flask import render_template, request from app import app, db from models import Info @app.route('/', methods=['GET', 'POST']) def index(): data = Info(request.form['name'], request.form['number1'], request.form['number2']) db.session.add(data) db.session.commit() return render_template('index.html', data=data) models.py from app import db class Info(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) number1 = db.Column(db.Integer) number2 = db.Column(db.Integer) def __init__(self, name, number1, number2): self.name = name self.number1 = number1 self.number2 = number2 index.html Name: Number 1: Number 2: Submit
tagged with: flask
linked to: http://stackoverflow.com/q/46280558
answer count: 1

http://stackoverflow.com/a/51676622
has comment: http://stackoverflow.com/comment/90319335
upvote count: 1
type: Answer
downvote count: 0
has body: Before answering the question, I must advise that a Linear Regression, especially this specific Linear Regression, is a very simplistic modeling method for stock prices that may not have a huge upside in terms of accuracy. This specific script from Kaggle is trying to find a correlation between a stock price and its price exactly 30 days prior. In the example on Kaggle, we can notice that their X variable is pulled straight from df'Adj Close' while their Y variable is a shifted form of that column that they called label (which is your df'prediction') When you set X equal to df.drop(["prediction"],1) in line 3, you are setting X equal to the entirety of all the other columns in the data frame (this is wrong). tl;dr: The example regression script on Kaggle works, but the underlying financial theory is unsound. Your code has some key differences from the example script that may cause (un)foreseen errors.
answers question: http://stackoverflow.com/q/51674644
score: 1
has comment: http://stackoverflow.com/comment/90383975

http://stackoverflow.com/a/51725178
type: Answer
has comment: http://stackoverflow.com/comment/90412065
score: 1
upvote count: 1
has body: You could do so: paths='/notpath/exclude&gt;/ev/path1&gt;/ev/path2&gt;' f_paths = paths.split('&gt;')[1:-1] Output: ['/ev/path1', '/ev/path2']
answers question: http://stackoverflow.com/q/51725028
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51725028
downvote count: 0

http://stackoverflow.com/q/51779134
has answer: http://stackoverflow.com/a/51781231
tagged with: python
has comment: http://stackoverflow.com/comment/90516697
type: AnsweredQuestion
has body: I have a dataframe like this A B 2018-02-01 00:00:00 5.592860 2.789900 2018-02-01 00:15:00 5.288981 2.054017 2018-02-01 00:30:00 5.319665 2.232686 2018-02-01 00:45:00 5.198657 2.236154 2018-02-01 01:00:00 5.018134 2.064312 The Column A will not have any missing values, but column B will be having. I have another list like this of length 12 named forecasts [0.09545173 0.09946214 0.10596157 0.12075519 0.14446978 0.16848372 0.20479251 0.23742175 0.26723814 0.29389328 0.30628437 0.3140854 ] I want to loop through each row in the dataframe and check whether next 12 rows have any nan. If nan is present, replace that value from the corresponding index from the list. If the 2nd row from the current index is nan then replace that nan by forecasts[2] To make things more clear, I will have a dataframe with data like I said the question. There may be misses in the column B but not A. I will have a list of 12 location for each timestamp. The list being named forecast will have the forecasted value of present timestamp in forecasts[0] and 11th timestamp from now in forecast[11]. I want to loop though each timestamp in the dataset, check whether any nan is present in the next 12 locations of the dataframe in the column B. If there are nan, then replace it with the forecast. How can I do this easily with pandas.?
has answer: http://stackoverflow.com/a/51779152
has answer: http://stackoverflow.com/a/51779192
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90516205
possible better answer: http://stackoverflow.com/a/51779192
has comment: http://stackoverflow.com/comment/90516373
accepted answer: http://stackoverflow.com/a/51779152
has comment: http://stackoverflow.com/comment/90516404
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/90516341
has comment: http://stackoverflow.com/comment/90516478
favorite count: 0
has title: Replace missing values from list in Pandas

http://stackoverflow.com/q/51646271
tagged with: client
favorite count: 0
upvote count: 1
type: AnsweredQuestion
tagged with: server
has body: Could you please help....I'm really struggling. I can't invoke both functions in server from the client side by below program.Help me to understand how to invoke multiple functions in server from client.Thanks in advance Server.py #!/usr/bin/env python from twisted.spread import pb from twisted.internet import reactor class Main(pb.Root): def remote_name(self,idno): print'Id NO:', idno def num(idno): switcher={ 1:'\t\tFirst', 2:'\t\tSecond', 3:'\t\tThird', } return switcher.get(idno, 'Invalid Number') print num(idno) def remote_hello(self, st): print'From Client:', st return st if __name__=='__main__': reactor.listenTCP(5000,pb.PBServerFactory(Main())) reactor.run() Client.py #!/usr/bin/env python from twisted.spread import pb from twisted.internet import reactor def main(): f = pb.PBClientFactory() reactor.connectTCP('localhost',5000,f) d=f.getRootObject() print 'Enter ID No:' no=input() d.addCallback(lambda new:new.callRemote('name',no)) d.addCallback(lambda obj:obj.callRemote('hello', 'hello world')) reactor.run() if __name__=='__main__': main() If i try to execute this, remote_name function only executed.There is no response from remote_hello function.This is my problem.
score: 1
has answer: http://stackoverflow.com/a/51651512
type: Question
tagged with: twisted
tagged with: function
answer count: 1
downvote count: 0
has title: Python Twisted in PB, server client function invoking
accepted answer: http://stackoverflow.com/a/51651512
tagged with: python

http://stackoverflow.com/comment/90316930
score: 0
type: AnswerComment
has text: Can you also print lstA and lstB and take screenshots?
type: Comment
comment on: http://stackoverflow.com/a/51674874

http://stackoverflow.com/comment/90315309
has text: Woah! I can't believe i missed such a simple thing! Thanks alot!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51675958
type: Comment

http://stackoverflow.com/q/51683471
has comment: http://stackoverflow.com/comment/90329695
score: 1
has comment: http://stackoverflow.com/comment/90329584
accepted answer: http://stackoverflow.com/a/51695373
tagged with: tensorflow
type: Question
has body: I'm building a model in keras that detects building rooftops from images. I want to add a custom sharpening layer inside model. I know we can sharpen images in preprocessing, but it would be nice if i add a layer. I tried Lambda layer with my custom sharpening function but it didn't worked, then i tried a custom layer and got the same error: TypeError Traceback (most recent call last) &lt;ipython-input-5-3062d6b8160d&gt; in &lt;module&gt;() 1 # MY MODEL 2 from u_net import mymodel300 ----&gt; 3 model = mymodel300((300, 300, 3)) ~\Desktop\SAVERA\MYCODE\u_net.py in mymodel300(input_shape) 186 # LAYERS 187 inputs = Input(shape=input_shape) --&gt; 188 sharp = Sharpen(num_outputs=(300,300,3))(inputs) 189 # 300x300 190 ~\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs) 701 702 if not in_deferred_mode: --&gt; 703 outputs = self.call(inputs, *args, **kwargs) 704 if outputs is None: 705 raise ValueError('A layer\'s `call` method should return a Tensor ' ~\Desktop\SAVERA\MYCODE\u_net.py in call(self, input_) 179 kernel_sharp = np.array(([-2, -2, -2], [-2, 17, -2], [-2, -2, -2]), dtype='int') 180 #denoised = cv2.fastNlMeansDenoisingColored(img,None,5,5,2,10) --&gt; 181 self.sharp = cv2.filter2D(input_, -1, kernel_sharp) 182 return self.sharp 183 TypeError: src is not a numpy array, neither a scalar Here is my custom layer: from tensorflow.keras.layers import Layer from tensorflow.keras import backend as K # CUSTOM SHARPEN LAYER class Sharpen(Layer): def __init__(self, num_outputs): super(Sharpen, self).__init__() self.num_outputs = num_outputs def call(self, input_): import numpy as np import cv2 # SHARPEN kernel_sharp = np.array(([-2, -2, -2], [-2, 17, -2], [-2, -2, -2]), dtype='int') #denoised = cv2.fastNlMeansDenoisingColored(img,None,5,5,2,10) self.sharp = cv2.filter2D(input_, -1, kernel_sharp) return self.sharp Here is the model where i want to put this layer: def mymodel300(input_shape=(300, 300, 3)): inp…
answer count: 2
downvote count: 0
tagged with: neural-network
tagged with: keras
favorite count: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90329779
tagged with: python
has title: How to add custom image sharpening layer in keras?
has answer: http://stackoverflow.com/a/51683552
has answer: http://stackoverflow.com/a/51695373
has comment: http://stackoverflow.com/comment/90329711
possible better answer: http://stackoverflow.com/a/51683552
has comment: http://stackoverflow.com/comment/90329768
has comment: http://stackoverflow.com/comment/90329728
upvote count: 1
has comment: http://stackoverflow.com/comment/90329627
type: AnsweredQuestion

http://stackoverflow.com/comment/90494419
type: QuestionComment
has text: I'm curious why you do not want to use QMainWindow ?, I just checked the source code of QMainWindow and it has a custom layout.
comment on: http://stackoverflow.com/q/51767548
score: 0
type: Comment

http://stackoverflow.com/comment/90274671
type: Comment
comment on: http://stackoverflow.com/a/51654536
type: AnswerComment
has text: This takes all possible combination of pairs which is not needed. I need pairs of adjacent integers in the values only... e.g. from `21: [1, 2, 19, 20, 21]`, I need pairs of `[1,2],[2,19],[19,20],[20,21]` ...
score: 0

http://stackoverflow.com/a/51719100
has comment: http://stackoverflow.com/comment/90434206
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90399589
has comment: http://stackoverflow.com/comment/90399731
has comment: http://stackoverflow.com/comment/90399755
has comment: http://stackoverflow.com/comment/90414784
answers question: http://stackoverflow.com/q/51718642
accepted answer of: http://stackoverflow.com/q/51718642
upvote count: 3
has comment: http://stackoverflow.com/comment/90400473
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90400170
has body: Seems you wrongly understand memory consumption definition. Every process (with index i) eats one byte more every d[i] seconds, so it consumes k bytes after k*d[i] seconds. We can say that speed of memory consumption is 1/d[i] bytes/second on the long time interval, but memory consumption rise is discrete. time 0 di 2di 3di mem 0 1 2 3 For example three processes with d = [1,3,2] seconds/byte memory consumption depends on time as: process p0 p1 p2 overall time 0 0 0 0 0 1 1 0 0 1 2 2 0 1 3 3 3 1 1 5 4 4 1 2 7 5 5 1 2 8 6 6 2 3 11 Memory occupied by every process rises step-by-step, but these steps arise on different moments of time (imagine stairs with uneven steps). We can calculate memory consumption for any moment t - just sum memory for all processes OverallMem(t) = t//d[0] + t//d[1] + t//[d[2]+... where // is integer division (div, floor(t/d[i])) Simple way: calculate memory consumption using formula above for t=1, t=2, t=3... and so on until it exceeds X. Works for small X but slow for large X. Python 3 example: def timetodie(lst, x): mem = 0 t = 0 while (mem &lt; x): t += 1 mem = sum(t//v for v in lst) #mem = 0 #for v in lst: #mem += t // v return t print(timetodie([1,3,2], 6)) print(timetodie([2,5,7], 11)) &gt;&gt;4 &gt;&gt;14 Because memory consumption is non-decreasing, we can apply binary search approach to find moment t when OverallMem(t) becomes larger than X. Starting conditions: left border for binary search is 0 rought right border is X * Min(d[i]) More optimal left border proposed by @AJNeufeld: X//sum(1/v for v in lst). Perhaps in this form: math.floor(x / sum(1/v for v in lst)) I hope that this clue is enough to elaborate solution
has comment: http://stackoverflow.com/comment/90399867
type: Answer
has comment: http://stackoverflow.com/comment/90414935
has comment: http://stackoverflow.com/comment/90400543
has comment: http://stackoverflow.com/comment/90400114

http://stackoverflow.com/comment/90537158
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51789837
type: Comment
has text: Where are your 6 and 8 coming from in your expected set? Do you just want a set of all numbers in the flattened input list? In this case `{1, 2, 3, 4}`?

http://stackoverflow.com/comment/90275358
type: AnswerComment
has text: Yes this is what I'm really trying to get at Edward, that specificity is key to debugging. Using specific exceptions will help the OP with knowing what errors to expect in his code and better handle the errors when they arise.
comment on: http://stackoverflow.com/a/51655368
type: Comment
score: 0

http://stackoverflow.com/comment/90255621
score: 2
has text: Getting a "clean array of pixels" is the easy part. Pillow+NumPy will do that just fine. Other libraries could also do it just fine. None of them are going to do it any better than the others; barring the use of image formats they don't support, or bugs, they're all going to give you the exact same array of pixels.
type: Comment
comment on: http://stackoverflow.com/q/51645862
type: QuestionComment

http://stackoverflow.com/comment/90252629
has text: Yes, the default id is 0 when the store has nothing, the add() function then adds the id by 1 if there is a drone added to the store
comment on: http://stackoverflow.com/q/51643904
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90430266
has text: I think within keras and tensorflow the derivation is automatic and cannot be set manually.
type: Comment
comment on: http://stackoverflow.com/q/51733311
score: 0
type: QuestionComment

http://stackoverflow.com/a/51648413
has comment: http://stackoverflow.com/comment/90260314
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51648159
type: AcceptedAnswer
has body: Different approach: df2 = pd.DataFrame() for column in df: df2['{}_pos'.format(column)] = df[column].str[0].astype(int) df2['{}_size'.format(column)] = df[column].str[1].astype(int) print(df2)
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51648159

gunicorn
tags question: http://stackoverflow.com/q/51643559
tags question: http://stackoverflow.com/q/51773930
type: Tag
tags question: http://stackoverflow.com/q/51795093
tag name: gunicorn
tags question: http://stackoverflow.com/q/51664615

http://stackoverflow.com/comment/90468939
score: 0
has text: Python is application code
comment on: http://stackoverflow.com/q/51754338
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51725322
type: UnansweredQuestion
upvote count: 1
has title: Create a dictionary based on same key pairs from dictionary inside a list
downvote count: 1
tagged with: list
type: Question
has body: I have dictionaries inside list as: [{'c1': 'Cars ', 'c2': 'Class', 'keywords': 'muv'}, {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'hatchback'}, {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'suv'}, {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'sedan'}, {'c1': 'Cars ', 'c2': 'Class', 'keywords': 'coupe'}, {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'electric'}, {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'diesel'}, {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'cng'}, {'c1': 'Cars ', 'c2': 'FuelType', 'keywords': 'petrol'}] I want to store values of key keywords into a dictionary for same pair of values for keys c1 and c2 by name of key as c1#c2. So output expected is something like: cars= {'Cars#Class': ['muv','hatchback','suv','sedan','coupe'], 'Cars#FuelType': ['electric','diesel','cng','petrol']} So when I will use cars['Cars#Class'] gives me ['muv','hatchback','suv','sedan','coupe'].
has answer: http://stackoverflow.com/a/51725488
has answer: http://stackoverflow.com/a/51725560
tagged with: arrays
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51725550
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51726052
tagged with: dictionary
has answer: http://stackoverflow.com/a/51725377
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90410870

http://stackoverflow.com/comment/90844059
comment on: http://stackoverflow.com/q/51658120
has text: @CharlesDuffy I guess he is dynamically importing class which is why he may require exec, I am also stuck in the same issue
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51774635
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51708356
upvote count: 1
has body: Below is the code I ended up with. This solution solves my two problems above: 1. It doesn't trigger the tbl_create task if an upstream tasks fail 2. The DAG registers as FAILED if any of the check tasks fail. I feel as though this solution is a little messy and would love suggestions for improvement or ways to make it more "Airflow" from airflow.models import DAG from airflow.models import Variable from airflow.operators.postgres_operator import PostgresOperator from airflow.operators.check_operator import ValueCheckOperator, CheckOperator from airflow.operators.python_operator import BranchPythonOperator from airflow.operators.dummy_operator import DummyOperator from airflow.utils.trigger_rule import TriggerRule from datetime import datetime, timedelta from airflow.hooks.postgres_hook import PostgresHook sql_path = Variable.get('sql_path') default_args = { 'owner': 'enmyj', 'depends_on_past':False, 'email_on_failure': False, 'email_on_retry': False, 'retries': 0 } dag = DAG( 'test', default_args=default_args, schedule_interval=None, template_searchpath=sql_path ) # check number of weeks in bill pay (made up example) check_one = CheckOperator( task_id='check_one', conn_id='conn_id', sql="""select count(distinct field) from dbo.table having count(distinct field) &gt;= 4 """, dag=dag ) def check_two_func(): p = Hook('conn_id') sql="""select count(distinct field) from dbo.table having count(distinct field) &lt;= 100""" count = p.get_records(sql)[0][0] if count == 0: return 'dummy_fail' else: return 'dummy_success' check_two = BranchPythonOperator( task_id = 'check_two', python_callable = check_two_func, dag=dag ) dummy_fail = DummyOperator(task_id='dummy_fail',dag=dag) dummy_success = DummyOperator(task_id='dummy_success',dag=dag) join = DummyOperator(task_id='join',dag=dag) check_one &gt;&gt; check_two check_two &gt;&gt; dummy_fail check_two &gt;&gt; dummy_success ls = ['foo','bar','baz','quz','apple'] for tbl_name in ls: def has_table(tbl_name=tbl_name): p = Postgre…

http://stackoverflow.com/a/51657375
type: AcceptedAnswer
downvote count: 0
has body: Find the 'img' element, in the 'div' element you found, then read the attribute 'src' from it. from bs4 import BeautifulSoup html =""" &lt;html&gt;&lt;body&gt; &lt;div class="style3" id="weather_today_content"&gt; &lt;img alt="" src="/database/img/weather_today.jpg?ver=2018-08-01" style="width: 400px"/&gt; &lt;/div&gt; &lt;/body&gt;&lt;/html&gt; """ soup = BeautifulSoup(html, 'html.parser') weather_today = soup.find("div", {"id": "weather_today_content"}) print (weather_today.find('img')['src']) Outputs: /database/img/weather_today.jpg?ver=2018-08-01
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51657210
accepted answer of: http://stackoverflow.com/q/51657210

http://stackoverflow.com/comment/90375580
has text: Works on Python 3.6 with the input you supplied
comment on: http://stackoverflow.com/a/51707198
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90526015
type: QuestionComment
score: 2
has text: You're only adding the attribute when calling the function. It doesn't exist before you call the function.
comment on: http://stackoverflow.com/q/51784502
type: Comment

http://stackoverflow.com/q/51776259
score: -1
has body: import math user_bin = str while True: try: user_bin = int(input('Please enter binary number: '), 2) except ValueError: print('Please make sure your number contains digits 0-1 only.') if (user_bin) != range(0,256): print('Please make sure your number is 8-bit') else: print(user_bin) I double checked by removing the if and else statement completely and the binary is being converted correctly, yet somehow converting 10101010 into 170 as user_bin, the result of 170 isn't considered within the range and it always prints the message 'Please make sure your number is 8-bit'. I feel like the issue is based around my range function but it could easily be other things. I doubt this is efficiently made so I'm open to any tips beyond just the solution to my question.
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51776305
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/51776305
favorite count: 0
type: Question
has title: Why doesn't "(value) != range(0,256)" detect values outside the range 0-256?
tagged with: python
has comment: http://stackoverflow.com/comment/90511014
has comment: http://stackoverflow.com/comment/90511057

http://stackoverflow.com/q/51662547
has answer: http://stackoverflow.com/a/51666243
has body: Is there a way to truncate datetime to Hour/Day/Week/Month/Year in SQLAlchemy that works for all DBMS (Postgres and SQLite in particular)?
type: AnsweredQuestion
has title: Truncate Hour/Day/Week/Month/Year in SQLAlchemy
linked to: http://stackoverflow.com/q/51660912
tagged with: sqlalchemy
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/51666243
tagged with: sql
tagged with: python

http://stackoverflow.com/a/51732509
answers question: http://stackoverflow.com/q/51732255
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90426521
has body: It sounds like your goal is to write a bash one-liner and then shove it in python, so I'll focus on the bash. I'm assuming your stdout for cmd1 needs to go both to the next command and to a file, and your cmd2 just needs to pass stdout to file. tee is perfect for this. cmd1 | tee /path/to/cmd1file.log | cmd2 &gt; /path/to/cmd2file.log In general, | takes the output of one command and makes in the input for the next command in the line. tee takes input, pushes one copy to stdout and puts one copy somewhere else; in this case, to a log file. &gt; writes the stdout to a file.
has comment: http://stackoverflow.com/comment/90426188
type: Answer
score: 2

http://stackoverflow.com/comment/90527211
has text: U mean to say as asna and awna?
type: Comment
comment on: http://stackoverflow.com/a/51784961
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90294411
type: Comment
type: QuestionComment
has text: You're looking at the wrong answer (of the many). Use https://stackoverflow.com/a/1958228/2681632. The answer you tried is for entities, or in other words model objects.
score: 0
comment on: http://stackoverflow.com/q/51663958

http://stackoverflow.com/comment/90418878
has text: @EdwardMinnix Thanks for your answer. I did not know about the __hash__ method, so thanks for explaining that, which clears up what I suspected would be an issue but wasn't sure why. It is definitely clear to me now why hashing won't work. I hadn't thought of the problems you mention with the sorting algorithm. I think I assumed that the first letters of "similar" words would always be the same so I could 'partial' sort on that, but given the source of my data, while this is very likely to be the case, this is not even necessarily true.
comment on: http://stackoverflow.com/a/51727695
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51709395
tagged with: local-variables
linked to: http://stackoverflow.com/q/633127
tagged with: global-variables
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/10139866
has body: All, I have this request but first I will explain what I'm trying to achieve. I coded a python script with many global variables but also many methods defined inside different modules (.py files). The script sometimes moves to a method and inside this method I call another method defined in another module. The script is quite complex. Most of my code is inside Try/Except so that every time an exception is triggered my code runs a method called "check_issue()" in which I print to console the traceback and then I ask myself if there's any variable's value I want to double check. Now, I read many stackoverflow useful pages in which users show how to use/select globals(), locals() and eval() to see current global variables and local variables. What I would specifically need though is the ability to input inside method "check_issue()" the name of a variable that may be defined not as global and not inside the method check_issue() either. Using classes is not a solution since I would need to change hundreds of lines of code. These are the links I already read: Viewing all defined variables Calling variable defined inside one function from another function How to get value of variable entered from user input? This is a sample code that doesn't work: a = 4 b = "apple" def func_a(): c = "orange" ... check_issue() def check_issue(): print("Something went wrong") var_to_review = input("Input name of var you want to review") # I need to be able to enter "c" and print the its value "orange" print(func_a.locals()[var_to_review ]) # this doesn't work Could somebody suggest how to fix it? Many thanks
score: -1
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51709768
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/15168765
type: UnansweredQuestion
has title: Python use input to select local variable inside another function

http://stackoverflow.com/comment/121760174
type: AnswerComment
has text: @MStoner I don't understand your comment. What "above approach" works fine?
type: Comment
comment on: http://stackoverflow.com/a/67808043
score: 0

http://stackoverflow.com/a/51754103
answers question: http://stackoverflow.com/q/51753809
has comment: http://stackoverflow.com/comment/90468299
has body: dict.keys only returns the top level keys of the dictionary. If you want to get all nested keys of a dictionary, you will need to define your own function. # interface for dictionary-like objects from collections.abc import Mapping def nested_keys(d) -&gt; set: """ Return a set containing all nested keys. """ # If it is not a dict-like object, return an empty set if not isinstance(d, Mapping): return set() keys = d.keys() for v in d.values(): # Update the keys set with the keys in each value by using the union (or) operator: | keys |= nested_keys(v) return keys
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90468245
downvote count: 0
score: 1

http://stackoverflow.com/q/51657157
has comment: http://stackoverflow.com/comment/90278667
favorite count: 0
accepted answer: http://stackoverflow.com/a/51659229
has comment: http://stackoverflow.com/comment/90280620
tagged with: python
score: 2
type: AnsweredQuestion
has body: I want to do a simple GUI that allows the user to add or remove traces from a plot for any number of traces. It looks like this: The problems I'm having: I don't know how to make the axes not to superpose with each other for a generic number of plots. When I plot more than one trace, and then delete all but one, there are two axes showing for some reason. There should always be one axis per trace being shown. Is there a way to fix these issues? You can find my code below. The only function that should be changed is update_canvas(), I believe. To try it out, just modify the list name_vars in the main with the number of variables you want. The rest of the example code is self-contained. import numpy as np from matplotlib.backends.qt_compat import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvas from matplotlib.figure import Figure class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(ApplicationWindow, self).__init__(parent) global name_vars self.x = np.array([1,2,3,4,5]) self.y = np.random.random((5, len(name_vars))) self.num_vars = np.size(self.y,1) self.name_vars = name_vars self.tags_on = [0] * self.num_vars self.colors = ['#1F77B4','#FF7F0E','#2CA02C','#D62728','#9467BD', '#8C564B','#E377C2','#F7F7F7','#BCBD22','#17BECF'] self._main = QtWidgets.QWidget() self.setCentralWidget(self._main) canvas = FigureCanvas(Figure(figsize=(10, 10))) self.canvas_ax = canvas.figure.subplots() self.canvas_ax.set_xlabel("Time") self.canvas_ax_twin = [] self.list_tags = QtWidgets.QComboBox(self) for name in self.name_vars: self.list_tags.addItem(name) button_add = QtWidgets.QPushButton('Add', self) button_remove = QtWidgets.QPushButton('Remove', self) button_add.clicked.connect(self.add_plot) button_remove.clicked.connect(self.remove_plot) layout = QtWidgets.QGridLayout(self._main) layout.addWidget(canvas, 0, 0) dropdown_layout = QtWidgets.QHBoxLayout() dropdown_layout.addWidget(self.list_tags) dropdown_layout.addWidget(button_ad…
upvote count: 2
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/51659229
tagged with: matplotlib
has title: How to aesthetically show a generic number of axes in matplotlib?
tagged with: pyqt
tagged with: user-interface
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51747452
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52380170
type: Question
downvote count: 0
answer count: 1
tagged with: mpi4py
accepted answer: http://stackoverflow.com/a/52380170
tagged with: mpi
has title: MPI4PY shared memory - memory usage spike on access
score: 1
tagged with: shared-memory
favorite count: 0
has body: I'm using shared memory to share a large numpy array (write-once, read-many) with mpi4py, utilising shared windows. I am finding that I can set up the shared array without problem, however if I try to access the array on any process which is not the lead process, then my memory usages spikes beyond reasonable limits. I have a simple code snippet which illustrates the application here: from mpi4py import MPI import numpy as np import time import sys shared_comm = MPI.COMM_WORLD.Split_type(MPI.COMM_TYPE_SHARED) is_leader = shared_comm.rank == 0 # Set up a large array as example _nModes = 45 _nSamples = 512*5 float_size = MPI.DOUBLE.Get_size() size = (_nModes, _nSamples, _nSamples) if is_leader: total_size = np.prod(size) nbytes = total_size * float_size else: nbytes = 0 # Create the shared memory, or get a handle based on shared communicator win = MPI.Win.Allocate_shared(nbytes, float_size, comm=shared_comm) # Construct the array buf, itemsize = win.Shared_query(0) _storedZModes = np.ndarray(buffer=buf, dtype='d', shape=size) # Fill the shared array with only the leader rank if is_leader: _storedZModes[...] = np.ones(size) shared_comm.Barrier() # Access the array - if we don't do this, then memory usage is as expected. If I do this, then I find that memory usage goes up to twice the size, as if it's copying the array on access if shared_comm.rank == 1: # Do a (bad) explicit sum to make clear it is not a copy problem within numpy sum() SUM = 0. for i in range(_nModes): for j in range(_nSamples): for k in range(_nSamples): SUM = SUM + _storedZModes[i,j,k] # Wait for a while to make sure slurm notices any issues before finishing time.sleep(500) With the above set up, the shared array should take about 2.3GB, which is confirmed when running the code and querying it. If I submit to a queue via slurm on 4 cores on a single node, with 0.75GB per process it runs ok only if I don't do the sum. However, if if do the sum (as shown, or using np.sum or similar), then slurm complai…
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90418205
type: Comment
type: QuestionComment
score: 0
has text: @shmee After using top the script gets up to 75% memory utilization with the process running at Line 149 query. I actually went and queried the database myself and saw that the Line 149 item is going to return a lot of results. Is there any work around?
comment on: http://stackoverflow.com/q/51726782

http://stackoverflow.com/q/51726732
has title: How to process data for 3d convolutional neural network?
tagged with: conv-neural-network
type: Question
accepted answer: http://stackoverflow.com/a/51732226
tagged with: mxnet
score: 0
answer count: 1
has body: I have a collection of 11*11*21 3D data that I want to use a 3D convnet to classify. By using gluon's dataloader with a batch size of 64, my input tensor for the network was (64L, 11L, 11L, 21L). When I tried to run the program I got the following error. "infer_shape error. Arguments: data: (64L, 11L, 11L, 21L)" I then realized that 3D converts take 5D tensors as inputs and thus I am stuck on how to create a 5D tensor input for the network. If it helps here is the code I am currently using to create my data for the convnet. train_dataset = mx.gluon.data.ArrayDataset((noA_list+A_list), (label_noA+label_A)) test_dataset = mx.gluon.data.ArrayDataset((noA_test_list+A_list_test),(label_noA_test+label_A_test)) train_data = mx.gluon.data.DataLoader(train_dataset, batch_size= 64,shuffle= True, num_workers = cpucount) test_data = mx.gluon.data.DataLoader(test_dataset,batch_size= 64,shuffle= True, num_workers = cpucount)
has answer: http://stackoverflow.com/a/51732226
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51645982
has title: Pandas groupby and replace duplicates with empty string
has comment: http://stackoverflow.com/comment/90256787
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51646118
downvote count: 0
has comment: http://stackoverflow.com/comment/90255956
favorite count: 0
possible better answer: http://stackoverflow.com/a/51646176
has answer: http://stackoverflow.com/a/51646176
has body: I have a dataframe like the following: import pandas as pd d = {'one':[1,1,1,1,2, 2, 2, 2], 'two':['a','a','a','b', 'a','a','b','b'], 'letter':[' a','b','c','a', 'a', 'b', 'a', 'b']} df = pd.DataFrame(d) &gt; one two letter 0 1 a a 1 1 a b 2 1 a c 3 1 b a 4 2 a a 5 2 a b 6 2 b a 7 2 b b And I am trying to convert it to a dataframe like the following, where empty cells are filled with empty string '': one two letter 1 a a b c b a 2 a a b b a b When I perform groupby with all columns I get a series object that is basically exactly what I am looking for, but not a dataframe: df.groupby(df.columns.tolist()).size() 1 a a 1 b 1 c 1 b a 1 2 a a 1 b 1 b a 1 b 1 How can I get the desired dataframe?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51646118
type: Question

http://stackoverflow.com/q/51782913
type: Question
has body: Situation Users make purchases, which are stored as transactions in 3 different tables (depending on the type). I need to calculate total amount of transactions/purchases of female and male users, so I need to look into all 3 tables. For this I created a @property in the User table: @property def count_credits_purchases(self): trans = object_session(self).query(Transaction_1).filter(Transaction_1.type == "credits").with_parent(self).count() trans_vk = object_session(self).query(Transaction_2).filter(Transaction_2.type == "credits").with_parent(self).count() trans_stripe = object_session(self).query(Transaction_3).filter(Transaction_3.type == "credits").with_parent(self).count() value = trans + trans_vk + trans_stripe return int(value) I am trying to calculate the total amount of purchases by using sqlalchemy func.sum(): total_purchases_males_credits = db_session.query(func.sum(Users.count_credits_purchases)) .filter(Users.date_added &gt;= start_date, Users.date_added &lt;= end_date, Users.gender == "1") .scalar() Problem AttributeError: 'property' object has no attribute 'translate' The translate method is a string method, what is happening here? I definitely return an integer in count_credits_purchases. I made a test and checking the value per user is always correct: all_users = db_session.query(Users).limit(200) for user in all_users: print (user.count_credits_purchases) # gives correct result I could make a variable and calculate it in the loop, but it is super unefficient and would need probably 1 hour if there are 50k users. I need to understand how to work with the @property attribute
tagged with: flask
possible better answer: http://stackoverflow.com/a/51783135
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51784092
accepted answer: http://stackoverflow.com/a/51784092
has comment: http://stackoverflow.com/comment/90523286
has title: Sqlalchemy AttributeError: 'property' object has no attribute 'translate'
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51783135
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90523399
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy

http://stackoverflow.com/q/51673503
has comment: http://stackoverflow.com/comment/90309887
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90310081
has comment: http://stackoverflow.com/comment/90309736
tagged with: python
tagged with: list
has body: For combining two lists of booleans based on OR, np.logical_or can be used, and similarity AND can be done with np.logical_and. However, if I have a list of 10 lists of boolean values and want to combine them using either AND or OR, I cannot find an easy way to do this. Could you please suggest the most efficient way? EDIT: booleans = [[True, True, False, True, False], [True, False, False, False, False], [True, False, False, False, False]] OR output: [True, True, False, True, False] AND output: [True, False, False, False, False] Thanks, Jack
has title: Combine list of list of booleans based on AND or OR condition
has answer: http://stackoverflow.com/a/51673686
type: Question
has comment: http://stackoverflow.com/comment/90309795
has comment: http://stackoverflow.com/comment/90310002
linked to: http://stackoverflow.com/q/20528328
has comment: http://stackoverflow.com/comment/90309801
has comment: http://stackoverflow.com/comment/90311869
has comment: http://stackoverflow.com/comment/90309740
upvote count: 2
tagged with: boolean
score: 0
downvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51672709
has answer: http://stackoverflow.com/a/61076257
upvote count: 8
possible better answer: http://stackoverflow.com/a/51673006
linked to: http://stackoverflow.com/q/49259580
tagged with: pandas
has answer: http://stackoverflow.com/a/51673006
tagged with: python
has comment: http://stackoverflow.com/comment/90308182
has answer: http://stackoverflow.com/a/51672855
favorite count: 0
score: 8
answer count: 5
has comment: http://stackoverflow.com/comment/90308112
has answer: http://stackoverflow.com/a/51672878
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61893629
linked to: http://stackoverflow.com/q/40901770
has body: I want to convert data of 'edjefe' column which contains int as well as 'yes' and 'no' values. My problem is I just want to map 'yes' and 'no' to 1 and 0 and keep the int values as it is So I wrote this code def foo(x): if x == 'no': return 0 elif x == 'yes': return 1 else: return x and df1.edjefe.map(lambda x : foo(x)) But I am getting an error as, RecursionError: maximum recursion depth exceeded while calling a Python object
has title: Converting 'no' and 'yes' into 0 and 1 in pandas dataframe
accepted answer: http://stackoverflow.com/a/51672855
duplicate of: http://stackoverflow.com/q/40901770
has comment: http://stackoverflow.com/comment/90308104
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90308015
tagged with: series

http://stackoverflow.com/q/51739199
has answer: http://stackoverflow.com/a/73505957
has answer: http://stackoverflow.com/a/56832680
tagged with: port
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51739258
has answer: http://stackoverflow.com/a/51739548
score: 16
upvote count: 16
type: Question
accepted answer: http://stackoverflow.com/a/51739548
has answer: http://stackoverflow.com/a/69047702
possible better answer: http://stackoverflow.com/a/72517084
has body: I am getting following error when I run Jupyter Notebook: (base) C:\Users\ramne&gt;jupyter notebook [I 01:19:00.648 NotebookApp] The port 8888 is already in use, trying another port. And when I do netstat -ano | find Str "8888" , I get the following: C:\Users\ramne&gt;netstat -ano | findStr "8888" TCP 127.0.0.1:8888 0.0.0.0:0 LISTENING 16024 TCP [::1]:8888 [::]:0 LISTENING 16024 I don't know what the default connection of port 8888 is or what its behavior should be like. How do I fix this error so I can open Jupyter Notebook?
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/72517084
favorite count: 0
has answer: http://stackoverflow.com/a/67515501
has title: Error "Unable to open Jupyter Notebook: Port 8888 is already in use"

http://stackoverflow.com/q/51764048
linked to: http://stackoverflow.com/q/4880960
has comment: http://stackoverflow.com/comment/90486823
score: -4
has body: I have a list of dictionaries. Example: l = [{"a" : 1}, {"b" : 5}, {"a" : 10}, {"b" : 10}, {"a" : 10} ] I want to get the sum of the each key like this { "a" : 30, "b" : 15 }
answer count: 1
has title: python : Get the sum of values of a key in list of dictionaries
favorite count: 0
duplicate of: http://stackoverflow.com/q/50974070
has answer: http://stackoverflow.com/a/51764124
upvote count: 2
tagged with: python
tagged with: dictionary
downvote count: 6
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51764124
type: Question
linked to: http://stackoverflow.com/q/50974070

http://stackoverflow.com/comment/90434295
type: Comment
comment on: http://stackoverflow.com/a/51735582
has text: I tried `import Crypto` but it did not work. **Error** `nvalid operation: OSError: Cannot load native module 'Crypto.Cipher._raw_ecb': Trying '_raw_ecb.so': /rdsdbdata/user_lib/1/0/12345.zip/Crypto/Util/../Cipher/_raw_ecb.so: cannot open shared object file: Not a directory, Trying '_raw_ecbmodule.so': ` Please advise Here is the library module Folder - pycryptodome: Folder - Crypto __init__ Folder - Cipher AES _mode_ecb
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90468921
type: AnswerComment
score: 0
type: Comment
has text: But I do have different, independent sequences that could be batched! That would be an idea worth looking into.
comment on: http://stackoverflow.com/a/51754422

http://stackoverflow.com/comment/90404956
score: 0
has text: I have updated the code and the picture. As it can be seen, rows inserted inside `table_widget_1` and `table_widget_2` are not visible due to size restriction of `QListWidgetItem`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51722119

http://stackoverflow.com/q/51695968
tagged with: http://stackoverflow.com/tag/zip
has body: I am trying to zip a file and not a folder or a directory. Here is how I thought of doing it: from shutil import make_archive make_archive("name_of_zip", "zip", "image.png") I know I can use ZipFile but I have heard that it is not so reliable. But I get an error because I cant zip a file and I can only zip a directory. NotADirectoryError: [Errno 20] Not a directory: 'image.png' Is there a way to do this in Python or would I have to use subprocess and run a like this : $ zip zip_with_image.zip image.png adding: requirements.txt (stored 0%)
has answer: http://stackoverflow.com/a/51696409
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51696170
tagged with: python
type: Question
has title: How can I zip a file not a folder/directory in Python
answer count: 2
score: 0
tagged with: shutil

http://stackoverflow.com/a/51742381
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51742329
answers question: http://stackoverflow.com/q/51742329
has body: You can use pd.Series.where: df['a'].where(df['a'].isin(valid), inplace=True) print(df) a b 0 5.0 12 1 NaN 3 2 NaN 10 3 22.0 9 A few points to note: pd.Series.isin will work more efficiently with a list versus a set. See also Pandas pd.Series.isin performance with set versus array. Your series will necessarily be converted to float since NaN is considered float. The operation does not require assignment to a variable when inplace=True is used.
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51781648
possible better answer: http://stackoverflow.com/a/51781812
has answer: http://stackoverflow.com/a/51781812
has comment: http://stackoverflow.com/comment/90520900
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90520853
has title: Strip method at Python doesn't clear all
has answer: http://stackoverflow.com/a/51781696
has comment: http://stackoverflow.com/comment/90520956
answer count: 2
downvote count: 4
has body: i have some problem to strip '[' at my string (read from file). code data = open(Koorpath1,'r') for x in data: print(x) print(x.strip('[')) result [["0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]] "0.9986130595207214","26.41608428955078"],["39.44521713256836","250.2412109375"],["112.84327697753906","120.34269714355469"],["260.63800048828125","15.424667358398438"],["273.6199645996094","249.74160766601562"]] Desired output : "0.9986130595207214","26.41608428955078","39.44521713256836","250.2412109375","112.84327697753906","120.34269714355469","260.63800048828125","15.424667358398438","273.6199645996094","249.74160766601562" Thanks
accepted answer: http://stackoverflow.com/a/51781696
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/90520984
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/90520909
type: AnsweredQuestion
tagged with: strip

http://stackoverflow.com/a/51652793
has comment: http://stackoverflow.com/comment/90274046
has comment: http://stackoverflow.com/comment/90270384
answers question: http://stackoverflow.com/q/51652496
has comment: http://stackoverflow.com/comment/90271919
has comment: http://stackoverflow.com/comment/90271189
has body: You can either have a matrix-like list, when the shape of the arrays is all the same: matrix_like_list = np.array([np.arange(10) for i in range(3)]) &gt;&gt;&gt; array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) with shape (3, 10), or you can have a list of arrays when the size of at least one array is different: list_of_arrays = np.array([np.arange(np.random.randint(10)) for i in range(3)]) &gt;&gt;&gt; array([array([0, 1, 2, 3, 4, 5]), array([0, 1, 2, 3, 4, 5, 6]), array([0, 1, 2, 3, 4, 5, 6])], dtype=object) The resulting object will have shape (3,). There are no other options.
score: 0
has comment: http://stackoverflow.com/comment/90270645
has comment: http://stackoverflow.com/comment/90273808
has comment: http://stackoverflow.com/comment/90273691
type: Answer
has comment: http://stackoverflow.com/comment/90274131
has comment: http://stackoverflow.com/comment/90273134
has comment: http://stackoverflow.com/comment/90271724

http://stackoverflow.com/q/51778965
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90515822
tagged with: http
has comment: http://stackoverflow.com/comment/90515777
tagged with: urllib
type: Question
has body: I am calling an API and it's returning a list of dictionaries, but in bytes type. I tried decoding, but wound up with a string instead of a list of dictionaries. I am unsure how to decode this and have the list of dictionaries back to then be able to write to a dataframe or CSV. My code looks like this (I hid the subscription key): headers = { # Request headers 'Ocp-Apim-Subscription-Key': '***', } params = urllib.parse.urlencode({ }) try: conn = http.client.HTTPSConnection('api.fantasydata.net') conn.request("GET", "/nascar/v2/json/drivers?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() print(data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) The output was this (shortened): b'[{ "DriverID":80000544, "FirstName":"Jeffrey", "LastName":"Abbey", "Number":34, "Team":null, "BirthDate":null, "BirthPlace":null, "Gender":null, "Height":null, "Weight":null, "Manufacturer":null, "Engine":null, "Chassis":null, "Sponsors":null, "CrewChief":null, "PhotoUrl":"https:\\/\\/s3-us-west-2.amazonaws.com\\/static.fantasydata.com\\/headshots\\/nas\\/low-res\\/0.png", "Updated":"2018-07-14T03:17:41", "Created":"2017-07-15T09:38:41"}, ...
tagged with: decode
has title: Converting API call into List of Dictionaries to Write to Dataframe
score: 0
has comment: http://stackoverflow.com/comment/90515810
tagged with: pandas
tagged with: python
answer count: 0

http://stackoverflow.com/q/51703708
favorite count: 0
has comment: http://stackoverflow.com/comment/90373853
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90368452
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51703839
has comment: http://stackoverflow.com/comment/90368382
score: 1
linked to: http://stackoverflow.com/q/14361256
type: Question
has comment: http://stackoverflow.com/comment/90373064
has title: Why isn't there __dict__ in dir("an imported module") as an attribute?
has comment: http://stackoverflow.com/comment/90368740
answer count: 3
has comment: http://stackoverflow.com/comment/90372911
has answer: http://stackoverflow.com/a/51703868
has body: In Python, we are always told that dir lists any attribute of its questioned object. But why isn't there __dict__ in dir("an imported module")?
has answer: http://stackoverflow.com/a/51703825

http://stackoverflow.com/comment/90543600
comment on: http://stackoverflow.com/q/51792592
has text: @Mitar I think that nosklo is suggesting that you dig into the code for grpcio-testing to figure out how to use it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90421684
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51729252
has text: @I got it really nice solution !

http://stackoverflow.com/comment/90325898
has text: It's most likely an issue about encoding the data as base64. I do recommend you to check the link in the updated answer please.
comment on: http://stackoverflow.com/a/51681251
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51717924
answer count: 5
tagged with: loops
has comment: http://stackoverflow.com/comment/90396872
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90396864
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/51717964
has answer: http://stackoverflow.com/a/51718126
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51718097
score: 1
has title: Understanding if statement within loop
possible better answer: http://stackoverflow.com/a/51717963
has answer: http://stackoverflow.com/a/51718123
favorite count: 0
has answer: http://stackoverflow.com/a/51717963
type: Question
has comment: http://stackoverflow.com/comment/90396910
has answer: http://stackoverflow.com/a/51717964
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90396863
has body: I'm working through some examples from Treehouse via the Python course, and I'm having a hard time understanding the code below. As far as I can tell we are looping through "You got this!". However, I'm not sure what the if statement is actually doing; can someone explain this to me? for letter in "You got this!": if letter in "oh": print(letter)

http://stackoverflow.com/a/72893928
has body: There is VIRTUAL_ENV system variable already set with the path. Check &lt;your_venv&gt;/bin/activate (which is a simple script) to see how the virtual env is setup in general, but this variable will give you the clean path already: echo $VIRTUAL_ENV &lt;full virtual env path&gt;
answers question: http://stackoverflow.com/q/51749906
type: Answer
score: 6
upvote count: 7
downvote count: 1

http://stackoverflow.com/comment/90426415
type: QuestionComment
comment on: http://stackoverflow.com/q/51732697
type: Comment
has text: well - you are missing the `else:` case - that should happen if they do NOT match your if? currently nothing happens, so some do not make it inside your new list...
score: 0

http://stackoverflow.com/q/51647956
has comment: http://stackoverflow.com/comment/90264348
type: UnansweredQuestion
has body: I'm using python API for JIRA and from a few days, facing a problem while fetching the particular field types from issues. I'm using below code and it seemed to work fine till few days ago, but now it throws me an error: The code I'm using is: issues = jiraDC.search_issues('project={}'.format(project_id), start,size, fields=['issuetype', 'project', 'status', 'priority', 'created', 'customfield_14729', 'customfield_14731','customfield_14802']) The error I'm getting on running this code is: File "", line 32, in File "/usr/lib/python2.7/site-packages/jira/client.py", line 2084, in search_issues fields = fields.copy() AttributeError: 'list' object has no attribute 'copy' When I'm fetching all the fields, then there is no error coming, but this is slowing my code by a great deal. Can somebody point me in the right direction? Thanks
answer count: 0
type: Question
tagged with: python
has title: in JIRA python API, how to fetch certain fields from the issue?
has comment: http://stackoverflow.com/comment/90259509
score: 0

http://stackoverflow.com/q/51773843
has comment: http://stackoverflow.com/comment/90506658
has comment: http://stackoverflow.com/comment/90506655
has comment: http://stackoverflow.com/comment/90506940
score: 0
has comment: http://stackoverflow.com/comment/90506613
has body: Is it possible to track a history of owners of files within Windows Explorer or is the creator and last owner retained? I am trying to find the penultimate owner of a file not the most recent. I have been using os.stat but it seems only the final owner is retained.
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/90506521
tagged with: python
answer count: 0
has title: History of owners of files - os.stat
type: Question
has comment: http://stackoverflow.com/comment/90506732
has comment: http://stackoverflow.com/comment/90506747

http://stackoverflow.com/comment/90340810
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51689491
type: AnswerComment
has text: Thanks, i've finally used `reindex(arange(12))` since `range(1,13)` left Jan empty.

http://stackoverflow.com/comment/90410841
type: Comment
has text: I think that would work but what would the code look like? Mine is: 'from Anaconda2/bin/python import pandas as pd'. It is now returning a syntax error on the '/' and I still am not sure if it is still importing pandas because I can only view one error message at a time
type: AnswerComment
comment on: http://stackoverflow.com/a/51700041
score: 0

http://stackoverflow.com/q/51737572
has answer: http://stackoverflow.com/a/51737654
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/51737654
tagged with: python
tagged with: discord
upvote count: 1
has title: How to assign a user a role in a server from a direct message discord.py
downvote count: 1
has body: So I am trying to make a bot where if a user direct messages the bot, it will give them a role in a server that both the user and the bot are in. I tried to just add the role based on the role ID but that did not work. Here is an example of what I was thinking which could maybe help explain it a bit better. role = (role ID) member = message.author await client.add_roles(member, role) Now keep in mind this will be happening in a direct message, and not in a server where this would be much easier. If anyone knows how to do this or has any ideas, please let me know. Thanks
type: AnsweredQuestion
tagged with: discord.py
has comment: http://stackoverflow.com/comment/90435740
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90435684

http://stackoverflow.com/comment/90481150
type: Comment
type: QuestionComment
has text: @Ian did that when taking input.
score: 0
comment on: http://stackoverflow.com/q/51760829

http://stackoverflow.com/q/51767793
has answer: http://stackoverflow.com/a/51768039
has answer: http://stackoverflow.com/a/51768075
has body: I want to use the following function in order mutate the elements of two lists: If a list element starts with a "U", the element should be mutated to "1", otherwise the list element should be mutated to "0". Here is the code: def measure(p): for x in range(len(p)): if p[x][0] == 'U': p[x] = 1 else: p[x] = 0 return p print measure(['Dave','Sebastian','Katy']) print measure(['Umika','Umberto']) The correct result should be [0, 0, 0] [1, 1] But the current code produces: [0, 'Sebastian', 'Katy'] [1, 'Umberto'] It seems that the iteration stopped after the first element. How can I solve this problem?
upvote count: 2
has comment: http://stackoverflow.com/comment/90496958
downvote count: 1
has answer: http://stackoverflow.com/a/51767911
answer count: 5
type: UnansweredQuestion
has title: Python for loop: iteration not complete
has answer: http://stackoverflow.com/a/51767886
tagged with: for-loop
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51767964
type: Question
tagged with: python

http://stackoverflow.com/comment/90383441
has text: oh.. yes that `/16`. i will update
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51710785

http://stackoverflow.com/a/51709959
accepted answer of: http://stackoverflow.com/q/51709814
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51709814
has body: In addition to missing split() on text, you've got your conditions a little mixed up. Try: ' '.join( shortword for shortword in text.split(" ") if len(shortword) &gt;= 3 or shortword in not_shortword ) # 'ne suis pas table'
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/90472731
type: Comment
comment on: http://stackoverflow.com/q/51756539
has text: I was using the basic read_csv function. pd.read_csv('author.xlsx',encoding = 'utf-8').Then I tried to read line by line
score: 0
type: QuestionComment

http://stackoverflow.com/q/51770274
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90499456
has comment: http://stackoverflow.com/comment/90499604
accepted answer: http://stackoverflow.com/a/51777443
tagged with: http://stackoverflow.com/tag/csv
tagged with: pickle
tagged with: python
type: AnsweredQuestion
type: Question
has title: Storing and extracting pickle file from CSV or DataFrame
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51777443
has body: I am storing sklearn models with pickle. But the environment I am working in only allows the persistence of CSV and DataFrame Data. I tried saving models to DataFrames with: #create empty DataFrame model_df = pd.DataFrame(columns=["modelstring"]) #Save one model to each row for model in range(1, len(model_dict)): model_df.loc[model] = pickle.dumps(model_dict[model], protocol = 3) ... #Store and reload csv file model_df["modelstring"].to_csv("models.csv") model_df2 = pd.read_csv("models.csv") ... #Load Model from Pickle model = pickle.loads(model_df2.loc[1].modelstring) But when reading them out, the files are not byte codes anymore, but strings, which I can't convert back to byte. input format: b'\x80\x03csklearn.svm.classes\nOneClassSVM\nq\x...' output format: 'b\'\x80\x03csklearn.svm.classes\nOneClassSVM\nq...' Is there any way to store the models in the csv and being able to read them back out? Thanks.
answer count: 1

http://stackoverflow.com/q/51709917
has comment: http://stackoverflow.com/comment/90382135
has comment: http://stackoverflow.com/comment/90383291
score: 0
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/90384807
tagged with: python
has body: I run a flask server with sqlalchemy connecting to an sqlite database. To update my database tables I exported my data to a file, updated the necessary tables and then imported the data again. This data in the database is all correct and in the right place. The problem is in the passwords, they are stored as a blob (largebinary in sqlalchemy). When creating a new account with a password, the account works immediately without any problems. However all the old passwords that I have imported from the old database do not work anymore and throw an error. The error that gets thrown is the following: TypeError: string argument without an encoding The type of the new passwords in the database is what it should be: &lt;class 'bytes'&gt; With the migrated passwords, I can not even check what type it is, as it throws the TypeError during retrieval of this field. The data is stored as a blob: password BLOB NOT NULL A not working password: $2b$12$CC6OVZTOy3Bc9bsxAeALpuJPc.iZmVwXFB/Cj6.xRlgF2dRdTh11y A working password: $2b$12$NL8reAO7rx1NC5DwgeWVt.ojV0I6czlOKcXAOF87L5NoVsdmOulle
has answer: http://stackoverflow.com/a/51722623
type: AnsweredQuestion
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/90382849
has title: Sqlalchemy largebinary does not have an encoding after migrating data
has comment: http://stackoverflow.com/comment/90382576
accepted answer: http://stackoverflow.com/a/51722623

http://stackoverflow.com/q/51679027
score: 3
tagged with: types
answer count: 1
has answer: http://stackoverflow.com/a/51679252
has comment: http://stackoverflow.com/comment/90321305
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: Say I have a function that takes other functions as arguments: Metric = Callable[List[float], float] def metric_doubler(metric: Metric, lst: List[float]): return 2*metric(lst) And I want to write other functions and declare that they have type Metric, e.g. def my_mean(lst: List[float]) -&gt; float: return sum(lst)/len(lst) Is there a way to assert that my_mean in this case has type Metric? In particular, the real use case is when I have a lot of such functions, and want to catch errors if I need to change the type of Metric.
has comment: http://stackoverflow.com/comment/90322333
has comment: http://stackoverflow.com/comment/90321450
has title: How to declare that a function itself has a certain type?
has comment: http://stackoverflow.com/comment/90322024
downvote count: 1
type: Question
upvote count: 4
tagged with: mypy
has comment: http://stackoverflow.com/comment/90321637
has comment: http://stackoverflow.com/comment/90322212

http://stackoverflow.com/comment/90532759
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51787558
has text: thanks, could you please tell how gunicorn can fix this issue?
score: 0

http://stackoverflow.com/a/51979140
has comment: http://stackoverflow.com/comment/90938750
type: Answer
has comment: http://stackoverflow.com/comment/90934909
has comment: http://stackoverflow.com/comment/90938796
has comment: http://stackoverflow.com/comment/90934794
has comment: http://stackoverflow.com/comment/91374870
score: 13
has comment: http://stackoverflow.com/comment/91366567
downvote count: 0
has body: The issue seems to be that new virtual environments are using an old version of pip. Note that pip is installed from a source tarfile (or wheel) included with virtualenv, in the site-packages/virtualenv_support directory. $ ls -l /path/to/site-packages/virtualenv_support pip-9.1-py2.py3-none-any.whl A quick way to workaround the problem is to make sure you upgrade pip whenever you create a new virtualenv, like so: $ virtualenv venv $ venv/bin/pip install -U pip Alternatively, make sure you have the latest version of virtualenv. According to their release notes, virtualenv==16 is using pip==10. $ pip install -U virtualenv Finally, since virtualenv looks for pip*.whl in virtualenv_support, this will also work: $ mv /path/to/site-packages/virtualenv_support/pip*.whl{,bak} $ pip wheel -w /path/to/site-packages/virtualenv_support/ 'pip==18' All new virtualenvs will use the version of pip that you installed into virtualenv_support. However, this feels hacky. (Attempted with virtualenv==16. This results in all new virtualenvs with pip==18.)
has comment: http://stackoverflow.com/comment/90938761
accepted answer of: http://stackoverflow.com/q/51644402
answers question: http://stackoverflow.com/q/51644402
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90938720
upvote count: 13
has comment: http://stackoverflow.com/comment/90938781
has comment: http://stackoverflow.com/comment/90938816

http://stackoverflow.com/a/51680666
has body: Why not just use quiver() in your case? See here. import matplotlib.pyplot as plt import numpy as np plt.figure() def rand(n): return 2.0*np.random.rand(n)-1.0 def plt_arrows(n, c, l, xpos, ypos): X, Y = rand(n), rand(n) U, V = 4.*rand(n), 4.*rand(n) Q = plt.quiver(X, Y, U, V, angles="xy", scale=30, label=l, color=c) qk = plt.quiverkey(Q, xpos, ypos, 2, label=l, labelpos='N', labelcolor=c) plt_arrows(20, "g", "good", 1.05, 0.9) plt_arrows(20, "r", "bad", 1.05, 0.8) plt.show()
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90324648
score: 2
answers question: http://stackoverflow.com/q/51680405
accepted answer of: http://stackoverflow.com/q/51680405
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90416428
score: 0
has text: per official Keras documentation - factor: factor by which the learning rate will be reduced. new_lr = lr * factor. So yes, you are correct.
comment on: http://stackoverflow.com/a/51724965
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51786386
score: 0
tagged with: common-crawl
tagged with: byte
has answer: http://stackoverflow.com/a/51800448
favorite count: 0
linked to: http://stackoverflow.com/q/66794188
has comment: http://stackoverflow.com/comment/90583658
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51823232
tagged with: warc
tagged with: python
has comment: http://stackoverflow.com/comment/90872014
has comment: http://stackoverflow.com/comment/90586771
upvote count: 1
downvote count: 1
has body: I am reading a WARC file with python's 'warc' library. Current file that I am using, is around 4.50 GB. The thing is ; file = warc.open("random.warc") html_lists = [line for line in file] Executing these 2 lines takes up to 40 seconds. Since there will be 64000 more files like this one, it is not acceptable that it takes 40 seconds per file. Do you guys have any tips to improve performance or any different approaches? Edit : I found out that Beautifulsoup operations take some time. So I removed it and wrote the necessary stuff myself. It is 100x faster now. It takes +- 60 seconds to read and process 4.50 GB data. With this line of code I remove the scripts from data; clean = re.sub(r"&lt;script.*?&lt;/script&gt;", "", string=text) And with this one I split the text and remove the stamp which I don't need warc_stamp = str(soup).split(r"\r\n\r\n") As I said it is faster but 60 seconds are not that good in this case. Any suggestions ?
type: Question
has title: Reading WARC Files Efficiently
answer count: 2

http://stackoverflow.com/q/51720606
type: Question
has comment: http://stackoverflow.com/comment/90401791
has answer: http://stackoverflow.com/a/51722047
has body: For example ['ram', 'shyam', 'great', 'bad'] here are four indexes, now I want all the things in list with less indexes like ['ram', 'shyam', 'great,bad'] here only 3 indexes.
has answer: http://stackoverflow.com/a/51720702
has answer: http://stackoverflow.com/a/51720675
tagged with: python-2.7
has title: how to create a list in python from an existing list with all the elements from first list but with lesser indexes
has comment: http://stackoverflow.com/comment/90401798
has answer: http://stackoverflow.com/a/51720656
favorite count: 0
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51720685
score: -1
upvote count: 2
downvote count: 3

http://stackoverflow.com/a/51709004
upvote count: 3
type: AcceptedAnswer
has body: You have a perfect use case for leveraging the BranchPythonOperator which will allow you to perform a check to see if the table exist and then either proceed with creating the table before inserting to that table without having to worry about TRIGGER_RULES and make your DAG logic much more clear from the UI.
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/51708356
answers question: http://stackoverflow.com/q/51708356
has comment: http://stackoverflow.com/comment/90423904
downvote count: 0

http://stackoverflow.com/a/62593771
answers question: http://stackoverflow.com/q/51729853
score: 5
upvote count: 5
downvote count: 0
type: Answer
has body: It is most certainly possible to run tensorflow on AMD GPUs. About 2 years back ROCm was released which gets things done. However, the is a caveat, that it runs only on Linux as of now owing to its open-source origins. So if you are willing to use Linux then you can most certainly train your DL models using AMD GPUs. That said the amount of support you will get is low as the community is still not large enough. Google search for ROCm and you can get instructions on how to get it set up and running on a Linux machine. May be it will work with WSL2 in windows, but I have not tried it yet and so cannot comment on that. here is a link to ROCm installation docs

http://stackoverflow.com/q/51673700
tagged with: python
possible better answer: http://stackoverflow.com/a/51673808
tagged with: selenium-webdriver
tagged with: xpath
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: selenium
type: Question
answer count: 3
accepted answer: http://stackoverflow.com/a/51673798
tagged with: css-selectors
upvote count: 1
has answer: http://stackoverflow.com/a/51674322
has title: How to wait and get the status of web element using selenium webdriver and python
favorite count: 0
has answer: http://stackoverflow.com/a/51673808
has body: I am trying to check the status of element which has status change from "Running" to "Success". The status change might take around 1 minute or for every few seconds i need to retry checking the status of element. Can someone help me how to achieve this , following is the html structure and snippet that i am trying. Running Running Copy of Discovery v4madhu-test3-automate 03 Aug 16:14 autotest dmatarget14.hpeswlab.net Success Success Copy of Discovery v4madhu-test3-automate 03 Aug 16:14 autotest dmatarget14.hpeswlab.net sample code timeout = 60 maxtime = time.time() + timeout result = None while result is "SUCCESS": try: # connect result = driver.find_element_by_xpath('//td[contains,"dmatarget14.hpeswlab.net"] and td[contains,"Success"]/ancestor::tr') time.sleep(5) except: if time.time() > maxtime: raise Exception
has answer: http://stackoverflow.com/a/51673798

http://stackoverflow.com/comment/90269573
score: 0
type: Comment
type: QuestionComment
has text: I think I can adapt an implementation of the following widget to what QRangeSlider does https://imgur.com/a/HJ1JwLK
comment on: http://stackoverflow.com/q/51652527

http://stackoverflow.com/a/52649180
score: 0
has body: you need to install the contrib package sudo -H pip install opencv-contrib-python sudo -H pip install opencv-python
type: Answer
answers question: http://stackoverflow.com/q/51788344

http://stackoverflow.com/comment/90405863
comment on: http://stackoverflow.com/q/51702122
has text: The best is not to call asyncio code from Flask, sorry.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51684403
has body: I need to overwrite each line of a (txt) file in python with (first 10 digits of) it's hashcode. I'm having troubles with the writing part ( I can print it but not write it). the old part of the file('x) should be overwritten with the new part(the hash). [FAIL] File passwords.txt should be transformed from ['x'] to ['2d711642b7'] Expected value: ['2d711642b7'] Actual value: ['x', '2d711642b7'] def hash_file(filename): import hashlib import fileinput from hashlib import sha256 with open(filename,'rb+') as f: for line in f: hash =sha256(line.rstrip()).hexdigest() b = bytes(hash[0:10], 'utf-8') f.write(b)
tagged with: python
type: AnsweredQuestion
has title: Python IO replace/overwrite text-file with hashcode
has comment: http://stackoverflow.com/comment/90331095
has comment: http://stackoverflow.com/comment/90331106
type: Question
has comment: http://stackoverflow.com/comment/90331175
has comment: http://stackoverflow.com/comment/90331750
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52024921
accepted answer: http://stackoverflow.com/a/52024921
tagged with: hash
has comment: http://stackoverflow.com/comment/90331166

http://stackoverflow.com/q/51767835
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90494529
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90494516
has comment: http://stackoverflow.com/comment/90494690
type: AnsweredQuestion
score: 1
tagged with: multi-index
type: Question
has body: I am getting inconsistent indexing behaviour depending on whether one of the indices in my MultiIndex dataframe is an integer or a string. Here is an example: MultiIndex with one string index: a = [['a','a','a','b','b','b','c','c'],[2,1,1,1,2,2,2,1]] b = [['a','b','c','a','b','c','a','b'],[2,2,2,2,4,4,4,4]] index=pd.MultiIndex.from_tuples(list(zip(*b)),names=['num1','num2']) df1=pd.DataFrame({'letters': a[0],'numbers': a[1]},index=index) df1.sort_index(inplace=True) # avoid lex sort warnings df1 letters numbers num1 num2 a 2 a 2 2 b 1 4 c 2 b 2 a 1 4 b 2 4 c 1 c 2 a 1 4 b 2 df1.loc['a',2]['letters'][0] 'a' df1.loc['a',2]['letters'][1] 'b' MultiIndex with all integer indices: a = [['a','a','a','b','b','b','c','c'],[2,1,1,1,2,2,2,1]] b = [[1,2,3,1,2,3,1,2],[2,2,2,2,4,4,4,4]] index=pd.MultiIndex.from_tuples(list(zip(*b)),names=['num1','num2']) df1=pd.DataFrame({'letters': a[0],'numbers': a[1]},index=index) df1.sort_index(inplace=True) # avoid lex sort warnings df1 letters numbers num1 num2 1 2 a 2 2 b 1 4 c 2 2 2 a 1 4 b 2 4 c 1 3 2 a 1 4 b 2 df1.loc[1,2]['letters'][0] 'a' df1.loc[1,2]['letters'][1] num2 2 a 2 b Name: letters, dtype: object The behaviour in the first case is what I expect. Could someone explain why in the second case indexing with 1 returns a series instead of the string 'b'?
has answer: http://stackoverflow.com/a/51767999
accepted answer: http://stackoverflow.com/a/51767999
has title: Inconsistent behaviour in MultiIndex Indexing

http://stackoverflow.com/comment/90373688
has text: Where's word coming from if you aren't returning it?? (as per your code)
comment on: http://stackoverflow.com/q/51706137
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/51715438
tags question: http://stackoverflow.com/q/51791873
tags question: http://stackoverflow.com/q/51752263
tags question: http://stackoverflow.com/q/51739682
tags question: http://stackoverflow.com/q/51643332
tags question: http://stackoverflow.com/q/51756089
tags question: http://stackoverflow.com/q/51713844
tags question: http://stackoverflow.com/q/51775971
tags question: http://stackoverflow.com/q/51774081
tags question: http://stackoverflow.com/q/51760262
tags question: http://stackoverflow.com/q/51774735
tags question: http://stackoverflow.com/q/51721489
tags question: http://stackoverflow.com/q/51683492
tags question: http://stackoverflow.com/q/51714942
tags question: http://stackoverflow.com/q/51712719
tags question: http://stackoverflow.com/q/51685551
tags question: http://stackoverflow.com/q/51717839
tags question: http://stackoverflow.com/q/51669892
tags question: http://stackoverflow.com/q/51649710
tags question: http://stackoverflow.com/q/51643669
tags question: http://stackoverflow.com/q/51645514
tags question: http://stackoverflow.com/q/51650395
tags question: http://stackoverflow.com/q/51688712
tags question: http://stackoverflow.com/q/51781859
type: Tag
tags question: http://stackoverflow.com/q/51726922
tags question: http://stackoverflow.com/q/51644623
tags question: http://stackoverflow.com/q/51762461
tags question: http://stackoverflow.com/q/51690627
tags question: http://stackoverflow.com/q/51657210
tags question: http://stackoverflow.com/q/51657000
tags question: http://stackoverflow.com/q/51731623
tags question: http://stackoverflow.com/q/51743583
tags question: http://stackoverflow.com/q/51794609
tags question: http://stackoverflow.com/q/51775402
tags question: http://stackoverflow.com/q/51779728
tags question: http://stackoverflow.com/q/51754318
tags question: http://stackoverflow.com/q/51744615
tags question: http://stackoverflow.com/q/51653495
tags question: http://stackoverflow.com/q/51703185
tags question: http://stackoverflow.com/q/51789605
tags question: http://stackoverflow.com/q/51687362
tags question: http://stackoverflow.com/q/51762116
tags question: http://stackoverflow.com/q/51713152
tags question: http://stackoverflow.com/q/51752231
tags question: http://stackoverflow.com/q/51678021
tag name: html
tags question: http://stackoverflow.com/q/51765879
tags question: http://stackoverflow.com/q/51724962
tags question: http://stackoverflow.com/q/51660176
tags question: http://stackoverflow.com/q/51667760
tags question: http://stackoverflow.com/q/51699773
tags question: http://stackoverflow.com/q/51765827
tags question: http://stackoverflow.com/q/51656193
tags question: http://stackoverflow.com/q/51664323
tags question: http://stackoverflow.com/q/51682151
tags question: http://stackoverflow.com/q/51766848
tags question: http://stackoverflow.com/q/51733288
tags question: http://stackoverflow.com/q/51661907
tags question: http://stackoverflow.com/q/51785094
tags question: http://stackoverflow.com/q/51644921

http://stackoverflow.com/comment/90547467
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51794615
has text: Also, `\d+(\.\d+)*` matches things like `1.2.3.4.5`. You don't want to match an arbitrary number of decimals; you want to match 0 or 1. Use `\d(\.\d+)?`.
type: Comment

http://stackoverflow.com/comment/90356680
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51694319
has text: Hi and thanks for the help, i didnt notice the part "label1.pack" without the "()", but it is not the problem.:c , also i did what u said about ".place" and ".pack" but the issue persist :c
score: 0

http://stackoverflow.com/comment/90457493
comment on: http://stackoverflow.com/a/51747866
type: AnswerComment
type: Comment
has text: that works very well. thanks a lot! can I also adjust the bar width depending on a column, let's call it "class_size" with one value for each land_cover (value between 0 and 1)?
score: 0

http://stackoverflow.com/a/51734908
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51734814
upvote count: 1
has comment: http://stackoverflow.com/comment/90430745
score: 1
has comment: http://stackoverflow.com/comment/90430696
has comment: http://stackoverflow.com/comment/90430839
has body: Try this solution: from pandas import DataFrame, merge df1['key'] = 1 df2['key'] = 1 result = df1.merge(df2, on='key').drop('key', axis=1)
answers question: http://stackoverflow.com/q/51734814
type: AcceptedAnswer

http://stackoverflow.com/comment/115635427
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51716170
has text: @NickChammas you're right, missed a backslash before the dot, turning it into a glob. Thank you for the hint!
type: AnswerComment

http://stackoverflow.com/comment/90506226
type: QuestionComment
has text: @baptistemm saw that thanks yeah strange that ansible-container doesn't lock it down in their requirements.txt https://github.com/ansible/ansible-container/blob/release-0.9.2/requirements.txt
score: 0
comment on: http://stackoverflow.com/q/51773088
type: Comment

http://stackoverflow.com/q/51640528
type: Question
has body: I have a bash script that has the launch agent <?xml version="1.0" encoding="UTF-8"?> Label com.user.loginscript ProgramArguments /Users/Documents/Untitled.bash RunAtLoad <true/> and the bash script runs a python script that connects to a server and downloads a file. However the when the login agent runs and the bash script runs, the python script will not connect to the server to download the file. How can I fix this. (I am also on my mac)
score: 0
tagged with: bash
has title: Script that runs at login doesn't use internet
has comment: http://stackoverflow.com/comment/90249059
tagged with: macos
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90245498

http://stackoverflow.com/comment/99038852
type: QuestionComment
has text: `connection.set_charset_collation('latin1')` worked around it for me, for the dumb reason that latin1 will never have decode errors. Connector seems to have gone ignorant of BINARY data types.
score: 0
comment on: http://stackoverflow.com/q/51657097
type: Comment

http://stackoverflow.com/comment/90532806
comment on: http://stackoverflow.com/q/51787702
score: 0
type: Comment
has text: Cna you show us your project structure?
type: QuestionComment

http://stackoverflow.com/a/51663408
downvote count: 0
has comment: http://stackoverflow.com/comment/90291710
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90291741
upvote count: 1
has body: Here is another way a bit easier to understand but using merge as @sacul's solution. I would create two dataframes df_visitor and df_home with the values from team_stats_1970_2017, for each row and for the team in the columns 'visitor_team' and 'home_team' respectively, such as: df_visitor = (game_df'season_yr','visitor_team'.rename(columns={'visitor_team':'team'}) .merge(team_stats_1970_2017, how='left')) df_home = (game_df'season_yr','home_team'.rename(columns={'home_team':'team'}) .merge(team_stats_1970_2017, how='left')) and you get for example for df_home: season_yr team r_per_g pa ab b_r b_h b2 b3 b_hr 0 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 1 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 2 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 3 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 4 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 5 2017 ARI 5.01 6224.0 5525 812 1405 314 39 220 6 2017 ATL 4.52 6216.0 5584 732 1467 289 26 165 For each row, it's the value from team_stats_1970_2017 associated to the team in game_df at the same row int he column 'home_team'. Now to add the difference at the original dataframe game_df you can do: # first get the lists of columns you want to add col_features = team_stats_1970_2017.columns[2:] game_df[col_features] = df_visitor[col_features] - df_home[col_features] and finally to add the column result, you can use np.where: import numpy as np game_df['results'] = np.where(game_df['visitor_team_runs'] &gt; game_df['home_team_runs'], 1, 0) # meaning if p2 &gt; p1 then 1 else 0 as in your code I think
has comment: http://stackoverflow.com/comment/90291436
accepted answer of: http://stackoverflow.com/q/51662445
answers question: http://stackoverflow.com/q/51662445
type: AcceptedAnswer

http://stackoverflow.com/comment/90293024
type: Comment
type: QuestionComment
score: 2
has text: What is the error you are getting? What have you done to try to remedy the problem?
comment on: http://stackoverflow.com/q/51664897

http://stackoverflow.com/comment/129664013
has text: It's not clear what's going on with this question. Please read [mre] and clearly state a problem, if there is one. Note well that this is **not a discussion forum**; please don't "update" to indicate fixes. If the problem was resolved, the question still stands; if not, there is potentially a **new question**.
comment on: http://stackoverflow.com/q/51674597
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90350539
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51693425
score: 0
has text: Well, it only works for else value now, but servos don't change to 130 and I don't know why. I keep trying on my own, i don't want to trouble you so much :)

http://stackoverflow.com/q/51788241
accepted answer: http://stackoverflow.com/a/51788314
tagged with: web-scraping
type: Question
possible better answer: http://stackoverflow.com/a/51788403
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51788314
has body: I'm parsing a site using BeautifulSoup4. The code: for link in soup.find_all("div", {"class": "fl nav_left_2j"}): for item in link.find_all("li"): print(item) Gets me: 北京市 ***** 天津市 ***** 河北省 ***** 山西省 ***** 内蒙古自治区 ***** 辽宁省 ***** 吉林省 ***** 黑龙江省 ***** 上海市 ***** 江苏省 ***** 浙江省 ***** 安徽省 ***** 福建省 ***** 江西省 ***** 山东省 ***** 河南省 ***** 湖北省 ***** 湖南省 ***** 广东省 ***** 广西壮族自治区 ***** 海南省 ***** 重庆市 ***** 四川省 ***** 贵州省 ***** 云南省 ***** 西藏自治区 ***** 陕西省 ***** 甘肃省 ***** 青海省 ***** 宁夏回族自治区 ***** 新疆维吾尔自治区 ***** 香港特别行政区 ***** 澳门特别行政区 ***** 台湾省 ***** Which is great! Now I want to extract the href (and eventually the title, but I'm assuming if I solve for one I solve for both). According to the docs, I should be able to add: print(item.get('href')) and get all of the links. Unfortunately, all I get is "None". But there are hrefs there! I can see them! I'd prefer not to have to build a bunch of regexes if there is built in functionality to do this correctly. What mindbogglingly obvious thing am I doing wrong? thanks!
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51788403
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51788436
tagged with: python
has title: Extracting href from beautifulsoup: why None?
has comment: http://stackoverflow.com/comment/90533812

http://stackoverflow.com/a/51721496
type: Answer
answers question: http://stackoverflow.com/q/51720829
downvote count: 0
has body: In your code, look at the lines marked with !!!!: #Reduce pixels shrinked = shrink3(gray, int(gray.shape[0]/3), int(gray.shape[1]/3)) # # Add white Points !!!! y, x = np.where(shrinked &gt;= 0) # Set z values to summed values z=[] for y1 in range(0, shrinked.shape[0]): for x1 in range(0, shrinked.shape[1]): z = np.append(z, shrinked.item(y1,x1)) # meshgrid x_min, x_max = x.min() - 1, x.max() + 1 y_min, y_max = y.min() - 1, y.max() + 1 ti = np.linspace(x_min, x_max, (x_max-x_min+1)*3) tii = np.linspace(y_min, y_max, (y_max+y_min+1)*3) !!!! xx, yy = np.meshgrid(ti, tii) # rbf interpolation rbf = Rbf(x, y, z, function='gaussian', epsilon=eps/shrinkEps, smooth=smoo) zz = rbf(xx, yy) jet = cm = plt.get_cmap('jet') plt.pcolor(xx, yy, zz, cmap=jet) plt.colorbar() You switch the x and y. Maybe you can do: yy, xx = np.meshgrid(tii, ti)
score: 1
has comment: http://stackoverflow.com/comment/90403521
upvote count: 1

http://stackoverflow.com/comment/90336490
comment on: http://stackoverflow.com/a/51679264
type: AnswerComment
score: 0
type: Comment
has text: @DavidA I think for the moment you should just focus on getting familiar with Tkinter before you try to write a program that combines Pandas and Tkinter.

http://stackoverflow.com/comment/90353133
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51695747
score: 0
has text: Your link is broken. Should end on html :). (Can't edit because it's less than 6 characters!)

http://stackoverflow.com/q/51798719
answer count: 1
tagged with: python-3.x
has body: Views.py def cartdata(request): emailid = request.session['emailid'] dressid = cart_details.objects.values_list('dressid').filter(emailid=emailid) cartdress = array.array('i',[dress_details.objects.all().filter(dress_id=dressid)]) for i in cartdress: cartdetails = dress_details.objects.all().filter(dress_id=i) return render(request, 'project/shop.html', {'cartdetails':cartdetails}) shop.html {% for i in cartdetails %} {{ i.dress_name }} {{ i.dress_type }} Size:{{ i.dress_size }} Color: {{ i.dress_color }} RS.{{ i.dress_price }} {% endfor %} database in database 2 tables are there. 1st Cart table where 3 columns 1)cartid(primarykey) 2)email(session variable) 3)dressid(fetching from dress table) 2nd Dress table where all the data of dress available. My main question is I'm not able to fetch whole data how can I fetch in djano.?
tagged with: python
type: UnansweredQuestion
score: 0
has title: Django how to pass bulk values in html via for loop and array?
tagged with: django
has answer: http://stackoverflow.com/a/51798834
type: Question

http://stackoverflow.com/comment/90281325
has text: @AdamParkin The loop can get stopped from a callback or coroutine in the event loop thread - for example, a coroutine can detect an "exit" command on a socket and call `loop.stop()`. This is how things work when there is only one thread in the picture, and it only runs the event loop, and that's a perfectly valid (even typical) usage of asyncio. If you do use multiple threads, then all other threads must invoke `loop.stop()` as `loop.call_soon_threadsafe(loop.stop)` (note lack of parentheses after `loop.stop`), and the same for anything else loop-related.
score: 3
comment on: http://stackoverflow.com/a/51647591
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51747842
answer count: 1
has answer: http://stackoverflow.com/a/51769567
has body: I am working with google cloud functions in python and I am facing the following difficulties: I don't know how to add a token to the automatically generated endpoint for my HTTP cloud function : Below is the code I deployed : from flask import Flask, request from flask_httpauth import HTTPBasicAuth auth = HTTPBasicAuth() PROJECT = "projectname" app = Flask(__name__) @app.route('/', methods=['PUT', 'POST']) @auth.login_required def httpfunction(request): data = request.stream.read() return data The generated URL is : https://europe-west1-projectname.cloudfunctions.net/httpfunction I want to add a token to it in order to avoid inappropriate persons to make use it , so basically here I want to avoid POST and PUT requests from unauthorized users. Any ideas how to do this please ?
favorite count: 0
type: UnansweredQuestion
has title: add token to endpoint for goolge cloud function python
tagged with: python
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/46358013
tagged with: flask
score: 0
upvote count: 1
tagged with: google-cloud-functions

http://stackoverflow.com/q/51664292
favorite count: 0
has title: (Python) AttributeError: 'NoneType' object has no attribute 'text'
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
upvote count: 7
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/51664377
score: 7
has answer: http://stackoverflow.com/a/69867172
answer count: 2
has body: I'm getting the error below when I'm parsing the xml from the URL in the code. I won't post the XML because it's huge. The link is in the code below. ERROR: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-70-77e5e1b79ccc&gt; in &lt;module&gt;() 11 12 for child in root.iter('Materia'): ---&gt; 13 if not child.find('EmentaMateria').text is None: 14 ementa = child.find('EmentaMateria').text 15 AttributeError: 'NoneType' object has no attribute 'text' MY CODE: url = 'http://legis.senado.leg.br/dadosabertos/senador/4988/autorias' import requests from xml.etree import ElementTree response = requests.get(url, stream=True) response.raw.decode_content = True tree = ElementTree.parse(response.raw) root = tree.getroot() for child in root.iter('Materia'): if child.find('EmentaMateria').text is not None: ementa = child.find('EmentaMateria').text for child_IdMateria in child.findall('IdentificacaoMateria'): anoMateria = child_IdMateria.find('AnoMateria').text materia = child_IdMateria.find('NumeroMateria').text siglaMateria = child_IdMateria.find('SiglaSubtipoMateria').text print('Ano = '+anoMateria+' | Numero Materia = '+materia+' | tipo = '+siglaMateria+' | '+ementa) What I'm overlooking here? Thanks
tagged with: xml-parsing
possible better answer: http://stackoverflow.com/a/69867172
downvote count: 0
accepted answer: http://stackoverflow.com/a/51664377

http://stackoverflow.com/comment/90351324
type: QuestionComment
has text: After activating virtual environment when i am trying to run python manage.runserver my_ip_address:8080 then it is working properly. If there could have been additional requirements then this command should have shown error. @AyeshmanthaPerera
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51694915

http://stackoverflow.com/a/51684621
accepted answer of: http://stackoverflow.com/q/51684312
type: Answer
answers question: http://stackoverflow.com/q/51684312
has body: Should this be in square brackets instead of ()? data=data('Time Series (Daily)') i.e. are you trying to access the key 'Time Series (Daily)' in the data dict? If so, use: data = data['Time Series (Daily)'] Otherwise you are trying to call a function data() with the argument 'Time Series (Daily)'
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90505226
type: Comment
comment on: http://stackoverflow.com/a/51772961
has text: Also, `print(i)` before and after the `pop()` to compare where "seq" is not available.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51730154
has comment: http://stackoverflow.com/comment/90451282
has body: Unfortunately, you're going to have to compute those distances on the cluster centers yourself. Scikit doesn't provide a method for that right out of the box. Here's a comparable problem setup: from sklearn.datasets import load_iris from sklearn.cluster import KMeans from sklearn.metrics.pairwise import euclidean_distances X, y = load_iris(return_X_y=True) km = KMeans(n_clusters = 5, random_state = 1).fit(X) And how you'd compute the distances: dists = euclidean_distances(km.cluster_centers_) And then to get the stats you're interested in, you'll only want to compute on the upper (or lower) triangular corner of the distance matrix: import numpy as np tri_dists = dists[np.triu_indices(5, 1)] max_dist, avg_dist, min_dist = tri_dists.max(), tri_dists.mean(), tri_dists.min()
answers question: http://stackoverflow.com/q/51729851
upvote count: 17
score: 17
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51729851
type: Answer

http://stackoverflow.com/q/51650855
possible better answer: http://stackoverflow.com/a/51660552
tagged with: pandas
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51660552
downvote count: 0
accepted answer: http://stackoverflow.com/a/51651169
has comment: http://stackoverflow.com/comment/90265549
has title: How to split column from DataFrame with Pandas
favorite count: 0
type: Question
upvote count: 2
answer count: 2
has body: I am reading a CSV file from an API call into a data frame with pandas for some data manipulation. Currently, I'm getting this response: n [78]: dfname Out[78]: productID amountInStock index index_col 7 1.0 NaN 1 7 19 4.0 NaN 2 19 20 1.0 NaN 3 20 22 2.0 NaN 4 22 I then call dfname.reset_index() to create a better index: dfname.reset_index() Out[80]: level_0 productID amountInStock index index_col 0 7 1.0 NaN 1 7 1 19 4.0 NaN 2 19 2 20 1.0 NaN 3 20 3 22 2.0 NaN 4 22 But the problem is that the 'productID' series has two columns and I can't work out how to split them! dfname.productID Out[82]: 7 1.0 19 4.0 20 1.0 22 2.0 What I want is dfname.productID to return: dfname.productID Out[82]: 7 19 20 22 and the other figures currently in productID should be assigned to 'stockqty'. How do I split this field so that it returns two columns instead of one? I've tried .str.split() to no avail. The properties of the object are Name: productID, Length: 2102, dtype: float64
tagged with: python
has comment: http://stackoverflow.com/comment/90265287
tagged with: indexing
tagged with: dataframe
tagged with: series
has answer: http://stackoverflow.com/a/51651169

http://stackoverflow.com/comment/90388400
score: 0
type: Comment
has text: I tried a variation of your code, but I got an error, please review my main post I've added the information at the bottom.
type: AnswerComment
comment on: http://stackoverflow.com/a/51713351

http://stackoverflow.com/comment/90258692
comment on: http://stackoverflow.com/q/51641287
type: Comment
type: QuestionComment
score: 0
has text: [How do I type a floating point infinity literal in python - Stack Overflow](https://stackoverflow.com/questions/2919754/how-do-i-type-a-floating-point-infinity-literal-in-python) -

http://stackoverflow.com/q/51683952
has answer: http://stackoverflow.com/a/51787467
accepted answer: http://stackoverflow.com/a/51787467
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/51195392
type: Question
upvote count: 2
tagged with: graph
answer count: 1
favorite count: 0
has body: I'm working on a Python project involving molecules, and for now I have been representing molecules as graphs. I have three different numpy arrays describing each graph: a binary adjacency matrix, an array storing the atomic number of each atom in the molecule, and a matrix storing the type of bonds between atoms. i only represent heavy atoms in the graphs, so no hydrogens. I am looking for a way to check the validity of the molecules, and I have been trying to use RDKit's SanitizeMol function to do so. Is there an easy way to convert a graph into a Mol object? I also have functions to convert my numpy format to a Networkx graph, but I can't find any way of doing the following step (nx to RDKit). I have been trying to use an EditablMol to build the Mol manually, but then the absence of hydrogens in the graphs causes some issues with the valence of several atoms. I'm a bit stuck, any help is appreciated. Thanks
tagged with: rdkit
tagged with: molecule
has title: How to convert molecule from graph representation to RDKit Mol
tagged with: python

http://stackoverflow.com/q/51689145
tagged with: gcloud
has answer: http://stackoverflow.com/a/51693619
accepted answer: http://stackoverflow.com/a/51693619
favorite count: 0
upvote count: 2
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90341427
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90341161
has title: Google cloud ML with Scikit-Learn raises: 'dict' object has no attribute 'lower'
has body: I used the following tutorial to use my Scikit-learn sentiment-analysis model in Google Cloud: https://cloud.google.com/ml-engine/docs/scikit/quickstart My model defined as follows: import csv import os from collections import defaultdict import sys import re import numpy as np import random import math import sklearn.datasets from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier from sklearn import metrics from sklearn.model_selection import GridSearchCV from sklearn.externals import joblib from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score def build_data_cv(datafile, trait_number): """ Loads data """ with open(datafile, "rb") as csvf: csvreader = csv.reader(csvf,delimiter=',',quotechar='"') data = [] target = np.array([]) for index, line in enumerate(csvreader): # escape header if index &lt; 1: continue document = unicode(line[1], errors='replace') data.append(document) index_of_trait = trait_number + 2 if line[index_of_trait].lower()=='y': target = np.append(target, 1.0) else: target = np.append(target, 0.0) dataset = sklearn.datasets.base.Bunch(data=data, target=target) dataset.target_names = ["positive", "negative"] return dataset # main program if __name__=="__main__": current_directory = os.getcwd() + "/" data_file = current_directory + "essays.csv" class_labels = ['EXT','NEU','AGR','CON','OPN'] for index, selected_trait in enumerate(class_labels): print selected_trait dataset = build_data_cv(data_file, index) X_train, X_test, y_train, y_test = train_test_split(dataset.data, dataset.target, test_size=0.2, random_state=0) clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=42, max_iter=5, tol=None)), ]) # clf.fit(X_…
has comment: http://stackoverflow.com/comment/90340860
type: Question
downvote count: 0
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/90365012
has text: @sammydude you can do the same inside `get_context_data` method.
type: Comment
comment on: http://stackoverflow.com/a/51700671
score: 0
type: AnswerComment

http://stackoverflow.com/q/51784310
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90526132
has answer: http://stackoverflow.com/a/51784764
has answer: http://stackoverflow.com/a/76751523
tagged with: python-3.x
has body: When the user has incorrect input and press'Submit' button. The invalid message box will be shown. After the invalid message box has closed by the user, I want the entries by the user can be cleared. I have searched for some information. Someone recommends using 'delete'. However, I get some error when I use 'delete' Someone recommends setting the entry variable again as ''. However, I am confused where should I reset the variable. Can anyone tell me how to do ? def user_login(window): # some codes to find whether valid or not. Valid: found = True entry_value = entry_value.get() if found: messagebox.showinfo(title='Successful login', message='Valid password. Welcome to 7vinBB air traffic control system !') else: messagebox.showerror(title='Error', message='Invalid password. Please enter again. You have ' + str(5-count1) + ' times left') class LoginFrame(Frame): def __init__(self, master): super().__init__(master) self.entry_value = entry(self, font='Courier 17') self.login_button = button(command=lambda: user_login(root)) self.entry_value.place(x=330, y=245) self.login_button.place(x=440, y=420) root = Tk() lf = LoginFrame(root) root.mainloop()
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90526725
tagged with: tkinter
has title: Tkinter, can I clear all entries after inputting wrongly and press 'Submit' button by user?
has comment: http://stackoverflow.com/comment/90528471
score: 0
has comment: http://stackoverflow.com/comment/90525663

http://stackoverflow.com/a/61682733
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51788397
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/112588048
has body: As of Python 3.8, pprint has a sort_dicts keyword argument you can set to prevent it from sorting dictionary keys alphabetically. If you set it to false, it will use the default ordering of dictionaries (e.g. insertion order). Example: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(dict(z=0, a=1), sort_dicts=False) {'z': 0, 'a': 1}

http://stackoverflow.com/comment/90283501
type: Comment
comment on: http://stackoverflow.com/a/51658027
has text: I eventually got this working in my larger code. Unbeknowest to me, I had a forgotten variable called `list` that kept causing the `TypeError`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51687782
tagged with: pymongo
type: Question
tagged with: mongodb
has title: How to dump JSON file into mongodb using Python
has answer: http://stackoverflow.com/a/51691059
score: 0
answer count: 1
has body: First of all this hasn't been asked before or if I asked there wasn't any answer provided so I am opening this new thread. I need best way to dump a JSON file in mongodb. There could be multiple ways but I am looking for ways which gives good performance.
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/51753462
tagged with: google-chrome-extension
has comment: http://stackoverflow.com/comment/90471986
type: UnansweredQuestion
tagged with: python
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/90466821
answer count: 0
linked to: http://stackoverflow.com/q/38226305
type: Question
has body: I try to use Python to log in a web, type in use id and password, and download some files. however, before logging the page, there is a error msg says "Failed to load extension from C:\User\xyz\AppData\Local\Temp\scoped_dir12188_17478\internal. Loading of unpacked extensions is disabled by administrator" . After I hit "Enter", the rest goes well. I have searched here, and find one post is related to my question, Here. But the code is still not working for me. the pop up error windows is still showing up. Any ideas or suggestion is highly welcome. Thank you! Here is my code: import time import urllib3 from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options driverpath = 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python36\\chromedriver.exe' chrome_options = Options() chrome_options.add_argument("--disable-extensions") browser = webdriver.Chrome(executable_path=driverpath, chrome_options=chrome_options) url ='https://userid:password@weblink' browser.get(url)
has comment: http://stackoverflow.com/comment/90471978
score: 0
has title: Python disable Chrome Extension
has comment: http://stackoverflow.com/comment/90466933

http://stackoverflow.com/a/51644232
score: 1
upvote count: 1
downvote count: 0
has body: According to the Python documentation for XPath, only a small subset of XPath syntax is supported. You can use [n] to select a particular item by position, but the more general position() function is not supported. [position] Selects all elements that are located at the given position. The position can be either an integer (1 is the first position), the expression last() (for the last position), or a position relative to the last position (e.g. last()-1). If you want to ignore the first element you will have to iterate over the collection yourself.
type: Answer
answers question: http://stackoverflow.com/q/51643985

http://stackoverflow.com/comment/90263074
type: QuestionComment
has text: @WillemVanOnsem u r correct, nice !
score: 1
comment on: http://stackoverflow.com/q/51649732
type: Comment

http://stackoverflow.com/comment/90540082
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51791299
type: QuestionComment
has text: Welcome to your first question on StackOverflow. This code snippet is not complete, since you do not show us the `input.csv` file. You also do not show the full traceback for the error message. Please read and follow [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).

http://stackoverflow.com/q/51680287
tagged with: python
has title: Exit code -1 with while:True block
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90323902
has body: So I ran across an interesting problem in python today regarding return codes. I compressed down my code to as little as possible to show my point. Here is the code block: def main(): try: while True: print(".") except KeyboardInterrupt: print("Catch") return if __name__ == "__main__": main() Obviously you would never use code like this, I mean, it just print out infinite . and why would you want that? That is not the point however, the point is that when I terminate this program it not only does NOT print Catch but it returns an exit code of -1! Two questions based on that: Why does the try catch block not work? What can I use to catch this kind of error? EDIT Thank you for all your comments so far, a few notes and and a new question: My OS is Windows 10. I use Pycharm as my IDE, I use CTRL-SHIFT-F10 to run the program and CTRL-F2 to close it, which emulates the "run" and "terminate" buttons on the top right, my experience is that this counts as a keyboard interrupt. Pycharm displays the exit code after running code with configurations. So is the IDE close no longer counting as a keyboard inturrupt? If so, does anybody know how to configure it to do so? Or do I really just need to run the script from the terminal?
has comment: http://stackoverflow.com/comment/90325899
score: 0
has comment: http://stackoverflow.com/comment/90324375
has comment: http://stackoverflow.com/comment/90323896
has comment: http://stackoverflow.com/comment/90323976
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90323892
has comment: http://stackoverflow.com/comment/90323891

http://stackoverflow.com/comment/90499062
score: 0
type: AnswerComment
has text: Yes, I mentioned that the split was incorrect in the comments which is why the function is split into two. However preallocating the array `procs` seems a bit absurd to me, because you are making the code more complicated and difficult to understand for a performance benefit that might not even be measurable--you have to fork/exec each time through the loop, and that's orders of magnitude more expensive than `append`.
comment on: http://stackoverflow.com/a/51769087
type: Comment

http://stackoverflow.com/a/51693726
answers question: http://stackoverflow.com/q/51693585
has comment: http://stackoverflow.com/comment/90362689
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51693585
type: Answer
has body: The complexity of your both approaches is O(N^2) and that's because you have an indexing at each iteration (string[charIndex]). However your second approach is generally a better way to go in this case. But you could also do it in a more optimized way (in terms of run-time) using a dictionary comprehension as following: ascii_occurrence = {charIndex: ind for ind, charIndex in enumerate(string)} In this case besides not getting the characters with an indexing you don't need to assign items to a previously created dictionary. Instead, Python will creates the dictionary for you on demand which will save you calling the __setitem__ function at each iteration which itself is a combination of suspending and resuming the function frames. The complexity of this snippet in terms of both run-time and memory is of course O(N). Now, if you're looking for a way to be more optimized it's easily possible but you have to sacrifice a little bit of other thing. This is to say that if you want lesser run-time you should give up some memory and vice versa. But if you don't want to do this you may wanna consider creating your dictionary before you get to this point at all. You can create your dictionary at the time of creating the main string. There are also other tricky approaches that you can do here like creating a dict from the enumerate object directly by passing it to dict object. But in this case indexes will be the key and characters will become the value. ascii_occurrence = dict(enumerate(string))

http://stackoverflow.com/comment/90399054
type: AnswerComment
type: Comment
has text: @StephenRauch, I have limited knowledge on regex :(.
score: 1
comment on: http://stackoverflow.com/a/51719059

http://stackoverflow.com/q/51665042
answer count: 1
downvote count: 0
score: 1
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51665068
favorite count: 0
tagged with: time
has title: Reorder timestamps pandas
upvote count: 1
has body: I have a pandas column that contain timestamps that are unordered. When I sort them it works fine except for the values H:MM:SS. d = ({ 'A' : ['8:00:00','9:00:00','10:00:00','20:00:00','24:00:00','26:20:00'], }) df = pd.DataFrame(data=d) df = df.sort_values(by='A',ascending=True) Out: A 2 10:00:00 3 20:00:00 4 24:00:00 5 26:20:00 0 8:00:00 1 9:00:00 Ideally, I'd like to add a zero before 5 letter strings. If I convert them all to time delta it converts the times after midnight into 1 day plus n amount of hours. e.g. df['A'] = pd.to_timedelta(df['A']) A 0 0 days 08:00:00 1 0 days 09:00:00 2 0 days 10:00:00 3 0 days 20:00:00 4 1 days 00:00:00 5 1 days 02:20:00 Intended Output: A 0 08:00:00 1 09:00:00 2 10:00:00 3 20:00:00 4 24:00:00 5 26:20:00
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51665068
type: Question

selenium-webdriver
tags question: http://stackoverflow.com/q/51651627
tags question: http://stackoverflow.com/q/51756925
tags question: http://stackoverflow.com/q/51686224
tags question: http://stackoverflow.com/q/51682386
tags question: http://stackoverflow.com/q/51700417
tags question: http://stackoverflow.com/q/51732570
tags question: http://stackoverflow.com/q/51736487
tags question: http://stackoverflow.com/q/51723825
tags question: http://stackoverflow.com/q/51682413
tags question: http://stackoverflow.com/q/51769191
tags question: http://stackoverflow.com/q/51689617
tags question: http://stackoverflow.com/q/51732681
tags question: http://stackoverflow.com/q/51795743
tags question: http://stackoverflow.com/q/51742140
tags question: http://stackoverflow.com/q/51777361
tags question: http://stackoverflow.com/q/51666661
tags question: http://stackoverflow.com/q/51681276
tags question: http://stackoverflow.com/q/51709267
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/51784033
tags question: http://stackoverflow.com/q/51736882
tags question: http://stackoverflow.com/q/51646908
tags question: http://stackoverflow.com/q/51737769
tags question: http://stackoverflow.com/q/51679081
tags question: http://stackoverflow.com/q/51756089
tags question: http://stackoverflow.com/q/51721185
tags question: http://stackoverflow.com/q/51647573
tags question: http://stackoverflow.com/q/51673700
tags question: http://stackoverflow.com/q/51755623
tags question: http://stackoverflow.com/q/51696754
tags question: http://stackoverflow.com/q/51724472
tags question: http://stackoverflow.com/q/51714711
tags question: http://stackoverflow.com/q/51776295
tags question: http://stackoverflow.com/q/51743859
tags question: http://stackoverflow.com/q/51723000
tags question: http://stackoverflow.com/q/51747425
tags question: http://stackoverflow.com/q/51747778
type: Tag
tags question: http://stackoverflow.com/q/51720074
tags question: http://stackoverflow.com/q/51781657
tags question: http://stackoverflow.com/q/51739332
tags question: http://stackoverflow.com/q/51707357
tags question: http://stackoverflow.com/q/51775122
tags question: http://stackoverflow.com/q/51770608
tags question: http://stackoverflow.com/q/51685330
tags question: http://stackoverflow.com/q/51709239
tags question: http://stackoverflow.com/q/51642133
tags question: http://stackoverflow.com/q/51654651
tags question: http://stackoverflow.com/q/51778832
tags question: http://stackoverflow.com/q/51693420
tags question: http://stackoverflow.com/q/51679002

http://stackoverflow.com/comment/121786979
comment on: http://stackoverflow.com/a/67808043
has text: The approach of setting ncolors as per Hakan Özler's comment. Sorry for the confusion
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51798813
accepted answer of: http://stackoverflow.com/q/51797925
type: Answer
answers question: http://stackoverflow.com/q/51797925
has body: For windows you can use topmost root.wm_attributes("-topmost", 1)
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/51774831
tagged with: pyodbc
answer count: 1
has title: pyodbc is present in showing "No module name pyodbc"
accepted answer: http://stackoverflow.com/a/51774930
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 1
tagged with: python-3.x
has body: I am trying to connect my python code to sql server. But there is an error which shows: import pyodbc ModuleNotFoundError: No module named 'pyodbc' import pyodbc cnxn = pyodbc.connect("Driver={SQL Server};" "Server=localhost;" "Database=SCMS2;" "uid=sa;pwd=tazbirul94") cursor = cnxn.cursor() cursor.execute('SELECT * FROM Suppliers') for row in cursor: print('row = %r' % (row,)) Here is the pip freeze command: This shows my odbc is present: Here is the error Here is my pycharm environment path
has answer: http://stackoverflow.com/a/51774930
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90354431
comment on: http://stackoverflow.com/q/51696475
score: 2
has text: You're saying that "urllib is not as easy to use as it could be". So use requests instead: https://pypi.org/project/requests/ . Also, at some point instead of `split()` you'll find it easier to use Beautiful Soup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51650591
downvote count: 0
favorite count: 0
tagged with: inkscape
has title: Inkscape extension: python doesn't invoke .exe
has body: I'm developing a plugin for Inkscape. Some versions: Inkscape v0.92.3 Windows 10, version 1803 (build 17134.165) Python 3.7 explicitly installed MonoDevelop Version 7.7 Preview (7.7) Extra versions below Installation Locations: Inkscape: C:\Program Files\Inkscape Extension: C:\Program Files\Inkscape\share\extensions Contains: myplugin.inx, myplugin.py, MyPlugin.exe I've made a plugin which, for development reasons, works as currently intended. Most important of all, it runs when I run it either from MonoDevelop, or the built exe itself (both with the generated .dll's etc in the same location, or with only the exe copied to a different location). I use (a slightly edited version of) SugarPillStudio's python script to run the .exe file. However, when I run that python script by invoking the extension, the .exe is not launched. Inkscape blinks a message that says 'MyPlugin is launching...' and closes that as fast as it opens. I know that the python script works, because I have it print debugging lines to a .log file on my desktop. I know that the .exe doesn't launch because I have it also writing lines to the same .log file, first thing when the main() is invoked. When I (successfully) run the .exe it does print to the file, when I run the extension it doesn't. This leads me to believe there's a problem with the python script in invoking the .exe. Any help? Python Script: #!/usr/bin/env python ''' sugarpillstudios.com/wp/?p=142 ''' import os, sys, subprocess, datetime f=open("C:\Users\Diamundo\Documents\plugin.log", "a+") f.write("[PYT] %s Python script called at: %s.\n" % (datetime.datetime.now().isoformat(), os.getcwd() ) ) argv = [] for arg in sys.argv[:]: if arg.startswith("--executable="): executable = arg.split("=")[1] else: argv.append(arg) argv[0] = executable f.write("[PYT] %s %s\n" % ( datetime.datetime.now().isoformat(), executable ) ) process = subprocess.Popen(argv,shell=False,stdout=subprocess.PIPE) print process.communicate()[0] Plugin.inx: MyPlugin name…
tagged with: python
accepted answer: http://stackoverflow.com/a/51705157
tagged with: subprocess
possible better answer: http://stackoverflow.com/a/51658523
upvote count: 1
has answer: http://stackoverflow.com/a/51658523
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/51705157
answer count: 2

xlwings
tags question: http://stackoverflow.com/q/51676628
type: Tag
tag name: xlwings

http://stackoverflow.com/comment/90460642
score: 0
has text: Possible duplicate of [avrdude: ser\_open(): can't open device "/dev/ttyACM0": Device or resource busy](https://stackoverflow.com/questions/40951728/avrdude-ser-open-cant-open-device-dev-ttyacm0-device-or-resource-busy)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51749228

http://stackoverflow.com/comment/90265766
comment on: http://stackoverflow.com/q/51651063
has text: oh ok i will try
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90463224
comment on: http://stackoverflow.com/q/51751589
score: 0
type: Comment
type: QuestionComment
has text: Having the exact command used to run things, in easy copy-passable form, can be useful information if, e.g., you need to reproduce the same test with a different Python installation, or explain some weird behavior in a Stack Overflow question. When it’s not needed, it’s ugly. And I can understand why you might want to disable it by default (you can always turn it back on when you need it, right?), so this isn’t an answer; I’m just pointing out that debuggers naturally tend to err on the side of too much ugliness by default rather than too little.

http://stackoverflow.com/a/51682994
has comment: http://stackoverflow.com/comment/137967119
upvote count: 8
has comment: http://stackoverflow.com/comment/133075333
has comment: http://stackoverflow.com/comment/133043397
has comment: http://stackoverflow.com/comment/90718103
answers question: http://stackoverflow.com/q/51641546
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133009278
has body: You can have an expected condition class to wait for a combination of expected conditions. Here is an example of one. class wait_for_all(object): def __init__(self, methods): self.methods = methods def __call__(self, driver): try: for method in self.methods: if not method(driver): return False return True except StaleElementReferenceException: return False This would then be used by building an array of the expected conditions and checking for all of them in the same wait. (Example lines split for clarity.) methods = [] methods.append(EC.visibility_of_element_located(BY.ID, "idElem1")) methods.append(EC.visibility_of_element_located(BY.ID, "idElem2")) method = wait_for_all(methods) WebDriverWait(driver, 5).until(method) This will perform one five second wait while checking for visibility of two different elements. I have documented this further in a blog post here.
accepted answer of: http://stackoverflow.com/q/51641546
score: 8
has comment: http://stackoverflow.com/comment/112149397
type: Answer
has comment: http://stackoverflow.com/comment/93112861
has comment: http://stackoverflow.com/comment/90677941
has comment: http://stackoverflow.com/comment/137937391
downvote count: 0

http://stackoverflow.com/comment/90559456
has text: This suggestion is not good. The second `while` loop blocks the execution of the main `while` loop.
comment on: http://stackoverflow.com/a/51797485
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90303079
comment on: http://stackoverflow.com/a/51670233
score: 0
type: AnswerComment
has text: @BilalKhan as far as I know, no. The [docs](https://docs.python.org/2/library/threading.html#threading.Thread) say that target has to be a callable object
type: Comment

http://stackoverflow.com/q/51676275
score: 3
has body: I am trying to use XGBoost with GPU on Google Colaboratory. Here is my notebook: import numpy as np import os import xgboost as xgb train_X = np.random.rand(100,5) train_Y = np.random.choice(2, 100) test_X = np.random.rand(10,5) test_Y = np.random.choice(2, 10) xg_train = xgb.DMatrix(train_X, label=train_Y) xg_test = xgb.DMatrix(test_X, label=test_Y) param = {} # use softmax multi-class classification param['objective'] = 'multi:softmax' # scale weight of positive examples param['eta'] = 0.1 param['max_depth'] = 6 param['silent'] = 1 param['nthread'] = 4 param['num_class'] = 2 param['gpu_id'] = 0 param['max_bin'] = 16 param['tree_method'] = 'gpu_hist' # watchlist allows us to monitor the evaluation result on all data in the list watchlist = [(xg_train, 'train'), (xg_test, 'test')] num_round = 5 bst = xgb.train(param, xg_train, num_round, watchlist) When I run last line: bst = xgb.train(param, xg_train, num_round, watchlist) I get "Runtime died, Automatically restarting" Any ideas how to troubleshoot?
has answer: http://stackoverflow.com/a/54044849
has answer: http://stackoverflow.com/a/56991425
has comment: http://stackoverflow.com/comment/117243377
has title: XGBoost with GPU on Google Colaboratory
downvote count: 0
has answer: http://stackoverflow.com/a/67096883
tagged with: google-colaboratory
tagged with: xgboost
favorite count: 0
has answer: http://stackoverflow.com/a/51760112
tagged with: gpu
tagged with: python
answer count: 4
upvote count: 3
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/51775992
accepted answer of: http://stackoverflow.com/q/51775903
answers question: http://stackoverflow.com/q/51775903
score: 0
has comment: http://stackoverflow.com/comment/90510655
type: AcceptedAnswer
has body: It wants you to transform your input. Try using X_poly = poly_features.fit_transform(X.values.reshape(1,-1))[1]
has comment: http://stackoverflow.com/comment/90510615
type: Answer

http://stackoverflow.com/comment/90273856
type: Comment
has text: I’m not killing it manually, it just displays that warning and then the command input line comes back for me to type something else. that’s why i assumed it was this warning preventing it from running
type: QuestionComment
comment on: http://stackoverflow.com/q/51650896
score: 0

http://stackoverflow.com/a/51658048
has comment: http://stackoverflow.com/comment/90280032
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51657999
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51657999
type: Answer
score: 2
downvote count: 0
has body: If type of key column is string use radd: df['key'] += df.groupby('key').cumcount().add(1).astype(str).radd('_') #alternative #df['key'] += '_' + df.groupby('key').cumcount().add(1).astype(str) If integer first is necessary converting: df['key'] = df['key'].astype(str) + '_' + df.groupby('key').cumcount().add(1).astype(str) print (df) line# key amino0 pos0 amino1 pos1 amino2 pos2 0 0 14_1 A 13 M 2 K 14 1 1 12_1 A 13 M 2 A 1 2 2 1_1 A 1 M 2 P 3 3 3 2_1 P 3 P 4 B 6 4 4 1_2 A 1 M 2 P 35 5 5 12_2 A 31 A 32 M 41 6 6 1_3 M 24 P 23 A 22 7 7 12_3 A 31 A 32 M 42 8 8 4_1 J 5 P 4 B 6 9 9 3_1 B 6 I 7 P 4 10 10 8_1 B 6 H 10 I 7 Details: First use GroupBy.cumcount for counter per groups defined by colum key: print (df.groupby('key').cumcount()) 0 0 1 0 2 0 3 0 4 1 5 1 6 2 7 2 8 0 9 0 10 0 dtype: int64 Then add 1 for starting by 1, it is like + 1: print (df.groupby('key').cumcount().add(1)) 0 1 1 1 2 1 3 1 4 2 5 2 6 3 7 3 8 1 9 1 10 1 dtype: int64 For converting to strings use astype, object means obviously string: print (df.groupby('key').cumcount().add(1).astype(str)) 0 1 1 1 2 1 3 1 4 2 5 2 6 3 7 3 8 1 9 1 10 1 dtype: object

http://stackoverflow.com/a/51787228
has body: Okay, I figured it out. Listing all properties of a form by: form = SignUpForm() for d in dir(form): print(d) I found, by trials and errors, that you can list fields of the form: form = SignUpForm() for d in form.fields: print('field name:', d) print('field label:', form.fields[d].label) print('field text:', form.fields[d].help_text) print("") returns: field name: username field label: Username field text: Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. field name: display_name field label: None field text: Your display name field name: password1 field label: Password field text: Your password can't be too similar to your other personal information. Your password mus t contain at least 8 characters. Your password can't be a commonly used password. Your password can& #39;t be entirely numeric. field name: password2 field label: Password confirmation field text: Enter the same password as before, for verification. I can easily alter those fields by writting: x = form.fields['username'] x.label = "foo" x.help_text = "bar" and I got:
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90540330
accepted answer of: http://stackoverflow.com/q/51787227
has comment: http://stackoverflow.com/comment/90532592
downvote count: 0
answers question: http://stackoverflow.com/q/51787227
type: AcceptedAnswer

http://stackoverflow.com/comment/90402862
score: 0
has text: @John: In more detail: If the user presses a final button on the MSS screen, an `MSS.result` will be set. So far I did not manage to stop the ApplicationFlow until this result is available. A `while "result not available" loop`has the effect that the MSS screen is not even shown, probably as the main thread is busy. I was only successful, when I moved the ApplicationFlow to another thread ... but this does not seem to work either.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51701737

http://stackoverflow.com/comment/90349496
has text: you gave the first solution which dealt the duplication problem and so I give it to you.
comment on: http://stackoverflow.com/a/51693991
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90366308
type: QuestionComment
has text: **You Should first code and if you're unable to resolve then ask Questions in SOF** Yet go through this https://github.com/NsrM/hello-world/blob/master/StackOflow1 for java code for your problem.
score: 0
comment on: http://stackoverflow.com/q/51701318
type: Comment

http://stackoverflow.com/q/51726839
answer count: 0
has comment: http://stackoverflow.com/comment/90414104
has comment: http://stackoverflow.com/comment/90416585
type: Question
tagged with: python-3.6
score: 0
has comment: http://stackoverflow.com/comment/90415519
has title: How can I display monospace font(or constant distance) in console on cross-platform?
has body: I'm developing CLI game which contains expression of Metro. I want to display on console like it, and I did it on windows. The code translate XML(XY location data) to links, that contains signs of Station: class Metro(): def __init__(self, data_root): # data_root는 xml을 파싱한 루트 요소이다. self.data_root = data_root # self.stations_dic 딕셔너리에 '인덱스 번호 : 각 요소' 구조를 넣는다. self.stations_dic = {} for element in self.data_root.findall('station'): station = Station(element) self.stations_dic[int(element.attrib['index_number'])] = station # 아래 코드에서는 2차원 배열로 맵을 작성한다. # self.metro_map[x좌표][y좌표] 는 'station' Element를 반환한다. x_list = [] y_list = [] for key in self.stations_dic.keys(): locate = self.stations_dic[key].location x_list.append(locate[0]) y_list.append(locate[1]) self.max_x = max(x_list) self.max_y = max(y_list) self.symbol_map = [[None]*(self.max_y + 1) for i in range(self.max_x + 1)] for key in self.stations_dic.keys(): locate = self.stations_dic[key].location self.symbol_map[locate[0]][locate[1]] = self.stations_dic[key] for near_i in self.stations_dic[key].near_number_list: symbol = self.stations_dic[key] * self.stations_dic[near_i] if symbol != None: sy_locate = symbol.locate self.symbol_map[sy_locate[0]][sy_locate[1]] = symbol # self.metro_map은 바뀌지 않고 불러와 설정한 대로 불변이어야 한다. def etro_display(self, current_location): # 이 파일을 import하고 m = Metro(인자)로 선언한 뒤 # m.etro_display(location) 형태로 사용한다. from colorama import init, Fore, Back, Style init() c = {1 : Fore.RED, 2 : Fore.GREEN, 3 : Fore.YELLOW, 4 : Fore.BLUE, 5 : Fore.MAGENTA, 6 : Fore.WHITE, 7 : Fore.CYAN} # 노선도를 출력하는 부분이다. for y in range(0, self.max_y + 1): for x in range(0, self.max_x + 1): if [x, y] == current_location: print(Style.RESET_ALL + Fore.WHITE + Back.BLACK + '●', end='') else: try: if isinstance(self.symbol_map[x][y].line, int) == True: print(Style.RESET_ALL + c[self.symbol_map[x][y].line] + Back.BLACK + self.symbol_map[x][y].symbol, end='') else: print(Style.RESET_ALL + Fore.WHITE + Back.BLACK + self.symbol_map[x]…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51775179
has comment: http://stackoverflow.com/comment/90509186
has comment: http://stackoverflow.com/comment/90509296
accepted answer of: http://stackoverflow.com/q/51774922
type: Answer
upvote count: 2
has body: You basically want to use dfTeam as a dictionary to map Team Codes to Names. For each column, you can just perform the mapping. d = dfTeam.set_index('Team Code').Name for oldName,newName in teamDict.items(): dfFULL[newName] = dfFULL[oldName].map(d) # Then get rid of all old names dfFull = dfFull.drop(columns=list(teamDict.keys()))
has comment: http://stackoverflow.com/comment/90509149
score: 2
answers question: http://stackoverflow.com/q/51774922
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51673938
tagged with: python-2.7
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51674058
accepted answer: http://stackoverflow.com/a/51674058
upvote count: 10
tagged with: python
type: AnsweredQuestion
has body: I have 2 rows that look like these, ------------------------------ DealName | Target | Acquirer | ----------------------------- ABC-XYZ | ABC | None | ------------------------------ ABC-XYZ | None | XYZ | ------------------------------ I'm looking to merge them into a single as: ------------------------------ DealName | Target | Acquirer | ----------------------------- ABC-XYZ | ABC | XYZ | ------------------------------ Not sure how to accomplish this in Pandas. Any pointers will be highly appreciated! Thanks in advance
tagged with: pandasql
type: Question
has title: Pandas Merge two rows into a single row based on columns
score: 9

http://stackoverflow.com/q/51663348
has title: Custom Accuracy/Loss for each Output in Multiple Output Model in Keras
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/99021058
tagged with: python
has answer: http://stackoverflow.com/a/54042409
score: 2
linked to: http://stackoverflow.com/q/56180206
upvote count: 2
tagged with: tensorflow
has body: I am trying to define custom loss and accuracy functions for each output in a two output neural network model using Keras. Let's call the two outputs: A and B. My objectives are: Give the accuracy/loss functions for one of the outputs names such that they can be reported on the same graphs in tensorboard as the same corresponding output from older/existing models I have laying around. So for example, accuracies and losses for output A in this two output network should be viewable in the same graph in tensorboard as output A of some older model that I have. More specifically, these older models all output A_output_acc, val_A_output_acc, A_output_loss and val_A_output_loss. So I want the corresponding metric readouts for the A output in this new model to have those names as well so that they are viewable/comparable on the same graph in tensorboard. Allow for easy configuration of accuracy/loss functions so that I can swap at whim different losses/accuracies for each output without hard coding them. I have a Modeler class that constructs and compiles a network. The relevant code follows. class Modeler(BaseModeler): def __init__(self, loss=None,accuracy=None, ...): """ Returns compiled keras model. """ self.loss = loss self.accuracy = accuracy model = self.build() ... model.compile( loss={ # we are explicit here and name the outputs even though in this case it's not necessary "A_output": self.A_output_loss(),#loss, "B_output": self.B_output_loss()#loss }, optimizer=optimus, metrics= { # we need to tie each output to a specific list of metrics "A_output": [self.A_output_acc()], # self.A_output_loss()], # redundant since it's already reported via `loss` param, # ends up showing up as `A_output_loss_1` since keras # already reports `A_output_loss` via loss param "B_output": [self.B_output_acc()] # self.B_output_loss()] # redundant since it's already reported via `loss` param # ends up showing up as `B_output_loss_1` since keras # already reports `B_output_loss` via loss pa…
type: Question

http://stackoverflow.com/q/51662838
has comment: http://stackoverflow.com/comment/90289625
has title: Pandas Column based on values in other columns
has comment: http://stackoverflow.com/comment/90289136
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51663479
downvote count: 0
has comment: http://stackoverflow.com/comment/90289215
has comment: http://stackoverflow.com/comment/90289758
has body: Basically, I would like to fill in column Discount_Sub_Dpt with 'Yes' or 'No' depending on if there is a Discount for that Sub_Dpt for that week EXCLUDING the product on which that row lands (for instance I don't want any of the A rows to consider whether there is a Discount for that week for A but rather only for the products in that sub department(in most cases there is more than one other product). I have tried using groupby with Sub_Dpt and Week to no avail. Does anyone know how to solve this issue? The Yellow column is obviously the desired outcome from the code. Here is some of the code I have used, I am trying to create the column first and then update the values (but it could all potentially be wrong) (also I intentionally named the data frame df1): df1['Discount_Sub_Dpt'] = np.where((df1['Discount']=='Yes'),'Yes','No') grps = [] grps.append(df1.Sub_Dpt.unique()) for x in grps: x = str(x) yes_weeks = df1.loc[(df1.Discount_SubDpt == 'Yes') &amp; (df1.Sub_Dpt_Description == x),'Week'].unique() df1.loc[df1['Week'].isin(yes_weeks) &amp; df1['Sub_Dpt_Description'] == x, 'Discount_SubDpt'] = 'Yes'
has comment: http://stackoverflow.com/comment/90289241
favorite count: 0
has comment: http://stackoverflow.com/comment/90289660
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
possible better answer: http://stackoverflow.com/a/51663477
has comment: http://stackoverflow.com/comment/90289195
has answer: http://stackoverflow.com/a/51663429
answer count: 4
has answer: http://stackoverflow.com/a/51663477
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90289339
has answer: http://stackoverflow.com/a/51663210
has comment: http://stackoverflow.com/comment/90289378
score: 1
has answer: http://stackoverflow.com/a/51663479
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90289229

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/51763447

http://stackoverflow.com/comment/90381375
has text: It wonderfully did the trick @Andrej. Provided a plus. Gonna accept it in a while. Btw, can you provide a little description on what this line `formdata[i['name']] = 'Results'` is actually doing here? Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51709302
type: Comment

http://stackoverflow.com/a/51724077
type: Answer
answers question: http://stackoverflow.com/q/51723910
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90412337
has body: If you debug the first line of code which says: pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32) and then use pts.shape, you will get (4, 2), which means that pts at this point in time has 4 rows and 2 columns. Now it may be possible that the function which is taking this matrix is expecting the input in some other format, which in your case seems to be (4, 1, 2), which means 4 rows, 1 column and each element with 2 sub-elements. To convert the (4, 2) shape in (4, 1, 2) shape, we use the following line of code: pts = pts.reshape((-1,1,2)) What the above line means is that, I need a matrix with unknown number of rows but a single column and each element with 2 sub-elements. Now numpy internally calculates the size of unknown and automatically creates a matrix for you. It is just a fancy way of doing pts.reshape((4,1,2)) Also quoting the documentation: One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
has comment: http://stackoverflow.com/comment/90411618
downvote count: 0

http://stackoverflow.com/comment/90364119
score: 0
has text: The amc file already contains the joint angles. What more do you need?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51698806

http://stackoverflow.com/a/51688209
score: 1
answers question: http://stackoverflow.com/q/51684727
accepted answer of: http://stackoverflow.com/q/51684727
type: AcceptedAnswer
downvote count: 0
has body: As was said by @Zero, so you can mark this as answered, you can use: population.shift(1).rolling(2).min()
type: Answer
upvote count: 1

http://stackoverflow.com/q/51783225
downvote count: 1
favorite count: 0
upvote count: 0
has body: I have some problems with joining CSV files together. I successfully joined 4 files using Pandas.join method. But now when I want to join next files, I can't do that.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51783720
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90523750
type: Question
answer count: 1
tagged with: database
score: -1
has title: Joining CSV files together using Pandas
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/51797306
downvote count: 1
has comment: http://stackoverflow.com/comment/90551818
upvote count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51798482
score: -1
type: Question
has title: Scikit learn and data set analysis
has answer: http://stackoverflow.com/a/51798482
answer count: 1
tagged with: scikit-learn
favorite count: 0
has body: I am new to Scikit learn and I tried the first program they have given in their website the code is given below: from sklearn import svm from sklearn import datasets clf = svm.SVC() iris = datasets.load_iris() X, y = iris.data, iris.target clf.fit(X, y) while I compile the last line I get the following error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: fit() missing 1 required positional argument: 'y' pls help me with this issue.

http://stackoverflow.com/comment/90252149
score: 0
has text: `matplotlib.collections.LineCollection.segments` might have the actual line parameters?
comment on: http://stackoverflow.com/q/51643995
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51712187
has answer: http://stackoverflow.com/a/51712460
has comment: http://stackoverflow.com/comment/90385799
score: 0
answer count: 1
has title: Creating lots of dictionaries from a list of names
tagged with: python
has comment: http://stackoverflow.com/comment/90386011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90386107
type: Question
has comment: http://stackoverflow.com/comment/90386140
has comment: http://stackoverflow.com/comment/90386223
has body: I am making a times table/ division game where I have created dictionaries for each times table and division (up to 12) made up of the question as the key and answer as the value. That is 24 dictionaries! There is surely a better way of doing this than what I have done, perhaps creating a for loop. I have managed to make each times table/ division dictionary using the following loop code (24 times; 12 for the multiple tables and 12 for the division equivalents) I have included an example of a multiple dictionary as well as a division one. eleven_division = {} for i in range (0,13): division_factor = 11 answer = i * division_factor eleven_division ['{} / {} ='.format(answer,division_factor)] = i six_times = {} for i in range (0,13): multiple = 6 answer = i * multiple six_times ['{} x {} ='.format(i,multiple)] = answer I would like to create all the dictionaries using nested for loops, but have each dictionary named in the following way: two_times, three_times, four_times. However, I can figure out a way to do this. I know I can do this to print out all the division tables. for x in range (1,13): division_factor = x for i in range (0,13): answer = i * division_factor print ('%s / %s = %s' %(answer, x, i)) I now need to create a new dictionary every time is goes through the loop so I thought the following might do it, but no! dicts =['one division', 'two division','three division','four division', 'five division', 'six division', 'seven division', 'eight division', 'nine division', 'ten division', 'eleven division', 'twelve division'] for f in dicts: f = {} for x in range (1,13): division_factor = x for i in range (0,13): answer = i * division_factor f ['{} x {} ='.format(answer,x)] = i print (one division) #THIS IS THE BIT I WANT WORKING! I hope I have made my issue clear enough for you. TIA!

http://stackoverflow.com/q/51716465
type: AnsweredQuestion
downvote count: 0
tagged with: docstring
accepted answer: http://stackoverflow.com/a/52550485
favorite count: 0
has body: Goal: generate docstring in vscode for Python automatically and format the generated docstring to my liking. Solution: I installed the autoDocstring extension. Problem: I don't know how to get the generated docstring to be formatted the way I want it. In the description under the "Extension Settings" heading, it seems to suggest that you can change the default format with the "autoDocstring.docstringFormat" setting. My question is, how does one configure that setting? I've looked around and cannot find a solution.
has answer: http://stackoverflow.com/a/73807627
score: 19
type: Question
possible better answer: http://stackoverflow.com/a/73807627
answer count: 2
tagged with: python
has title: Python Visual Studio Code autoDocstring Configuration
upvote count: 19
has answer: http://stackoverflow.com/a/52550485
tagged with: visual-studio-code

http://stackoverflow.com/comment/90414864
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51727132
has text: excellent! In order to have do without unit specification (inch, cm...), is there a way to simply multiply the current width by a number, say 4? In other words, given the default figsize values, we just want to scale them up or down by a certain factor.
type: AnswerComment

http://stackoverflow.com/a/51648074
answers question: http://stackoverflow.com/q/51648023
has body: You need: full_data = pd.concat([train,test]) df_new = pd.get_dummies(full_data, columns=categorical_columns, drop_first=True)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90260563

http://stackoverflow.com/a/51768273
has body: You don't. Add Guild Member allows your bot, which has been added to a server, to give other people access to the server. The ability to accept invites through the API has been intentionally removed. I don't expect the ability to log into the API with a username/password to remain long either. User automation/self bots (running a bot that uses a user account) is not allowed by Discord, and their API is changing to reflect that. If you have some other reason for needing this functionality, feel free to ask about that problem in more detail.
type: Answer
answers question: http://stackoverflow.com/q/51764308
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51764308
score: 0

http://stackoverflow.com/q/51795186
has comment: http://stackoverflow.com/comment/90548753
has comment: http://stackoverflow.com/comment/90548662
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51795221
tagged with: python
has comment: http://stackoverflow.com/comment/90548674
has body: I have a large csv that has null values as whitespace (e.g. " ,"). I need to turn them all to empty strings (",") for some datatype-specific stuff I need to do in postgres. I thought this would be a FAQ, but I can't seem to find another example of someone doing this in Pandas. I'm guessing I need to iterate through my csv and replace each instance of ", ," with ",,". Here's an example of two rows. You can see that the empty cells are whitespaces: 11111.00130.00000,12,NAME NAME T YES,2017,0,1477.51,1477.51, ,444 ALPHABET AVE,COLUMBUS,AL,12345-4544,RESIDENTIAL,10/1/2017, ,N,Y,ROBERTS,BLOCK 1,LOTS 19-20, , , ,1/1/1900, , ,479.29,159.95,327.14,104.27,406.86,0,0,0,0 11111.00130.00000,12,NAME NAME T YES,2016,0,1411.59,1411.59, ,333 ALPHABET AVE,COLUMBUS,AL,12345-4544,RESIDENTIAL,10/1/2016, ,N,Y,ROBERTS,BLOCK 1,LOTS 19-20, , , ,1/1/1900, , ,479.29,158.58,312.6,72.95,388.17,0,0,0,0
favorite count: 0
type: UnansweredQuestion
tagged with: etl
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90547965
has comment: http://stackoverflow.com/comment/90548742
has title: Use pandas to replace whitespace (" ,") with empty string (",") in csv
has comment: http://stackoverflow.com/comment/90547920
has comment: http://stackoverflow.com/comment/90548737
has comment: http://stackoverflow.com/comment/90548027
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51798749

http://stackoverflow.com/comment/90324269
has text: This function is a callback.
comment on: http://stackoverflow.com/q/51680405
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51845255
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/51726018
answers question: http://stackoverflow.com/q/51726018
has body: I modified snippet you provided. Main change was not using html dataframe as attachment but just insert it in message body. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage with open('df.html', 'w') as fil: df.head().to_html(fil) att1 = 'df.html' att2 = path + 'Indices.png' att3 = path + 'Segments.png' subject = 'Market Update' body = 'This Weeks Report' msg = MIMEMultipart('alternative') msg["To"] = myEml msg["From"] = myEml msg["Subject"] = subject with open(att1, 'r') as fp: html = fp.read() msgText = MIMEText('%s %s ' % (body, html, att2, att3), 'html') msg.attach(msgText) with open(att2, 'rb') as fp: img = MIMEImage(fp.read()) img.add_header('Content-ID', '<{}>'.format(att2)) msg.attach(img) with open(att3, 'rb') as fp: img = MIMEImage(fp.read()) img.add_header('Content-ID', '<{}>'.format(att3)) msg.attach(img) s = smtplib.SMTP_SSL(mySMTP, smtpPORT) s.ehlo() s.starttls() s.login(username,password) s.sendmail(me,you, msg.as_string()) s.quit()
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51660755
has answer: http://stackoverflow.com/a/51660904
has comment: http://stackoverflow.com/comment/90285128
type: Question
has answer: http://stackoverflow.com/a/51660830
has body: Performing a filter within groupby and encountering trouble. The filter is for the elements within each dataframe of the groupby; unique to that dataframe of the groupby. I want to groupby the first df on ID, then return a df filtered for the values on a condition shown in conditions_df. That condition is associated with the same value as the first groupby. df = pd.DataFrame({'ID':[1,1,2,2,3,3], 'V': [0,1,1,0,1,1]}) condition_df = pd.DataFrame(index = [1,2,3], data= {'Condition': [0,1,1]}) I'd like to see a data frame returned: df = pd.DataFrame({'ID':[1,2,3,3], 'V': [0,1,1,1]}) This does not seem to work. df.groupby(['ID']).filter(lambda x: x['V'] == condition_df.loc[x.index, ['Condition']]) Even simplifying without that lookup in condition does not seem to work. df.groupby(['ID']).filter(lambda x: x['V'] == 0) Both return a "TypeError: filter function returned a Series but expected a scalar bool" Totally open to alternative methods of accomplishing the same complex filtering task!
has title: Groupby Filter unique to Group
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/51660873
has comment: http://stackoverflow.com/comment/90285026
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/comment/90393473
has text: @snoopy Every object in CPython has to include at least a refcount, and a pointer to its type. So, on a 64-bit platform, the smallest non-singleton objects are 24 bytes.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51716019

http://stackoverflow.com/q/51794398
linked to: http://stackoverflow.com/q/33769041
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90592729
linked to: http://stackoverflow.com/q/43568778
has comment: http://stackoverflow.com/comment/90607601
tagged with: loss-function
tagged with: tensorflow
type: Question
has title: Constructing a Custom Loss Function in Keras
linked to: http://stackoverflow.com/q/41514722
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51827450
accepted answer: http://stackoverflow.com/a/51827450
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90607921
has body: I am attempting to write a custom loss function in Keras from this paper. Namely, the loss I want to create is this: This is a type of ranking loss for multi-class multi-label problems. Here are the details: Y_i = set of positive labels for sample i Y_i^bar = set of negative labels for sample i (complement of Y_i) c_j^i = prediction on i^th sample at label j In what follows, both y_true and y_pred are of dimension 18. def multilabel_loss(y_true, y_pred): """ Multi-label loss function. More complete description here... """ zero = K.tf.constant(0, dtype=tf.float32) where_one = K.tf.not_equal(y_true, zero) where_zero = K.tf.equal(y_true, zero) Y_p = K.tf.where(where_one) Y_n = K.tf.where(where_zero) n = K.tf.shape(y_true)[0] loss = 0 for i in range(n): # Here i is the ith sample; for a specific i, I find all locations # where Y_p, Y_n belong to the ith sample; axis 0 denotes # the sample index space Y_p_i = K.tf.equal(Y_p[:,0], K.tf.constant(i, dtype=tf.int64)) Y_n_i = K.tf.equal(Y_n[:,0], K.tf.constant(i, dtype=tf.int64)) # Here I plug in those locations to get the values Y_p_i = K.tf.where(Y_p_i) Y_n_i = K.tf.where(Y_n_i) # Here I get the indices of the values above Y_p_ind = K.tf.gather(Y_p[:,1], Y_p_i) Y_n_ind = K.tf.gather(Y_n[:,1], Y_n_i) # Here I compute Y_i and its complement yi = K.tf.shape(Y_p_ind)[0] yi_not = K.tf.shape(Y_n_ind)[0] # The value to normalize the inner summation normalizer = K.tf.divide(1, K.tf.multiply(yi, yi_not)) # This creates a matrix of all combinations of indices k, l from the # above equation; then it is reshaped prod = K.tf.map_fn(lambda x: K.tf.map_fn(lambda y: K.tf.stack( [ x, y ] ), Y_n_ind ), Y_p_ind ) prod = K.tf.reshape(prod, [-1, 2, 1]) prod = K.tf.squeeze(prod) # Next, the indices are fed into the corresponding prediction # matrix, where the values are then exponentiated and summed y_pred_gather = K.tf.gather(y_pred[i,:].T, prod) s = K.tf.cast(K.sum(K.tf.exp(K.tf.subtract(y_pred_gather[:,0], y_pred_gather[:,1]))), tf.float64) l…
has comment: http://stackoverflow.com/comment/90608131
tagged with: tensor
upvote count: 2
tagged with: python

http://stackoverflow.com/q/51749603
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: Python script is randomly failing due to the CPU utilization at 99% and kernels kills my script
tagged with: cpu
has comment: http://stackoverflow.com/comment/90459192
has comment: http://stackoverflow.com/comment/90459560
has comment: http://stackoverflow.com/comment/90463411
type: Question
score: 0
tagged with: sql
has comment: http://stackoverflow.com/comment/90460853
has comment: http://stackoverflow.com/comment/90459514
has body: I have a python script that is getting killed by the kernel after reaching 99% CPU utilization. The python is performing SQL queries against a postgresql db and appending the results to a single JSON file. The issue occurs when I reach query 150 and the CPU utilization goes to 99+% and then the kernel kills the script. How can I improve my code so this doesn't happen? I would greatly appreciate your help! Code from __future__ import print_function try: import psycopg2 except ImportError: raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n') sys.exit(1) import re import sys import json import pprint import time outfilepath = "crtsh_output/crtsh_flat_file" outfilepath = "crtsh2" + ".json" DB_HOST = 'crt.sh' DB_NAME = 'certwatch' DB_USER = 'guest' # DELAY = 0 def connect_to_db(): start = 0 offset = 10 flag = True while flag: filepath = 'forager.txt' with open(filepath) as fp, open(outfilepath) as outfile: unique_domains = '' try: conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) cursor = conn.cursor() cursor.itersize = 10000 for cnt, domain_name in enumerate(fp): print("Line {}: {}".format(cnt, domain_name)) print(domain_name) domain_name = domain_name.rstrip() cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_keyAlgorithm(c.certificate), x509_keySize(c.certificate), x509_publicKeyMD5(c.certificate), x509_publicKey(c.certificate), x509_rsaModulus(c.certificate), x509_serialNumber(c.certificate), x509_signatureHashAlgorithm(c.certificate), x509_signatureKeyAlgorithm(c.certificate), x509_subjectName(c.certificate), x509_name(c.certificate), x509_name_print(c.certificate), x509_commonName(c.certificate), x509_subjectKeyIdentifier(c.certificate), x509_extKeyUsages(c.certificate), x509_certPolicies(c.certificate), x509_canIssueCerts(c.certificate), x509_getPath…
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90478352
tagged with: python
has comment: http://stackoverflow.com/comment/90459311

http://stackoverflow.com/comment/90423375
score: 9
type: Comment
type: QuestionComment
has text: try `model1.history.history['val_loss']` and similarly for others.
comment on: http://stackoverflow.com/q/51731207

http://stackoverflow.com/comment/90494896
has text: Solved! only the second part happens to be meaningful
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51767723
type: Comment

http://stackoverflow.com/q/51689442
type: Question
has answer: http://stackoverflow.com/a/51689457
has comment: http://stackoverflow.com/comment/90341850
linked to: http://stackoverflow.com/q/3754620
has comment: http://stackoverflow.com/comment/90340667
tagged with: boolean
tagged with: cs50
answer count: 2
favorite count: 0
tagged with: while-loop
type: UnansweredQuestion
has title: How did they break out from this while true loop?
has comment: http://stackoverflow.com/comment/90340809
tagged with: python
has answer: http://stackoverflow.com/a/51689489
score: -2
downvote count: 3
has body: In my understanding while True: mean loop forever, like saying while True == True. There is also mechanism to break out of the infinite loop using a break statement. I came across a function, in the cs50 module, using a while loop (to keep prompting for an int), where there is no break. I am trying to understand how, when we input an int the "True statement" change to False (that's how I understand it) in the loop and we stop prompting the user. In other words what can change the while True to false in the code? The function is as follow: def get_long(prompt=None): """ Read a line of text from standard input and return the equivalent long; if text does not represent a long, user is prompted to retry. If line can't be read, return None. """ while True: s = get_string(prompt) if s is None: return None if re.search(r"^[+-]?\d+$", s): try: return long(s, 10) except ValueError: pass # temporarily here for backwards compatibility if prompt is None: print("Retry: ", end="") The get_string() function used inside is as follow: def get_string(prompt=None): """ Read a line of text from standard input and return it as a string, sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n) as line endings. If user inputs only a line ending, returns "", not None. Returns None upon error or no input whatsoever (i.e., just EOF). Exits from Python altogether on SIGINT. """ try: if prompt is not None: print(prompt, end="") s = sys.stdin.readline() if not s: return None return re.sub(r"(?:\r|\r\n|\n)$", "", s) except KeyboardInterrupt: sys.exit("") except ValueError: return None I am trying to figure how the while True statement is no more true when the s variable get a string and when the string is casted into an int ? Can someone please explain this to me, maybe I am missing something about the while True: statements.
upvote count: 1

http://stackoverflow.com/comment/90381994
score: 0
type: Comment
has text: @DSM yep using mask is little bit redundant, since we have where already :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/51710258

http://stackoverflow.com/a/51735550
accepted answer of: http://stackoverflow.com/q/51735493
answers question: http://stackoverflow.com/q/51735493
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has body: "Truncate the file" does not mean writing over existing contents (but leaving that content present until it's overwritten); rather, it means entirely removing everything past the point at which the file is truncated. In this case, that point is the very beginning of the file. If you want to open the file and be able to read existing contents before performing an in-place write over any subset, r+ is the appropriate mode. Quoting a definition of "truncate" from WordNet 3.0, to "truncate" something is to cut it off, or cut it short: truncate 3: make shorter as if by cutting off; "truncate a word"; "Erosion has truncated the ridges of the mountains" [syn: truncate, cut short] Thus, the name matches well with the behavior at hand.
score: 3

http://stackoverflow.com/comment/90402585
type: Comment
has text: Alternatively, `del max` is easier and a bit more thorough. (It *looks* like it should make things worse, but it doesn't.)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51720946

http://stackoverflow.com/comment/90284802
has text: @ImportanceOfBeingErnest also if second one is a PDF then why doesnt it start at 0?
comment on: http://stackoverflow.com/q/51660271
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51735164
score: 1
upvote count: 1
has body: Most commands affecting subplots replace any axis existing in the same area. You've created a single axes for the figure with the line fig, ax = plt.subplots() Subsequent calls to subplots or subplot will remove this axis and create a new one. You need to setup both axes at the same time. You can execute fig, (ax1, ax2) = figure(ncol=2) Then use sca(ax1) before your current code. That will make ax1 the axis matplotlib draws on. After the current code and before the code to draw matrices use the command again to set ax2 (i.e. sca(ax2)).
accepted answer of: http://stackoverflow.com/q/51734780
answers question: http://stackoverflow.com/q/51734780
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90585890
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51788144
has text: Oh, I did a mistake, I named the `__init__.py` by `init.py` that's whay I got the error, It solves my problem so thank you so much
type: AnswerComment

http://stackoverflow.com/q/51693024
has answer: http://stackoverflow.com/a/51693137
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51693137
tagged with: python
favorite count: 0
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/51693134
tagged with: networkx
type: Question
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51693134
has title: Compare 2 lists while iterating through another list - Python
has body: I have a list source which represents nodes in a network graph. I iterate through the nodes in source to obtain a sub-list of neighbouring nodes. At the same time, all neighbouring nodes are compared against another list watch_list. I want to create a separate list adjacent that specifies whether the node in source has a neighbour in watch_list. See the code below: import networkx as nx import pandas as pd source = ['A','C','B','D','G','C','B','G'] target = ['B','T','G','A','T','B','H','V'] weight = [2, 1, 6, 6, 3, 3, 2, 1] watch_list = ['H','D','T'] df = pd.DataFrame([source,target,weight]) df = df.transpose() df.columns = ['source','target','weight'] G = nx.from_pandas_edgelist(df,'source','target','weight') adjacent = [] for i in source: for j in list(nx.all_neighbors(G, i)): if j in watch_list: adjacent.append('Y') else: adjacent.append('N') print(adjacent) Running this code returns the following list: &gt;&gt;&gt; ['N', 'Y', 'Y', 'N', 'N', 'N', 'N', 'Y', 'N', 'N', 'Y', 'N', 'Y', 'N', 'N', 'N', 'N', 'Y', 'N', 'Y', 'N'] The problem is that the code is iterating through the all the neighbours and appending 'Y' or 'N' with each iteration. How can I control the flow to append 'Y' or 'N' only once, indicating that a node in source either has a neighbour on the watch_list ('Y'), or doesn't ('N'). It seems like a simple flow-control question, but I can't seem to get it right. Any advice appreciated!

http://stackoverflow.com/comment/107483949
type: AnswerComment
has text: MattS is right, `KDE` default is True , need set `KDE=False, norm_hist=False`
type: Comment
comment on: http://stackoverflow.com/a/51667318
score: 3

http://stackoverflow.com/comment/90428798
comment on: http://stackoverflow.com/q/51733931
score: 0
type: Comment
has text: If we break this down to assembler you are looking at more cycles in the CPU to process the first example over the second so unless the first example gets converted to an else then the second will always be a faster run time. The compare command takes a min of 2 cycles on an Intel processor.
type: QuestionComment

http://stackoverflow.com/a/51718580
answers question: http://stackoverflow.com/q/51718228
upvote count: 1
has body: from itertools import permutations, combinations # Here you can use which one is more suited for your situation: permutations or combinations def func1(test): def func2(longlist): result = [] for t in test: perms = permutations(longlist, t) result += perms result = [''.join(t) for t in result] return result return func2 f2 = func1([1, 2]) print(f2('abc')) You get ['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb'] if you used permutations ['a', 'b', 'c', 'ab', 'ac', 'bc'] if you used combinations
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51649467
has body: All, I have a dataframe that looks like this. PctPerBroker MaxPctBalance MinPctBalance 29 0.222204 0.3 0.1 30 0.172765 0.3 0.1 31 0.166435 0.3 0.1 32 0.211877 0.3 0.1 33 0.226718 0.3 0.1 I am struggling with some basic stuff: if ( (Broker['PctPerBroker']&gt;Broker['MaxPctBalance'])| Broker['PctPerBroker']&lt;Broker['MinPctBalance']) ): do something i get an error if ( (Broker['PctPerBroker']&gt;Broker['MaxPctBalance']) ):# | (Broker['PctPerBroker']&lt;Broker['MinPctBalance']) ): File "/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/pandas/core/generic.py", line 1121, 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(). where am I going wrong? Thanks a lot
type: Question
duplicate of: http://stackoverflow.com/q/36921951
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90262378
has title: If condition python
has comment: http://stackoverflow.com/comment/90262461
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/36921951
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90262283

http://stackoverflow.com/a/51656434
type: Answer
has comment: http://stackoverflow.com/comment/90276650
score: 4
upvote count: 4
has body: Try this: a="srting=123d*gss6agn" a.split("=")[0]+"=" or this: a="srting=123d*gss6agn" a[:a.index("=")+1] To open a file: with open("path/to/your/file.txt","r") as f: a=f.read() # and then use an option above
downvote count: 0
answers question: http://stackoverflow.com/q/51656394

http://stackoverflow.com/comment/90453026
score: 1
comment on: http://stackoverflow.com/a/51746560
type: AnswerComment
has text: @bedford this is a pseudo code, you have to query based on number of records you want to fetch defined in limit.
type: Comment

http://stackoverflow.com/comment/90480945
type: QuestionComment
has text: sorry the question was incomplete, hope this edit helps
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51760829

http://stackoverflow.com/q/51763854
has comment: http://stackoverflow.com/comment/90486567
has comment: http://stackoverflow.com/comment/90486710
accepted answer: http://stackoverflow.com/a/51764010
tagged with: file
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/90486449
answer count: 2
has answer: http://stackoverflow.com/a/51763947
downvote count: 0
has answer: http://stackoverflow.com/a/51764010
favorite count: 0
has title: How to properly open a file in python and have the text contents printed out
has body: I am trying to open an existing file called sun_og.text. Below is my code. I want what is written in the file to print out in my terminal. f = open("sun_og.txt", "r") file_contents = f.read() print (file_contents) file.close() But I keep getting this error message FileNotFoundError: [Errno 2] No such file or directory: 'sun_og.txt'
possible better answer: http://stackoverflow.com/a/51763947
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51657219
has comment: http://stackoverflow.com/comment/90601935
has comment: http://stackoverflow.com/comment/90278265
tagged with: python-3.6
score: 0
answer count: 2
tagged with: python-3.5
has body: I have installed python3.5 on my server. I installed pysher with pip3, everything works fine, in python3.5 terminal, I can use import pysher without error. Now, I develop script, where is some python3.6 features, so I installed python3.6 on my server and now, I am not able to import pysher in python3.6 terminal: &gt;&gt;&gt; import pysher Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'pysher' So I tried install pysher again: # pip3 install pysher The program 'pip3' is currently not installed. You can install it by typing: apt install python3-pip Even when I konw I have installed python3-pip, I tried it agian: # apt install python3-pip Reading package lists... Done Building dependency tree Reading state information... Done python3-pip is already the newest version (8.1.1-2ubuntu0.4). 0 upgraded, 0 newly installed, 0 to remove and 138 not upgraded. Of course, I can rewrite my second script to work with python3.5, but I am curious why it is not working and how to repair it. UPDATE 1: dpkg -L python3-pip | grep bin /usr/bin /usr/bin/pip3 export PATH="$PATH:/usr/bin/pip3" pip3 search pysher The program 'pip3' is currently not installed. You can install it by typing: apt install python3-pip This did not work, so I try get version of pip3: # /usr/bin/pip3 --version -bash: /usr/bin/pip3: No such file or directory pip3 is not in /usr/bin/.
has title: Can't import package in python3.6
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51657451
tagged with: python
has answer: http://stackoverflow.com/a/51657304
has comment: http://stackoverflow.com/comment/90608651
type: Question

http://stackoverflow.com/q/51769644
score: 12
has answer: http://stackoverflow.com/a/51770165
answer count: 2
possible better answer: http://stackoverflow.com/a/64518978
accepted answer: http://stackoverflow.com/a/51770165
tagged with: pandas
downvote count: 1
has title: Drop column using Dask dataframe
favorite count: 0
tagged with: python-3.x
tagged with: dask
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/64518978
upvote count: 13
has body: This should work: raw_data.drop('some_great_column', axis=1).compute() But the column is not dropped. In pandas I use: raw_data.drop(['some_great_column'], axis=1, inplace=True) But inplace does not exist in Dask. Any ideas?

http://stackoverflow.com/comment/90399992
score: 0
type: Comment
has text: That's error related to your data....try this.. tag = list(map(lambda x: str(x).decode('utf-8'), tag))... Ensure data consistency...
type: AnswerComment
comment on: http://stackoverflow.com/a/51713351

http://stackoverflow.com/a/51728416
answers question: http://stackoverflow.com/q/51728070
score: 1
upvote count: 1
has body: rolling_mean is removed in pandas. Instead you should use pandas.DataFrame.rolling and then apply mean(). Take a look here. You can edit it like this: ts.rolling(window=12).mean()
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90293951
has text: The ideal solution is to design you program to be installed—whether via `pip`, or something like a WIndows installer/Mac DMG/etc. as built by something like `PyInstaller`. Then, you use the `setuptools` [Resource Manager API](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resourcemanager-api). `setuptools` makes sure that, wherever the file gets installed (even if it's buried inside a `.exe` file), you can just call `resource_stream` to open it (or just call `resource_string` to get its contents).
comment on: http://stackoverflow.com/q/51665254
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90355939
comment on: http://stackoverflow.com/q/51691048
has text: I would suggest that you produce a [mcve] of a code where you use `adjustText` and which shows the issue. This would make it easier to localize the problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51693386
answers question: http://stackoverflow.com/q/51692955
type: Answer
score: 3
has body: As you see, there isn't an attribute called to. That's the name of a parameter of the ForeignKey initializer. Since the argument can be a string model reference, or "self", it makes sense that the attribute representing the actual model target should have a different name. The Field attribute reference defines the API for introspecting field objects. What you're after is something like: if field.many_to_one: print(field.related_model)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51692955
upvote count: 3
has comment: http://stackoverflow.com/comment/90352009

http://stackoverflow.com/a/51789097
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90593051
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51788658
has comment: http://stackoverflow.com/comment/90599499
answers question: http://stackoverflow.com/q/51788658
type: Answer
has comment: http://stackoverflow.com/comment/90588471
upvote count: 2
score: 2
has body: If you want to do this recursively, you can have a function, that generates an edge from the node it is passed to each of its children, as well as calling itself for each of the children. Then all you need to do is call it for every node in the root list (and you need to collect all generated edges in a list). This could be implemented as follows (root holds your data): def get_edges(node): if "children" not in node: # ensure the node has children return [] label = node["label"] children = node["children"] result = [(label, c["label"]) for c in children] # create the edges for c in children: result.extend(get_edges(c)) # travers the tree recursively and collect all edges return result edges = sum(map(get_edges, root), []) # create and combine all the edge lists Running this code with the data you provided yields the following: [('Something1', 'Something2'), ('Something1', 'Somethin7'), ('Something1', 'Something2'), ('Something2', 'Something18'), ('Something2', 'Something14'), ('Something18', 'Something20'), ('Something18', 'Something19'), ('Something14', 'Something15'), ('Somethin7', 'Something9'), ('Somethin7', 'Something8'), ('Something9', 'Something10'), ('Something2', 'Something5'), ('Something2', 'Something4')]
has comment: http://stackoverflow.com/comment/90588839

http://stackoverflow.com/comment/90502414
comment on: http://stackoverflow.com/a/51734783
has text: That makes sense. Thanks for the very helpful answer!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51758413
has comment: http://stackoverflow.com/comment/90477850
has body: I need a help to update my theta value for each last two numbers for 5 element in the message: msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def get_new_theta(msg): # addition for each last 2 number in 5 elements in the msg # for example: new_theta=theta+(4+5), new_theta=new_theta+(9+10) and so on... return new_theta #initial theta theta=1 for b in msg: hwpx = [0,math.cos(4*math.radians(theta)),math.sin(4*math.radians(theta)), 0] a=b*hwpx print (a) This is the expected output: theta=1 1*[0,math.cos(4*math.radians(1)),math.sin(4*math.radians(1)), 0] 2*same as above 3*same as above 4*same as above 5*same as above theta=1+(4+5)=10 6*[0,math.cos(4*math.radians(10)),math.sin(4*math.radians(10)), 0] 7*same as above 8*same as above 9*same as above 10*same as above theta=10+(9+10)=29 Noted that the value of theta will be update for each 5 element. And the new theta will be used to calculated for the next element. However,when I run this code, loop was not successfully implemented. msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] theta=1 def get_new_theta(msg, theta): new_theta = [theta] for a, b in zip(msg[3::5], msg[4::5]): new_theta.append(new_theta[-1] + a + b) return new_theta theta=1 for b in msg: theta=get_new_theta(msg, theta) hwpx = [0, math.cos(4*math.radians(theta)), math.sin(4*math.radians(theta)), 0] a=b*hwpx print (theta) I got this error: hwpx = [0, math.cos(4*math.radians(theta)), math.sin(4*math.radians(theta)), 0] TypeError: a float is required` Thank you
possible better answer: http://stackoverflow.com/a/51758458
answer count: 3
has answer: http://stackoverflow.com/a/51758716
has comment: http://stackoverflow.com/comment/90476455
has comment: http://stackoverflow.com/comment/90477271
has answer: http://stackoverflow.com/a/51758458
has answer: http://stackoverflow.com/a/51758530
has title: Update value in the list using Python
favorite count: 0
has comment: http://stackoverflow.com/comment/90476263
tagged with: python
has comment: http://stackoverflow.com/comment/90477330
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51758716
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/90477693
has comment: http://stackoverflow.com/comment/90477439
upvote count: 1
has comment: http://stackoverflow.com/comment/90477397
has comment: http://stackoverflow.com/comment/90477196
type: Question
downvote count: 0

http://stackoverflow.com/a/51739674
type: Answer
downvote count: 0
score: 1
has body: Well, you can do those calculations in metaclass' __new__ method: class MyCalculatedClassAttrsMeta(type): def __new__(cls, name, bases, dct): c = super().__new__(cls, name, bases, dct) c.y = c.x + 100 return c class A(metaclass=MyCalculatedClassAttrsMeta): x = 1 class B(A): x = 2 print(A.x, A.y) print(B.x, B.y) The output will be: 1 101 2 202
answers question: http://stackoverflow.com/q/51739255
upvote count: 1

http://stackoverflow.com/comment/90426797
type: QuestionComment
type: Comment
has text: What goes in page and options?
score: 0
comment on: http://stackoverflow.com/q/51733030

http://stackoverflow.com/q/51763519
upvote count: 3
tagged with: selenium
has title: Selenium webdriver stalling after timeout
answer count: 1
has answer: http://stackoverflow.com/a/56813903
tagged with: timeout
type: UnansweredQuestion
has body: I am using selenium webdriver on chrome to scrape a website's search results, with python 3.6 on Windows 10. When using driver.get(), certain pages do not load, and selenium times out (regardless of how long I set the timeout for). My error is that after timing out, I cannot get another url. My code: driver = webdriver.Chrome() for link in link_list: try: driver.get(link) # do some stuff except: continue What happens is that if driver.get(somelink) throws a timeout exception, then driver.get will fail every subsequent time. The chrome window itself stalls on somelink permanently. It seems like driver is stopping completely if it throws an exception, regardless of whether or not I catch it. I am not sure if this happens regardless of the type of exception, or if it only happens on timeout. I have a workaround where I close and re-open the window, but it's messy. Is there any way to make the browser continue?
has comment: http://stackoverflow.com/comment/100061655
score: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: python
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/100182491

http://stackoverflow.com/comment/90447431
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51734382
type: Comment
has text: @AlImran I'm aware of the CoC, could you clarify how this relates to my comment? Particularly as the first link in the "Expectations" box is the same page I linked to?

http://stackoverflow.com/a/51734606
type: Answer
has body: So, I learned that my problem with installing beautifulsoup was because of the firewall restriction in my organization, which I was relating to pip install. I learned of the proxy settings and using that, got to install bs4 via the conda interpreter. Thank you for all the answers, which made me think through on various aspects, which I would not have thought of without the probing questions brought up here.
answers question: http://stackoverflow.com/q/51733027
score: 0

http://stackoverflow.com/a/51720925
has body: First off, CAPTCHAs are meant to do exactly that: repel robots/scripts from brute-forcing, or doing repeated actions on certain app features (e.g: login/register flows, send messages, purchase flows, etc.). So you can only go around... never through. That being said, you can simulate the logged-in state by doing one of the following: loading the authentication cookies required for the user to be logged in (usually it's only one cookie with a token of some sorts); loading a custom profile in the browser that already has that user logged in; use some form of basic auth when navigating to that specific URL (if the web-app has any logic to support this); Recommended approach: Usually in most companies (at least from my exp), there usually is a specific cookie, or flag that you can set to disable CAPTCHAs for testing purposes. If this is not the case, talk to your PM/DEVs to create such a feature that permits the testing of your web-app. Don't want to advertise advertise my content, but I think I best tackled this topic HERE. Maybe it can further help. Hope you solve the problem. Cheers!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51720039

http://stackoverflow.com/comment/90426981
has text: tell me other way
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51730523
type: Comment

http://stackoverflow.com/a/51675019
type: Answer
answers question: http://stackoverflow.com/q/51673220
score: 0
has body: You can try transpose the data then sum it by the index you want and transpose it back the way you want df.transpose().sum(level=[0,1]).transpose() In case you needed to pivot your results.

http://stackoverflow.com/q/51665533
tagged with: resnet
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51669193
has body: https://github.com/wenxinxu/resnet-in-tensorflow#overall-structure The link above is the Resnet model for cifar10. I am modifying above code to do object detection using Resnet and Cifar10 as training/validating dataset. ( I know the dataset is for object classification) I know that it sounds strange, but hear me out. I use Cifar10 for training and validation then during testing I use a sliding window approach, and then I classify each of the windows to one of 10 classes + "background" classes. for background classes, I used images from ImageNet. I search ImageNet with following keyword: construction, landscape, byway, mountain, sky, ocean, furniture, forest, room, store, carpet, and floor. then I clean bad images out as much as I can including images that contain Cifar10 classes, for example, I delete a few "floor" images that have dogs in it. I am currently running the result in Floydhub. Total steps that I am running is 60,000 which is where section under "training curve" from the link about suggests that the result starts to consolidate and do not converge further ( I personally run this code myself and I can back up the claim) My question is: what is the cause of the sudden step down in training and validation data which occurs at about the same step? What if(or Is it possible that)training and validation data don't converge in a step-like fashion at about the same step? what I mean is, for example, training steps down at around 40,000 and validation just converge with no step-down? (smoothly converge)
type: Question
answer count: 1
has title: validation and training don't converge at the same time, but validation still converges
score: 0
tagged with: python
tagged with: object-detection
tagged with: classification
type: UnansweredQuestion

http://stackoverflow.com/comment/90393847
type: QuestionComment
has text: Usually *buildozer* is run without `sudo`. Remove `random` from buildozer.spec. Try `buildozer android debug`
score: 0
comment on: http://stackoverflow.com/q/51716272
type: Comment

http://stackoverflow.com/q/51693763
has answer: http://stackoverflow.com/a/51693826
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90392193
tagged with: matlab
upvote count: 3
has title: How to control persistent object from command line in Python
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90353800
has body: I come from a Matlab background. In Matlab, one is able to create a persistent object (that persists in the 'workspace'), and then manipulate it from the command line. In other words I can do something like this all from the command line: myStatic.initiate() // myStatic is a static class that consists of static functions only; the initiate function would create the persistent object myStatic.method1() ... myStatic.stop() // Erasing the workspace Would I be able to do something like this in Python?
has comment: http://stackoverflow.com/comment/90617079
answer count: 2
has answer: http://stackoverflow.com/a/51693824
has comment: http://stackoverflow.com/comment/90349014
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90349025

http://stackoverflow.com/comment/90263476
comment on: http://stackoverflow.com/a/51649193
type: Comment
score: 0
type: AnswerComment
has text: @Zephyr - Problem is duplicates in `df1.Name` like `df1 = pd.DataFrame({'Name':['John','Merry','John travis', 'John'], "Position":['CEO','CTO','Engr', 'boss']})`, solution is remove dupes by `df1 = df1.drop_duplicates(subset=['Name'])` or better `df['Position'] = df.Last_Name.map (df1.groupby('Name').Position.apply(', '.join))`

http://stackoverflow.com/q/51765812
score: 1
type: Question
has body: I need to get raw (compressed) content. My goal is to save it to S3 as it is. It is easy to do with requests: import requests response = requests.get('http://google.com', stream=True) content = response.raw.read() # b'\x1f\x8b\x08\x00\x00\x00\x00...' However with aiohttp I always get already ungzipped content: import asyncio import aiohttp async def download(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: content = await response.content.read() # b'&lt;!doctype html&gt;&lt;html...' if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(download('http://google.com'))
upvote count: 1
answer count: 1
has title: How to get raw response stream using aiohttp?
has answer: http://stackoverflow.com/a/51766288
accepted answer: http://stackoverflow.com/a/51766288
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: aiohttp
downvote count: 0

http://stackoverflow.com/q/51705712
tagged with: python-3.x
score: -8
has answer: http://stackoverflow.com/a/51709302
tagged with: python
accepted answer: http://stackoverflow.com/a/51709302
upvote count: 4
type: AnsweredQuestion
has body: I've written a script in Python in combination with BeautifulSoup to parse some content from a webpage. In the landing page there are two tables. I need to use the Results tab from the first table which will lead to the target page. From the target page I'm only after this information Grade: M 300 metres and so on. There are multiple tabs just above it like 1,2,3,4, etc. which have different Grade status. I wish to fetch them all. As the Results tabs located in the landing page do not have any link connected to it, I had to use post request to fetch the content from the target page. Browser simulator is not an option for me in this case. The bottom line is I need to use six post requests to reach the content of six Results tabs. The script I'm pasting below can handle the content of the last results tab. How can I fix the loop to get the content from all the Results tab at the same time? This is my try: import requests from bs4 import BeautifulSoup url = "https://www.thedogs.com.au/Racing/Results.aspx?SearchDate=3-Jun-2018" def get_info(session,link): session.headers['User-Agent'] = "Mozilla/5.0" res = session.get(link) soup = BeautifulSoup(res.text,"lxml") formdata = {} for items in soup.select("#aspnetForm input"): if "ctl00$ContentPlaceHolder1$rptrLatestRacingResults$ctl" in items.get("name"):continue if "ctl00$ContentPlaceHolder1$rptrSearchResults$ctl0" in items.get("name"): formdata[items.get("name")] = items.get("value") else: formdata[items.get("name")] = items.get("value") session.headers['User-Agent'] = "Mozilla/5.0" req = session.post(link,data = formdata) soup = BeautifulSoup(req.text,"lxml") for iteminfo in soup.select("[id^='ctl00_ContentPlaceHolder1_tabContainerRaces_tabRace'] span"): if "Grade:" in iteminfo.text: print(iteminfo.text) if __name__ == '__main__': with requests.Session() as session: get_info(session,url) See the two images below (one after another) to recognize the content I'm trying to fetch:
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/90379300
has title: Can't deal with some complicated laid-out content from a webpage
downvote count: 12
answer count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/a/51739959
score: 1
has comment: http://stackoverflow.com/comment/90440119
has comment: http://stackoverflow.com/comment/90440179
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51739196
type: Answer
has body: The error you are receiving is being caused by the order of your code: 1 import pandas as pd 2 df = pd.read_sql(sql, cnxn) ## You call the variable sql here, but don't assign it until line 6 3 4 cnxn = pyodbc.connect(connection_info) 5 cursor = cnxn.cursor() 6 sql = """SELECT * FROM AdventureWorks2012.Person.Address 7 WHERE City = 'Bothell' 8 ORDER BY AddressID ASC""" 9 df = psql.frame_query(sql, cnxn) 10 cnxn.close() You are calling the variable sql on line 2, but you don't actually define the variable until line 6. You are also missing a few libraries, and based off beardc's code it looks like you've meshed some of the wrong parts of his two answers together. Try arranging the code like this: (Please note this code is untested, and the other issues described below) #Import the libraries import pandas as pd import pyodbc #Give the connection info cnxn = pyodbc.connect(connection_info) #Assign the SQL query to a variable sql = "SELECT * FROM AdventureWorks2012.Person.Address WHERE City = 'Bothell' ORDER BY AddressID ASC" #Read the SQL to a Pandas dataframe df = pd.read_sql(sql, cnxn) In answer to your questions: Yes, you need to change the connection_info to the info in your database. There is a good example of the text you need to put in there here This specific issue isn't being caused by your network restrictions.
upvote count: 1
has comment: http://stackoverflow.com/comment/90440039
answers question: http://stackoverflow.com/q/51739196

http://stackoverflow.com/comment/90411449
comment on: http://stackoverflow.com/q/51723928
has text: Thanks. And just wondering given your comment on jpp's answer. Is the only condition for the grouping that the four groups contain the 3 cities? So it doesnt matter if `2017-01-03 | new york` is in group 1 or group 4 ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51662773
downvote count: 0
type: Question
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/54208040
accepted answer: http://stackoverflow.com/a/51957870
tagged with: geopandas
has title: Cannot import Geopandas with PyInstaller executable - despite running fine in the virtual env
favorite count: 0
has body: When my Python application frozen with PyInstaller attempts to import Geopandas, it stops working. Windows 10 PyInstaller 3.3.1 Geopandas 0.4 Here is the source code: print("Hello, StackOverflow") import geopandas as gpd Here is the resulting console output of the compiled EXE: Hello, StackOverflow Traceback (most recent call last): File "application.py", line 3, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "d:\documents\projecttwo\publish\harv_venv1\env\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "site-packages\geopandas\__init__.py", line 9, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "d:\documents\projecttwo\publish\harv_venv1\env\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "site-packages\geopandas\datasets\__init__.py", line 7, in &lt;module&gt; StopIteration [6764] Failed to execute script application This behavior is consistent when I attempt to import Geopandas is much more complex applications, and the console output is constant. Geopandas is installed correctly within the Python 3.6.3 virtual environment (through PIP, I've tried versions 0.4 and 0.3 as well) and works just fine prior to compilation (ie. python application.py runs successfully). I have attempted installing both geopandas and pyinstaller from different sources (eg. Gohlke's wheel), with the same results. I have also tried creating an entirely new virtual env from scratch, installing Fiona from Gohlke and geopandas from pip. I suspect some…
upvote count: 5
has answer: http://stackoverflow.com/a/51957870
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/54208040
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51743583
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90447509
favorite count: 0
type: Question
tagged with: lxml
has title: lxml.html treats two similar inputs differently?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/51744291
upvote count: 3
has comment: http://stackoverflow.com/comment/90447756
answer count: 1
has comment: http://stackoverflow.com/comment/90447450
accepted answer: http://stackoverflow.com/a/51744291
has body: I am seeing some unexpected output while using lxml.html. import lxml.html as LH xmlspec = "<?xml version='1.0' encoding='iso-8859-1'?>" a = LH.fromstring(xmlspec + " Body ") b = LH.fromstring(xmlspec + " Body ") print a # says element p while I would have expected html print b # says element html which is expected Can someone explain why is this happening? Everything works fine when you remove the xml specification! Is there a right way to deal with this?

http://stackoverflow.com/comment/90487276
type: AnswerComment
type: Comment
has text: I will try Selenium. I updated the issue on the html_request GitHub. Thanks for the advices
comment on: http://stackoverflow.com/a/51764164
score: 0

http://stackoverflow.com/q/51673541
has comment: http://stackoverflow.com/comment/90310520
tagged with: python-3.x
has title: fast iteration over two numpy arrays
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90310736
has body: I'm trying two implement the following problem in python I have two 1D numpy arrays containing indices in the range from 0 to gridsize-1 (call them i1,i2). I also have a 1D numpy array with data (call it d). All three Arrays have the same length. The arrays with the indices can contain a specific index pair (call it s1,s2) multiple times. I now want two map the data array to a 2D Array (call it arr) in order to plot it. For those index pairs that appear multiple times I want to take the average of the data entries corresponding to these indices. I tried the following code (without the averaging) d #data array i1 #first 1D numpy index array i2 #second 1D numpy index array gridsize = 1000 arr = np.zeros(gridsize**2) for i in range(d.size): arr[ i1[i], i2[i] ] = d[i] The code is working so far but very slow (about 2s for the size of the arrays which is not acceptable) Any recommendation to speed it up? I suggest the problem lies in the the accessing of the individual elements in the arrays. Is there may be a built in numpy function to do that? Thank you, Michael
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/90310042
has answer: http://stackoverflow.com/a/51674360
answer count: 1

http://stackoverflow.com/a/51756035
type: Answer
has body: You have most of the right pieces and roughly in the right order. We just need to fine tune your code a little bit as far as indentation, usage and style: import turtle def draw_square(my_turtle): for i in range(4): my_turtle.forward(100) my_turtle.right(90) window = turtle.Screen() window.bgcolor('green') alex = turtle.Turtle() alex.color('black') alex.speed('slow') alex.shape('triangle') draw_square(alex) window.mainloop()
answers question: http://stackoverflow.com/q/51754175
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51754175
score: 0

http://stackoverflow.com/comment/90454732
type: Comment
has text: @JeruLukecv2.xfeatures2d.SIFT_create(sigma = 1.2 ,contrastThreshold = 0.01, edgeThreshold = 20) gave me some good recognition for the wheels of the toy car.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51697228

http://stackoverflow.com/comment/90540819
has text: I believe there is an error in your xml file, there are some "measure" tags inside some other "measure" tags
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51750726

http://stackoverflow.com/comment/90372467
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51705871
score: 0
has text: `except` belongs with `try`, not `if`. See https://docs.python.org/3/reference/compound_stmts.html

http://stackoverflow.com/comment/90431253
score: 0
comment on: http://stackoverflow.com/q/51735124
type: QuestionComment
type: Comment
has text: I will try your suggestion, thanks! EDIT: I forgot the sqrts in the equations :/ I will still try that

http://stackoverflow.com/comment/90556164
has text: If I were you I would use another database, like SolR or ElasticSearch, to store your data.
comment on: http://stackoverflow.com/q/51796291
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90346188
type: AnswerComment
type: Comment
has text: Thank you Divakar for the reply. Any insights on why the second approach failed?
comment on: http://stackoverflow.com/a/51692327
score: 0

http://stackoverflow.com/comment/90501637
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51770458
has text: thanks :) ya it does work but takes more than an hour. just wanted to know what kind of changes should i be making in order to make it run faster.
score: 0

slice
tags question: http://stackoverflow.com/q/51686340
tags question: http://stackoverflow.com/q/51744314
tags question: http://stackoverflow.com/q/51736715
tags question: http://stackoverflow.com/q/51708532
tags question: http://stackoverflow.com/q/51766851
type: Tag
tag name: slice
tags question: http://stackoverflow.com/q/51732396
tags question: http://stackoverflow.com/q/51730480
tags question: http://stackoverflow.com/q/51657622

http://stackoverflow.com/q/51778645
favorite count: 0
tagged with: postgresql
tagged with: python
has answer: http://stackoverflow.com/a/51778700
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51778700
tagged with: psycopg2
type: Question
has answer: http://stackoverflow.com/a/51783518
has comment: http://stackoverflow.com/comment/90515278
answer count: 2
has title: How to insert a dictionary into Postgresql Table with Pscycopg2
has body: How do I insert a python dictionary into a Postgresql2 table? I keep getting the following error, so my query is not formatted correctly: Error syntax error at or near "To" LINE 1: INSERT INTO bill_summary VALUES(To designate the facility of... import psycopg2 import json import psycopg2.extras import sys with open('data.json', 'r') as f: data = json.load(f) con = None try: con = psycopg2.connect(database='sanctionsdb', user='dbuser') cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute("CREATE TABLE bill_summary(title VARCHAR PRIMARY KEY, summary_text VARCHAR, action_date VARCHAR, action_desc VARCHAR)") for d in data: action_date = d['action-date'] title = d['title'] summary_text = d['summary-text'] action_date = d['action-date'] action_desc = d['action-desc'] q = "INSERT INTO bill_summary VALUES(" +str(title)+str(summary_text)+str(action_date)+str(action_desc)+")" cur.execute(q) con.commit() except psycopg2.DatabaseError, e: if con: con.rollback() print 'Error %s' % e sys.exit(1) finally: if con: con.close()
downvote count: 0
accepted answer: http://stackoverflow.com/a/51783518

http://stackoverflow.com/comment/90449259
type: Comment
type: QuestionComment
has text: Please provide a [mcve]. We need to be able to reproduce the problem.
comment on: http://stackoverflow.com/q/51744668
score: 0

http://stackoverflow.com/a/51772004
answers question: http://stackoverflow.com/q/51771656
has body: You say you're using a proxy server on your machine. That is probably the problem, and it's why your error message says it's timing out. pip needs to be told about the proxy: $ pip3.7.exe install urllib3 --proxy=http://name.of.proxy.com at which point it will use the proxy and will complete its request. No guarantees what it will find, but the error message for that should be more helpful.
score: 0
has comment: http://stackoverflow.com/comment/104086911
type: Answer

http://stackoverflow.com/comment/90407596
type: Comment
comment on: http://stackoverflow.com/a/51723177
score: 0
type: AnswerComment
has text: That's the weird thing. It doesn't seems to change anything converting it to dBs. In fact, attending to the colorbar output, the power in some frequencies seems to reach the 40k dBs, which is ABSURD. Something like those numbers/1000 should be more reasonable, but again, I do not understand where those numbers are getting from. Thx btw.

http://stackoverflow.com/q/51737205
has title: iterate over columns to plot a graph of output data
has body: I have written a small python script that plots a graph of my data. I wanted to modify the y variable such that I do not have to change the usecols=range(1,11) parameter every time my input changes. Is it possible to define a for loop within the np.gefromtxt function? import numpy as np import matplotlib.pyplot as plt x = np.genfromtxt('classdist.csv', usecols=(0)) y = np.genfromtxt('classdist.csv', usecols=range(1,11)) y1 = y * 100 print ' x=', x, '\n\n y=', y1 plt.plot(x, y1, linewidth =2) plt.show()
has answer: http://stackoverflow.com/a/51743932
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51743422
tagged with: matplotlib
type: Question
tagged with: numpy
answer count: 2
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/51711170
possible better answer: http://stackoverflow.com/a/51711245
answer count: 2
has answer: http://stackoverflow.com/a/51711245
tagged with: python
has title: numpy: summing along all but last axis
has comment: http://stackoverflow.com/comment/90385959
has answer: http://stackoverflow.com/a/51711723
upvote count: 23
accepted answer: http://stackoverflow.com/a/51711723
tagged with: numpy
has body: If I have an ndarray of arbitrary shape and I would like to compute the sum along all but the last axis I can, for instance, achieve it by doing all_but_last = tuple(range(arr.ndim - 1)) sum = arr.sum(axis=all_but_last) Now, tuple(range(arr.ndim - 1)) is not exactly intuitive I feel. Is there a more elegant/numpy-esque way to do this? Moreover, if I want to do this for multiple arrays of varying shape, I'll have to calculate a separate dimension tuple for each of them. Is there a more canonical way to say "regardless of what the dimensions are, just give me all but one axis"?
type: AnsweredQuestion
downvote count: 0
score: 23
favorite count: 0
type: Question

http://stackoverflow.com/q/51700643
tagged with: linegraph
has body: I've been working with the python bokeh function, and I wish to display a graph of a stock when the ticker is entered into the TextInput section. However, in my case the only way I've made this work is to create a new p.line within the update function, which overlays one stock graph on top of another. Is there a way to update my source data or update function such that a graph with only the input stock is shown? p=figure( height=400, x_axis_type='datetime', title=(company+' ('+tickerstring+') '), tools='pan, box_zoom, wheel_zoom, reset', ) p.line('x', 'y', source=source) line1=p.line(thedates, stockcloseprices) p.grid.grid_line_color="white" p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.add_tools(HoverTool( tooltips=[ ("Date", "@x{%F}"), ('Close',"@y") ], formatters={ 'x':'datetime', # use 'datetime' formatter for 'date' field }, mode='vline' )) source = ColumnDataSource(data=dict( x=thedates, y=stockcloseprices )) div = Div(text='&lt;br&gt;&lt;b&gt; Key Points &lt;/b&gt;&lt;br&gt;&lt;br&gt;'+percentagechange+'&lt;br&gt;&lt;br&gt;'+performance, width=200, height=100) def update(f): fstocksymbol=str(f.upper()) if fstocksymbol in stocksymbols: p.title.text = (symbolsdictionary[fstocksymbol]).upper()+' ('+fstocksymbol+')' tickerstring=fstocksymbol firstfunction=stockname(tickerstring) secondfunction=stockdata(firstfunction) stockdates=[] stockcloseprices=[] for value in secondfunction: stockdates.append(value[0]) stockcloseprices.append(value[4]) thedates = np.array(stockdates, dtype=np.datetime64) p.line(thedates, stockcloseprices) push_notebook() elif fstocksymbol=='': print('') else: print("") interact(update, f='') grid = gridplot([p, div, button], ncols=2, plot_width=570, plot_height=400) show(grid, notebook_handle=True)
tagged with: visualization
type: AnsweredQuestion
has title: Python Bokeh graph displays two lines when update function called
type: Question
has answer: http://stackoverflow.com/a/51712551
tagged with: python
score: 0
tagged with: bokeh
answer count: 1
tagged with: updates
accepted answer: http://stackoverflow.com/a/51712551

http://stackoverflow.com/q/51651956
linked to: http://stackoverflow.com/q/11865378
has comment: http://stackoverflow.com/comment/90297352
tagged with: probability
has comment: http://stackoverflow.com/comment/90385400
answer count: 1
accepted answer: http://stackoverflow.com/a/51712215
has body: I want to plot some points with the rbf function like here to get the density distribution of the points: if i run the following code, it works fine: from scipy.interpolate.rbf import Rbf # radial basis functions import cv2 import matplotlib.pyplot as plt import numpy as np # import data x = [1, 1, 2 ,3, 2, 7, 8, 6, 6, 7, 6.5, 7.5, 9, 8, 9, 8.5] y = [0, 2, 5, 6, 1, 2, 9, 2, 3, 3, 2.5, 2, 8, 8, 9, 8.5] d = np.ones(len(x)) print(d) ti = np.linspace(-1,10) xx, yy = np.meshgrid(ti, ti) rbf = Rbf(x, y, d, function='gaussian') jet = cm = plt.get_cmap('jet') zz = rbf(xx, yy) plt.pcolor(xx, yy, zz, cmap=jet) plt.colorbar() # Plotting the original points. plot3 = plt.plot(x, y, 'ko', markersize=5) # the original points. plt.show() Now I want to change my input data: # import data input = "testProbe.jpg" image = cv2.imread(input) # load the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert it to grayscale # threshold the image to reveal light regions in the gray image thresh = cv2.threshold(gray, 145, 200, cv2.THRESH_BINARY)[1] x, y = np.where(thresh &gt; 0) d = np.ones(len(x)) And I get the following error message: Traceback (most recent call last): File "C:/Users/.../Python/pythonprojects/03a_test_rbfWithScipy.py", line 32, in &lt;module&gt; rbf = Rbf(x, y, z, function='gaussian') File "C:\Users\...\Python\Anaconda2\lib\site-packages\scipy\interpolate\rbf.py", line 220, in __init__ self.nodes = linalg.solve(self.A, self.di) File "C:\Users\...\Python\Anaconda2\lib\site-packages\scipy\interpolate\rbf.py", line 226, in A r = self._call_norm(self.xi, self.xi) File "C:\Users\...\Python\Anaconda2\lib\site-packages\scipy\interpolate\rbf.py", line 236, in _call_norm return self.norm(x1, x2) File "C:\Users\...\Python\Anaconda2\lib\site-packages\scipy\interpolate\rbf.py", line 118, in _euclidean_norm return np.sqrt(((x1 - x2)**2).sum(axis=0)) MemoryError The error message appears really fast and when I look at the task manager, the PC is not running at full capacity. He …
has title: memory error by using rbf with scipy
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: probability-density
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90294981
has comment: http://stackoverflow.com/comment/90295384
type: Question
has answer: http://stackoverflow.com/a/51712215
upvote count: 2
tagged with: out-of-memory
tagged with: python

http://stackoverflow.com/a/51689232
has comment: http://stackoverflow.com/comment/90354789
answers question: http://stackoverflow.com/q/51688756
type: Answer
downvote count: 0
score: 1
has body: Do you need something like this? This works with Python 3.6+ name = input('Your name: ') print(f'Hello {name}')
upvote count: 1

http://stackoverflow.com/q/51715182
accepted answer: http://stackoverflow.com/a/51717233
type: Question
tagged with: performance
has answer: http://stackoverflow.com/a/51717233
has comment: http://stackoverflow.com/comment/90393916
has comment: http://stackoverflow.com/comment/90393638
has body: I have written some code that computes flexural moments imposed by different trucks for a bridge with 300 ft length. Truck data are contained in two lists: ax_list and sp_list, which are the axle weights and axle spacings, respectively. There is nothing much to the code, however, this needs to be repeated for millions of different truck types, and I am trying to optimize my code, which takes real long time when the actual data size set is concerned. I tried using Numba to see if I can get any speed gains, but it did not change the execution time, whether I add Numba @jit decorators for each function or not. What am I doing wrong here? Any help would be welcome! I also included code to generate representative pseudo data for 1000 records below: import random from numba import jit import numpy as np from __future__ import division #Generate Random Data Set ax_list=[] sp_list=[] for i in xrange(1000): n = random.randint(3,10) ax = [] sp = [0] for i in xrange(n): a = round(random.uniform(8,32),1) ax.append(a) for i in xrange(n-1): s = round(random.uniform(4,30), 1) sp.append(s) ax_list.append(ax) sp_list.append(sp) #Input Parameters L=300 step_size=4 cstep_size=4 moment_list=[] @jit #Simple moment function def Moment(x): if x&lt;L/2.0: return 0.5*x else: return 0.5*(L-x) #Attempt to vectorize the Moment function, hoping for speed gains vectMoment = np.vectorize(Moment,otypes=[np.float],cache=False) @jit #Truck movement function that uses the vectorized Moment function above def SimpleSpanMoment(axles, spacings, step_size): travel = L + sum(spacings) spacings=list(spacings) maxmoment = 0 axle_coords =(0-np.cumsum(spacings)) while np.min(axle_coords) &lt; L: axle_coords = axle_coords + step_size moment_inf = np.where((axle_coords &gt;= 0) &amp; (axle_coords &lt;=L), vectMoment(axle_coords), 0) moment = sum(moment_inf * axles) if maxmoment &lt; moment: maxmoment = moment return maxmoment Then to run the loop for 1000 times: %%timeit for i in xrange(len(ax_list)): moment_li…
tagged with: numpy
answer count: 1
favorite count: 0
tagged with: optimization
score: 0
tagged with: python
has title: No speed gain from Numba optimized functions
type: AnsweredQuestion
upvote count: 2
downvote count: 2
tagged with: numba

http://stackoverflow.com/comment/90405171
has text: I'm pretty sure that when size of `QTableWidget` changes (by adding new `QTableWidgetItem`) I need to figure out what's the actual size of whole `QTableWidget` and then update size of `QListWidgetItem` associated with that particular `QTableWidget`.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51722119

http://stackoverflow.com/comment/90467889
comment on: http://stackoverflow.com/q/51748978
has text: Take your code and strip out all of the Selenium related stuff... just mock some data and write it to the CSV file... now does it work? Try things like `print(doctor.title)`, etc... does that work? You really need to do some more debugging and strip the code down to a [mcve] on your own. You'll likely find the issue while doing that.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90394923
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51698649
has text: Ok, just confirmed that it's working and what not. Bitnami Trac installer is definitely the way to go at the moment
score: 0

http://stackoverflow.com/comment/90314892
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51675526
has text: Get it :). There is a speed drop as you say. But i waited 5 min and nothing happened with this high num. Is there a way to get rid of this? edit: waiting more is the way to get rid of this. Thanks @Alfie

http://stackoverflow.com/a/51679306
answers question: http://stackoverflow.com/q/51679270
has body: It looks like that on line 55 you call pprint.pprint(unique_domains) which is defined in your try. So if the try fails, you won't have it to pprint outside of it. What you could do so it won't error out is simply define unique_domains before your try, you could set it to '' or None just depends on what you want to do with it if it's failed. That should get you past this speed bump, good luck! :) If you'd like to your DB connection to retry, you could loop your try except logic a defined number of times.
has comment: http://stackoverflow.com/comment/90322435
has comment: http://stackoverflow.com/comment/90322527
has comment: http://stackoverflow.com/comment/90322006
type: Answer
score: 0

http://stackoverflow.com/q/51787257
has comment: http://stackoverflow.com/comment/129389063
favorite count: 0
has answer: http://stackoverflow.com/a/51787309
type: Question
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/3380484
has comment: http://stackoverflow.com/comment/90531664
has title: How to replace '\0' with '/0'?
has body: Why does replacing backslashes with frontslashes like below does not work for the second backslash?: x = 'O:\MAP\04_Operational Finance\Billing\Billings Reconciliation'.replace('\\', '/') print(x) Printing output is: O:/MAP_Operational Finance/Billing/Billings Reconciliation
accepted answer: http://stackoverflow.com/a/51787309
has answer: http://stackoverflow.com/a/51787311
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51787311
duplicate of: http://stackoverflow.com/q/3380484
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51787350

http://stackoverflow.com/q/51665928
has title: Replace Variables in a .docx file with user inputted variables
has answer: http://stackoverflow.com/a/51666127
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51666127
upvote count: 1
has body: I have a project that I am working on. I have a .docx template that I've created. Within there, I have multiple variables across the whole document that need to be replaced with user-imputed information, (some variables are replaces more than once within the doc). I have this code that I modified from previous .txt files that I have worked with. I am not able to take the .docx file, edit the vars with user imputed info and create a new file that I can share/print. Any help would be appreciated. I have attempted to try to use python-docx but alas, I have not fully understood the concept and make it work. Sample code follows: from __future__ import with_statement import fileinput #def terms and ask user for imput def loaDocOne(): words = ["[clientName]","[addressLine1]","[addressLine2]","[todaysDate]","[fileNum]","[originalClient]","[refNum]","[currentBal]","] clientName = input('Enter Clients name: ') addressLine1 = input('Enter Clients Address Line 1: ') addressLine2 = input('Enter Clients Address Line 2: ') todaysDate = input('Enter Todays Date: ') fileNum = input('Enter File Number: ') originalClient = input('Enter Original Client: ') refNum = input('Enter Original Refrence Number: ') #open file def replaceFunc(): with open ('template.docx') as f: for line in f: line = line.replace("[clientName]",clientName) line = line.replace("[addressLine1]",addressLine1 ) line = line.replace("[addressLine2]",addressLine2 ) line = line.replace("[todaysDate]",todaysDate) line = line.replace("[fileNum]",fileNum ) line = line.replace("[originalClient]", originalClient) line = line.replace("[refNum]",refNum ) #Find out if everything looks good to continue def goOn(): doYouWantToContinue = input('Does Everything Look Correct? yes/no: ') if doYouWantToContinue == 'yes': replaceFunc() else: loaDocOne() loaDocOne() goOn() replaceFunc() Also, Is there a way to take the outputted file and make it 'document_name_'fileNum'' with the user provided file number?
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90467546
comment on: http://stackoverflow.com/q/51752911
type: Comment
type: QuestionComment
has text: @Srini yeah, it never reaches the breakpoint. It works just fine in regular run mode. I have confirmed the library I am using does not behave well in debugger mode.
score: 0

http://stackoverflow.com/comment/90410057
type: Comment
type: QuestionComment
has text: Have you tried putting your logger overriding code at the end of the `/var/www/xyz_pythonanywhere_com_wsgi.py` file?
comment on: http://stackoverflow.com/q/51719075
score: 0

http://stackoverflow.com/q/51785931
has comment: http://stackoverflow.com/comment/90552777
upvote count: 2
has comment: http://stackoverflow.com/comment/90529289
type: Question
has title: How to find the distance (in pixels) between the Sprite and screen corners?
has answer: http://stackoverflow.com/a/51786400
accepted answer: http://stackoverflow.com/a/51786400
answer count: 1
downvote count: 0
favorite count: 0
has body: I need to find the distance (in pixels) between the animated worker objects and the 4 corners of the screen (upper left, upper right, lower left, lower right). Which function of pygame gives this information? I need to get this information at each update iteration. import pygame, random import sys WHITE = (255, 255, 255) GREEN = (20, 255, 140) GREY = (210, 210 ,210) RED = (255, 0, 0) PURPLE = (255, 0, 255) SCREENWIDTH=1000 SCREENHEIGHT=578 IMG_BACKGROUND = "background.jpg" IMG_WORKER_RUNNING = "images/workers/worker_1.png" IMG_WORKER_IDLE = "images/workers/worker_2.png" IMG_WORKER_ACCIDENT = "images/workers/accident.png" class Background(pygame.sprite.Sprite): def __init__(self, image_file, location, *groups): # we set a _layer attribute before adding this sprite to the sprite groups # we want the background to be actually in the back self._layer = -1 pygame.sprite.Sprite.__init__(self, groups) # let's resize the background image now and only once self.image = pygame.transform.scale(pygame.image.load(image_file).convert(), (SCREENWIDTH, SCREENHEIGHT)) self.rect = self.image.get_rect(topleft=location) class GeoFenceInfluenceZone(pygame.sprite.Sprite): def __init__(self, rect, *groups): # we set a _layer attribute before adding this sprite to the sprite groups self._layer = 0 pygame.sprite.Sprite.__init__(self, groups) self.image = pygame.surface.Surface((rect.width, rect.height)) self.image.fill(GREY) self.rect = rect class GeoFence(pygame.sprite.Sprite): def __init__(self, rect, risk_level, *groups): # we set a _layer attribute before adding this sprite to the sprite groups self._layer = 1 pygame.sprite.Sprite.__init__(self, groups) self.image = pygame.surface.Surface((rect.width, rect.height)) self.image.fill(GREEN) self.rect = rect self.risk_level = risk_level self.font = pygame.font.SysFont('Arial', 20) text = self.font.render(risk_level, 1, (255,0,0), GREEN) text_rect = text.get_rect(center=(rect.width/2, rect.height/2)) self.image.blit(text, text_rect) class Wo…
tagged with: python-3.x
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/51719987
downvote count: 0
answers question: http://stackoverflow.com/q/51719951
score: 34
type: Answer
has comment: http://stackoverflow.com/comment/104493479
upvote count: 34
has comment: http://stackoverflow.com/comment/90417662
has comment: http://stackoverflow.com/comment/90425701
has body: You can use the following command lines in terminal (permissions may be required): conda env remove --name myenv alternatively: conda remove --name myenv --all You can do conda info --envs to verify the action was successful. More info here.
has comment: http://stackoverflow.com/comment/90417928

http://stackoverflow.com/comment/90466448
type: QuestionComment
score: 0
type: Comment
has text: Can you provide a minimal complete verifiable example? Please read [this](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/51752581

http://stackoverflow.com/q/51651266
downvote count: 0
has comment: http://stackoverflow.com/comment/90267392
score: 1
has comment: http://stackoverflow.com/comment/90266435
has body: I need to get confidence of model in returned answer, because sometimes probabilities looks strange. I use d = clf.decision_function(s)[0] probs = np.exp(d) / (1 + np.exp(d)) to get probabilities of every class. Is any way to get confidence of RidgeClassifier?
type: Question
tagged with: scikit-learn
has title: Sklearn: get confidence of ridgeclassifier
has comment: http://stackoverflow.com/comment/90267747
upvote count: 1
has comment: http://stackoverflow.com/comment/90266793
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90266138

http://stackoverflow.com/a/51791818
accepted answer of: http://stackoverflow.com/q/51791754
type: AcceptedAnswer
score: 0
type: Answer
has body: Do whichever changes you want manually once on an arbitrary system, then make a copy of the application's configuration files (in this case ~/.config/vlc) When you want to replicate the settings on a different machine, simply copy the settings to the same location.
answers question: http://stackoverflow.com/q/51791754

http://stackoverflow.com/comment/90520126
score: 0
comment on: http://stackoverflow.com/q/51772333
type: Comment
type: QuestionComment
has text: I wish to gather data from https://in.finance.yahoo.com/quote/%5ENSEI?p=^NSEI&.tsrc=fin-srch-v1 I am not sure about the usage policy.

http://stackoverflow.com/comment/90340988
type: Comment
has text: Which doesn't work for `worldworldworld` as explained in the comments above.
score: 1
comment on: http://stackoverflow.com/a/51689626
type: AnswerComment

http://stackoverflow.com/q/51669304
type: AnsweredQuestion
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51669363
favorite count: 0
accepted answer: http://stackoverflow.com/a/51669363
tagged with: python-3.x
has body: I'm using Python 3.6 and I need to turn the list below into a dictionary of dictionaries: myList = [['A',[['a',1],['b',0],['c',1]]],['B',[['a',0],['b',1],['c',1]]]] Output: myDict = {A: {a: 1, b: 0, c: 1}, B: {a: 0, b: 1, c: 1}} I tried to use: myDict = defaultdict(lambda: defaultdict(list)) for key1, key2, *values in myList: myDict[key1][key2].extend(values) But I get an error: TypeError: unhashable type: 'list'
has title: Turn a list of lists of lists of lists into a dictionary
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/90414978
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51727323
has text: Sorry, if i wasn't precise. I want `['AA, 'AA, 'AA', 'AA', 'BB', 'BB', 'BB', 'BB']`, not mixing elements.

http://stackoverflow.com/comment/90371190
type: QuestionComment
has text: Surely it didn't work because you still `return`ed the original username afterwards?
score: 0
comment on: http://stackoverflow.com/q/51704795
type: Comment

http://stackoverflow.com/comment/90335380
type: AnswerComment
has text: @FinnAndersen: the decorators are applied to the new function that `View.as_view()` returns; this has the advantage that you can reach the decorators through the Flask APIs for endpoints and routing too. If you don't need that, then applying the decorators to `dispatch_request()` is just fine.
type: Comment
comment on: http://stackoverflow.com/a/51675874
score: 0

http://stackoverflow.com/comment/90397304
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51704699
has text: I was able to fix your solution by adding this code: if longest > length: print(longest) else: print(length)
type: AnswerComment

http://stackoverflow.com/comment/90388295
has text: Stackoverflow is not really set up to teach beginner level code. Go to a different forum where comments can contain code.
comment on: http://stackoverflow.com/a/51713302
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51714694
has title: Trying to parse a div class but can't get the correct results
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90392761
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51715702
score: 2
downvote count: 0
type: UnansweredQuestion
has body: I'm trying to parse the div class titled "dealer-info" from the URL below. https://www.nissanusa.com/dealer-locator.html I tried this: import urllib.request from bs4 import BeautifulSoup url = "https://www.nissanusa.com/dealer-locator.html" text = urllib.request.urlopen(url).read() soup = BeautifulSoup(text) data = soup.findAll('div',attrs={'class':'dealer-info'}) for div in data: links = div.findAll('a') for a in links: print(a['href']) Normally, I would expect that to work, but I'm getting this result: HTTPError: Forbidden Also, tried this. import urllib.request user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' url = "https://www.nissanusa.com/dealer-locator.html" headers={'User-Agent':user_agent,} request=urllib.request.Request(url,None,headers) #The assembled request response = urllib.request.urlopen(request) data = response.read() # The data u need print(data) That gives me all the HTML on the site, but it's pretty ugly to look at, or make any sense of at all. I'm trying to get a structured data set, of "dealer-info". I am using Python 3.6.
type: Question

http://stackoverflow.com/a/54611198
has body: Ciao @DavideNardone Regarding the performance measure, @kutschkem is right: if you're working on a binary classification and your method generates a confusion matrix, use the Matthews correlation coefficient (MCC) instead of accuracy or F1 score or other rates. Please take a look at Tip 8 in my paper for the scientific reasons. Regarding how to choose the best configuration for your model, I think your majority approach is on the right direction. I would reframe it this way: Voting the best configuration (highest Matthews correlation coefficient MCC) when the number of features varies and then Picking the configuration which has the largest number of vote. Perhaps this approach is not the best in the world, but surely has a strong scientific background (the majority vote, in fact, is used in random forest as well). Also, I think Stack Overflow might not be the best place where to ask computational intelligence questions; I would suggest you to move/re-ask this question on Cross Validated or other Stack Exchange websites. Good luck!
answers question: http://stackoverflow.com/q/51773317
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/96219591
score: 1
upvote count: 1

http://stackoverflow.com/q/51790913
answer count: 1
has comment: http://stackoverflow.com/comment/90540054
has body: Solution: removing the print statement shows the data once. But I do not understand the logic behind this? This seems like a very straightforward issue but I am having a great deal of trouble finding a solution or anyone else that has replicated this issue. I am simply trying to read some data from a csv using pandas. The csv is fairly large and I thought was the cause of the issue but I created a new test case csv by hand which is simply a 3x3 grid: A b c 1 2 3 4 5 6 This also caused the issue that I have not seen before. Essentially when I interact with the dataframe it is replicated twice. import json #(for later use) import pandas as pd import numpy as np data = pd.read_csv("Workbook1.csv") print (data) output: A b c 0 1 2 3 1 4 5 6 A b c 0 1 2 3 1 4 5 6 print (type(data)) output: &lt;class 'pandas.core.frame.DataFrame'&gt; &lt;class 'pandas.core.frame.DataFrame'&gt; It's not the case that I can drop the first few rows to delete one half either: data.drop(data.index[0], axis =0, inplace = True) print (data) output: A b c 1 4 5 6 A b c 1 4 5 6 It seems like the strangest problem that I have not seen before from using pandas and reading files multiple times with no such similar issue. Edit Further to this, when I remove the 'import json' at the top, the script fails all together stating that 'module' object has no attribute 'read_csv' import pandas as pd import numpy as np data = pd.read_csv('Workbook1.csv') data Results in AttributeError: 'module' object has no attribute 'read_csv'
has comment: http://stackoverflow.com/comment/90539656
tagged with: pandas
has comment: http://stackoverflow.com/comment/90539341
tagged with: python
favorite count: 0
has title: pandas.read_csv duplicate issue
has comment: http://stackoverflow.com/comment/90539777
type: UnansweredQuestion
downvote count: 1
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51799465

http://stackoverflow.com/a/55329375
has body: The problem appears to be that your coordinates are too old; satellite coordinates are generally only accurate for a couple of weeks to either side of the moment they're released. In this case: print(sat._epoch) the coordinates were 4 months old when you tried them out: 2018/4/17 17:43:30 If you try a value like now = '2018-04-18' I think you'll get a more reasonable number.
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51676631

http://stackoverflow.com/comment/90300999
comment on: http://stackoverflow.com/a/51669064
score: 0
type: Comment
has text: @MrYouMath I recommend consulting the documentation more often :)
type: AnswerComment

http://stackoverflow.com/q/51723910
has answer: http://stackoverflow.com/a/51724077
has comment: http://stackoverflow.com/comment/90436014
type: Question
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/90428923
has comment: http://stackoverflow.com/comment/90416956
tagged with: numpy
answer count: 2
has body: I'm a newer to python-opencv, so I read this tutorial and found some sample codes like this: pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32) pts = pts.reshape((-1,1,2)) cv2.polylines(img,[pts],True,(0,255,255)) it's about to show you how to draw polygons using cv2.polylines function, most of them are easy to understand, which I'm curious about is : pts = pts.reshape((-1,1,2)) #I understand this makes pts.shape to be (4,1,2) I try to remove this code and find that didn't make any difference, it works fine, either. before this reshape operation, pts's shape is (4,2), which is intuitive enough for me. Besides, when I write codes like this: convex_pts = cv2.convexHull(pts) #get a convexhull from pts，pts's shape is(4,2) print(convex_pts) #[[[72,20]],[[20,30]],[[10,5]],[[50,10]]] print(convex_pts.shape) #(4,1,2) it seems to me that python-opencv insists to "unsqueeze" it and make it has shape like(x,1,2), that's weird to me cause when the shape is (x,2) it just works fine in the tutorial case .Any reason why is this necessary ? I searched around and found nothing helpful, am I missing something? So I want to know why and at what situation points need to be reshaped like this?
has comment: http://stackoverflow.com/comment/90415680
has comment: http://stackoverflow.com/comment/90411298
downvote count: 0
has answer: http://stackoverflow.com/a/51724120
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90408563
type: AnsweredQuestion
has title: At what situation points need to be reshaped like reshape(-1,1,2) in python-opencv?
possible better answer: http://stackoverflow.com/a/51724077
upvote count: 3
accepted answer: http://stackoverflow.com/a/51724120

http://stackoverflow.com/comment/90534362
type: Comment
comment on: http://stackoverflow.com/a/51784356
has text: Thanks for letting me know.
type: AnswerComment
score: 0

http://stackoverflow.com/a/51646164
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51645874
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51645874
type: Answer
score: 3
upvote count: 3
has body: The answer to your direct question is simple. You've already worked out how to split the list into these two lists: ['a5 abc xyz','a6 abc deg'] ['w1 3 45 7','r4 2 7 9'] Now, you just need to sort each one, and add them together. But this really isn't the right approach in the first place. When looking at how to do a custom sort, the first thing you should do is ask yourself whether some other list, which you could easily transform this one into, would be trivial to sort. For example, imagine you had this: list_of_sent = [ (False, 'a5 abc xyz'), (True, 'w1 3 45 7'), (False, 'a6 abc deg'), (True, 'r4 2 7 9')] … where that first value in each tuple is True iff the second word in the string is a number. If that were your list, you could just call sort or sorted on it, and you'd be done. So, can you transform each of your strings into a tuple like that? Sure you can: def flagnumbers(words): isnumber = words.split()[1].isdigit() return isnumber, words And how, you can just pass that as the key function to sort your list: list_of_sent = ['a5 abc xyz','w1 3 45 7','a6 abc deg','r4 2 7 9'] print(sorted(list_of_sent, key=flagnumbers)) That's it. The Sorting HOWTO in the docs covers key functions in more detail, with some nice examples.

http://stackoverflow.com/comment/90518300
has text: This [link](https://stackoverflow.com/a/51315029/3702377) is another way
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51780257

http://stackoverflow.com/q/51713938
tagged with: python
has answer: http://stackoverflow.com/a/51716258
downvote count: 0
score: 1
has title: how to revise field_to_native in Django/Rest FrameWork
type: Question
tagged with: django-rest-framework
has body: Recently, I am moved a django app from Django 1.4 to Django 1.11. I met a problem about field_to_native. I appreciate very much for any hints. The original code: class LoopgroupDqHyperlinkedIdentityField(relations.HyperlinkedIdentityField): def field_to_native(self, obj, field_name): # copied from superclass request = self.context.get('request', None) format = self.format or self.context.get('format', None) view_name = self.view_name or self.parent.opts.view_name # new lgdq_attrs = 'loopgroup_id', 'year', 'month' view_kwargs = dict((X, getattr(obj, X)) for X in lgdq_attrs) return RF_reverse(view_name, kwargs=view_kwargs, request=request, format=format) class LoopgroupDqSerializer(HyperlinkedModelSerializer): url = LoopgroupDqHyperlinkedIdentityField() class Meta: model = LoopgroupDq fields = tuple(X.name for X in LoopgroupDq._meta.fields) + ('url',) The system returns the following error File "/srv/projects/python/dotfreewaydata/dataquality/serializers.py", line 43, in LoopgroupDqSerializer url = LoopgroupDqHyperlinkedIdentityField() File "/srv/virtual_environments/dotfreewaydata/local/lib/python2.7/site-packages/rest_framework/relations.py", line 408, in init assert view_name is not None, 'The view_name argument is required.' AssertionError: The view_name argument is required. I google this error message and found that field_to_native has been deprecated in Django Rest Framework 3.0. In http://www.django-rest-framework.org/topics/3.0-announcement/ They mentioned 1)The field_from_native() and field_to_native() methods are removed. 2)Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation(). Use get_value to modify the data value passed to_internal_value(). The website gives some simple example. However, I don't understand. Could anyone tell me how to modify "field_to_native" to "get_attribute" and "get_value" and so on.
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/90491392
type: QuestionComment
has text: Then you can first do a `.fillna()`
comment on: http://stackoverflow.com/q/51766069
score: 0
type: Comment

http://stackoverflow.com/q/51765063
has comment: http://stackoverflow.com/comment/90488991
has comment: http://stackoverflow.com/comment/90489088
has title: Resample sum keeping the index of last observation per day pandas
answer count: 2
has answer: http://stackoverflow.com/a/51765602
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51765981
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: resampling
tagged with: python
score: 2
type: Question
has body: I have a dataframe: Localmax symbol dvol idx 2016-10-19 09:05:00 st1 5172.159 2016-10-19 09:05:00 2016-10-19 09:05:00 st2 5172.18 2016-10-19 09:05:00 2016-10-19 17:30:00 st1 5000 2016-10-19 17:30:00 2016-10-19 17:40:00 st2 8000 2016-10-19 17:40:00 How can I do resample per symbol, so that I have a sum of dvol per day, KEEPING the index of the last observation per day? I tried: &gt; df['idx']=df.index &gt; dvol_sum = df.groupby(['symbol', Grouper(freq='D')])['dvol', 'idx'].agg(['sum']) but it produced just one column of dvol, and the index with 00:00:00 time stamp.. The expected output is: Localmax symbol dvol 2016-10-19 17:30:00 st1 sum of dvol for 2016-10-19 for st1 2016-10-19 17:40:00 st2 sum of dvol for 2016-10-19 for st2

http://stackoverflow.com/comment/90282472
has text: you don't have to use the `split` function if you just want to get all the characters separately.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51659430

http://stackoverflow.com/q/51753705
has comment: http://stackoverflow.com/comment/90467924
has comment: http://stackoverflow.com/comment/90467744
type: Question
tagged with: counter
has title: how to count n grams from a column
tagged with: n-gram
score: 0
has comment: http://stackoverflow.com/comment/90468199
has comment: http://stackoverflow.com/comment/90468162
tagged with: python
has body: So I am using N-grams for the first time. What I have done is I took a df with multiple rows and columns. I removed the stop words and tokenized them. My Code is this from nltk.corpus import stopwords stop = stopwords.words('english') # Exclude stopwords with Python's list comprehension and pandas.DataFrame testdf['issues_without_stopwords'] = testdf['issue'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop) if x[0]])) testdf['questions_without_stopwords'] = testdf['question'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)])) # Remove Punctuations and Tokenize from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(r'\w+') testdf['questions_tokenized'] = testdf['question'].apply(lambda x: tokenizer.tokenize(x)) testdf['issue_tokenized'] = testdf['issue'].apply(lambda x: tokenizer.tokenize(x)) testdf["Concate"] = testdf['issue_tokenized']+ testdf['questions_tokenized'] #Create your n-grams (1st method) def find_ngrams(input_list, n): return list(zip(*[input_list[i:] for i in range(n)])) df1 = testdf["Concate"].apply(lambda x: find_ngrams(x, 4)) from itertools import tee, islice from collections import Counter #Create your n-grams and count them in cell (2nd method) def ngrams(lst, n): tlst = lst while True: a, b = tee(tlst) l = tuple(islice(a, n)) if len(l) == n: yield l next(b) tlst = b else: break df2 = Counter(ngrams(df2["value"], 4)) I was then able to convert them into 4-gram. This is my raw sample data: issue question 0 Menstrual health How to get my period back 1 stomach pain any advise 2 Vaping I am having a tonsillectomy tomorrow 3 Mental health Ive been feeling sad most of the time 4 Kidney stone I was diagnosed with one Saturday at Er What I want is a column with all the n grams and another column with its freq. something like this: N - grams Freq [(n, gram, talha)] 2 [(talha, software, python)] 1 I also need to remove all the duplicate n grams, for example [(n, gram, talha)] and [(talha, g…
answer count: 0
has comment: http://stackoverflow.com/comment/90468309
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17531684
has comment: http://stackoverflow.com/comment/90485080
has comment: http://stackoverflow.com/comment/90477731
has comment: http://stackoverflow.com/comment/90468280
tagged with: nltk

http://stackoverflow.com/a/51661285
accepted answer of: http://stackoverflow.com/q/51660176
answers question: http://stackoverflow.com/q/51660176
score: 0
type: AcceptedAnswer
type: Answer
has body: Never mind, figured it out: curr_tags = {} for each_tag in html_tags: if html_tags.index(each_tag) == 0: each_tag.attrs['id'] = 'rule_1' else: parent_id = each_tag.parent.attrs['id'] if parent_id in curr_tags.keys(): curr_tags[parent_id] += 1 else: curr_tags[parent_id] = 1 each_tag.attrs['id'] = parent_id + '.{0}'.format(curr_tags[parent_id])

http://stackoverflow.com/a/51725219
downvote count: 0
has comment: http://stackoverflow.com/comment/90411052
answers question: http://stackoverflow.com/q/51723000
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90410962
accepted answer of: http://stackoverflow.com/q/51723000
type: Answer
has comment: http://stackoverflow.com/comment/90411167
score: 3
has comment: http://stackoverflow.com/comment/90412021
upvote count: 3
has body: As per your question you won't be able to open multiple windows for different drop-down options as the &lt;options&gt; tags doesn't contains any href attribute. They will always render the new page in the same browser window. However to select a date from the Dropdown and then click() Search to view the planning applications you can use the following solution: Code Block: from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') url = 'https://services.wiltshire.gov.uk/PlanningGIS/LLPG/WeeklyList' driver.get(url) select = Select(driver.find_element_by_xpath("//select[@class='formitem' and @id='selWeek']")) list_options = select.options for item in range(len(list_options)): select = Select(driver.find_element_by_xpath("//select[@class='formitem' and @id='selWeek']")) select.select_by_index(str(item)) driver.find_element_by_css_selector("input.formbutton#csbtnSearch").click() print(driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[1]/td[1]/a').text) driver.get(url) driver.quit() Console Output: 18/06760/FUL 18/07187/LBC 18/06843/FUL 18/06705/FUL 18/06449/FUL 18/05534/FUL 18/06030/DEM 18/05784/FUL 18/05914/LBC 18/05241/FUL trivia To scrape all the links you need to replace: find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[1]/td[1]/a') with: find_elements_by_xpath('//*[@id="form1"]/table/tbody/tr[1]/td[1]/a')

http://stackoverflow.com/comment/90399904
type: Comment
comment on: http://stackoverflow.com/a/51694298
type: AnswerComment
score: 0
has text: to my understanding, the difference between `df[i]` and `df.loc[i]` is that the latter support editing. Isn't this the case?

http://stackoverflow.com/q/51643746
has comment: http://stackoverflow.com/comment/90252680
type: Question
tagged with: numpy
tagged with: nltk
downvote count: 0
has comment: http://stackoverflow.com/comment/90251866
has answer: http://stackoverflow.com/a/51648892
answer count: 1
linked to: http://stackoverflow.com/q/8929284
has body: I'm doing NLP in Python 3 and trying to optimize the speed of a code. The code converts a list of words to a list (or array) of numbers using a given dictionary. For example, mydict = {'hello': 0, 'world': 1, 'this': 2, 'is': 3, 'an': 4, 'example': 5} word_list = ['hello', 'world'] def f(mydict, word_list): return [mydict[w] for w in word_list] # f(mydict, word_list) == [1, 2] I want to speed up the function f, especially when the word_list is about 100 words long. Is it possible? Use of external libraries like nltk, spacy, numpy etc is OK. Currently, it takes 6us on my laptop. &gt;&gt;&gt; %timeit f(mydict, word_list*50) 6.74 us +- 2.77 us per loop (mean +- std. dev. of 7 runs, 100000 loops each)
has title: Fast dictionary lookup for word list in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/90285061
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90252137
tagged with: spacy
has comment: http://stackoverflow.com/comment/90388829
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90252697
has comment: http://stackoverflow.com/comment/90253935
score: 1
upvote count: 1

http://stackoverflow.com/a/51755835
downvote count: 0
answers question: http://stackoverflow.com/q/51755534
type: Answer
upvote count: 1
score: 1
has body: You're starting from an incorrect premise: And os.chdir switches the directory for all processes being run, as far as I know. Nope. It switches the directory for the current process, not every process on the system (or even every process in the group, or anything like that). Of course if you chdir in the parent before starting the children, the children will start in that new directory. But if you chdir in any of the children, it won't affect anyone else. And if you chdir in the parent after starting the children, it also won't affect anyone else. How can I ensure that each process safely runs in an appropriate directory without suddenly being kicked out of it by another one? You don't have to do anything; that's how every operating system already works. If you want to verify this for yourself, try running this program. On whatever platform you want, with every startmethod supported by that platform, you will see that the children can change directories independently, without affecting each other or the parent. import multiprocessing import os def func(): pid = str(os.getpid()) print(f'{pid}: {os.getcwd()}') try: os.mkdir(pid) except FileExistsError: pass os.chdir(pid) print(f'{pid}: {os.getcwd()}') if __name__ == '__main__': import sys startmethod = sys.argv[1] if len(sys.argv)&gt;1 else 'fork' multiprocessing.set_start_method(startmethod) print(f'{os.getpid()}: {os.getcwd()}') children = [multiprocessing.Process(target=func) for _ in range(2)] for child in children: child.start() for child in children: child.join() print(f'{os.getpid()}: {os.getcwd()}')

http://stackoverflow.com/q/51707081
has comment: http://stackoverflow.com/comment/90375429
has answer: http://stackoverflow.com/a/51707490
score: 2
has body: So, i created Some class class Some: @classmethod def __init__(cls, somevar): cls.somevar = somevar @classmethod def read(cls): return cls.somevar Now I tried to set variable outside and read it from class: instance = Some([1, 2, 3]) instance.somevar = [4, 5, 6] print(instance.read()) &gt;&gt;&gt;&gt; [1, 2, 3] But calling same named variable outside class give me expected output instead, print(instance.somevar) &gt;&gt;&gt;&gt; [4, 5, 6] What is my misunderstanding about the OOP? EDIT My goal is to create multiple instances of Some that will have their own values.
accepted answer: http://stackoverflow.com/a/51707202
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90375890
has comment: http://stackoverflow.com/comment/90375690
has comment: http://stackoverflow.com/comment/90375786
tagged with: python
has title: Why class variable read from method and outside are different?
answer count: 4
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90375057
has answer: http://stackoverflow.com/a/51707204
has comment: http://stackoverflow.com/comment/90375288
has answer: http://stackoverflow.com/a/51707202
type: Question
has answer: http://stackoverflow.com/a/51707560
tagged with: oop
possible better answer: http://stackoverflow.com/a/51707204

http://stackoverflow.com/comment/90308218
type: Comment
type: QuestionComment
score: 1
has text: Not a precanned solution, but you can get inspired by [this SO qustion and answer](https://stackoverflow.com/questions/24633664/confidence-interval-for-exponential-curve-fit)
comment on: http://stackoverflow.com/q/51672325

http://stackoverflow.com/comment/90506682
type: QuestionComment
has text: can you show sample data frame as well? It will help to reproduce the issue and work on it.
comment on: http://stackoverflow.com/q/51773764
score: 0
type: Comment

http://stackoverflow.com/q/51748004
has body: I have a python code roughly like this: class SomeClass(): def get_date(self): date = # read the data from the database in YYYY-MM-DD HH:MM:SS format return date now, I will use the returned value in an API query, which accepts the input as a unix timestamp. Actually I can give the returned date to another function to have it converted to a timestamp, but I thought it would be a good opportunity to learn about function cascading / chaining, which I've always wondered about in Python. Now, what I basically want to achieve is something like this: If I just execute SomeClass.get_date(), I want to have the date in the same format that has been returned from the database, which is YYYY-MM-DD HH:MM:SS If I execute SomeClass.get_date().as_timestamp(), I should get it as timestamp. If not possible, I would settle for having it like SomeClass.get_date().as_datetime() and SomeClass.get_date().as_timestamp() I might use the second function (.as_timestamp()) for more than one primary function (there are multiple datetime columns that I may need to be converted into timestamp). I've looked into some examples of function cascading. They are mostly saying that key to this is returning the self, but I could not find any info about how to implement it in the way I need to. I basically need the return value to be fed into the second function (I guess), but not sure if it is possible, and don't know how to do it. Any ideas?
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51749298
type: Question
has title: How to properly implement method cascading - chaining in Python?
downvote count: 0
has comment: http://stackoverflow.com/comment/90455831
answer count: 1
accepted answer: http://stackoverflow.com/a/51749298
tagged with: chaining
favorite count: 0
has comment: http://stackoverflow.com/comment/90456044

http://stackoverflow.com/comment/90396893
type: AnswerComment
has text: @Thomas Thank you. But username is ForeignKey in Alarm model, not CharField. So assigning shouldn't give any problem in this situation. Or I missed something?
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51717771

python-multithreading
tags question: http://stackoverflow.com/q/51670299
tags question: http://stackoverflow.com/q/51718428
tags question: http://stackoverflow.com/q/51670530
tags question: http://stackoverflow.com/q/51651132
tags question: http://stackoverflow.com/q/51775413
tags question: http://stackoverflow.com/q/51674786
tags question: http://stackoverflow.com/q/51692526
tags question: http://stackoverflow.com/q/51699802
tags question: http://stackoverflow.com/q/51731438
type: Tag
tags question: http://stackoverflow.com/q/51657549
tag name: python-multithreading
tags question: http://stackoverflow.com/q/51656853
tags question: http://stackoverflow.com/q/51769171

http://stackoverflow.com/comment/90490982
comment on: http://stackoverflow.com/a/51766234
score: 0
has text: Is isClicked a variable I have to define?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51698291
has comment: http://stackoverflow.com/comment/90358446
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90358043
has comment: http://stackoverflow.com/comment/90358693
has answer: http://stackoverflow.com/a/51698593
tagged with: dataframe
has title: Pandas - create new columns with groupby sum and where clause
type: Question
upvote count: 2
has body: I was using the following line of code to set a groupby sum to a new column df['new_col'] = df.groupby(['col1', 'col2'])['amount'].transform(sum) This worked pretty well, but I also need to only sum amounts for where another col(map) is a certain value I tried using this: df['new_col'] = df[df['map'] == 'newCol'].groupby(['col1', 'col2'])['amount'].transform(sum) But got an error: "ValueError: cannot reindex from a duplicate axis" I cannot use boolean indexing right before the first example because I need to create several new columns, each with map as a new value. Therefore, I can't keep modifying the df in place like that. EDIT: Data sample: d={'source': {'0': 'r', '1': 'r', '2': 'r', '3': 'r', '4': 'r'}, 'date': {'0': Timestamp, '1': Timestamp, '2': Timestamp, '3': Timestamp, '4': Timestamp}, 'name': {'0': 'A', '1': 'A', '2': 'A', '3': 'A', '4': 'A'}, 'codename': {'0': 'D', '1': 'D', '2': 'D', '3': 'E', '4': 'F'}, 'map': {'0': 'X', '1': 'X', '2': 'X', '3': 'X', '4': 'Y'}, 'amount': {'0': 250.0, '1': 450.0, '2': 360.0, '3': 10.0, '4': -436.0}, 'extra': {'0': 'P', '1': 'P', '2': 'P', '3': 'P', '4': 'P'}} df = pd.DataFrame(d) Grouping by date, name, and extra. All the new columns are going to be summing by amount where map equals a different value.
has comment: http://stackoverflow.com/comment/90358523
answer count: 1
has comment: http://stackoverflow.com/comment/90358494
favorite count: 0
has comment: http://stackoverflow.com/comment/90358859
has comment: http://stackoverflow.com/comment/90358703
tagged with: pandas
has comment: http://stackoverflow.com/comment/90358029

http://stackoverflow.com/comment/90469501
type: Comment
comment on: http://stackoverflow.com/a/51702647
has text: I have added the implemented code to make an "automated" training. You should check it out maybe it will become more clear on how it works. Steps are written in the comments. Note that this is written for OpenCV 3. Cheers!
score: 0
type: AnswerComment

http://stackoverflow.com/a/51787954
has comment: http://stackoverflow.com/comment/90598482
has comment: http://stackoverflow.com/comment/90599888
has comment: http://stackoverflow.com/comment/90547238
has comment: http://stackoverflow.com/comment/90600478
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90599519
has comment: http://stackoverflow.com/comment/90601366
has comment: http://stackoverflow.com/comment/90617470
accepted answer of: http://stackoverflow.com/q/51689620
has comment: http://stackoverflow.com/comment/90602258
has comment: http://stackoverflow.com/comment/90600687
answers question: http://stackoverflow.com/q/51689620
upvote count: 1
has comment: http://stackoverflow.com/comment/90633547
type: AcceptedAnswer
has body: I'm trying to give a somewhat complete answer. First of all: Can this code be adapted to be run on the GPU using (py)OpenCL? Most probably yes. Can this been done automatically? No (afaik). Most of the questions I get about OpenCL are along the lines of: "Is it worth porting this piece of code to OpenCL for a speedup gain?" You are stating, that your outer loop is independent on the results of other runs, which makes the code basically parallelizable. In a straightforward implementation, each OpenCL working element would execute the same code with slightly different input parameters. Not regarding overhead by data transfer between host and device, the running time of this approach would be equal to the running time of the slowest iteration. Depending on the iterations in your outer loop, this could be a massive speed gain. As long as the numbers stay relatively small, you could try the multiprocessing module in python to parallelize these iterations on the CPU instead of the GPU. Porting to the GPU usually only makes sense, if a huge number of processes are to be run in parallel (about 1000 or more). So in your case, if you really want an enormous speed boost, see if you can parallelize all calculations inside the loop. For example, you have 150 iterations and 2000 data points. If you could somehow parallelize these 2000 data points, this could offer a much bigger speed gain, which could justify the work of porting the whole code to OpenCL. TL;DR: Try parallelizing on CPU first. If you find the need to run more than several 100s of processes at the same time, move to GPU. Update: Simple code for parallelizing on CPU using multiprocessing (without callback) import numpy as np import time import multiprocessing as mp m = 3 # Dimension of datapoints num_points = 2000 # Number of datapoints iterMax = 150 # Maximum number of iterations NMax = 10 # Maximum number of neurons #%% np.random.seed(0) y = np.random.rand(num_points,m) # Generate always the same dataset sigma_0 =…
has comment: http://stackoverflow.com/comment/90603161
type: Answer

http://stackoverflow.com/comment/90540916
has text: You could use descriptors to raise an AttributeError when the `__set__` method is called
comment on: http://stackoverflow.com/q/51791679
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90348157
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51693269
has text: I enjoy making it short.
type: AnswerComment

http://stackoverflow.com/a/51744662
score: 2
answers question: http://stackoverflow.com/q/51744314
downvote count: 0
has body: You can try with one of these 2: df['age'] = df['age'].astype(str).str.split('-').str[0].astype(int) df['age'] = df['age'].astype(str).str[:4].astype(int)
type: Answer
has comment: http://stackoverflow.com/comment/90449184
upvote count: 2

http://stackoverflow.com/comment/90487520
has text: Thanks for sharing I tried above mentioned but still getting same error. In example which you share is for binary classification but I am using it for multiclass classification so just change loss='binary_crossentropy' to loss='categorical_crossentropy'
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51763330

http://stackoverflow.com/a/51712593
has comment: http://stackoverflow.com/comment/90411374
has comment: http://stackoverflow.com/comment/90395894
has comment: http://stackoverflow.com/comment/90411816
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90412407
type: Answer
has comment: http://stackoverflow.com/comment/90393236
accepted answer of: http://stackoverflow.com/q/51712106
downvote count: 0
has body: with open('input.txt') as fp: for line in fp: b = line.split("|") x,y = b In this code x is the integer before | and y is integer after |. So total code would be: import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.pipeline import make_pipeline X_arr = [] Y_arr = [] with open('input.txt') as fp: for line in fp: b = line.split("|") x,y = b X_arr.append(int(x)) Y_arr.append(int(y)) X=np.array([X_arr]).T print(X) y=np.array(Y_arr) print(y) model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression(fit_intercept = False)) model.fit(X,y) X_predict = np.array([[3]]) print(model.predict(X_predict))
score: 1
answers question: http://stackoverflow.com/q/51712106
has comment: http://stackoverflow.com/comment/90395760
has comment: http://stackoverflow.com/comment/90411621

http://stackoverflow.com/a/53307244
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51705239
has body: I've written a new python lib for collision detection between concave/convex polygons, and circles. It works very well, and is pretty efficient. It's pretty simple to use, and there are examples in the repository, as well as documentation. https://github.com/QwekoDev/collision
type: Answer

http://stackoverflow.com/comment/90293793
has text: This is great. Thanks!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51647864
type: Comment

http://stackoverflow.com/comment/90548627
type: Comment
comment on: http://stackoverflow.com/a/51734632
score: 0
has text: No problem, if it worked please mark the answer as correct! Happy coding/data sci-ing!!
type: AnswerComment

http://stackoverflow.com/q/51682837
tagged with: python-2.7
answer count: 2
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51684728
accepted answer: http://stackoverflow.com/a/51684728
has answer: http://stackoverflow.com/a/51682979
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: opencv
has title: Use Python OpenCV to Crop/Rotate/Resize Playing Cards From an Image
possible better answer: http://stackoverflow.com/a/51682979
score: 1
has body: I'm new to OpenCV (using 3.4.1 on Python 2.7) and wanting to learn how to process an image containing 9 playing cards. I know how to read in the image and have seen some examples of image processing, but don't know where to go from there. Ideally, I want to crop each of the nine cards from the image, rotate them to be completely straight (if offset), resize if needed, and save each card to a new image while retaining the color. Any examples to get me in the right direction are greatly appreciated! Thanks!

http://stackoverflow.com/comment/90521246
has text: I wouldn't trust a source which contains typos in the file name of the source code (`dir_wlaker_multiprocess.py`). If the author failed to name his file properly, he may be also failed to debug his code?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51781720

http://stackoverflow.com/comment/90448609
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51744142
has text: Hi, thank you for your answer. Upon the first run it worked as you said it should but when I added one more string it started to say '<filter object at 0x107773e10>' and when i removed the string to how it originally was it stayed printing the filter object message
type: AnswerComment

http://stackoverflow.com/a/51650576
answers question: http://stackoverflow.com/q/51650240
type: Answer
score: 0
has body: Using pd.pivot_table: res = pd.pivot_table(df, index='SK_ID_CURR', columns='CREDIT_ACTIVE', values='CREDIT_DAY_OVERDUE', aggfunc='sum') print(res) CREDIT_ACTIVE Active BadDebt Sold SK_ID_CURR 436084 2838 0 0

http://stackoverflow.com/comment/90496121
type: Comment
type: QuestionComment
has text: It seems curious that your final one ends up the same length as df1 given a merge is an inner join by default. Do you have a low spec system where it just so happens you've got such a large columns of columns (and potentially large sized columns) and overlapping columns that result in more columns) your system is thrashing your swapfile?
score: 0
comment on: http://stackoverflow.com/q/51768192

http://stackoverflow.com/comment/90277934
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51656818
score: 0
has text: For more information about the underlying library used by numpy, show the output of `np.show_config()`.

http://stackoverflow.com/comment/90468258
has text: Can you add your current attempt to the question?
score: 0
comment on: http://stackoverflow.com/q/51754263
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90474910
comment on: http://stackoverflow.com/a/51737649
type: Comment
has text: Well, you could certainly loop through the Parameters, making each one fixed or variable and redo the fit, then compare the AIC value to determine if that parameter is needed to explain the data. I'm sure that could be abused, but that seems to be a typical concern for stepwise regression.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51656787
type: Answer
has body: new_df = pd.concat([df] * 50, ignore_index=True) new_df["hours"] = np.arange(df.shape[0]) new_df["cumulative_value"] = df["value_to_add"].cumsum()
score: 0
answers question: http://stackoverflow.com/q/51656402

http://stackoverflow.com/a/51750087
has body: @ImportanceOfBeingErnest: I can live with having rounded instead of "butted" dashes. Your proposal certainly solves my problem. When translating your Python code to Julia it reads: using PyPlot plot([0,1],[-0.05,-0.05],linestyle="--",linewidth=1,dash_capstyle="round") annotate("",xy=(1,0.05),xytext=(0,0.05),xycoords="data", arrowprops=Dict("arrowstyle"=&gt;"-","linestyle"=&gt;"--","linewidth"=&gt;1, "shrinkA"=&gt;0, "shrinkB"=&gt;0)) ylim(-0.5,0.5) This is exactly what I need.
answers question: http://stackoverflow.com/q/51746400
score: 0
type: Answer

http://stackoverflow.com/a/51731585
score: 1
answers question: http://stackoverflow.com/q/51712015
has body: Update:- So, I found out that the issue was with the initial migration itself. Since, the tables were already existing in my case, it might have taken it as duplicate object names when trying to migrate the first time. I had to fake the initial migration so that it only checks if the tables exist for the models and if it does then migrate. Below is the command for the same. It worked perfectly and my initial migration was successful. python manage.py makemigrations python manage.py migrate --fake-initial
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51712015
type: Answer
upvote count: 1

http://stackoverflow.com/a/51737325
downvote count: 0
answers question: http://stackoverflow.com/q/51737156
type: AcceptedAnswer
type: Answer
upvote count: 1
has body: You can use merge and then duplicated + loc to update your merged column: merge_cols = ['B', 'C'] df2 = pd.merge(df, df1, on=merge_cols) df2.loc[df2[merge_cols].duplicated(), 'A_y'] = '' print(df2) A_x B C A_y 0 10:00:05 ABC 1 10:00:00 1 13:00:05 ABC 1 2 11:00:05 DEF 1 11:00:00 3 12:00:05 XYZ 1 12:00:00 4 14:00:05 DEF 2 14:00:00
score: 1
accepted answer of: http://stackoverflow.com/q/51737156

http://stackoverflow.com/q/51689418
downvote count: 0
has comment: http://stackoverflow.com/comment/90340917
has comment: http://stackoverflow.com/comment/90340965
favorite count: 0
has body: I want to match every substring that begins with w and ends d with regex. For example for input worldworld it should return ('worldworld', 'world', 'world'). (note: there are two world but they are different because they are at different position in the string) For this purpose I ended with this program with following regex: import re s = '''worldworld''' for g in re.finditer(r'(?=(w.*d))(?=(w.*?d))', s): print(g.start(1), g.end(1), g[1]) print(g.start(2), g.end(2), g[2]) print('-' * 40) This prints: 0 10 worldworld 0 5 world ---------------------------------------- 5 10 world 5 10 world ---------------------------------------- It finds all substrings, but some are duplicates also (notice the starting and ending position of the group). I can filter the groups afterwards with group's starting and ending position, but I'm wondering if it can be done with change to my regex, to only return unique groups. Can I change this regex to only match group that is different from other? If yes how? I'm open to suggestions how to solve this problem.
has comment: http://stackoverflow.com/comment/90340930
tagged with: regex
accepted answer: http://stackoverflow.com/a/51689884
has title: Match group only if it's different than other matching group
has answer: http://stackoverflow.com/a/51689626
tagged with: python
has comment: http://stackoverflow.com/comment/90340588
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51689626
has comment: http://stackoverflow.com/comment/90340914
score: 4
has comment: http://stackoverflow.com/comment/90340586
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/51689884

http://stackoverflow.com/comment/90310095
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51673543
has text: This is the result `Index([u'A', u'B', u'C'], dtype='object', name=u'DF name')`

http://stackoverflow.com/a/51733296
has comment: http://stackoverflow.com/comment/90427234
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51733208
answers question: http://stackoverflow.com/q/51733208
type: AcceptedAnswer
downvote count: 0
has body: If you're trying to modify a global variable within a function you must tell the function that you're going to be working with a global variable, because functions assume you want them to use a local variable. Try this: v1 =0 v2 =0 def print_value1(val1): global v1 v1 = val1 print (v1) def print_value2(val2): global v2 v2 = val2 print (v2) and carry on from there!

http://stackoverflow.com/a/51801898
accepted answer of: http://stackoverflow.com/q/51798304
type: AcceptedAnswer
has body: So to summarize, you need to reverse IP and TCP order. What people call TCP/IP is indeed a TCP layer stacked on top of an IP layer. Here is for instance the stack of basic layers: Each stack adds new informations: Ethernet gives the MAC addresses so that the packet goes to the router. Then IP tells to which computer the data should be sent. TCP finally announces some data, extensions..... It needs to be in this order: you need to know where the packet needs to go before specifying the data
answers question: http://stackoverflow.com/q/51798304
type: Answer
score: 0

http://stackoverflow.com/q/51690430
type: Question
has comment: http://stackoverflow.com/comment/90342810
score: 0
answer count: 1
has body: I am currently using a list to spawn in the enemies running across the screen and wanted to know what I am doing wrong in my code. I want the basketball to collide with the badlist. When I run there are no errors, the basketball just doesn't collide with the badlist. death = pygame.Rect.collidelist(badlist, basketball) if death: myfont = pygame.font.SysFont('Comic Sans MS', 50) textsurface = myfont.render('The Baddies got you', True, (0, 0, 0)) screen.blit(textsurface,(700,700))
tagged with: pygame
has title: List collision not working
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51690557
tagged with: python
has comment: http://stackoverflow.com/comment/90342809
tagged with: collision
tagged with: list
has comment: http://stackoverflow.com/comment/90342772

http://stackoverflow.com/a/51756051
answers question: http://stackoverflow.com/q/51755927
type: AcceptedAnswer
score: 0
type: Answer
has body: Setup df1 = pd.DataFrame( [[1, 2, 3, 4, 5, 6] * 2] * 3, columns=pd.MultiIndex.from_product(['ID1 ID2 ID3'.split(), range(4)]) ) df2 = df1.ID1 * 2 df1 ID1 ID2 ID3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 4 5 6 1 2 3 4 5 6 1 1 2 3 4 5 6 1 2 3 4 5 6 2 1 2 3 4 5 6 1 2 3 4 5 6 df2 0 1 2 3 0 2 4 6 8 1 2 4 6 8 2 2 4 6 8 The problem is that Pandas is trying to line up indices (or columns in this case). We can do some transpose/join trickery but I'd rather avoid that. Option 1 Take advantage of the fact that we can assign via loc an array so long as the shape matches up. Well, we better make sure it does and that the order of columns and index are correct. I use align with the right parameter to do this. Then assign the values of the aligned df2 df1.loc[:, 'ID1'] = df2.align(df1.ID1, 'right')[0].values df1 ID1 ID2 ID3 0 1 2 3 0 1 2 3 0 1 2 3 0 2 4 6 8 5 6 1 2 3 4 5 6 1 2 4 6 8 5 6 1 2 3 4 5 6 2 2 4 6 8 5 6 1 2 3 4 5 6 Option 2 Or, we can give df2 the additional level of column indexing that we need to lined it up. The use update to replace the relevant cells in place. df1.update(pd.concat({'ID1': df2}, axis=1)) df1 ID1 ID2 ID3 0 1 2 3 0 1 2 3 0 1 2 3 0 2 4 6 8 5 6 1 2 3 4 5 6 1 2 4 6 8 5 6 1 2 3 4 5 6 2 2 4 6 8 5 6 1 2 3 4 5 6 Option 3 A creative way using stack and assign with unstack df1.stack().assign(ID1=df2.stack()).unstack() ID1 ID2 ID3 0 1 2 3 0 1 2 3 0 1 2 3 0 2 4 6 8 5 6 1 2 3 4 5 6 1 2 4 6 8 5 6 1 2 3 4 5 6 2 2 4 6 8 5 6 1 2 3 4 5 6
accepted answer of: http://stackoverflow.com/q/51755927
has comment: http://stackoverflow.com/comment/90490055

http://stackoverflow.com/q/51745197
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51745362
has comment: http://stackoverflow.com/comment/90459711
has body: I have one string as below: key_val = "count=2, name=['hello', 'hi'], word='Dial::100', roll=12" I need to get the dictionary from the string as below: d_key_val = {'count'=2, 'name'=['hello', 'hi'], 'word'='Dial::100', 'roll'=12} I tried with the following: regx = r'(?P&lt;key&gt;\w+)=(?P&lt;value&gt;\[.+?\]|\d+|\S+)' r_key_val = re_findall(regx, key_val) for key, value in r_key_val: d_key_val[key] = value But it is storing values as all string: d_key_val = {'count'='2', 'name'="['hello', 'hi']", 'word'="'Dial::100'", 'roll'='12'} Is there any way or regex to store the values as same data type as it has in string?
possible better answer: http://stackoverflow.com/a/51745314
answer count: 2
has answer: http://stackoverflow.com/a/51745314
downvote count: 0
accepted answer: http://stackoverflow.com/a/51745362
favorite count: 0
has title: String containing list and other data types to dictionary without changing the data type in python
linked to: http://stackoverflow.com/q/1814400

http://stackoverflow.com/q/51640610
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90245604
tagged with: python-2.7
score: 0
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/2078978
answer count: 7
has comment: http://stackoverflow.com/comment/90245818
favorite count: 0
has answer: http://stackoverflow.com/a/51640635
accepted answer: http://stackoverflow.com/a/51640635
has answer: http://stackoverflow.com/a/51640648
has answer: http://stackoverflow.com/a/51640646
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51646771
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90245610
has body: Let's say I have a dictionary of all states abbreviations as a key, and the long names as the value: statesDict = {'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas',...} I also have a list of pre-selected state abbreviations: statesAbbrv = ['AL', 'CA', 'CO', 'DE'] Based on the items in the cleanStates list, I want to chose only the values (the long names) for the state abbreviations keys in the stateNames dictionary and place them in a new list; stateNames = [] So, the results of the comparison will look like this: stateNames = ['Alabama', 'California', 'Colorado', 'Deleware'] I was thinking the following, but it's not working. What am I doing wrong here? stateNames = [] for i in statesAbbrv: for k, v in statesDict: if stateDict[k] == stateAbbrv[i]: stateNames.append(stateDict(k)) print stateNames
type: Question
possible better answer: http://stackoverflow.com/a/51640658
has answer: http://stackoverflow.com/a/51640637
has answer: http://stackoverflow.com/a/51640658
has title: Comparing list values to items in a dictionary
has answer: http://stackoverflow.com/a/51640715

http://stackoverflow.com/a/51696642
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51696548
type: Answer
accepted answer of: http://stackoverflow.com/q/51696548
downvote count: 0
score: 1
has body: Do not use curly braces . Python uses curly braces for dictionaries .

http://stackoverflow.com/q/51690027
tagged with: python
has body: When I input a name of dataframe in jupyter-notebook, it prints a pretty table: fail_data It can even recognize the TeX notation. But when I need to print the data in the cycle, the output looks not so good: fail_data_gr = fail_data.groupby('test_name') for k, v in fail_data_gr: print(v) How to make this output looking like the first one?
tagged with: jupyter-notebook
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90341864
downvote count: 0
accepted answer: http://stackoverflow.com/a/51690061
type: Question
has answer: http://stackoverflow.com/a/51690061
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/103911474
answer count: 1
linked to: http://stackoverflow.com/q/51288869
has title: jupyter-notebook: print fine table in a cycle
favorite count: 0

http://stackoverflow.com/comment/90382169
type: AnswerComment
type: Comment
has text: @ Alfred: this was the first obvious step i took. i got the same error
comment on: http://stackoverflow.com/a/51704835
score: 0

http://stackoverflow.com/comment/90319198
has text: Could go in Software Engineering
comment on: http://stackoverflow.com/q/51677887
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51720909
type: Question
score: 31
possible better answer: http://stackoverflow.com/a/60217751
has answer: http://stackoverflow.com/a/60217751
linked to: http://stackoverflow.com/q/28210566
linked to: http://stackoverflow.com/q/26550004
has title: How to get "python -m venv" to directly install latest pip version
tagged with: python-venv
has answer: http://stackoverflow.com/a/51721906
has answer: http://stackoverflow.com/a/76120293
has answer: http://stackoverflow.com/a/56229305
downvote count: 0
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/90424102
favorite count: 0
has comment: http://stackoverflow.com/comment/93763742
has answer: http://stackoverflow.com/a/78474449
answer count: 5
tagged with: python
has body: As part of the compilation step for a new python version, I fetch and run get-pip.py, to have the latest pip installed next to the python executable: $ /opt/python/3.7.0/bin/python --version Python 3.7.0 $ /opt/python/3.7.0/bin/pip --version pip 18.0 from /opt/python/3.7.0/lib/python3.7/site-packages/pip (python 3.7) I have 25 such versions under /opt/python, although I mostly use the five latest versions of each major.minor version that is not EOL. To setup an invironment I used to run virtualenv or my virtualenvutils with the -p /opt/python/X.Y.Z/bin/python option to get a virtual environment with a specific version. With Python 3.7 this gives the imp module deprecation warning: $ virtualenv -p /opt/python/3.7.0/bin/python /tmp/py37virtualenv Running virtualenv with interpreter /opt/python/3.7.0/bin/python Using base prefix '/opt/python/3.7.0' /opt/util/virtualenvutils/lib/python3.6/site-packages/virtualenv.py:1041: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp New python executable in /tmp/py37virtualenv/bin/python Installing setuptools, pip, wheel...done. I have little hope this will be solved in virtualenv, as this has had a PendingDeprecationWarning at least since 2014 (as can be seen from the output in this question) While investigating replacing virtualenv with python -m venv in virtualenvutils, I first created a new venv based virtual environment by hand: $ /opt/python/3.7.0/bin/python -m venv /tmp/py37venv $ /tmp/py37venv/bin/pip --version pip 10.0.1 from /tmp/py37venv/lib/python3.7/site-packages/pip (python 3.7) That has an old pip version! If you use it, you'll get: You are using pip version 10.0.1, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command In the virtual environment created with virtualenv you immediately get the latest version: $ /tmp/py37virtualenv/bin/pip --version pip 18.0 from /tmp/py37virtuale…
accepted answer: http://stackoverflow.com/a/56229305
type: AnsweredQuestion
upvote count: 31
tagged with: pip
has comment: http://stackoverflow.com/comment/90402796

datetime
tags question: http://stackoverflow.com/q/51754413
tags question: http://stackoverflow.com/q/51671209
tags question: http://stackoverflow.com/q/51761992
tags question: http://stackoverflow.com/q/51762231
tags question: http://stackoverflow.com/q/51750077
tags question: http://stackoverflow.com/q/51645542
tags question: http://stackoverflow.com/q/51697672
tags question: http://stackoverflow.com/q/51778005
tags question: http://stackoverflow.com/q/51755969
tags question: http://stackoverflow.com/q/51651243
tags question: http://stackoverflow.com/q/51650634
tags question: http://stackoverflow.com/q/51752918
tags question: http://stackoverflow.com/q/51706767
tags question: http://stackoverflow.com/q/51748650
tags question: http://stackoverflow.com/q/51749218
tags question: http://stackoverflow.com/q/51729728
tags question: http://stackoverflow.com/q/51712766
tags question: http://stackoverflow.com/q/51659683
tags question: http://stackoverflow.com/q/51774318
tags question: http://stackoverflow.com/q/51677784
tags question: http://stackoverflow.com/q/51646101
tags question: http://stackoverflow.com/q/51720999
tags question: http://stackoverflow.com/q/51792216
tags question: http://stackoverflow.com/q/51717268
tags question: http://stackoverflow.com/q/51656174
tags question: http://stackoverflow.com/q/51685524
tags question: http://stackoverflow.com/q/51652952
tags question: http://stackoverflow.com/q/51746802
tags question: http://stackoverflow.com/q/51743354
tags question: http://stackoverflow.com/q/51713659
tags question: http://stackoverflow.com/q/51661280
tags question: http://stackoverflow.com/q/51760021
tag name: datetime
tags question: http://stackoverflow.com/q/51709244
tags question: http://stackoverflow.com/q/51659346
tags question: http://stackoverflow.com/q/51780077
type: Tag
tags question: http://stackoverflow.com/q/51688576
tags question: http://stackoverflow.com/q/51790793
tags question: http://stackoverflow.com/q/51733965
tags question: http://stackoverflow.com/q/51760948
tags question: http://stackoverflow.com/q/51695678
tags question: http://stackoverflow.com/q/51778397
tags question: http://stackoverflow.com/q/51741177
tags question: http://stackoverflow.com/q/51684954
tags question: http://stackoverflow.com/q/51790883
tags question: http://stackoverflow.com/q/51750164
tags question: http://stackoverflow.com/q/51705671
tags question: http://stackoverflow.com/q/51794455

http://stackoverflow.com/comment/90402529
type: AnswerComment
comment on: http://stackoverflow.com/a/51720628
type: Comment
has text: what needs more explaining? the `first` function?
score: 0

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/51725651

http://stackoverflow.com/comment/90288734
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51662544
type: Comment
has text: @zondo oh, that makes sense. Thanks, I'll see if it helps.

http://stackoverflow.com/comment/90274270
score: 0
comment on: http://stackoverflow.com/q/51655360
type: Comment
type: QuestionComment
has text: Did you create and apply migrations?

http://stackoverflow.com/comment/90372408
has text: I edited the post and add the html . Sorry.
comment on: http://stackoverflow.com/q/51704509
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51699120
tagged with: if-statement
score: 1
has body: I have a list list=["John","Tanner",'Mary','Anna',"Oscar",'ID'] and a text file. Inside the text file looks like the following: ID 'blablablabla...' V1 'John' 'blablablabla...' V2 'Anna' 'blablablabla...' V3 'Josh' 'blablablabla...' V4 'Mary' 'blablablabla...' V5 'Steven' 'blablablabla...' I want to search the list inside the text file, and at the end I want to get the results as: RESULT=[1,'NA',4,2,'NA',0]. 1,4 and 2 are the numbers extracted from V1, V4 and V2. Here is the code: start_time = time.time() for item in list: with open('C:/Mary/test.txt', 'r') as file: for line in file: if item in line: var_name=line.split()[0] if var_name=='ID': var_loc.append(0) else: var_loc.append(int(re.split('(\d+)',var_name)[1])) break #else: # var_loc.append('NA') total_time = time.time() - start_time total_time Question: When I pick an item from the list and search inside the text, and then it does not exist in the text, I want it to return 'NA'. But I couldn't figure it out to do it correctly. As I said I want the result looks like this at the end: RESULT=[1,'NA',4,2,'NA',0]. Thanks.
has title: Search a string in a text using python
upvote count: 1
answer count: 1
tagged with: full-text-search
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51699242
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51699242
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/90359700
type: Question

http://stackoverflow.com/comment/90676920
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51801150
type: Comment
has text: @naokifujita glad I could help. And yes, please, if you find other alternatives, don't hesitate to post here yourself, and feel free to ping me with it :)

http://stackoverflow.com/q/51659335
score: 0
has comment: http://stackoverflow.com/comment/90282274
tagged with: pyqt5
has body: I have created the main window which saves a .txt file i.e text entered in label team name Second Image shows another popup-main window which is invoked when evaluate menu bar is clicked
tagged with: user-interface
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90283024
has title: How to open .txt file saved from main window to combo-Box of other-popup window with pyqt5?

http://stackoverflow.com/comment/90406615
has text: @littlecat it is there, the arrow is visible in the notebook
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51723027
score: 0

http://stackoverflow.com/q/51762565
tagged with: package
tagged with: python
has body: I want to skip one line of code of a package that I import, without actually changing the code of the package itself. So is there a way in which I can manipulate the imported package in my own code?
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: import
type: Question
upvote count: 1
downvote count: 0
favorite count: 0
has title: How can I change the code of an imported package
has comment: http://stackoverflow.com/comment/90484377

http://stackoverflow.com/q/51711270
tagged with: serial-port
has body: I am new to Arduino, I just want to rotate servo motor left and right. My arduino code looks like this: #include &lt;Servo.h&gt; int servoPin = 9; Servo myServo; int pos1 = 0; void setup() { Serial.begin(9600); myServo.attach(servoPin); } void loop() { myServo.write(180); delay(1000); myServo.write(0); delay(1000); } And it works perfectly. Now I want to achieve the same thing with python, so my python code looks like this: import serial import time ser = serial.Serial('/dev/ttyACM0', 9600) while True: print("Writing") ser.write("180;".encode()) time.sleep(1) ser.write("0;".encode()) time.sleep(1) ser.close() This code prints "Writing" in log but does absolutely nothing.
has comment: http://stackoverflow.com/comment/90383924
tagged with: python
has answer: http://stackoverflow.com/a/51711358
type: AnsweredQuestion
has title: Python doesn't write to Arduino serial
tagged with: hardware
tagged with: servo
tagged with: arduino
type: Question
upvote count: 1
downvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51711358
favorite count: 0
score: 0

http://stackoverflow.com/comment/90494692
has text: I'm already checkpointing after each train epoch. I just felt that resetting the graph and rebuilding it over and over again would be wasteful, specially since I'd do it twice per epoch: once to eval and then again to train. But if it doesn't exist I can use the workaround.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51767738

http://stackoverflow.com/q/51653532
has answer: http://stackoverflow.com/a/51653733
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90270500
score: 0
has title: Writing multiple Emails to a text file Python IMAP
tagged with: web-applications
accepted answer: http://stackoverflow.com/a/51653733
answer count: 1
has body: I currently have a code that works in a pyramid web-application. By pressing a button, the web app runs a function that reads unread Emails from inbox, deletes first 6 lines (not important info) and writes them onto a file. Later, this data is used as plotting data with matplotlib. My current problem is that the code only reads one unread Email at a time. This means that if I have for example 5 unread emails with data that I want to write to a file, the press of the button only writes the data of one Email, while I want the data from all 5 Emails. Is there any possible way to read all unread Emails at once and write them onto a text file? I've been thinking about adding code that counts the amount of unread emails, and it keeps looping the read/write function until the unread amount reaches 0. There might be a more professional way to do this, so that's why I ask. Thanks in advance! Here is my current code: @view_config(route_name='update-data') def update_view(request): m = imaplib.IMAP4_SSL('imap.gmail.com') m.login('email@gmail.com', 'password') m.list() m.select('inbox') result, data = m.uid('search', None, 'FROM', '"senderEmail"', 'UNSEEN') # Only unseen mail i = len(data[0].split()) #space separate string if i == 0: return Response(' ' + ' Data cannot be updated No new emails ' + ' ') for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = m.uid('fetch', latest_email_uid, '(RFC822)') raw_email = email_data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) for part in email_message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload(decode=True) with open('C:/Email/file.txt', 'a') as myfile: # Opens file.txt and writes the email body myfile.write(str(body)) with open('C:/Email/file.txt', 'r+') as f: # Opens file.txt again in read mode and reads lines lines = f.readlines() with open ('C:/Email/newfile.txt','a') as g: # Writes file.txt contents to newfile.tx…
tagged with: imap
type: AnsweredQuestion

http://stackoverflow.com/comment/90460675
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51750164
has text: @Onyambu That's the challenge that I am facing. The only fixed timeframes everyday is 9-10,10-11,11-13,13-15
score: 0

http://stackoverflow.com/q/51757619
tagged with: django
accepted answer: http://stackoverflow.com/a/51777192
has title: ImportError: No module named applicationform.wsgi
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51777192
upvote count: 1
answer count: 1
tagged with: amazon-web-services
favorite count: 0
tagged with: python-2.7
tagged with: python
tagged with: deployment
downvote count: 0
has body: I'm deploying an app in AWS, when I run gunicorn in a virtual env to test if it works correctly I'm getting the error message below: (venv) ubuntu@ip-172-31-14-232:~/applicationform/newProject$ gunicorn --bind 0.0.0.0:8000 applicationform.wsgi:application [2018-08-09 00:52:20 +0000] [22973] [INFO] Starting gunicorn 19.9.0 [2018-08-09 00:52:20 +0000] [22973] [INFO] Listening at: http://0.0.0.0:8000 (22973) [2018-08-09 00:52:20 +0000] [22973] [INFO] Using worker: sync [2018-08-09 00:52:20 +0000] [22977] [INFO] Booting worker with pid: 22977 [2018-08-09 00:52:20 +0000] [22977] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/applicationform/venv/local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ImportError: No module named applicationform.wsgi [2018-08-09 00:52:20 +0000] [22977] [INFO] Worker exiting (pid: 22977) [2018-08-09 00:52:20 +0000] [22973] [INFO] Shutting down: Master [2018-08-09 00:52:20 +0000] [22973] [INFO] Reason: Worker failed to boot. Testing the app on AWS I also get the internal server error. The…

http://stackoverflow.com/comment/90273691
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51652793
has text: https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.matrix.html, numpy actually has matrices, there is a difference
score: 0

http://stackoverflow.com/comment/90308302
type: QuestionComment
comment on: http://stackoverflow.com/q/51671304
type: Comment
score: 0
has text: Hi Ai Da, yes I am sure the attrib3 is not in the source file when first run the script, I am sure and I put the 'if' just to guarantee a second append could happen after the first one when NOTFOUND will be update from 0 to 1

http://stackoverflow.com/comment/127244323
type: Comment
comment on: http://stackoverflow.com/a/66289898
has text: One thing to add: There's no solution for 0 even though `0 * factorial(-1)` should return 0 the factorial is still called, providing no solution due to infinite recursion.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/137888721
type: Comment
comment on: http://stackoverflow.com/a/76095493
score: 0
type: AnswerComment
has text: Thanks. This was really the issue. Anaconda was not installed in the first place. So, I had to install it actually in the specific environment that I was using, and then the rest ...

http://stackoverflow.com/q/51765515
type: Question
has answer: http://stackoverflow.com/a/51765611
tagged with: ordereddictionary
has title: Parsing OrderedDict
score: 0
answer count: 1
tagged with: parsing
has body: I've been trying to parse this OrderedDict to get the 'Id' value from the following return of a SQL. OrderedDict([ ('totalSize', 1), ('done', True), ('records', [OrderedDict([ ('attributes', OrderedDict([ ('type', 'Device__c'), ('url', '/services/data/v38.0/sobjects/Device__c/a001r00000qCgp1AAC')])), ('Id', 'a001r00000qCgp1AAC')])])]) The following is the print(query_result['records']). How can I go further? OrderedDict([ ('attributes', OrderedDict([ ('type', 'Device__c'), ('url', '/services/data/v38.0/sobjects/Device__c/a001r00000qCgp1AAC')])), ('Id', 'a001r00000qCgp1AAC')])] Grateful for your time.
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/51797523
has answer: http://stackoverflow.com/a/51798035
has comment: http://stackoverflow.com/comment/90552124
tagged with: python-3.x
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51798035
tagged with: dataframe
score: -1
has title: filter on one column and rank on another without grouping in dataframe
type: Question
has comment: http://stackoverflow.com/comment/90552638
has body: I have a data frame having 4 columns student_name, total_marks, is_shortlisted, rank I wanted to rank rows on the basis of the total_marks column where the is_shortlisted = "Y". sample input data : name total_marks is_shortlisted Aman 67 Y Nitin 89 Y Ankur 76 Y Mohit 56 N Ashish 64 Y sample output data : name total_marks is_shortlisted rank Aman 67 Y 3 Nitin 89 Y 1 Ankur 76 Y 2 Mohit 56 N nan Ashish 64 Y 4
answer count: 1
favorite count: 0
tagged with: pandas

http://stackoverflow.com/q/51690019
tagged with: md5
downvote count: 1
accepted answer: http://stackoverflow.com/a/51690046
type: Question
has title: Python 3.6 equivalent of md5 digest() method?
score: -1
tagged with: python-2.7
upvote count: 0
answer count: 1
tagged with: cryptographic-hash-function
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90341883
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51690046
has body: I'am having trouble in achieving the same results of md5 digest() method from Python 2.7 in Python 3.6. Python 2.7: import md5 encryption_base = 'cS35jJYp15kjQf01FVqA7ubRaNOXKPmYGRbLUiimX0g3frQhzOZBmTSni4IEjHLWYMMioGaliIz5z8u2:abcdefghkmnopqrstuvwxyz:4' digest = md5.new (encryption_base).digest() print(digest) #T┼Çƒ×ÞRK(M&lt;¶┤# ² Python 3.6: from hashlib import md5 encryption_base = 'cS35jJYp15kjQf01FVqA7ubRaNOXKPmYGRbLUiimX0g3frQhzOZBmTSni4IEjHLWYMMioGaliIz5z8u2:abcdefghkmnopqrstuvwxyz:4' digest = md5(encryption_base.encode()).digest() print(digest) #b'T\xc5\x80\x9f\x9e\xe8RK(M&lt;\xf4\xb4#\t\xfd' How can I get the same string as in the Python 2.7 result? .hexdigest is not the case for this also.

http://stackoverflow.com/comment/90472700
type: Comment
has text: Now it gives me a 500 Internal Server Error
type: AnswerComment
comment on: http://stackoverflow.com/a/51756023
score: 0

http://stackoverflow.com/q/51747425
linked to: http://stackoverflow.com/q/14088541
answer count: 1
downvote count: 0
has body: I have a text document with a single URL on every line. I want each URL to be opened in a new tab. Heres what I have so far: tabs = 0 f = open('links.txt', 'r', encoding='utf-8') for line in f: url = line driver.execute_script("window.open(url, 'new_window')") sleep(7) # time to let tge page load tabs = tabs + 1 # to keep track of how many tabs I have This gives me the error: Traceback (most recent call last): File "scraper.py", line 100, in driver.execute_script("window.open(url, 'new_window')") File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 635, in execute_script 'args': converted_args})['value'] File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: url is not defined I have tried everything, but can't get it to work. Any Ideas?
favorite count: 0
has answer: http://stackoverflow.com/a/51747654
tagged with: python
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51747654
upvote count: 2
tagged with: selenium
tagged with: google-chrome
type: Question
has title: Python + Selenium WebDriver: open URL in new tab
has comment: http://stackoverflow.com/comment/90454813

http://stackoverflow.com/q/51755268
score: 9
type: Question
has comment: http://stackoverflow.com/comment/90470503
has comment: http://stackoverflow.com/comment/90470646
possible better answer: http://stackoverflow.com/a/51905356
has comment: http://stackoverflow.com/comment/90470453
has comment: http://stackoverflow.com/comment/90470631
has comment: http://stackoverflow.com/comment/90470758
has comment: http://stackoverflow.com/comment/90852173
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/44367672
has comment: http://stackoverflow.com/comment/90470719
favorite count: 0
upvote count: 9
has title: Pandas merge on `datetime` or `datetime` in `datetimeIndex`
linked to: http://stackoverflow.com/q/49481064
has body: Currently I have two data frames representing excel spreadsheets. I wish to join the data where the dates are equal. This is a one to many join as one spread sheet has a date then I need to add data which has multiple rows with the same date an example: A B date data date data 0 2015-0-1 ... 0 2015-0-1 to 2015-0-2 ... 1 2015-0-2 ... 1 2015-0-1 to 2015-0-2 ... In this case both rows from A would recieve rows 0 and 1 from B because they are in that range. I tried using df3 = pandas.merge(df2, df1, how='right', validate='1:m', left_on='Travel Date/Range', right_on='End') to accomplish this but received this error. Traceback (most recent call last): File "&lt;pyshell#61&gt;", line 1, in &lt;module&gt; df3 = pandas.merge(df2, df1, how='right', validate='1:m', left_on='Travel Date/Range', right_on='End') File "C:\Users\M199449\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\reshape\merge.py", line 61, in merge validate=validate) File "C:\Users\M199449\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\reshape\merge.py", line 555, in __init__ self._maybe_coerce_merge_keys() File "C:\Users\M199449\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\reshape\merge.py", line 990, in _maybe_coerce_merge_keys raise ValueError(msg) ValueError: You are trying to merge on object and datetime64[ns] columns. If you wish to proceed you should use pd.concat I can add more information as needed of course
has answer: http://stackoverflow.com/a/51905356
tagged with: python
has comment: http://stackoverflow.com/comment/90470672
has comment: http://stackoverflow.com/comment/90470548
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51755666
accepted answer: http://stackoverflow.com/a/51755666
downvote count: 0
has comment: http://stackoverflow.com/comment/90688644
linked to: http://stackoverflow.com/q/46525786

http://stackoverflow.com/q/51690173
score: 1
has answer: http://stackoverflow.com/a/51690691
type: Question
has comment: http://stackoverflow.com/comment/90343093
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51690691
has body: So I'm using Python and Tkinter, I'm making a to-do list. Except, there is a very slow wait time when I press ENTER to running the function. The Code: from tkinter import * import pickle ''' Final Version ''' def delete_all(): first_listbox.delete(0, END) while len(tasks) &gt; 0: del tasks[0] def add(event): if entry.get().strip() == '': return None first_listbox.insert(END, entry.get()) tasks.append(entry.get()) entry.delete(0, END) def delete(): selection = first_listbox.curselection() first_listbox.delete(selection) tasks.remove(entry.get()) root = Tk() frame = Frame(root, bg='LightBlue') frame.grid(row=0, column=0, sticky=W, rowspan=10, columnspan=10) frame.bind('&lt;Enter&gt;', add) root.geometry('400x400') root.title('Bad to-do list') root.configure(bg='LightBlue') first_listbox = Listbox(frame, width=50, selectmode = BROWSE) first_listbox.grid(row=0, column=0, rowspan = 5, sticky=W) entry = Entry(frame, width=50) entry.grid(row=5, column=0, sticky=W, columnspan=2) #submit_button = Button(frame, text='Insert', command=add)&lt;-- Old Code Before Binding Enter #submit_button.grid(row=5, column=1, sticky=W) &lt;-- Old Code Before Binding Enter delete_button = Button(frame, text='Done', command=delete) delete_button.grid(row=0, column=1, sticky=W) delete_all_button = Button(frame, text='Delete All', command=delete_all) delete_all_button.grid(row=1, column=1, sticky=W, columnspan=2) pickle_out = open('to-do-example.pickle', 'rb') tasks = pickle.load(pickle_out) pickle_out.close() for item in tasks: first_listbox.insert(0, item) root.mainloop() pickle_out = open('to-do-example.pickle', 'wb') pickle.dump(tasks, pickle_out) pickle_out.close() When I run it, it works fine But, the wait time for adding new tasks after pressing ENTER is terribly slow. But, strangely, if I use the left mouse click for the binding part instead of the enter key, it works fine responding instantly? Could someone please explain.
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90343117
has title: Very Slow Response To Enter Key Binding in Python Tkinter
upvote count: 1
type: AnsweredQuestion
tagged with: performance

http://stackoverflow.com/comment/90246362
has text: Again, you do not take into account that depth and temp are not independent variables.
comment on: http://stackoverflow.com/a/51640397
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90263235
comment on: http://stackoverflow.com/a/51649066
score: 3
has text: I don't think `sudo` will bring anything since it looks like the OP is alrrady root in the container.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90438882
type: QuestionComment
has text: The message "Host key verification failed." indicates a host key verification issue. You might have to clean the old key(s) from `~/.ssh/known_hosts` on the runner.
comment on: http://stackoverflow.com/q/51739195
score: 0
type: Comment

http://stackoverflow.com/q/51648849
has comment: http://stackoverflow.com/comment/90265511
tagged with: mysql
has answer: http://stackoverflow.com/a/51651873
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/90266650
accepted answer: http://stackoverflow.com/a/51651873
answer count: 1
has title: How to truncate and insert on the same transaction using sqlalchemy?
tagged with: sql
has comment: http://stackoverflow.com/comment/90264329
tagged with: python
has body: I have a production_table and stage_table. I have a python script that runs for few hours and generate data in the stage_table. I want at the end of the script to COPY data from the stage_table to the production_table. Basically this is what I want: 1. TRUNCATE production_table 2. COPY production_table from stage_table This is my code: from sqlalchemy import create_engine from sqlalchemy.sql import text as sa_text engine = create_engine("mysql+pymysql:// AMAZON AWS") engine.execute(sa_text('''TRUNCATE TABLE {1}; COPY TABLE {1} from {0}'''.format(stage_table, production_table)).execution_options(autocommit=True)) This should generate : TRUNCATE TABLE production_table; COPY TABLE production_table from stage_table However this doesn't work. sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, u"You have an error in your SQL syntax; How can I make it work? and how can I make sure that the TRUNCATE and COPY are together. I don't want TRUNCATE to happen if COPY aborts.
linked to: http://stackoverflow.com/q/20518677
score: 0
has comment: http://stackoverflow.com/comment/90264565
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/90326730
has text: I have figured out that server side handle the w and h in post body. So I send `w` and `h` in post data, and solved. Thank you for your information.
type: Comment
comment on: http://stackoverflow.com/a/51670336
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90380009
has text: @EmotionIce I wrote the command the way I did so that you pass the old and new name to the command directly. See the example usage in my answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/51707897
score: 0
type: Comment

http://stackoverflow.com/comment/90279572
comment on: http://stackoverflow.com/q/51656818
type: Comment
type: QuestionComment
has text: @MarcGlisse that is completely accurate. I am trying to set it up
score: 0

http://stackoverflow.com/comment/90450457
comment on: http://stackoverflow.com/q/51743057
score: 0
type: Comment
type: QuestionComment
has text: Yes I was able to do that

http://stackoverflow.com/comment/90391679
score: 0
type: Comment
type: QuestionComment
has text: @abarnert Running your first comment still gives me the same pattern of retry errors and sslerror as all pip commands have been :( I also saw that article as well and tried the easy_install method (described in my post)
comment on: http://stackoverflow.com/q/51714885

http://stackoverflow.com/a/51667108
has comment: http://stackoverflow.com/comment/90330496
score: 0
answers question: http://stackoverflow.com/q/51665352
type: Answer
has body: This code should not even work, these lines : logger = logging.getLogger() mode = logger.error logger.setLevel(mode) Should be like this: logger = logging.getLogger() mode = logging.ERROR logger.setLevel(mode) After I changed them it worked. One more mention is that be sure that these lines: ts = str(datetime.datetime.now()) log = "DIF_logfile_"+ts Create a valid filename, they did not on my system

scrapyd
tags question: http://stackoverflow.com/q/51662819
tag name: scrapyd
type: Tag

http://stackoverflow.com/comment/90487093
has text: Almost - this returns [3.4,2.1,2], which are the minimum values for each list. I need the minimum value per index of the lists.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51764086

http://stackoverflow.com/q/51710772
tagged with: joblib
favorite count: 0
has body: I would like to better understand how joblib handles global objects. Consider following simple example. from joblib import Parallel, delayed class Engine: def f(self, x): return x+2 engine = Engine() def run_engine(x): return engine.f(x) def main(): res = Parallel(n_jobs=5)(delayed(run_engine)(x) for x in range(0,100)) print(res) if __name__ == '__main__': main() What is going to happen to engine object? Is it going to be copied or somehow shared by all spawned processes? If copied, are there any serialization requirements? And how many times will it be copied, n_jobs times or once per each call to run_engine? Are all objects in the scope copied or does joblib somehow magically infer which are necessary?
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
has title: Global objects with joblib
type: Question
downvote count: 0

http://stackoverflow.com/comment/106981274
type: Comment
score: 0
has text: @GeorgeUdosen I agree, it should be `value` and not `"value"`. I forgot to update that when I posted this. Updating now. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/51775922

http://stackoverflow.com/a/51758419
has comment: http://stackoverflow.com/comment/90476842
has comment: http://stackoverflow.com/comment/90476631
has body: I assume you have two installations of python - 3.6.4 and 3.6.6. To install a new module to Python 3.6.4, you need to first activate that environment. You can do that by navigating to the installation path. And running the activate script by navigating to the scripts folder: [Env-path]\Scripts\activate Once you have activated the environment. You can install pandas there.
has comment: http://stackoverflow.com/comment/90476612
score: 0
has comment: http://stackoverflow.com/comment/90476408
has comment: http://stackoverflow.com/comment/90476441
has comment: http://stackoverflow.com/comment/90476685
has comment: http://stackoverflow.com/comment/90476885
answers question: http://stackoverflow.com/q/51758197
has comment: http://stackoverflow.com/comment/90476790
type: Answer
has comment: http://stackoverflow.com/comment/90476684
has comment: http://stackoverflow.com/comment/90476442

http://stackoverflow.com/a/51767336
score: 0
answers question: http://stackoverflow.com/q/51767194
type: Answer
has body: Did you checked the good directory on the good server ? Creating a $PWD/some_dir in a DinD context, The result should be in a some_dir created in docker user home dir in the server running Gitlab CI container.

http://stackoverflow.com/q/51742092
upvote count: 0
has comment: http://stackoverflow.com/comment/90444104
has title: Floating point numbers in python
score: -1
linked to: http://stackoverflow.com/q/588004
tagged with: python-3.7
answer count: 2
duplicate of: http://stackoverflow.com/q/588004
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: floating-point
downvote count: 1
type: Question
has body: How to get correct number after calculation? For instance, I want 2.2 - 1 equal to 1.2 and not 1.2000000000002. Wanna get exactly correct answer without rounding the number itself and without just simply changing the way of printing the number via print('%1.1f' % number).
has answer: http://stackoverflow.com/a/51742189
has answer: http://stackoverflow.com/a/51742145

http://stackoverflow.com/q/51765191
has title: pytest fixture with scope session running for every test
tagged with: pytest
upvote count: 3
accepted answer: http://stackoverflow.com/a/51765497
downvote count: 0
type: AnsweredQuestion
score: 3
favorite count: 0
has answer: http://stackoverflow.com/a/51765497
type: Question
has body: Correct me if I'm wrong, but if a fixture is defined with scope="session", shouldn't it be run only once per the whole pytest run? For example: import pytest @pytest.fixture def foo(scope="session"): print('foooooo') def test_foo(foo): assert False def test_bar(foo): assert False I have some tests that rely on data retrieved from some APIs, and instead of querying the API in each test, I rather have a fixture that gets all the data at once, and then each test uses the data it needs. However, I was noticing that for every test, a request was made to the API.
tagged with: python
answer count: 1

http://stackoverflow.com/comment/103187432
score: 0
type: Comment
has text: @zeellos- I'm using R for all my timeseries modelling, and have been suggested to look into RNN via Keras/Tensorflow by some peers. I was wondering what has your experience using Python for Keras/TF been like vs. Prophet? I've found no comparisons between the two online, and am looking for more information on how the two compare.
comment on: http://stackoverflow.com/a/51643481
type: AnswerComment

http://stackoverflow.com/a/51712879
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51712489
has body: You can add them all together, i assumed all filepath have the same syntax 1/1_20180625_234436.jpg df['filepath'] = df['old_cameraid'].astype(str) + '/' + df['filepath'].astype(str).map(lambda x: x.split('/')[-1])
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51712489

http://stackoverflow.com/q/51648159
linked to: http://stackoverflow.com/q/45122154
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51648215
favorite count: 0
has title: How to split several column's data in pandas?
has answer: http://stackoverflow.com/a/51648874
possible better answer: http://stackoverflow.com/a/51648215
tagged with: python
has answer: http://stackoverflow.com/a/51648413
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: I have a dataframe which looks like this: df = pd.DataFrame({'hard': [['525', '21']], 'soft': [['1525', '221']], 'set': [['5245', '271']], 'purch': [['925', '201']], \ 'mont': [['555', '621']], 'gest': [['536', '251']], 'memo': [['825', '241']], 'raw': [['532', '210']]}) df Out: gest hard memo mont purch raw set soft 0 [536, 251] [525, 21] [825, 241] [555, 621] [925, 201] [532, 210] [5245, 271] [1525, 221] I should split all of the columns like this: df1 = pd.DataFrame() df1['gest_pos'] = df.gest.str[0].astype(int) df1['gest_size'] = df.gest.str[1].astype(int) df1['hard_pos'] = df.hard.str[0].astype(int) df1['hard_size'] = df.hard.str[1].astype(int) df1 gest_pos gest_size hard_pos hard_size 0 536 251 525 21 I have more than 70 columns and my method takes lot of place and time. Is there an easier way to do this job? Thanks!
accepted answer: http://stackoverflow.com/a/51648413
tagged with: dataframe

http://stackoverflow.com/q/51770544
answer count: 0
score: 0
has body: I have a mysterious test that's taking much longer to run than it should. I have tried to debug it for a while now but I've run out of creativity. The test does create a lot of database records, but still, it's only a few hundreds, I could understand it taking one minute, but definitely not 20. Here's the relevant code that chokes for some reason: from rest_framework.test import APITestCase class MyTest(APITestCase, ...): ... def setUp(self): self.setup_questions() def setup_questions(self): question_levels = [ QuestionLevelFactory.create(title="Major", ...), QuestionLevelFactory.create(title="Minor", ...), QuestionLevelFactory.create(title="Recommended", ...) ] questionnaire1 = QuestionnaireFactory.create(...) questionnaire2 = QuestionnaireFactory.create(...) possible_answer_set = PossibleAnswerSetFactory.create(...) for question_level in question_levels: if question_level.title == "Recommended": questionnaire = questionnaire2 counter = 25 else: questionnaire = questionnaire1 counter = 100 for i in range(counter): if i &lt;= 97: question = QuestionFactory.create( level_object=question_level, possible_answer_set=possible_answer_set, questionnaire=questionnaire ) else: question = QuestionFactory.create( level_object=question_level, possible_answer_set=possible_answer_set, questionnaire=questionnaire, code="{}-{}".format(question_level.title, i) ) if i &lt; 95: AnswerFactory.create( question=question, assessment=self.assessment, value="yes" ) elif i &lt;= 97: AnswerFactory.create( question=question, assessment=self.assessment, value="not_applicable" ) else: AnswerFactory.create( question=question, assessment=self.assessment, value="no", justification="{} {} justification".format(question_level.title, i) ) Note that, when the question_levels are listed in this order, the test only starts chocking when processing the "Minor" level. The first one ("Major") one is processed much faster. When I switch Minor and Major, things are slow from the beginning. This is a legacy pr…
has comment: http://stackoverflow.com/comment/90532511
type: Question
tagged with: testing
tagged with: docker
has comment: http://stackoverflow.com/comment/90530543
tagged with: factory-boy
has comment: http://stackoverflow.com/comment/90499856
has title: Django test taking 20min+ (sometimes)
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/123422883
has comment: http://stackoverflow.com/comment/90532711

http://stackoverflow.com/comment/90313276
has text: I think what I'm asking is how to call the function with the writing to file part?
type: Comment
comment on: http://stackoverflow.com/a/51656381
score: 0
type: AnswerComment

http://stackoverflow.com/a/51752688
score: 7
downvote count: 0
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51752600
type: Answer
answers question: http://stackoverflow.com/q/51752600
has body: for list of lists p, we can transpose and unpack using p1, p2 = zip(*p) then find min and max as max(p1) min(p1) max(p2) min(p2)

http://stackoverflow.com/a/51714538
answers question: http://stackoverflow.com/q/51714489
has body: You can catch multiple types of errors in one line. From Python Documentation: An except clause may name multiple exceptions as a parenthesized tuple It would be more pythonic to catch your errors like so: except (IndexError, KeyError)...
accepted answer of: http://stackoverflow.com/q/51714489
upvote count: 4
downvote count: 0
score: 4
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51768292
accepted answer of: http://stackoverflow.com/q/51763924
type: Answer
answers question: http://stackoverflow.com/q/51763924
score: 2
downvote count: 0
upvote count: 2
has body: To begin troubleshooting, it may be effective to use the tee=True solver option in order to stream solver output to console. That is: results = opt.solve(model, tee=True) Past that, we get into modeling theory, and I would refer you to a modeling reference such as the HP Williams book.
type: AcceptedAnswer

http://stackoverflow.com/q/51699167
has body: How do I edit an existing Wagtail page programmatically? There's a few explanations of how to add new pages, but I still can't seem to figure out how to edit a single field on an existing page. I'd like to use the 'Title' field as reference. This seems to be completely undocumented officially, but there is a nice written guide to adding pages programmatically here.
upvote count: 2
accepted answer: http://stackoverflow.com/a/51715689
tagged with: django
score: 2
type: AnsweredQuestion
tagged with: content-management-system
type: Question
tagged with: wagtail
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90359838
favorite count: 0
has title: Wagtail - Programmatically Edit Existing Page
tagged with: python
has answer: http://stackoverflow.com/a/51715689

http://stackoverflow.com/comment/90434842
score: 0
has text: The link to your image is broken, can you fix it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51729465

http://stackoverflow.com/comment/90337512
comment on: http://stackoverflow.com/q/51687684
has text: But really you should explain why you think you need this.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51783313
tagged with: sqlalchemy
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51789675
tagged with: python
has title: How do I get sqlalchemy.create_engine with mysqlconnector to connect using mysql_native_password?
has body: I'm working with pandas and sqlalchemy, and would like to load a DataFrame into a MySQL database. I'm currently using this code snippet: db_connection = sqlalchemy.create_engine('mysql+mysqlconnector://user:pwd@hostname/db_name') some_data_ref.to_sql(con=db_connection, name='db_table_name', if_exists='replace') sqlalchemy, pandas have been imported prior to this. My MySQL backend is 8.x, which I know uses caching_sha2_password. If I were to connect to the database using mysql.connector.connect and I want to use the mysql_native_password method, I know that I should specify auth_plugin = mysql_native_password like so: mysql.connector.connect(user=user, password=pw, host=host, database=db, auth_plugin='mysql_native_password') My question: Is there a way to force mysql_native_password authentication with sqlalchemy.create_engine('mysql+mysqlconnector://...)? Any advice on this would be much appreciated...
upvote count: 6
tagged with: mysql-connector-python
type: AnsweredQuestion
score: 6
tagged with: mysql
accepted answer: http://stackoverflow.com/a/51789675
type: Question

http://stackoverflow.com/a/51659948
type: Answer
has body: The direct, simple, readable answer (pythonic?): a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for n in range(0, len(a), 8): a[n+4:n+8] = a[n+7:n+3:-1] print(a)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51659879
downvote count: 0

http://stackoverflow.com/q/51736015
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90439775
has comment: http://stackoverflow.com/comment/90440836
accepted answer: http://stackoverflow.com/a/51737367
tagged with: django
upvote count: 1
type: Question
score: 1
downvote count: 0
answer count: 1
has title: Increment Visits Counter from Django REST
has answer: http://stackoverflow.com/a/51737367
favorite count: 0
tagged with: rest
has body: for some reason i can't figure out why my counter is only updating at first url fetch or when server is restarted (or when i just save my code and local server is updating) but not anymore after it. Made a simple counter class models.py class HitCount(models.Model): visits = models.IntegerField(default=0) And a simple update when view is supposed to be fetch from react views.py class HitCountViewSet(viewsets.ModelViewSet): HitCount.objects.filter(pk=1).update(visits=F('visits') + 1) queryset = HitCount.objects.all() serializer_class = HitCountSerializer Also, in case of, there's my serializer.py class HitCountSerializer(serializers.ModelSerializer): class Meta: model = HitCount fields = ('visits',) My goal is simply to update the counter when I fetch the url then get the count data for show purposes.

http://stackoverflow.com/q/51657764
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51658027
score: 0
type: Question
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/51723996
has answer: http://stackoverflow.com/a/51657945
accepted answer: http://stackoverflow.com/a/51658027
tagged with: for-loop
answer count: 3
possible better answer: http://stackoverflow.com/a/51657945
has body: Lets say I have a dictionary of state abbreviations and the corresponding names: stateDict = {'AL': 'Alabama', 'AK': 'Alaska', 'AZ': 'Arizona', ...} I also have a list of dictionaries that has the state abbreviations, as well as other data, including county and county fips codes: stateList = [{'county': 'Los Angeles County', 'state': 'CA', 'fips': '06037', 'cid': '060655'}, {'county': 'Jasper County', 'state': 'AL', 'fips': '18073', 'cid': '180100'}, {'county': 'Lafayette Parish', 'state': 'LA', 'fips': '22055', 'cid': '220102'}, {'county': 'Carver County', 'state': 'AL', 'fips': '27019', 'cid': '275233'}, {'county': 'Bertie County', 'state': 'NC', 'fips': '37015', 'cid': '227344'}...] As you can see above, we have more than one entry for 'state': 'AL'. What I want to do here is using dictionary 1: stateDict, choose all the entries in list stateList for 'AL' and then place the state name in a new list with all of the county fips codes that are shown in stateList for 'AL' (or any other state that is in stateDict). So the outcome would look like this: stateInfo = ['Alabama': {'01003', '01004', '01017'}, 'Alaska': {'02030', '02113', '02014'}...] Or perhaps like this (I'm not sure what would be appropriate exactly): stateInfo = {'Alabama': ['01003', '01004', '01017'], 'Alaska': ['02030', '02113', '02014']...} Using previously mentioned methods, I would use something like this, but because I am pulling the data for stateInfo, I am somewhat confused. Suggestions? stateInfo = {} for i in stateList: fips = [] for j in stateDict: for k, v in stateDict: if 'state' in stateList[i] == k for stateDict[j]: stateInfo[stateDict[v]].append(stateList('fips'[v])
has title: Merging data from multiple dictionaries and lists
tagged with: python
tagged with: dictionary

separator
tags question: http://stackoverflow.com/q/51665498
type: Tag
tag name: separator

python-3.6
tags question: http://stackoverflow.com/q/51687392
tags question: http://stackoverflow.com/q/51639826
tags question: http://stackoverflow.com/q/51729665
tags question: http://stackoverflow.com/q/51797311
tags question: http://stackoverflow.com/q/51736864
tags question: http://stackoverflow.com/q/51657219
tags question: http://stackoverflow.com/q/51758428
tags question: http://stackoverflow.com/q/51732834
tags question: http://stackoverflow.com/q/51659720
tags question: http://stackoverflow.com/q/51710172
type: Tag
tags question: http://stackoverflow.com/q/51752990
tags question: http://stackoverflow.com/q/51682390
tags question: http://stackoverflow.com/q/51797475
tags question: http://stackoverflow.com/q/51767395
tags question: http://stackoverflow.com/q/51726399
tags question: http://stackoverflow.com/q/51690997
tags question: http://stackoverflow.com/q/51660453
tags question: http://stackoverflow.com/q/51676436
tags question: http://stackoverflow.com/q/51797312
tags question: http://stackoverflow.com/q/51663957
tags question: http://stackoverflow.com/q/51726839
tags question: http://stackoverflow.com/q/51762227
tags question: http://stackoverflow.com/q/51797718
tags question: http://stackoverflow.com/q/51697398
tags question: http://stackoverflow.com/q/51706767
tags question: http://stackoverflow.com/q/51770056
tag name: python-3.6
tags question: http://stackoverflow.com/q/51769239
tags question: http://stackoverflow.com/q/51666835
tags question: http://stackoverflow.com/q/51656536
tags question: http://stackoverflow.com/q/51692745
tags question: http://stackoverflow.com/q/51702122
tags question: http://stackoverflow.com/q/51676983
tags question: http://stackoverflow.com/q/51742830
tags question: http://stackoverflow.com/q/51777082
tags question: http://stackoverflow.com/q/51775820

http://stackoverflow.com/a/67396796
type: Answer
upvote count: 1
score: 1
has body: When I tried the accepted answer, it killed some visible firefox windows as well. Using htop, I found that all firefox windows running in headless mode using python selenium corresponded to the command /usr/lib/firefox/firefox --marionette --headless -foreground -no-remote -profile <tmp file>. So, using this answer on Unix stack exchange, I came up with: for pid in $(ps -ef | grep "firefox --marionette -headless" | awk '{print $2}'); do kill -9 $pid; done`
answers question: http://stackoverflow.com/q/51730930
downvote count: 0

celery
tags question: http://stackoverflow.com/q/51703391
tag name: celery
tags question: http://stackoverflow.com/q/51744642
tags question: http://stackoverflow.com/q/51665098
tags question: http://stackoverflow.com/q/51656516
tags question: http://stackoverflow.com/q/51750564
tags question: http://stackoverflow.com/q/51657950
tags question: http://stackoverflow.com/q/51785636
type: Tag
tags question: http://stackoverflow.com/q/51734952
tags question: http://stackoverflow.com/q/51780526
tags question: http://stackoverflow.com/q/51789799
tags question: http://stackoverflow.com/q/51712014

http://stackoverflow.com/q/51752903
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79539604
tagged with: python
has comment: http://stackoverflow.com/comment/90465890
has comment: http://stackoverflow.com/comment/90466205
upvote count: 1
downvote count: 1
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/90466168
has comment: http://stackoverflow.com/comment/90466019
has comment: http://stackoverflow.com/comment/90466232
has body: I coded a Discord self bot that sends a picture that acts like a global emote without nitro. Example: me: !ok me(bot): ok.png But when I edit my code and add more pictures and stuff and I load it again (By doing "mybot.py" in cmd) it takes around 5 minutes to finally print "Self bot working." in the cmd window... what is the problem? I don't think it's a problem with my code because it's working overall. I'm using python 3.6 and windows. import discord import asyncio client = discord.Client() @client.event async def on_ready(): print("nonitro Loaded.\n") @client.event async def on_message(message): if message.author == client.user: if(message.content.startswith("!ok")): emo = "./img/ok.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(message.channel, emo) if message.author == client.user: if(message.content.startswith("!xd")): emo = "./img/xd.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(message.channel, emo) if message.author == client.user: if(message.content.startswith("!coffee")): emo = "./img/coffee.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(message.channel, emo) if message.author == client.user: if(message.content.startswith("!thonk")): emo = "./img/thonk.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(message.channel, emo) if message.author == client.user: if(message.content.startswith("!like")): emo = "./img/like.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(message.channel, emo) if message.author == client.user: if(message.content.startswith("!kek")): emo = "./img/kek.png" async for msg in client.logs_from(message.channel,limit=1): await client.delete_message(msg) await client.send_file(mess…
score: 0
answer count: 2
has title: DISCORD: My Discord self bot takes too much time to load
has answer: http://stackoverflow.com/a/51764694
tagged with: discord
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51689885
upvote count: 3
answers question: http://stackoverflow.com/q/51689856
downvote count: 0
has body: No, you can't extend builtin classes like float or int. &gt;&gt;&gt; int.double = lambda self: self * 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't set attributes of built-in/extension type 'int' (You can modify non-builtin classes though, but you really shouldn't, as code doing that is hard to reason about.) Your particular example is better served by an unit library like pint -- using libraries like that prevents you from making $125 million mistakes doing math between metric and imperial units, too.
type: Answer
score: 3

http://stackoverflow.com/comment/90508870
comment on: http://stackoverflow.com/q/51750396
type: Comment
type: QuestionComment
score: 1
has text: This question has many duplicates on StackOverflow. See: https://stackoverflow.com/questions/20994716/what-is-the-difference-between-pip-and-conda?rq=1 https://stackoverflow.com/questions/49158543/best-practices-with-pip-and-conda-for-consistency/49162977#49162977 https://stackoverflow.com/questions/45471477/python-package-can-be-installed-by-pip-but-not-conda/45486051?s=2|87.5032#45486051 https://stackoverflow.com/questions/45917541/what-is-the-effect-of-using-pip-to-install-python-packages-on-anaconda/45919845?s=6|64.9264#45919845

http://stackoverflow.com/comment/90539361
comment on: http://stackoverflow.com/a/51789157
has text: Thank you! `map` was what I was missing in my repertoire.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90246302
comment on: http://stackoverflow.com/q/51640798
has text: Include snippets of your code with some comments explaining what you want to happen where please.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51801594
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51787922
score: 1
has body: mock.patch("MockSandbox.ConnectHandler") returns you a mock for the class, so mock_ssh.disconnect is a class method. You want to check the instance method instead. Access the mock instance via mock_ssh.return_value: mock_ssh.return_value.disconnect.assert_called()
downvote count: 0
answers question: http://stackoverflow.com/q/51787922
type: AcceptedAnswer

http://stackoverflow.com/comment/110680123
score: 0
type: AnswerComment
has text: Be careful with the env's
type: Comment
comment on: http://stackoverflow.com/a/62584783

http://stackoverflow.com/comment/90408847
comment on: http://stackoverflow.com/q/51724039
score: 1
type: Comment
type: QuestionComment
has text: No, but it will tell you that you already have one installed (if the previous one is installed by conda).

http://stackoverflow.com/a/51660851
answers question: http://stackoverflow.com/q/51660091
has body: Use subprocess.check_output. It returns the output of the command.
score: 0
type: Answer

http://stackoverflow.com/a/51775142
has comment: http://stackoverflow.com/comment/90536308
has comment: http://stackoverflow.com/comment/90532235
has comment: http://stackoverflow.com/comment/90536047
has body: I've always assigned the command by configuring the scrollbars, not the canvas. Try replacing your lines: canvas.configure... With: yscrollbar.config(command=canvas.yview)
answers question: http://stackoverflow.com/q/51772466
has comment: http://stackoverflow.com/comment/90536133
score: 0
type: Answer

http://stackoverflow.com/comment/92383967
comment on: http://stackoverflow.com/q/51754897
score: 0
type: Comment
has text: Nothing looks out of the ordinary. Is the training set you're using something you can make available so that we can try out the code?
type: QuestionComment

http://stackoverflow.com/a/51691727
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/100609710
answers question: http://stackoverflow.com/q/51688973
accepted answer of: http://stackoverflow.com/q/51688973
type: Answer
has body: You are right, tesseract works better with higher resolutions so sometimes resizing the image helps - but don't convert to 1 bit. I got good results converting to grayscale, making it 3 times as large and making the letters a bit brighter: &gt;&gt;&gt; im = Image.open('j78TY.png')\ .convert('L').resize([3 * _ for _ in im.size], Image.BICUBIC)\ .point(lambda p: p &gt; 75 and p + 100) &gt;&gt;&gt; pytesseract.image_to_string(im) 'NedNoodleArms' Check this jupyter notebook:
upvote count: 10
has comment: http://stackoverflow.com/comment/92854195
score: 10
has comment: http://stackoverflow.com/comment/92825457
has comment: http://stackoverflow.com/comment/92850680

http://stackoverflow.com/comment/90356384
type: QuestionComment
has text: I used distribution fitting in JMP with the sample data you've linked to. Top choices seem to be a Johnson SI distribution or a LogNormal distribution. It's pretty ambiguous given how little data there is. Given that column 5 is described as the log of the measurement, I'd recommend trying LogNormal fits.
type: Comment
comment on: http://stackoverflow.com/q/51682521
score: 0

http://stackoverflow.com/q/51657074
upvote count: 1
type: Question
has body: I'm working on a dashboard that I am using aiohttp and pandas to_html() function to create a HTML table from an api scraping dataframe, basically. I'm using a simple memory cache and running it on a remote server, so I'd like to figure out how to have the page "auto refresh." I've been looking at a lot of websites but most of them have access to the backend HTML5 in order to configure &lt;meta http-equiv="refresh" content="5" /&gt;. Because I am using pandas.to_html, is there a simple way to go about this within my python script, or will I need a js script to enable such a function?
has comment: http://stackoverflow.com/comment/90278107
downvote count: 0
score: 1
has title: Is there a way to pass meta refresh in pandas to_html?
favorite count: 0
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51702647
has comment: http://stackoverflow.com/comment/90457461
has comment: http://stackoverflow.com/comment/90458049
has comment: http://stackoverflow.com/comment/107299039
has comment: http://stackoverflow.com/comment/106430203
type: Answer
has comment: http://stackoverflow.com/comment/115542054
has body: I have made an example to maybe give you an idea on how to proceede. I made it without your transformations of the image but you could do it with them if you would like. What I did was to first transform the image to binary with cv2.THRESH_BINARY. Next I made a mask and drew the contours by limiting them with size (cv2.contourArea()) and ratio (got it from cv2.boundingRect()) for threshold. Then I conected all the contours that are near each other using cv2.morphologyEx() and a big kernel size (50x50). Then I selected the biggest contour (text) and drew a rotated rectangle with cv2.minAreaRect() which got me the rotational angle. Then I could rotate the image using cv2.getRotationMatrix2D() and cv2.warpAffine() and get a slightly bigger bounding box using the highest X, Y and lowest X,Y values of the rotated rectangle which I used to crop the image. Then I serched again for contours and removed the noise (little contours) from the image and the result is a text with high contrast. Final result: This code is meant only to give an idea or another point of view to the problem and it may not work with other images (if they differ from the original too much) or at least you would have to adjust some parameters of code. Hope it helps. Cheers! Code: import cv2 import numpy as np # Read image and search for contours. img = cv2.imread('rotatec.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, threshold = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) # Create first mask used for rotation. mask = np.ones(img.shape, np.uint8)*255 # Draw contours on the mask with size and ratio of borders for threshold. for cnt in contours: size = cv2.contourArea(cnt) x,y,w,h = cv2.boundingRect(cnt) if 10000 > size > 500 and w*2.5 > h: cv2.drawContours(mask, [cnt], -1, (0,0,0), -1) # Connect neighbour contours and select the biggest one (text). kernel = np.ones((50,50),np.uint8) opening = cv2.morphologyE…
score: 7
has comment: http://stackoverflow.com/comment/90469501
has comment: http://stackoverflow.com/comment/90463580
upvote count: 7
answers question: http://stackoverflow.com/q/51699779
downvote count: 0
has comment: http://stackoverflow.com/comment/90434169
has comment: http://stackoverflow.com/comment/90434102
has comment: http://stackoverflow.com/comment/90438239

try-except
tags question: http://stackoverflow.com/q/51677027
tags question: http://stackoverflow.com/q/51726782
tags question: http://stackoverflow.com/q/51777830
tags question: http://stackoverflow.com/q/51715089
tags question: http://stackoverflow.com/q/51764409
tags question: http://stackoverflow.com/q/51679270
type: Tag
tags question: http://stackoverflow.com/q/51665352
tag name: try-except

http://stackoverflow.com/comment/90466405
has text: Thanks for the suggestion! If I used this library would I be taking a speed hit during some other part of the processing--like for example opening the CSV or performing vectorized calculations on the df?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51752942

http://stackoverflow.com/q/51678110
has comment: http://stackoverflow.com/comment/90321738
has comment: http://stackoverflow.com/comment/90320701
type: Question
has answer: http://stackoverflow.com/a/71363176
has body: I have a CSV file that looks like this: first-name,last-name,email-address Yes,Beth,bethfat@gmail.com Iran,Dajango,django@me.com Paul,Walker,info@walker.com Ray,Johnson,JJRay@gmail.com I'm trying to convert this CSV file into a Excel file for further use by using Pandas. How I'm doing so is by reading the data from a webpage: import requests def get_data(url): headers = { "Connection": "close", "User-Agent": "TBG/Converter (TBG;file-converter)" } req = requests.get(url, headers=headers) return req.content def parse_html(html): retval = {} data = html.split("&lt;/head&gt;") data = data[-1] data = data.split("\n") retval["header"] = data[0].strip() data = data[1:-1] emails = set() for email in data: emails.add(email.split("&lt;br&gt;")[-1]) retval["userInformation"] = list(emails) return retval And writing it to a temporary CSV file: import pandas as pd def write_to_xlsx(data_dict, filename): tmp_filename = "/tmp/{}.csv".format(rand()) with open(tmp_filename, "a+") as tmp: data = [data_dict["header"]] for item in data_dict["userInformation"]: item = item.split(",") item = ",".join([c.strip() for c in item]) data.append(item) csv_format = "\n".join(data) tmp.write(csv_format) print tmp_filename with pd.ExcelWriter(filename) as ew: pd.read_csv(tmp_filename).to_excel( ew, index=False, sheet_name=tmp_filename.split(".")[0], encoding="utf-8" ) ew.save() During the writing of the Excel file I get an error telling me: Traceback (most recent call last): File "converter.py", line 70, in &lt;module&gt; write_to_xlsx(sorted_data, config["filename"].format(str(datetime.datetime.now()).split(" ")[0])) File "converter.py", line 63, in write_to_xlsx ew.save() File "/Users/admin/bin/python/printers/venv/mailchimper/lib/python2.7/site-packages/pandas/io/excel.py", line 985, in __exit__ self.close() File "/Users/admin/bin/python/printers/venv/mailchimper/lib/python2.7/site-packages/pandas/io/excel.py", line 989, in close return self.save() File "/Users/admin/bin/python/printers/venv/ma…
score: 0
has title: IndexError: At least one sheet must be visible reading from a CSV file
answer count: 2
has comment: http://stackoverflow.com/comment/90322930
tagged with: pandas
has comment: http://stackoverflow.com/comment/90667354
has comment: http://stackoverflow.com/comment/135180260
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/46840960
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/76755747
tagged with: python
tagged with: excel

http://stackoverflow.com/a/51722171
has body: Guys i have solve this problem, what i did is create a new folder in my desktop and make a new spec file and run it and it runs okay. 1) Create a new file on desktop 2) Open Terminal 3) buildozer init >> edit your file 4) buildozer android debug
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51716272

http://stackoverflow.com/q/51788085
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51788157
has answer: http://stackoverflow.com/a/51788165
type: Question
has comment: http://stackoverflow.com/comment/90533423
has body: Ight, so im a complete novice when it comes to python, so try not to laugh when you see my code. Im trying to make a simple socketing server and client where i can send some data from the client to the server and have it send it back. Here it is: Server: import socket def Main(): print("--------------------------------------------------------------------------------") print("Please input host. If field left blank, host is localhost") host = input() if host == "": host = "127.0.0.1" print("Please input port. Now that i think about it, don't, unless told to, just leave it as is (Blank)") port = input() if port == "": port = 5000 print("--------------------------------------------------------------------------------") ############################################################################################################################################# s = socket.socket() s.bind((host,port)) s.listen(1) c, addr = s.accept() print("Connecton from: " + str(addr)) while True: data = c.recv(1024).decode("utf-8") if not data: break print("From connected user: " + data) data = data * 2 #This is just to test if it works, by doubing it print("Sending: " + data) c.send(data.encode("utf-8")) s.close if __name__ == "__main__": Main() Right, so here is my client: import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket s.connect((host,port)) message = input("-&gt; ") while message != "quit": s.send(message.encode("utf-8")) data = s.recv(1024).decode("utf-8") print("Recicved from server: "+ data) message = input("-&gt; ") s.close() if __name__ == "__main__": Main() Ya see, if i try to run the client, i get a Type Error: Traceback (most recent call last): File "C:/Users/Napoleon/Desktop/Szymon/Python/Client.py", line 34, in &lt;module&gt; Main() File "C:/Users/Napoleon/Desktop/Szymon/Python/Client.py", line 20, in Main s.connect((host,port)) TypeError: descriptor 'connect' requires a '_socket.socket' object but received a 'tuple' So could any of you help me fi…
upvote count: 4
answer count: 2
has title: Type Error when trying to socket due to python reading host as a tuple
has answer: http://stackoverflow.com/a/51788157
downvote count: 0
score: 4
favorite count: 0
tagged with: sockets
tagged with: python
possible better answer: http://stackoverflow.com/a/51788165

http://stackoverflow.com/comment/90386134
score: 0
type: AnswerComment
has text: @ gabriel Random.shuffle will not be considered as inbuilt function
type: Comment
comment on: http://stackoverflow.com/a/51712094

http://stackoverflow.com/comment/90400746
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51718094
has text: I have known the reason.We need to run the project in the terminal instead of IDE.
score: 0

http://stackoverflow.com/q/51690935
upvote count: 1
has answer: http://stackoverflow.com/a/65467532
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90344761
score: -3
tagged with: optimization
has body: Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect. I need to do it without using arrays, exceptions, imports, lists, or the for loop. Only conditionals and while loops can be used. I wrote the code below, but I feel that my algorithm is too lengthy. Can this program be written in a more concise way? The purpose of my question is to see if there would be a more "Pythonic" way to write the same program, whose code I provided below. s = (input('Enter 10 numbers: ')) t = '' # initialize empty "number" string x = len(s)-1 y = 0 # initialize checked integer z = 0 # initialize preceding integer i = 0 # initialize counter while i &lt;= x: print('i=', i) while i &lt;= x and s[i] != ' ': t = t + s[i] # concatenate "string number" i = i+1 if len(t) &gt; 0: # to not run out of string index y = int(t) if y%2 != 0: # compare odd numbers if y &gt; z: z = y if y &lt; z and z%2 == 0: # if y is a negative odd integer z=y if i &lt;= x and s[i] == ' ': i=i+1 t = '' # reset the "number" string if z == 0: print('No odd numbers entered') else: print('The largest odd number entered is', z)
answer count: 4
downvote count: 4
has answer: http://stackoverflow.com/a/51691047
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/98578100
favorite count: 0
has answer: http://stackoverflow.com/a/51691188
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/51691111
has comment: http://stackoverflow.com/comment/90354688
tagged with: python
possible better answer: http://stackoverflow.com/a/51691188
has title: Largest odd number Python code simplification
has comment: http://stackoverflow.com/comment/90344018
has comment: http://stackoverflow.com/comment/98518064
has comment: http://stackoverflow.com/comment/90343636
accepted answer: http://stackoverflow.com/a/51691111
has comment: http://stackoverflow.com/comment/98538901
has comment: http://stackoverflow.com/comment/90344778

http://stackoverflow.com/q/51695477
has title: Sending email with attached file
type: Question
has comment: http://stackoverflow.com/comment/90352627
score: 0
has comment: http://stackoverflow.com/comment/90352910
has comment: http://stackoverflow.com/comment/90352395
has comment: http://stackoverflow.com/comment/90354602
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: django
has body: I'm trying to send an email with an attached file with, it works fine until the attachment part. It gives me an error expected str, bytes or os.PathLike object, not NoneType here is the code am using ; html {% csrf_token %} Message details Message title: Message text: Enter text here... You contact details: Email: Number: Send views.py def class_msg(request, pk): current_ad = get_object_or_404(AdPost, pk=pk) title = request.POST.get('msgtitle') txt = request.POST.get('msgtxt') email = request.POST.get('email') number = request.POST.get('number') file = request.FILES.get('file') if request.method == 'POST': email_msg = "You have recievied this message from Jehlum.com user - Message text (( " + txt + " )) contact details of sender Email: " + email + " phone number: " + number + " ." email = EmailMessage('new message no Jehlum ' + title, email_msg, to=[current_ad.contact_email]) email.attach_file(file) email.send() return redirect('msg_succ') return render(request, 'msg/class_msg.html')

http://stackoverflow.com/comment/90283480
type: QuestionComment
comment on: http://stackoverflow.com/q/51659737
has text: @DYZ Tt is just fileread, I changed the code when entering into this question from basefileread to fileread so its more comprehensible.
score: 0
type: Comment

http://stackoverflow.com/comment/90713393
type: AnswerComment
type: Comment
score: 0
has text: Hello Max. I think there may be some misconception regarding the output of reinforcement learning. RL will only output the Q-value if the RL algorithm you are using is the Q-learning algorithm. The Q-learning algorithm describes the "goodness" of performing a certain action in a given state. Traditionally, RL is done through policy iteration and value iteration. The Q-value you're talking about is a value iteration approach. If you want to output the power / angle, you need to use the policy iteration approach, where the RL takes some actions and outputs an action.
comment on: http://stackoverflow.com/a/51794321

http://stackoverflow.com/q/51716948
downvote count: 0
has body: I'm trying to extract keypoints using MSER and use SIFT as a feature descriptor, and then match the matching keypoints. I did the following using Python: import numpy as np import cv2 from matplotlib import pyplot as plt img1 = cv2.imread('1.jpg') img2 = cv2.imread('2.jpg') mser = cv2.MSER_create() kp1 = mser.detect(img1) kp2 = mser.detect(img2) sift = cv2.xfeatures2d.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, kp1) kp2, des2 = sift.detectAndCompute(img2, kp2) bf = cv2.BFMatcher() matches = bf.knnMatch(des1,des2, k=2) good = [] for m, n in matches: if m.distance &lt; 0.8 * n.distance: good.append(m) good = sorted(good, key=lambda x: x.distance) print len(good) matching_result = cv2.drawMatches(img1, kp1, img2, kp2, good, None, flags=2) cv2.imwrite('result.jpg', matching_result) But, get the following error: kp1, des1 = sift.detectAndCompute(img1, kp1) TypeError: mask is not a numpy array, neither a scalar How can I fix this issue? And, is it right the way I'm using the detector and descriptor?
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: computer-vision
tagged with: opencv
score: 1
tagged with: image-processing
type: Question
has answer: http://stackoverflow.com/a/51717606
tagged with: image
has title: Using MSER as a keypoint detector and SIFT as descriptor
has comment: http://stackoverflow.com/comment/90403510
answer count: 1

natural-logarithm
type: Tag
tag name: natural-logarithm
tags question: http://stackoverflow.com/q/51791420

http://stackoverflow.com/q/51731976
answer count: 2
has title: How to split a numpy array into subarrays based on a list of numbers?
has comment: http://stackoverflow.com/comment/90425539
has answer: http://stackoverflow.com/a/51734646
has comment: http://stackoverflow.com/comment/90425275
has comment: http://stackoverflow.com/comment/90425169
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90425108
accepted answer: http://stackoverflow.com/a/51734646
type: Question
has body: I have a numpy.array that holds some time-series data, where data[:,0] is the time, and the other columns are some measurements. I also have a list_of_peaks which is a list of times where there is something interesting in the data. My goal is to calculate a certain measure for each point in list_of_peaks which is based the points in data closer to it than any other peak, i.e. I want to partition data halfway between each point in list_of_peaks. My current (very slow) algorithm is this: def measure(d,t_m,t_p): radius = d[(d[:,0] &gt; t_m)* (d[:,0] &lt; t_p)] return np.max(radius) - np.min(radius) list_of_measures = [] for i in range(len(list_of_peaks)): if i == 0: list_of_measures.append(measure(data,data[0,0],(list_of_peaks[i+1] - list_of_peaks[i])/2+list_of_peaks[i])) elif i == len(list_of_peaks) - 1: list_of_measures.append(measure(data,list_of_peaks[i] - (list_of_peaks[i]-list_of_peaks[i-1])/2,data[-1,0])) else: list_of_measures.append(measure(data,list_of_peaks[i] - (list_of_peaks[i]-list_of_peaks[i-1])/2,(list_of_peaks[i+1] - list_of_peaks[i])/2+list_of_peaks[i])) I haven't found any nice built-in numpy function that would serve my purpose, but I am pretty sure this can be done a LOT better, I just don't think see how.
tagged with: numpy
has answer: http://stackoverflow.com/a/51734245
possible better answer: http://stackoverflow.com/a/51734245
score: 0

http://stackoverflow.com/q/51643547
tagged with: django
tagged with: python
score: 0
answer count: 2
has title: Django resolve() doesn't resolve a valid path
has answer: http://stackoverflow.com/a/51643719
has answer: http://stackoverflow.com/a/76281602
type: UnansweredQuestion
has body: I want to run test in Django, and I have a very simple test case that aims to test whether an url is reachable. I am using a valid path, but I still get a Resolver404 error. I don't know if it has something to do with multilanguage settings, or something. This is my main urls.py: from django.contrib import admin from django.conf.urls.i18n import i18n_patterns from django.urls import path, include from rest_framework.authtoken import views from django.conf.urls.static import static from django.conf import settings urlpatterns = i18n_patterns( path('api-token-auth/', views.obtain_auth_token), path('', include('FrontEndApp.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('rosetta/', include('rosetta.urls')), path('general/', include('GeneralApp.urls')), #path('invoices_manager/', include('InvoicesManagerApp.urls')), path('operations_manager/', include('OperationsManagerApp.urls')), #path('payments_manager/', include('PaymentsManagerApp.urls')), #path('providers_manager/', include('ProvidersManagerApp.urls')), path('rates_manager/', include('RatesManagerApp.urls')), #path('reports_manager/', include('ReportsManagerApp.urls')), path('reservations_manager/', include('ReservationsManagerApp.urls')), path('users_manager/', include('UsersManagerApp.urls')) ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my app urls.py: from django.urls import path, include from GeneralApp import views, models from rest_framework import routers, renderers APP_NAME = 'GeneralApp' urlpatterns = [ path('', include(router.urls)), path('catalogs/', views.CatalogViewSet.as_view({'get':'list'})), path('countries/', countries_list, name='rest_countries_list'), path('countries/&lt;int:pk&gt;/', country_detail, name='rest_country_detail'), path('countries/&lt;int:pk&gt;/states/', states_list, name='rest_country_states_list'), path('states/', states_list, name='rest_states_list'), path('states/&lt;int:pk&gt;/', state…
tagged with: django-rest-framework
type: Question

http://stackoverflow.com/comment/90516609
type: QuestionComment
comment on: http://stackoverflow.com/q/51779298
score: 1
has text: I don't understand how you get `4 B B` and not `4 A B`.
type: Comment

http://stackoverflow.com/a/56813903
answers question: http://stackoverflow.com/q/51763519
upvote count: 1
score: 1
has body: This is a long-standing bug in Selenium and has no solution currently.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51705898
has answer: http://stackoverflow.com/a/51707897
has comment: http://stackoverflow.com/comment/90377956
has title: How to change a channels name using discord.py v.1.0.0a?
tagged with: discord
favorite count: 0
tagged with: python-3.x
has body: i've already searched a lot about this online. There I came across the API Refrence (https://discordpy.readthedocs.io/en/rewrite/api.html#discord.TextChannel) which kind of helped me finding what command I need to use. So my conculsion would be to use this code: channel = client.get_channel(475772135730708480) @client.command() async def emoivb(ctx): await discord.VoiceChannel.edit(channel, name = "test") the problem is that it doesnt work with this error: File "C:/Users/MyUser/Desktop/discordbot.py", line 25, in emoivb await discord.VoiceChannel.edit(channel, name = "test") So this error doesnt help me at all... but im sure I just didnt understand the API refrence correctly and didnt use the command as it is supposed to be used. Im pretty new to python coding so that is the most likely thing to have happended. If anyone has some more python knowledge and is able to understand what I did wrong I would really appreciate your help! :)
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
tagged with: discord.py
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51645361
answer count: 1
downvote count: 0
score: 7
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90254712
has comment: http://stackoverflow.com/comment/90254832
linked to: http://stackoverflow.com/q/2828953
accepted answer: http://stackoverflow.com/a/51645756
tagged with: future-warning
has comment: http://stackoverflow.com/comment/90254852
tagged with: openpyxl
upvote count: 7
has title: openpyxl - FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead
has comment: http://stackoverflow.com/comment/90255185
type: AnsweredQuestion
type: Question
has body: I'm getting a warning when loading an xlsm file using openpyxl for python, then saving/closing it after I add some data to specific 7 cells in a specific sheet. The issue is that I'm getting a "FutureWarning" that I have no idea what it is about. I've searched for this for some time now and have not been able to decipher. I'm suspecting that the wb.save() method is what's triggering this warning as it doesn't show up when I comment this specific line up. Does anyone know what this is? CODE wb = openpyxl.load_workbook(filename=directory_path.xlsm, keep_vba=True) ws = wb['sheetname'] ws.cell(row1, col1).value = ### (some number) ws.cell(row2, col2).value = ### (some number) ws.cell(row3, col3).value = ### (some number) ws.cell(row4, col4).value = ### (some number) ws.cell(row5, col5).value = ### (some number) ws.cell(row6, col6).value = ### (some number) ws.cell(row7, col7).value = ### (some number) wb.save(directory_path.xlsm) wb.close() WARNING MESSAGE C:\Users\...\Anaconda3\lib\site-packages\openpyxl\comments\shape_writer.py:75: FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead. if not shape_types:
has answer: http://stackoverflow.com/a/51645756

http://stackoverflow.com/a/52577880
has comment: http://stackoverflow.com/comment/106135688
score: 51
type: Answer
has comment: http://stackoverflow.com/comment/106135566
has comment: http://stackoverflow.com/comment/92091455
downvote count: 0
answers question: http://stackoverflow.com/q/51762514
accepted answer of: http://stackoverflow.com/q/51762514
upvote count: 51
has body: I worked on a Python package modeled after the Kneedle algorithm. It finds x=5 as the point where the curve starts to flatten. The documentation and the paper discuss the algorithm for choosing the knee point in more detail. y = [7342.1301373073857, 6881.7109460930769, 6531.1657905495022, 6356.2255554679778, 6209.8382535595829, 6094.9052166741121, 5980.0191582610196, 5880.1869867848218, 5779.8957906367368, 5691.1879324562778, 5617.5153566271356, 5532.2613232619951, 5467.352265375117, 5395.4493783888756, 5345.3459908298091, 5290.6769823693812, 5243.5271656371888, 5207.2501206569532, 5164.9617535255456] x = range(1, len(y)+1) from kneed import KneeLocator kn = KneeLocator(x, y, curve='convex', direction='decreasing') print(kn.knee) 5 import matplotlib.pyplot as plt plt.xlabel('number of clusters k') plt.ylabel('Sum of squared distances') plt.plot(x, y, 'bx-') plt.vlines(kn.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
has comment: http://stackoverflow.com/comment/108814424
type: AcceptedAnswer

http://stackoverflow.com/a/51669284
accepted answer of: http://stackoverflow.com/q/51667938
upvote count: 1
answers question: http://stackoverflow.com/q/51667938
has comment: http://stackoverflow.com/comment/90301641
type: AcceptedAnswer
has body: You can use CSS selectors built-in within BeautifulSoup. Selector option[selected] will find tag with attribute selected: data = """ 09 10 11 """ from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'lxml') print(soup.select_one('option[selected]').text) Prints: 09 Edit: If you want to find option with value=08, you can do CSS selector `option[value=08]`: data = """ 08 09 10 11 """ from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'lxml') print(soup.select_one('option[value=08]')) Prints: 08
type: Answer
has comment: http://stackoverflow.com/comment/90306210
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90304213

http://stackoverflow.com/comment/90349688
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51693934
has text: thanks Wiktor.. how does re.split() marks the first occurrence of comma in the source string using the following regex when [^"]* is used..... ,(?=(?:"[^"]*"|[^"])*$)
type: Comment

http://stackoverflow.com/comment/90425959
score: 0
has text: What is the question?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51732577

http://stackoverflow.com/comment/90277318
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51656419
type: Comment
has text: How can I use python3 signature then? I am using Django 2.0.6 and python 3.6.5, why is the python 2 signature being used?

http://stackoverflow.com/comment/90266769
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51650641
has text: Of course there are no rows where that condition holds but you already know it.

http://stackoverflow.com/q/51759654
type: Question
tagged with: normal-distribution
has comment: http://stackoverflow.com/comment/90507481
has comment: http://stackoverflow.com/comment/90478409
has title: How can you output the same multivariate gaussian each time
has body: I am using the following code to create a multivariate gaussian dist: f=100 mean1 = [-5,-3] cov1 = [[5,0], [0, 3]] g1=np.random.multivariate_normal(mean1, cov1, f) how can I ensure I get the same exact numbers each time? Is it possible?
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90479542
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90479161
downvote count: 1

http://stackoverflow.com/comment/90456850
score: 0
type: Comment
has text: @JamesLiu I have updated the question to better reflect my issue. The keyword can have multiple plus symbols.
comment on: http://stackoverflow.com/a/51748010
type: AnswerComment

http://stackoverflow.com/comment/90542135
type: AnswerComment
has text: I guess that will be enough. Thanks a lot. Also this will make for me to much easier to implement other features.
type: Comment
comment on: http://stackoverflow.com/a/51792186
score: 0

http://stackoverflow.com/comment/90337231
score: 0
type: Comment
type: QuestionComment
has text: @DYZ I'll try saving it to df.to_excel(). I think my problem is that I am thinking that the changes are happening in the same excel file that the iteration is currently in.
comment on: http://stackoverflow.com/q/51687559

http://stackoverflow.com/comment/90489644
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51765436
has text: why not loop through your list of strings? `for mystr in riclist: ek.get_timeseries(rics=chosenric, start_date=2018-01-01, fields="CLOSE") `

http://stackoverflow.com/q/51699817
tagged with: python-requests
downvote count: 1
type: Question
has title: python async post requests
score: 18
has answer: http://stackoverflow.com/a/51701779
answer count: 2
accepted answer: http://stackoverflow.com/a/51704098
possible better answer: http://stackoverflow.com/a/51701779
favorite count: 0
tagged with: python-asyncio
tagged with: python
type: AnsweredQuestion
upvote count: 19
has body: I was wondering if there was any way to make this script a lot faster - like instantly create 1000 accounts for example or at least in a matter of a few seconds. I’ve tried doing some async stuff myself but this is as far as I could get, I am just a beginner with asynchronous programming so any help is appreciated. import asyncio import aiohttp async def make_numbers(numbers, _numbers): for i in range(numbers, _numbers): yield i async def make_account(): url = "https://example.com/sign_up.php" async with aiohttp.ClientSession() as session: async for x in make_numbers(35691, 5000000): async with session.post(url, data ={ "terms": 1, "captcha": 1, "email": "user%s@hotmail.com" % str(x), "full_name": "user%s" % str(x), "password": "123456", "username": "auser%s" % str(x) }) as response: data = await response.text() print("-&gt; Creating account number %d" % x) print (data) loop = asyncio.get_event_loop() try: loop.run_until_complete(make_account()) finally: loop.close()
tagged with: aiohttp
has answer: http://stackoverflow.com/a/51704098

http://stackoverflow.com/comment/90490823
comment on: http://stackoverflow.com/a/51765875
has text: I was removing and adding because the picture was not updating the way I wrote it. I'm still a beginner at this. Thank you very much! It works now
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90291403
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51663867
type: Comment
has text: [Does this question help](https://stackoverflow.com/q/38095436/4650297)?

http://stackoverflow.com/q/51711189
has comment: http://stackoverflow.com/comment/90385008
type: Question
has comment: http://stackoverflow.com/comment/90383820
has title: Defining and Calling a Function within a Python Class
answer count: 3
downvote count: 0
has body: I'm creating a class and I'm hoping to call a user-defined function within a method for that class. I'd also like to define the function within the class definition. However, when I call the class, I get the error message name *whatever function* is not defined. For instance, something like this: class ExampleClass(): def __init__(self, number): self.number = number def plus_2_times_4(x): return(4*(x + 2)) def arithmetic(self): return(plus_2_times_4(self.number)) But when I call: instance = ExampleClass(number = 4) instance.arithmetic() I get the error message. So basically I want to define the function in one step (def plus_2_times_4) and use the function when defining a method in another step (def arithmetic...). Is this possible? Thanks so much in advance!
has answer: http://stackoverflow.com/a/51711504
has answer: http://stackoverflow.com/a/51711258
possible better answer: http://stackoverflow.com/a/51711299
score: 8
favorite count: 0
has answer: http://stackoverflow.com/a/51711299
upvote count: 8
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51711258

http://stackoverflow.com/comment/90473288
type: AnswerComment
type: Comment
has text: No the source just provides the 2 sets of lats/lons, analagous to those in the example.
comment on: http://stackoverflow.com/a/51756665
score: 0

http://stackoverflow.com/comment/90308455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51667585
has text: Sorry. It's 28*28 pixels of binary images of written numbers. Each row is consisted with a label and 784 columns of binary value (1 is white and 0 is black )

http://stackoverflow.com/q/51757428
has body: I am trying to draw the world map of storm form 1945 to 2017 but every time the final image would have some weird horizontal lines (shown in the picture below) which make it unusable. anyone knows what's going on? please give me some advice how I could remove those lines. Thank you very much https://pasteboard.co/HyiElwe.png
linked to: http://stackoverflow.com/q/50992136
tagged with: matplotlib-basemap
favorite count: 0
has comment: http://stackoverflow.com/comment/90474392
has title: weird horizontal lines on maps
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90731373
has comment: http://stackoverflow.com/comment/90474314
has comment: http://stackoverflow.com/comment/90474422
tagged with: python
has comment: http://stackoverflow.com/comment/90474354
tagged with: maps
score: 2
answer count: 0
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/90474578
has comment: http://stackoverflow.com/comment/90474593
has comment: http://stackoverflow.com/comment/90474673
has comment: http://stackoverflow.com/comment/90474331
upvote count: 2
has comment: http://stackoverflow.com/comment/90476981

http://stackoverflow.com/q/51668214
answer count: 0
has comment: http://stackoverflow.com/comment/90299509
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90299570
tagged with: python
has comment: http://stackoverflow.com/comment/90300899
has body: I am trying to execute this instruction: sudo pip install -r requirements.txt But I foun this error: Command /usr/bin/python -c "import setuptools, tokenize; __file__='/tmp/pip_build_root/pyzmq/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-JB30wJ-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/pyzmq Storing debug log for failure in /home/userrr/.pip/pip.log I would be very grateful if you could help me please. Thanks in advance.
has comment: http://stackoverflow.com/comment/90299129
has comment: http://stackoverflow.com/comment/90299396
type: Question
has title: how to install install some Python packages, debug log output?
has comment: http://stackoverflow.com/comment/90299349
linked to: http://stackoverflow.com/q/44014318
score: 0
has comment: http://stackoverflow.com/comment/90299623
has comment: http://stackoverflow.com/comment/90299708
has comment: http://stackoverflow.com/comment/90299291
has comment: http://stackoverflow.com/comment/90299411

http://stackoverflow.com/q/51768385
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51826935
tagged with: python
accepted answer: http://stackoverflow.com/a/51826935
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm wrinting a program that sometimes has to show an obj file. So I wrote a function (actually, I modified a code from here : https://github.com/greenmoss/PyWavefront/blob/master/example/pyglet_demo.py ) that open a pyglet window, with my rotating 3D object, and when the window is closed, the function end, and I can continue to do stuff until I have to display another (or the same) obj file. This function works, but only the first time I call it. After that I just have a black window. So I hope someone know what I did wrong... Here is my (a bit simplified) code: import ctypes from pyglet.gl import * rotation = 0 def show_3d(meshes): window = pyglet.window.Window(1024, 720, caption='Demo') lightfv = ctypes.c_float * 4 @window.event def on_resize(width, height): glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., float(width)/height, 1., 500.) glMatrixMode(GL_MODELVIEW) return True @window.event def on_draw(): window.clear() glLoadIdentity() glLightfv(GL_LIGHT0, GL_POSITION, lightfv(-1.0, 1.0, 1.0, 0.0)) glEnable(GL_LIGHT0) glTranslated(0, 0, -300) glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glCullFace(GL_FRONT_AND_BACK) glRotatef(rotation, 0, 1, 0) glEnable(GL_LIGHTING) meshes.draw() def update(dt): global rotation rotation += 60*dt pyglet.clock.schedule(update) pyglet.app.run() if __name__ == "__main__": from pywavefront import Wavefront mesh = Wavefront("path to a .obj") show_3d(mesh) # awesome 3D animation # some stuff show_3d(mesh) # just a black window
type: Question
tagged with: pyglet
tagged with: opengl
has title: Display two pyglet window in a row

http://stackoverflow.com/comment/90283545
type: Comment
has text: The error message says that `df_w['Close']` is of type `datetime64` and it does not support operation `.ewm`. What is `ewm` and why do you think you can apply it to a datetime column?
type: QuestionComment
comment on: http://stackoverflow.com/q/51659963
score: 0

http://stackoverflow.com/q/51747284
downvote count: 5
has comment: http://stackoverflow.com/comment/90454294
has comment: http://stackoverflow.com/comment/90454266
has body: I have a python script which is the follow def id_generator(size=12, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) how do I do that to generate it till it fullfills all possibilities without outputting the same thing twice? I need 12 random characters of a-z/0-9 and need to fullfill all the possibilities. Thanks
has comment: http://stackoverflow.com/comment/90454349
has comment: http://stackoverflow.com/comment/90454615
has comment: http://stackoverflow.com/comment/90454284
has comment: http://stackoverflow.com/comment/90494316
has comment: http://stackoverflow.com/comment/90499009
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51747408
score: -5
has title: Random Never same 12 digits code Python
has answer: http://stackoverflow.com/a/51747364
type: Question
has comment: http://stackoverflow.com/comment/90454356
answer count: 2
has comment: http://stackoverflow.com/comment/90454287
upvote count: 0

http://stackoverflow.com/comment/90548513
has text: @cricket_007 I want to implement it using pyspark, I plan to create a hive table on top of my file . That's the reason I want to move it from my server location to hdfs location. I can write a shell command -copyFromLocal but I want to do this using python in pyspark. How do I do it?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51775918

http://stackoverflow.com/a/51768311
answers question: http://stackoverflow.com/q/51762528
score: 0
has body: requires value to be a flat/ typedarray indicates that there is an issue with the dimension or rank of the array passed in as parameter to the tensor. tf.tensor1d requires the parameter to be a flat array (array of depth 1), meaning that the array should not be nested [1, 2, 3]. Likewise tf.tensor2d requires the parameter to be an array of depth 2, it should be like [[1, 2], [3,4]]. To fix the issue: x = tf.tensor1d([form.value.p, form.value.glu, form.value.bp, form.value.sk, form.value.insulin,form.value.bmi, form.value.op, form.value.a, form.value.pred]) You declared your y to be a tensor2d and form.value.pred is used both as feature (x) and a label (y). Whether it is a typo or the architecture you're implementing. But to be coherent, the data structure is not the same in x and y. So you might consider declaring your y to be also a tensor1d or you make sure that you flatten form.value.pred before using it in x
type: Answer

http://stackoverflow.com/comment/90495314
type: Comment
has text: Above code is to make sure that we are inputting correct value in DB @shmee
comment on: http://stackoverflow.com/a/51766154
score: 0
type: AnswerComment

http://stackoverflow.com/a/51760349
score: 0
answers question: http://stackoverflow.com/q/51758871
type: Answer
has body: i used rpyc to make a local connection, something like this: main.py: class Network(rpyc.Service): def __init__(self): super(Network, self).__init__() #Objects to share with modules self.User = User #Start connection conn = ThreadedServer(self, port=10000, protocol_config={"allow_public_attrs": True}) t = Thread(target=conn.start) t.daemon = True t.start() if __name__ == '__main__': conn = Network() command.py: conn = rpyc.connect("localhost", 10000) User = conn.root.User def execute(): #do some stuff and get a user object my_user = User(user_obj) my_user.add_role('mod')

http://stackoverflow.com/q/51773496
type: Question
upvote count: 2
tagged with: pylint
tagged with: python
has comment: http://stackoverflow.com/comment/90647482
answer count: 1
has body: Consider: @api.route('/my-resource/<id>', endpoint='my-resource') @api.doc(params={'id': 'An ID'}) class MyResource(Resource): @api.doc(responses={403: 'Not Authorized'}) def post(self, id): api.abort(403) Pylint complains: R0201: POST Method could be a function (no-self-use)" How can I avoid this Pylint error? I tried writing a constructor like: @api.route('/my-resource/<id>', endpoint='my-resource') @api.doc(params={'id': 'An ID'}) class MyResource(Resource): def __init__(self): self.counter = 0 @api.doc(responses={403: 'Not Authorized'}) def post(self, id): api.abort(403) But this does not work. It throws Internal server error while calling the API. Error: lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) lib/python3.7/site-packages/flask_restplus/api.py", line 319, in wrapper resp = resource(*args, **kwargs) /lib/python3.7/site-packages/flask/views.py", line 87, in view self = view.view_class(*class_args, **class_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given
type: UnansweredQuestion
tagged with: flask-restplus
score: 2
has title: Pylint error "R0201: POST Method could be a function (no-self-use)"
downvote count: 0
has answer: http://stackoverflow.com/a/51781706
favorite count: 0

http://stackoverflow.com/comment/90342560
comment on: http://stackoverflow.com/a/51683695
score: 0
type: Comment
has text: thank you, that made it work now but i believe there is a problem with my 'except ValueError' because when i put in a letter it prints ("Please enter a whole number from 0 to 3") but it does not reask the question like with the 'if'
type: AnswerComment

http://stackoverflow.com/comment/90433468
score: 0
type: Comment
type: QuestionComment
has text: @LevZakharov: I've tried multiple things (hard refreshes, incognito mode, separate web browser) and still see an image on my end. I don't think there's a broken link.
comment on: http://stackoverflow.com/q/51736340

http://stackoverflow.com/q/51713790
favorite count: 0
has title: How to cast string to ArrayType of dictionary (JSON) in PySpark
has body: Trying to cast StringType to ArrayType of JSON for a dataframe generated form CSV. Using pyspark on Spark2 The CSV file I am dealing with; is as follows - date,attribute2,count,attribute3 2017-09-03,'attribute1_value1',2,'[{"key":"value","key2":2},{"key":"value","key2":2},{"key":"value","key2":2}]' 2017-09-04,'attribute1_value2',2,'[{"key":"value","key2":20},{"key":"value","key2":25},{"key":"value","key2":27}]' As shown above, it contains one attribute "attribute3" in literal string, which is technically a list of dictionary(JSON) with exact length of 2. (This is the output of function distinct) Snippet from the printSchema() attribute3: string (nullable = true) I am trying to cast the "attribute3" to ArrayType as follows temp = dataframe.withColumn( "attribute3_modified", dataframe["attribute3"].cast(ArrayType()) ) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: __init__() takes at least 2 arguments (1 given) Indeed, ArrayType expects datatype as argument. I tried with "json", but it did not work. Desired Output - In the end, I need to convert attribute3 to ArrayType() or plain simple Python list. (I am trying to avoid use of eval) How do I convert it to ArrayType, so that I can treat it as list of JSONs? Am I missing anything here? (The documentation,does not address this problem in straightforward way)
has comment: http://stackoverflow.com/comment/90389478
tagged with: python
has comment: http://stackoverflow.com/comment/90389232
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51714146
linked to: http://stackoverflow.com/q/48427185
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/90389029
tagged with: apache-spark-sql
score: 7
tagged with: pyspark
has comment: http://stackoverflow.com/comment/90389156
answer count: 2
possible better answer: http://stackoverflow.com/a/51714341
downvote count: 0
has answer: http://stackoverflow.com/a/51714146
has answer: http://stackoverflow.com/a/51714341

http://stackoverflow.com/comment/90450534
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51745416
has text: @Chris_Rands How can I use try and except clause with pass statement to achieve this?

http://stackoverflow.com/comment/90384418
score: 0
type: Comment
has text: @AhmedGamal Yes, `df = pd.read_clipboard()` followed by my code gave me that answer. How is your answer different?
comment on: http://stackoverflow.com/a/51711375
type: AnswerComment

http://stackoverflow.com/q/51655747
answer count: 6
score: 4
accepted answer: http://stackoverflow.com/a/51655850
tagged with: search
upvote count: 4
has comment: http://stackoverflow.com/comment/90275080
possible better answer: http://stackoverflow.com/a/51655811
has answer: http://stackoverflow.com/a/51655961
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51655908
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51656276
type: Question
has body: I'm trying to search a list I have for specific values and if any of those values exist in the list, I would like to perform a different operation. Currently this is the list I am working with: print(categories) ['Creams', 'Bath', 'Personal Care'] What I would like to do is search this categories list for some different values. To do this, I've converted categories into a set and am individually searching for each of the values with an if statement. For example: c = set(categories) if "Conditioners" in c: print("1") if "Bath" in c: print("2") if "Shaving Gels" in c: print("3") Which returns: 2 What I would ideally like to do is put my criteria into a list or some other relevant data structure and have it perform that particular operation if that value exists within categories in an efficient manner.
has answer: http://stackoverflow.com/a/51655850
has title: Python - Searching multiple values in list and performing multiple operations
has answer: http://stackoverflow.com/a/51655872
has answer: http://stackoverflow.com/a/51655811

http://stackoverflow.com/comment/90456556
type: QuestionComment
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html
comment on: http://stackoverflow.com/q/51748268
score: 0
type: Comment

http://stackoverflow.com/a/51641959
type: Answer
has body: Assuming you have a nested dictionary, you can use print with an unpacked generator expression. str.format is one way to extract the relevant data from your dictionary: my_dict = {"Hello": {'count': 2, 'distance': 6}, "Clear": {'count': 8, 'distance': 8}} print(*('{} - count: {}'.format(i, d[i]['count']) for i in d), sep='\n') Hello - count: 2 Clear - count: 8
answers question: http://stackoverflow.com/q/51641812
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/90286869
type: Comment
type: QuestionComment
has text: @SuperStew I receive an error that stops me from executing the processes in the second function
comment on: http://stackoverflow.com/q/51661710
score: 0

http://stackoverflow.com/a/51678107
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51678016
has body: You're almost there, just add in sep=' ' to make sure that it reads spaces as the delimiter: df = pd.read_table('file.txt', sep = ' ', comment="%", header=None, names=["c1","c2","c3","c4"]) &gt;&gt;&gt; df c1 c2 c3 c4 0 s 1 2 s 1 t 3 2 f 2 p 2 2 f 3 i 0 9 e 4 u 3 3 e
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51678016

http://stackoverflow.com/comment/90504551
has text: Possible duplicate of [How to implement 'in' and 'not in' for Pandas dataframe](https://stackoverflow.com/questions/19960077/how-to-implement-in-and-not-in-for-pandas-dataframe)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51772836
type: QuestionComment

http://stackoverflow.com/comment/90515399
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51778216
type: Comment
has text: @RafaelC do you alo have any idea why we get different results from the two solutions?

http://stackoverflow.com/comment/90324775
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51679264
has text: @DavidA In `GUI` we have the call `self.nb = self.create_notebook(names)` to create the Notebook. That calls the `.create_notebook` method, which in turn does `nb = MyNotebook(self, names)` to create an instance of the `MyNotebook` class. And when that instance is created the `MyNotebook.__init__` is run which performs the actions of initializing a `ttk.Notebook` (which MyNotebook needs in order to be a valid child of `ttk.Notebook`) and adding the desired tabs to it.
type: AnswerComment

http://stackoverflow.com/q/51758480
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90527964
score: -1
type: Question
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51758878
has body: I've ran the following lines of code import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.datasets import load_boston boston = load_boston() print(boston.data.shape) from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split x = pd.DataFrame(boston.data) x.columns = boston.feature_names y=pd.DataFrame(boston.target) y.columns=['TARGET'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=101) model = LinearRegression() model.fit(x_train,y_train) print('Coefficients: \n', model.coef_) len(model.coef_) Coefficients: -8.74917163e-02 5.02793747e-02 2.06785359e-02 3.75457604e+00 -1.77933846e+01 3.24118660e+00 1.20902568e-02 -1.40965453e+00 2.63476633e-01 -1.03376395e-02 -9.52633123e-01 6.20783942e-03 -5.97955998e-01 1 coeffecients = pd.DataFrame(data=model.coef_,index=x.columns,columns=['Coefficient']) error msg: Shape of passed values is (13, 1), indices imply (1, 13) I think the issue is from the length for the array of coefficients being 1. Not sure though.
downvote count: 1
tagged with: python
favorite count: 0
tagged with: sklearn-pandas
upvote count: 0
has title: Working with the sklearn Boston Housing Dataset: Trying to create dataframe for coefficients

http://stackoverflow.com/q/51749906
has answer: http://stackoverflow.com/a/51750686
score: 16
tagged with: virtualenvwrapper
downvote count: 1
has answer: http://stackoverflow.com/a/51750625
upvote count: 17
type: Question
has body: how can I find the path of virtualenv python ,built with this tutorial? (i want to find python in this env and use it in my eclipse) $ sudo pip install virtualenv virtualenvwrapper $ export WORKON_HOME=$HOME/.virtualenvs $ source /usr/local/bin/virtualenvwrapper.sh $ echo -e "\n# virtualenv and virtualenvwrapper" &gt;&gt; ~/.bashrc $ echo "export WORKON_HOME=$HOME/.virtualenvs" &gt;&gt; ~/.bashrc $ echo "source /usr/local/bin/virtualenvwrapper.sh" &gt;&gt; ~/.bashrc $ source ~/.bashrc $ mkvirtualenv cv -p python3
has title: how can I find the path of virtualenv python
has comment: http://stackoverflow.com/comment/90460756
accepted answer: http://stackoverflow.com/a/51750686
answer count: 3
tagged with: virtualenv
possible better answer: http://stackoverflow.com/a/72893928
favorite count: 0
has answer: http://stackoverflow.com/a/72893928
tagged with: linux
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51773456
has comment: http://stackoverflow.com/comment/90506099
has comment: http://stackoverflow.com/comment/90505721
has comment: http://stackoverflow.com/comment/90505883
has comment: http://stackoverflow.com/comment/90506016
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51773248
type: Answer
upvote count: 1
score: 1
has body: This is likely because you did not indent any of your elif statements to line up with your if statement, this is how python knows to "connect" statements/blocks of code. It should look like this: @client.event async def on_message(message): global botnum # we do not want the bot to reply to itself if message.author == client.user: return elif message.content.startswith('Peribot'): msg = "I'm Busy! D:&lt;".format(message) await client.send_message(message.channel, msg) elif botnum == 20: msg = "You Clods are so loud!".format(message) await client.send_message(message.channel, msg) botnum = 0 elif message.content.startswith('info'): msg = "Created by Popleoma with the intent of being a fun bot. Commands are Peribot, info, and more to come!".format(message) await client.send_message(message.channel, msg) else: botnum += 1 client.run("") In addition to this you put an elif block after an else statement which will not work. Here is a tutorial on python indentation for future reference: https://docs.python.org/2.0/ref/indentation.html
has comment: http://stackoverflow.com/comment/90506135
answers question: http://stackoverflow.com/q/51773248
downvote count: 0

http://stackoverflow.com/comment/127505770
type: QuestionComment
has text: [question] https://stackoverflow.com/questions/62390314/how-to-call-asynchronous-function-in-django
comment on: http://stackoverflow.com/q/51790935
score: 0
type: Comment

http://stackoverflow.com/q/51785296
tagged with: topic-modeling
type: Question
has answer: http://stackoverflow.com/a/56265758
linked to: http://stackoverflow.com/q/55091094
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/112291694
tagged with: python
tagged with: gensim
favorite count: 0
has body: I am trying to load a saved gensim lda mallet: ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=n_topics,id2word=id2word) ldamallet.save('ldamallet') When testing this for a new query (with the original corpus and dictionary), everything seems fine for the first load. ques_vec = [dictionary.doc2bow(words) for words in data_words_list] for i, row in enumerate(lda[ques_vec]): row = sorted(row, key=lambda x: (x[1]), reverse=True) On executing the same code afterward, it is this error that pops up: java.io.FileNotFoundException: /tmp/9f371_corpus.mallet (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.(FileInputStream.java:138) at cc.mallet.types.InstanceList.load(InstanceList.java:787) at cc.mallet.classify.tui.Csv2Vectors.main(Csv2Vectors.java:131) Exception in thread "main" java.lang.IllegalArgumentException: Couldn't read InstanceList from file /tmp/9f371_corpus.mallet at cc.mallet.types.InstanceList.load(InstanceList.java:794) at cc.mallet.classify.tui.Csv2Vectors.main(Csv2Vectors.java:131) Traceback (most recent call last): File "topic_modeling1.py", line 406, in topic = get_label(text, id2word, first, ldamallet) File "topic_modeling1.py", line 237, in get_label for i, row in enumerate(lda[ques_vec]): File "/home/user/sjha/anaconda3/envs/conda_env/lib/python3.6/site-packages/gensim/models/wrappers/ldamallet.py", line 308, in getitem self.convert_input(bow, infer=True) File "/home/user/sjha/anaconda3/envs/conda_env/lib/python3.6/site-packages/gensim/models/wrappers/ldamallet.py", line 256, in convert_input check_output(args=cmd, shell=True) File "/home/user/sjha/anaconda3/envs/conda_env/lib/python3.6/site-packages/gensim/utils.py", line 1806, in check_output raise error subprocess.CalledProcessError: Command '/home/user/sjha/projects/topic_modeling/mallet-2.0.8/bin/mallet import-file --preserve-case --keep-sequence --rem…
type: UnansweredQuestion
tagged with: mallet
upvote count: 1
has comment: http://stackoverflow.com/comment/98310975
tagged with: lda
score: 1
has title: Gensim mallet bug? Fails to load the saved model more than once
has comment: http://stackoverflow.com/comment/112291739

list
type: Tag
tags question: http://stackoverflow.com/q/51664618
tags question: http://stackoverflow.com/q/51667176
tags question: http://stackoverflow.com/q/51765551
tags question: http://stackoverflow.com/q/51661522
tags question: http://stackoverflow.com/q/51732183
tags question: http://stackoverflow.com/q/51737178
tags question: http://stackoverflow.com/q/51758413
tags question: http://stackoverflow.com/q/51677734
tags question: http://stackoverflow.com/q/51728873
tags question: http://stackoverflow.com/q/51705399
tags question: http://stackoverflow.com/q/51689860
tags question: http://stackoverflow.com/q/51797311
tags question: http://stackoverflow.com/q/51656851
tags question: http://stackoverflow.com/q/51781053
tags question: http://stackoverflow.com/q/51716479
tags question: http://stackoverflow.com/q/51689892
tags question: http://stackoverflow.com/q/51728089
tags question: http://stackoverflow.com/q/51662051
tags question: http://stackoverflow.com/q/51741054
tags question: http://stackoverflow.com/q/51732256
tags question: http://stackoverflow.com/q/51781149
tags question: http://stackoverflow.com/q/51649221
tags question: http://stackoverflow.com/q/51750512
tags question: http://stackoverflow.com/q/51772877
tags question: http://stackoverflow.com/q/51663516
tags question: http://stackoverflow.com/q/51761012
tags question: http://stackoverflow.com/q/51757162
tags question: http://stackoverflow.com/q/51798405
tags question: http://stackoverflow.com/q/51641518
tags question: http://stackoverflow.com/q/51793677
tags question: http://stackoverflow.com/q/51756652
tags question: http://stackoverflow.com/q/51770922
tags question: http://stackoverflow.com/q/51701176
tags question: http://stackoverflow.com/q/51743582
tags question: http://stackoverflow.com/q/51778828
tags question: http://stackoverflow.com/q/51705819
tags question: http://stackoverflow.com/q/51742743
tags question: http://stackoverflow.com/q/51699120
tags question: http://stackoverflow.com/q/51690430
tags question: http://stackoverflow.com/q/51659435
tag name: list
tags question: http://stackoverflow.com/q/51745678
tags question: http://stackoverflow.com/q/51752885
tags question: http://stackoverflow.com/q/51664954
tags question: http://stackoverflow.com/q/51775953
tags question: http://stackoverflow.com/q/51725921
tags question: http://stackoverflow.com/q/51668340
tags question: http://stackoverflow.com/q/51693022
tags question: http://stackoverflow.com/q/51657795
tags question: http://stackoverflow.com/q/51653771
tags question: http://stackoverflow.com/q/51641379
tags question: http://stackoverflow.com/q/51773853
tags question: http://stackoverflow.com/q/51661375
tags question: http://stackoverflow.com/q/51712316
tags question: http://stackoverflow.com/q/51756444
tags question: http://stackoverflow.com/q/51660187
tags question: http://stackoverflow.com/q/51790883
tags question: http://stackoverflow.com/q/51780856
tags question: http://stackoverflow.com/q/51720306
tags question: http://stackoverflow.com/q/51757224
tags question: http://stackoverflow.com/q/51792627
tags question: http://stackoverflow.com/q/51710490
tags question: http://stackoverflow.com/q/51769198
tags question: http://stackoverflow.com/q/51737789
tags question: http://stackoverflow.com/q/51667086
tags question: http://stackoverflow.com/q/51658919
tags question: http://stackoverflow.com/q/51790555
tags question: http://stackoverflow.com/q/51665444
tags question: http://stackoverflow.com/q/51717984
tags question: http://stackoverflow.com/q/51729909
tags question: http://stackoverflow.com/q/51648189
tags question: http://stackoverflow.com/q/51647981
tags question: http://stackoverflow.com/q/51740535
tags question: http://stackoverflow.com/q/51673503
tags question: http://stackoverflow.com/q/51681081
tags question: http://stackoverflow.com/q/51746930
tags question: http://stackoverflow.com/q/51775338
tags question: http://stackoverflow.com/q/51781908
tags question: http://stackoverflow.com/q/51781985

http://stackoverflow.com/comment/90318563
score: 0
type: Comment
has text: @hAICHI You need to select every `<CI_JOURNAL>` tag and the missing values replace with `'Blank'`. The existing code you have doesn't know what's missing.
comment on: http://stackoverflow.com/a/51661785
type: AnswerComment

http://stackoverflow.com/q/51721079
has answer: http://stackoverflow.com/a/51721222
has comment: http://stackoverflow.com/comment/90434515
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51722347
tagged with: aws-lambda
tagged with: python
has answer: http://stackoverflow.com/a/51722347
possible better answer: http://stackoverflow.com/a/51721222
has title: How can I run my python script on AWS lambda 24/7
type: AnsweredQuestion
type: Question
has body: Is it possible to run my run my python script on AWS lambda 24/7 without the 5mins limit?

http://stackoverflow.com/q/51750894
tagged with: fuzzywuzzy
has comment: http://stackoverflow.com/comment/90461772
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90464859
has body: I have an excel worksheet with 4 columns as SPI1, D, SPI2, O and they are sorted by SellerPartyId ie SPI. I would like to see those in O which are not present in D. The number of rows on Originator Name is over 20,000 while those in DBAName is around 1,000. I have seen a number of solutions but it does not match my desired results. I am quite new to Python so any help would be awesome. enter image description here
tagged with: python
has comment: http://stackoverflow.com/comment/90465572
has title: FuzzyWuzzy in python for matching thousands of rows
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/90464914
has comment: http://stackoverflow.com/comment/90464212

http://stackoverflow.com/q/51717955
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/90436313
type: UnansweredQuestion
tagged with: python
downvote count: 0
has title: How to access a value from a drop down box selection to use in url_for
has body: I have the below working for the top summary link - drop box and a submit changes the type. But I want to create links for each circle that also uses the value from the drop down box. I tried the below under active users.. <a href="{{ url_for('details', active='active', type=type) }} But when I click the link it has no type information. Is this possible? {% for type in types %} {{ type }} {% endfor %} Select Type Total Users {{ total_users }} Active Users {{ total_active }} Total Logged {{ '{:,}'.format(total) }} Attendence {{ '{:.0%}'.format(attendance) }}
has comment: http://stackoverflow.com/comment/90462142
type: Question
has comment: http://stackoverflow.com/comment/90436330
score: 1
has comment: http://stackoverflow.com/comment/90436320
has answer: http://stackoverflow.com/a/51732359
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51761810
has title: After clustering, How do i choose the best customers (subset) from the top cluster?
score: 0
has comment: http://stackoverflow.com/comment/90483777
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: unsupervised-learning
has comment: http://stackoverflow.com/comment/90483740
has answer: http://stackoverflow.com/a/51762007
type: Question
tagged with: cluster-analysis
has body: I ran a clustering exercise to identify my top customers based on 12 distinct features, using K-Means (on 3 PCA dimensions and 5 PCA dimensions) and GMM (using 5 PCA dimensions) methodologies. Both the outputs from the K-Means produced almost similar customers as the best set (1182 customers in each case with an overlap of 1156) while the GMM approach gave me 660 customers as my top customers. These 660 customers were present in both the K-Means approaches. Now i want to identify who my top customers are from among this list. Could you please suggest any statistical approaches that i could use to say that these X number of customers are truly my best set and run some A/B tests on them? I do not want to go with the full identified set as it might cost me more to do what is planned to such a large set of customers.

http://stackoverflow.com/q/51777823
score: 0
has answer: http://stackoverflow.com/a/51849351
type: Question
tagged with: python-3.7
answer count: 1
accepted answer: http://stackoverflow.com/a/51849351
tagged with: basehttpserver
has body: So basically, I am making an HTTP webhooks server in Python 3 and wanted to add a restart function because shell access is very limited on the server it will be running on. I found this snippet somewhere on Stack Overflow earlier: def restart_program(): """Restarts the current program, with file objects and descriptors cleanup """ try: p = psutil.Process(os.getpid()) fds = p.open_files() + p.connections() print (fds) for handler in fds: os.close(handler.fd) except Exception as e: logging.error(e) python = sys.executable os.execl(python, python, *sys.argv) For the most part, it works, but I wanted to make sure so I ran a few tests with lsof and found that every time I restarted the server, two more lines (files) were added to the list of open files: python3 13923 darwin 5u systm 0x18cd0c0bebdcbfd7 0t0 [ctl com.apple.netsrc id 9 unit 36] python3 13923 darwin 6u unix 0x18cd0c0beb8fc95f 0t0 -&gt;0x18cd0c0beb8fbcdf (the adresses varying each restart) These are only present when I initiate httpd = ThreadingSimpleServer((host, port), Handler). But even after I call httpd.server_close() these open files persist and psutil doesn't seem to find them. This isn't really required feature. If this proves to be too much overhead I can drop it, but right now I am only interested in why my code doesn't work and a solution for my own sanity. Thanks in advance! UPDATE: Changing p.connections() to p.connections(kind='all') got me the unix type fd. Still not sure how to close the systm type fd. Turns out the unix fd had to do with DNS... UPDATE: Well, it looks like I found a solution, however messy it may be. class MyFileHandler(object): """docstring for MyFileHandler.""" def __init__(self, fd): super(MyFileHandler, self).__init__() self.fd = fd def get_open_systm_files(pid=os.getpid()): proc = subprocess.Popen(['lsof', '-p', str(pid)], stdout=subprocess.PIPE) return [MyFileHandler(int(str(l).split(' ')[6][:-1])) for l in proc.stdout.readlines() if b'systm' in l] def restart_program(): …
has title: Python : http.server.HTTPServer : How to close ALL opened files?
tagged with: python
tagged with: lsof
tagged with: unix
type: AnsweredQuestion

http://stackoverflow.com/q/51641380
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I've searched for a few days looking for a clue on how to easily format text commentary into the output of sympy when running inside (say) a Jupyter notebook. Simple example of what i've tried so far: init_printing(use_latex='mathjax') print("Here is an integral ") Integral(expr1,x) ...which outputs a crappy looking text comment above the line with a pretty good looking integral expression. Instead, I'm looking for a text comment that'd be included on the same line as the integral and present itself with better formatting instead of just "code block" font. Ideally, there'd be some sort of "printf" style function; but I just not have been able to find it.
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51656837
has answer: http://stackoverflow.com/a/51645101
downvote count: 2
upvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/51644064
answer count: 3
tagged with: sympy
has title: Text comments in sympy output
tagged with: jupyter

http://stackoverflow.com/comment/90449318
type: Comment
comment on: http://stackoverflow.com/a/51744281
score: 0
type: AnswerComment
has text: And now a chained question - Is possible to manipulate Keras to do the same? But maybe I'll open a new question for that. Thanks again.

http://stackoverflow.com/comment/90333604
comment on: http://stackoverflow.com/a/51685653
type: AnswerComment
has text: Whats the "pprint" youre using here?
score: 0
type: Comment

http://stackoverflow.com/a/51746662
type: Answer
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90494568
has body: I think the easiest way would be to just type the word in quotes and check in the file immediately without a loop: 'and' in open(r'C:\Users\user\Desktop\something.csv').read().split() gives: True Or if you know what words you want to check, you can pass them in a list and check them with this code to categorise them in found and not found categories like this: li = ['area','keep','have','sky'] #make a list with the words you want to check for i in li: if i in open(r'C:\Users\user\Desktop\something.csv').read().split(): print('found:' + i) else: print('not found:' + i) Which gives the following: found:area found:keep found:have not found:sky Or a third way that looks more like your code and also counts how many times it is found: import csv with open(r'C:\Users\user\Desktop\something.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) z=0 ax=csv_file.read().split() if 'and' in ax: print('found') for line in ax: z+=line.count('and') print(z) Which gives: found 191 If the word is in the csv.
has comment: http://stackoverflow.com/comment/90494127
answers question: http://stackoverflow.com/q/51746376

http://stackoverflow.com/a/51740089
type: Answer
accepted answer of: http://stackoverflow.com/q/51740012
answers question: http://stackoverflow.com/q/51740012
upvote count: 4
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/90440449
downvote count: 0
has comment: http://stackoverflow.com/comment/90440327
has body: Use In [263]: df['Y_M'] = pd.date_range( start='1990-01-01', periods=len(df.index), freq='MS').strftime('%Y-%m') In [264]: df Out[264]: product Y_M 0 23.590 1990-01 1 26.931 1990-02 2 24.740 1990-03 3 25.806 1990-04 4 24.364 1990-05 5 24.477 1990-06 6 23.901 1990-07

http://stackoverflow.com/q/51641703
has answer: http://stackoverflow.com/a/51646950
type: UnansweredQuestion
tagged with: selenium
has body: I need to automate some pdf documents downloads with python and selenium. The preferences of chrome and firefox are already done to automate download, but I have a problem with this especific website, it does not download the document automatically, it opens a new tab website: http://sistemas.sefaz.ma.gov.br/certidoes/jsp/emissaoCertidaoNegativa/emissaoCertidaoNegativa.jsf Select CPF/CNPJ and use this number to access the document 22977333000108. After filling the form I get the document in a new tab with the same url like on the screenshot Documment Screenshot (Sorry, had to hide the documments numbers). If I manually download it and rename as PDF file it works fine. How can I download it as a pdf file with selenium? My code is like: urlForm = 'https://sistemas.sefaz.ma.gov.br/certidoes/jsp/emissaoCertidaoNegativa/emissaoCertidaoNegativa.jsf' #loading firefox webdriver with preferences driver = loadDriver( urlForm ) #form filled # Clicking submit button btnSubmit = driver.find_element_by_id('form1:j_id28') btnSubmit.click() time.sleep(3) # switch to new tab driver.switch_to.window(driver.window_handles[-1]) Then I try to download the file with glob like this: certidoes = glob.glob('emissaoCertidaoNegativa*') print(certidoes) but it prints something like: [emissaoCertidaoNegativa.jsf;jsessionid=44297D6C88452FC479FC0E94013D3C0A] and when I try to rename it to pdf I get an empty file... can someone help?
type: Question
has comment: http://stackoverflow.com/comment/90255493
has title: How to automatically download a PDF file from a JSF page
score: 0
answer count: 1
tagged with: python
tagged with: download

jinja2
tags question: http://stackoverflow.com/q/51766916
tags question: http://stackoverflow.com/q/51652591
tags question: http://stackoverflow.com/q/51763332
tags question: http://stackoverflow.com/q/51783658
tags question: http://stackoverflow.com/q/51707419
tags question: http://stackoverflow.com/q/51681104
tags question: http://stackoverflow.com/q/51660889
tags question: http://stackoverflow.com/q/51742163
tags question: http://stackoverflow.com/q/51676630
tags question: http://stackoverflow.com/q/51639816
tags question: http://stackoverflow.com/q/51698402
tags question: http://stackoverflow.com/q/51649710
type: Tag
tags question: http://stackoverflow.com/q/51726405
tag name: jinja2
tags question: http://stackoverflow.com/q/51733792
tags question: http://stackoverflow.com/q/51687362
tags question: http://stackoverflow.com/q/51746303
tags question: http://stackoverflow.com/q/51735093

http://stackoverflow.com/q/51792853
duplicate of: http://stackoverflow.com/q/12786102
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51792883
has title: Python: Call a method with a given list of arguments
type: Question
linked to: http://stackoverflow.com/q/12786102
answer count: 2
has answer: http://stackoverflow.com/a/51792884
has body: I am unit-testing my software with PyUnit and find it unfortunate that the assertions provided by mock objects (e.g. mock.assert_called_with) don't seem to provide a way to set a message in case the assertion fails. That's why I want to use a wrapper like this: def wrap_mock_msg(mock_method, *args, msg): try: mock_method(&lt;args here!&gt;) except AssertionError as e: raise AssertionError(e.args, msg) It takes the assertion method of a given mock object as mock_method, the message to be displayed upon failure as msg, and a series of arguments to be passed to the mock_method as args. I need it to be a variable args list, since mock.assert_called_with(arg1, arg2, .., arg_n) can also take any number of arguments, depending on the method I'm trying to mock. Unfortunately, I can't just pass a list of arguments to the mock_method, since it will of course be taken as a single argument. Now, this leads me to the challenge of having to pass the list of arguments to the mock_method as if I had hard-typed it. For example: args = ['an', 'example'] ..should result in the following call: mock_method('an', 'example') Is there any way to achieve this?
score: 0
tagged with: function-call
accepted answer: http://stackoverflow.com/a/51792884
has answer: http://stackoverflow.com/a/51792883

http://stackoverflow.com/comment/90252245
comment on: http://stackoverflow.com/q/51643987
has text: I closed PyCharm. The command shows a python instance, which is strange considering I have no applications running python
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90288257
comment on: http://stackoverflow.com/q/51660481
has text: im running the scraper, in 10 minutes i publish the result, thanks !
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51735090
has answer: http://stackoverflow.com/a/51736367
type: UnansweredQuestion
tagged with: tensorflow
downvote count: 0
score: 1
type: Question
upvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
has title: Input to tf.keras Conv2D layer not of appropriate size
tagged with: python
has body: I am following the steps outlined in the tutorial here I am attempting to run the following code from the tutorial in a cell inside of a Google Colaboratory notebook: import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train = x_train.astype('float32') / 255 x_test = x_test.astype('float32') / 255 model = tf.keras.Sequential() # Must define the input shape in the first layer of the neural network model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(256, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(10, activation='softmax')) # Take a look at the model summary model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=64, epochs=10) # Evaluate the model on test set score = model.evaluate(x_test, y_test, verbose=0) # Print test accuracy print('\n', 'Test accuracy:', score[1]) When I run the cell , I get the following error: Error when checking input: expected conv2d_5_input to have 4 dimensions, but got array with shape (60000, 28, 28) I feel like I am missing something that is fundamental to the usage of a convolutional layer, nonetheless it appears as though this should have worked. I found some similar questions on SO where people recommended manipulating the "input_shape" argument. I've tried changing it to (60000, 28, 28) and also added additional dimensions with values of 1, but nothing has worked so far. Can anyone point out where I might be missing some…

http://stackoverflow.com/q/51745439
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/90451484
linked to: http://stackoverflow.com/q/45811119
downvote count: 1
has comment: http://stackoverflow.com/comment/90450619
has answer: http://stackoverflow.com/a/51745597
type: Question
tagged with: if-statement
duplicate of: http://stackoverflow.com/q/45811119
score: -1
has body: I would like to overwrite a variable according to a specific condition and in the other cases keep its original value. in pseudo code: if age &lt; 2 then id=99, else id I miss the "else id" style sentence raw_data1 = {'id': [1,2,3,5], 'age': [0, np.nan, 10, 2]} df1 = pd.DataFrame(raw_data1, columns = ['id','age']) df1['id'] = np.where(df1['age']&lt;2,99) df1['id']=df['age'].apply(lambda x:99 if x&lt;2)
has title: lambda function of if else statement in python pandas
tagged with: pandas
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/90408288
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51723451
score: 0
has text: Google is your friend.

http://stackoverflow.com/comment/90462872
type: Comment
comment on: http://stackoverflow.com/a/51736020
has text: @Sergei There isn't. `sum` just reduces collection calling `__add__` method.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90260346
comment on: http://stackoverflow.com/a/51645207
score: 0
type: AnswerComment
type: Comment
has text: for anyone who has similar issues related to cx_freeze, I'd recommend **pyinstaller** as described [here](https://medium.com/dreamcatcher-its-blog/making-an-stand-alone-executable-from-a-python-script-using-pyinstaller-d1df9170e263)

http://stackoverflow.com/comment/90554630
comment on: http://stackoverflow.com/a/51798965
has text: @FaizanAli I will not provide any information about that, since other people may think it is a good idea, which is not. One solution is to modify the repository configuration to use the `repo` HTTPS url with credentials in it. Again this avoids any password prompt but you have the credentials in plaintext in your repository configuration. Check [this question on ServerFault](https://serverfault.com/questions/815043/how-to-give-username-password-to-git-clone-in-a-script-but-not-store-credential) for some more information. Obviously you can change this configuration from the notebook...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51792119
has body: I have multiple datasets that I need to be plotted on the same axes. Just an example of the datasets are: Dataset 01 as two separate lists: Waves Values 340 520 341 532 342 536 . . . . 2500 720 Dataset 02 as a dataframe df: Wavelength Data 320 560 350 572 . . . . 2650 780 My attempt at the plot is as follows: fig,ax=plt.subplots(figsize=(15, 10)) ax = plt.plot(x = Waves , y = Values) # list names df.plot(ax=ax, x='Wavelength', y='Data') plt.show() I get the following error: AttributeError: 'list' object has no attribute 'get_figure'
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51792287
tagged with: matplotlib
tagged with: dataframe
has title: Pandas multiple dataset plot error
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/51792287
tagged with: pandas

http://stackoverflow.com/q/51641780
has comment: http://stackoverflow.com/comment/90248181
type: Question
has comment: http://stackoverflow.com/comment/90248249
score: 2
has comment: http://stackoverflow.com/comment/90248804
accepted answer: http://stackoverflow.com/a/51642228
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90248794
has comment: http://stackoverflow.com/comment/90248168
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/90248348
upvote count: 3
has answer: http://stackoverflow.com/a/51642228
downvote count: 1
type: AnsweredQuestion
tagged with: swig
has title: How do I make a python class satisfying an interface in SWIG?
has comment: http://stackoverflow.com/comment/90248714
has comment: http://stackoverflow.com/comment/90248318
has body: I'd like to make an object in Python that sastifies a C++ instance using SWIG. Given I have an example like Example.h: struct iCat { virtual int paws() const = 0; }; int pawGiver(const iCat&amp; cat); struct cat : public iCat { int paws() const { return 4; } }; And Example.cpp: #include "Example.h" int pawGiver(const iCat&amp; cat) { return cat.paws(); } And example.i: /* File : example.i */ %module example %{ #include "Example.h" %} %include "Example.h" The above, of course, compile fine. I wrote the below to try to make an iCat in Python, i.e.: import example; class pyCat(example.iCat): def __init__(self): super().__init__() def paws(self): return 3; z = pyCat() example.pawGiver(z) Is what I'm trying to do even possible? Can a Python class fulfill a C++ instance? What am I doing wrong?

http://stackoverflow.com/a/51713469
has comment: http://stackoverflow.com/comment/90388965
has comment: http://stackoverflow.com/comment/90388571
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90388519
accepted answer of: http://stackoverflow.com/q/51713418
has body: Just fetch the results and print. Replace print with select. Cursor only deals with the result set cursor.execute('select convert(varchar, getdate(), 14)') row = cursor.fetchone() if row: print(row)
type: Answer
answers question: http://stackoverflow.com/q/51713418

http://stackoverflow.com/q/51660709
tagged with: urllib
type: Question
score: 5
upvote count: 5
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51951626
favorite count: 0
tagged with: python-3.x
has body: Trying to run several ids through a webservice using python and I am getting the 'http.client.RemoteDisconnected: Remote end closed connection without response' error. I don't want to try/catch this error, I want to investigate why I am getting this response. I have been able to get 400 and 500 level errors raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 413: using the method I am including below, and I understood those errors (so I don't believe the error is related to how I have coded this but who knows) import pandas as pd from urllib.parse import urlencode import urllib.request contact = "" url = 'https://www.uniprot.org/uploadlists/' mouse_ten_tissues = pd.read_csv('Z:\\\mouse_data\\refex\\RefEx_expression_RNAseq10_mouse_PRJNA30467.tsv', delimiter='\t', encoding='utf-8') mouse_ten_refseq = mouse_ten_tissues['NCBI_RefSeqID'].to_string() query_mouse_human_refseq_id_params = { 'from': 'REFSEQ_NT_ID', 'to': 'GENENAME', 'format': 'tab', 'query': mouse_ten_refseq } query_mouse_human_refseq_id_data = urlencode(query_mouse_human_refseq_id_params).encode("utf-8") query_mouse_human_refseq_id_request = urllib.request.Request(url, query_mouse_human_refseq_id_data) query_mouse_human_refseq_id_request.add_header('User-Agent', 'Python %s' % contact) query_mouse_human_refseq_id_response = urllib.request.urlopen(query_mouse_human_refseq_id_request) with query_mouse_human_refseq_id_response as f: query_mouse_human_refseq_id_resp = f.read() The error I get is: Traceback (most recent call last): File "C:/Users/me/read_data.py", line 35, in &lt;module&gt; query_mouse_human_refseq_id_response = urllib.request.urlopen(query_mouse_human_refseq_id_request) File "C:\Users\me\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "C:\Users\me\Python\Python37-32\lib\urllib\request.py", line 525, in open response = self._open(req, data) File "C:\Users\me\Python\Python37-32\lib\urllib\request.py", lin…
tagged with: python
has comment: http://stackoverflow.com/comment/90286066
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51951626
has title: Python http.client.RemoteDisconnected
tagged with: http

http://stackoverflow.com/comment/90398290
has text: Then likely you should `pip3` to install.
type: AnswerComment
comment on: http://stackoverflow.com/a/51700245
score: 0
type: Comment

http://stackoverflow.com/q/51674948
type: Question
accepted answer: http://stackoverflow.com/a/51680105
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has title: How can I get Youtube videos after searching through the Youtube api
has comment: http://stackoverflow.com/comment/90313000
has comment: http://stackoverflow.com/comment/90312913
has answer: http://stackoverflow.com/a/51680105
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has body: I want to make a python program that uses Youtube's api. The thing that I want to do is searching Youtube videos and showing the results in my program. Program gonna run like this: There is gonna be a textbox you write something and hit enter then you'll see the Youtube results below . What should I do for doing this in python or is this impossible?
tagged with: youtube-api
downvote count: 1

http://stackoverflow.com/q/51697937
tagged with: python
has comment: http://stackoverflow.com/comment/90357378
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2697640
has answer: http://stackoverflow.com/a/51698085
tagged with: multiprocessing
type: Question
answer count: 2
tagged with: race-condition
accepted answer: http://stackoverflow.com/a/51698085
has body: I'm trying to learn how to implement multiprocessing for computing Monte Carlo simulations. I reproduced the code from this simple tutorial where the aim is to compute an integral. I also compare it to the answer from WolframAlpha and compute the error. The first part of my code has no problems and is just there to define the integral function and declare some constants: import numpy as np import multiprocessing as mp import time def integrate(iterations): np.random.seed() mc_sum = 0 chunks = 10000 chunk_size = int(iterations/chunks) for i in range(chunks): u = np.random.uniform(size=chunk_size) mc_sum += np.sum(np.exp(-u * u)) normed = mc_sum / iterations return normed wolfram_answer = 0.746824132812427 mc_iterations = 1000000000 But there's some very spooky stuff that happens in the next two parts (I've labelled them because it's important). First (labelled "BLOCK 1"), I do the simulation without any multiprocessing at all, just to get a benchmark. After this (labelled "BLOCK 2"), I do the same thing but with a multiprocessing step. If you're reproducing this, you may want to adjust the num_procs variable depending on how many cores your machines has: #### BLOCK 1 single_before = time.time() single = integrate(mc_iterations) single_after = time.time() single_duration = np.round(single_after - single_before, 3) error_single = (wolfram_answer - single)/wolfram_answer print(mc_iterations, "iterations on single-thread:", single_duration, "seconds.") print("Estimation error:", error_single) print("") #### BLOCK 2 if __name__ == "__main__": num_procs = 8 multi_iterations = int(mc_iterations / num_procs) multi_before = time.time() pool = mp.Pool(processes = num_procs) multi_result = pool.map(integrate, [multi_iterations]*num_procs) multi_result = np.array(multi_result).mean() multi_after = time.time() multi_duration = np.round(multi_after - multi_before, 3) error_multi = (wolfram_answer - multi_result)/wolfram_answer print(num_procs, "threads with", multi_iterations, "it…
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90357436
favorite count: 0
possible better answer: http://stackoverflow.com/a/51698127
has title: Python: Very strange behavior with multiprocessing; later code causes "retroactive" slowdown of earlier code
upvote count: 2
has answer: http://stackoverflow.com/a/51698127
tagged with: multithreading

http://stackoverflow.com/a/51761619
has comment: http://stackoverflow.com/comment/90482470
type: Answer
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90482313
has body: import pandas as pd df= pd. read_csv('breast-cancer-wisconsin.data.txt') # Give commands to extract the directory like getcwd() #like , data_path = os.path.join(os.getcwd(), 'data') file location = 'C:\Users\qeee11\Downloads\breast-cancer-wisconsin.data.txt' getcwd() details Another solution is to use ! shell commands , to change the directory, you can write commands like !cd , and !ls to change the directory to the current file.
has comment: http://stackoverflow.com/comment/90483985
answers question: http://stackoverflow.com/q/51761408
has comment: http://stackoverflow.com/comment/90483435
score: -1
has comment: http://stackoverflow.com/comment/90483068
has comment: http://stackoverflow.com/comment/90485053
has comment: http://stackoverflow.com/comment/90482250

http://stackoverflow.com/q/51779568
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90516850
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51782799
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/51780092
downvote count: 1
type: Question
tagged with: sql-insert
has title: How do I store a picture in a table with python-sqlite3?
tagged with: database
has answer: http://stackoverflow.com/a/51782100
answer count: 3
tagged with: sqlite
has body: I'm trying to store a picture in sqlite3 table. I'm using python and sqlite3. Please let me know if you have a sample code or how to save a picture to a sqlite3 table.
favorite count: 0

http://stackoverflow.com/q/51722864
has comment: http://stackoverflow.com/comment/90406446
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90406729
linked to: http://stackoverflow.com/q/51519101
has title: Reshaping pandas DataFrame Python 3.x
type: Question
upvote count: 4
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/51723228
has answer: http://stackoverflow.com/a/51723207
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/69611802
possible better answer: http://stackoverflow.com/a/51723228
tagged with: python
favorite count: 0
has body: I have a pandas like so: df = cid pid purl tid turl sid surl c1 p1 urlp1 t1 urlt1 s1 urls1 c1 p1 urlp1 t1 urlt1 s2 urls2 c1 p1 urlp1 t1 urlt1 s3 urls3 c2 p2 urlp2 t2 urlt2 s5 urls5 c2 p2 urlp2 t2 urlt2 s6 urls6 What I want is a result something like this: cid uid url c1 p1 urlp1 c1 t1 urlt1 c1 s1 urls1 c1 s2 urls2 c1 s3 urls3 c2 p2 urlp2 c2 t2 urlt2 c2 s5 urls5 c2 s6 urls6 I tried using pd.melt to achieve this but I could only do it partially like so: df2 = pd.melt(df, id_vars = 'cid', value_vars = ['pid','tid','purl'], value_name = 'userid') How to get more columns? I need more columns for value_name? How can I achieve this?
accepted answer: http://stackoverflow.com/a/51723207

http://stackoverflow.com/comment/90890095
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51755666
score: 0
has text: Thanks! Didn't even realize it had a bounty! Plus I learned a lot with IntervalIndex and the numpy solutions :D

http://stackoverflow.com/comment/90645613
type: Comment
has text: @Tina, just call `reset_index()` on the result, so `df.sort_values('C').groupby(['A', 'B'], sort=False).agg({'C': 'sum', 'E': 'last'}).reset_index()`
type: AnswerComment
comment on: http://stackoverflow.com/a/51795419
score: 0

http://stackoverflow.com/a/51727036
has comment: http://stackoverflow.com/comment/134816653
answers question: http://stackoverflow.com/q/51698662
accepted answer of: http://stackoverflow.com/q/51698662
upvote count: 21
score: 21
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/118398399
type: Answer
has body: The answer is slightly different wether you are on a Mac or a Linux (I am not that used of Windows for Python working). Install (MacOS =&gt;) Be sure that the XCode CLI tools are installed on your computer. xcode-select --install Then, to install the virtualenv, you have to enter the following command. pyenv install 3.6.4 Here, you can have some issues regarding the zlib library that is not available. Nevertheless, the XCode CLI should have installed zlib. So you are good to go (it still has some issues on MacOS Mojave nevertheless). Create Virtualenv Then create a new virtualenv for a future use : pyenv virtualenv 3.6.4 v3.6.4 Check Check that everything is ok and that the virtualenv is installed through the following command : pyenv virtualenvs Use Then you just have to use it. For instance for a local use : pyenv local v3.6.4 Check Check that everything is ok: pyenv local and it should show v3.6.4.

http://stackoverflow.com/comment/90326516
has text: It is fine. You will not have any problems. However, if you can compile TensorFlow with AVX2 FMA instructions turned on, it may run “a little bit faster”.
score: 1
comment on: http://stackoverflow.com/q/51681727
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90288921
type: AnswerComment
has text: no i didn't i said >say Hi also this doesn't convert the command because when i did >Say hi it said `discord.ext.commands.errors.CommandNotFound: Command "Say" is not found` so it doesn't convert the command still
comment on: http://stackoverflow.com/a/51661574
type: Comment
score: 0

http://stackoverflow.com/comment/90312299
score: 0
type: Comment
type: QuestionComment
has text: @brunodesthuilliers **settings.DEFAULT_CHARSET** Didn't have this property in settings, but just tried to add it, and it has no effect **Do you have accented characters in your model's fields labels or help_text ?** In model's fields **Do you have this problem on some records only or on all records ?** It reproduces in all records with non-ascii symbols **Do you have the problem if trying to create a new event from the admin ?** Actually yes. Just checked it one more time right now
comment on: http://stackoverflow.com/q/51674134

http://stackoverflow.com/a/51731286
type: AcceptedAnswer
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51729973
accepted answer of: http://stackoverflow.com/q/51729973
downvote count: 0
has body: I assume that the images was uploaded by the user. add this to your urls.py if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) All uploaded files or "media" will have the Media URL. It only makes sense that Media URL must be added to urls.py

http://stackoverflow.com/comment/90352911
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51695664
has text: What's wrong with the code you found? Just replace the `pass` with `if i > 95000: raise ValueError('File is too big')` inside the loop.
score: 0

http://stackoverflow.com/comment/90418077
has text: No, the extension txt / tab delimiting is no problem.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51728207
type: Comment

http://stackoverflow.com/comment/90548995
has text: @SuleymanSuleyman-zade there are third party repository support AMD RADEON GPU https://github.com/ROCmSoftwarePlatform/tensorflow-upstream.
score: 4
comment on: http://stackoverflow.com/a/51730706
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51734113
favorite count: 0
tagged with: slack-api
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90431562
has title: Implementing Conversation Time Measuring App Slack
has body: I'm fairly new to the Slack API. I wanted to write a slack app that does that measures the amount of time spent conversing. More specifically, I want to measure the amount of time between the first and last message sent in conversations with 5+ messages from different people in which the average time between a message and a response is &lt; 1 min Can anyone think of a way to do this with the Slack API? I'm not looking for an implementation; I just want some advice on which API to use and suggestions from those experienced in the Slack API.
has answer: http://stackoverflow.com/a/51736696
tagged with: slack
type: Question
score: -1
downvote count: 2
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/90342607
type: Comment
comment on: http://stackoverflow.com/a/51688692
type: AnswerComment
score: 0
has text: @scyonidee oh oops, that's because the w in `while` was capitalized. Fixed.

http://stackoverflow.com/q/51732146
has comment: http://stackoverflow.com/comment/90425153
has comment: http://stackoverflow.com/comment/90425159
favorite count: 0
has body: I'm debugging my program which converts input excel file to output csv file. In the reformatting part of the program, it gives an error saying IndexError: list index out of range. I put a try-except loop to see where the program is getting stuck. It first gets stuck when the program finds that len(x) is 45500; however, i is only 12500. I'm really confused why the program would get stuck at this point since i should be in the range of len(x). Furthermore, when the break in the except portion of the loop is removed to allow the program run to completion, the except loop keeps printing out len(x) which is 45500 and i which finally ends at 45499. Even then, i should be in the range. Make_csv is the function where the problem is occurring; the 2 functions above it is where the matrix is being created. Matrix[0] is a 1 x 45500 matrix reading the first column of data from the excel input file. Matrix[1] is a 1 x 12500 matrix reading the second column of the file. Any help is appreciated. def create_mat(columns, sets): matrix = [] for i in range(sets): ncolT = "Time%d" % (i + 1) # from 1 to .. ncolD = "Data%d" % (i + 1) # from 1 to .. if len(columns[ncolT]) == len(columns[ncolD]): length = len(columns[ncolT]) x = [] y = [] # read the time print(ncolD + '--' + ncolT) svline = 0 for j in columns[ncolT]: svline = svline + 1 print(svline) j = j.replace(',', '.') ''' while True: print(j) except ValueError,j: print("error") ''' print(j) try: fNum = round(float(j), 1) except ValueError: print("error") x.append(fNum) # x.append(fNum+0.1) # read the values measured for j in columns[ncolD]: try: j = j.replace(',', '.') fNum = float(j) y.append(fNum) except ValueError: print("error") matrix.append(x) matrix.append(y) else: print("Column sizes are not matching") return matrix def unify_dataset(matrix, sets): uni_x = [] uni_y = [] dt = 0 dy = 0 # align y values at zero dy = matrix[1][0] # unify partial measurements for i in range(sets): cur_x = matrix[2 * i] cur_y = matrix[2 * i + 1] if…
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90426330
has comment: http://stackoverflow.com/comment/90425152
has title: Python List Index Out of Range When In Range
score: 0
has comment: http://stackoverflow.com/comment/90425171
upvote count: 1
downvote count: 1
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90460156
type: Comment
comment on: http://stackoverflow.com/a/51740383
type: AnswerComment
has text: I corrected the answer. With the recursive function it will work. Now I also tested it completely ;)
score: 0

http://stackoverflow.com/comment/90395904
has text: Python 2 and Python 3 differ in syntax for strings. An accurate answer needs to know if `s` is a Python 2 byte string or a Python 3 Unicode string.
type: QuestionComment
comment on: http://stackoverflow.com/q/51707067
score: 0
type: Comment

http://stackoverflow.com/comment/90542456
type: Comment
comment on: http://stackoverflow.com/a/51735438
type: AnswerComment
has text: I added some links to installed packages in the virtualenv. This seemed to workaround the problems so far (still building.). Not sure if this is helpful, as it is does not fully isolate the installation to a virtualenv.
score: 0

http://stackoverflow.com/a/70388018
answers question: http://stackoverflow.com/q/51793744
score: 2
upvote count: 2
has body: # -*- coding: utf-8 -*- from fabric import task from invoke import run as local @task(default=True) def testwxmsg(c): local("pytest --reuse-db --no-migrations tests/weixin/test_release_accrual.py")
downvote count: 0
type: Answer

http://stackoverflow.com/q/51697644
upvote count: 4
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/47434610
has answer: http://stackoverflow.com/a/53029496
has comment: http://stackoverflow.com/comment/90358023
has comment: http://stackoverflow.com/comment/90357255
favorite count: 0
linked to: http://stackoverflow.com/q/33161030
tagged with: python-3.x
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/53029496
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/90356878
score: 4
has answer: http://stackoverflow.com/a/51698287
tagged with: performance
has comment: http://stackoverflow.com/comment/90369214
has comment: http://stackoverflow.com/comment/90454693
has title: Python: improving performance of a for loop with function call inside that depends on loop index only
accepted answer: http://stackoverflow.com/a/51698287
has comment: http://stackoverflow.com/comment/90356818
has comment: http://stackoverflow.com/comment/90357321
has comment: http://stackoverflow.com/comment/90357209
has body: I am guilty of writing code in python as if it were Fortran. I am rewriting many parts of a long code already written by myself in Fortran, because i want to extend the code significantly and it is MUCH easier to extend in python for proof of concept work. If it can be sped up enough however, I will simply use python I am not actually interested in turning the crank on the programs over and over. Once an idea is proven to work, I move on to the next problem. This is why I wish to work in python. Unfortunately, right now, it takes several weeks to run as written in python. Even an order of magnitude speedup on the following for loop would make it a feasible testing platform. A similar question for the R language has been posed Improving loop performance with function call inside but surprisingly I don't see one for python. This one is similar but the function in the for loop has dependencies, which mine does not Improve performance of a for loop in Python (possibly with numpy or numba) A huge bottleneck is a single for loop Simple Code import numpy as np part = 3 # a random index of an array, fixed here for example purposes nmol = 1000 energy = np.zeros((nmol),dtype=np.float_) for i in range(nmol): energy[i] = np.where( part != i,function(part,i),0.0) # if i = part, energy = 0.0 speeding up the function itself is another and separate problem. There must be a way to use numpy or another method to run all calls simultaneously For example purposes lets say def function(i,j): for k in range(100000): # this loop is simply to make the time about a second or 2 ener = (i + j) * (i * j) # entirely arbitrary and not my real problem return ener In reality my function calls several function that depend on part and "i". The full working example is: import numpy as np import time as time def function(i,j): for k in range(10000): # this loop is simply to make the time about a second or 2 ener = (i + j) * (i * j) # entirely arbitrary and not my real problem return ener part = 3 # a …
has comment: http://stackoverflow.com/comment/90358134

http://stackoverflow.com/a/62290316
type: Answer
answers question: http://stackoverflow.com/q/51786133
upvote count: 0
has body: Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) import numpy as np np_1= np.arange(15).reshape(5,3) np_2=np.arange(6).reshape(3,2) np.matmul(np_1,np_2)
score: -1
downvote count: 1

http://stackoverflow.com/a/51716845
has comment: http://stackoverflow.com/comment/90465605
answers question: http://stackoverflow.com/q/51716708
downvote count: 0
has body: The problem is that include_package_data=True doesn't mean what you think it means (or what most reasonable people would think it means). The short version is, just get rid of it. From the docs: If set to True, this tells setuptools to automatically include any data files it finds inside your package directories that are specified by your MANIFEST.in file. For more information, see the section below on Including Data Files. If you follow the link, you'll see that it in fact makes setuptools ignore whatever you told it explicitly in package_data, and instead look for every file mentioned in MANIFEST.in and find it within your directory tree (or source control tree): If using the setuptools-specific include_package_data argument, files specified by package_data will not be automatically added to the manifest unless they are listed in the MANIFEST.in file. And, since you don't have a MANIFEST.in, this means you end up with nothing. So, you want to do one of two things: Remove include_package_data=True. Create a MANIFEST.in and remove package_data=…. This is all complicated by the fact that there are lots of examples and blog posts and tutorials left over from the distribute days1 that are just plain wrong for modern setuptools. In fact, there are a whole lot more out-of-date and wrong posts out there than correct ones. The obvious answer is to just only use the tutorials and examples from the PyPA on pypa.org… but unfortunately, they haven't get written tutorials that cover anywhere near everything that you need. So, often, you pretty much much have to read old tutorials, then look up everything they tell you in the reference docs to see which parts are wrong. 1. IIRC, in distribute, the include_package_data=True would cause your extra files to get added to an sdist, just not to anything else. Which still sounds useless, right? Except that you could make your egg and other distributions depend on building the sdist then running a script that generates the MANIFEST.in p…
type: Answer
has comment: http://stackoverflow.com/comment/90463586
score: 1
has comment: http://stackoverflow.com/comment/90395126
upvote count: 1
has comment: http://stackoverflow.com/comment/90395008

http://stackoverflow.com/comment/90279921
type: Comment
has text: It's unclear from your question what you want. `if 0 in amount or 1 in amount` is clearly wrong. Do you want to check if the `amount` is equal to either `0` or `1`? In that case, write `if amount == 0 or amount ==1:`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51658123

http://stackoverflow.com/a/51773836
type: Answer
has comment: http://stackoverflow.com/comment/106673836
has comment: http://stackoverflow.com/comment/90508354
answers question: http://stackoverflow.com/q/51772908
accepted answer of: http://stackoverflow.com/q/51772908
has comment: http://stackoverflow.com/comment/90508182
score: 26
upvote count: 26
has comment: http://stackoverflow.com/comment/90510237
has comment: http://stackoverflow.com/comment/134363670
has comment: http://stackoverflow.com/comment/90509750
type: AcceptedAnswer
downvote count: 0
has body: You can use pyspark.sql.functions.percent_rank() to get the percentile ranking of your DataFrame ordered by the timestamp/date column. Then pick all the columns with a rank &lt;= 0.8 as your training set and the rest as your test set. For example, if you had the following DataFrame: df.show(truncate=False) #+---------------------+---+ #|date |x | #+---------------------+---+ #|2018-01-01 00:00:00.0|0 | #|2018-01-02 00:00:00.0|1 | #|2018-01-03 00:00:00.0|2 | #|2018-01-04 00:00:00.0|3 | #|2018-01-05 00:00:00.0|4 | #+---------------------+---+ You'd want the first 4 rows in your training set and the last one in your training set. First add a column rank: from pyspark.sql.functions import percent_rank from pyspark.sql import Window df = df.withColumn("rank", percent_rank().over(Window.partitionBy().orderBy("date"))) Now use rank to split your data into train and test: train_df = df.where("rank &lt;= .8").drop("rank") train_df.show() #+---------------------+---+ #|date |x | #+---------------------+---+ #|2018-01-01 00:00:00.0|0 | #|2018-01-02 00:00:00.0|1 | #|2018-01-03 00:00:00.0|2 | #|2018-01-04 00:00:00.0|3 | #+---------------------+---+ test_df = df.where("rank &gt; .8").drop("rank") test_df.show() #+---------------------+---+ #|date |x | #+---------------------+---+ #|2018-01-05 00:00:00.0|4 | #+---------------------+---+
has comment: http://stackoverflow.com/comment/110425864

http://stackoverflow.com/comment/90389976
comment on: http://stackoverflow.com/a/51713216
type: Comment
has text: Again, according to documentation: "It’s likely that you would need to export some custom fields over the API. This can be done by adding a list of fields to be exported into the api_fields attribute for each page model." or you can use a custom serializer: "Serialisers are used to convert the database representation of a model into JSON format. You can override the serializer for any field using the serializer keyword argument." - http://docs.wagtail.io/en/v2.0/advanced_topics/api/v2/configuration.html#adding-custom-page-fields
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90357295
type: Comment
has text: That looks like it will work, but I want to do it 'in place' within an svg file... that code does it print out the whole file whether the line is matched or not?
comment on: http://stackoverflow.com/a/51697882
score: 0
type: AnswerComment

http://stackoverflow.com/a/51791615
type: Answer
has body: I think this should work: topic = Topic.objects.get(1) members = GroupMember.objects.filter(group__in = topic.groups.all()) Can refer the django's documentation on in here: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#in
score: 1
accepted answer of: http://stackoverflow.com/q/51791455
answers question: http://stackoverflow.com/q/51791455
has comment: http://stackoverflow.com/comment/90541349
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90541058
has comment: http://stackoverflow.com/comment/90541473

http://stackoverflow.com/comment/90286856
has text: It doesn't download the file if I pasted the signed url in my browser. I suppose this is because it is kept inside a private s3 bucket and I do not own that bucket
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51660664

http://stackoverflow.com/a/64098479
has body: ImageDataGenerator class ensures that the model receives new variations of the images at each epoch. But it only returns the transformed images and does not add it to the original corpus of images. If it was, in fact, the case, then the model would be seeing the original images multiple times which would definitely overfit our model. https://www.analyticsvidhya.com/blog/2020/08/image-augmentation-on-the-fly-using-keras-imagedatagenerator/
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51748514
downvote count: 0

http://stackoverflow.com/comment/90508883
type: QuestionComment
comment on: http://stackoverflow.com/q/51773495
has text: So I should transform it in a list of numbers like [1,2,3,4]? I tought it should recieve a list of tuples because that's what the sklearn returned to me. everything has the same size and I'm not sure if it would work the same way if I don't send them in pairs.
score: 0
type: Comment

http://stackoverflow.com/comment/90502613
type: Comment
comment on: http://stackoverflow.com/a/51771677
has text: ``Cacheable`` only has to fully implement ``ICacheable`` if ``Cacheable`` is a *concrete* subclass and gets instantiated. A virtual subclass does not inherit anything, including the ABC consistency checks. A concrete but incomplete subclass is just a more specialised yet still abstract base class.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90505336
type: Comment
comment on: http://stackoverflow.com/q/51754172
score: 0
type: QuestionComment
has text: Why are you not want to use wxErlang?

http://stackoverflow.com/comment/90392761
type: QuestionComment
comment on: http://stackoverflow.com/q/51714694
has text: Have you tried to minimize the differences between your two example snippets?
score: 0
type: Comment

http://stackoverflow.com/comment/90287179
has text: I have to use square root for the Pythagorean theorm converting xy components back to a vector form, but in my gravitational acceleration equation I am only squaring. a = k * m / d^2
type: Comment
comment on: http://stackoverflow.com/a/51661723
score: 0
type: AnswerComment

http://stackoverflow.com/q/51777727
has title: Retrieving date range from Pandas HDF5Store
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: hdf5
upvote count: 1
type: Question
has body: I wish to select a date range from my HDFStore using Pandas. I noticed that my datetimes (millisecond frequency) are stored as Unix time with extra right padded zeroes i.e 1514797200002000000. I suspect my where clause is incorrect. This is my reproducible code: import pandas as pd import numpy as np path_file = "hdf5_store.h5" data = np.random.randn(5) cols = ["values"] date_range = pd.date_range('20180101 09:00:00', periods=5, freq='ms') df = pd.DataFrame(data=data, index=date_range, columns=cols) with pd.HDFStore(path_file, mode="w", driver="H5FD_CORE") as store: store.append("df", df, format="table", data_columns=["date_time"], index=False) store.create_table_index("df", columns=["date_time"], kind="full") print(store["df"]) df1 = pd.read_hdf(path_file, "df", where=["date_time&gt;1514797200002000000"]) print(df1)
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51778427
tagged with: hdfstore
favorite count: 0

http://stackoverflow.com/q/51778321
tagged with: python-3.x
has body: I have recently installed Python 3.7 on my Mac and downloaded Atom with the 'Run' script so that I can run Python and its packages on Atom. However, I am not managing to run Python packages in Atom (just in IDLE 3.7). I made a test by just importing pandas into it. I installed the Python packages using 'pip install package_name'. The options that I have to run Python are: The message that appears is: Python packages run successfully only on IDLE 3.7. I might have downloaded other Python versions in the past, but I have already uninstalled and installed again newer ones. I just would like to have one Python version on my Mac - the most recent one. How can I sort out this problem?
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90517195
has title: Why does Python packages run in IDLE 3.7 but not in Atom?
score: 0
has comment: http://stackoverflow.com/comment/90582275
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90530327
answer count: 0

http://stackoverflow.com/q/51734496
has answer: http://stackoverflow.com/a/51734718
linked to: http://stackoverflow.com/q/31649669
tagged with: python
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51735185
score: 1
type: Question
has body: I'm trying to write a simple program to track my attandance to my two university courses this semester. I need to have at least an 80% of attendance to each class of each subject. Each subject has three classes (T,TP and P). After tinkering for a while I've come to find the groupby pandas function: import pandas as pd import sys df = pd.read_csv(sys.argv[1]) g = df.groupby(['Subject','Class']).count() print(g) The source file has a row for each class where I'll note "Presente" when I go. I will also note "Sin Clases" when there is no class due to some external reason. This is what top 5 rows of the source file looks like: Date Day Subject Class Attendance Comments 0 6/8/2018 2 Medieval T Presente NaN 1 6/8/2018 2 Logica T Presente NaN 2 6/8/2018 2 Logica P NaN NaN 3 8/8/2018 4 Logica TP Sin clases Movilización IVE 4 8/8/2018 4 Logica P NaN Movilización IVE This is the current output. What I'm not able to figure is how to perform some kind of operation and add a column. For example, adding a column counting only those rows with value "Presente" for each subgroup. I find myself complicating things too much, i'm afrading i'm missing something. z:\devs\py\asist&gt;python asistb.py asist2q.csv Date Day Attendance Comments Subject Class Logica P 32 32 3 4 T 16 16 4 3 TP 16 16 1 1 Medieval P 16 16 0 0 T 32 32 5 4 TP 16 16 1 1 A tip or hint on how to approach the problem is greatly appreciated. Thanks a lot!
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
has title: Performing operations on data and adding column to groupby results
favorite count: 0

http://stackoverflow.com/q/51642133
has answer: http://stackoverflow.com/a/51642994
has comment: http://stackoverflow.com/comment/90252082
has title: How I can count all elements in 2 or more pages in selenium?
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/90249076
tagged with: python
tagged with: selenium-webdriver
has body: The problem is that I can't count all elements on 2 webpages correctly in Selenium. pages = driver.find_elements(By.CLASS_NAME, "page") #getting list of pages for x in pages: #loop through this list x.click() #click on page number prices += driver.find_elements(By.CLASS_NAME, "final-price") #addition 1pg and 2pg elements print(len(prices)) Result is wrong: it adds 1pg with 1pg, not 1pg with 2pg. tried to insert wait - did not help :( I want to note that page is not reloading, just scroll up and shows new results after clicking on the page 2, it must be using ajax.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90249452
tagged with: selenium
type: Question

http://stackoverflow.com/q/51738520
has answer: http://stackoverflow.com/a/51741578
answer count: 1
downvote count: 1
favorite count: 0
has body: Hello im trying to run my scrapy on a VPS server using docker when i try to run it return an error: performing post-bootstrap initialization ... ok web_1 | 2018-08-08 07:04:03 [scrapy.middleware] INFO: Enabled item pipelines: web_1 | ['tutorial.pipelines.TutorialPipeline'] web_1 | 2018-08-08 07:04:03 [scrapy.core.engine] INFO: Spider opened web_1 | 2018-08-08 07:04:03 [scrapy.core.engine] INFO: Closing spider (shutdown) web_1 | 2018-08-08 07:04:03 [scrapy.core.engine] ERROR: Scraper close failure web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/scrapy/crawler.py", line 82, in crawl web_1 | yield self.engine.open_spider(self.spider, start_requests) web_1 | psycopg2.OperationalError: server closed the connection unexpectedly web_1 | This probably means the server terminated abnormally web_1 | before or while processing the request. web_1 | web_1 | web_1 | During handling of the above exception, another exception occurred: web_1 | web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks web_1 | current.result = callback(current.result, *args, **kw) web_1 | File "/scrapy_estate/tutorial/pipelines.py", line 19, in close_spider web_1 | self.cur.close() web_1 | AttributeError: 'TutorialPipeline' object has no attribute 'cur' web_1 | 2018-08-08 07:04:03 [scrapy.statscollectors] INFO: Dumping Scrapy stats: web_1 | {'finish_reason': 'shutdown', web_1 | 'finish_time': datetime.datetime(2018, 8, 8, 7, 4, 3, 806923), web_1 | 'log_count/ERROR': 1, web_1 | 'log_count/INFO': 6} web_1 | 2018-08-08 07:04:03 [scrapy.core.engine] INFO: Spider closed (shutdown) web_1 | Unhandled error in Deferred: web_1 | 2018-08-08 07:04:03 [twisted] CRITICAL: Unhandled error in Deferred: web_1 | web_1 | 2018-08-08 07:04:03 [twisted] CRITICAL: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/twisted/internet/defer.py"…
tagged with: vps
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: scrapy
has title: Docker scrapy spider AttributeError: 'TutorialPipeline' object has no attribute 'cur'
type: Question
score: -1
tagged with: docker

http://stackoverflow.com/comment/129274174
type: QuestionComment
has text: I would like to know how to dump the python error message to browser page (when in apache development environment, obviously not in production) instead of having to go tail the the log file. Is this possible? Its worth noting that this is easily configured in PHP. What about Python?
score: 0
comment on: http://stackoverflow.com/q/51777546
type: Comment

http://stackoverflow.com/comment/90504361
comment on: http://stackoverflow.com/a/51772704
has text: Yes. It works this way. I checked. I knew that using `from math import *` could be bad decision here. Upvoted! @Suyoung Check this. It will work.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51708268
has comment: http://stackoverflow.com/comment/90379390
has comment: http://stackoverflow.com/comment/90378004
score: 3
has comment: http://stackoverflow.com/comment/90379984
has comment: http://stackoverflow.com/comment/90380850
type: Question
has body: As per splinter docs to Take a full view screenshot: browser = Browser() screenshot_path = browser.screenshot('absolute_path/your_screenshot.png', full=True) I am using the same code but it throws TypeError: screenshot() got an unexpected keyword argument 'full' Here is the code - from splinter import Browser import time with Browser('chrome') as browser: url = "http://www.google.com" browser.visit(url) browser.fill('q', 'List of top IT firms') button = browser.find_by_name('btnG') button.click() browser.screenshot('D:/sss/your_screenshot1.png', full=True) time.sleep(3) browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") browser.screenshot('D:/sss/your_screenshot2.png', full=True) Please help me here. Thanks in advance!
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/54277573
favorite count: 0
has title: Python Splinter : how to take a screenshot of full page?
has comment: http://stackoverflow.com/comment/90380401
has comment: http://stackoverflow.com/comment/90378224
tagged with: python
has comment: http://stackoverflow.com/comment/90379688
tagged with: splinter
type: UnansweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/90380243

http://stackoverflow.com/q/51778832
answer count: 1
linked to: http://stackoverflow.com/q/12019780
favorite count: 0
has comment: http://stackoverflow.com/comment/90517059
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51779009
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
has title: How to extract the text 154 from nested div as per the html provided through Selenium and Python
tagged with: selenium
downvote count: 1
type: Question
has body: I am new to Python web scraping. I am writing a program that tries to capture the number 154 of class named "stat answers col-3" by using selenium library in Python. 154 answers 44 questions Here is my code: from selenium import webdriver driver = webdriver.Chrome(executable_path="/Users/username/Downloads/chromedriver") driver.get("website address") content = driver.find_element_by_xpath('//div[@id="user-card" and @class="stat answers col-3"]').__getattribute__("number") However, I was not able to run the program. Could please anyone point where I am making mistake.
score: -1
has comment: http://stackoverflow.com/comment/90517184
tagged with: css-selectors
has comment: http://stackoverflow.com/comment/90516757
upvote count: 0

http://stackoverflow.com/comment/90287116
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51661554
has text: `db.session.add(foo)` followed by `db.session.commit()`

http://stackoverflow.com/a/51700116
has comment: http://stackoverflow.com/comment/90361674
downvote count: 0
answers question: http://stackoverflow.com/q/51700053
score: 5
type: Answer
has body: When your page is first loaded, there is no request.form dictionary, which is why you get the key error. You need to write an if statement to check if the form was submitted or if the page is being loaded the first time. from flask import redirect, url_for @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': data = Info(request.form['name'], request.form['number1'], request.form['number2']) db.session.add(data) db.session.commit() return redirect(url_for('index')) else: return render_template('index.html')
upvote count: 5

http://stackoverflow.com/q/51672643
tagged with: python
has title: How to plot a new graph in an already existing matplotlib
upvote count: 1
tagged with: plot
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51672809
has body: I have a subplot in python matplotlib,and I want to determine the other subplot based on observations of this subplot. I want to see two subplots, one empty, and after observing the nonempty one, determine an input, input it from the keyboard and have the second subplot generated in the empty space next to the first one. Also maybe do this multiple times reusing the initially empty subplot. What is the best way to do this kind of interactive plot subplot(1,2,1) plt.plot(x_range,points,'o') plt.subplot(1,2,2) #maybe plot some prompt in the second subplot plt.show() #proceed, clean plot subplot(1,2,1) plt.plot(x_range,points,'o') point_chosen = input("choose a point: ") #checking validity plt.bar(range(x), y(point_chosen)) plt.show() I didn't manage to stop the plot as well, plt.show() was blocking. If I used plot.ion() at the beginning it would immediately close the plotting windows.
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51672809
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51676088
has comment: http://stackoverflow.com/comment/90316128
tagged with: curl
possible better answer: http://stackoverflow.com/a/51798120
has answer: http://stackoverflow.com/a/51798120
tagged with: fiware-orion
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51676147
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90316310
has title: Converting Curl command line to python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90315853
downvote count: 0
accepted answer: http://stackoverflow.com/a/51676147
favorite count: 0
has body: I am using the Fiware Orion Context Broker and I want to POST some data using a python script. The command line (which works fine) looks like this: curl -X POST -H "Accept: application/json" -H "Fiware-ServicePath: /orion" -H "Fiware-Service: orion" -H "Content-Type: application/json" -d '{"id": "JetsonTX1", "type": "sensor", "title": {"type": "Text","value": "Init"}, "percentage": { "type": "Text", "value": "0%"}}' "http://141.39.159.63:1026/v2/entities/" My Python script: import requests import json url = 'http://141.39.159.63:1026/v2/entities/' data = '''{ "title": { "value": "demo", "type": "Text" }, "percentage": { "type": "Text", "value": "0%" }''' data_json = json.dumps(data) headers = {"Accept": "application/json", "Fiware-ServicePath": "/bonseyes", "Fiware-Service": "bonseyes", "Content-Type": "application/json"} response = requests.post(url, data=data_json, headers=headers) print(response.json()) This is what response.json() returns: {u'description': u'Errors found in incoming JSON buffer', u'error': u'ParseError'} Any ideas how to fix this? Thank you!

http://stackoverflow.com/q/51733223
has answer: http://stackoverflow.com/a/51733308
tagged with: list
has title: Getting error while converting to pandas dataframe from a list
tagged with: dataframe
has body: I am trying to convert a list of values to a dataframe in a single row so the output should be a pandas dataframe with single row but getting object of type 'int' has no len() I tried other SO posts but same error. metadata = [var1, var2, var3, var4, var5] df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5'], data=metadata)
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51733959
has comment: http://stackoverflow.com/comment/90427099
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90427181
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/51774267
has comment: http://stackoverflow.com/comment/90508025
has comment: http://stackoverflow.com/comment/90507745
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has body: You can use sum: records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]] list_order = ['female', 'male'] new_records = sorted(records, key=lambda x:sum(list_order.index(i[1]) for i in x)) Output: [[['Sally', 'female', 1], ['Sally', 'female', 2], ['Sally', 'female', 3]], [['Jack', 'male', 1], ['Jack', 'male', 2], ['Jack', 'male', 3]]]
accepted answer of: http://stackoverflow.com/q/51774221
type: Answer
answers question: http://stackoverflow.com/q/51774221

http://stackoverflow.com/comment/90385975
type: AnswerComment
has text: because the weights update happens after each iteration (batch=1) no need for avg
type: Comment
comment on: http://stackoverflow.com/a/51707861
score: 0

http://stackoverflow.com/a/51677338
has comment: http://stackoverflow.com/comment/90352029
answers question: http://stackoverflow.com/q/51677207
has comment: http://stackoverflow.com/comment/90325889
type: Answer
has body: I will help with the argparse part, so you can focus on your "something" you must do to the images: import os import argparse parser = argparse.ArgumentParser(description='Process some images') parser.add_argument('--input', help='the input directory', required=True) parser.add_argument('--dest', help='the destination', required=True) args = parser.parse_args() for path, dirs, files in os.walk(args.input): for filename in files: fullname = os.path.join(path, filename) result, result_filename = do_something(fullname) result_fullname = os.path.join(args.dest, result_filename) with open(result_fullname, 'wb') as f: f.write(result) This assumes your function do_something will be able to return a result and a new result_filename that will be used to write the file in the --dest directory - if you want to use the same filename just use the filename variable instead.
score: 0

http://stackoverflow.com/q/51695904
possible better answer: http://stackoverflow.com/a/51695935
type: AnsweredQuestion
upvote count: 0
has body: I have tried this key b"\xa9Z\xfe\x16*L\xfaJ\xab\x87\xc3\xdf$:f\xb3U^\xf4Nf\xe8\xc2\x1cZ\xc1\xd8\xdc\xe4h\x98\xac\xa3b\x98\xbc\x9e\xb5\xa8\x8d\xf7n\x1b\xa6\xbfMe\xa4\xd8\xc0\xd9'\x10\x86L?\xd3\xd4\xbd\xc2H\xaa\xe7\x07" Open file in wb mode &gt;&gt;&gt; f = open('privkey.bin', 'wb' ) &gt;&gt;&gt; f.write(key) 64 Any way the file is empty. Why?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51695933
type: Question
tagged with: python
score: -2
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/90353240
has answer: http://stackoverflow.com/a/51695935
has answer: http://stackoverflow.com/a/51695933
has title: How to write bytes to file from Python shell?
has comment: http://stackoverflow.com/comment/90353258

http://stackoverflow.com/q/51688552
has answer: http://stackoverflow.com/a/51694899
type: Question
upvote count: 1
answer count: 1
has body: when i write this code: import pyttsx engine = pyttsx.init() engine.say('hello world ') engine.runAndWait() i get this probleme File "C:/Users/youssef123/PycharmProjects/fgq/ghqsd.py", line 1, in &lt;module&gt; import pyttsx File "C:\Users\youssef123\PycharmProjects\fgq\venv\lib\site-packages\pyttsx\__init__.py", line 18, in &lt;module&gt; from engine import Engine ModuleNotFoundError: No module named 'engine' how can i fix that please
tagged with: pyttsx
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has title: pyttsx error: No module named 'engine'

http://stackoverflow.com/q/51765983
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55909292
tagged with: dataframe
linked to: http://stackoverflow.com/q/28538536
has comment: http://stackoverflow.com/comment/90490676
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51766436
has comment: http://stackoverflow.com/comment/90490968
upvote count: 13
has title: Dropping multiple Pandas columns by Index
accepted answer: http://stackoverflow.com/a/51767407
tagged with: pandas
has answer: http://stackoverflow.com/a/51766101
favorite count: 0
has answer: http://stackoverflow.com/a/51766225
linked to: http://stackoverflow.com/q/24560298
has answer: http://stackoverflow.com/a/51767407
possible better answer: http://stackoverflow.com/a/51766436
downvote count: 0
answer count: 5
linked to: http://stackoverflow.com/q/33042633
score: 13
tagged with: python
has body: I have a large pandas dataframe (>100 columns). I need to drop various sets of columns and i'm hoping there is a way of using the old df.drop(df.columns['slices'],axis=1) I've built selections such as: a = df.columns[3:23] b = df.colums[-6:] as a and b represent column sets I want to drop. The following list(df)[3:23]+list(df)[-6:] yields the correct selection, but i can't implement it with a drop: df.drop(df.columns[list(df)[3:23]+list(df)[-6:]],axis=1) ValueError: operands could not be broadcast together with shapes (20,) (6,) I looked around but can't get my answer. Selecting last n columns and excluding last n columns in dataframe (Below pertains to the error I receive): python numpy ValueError: operands could not be broadcast together with shapes This one feels like they're having a similar issue, but the 'slices' aren't separate: Deleting multiple columns based on column names in Pandas Cheers

http://stackoverflow.com/q/51715277
favorite count: 0
has comment: http://stackoverflow.com/comment/90865143
accepted answer: http://stackoverflow.com/a/51715475
has comment: http://stackoverflow.com/comment/90991623
upvote count: 2
has title: Python Automate the Boring Stuff: Bullet Points can't run program
tagged with: python
has comment: http://stackoverflow.com/comment/90971081
answer count: 4
type: AnsweredQuestion
score: 2
has body: Ok so I'm working on Chapter 6 on Automate the Boring stuff and I'm having trouble understanding how to get it to run the project. It runs but all that comes up is the "Press any key to continue...". It's like I can't input and string for it to work... or at least I think that's how it's supposed to go. I'm not the best with pyperclip or getting things to run yet. Can anyone help me understand how I can get this to work, so I can have some output? I'm not sure how to use the clipboard in the cmd line either, any ideas? #! python3 # bulletPointAdder.py - Adds Wikipedia bullet points to the start # of each line of text on the clipboard. import pyperclip text = pyperclip.paste() # Separate lines and add stars. lines = text.split('\n') for i in range(len(lines)): # loop through all indexes for "lines" list lines[i] = '* ' + lines[i] # add star to each string in "lines" list text = '\n'.join(lines) pyperclip.copy(text) This is the bin file I'm using: @py C:\Users\david\MyPythonScripts\AddingBullets.py %* @pause
has answer: http://stackoverflow.com/a/62193099
type: Question
has answer: http://stackoverflow.com/a/55503295
has answer: http://stackoverflow.com/a/51715475
tagged with: project
downvote count: 0
possible better answer: http://stackoverflow.com/a/62193099
has comment: http://stackoverflow.com/comment/90943406
has answer: http://stackoverflow.com/a/61005327
tagged with: pyperclip
has comment: http://stackoverflow.com/comment/111441675

http://stackoverflow.com/q/51647710
has body: AIM- To predict price per square foot of 4 houses, given their 2 features (namely feature1 and feature2). I have 7 houses with feature1, feature2 and price per square foot provided. The last 4 houses have only "feature1" and "feature2". I know what values should be present there. When i compare that with my [redicted values, it is entirely different. MY CODE - I have a CSV file, that i read and convert it into a pandas data frame from where I train and test the model using LinearRegression. DATA - Here is the snapshot of my data, this is the data i am using, and I need to predict the last 4 "Pricepersqrft" values. PROBLEM- I am unable to get an accuracy of more than 10 percent, which means I am not getting the right "Pricepersqrft" for the last 4 houses. HERE IS MY CODE - import numpy as np import pandas as pd import scipy import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression from sklearn import datasets csvfileData = THE DATA SHOWN IN THE SNAPSHOT dataRead = pd.read_csv(csvfileData) dfCreated = pd.DataFrame(dataRead) #creating a pandas dataframe print(dfCreated) # print(dfCreated.head()) #shows first 5 rows of data frame dfCreated.drop(dfCreated.columns[[0]], axis=1, inplace = True) print(dfCreated) # where_are_NaNs = numpy.isnan(dfCreated) #previous line displayed Nan where no value was present for "Pricepersqrft column" # dfCreated[where_are_NaNs] = 0 #use numpy's isnan and set all Nan to 0 # print(dfCreated) dfCreated.hist(bins = 10, figsize=(20,15)) #plotting histograms using matplotlib plt.show() #creating scatter plots dfCreated.plot(kind="scatter", x= "Feature1", y="Feature2", alpha=0.5) correlationMatrix = dfCreated.corr() #computes correlation between 2 columns print(correlationMatrix["Feature1"].sort_values(ascending=False)) #value that needs to be predicted Y= dfCreated['Pricepersqrft'] print(Y) #training the model and testing, train_test_split expects both dataframes to be…
has comment: http://stackoverflow.com/comment/90259397
score: 0
type: UnansweredQuestion
tagged with: machine-learning
type: Question
tagged with: linear-regression
has title: My Linear Regression model is showing a score of 10 percent, how do i improve it?
has comment: http://stackoverflow.com/comment/90259456
answer count: 1
has comment: http://stackoverflow.com/comment/90259235
has answer: http://stackoverflow.com/a/51649229
tagged with: python

http://stackoverflow.com/comment/90309576
has text: Then I suggest to [edit] your question, and change both the title and main question in the text, to e.g. "What is the use of a plain variable by itself in Python?" That is a slightly different, but hopefully, clearer question than "why".
type: Comment
comment on: http://stackoverflow.com/q/51673352
score: 1
type: QuestionComment

http://stackoverflow.com/a/51757265
has comment: http://stackoverflow.com/comment/90474284
has body: Try this: sedol_list = set() for d in self.holdings_history.keys(): for i in np.arange(0,len(self.holdings_history[d]),1) : sedol_list.add(self.holdings_history[d][i].sedol)) You basically used the set method on a string (which is syntactically right because strings are arrays in python and other languages) so you just get a bunch of non redundant characters from a string. Hopefully this fixed your problem!
has comment: http://stackoverflow.com/comment/90474091
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51757224
answers question: http://stackoverflow.com/q/51757224

http://stackoverflow.com/comment/90281787
has text: I can change the lambdas in the dictionary to be whatever I need them to be. Essentially, I'm just looking for a different lambda if two or more key values match the contents of the list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51658919
score: 0

http://stackoverflow.com/comment/90286498
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51659963
has text: Please have a look now.

http://stackoverflow.com/a/51687952
type: Answer
has body: This one should scale as O(N): def same_count(s): c1 = 0 c2 = 0 l1 = list() l2 = list() n = len(s) for i in range(n): # count forward from start if s[i] == '#': c1 += 1 # count backward from end if s[n - i - 1] == '$': c2 += 1 l1.append(c1) l2.append(c2) # reverse second list l2 = list(reversed(l2)) # find index where counts are the same match = [i for i in range(1,n-1) if l1[i-1] == l2[i+1]] if match: return match[0] else: return None print(same_count('##$$$#')) print(same_count('###$$$##')) print(same_count('#$$')) #output: #2 #None #1
answers question: http://stackoverflow.com/q/51687658
score: 0

http://stackoverflow.com/comment/90472047
type: AnswerComment
type: Comment
has text: Thank you for the detailed response, works fine for me now. I'm new to Python programming and I knew there should be a solution similar to this unless PyCharm blocks any manipulation of the debugger which they don't :)
comment on: http://stackoverflow.com/a/51755680
score: 0

http://stackoverflow.com/comment/90540102
type: Comment
comment on: http://stackoverflow.com/q/51765943
has text: Thanks. Ur solution is worked
score: 0
type: QuestionComment

http://stackoverflow.com/q/51751297
has answer: http://stackoverflow.com/a/51752189
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: python
score: 1
tagged with: python-3.x
has title: Plotting a simple line between two points in Matplotlib
upvote count: 1
accepted answer: http://stackoverflow.com/a/51752189
answer count: 1
tagged with: plot
has body: I want to draw a simple line as show in this figure. Here is what I tried but failed: import matplotlib.pyplot as plt x = [1,10,100,1000,10000] y = [1,10**(-1),10**(-2),10**(-3),10**(-4)] plt.plot(x, y,'gray',linestyle='--',marker='') This code gives me very odd output. I need to make it same as in the figure. I don't have all data points beside I only have those numbers in figure that I posted above.
tagged with: matplotlib

http://stackoverflow.com/a/51832523
has body: After many attempts, I came to realize that the function that I'm trying to call is in infinite loop. To access password_generator() method, I have to do Register().password_generator(). So that's also means __init__ method is called- because of Register(). In the __init()__, I again call Register(). This is why it becomes an infinite loop. To solve this, we have to use: def __init__(self, *args, **kwargs): self.password = self.password_generator()
accepted answer of: http://stackoverflow.com/q/51647581
answers question: http://stackoverflow.com/q/51647581
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51645311
upvote count: 6
answers question: http://stackoverflow.com/q/51645249
has comment: http://stackoverflow.com/comment/90254664
has comment: http://stackoverflow.com/comment/90254816
accepted answer of: http://stackoverflow.com/q/51645249
type: AcceptedAnswer
downvote count: 0
has body: exit isn't in globals() because it isn't a global, it's a builtin. In Python, the "global" namespace is per-module, not system-wide. There's a special "builtins" module that holds the things that are truly system-wide, like the normal builtin functions and a few special things like exit. You can access this module with import builtins. The way the interpreter accesses this module is a little funky. Global lookup works roughly like this: def get_global(global_namespace, name): try: return global_namespace[name] except KeyError: pass try: builtins = global_namespace['__builtins__'] except KeyError: raise NameError(name) if isinstance(builtins, types.ModuleType): builtins = builtins.__dict__ try: return builtins[name] except KeyError: raise NameError(name) There's special code in places like exec, and the internal code for building function objects, that makes sure that if you override the normal globals dictionary, __builtins__ gets copied over (unless you explicitly tell it not to). When the import system builds a module object out of your module source (or compiled .pyc), it calls exec, so every module's globals ends up with the right __builtins__. Most things in the builtins module are there because they're compiled into it (as you'd expect from the name); for CPython, you can see the source in Python/bltinmodule.c. But notice that exit isn't there. In fact, it's injected into the builtins module by the site module, which is imported (unless you disable it) as part of the normal startup sequence. You can see the code that does this in Lib/site.py and Lib/_sitebuiltins.py. And the exit constant says it's injected this way. So, when you type exit in your code, or at the interactive prompt, it's found in globals()['__builtins__']['exit'] or globals()['__builtins__'].__dict__['exit']. But if you want to access it manually, you're better off doing an import builtins and accessed it as builtins.exit. Although really, you rarely want to access builtins.exit anyway; if you…
has comment: http://stackoverflow.com/comment/90254687
has comment: http://stackoverflow.com/comment/90254955
has comment: http://stackoverflow.com/comment/90254764
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/90273953

http://stackoverflow.com/q/51684213
has comment: http://stackoverflow.com/comment/90330765
tagged with: scope
tagged with: python
has title: Python variable scope with specific example
answer count: 0
type: UnansweredQuestion
has body: This question has been ask before, but it is not quite fit my case. right = 0 mistake = 0 plt.figure(figsize=(16,16)) for i in range(test_image_batch.shape[0]): plt.subplot(12,12, i+1) plt.imshow(test_image_batch[i]) plt.axis('off') bestnum = 0.0 bestclass = 0 for j in range(10): if bestnum &lt; batch_prediction_array[i][j]: bestnum = batch_prediction_array[i][j] bestclass = j print("bestclass", bestclass) #only gives the correct maxmimum value when bestclass is declared inside the outer for loop if test_label[i] == bestclass: plt.title(cifar10_labels[bestclass]) right += 1 else: plt.title(cifar10_labels[bestclass] + "!=" + cifar10_labels[test_label[i][0]], color='#ff0000') mistake += 1 This is part of my code that search for maximum prediction value and plot it on the graph. In my understanding, bestclass should have value of the more inner scope, so bestclass should have the same value both when bestclass is first declared inside and outside of for i in range(test_image_batch.shape[0]): However, that is not the case. bestclass only gives the correct maximum value for all of batch_prediction_array[i] when it is declared inside the outer for loop. When bestclass is declared outside the outer for loop, it only print the correct maximum value for the first batch_prediction_array[i]. I am 100 percent sure that bestclass is not declared anywhere else in the code except the code shown above. It is even more strange because I cannot reproduce the same behavior. So my question is what did I miss? I understand LEGB rule, but in this particular case. It does not seem to follow LEGB rule. If this helps at all, I am coming from java background. EDIT: I just found out that when bestclass is declared outside outer for loop, if statement was skipped, but bestclass value was changed to 1. (which is batch_prediction_array[0][3])
type: Question
has comment: http://stackoverflow.com/comment/90330928
has comment: http://stackoverflow.com/comment/90331272
score: 0

http://stackoverflow.com/a/51778516
answers question: http://stackoverflow.com/q/51778480
type: Answer
upvote count: 24
score: 24
has body: Using str.replace would work: df['Grade'] = df['Grade'].str.replace('%', '')
downvote count: 0

http://stackoverflow.com/q/51755136
score: 1
has title: PyCharm updated and now every script gets executed in Python Console
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51857007
type: AnsweredQuestion
tagged with: ubuntu-18.04
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90470632
favorite count: 0
has answer: http://stackoverflow.com/a/51857007
has comment: http://stackoverflow.com/comment/90500643
tagged with: python
has body: This morning when I got into the office, PyCharm said I need to update my IDE, so I updated it to the latest "professional" PyCharm edition. However, whenever I run my code, it now goes to Python Console pane instead of a Run pane appearing. At first, interactive python was completely broken, but after I redownloaded IPython, I got the interactive portion back, but my run is still missing. Please refer to the below pictures. As you can see, in the new PyCharm, the title of the runs are called "Python Console (1), Python Console (2), etc with no names, and it is ran in Python console. In the old PyCharm, the file had its respective name and was in the "4. Run" category on the bottom left of PyCharm, and not in the Console section. New PyCharm after IDE Update Old PyCharm with Run Additional Info: I am using Python 3.6, PyCharm Professional Edition, Ubuntu 18.04.
tagged with: pycharm

http://stackoverflow.com/a/51640350
upvote count: 1
has comment: http://stackoverflow.com/comment/90245202
score: 1
has comment: http://stackoverflow.com/comment/90245187
has body: Use the end= parameter. This will redefine what print appends. It looks like your string in question has a trailing newline in it and that isn't being reflected correctly in your editor. print('a', end="") letter = input('letter: ') print(letter)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90245273
answers question: http://stackoverflow.com/q/51640322
has comment: http://stackoverflow.com/comment/90245130
has comment: http://stackoverflow.com/comment/90245305
accepted answer of: http://stackoverflow.com/q/51640322
has comment: http://stackoverflow.com/comment/90245288
type: Answer
has comment: http://stackoverflow.com/comment/90245234
has comment: http://stackoverflow.com/comment/90245253

http://stackoverflow.com/a/51734842
has body: You need to parse each number one at a time. You are trying to input all of the numbers at once, which will not work. Try this: limit=int(input()) answer=1 a=[] numbers = input() toParse = numbers.split(' ') #breaks input string into individual numbers for i in range(toParse): data=int(toParse[i]) a.append(data) for j in a: answer = answer*j+10**9+7 print(answer) I changed your code to 1) take in the input numbers before the loop, then 2) split them into a list where each element is one of the numbers in your original string, which 3) can then be parsed as data in your loop.
type: Answer
answers question: http://stackoverflow.com/q/51734769
score: 0

http://stackoverflow.com/comment/90408176
comment on: http://stackoverflow.com/a/51718371
score: 0
type: AnswerComment
type: Comment
has text: Thank you for your help, every thing is working ok now

http://stackoverflow.com/comment/90538598
score: 0
has text: @Ef.O Unfortunately I have little if any knowledge of R.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51790340

http://stackoverflow.com/comment/90459560
has text: @LaurenzAlbe Thanks for your help. I can't find the error message in the kernel log. I'm loooking in /etc/rsyslog.d/50-default.conf ? Is this the right one? If not, where should I look?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51749603

list-comprehension
tags question: http://stackoverflow.com/q/51706165
tags question: http://stackoverflow.com/q/51745416
tags question: http://stackoverflow.com/q/51747260
tags question: http://stackoverflow.com/q/51698925
tags question: http://stackoverflow.com/q/51798705
tag name: list-comprehension
tags question: http://stackoverflow.com/q/51663167
tags question: http://stackoverflow.com/q/51640610
type: Tag
tags question: http://stackoverflow.com/q/51752634
tags question: http://stackoverflow.com/q/51764971
tags question: http://stackoverflow.com/q/51731684
tags question: http://stackoverflow.com/q/51666955
tags question: http://stackoverflow.com/q/51641379
tags question: http://stackoverflow.com/q/51711985
tags question: http://stackoverflow.com/q/51765912

http://stackoverflow.com/a/51717579
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51717004
has body: The best way is to use format() and the symbol {} in your strings. It's also more portable, and works with all kinds of objects, including numbers and strings. And it is way clearer, your text message keeps entirely there, look at that! print("There was once a man named {},".format(character_name)) print("he was {} years old.".format(character_age)) print("He really liked the name {},".format(character_name)) print("but didn't like being {}.".format(character_age))

http://stackoverflow.com/q/51753825
has body: I have Python 3.6 installed using Anaconda as the sole Python instance on my computer. Following the installation instructions on TensorFlow, I created a conda environment called tensorflow running Python 3.5, activated it and ran pip install --ignore-installed --upgrade tensorflow to install tensorflow. While inside the environment I am able to validate the installation by running import tensorflow, which works fine. To run my scripts in this environment in VS Code, I followed the instructions on configuring Python environments and selected the interpreter such that it corresponds to the conda environment I created. This adjusts the python path variable in VS Code's user settings accordingly. { "window.zoomLevel": 2, "files.autoSave": "off", "workbench.colorTheme": "Abyss", "python.pythonPath": "C:\\Users\\osharaki\\Anaconda3\\envs\\tensorflow\\python.exe" } However, when I try to run a script inside VS Code that imports tensorflow I still receive the following error: ModuleNotFoundError: No module named 'tensorflow' The resource that came closest to answering my issue was this. What am I missing?
tagged with: visual-studio-code
linked to: http://stackoverflow.com/q/43351596
has comment: http://stackoverflow.com/comment/90538626
score: 0
has title: Modules installed in Conda environment not being found by VS code
tagged with: python
has comment: http://stackoverflow.com/comment/116430992
has comment: http://stackoverflow.com/comment/108700763
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90615637
has comment: http://stackoverflow.com/comment/90532601
has comment: http://stackoverflow.com/comment/90505054
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90652414
has comment: http://stackoverflow.com/comment/90552436
tagged with: conda
type: Question

http://stackoverflow.com/q/51769590
has comment: http://stackoverflow.com/comment/90500937
has comment: http://stackoverflow.com/comment/90500043
score: 0
has comment: http://stackoverflow.com/comment/90501450
has answer: http://stackoverflow.com/a/51769981
has title: Using request args in Flask for a variable URL and second value returns as none
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90505930
has comment: http://stackoverflow.com/comment/90500441
has comment: http://stackoverflow.com/comment/90500300
has comment: http://stackoverflow.com/comment/90499221
has comment: http://stackoverflow.com/comment/90505830
tagged with: flask
has comment: http://stackoverflow.com/comment/90501072
has comment: http://stackoverflow.com/comment/90498880
has comment: http://stackoverflow.com/comment/90500716
has comment: http://stackoverflow.com/comment/90500862
answer count: 1
has body: URL: http://127.0.0.1:5000/login?apple=exec&amp;basket=app Apple value returns as exec but basket value returns as None instead of app. Problem with picking up second value from flask import Flask, request, render_template app = Flask(__name__) @app.route('/login', methods=['GET']) def login(): a = str(request.args.get('apple', type = str)) b = str(request.args.get('basket', type = str)) return (b) if __name__ == "__main__": app.run()
favorite count: 0
has comment: http://stackoverflow.com/comment/90501980
linked to: http://stackoverflow.com/q/47071256
has comment: http://stackoverflow.com/comment/90500753
has comment: http://stackoverflow.com/comment/90501119
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90498694
linked to: http://stackoverflow.com/q/25065900
has comment: http://stackoverflow.com/comment/90500108

http://stackoverflow.com/comment/90477985
comment on: http://stackoverflow.com/q/51759135
score: 0
type: Comment
type: QuestionComment
has text: After rebooting, however, python started working in general but not for the original code that caused the issue in the first place.

sparkle
tag name: sparkle
type: Tag
tags question: http://stackoverflow.com/q/51704175

http://stackoverflow.com/comment/128781560
comment on: http://stackoverflow.com/a/51710151
has text: @MartijnPieters that's not the point. The point is that Optional doesn't mean what you say it means.
type: AnswerComment
type: Comment
score: 3

http://stackoverflow.com/comment/90521319
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51741025
has text: You need to work your way through the tutorial to familiarise yourself with how the library works.

http://stackoverflow.com/comment/90311659
has text: The `csv` module isn't quite as high-level as `pandas`. You need to construct the `dict` yourself. Use `csv.reader` to get 2-lists and build up your dict row by row: `mydict[row[0]] = row[1]`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51673981
score: 0

http://stackoverflow.com/q/51742446
has comment: http://stackoverflow.com/comment/90449091
answer count: 0
tagged with: tensorflow
has title: Getting the .whl for tensorflow to support all CPU instruction sets
type: Question
score: 0
has body: When I start jupyter-notebook I see: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA When I go to the tensorflow GitHub project page intending to raise an issue about supporting all CPU instruction sets, it tells me to ask on SO first (so here I am). Why wouldn't tensorflow be compiled to support all CPU instruction sets? How would I contact the .whl packager to ask them to include all CPU instruction sets? (I signed up to pypi.org but I don't seem to be able to message people through there.
has comment: http://stackoverflow.com/comment/90449288
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51751589
tagged with: visual-studio
answer count: 0
has body: I'm using visual studio code running Python 3 and every time I run debug in the terminal window it shows my entire file directory for the current .py file I'm working on. Here's an example: Maxs-MBP:Exercise Files maxcalcroft$ cd "/Users/maxcalcroft/Desktop/Exercise Files" ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" python /Users/maxcalcroft/.vscode/extensions/ms-python.python-2018.6.0/pythonFiles/PythonTools/visualstudio_py_launcher.py "/Users/maxcalcroft/Desktop/Exercise Files" 52452 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput "/Users/maxcalcroft/Desktop/Exercise Files/Chap01/hello-working.py" Hello, World. Maxs-MBP:Exercise Files maxcalcroft$ This was just a simple print "Hello, World." command yet I get all this extra directory stuff. One answer I saw showed going into the launch.json file and amending the cwd but there's not an option for me to change that in my launch.json file.
upvote count: 1
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/90462987
has comment: http://stackoverflow.com/comment/90463224
score: 1
has title: How do I stop the file directory printing in my debug terminal every time I run debug?
has comment: http://stackoverflow.com/comment/90463316
tagged with: launch
has comment: http://stackoverflow.com/comment/90465448
downvote count: 0
has comment: http://stackoverflow.com/comment/90463062
favorite count: 0
tagged with: terminal
has comment: http://stackoverflow.com/comment/90465499
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51707202
has comment: http://stackoverflow.com/comment/90375527
type: Answer
has body: In fact, you misunderstood what a class variable is. When you're using instance.somevar = [4, 5, 6] it doesn't mutate the value that you think. Instead, what you'd need to do is change the actual class variable like so, instance = Some([1, 2, 3]) instance.somevar = [4, 5, 6] print(instance.read()) instance2 = Some([4, 5, 6]) print(instance.read()) &gt;&gt;&gt;&gt; [1, 2, 3] [4, 5, 6] Indeed, don't forget that by using the @classmethod decorator, cls is actually the class itself. Therefore, in your case, cls.somevar will be shared across all classes. Also, since you decorated your __init__, you'll be changing the value of that variable every time you will instantiate the class as shown empirically in my above example. Note that this is probably not the implementation you are looking for. You probably want to be using self like this instead, class Some: def __init__(self, somevar): self.somevar = somevar def read(self): return self.somevar instance = Some([1, 2, 3]) print(instance.read()) instance.somevar = [4, 5, 6] print(instance.read()) &gt;&gt;&gt;&gt; [1, 2, 3] [4, 5, 6]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51707081
answers question: http://stackoverflow.com/q/51707081
has comment: http://stackoverflow.com/comment/90375565
score: 5
has comment: http://stackoverflow.com/comment/90375677
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/51652872
tagged with: recaptcha
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
has body: I have a flask application, where I want to add a recaptcha field. I use it to verify, that an email can be sent. here is my code so far: from flask import render_template, request, flash, session, url_for, redirect from flask import Flask from flask_mail import Mail, Message from flask_recaptcha import ReCaptcha app.config.update({'RECAPTCHA_ENABLED': True, 'RECAPTCHA_SITE_KEY': '6LdJ4GcUAAAAAN0hnsIFLyzzJ6MWaWb7WaEZ1wKi', 'RECAPTCHA_SECRET_KEY': 'secret-key'}) app=Flask(__name__) recaptcha = ReCaptcha(app=app) mail_settings = { "MAIL_SERVER": 'smtp.gmail.com', "MAIL_PORT": 465, "MAIL_USE_SSL": True, "MAIL_USERNAME": 'USERNAME', "MAIL_PASSWORD": 'PASSWORD' } app.config.update(mail_settings) mail = Mail(app) @app.route('/') def index(): return render_template('index.html') @app.route('/mail', methods=['GET', 'POST']) def send_mail(): r = requests.post('https://www.google.com/recaptcha/api/siteverify', data = {'secret' : 'secret_key', 'response' : request.form['g-recaptcha-response']}) google_response = json.loads(r.text) print('JSON: ', google_response) if google_response['success']: msg = Message('Thank you for contacting me', sender='kristofferlocktolboll@gmail.com', recipients = [request.form['email']]) msg.body ='sut den' mail.send(msg) return render_template('index.html') else: return render_template('index.html') app.run(debug=True) The problem is that whenever I have the flask_recaptcha import ReCaptcha I get the following error: it looks like the import statement is incorrect, but since I'm not using WTForms, I don't know what do else. Whenever I remove the import statement it gives a syntax error instead (which makes sense) Usage: flask run [OPTIONS] Error: The file/path provided (routes) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py
has title: flask getting an error, when importing recaptcha
type: Question
tagged with: flask
upvote count: 1

http://stackoverflow.com/comment/90505657
comment on: http://stackoverflow.com/a/51773335
type: AnswerComment
type: Comment
has text: `await` says that your code is going to wait for a coroutine to finish, but it's okay if other code runs in the meantime. It was introduced in [PEP 492](https://www.python.org/dev/peps/pep-0492/). If that's a little too much of a technical document, I recommend searching for Python tutorials covering coroutines, async, and await. See also [Tasks and Coroutines](https://docs.python.org/3/library/asyncio-task.html) from the documentation.
score: 1

http://stackoverflow.com/q/51771726
favorite count: 0
has comment: http://stackoverflow.com/comment/90502139
possible better answer: http://stackoverflow.com/a/51771797
downvote count: 2
tagged with: python
type: AnsweredQuestion
has title: How to find top 5 ips accessing my website server using python?
linked to: http://stackoverflow.com/q/13332268
accepted answer: http://stackoverflow.com/a/51771843
score: -1
upvote count: 1
type: Question
answer count: 2
has body: In Linux it's straightforward : awk ‘ {print $1}’ logfile | sort | uniq -c | sort -nr | head -n 5 How can I transform the same logic into a Python function? Thanks.
has answer: http://stackoverflow.com/a/51771843
has answer: http://stackoverflow.com/a/51771797

http://stackoverflow.com/comment/90538499
comment on: http://stackoverflow.com/q/51790518
has text: Because insert works in place and returns None
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51655872
type: Answer
has body: Probably a dictionary would be a suitable datatype. You could complete your task like such. diction = {"Conditioners": 1, "Bath": 2} #add whatever else you want for item in categories: try: print(diction[item]) except: continue
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51655747
downvote count: 0

http://stackoverflow.com/comment/90496175
comment on: http://stackoverflow.com/a/51768580
type: AnswerComment
type: Comment
has text: I've tried it without specifying CA and it worked as well, which is weird.
score: 1

http://stackoverflow.com/comment/90517128
score: 0
has text: also your JSON-object example is not complete
type: Comment
comment on: http://stackoverflow.com/q/51779699
type: QuestionComment

http://stackoverflow.com/comment/90347739
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51693161
type: QuestionComment
has text: because `_d` and `d` are valid, underscore or not. `_d` is a naming convention discouraging you to use it, but it's still valid

http://stackoverflow.com/a/51697754
has comment: http://stackoverflow.com/comment/90357658
type: Answer
accepted answer of: http://stackoverflow.com/q/51697707
score: 5
has comment: http://stackoverflow.com/comment/90356941
has comment: http://stackoverflow.com/comment/90358035
upvote count: 5
has comment: http://stackoverflow.com/comment/131504246
has body: Have you tried this command? Pyinstaller.exe --onefile --windowed --icon=app.ico app.py Update your .specfile and set console = True exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='aNote', debug=False, strip=False, upx=False, clean=True, runtime_tmpdir=None, console=True, icon='c:\\aNote\\theme\\anoteicon.ico', version='version.txt') Use the sample code you can run a window UI instead of console: from PyQt5 import QtGui app = QtGui.QApplication([]) mainwindow = QtGui.QMainWindow() mainwindow.show() app.setWindowIcon(QtGui.QIcon('your.ico')) mainwindow.setWindowIcon(QtGui.QIcon('your.ico')) app.exec_()
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90357611
answers question: http://stackoverflow.com/q/51697707

http://stackoverflow.com/q/51751845
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: discord.py
has body: I'm getting an error when trying to get data from a json file. It's KeyError for issuer_name when i use this code: @ticket.command(pass_context=True) @commands.has_role("Tech Support Lead") async def info(self,ctx): ticket = ctx.message.content[13:] if ticket == "": await self.bot.say("Please supply a ticket id") return with open("data/tickets.json", "r") as f: tickets = json.load(f) print(tickets[ticket]["issuer_name"]) And it's TypeError(list indices must be int or slices, not str) when i use this code: @ticket.command(pass_context=True) @commands.has_role("Tech Support Lead") async def info(self,ctx): ticket = ctx.message.content[13:] if ticket == "": await self.bot.say("Please supply a ticket id") return with open("data/tickets.json", "r") as f: tickets = json.load(f) print(tickets[ticket]["ticket_data"]["issuer_name"]) This is my JSON file: {"amount_of_open_tickets": 1, "13": {"ticket_data": [{"issuer_id": "244204285729046528", "issuer_name": "Veestire", "ticket_message": "l", "claimed": null}]}}
has title: Error when trying to get data from a json file
has answer: http://stackoverflow.com/a/51751995
score: 0
has comment: http://stackoverflow.com/comment/90463790
answer count: 1
accepted answer: http://stackoverflow.com/a/51751995
tagged with: python

http://stackoverflow.com/a/52051100
answers question: http://stackoverflow.com/q/51776809
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/138819605
has body: If you want to receive an array from C, I recommend you use NumPy SWIG bindings numpy.i. Here I am using ARGOUTVIEWM_ARRAY1 such that the memory allocated in C will henceforth be managed by the NumPy array. If this does not suit your needs, you can choose a different typemap instead. There is good documentation. I also rename the the library_function so I can override it with my own function which has the correct signature for the NumPy typemap. test.t %module example %{ #define SWIG_FILE_WITH_INIT #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; double* library_function(void) { double* p = malloc(sizeof(double) * 10); for(int i = 0; i &lt; 10; ++i) p[i] = 1.1 * i; printf("%p\n",p); return p; } %} %include "numpy.i" %init %{ import_array(); %} %apply (double** ARGOUTVIEWM_ARRAY1, int* DIM1) {(double** data, int* length)}; %rename (library_function) encapsulate_library_function; %inline %{ void encapsulate_library_function(double** data, int* length) { *data = library_function(); *length = 10; } %} test.py from example import library_function a = library_function() print(type(a)) print(a) Example invocation: $ swig -python test.i $ clang -Wall -Wextra -Wpedantic -I /usr/include/python3.6m/ -fPIC -shared -o _example.so test_wrap.c -lpython3.6m $ python3 test.py 0x2b9d4a0 &lt;class 'numpy.ndarray'&gt; [ 0. 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9]
upvote count: 1
type: Answer

http://stackoverflow.com/comment/90428333
has text: The json files serve almost as a config for the python
score: 0
comment on: http://stackoverflow.com/q/51733318
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51750056
tagged with: python
tagged with: pycharm
type: Question
score: 0
has answer: http://stackoverflow.com/a/51750109
has body: This may be a stupid question but I am struggling to import windows related modules into PyCharm while running on Linux Mint. E.g. PyHook, pywin32. I get no module found. Other modules install fine though. I have tried Python 2 and 3. Do I have to program in windows to import these?
answer count: 1
has title: Do you need to be on windows to import windows related modules?
type: UnansweredQuestion

http://stackoverflow.com/comment/90401868
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51719571
has text: i am getting an error Reverse for 'emp_pay' with arguments '('Information_technology',)' not found. 1 pattern(s) tried: ['hrmsapp/employees_by_departments/<str:department>/$'] Request Method: GET Request URL: http://127.0.0.1:8000/hrmsapp/Payslip_departments Django Version: 2.0.7 Exception Type: NoReverseMatch Exception Value:

http://stackoverflow.com/comment/90254910
score: 0
type: Comment
type: QuestionComment
has text: @WarrenWeckesser Ah, I hadn't realized that the pulse needs to span over the edges rather than be in the middle! It makes sense in retrospect, given that this is how the frequency space works. It works if I call np.fft.fftshift on the array after creating it. I suppose if you want to write this as an answer, I'll accept it.
comment on: http://stackoverflow.com/q/51645045

http://stackoverflow.com/q/51734352
has title: Items in list is not removed accordingly
duplicate of: http://stackoverflow.com/q/6500888
has comment: http://stackoverflow.com/comment/90429410
score: 0
has comment: http://stackoverflow.com/comment/90429460
has comment: http://stackoverflow.com/comment/90429461
has comment: http://stackoverflow.com/comment/90429577
has comment: http://stackoverflow.com/comment/90429669
has comment: http://stackoverflow.com/comment/90430045
tagged with: python
has body: I am trying to remove items within a list based on the list of items from another list (in which the items within are slightly different). It is like a "wildcard" search in which I end up using endswith to check as follows: main_ctrls = [ "main_start_ctrl", "main_global_ctrl", "main_local_ctrl", "main_path_ctrl" ] toy_ctrls = ['toyBody:main_start_ctrl', 'toyBody:main_global_ctrl', 'toyBody:leg_ctrl', 'toyBody:main_local_ctrl', 'toyBody:main_path_ctrl'] for index, ctrl in enumerate(toy_ctrls): if ctrl.endswith(tuple(main_ctrls)): #toy_ctrls.remove(ctrl) # del toy_ctrls[index] # toy_ctrls.pop(index) print toy_ctrls # Returns : ['toyBody:base_global_ctrl', 'toyBody:base_path_ctrl', 'toyBody:leg_ctrl'] However, as seen in the above code, I have tried .remove(), del, .pop() and it returns the same output (3 items in the list) instead of the 1 item - ['toyBody:leg_ctrl'] that I am expecting. Could someone kindly advise?
duplicate of: http://stackoverflow.com/q/6022764
answer count: 0
has comment: http://stackoverflow.com/comment/90429525
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1207406
type: Question
tagged with: list
has comment: http://stackoverflow.com/comment/90429564
duplicate of: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/90429573
has comment: http://stackoverflow.com/comment/90429499

heap
tags question: http://stackoverflow.com/q/51735692
type: Tag
tags question: http://stackoverflow.com/q/51706537
tag name: heap

http://stackoverflow.com/comment/90361241
comment on: http://stackoverflow.com/q/51699867
has text: Thank you, the first upload, I will pay attention next time-_-
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51741804
score: -1
has comment: http://stackoverflow.com/comment/90444478
has body: A list of ints is entered into the program 1 at a time, for example: [1, 3, 1, 4, 4, 3, 1] Task: Print a list that contains exactly the same numbers as the given list, but rearranged so that every 3 is immediately followed by a 4. The 3's must not move index places, but every other number may move. The output of the example should read: [1, 3, 4, 1, 1, 3, 4] My code so far is only able to complete the rules 1 and 2. How could my code be modified to cater to this? newList=[] n=0 numCount= int(input()) while True: try: n = int(input()) except: break if len(newList) !=(numCount): if n == 3: newList.append(3) newList.append(4) else: newList.append(n) print(newList)
type: Question
has comment: http://stackoverflow.com/comment/90443537
tagged with: list-manipulation
has answer: http://stackoverflow.com/a/51742501
has comment: http://stackoverflow.com/comment/90444313
accepted answer: http://stackoverflow.com/a/51742466
has comment: http://stackoverflow.com/comment/90444060
has comment: http://stackoverflow.com/comment/90444550
possible better answer: http://stackoverflow.com/a/51742432
answer count: 3
has comment: http://stackoverflow.com/comment/90444158
has answer: http://stackoverflow.com/a/51742432
has comment: http://stackoverflow.com/comment/90443707
favorite count: 0
has comment: http://stackoverflow.com/comment/90444430
upvote count: 2
has comment: http://stackoverflow.com/comment/90443906
has comment: http://stackoverflow.com/comment/90443586
has title: Advanced list comprehension
tagged with: python
has comment: http://stackoverflow.com/comment/90444206
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51742466
has comment: http://stackoverflow.com/comment/90443806
downvote count: 3

http://stackoverflow.com/comment/90540508
score: 1
type: AnswerComment
has text: Yes, seems like resize function always returns a new Mat object.
type: Comment
comment on: http://stackoverflow.com/a/51791513

http://stackoverflow.com/q/51646673
has answer: http://stackoverflow.com/a/51647178
has comment: http://stackoverflow.com/comment/90257167
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90257130
accepted answer: http://stackoverflow.com/a/51647211
has body: Here is my problem: I have an encrypted bytes file like this: [w\x84\x7f@\xc6\xab\xc8 I want to decrypt it with PyCrypto, but I find a confused bug like the following: Code here: from Crypto.Cipher import DES key = 'jsfghutp' cipher = DES.new(key, DES.MODE_ECB) s = open('d:/Thu-Aug-2018.bin','rb').read() cipher.decrypt(s) If I run this, it will throw an error: ValueError Traceback (most recent call last) &lt;ipython-input-3-4fcf0e8076ca&gt; in &lt;module&gt;() ----&gt; 1 cipher.decrypt(s) D:\Python\anaconda\lib\site-packages\Crypto\Cipher\blockalgo.py in decrypt(self, ciphertext) 293 return res 294 --&gt; 295 return self._cipher.decrypt(ciphertext) 296 ValueError: Input strings must be a multiple of 8 in length I print the value of s: s = b'[w\\x84\\x7f@\\xc6\\xab\\xc8' However this is not right, what I need is the following result: &gt;&gt;&gt; cipher.decrypt(b'[w\x84\x7f@\xc6\xab\xc8') b'test aaa' That is, I think I must replace the \\\\ with \ in the bytes file, but I failed to do it with a correct way. Does anyone knows how to solve this?
score: 2
tagged with: python-3.5
downvote count: 0
has comment: http://stackoverflow.com/comment/90257501
has comment: http://stackoverflow.com/comment/90257921
has title: How to replace the ' \\ ' with ' \ ' in a bytes file?
type: AnsweredQuestion
tagged with: python
possible better answer: http://stackoverflow.com/a/51647178
has answer: http://stackoverflow.com/a/51647211
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51666050
has body: I would like to sum values by time. time epoch is 10sec and I want to make it 1minute. Following data are given. Date Time X 0 2017-10-15 12:50:00 10 1 2017-10-15 12:50:10 20 2 2017-10-15 12:50:20 30 3 2017-10-15 12:50:30 20 4 2017-10-15 12:50:40 10 5 2017-10-15 12:50:50 10 and I want to make it like this. Date Time X 0 2017-10-15 12:50:00 100 1 2017-10-15 12:51:00 300 I read this file with pandas. so the type of Time variable is pandas.core.series.Series. And I tried to use df.resample(), but it didn't work. What can I do here?? Thanks for your help.
favorite count: 0
tagged with: pandas
upvote count: 1
tagged with: python
downvote count: 0
has title: How to aggregate values by time in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90295267
score: 1
accepted answer: http://stackoverflow.com/a/51666099
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51666099

http://stackoverflow.com/comment/90504521
score: 0
type: QuestionComment
type: Comment
has text: @Scott Checked but will that work with a 3d matrix (length * width * RGB)?
comment on: http://stackoverflow.com/q/51772023

http://stackoverflow.com/comment/90316509
type: Comment
comment on: http://stackoverflow.com/a/51667568
type: AnswerComment
has text: @Arne For working with names coming from a data source, yeah. You would do the same even if these names had "normal" identifier values, since you'd have to loop over a sequence of them anyway. Don't/can't write declarative code here, so you set with `setattr` and get with `getattr`.
score: 0

http://stackoverflow.com/comment/90500234
type: Comment
comment on: http://stackoverflow.com/a/51757457
has text: See e.g. `parse_dates` option in https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html
score: 0
type: AnswerComment

http://stackoverflow.com/q/51778723
has answer: http://stackoverflow.com/a/51778898
favorite count: 0
accepted answer: http://stackoverflow.com/a/51778898
has answer: http://stackoverflow.com/a/51816152
has comment: http://stackoverflow.com/comment/90585447
tagged with: count
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/90584878
has title: Count of current unique values in a pandas df
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90584425
has comment: http://stackoverflow.com/comment/90587109
type: Question
possible better answer: http://stackoverflow.com/a/51778756
has comment: http://stackoverflow.com/comment/90654971
has answer: http://stackoverflow.com/a/51778756
has comment: http://stackoverflow.com/comment/90584169
upvote count: 13
has comment: http://stackoverflow.com/comment/90515397
has comment: http://stackoverflow.com/comment/90515434
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/90584587
has body: I'm trying to return a count of unique values in a pandas df. It's a cumulative count at each row. I'm aiming incorporate a function that determines how many values are currently occurring at any point in time. import pandas as pd df = pd.DataFrame({ 'A' : ['8:06:00','11:00:00','11:30:00','12:00:00','13:00:00','13:30:00','14:00:00','17:00:00'], 'B' : ['ABC','ABC','DEF','XYZ','ABC','LMN','DEF','ABC'], 'C' : [1,2,1,1,3,1,2,4], }) A B C 0 8:06:00 ABC 1 1 11:00:00 ABC 2 2 11:30:00 DEF 1 3 12:00:00 XYZ 1 4 13:00:00 ABC 3 5 13:30:00 LMN 1 6 14:00:00 DEF 2 7 17:00:00 ABC 4 So there are 4 unique values in col['B']. Which I'm measuring via df1 = df['B'].nunique() But I'm hoping to incorporate a function the iterates through the column to identify if any specific value occurs again. If not I want the count to decrease. If it's the first time the value appears I want to increase the count. If the value has already appeared and appears again, the count should stay the same. This would display how many values are occurring at any point in time. Using @jpp's code, we produce the following: cum_maxer = pd.Series(pd.factorize(df['B'])[0] + 1).cummax() df['res'] = cum_maxer - df['B'].duplicated().cumsum() print(df) Out: A B C res 0 8:06:00 ABC 1 1 1 11:00:00 ABC 2 0 2 11:30:00 DEF 1 1 3 12:00:00 XYZ 1 2 4 13:00:00 ABC 3 1 5 13:30:00 LMN 1 2 6 14:00:00 DEF 2 1 7 17:00:00 ABC 4 0 Intended output for 'res' 0 1 1 1 2 2 3 3 4 2 5 3 6 2 7 1 Essentially, if the value appears for the first time I want to add it to a cumulative count. If the value finishes (doesn't appear later on) then the count should decrease. If value has already appeared and appears again the count should stay the same. Rundown on each row and the intended output: 1st row, ABC appears for the first time and appears later on. Count = +1 2nd row, ABC appears again so no increase. It also appears later so no decrease. Count = no change 3rd row, DEF appears for the first time and appears later on. Count = +1 4th row, XYZ ap…
has comment: http://stackoverflow.com/comment/90570395
tagged with: unique

http://stackoverflow.com/comment/90380835
has text: I believe one approach could be to concatenate col1, col4 and col7 and do left join to original df. Wherever there would be a structure match you will get the value. replace it will 'yes' and rest with 'no'
comment on: http://stackoverflow.com/q/51709412
type: Comment
type: QuestionComment
score: 0

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/51679235
tags question: http://stackoverflow.com/q/51701515
tags question: http://stackoverflow.com/q/51735140
tags question: http://stackoverflow.com/q/51728287
tags question: http://stackoverflow.com/q/51797957
type: Tag
tags question: http://stackoverflow.com/q/51722339
tags question: http://stackoverflow.com/q/51778168
tags question: http://stackoverflow.com/q/51689035
tags question: http://stackoverflow.com/q/51777914
tags question: http://stackoverflow.com/q/51703320
tags question: http://stackoverflow.com/q/51792002
tags question: http://stackoverflow.com/q/51797312

http://stackoverflow.com/q/51765475
has comment: http://stackoverflow.com/comment/90489734
type: Question
has body: with open('employee.txt') as textfile: csvreader = csv.reader(textfile, delimiter='\t') csvdata = [] for row in csvreader: csvdata.append(row) conn = pymysql.connect (host = "localhost",user = "root", passwd = "password",db = "details1") c = conn.cursor() for row in csvdata: c.execute("INSERT INTO employee6(serial_no, first_name, last_name, age, sex,city) VALUES ('%s', '%s', '%s', '%s', '%s','%s')" % (serial_no,first_name,last_name,age,sex,city)) conn.commit() c.close()`enter code here` but I am getting an error in () 8 c = conn.cursor() 9 for row in csvdata: ---> 10 c.execute("INSERT INTO employee6(serial_no, first_name, last_name, age, sex,city) VALUES ('%s', '%s', '%s', '%s', '%s','%s')" % (serial_no,first_name,last_name,age,sex,city)) 11 12 conn.commit() NameError: name 'serial_no' is not defined why am i getting this error
has comment: http://stackoverflow.com/comment/90490690
has comment: http://stackoverflow.com/comment/90494514
has title: how to insert tab limited text file into sql database using python?
score: 0
answer count: 2
tagged with: sql
has answer: http://stackoverflow.com/a/51766154
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90489972
tagged with: text-files
has answer: http://stackoverflow.com/a/51768456
has comment: http://stackoverflow.com/comment/90494370

http://stackoverflow.com/comment/90495751
type: AnswerComment
score: 0
has text: seems like. Do I get you right? You just want to show a toolbar on a widget in your application, not on the (Main)Window of your application...???
type: Comment
comment on: http://stackoverflow.com/a/51767877

http://stackoverflow.com/comment/90314531
has text: Thanks, added in the begging of the answer
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51675509

http://stackoverflow.com/a/51736397
score: 1
answers question: http://stackoverflow.com/q/51735903
type: Answer
accepted answer of: http://stackoverflow.com/q/51735903
has body: I found the answer to my own question: If you disable the IP_MULTICAST_LOOP option on the sending socket, then: 1) Wireshark will STILL report two IGMPv2 join messages, same as before 2) Wireshark will STILL report two UDP multicast messages, same as before 3) However, the receiving socket will only receive a single UDP multicast message (the example program will block on "Receiving second message...") Here is the updated code for macOS: txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0) # &lt;&lt;&lt; FIX txsock.connect(group) Annoyingly, the behavior on Linux is the opposite: If you leave IP_MULTICAST_LOOP to its default value of enabled, as in the original example program, you will receive exactly one copy of the sent packet. If you disable IP_MULTICAST_LOOP, as in the "fixed" example program, you will not receive any copy of the sent packet (at least not on AWS). After further investigation, I found that the behavior does not depend on the platform on which the code runs (macOS vs Linux) but on the router to which the platform is connected.
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51710522
tagged with: logging
score: 2
has title: Python logging: Set level in `main.py` and inherit to child loggers
has body: I have a Python project that looks like this: my_project |- my_dir | |- part_1.py | |- part_2.py | |- ... |- main.py Every file (main.py and part_1.py, part_2.py, ...) should be able to write to the same log file, with the following two requirements: The file name should appear in the log message: a line in the log file should look like ERROR - my_dir.part_1 - Something went wrong in part_1.py The log level for all loggers should be set programatically from main.py: # main.py from my_dir import part_1, part_2, ... ... logger.setLevel('DEBUG') result_1 = part_1.my_function() # Logger in part_1.py should be set to DEBUG level logger.setLevel('WARNING') result_2 = part_2.my_other_function() # Logger in part_2.py should be set to WARNING level I accomplish the first requirement by beginning each file in my_dir with import logging logger = logging.getLogger(__name__) Setting the same level for all loggers works if I use a config file and do logging.config.fileConfig('config.ini'). But changes to the log level made in main.py are not propagated to the other loggers. What is the best way to handle this situation?
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90382882
has comment: http://stackoverflow.com/comment/90407171
tagged with: python
has comment: http://stackoverflow.com/comment/90382357
favorite count: 0
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90382740

http://stackoverflow.com/comment/90397780
type: AnswerComment
score: 0
type: Comment
has text: Yes, it's slightly ambiguous. But in this case a simple string replacement won't do because in the OP's example there is a string in the list that is more than one character long.
comment on: http://stackoverflow.com/a/51718057

http://stackoverflow.com/comment/90434376
score: 0
comment on: http://stackoverflow.com/q/51736860
has text: It fits in RAM.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51678388
answer count: 0
has body: I'm fairly new to machine learning. I'm teaching myself how to implement Multiple Linear Regression from scratch in Python. This isn't a homework problem, just a personal initiative. I'm using the Boston Housing dataset for this. The coefficient values and intercept don't match scikit-learn's values. Can someone please help identify what I'm doing wrong and possibly provide the solution as well? I'd like to learn from it. I've been at it for a week now. Here is the code for Multiple Linear Regression from scratch: Here is the code for Multiple Linear Regression using sklearn: Coefficients in sklearn - [ 7.72409427 -0.01673352] Intercept in sklearn - -19.129291077739456 Features I'm using - RM and CRIM Dependent variable - house prices equations for gradient descent I'm using (I think these might be incorrect): For intercept -(2 / N) * SUM OF y_val - (m1x1 + m2x2 + b) for all values of x and y For m1 -(2/N) * SUM OF x1 * (y_val - (m1x1 + m2x2 + b)) for all values of x and y For m2 -(2/N) * SUM OF x2 * (y_val - (m1x1 + m2x2 + b)) for all values of x and y
upvote count: 2
has comment: http://stackoverflow.com/comment/90320090
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90320758
has comment: http://stackoverflow.com/comment/96460445
tagged with: linear-regression
score: 1
downvote count: 1
type: Question
tagged with: scikit-learn
has title: Multiple Linear Regression from scratch in Python
favorite count: 0

http://stackoverflow.com/comment/90394406
comment on: http://stackoverflow.com/q/51716168
score: 0
type: Comment
type: QuestionComment
has text: Awesome thank-you, this was my problem I tried running just migrate and it worked this time.

http://stackoverflow.com/a/51719788
has body: It is because as the code is unwrapped it simplifies to: x = 99 print(x) print('f3') This is the sequence of unwrapping: def f1(): x = 99 def f2(): def f3(): print(x) print('f3') f3() f2() f1() becomes x = 99 def f2(): def f3(): print(x) print('f3') f3() f2() becomes x = 99 def f3(): print(x) print('f3') f3() becomes x = 99 print(x) print('f3') which is then what is executed.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51719663
accepted answer of: http://stackoverflow.com/q/51719663
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/51709681
accepted answer: http://stackoverflow.com/a/51709735
type: AnsweredQuestion
upvote count: 5
linked to: http://stackoverflow.com/q/38132755
type: Question
score: 5
has title: List packages (with respective versions) installed in a virtualenv without using pip
linked to: http://stackoverflow.com/q/19097057
answer count: 1
downvote count: 0
tagged with: virtualenv
has body: Context: After updating from Debian 8 to 9, Python 3.4 virtualenvs stopped working because system site-packages were all replaced by the Python 3.5 version. This answer suggests removing the old virtualenv, creating a new one, and reinstalling all packages using pip install -r requirements.txt. However, I don't have a requirements.txt for all virtualenv. I know that such file can be created with pip freeze, but for the reason stated above, pip won't work1. Problem: I need to generate a list of the packages and their respective installed in a virtualenv that I cannot activate. Question: Is there a way to get a list similar to the output of pip freeze for a virtualenv without actually running pip? Note: This question is different from “Return a list of imported Python modules used in a script?” and because the requested answers should not need to access the scripts that use the virtualenv, and should also return the versions of the packages installed in the virtualenv2. 1 Namely, running pip (with any parameters) raises ImportError: No module named 'encodings'. 2 Full disclosure: I asked a similar question that was wrongly closed as duplicate.
linked to: http://stackoverflow.com/q/2572582
has answer: http://stackoverflow.com/a/51709735
favorite count: 0
tagged with: pip
tagged with: python

http://stackoverflow.com/q/51654651
accepted answer: http://stackoverflow.com/a/51654741
answer count: 1
tagged with: selenium
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: How to handle errors (unable to locate element) in Selenium
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51654741
has body: I am writting bot using Selenium for a game where is a lot of clicking. Sometimes it shows error Unable to locate element: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div[1]/header/div/div[1]/a I have correct Xpath but sometimes it gives me an error in different parts in my code. It is not that I have one mistake and it always show error in one place. My problem is that those errors are random. I am handling it like this: try: secondPhoto = self.driver.find_element_by_xpath( '/html/body/span/section/main/article/div[2]/div/div[1]/div[1]') secondPhotoOpen = ActionChains(self.driver) secondPhotoOpen.move_to_element(secondPhoto) secondPhotoOpen.click() secondPhotoOpen.perform() except: time.sleep(3) self.driver.find_element_by_xpath( '/html/body/span/section/main/article/div[1]/div/div/div[1]/div[2]').click() This is not a ideal solution. It still shows errors but less frequently. I am also using time.sleep. Usually errors show up when I am doing something else on internet or I have lags(this is the reason why I am using time.sleep) Now, I have about 50 .click() in my code and for all clicks I am doing try except but still it is not working correctly. Do you have an effective solution for this? How to write a code that use .click() to be 100% sure it works regardless lags, other browser activity? How to wait for full load of next page/image after click() ( I am using time.sleep)?
tagged with: click
favorite count: 0

http://stackoverflow.com/q/51719374
tagged with: progress-bar
has answer: http://stackoverflow.com/a/51732176
answer count: 1
tagged with: kivy
favorite count: 0
has body: I am new in kivy i can not add customise colour on progress bar kivy please help me to implement this ProgressBar: id: pb size_hint:dp(.9),dp(.4) background_color:"#22222" #value: (app.time * 20) % 100. value: 50 pos_hint: {"right": 1, "top": .65}
tagged with: python
accepted answer: http://stackoverflow.com/a/51732176
type: AnsweredQuestion
downvote count: 3
upvote count: 7
type: Question
has title: how to change color of progress bar kivy
score: 4

http://stackoverflow.com/a/51697167
has body: Try: my_list = ["1, 2, 3", "4, 5, 6"] new_list = [] for e in my_list: for sub_e in e.split(","): new_list.append(int(sub_e))
has comment: http://stackoverflow.com/comment/90355975
upvote count: 2
has comment: http://stackoverflow.com/comment/90355807
type: Answer
has comment: http://stackoverflow.com/comment/90356233
answers question: http://stackoverflow.com/q/51696616
has comment: http://stackoverflow.com/comment/90355920
score: 2
has comment: http://stackoverflow.com/comment/90355844
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51696616

http://stackoverflow.com/comment/90475914
has text: Yes that's exactly what I mean.
score: 1
comment on: http://stackoverflow.com/a/51757780
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51698459
upvote count: 3
type: Question
has body: I have a pandas df that's indexed by id and date. I would like to run some regressions for each id in parallel using dask. I know dask splits the df into N partitions but is there a way to force it to split by id column? This way when I do map_partitions I can simply apply my rolling regression function to each partition.
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: dask
type: UnansweredQuestion
has title: specify how to partition dask dataframe?
tagged with: python
score: 3
answer count: 0

http://stackoverflow.com/q/51713273
favorite count: 0
has answer: http://stackoverflow.com/a/51713342
tagged with: regex
has body: I'm trying to extract the string muscle pain from the following strings. I need to use a regular expression that works for all three cases. string1 = 'A1 muscle pain: immunotherapy' string2 = 'A2B_45 muscle pain: topical medicine e.g. ....' string3 = 'A2_45 muscle pain (pain): topical medicine e.g. ....' The following code works for string1 and string2. But it does not work for string3. What I get is always muscle pain (pain). Can anyone help me with that. I tried so many times with different expression but could not figure out how. re.match(r"^[A-Z]+\d*[A-Z]*_?\d*\s(.*)[:\(]", string3).group(1)
has title: Extract string before colon or parenthesis with regex in python
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51714309
downvote count: 1
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90387940
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51714309
possible better answer: http://stackoverflow.com/a/51713342

http://stackoverflow.com/q/51761348
type: UnansweredQuestion
has title: plot histogram with feature on x-axis and each bar should reflect target class var with diff colors
type: Question
score: 0
tagged with: pandas
answer count: 1
has body: I don't even know how to correctly explain my problem in words so let me give an example instead. Suppose I have a dataframe like this d = {'feat':[1,1,1,2,3,4,5,1,4,5],'grade':['A','B','A','A','B','C','D','C','D','A']} df1 = pd.DataFrame(d) df1 feat grade 0 1 A 1 1 B 2 1 A 3 2 A 4 3 B 5 4 C 6 5 D 7 1 C 8 4 D 9 5 A So I have a feature variable(feat) with a target class variable grade and my feature could fall only in one of A,B,C,D grade. Now when I do this df1.groupby('feat')['grade'].value_counts() I get feat grade 1 A 2 B 1 C 1 2 A 1 3 B 1 4 C 1 D 1 5 A 1 D 1 Name: grade, dtype: int64 Now this is exact shape of my problem, I want to plot histogram of this dataframe such that x-axis would represent feat and each bar of this histogram would be made of different colors which would be proportional to occurrences of grades.
tagged with: data-visualization
has answer: http://stackoverflow.com/a/51763195
tagged with: python

http://stackoverflow.com/comment/90603983
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51795534
has text: It's not your target HTML (there is no `a` tags inside)
score: 0

http://stackoverflow.com/comment/90335521
comment on: http://stackoverflow.com/q/51686658
has text: Your code runs without error on a few small test cases I tried. To debug you might try: running smaller random samples of your data to see if you always get the error; use a for loop (with `iterrows()`) instead of `apply` and use `print` statements to figure out where the error occurs; try running with only one of the `x.replace()` methods in the chain, then two, then three, etc. If you have really long strings I guess it's possible that keeping track of so many replacements is causing some memory issues (?).
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90422064
type: Comment
type: QuestionComment
score: 1
has text: Inception expects data of shape `(139, 139, 3)`, where 3 stands for the *channels* (R, G, B); resizing as you do in `np.reshape(worka,[1,19321])` won't work, and that is exactly what the error message tells you.
comment on: http://stackoverflow.com/q/51730484

http://stackoverflow.com/comment/95065904
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51716020
has text: @AmirRezazadeh There could be any number of potential typos in the input. What if there are more than one forward slashes? What if there's a random letter in between the space and the slash? OP didn't ask about this issue, so my answer didn't account for it.

javascript
tags question: http://stackoverflow.com/q/51767105
tags question: http://stackoverflow.com/q/51782704
tags question: http://stackoverflow.com/q/51766848
tags question: http://stackoverflow.com/q/51777504
tags question: http://stackoverflow.com/q/51642011
tags question: http://stackoverflow.com/q/51762655
tags question: http://stackoverflow.com/q/51709990
tags question: http://stackoverflow.com/q/51659551
tag name: javascript
tags question: http://stackoverflow.com/q/51721489
tags question: http://stackoverflow.com/q/51737806
tags question: http://stackoverflow.com/q/51731623
tags question: http://stackoverflow.com/q/51773135
type: Tag
tags question: http://stackoverflow.com/q/51754318
tags question: http://stackoverflow.com/q/51737696
tags question: http://stackoverflow.com/q/51756026
tags question: http://stackoverflow.com/q/51722445
tags question: http://stackoverflow.com/q/51661409
tags question: http://stackoverflow.com/q/51662106
tags question: http://stackoverflow.com/q/51703688
tags question: http://stackoverflow.com/q/51714787
tags question: http://stackoverflow.com/q/51680731
tags question: http://stackoverflow.com/q/51671278
tags question: http://stackoverflow.com/q/51771415
tags question: http://stackoverflow.com/q/51715712
tags question: http://stackoverflow.com/q/51662185
tags question: http://stackoverflow.com/q/51642600
tags question: http://stackoverflow.com/q/51700524

http://stackoverflow.com/comment/90296431
score: 0
type: QuestionComment
type: Comment
has text: @PM2Ring In this case you can create an instance by `c = C()`. In my code I'm storing them in a dictionary. `classes = {"Foo Bar", type('Foo Bar', (object,),{}), ...}`
comment on: http://stackoverflow.com/q/51666361

http://stackoverflow.com/comment/90338677
score: 1
comment on: http://stackoverflow.com/q/51688333
has text: If the error message says it doesn't expect a list, then you probably deal with lists here not arrays. It could be useful to clarify that by [edit]ing the post (and including a minimal sample input).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90340769
score: 0
comment on: http://stackoverflow.com/q/51663321
type: QuestionComment
type: Comment
has text: The image is a 3D image numpy array, between this piece of code and the previous one there are some calculations to find maxvalLine and maxvalCol so it doesn't affect the shape of the original image or any of that(sorry that i can't post it) in the main function here is how i called the function im ="doc4.jpg" recusiveCut(im) to guarantee you the type of my the image I have used print (type(im)) and print(im) to see the array here are the results <class 'numpy.ndarray'> [[[ 97 111 130] [133 149 162] [ 9 24 33] ... [122 121 130] ]] your help is so much appreciated.

http://stackoverflow.com/q/51659383
has comment: http://stackoverflow.com/comment/90313434
has comment: http://stackoverflow.com/comment/90313129
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/90313685
has title: results from sklearn's metrics.accuracy_score seem wrong
has body: Here's the code: xtrain, xtest, ytrain, ytest = train_test_split(xx, yy, test_size=0.50) clf = MultinomialNB(alpha=1.0) clf.fit(xtrain, ytrain) predictions = clf.predict(xtest) print 'score:', metrics.accuracy_score(ytest, predictions) Standard stuff, but here's the problem. The score, as you can see below, is impossibly high. The actual outcome (not showing the code for that but it's just basic reporting on predictions vs the Y column) is that 3621 rows were predicted to be in the class. Of those, only 299 actually were (true positives). Nothing at all like 99% accuracy. score: 0.9942950664902702 num rows: 644004 Y == 1: 651 picked: 3621 | true positives: 299 | false positives: 3322 I didn't want to tag this as related specifically to MultinomialNB because I found that RandomForestClassifier gives the same result. The problem (or the problem with me) appears to be related to the scoring function itself.
score: 0
has answer: http://stackoverflow.com/a/51673393
upvote count: 1
accepted answer: http://stackoverflow.com/a/51673393
answer count: 1
downvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90313253
favorite count: 0
has comment: http://stackoverflow.com/comment/90298912
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51694496
tagged with: python
has comment: http://stackoverflow.com/comment/90374454
has comment: http://stackoverflow.com/comment/90353649
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/90350870
type: UnansweredQuestion
score: 2
has body: I have a 3D array. Each 2D slice has labelnumbers which could have numbers between 1 and 1800. Now I want to check If some of the labelnumbers only occur once along the z axis. So my idea was to loop over the 3d array and use numpy.unique. But I wonder If there is a smarter way to get thos unique labelnumbers.. UPDATED Here is a approach of me, but I think there must be a faster way import numpy as np from collections import Counter array = np.array([[[0,0,1],[1,2,4],[4,4,4]],[[5,5,1],[5,5,1],[4,4,4]],[[0,0,1],[2,2,4],[4,4,4]]]) uniqueNumbers=[] for x in range(len(array)): uniqueNumbers.extend(np.unique(array[x]).tolist()) cnt = Counter(uniqueNumbers) ultimateUnique=([k for k, v in cnt.items() if v &lt;= 1]) print(ultimateUnique) output: [5] So in this case only the label 5 is occuring in slice 2 and should be recognized.
answer count: 0
downvote count: 0
has title: Python: Get unique labelnumbers in a 3D array
favorite count: 0
has comment: http://stackoverflow.com/comment/90358284
type: Question
upvote count: 2

http://stackoverflow.com/comment/90435985
comment on: http://stackoverflow.com/q/51737752
type: Comment
type: QuestionComment
has text: [Can you please post the text file as text not image](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question)
score: 0

networkx
tags question: http://stackoverflow.com/q/51758571
tags question: http://stackoverflow.com/q/51734447
tags question: http://stackoverflow.com/q/51675312
tag name: networkx
tags question: http://stackoverflow.com/q/51793856
type: Tag
tags question: http://stackoverflow.com/q/51652106
tags question: http://stackoverflow.com/q/51793808
tags question: http://stackoverflow.com/q/51693024
tags question: http://stackoverflow.com/q/51722860
tags question: http://stackoverflow.com/q/51712821

http://stackoverflow.com/comment/90542967
comment on: http://stackoverflow.com/a/51792693
type: Comment
score: 1
has text: Looks like @sacul wrote answer to my comment while i wrote it. It works now. Thanks!
type: AnswerComment

http://stackoverflow.com/comment/90263277
type: QuestionComment
comment on: http://stackoverflow.com/q/51649956
score: 6
has text: If you want to get the element from your nested list, it's `a[0][0]`. Otherwise, not clear what you're after.
type: Comment

http://stackoverflow.com/q/51679311
upvote count: 2
tagged with: classification
tagged with: machine-learning
tagged with: python
has body: I'm currently working on a program that can do binary image classification with machine learning. I have a list of labels and a list of images that i'm using as inputs which are then fed into the Inception V3 model. Will inputting of the dataset this way work with the inception V3 architecture? Is it necessary to organize the images with labeled folders before feeding it into the model? Thanks for your help!
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51680611
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51680611
downvote count: 0
has title: Is Dataset Organization for Image Classification Necessary?
tagged with: keras
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90824045
comment on: http://stackoverflow.com/q/51732854
score: 0
type: Comment
type: QuestionComment
has text: @Parfait Thanks for the tip. I'll follow that practice. It's been a while and I forgot that you have destroy all your objects when you are finished with them to avoid memory leaks.

http://stackoverflow.com/comment/90545274
score: 0
type: Comment
type: QuestionComment
has text: Because there are GUI builders for wxPython which make the designing much easier and its by doing that I'll get extra points for the project
comment on: http://stackoverflow.com/q/51754172

http://stackoverflow.com/q/51690825
has comment: http://stackoverflow.com/comment/90343505
score: -2
has comment: http://stackoverflow.com/comment/90343436
has body: My program reads a file (batch_files) that contains a list of file names containing tranches of data. If batch_files is empty, the code will create a new text file. If batch_files contains file names, the program will append data to the existing file(s). Here is my original code/pseudo code, which worked in Python 3.5: with open(path + batch_files, 'r+', encoding='utf-8') as file_list: batch_names = [line.rstrip('\n') for line in file_list] series_count = len(batch_names) # Initialize an empty batch if none exists. if series_count == 0: series_count += 1 Pseudo-code: create file and append file name to `batch_files` # Load existing batches. for file_name in batch_names: with open(path + file_name, 'r', encoding='utf-8') as tranche: Pseudo-code: append data to existing file. In Python 3.6.6, I receive the following error: PermissionError: [Errno 13] Permission denied:'[error message includes the working directory path without a filename]' Even though batch_files is empty, i.e. batch_names = [''], len(batch_names) equals 1 (per debugging trace). The code then skips the file initialization subroutine because if series_count == 0 is false. Then the code tries to load a non-existent data file but produces an error because there is no text in file_name. I tried the following empty list and file tests: if not batch_names: per this thread. if os.stat(path + batch_files).st_size == 0: per this thread. Both versions failed to trigger file initialization. See edits below for more information on getting these solutions to work. Side Note: I am using Notepad++ to ensure batch_files is empty. The file size is 0k. OS is Windows 10. Why does my code think batch_files isn't empty? How do you suggest I fix the problem? Edit: Per @saarrrr, the list contains an empty text string, so I used the following code to solve the issue. Preferred Method: batch_list = [line.rstrip('\n') for line in file_list] # Remove empty text strings. batch_names = list(filter(None, batch_list)) # Initialize …
downvote count: 2
has answer: http://stackoverflow.com/a/51690843
answer count: 1
linked to: http://stackoverflow.com/q/2507808
favorite count: 0
has comment: http://stackoverflow.com/comment/90343412
type: UnansweredQuestion
has title: Empty file not reading as empty in Python 3
tagged with: python
has comment: http://stackoverflow.com/comment/90343442
linked to: http://stackoverflow.com/q/2967194
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/90343432
tagged with: file
tagged with: empty-list
type: Question
linked to: http://stackoverflow.com/q/53513

http://stackoverflow.com/a/51777452
score: 1
type: Answer
upvote count: 1
has body: use groupby to group by each time down is equal to 1, than transform with your desired calculation. Then you can find where down is 1 again, and convert to NaN (as the calculation is meaningless there, as per your example): df['percentage'] = (df.groupby(df.down.eq(1).cumsum())['distance'] .transform(lambda x: (x-x.iloc[0])/x)) df.loc[df.down.eq(1),'percentage'] = np.nan &gt;&gt;&gt; df down distance percentage 1 1.0 10.0 NaN 2 2.0 13.0 0.230769 3 3.0 15.0 0.333333 4 3.0 20.0 0.500000 5 4.0 1.0 -9.000000 6 1.0 10.0 NaN 7 2.0 9.0 -0.111111 8 3.0 3.0 -2.333333 9 1.0 10.0 NaN
downvote count: 0
answers question: http://stackoverflow.com/q/51777429

http://stackoverflow.com/q/51647333
has answer: http://stackoverflow.com/a/51650633
score: 0
has body: I am using this repository has the basecode (https://github.com/ndaidong/tf-object-detection) which uses Tensorflow Object Detection, to detect the review, date, likes and rating in a screenshot of a review. I went through 100 images (just wanted to test if this was possible), annotating the images with 4 labels (review, date, likes and rating), converted from XML to CSV and then generated the TFrecords. This was done for both training and evaluation data. 100 images for training and 20 images for evaluation. Here is a screenshot of what I have annotated. Click here for an example of the annotated image For the training, I used the following config model { ssd { num_classes: 4 image_resizer { fixed_shape_resizer { height: 500 width: 2000 } } feature_extractor { type: "ssd_mobilenet_v2" depth_multiplier: 1.0 min_depth: 16 conv_hyperparams { regularizer { l2_regularizer { weight: 3.99999989895e-05 } } initializer { truncated_normal_initializer { mean: 0.0 stddev: 0.0299999993294 } } activation: RELU_6 batch_norm { decay: 0.999700009823 center: true scale: true epsilon: 0.0010000000475 train: true } } use_depthwise: true } box_coder { faster_rcnn_box_coder { y_scale: 10.0 x_scale: 10.0 height_scale: 5.0 width_scale: 5.0 } } matcher { argmax_matcher { matched_threshold: 0.5 unmatched_threshold: 0.5 ignore_thresholds: false negatives_lower_than_unmatched: true force_match_for_each_row: true } } similarity_calculator { iou_similarity { } } box_predictor { convolutional_box_predictor { conv_hyperparams { regularizer { l2_regularizer { weight: 3.99999989895e-05 } } initializer { truncated_normal_initializer { mean: 0.0 stddev: 0.0299999993294 } } activation: RELU_6 batch_norm { decay: 0.999700009823 center: true scale: true epsilon: 0.0010000000475 train: true } } min_depth: 0 max_depth: 0 num_layers_before_predictor: 0 use_dropout: false dropout_keep_probability: 0.800000011921 kernel_size: 3 box_code_size: 4 apply_sigmoid_to_scores: false } } anchor_generator { ssd_anchor…
tagged with: python
tagged with: object-detection
has comment: http://stackoverflow.com/comment/90430140
tagged with: machine-learning
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has title: Tensorflow Object Detection: Not Predicting using Custom Data
accepted answer: http://stackoverflow.com/a/51650633
answer count: 1

http://stackoverflow.com/comment/90282434
type: Comment
has text: It should be a config.yml file. Thanks for pointing, updated. The file name and foldername are correct. The purpose of .ebextentions is different. You can read about different config files and why they are used: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-configuration-methods-before.html#configuration-options-before-ebextensions You can auto generate the file using "eb init" command too. Hope that helps.
comment on: http://stackoverflow.com/a/51658117
score: 0
type: AnswerComment

http://stackoverflow.com/a/51645550
accepted answer of: http://stackoverflow.com/q/51645195
answers question: http://stackoverflow.com/q/51645195
has body: You are on the right track, except that DataFrame.align doesn't combine two dataframes, rather it aligns them so that the two dataframes have the same row and/or column configuration. Let's try an example: Initialising two dataframes with some descriptive column names and toy data: df1 = pd.DataFrame([[1,2,3,4], [6,7,8,9]], columns=['D', 'B', 'E', 'A'], index=[1,2]) df2 = pd.DataFrame([[10,20,30,40], [60,70,80,90], [600,700,800,900]], columns=['A', 'B', 'C', 'D'], index=[2,3,4]) Now, let's view these data frames by themselves: print(df1) D B E A 1 1 2 3 4 2 6 7 8 9 print(df2) A B C D 2 10 20 30 40 3 60 70 80 90 4 600 700 800 900 Let's align these two dataframes, aligning by columns (axis=1), and performing an outer join on column labels (join='outer'): a1, a2 = df1.align(df2, join='outer', axis=1) print(a1) print(a2) A B C D E 1 4 2 NaN 1 3 2 9 7 NaN 6 8 A B C D E 2 10 20 30 40 NaN 3 60 70 80 90 NaN 4 600 700 800 900 NaN A few things to notice here: The columns in df1 have been rearranged so they align with the columns in df2. There is a column labelled 'C' that has been added to df1, and a column labelled 'E' that has been added to df2. These columns have been filled with NaN. This is because we performed an outer join on the column labels. None of the values inside the DataFrames have been altered. Note that the row labels are not aligned; df2 has rows 3 and 4, whereas df1 does not. This is because we requested alignment on columns (axis=1). What happens if we align on both rows and columns, but change the join parameter to 'right'? a1, a2 = df1.align(df2, join='right', axis=None) print(a1) print(a2) A B C D 2 9.0 7.0 NaN 6.0 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN A B C D 2 10 20 30 40 3 60 70 80 90 4 600 700 800 900 Note that: Only the columns and rows that are found in the "right" dataframe (df2) are retained. Column 'E' is no longer present. This is because we made a right join on both the column and row labels. Rows with labels 3 and 4 have been added to df1, fil…
has comment: http://stackoverflow.com/comment/112706729
score: 118
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 118
has comment: http://stackoverflow.com/comment/120598439

http://stackoverflow.com/a/51644142
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51642935
has body: IIUC d'x','y'=np.sort(d'x','y',1) pd.crosstab([d.x,d.y],d.score) Out[94]: score 1 2 3 x y a b 1 0 2 c 0 1 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/90497458
type: Comment
comment on: http://stackoverflow.com/q/51769198
has text: It's just that I want to feed the whole thing to a neural net and I doesn't make any sense to say that a sample " s " has a feature " f " when it doesn't
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90275246
has text: My advice is: Don't use threads, use [trio](https://trio.readthedocs.io/), it is designed for (among other things) exiting gracefully.
comment on: http://stackoverflow.com/q/51654367
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51746848
tagged with: raspberry-pi
downvote count: 0
favorite count: 0
has title: Strange character square + 0101 in Python 3
has answer: http://stackoverflow.com/a/51746940
tagged with: python
tagged with: python-3.x
has body: I am collecting temperature from a digital sensor connected to an i2c port in a Raspberry running on Ubuntu Core and I am using the following code: import pigpio import RPi.GPIO as GPIO pi = pigpio.pi() if not pi.connected: print("no pi") exit() bus = 1 address = 0x5a read_bytes = 9 while True: handle = pi.i2c_open(bus,address) count, data = pi.i2c_read_device(handle, read_bytes) pi.i2c_close(handle) pi.stop() print(count) print(data) exit() However, the code returns a weird character for temperature, as seen below: How can I transform this character into a readable number ? Is this somewhat related to unicode ?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90453528
upvote count: 1
score: 1
tagged with: python-unicode
type: Question
has answer: http://stackoverflow.com/a/51746976
answer count: 2

http://stackoverflow.com/q/51780410
favorite count: 0
downvote count: 3
has title: Aggregate data frame rows based on conditions
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90518694
has comment: http://stackoverflow.com/comment/90518526
type: UnansweredQuestion
tagged with: python
has body: I have this table A B C E 1 2 1 3 1 2 4 4 2 7 1 1 3 4 0 2 3 4 8 3 Now, I want to remove duplicates based on column A and B and at the same time sum up column C. For E, it should take the value where C shows the max value. The desirable result table should look like this: A B C E 1 2 5 4 2 7 1 1 3 4 8 3 I tried this: df.groupby(['A', 'B']).sum()['C'] but my data frame does not change at all as I am thinking that I didn't incorporate the E column part properly...Can somebody advise? Thanks so much!
score: -1
has answer: http://stackoverflow.com/a/51791697
has comment: http://stackoverflow.com/comment/90538900
type: Question
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90518459

http://stackoverflow.com/comment/90618635
score: 1
comment on: http://stackoverflow.com/q/51752222
has text: There are [28 questions about LDA+QDA on CrossValidated](https://stats.stackexchange.com/search?tab=votes&q=LDA%20QDA%20is%3aquestion), recommend you skim them, at least start with the ones with the most votes. Show us some basic summary statistics or distribution plot of the different classes in feature-space, think about some fast-and-dirty transforms to make those a bit more normal, rerun the classifiers, tell us what improvement you got, look at the confusion matrix. Basically, develop an intuition for why QDA or LDA perform the way they do, per-class. Before you go classifier-shopping.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51663523
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51661864
has comment: http://stackoverflow.com/comment/90312307
downvote count: 0
upvote count: 1
has body: You could have FFmpeg just output the i frames as JPG. And use a python wrapper to trigger this command. This will output all the i frames as JPG images. ffmpeg -i 2.flv -vf "select=eq(pict_type\,I)" -vsync vfr frame-%02d.jpg Credit to this comment a similar superuser.com question. https://superuser.com/questions/669716/how-to-extract-all-key-frames-from-a-video-clip#comment1184347_669733 Hope that helps. Cheers. Ian

http://stackoverflow.com/comment/90561682
type: AnswerComment
has text: hey thanks for your help i tweaked your code a little bit now it works pretty fast
type: Comment
comment on: http://stackoverflow.com/a/51800015
score: 0

http://stackoverflow.com/comment/93761915
type: QuestionComment
comment on: http://stackoverflow.com/q/51716417
score: 0
has text: Thanks! I had found the set_shape solution and that's what I'm using. It feels a bit unnatural, but works.
type: Comment

http://stackoverflow.com/comment/90360687
score: 0
type: Comment
type: QuestionComment
has text: Exactly. So basically a 3d matrix with 10 million entries, for each of the 1000 patients I have.
comment on: http://stackoverflow.com/q/51699220

http://stackoverflow.com/comment/90447389
type: Comment
comment on: http://stackoverflow.com/a/51743703
type: AnswerComment
has text: as jpp stated in the comment above, you should convert your values into floating point numbers before you sort them if you want them to be sorted mathematically. Otherwise you are just sorting strings based on their ASCII codes.
score: 0

http://stackoverflow.com/q/51788995
tagged with: pandas
has comment: http://stackoverflow.com/comment/90535942
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90536262
has comment: http://stackoverflow.com/comment/90536966
type: UnansweredQuestion
tagged with: python
has body: I am trying load the data worth of 44 mb in to a Pandas data frame. this is the code: import pandas as pd from sqlalchemy import create_engine import cx_Oracle import sqlalchemy engineor = create_engine('oracle+cx_oracle://xxxxx:xxx@xxx:1521/?service_name=XXX') sql = "select * from accounts where date &gt;= '10-MAY-18 06.00.16.170000000 PM'" do = pd.read_sql(sql, engineor) do.info(memory_usage='deep') The above query returns around 70k rows and the size is around 44 mb. When I run this from my local machine (Win 7) in Anaconda, the data loads in to data frame without any issues in a minute or two. However, when I run the same thing in Docker container (Linux based) it just hangs. I verified that docker container has sufficient memory, and memory doesn't grow over time (although the size is quite small ~44 mb). It just gets submitted and hangs indefinitely that I am unable to kill it by pressing control + c or control + z. I need to disconnect from the machine and login back. I tried to match the version of Pandas from Anaconda that I am running on local machine. But it didn't help much, it is still hanging. The only thing that is now differing between my local machine and the Python version. In docker container it is 3.5.3 and in my local version it is 3.6.3, and that Anaconda is running from Windows and docker container is Linux based. I am not sure if these things make any difference. Any suggestions on how to overcome this?
linked to: http://stackoverflow.com/q/48430886
has title: Python Pandas hanging in Docker container for small volume of data
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90538625
has comment: http://stackoverflow.com/comment/90546562
has comment: http://stackoverflow.com/comment/90536511
has answer: http://stackoverflow.com/a/65388991
tagged with: docker
has comment: http://stackoverflow.com/comment/90537399
has comment: http://stackoverflow.com/comment/90540150

http://stackoverflow.com/comment/90401305
comment on: http://stackoverflow.com/q/51720097
score: 0
type: QuestionComment
has text: The `math.log` docs say it uses the log division method when given a base.
type: Comment

variables
tags question: http://stackoverflow.com/q/51735189
tag name: variables
tags question: http://stackoverflow.com/q/51688239
tags question: http://stackoverflow.com/q/51699921
tags question: http://stackoverflow.com/q/51733545
tags question: http://stackoverflow.com/q/51643173
tags question: http://stackoverflow.com/q/51751900
tags question: http://stackoverflow.com/q/51768267
tags question: http://stackoverflow.com/q/51700305
type: Tag
tags question: http://stackoverflow.com/q/51756436
tags question: http://stackoverflow.com/q/51690799
tags question: http://stackoverflow.com/q/51671587
tags question: http://stackoverflow.com/q/51691768
tags question: http://stackoverflow.com/q/51663957
tags question: http://stackoverflow.com/q/51786785
tags question: http://stackoverflow.com/q/51717004
tags question: http://stackoverflow.com/q/51646123
tags question: http://stackoverflow.com/q/51700572
tags question: http://stackoverflow.com/q/51760939
tags question: http://stackoverflow.com/q/51687684
tags question: http://stackoverflow.com/q/51777830
tags question: http://stackoverflow.com/q/51694468
tags question: http://stackoverflow.com/q/51698417

http://stackoverflow.com/a/51720675
score: 1
has body: You can do so: a = ['ram', 'shyam', 'great', 'bad'] a[2:4] = [', '.join(a[2:4])] Output: ['ram', 'shyam', 'great, bad']
answers question: http://stackoverflow.com/q/51720606
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/51776924
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51776799
has comment: http://stackoverflow.com/comment/90512756
answers question: http://stackoverflow.com/q/51776799
score: 4
has body: It appears that you're looking for the text field as a secondary sort key. The easiest way is to simply use a tuple for your keys, in priority order: sorted(data, key=lambda x: (x['value'], x['text']) ) Does that yield what you need? Output: [{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'b', 'value': 50}, {'text': 'k', 'value': 50}, {'text': 'y', 'value': 52}] The values (k, 50) and (b, 50) are now in the other order; I'm hopeful that I read your mind correctly. UPDATE per OP clarification I checked the docs. Python's sort method is stable, so you don't need the second sort key at all: in case of a tie, sort will maintain the original ordering: &gt;&gt;&gt; data.sort(key= lambda x:x['value']) &gt;&gt;&gt; data [{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'k', 'value': 50}, {'text': 'b', 'value': 50}, {'text': 'y', 'value': 52}] ... and this is what you requested.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90512810

http://stackoverflow.com/comment/90411242
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51725490
has text: So the function returns indices? where are you storing/printing them

http://stackoverflow.com/comment/90452135
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/51746197
has text: If you're using Python 2 it would be [`string.maketrans`](https://docs.python.org/2/library/string.html#string.maketrans), and it takes only two arguments.

http://stackoverflow.com/comment/90354001
score: 2
has text: This is a presentational matter, you should probably do the conversion to local time as late as possible in your code. Are you using a template to show the result, or does this go through an API call, or something else?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51695678

http://stackoverflow.com/a/51781436
type: Answer
has comment: http://stackoverflow.com/comment/90520510
upvote count: 2
answers question: http://stackoverflow.com/q/51781254
has body: You can add the new values in the initial list with changing the key and removing the initial values yourdict[j+'_'+str(num)] = yourdict.pop(j) keys() returns all the keys of a dict (name, age, country in your case) a = {'namelist': [{'name':"John",'age':23,'country':'USA'}, {'name':"Mary",'age':12,'country':'Italy'}, {'name':"Susan",'age':32,'country':'UK'}]} num = 1 for i in a['namelist']: for j in list(i.keys()): i[j+'_'+str(num)] = i.pop(j) num += 1 print(a) # {'namelist': [ # {'name_1': 'John', 'country_1': 'USA', 'age_1': 23}, # {'name_2': 'Mary', 'country_2': 'Italy', 'age_2': 12}, # {'name_3': 'Susan', 'age_3': 32, 'country_3': 'UK'}]}
has comment: http://stackoverflow.com/comment/90520390
downvote count: 0
score: 2

http://stackoverflow.com/q/51646568
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/91742850
has comment: http://stackoverflow.com/comment/90291923
has body: The release of Google Cloud Vision API had been on July 24, but what else was there later? There was no problem when using Document Text Detection of Vision API on July 25, but when I did the same thing on Augst 1, it became a error response "Bad image data". Not all images causes this error. Several images causes "Bad image data" response. Using the not Document Text Detection but Text Detection API, I can get the correct response. Does anyone else have the same problem? My code is following. import io import os # Imports the Google Cloud client library from google.cloud import vision from google.cloud.vision import types def detect_document(path): """Detects document features in an image.""" client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.document_text_detection(image=image) document = response.full_text_annotation print response for page in document.pages: for block in page.blocks: block_words = [] for paragraph in block.paragraphs: block_words.extend(paragraph.words) block_symbols = [] for word in block_words: block_symbols.extend(word.symbols) block_text = '' for symbol in block_symbols: block_text = block_text + symbol.text print(block_text) print(block.bounding_box) detect_document('test.jpg') Response is following. error { code: 3 message: "Bad image data." }
has comment: http://stackoverflow.com/comment/90297375
has comment: http://stackoverflow.com/comment/90304040
upvote count: 5
answer count: 0
has title: Document Text Detection API respond error "Bad image data" since July 25 or later
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90665166
tagged with: google-cloud-vision
has comment: http://stackoverflow.com/comment/90661589
has comment: http://stackoverflow.com/comment/90659030
favorite count: 0
has comment: http://stackoverflow.com/comment/90265003
type: Question
has comment: http://stackoverflow.com/comment/90625959

http://stackoverflow.com/a/75776883
answers question: http://stackoverflow.com/q/51770608
upvote count: 5
score: 5
has body: Removal There are multiple methods available 1. Using the chrome-developer-protocol with Page.removeScriptToEvaluateOnNewDocument like in Selenium-Profiles With Python # driver already initialized here driver.execute_cdp_cmd("Page.removeScriptToEvaluateOnNewDocument", {"identifier":"1"}) see docs for other programming-languages 2. Using the chrome-developer-protocol with Page.addScriptToEvaluateOnNewDocument using a script from undetected-chromedriver With Python # driver already initialized here js = """ let objectToInspect = window, result = []; while(objectToInspect !== null) { result = result.concat(Object.getOwnPropertyNames(objectToInspect)); objectToInspect = Object.getPrototypeOf(objectToInspect); } result.forEach(p => p.match(/.+_.+_(Array|Promise|Symbol)/ig) &&delete window[p]&&console.log('removed',p)) """ driver.execute_cdp_cmd("Page.removeScriptToEvaluateOnNewDocument", {"source":js}) Note that this one might be detectable. 3. By patching the compiled chromedriver. Meaning just remove all occurrences of cdc_* in the chromedriver-binary :) For a Python script, see undetected_chromedriver/patcher.py Details The window.cdc_adoQpoasnfa76pfcZLmcfl_Xxxxx variables get added from chromedriver on every new page using the using the chrome-developer-protocol with Page.addScriptToEvaluateOnNewDocument with the script: (function () { window.cdc_adoQpoasnfa76pfcZLmcfl_Array = window.Array; window.cdc_adoQpoasnfa76pfcZLmcfl_Object = window.Object; window.cdc_adoQpoasnfa76pfcZLmcfl_Promise = window.Promise; window.cdc_adoQpoasnfa76pfcZLmcfl_Proxy = window.Proxy; window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol = window.Symbol; }) (); Fortunately, it's always the first script ==> identifier="1". That's also, why 1.method works. They seem to be hardcoded into chromedriver and used for making shure, that chromedriver still works in case javascript properties get overwritten code Note: I am the developer of Selenium-Profiles
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90482579
type: Comment
has text: @VegardKT, I included few script in which I am changing target variable which in "group" to onehotcoding and train_data_features contain feature which is used to train model , I am using python 3.5 version and windows 10, I am not sure whether it is issue with multiprocessing
comment on: http://stackoverflow.com/q/51760851
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90335223
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51674874
type: AnswerComment
has text: It works super great now!!! Thank you so much! Do you happen to have any idea how I could fetch the whole rows from the matching names along with them? :)

http://stackoverflow.com/a/51743523
has body: If you set the starting point at -2 instead of zero, it finds the left root. If you use [-2., 0] instead fsolve return both roots (see this answer): x, info, flag, msg = fsolve(gamma, [-2., 0], args=(k), full_output=True) print(x) # [-1. 1.49999586] The difficult question is how to choose the starting points...
score: 0
has comment: http://stackoverflow.com/comment/90447931
has comment: http://stackoverflow.com/comment/90474046
type: Answer
has comment: http://stackoverflow.com/comment/90454471
answers question: http://stackoverflow.com/q/51742171

http://stackoverflow.com/q/51699779
tagged with: opencv
has answer: http://stackoverflow.com/a/51737457
has answer: http://stackoverflow.com/a/51702647
score: 4
linked to: http://stackoverflow.com/q/9413216
type: Question
upvote count: 4
has title: How to find rotate and crop a section of text in openCV, python
tagged with: raspberry-pi
has body: I'm in a struggle with a project that takes an image of a pretty clear font from say a label for example reads the "text region" and outputs it as a string using OCR tesseract for instance. Now I've made quite some progress with the thing as I added varios global filters to get to a quite clear result but I'm struggling with finding method of filtering just the text out of there and then you have to think about rotating it to be as horizontal as possible and then after that the easy part should be to crop it. May I have any leads to how to do that not using traning data and over complicating the system sins I only use a rasdpberry pi to do the computing? Thanks for helping here's what I've came up with so far: Original Image(Captured from PiCamera): Adaptive thresh after shadow removal: [ Glocad tresh after shadow removal: Here's the code: # import the necessary packages from PIL import Image import pytesseract import argparse import cv2 import os import picamera import time import numpy as np #preprocess = "tresh" #Remaining textcorping and rotating: import math import json from collections import defaultdict from scipy.ndimage.filters import rank_filter def dilate(ary, N, iterations): """Dilate using an NxN '+' sign shape. ary is np.uint8.""" kernel = np.zeros((N,N), dtype=np.uint8) kernel[(N-1)/2,:] = 1 dilated_image = cv2.dilate(ary / 255, kernel, iterations=iterations) kernel = np.zeros((N,N), dtype=np.uint8) kernel[:,(N-1)/2] = 1 dilated_image = cv2.dilate(dilated_image, kernel, iterations=iterations) return dilated_image def props_for_contours(contours, ary): """Calculate bounding box &amp; the number of set pixels for each contour.""" c_info = [] for c in contours: x,y,w,h = cv2.boundingRect(c) c_im = np.zeros(ary.shape) cv2.drawContours(c_im, [c], 0, 255, -1) c_info.append({ 'x1': x, 'y1': y, 'x2': x + w - 1, 'y2': y + h - 1, 'sum': np.sum(ary * (c_im &gt; 0))/255 }) return c_info def union_crops(crop1, crop2): """Union two (x1, y1, x2, y2) rects.""" x11, y…
linked to: http://stackoverflow.com/q/36255654
downvote count: 0
has answer: http://stackoverflow.com/a/51755867
favorite count: 0
answer count: 3
tagged with: python
tagged with: text
tagged with: python-tesseract
linked to: http://stackoverflow.com/q/51751953
type: UnansweredQuestion

http://stackoverflow.com/a/51775840
has comment: http://stackoverflow.com/comment/90512785
accepted answer of: http://stackoverflow.com/q/51775812
has body: Python works differently from the english language. if noun2[:1]=='a' or 'e' or 'i' or 'o' or 'u': should be if noun2[:1]=='a' or noun2[:1]=='e' or noun2[:1]=='i' or noun2[:1]=='o' or noun2[:1]=='u': Something like this would be a better way to do it if noun2[:1] in 'aeiou': This question has been previously answered here. You can read more about logical OR here.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51775812
has comment: http://stackoverflow.com/comment/90514697

http://stackoverflow.com/comment/90364755
type: Comment
has text: Why did U use na_position='first'? If U use sum null values as a key.
comment on: http://stackoverflow.com/a/51701800
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90370185
comment on: http://stackoverflow.com/q/51703661
score: 0
has text: Maybe you are looking for this? https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve
type: QuestionComment
type: Comment

redis
tags question: http://stackoverflow.com/q/51656516
tags question: http://stackoverflow.com/q/51722759
tags question: http://stackoverflow.com/q/51739878
tags question: http://stackoverflow.com/q/51647594
tags question: http://stackoverflow.com/q/51734952
tags question: http://stackoverflow.com/q/51780526
type: Tag
tags question: http://stackoverflow.com/q/51703391
tags question: http://stackoverflow.com/q/51688505
tags question: http://stackoverflow.com/q/51661915
tag name: redis
tags question: http://stackoverflow.com/q/51773588

http://stackoverflow.com/q/51732867
tagged with: seaborn
has comment: http://stackoverflow.com/comment/92104319
downvote count: 1
has answer: http://stackoverflow.com/a/51733133
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90426740
score: 7
has comment: http://stackoverflow.com/comment/90426859
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90426657
accepted answer: http://stackoverflow.com/a/51733133
has body: I have 2 data sets in Pandas Dataframe and I want to visualize them on the same scatter plot so I tried: import matplotlib.pyplot as plt import seaborn as sns sns.pairplot(x_vars=['Std'], y_vars=['ATR'], data=set1, hue='Asset Subclass') sns.pairplot(x_vars=['Std'], y_vars=['ATR'], data=set2, hue='Asset Subclass') plt.show() But all the time I get 2 separate charts instead of a single one How can I visualize both data sets on the same plot? Also can I have the same legend for both data sets but different colors for the second data set?
favorite count: 0
has comment: http://stackoverflow.com/comment/90426514
upvote count: 8
has title: Seaborn plot two data sets on the same scatter plot
tagged with: pandas
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/51734009
type: Question
has comment: http://stackoverflow.com/comment/90429587
has title: ImportError: No module named Tkinter
score: -1
has answer: http://stackoverflow.com/a/51735372
has body: My object_detection code is running perfectly on Jupyter Notebook. However, when i execute it after converting to .py file. Following error is throwing. [root@linux object_detection]# python object_detection_tutorial.py Traceback (most recent call last): File "object_detection_tutorial.py", line 22, in &lt;module&gt; from matplotlib import pyplot as plt File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in &lt;module&gt; from . import tkagg # Paint image to Tk photo blitter extension. File "/usr/lib64/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in &lt;module&gt; from six.moves import tkinter as Tk File "/usr/lib/python2.7/site-packages/six.py", line 203, in load_module mod = mod._resolve() File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve return _import_module(self.mod) File "/usr/lib/python2.7/site-packages/six.py", line 82, in _import_module __import__(name) ImportError: No module named Tkinter Python Version: 2.7 Linux : RHEL
answer count: 1
duplicate of: http://stackoverflow.com/q/43657590
favorite count: 0
has comment: http://stackoverflow.com/comment/90428825
has comment: http://stackoverflow.com/comment/90430515
tagged with: rhel
type: UnansweredQuestion
tagged with: python
upvote count: 0
linked to: http://stackoverflow.com/q/43657590
downvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/90514077
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51777830
type: QuestionComment
has text: So if I understand correctly, you need to get exception info in a variable? Is that correct, while still be able to log this? why not something like `globalVar = sys.exc_info()` inside the `try: except:` block and simply using `logging.exception` ? or saving `traceback.format_exc()` to a variable and passing that variable to `logging.error` as you are doing?

http://stackoverflow.com/comment/90551444
score: 1
has text: Have you had a look at https://stackoverflow.com/questions/30313872/using-a-label-in-a-having-clause-in-sqlachemy/30320526#30320526? Note that referencing a column alias in HAVING [is a MySQL extension](https://dba.stackexchange.com/questions/50391/why-does-mysql-allow-having-to-use-select-aliases), and I'm fairly certain that any optimizer worth its salt would not actually perform the subquery twice, even if the original query looks that way.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51793704

http://stackoverflow.com/comment/90410135
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51721466
has text: Could you explain a bit more why you are not happy choosing the template with the highest inlier percentage?
score: 0

http://stackoverflow.com/q/51720348
upvote count: 2
tagged with: python-2.7
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/51720395
tagged with: pandas
answer count: 1
has body: I have two DataFrames and I would like to take the median of one column grouped by a set of two other columns from dataframe A and then merge the calculated median into dataframe B. Let me explain it using the example below: I have two DataFrames which look like # DataFrame 1 pu_c do_c fare 0 0 5 10 1 0 5 20 2 1 1 3 # DataFrame 2 pu_c do_c 0 0 3 1 0 5 2 1 1 I would like to take the median of fare grouped by pu_c and do_c using: a = df1.groupby(['pu_c', 'do_c']).median()['fare'] which will result in: pu_c do_c 0 5 15 1 1 3 Now I want to merge the median fare calculated in a from df1 into another dataframe such as df2. I know how to do it using the for loops and messy code. I am wondering if there is an efficient way to do it using pandas' merge or concat functions. My desired output in this example is pu_c do_c median_fare 0 0 3 NaN (or whatever) 1 0 5 15 2 1 1 3 Note: to reproduce my dataframes use: import pandas as pd pu_c = [0, 0, 1] do_c = [5, 5, 1] do_c2 = [3, 5, 1] fare = [10, 20, 3] df1 = pd.DataFrame({'pu_c': pu_c, 'do_c': do_c, 'fare': fare}) df2 = pd.DataFrame({'pu_c': pu_c, 'do_c': do_c2})
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51720395
has title: How to merge a dataframe with MultiIndex into another dataframe in an efficient way?

http://stackoverflow.com/q/51661375
tagged with: python
tagged with: dictionary
tagged with: list
tagged with: duplicates
has comment: http://stackoverflow.com/comment/90286205
type: Question
tagged with: debugging
has body: I am a beginner in python, and I would like to create a simple program that assigns each element in list1 to its respective element in list2 using the zip function. list1=[1,2,3,4,1] list2=[2,3,4,5,6] dictionary=dict(zip(list1,list2)) print(dictionary) However, because I have a duplicate value in list1, the dictionary displays the following results: {1: 6, 2: 3, 3: 4, 4: 5} Because 1 is a duplicate value in list1, only 1:6 is displayed and not 1:2 as well. How can I change my code such that the duplicate value is taken into account and is displayed in its respective order? {1: 2, 2: 3, 3: 4, 4: 5, 1: 6} Thank you
has comment: http://stackoverflow.com/comment/90286361
has answer: http://stackoverflow.com/a/51661631
has comment: http://stackoverflow.com/comment/90286376
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90286196
has comment: http://stackoverflow.com/comment/90286149
favorite count: 0
has comment: http://stackoverflow.com/comment/90286391
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has title: How can I deal with duplicate values when creating a dictionary in Python?

http://stackoverflow.com/comment/90364244
type: Comment
comment on: http://stackoverflow.com/a/51700995
has text: Let me try to understand more. So when you said, "The first time the loop runs, it replaces a with* ", do you meant the letter 'a' in the string or the string a?? and also, if you meant the letter 'a', the logic would go wrong, as the condition evaluates to true only for the letter 'b' and secondly, if you meant the string a, then do you mean to say python/ the code replaces all but the first occurence of the letter 'b' in the word, in just the first iteration itself?? can you explain the flow here?? Thanks a lot
type: AnswerComment
score: 0

http://stackoverflow.com/q/51749631
has comment: http://stackoverflow.com/comment/90459889
tagged with: timeit
has answer: http://stackoverflow.com/a/51749679
type: Question
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51749952
has body: I'm timing element removal from a python set vs. a list. My timeit code for the list is raising a ValueError: ... x not in list, but only when I run more than one iteration with timeit !?? It appears that for the list, the variable created in the setup code is re-used in the subsequent iteration (as if the setup code is not run the second time??). Here's my code: In [1]: import timeit In [2]: timeit.timeit(stmt='a.discard(10**5)', setup='a = set(range(10**6))', number=100000) Out[2]: 0.02187999989837408 In [3]: timeit.timeit(stmt='a.remove(10**5)', setup='a = list(range(10**6))', number=1) Out[3]: 0.023419374600052834 In [4]: timeit.timeit(stmt='a.remove(10**5)', setup='a = list(range(10**6))', number=2) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ... ValueError: list.remove(x): x not in list What's going on??
favorite count: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/51749952
tagged with: python
has title: python's timeit is not initialising list in setup code
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51749731
tagged with: set
has comment: http://stackoverflow.com/comment/90461251
possible better answer: http://stackoverflow.com/a/51749679
upvote count: 1

http://stackoverflow.com/q/51761768
tagged with: pycharm
score: 1
upvote count: 1
type: AnsweredQuestion
has title: Python 2 type code-completion in JetBrains?
has answer: http://stackoverflow.com/a/51762162
type: Question
tagged with: python-2.7
answer count: 2
downvote count: 0
tagged with: docstring
favorite count: 0
has body: class A: """ A Attributes: type (int): type field required ([str]): required field """ type = None # type: str required = None # type: [str] def __init__(self, type, required): """ The constructor for A class. Parameters: type (int): type field required ([str]): required field """ self.type = type self.required = required Which works for strings: But not lists:
tagged with: python-sphinx
tagged with: python
possible better answer: http://stackoverflow.com/a/51761824
accepted answer: http://stackoverflow.com/a/51762162
has answer: http://stackoverflow.com/a/51761824

http://stackoverflow.com/comment/90512002
type: AnswerComment
has text: Fantastic. Thank you very much
type: Comment
comment on: http://stackoverflow.com/a/51776365
score: 0

http://stackoverflow.com/q/51672962
tagged with: qtablewidget
has title: QTableWidget or QTableView for toggling cell images
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51679117
has body: I am looking for a guidance over here. I want to have a a table with rows of data. One of the column is empty dedicated to user input. if user likes the data in the row clicking on the empty cell will display an image i.e. heart. if user changes her/his mind later clicking on the image will erase it. I am not sure of QTableView will support it functionality. If I am wrong with my assumption that it can be done with QTableView or QTableWidget, i appreciate any guidance in the right direction. Thanks in advance.
type: Question
tagged with: python
tagged with: qtableview
tagged with: pyqt5
upvote count: 1
accepted answer: http://stackoverflow.com/a/51679117
answer count: 1

http://stackoverflow.com/q/51790199
type: Question
has answer: http://stackoverflow.com/a/51790340
has body: Say I have a condition that if a number ends with.00 add 2 to it and if a number ends with.99 add 3 to it. So if I had 5.00 and 5.99, I want to write a nested if statement that would allow me to add the right value to the original number based on its ending. How to do that in R (or python)?
tagged with: if-statement
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/90537829
tagged with: http://stackoverflow.com/tag/r
tagged with: nested-if
has answer: http://stackoverflow.com/a/51790246
has answer: http://stackoverflow.com/a/51790333
accepted answer: http://stackoverflow.com/a/51790340
favorite count: 0
possible better answer: http://stackoverflow.com/a/51790246
upvote count: 2
downvote count: 2
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51790272
has title: Conditional If statements with decimal constraints
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90538383
has comment: http://stackoverflow.com/comment/90537940

http://stackoverflow.com/q/51662866
has answer: http://stackoverflow.com/a/51691711
has body: I'm trying to copy a large number of files from one directory to another. However, in trying to speed up the process by using Threading I get an error where it complains about too many open files. Currently the test batch of files is around 700+ and below is the code. How do I fix this? In my example, I'm copying files from one location on the network to another location on the same network and files range from 1mb to 100mb. def copy_file_to_directory(file, directory): ''' Description: Copies the file to the supplied directory if it exists ''' if os.path.isfile(file): url = os.path.join(directory, os.path.basename(file)) try: shutil.copyfile(file, url) shutil.copystat(file, url) return True except IOError as e: print (e) return False def copy_files_to_directory(files, directory): ''' Directory: Copy a list of files to directory, overwriting existing files ''' if not os.path.isdir(directory): os.makedirs(directory) if not os.path.isdir(directory): return False workers = [] for x in files: if os.path.isfile(x): worker = threading.Thread(target=copy_file_to_directory, args=(x,directory)) workers.append(worker.start()) # wait until they are all done processing for x in workers: x.join() return True files = [] # list of files copy_files_to_directory(files, 'C:/Users/John')
accepted answer: http://stackoverflow.com/a/51662940
has comment: http://stackoverflow.com/comment/90350832
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90340649
has comment: http://stackoverflow.com/comment/90345096
has comment: http://stackoverflow.com/comment/90321461
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90292445
tagged with: python
linked to: http://stackoverflow.com/q/18280612
has answer: http://stackoverflow.com/a/51662940
has title: Python copying mass number of files errors to many open files
possible better answer: http://stackoverflow.com/a/51691711
has comment: http://stackoverflow.com/comment/90289209

http://stackoverflow.com/q/51718969
has body: Curently I've a Django Application and it works perfect when using their models on my project. But when I try to create a new object when testing on my test.py it wont save tried debug and it returns for object.pk (None) Here is my code: class TestUserViews(TestCase): def test_authentication_success(self): try: cc = Country.objects.create(name="Lala Land") print('country saved') print(cc.id) print('-----') except Exception as error: print(error) try: ll = Language.objects.create(name="English") print('language saved') print(ll.id) print('-----') except Exception as error: print(error) try: user = User.objects.create(first_name="user name", last_name="user last", phone="000123455", identification="0000001123", address="my house", country=cc, language=ll, email="email@mail.com", password=hash_string("mypassword")) print('User saved') print(user.id) except Exception as error: print(error)
score: 0
has comment: http://stackoverflow.com/comment/90398830
has comment: http://stackoverflow.com/comment/90399161
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: MySQL not saving on test_ database when testing using Django
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/90415289

http://stackoverflow.com/q/51651243
tagged with: pandas
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51651337
favorite count: 0
tagged with: python-3.x
type: Question
possible better answer: http://stackoverflow.com/a/51651470
answer count: 2
tagged with: datetime
has answer: http://stackoverflow.com/a/51651470
tagged with: python
downvote count: 1
upvote count: 3
has answer: http://stackoverflow.com/a/51651337
has body: I have Date and timestamps in two different rows in Pandas DataFrame. Any pointer how to parse date and time together in one row which can be further used for time-series analysis further? e.g. Row 1 Date 2017-12-11 00:00:00 2017-12-11 00:00:00 2017-12-11 00:00:00 2017-12-11 00:00:00 Row 2 Timestamp 01:00:00 02:00:00 03:00:00 04:00:00 and then some more rows having more data Can Row 1 and Row 2 be combined together to have complete date/timestamp information together? I was thinking of applying Transpose and then using parse_dates on columns. Is there any other direct way of doing that in python?
has title: Parsing dates from two different rows in Pandas

http://stackoverflow.com/comment/90255422
has text: You can make your application fullscreen, do `.setMaximized()` or `.setFullScreen()`
comment on: http://stackoverflow.com/q/51645592
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51693319
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90607303
tagged with: slack-api
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: bots
downvote count: 0
score: 1
has title: slack python api delete message
has comment: http://stackoverflow.com/comment/90384011
type: Question
has answer: http://stackoverflow.com/a/67678829
accepted answer: http://stackoverflow.com/a/67678829
has body: I am trying to use my bot to delete certain messages in a slack channel with this api call import os import time import re from slackclient import SlackClient slack_client = SlackClient( 'xsssssseeeeeeee') slack_mute_bot_id = None def delete_message(slack_event): for event in slack_event: if event["type"] == "message": message_text = event['text'] time_stamp = event['ts'] channel_id = event['channel'] slack_client.api_call( 'chat.delete', channel=channel_id, ts=time_stamp, as_user=True ) print(message_text + " delted") if __name__ == "__main__": if slack_client.rtm_connect(with_team_state=False): slack_mute_bot_id = slack_client.api_call("auth.test")["user_id"] while True: # print(slack_client.rtm_read()) delete_message(slack_client.rtm_read()) time.sleep(1) else: print("Connection failed. Exception traceback printed above.") I do not get any error message after doing this and the bot does not delete the message. I am using the bot user token. I have benn able to send message succesfully but the delete method does not work and still gives np responses

http://stackoverflow.com/a/51690575
downvote count: 0
score: 1
has body: Here's what I ended up doing, effectively modeled off of @kabanus suggestions. Note I have another module called arguments1 that imports variables. import pandas as pd import numpy as np from arguments1 import * def common_value_solver(range): short_ma = arguments1.short_ma long_ma = arguments1.long_ma sum_short = range.tail(short_ma-1).sum() sum_long = range.tail(long_ma-1).sum() count_short = short_ma_arg count_long = long_ma_arg ptv = ((count_long * sum_short) - (count_short * sum_long) / (count_short - count_long)) return ptv
has comment: http://stackoverflow.com/comment/90346923
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51690079
answers question: http://stackoverflow.com/q/51690079
type: AcceptedAnswer

http://stackoverflow.com/comment/100248363
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/54582701
type: Comment
has text: @Ben Thank you, glad it helped revive another old system. Regarding the `import main` error, yeah, it's common nowadays past manual pip upgrades in most distro OSes, both Linux and Mac. I've covered a range of solutions in a related thread [here](https://stackoverflow.com/a/49988228/9575715)

http://stackoverflow.com/q/51771010
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90501274
has comment: http://stackoverflow.com/comment/90500886
type: Question
tagged with: google-sheets-api
answer count: 2
has title: How to copy a Google sheet with Python?
has answer: http://stackoverflow.com/a/51774195
upvote count: 3
downvote count: 1
has body: Is there a way to copy a Google Spreadsheet programatically using Python? I am using Gspread to manipulate my Google sheet, but there is no support for this functionality. Any suggestions?
tagged with: gspread
favorite count: 0
has answer: http://stackoverflow.com/a/51771123
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90500826

http://stackoverflow.com/comment/90417999
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51728551
has text: hi @ksooklall see edit. When I trained it for multiple epochs the weights diverged

http://stackoverflow.com/comment/90313627
score: 0
comment on: http://stackoverflow.com/a/51674871
type: AnswerComment
type: Comment
has text: actually I tried it sailesh's , answer is correct You can run the program like this: $ python tasks.py st1.txt

http://stackoverflow.com/q/51713844
favorite count: 0
has comment: http://stackoverflow.com/comment/90389608
tagged with: multiprocessing-manager
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90389669
duplicate of: http://stackoverflow.com/q/32815451
has comment: http://stackoverflow.com/comment/90389314
tagged with: http://stackoverflow.com/tag/html
tagged with: python
linked to: http://stackoverflow.com/q/28423069
has comment: http://stackoverflow.com/comment/90423143
answer count: 0
score: 1
duplicate of: http://stackoverflow.com/q/28423069
upvote count: 1
has comment: http://stackoverflow.com/comment/90401290
type: Question
tagged with: python-multiprocessing
has body: I'm have written a python script on a Raspberry Pi that controls a large and somewhat complex piece of hardware. Currently the use interface is a python console. I run the python program, and the can enter commands from the console with input("> "). Now I want to add a web interface to this program, and I'm trying to figure out the right way to do that. I've written a basic web UI in flask, but I haven't found a good way to connect the flask interface with the main script. Because the server controls a single piece of hardware, the main object (handling the hardware control) is only instantiated once. In addition, there is significant hardware configuration that must happen each time the script is run (each time the main object is created.) Flask seems to create a new thread for each client session, and only persist variable across that session. How can I link flask events (i.e, web user presses a button) to a method in the main object? Am I using the wrong tool for the job? What is the right tool? What is the correct way to do this? Alternatively, what is a jank way to do this? EDIT: The linked questions are similar, and led me down the path to the answer below, but they really didn't answer the question, so much as point to some code that solved that specific example. I think the below answer is far more helpful. (Of course I'm a bit biased; I wrote it) I found a solution, so I'll share it here. (I guess I can't answer my own questions?) The Flask Web App system (and all WSGI web apps?) rely on the principle that the web app can be executed in a totally fresh environment, without needing to be passed objects on creation. I guess this makes sense for Web Apps, but it adds a ton of annoying complexity to Web UIs, that is, web interfaces purpose built to interface a single instance of a larger program. As a hardware/solutions engineer, I tend to need a Web UI to control a single piece of hardware. If there is something better than flask for this purpose please leave …
tagged with: flask
has title: Connect Flask server with many threads to single server-side thread
has comment: http://stackoverflow.com/comment/90389938
downvote count: 0

http://stackoverflow.com/q/51683888
has comment: http://stackoverflow.com/comment/90333607
has comment: http://stackoverflow.com/comment/90332277
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90331319
has title: Django Disallowed Host
linked to: http://stackoverflow.com/q/21970750
answer count: 0
has comment: http://stackoverflow.com/comment/90331210
tagged with: host
type: Question
has body: I've been seraching the forums and also tried what most answers advised to. Error Msg: DisallowedHost at / Invalid HTTP_HOST header: 'theile-albrecht.de'. You may need to add u'theile-albrecht.de' to ALLOWED_HOSTS. Request Method: GET Request URL: http://theile-albrecht.de/ Django Version: 1.11.15 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'theile-albrecht.de'. You may need to add u'theile-albrecht.de' to ALLOWED_HOSTS. Exception Location: /usr/local/lib/python2.7/dist-packages/django/http/request.py in get_host, line 113 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Sat, 4 Aug 2018 08:33:11 +0000 That's what I did: ALLOWED_HOSTS = ['theile-albrecht.de'] I also tried: ALLOWED_HOSTS = ['*'] aswell as localhost After each try I restarted the server but didnt work
has comment: http://stackoverflow.com/comment/90334500
score: 0

http://stackoverflow.com/q/51699494
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
has title: AttributeError using scipy.sparse.toarray()
tagged with: sparse-matrix
accepted answer: http://stackoverflow.com/a/51699510
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: import scipy as sp import numpy as np a=sp.sparse.coo_matrix(np.random.randint(0,9,[4,5])) b=sp.sparse.coo_matrix(np.random.randint(0,9,[4,2])) sp.hstack([a,b]).toarray() is giving me AttributeError: 'numpy.ndarray' object has no attribute 'toarray' could you help me with my silly mistake here?
score: 1
has answer: http://stackoverflow.com/a/51699510
tagged with: scipy

http://stackoverflow.com/q/51783976
has comment: http://stackoverflow.com/comment/90526750
has comment: http://stackoverflow.com/comment/90526721
has body: I am too stupid to ask a question. A lot of literature mentioned that we need to compare the to-insert value with the value of "current Node". So basically, my question is: In order to insert a new Node into a tree, we need to enter a Node. Firstly, the tree has to check whether this Node is in it. If yes, then we need to enter a value, which will be compared and then inserted. class BTree: def __init__(self): self.root = None def isEmpty(self): if not self.root: print('tree is empty') return self.root def insert(self, Node, data): if not self.isEmpty(): print('the tree is empty, now is inserting ROOT') self.root = Node(data) else: current = self.root parent = None while True: #search the Node in the tree# #if it is in the tree, insert# It is too complicated, isn't it? Because we need even implement the search algorithm in the while loop. Could you please give me some suggestions? Thanks
tagged with: data-structures
has comment: http://stackoverflow.com/comment/90526467
score: 0
has comment: http://stackoverflow.com/comment/90526616
has comment: http://stackoverflow.com/comment/90525078
has comment: http://stackoverflow.com/comment/90525119
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90525070
answer count: 0
has comment: http://stackoverflow.com/comment/90527021
has comment: http://stackoverflow.com/comment/90526584
has title: Binary Search Tree: how to locate the "current Node" while inserting
type: Question

http://stackoverflow.com/q/51737178
tagged with: loops
type: Question
has body: I'm currently going through different Python3 challenges on Hackerrank and I ran into this problem that caught me off guard. I found the solution but I'm having trouble wrapping my mind around how it works. I'm familiar with loops in python but I can't seem to trace the code step by step. Problem You are given three integers X, Y, and Z representing the dimensions of a cuboid along with an integer N. You have to print a list of all possible coordinates given by on a 3D grid where the sum of is not equal to N. Input Format Four integers X, Y, Z, and N each on four separate lines, respectively. Constraints Print the list in lexicographic increasing order. Sample Input 1 1 1 2 Sample Output [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] Solution x, y, z, n = (int(input()) for _ in range(4)) print([[a, b, c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n])
score: 0
answer count: 1
tagged with: nested
has answer: http://stackoverflow.com/a/51737217
tagged with: python-3.x
has title: List Comprehensions and Loops
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51737217

http://stackoverflow.com/q/51707544
tagged with: plotly-dash
score: 0
has comment: http://stackoverflow.com/comment/90536570
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90528655
has title: Dash layout python
tagged with: excel
has body: I've been working on a dash application and I've ran into a bit of a pickle. My main issue is with the layout - I'm trying to format a dropdown menu which permits a user to select a worksheet, and then output the contents of that worksheet on the page. However I haven't been able to format it to display on the second page; I can only make it display on every page or none at all. Here is what I currently have for the layout (IE I want this to display on the timelinesDates page) - app.layout = html.Div([ dcc.Location(id='url', refresh=True), html.Div(id='page-content', children =[ html.H2("Select Target Company"), html.Div([dcc.Dropdown(id="field_dropdown", options=[{ 'label': i, 'value': i } for i in dropdown_options], value='Sheet3')], style={'width': '25%', 'display': 'inline-block'}), dt.DataTable(rows=[{}], row_selectable=False, sortable=False, selected_row_indices=[], id='datatable') ]) ]) @app.callback( dash.dependencies.Output('datatable', 'rows'), [dash.dependencies.Input('field_dropdown', 'value')]) @app.callback(dash.dependencies.Output('page-content', 'children'), [dash.dependencies.Input('url', 'pathname')]) def display_page(pathname): if pathname == '/' or pathname == '/overview': return overview elif pathname == '/timeline-dates': return timelineDates, def update_datatable(user_selection): if user_selection == 'Sheet1': return global_df_sheet_to_df_map.parse(0).to_dict('records') elif user_selection == 'Sheet2': return global_df_sheet_to_df_map.parse(1).to_dict('records') else: return global_df_sheet_to_df_map.parse(2).to_dict('records') elif pathname == '/further-analysis': return furtherAnalysis elif pathname =='/excel-data': return excelData elif pathname == '/full-view': return overview,timelineDates,furtherAnalysis, excelData else: return noPage
type: Question
has comment: http://stackoverflow.com/comment/90379925

http://stackoverflow.com/q/51692893
has comment: http://stackoverflow.com/comment/90353042
has answer: http://stackoverflow.com/a/51692973
answer count: 3
has comment: http://stackoverflow.com/comment/90347256
favorite count: 0
has title: Python regular expression return positions of string inside the parenthesis
has answer: http://stackoverflow.com/a/51692938
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51692963
has body: Using regular expression I'm trying to get the positions of string inside the parenthesis. For example I want to get the position of "Home Depot" ; sent = "Sales to two of the segment's customers, The Home Depot and Lowe's Home Improvement Warehouse, accounted for greater than 10% of the Corporation's consolidated sales for 2004, 2003, and 2002." regex_ = re.compile("Sales to two of the segment's customers, The (Home Depot) However, regex_.search(sent).span() returns (0, 55) not (45, 55) Since, there could be multiple "home depot" in sent, I am not able to use re.search('Home Depot', sent).span() which might not return the exact position of Home Depot I am looking for.
type: Question
score: -1

http://stackoverflow.com/comment/90344014
comment on: http://stackoverflow.com/a/51682637
type: AnswerComment
score: 0
type: Comment
has text: @Gabrielle what are we looking for without a threshold?

http://stackoverflow.com/comment/90507360
type: Comment
comment on: http://stackoverflow.com/a/51771086
has text: what happens when you manually debug this? does it right click on the element and can you see the menu options on the browser?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51788574
has comment: http://stackoverflow.com/comment/90536035
tagged with: python
tagged with: twilio
answer count: 0
type: UnansweredQuestion
has title: Twilio voice recording survey
type: Question
has body: I am creating an app using the twilio API. My goal is to record a series of answers by call recipient but I am facing an issue that with asking next question and stopping the recording, to stop the call with a key press I have provided finish_on_key instead of finishing the call, it is repeating the code and the question. I am not sure where i am going wrong with this. My code is not executing after response.record(finish_on_key='*').
has comment: http://stackoverflow.com/comment/90536305
score: 0

http://stackoverflow.com/q/51660672
has answer: http://stackoverflow.com/a/51660736
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
tagged with: python
has title: More complex logic with pandas loc?
has answer: http://stackoverflow.com/a/51660766
upvote count: 1
type: UnansweredQuestion
has body: If I want to match a column for multiple characteristics, i.e. df.loc[df['col1'] == (5 or 6), 'col2'] = 5 How can I do this? I tried this method but it did not work.

http://stackoverflow.com/q/51655119
score: 0
has body: So here's the idea: you can generate a spectrogram from an audio file using shorttime Fourier transform (stft). Then some people have generated something called a "binary mask" to generate different audio (ie. with background noise removed etc.) from the inverse stft. Here's what I understand: stft is a simple equation that is applied to the audio file, which generates the information that can easily be displayed a spectrogram. By taking the inverse of the stft matrix, and multiplying it by a matrix of the same size (the binary matrix) you can create a new matrix with information to generate an audio file with the masked sound. Once I do the matrix multiplication, how is the new audio file created? It's not much but here's what I've got in terms of code: from librosa import load from librosa.core import stft, istft y, sample_rate = load('1.wav') spectrum = stft(y) back_y = istft(spectrum) Thank you, and here are some slides that got me this far. I'd appreciate it if you could give me an example/demo in python
answer count: 1
tagged with: spectrogram
type: UnansweredQuestion
tagged with: python
tagged with: librosa
tagged with: audio
has answer: http://stackoverflow.com/a/51773435
type: Question
has title: How do I apply a binary mask and STFT to produce an audio file?
tagged with: linear-algebra

http://stackoverflow.com/a/53947807
has comment: http://stackoverflow.com/comment/94973687
accepted answer of: http://stackoverflow.com/q/51722253
downvote count: 0
has body: There is a new python package pyreadr that makes very easy import RData and Rds files into python: import pyreadr result = pyreadr.read_r('mtcars_nms.rdata') mtcars = result['mtcars_nms'] It does not depend on having R or other external dependencies installed. It is a wrapper around the C library librdata, therefore it is very fast. You can install it very easily with pip: pip install pyreadr The repo is here: https://github.com/ofajardo/pyreadr Disclaimer: I am the developer.
upvote count: 13
has comment: http://stackoverflow.com/comment/98036509
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/95010375
answers question: http://stackoverflow.com/q/51722253
type: Answer
score: 13

http://stackoverflow.com/comment/90539233
comment on: http://stackoverflow.com/q/51790793
has text: it's impossible to generate a wk start with those values given the input
score: 0
type: Comment
type: QuestionComment

string
tags question: http://stackoverflow.com/q/51649215
tags question: http://stackoverflow.com/q/51743530
tags question: http://stackoverflow.com/q/51744314
tags question: http://stackoverflow.com/q/51722546
tags question: http://stackoverflow.com/q/51755232
tags question: http://stackoverflow.com/q/51649149
tags question: http://stackoverflow.com/q/51647981
tags question: http://stackoverflow.com/q/51794693
tags question: http://stackoverflow.com/q/51675577
tags question: http://stackoverflow.com/q/51728576
tags question: http://stackoverflow.com/q/51659430
tags question: http://stackoverflow.com/q/51746290
tags question: http://stackoverflow.com/q/51784775
tags question: http://stackoverflow.com/q/51665191
tags question: http://stackoverflow.com/q/51690724
tags question: http://stackoverflow.com/q/51659503
tags question: http://stackoverflow.com/q/51741865
tags question: http://stackoverflow.com/q/51771831
tags question: http://stackoverflow.com/q/51716904
tags question: http://stackoverflow.com/q/51677514
tags question: http://stackoverflow.com/q/51687658
tags question: http://stackoverflow.com/q/51687318
tags question: http://stackoverflow.com/q/51678823
tags question: http://stackoverflow.com/q/51676365
tags question: http://stackoverflow.com/q/51682060
tags question: http://stackoverflow.com/q/51727274
tags question: http://stackoverflow.com/q/51718533
tags question: http://stackoverflow.com/q/51666374
tags question: http://stackoverflow.com/q/51641586
tags question: http://stackoverflow.com/q/51644051
tags question: http://stackoverflow.com/q/51752897
tags question: http://stackoverflow.com/q/51685853
tags question: http://stackoverflow.com/q/51758713
tags question: http://stackoverflow.com/q/51777082
tags question: http://stackoverflow.com/q/51640761
tags question: http://stackoverflow.com/q/51766834
tags question: http://stackoverflow.com/q/51668165
tags question: http://stackoverflow.com/q/51742085
tags question: http://stackoverflow.com/q/51706383
tags question: http://stackoverflow.com/q/51741691
tags question: http://stackoverflow.com/q/51773772
tags question: http://stackoverflow.com/q/51788857
tags question: http://stackoverflow.com/q/51655987
tags question: http://stackoverflow.com/q/51665129
tags question: http://stackoverflow.com/q/51701318
tag name: string
tags question: http://stackoverflow.com/q/51683877
tags question: http://stackoverflow.com/q/51667999
tags question: http://stackoverflow.com/q/51757710
tags question: http://stackoverflow.com/q/51694073
tags question: http://stackoverflow.com/q/51737010
tags question: http://stackoverflow.com/q/51781149
tags question: http://stackoverflow.com/q/51644984
tags question: http://stackoverflow.com/q/51784222
tags question: http://stackoverflow.com/q/51747078
tags question: http://stackoverflow.com/q/51766367
tags question: http://stackoverflow.com/q/51757162
tags question: http://stackoverflow.com/q/51674701
tags question: http://stackoverflow.com/q/51707067
tags question: http://stackoverflow.com/q/51756652
tags question: http://stackoverflow.com/q/51742799
type: Tag
tags question: http://stackoverflow.com/q/51700876
tags question: http://stackoverflow.com/q/51641812
tags question: http://stackoverflow.com/q/51745600
tags question: http://stackoverflow.com/q/51778480
tags question: http://stackoverflow.com/q/51748890
tags question: http://stackoverflow.com/q/51752211
tags question: http://stackoverflow.com/q/51781648
tags question: http://stackoverflow.com/q/51730643
tags question: http://stackoverflow.com/q/51664954
tags question: http://stackoverflow.com/q/51775953
tags question: http://stackoverflow.com/q/51690245
tags question: http://stackoverflow.com/q/51735607
tags question: http://stackoverflow.com/q/51656964
tags question: http://stackoverflow.com/q/51743092
tags question: http://stackoverflow.com/q/51672437
tags question: http://stackoverflow.com/q/51776454
tags question: http://stackoverflow.com/q/51658697
tags question: http://stackoverflow.com/q/51689892

http://stackoverflow.com/comment/90273034
type: AnswerComment
comment on: http://stackoverflow.com/a/51654453
type: Comment
has text: Ah ok, something so simple I overlook... Working on this now. I'll keep you updated.
score: 0

http://stackoverflow.com/q/51766109
has answer: http://stackoverflow.com/a/51788851
type: Question
has answer: http://stackoverflow.com/a/59272072
score: -1
upvote count: 2
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/90499719
has comment: http://stackoverflow.com/comment/90490693
tagged with: keras
favorite count: 0
type: UnansweredQuestion
has title: Error in importing Keras sequential model
tagged with: python
has body: I have installed keras followed by tensorflow. When I execute keras sequential model, I get an error message stating that from keras.models import sequential Using TensorFlow backend. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'sequential'
has comment: http://stackoverflow.com/comment/90490836
has comment: http://stackoverflow.com/comment/90491642

http://stackoverflow.com/q/51791406
type: Question
has comment: http://stackoverflow.com/comment/90540570
has comment: http://stackoverflow.com/comment/90540634
linked to: http://stackoverflow.com/q/8316176
answer count: 1
has answer: http://stackoverflow.com/a/51791816
has comment: http://stackoverflow.com/comment/90540803
has body: Here is my code to read from some data into MySql, the Mysql table contains 3 columns that in one of the columns I want to insert items of an array, each into a new row, and I do not want to have duplicate rows: db = MySQLdb.connect("127.0.0.1", "root", "M0", "my", local_infile=True,use_unicode=True, charset="utf8") cursor = db.cursor() r=["2","3"] params = ['?' for item in r] sql="insert ignore into array (firt,last_name,arrays) values 'nina','sa',(%s);" % ','.join(params) cursor.execute(sql,r) db.commit(); db.close() I have already looked into this post [1] as well ! However, on both of them I get this error: _mysql_exceptions.ProgrammingError: not all arguments converted during string formatting any suggestions, please?
accepted answer: http://stackoverflow.com/a/51791816
tagged with: python
linked to: http://stackoverflow.com/q/51824426
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90540512
tagged with: mysql
has title: Read from list into MySql
has comment: http://stackoverflow.com/comment/90540534

http://stackoverflow.com/comment/90428886
score: 0
type: Comment
type: QuestionComment
has text: @PMende actually I am thinking into approximating* rounding behaviour with a continous function I will make myself. I will check out variance of normalized gaussian, thanks for that.
comment on: http://stackoverflow.com/q/51733311

http://stackoverflow.com/comment/90364250
type: QuestionComment
score: 0
has text: you can do `cm_inc.site` or `cm_inc['site']` (`cm_inc` is a DataFrame with 1 column)
type: Comment
comment on: http://stackoverflow.com/q/51698989

http://stackoverflow.com/comment/90526181
comment on: http://stackoverflow.com/q/51762389
type: Comment
type: QuestionComment
has text: Possible duplicate of [Django : Unable to run server](https://stackoverflow.com/questions/48585988/django-unable-to-run-server)
score: 0

http://stackoverflow.com/q/51702747
upvote count: 1
has comment: http://stackoverflow.com/comment/90366564
answer count: 0
type: UnansweredQuestion
tagged with: flask
has title: Is every flask request run on a separate thread?
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/38876721
favorite count: 0
type: Question
tagged with: multithreading
tagged with: python
has body: The following is my code : from flask import Flask app = Flask(__name__) @app.route('/hello/&lt;value&gt;') def hello_world(value): if value == "1": while True: print('hello') else: return 'Hello '; if __name__ == '__main__': app.run() I wrote this code to see whether the flask app spawns a thread with each request or not. I opened two tabs where in the first tab I passed the value as '1' and '2' to the other. The first blocked the tab and second displayed 'Hello' on the browser. My query is whether each request to a flask server is run on a separate thread ? If yes why do we have the following feature in flask ? app.run(threaded=True)
has comment: http://stackoverflow.com/comment/90371438
duplicate of: http://stackoverflow.com/q/38876721

http://stackoverflow.com/q/51738137
has body: I am currently constructing a function with the inputs (Location, Time) "City, State, Country" and "Year-Month-Day Hour:Min:Sec" with the output of sidereal time that can be used in astronomical calculations. Currently I am passing the location through geopy to find the longitude/latitude and then using timezonefinder to find the exact time zone. From there I am using pytz to convert my local time to UTC while taking into account DST. I have a database built in which I can find the sidereal time using that converted Time and Date. My issue is to be accurate I can not use the local time I need to use the local mean time, which is the local time adjusted depending on how far away it is from the time zone meridian. For example if your city has a longitude of -80 and is in America/New_York (Eastern Time) the meridian which actually lines up with the sun is -75 Longitude meaning you are actually 20 minutes earlier then Eastern Time with respect to the sun. But because of DST and the fact that the timezones are not really treated as uniform segments on a map, I can not find a solid way of calculating this difference. The best way I can think of doing it is to convert my location into a long/lat. Find the time zone for that location and then covert that timezone somehow into the meridian. I will post my code for others who work better with visuals. from timezonefinder import TimezoneFinder import geopy.geocoders, pytz, certifi, ssl, datetime, ephem, math def position(city, state, country): """ :param city: String of city Ex. Chattannoga :param state: String of state Ex. TN :param country: String USA :return: latitude and longitude """ ctx = ssl.create_default_context(cafile=certifi.where()) geopy.geocoders.options.default_ssl_context = ctx geo_locator = geopy.geocoders.Nominatim(user_agent="my-application", scheme='http') location = geo_locator.geocode(city + ' ' + state + ' ' + country) return location.longitude, location.latitude def timezone(longitude, latitude): """ :p…
tagged with: latitude-longitude
tagged with: time
tagged with: timezone
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90484634
tagged with: python
has title: Python: Finding Local Mean Time (Adjusted for the distance in longitude from the locations time zone meridian)
type: Question
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/52307029

http://stackoverflow.com/comment/90460561
has text: @JeremyFriesner Although both talks about seg fault, it seems that they are trying to figure out what/when/how, I gave up of that.. I just want to handle the issue
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51750173

http://stackoverflow.com/comment/90516018
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51778992
has text: Unless you provide the test code and the full exception we will not be able to help you. Please [edit] these details into your question.
score: 0

http://stackoverflow.com/comment/90307621
type: Comment
has text: I want to return the tuple itself, or any data that is available in the object attributes. But not the string representation. That was just an attempt.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51672331

http://stackoverflow.com/q/51740108
tagged with: buffer
has title: BufferError: could not get scalar buffer information
type: UnansweredQuestion
tagged with: python
upvote count: 4
has body: import multiprocessing as mp def parallel_apply(data, fun, args): pool = mp.Pool(mp.cpu_count() - 1) result = [pool.apply(fun, (data.loc[x, :], *args)) for x in data.index] result = [p.get() for p in result] end_result = pd.concat(result) return end_result from this part of code i get following error: "BufferError: could not get scalar buffer information". I've tried several things but non of them worked. any sugesstion? thanks for help
downvote count: 0
tagged with: memory
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
score: 4
has answer: http://stackoverflow.com/a/51770875
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51759005
tagged with: beautifulsoup
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51759332
score: 0
answer count: 1
tagged with: urllib2
has title: Python, Beautifulsoup, CSV Array Output
has body: I've been trying to figure this out for a while.. but being new to Python and BS I'm not getting far. Here's the code: import urllib2 import csv from bs4 import BeautifulSoup urls = ["https://coinmarketcap.com/currencies/bitcoin/historical-data/", "https://coinmarketcap.com/currencies/ethereum/historical-data/", "https://coinmarketcap.com/currencies/ripple/historical-data", "https://coinmarketcap.com/currencies/bitcoin-cash/historical-data", "https://coinmarketcap.com/currencies/litecoin/historical-data"] for url in urls: page = urllib2.urlopen(url) soup = BeautifulSoup(page, "html.parser") row = soup.find("tr", attrs={"class":"text-right"}) row2 = row.find_all("td") print (row2[0].text, row2[1].text, row2[2].text, row2[3].text, row2[4].text, row2[5].text) Print Output: (u'Aug 08, 2018', u'6746.85', u'6746.85', u'6226.22', u'6305.80', u'5,064,430,000') (u'Aug 08, 2018', u'379.89', u'380.67', u'353.73', u'356.61', u'2,016,080,000') (u'Aug 08, 2018', u'0.380875', u'0.380875', u'0.326996', u'0.331944', u'360,857,000') (u'Aug 08, 2018', u'660.05', u'660.05', u'575.64', u'585.45', u'450,595,000') (u'Aug 08, 2018', u'68.16', u'68.16', u'62.14', u'62.49', u'313,187,000') The 'Print Output' as above, is how I want the csv output to look.. however when I add the code for the csv writer I only get the last row of data from the array: with open("hello world.csv",'wb') as f: wr = csv.writer(f) wr.writerows([(row2[0].text, row2[1].text, row2[2].text, row2[3].text, row2[4].text, row2[5].text)]) writerows Output: (u'Aug 08, 2018', u'68.16', u'68.16', u'62.14', u'62.49', u'313,187,000') Any help in making the csv output the same as the print would be greatly apprecaited! Many thanks, OM
accepted answer: http://stackoverflow.com/a/51759332
type: AnsweredQuestion

http://stackoverflow.com/comment/90330923
type: Comment
has text: If you still don't get it, Create a repo on Github I will make changes to it directly.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51683649

http://stackoverflow.com/a/51715882
accepted answer of: http://stackoverflow.com/q/51715599
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51715599
downvote count: 0
has comment: http://stackoverflow.com/comment/90394092
type: Answer
has body: There are some setups where you have a bunch of packages installed somewhere that isn't the normal install location for setuptools, and comes after the normal install location on sys.path. Probably the most common of these setups is Apple's pre-installed Python 2.7, so I'll use it as an example. Even if that isn't your setup, it will be hopefully still be instructive. Apple includes an Extras directory (at /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), with a bunch of third-party packages that either Apple's own tools need, or that Apple thought you might want (back when Apple cared about providing the best Python experience of any platform). For example, on macOS 10.13, that directory will include NumPy 1.8.0. These packages are all installed as distribute-style eggs. (Some linux distros do, or at least used to do, similar things, with Python packages built as RPM/DEB/etc. packages, which go into adistutils directory, unlike things you install via pip or manually, which go into a setuptools directory. The details are a bit different, but the effects, and the workaround, end up being the same.) If you install pip, and then try to pip install -U numpy or pip uninstall numpy, pip will see the distribute-style numpy-1.8.0rc1-py2.7.egg-info file and refuse to touch it for fear of breaking everything. If you just pip install numpy, however, it will look only in the standard site-packages installation location used by setuptools, /Library/Python/2.7/site-packages, see nothing there, and happily install a modern version of NumPy for you. And, because /Library/Python/2.7/site-packages comes before /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python on your sys,path, the new NumPy will hide the ancient NumPy, and everything will just work as intended. There can be a few problems with this. Most notably, if you try to install something which isn't included in Extras itself, but which has a dependency that is included in Ext…
upvote count: 1

http://stackoverflow.com/comment/90292638
comment on: http://stackoverflow.com/q/51664603
score: 0
type: Comment
type: QuestionComment
has text: in views.py, there is no code for password_change. It is the inbuilt authentication feature provided by django. @JerinPeterGeorge

http://stackoverflow.com/comment/90507667
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51774300
has text: What's the problem you're having?
score: 0

http://stackoverflow.com/q/51661980
tagged with: pandas
has comment: http://stackoverflow.com/comment/90288385
accepted answer: http://stackoverflow.com/a/63927754
tagged with: python
has comment: http://stackoverflow.com/comment/90287734
has answer: http://stackoverflow.com/a/51662775
has answer: http://stackoverflow.com/a/63927754
score: 6
tagged with: excel
type: AnsweredQuestion
has body: I need to read a very large Excel file into a DataFrame. The file has string, integer, float, and Boolean data, as well as missing data and totally empty rows. It may also be worth noting that some of the cell values are derived from cell formulas and/or VBA - although theoretically that shouldn't affect anything. As the title says, pandas sometimes reads Boolean values as float or int 1's and 0's, instead of True and False. It appears to have something to do with the amount of empty rows and type of other data. For simplicity's sake, I'm just linking a 2-sheet Excel file where the issue is replicated. Boolean_1.xlsx Here's the code: import pandas as pd df1 = pd.read_excel('Boolean_1.xlsx','Sheet1') df2 = pd.read_excel('Boolean_1.xlsx','Sheet2') print(df1, '\n' *2, df2) Here's the print. Mainly note row ZBA, which has the same values in both sheets, but different values in the DataFrames: Name stuff Unnamed: 1 Unnamed: 2 Unnamed: 3 0 AFD a dsf ads 1 DFA 1 2 3 2 DFD 123.3 41.1 13.7 3 IIOP why why why 4 NaN NaN NaN NaN 5 ZBA False False True Name adslfa Unnamed: 1 Unnamed: 2 Unnamed: 3 0 asdf 6.0 3.0 6.0 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN 5 ZBA 0.0 0.0 1.0 I was also able to get integer 1's and 0's output in the large file I'm actually working on (yay), but wasn't able to easily replicate it. What could be causing this inconsistency, and is there a way to force pandas to read Booleans as they should be read?
has comment: http://stackoverflow.com/comment/90287422
downvote count: 0
has title: Pandas.read_excel sometimes incorrectly reads Boolean values as 1's/0's
linked to: http://stackoverflow.com/q/4869189
possible better answer: http://stackoverflow.com/a/51662775
type: Question
answer count: 2
upvote count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/90287448

http://stackoverflow.com/q/51656247
upvote count: 0
accepted answer: http://stackoverflow.com/a/51661210
answer count: 1
has title: Python | How can i run a loop for x seconds and then break out of it without sleep?
has body: I have a while loop that checks for a variable to turn true. The problem is that if that variable dont turn true, it loops forever. Is there a way to make the while loop check for that variable for x seconds and then abandon the loop? This script is runned on a raspberry pi. The while loop is checking if a button has been pressed. If i let the loop be as it is, it will run the loop forever waiting for that button, the modification i want to make is to stop the while loop after 10 seconds or so if the button hasn t been pressed (the variable is still false).
has comment: http://stackoverflow.com/comment/90276416
has comment: http://stackoverflow.com/comment/90276122
has comment: http://stackoverflow.com/comment/90276202
has comment: http://stackoverflow.com/comment/90276940
has answer: http://stackoverflow.com/a/51661210
linked to: http://stackoverflow.com/q/492519
has comment: http://stackoverflow.com/comment/90276185
favorite count: 0
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/90276386
type: AnsweredQuestion
type: Question
tagged with: raspberry-pi
downvote count: 4

http://stackoverflow.com/a/51767623
has comment: http://stackoverflow.com/comment/90524624
has comment: http://stackoverflow.com/comment/90513702
score: 2
has body: Assuming you have a model like this, class SampleModel(models.Model): doc = models.FileField(upload_to='media/', null=True, blank=True) then do something like this to add file to model, from django.core.files import File myfile = open("sample.csv", 'r') sample = SampleModel.objects.create(doc=File(myfile)) UPDATE from django.core.files import File myfile = open("sample.csv", 'r') sample = Cancion.objects.create(csv=File(myfile))
downvote count: 0
has comment: http://stackoverflow.com/comment/90525139
upvote count: 2
has comment: http://stackoverflow.com/comment/90525489
has comment: http://stackoverflow.com/comment/90525629
type: Answer
has comment: http://stackoverflow.com/comment/90524938
has comment: http://stackoverflow.com/comment/90525544
has comment: http://stackoverflow.com/comment/90506924
has comment: http://stackoverflow.com/comment/90524533
has comment: http://stackoverflow.com/comment/90525285
accepted answer of: http://stackoverflow.com/q/51765879
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51765879

http://stackoverflow.com/q/51798050
favorite count: 0
tagged with: jupyter-notebook
has body: I recently installed the Anaconda Navigator (Anaconda 2) on a Windows 8.1 machine. If I launch Jupyter Notebook from the Anaconda window, I am met with a 'Page cannot be displayed' error in my browser (Chrome). I have tried launching Jupyter Notebook from the Anaconda Prompt (no notable error message output). I have also tried opening the Notebook in a different browser (Firefox), and I have tried running the Prompt in Administrator mode. No luck. I have Jupyter Notebook version 5.6.0 according to the Navigator, but if I type jupyter --version at the prompt it says 4.4.0 (wondering if this is a problem?) I kind of expected to be able to launch a Notebook right off the bat after installing Anaconda. Is there some set-up I have missed? (Edit) Tried a few more things, after reading the Jupyter Notebook docs. Tried replacing 'localhost' in the URL with 127.0.0.1, and tried opening the link Chrome with --disable-web-security. Didn't help.
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: anaconda
downvote count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51799298
has title: Can't launch Jupyter Notebook at all
answer count: 1
tagged with: jupyter

http://stackoverflow.com/comment/130446904
score: 0
type: Comment
type: QuestionComment
has text: Did you ever get an answer to this question btw?
comment on: http://stackoverflow.com/q/51739720

http://stackoverflow.com/comment/90424512
has text: Ok. Thank you! I will try that out.
type: Comment
comment on: http://stackoverflow.com/a/51730840
score: 0
type: AnswerComment

http://stackoverflow.com/q/51759314
has comment: http://stackoverflow.com/comment/90478156
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/90477963
linked to: http://stackoverflow.com/q/7243750
has answer: http://stackoverflow.com/a/51759473
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51761181
has body: I want to download data from https://download.bls.gov/pub/time.series/ln/ln.data.1.AllData to dataframe. I have tried below script, but could not succeeded. import requests, io import pandas as pd URL = 'https://download.bls.gov/pub/time.series/ln/ln.data.1.AllData' #1 urlData = requests.get(URL).content rawData = pd.read_csv(io.StringIO(urlData.decode('utf-8'))) print(len(rawData)) Error: Python IDLE Got Stuck #2 r = requests.get(URL) urlData = pd.read_csv(io.StringIO(r)) print(len(urlData)) Error:- urlData = pd.read_csv(io.StringIO(r)) TypeError: initial_value must be str or None, not Response #3 urlData = pd.read_csv(URL, header=None) print(len(urlData))
favorite count: 0
has comment: http://stackoverflow.com/comment/90478358
has comment: http://stackoverflow.com/comment/90477793
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90477849
possible better answer: http://stackoverflow.com/a/51761181
accepted answer: http://stackoverflow.com/a/51759473
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51759440
downvote count: 1
has comment: http://stackoverflow.com/comment/90478298
has comment: http://stackoverflow.com/comment/90477881
has title: Download data from URL in Python 3.6
type: AnsweredQuestion

http://stackoverflow.com/a/51752639
type: Answer
has comment: http://stackoverflow.com/comment/90466192
accepted answer of: http://stackoverflow.com/q/51752353
has body: This behavior is per the Module Search Path. When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. So, one answer is that you can manipulate sys.path, putting whichever directory you want to use first in the list. But, this doesn't really solve your long term issue. A better approach would be to organize your own code into Packages. Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. If you put your signal.py in a package myPkg, you could then import it specifically, using; import myPkg.signal This still might not solve all issues if you import both signal modules into the same script. However, you can assign a new module name on import using; import myPkg.signal as mySignal In a working directory create this structure; /path/to/myPkg/ __init__.py signal.py tests/ __init__.py test.py In test.py put something like this print '1' import signal print '2' import myPkg.signal as ms Now, to run this you want to add myPkg to PYTHONPATH, or for a quick check try it in the interpreter. NOTE: the cd to the parent directory of myPkg, not into myPkg. cd /path/to python &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/usr/lib/python27.zip', '/usr/lib/…
has comment: http://stackoverflow.com/comment/90465257
has comment: http://stackoverflow.com/comment/90466217
has comment: http://stackoverflow.com/comment/90468467
has comment: http://stackoverflow.com/comment/90465218
upvote count: 4
has comment: http://stackoverflow.com/comment/90469327
has comment: http://stackoverflow.com/comment/90465872
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/51752353
has comment: http://stackoverflow.com/comment/90466247

http://stackoverflow.com/comment/90492169
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51766679
score: 0
has text: What about using `extend` instead of `append` to remove the list of list problem? Something like `temp.extend(....)`

http://stackoverflow.com/q/51711450
type: Question
answer count: 1
favorite count: 0
has title: Combining detectors and descriptors for feature matching
has answer: http://stackoverflow.com/a/51770697
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/90384483
upvote count: 1
tagged with: python
tagged with: computer-vision
tagged with: opencv
has body: I have used Python OpenCv to match features (keypoints) using SIFT for instance. Here, SIFT has been used as a detector and descriptor. How can we use Harris corner for instance as a detector, and SIFT as a descriptor. Is there a code example that can show how we can combine some detector with another descriptor? Thanks.
tagged with: sift
score: -1
tagged with: image

http://stackoverflow.com/q/51693148
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51693191
tagged with: python
duplicate of: http://stackoverflow.com/q/17778372
type: AnsweredQuestion
has body: Sorry, i'm a complete beginner, just started yesterday. I have an issues with the below code. So, as long as I enter a number, it works fine and it will return as 'int' (that's what I need). But, if I enter anything else that triggers the number_validation() functions again, it will return as 'NoneType'. Any idea why or what am I doing wrong? Thanks for you help! def number_validation(): number = input("Please enter a number: ") if number == "": print("You need to enter a number") number_validation() elif number != "": if number.isdigit() == True: number = int(number) return number else: print("Numbers only, no spaces, please try again!") number_validation()
accepted answer: http://stackoverflow.com/a/51693191
has title: Python Code returns 'NoneType' instead of 'int'
type: Question
tagged with: nonetype
linked to: http://stackoverflow.com/q/17778372
tagged with: int

http://stackoverflow.com/comment/90407775
type: Comment
comment on: http://stackoverflow.com/a/51721906
score: 0
type: AnswerComment
has text: Guess we have different usage scenarios.

http://stackoverflow.com/a/51758952
accepted answer of: http://stackoverflow.com/q/51758626
downvote count: 0
score: 1
has body: I think need compare columns (Series): mask = extrasDF['currentWorkspaceGuid'].isin(workspacesDF['currentWorkspaceGuid']) in_workspaces = extrasDF[mask] print (in_workspaces) currentWorkspaceGuid modelGuid \ 0 8a81b09c56cdf89c0157345759d75644 635D5FAAC46D4856AAFD21AC6386DDCA 1 8a81948240d60b1901417a266a536462 4076B1A8B1E34D549FFFE9F5FFE4538A 2 402882f738cf7433013b612dc5f60bbd 4CA3CDC12CD349ABA8658365480073CA 3 8a8194884c860a53014ca1f6596d54e9 15E3E6B6087A4CA6838616A418E9657A 4 8a8194884a34d3ff014a4f31bea3705a C47D186A479140BFAB24AF8D24E8B2BA memoryUsage lastModified 0 1191785 2018-08-08 17:57:45 1 5400000 2016-09-13 18:32:50 2 550000 2017-11-23 16:26:10 3 830000 2018-05-22 17:35:50 4 816686 2018-07-31 09:39:16 For filter non matched values add ~ for invert boolean mask: not_in_workspaces = extrasDF[~mask] print (not_in_workspaces) Empty DataFrame Columns: [currentWorkspaceGuid, modelGuid, memoryUsage, lastModified] Index: [] Details: print (mask) 0 True 1 True 2 True 3 True 4 True Name: currentWorkspaceGuid, dtype: bool print (~mask) 0 False 1 False 2 False 3 False 4 False Name: currentWorkspaceGuid, dtype: bool
has comment: http://stackoverflow.com/comment/90477729
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90477558
type: Answer
answers question: http://stackoverflow.com/q/51758626
has comment: http://stackoverflow.com/comment/90507277

http://stackoverflow.com/q/51654961
has comment: http://stackoverflow.com/comment/90273417
has comment: http://stackoverflow.com/comment/90273587
has body: I have two models as follow : class Books(models.Model): poster = models.CharField(max_length=2000) bookid = models.CharField(max_length=10) title = models.CharField(max_length=150) year = models.IntegerField() def __str__(self): return self.title class UserRating(models.Model): userid = models.CharField(max_length=20) rating = models.CharField(max_length=5) bookid = models.CharField(max_length=10) In the views.py I get all the current logged in user rates and put it in bookid list : def rated(request): rate = UserRating.objects.filter(userid=request.user.id)[:5] bookid = [] for i in rates: bookid.append(i.bookid) What I want to do is getting every book poster by its bookid.diplaying all books that the user rated with its poster and the rate. How can I do that?
has comment: http://stackoverflow.com/comment/90273346
tagged with: django
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51655229
tagged with: django-models
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90273850
downvote count: 0
has title: Get data from a model based on a list from another model object
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90273450
type: Question
has comment: http://stackoverflow.com/comment/90273407
tagged with: python

http://stackoverflow.com/q/51787441
has answer: http://stackoverflow.com/a/51787687
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: multi-index
has body: I have a DataFrame with a MultiIndex. The first level is a DatetimeIndex with weekly frequency. The second level is NOT consistent across groupings by the first level. I want to group the first level by month and take the first weeks rows. Setup midx = pd.MultiIndex.from_arrays([ pd.date_range('2018-01-01', freq='W', periods=10).repeat(2), list('ABCDEFGHIJ' * 2) ], names=['Date', 'Thing']) df = pd.DataFrame(dict(Col=np.arange(10, 30)), midx) Expected Results df Col Date Thing 2018-01-07 A 10 # This is the first week B 11 # of January 2018 2018-01-14 C 12 D 13 2018-01-21 E 14 F 15 2018-01-28 G 16 H 17 2018-02-04 I 18 # This is the first week J 19 # of February 2018 2018-02-11 A 20 B 21 2018-02-18 C 22 D 23 2018-02-25 E 24 F 25 2018-03-04 G 26 # This is the first week H 27 # of March 2018 2018-03-11 I 28 J 29 Results should be Col Date Thing 2018-01-07 A 10 # This is the first week B 11 # of January 2018 2018-02-04 I 18 # This is the first week J 19 # of February 2018 2018-03-04 G 26 # This is the first week H 27 # of March 2018 Attempt df.unstack().asfreq('M', 'ffill').stack() Col Date Thing 2018-01-31 G 16.0 H 17.0 2018-02-28 E 24.0 F 25.0 This is wrong on several levels. Date is actual month end and not the actual date observed. Things are not from the correct date. Notice that I wanted ['A', 'B'] from '2018-01-07' and not ['G', 'H']. I'm unstacking to enable myself to use asfreq but that introduces nan and converts to float I don't know what happened to March 2018
type: Question
possible better answer: http://stackoverflow.com/a/51788396
tagged with: dataframe
answer count: 2
tagged with: pandas
upvote count: 1
has title: resample a MultiIndex
accepted answer: http://stackoverflow.com/a/51787687
favorite count: 0
has answer: http://stackoverflow.com/a/51788396

http://stackoverflow.com/q/51639866
has title: Joining DataFrame with multiple indexes
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51640242
has body: I'm taking a standard data frame and creating various sub-set data frames of summary data. These subsets will all be at double indexed with the first index being the same. I'm being asked to get all my summary data together (They want to create a single JSON for all summary data). I thought combining the data frames would be the easiest solution, but I'm having trouble. Standard Dataframe example: df ID DEPT STATUS TYPE 0 100 5001 Active E 1 101 5001 Active M 2 101 5001 Active M 3 102 5005 Expired E 4 107 5001 Inactive M 5 110 5002 Inactive E 6 110 5002 Inactive E I then create my summary data and rename the column: status_df = pd.DataFrame(df.groupby(['DEPT','STATUS'])['ID'].nunique()) status_df.columns = ['Count_Status'] Count_Status DEP STATUS 5001 Active 2 Inactive 1 5002 Inactive 1 5005 Expired 1 and again for the other column: type_df = pd.DataFrame(df.groupby(['DEPT','TYPE'])['ID'].nunique()) type_df.columns = ['Count_Type'] Count_Type DEP TYPE 5001 E 1 M 2 5002 E 1 5005 E 1 What I would like to create: Count_Status Count_Type DEP STATUS TYPE 5001 Active 2 NaN Inactive 1 NaN E NaN 1 M NaN 2 5002 Inactive 1 NaN E NaN 1 5005 Expried 1 NaN E NaN 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 3
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/51640242

http://stackoverflow.com/comment/90526193
score: 0
type: Comment
has text: @Arman Yes, I saw and commented some info about the root cause of issue.
comment on: http://stackoverflow.com/a/51767948
type: AnswerComment

http://stackoverflow.com/a/51697882
has comment: http://stackoverflow.com/comment/90357295
score: 0
has comment: http://stackoverflow.com/comment/90357573
has comment: http://stackoverflow.com/comment/90357532
has comment: http://stackoverflow.com/comment/90359359
type: Answer
has comment: http://stackoverflow.com/comment/90379706
answers question: http://stackoverflow.com/q/51697171
has body: lines = """&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"&gt; &lt;!-- Page 1 --&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" width="1198" height="1576" viewBox="0 0 1198 1576" version="1.1" style="display: block;margin-left: auto;margin-right: auto;"&gt; &lt;path d="M0,0 L0,1576 L1198,1576 L1198,0 Z " fill="#FFFFFF" stroke="none"/&gt; &lt;image preserveAspectRatio="none" x="0" y="0" width="1199" height="1577" xlink:href="https://cdn-assets.somewhere.com/f929e7b4404d3e48918cdc0ecd4efbc9fa91dab5_2734/9c237c7e35efe88878f9e5f7a3555f7a379ed9ee9d95b491b6d0003fd80afc6b/9c68a28d6b5161f7e975a163ff093a81172916e23c778068c6bfefcfab195154.jpg?q=80"/&gt; &lt;g fill="#112449"&gt; &lt;use xlink:href="#f0_2" transform="matrix(19.1,0,0,19.1,885.3,204.3)"/&gt; &lt;use xlink:href="#f0_o" transform="matrix(19.1,0,0,19.1,910,204.3)"/&gt; &lt;use xlink:href="#f0_t" transform="matrix(19.1,0,0,19.1,930.3,204.3)"/&gt; &lt;use xlink:href="#f0_f" transform="matrix(19.1,0,0,19.1,949.6,204.3)"/&gt;""" import re newlines = [] for line in lines.split('\n'): myregex = re.compile(r"(?:xlink:href\=\")(.*)(?:\?q=80\"\/\&gt;)") result = myregex.search(line) if result: print(result) #If a match is found, replace the text in the line origfullimgfilename = result.group(1) replfullimgfilename='page-##-img1.jpg' line = re.sub(origfullimgfilename, replfullimgfilename, line) newlines.append(line) print( '\n'.join(newlines) )

http://stackoverflow.com/a/51662874
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51651942
downvote count: 0
has body: You'll need to do a little more work to compute this. import numpy as np df = pd.DataFrame({'docId': [1,2,3], 'sent': ['This is the first sentence', 'This is the second sentence', 'This is the third sentence']}) # Tokenize and generate count vectors word_vec = df.sent.apply(str.split).apply(pd.value_counts).fillna(0) # Compute term frequencies tf = word_vec.divide(np.sum(word_vec, axis=1), axis=0) # Compute inverse document frequencies idf = np.log10(len(tf) / word_vec[word_vec &gt; 0].count()) # Compute TF-IDF vectors tfidf = np.multiply(tf, idf.to_frame().T) print(tfidf) is the first This sentence second third 0 0.0 0.0 0.095424 0.0 0.0 0.000000 0.000000 1 0.0 0.0 0.000000 0.0 0.0 0.095424 0.000000 2 0.0 0.0 0.000000 0.0 0.0 0.000000 0.095424 Depending on your situation, you may want to normalize: # L2 (Euclidean) normalization l2_norm = np.sum(np.sqrt(tfidf), axis=1) # Normalized TF-IDF vectors tfidf_norm = (tfidf.T / l2_norm).T print(tfidf_norm) is the first This sentence second third 0 0.0 0.0 0.308908 0.0 0.0 0.000000 0.000000 1 0.0 0.0 0.000000 0.0 0.0 0.308908 0.000000 2 0.0 0.0 0.000000 0.0 0.0 0.000000 0.308908
has comment: http://stackoverflow.com/comment/120797789
type: Answer

http://stackoverflow.com/comment/90260297
type: QuestionComment
comment on: http://stackoverflow.com/q/51648284
has text: I need something like: `{'pk': 3115, 'row1': value1, 'row2':'value2'...}`
score: 0
type: Comment

http://stackoverflow.com/comment/90266310
type: QuestionComment
has text: Possibly, pip and python are different versions. Try reinstalling with `python -m pip install <whatever>`.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51651515

http://stackoverflow.com/q/51791750
upvote count: 1
tagged with: python
answer count: 1
has body: I have this in a Pandas DataFrame: site channel week value 0 Canada A W01 NaN 1 Canada A W02 NaN 2 Canada A W03 12 3 Canada B W01 NaN 4 Canada B W02 NaN 5 Canada B W03 66 I need to get this: site channel week value 0 Canada A W01 12 1 Canada A W02 12 2 Canada A W03 12 3 Canada B W01 66 4 Canada B W02 66 5 Canada B W03 66 In words, I need to fill the null values in column value with the values that correspond to the specific combination of site and channel. How can I do this?
has title: Pandas: filling null values based on values in multiple other columns
type: AnsweredQuestion
tagged with: null
downvote count: 0
has answer: http://stackoverflow.com/a/51791846
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/90540995
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51791846

http://stackoverflow.com/q/51733483
has comment: http://stackoverflow.com/comment/90427640
type: Question
has answer: http://stackoverflow.com/a/51733492
duplicate of: http://stackoverflow.com/q/25695878
has comment: http://stackoverflow.com/comment/90427662
score: -1
linked to: http://stackoverflow.com/q/25695878
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has body: I'm working in python, and have a dataframe(df), which includes the column 'CONTRACT_ID'. There are different numbers in this column. There is also another column called NPV, which is made up of numbers. CONTRACT_ID NPV 0 1 90 1 1 90 2 2 130 3 2 130 4 3 105 5 3 105 ... ... I don't want these duplicates to appear twice, so I tried to drop duplicates (only on column CONTRACT_ID) using this code: df.drop_duplicates(subset=['CONTRACT_ID'], keep=False) My expected result would be like so: CONTRACT_ID NPV 0 1 90 1 2 130 2 3 105 ... The code didn't work however. It ran with no error, but it simply didn't get rid of the duplicates at all. Am I doing something wrong? Thanks!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51733492
has title: Drop Duplicates isn't working on python
downvote count: 2

http://stackoverflow.com/comment/90540502
comment on: http://stackoverflow.com/a/51791383
has text: @CheerSal now I added example code to complete the number of columns to 10 when you have less than 10 columns.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51757511
has answer: http://stackoverflow.com/a/51757540
score: 4
has answer: http://stackoverflow.com/a/51757536
has answer: http://stackoverflow.com/a/51757733
has comment: http://stackoverflow.com/comment/90475350
has answer: http://stackoverflow.com/a/51761823
downvote count: 0
favorite count: 0
has body: I'm looking for the most beautiful and short way to multiply those types of lists: a = [True, False, True, False, False] b = [100, 200] Length of b equals to number of True elements in a The answer that I need is [100, 0, 200, 0, 0] here Are there any simple ways to get that answer? It looks like element-wise multiplication, but the fact is that the size of the second list is smaller, so common numpy methods don't work without bad code. Hope, you'll find nice solution
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/51757536
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51757540
has title: Element-wise boolean multiplication
type: Question
upvote count: 4
tagged with: numpy

http://stackoverflow.com/comment/90467685
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51753923
score: 1
has text: Why can't you use two conditions in your if statement?

polygon
tags question: http://stackoverflow.com/q/51709652
tag name: polygon
type: Tag

http://stackoverflow.com/a/51768146
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51767729
has comment: http://stackoverflow.com/comment/90527191
has body: Part 2. of your question is simple enough to do - you just need to define the width of the bins by passing a list of the boundaries. import matplotlib.pyplot as plt X = [0.21, 0.21, 0.33, 0.52, 0.22, 0.35, 0.43] plt.hist(X, bins=[0.0, 0.2, 0.4, 0.6]) plt.show() This will create bins [0.0, 0.2), [0.2, 0.4), [0.4, 0.6] where '[' is inclusive and '(' is exclusive. Not clear on what you require in part 1. of your question.
upvote count: 1
type: Answer

http://stackoverflow.com/q/51735660
has title: HTML Encode / Decode : Perl / Python output does not match
type: UnansweredQuestion
type: Question
score: 0
tagged with: perl
answer count: 1
has answer: http://stackoverflow.com/a/51735734
tagged with: unicode
has body: Input Text: ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml) Using this online tool to verify the output for encode and decode: http://www.web2generators.com/html-based-tools/online-html-entities-encoder-and-decoder, the output returned by the website are below: Decode Text ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml) Encode Text ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml) I wrote Perl and Python code to try to see if I can get the same output: Python Code from HTMLParser import HTMLParser try: from html import escape # python 3.x except ImportError: from cgi import escape # python 2.x def htmldecode(s): h = HTMLParser() return h.unescape(s) text = "ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)" print (htmldecode(text)) print (escape(htmldecode(text))) Output from Python for Encode Text : ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml) Tried Perl Code as well use HTML::Entities; my $input = "ABC™ Blue® Testmix, 200 x 20 µl rxns, 2 ml (2 x 1 ml)"; print encode_entities($input), "\n" However, the output is ABCâ„¢ BlueÂ® Testmix, 200 x 20 Âµl rxns, 2 ml (2 x 1 ml) What am i doing wrong that the output does not match the output returned from http://www.web2generators.com/html-based-tools/online-html-entities-encoder-and-decoder
tagged with: python
tagged with: utf-8

http://stackoverflow.com/comment/111407743
comment on: http://stackoverflow.com/a/51748870
has text: So, how can one 'actually' augment and increase the number of images?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/70294857
answers question: http://stackoverflow.com/q/51764757
type: Answer
score: 0
has body: A suggestion based on Bryan's answer: I understand the recommended way from an event-based perspective, but it does not feel very intuitive to me. I have to look up the trick every time I need it. Therefore, I have created a small mixin class that makes usage a bit more intuitive: import tkinter as tk class TkWaitMixin: """Simple wait timer that makes Tk waiting functionality more intiutive. Applies the recommended way according to https://stackoverflow.com/a/51770561/12646289. """ def start_wait_timer(self, milliseconds): self.resume = tk.BooleanVar(value=False) self.master.after(milliseconds, self.resume.set, True) # Assume master attribute is available: # https://stackoverflow.com/a/53595036/12646289 def wait_on_timer(self): self.master.wait_variable(self.resume) Example usage: import tkinter as tk class MyWindow(tk.Tk, TkWaitMixin): def __init__(self, master): self.master = master self.message_label = tk.Label('') self.message_label.pack(padx=50, pady=50) def show_message(self, message, milliseconds): self.start_wait_timer(milliseconds) self.message_label['text'] = message self.wait_on_timer() self.message_label['text'] = '' root = tk.Tk() mywin = MyWindow(master=root) mywin.show_message('Hello world', 2000) root.mainloop() Obviously, this will only be of use if you use classes in your tkinter code. Also note that the master attribute should be available in the main class to which the mixin is added. Edit Alternatively, usage can be made even easier with a context manager: import tkinter as tk class TkWait: def __init__(self, master, milliseconds): self.duration = milliseconds self.master = master def __enter__(self): self.resume = tk.BooleanVar(value=False) return self def __exit__(self, exc_type, exc_val, exc_tb): self.master.after(self.duration, self.resume.set, True) self.master.wait_variable(self.resume) Note that the waiting starts when the context manager is exited. Example usage: import tkinter as tk class MyWindow(tk.Tk): def __init__(self, master): sel…

http://stackoverflow.com/q/51660537
tagged with: mysql-connector
has comment: http://stackoverflow.com/comment/90285241
type: Question
has title: Python / mysql.connector - reusing a single database connection across multiple cursors
has body: I am trying to find a way to reuse the DB connection across multiple executions. But upon executing the second db.cursor() I get error: mysql.connector.errors.OperationalError: MySQL Connection not available. import mysql.connector db = mysql.connector.connect(host="***", user="***", password="***", database="***") db.autocommit = True cursor = db.cursor() cursor.execute("call procedure1();") rows1 = cursor.fetchall() cursor = db.cursor() cursor.execute("call procedure2()") rows2 = cursor.fetchall()
score: 1
has comment: http://stackoverflow.com/comment/90285411
has comment: http://stackoverflow.com/comment/90284911
tagged with: mysql
has comment: http://stackoverflow.com/comment/90285566
has comment: http://stackoverflow.com/comment/90284879
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90286040
has answer: http://stackoverflow.com/a/56698881
tagged with: python
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51782492
has comment: http://stackoverflow.com/comment/90804508
has comment: http://stackoverflow.com/comment/90804692
has body: One important fact to realize is that you can use broadcasting to solve this problem efficiently. So for the 2D case you could do d1, d2 = (3, 4) A = numpy.sqrt(numpy.arange(d1)[:, None] * numpy.arange(d2)[None, :]) # array([[0. , 0. , 0. , 0. ], # [0. , 1. , 1.41421356, 1.73205081], # [0. , 1.41421356, 2. , 2.44948974]]) Once you feel comfortable with using broadcasting to do these outer products (or sums, or comparisons etc.) we can try to solve this for the nD case. Looking at the input arrays of the above code we realize they have shapes (d1, 1) ( 1, d2) So to do this in nD we need to find a method that takes linear index arrays and automatically creates arrays of shapes (d1, 1, 1, ...) ( 1, d2, 1, ...) ( 1, 1, d3, ...) Numpy offers such a function: numpy.meshgrid(..., sparse=True) numpy.meshgrid(numpy.arange(3), numpy.arange(4), sparse=True) Knowing this we can put it all together in one line: D = (3, 4, 5) numpy.sqrt(numpy.prod(numpy.meshgrid(*[numpy.arange(d) for d in D], sparse=True, indexing='ij'))) # array([[[0. , 0. , 0. , 0. , 0. ], # [0. , 0. , 0. , 0. , 0. ], # [0. , 0. , 0. , 0. , 0. ]], # # [[0. , 0. , 0. , 0. , 0. ], # [0. , 1. , 1.41421356, 1.73205081, 2. ], # [0. , 1.41421356, 2. , 2.44948974, 2.82842712]], # # [[0. , 0. , 0. , 0. , 0. ], # [0. , 1.41421356, 2. , 2.44948974, 2.82842712], # [0. , 2. , 2.82842712, 3.46410162, 4. ]], # # [[0. , 0. , 0. , 0. , 0. ], # [0. , 1.73205081, 2.44948974, 3. , 3.46410162], # [0. , 2.44948974, 3.46410162, 4.24264069, 4.89897949]]]) Performance evaluation To evaluate the performance of all three solutions, let's time their speed for several different tensor sizes: D=(2,3,4,5) %timeit np.fromfunction(function=myfunc2, shape=D) # 501 µs ± 9.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit np.fromfunction(function=creation_function, shape=D) # 24.2 µs ± 455 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit numpy.sqrt(numpy.prod(numpy.meshgrid(*[numpy.arange(d) for d in D], spar…
has comment: http://stackoverflow.com/comment/90523400
type: Answer
answers question: http://stackoverflow.com/q/51782224
has comment: http://stackoverflow.com/comment/90523808
has comment: http://stackoverflow.com/comment/90523610
has comment: http://stackoverflow.com/comment/90528016
has comment: http://stackoverflow.com/comment/90546162
has comment: http://stackoverflow.com/comment/90523300
has comment: http://stackoverflow.com/comment/90804167
has comment: http://stackoverflow.com/comment/90527045
has comment: http://stackoverflow.com/comment/90528304
has comment: http://stackoverflow.com/comment/90804265
has comment: http://stackoverflow.com/comment/90543707
upvote count: 1
has comment: http://stackoverflow.com/comment/90526692
downvote count: 1
has comment: http://stackoverflow.com/comment/90804832
has comment: http://stackoverflow.com/comment/90528169
has comment: http://stackoverflow.com/comment/90526897
has comment: http://stackoverflow.com/comment/90804665
has comment: http://stackoverflow.com/comment/90527264
has comment: http://stackoverflow.com/comment/90522977
accepted answer of: http://stackoverflow.com/q/51782224
score: 0
has comment: http://stackoverflow.com/comment/90523201
has comment: http://stackoverflow.com/comment/90523553
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90523657
has comment: http://stackoverflow.com/comment/90526451

http://stackoverflow.com/comment/90544357
has text: use `out = np.zeros(a, dtype=np.bool8)` then `out[i:k, k] = True`
score: 1
comment on: http://stackoverflow.com/a/51793259
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51770813
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51770349
type: Answer
has body: You could loop through the columns: sess = tf.InteractiveSession() A = tf.distributions.Categorical(probs=[0.5, 0.5]) for i in range(2): B = tf.distributions.Categorical(probs=list(qs[:,i])) print(tf.distributions.kl_divergence(A, B).eval())

http://stackoverflow.com/q/51728645
answer count: 2
possible better answer: http://stackoverflow.com/a/65682393
tagged with: flask
score: 0
tagged with: whoosh
accepted answer: http://stackoverflow.com/a/51734419
has title: Flask-WhooshAlchemy raises NameError: name 'unicode' is not defined
tagged with: python
type: AnsweredQuestion
has body: Trying to create a search in a Flask app with WhooshAlchemy, but got an error. class Employee(db.Model): __searchable__ = ['first_name', 'patronymic', 'last_name', 'position', 'office', 'birthday'] id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(60)) patronymic = db.Column(db.String(60)) last_name = db.Column(db.String(60)) position = db.Column(db.String(60)) office = db.Column(db.String) birthday = db.Column(db.Date) def __init__(self, first_name, patronymic, last_name, position, office, birthday): self.first_name = first_name self.patronymic = patronymic self.last_name = last_name self.position = position self.office = office self.birthday = birthday def __repr__(self): return '&lt;First name: {}, Patronymic: {}, Last name: {}, Position: {}, Office: {}, Birthday: {}&gt;'\ .format(self.first_name, self.patronymic, self.last_name, self.position, self.office, self.birthday) wa.whoosh_index(app, Employee) @app.route('/results') @login_required def results(): q = request.args.get('q') if q: result = Employee.query.whoosh_search('q').all() else: result = Employee.query.all() return render_template('results.html', result=result) Traceback (most recent call last): File "/Users/vladimir/PycharmProjects/adminFlask/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "/Users/vladimir/PycharmProjects/adminFlask/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/Users/vladimir/PycharmProjects/adminFlask/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/vladimir/PycharmProjects/adminFlask/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise raise value File "/Users/vladimir/PycharmProjects/adminFlask/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/Users/vlad…
has answer: http://stackoverflow.com/a/65682393
type: Question
has answer: http://stackoverflow.com/a/51734419

http://stackoverflow.com/comment/90464228
type: Comment
score: 0
has text: `charity = nx.Graph([(u,v,d) for u,v,d in graph.edges(data=True) if d["source"]=="charity"]) print(list(nx.bfs_tree(charity, node)))`
type: AnswerComment
comment on: http://stackoverflow.com/a/51735129

http://stackoverflow.com/q/51766102
has body: I have as array Y =[[ 5. 0. 4. 1. 9. 2. 1. 3. 1. 4. 3. 5. 3. 6. 1. 7. 2. 8. 6. 9. 4. 0. 9. 1. 1. 2. 4. 3. 2. 7. 3. 8. 6. 9. 0. 5. 6. 0. 7. 6. 1. 8. 7. 9. 3. 9. 8. 5. 9. 3. 3. 0. 7. 4. 9. 8. 0. 9. 4. 1. 4. 4. 6. 0. 4. 5. 6. 1. 0. 0. 1. 7. 1. 6. 3. 0. 2. 1. 1. 7. 9. 0. 2. 6. 7. 8. 3. 9. 0. 4. 6. 7. 4. 6. 8. 0. 7. 8. 3. 1. 1. 2. 3.]] Then I use the command: Y.astype(int) When printing Y after the astype command I still have as result 5. 0. 4. and so on. But what I want is 5 0 4 etc... What do I wrong?
has comment: http://stackoverflow.com/comment/90495532
tagged with: python
has title: converting the values in my array into INT
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51768909
type: Question
tagged with: numpy
score: 0
answer count: 2
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/51766270

http://stackoverflow.com/q/51774091
has comment: http://stackoverflow.com/comment/90507359
answer count: 1
tagged with: neural-network
linked to: http://stackoverflow.com/q/7098625
favorite count: 0
has body: I'm trying to build an Agent that can play Pocket Tanks using RL. The problem I'm facing now is that how can I train a neural network to output the correct Power and Angle. so instead of actions classification. and I want a regression.
tagged with: reinforcement-learning
has answer: http://stackoverflow.com/a/51794321
tagged with: python
type: AnsweredQuestion
upvote count: 3
downvote count: 2
has title: Regression through reinforcement learning
type: Question
accepted answer: http://stackoverflow.com/a/51794321
score: 1
has comment: http://stackoverflow.com/comment/90510389
has comment: http://stackoverflow.com/comment/90508089

http://stackoverflow.com/comment/90429558
comment on: http://stackoverflow.com/q/51732255
score: 0
type: Comment
type: QuestionComment
has text: Thank you to Charles and Jeremy; between your comments and suggestions I was able to get it to work.

http://stackoverflow.com/comment/90259556
has text: No probs ): Have fun !
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51647919

http://stackoverflow.com/comment/90463826
has text: I'm glad if it helped. If my answer solved your problem, feel free to upvote and/or accept it, as you see fit. For the ValueError, I'm not sure I can help. To get the right attention, you should post a new question (if you haven't done so already).
type: Comment
comment on: http://stackoverflow.com/a/51739453
score: 0
type: AnswerComment

http://stackoverflow.com/q/51644440
answer count: 1
has comment: http://stackoverflow.com/comment/90253176
has body: I made a telegram bot using python and the pyTelegramBotAPI api. The thing is, when I run my bot more than 5 minutes it throws an error "conection reset by peer". So I decided to do an infinite polling. with infinite polling stops working every 10 min for 1 min throwing: RuntimeError: maximum recursion depth exceeded After that, It runs for 10 min more, but with this error: 2018-08-01 21:16:27,187 (util.py:65 PollingThread) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 409 Conflict. Response body:\n[{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}]',) And If I decide to send something in telegram, sometimes the bot make double response, It seems they are running two instances of the bot, but why? There is a way to solve this? Maybe a shell scripting to terminate the process using scheduling every n minutes or something like that. I tried also deploy with heroku with no sucess. Every idea to keep that bot running is welcome. Here is my polling: def principal(): while True: try: bot.infinity_polling(True) bot.polling(none_stop=True) except: time.sleep(10) principal()
favorite count: 0
tagged with: telegram-bot
has comment: http://stackoverflow.com/comment/90252974
tagged with: python
score: 2
downvote count: 1
type: AnsweredQuestion
tagged with: server
upvote count: 3
has title: Keep python telegram bot running
has comment: http://stackoverflow.com/comment/90252993
type: Question
has comment: http://stackoverflow.com/comment/93223986
has answer: http://stackoverflow.com/a/51645254
accepted answer: http://stackoverflow.com/a/51645254

http://stackoverflow.com/comment/90432815
comment on: http://stackoverflow.com/q/51735899
score: 0
type: Comment
has text: I'm voting to close this question as off-topic because it's not a programming question. There are bigger issues here that ought to be addressed (Why are random users running "magic commands" as root on a server? Why does root have a Desktop? How can (vital to the business) files just disappear? etc.), but that's both too broad and way out of scope for StackOverflow.
type: QuestionComment

http://stackoverflow.com/q/51790986
has answer: http://stackoverflow.com/a/51790998
has comment: http://stackoverflow.com/comment/90539539
answer count: 1
has title: Populate a column based on the value of other column
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/90539442
favorite count: 0
has body: Lets say I have a list vowels= ['a','e','i','o','u'] I have a pandas dataframe id alphabet 1 b 2 a 3 c 4 i I need output like id alphabet label 1 b 2 a vowel 3 c 4 i vowel I tried df.loc[df.alphabet in vowels, 'label'] = "vowel" This gives me a error. how do i do this?
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/19960077
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51790998
score: 1
type: Question

http://stackoverflow.com/comment/90762470
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51744921
has text: Hi Ruben, thanks I these days I can't work on this project. When I will came back at home I will try a bold a mini webapp to drive the script

http://stackoverflow.com/comment/90455574
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51747017
has text: Are the start and end dates the same for all stores?

http://stackoverflow.com/a/51758587
score: 1
answers question: http://stackoverflow.com/q/51758417
downvote count: 1
type: Answer
upvote count: 2
has body: You can also specify the agg funcs s = lambda s: sum(int(k) for k in s) d = {i: s for i in range(8)} d.update({0: 'first', 7: 'first'}) df.groupby((df[0] == 'None').cumsum().shift().fillna(0)).agg(d) 0 1 2 3 4 5 6 7 0 0.0 a 1 1 1 1 0 0 i 1.0 e 0 1 0 1 1 0 m 2.0 h 0 0 0 0 1 0 p

http://stackoverflow.com/a/51722514
has body: Make a data frame and then set the column to index and then convert it to json: data_frame = pd.DataFrame(columns = title, data = value) data = data_frame.set_index('Code') json1 = data.to_json(orient='index')
type: Answer
answers question: http://stackoverflow.com/q/51722090
score: 0

http://stackoverflow.com/q/51734193
has body: I have a numpy array that looks like this: [ ('{893EE51E-0CD1-4C06-B672-365EECA26C33}', 'image/jpeg', 'Photo1.jpg', []), ('{893EE51E-0CD1-4C06-B672-365EECA26C33}', 'image/jpeg', 'Photo2.jpg', []), ('{893EE51E-0CD1-4C06-B672-365EECA26C63}', 'image/jpeg', 'Photo1.jpg', []), ('{893EE51E-0CD1-4C06-B672-365EECA26C73}', 'image/jpeg', 'Photo1.jpg', []) ] How can i find the unique values at "position 0" of each tuple? Ideally i'd like to output an array (or list) that looks like this: [ '{893EE51E-0CD1-4C06-B672-365EECA26C33}', '{893EE51E-0CD1-4C06-B672-365EECA26C63}', '{893EE51E-0CD1-4C06-B672-365EECA26C73}' ]
tagged with: tuples
has title: find unique values at a given position in a numpy array of tuples
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51734662
has comment: http://stackoverflow.com/comment/90430493
tagged with: unique
favorite count: 0
has answer: http://stackoverflow.com/a/51734549
possible better answer: http://stackoverflow.com/a/51734662
accepted answer: http://stackoverflow.com/a/51734549
has comment: http://stackoverflow.com/comment/90429716
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51734337
type: Question
tagged with: numpy

python-requests
tags question: http://stackoverflow.com/q/51732475
tags question: http://stackoverflow.com/q/51664323
tags question: http://stackoverflow.com/q/51675330
tags question: http://stackoverflow.com/q/51653660
type: Tag
tags question: http://stackoverflow.com/q/51692985
tags question: http://stackoverflow.com/q/51714907
tags question: http://stackoverflow.com/q/51731389
tags question: http://stackoverflow.com/q/51669488
tags question: http://stackoverflow.com/q/51735346
tags question: http://stackoverflow.com/q/51664292
tags question: http://stackoverflow.com/q/51697465
tags question: http://stackoverflow.com/q/51775462
tags question: http://stackoverflow.com/q/51699817
tags question: http://stackoverflow.com/q/51690162
tags question: http://stackoverflow.com/q/51748902
tags question: http://stackoverflow.com/q/51777495
tags question: http://stackoverflow.com/q/51754074
tags question: http://stackoverflow.com/q/51796267
tags question: http://stackoverflow.com/q/51784825
tags question: http://stackoverflow.com/q/51756727
tags question: http://stackoverflow.com/q/51646333
tags question: http://stackoverflow.com/q/51697244
tags question: http://stackoverflow.com/q/51682151
tags question: http://stackoverflow.com/q/51777832
tags question: http://stackoverflow.com/q/51753260
tags question: http://stackoverflow.com/q/51709517
tags question: http://stackoverflow.com/q/51760210
tags question: http://stackoverflow.com/q/51788258
tags question: http://stackoverflow.com/q/51778764
tags question: http://stackoverflow.com/q/51762655
tags question: http://stackoverflow.com/q/51702498
tags question: http://stackoverflow.com/q/51738413
tags question: http://stackoverflow.com/q/51684985
tags question: http://stackoverflow.com/q/51757810
tags question: http://stackoverflow.com/q/51715711
tags question: http://stackoverflow.com/q/51792571
tags question: http://stackoverflow.com/q/51792303
tags question: http://stackoverflow.com/q/51793874
tags question: http://stackoverflow.com/q/51694687
tags question: http://stackoverflow.com/q/51657562
tags question: http://stackoverflow.com/q/51676088
tags question: http://stackoverflow.com/q/51689829
tags question: http://stackoverflow.com/q/51757608
tags question: http://stackoverflow.com/q/51777724
tags question: http://stackoverflow.com/q/51796368
tags question: http://stackoverflow.com/q/51644949
tags question: http://stackoverflow.com/q/51665087
tags question: http://stackoverflow.com/q/51667938
tags question: http://stackoverflow.com/q/51669572
tags question: http://stackoverflow.com/q/51759314
tags question: http://stackoverflow.com/q/51765719
tags question: http://stackoverflow.com/q/51704976
tags question: http://stackoverflow.com/q/51695583
tags question: http://stackoverflow.com/q/51692872
tags question: http://stackoverflow.com/q/51644564
tags question: http://stackoverflow.com/q/51774074
tag name: python-requests
tags question: http://stackoverflow.com/q/51773707
tags question: http://stackoverflow.com/q/51692278
tags question: http://stackoverflow.com/q/51662106
tags question: http://stackoverflow.com/q/51713337
tags question: http://stackoverflow.com/q/51689111
tags question: http://stackoverflow.com/q/51686371
tags question: http://stackoverflow.com/q/51674751
tags question: http://stackoverflow.com/q/51747092
tags question: http://stackoverflow.com/q/51740051
tags question: http://stackoverflow.com/q/51785640
tags question: http://stackoverflow.com/q/51762805
tags question: http://stackoverflow.com/q/51661796
tags question: http://stackoverflow.com/q/51757421

http://stackoverflow.com/q/51755722
type: Question
has answer: http://stackoverflow.com/a/70169522
score: 3
has body: I'm new to pudb. It run fine for the most-part, but when I try to enter a library it apparently doesn't recognize, I get the following message: &lt;no source code available&gt; If this is generated code and you would like the source code to show up here, add it to linecache.cache, like import linecache linecache.cache[filename] = (size, mtime, lines, fullname) You can also set the attribute _MODULE_SOURCE_CODE in the module in which this function was compiled to a string containing the code. I've tried importing 'linecache' and the 'cache' attribute is a dictionary. I've tried creating an entry for the missing module a few times with no success. Can someone please give an example on an easier and/or practical way to add an unrecognized module to pudb?
has answer: http://stackoverflow.com/a/56460439
answer count: 3
downvote count: 1
tagged with: pudb
has answer: http://stackoverflow.com/a/75215157
has title: PUDB Error: <no source code available>
favorite count: 0
has comment: http://stackoverflow.com/comment/90471188
has comment: http://stackoverflow.com/comment/90473018
tagged with: python
upvote count: 4
type: UnansweredQuestion

http://stackoverflow.com/q/51793651
has comment: http://stackoverflow.com/comment/90545065
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: How to group data based on the scatter plot from Panda plotted figure
upvote count: 1
has comment: http://stackoverflow.com/comment/90545097
type: Question
has comment: http://stackoverflow.com/comment/90544940
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90545179
has body: I would like to group into two categories. I used panda get a scatter plot of my data. See the figure, I want all the data in the left upper corner to be a group and the remaining data into a secondary group. How can I sort my data based on the plotted figure? Thanks for any help! index x y 11 86.58 3.31 26 128.79 2.79 46 43.34 6.32 71 95.39 3.90 72 93.95 3.40 73 117.76 3.06 75 82.37 3.83 ............. g=sns.jointplot(x='x',y='y',data=GA_m_W,space = 0.1,ratio = 3) figure
has comment: http://stackoverflow.com/comment/90548310
downvote count: 0
favorite count: 0

boto3
tags question: http://stackoverflow.com/q/51645560
tags question: http://stackoverflow.com/q/51750492
tags question: http://stackoverflow.com/q/51644377
tags question: http://stackoverflow.com/q/51738406
tags question: http://stackoverflow.com/q/51759237
tags question: http://stackoverflow.com/q/51676317
tag name: boto3
tags question: http://stackoverflow.com/q/51748310
tags question: http://stackoverflow.com/q/51670783
tags question: http://stackoverflow.com/q/51687990
tags question: http://stackoverflow.com/q/51728359
type: Tag
tags question: http://stackoverflow.com/q/51695467
tags question: http://stackoverflow.com/q/51758593
tags question: http://stackoverflow.com/q/51795506

http://stackoverflow.com/comment/90543018
score: 0
type: Comment
type: QuestionComment
has text: There, I have put my attempts. Yeah, with your answer I am now seeing the problem in a different way. I will give a try with cumsum
comment on: http://stackoverflow.com/q/51791933

http://stackoverflow.com/q/51643100
accepted answer: http://stackoverflow.com/a/51643277
has comment: http://stackoverflow.com/comment/90250833
has comment: http://stackoverflow.com/comment/90250651
type: Question
upvote count: 0
score: -2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90250787
answer count: 1
has answer: http://stackoverflow.com/a/51643277
favorite count: 0
tagged with: python-3.x
tagged with: subprocess
has body: I'm struggling with a python program to redirect the output of all print calls to a file and email it. Below is my program. Everything works fine except the OUTFILE in the email coming up empty (perhaps the file is still open while it tries to email it). As I'm little confused about the sequence and want to call the send_status_report() defined after the file is closed, how do I make it work. #! /usr/bin/python import subprocess import os import pty import sys import smtplib import time from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication def current_time(): from datetime import datetime return datetime.now().strftime('%Y-%m-%d-%H-%M-%S') BIN="/home/netsys/filerscripts/MANU-TEST/storage-automations/REDBUTTON-DR/" LOG=BIN+"Logs/" YMD=current_time() OUTFILE="ResyncLog_"+YMD+".txt" SMTP_SERVER="xxxxxxxx.xxx.com" #define to Call the reverse resync and output the log to both file and screen def send_status_report(): dir_path = LOG files = [OUTFILE, "CLUSTERDEL.LOG", "RESYNC.LOG","UPDATE.LOG"] msg = MIMEMultipart() msg['To'] = "abc@abc.com" msg['From'] = "abc@abc.com" msg['Subject'] = "Netapp RB Automation:Reverse Resync Status" body = MIMEText('Test results attached.', 'html', 'utf-8') msg.attach(body) # add message body (text or html) for f in files: # add files to the message file_path = os.path.join(dir_path, f) attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt") attachment.add_header('Content-Disposition','attachment', filename=f) msg.attach(attachment) s = smtplib.SMTP() s.connect(host=SMTP_SERVER) s.sendmail(msg['From'], msg['To'], msg.as_string()) print 'done!' s.close() def main(): subprocess.call(BIN+"ReverseSync.py", shell=True) if __name__=="__main__": sentinel_option = '--dont-spawn' if sentinel_option not in sys.argv: # run itself copying output to the log file with open(LOG+OUTFILE, 'wb') as log_file: def read(fd): data = os.read(fd, 1024) log_file.write…
downvote count: 2
has title: Issue with the __name__=="__main__" function calling
tagged with: python
has comment: http://stackoverflow.com/comment/90250848
has comment: http://stackoverflow.com/comment/90250865
has comment: http://stackoverflow.com/comment/90250691
type: AnsweredQuestion

http://stackoverflow.com/a/51769278
answers question: http://stackoverflow.com/q/51769171
has comment: http://stackoverflow.com/comment/90511384
has comment: http://stackoverflow.com/comment/90497274
type: Answer
has comment: http://stackoverflow.com/comment/90503516
score: 0
has body: From IDLE: &gt;&gt;&gt; import time &gt;&gt;&gt; time.sleep(0.5) &gt;&gt;&gt; s = "asdf" + time.sleep(0.5) + "asdf" Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; s = "asdf" + time.sleep(0.5) + "asdf" TypeError: can only concatenate str (not "NoneType") to str So, in short, not in that way. But, the following works in that it's a single item to return (kind of): &gt;&gt;&gt; x = (print("asdf"), time.sleep(0.5), print("asdf")) asdf asdf &gt;&gt;&gt; x (None, None, None) &gt;&gt;&gt; A better method might be to return a tuple of (list of strings, time interval) which can be passed to another function for printing.
has comment: http://stackoverflow.com/comment/90497370
has comment: http://stackoverflow.com/comment/90503430

http://stackoverflow.com/q/51784604
type: Question
tagged with: matplotlib
score: 0
tagged with: pandas
tagged with: python-3.x
has body: I am having trouble plotting the area around the predictions of my model which I thought would be straightforward with fill_between plot. For a reproducible example: df1 Ground_Truth Predictions Predictions_hi Predictions_lo 410 15.0 14.810122 18.356809 11.263436 85 26.6 27.131472 28.320380 25.942565 280 45.4 45.404620 47.274549 43.534691 422 20.8 19.081849 20.711096 17.452601 199 34.9 29.703281 32.416996 26.989566 364 21.9 49.010702 52.162232 45.859172 5 28.7 27.330305 29.026654 25.633956 415 7.2 8.412145 10.244244 6.580046 209 20.0 17.257462 19.459939 15.054985 284 32.2 28.166823 30.390787 25.942859 The data in json format: {"Ground_Truth":{"410":15.0,"85":26.6,"280":45.4,"422":20.8,"199":34.9,"364":21.9,"5":28.7,"415":7.2,"209":20.0,"284":32.2},"Predictions":{"410":14.8101220869,"85":27.1314724323,"280":45.4046198732,"422":19.0818488429,"199":29.7032811382,"364":49.0107021787,"5":27.3303047283,"415":8.4121453666,"209":17.2574622383,"284":28.1668228107},"Predictions_hi":{"410":18.3568086485,"85":28.3203798966,"280":47.2745488681,"422":20.7110962223,"199":32.4169963433,"364":52.1622320467,"5":29.0266538906,"415":10.2442444504,"209":19.4599393417,"284":30.3907868523},"Predictions_lo":{"410":11.2634355254,"85":25.9425649679,"280":43.5346908782,"422":17.4526014635,"199":26.989565933,"364":45.8591723107,"5":25.6339555659,"415":6.5800462828,"209":15.054985135,"284":25.9428587691}} My code is the following: results_df1.plot(x= 'Ground_Truth', y = 'Predictions', kind = 'scatter', color = 'r') plt.plot(results_df1['Ground_Truth'],results_df1['Ground_Truth'], color = 'b') plt.fill_between(results_df1['Ground_Truth'], results_df1['Predictions_lo'], results_df1['Predictions_hi'], alpha = 0.1) plt.show() This code returns the following plot: You see the jig-jag which I did not expect.
type: UnansweredQuestion
tagged with: python
has title: Using fill_between() plot in pyplot
has comment: http://stackoverflow.com/comment/90526197
answer count: 0
has comment: http://stackoverflow.com/comment/102887224

http://stackoverflow.com/a/51776996
has body: What you can do is - create a column which identifies the group and then group by that column, followed by a random shuffle of each group. df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) df['group_id'] = np.arange(df.shape[0]) // 10 # // is integer division in python3, won't work in python2 shuffled_groups = [v.drop(['group_id'], axis=1).sample(frac=1).reset_index(drop=True) for k, v in df.groupby('group_id')]
score: 0
answers question: http://stackoverflow.com/q/51776744
type: Answer

http://stackoverflow.com/comment/90361797
type: Comment
type: QuestionComment
has text: Can you please clarify what you mean by "It's not clear if we have to actually capture scanned devices in the whitelist for the scan to succeed (goes by too fast to catch and stop)"?
score: 0
comment on: http://stackoverflow.com/q/51700050

http://stackoverflow.com/comment/119507349
has text: subprocess.run(['adb', 'exec-out', 'screencap', '-p', '>', 'screen.png'],shell=True)
type: Comment
comment on: http://stackoverflow.com/a/51726920
type: AnswerComment
score: 0

http://stackoverflow.com/q/51675246
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90313743
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/90313570
has comment: http://stackoverflow.com/comment/90315555
has comment: http://stackoverflow.com/comment/90324711
score: 0
has title: Parsing file-like object into create_ffmpeg_player in discord.py not working
has body: The API documentation for create_ffmpeg_player says it allows passing file-like objects into create_ffmpeg_player as it will be passed to stdin. create_ffmpeg_player(filename, *, use_avconv=False, pipe=False, stderr=None, options=None, before_options=None, headers=None, after=None) filename – The filename that ffmpeg will take and convert to PCM bytes. If pipe is True then this is a file-like object that is passed to the stdin of ffmpeg here's what I am inputting: buffer = BytesIO() c.setopt(c.WRITEDATA, buffer) c.perform() player = voice.create_ffmpeg_player(buffer,pipe=True) The PycURL object writes data to buffer which is the BytesIO object. Then I try to parse the file-like object into create_ffmpeg_player() but I get the following error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event yield from getattr(self, event)(*args, **kwargs) File "test.py", line 116, in on_message player = voice.create_ffmpeg_player(buffer,pipe=True) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\voice_client.py", line 431, in create_ffmpeg_player p = subprocess.Popen(args, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 667, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 904, in _get_handles p2cread = msvcrt.get_osfhandle(stdin.fileno()) io.UnsupportedOperation: fileno The error shows me that somewhere in the stack, a routine is trying to get the fileno() of the object, but since this is not a real file, there is no file handle, or "fileno". For a temporary work-around I am creating a physical file on disk and parsing that file into the function, but for this program, the function will be run many times so doing physical read/writes is not practic…
tagged with: python

http://stackoverflow.com/q/51715561
tagged with: color-detection
score: 0
has comment: http://stackoverflow.com/comment/90392763
favorite count: 0
has title: Color Detection of Balls using Webcams and perform actions
type: UnansweredQuestion
tagged with: python
tagged with: artificial-intelligence
has body: I have a clear idea how to identify colors of any objects placed in front of webcam but i need some help for performing some actions according to the color. Suppose for a red ball,my laptop screen will slide to next image of any image slider and for a blue ball it will slide to the previous. Any helps or suggestions please.
answer count: 0
has comment: http://stackoverflow.com/comment/90392719
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/51779151
score: 1
upvote count: 1
type: Question
has body: This is not a specific code question, but rather a general question on how something would be done in Python. I am working on multiple cryptocurrency exchanges, and have to send HTTP requests to receive API data. For private user data and trade execution, I have to provide several parameters, almost all of which are generally unclear and one of which is a hash. The secret API key must somehow be hashed with hmac, in a specific order with the inclusion of other parameters and fields, to provide the correct parameter in the request. How on earth is this done correctly? I will provide sample instructions from an exchange. Signing Requests POST requests have to be signed by authentication code. You have to use secret key for that, which you use to sign parameters with SHA512 algorithm. It is neccessary to send public key in header as API-Key and also hashed post message as API-Hash. It is request execution unix timestamp. This value is compared with server time. If difference is bigger than 5 seconds - operation won’t be executed. It is important to have synchronized time with NTP public time server - in other case server time can differ a lot than time of request machine. API call rate limit The rate limit is 1 req / second. API methods List of methods, which you have to send in method parameter. info - returns information about account balances How do I sign this in Python and provide what they actually want correctly, and how do I apply those concepts to other exchanges? Please provide an explanation that will allow me to recreate what you have said/done in other situations.
has title: HMAC (SHA512/SHA256) for HTTP Requests on Python (Cryptocurrency)
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/90537327
type: Comment
has text: Also, what exactly do you mean by "deployed to GCP"? That can mean several different things. But regardless, there's a probably 75% chance that you just don't have `coverage` installed in whatever GCP environment it's running in.
score: 3
comment on: http://stackoverflow.com/q/51789909
type: QuestionComment

tkinter
tags question: http://stackoverflow.com/q/51794733
tags question: http://stackoverflow.com/q/51645151
tags question: http://stackoverflow.com/q/51770056
tags question: http://stackoverflow.com/q/51646184
tags question: http://stackoverflow.com/q/51716414
tags question: http://stackoverflow.com/q/51749757
tags question: http://stackoverflow.com/q/51691835
tags question: http://stackoverflow.com/q/51772466
tags question: http://stackoverflow.com/q/51758308
tags question: http://stackoverflow.com/q/51781247
tags question: http://stackoverflow.com/q/51753750
tags question: http://stackoverflow.com/q/51785844
tag name: tkinter
tags question: http://stackoverflow.com/q/51735566
tags question: http://stackoverflow.com/q/51642116
tags question: http://stackoverflow.com/q/51640481
tags question: http://stackoverflow.com/q/51766129
tags question: http://stackoverflow.com/q/51790910
tags question: http://stackoverflow.com/q/51692037
tags question: http://stackoverflow.com/q/51784310
tags question: http://stackoverflow.com/q/51749783
tags question: http://stackoverflow.com/q/51678141
tags question: http://stackoverflow.com/q/51785000
tags question: http://stackoverflow.com/q/51783460
tags question: http://stackoverflow.com/q/51729665
tags question: http://stackoverflow.com/q/51690259
tags question: http://stackoverflow.com/q/51696759
tags question: http://stackoverflow.com/q/51716932
tags question: http://stackoverflow.com/q/51641188
tags question: http://stackoverflow.com/q/51713229
tags question: http://stackoverflow.com/q/51783787
tags question: http://stackoverflow.com/q/51697858
tags question: http://stackoverflow.com/q/51686567
tags question: http://stackoverflow.com/q/51684658
tags question: http://stackoverflow.com/q/51770294
tags question: http://stackoverflow.com/q/51713634
tags question: http://stackoverflow.com/q/51662441
tags question: http://stackoverflow.com/q/51737967
tags question: http://stackoverflow.com/q/51740818
tags question: http://stackoverflow.com/q/51681525
tags question: http://stackoverflow.com/q/51760130
tags question: http://stackoverflow.com/q/51796357
tags question: http://stackoverflow.com/q/51735803
tags question: http://stackoverflow.com/q/51740092
tags question: http://stackoverflow.com/q/51759683
tags question: http://stackoverflow.com/q/51792477
tags question: http://stackoverflow.com/q/51762835
tags question: http://stackoverflow.com/q/51695911
tags question: http://stackoverflow.com/q/51720014
tags question: http://stackoverflow.com/q/51664545
tags question: http://stackoverflow.com/q/51660795
tags question: http://stackoverflow.com/q/51695336
tags question: http://stackoverflow.com/q/51709861
tags question: http://stackoverflow.com/q/51737763
tags question: http://stackoverflow.com/q/51700305
tags question: http://stackoverflow.com/q/51690173
tags question: http://stackoverflow.com/q/51659737
tags question: http://stackoverflow.com/q/51669073
tags question: http://stackoverflow.com/q/51704416
tags question: http://stackoverflow.com/q/51678690
tags question: http://stackoverflow.com/q/51680636
tags question: http://stackoverflow.com/q/51696109
tags question: http://stackoverflow.com/q/51663525
tags question: http://stackoverflow.com/q/51692178
tags question: http://stackoverflow.com/q/51688546
tags question: http://stackoverflow.com/q/51774639
tags question: http://stackoverflow.com/q/51652837
tags question: http://stackoverflow.com/q/51787502
tags question: http://stackoverflow.com/q/51733663
tags question: http://stackoverflow.com/q/51746147
tags question: http://stackoverflow.com/q/51797925
tags question: http://stackoverflow.com/q/51771106
tags question: http://stackoverflow.com/q/51647603
tags question: http://stackoverflow.com/q/51751483
tags question: http://stackoverflow.com/q/51698528
tags question: http://stackoverflow.com/q/51656758
tags question: http://stackoverflow.com/q/51704745
tags question: http://stackoverflow.com/q/51742871
tags question: http://stackoverflow.com/q/51781651
tags question: http://stackoverflow.com/q/51744012

http://stackoverflow.com/a/51694877
answers question: http://stackoverflow.com/q/51694375
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: This is one approach. Using pd.to_datetime with errors="coerce" Ex: import pandas as pd df = pd.DataFrame({"Col1": ['12/3/2018', 'March 12, 2018', 'stackoverflow', 'Mar 12, 2018', 'no date text', '3/12/2018']}) df["Col1"] = pd.to_datetime(df["Col1"], errors="coerce") df = df[df["Col1"].notnull()] print(df) Output: Col1 0 2018-12-03 1 2018-03-12 3 2018-03-12 5 2018-03-12 Or if you want to maintain the original data import pandas as pd def validateDate(d): try: pd.to_datetime(d) return d except: return None df = pd.DataFrame({"Col1": ['12/3/2018', 'March 12, 2018', 'stackoverflow', 'Mar 12, 2018', 'no date text', '3/12/2018']}) df["Col1"] = df["Col1"].apply(validateDate) df.dropna(inplace=True) print(df) Output: Col1 0 12/3/2018 1 March 12, 2018 3 Mar 12, 2018 5 3/12/2018
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51694375

http://stackoverflow.com/q/51640628
has comment: http://stackoverflow.com/comment/90245783
has answer: http://stackoverflow.com/a/51641288
tagged with: pandas
answer count: 1
has title: sum of product over decreasing range
downvote count: 0
has comment: http://stackoverflow.com/comment/90245760
has comment: http://stackoverflow.com/comment/90246109
has comment: http://stackoverflow.com/comment/90246905
favorite count: 0
has comment: http://stackoverflow.com/comment/90245768
tagged with: python
accepted answer: http://stackoverflow.com/a/51641288
tagged with: vectorization
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I am implementing a small Python application to measure returns of a trading strategy. The function that computes the return takes the following imputs: a Pandas' dataframe containing the close prices a Pandas' series of booleans representing buy signals a Pandas' series of booleans representing sell signals a float representing the trading fees as a percentage of the initial capital This is what the data looks like: &gt;&gt;&gt; df.head() open high low close volume date 2015-01-02 5.34 5.37 5.11 5.21 108469 2015-01-05 5.21 5.26 4.85 4.87 160089 2015-01-06 4.87 4.87 4.55 4.57 316501 2015-01-07 4.63 4.75 4.60 4.67 151117 2015-01-08 4.69 4.89 4.69 4.81 159294 &gt;&gt;&gt; &gt;&gt;&gt; buy.head() 2015-01-02 True 2015-01-05 False 2015-01-06 False 2015-01-07 False 2015-01-08 False dtype: bool &gt;&gt;&gt; Without taking into account the fees, this is the formula to compute the ratios: Where C is the initial capital and ri is the return of one buy/sell trade. This can easily be easily implemented using a vectorized implementation: buy_sell = df[(buy==True)|(sell==True)] prices = buy_sell.close diffs = prices - prices.shift() ratios = diffs / prices.shift() return ((ratios + 1).product(axis=0)) When it comes time to take into account the fees, I end up with the following formula: Where f is the trading fee. This could easily be implemented using loops but is there a way to do this with a vectorized implementation? I am not a math expert but maybe the product being dependant on the summation indices prevents this? I tried looking this property online but can't seem to find anything. Maybe I am not formulating the question properly since I am lacking the technical jargon. Any thought on this would be appreciated :) Edit From DSM's answer, the solution is to perform a 'cumulative product' on the reversed series of ratios. This gives me the following solution: def compute_return(df, buy, sell, fees=0.): # Bunch of verifications operation performed on data buy_sell = df[(buy==T…
type: Question
tagged with: math

http://stackoverflow.com/q/51667176
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/90297339
has body: I am trying to make a circle detection program which will after detection control/test if the circle is really there. I am trying to do that with putting x and y of circle in a list once-this is the control list. The object list is every x and y of the circle continuously put in, not only once. Then it will count/compare with the control list ObjectList.count(ControlList[i]) how many times the x and y has appeared in the object list. And if it appeared more than 5 times it draws it. My question is how to get x and y from this: ['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87'] The first one is x and the second one is y if pregled == 0: # Checks if ControlList was wiped clear after 10 checks if count &lt; 11: # counts to 10 the sets pregled = 1 count = count + 1 for cnt1 in contours1: #ret = cv2.matchShapes(cnt,cnt1,1,0.0) area = cv2.contourArea(cnt1) if area &gt; 500: ret = cv2.matchShapes(cnt,cnt1,1,0.0) if ret &lt; 0.02: if len(cnt1) &gt; 0: M = cv2.moments(cnt1) if M["m00"] != 0: cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) #Conturji = '('+str(cx)+','+str(cy)+')' Conturji = str(cx) +','+ str(cy) # Puts everything in string if Conturji not in ControlList: # Checks if it already is in ControlList ControlList.append(Conturji) print(ControlList) `
has comment: http://stackoverflow.com/comment/90297330
has answer: http://stackoverflow.com/a/51667308
accepted answer: http://stackoverflow.com/a/51667276
has title: Python: How to get two integers out of one object in a list
favorite count: 0
has answer: http://stackoverflow.com/a/51667381
has answer: http://stackoverflow.com/a/51667394
possible better answer: http://stackoverflow.com/a/51667308
upvote count: 1
tagged with: python
answer count: 4
tagged with: opencv
type: AnsweredQuestion
tagged with: list
score: 0
downvote count: 1
has answer: http://stackoverflow.com/a/51667276

http://stackoverflow.com/q/51672325
score: 0
has comment: http://stackoverflow.com/comment/90307838
has comment: http://stackoverflow.com/comment/90307716
has body: I have fit a line of best fit to some scatter plot data import numpy as np import matplotlib.pyplot as plt testlvals = [2.5, 2.5, 2.54, 2.61, 2.62, 2.65, 2.68, 2.74, 2.77, 2.77, 2.85, 2.87, 2.88, 2.89, 2.94, 2.96, 3.02, 3.03, 3.03, 3.19, 3.25, 3.26, 3.27, 3.3, 3.32, 3.41, 3.45, 3.53, 3.55, 3.6, 3.63, 3.66, 3.66, 3.67, 3.68, 3.71, 3.72, 3.75, 3.78, 3.79, 3.83, 3.84, 3.95, 3.98, 3.98, 4.03, 4.04, 4.06, 4.1, 4.18, 4.21, 4.23, 4.31, 4.32, 4.53, 4.54, 4.57, 4.6, 4.61, 4.69, 4.91, 4.91, 4.93, 4.99, 5.09, 5.13, 5.17, 5.17, 5.27, 5.28, 5.34, 5.36, 5.39, 5.41, 5.42, 5.44, 5.61, 5.68, 5.68, 5.72, 5.73, 5.75, 5.81, 5.87, 5.94, 5.96] stormdll = [2.889243921893069e-05, 0.00022866553316519154, nan, 0.00013707129325248174, 0.00021835330960779531, 0.00062837761202857642, 0.00019650047630071017, 0.00010699446178025272, 0.00057187879938179747, 0.0011665035757214481, 0.00016776735479387793, 0.0013124897173367673, 0.0017014387306167212, 0.00079760282220871714, 0.000266662827251465, 0.002300090861918372, 0.0015387413878198573, 0.00082950661801858578, 0.0017190452575373278, 0.0021515348463768745, 0.00010841924191146237, 0.001157811249298408, 0.002793117055536783, 0.0059201077854461543, 0.0072200686941846313, 0.0021081707069775814, 0.0023779309754600238, 0.00082597422775368672, 0.0028797886398615048, 0.0058324203223666746, 0.0068855175445071658, nan, 0.032420016410424954, 0.029937093955166857, 0.0026630311348559647, 0.0019588293726173519, 0.013178179035275815, 0.01871886867738189, nan, 0.0090262813383890899, 0.0033087173547989967, 0.0047291994757413351, 0.0051388504281628094, 0.14723532158149036, 0.34544643808304565, nan, 0.059498245597566141, 0.05540732157485579, 0.012831295188695307, 0.03129110483607251, 0.09790170866807188, 0.01500512745113935, 0.078234868919264705, 0.36838578043111231, nan, 0.71870618281078513, 0.10610407999700187, 0.14706358285998142, nan, 0.029435942422958519, 1.4940875970666132, nan, 1.0868491045209858, 2.129202954256384, nan, 3.3586976667282427, nan, 0.20401225505…
has comment: http://stackoverflow.com/comment/90307341
tagged with: python
has comment: http://stackoverflow.com/comment/90307766
linked to: http://stackoverflow.com/q/37800958
answer count: 0
type: UnansweredQuestion
tagged with: boundary
has title: Add curves to upper and lower boundaries of scatter plot
duplicate of: http://stackoverflow.com/q/37800958
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90308218
linked to: http://stackoverflow.com/q/27164114
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90309908
linked to: http://stackoverflow.com/q/24633664

http://stackoverflow.com/comment/90426307
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51732708
has text: @HeadOverFeet - I add link to docs, but is is easy, if check `print (x)` for each loop it return `Dataframe` per group. Also check last red alert why is first group returned twice. ;)
type: Comment

http://stackoverflow.com/comment/90389187
has text: The `neighbors` list has an error.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51713789

http://stackoverflow.com/a/51685653
has comment: http://stackoverflow.com/comment/90333845
answers question: http://stackoverflow.com/q/51685551
has comment: http://stackoverflow.com/comment/90333604
has comment: http://stackoverflow.com/comment/90333737
has comment: http://stackoverflow.com/comment/90333689
score: 0
has comment: http://stackoverflow.com/comment/90334036
has comment: http://stackoverflow.com/comment/90333666
has comment: http://stackoverflow.com/comment/90333698
has comment: http://stackoverflow.com/comment/90333758
type: Answer
has comment: http://stackoverflow.com/comment/90333623
has comment: http://stackoverflow.com/comment/90333994
has body: Assuming data will hold the HTML text: from bs4 import BeautifulSoup from pprint import pprint soup = BeautifulSoup(data, 'lxml') rows = [] for tr in soup.select('tr'): row = [td.text.strip() for td in tr.select('td') if td.text.strip() and td.text.strip() != '-'] if row: rows.append(row) pprint(rows, width=120) This will print: [['4342141', '25.07.2018 09:00', 'Golbasi Ankara, Turkey', 'Konya Havalimani Turkey'], ['4134123', '26.07.2018 09:00', 'Kucuktepe, Van, Turkey', 'Maltepe, Istanbul, Turkey']] For writing the rows list to csv you can use this script: import csv with open('data.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(rows) Then in data.csv file you will have: 4342141,25.07.2018 09:00,"Golbasi Ankara, Turkey",Konya Havalimani Turkey 4134123,26.07.2018 09:00,"Kucuktepe, Van, Turkey","Maltepe, Istanbul, Turkey"

python-unittest
tags question: http://stackoverflow.com/q/51678972
tags question: http://stackoverflow.com/q/51787922
tags question: http://stackoverflow.com/q/51728427
tags question: http://stackoverflow.com/q/51710660
tags question: http://stackoverflow.com/q/51715711
tags question: http://stackoverflow.com/q/51736864
tags question: http://stackoverflow.com/q/51658805
type: Tag
tags question: http://stackoverflow.com/q/51735421
tags question: http://stackoverflow.com/q/51737662
tags question: http://stackoverflow.com/q/51705439
tags question: http://stackoverflow.com/q/51655360
tag name: python-unittest

http://stackoverflow.com/a/51762364
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: You can use .set_index('Row Labels) to ensure your Row Labels column is interpreted as an axis for the heatmap and transpose your DataFrame with .T so that you get the time along the x-axis and the detectors for the y-axis. sns.heatmap(df.set_index('Row Labels').T)
answers question: http://stackoverflow.com/q/51761786
score: 2
accepted answer of: http://stackoverflow.com/q/51761786

http://stackoverflow.com/a/51668692
answers question: http://stackoverflow.com/q/51668608
downvote count: 0
score: 1
has body: I got it to work by adding self before calling COURSES (self.COURSES.items()), but is that correct? It is correct. By definition, attribute lookup starts at the instance, then goes through the class and its base classes. What you should be mindful of is if and how you want to react to shadowing attributes. self.COURSES allows instances and sub-classes to shadow the attribute for themselves. type(self).COURSES allows sub-classes but not instances to shadow the attribute. Example.COURSES never allows shadowing. You can try the difference with this example: class Lookup(object): ATTRIBUTE = 'Base' def lookup(self): print(self.ATTRIBUTE) # instance, class and base print(type(self).ATTRIBUTE) # class and base print(Lookup.ATTRIBUTE) # base class SubLookup(Lookup): ATTRIBUTE = 'Sub' print('&gt;&gt; base class') Lookup().lookup() print('&gt;&gt; sub class') SubLookup().lookup() print('&gt;&gt; instance') foo = SubLookup() foo.ATTRIBUTE = 'Instance' foo.lookup()
upvote count: 1
type: Answer

http://stackoverflow.com/comment/90310242
type: Comment
has text: Also, optparse is outdated. You should be using [argparse](https://docs.python.org/3/library/argparse.html#module-argparse).
type: QuestionComment
comment on: http://stackoverflow.com/q/51673671
score: 1

http://stackoverflow.com/comment/90288796
type: QuestionComment
has text: @DYZ Oh okay thank you
comment on: http://stackoverflow.com/q/51659737
score: 0
type: Comment

http://stackoverflow.com/a/51713423
score: 1
answers question: http://stackoverflow.com/q/51712638
has body: Some websites require a browser-like "User-Agent" header, other requires specific cookies. In this case, I found out by trial and error that both are required. What you need to do is: Send an initial request with a browser-like user-agent. This will fail with 403, but you will also obtain a valid cookie in the response. Send a second request with the same user-agent and the cookie that you got before. In code: import urllib.request from urllib.error import URLError # This handler will store and send cookies for us. handler = urllib.request.HTTPCookieProcessor() opener = urllib.request.build_opener(handler) # Browser-like user agent to make the website happy. headers = {'User-Agent': 'Mozilla/5.0'} url = 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=MET' request = urllib.request.Request(url, headers=headers) for i in range(2): try: response = opener.open(request) except URLError as exc: print(exc) print(response) # Output: # HTTP Error 403: Forbidden (expected, first request always fails) # &lt;http.client.HTTPResponse object at 0x...&gt; (correct 200 response) Or, if you prefer, using requests: import requests session = requests.Session() jar = requests.cookies.RequestsCookieJar() headers = {'User-Agent': 'Mozilla/5.0'} url = 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=MET' for i in range(2): response = session.get(url, cookies=jar, headers=headers) print(response) # Output: # &lt;Response [403]&gt; # &lt;Response [200]&gt;
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90279140
score: 0
type: AnswerComment
has text: @KhushalBadhan Can you search in /usr/lib by using the search command.
comment on: http://stackoverflow.com/a/51650157
type: Comment

http://stackoverflow.com/comment/90609971
has text: @Agile_Eagle Yeah, installed into an environment called grib and activated ipython from within that environment
comment on: http://stackoverflow.com/q/51758634
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90535450
has text: @Andrew `sticky=` basically tells the widgets to which side of the cell they should stick if the cell becomes larger than the widget, the default is to center the widget in the cell. `N`, `S`, `E` and `W` stand for north, south, east and west, so top, bottom, right and left. `N`, `S`, `E` and `W` are tkinter constants that are defined as `'n'`, `'s'`, `'e'` and `'w'`, so when you want the widget to stick to the top, bottom and left you can use either `sticky=N+S+W` or `sticky='nsw'`. Read more at [effbot](http://effbot.org/tkinterbook/grid.htm).
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51787791
type: Comment

http://stackoverflow.com/a/51667718
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51667626
type: Answer
answers question: http://stackoverflow.com/q/51667626
has body: You can assign a numpy array as a new column. final_df = train_df.assign(target=local_df["target"].values) For pandas >= 0.24, final_df = train_df.assign(target=local_df["target"].to_numpy())

http://stackoverflow.com/a/51718747
has comment: http://stackoverflow.com/comment/90422790
has comment: http://stackoverflow.com/comment/90424231
score: 1
has comment: http://stackoverflow.com/comment/90425739
has comment: http://stackoverflow.com/comment/90424382
has comment: http://stackoverflow.com/comment/90425552
has comment: http://stackoverflow.com/comment/90425829
has comment: http://stackoverflow.com/comment/90425882
has comment: http://stackoverflow.com/comment/90424547
downvote count: 0
has comment: http://stackoverflow.com/comment/90425598
has comment: http://stackoverflow.com/comment/90426031
answers question: http://stackoverflow.com/q/51716262
type: Answer
has body: In case you would want to try with waits , you can follow this code : wait = WebDriverWait(driver, 10) drop_down= wait.until(EC.visibility_of((By.CSS_SELECTOR, "select.PSDROPDOWNLIST[name^='TL_RPTD_TIME_PUNCH_TYPE'][id^='TL_RPTD_TIME_PUNCH_TYPE']"))) select = Select(drop_down) # select by visible text select.select_by_visible_text('Transfer') I am not sure whether ID is unique so, I have constructed a css selector with ID,name and class name. You will have to imports these : from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC Hope that will help.
has comment: http://stackoverflow.com/comment/90425772
has comment: http://stackoverflow.com/comment/90424503
upvote count: 1
has comment: http://stackoverflow.com/comment/90425974

http://stackoverflow.com/a/51745035
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90450520
has comment: http://stackoverflow.com/comment/90450061
has body: You can use pd.Series.duplicated to ignore the first occurrence: res = df[df['ID'].duplicated()].groupby('ID').sum() print(res) Period Variable ID 1 2 12 2 3 18
has comment: http://stackoverflow.com/comment/90449960
has comment: http://stackoverflow.com/comment/90450200
has comment: http://stackoverflow.com/comment/90449737
downvote count: 0
answers question: http://stackoverflow.com/q/51744769
type: Answer
has comment: http://stackoverflow.com/comment/90449784
has comment: http://stackoverflow.com/comment/90449799

http://stackoverflow.com/comment/90525489
score: 0
type: Comment
has text: I used your solution, and it adds a new model with the atributes that I add in SampleModel.objects.create(doc=File(myfile)). What I need is to add this csv file to the model that is created by the form. Sorry if I don't explain it really well :(
type: AnswerComment
comment on: http://stackoverflow.com/a/51767623

http://stackoverflow.com/q/51772616
tagged with: python-3.x
has body: I am trying to recreate this rasterio example: import numpy as np import rasterio from rasterio.features import rasterize from rasterio.transform import IDENTITY rows = cols = 10 geometry = { 'type': 'Polygon', 'coordinates': [[(2, 2), (2, 4.25), (4.25, 4.25), (4.25, 2), (2, 2)]] } with rasterio.Env(): result = rasterize([geometry], out_shape=(rows, cols)) with rasterio.open( "test.tif", 'w', driver='GTiff', width=cols, height=rows, count=1, dtype=np.uint8, nodata=0, transform=IDENTITY, crs={'init': "EPSG:4326"}) as out: out.write(result.astype(np.uint8), indexes=1) I have checked the result of rasterize (print(result)) which seems normal and sould result in a 2x2 pixel square: [[0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 1 1 0 0 0 0 0 0] [0 0 1 1 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0]] But I am getting a completely black image (nodata image).
tagged with: python
type: AnsweredQuestion
tagged with: rasterio
score: 0
type: Question
has answer: http://stackoverflow.com/a/51783752
tagged with: rasterizing
accepted answer: http://stackoverflow.com/a/51783752
has title: Rasterize Geometry Example not working
answer count: 1

http://stackoverflow.com/comment/93766938
type: Comment
comment on: http://stackoverflow.com/q/51716417
has text: I understand it. I had to use it in other things and I've the same impression.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51673146
has comment: http://stackoverflow.com/comment/90309152
score: 0
has title: Convert Latitude longitude to meters / feet in ( haversine in python )
duplicate of: http://stackoverflow.com/q/40802309
linked to: http://stackoverflow.com/q/40802309
tagged with: python
has comment: http://stackoverflow.com/comment/90309236
tagged with: haversine
tagged with: gps
has comment: http://stackoverflow.com/comment/90309131
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/639695
has body: I already find this answer How to convert latitude or longitude to meters? and about haversine formula but it's written in javascript. I want to know how can I give two coordinates like 48.829911, 2.373527 48.825843, 2.374273 and he will return for example there are 450 meters between them ? Do you have some function or library that I can use ? Thnks
tagged with: maps
type: Question
has comment: http://stackoverflow.com/comment/90308985
has comment: http://stackoverflow.com/comment/90309745
has comment: http://stackoverflow.com/comment/90310796

http://stackoverflow.com/q/51774470
has title: Cleanest way to support xarray, dask, and numpy arrays in one function
tagged with: python-xarray
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/61023124
accepted answer: http://stackoverflow.com/a/51795019
favorite count: 0
tagged with: dask
possible better answer: http://stackoverflow.com/a/61023124
has answer: http://stackoverflow.com/a/51795019
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90547466
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/90547509
tagged with: numpy
has body: I have a function that accepts multiple 2D arrays and creates two new arrays with the same shape. It was originally written to only support numpy arrays, but was "hacked" to support dask arrays if a "chunks" attribute was seen. A user who was using xarray DataArrays pointed out that this function now returns dask arrays because DataArray's have a "chunks" attribute. I'm wondering if the dask/xarray experts can tell me what the cleanest way to support all 3 (4?) object types might be without having to duplicate code for each type (numpy array, dask array, xarray with numpy, xarray with dask). Keep in mind the inputs are 2D arrays so the masking operations involved aren't supported out of the box. The related pull request for fixing this is here. Here is what we have so far while trying to avoid adding xarray and dask as required dependencies: if hasattr(az_, 'chunks') and not hasattr(az_, 'loc'): # dask array, but not xarray import dask.array as da az_ = da.where(top_s &gt; 0, az_ + np.pi, az_) az_ = da.where(az_ &lt; 0, az_ + 2 * np.pi, az_) elif hasattr(az_, 'loc'): # xarray az_.data[top_s &gt; 0] += np.pi az_.data[az_.data &lt; 0] += 2 * np.pi else: az_[top_s &gt; 0] += np.pi az_[az_ &lt; 0] += 2 * np.pi Edit: Is there an attribute that is semi-unique to xarray objects?

http://stackoverflow.com/comment/90409309
comment on: http://stackoverflow.com/q/51723005
type: Comment
type: QuestionComment
has text: Looks a bit like you pass around strings while I would expect it to be bytes. Not sure about the MQL5 part, but running your server code with some q&d Python client only required me to change `sock.sendto(reply, addr)` into `sock.sendto(bytes(reply, encoding="utf-8"), addr)` for it to work.
score: 0

http://stackoverflow.com/comment/90452747
comment on: http://stackoverflow.com/q/51746520
score: 0
has text: If there is some relation of variables to output - maybe you can group it in some way. If not possible consider some dictionary approach - large dictionary for mapping variables to expected value.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51678604
downvote count: 0
upvote count: 2
has body: Call your script with mass-email.py -m /path/to/my/file -c /path/to/csv Your arguments are defined by their flags. If you want your arguments to be positional, don't include the dashes before them. parser.add_argument('markdown', help='Path to Markdown Template', required=True) parser.add_argument('csv', help='Path to CSV file', required=True)
answers question: http://stackoverflow.com/q/51678520
type: Answer
has comment: http://stackoverflow.com/comment/90320500
score: 2
has comment: http://stackoverflow.com/comment/90322041

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/51770883
type: Tag

http://stackoverflow.com/q/51755271
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
has body: My problem I am trying to implement a Siamese network in Keras that is trained on triplets—[anchor_input, similar_input, different_input]—and executes on pairs—[input_a, input_b]—telling me whether they are similar or different. I am able to train fine on triplets, and have even trained and tested on pairs, but when I train on triplets and try to create my pair-wise network, I get the following error: ValueError: logits and labels must have the same shape (() vs (?, ?)) Current network overview My triplet network is defined using the following code, which I have pared down to something pretty minimal for this example: def siamese_triplet(in_shape, feature_dim): input_a = Input(shape=in_shape) # input is a series, n_samples by n_features input_b = Input(shape=in_shape) input_c = Input(shape=in_shape) base_network = create_model() # makes my Siamese kernel network processed_a = base_network(input_a) # base_network outputs a vector, say 50 elements long processed_b = base_network(input_b) processed_c = base_network(input_c) l1_distance = lambda x: K.abs(x[0] - x[1]) # vector, 50 elements long p_distance = Lambda(l1_distance, output_shape=lambda x: x[0])([processed_a, processed_b]) n_distance = Lambda(l1_distance, output_shape=lambda x: x[0])([processed_a, processed_c]) triplet_loss = Lambda(lambda x: K.mean(K.maximum(0, x[0] - x[1] + 1)), output_shape=(1,))([p_distance, n_distance]) # scalar model = Model([input_a, input_b, input_c], triplet_loss) optimizer = SGD() model.compile(optimizer=optimizer, loss=lambda x, y: y) # passes triplet loss through I train the network and get a fitted model object out. I then try to re-create the network with a structure built around input pairs, passing it the base_network layer extracted from my model, which ends up being model.layers[3]: # triplet_net = siamese_triplet(...) # model = triplet_net.fit(...) pair_net = siamese_pair(input_shape, model.layers[3]) with siamese_pair defined as: def siamese_pair(in_shape, base_network): inp…
has comment: http://stackoverflow.com/comment/90488106
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90494490
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90494628
downvote count: 0
tagged with: neural-network
tagged with: keras
has title: ValueError when trying to reconfigure Siamese network trained on triplets to operate on pairs
favorite count: 0

http://stackoverflow.com/q/51750726
has comment: http://stackoverflow.com/comment/90461785
linked to: http://stackoverflow.com/q/28259301
has answer: http://stackoverflow.com/a/51895668
tagged with: python
has answer: http://stackoverflow.com/a/51816249
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/51792013
has comment: http://stackoverflow.com/comment/90540819
type: Question
score: 5
has body: I have this xml file that would like to convert the contents to data frame for csv file in python: <?xml version="1.0" encoding="utf-8"?> tf:CustomTimeframe?1533008450802:1533019250802 test1 the output needs to look like this: timestamp max count node 1.53301E+12 11.14387512 6 Memory Utilization - test@server1 1.53301E+12 11.26842022 6 Memory Utilization - test@server1 1.53301E+12 13.74424839 6 Memory Utilization - test@server2 1.53301E+12 11.42728901 6 Memory Utilization - test@server2 1.53301E+12 8.429450035 6 Memory Utilization - test@server3 1.53301E+12 8.520565987 6 Memory Utilization - test@server3 1.53301E+12 1 1 Count Backend - test@server1 1.53301E+12 1 10 Count Backend - test@server1 1.53301E+12 1 1 Count Backend - test@server1 1.53301E+12 1 1 Count Backend - test@server1 I can do this in R like this: doc <- read_xml("C:/test1/test.xml") dat<-xml_find_all(doc, ".//measure/measure") %>% map_df(function(x) { xml_find_all(x, ".//measurement") %>% map_df(~as.list(xml_attrs(.))) %>% select(-min, -avg, -sum) %>% mutate(node=xml_attr(x, "measure")) }) I need to do this in python, any ideas?
possible better answer: http://stackoverflow.com/a/51792013
has answer: http://stackoverflow.com/a/51792079
downvote count: 0
accepted answer: http://stackoverflow.com/a/51816249
has comment: http://stackoverflow.com/comment/90461633
has title: how do you convert xml file to data frame or csv output in python
has comment: http://stackoverflow.com/comment/118766727
answer count: 4
favorite count: 0

http://stackoverflow.com/q/51644921
upvote count: 0
has comment: http://stackoverflow.com/comment/90253982
favorite count: 0
type: Question
score: -2
linked to: http://stackoverflow.com/q/36971604
has answer: http://stackoverflow.com/a/51645103
has title: Can't get the true html with python requests
has comment: http://stackoverflow.com/comment/90253936
has comment: http://stackoverflow.com/comment/90253938
downvote count: 2
answer count: 1
has body: When I use python urllib.request to parse a url, I got a 403 Forbidden.Here's the code: import urllib.request url='https://www.genecards.org/cgi-bin/carddisp.pl?gene=ERBB2' headers=('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36') opener=urllib.request.build_opener() opener.addheaders=[headers] urllib.request.install_opener(opener) data=urllib.request.urlopen(url).read().decode('utf-8') print(data) Then I get an error: Traceback (most recent call last): File "/Users/zhangqing/Documents/Yanpu/ERBB2 Gene.py", line 22, in &lt;module&gt; data=urllib.request.urlopen(url).read().decode('utf-8') File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 223, in urlopen return opener.open(url, data, timeout) File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 532, in open response = meth(req, response) File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 570, in error return self._call_chain(*args) File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/Users/zhangqing/anaconda/lib/python3.6/urllib/request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden When I try requests from python, the code is: import requests import re from requests.exceptions import RequestException def get_page(url): headers={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} try: res=requests.get(url,headers=headers) if res.status_code==200: return res.text except RequestException: return None html=get_page('https://www.genecards.org/cgi-bin/carddisp.pl?gene=ERBB2') print(html) I got a html like …
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/a/51791988
score: 0
type: Answer
has body: This is a constraint optimization problem, not a clustering problem. K-means etc. will not allow you to specify a value constraint. Properly formulate the objective function (what is acceptably close) and constraints (value limit), and try approaching it with a solver for such problems. Usually these are NP hard, so you can only afford to find a good, but not the best solution. Greedy strategies are desirable to reduce the runtime.
answers question: http://stackoverflow.com/q/51784897

http://stackoverflow.com/comment/90545894
has text: and this will do it for every row? No need to loop through it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51793625
type: AnswerComment

http://stackoverflow.com/comment/90481577
comment on: http://stackoverflow.com/q/51761269
has text: Meanwhile, can you reorganize things so the `input` happens in the main process, and the networking stuff happens in a child process, instead of the other way around? Sockets won't care about whether they're in the main process/group leader/console owner/whatever, but standard I/O might. So, if you can swap them, there's a good chance your problem just goes away, without needing to do any further debugging or changes.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51727799
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51689594
has body: def round_up(x): aX = abs(x) return math.ceil(aX)*(aX/x) This solution might work for you. For x = -1.2 round_up(x) = -2, x = 2.3 round_up(x) = 3 etc. edit: this solution will crash for x = 0. you can change the return value to return math.ceil(aX)*(aX/x) if x is not 0 else 0
type: Answer
has comment: http://stackoverflow.com/comment/90416026

http://stackoverflow.com/comment/90546331
type: AnswerComment
type: Comment
has text: Thank you, this is really helpful!
comment on: http://stackoverflow.com/a/51776732
score: 0

http://stackoverflow.com/comment/90601935
comment on: http://stackoverflow.com/q/51657219
score: 0
has text: How did you install python 3.6? It may have overwritten your system python2.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90378510
type: AnswerComment
comment on: http://stackoverflow.com/a/51707655
type: Comment
has text: @ot123: There is a space after the comma in my regex. It works with Python. Add the raw notation: `r'^\d+ min(?:, \d+ min)*$'`
score: 0

http://stackoverflow.com/q/51739253
score: 2
type: AnsweredQuestion
type: Question
has title: Python - Better way to iterate complex list than nested for loops
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90439104
tagged with: nested-loops
downvote count: 0
has answer: http://stackoverflow.com/a/51739626
favorite count: 0
has body: I am iterating a complex list in python with this format: [ { &lt;parent id&gt;: [ &lt;child id&gt;, &lt;child id&gt; ], &lt;parent id&gt;: [ &lt;child id&gt; ] }, { &lt;parent id&gt;: [ &lt;child id&gt;, &lt;child id&gt;, &lt;child id&gt; ], &lt;parent id&gt;: [ &lt;child id&gt; ] } ] The list will have dict as elements. These dict have keys of &lt;parent id&gt; and values of a list of &lt;child id&gt; There can be the same &lt;parent id&gt; in different dict, but &lt;child id&gt; can only belong to one &lt;parent id&gt;. An example is this: [ { 2: [1, 5], 3: [3, 7], 4: [6] }, { 1: [2, 4, 8], 4: [6] } ] Parent id 4 is in both dict elements but all child ids are unique to a parent id. Now I am iterating this data structure as input because I want to make sure that the condition of all childs being unique to a parent id is met. This is my code: def check_format(self, mapping): # mapping is the data structure unique_parent_list = [] child_list = [] for x in range(0, 2): for parent in mapping[x].keys(): if parent not in unique_parent_list: unique_parent_list.append(parent) for child in mapping[x][parent]: child_list.append(child) if len(child_list) &gt; len(set(child_list)): return 'Condition not met' else: return 'Condition met' This works, but I do not like that it is O^4 complexity or something like that. Is there a way to simplify or code this for better performance?
upvote count: 2
has answer: http://stackoverflow.com/a/51739824
accepted answer: http://stackoverflow.com/a/51739824
possible better answer: http://stackoverflow.com/a/51739626
tagged with: python

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/51787135
tags question: http://stackoverflow.com/q/51788344

http://stackoverflow.com/q/51798248
has body: I've trained a Doc2Vec model in order to do a simple binary classification task, but I would also love to see which words or sentences weigh more in terms of contributing to the meaning of a given text. So far I had no luck finding anything relevant or helpful. Any ideas how could I implement this feature? Should I switch from Doc2Vec to more conventional methods like tf-idf?
type: Question
score: 3
tagged with: python
tagged with: gensim
tagged with: nlp
has comment: http://stackoverflow.com/comment/90553384
upvote count: 3
tagged with: word2vec
answer count: 1
has title: How find the most decisive sentences or words in a document via Doc2Vec?
type: UnansweredQuestion
tagged with: doc2vec
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57778721

http://stackoverflow.com/comment/90293710
has text: And X > 0 resp. G > 0 all the time?
comment on: http://stackoverflow.com/q/51665236
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90458827
type: AnswerComment
comment on: http://stackoverflow.com/a/51749395
has text: Great solution @jpp
type: Comment
score: 2

http://stackoverflow.com/a/51772749
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51679605
answers question: http://stackoverflow.com/q/51679605
has body: As casimirethippolyte pointed out, patseg = re.sub(r'\W+', '\W+', seg) solved the problem for me.

http://stackoverflow.com/a/51776216
answers question: http://stackoverflow.com/q/51776191
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90510976
has body: If you have only two directories to search you can use glob on each directory separately and concatenate the result: json_files = glob.glob("AABC/*.json", recursive=True) + glob.glob("AADE/*.json", recursive=True)
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90510949

http://stackoverflow.com/comment/90313253
score: 0
comment on: http://stackoverflow.com/q/51659383
type: Comment
type: QuestionComment
has text: @desertnaut Yes. Thats what I was asking the OP. The code: `print 'score:', metrics.accuracy_score(ytest, predictions)` seems to be calculating the score from `xtest` and `ytest` and if the TP and FP are from these, the accuracy of 0.99 dont make sense. But seems like thats not the case.

http://stackoverflow.com/q/51673214
score: 0
has answer: http://stackoverflow.com/a/51673243
accepted answer: http://stackoverflow.com/a/51673243
tagged with: pip
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: python-venv
has title: Two pip versions in one venv - how to remove one of them
answer count: 1
has body: I've got venv with two versions of pip installed, how to remove one of them? Venv uses 10.0.1 by default, but when I try to run python -m pip install --upgrade pip I get: Requirement already up-to-date: pip in c:\users\&lt;username&gt;\pycharmprojects\convertshapefile\venv\lib\site-packages (18.0) ls from &lt;project&gt;\venv\Lib\site-packages: Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 03.08.2018 14:36 pip d----- 02.08.2018 16:58 pip-10.0.1-py3.7.egg d----- 03.08.2018 14:36 pip-18.0.dist-info d----- 02.08.2018 16:59 pyshp-1.2.12.dist-info d----- 02.08.2018 16:59 __pycache__ -a---- 03.08.2018 14:36 31 easy-install.pth -a---- 02.08.2018 16:58 563215 setuptools-39.1.0-py3.7.egg -a---- 02.08.2018 16:58 31 setuptools.pth -a---- 02.08.2018 16:59 52285 shapefile.py EDIT: After I pip-10.0.1-py3.7.egg renamed to pip-10.0.1-py3.7.egg_xxx, I get (venv) PS C:\Users\&lt;username&gt;\PycharmProjects\ConvertShapefile&gt; pip Traceback (most recent call last): File "C:\Users\&lt;username&gt;\PycharmProjects\ConvertShapefile\venv\lib\site-packages\setuptools-39.1.0-py3.7.egg\pkg_resources\__init__.py", line 574, in _build_master File "C:\Users\&lt;username&gt;\PycharmProjects\ConvertShapefile\venv\lib\site-packages\setuptools-39.1.0-py3.7.egg\pkg_resources\__init__.py", line 892, in require File "C:\Users\&lt;username&gt;\PycharmProjects\ConvertShapefile\venv\lib\site-packages\setuptools-39.1.0-py3.7.egg\pkg_resources\__init__.py", line 783, in resolve pkg_resources.VersionConflict: (pip 18.0 (c:\users\&lt;username&gt;\pycharmprojects\convertshapefile\venv\lib\site-packages), Requirement.parse('pip==10.0.1')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\&lt;username&gt;\PycharmProjects\ConvertShapefile\venv\Scripts\pip-script.py", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;froze…

http://stackoverflow.com/comment/90515898
type: QuestionComment
comment on: http://stackoverflow.com/q/51777361
score: 0
has text: Which portion of `HTML code` are you looking for?
type: Comment

http://stackoverflow.com/q/51787630
favorite count: 0
tagged with: pycharm
answer count: 5
downvote count: 1
has answer: http://stackoverflow.com/a/51959831
has answer: http://stackoverflow.com/a/51921771
type: AnsweredQuestion
has body: I want to develop with these tools: MS-Windows 10 Python3 gtk PyCharm I installed PyCharm, but up to now Python and gtk are not installed up to now. Sub questions: use 32 or 64 Bit version of Python? How to install gtk for python (pip or exe)? Use virtual env in PyCharm or use "Existing Interpreter"? AFAIK you cant install gtk for Python on Windows with pip. Update I follow this guide now: https://pygobject.readthedocs.io/en/latest/getting_started.html#windows-getting-started Update2 gtk on windows seems to be hardly used. There were many strange things, and I use pyside2 (QT) now and I am happy
accepted answer: http://stackoverflow.com/a/51849508
has answer: http://stackoverflow.com/a/62976733
type: Question
possible better answer: http://stackoverflow.com/a/51789197
has answer: http://stackoverflow.com/a/51789197
upvote count: 8
has title: Setting up developement environment: PyCharm, python-gtk, windows
tagged with: pygtk
tagged with: python
has answer: http://stackoverflow.com/a/51849508
score: 7

http://stackoverflow.com/q/51778991
answer count: 1
score: 0
tagged with: pandas
has body: I have a dataframe with a single column that contains States followed by their particular regions. The states are already in alphabetical order. I want to convert this single column into two columns. import pandas as pd places = [{'State':'Alabama'},{'State':'Auburn'},{'State':'Florence'},{'State':'Troy'},{'State':'Alaska'},{'State':'Fairbanks}] df0 = pd.DataFrame(places) s1 = df0.loc[df['State']=='Alabama'].index[0] #return row of state 'Alabama' s2 = df0.loc[df['State']=='Alaska'].index[0] #return row of state 'Alaska' df1 = df0 # create new dataframe for index, row in df0.iterrows(): # parse single column into two columns data if index == s1: df1['State']='Alabama' elif index &lt;= s2: df1['Region']=row['State'] df The above code returns: State Region 0 Alabama Alabama 1 Alabama Alabama ... ... ... 500 Alabama Alabama Note: In my example I only use Alabama and Alaska but there are another 500 rows below this for the other states. Any idea how I can get to the following: State Region 0 Alabama Auburn 1 Alabama Florence 2 Alabama Troy 3 Alaska Fairbanks ... ... ...
tagged with: python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51780356
has title: How do I convert a Pandas Dataframe with one column into a Pandas Dataframe of two columns?
has answer: http://stackoverflow.com/a/51780356
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/41130255
linked to: http://stackoverflow.com/q/406230

http://stackoverflow.com/a/51731789
type: Answer
has comment: http://stackoverflow.com/comment/90425022
has body: ProxyError is nothing but a class in python and the namespace rule apply to it too, so you need to either import ProxyError or use it where it is located. In requests library exceptions for the requests library are created at requests.exceptions so if you want to handle exception as below: try: proxyError = 0 connectFunction() except ProxyError: logPrint("Connection lost. Reconnecting...") proxyError = 1 you need to import exception class as below: from requests.exceptions import ProxyError otherwise you can handle it as below: try: proxyError = 0 connectFunction() except requests.exceptions.ProxyError: logPrint("Connection lost. Reconnecting...") proxyError = 1
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51731434
has comment: http://stackoverflow.com/comment/90427114
answers question: http://stackoverflow.com/q/51731434
has comment: http://stackoverflow.com/comment/90427151
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90425258

http://stackoverflow.com/q/51653319
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51653430
score: 2
type: AnsweredQuestion
tagged with: conditional-statements
has title: Why am I receiving a SyntaxError: invalid syntax regarding the use of an elif statement?
has body: I am trying write a code which generates a series of responses: if the user enters 1 number, several numbers or a string instead in order to generate a list of Fibonacci numbers. The code is as follows: def fib (a, b): return a + b number = int(input("Please write how many Fibonacci numbers you wish to have generated: ")) fibonacci_list = [] for n in range(number): if n in [0, 1]: fibonacci_list += [1] print("The first", number, "Fibonacci number is:", fibonacci_list) elif: fibonacci_list += [fib(fibonacci_list[n-2], fibonacci_list[n-1])] print("The first", number, "Fibonacci numbers are:", fibonacci_list) else: print('Sorry could not recognise the input')
type: Question
accepted answer: http://stackoverflow.com/a/51653359
tagged with: if-statement
has answer: http://stackoverflow.com/a/51653461
has answer: http://stackoverflow.com/a/51653359
possible better answer: http://stackoverflow.com/a/51653430
answer count: 3
has comment: http://stackoverflow.com/comment/90269950

http://stackoverflow.com/comment/90488918
type: Comment
comment on: http://stackoverflow.com/q/51765116
score: 0
type: QuestionComment
has text: Consider rewriting `type(event) == Event1 or type(event) == Event2` to `isinstance(event, (Event1, Event2))`.

http://stackoverflow.com/q/51755919
tagged with: python
has answer: http://stackoverflow.com/a/51776509
has body: I keep getting this error, line 37, in &lt;module&gt; ahealth = ahealth - attackdmg TypeError: unsupported operand type(s) for -: 'int' and 'tuple' It was for this line of code. if playerab == ('Attack'): attackdmg = randint(2,4) pcrit = randint(1,4) sleep(1) if pcrit == randint(1,4): attackdmg = attackdmg * (2,5) print('CRIT!') print('You decide to attack the Orc.') sleep(1) ahealth = ahealth - attackdmg print('You hit the orc for', (attackdmg)) sleep(1) print('The Orc has', (ahealth), ('health remaining.')) print orcturn = True playerturn = False I don't understand what is going on here, all of these variables are numbers. Thanks :)
has answer: http://stackoverflow.com/a/51756007
type: Question
has answer: http://stackoverflow.com/a/51755981
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90471483
has comment: http://stackoverflow.com/comment/90471719
has title: Error with subtraction with variables
type: UnansweredQuestion

http://stackoverflow.com/comment/90344685
score: 1
comment on: http://stackoverflow.com/q/51691499
has text: please remove the `return True` from inside `if` construct. Also use generators to read from file as its more efficient!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90298036
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51667190
type: AnswerComment
has text: @Rahul K P. Thanks for solution it is very elegant. Is it possible the result from list comprehension to take place into **ss1**. I mean to update values into **ss1** should reassign again?

http://stackoverflow.com/a/51653199
type: Answer
has comment: http://stackoverflow.com/comment/90291720
score: 0
has comment: http://stackoverflow.com/comment/90304364
has body: I think your construction of G_dis is wrong. Try using tuples like when you created G. This should work: G_dis = nx.Graph() for p1, d in nx.all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'): for p2, w in d.items(): G_dis.add_weighted_edges_from([(p1, p2, w)])
accepted answer of: http://stackoverflow.com/q/51652106
has comment: http://stackoverflow.com/comment/90402349
answers question: http://stackoverflow.com/q/51652106
type: AcceptedAnswer

http://stackoverflow.com/comment/90341743
comment on: http://stackoverflow.com/a/51685052
type: AnswerComment
has text: answering your first comment: It is a sparse vector, the length of the stored data may not reflect the dimension of the vector. The length value provided at initialization is the only way to access the true dimension of a `SparseVector` as defined above.
score: 0
type: Comment

http://stackoverflow.com/a/67808043
has comment: http://stackoverflow.com/comment/121758384
has comment: http://stackoverflow.com/comment/120058662
downvote count: 0
has comment: http://stackoverflow.com/comment/121760174
has comment: http://stackoverflow.com/comment/121786979
score: 6
type: Answer
upvote count: 6
has body: No need to worry about the color count if you set your color palette as a color map by setting "as_cmap" argument to True in sns.color_palette: ax = sns.lineplot(x="Wavelength", y="Absorption", hue="t (min)", lw=1, data=df1, palette=sns.color_palette('coolwarm', as_cmap = True), legend="brief")
answers question: http://stackoverflow.com/q/51762938

http://stackoverflow.com/q/51776834
favorite count: 0
has title: Detect pregnancy test results using OpenCV
linked to: http://stackoverflow.com/q/45322630
tagged with: python
has comment: http://stackoverflow.com/comment/90512068
has comment: http://stackoverflow.com/comment/90533697
has answer: http://stackoverflow.com/a/51777589
type: UnansweredQuestion
downvote count: 2
upvote count: 1
type: Question
tagged with: opencv
score: -1
answer count: 1
has body: Pretty much looking for what it says What I'm working with is a little different, but the end result is the same. Given an image, I'm wondering how I can count the lines (1 = negative, 2 = positive) to determine the results of the test. I've tried the same thing using TensorFlow with a large sample and I'm getting mixed results, and considering the project currently implements OpenCV for some other functionality, it would make sense to try to refactor this portion to use it as well. The images being detected could have differing angles, lighting, etc. The lines could also be a different color. Looking to avoid using Python specific items (such as Numpy) as the final code needs to be converted to C++ and Java, but given some python examples as a starting point would be great! I've been looking high and low for some sort of relevant example and haven't come up with anything. Any help is greatly appreciated!! I don't have exact images I can share currently, but these should provide similar enough approximations to get to the desired results:

http://stackoverflow.com/q/51787941
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51788104
type: UnansweredQuestion
has body: The following code doesn't add the column mean_val to the descripdat data frame descripdat.assign(mean_val= svrdat02.iloc[:,3:32].mean(axis=1)) even though the following works: descripdat['mean_val']=svrdat02.iloc[:,3:32].mean(axis=1)
has comment: http://stackoverflow.com/comment/90533387
tagged with: python
has title: Assign method of python dataframe object failing to add column
type: Question
has comment: http://stackoverflow.com/comment/90533345
score: -4
downvote count: 4
tagged with: pandas

http://stackoverflow.com/comment/90481274
has text: You don't do anything with the return value of your `compare` function
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51760939

http://stackoverflow.com/a/51740771
score: 0
type: Answer
has body: It does it because anywhere you're calling print it will print, so the best way to solve this is to remove the print or something else and also print is a none type Actually (None, 1) is the output of the code, it's just that when you're creating the dictionary it is printing so at the end your code is working as expected
answers question: http://stackoverflow.com/q/51740665

http://stackoverflow.com/comment/90559120
score: 0
comment on: http://stackoverflow.com/q/51794528
has text: you can see example output in the beginning of the question
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51692256
has body: You don't need the double groupby: Use drop_duplicates with ['b', 'c'] as your subset, to keep only unique rows, then groupby 'a' and use size: df.drop_duplicates(['b', 'c']).groupby('a').size() a 1 3 2 2 dtype: int64
has comment: http://stackoverflow.com/comment/90346077
downvote count: 0
upvote count: 6
answers question: http://stackoverflow.com/q/51692205
has comment: http://stackoverflow.com/comment/90346084
type: Answer
score: 6

http://stackoverflow.com/comment/90469078
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51754115
score: 1
has text: @Ben.T thank you. I just fixed it!

http://stackoverflow.com/comment/90502362
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51771656
has text: @user2906838 yes it's 3.7
score: 0

http://stackoverflow.com/comment/90536047
type: AnswerComment
comment on: http://stackoverflow.com/a/51775142
type: Comment
has text: Fair point. Interesting solution, I hadn't noticed that, good spot
score: 0

http://stackoverflow.com/q/51641761
has body: Environment: Corporate firewall Problem: When calling w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/API_KEY")) in web3.py, the request will be blocked by firewall with SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Attempt: Web3(Web3.HTTPProvider("https://ropsten.infura.io/v3/API_KEY", request_kwargs={'cert': "CERTIFICATE.pem"})) which should solve the issue according the python request documentation. However this problem persists. Question: Is there any mistake with my attempt? Is there a way to deactivate SSL cert?
tagged with: https
tagged with: reticulate
type: Question
tagged with: web3py
has title: Web3.py HTTPProvider requests SSL certificates
score: 4
upvote count: 4
tagged with: ethereum
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51677233
tagged with: python

http://stackoverflow.com/comment/90432906
score: 0
has text: Your Python script (`getdata.py`) is meant to be run on Windows. All it does is use Putty to log into `10.1.10.70`, run `~trak/Desktop/getdata.sh` there, and download the resulting `trakdelim.txt` file. If `getdata.sh` is gone from the server, this won't help you.
comment on: http://stackoverflow.com/q/51735899
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51716333
tagged with: kivy-language
tagged with: popup
accepted answer: http://stackoverflow.com/a/51716842
type: Question
type: AnsweredQuestion
tagged with: exit
answer count: 1
has title: Python kivymd Popup when exiting
has answer: http://stackoverflow.com/a/51716842
has body: I am trying to create a popup for exiting the application. But I keep getting an error "object.init() takes no arguments". Inside my project folder, I have a folder called "application". Inside this folder, I have copied the relevant kivymd *.py files into a folder called kivymd. I appreciate any help. After clicking the Exit Application selection, I want a popup with a button to accept or cancel the exiting of the application. Inside the application folder, I have three files: main.py, main.kv and labels.py (for injecting labels into the main.py and main.kv). The main.py is containing all the logic of the application. # -*- coding: utf-8 -*- import os # Set virtual keyboard from kivy.app import App from kivy.config import Config Config.set('kivy', 'keyboard_mode', 'systemandmulti') from kivy.uix.popup import Popup from kivy.uix.button import Button from kivy.core.window import Window Window.fullscreen = "auto" from kivy.lang import Builder from functools import partial from kivymd.list import BaseListItem from kivymd.material_resources import DEVICE_TYPE from kivymd.navigationdrawer import MDNavigationDrawer, NavigationDrawerHeaderBase from kivymd.theming import ThemeManager from kivymd.button import MDIconButton class HackedDemoNavDrawer(MDNavigationDrawer): # DO NOT USE def add_widget(self, widget, index=0): if issubclass(widget.__class__, BaseListItem): self._list.add_widget(widget, index) if len(self._list.children) == 1: widget._active = True self.active_item = widget # widget.bind(on_release=lambda x: self.panel.toggle_state()) widget.bind(on_release=lambda x: x._set_active(True, list=self)) elif issubclass(widget.__class__, NavigationDrawerHeaderBase): self._header_container.add_widget(widget) else: super(MDNavigationDrawer, self).add_widget(widget, index) class MainApp(App): theme_cls = ThemeManager() title = "Application" def build(self): main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), "./main.kv") ) self.theme_cls.theme_style = 'D…
score: 0
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/90303740
type: QuestionComment
has text: `writerows` iterates through the argument, thus it'll iterate through the string if thats what you're passing through, I suggest printing `new` inside the function to see if you're actually passing what you intend to be passing (as its unclear)
score: 0
comment on: http://stackoverflow.com/q/51670504
type: Comment

http://stackoverflow.com/q/51677314
has answer: http://stackoverflow.com/a/51684914
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/90318767
tagged with: tensorflow
has title: Inaccurate confusion matrix for a model with 98% test accuracy
type: Question
score: 5
has comment: http://stackoverflow.com/comment/90319693
tagged with: scikit-learn
tagged with: keras
has body: I trained a model for binary classification and received 98% of test accuracy and 99% of training accuracy. Today I wanted to calculate the confusion matrix and used below code to calculate them. model = load_model("model.h5") testGenerator = ImageDataGenerator(rotation_range=5, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=False, fill_mode='nearest' ) testData = testGenerator.flow_from_directory( 'Location', target_size=(74,448), batch_size=15, class_mode='binary', shuffle=False ) proba = model.predict_generator(testData,steps=3000//15) y_true = np.array([0] * 1482 + [1] * 1482 ) y_pred = proba &gt; 0.5 print(confusion_matrix(y_true, y_pred)) And I received this confusion matrix : As sklearn says : Which says here false negative and false positive are so high. How is that even possible since I had 98% of testing accuracy? Also I've used that model few times to generate predictions (using model.predict() fuction) and manually checked them. But each time it gave me correct classifications. Any Ideas how to get accurate results?
has comment: http://stackoverflow.com/comment/90318350
answer count: 1
has comment: http://stackoverflow.com/comment/90319787
favorite count: 0
has comment: http://stackoverflow.com/comment/90318330
upvote count: 5
tagged with: confusion-matrix
has comment: http://stackoverflow.com/comment/90318695
type: UnansweredQuestion

http://stackoverflow.com/q/51734703
answer count: 1
tagged with: flopy
favorite count: 0
has title: Extract heads from MODFLOW-USG binary output using flopy
has answer: http://stackoverflow.com/a/52100267
downvote count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has body: I am looking for a method to extract the simulated heads from a MODFLOW-USG binary head-save file. Flopy appears to support the operation using the flopy.utils.binaryfile Module, but I cannot get a simple test to work. The code below should return a list of all of the time outputs contained in the hds file, but only returns a single value for the first time step. Does flopy support extracting data from unstructured grid head-save files? modelname = 'Torr_TRu' import flopy.utils.binaryfile as bf # Create the headfile object headobj = bf.HeadFile(modelname+'.hds') times = headobj.get_times() print times
type: Question
upvote count: 1

http://stackoverflow.com/comment/90887448
type: AnswerComment
has text: Yes, try remove `.reset_index(level=1, drop=True)`
type: Comment
comment on: http://stackoverflow.com/a/51770117
score: 0

http://stackoverflow.com/comment/90245334
type: QuestionComment
comment on: http://stackoverflow.com/q/51640322
has text: Are you on Windows? Are you running the code inside an IDE (if so, which one?), or in the command prompt? (The reason I ask: on Windows, newlines get converted from `\n` to `\r\n`. Which is fine, because the command prompt _wants_ `\r\n`. But the "fake terminal" console in some IDE that doesn't get used much on Windows, or only gets used on Windows with Python 2.x, or who knows what, might get confused by that.)
score: 0
type: Comment

http://stackoverflow.com/q/51771935
has comment: http://stackoverflow.com/comment/90503080
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/19948159
tagged with: python
answer count: 0
score: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/90502841
type: Question
has comment: http://stackoverflow.com/comment/90503329
has title: How to limit QTreeView directory in PyQt5?
has body: I have this directory structure: files |----showme | |------asd.h | |------homework.docx | |------free games.exe |----my internet history | |-----------dont show me I would like it so that the QTreeView will only show the files/showme directory. How can I do this? this is my code: self.model.setRootPath('H:\\files\\showme') self.tree = QTreeView(self) self.tree.resize(620,300) self.tree.move(0,200) self.tree.setModel(self.model) EDIT: to clarify, I want it so that the base directory will be showme EDIT2: wrong code here, whoops!
has comment: http://stackoverflow.com/comment/90502697
tagged with: pyqt
linked to: http://stackoverflow.com/q/19948159

http://stackoverflow.com/q/51739271
tagged with: dataframe
has body: Say I have a dataframe, df: &gt;&gt;&gt; df Age Score 19 1 20 2 24 3 19 2 24 3 24 1 24 3 20 1 19 1 20 3 22 2 22 1 I want to construct a new dataframe that bins Age and stores their average scores of the bins in Score: Age Score 19-21 1.6667 22-24 2.1667 This is my way of doing it, which I feel is kind of convoluted: import numpy as np import pandas as pd data = pd.DataFrame(columns=['Age', 'Score']) data['Age'] = [19,20,24,19,24,24,24,20,19,20,22,22] data['Score'] = [1,2,3,2,3,1,3,1,1,3,2,1] _, bins = np.histogram(data['Age'], 2) df1 = data[data['Age']&lt;int(bins[1])] df2 = data[data['Age']&gt;int(bins[1])] new_df = pd.DataFrame(columns=['Age', 'Score']) new_df['Age'] = [str(int(bins[0]))+'-'+str(int(bins[1])), str(int(bins[1]))+'-'+str(int(bins[2]))] new_df['Score'] = [np.mean(df1.Score), np.mean(df2.Score)] Apart from being lengthy, this way doesn't scale well for more bins (as we'd need to write each entry for each bin in new_df). Is there a more efficient, clean way of doing this?
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51739329
has title: How to make a new dataframe to store the average values of the original dataframe's columns' bins?
tagged with: grouping
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
tagged with: binning
has answer: http://stackoverflow.com/a/51739329

http://stackoverflow.com/comment/90457153
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51748625
has text: 1. Does not specify what "the unwrap function" is or does or where it comes from. 2. Does not ask a question. (This could be addressed by posting the answer as an answer; [it's OK to answer your own question](https://stackoverflow.com/help/self-answer).) 3. The function provided isn't actually a function.

http://stackoverflow.com/comment/118793559
type: Comment
comment on: http://stackoverflow.com/a/66442394
has text: Also the use of textwrap.dedent is totally broken for multi-line f-strings, as the default case is to begin the dedent with a line-continuation `dedent('''\\`. This is plain broken imo and the bizarre purist attitudes like this from the py3 devs only serve to hurt the user.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90333091
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51684307
has text: Hi Sachin, Thank you for the response I tried this . However it is not redirecting, it is not calling chatbox_index() function in views.py file I added the redirection url in urls.py file as well.
type: AnswerComment

http://stackoverflow.com/comment/90480574
comment on: http://stackoverflow.com/a/51746191
score: 0
type: AnswerComment
type: Comment
has text: If you close the session and you want to reuse the previous cookies, you can use the one from user-data-dir=selenium. When you mentioned add_argument, your driver session would understand it needs to read from the cookies kept in that directory. That way you can reuse the cookies. But if you do not use add_argument, driver will look into default and see its empty so it will create new cookies and that way you cannot use the old cookies. add_argument("user-data-dir=selenium') basically directs the driver to use the data dir as "selenium" and then it will pick previous cookies.

http://stackoverflow.com/a/51654688
accepted answer of: http://stackoverflow.com/q/51654280
has body: Only thing I can see here that used cross_validation module earlier is train_test_split. So just change your import from: from sklearn.cross_validation import train_test_split to: from sklearn.model_selection import train_test_split and you are good to go.
answers question: http://stackoverflow.com/q/51654280
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90462751
type: QuestionComment
comment on: http://stackoverflow.com/q/51746147
score: 0
has text: No, Linux Mint 18.3
type: Comment

http://stackoverflow.com/q/51722090
tagged with: python
has answer: http://stackoverflow.com/a/51723874
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/51723742
type: Question
has body: I am new to Python. I have two lists. One is key list and another list is value list. title = ["Code","Title","Value",....] value = [["100","abcd",100",...],["101","efgh",200",...],...] data={} data.setdefault("data",[]).append({"code": sp[0],"val": sp[2]}) this code gives me the following result. {'data': [{'code': '100', 'val': '100'},{'code': '101', 'val': '200'}]} But I want the result as the below, { "100": { "Title": "abcd", "Value": "100", ............, ............}, "101": { "Title": "efgh", "Value": "200", ............, ............} } i.e., The first column of the value list should be the key of every Json array list and other items of the lists should be generated as key and value pair. How can I generate the Json array using Python code referring that two lists.
has answer: http://stackoverflow.com/a/51722514
has answer: http://stackoverflow.com/a/51723742
possible better answer: http://stackoverflow.com/a/51723874
score: 0
answer count: 3
has title: Writing json from two lists in Python

http://stackoverflow.com/a/51817090
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51797657
downvote count: 0
has body: My question is, if I have multiple coroutines writing to a single place how do I do that safely. The queues in asyncio seem to be one to one, not many to one - is that correct? That is not correct; asyncio queues are multiple-producer multiple-consumer. To implement the logic of your diagram, you need two synchronization primitives: a queue, filled by multiple instances of the sensor coroutine and drained by a single instance of the logic() coroutine an additional synchronization device per each actuator. Which kind of device is best here will depend on the requirements. For example, are actuators allowed to "lose" messages that come in faster than they are able to respond? Or, is the logic supposed to wait up? Depending on those, the synchronization between logic() and each actuator will be either a simple Event (or even just a Future) or another queue. Assuming you use a queue per actuator, your logic coroutine might look like this: async def logic(sensor_queue, actuator_queues): while True: item = await queue.get() # process the item and signal some actuators await actuator_queues[0].put(x1) await actuator_queues[1].put(x2)
answers question: http://stackoverflow.com/q/51797657

http://stackoverflow.com/comment/90360050
has text: If that's the case, then the result would be a 1D array, not a 3D matrix, correct?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51699220
score: 0

http://stackoverflow.com/comment/90282116
type: QuestionComment
comment on: http://stackoverflow.com/q/51659239
score: 0
has text: You are executing `create_server()` before you `start_new_thread` - which will execute `serve_forever()` and you are stuck. Put it inside `lambda` for example.
type: Comment

http://stackoverflow.com/comment/119179524
type: AnswerComment
has text: This removes the through model though and therefore doesn't fully answer the question. It works in this case, but there are use cases for through models that may need to be serialized.
comment on: http://stackoverflow.com/a/51785037
type: Comment
score: 1

http://stackoverflow.com/comment/93034769
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51652888
has text: All webs that that question give are dead... so... I think it can be answered here

http://stackoverflow.com/q/51701318
accepted answer: http://stackoverflow.com/a/51701641
tagged with: java
has body: I need a code to reverse order only the alphabets, without reversing the numbers. For Ex. Suppose I have : 3 D F 4 B 5 H 6 K (in a string or array) I should produce output: 3 K H 4 B 5 F 6 D
type: Question
upvote count: 0
tagged with: reverse
has comment: http://stackoverflow.com/comment/90366308
answer count: 1
has answer: http://stackoverflow.com/a/51701641
tagged with: string
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/90363748
tagged with: python
has title: Character Reversal without reversing numbers
downvote count: 6
tagged with: c++
has comment: http://stackoverflow.com/comment/90364016
type: AnsweredQuestion

http://stackoverflow.com/comment/90296678
type: Comment
comment on: http://stackoverflow.com/q/51666771
score: 0
type: QuestionComment
has text: What is expected output?

http://stackoverflow.com/comment/90412727
type: AnswerComment
comment on: http://stackoverflow.com/a/51726159
type: Comment
has text: @Ev.Kounis This shouldn't _work in general case_! also 2 is a parameter of list length and number of elements , I just didn't parameterize that.
score: 0

http://stackoverflow.com/a/51765707
has comment: http://stackoverflow.com/comment/90490948
has body: From the docs of an older scikit-learn version you can read the following: DEPRECATED: GMM.eval was renamed to GMM.score_samples in 0.14 and will be removed in 0.16. So I think you should use score_samples().
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90491606
upvote count: 1
answers question: http://stackoverflow.com/q/51765325
has comment: http://stackoverflow.com/comment/90490703
score: 1
has comment: http://stackoverflow.com/comment/90490872

http://stackoverflow.com/comment/90521181
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51781478
has text: @JJson I don't see how an underscore could cause any problems. If you want to be tricky, add some commas and/or quotes in your data.
score: 0

http://stackoverflow.com/comment/90376533
has text: i did this, in fact i just want to take the argument "C:/Users/michael/Documents/install" and to store it into a variable when i run the program, this is the exaple: -o C:/Users/michael/Documents/install -a all -p windows
type: Comment
comment on: http://stackoverflow.com/a/51707448
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90380110
has text: For one thing, your thread is doing user interface things that should only be done on the main thread. Not sure if that is THE problem, but try using Kivy's `Clock.schedule_once()` to do your `MSS.do_job()`, that will execute it on the main thread.
comment on: http://stackoverflow.com/q/51701737
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90268689
comment on: http://stackoverflow.com/q/51651812
score: 0
type: Comment
type: QuestionComment
has text: Why does your traceback says about line 24, while your script have 19 lines?

http://stackoverflow.com/comment/90482250
type: AnswerComment
comment on: http://stackoverflow.com/a/51761619
type: Comment
score: 0
has text: I don't understand what you are trying to say. Your answer is highly confusing: As a start: The first two lines are the exact same ones that OP has posted and will give therefor the same error. Your comment doesn't seem to have anything to do with the question. How does `data_path = os.path.join(os.getcwd(), 'data')` fit in here?

http://stackoverflow.com/q/51642240
score: 1
favorite count: 0
type: Question
tagged with: sockets
tagged with: python
has body: Im need is limited quantity the connections, in listen is set s.listen(2), but I don't see any exception and I can created three new connections and more. Where is the mistake? def func(): global addr host = socket.gethostbyname(socket.gethostname()) port = 9000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(2) while True: conn, addr = s.accept() if addr not in clients_addr: addr.append([conn, addr]) current_addr = addr thread = Thread(conn, current_addr) thread.start()
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/90249312
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35186725
has title: 'Listen()' value in socket not worked
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/90314411
has text: I can only suggest that you look at the variable `a=allHoldingsFund.loc[78, 'BrokerMixed']` and try to convert it into a string, then apply the function to your column and take the unique value.
type: AnswerComment
comment on: http://stackoverflow.com/a/51675274
type: Comment
score: 1

http://stackoverflow.com/q/51714251
tagged with: yield
tagged with: python-3.x
type: UnansweredQuestion
has body: I wrote a generator function in Python 3. Then I noticed that I do not use the values yielded by the generator. (I just call next() and ignore the result.) So I think I can replace all yields with yield None. The next question: Should I refactor a generator which returns only nones into something other? Maybe I can refactor my generator into a class and replace yield None with a dynamic method call? Is it always possible to refactor this way? (The questions is probably not very hard, and I may try to answer my own question in coming minutes or hours.)
has title: Refactor `yield None`
tagged with: python
tagged with: generator
answer count: 0
has comment: http://stackoverflow.com/comment/90390175
has comment: http://stackoverflow.com/comment/90390007
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/90390051
score: 0
has comment: http://stackoverflow.com/comment/90390000
has comment: http://stackoverflow.com/comment/90390563
has comment: http://stackoverflow.com/comment/90390310
has comment: http://stackoverflow.com/comment/90390424
has comment: http://stackoverflow.com/comment/90390364
has comment: http://stackoverflow.com/comment/90390493

http://stackoverflow.com/q/51737762
accepted answer: http://stackoverflow.com/a/51737771
tagged with: python-3.x
has title: How to convert list which contains a single string with multiple entries inside of string. Python 3
upvote count: 1
type: AnsweredQuestion
score: 1
has body: Let's say you have a list, which contains a single string as: listExample = ['cat, dog, mouse, elephant'] So printing this list return the values as a single string: &gt;&gt;&gt;'cat, dog, mouse, elephant' How do you get this string to the point where you can get the entries as multiple strings, such as: &gt;&gt;&gt;print(anotherList) &gt;&gt;&gt;['cat', 'dog', 'mouse', 'elephant']
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51737805
has answer: http://stackoverflow.com/a/51737771
downvote count: 0
possible better answer: http://stackoverflow.com/a/51737805
tagged with: python
favorite count: 0

http://stackoverflow.com/q/51748602
has body: I have dataframe like below X Y Z Value Time 0 18 55 1 70 100 1 18 55 2 67 200 2 18 57 2 75 300 3 18 58 1 35 400 4 19 54 2 70 500 X Y Z Value Time 0 17 15 1 40 100 1 17 60 2 67 200 2 17 57 5 75 300 3 17 79 1 35 400 4 17 54 2 70 500 X Y Z Value Time # Time in milliseconds 0 15 35 1 70 100 1 15 55 2 67 200 2 15 91 8 75 300 3 15 58 1 35 400 4 15 60 2 70 500 I want to save it as a text file with this format trying to group each row from different data frame for any particular time instant. X Y Z Value 18 55 1 70 17 15 1 40 15 35 1 70 Time: 100 X Y Z Value 18 55 2 67 17 60 2 67 15 55 2 67 Time: 200 # time grows ....
has title: Joining Multiple data frame to file.txt python based on time
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51748706
type: UnansweredQuestion
tagged with: text
tagged with: dataframe
type: Question
tagged with: numpy
score: 0
answer count: 1

http://stackoverflow.com/a/51785357
upvote count: 29
has body: The regex is outdated. It appears to cover Emoji's defined up to Unicode 8.0 (since U+1F91D HANDSHAKE was added in Unicode 9.0). The other approach is just a very inefficient method of force-encoding to ASCII, which is rarely what you want when just removing Emoji (and can be much more easily and efficiently achieved with text.encode('ascii', 'ignore').decode('ascii')). If you need a more up-to-date regex, take one from a package that is actively trying to keep up-to-date on Emoji; it specifically supports generating such a regex: import emoji def remove_emoji(text): return emoji.get_emoji_regexp().sub(u'', text) The package is currently up-to-date for Unicode 11.0 and has the infrastructure in place to update to future releases quickly. All your project has to do is upgrade along when there is a new release. Demo using your sample inputs: &gt;&gt;&gt; print(remove_emoji(u'తెలంగాణ రియల్ ఎస్టేట్ ')) తెలంగాణ రియల్ ఎస్టేట్ &gt;&gt;&gt; print(remove_emoji(u'Testరియల్ ఎస్టేట్ A.P&amp;T.S. ')) Testరియల్ ఎస్టేట్ A.P&amp;T.S. Note that the regex works on Unicode text, for Python 2 make sure you have decoded from str to unicode, for Python 3, from bytes to str first. Emoji are complex beasts these days. The above will remove complete, valid Emoji. If you have 'incomplete' Emoji components such as skin-tone codepoints (meant to be combined with specific Emoji only) then you'll have much more trouble removing those. The skin-tone codepoints are easy (just remove those 5 codepoints afterwards), but there is a whole host of combinations that are made up of innocent characters such as ♀ U+2640 FEMALE SIGN or ♂ U+2642 MALE SIGN together with variant selectors and the U+200D ZERO-WIDTH JOINER that have specific meaning in other contexts too, and you can't just regex those out, not unless you don't mind breaking text using Devanagari, or Kannada or CJK ideographs, to name just a few examples. That said, the following Unicode 11.0 codepoints are probably safe to remove (based on filt…
has comment: http://stackoverflow.com/comment/90528487
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90528384
has comment: http://stackoverflow.com/comment/90527909
has comment: http://stackoverflow.com/comment/90550934
has comment: http://stackoverflow.com/comment/90527925
type: Answer
has comment: http://stackoverflow.com/comment/90529414
accepted answer of: http://stackoverflow.com/q/51784964
has comment: http://stackoverflow.com/comment/90528499
has comment: http://stackoverflow.com/comment/90528578
has comment: http://stackoverflow.com/comment/90528100
answers question: http://stackoverflow.com/q/51784964
has comment: http://stackoverflow.com/comment/90527823
score: 29
has comment: http://stackoverflow.com/comment/90527977

http://stackoverflow.com/comment/90432597
comment on: http://stackoverflow.com/a/51735513
type: Comment
has text: @user322778 maybe my understanding of derivatives is really low as I have yet to go in college but it shouldnt matter right? furthermore there is no integer flowing in my model
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90357263
has text: Your example doesn't show creating `Tk` first. This answer would be better if you explained that in the body of the question.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51696142

http://stackoverflow.com/q/51676842
has comment: http://stackoverflow.com/comment/90317058
favorite count: 0
possible better answer: http://stackoverflow.com/a/51676894
accepted answer: http://stackoverflow.com/a/51677151
has comment: http://stackoverflow.com/comment/90656879
has answer: http://stackoverflow.com/a/51676941
tagged with: python
answer count: 4
tagged with: python-3.x
has body: Let's consider given a list [4, 5, 2, 19, 3, 8, 9] and given number is 8 then the output should be [4, 5, 2] because in output list there is no element greater than 8 and it is the only list with highest number of consecutive number. Please tell me the code in python 3 *NOTE: Please tell the logic without using import module. Here is my code test_cases = int(input()) for test_case in range(test_cases): n_and_c = list(map(int, input().split())) no_of_plots = n_and_c[0] max_cost_of_each_plot = n_and_c[1] list_of_cost_of_each_plot = list(map(int, input().split())) def list_of_required_plots(l_plots, m_plot): r = [] for i in l_plots: for j in range(len(l_plots)-1): if i &lt; m_plot: r.append(i) return r def list_of_eligible_plots(l_plots, r_plots): e = [] e.append(r_plots[0]) for i in range(len(r_plots) - 1): idx = l_plots.index(r_plots[i]) lp = 0 for j in range(len(r_plots)-1): if l_plots[idx+lp] == r_plots[i+lp] : e.append(r_plots[i+lp]) lp+=1 else: break return e def max_profit_func(r_plots, m_plot): m = 0 for i in r_plots: m+=(m_plot - i) return m required_plots = list_of_required_plots(list_of_cost_of_each_plot, max_cost_of_each_plot) eligible_plots = list_of_eligible_plots(list_of_cost_of_each_plot, required_plots) print(eligible_plots) if len(required_plots) == 0: print(0) else: max_profit = max_profit_func(eligible_plots, max_cost_of_each_plot) print(max_profit) I am trying to get the explained output for list_of_eligible_plots() in my code. Please any one help or suggest any logic. Thanks in advance
upvote count: 2
has comment: http://stackoverflow.com/comment/90319758
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51676982
has answer: http://stackoverflow.com/a/51677151
type: Question
has answer: http://stackoverflow.com/a/51676894
downvote count: 4
score: -2
has comment: http://stackoverflow.com/comment/90318854
tagged with: arrays
has comment: http://stackoverflow.com/comment/90316964
has title: How to find the list of consecutive elements in a random list where the resultant list should not have greater number than the given number

http://stackoverflow.com/a/51650215
has body: Although the answer is given in the comments below your question, this will just give you some idea on indexing. What you have is an integer value as a sublist within the list. a = [[2]] If you print its length and type print (len(a), type(a)) you get 1 &lt;class 'list'&gt; which means your a is a list with length 1. Since in python, indexing starts from 0, the content of list a is accessed as a[0]. But now repeating the above step again, print (len(a[0]), type(a[0])) yields 1 &lt;class 'list'&gt; which means the sublist a[0] is itself a list of length 1 and the content of this sublist a[0] can be accessed using the index 0. This means 0 index of a[0] as a[0][0]. This can go on forever depending on the number of sublists. But eventually the integer inside will result in TypeError because integer has no length. print (len(a[0][0])) yields TypeError: object of type 'int' has no len() Hope you understood the gist behind all this sublist and indexing.
score: 0
answers question: http://stackoverflow.com/q/51649956
type: Answer

http://stackoverflow.com/a/51708506
has body: A simple solution is to use the "soft placement" option for the session, that is, to ask TensorFlow to use the indicated device unless there is no kernel for it, in which case it would fallback to CPU: # ... with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # ... Another possibility is to pass instead a function to tf.device, such that the GPU device is selected unless the given operation meets some condition (typically when it has some specific type, in this case Assert, although there might be other operations that you would need to exclude in the model): def assign_device(op): if op.type != 'Assert': return '/gpu:0' else: return '/cpu:0' # ... with tf.device(assign_device): # ...
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51708373
accepted answer of: http://stackoverflow.com/q/51708373
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90391782
has text: i tried with this rule ['24','25','20'] and it returns 0.011245645615785078 my solution is exact but too slow
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51714672
type: Comment

http://stackoverflow.com/q/51668154
answer count: 1
has body: I want to group on the customer and match items where count is 1 with items where count is > 1 and if all the items are matched then add to new column the probable merge id. for example: customer 1, id=3 items are in id=2 so it's a match and proable merge id is 1 and Similarly for customer 2, id=7 is count 1 and items is within id=5 items, so match and probable merge id is 4. My Dataframe: count custmr id items 3 Customer1 1 Cabbage, beet, Okra, root 3 Customer1 2 Apple, Banana, Mango ,Pears, leafs 1 Customer1 3 Mango leafs 1 Customer1 4 tomato root 4 Customer2 5 grapes,leach,guava,pappaya 2 Customer2 6 blackberry,blueberry 1 Customer2 7 pappaya Expected Output: count custmr id items probable_merge_id 3 Customer1 1 Cabbage, beet, Okra, root 3 Customer1 2 Apple, Banana, Mango ,Pears, leafs 1 Customer1 3 Mango leafs 2 1 Customer1 4 tomato root 4 Customer2 5 grapes,leach,guava,pappaya 2 Customer2 6 blackberry,blueberry 1 Customer2 7 pappaya 4
has title: Pandas groupby and check if value of one row within another row value
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51669094
type: Question
has comment: http://stackoverflow.com/comment/90300061
score: 0
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/51782114
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90522000
accepted answer: http://stackoverflow.com/a/51782223
has comment: http://stackoverflow.com/comment/90521754
tagged with: replace
answer count: 2
has comment: http://stackoverflow.com/comment/90521765
possible better answer: http://stackoverflow.com/a/51782220
downvote count: 0
score: 1
has title: Python replace '\0' in string with null
has answer: http://stackoverflow.com/a/51782220
favorite count: 0
has body: I'm currently facing a strange problem. I want to replace the '\0' in strings with 'null' and read through many forums and always saw the same answer: text_it = "request on port 21 that begins with many '\0' characters, preventing the affected router" text_it.replace('\0', 'null') or text_it.replace('\x00', 'null') When I now print the string, I get the following result: "request on port 21 that begins with many '\0' characters, preventing the affected router" Nothing happened. So I used this method and it worked but it seems to be too much effort for such a small change: text_it = text_it.split('\0') text_it = text_it[0] + 'null' + text_it[1] Any idea why the replace function didn't work?
tagged with: null-terminated
tagged with: python
has answer: http://stackoverflow.com/a/51782223
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90521871

http://stackoverflow.com/comment/90306674
type: QuestionComment
score: 0
has text: I got it. I changed the command to pip install python-poppler-qt5.
comment on: http://stackoverflow.com/q/51665100
type: Comment

http://stackoverflow.com/comment/90450235
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51745287
has text: Impossible to answer without seeing the first few rows of your actual csv

http://stackoverflow.com/a/51750964
has comment: http://stackoverflow.com/comment/90466268
score: 48
type: Answer
answers question: http://stackoverflow.com/q/51750715
has comment: http://stackoverflow.com/comment/90465891
has comment: http://stackoverflow.com/comment/90466023
has body: The problem is you should not be running python base.py as part of the RUN directive. The RUN directive is executed only when you are building the image. The postgres container is not running at this point, nor has the network been created. Instead you want to use the CMD directive. Change the Dockerfile to this: FROM ubuntu:16.04 RUN apt-get update RUN apt-get -y install python-pip RUN apt-get update RUN pip install --upgrade pip RUN pip install psycopg2-binary COPY base.py base.py CMD ["python", "base.py"] The above should result in the hostname db to be resolved. However if your python code doesn't have any reconnection logic for connecting to the database the container will likely still error out. This because the postgres container will be running but the database won't be ready to accept connections. This can be temporarily fixed by adding restart: always to your docker-compose.yml. version: '3' services: db: image: 'postgres:latest' expose: - "5432" environment: POSTGRES_PASSWORD: pw1234 POSTGRES_DB: base123 aprrka: restart: always build: . depends_on: - db Hopefully this will get you up and running.
upvote count: 49
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/90466335
accepted answer of: http://stackoverflow.com/q/51750715

http://stackoverflow.com/comment/103770367
type: AnswerComment
comment on: http://stackoverflow.com/a/51660868
score: 0
type: Comment
has text: Since this answer is fairly old and I'm having to looking at it again, I did make an update to replace the `.format()`'s with f-string literals. I think it's more readable that way.

http://stackoverflow.com/a/51694581
upvote count: 1
answers question: http://stackoverflow.com/q/51694502
type: Answer
downvote count: 0
score: 1
has body: One solution could be df1[df1.merge(df2, 'left', ['y', 'z']).x_y.isnull()] Or, somewhat more low-key, df1[(df1'y', 'z' != df2'y', 'z').any(1)]

http://stackoverflow.com/a/51760712
answers question: http://stackoverflow.com/q/51760639
accepted answer of: http://stackoverflow.com/q/51760639
type: AcceptedAnswer
has body: Your first method will never work, since your function does not return a series, nor does it return anything for a row-wise calculation. Your second method is not in-place, you need to assign back to a series. For instance: df['sport_modified'] = df['sport'].apply(lambda x : x if x in top20_sport else 'Others') Your final solution can be more efficiently expressed using pd.Series.isin, negated via ~: L = ['Athletics', 'Gymnastics', ...] df.loc[~df['sport'].isin(L), 'sport_modified'] = 'Others'
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51781254
type: AnsweredQuestion
has title: Modify dictionary key
has answer: http://stackoverflow.com/a/51781489
accepted answer: http://stackoverflow.com/a/51781541
has answer: http://stackoverflow.com/a/51781566
type: Question
possible better answer: http://stackoverflow.com/a/51781436
has answer: http://stackoverflow.com/a/51781541
has answer: http://stackoverflow.com/a/51781502
has answer: http://stackoverflow.com/a/51781570
score: 0
has answer: http://stackoverflow.com/a/51781436
answer count: 7
has answer: http://stackoverflow.com/a/51781781
tagged with: python-3.x
tagged with: python
has body: Hi I have a dictionary like below { 'namelist': [{'name':"John",'age':23,'country':'USA'}, {'name':"Mary",'age':12,'country':'Italy'}, {'name':"Susan",'age':32,'country':'UK'}], 'classteacher':'Jon Smith' } I would like to know is it possible to change it to { 'namelist': [{'name_1':"John",'age_1':23,'country_1':'USA'}, {'name_2':"Mary",'age_2':12,'country_3':'Italy'}, {'name_3':"Susan",'age_3':32,'country_3':'UK'}], 'classteacher':'Jon Smith' } By adding _1, _2 .... on every last position of every key Is it possible? Thank you for your help

http://stackoverflow.com/comment/90495236
type: Comment
has text: So, you think that the best solution would be to put a secondary QMainWindow ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51767548

http://stackoverflow.com/a/60174813
score: 2
has body: Another solution. I improved the algorithm a little bit and also check the full name of the tag. import re def tagChecker(symbolString): s = Stack() pattern = re.compile('&lt;.*?&gt;') pattern_close = re.compile('&lt;/.*?&gt;') tag_list = re.findall(pattern, html_str) balanced = True index = 0 while index &lt; len(tag_list) and balanced: tag = tag_list[index] if not pattern_close.match(tag): s.push(tag) else: if s.isEmpty() or str.replace(tag, '/', '') != s.peek(): # s.peek() - function, which returns top of the stack without removing balanced = False else: s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False
downvote count: 0
answers question: http://stackoverflow.com/q/51756840
type: Answer
upvote count: 2

http://stackoverflow.com/q/51717394
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/51717512
accepted answer: http://stackoverflow.com/a/51717512
has body: When I do a contour plot, things go as expected x = (np.linspace(0, 10)) y = (np.linspace(0, 10)) X, Y = np.meshgrid(x, y) plt.contour(X, Y, np.sqrt(X) * Y) However, when I set the axis to log-log, nothing shows. When I enter the following code, pyplot only shows a blank screen. Is this expected behavior? How can I make the contour plot on a log-log axis? import matplotlib.pyplot as plt import numpy as np x = (np.linspace(0, 10)) y = (np.linspace(0, 10)) X, Y = np.meshgrid(x, y) plt.contour(X, Y, np.sqrt(X) * Y) plt.xscale('log') plt.yscale('log') plt.show()
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has title: pyplot log-log contour plot doesn't work
upvote count: 2

http://stackoverflow.com/comment/90547804
type: Comment
comment on: http://stackoverflow.com/a/51794372
has text: James: P.S. One way to fix this would be to define your own `Row` class that has it's own `__setitem__()` and `__getitem__()` methids and have the `Matrix` class create a list of them instead of a list-of-lists. In other words a list-of-Rows.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51717199
upvote count: 9
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51776155
type: AnsweredQuestion
tagged with: subplot
has answer: http://stackoverflow.com/a/51762070
downvote count: 0
has comment: http://stackoverflow.com/comment/90592397
favorite count: 0
possible better answer: http://stackoverflow.com/a/51762070
type: Question
has comment: http://stackoverflow.com/comment/90395964
tagged with: python
has title: How to adjust space between every second row of subplots in matplotlib
score: 9
has answer: http://stackoverflow.com/a/51776155
answer count: 3
tagged with: plot
has answer: http://stackoverflow.com/a/75257682
has body: I'm hoping to adjust the space between subplots horizontally. Specifically between every second row. I can adjust every row using fig.subplots_adjust(hspace=n). But is it possible to apply this to every 2nd row? import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize = (10,10)) plt.style.use('ggplot') ax.grid(False) ax1 = plt.subplot2grid((5,2), (0, 0)) ax2 = plt.subplot2grid((5,2), (0, 1)) ax3 = plt.subplot2grid((5,2), (1, 0)) ax4 = plt.subplot2grid((5,2), (1, 1)) ax5 = plt.subplot2grid((5,2), (2, 0)) ax6 = plt.subplot2grid((5,2), (2, 1)) ax7 = plt.subplot2grid((5,2), (3, 0)) ax8 = plt.subplot2grid((5,2), (3, 1)) fig.subplots_adjust(hspace=0.9) Using the subplots below I'm hoping to add a space between rows 2 and 3 and keep the rest as is.

http://stackoverflow.com/comment/90318400
score: 0
type: QuestionComment
has text: You need to decide the API you want. Do you want alternating `--input in1.png --output out1.png --input in2.png --output out2.png …` (kind of like ImageMagick `convert`)? If so, what happens if they write `--input in1.png --output out1.png --output out2.png`? Or maybe you want something like `--outsuffix _output file1.png file2.png file3.png`? Or… well, there are lots of options; look around at some other tools and see what they do and decide what you want to do. If you can't figure out how to implement it (probably with `argparse` or a third-party library), ask for help where you're stuck.
type: Comment
comment on: http://stackoverflow.com/q/51677462

http://stackoverflow.com/q/51678021
tagged with: difflib
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51678411
has comment: http://stackoverflow.com/comment/90320862
score: 1
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has title: How to compare two html files and show only the differences in a new html file using python
has body: I have used difflib but the html_table line is taking forever to execute. import difflib html_1 = data1 html_2 = data2 htmldiff = difflib.HtmlDiff() html_table = htmldiff.make_table([html_1], [html_2]) I have tried htmldiffer but it is giving me ValueError: stat: path too long for Windows from htmldiffer import diff str_a = data1 str_b = data2 d = diff.HTMLDiffer(data1, data2) print(d.combined_diff) I have tried htmltreediff it is giving NameError: name 'basestring' is not defined from htmltreediff import diff print (diff(data1, data2 , pretty=True))
tagged with: python-2.7

http://stackoverflow.com/comment/90821612
has text: But why is this an issue of macOS?
comment on: http://stackoverflow.com/a/51826289
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91139840
has text: @sayan_sen even when running the example? or just when running it on the real data?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51701369
type: Comment

http://stackoverflow.com/comment/90552606
type: AnswerComment
score: 0
type: Comment
has text: @MishraSiba I've edited the code . Can you check this please ?
comment on: http://stackoverflow.com/a/51792176

http://stackoverflow.com/comment/90360708
comment on: http://stackoverflow.com/q/51699109
type: Comment
type: QuestionComment
has text: Hi, I added the training and evaluating phase of the process also.
score: 1

http://stackoverflow.com/q/51793817
type: Question
has comment: http://stackoverflow.com/comment/90553603
score: 0
has body: I am developing a web app and i want to have obviously local environment. However I need to setup local env configs in my .env file and when I run python manage.py runserver it doesn't seem to load my env file, although heroku local does load it. Just to make sure I understand whats happening, id love to know what is the difference.
tagged with: python
has comment: http://stackoverflow.com/comment/90546620
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: heroku
has title: What's the difference between running heroku local and python manage.py

http://stackoverflow.com/comment/90443688
has text: I see. Then you might want to check out https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes
type: AnswerComment
comment on: http://stackoverflow.com/a/51740374
score: 0
type: Comment

http://stackoverflow.com/q/51768080
tagged with: python
has body: Question I have five models: class Features(models.Model): name = models.CharField(max_length=100, unique=True) class Filter(models.Model): name = models.CharField(max_length=100, unique=True) class Model(models.Model): name = models.CharField(max_length=200, unique=True) class TrainSet(models.Model): name = models.TextField(unique=True) class Algorithm(models.Model): feature = models.ManyToManyField(Features) filter = models.ManyToManyField(Filter) model = models.ForeignKey(Model, on_delete=models.DO_NOTHING, null=True) train_set = models.ForeignKey(TrainSet, on_delete=models.DO_NOTHING, null=True) I am doing some measurements that produce a calculated prediction based on features, filters, model and trainset. Those together form an algorithm First four are being changed trough the development process and because of that I would like to save each measurement with algorithm version. Problem If I would not care for data redundancy and database table normalizations I could create a different yet same algorithm for measurements. But because i care for redundancy and normalization I would like to check if the algorithm with respective one-to-many and many-to-many already exists. If instance exists, use that instance, otherwise create a new one. after each measurement the server that calculates the result sends a JSON to my django server in following form: { "filters": ["filter1", "filter2"], "model": "model-1", "features":["feature1", "feature2"], "trainset": "trainset1" } The problem is that i cannot find a way to check if an algorithm already exists with all its relations. What is the simplest way to find out if algorithm already exists? Update 1 I have tried Mohammad Ali's answer and it works partially. When the algorithm table is empty and i use following data: { "filters": ["filter1", "filter2"], "model": "model-1", "features":["feature1", "feature2"], "trainset": "trainset1" } it obviously finds zero rows. I then update the tables with data and then make the same …
tagged with: django
type: Question
tagged with: django-models
has answer: http://stackoverflow.com/a/51768927
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51768336
type: UnansweredQuestion
has title: Django - How to check if model instance has unique one-to-many and many-to-many relations

http://stackoverflow.com/comment/90300684
type: Comment
comment on: http://stackoverflow.com/a/51658365
has text: @RomanS I did not realise you had a lot of attributes that you wanted to do this with. Would having a single method that takes a string of an attribute name work? So it would check if the attr exists, and then print it? Or do you need each one to do something different?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90507633
score: 2
comment on: http://stackoverflow.com/q/51774445
has text: For the lookups integer hash values are used. This makes the type having a very low impact on the performance.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51751577
answers question: http://stackoverflow.com/q/51736340
has comment: http://stackoverflow.com/comment/90466778
score: 2
downvote count: 0
has body: In the following algorithm first I normalize the image pixels to have values zeros and ones. Then I examine the 8-connected neighbors of a non-zero pixel by applying a 3x3 unnormalized box-filter. If we multiply (pixelwise) the filter output from the input image, we get all the non-zero pixels, this time, their values tell us how many 8-connected neighbors they have plus 1. So, here the center pixel counts itself as its neighbor. Red is the center pixel. Yellow are its 8-connected neighborhood. We should eliminate the result pixel values less than 3. The code will make things clearer. It may not be very efficient. I didn't try to dig into Richard's code. May be he's doing a similar thing efficiently. import cv2 import numpy as np im = cv2.imread('USqDW.png', 0) # set max pixel value to 1 s = np.uint8(im &gt; 0) count = 0 i = 0 while count != np.sum(s): # non-zero pixel count count = np.sum(s) # examine 3x3 neighborhood of each pixel filt = cv2.boxFilter(s, -1, (3, 3), normalize=False) # if the center pixel of 3x3 neighborhood is zero, we are not interested in it s = s*filt # now we have pixels where the center pixel of 3x3 neighborhood is non-zero # if a pixels' 8-connectivity is less than 2 we can remove it # threshold is 3 here because the boxfilter also counted the center pixel s[s &lt; 3] = 0 # set max pixel value to 1 s[s &gt; 0] = 1 i = i + 1 After pruning:
upvote count: 2
has comment: http://stackoverflow.com/comment/90478724
type: Answer

http://stackoverflow.com/q/51738813
has body: I have posted below question, but question was not clear. Hence I am posting again with exact requirement and example. So that this time no one get confusion. I have Common VM (I will call it as CVM) and Two remote VM's (I will call it as RVM1 and RVM2). from CVM I have to run python scripts in RVM1 and RVM2 Machines . I have shell script in CVM. Below is what i am trying: #!/bin/sh ssh user@RVM1 "python -u runscript.py 5" ssh user@RVM2 "python -u runscript.py 10" ssh user@RVM1 "python -u runcommand.sh" runscript.py: import os import sys a = 10 b = 10 if sys.argv[1] == 10: #go back to shell script and wait to complete to shell script line (ssh user@RVM1 "python -u runcommand.sh") c = a + b print c Is this possible? if yes please help me how achieve this If this is not possible, how can i achieve this, During execution in RVM2 if sys.argv[1] == 10, then it should jump to RVM1 Machine and execute command. Again come back and resume remaining script in RVM2. Note: RVM1 and RVM2 Does not have access. Only CVM has access to RVM1 and RVM2
tagged with: multithreading
type: Question
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51742203
answer count: 1
tagged with: shell
has title: Execute script in multiple machines using shell script by calling python script
type: UnansweredQuestion
tagged with: ssh
tagged with: python

http://stackoverflow.com/comment/90432354
type: AnswerComment
type: Comment
has text: @roganjosh Unlikely, as `apply` is basically iterating row by row. See benchmarks in my edited answer.
comment on: http://stackoverflow.com/a/51735677
score: 0

http://stackoverflow.com/comment/90325825
score: 0
has text: To also match last message, try to change `(?=(`...`)` to `(?=(`...`|(?!.))`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51681281

http://stackoverflow.com/comment/90413535
comment on: http://stackoverflow.com/q/51726531
has text: I have realized the format was messed up and changed it to appear correctly.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51789799
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90537775
tagged with: django-celery
has answer: http://stackoverflow.com/a/51818234
type: Question
accepted answer: http://stackoverflow.com/a/51818234
has body: I have a signals.py inside my project/jobs app. This is the file: from celery.signals import task_postrun, after_task_publish from project.jobs.models import JobModel, JOB_STATUS_CHOICES @after_task_publish.connect def task_sent_handler(sender=None, headers=None, body=None, **kwargs): info = headers if 'task' in headers else body print('after_task_publish for task id {info[id]}'.format(info=info,)) @task_postrun.connect def task_postrun_handler(task_id=None, **kwargs): print('CONNECT', task_id) JobModel.objects.filter(task_id=task_id).update(status=JOB_STATUS_CHOICES.SUCCESS) task_sent_handler is fired while task_postrun_handler is not. signals.py is imported by my AppConfig, inside the ready() function. This is my celery config: CELERY_BROKER_URL = env('CELERY_BROKER_URL') CELERY_SEND_EVENTS = True CELERY_RESULT_BACKEND = env('CELERY_RESULT_BACKEND') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' Any suggestions as to why task_postrun may not be fired? They are both events under the Task category, so I can't see why one works and the other does not.
linked to: http://stackoverflow.com/q/7115097
has comment: http://stackoverflow.com/comment/90537222
score: 0
has comment: http://stackoverflow.com/comment/90539425
has comment: http://stackoverflow.com/comment/90537087
answer count: 1
has title: Celery @task_postrun.connect not firing
has comment: http://stackoverflow.com/comment/90537720
tagged with: django
tagged with: python
tagged with: celery

http://stackoverflow.com/comment/90389659
score: 0
type: Comment
type: QuestionComment
has text: there are 9 ham unigrams in the above. Therefore, I want the count 9 as the output.
comment on: http://stackoverflow.com/q/51714019

http://stackoverflow.com/comment/90418266
type: Comment
comment on: http://stackoverflow.com/a/51726543
score: 0
type: AnswerComment
has text: Are u sure, this location what in your error message: `Traceback (most recent call last): File "c:\python 3.6.3\lib\site-packages\pip\compat\__init__.py", line 73, `

http://stackoverflow.com/comment/90388883
comment on: http://stackoverflow.com/q/51713748
type: Comment
type: QuestionComment
has text: Please upgrade your code to a [mcve] -- without one, it's impossible to say what causes the error.
score: 3

http://stackoverflow.com/q/51715948
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: azure-active-directory
type: Question
has answer: http://stackoverflow.com/a/51718331
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51718331
tagged with: python
has body: I could manage to get access to Azure resources with the code bellow: from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource import ResourceManagementClient from azure.mgmt.compute import ComputeManagementClient from azure.graphrbac import GraphRbacManagementClient subscription_id = "aaaa" tenant_id = "bbbb" credentials = ServicePrincipalCredentials( client_id="cccc", secret="dddd", tenant=tenant_id ) client = ResourceManagementClient(credentials, subscription_id) for item in client.resource_groups.list(): print item compute_client = ComputeManagementClient(credentials, subscription_id) disks = compute_client.disks.list() for disk in disks: print disk But I can't access Azure AD with the same code!!! Is there a different way to access it? Why is it different?! See the code bellow: graphrbac_client = GraphRbacManagementClient(credentials, subscription_id) for item in graphrbac_client.groups.list(): print item Error: GraphErrorExceptionTraceback (most recent call last) in () 1 graphrbac_client = GraphRbacManagementClient(credentials, subscription_id) 2 ----> 3 for item in graphrbac_client.groups.list(): 4 print item /home/andre/.local/lib/python2.7/site-packages/msrest/paging.pyc in next(self) 129 return response 130 else: --> 131 self.advance_page() 132 return self.next() 133 /home/andre/.local/lib/python2.7/site-packages/msrest/paging.pyc in advance_page(self) 115 raise StopIteration("End of paging") 116 self._current_page_iter_index = 0 --> 117 self._response = self._get_next(self.next_link) 118 self._derserializer(self, self._response) 119 return self.current_page /home/andre/.local/lib/python2.7/site-packages/azure/graphrbac/operations/groups_operations.pyc in internal_paging(next_link, raw) 336 337 if response.status_code not in [200]: --> 338 raise models.GraphErrorException(self._deserialize, response) 339 340 return response GraphErrorException: Access Token missing or malformed. azure-common version = 1.1.14
has title: How to access Azure AD with Python SDK?

http://stackoverflow.com/q/51736465
tagged with: eve
has comment: http://stackoverflow.com/comment/90534863
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
tagged with: pymongo
upvote count: 1
has body: I'm working on an Eve tutorial and I'm stuck at an early point. I just have two python files: app.py: from eve import Eve app = Eve() settings.py: DOMAIN = { 'people': {} } I also have mongodb running which eve needs to run. When I run the eve app and then attempt to consume it with the regular localhost:5000, it works just fine. But when I attempt to consume localhost:5000/people, it results in a timeout with this error: pymongo.errors.ServerSelectionTimeoutError: hour must be in 0..23 I'm working on ubuntu 17.10 os, eve 0.8, pymongo 3.7.1, and mongodb 4.0.1. I just can't see where I'm going wrong as the code is so simple. I think it has to be the dependencies or something to do with an error in how eve is connecting, though I'm not sure. Eve seems to be constantly connecting and disconnecting from the database while it is running. I'm not sure if this is a regular thing or not. Anyone have any idea what might be going wrong? Many thanks for any help.
type: Question
tagged with: mongodb
downvote count: 0
has comment: http://stackoverflow.com/comment/90485032
has title: pymongo.errors.ServerSelectionTimeoutError: hour must be in 0..23

http://stackoverflow.com/comment/110708109
type: AnswerComment
has text: ROCm is there.. not just CUDA
type: Comment
comment on: http://stackoverflow.com/a/51730706
score: 1

http://stackoverflow.com/a/51761572
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51751953
type: Answer
has body: Tesseract is very sensitive to the image borders, so adding about 20 pix border around your filtered image will solve the issue. Regarding 7-segment font as stated in tesseract issue - LSTM (tess 4.*) might not be the best approach and there are different libraries which can handle this better. You can try this tessdata for tesseract 3.4;

http://stackoverflow.com/a/51700934
type: Answer
has comment: http://stackoverflow.com/comment/115521051
has comment: http://stackoverflow.com/comment/115519114
score: 39
has comment: http://stackoverflow.com/comment/133493501
accepted answer of: http://stackoverflow.com/q/51700729
upvote count: 39
answers question: http://stackoverflow.com/q/51700729
type: AcceptedAnswer
downvote count: 0
has body: By "combine them" I assume you mean to concatenate the two inputs. Assuming you concat along the second dimension: import torch from torch import nn class TwoInputsNet(nn.Module): def __init__(self): super(TwoInputsNet, self).__init__() self.conv = nn.Conv2d( ... ) # set up your layer here self.fc1 = nn.Linear( ... ) # set up first FC layer self.fc2 = nn.Linear( ... ) # set up the other FC layer def forward(self, input1, input2): c = self.conv(input1) f = self.fc1(input2) # now we can reshape `c` and `f` to 2D and concat them combined = torch.cat((c.view(c.size(0), -1), f.view(f.size(0), -1)), dim=1) out = self.fc2(combined) return out Note that when you define the number of inputs to self.fc2 you need to take into account both out_channels of self.conv as well as the output spatial dimensions of c.

http://stackoverflow.com/q/51736860
has comment: http://stackoverflow.com/comment/90434456
has comment: http://stackoverflow.com/comment/90434391
has comment: http://stackoverflow.com/comment/90434376
has comment: http://stackoverflow.com/comment/90434375
has answer: http://stackoverflow.com/a/51737061
has comment: http://stackoverflow.com/comment/90434360
has comment: http://stackoverflow.com/comment/90434439
tagged with: search
score: 0
answer count: 2
has body: I have an input of about 2-5 millions strings of about 400 characters each, coming from a stored text file. I need to check for duplicates before adding them to the list that I check (doesn't have to be a list, can be any other data type, the list is technically a set since all items are unique). I can expect about 0.01% at max of my data to be non-unique and I need to filter them out. I'm wondering if there is any faster way for me to check if the item exists in the list rather than: a=[] for item in data: if item not in a: a.add(item) I do not want to lose the order. Would hashing be faster (I don't need encryption)? But then I'd have to maintain a hash table for all the values to check first. Is there any way I'm missing? I'm on python 2, can at max go upto python 3.5.
accepted answer: http://stackoverflow.com/a/51737061
has comment: http://stackoverflow.com/comment/90434565
favorite count: 0
has title: Python: Fastest way to search if long string is in list of strings
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51736902
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51736902

http://stackoverflow.com/comment/90532138
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51787451
type: AnswerComment
has text: Thanks for the help!

http://stackoverflow.com/q/51793928
type: UnansweredQuestion
tagged with: python
has title: Distance between two Points in pandas csv Data-frame
has body: I want to calculate the distance between two coordinates points(Lat1,long1, and Lat2,Long2) for the below data frame. `name_x rnc_x lat1 long1 scrambling_code name_y rnc_y lat2 long2 UI11481 MURNC09 72.82584 19.01234 121 UI11481 MURNC09 72.82584 19.01234 UI11481 MURNC09 72.82584 19.01234 121 UI37616 MURNC09 72.8282 19.01753 UI11481 MURNC09 72.82584 19.01234 121 UM13167 MURNC04 72.85002 19.09671 UI11481 MURNC09 72.82584 19.01234 121 UM12606 MURNC12 72.8563 19.18566 UI11481 MURNC09 72.82584 19.01234 121 UI17997 MURNC01 72.82161 18.92689 UI11481 MURNC09 72.82584 19.01234 121 UM36021 MURNC07 72.8816 19.1771 UI11481 MURNC09 72.82584 19.01234 121 UM30099 MURNC12 72.871 19.2173 UI11481 MURNC09 72.82584 19.01234 121 UM2411 MURNC17 72.8599 19.2498 UI11481 MURNC09 72.82584 19.01234 121 UM41377 MURNC22 72.8531 19.0142 UI11481 MURNC09 72.82584 19.01234 121 UM35501 MURNC08 72.8538 19.3042 UI11481 MURNC09 72.82584 19.01234 121 UM6086 MURNC15 72.8046 18.9728 UI11481 MURNC09 72.82584 19.01234 121 UI28816 MURNC14 72.821753 19.060517 `
tagged with: geolocation
type: Question
has comment: http://stackoverflow.com/comment/90547439
tagged with: geopy
score: -1
has answer: http://stackoverflow.com/a/51849637
upvote count: 2
has comment: http://stackoverflow.com/comment/90545861
tagged with: pandas
tagged with: euclidean-distance
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90545838
downvote count: 3

http://stackoverflow.com/comment/90509294
type: QuestionComment
score: 1
has text: @saketk21, I went ahead and ignored the index while converting my file from xlsx to csv. data_xls.to_csv('def.csv,encoding='utf-8',index=False)
comment on: http://stackoverflow.com/q/51774634
type: Comment

http://stackoverflow.com/comment/114098241
type: Comment
has text: @mostafiz67 I can not open your notebook (it is not made public) and please start a new question.
comment on: http://stackoverflow.com/a/51683297
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90472208
comment on: http://stackoverflow.com/q/51756278
type: Comment
type: QuestionComment
has text: It's probably helpful to include the function body, and not just the signature.
score: 1

http://stackoverflow.com/a/51725795
has body: If they are string, you can use replace: df[col] = df[col].str.replace('[','') df[col] = df[col].str.replace(']','') Or if the square brackets you want to remove are only at the start or end of the string, with strip: df[col] = df[col].str.strip('[') df[col] = df[col].str.strip(']')
type: Answer
has comment: http://stackoverflow.com/comment/90412226
has comment: http://stackoverflow.com/comment/90412011
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90412277
has comment: http://stackoverflow.com/comment/90412402
has comment: http://stackoverflow.com/comment/90412338
has comment: http://stackoverflow.com/comment/90411978
answers question: http://stackoverflow.com/q/51725753
upvote count: 2

http://stackoverflow.com/q/51712467
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has body: I have already tried using a visualizer but this problem only returns none. This is the codewars question: https://www.codewars.com/kata/calculating-with-functions/solutions/python def zero(f = None): return 0 if not f else f(0) def one(f = None): return 1 if not f else f(1) def two(f = None): return 2 if not f else f(2) def three(f = None): return 3 if not f else f(3) def four(f = None): return 4 if not f else f(4) def five(f = None): return 5 if not f else f(5) def six(f = None): return 6 if not f else f(6) def seven(f = None): return 7 if not f else f(7) def eight(f = None): return 8 if not f else f(8) def nine(f = None): return 9 if not f else f(9) def plus(y): return lambda x: x+y def minus(y): return lambda x: x-y def times(y): return lambda x: x*y def divided_by(y): return lambda x: x/y four(plus(nine))
has title: Why doesn't this codewars algorithm work using only functions?
downvote count: 0
has comment: http://stackoverflow.com/comment/90386342
type: AnsweredQuestion
tagged with: algorithm
score: 1
type: Question
has answer: http://stackoverflow.com/a/51712521
accepted answer: http://stackoverflow.com/a/51712521

http://stackoverflow.com/q/51744615
has body: In my postgresql db i have the following fields: Field O is of type bytea called "File" and X is called "Document_name". When I call for that column to be displayed in my html file, it shows what i think is hex format: &lt;tr&gt; &lt;td&gt;{{ item.Document_name }}&lt;/td&gt; &lt;td&gt;{{ item.File }}&lt;/td&gt; &lt;/tr&gt; test &lt;memory at 0x7fecefe9e1c8&gt; Document_name &lt;memory at 0x7fecefe9e288&gt; Document_name &lt;memory at 0x7fecefe9e348&gt; Document_name &lt;memory at 0x7fecefe9e408&gt; Proposal Document &lt;memory at 0x7fecefe9e588&gt; test &lt;memory at 0x7fecefe9e4c8&gt; How do I make it so it displays the text I see in my DB e.g. User_storeis_for_PTK.docx instead of memory at 0x7fecefe9e288
has comment: http://stackoverflow.com/comment/90449037
score: 0
tagged with: postgresql
has title: Postgresql type bytea not displaying text in html
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90449779
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/51777605
type: Answer
answers question: http://stackoverflow.com/q/51775993
downvote count: 0
score: 1
has body: Can I write matchers in unittest.TestCase like in gmock matchers? Sure you can, many projects have already using their own YourTestCase inherited from unittest.TestCase, e.g. class TestDataStrut(YourTestCase) will be used instead of class TestDataStruct(unittest.TestCase). If you have to use the specific assert often in a large project, you have to do it yourself. Django TestCase Django testcases.py code An Example of creating your own TestCase
upvote count: 1

http://stackoverflow.com/comment/90314838
has text: You need to replace `data1=np.array[1,2,3,4]` by `data1=np.array([1,2,3,4])` for others to be able to work in the first step with your data. I prefer you edit it yourself. Same applies to the rest
comment on: http://stackoverflow.com/q/51675848
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51705719
has comment: http://stackoverflow.com/comment/90691185
has title: extract data from mongo wire protocol packets
tagged with: python
tagged with: wireshark
tagged with: mongodb-query
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: packet-capture
has body: I need to extract information from Mongo packets, but I don't found a simple way to do this. In the figure there is an example of the mongo packets that I use. Mongo Wire Protocol Packet In particular I would like to collect the data indicated as "prod1" and "23.22". I've use pyshark library with pyshark.FileCapture('capture.pcap',use_json=True), but I can get the data only with a series of nested loops. Is there a simple way, with the use of a tool or a specific library (also in different language of python), to extract these informations?
has comment: http://stackoverflow.com/comment/90631921
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/90372348

http://stackoverflow.com/comment/90486099
comment on: http://stackoverflow.com/q/51763172
type: QuestionComment
type: Comment
score: 0
has text: what do you mean by "only stores the dnd. Although there is the rest it doesn't store it." ... that pad files are not stored or that it only stores 1 dnd file and that's all?

http://stackoverflow.com/comment/90467797
type: Comment
type: QuestionComment
has text: Thanks Peter,I was just missing () when I was calling my functions.
comment on: http://stackoverflow.com/q/51753343
score: 0

http://stackoverflow.com/comment/90471272
has text: "use relative paths" isn't a reason to need to `chdir`. You can just manually resolve the paths relative to different directories.
score: 0
comment on: http://stackoverflow.com/q/51755534
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51660134
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51661785
type: Question
score: 0
answer count: 1
has body: Ignore the below Texts Paragraph XML code, a formal recommendation from the World Wide Web Consortium (W3C), is similar to Hypertext Markup Language (HTML). Both XML and HTML contain markup symbols to describe page or file contents. HTML code describes Web page content (mainly text and graphic images) only in terms of how it is to be displayed and interacted with. XML data is known as self-describing or self-defining, meaning that the structure of the data is embedded with the data, thus when the data arrives there is no need to pre-build the structure to store the data; it is dynamically understood within the XML. The XML format can be used by any individual or group of individuals or companies that want to share information in a consistent way. XML is actually a simpler and easier-to-use subset of the Standard Generalized Markup Language (SGML), which is the standard to create a document structure. So, for I used the below code to extract all 5 the fields. import requests from bs4 import BeautifulSoup import lxml soup = BeautifulSoup(contents,'lxml') a=[v.get_text() for v in soup.select('cia')] v=[v.get_text() for v in soup.select('civ')] p=[v.get_text() for v in soup.select('cip')] y=[v.get_text() for v in soup.select('ciy')] t=[v.get_text() for v in soup.select('cit')] print (a) print (v) print (p) print (y) print (t)
favorite count: 0
tagged with: beautifulsoup
tagged with: lxml
tagged with: python
has comment: http://stackoverflow.com/comment/90284282
tagged with: http://stackoverflow.com/tag/xml
has title: Python: if the XML tag doesn't exist, I need to print 'Blank' along with Output
type: UnansweredQuestion
tagged with: select

http://stackoverflow.com/q/51716954
type: Question
tagged with: numpy
tagged with: arrays
has body: I'd like to locate all the nonzero values within a 2D numpy array and move them so that the image is centered. I do not want to pad the array because I need to keep it the same shape. For example: my_array = np.array([[1, 1, 0, 0], [0, 0, 2, 4], [0, 0, 0, 0], [0, 0, 0, 0]]) # center... &gt;&gt;&gt; [[0 0 0 0] [0 1 1 0] [0 2 4 0] [0 0 0 0]] But in reality the arrays I need to center are much larger (like 200x200, 403x403, etc, and they are all square). I think np.nonzero and np.roll might come in handy, but am not sure of the best way to use these for my large arrays.
has answer: http://stackoverflow.com/a/51729499
has comment: http://stackoverflow.com/comment/90395430
has comment: http://stackoverflow.com/comment/90395228
score: 0
has title: How to center the nonzero values within 2D numpy array?
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90404632
accepted answer: http://stackoverflow.com/a/51729499
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90395404
has comment: http://stackoverflow.com/comment/90395466

http://stackoverflow.com/comment/90413443
comment on: http://stackoverflow.com/q/51726399
type: Comment
type: QuestionComment
score: 0
has text: @intentionallyleftblank installed with "pip install python3.6".

http://stackoverflow.com/q/51752634
accepted answer: http://stackoverflow.com/a/51752837
has comment: http://stackoverflow.com/comment/90465697
has comment: http://stackoverflow.com/comment/90465319
has comment: http://stackoverflow.com/comment/90465960
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51752837
has comment: http://stackoverflow.com/comment/90465809
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90465194
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51752749
tagged with: python
has answer: http://stackoverflow.com/a/51752749
tagged with: indexing
has title: Scatter plot with logical indexing
type: AnsweredQuestion
downvote count: 0
has body: I have a 100x2 array D and a 100x1 array c (with entries +/- 1) I'm trying to make a scatter plot of the columns in D corresponding to c = 1. I tried something like this: plt.scatter(D[0][c==1],D[1][c==1]) but it throws up IndexError: too many indices for array I'm aware that I've use list comprehension or something of that sort. I'm fairly new to Python and hence struggling with the format. Thanks a lot.
score: 1

http://stackoverflow.com/comment/90536603
comment on: http://stackoverflow.com/a/51789079
type: Comment
has text: @JacquelynneHeiman If this answered your question, you can click the grey checkmark under the voting buttons in the top left of this answer. If it turns into a green tick, that means that it's marked as the accepted answer. It gives me 15 reputation points if you do that.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51832254
type: Answer
accepted answer of: http://stackoverflow.com/q/51736172
downvote count: 0
has body: dask='allowed' means that you're applying a function that already knows how to handle dask arrays, e.g., a function written in terms of dask.array operations. In most cases, that does indeed mean that the function will operate on chunks one by one to lower memory usage, and will apply the computation in parallel. dask='parallelized' requires more information from the user because it creates its own wrapper that allows the provided function to act on dask arrays, by using low-level dask.array functions like atop. With dask='parallelized', you can provide a function that only knows how to handle NumPy arrays, and xarray.apply_ufunc will extend it to handle dask arrays, too.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/51736172
type: AcceptedAnswer

http://stackoverflow.com/q/51735127
type: UnansweredQuestion
tagged with: python
has body: LIBRARY create library pycryptodome language plpythonu from 's3://aws_python/library/pycryptodome/pycryptodome.zip' credentials 'aws_iam_role' region as 'aws-region'; FUNCTION CREATE OR REPLACE FUNCTION test.aes_encrypt(input varchar(max)) RETURNS varchar(max) STABLE AS ' if input is None: return None import pycryptodome encrypt=True secret_key = b''abcdefghijklmnop'' remainder = len(secret_key) % 16 modified_key = secret_key.ljust(len(secret_key) + (16 - remainder))[:32] remainder = len(input) % 16 modified_text = input.ljust(len(input) + (16 - remainder)) cipher = pycryptodome.AES.new(modified_key, pycryptodome.AES.MODE_ECB) return base64.b64encode(cipher.encrypt(modified_text)).strip() ' LANGUAGE plpythonu; I have tested this code in python and it worked correctly. Here function created successfully but when i use function test.aes_encrypt as select test.aes_encrypt('testing') then its throwing error: No module named Crypto.Cipher._mode_ecb. Please advise.
type: Question
has answer: http://stackoverflow.com/a/76160417
tagged with: user-defined-functions
has answer: http://stackoverflow.com/a/51735582
score: 0
answer count: 2
has title: Redshift UDF AES ENCRYPT - No module named Crypto.Cipher._mode_ecb
tagged with: amazon-redshift

http://stackoverflow.com/comment/90296054
type: QuestionComment
has text: That's what I said, I don't want to hard-code it.
comment on: http://stackoverflow.com/q/51665654
score: 0
type: Comment

http://stackoverflow.com/a/51748498
type: AcceptedAnswer
has body: This should work: First find the index of the rows where the values change, and then from the bottom insert theNaN. l = df.index[(df.key_value != df.key_value.shift(-1)) == True].tolist() a = [np.nan, np.nan, np.nan, np.nan] for i in reversed([x+1 for x in l]): for j in range(3): df = pd.DataFrame(np.insert(df.values, i, values=a, axis=0)) df.columns = ['key_value','a', 'date', 'b'] Output: key_value a date b 0 value_01 1 03/17/2018 10 1 value_01 2 03/18/2018 12 2 value_01 3 03/19/2018 13 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN 5 NaN NaN NaN NaN 6 value_02 1 04/01/2018 24 7 value_02 2 04/02/2018 27 8 value_02 3 04/03/2018 33 9 NaN NaN NaN NaN 10 NaN NaN NaN NaN 11 NaN NaN NaN NaN 12 value_03 1 03/17/2018 13 13 value_03 2 03/18/2018 17 14 value_03 3 03/19/2018 22 15 NaN NaN NaN NaN 16 NaN NaN NaN NaN 17 NaN NaN NaN NaN
has comment: http://stackoverflow.com/comment/90461917
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90457424
accepted answer of: http://stackoverflow.com/q/51748072
has comment: http://stackoverflow.com/comment/90459903
has comment: http://stackoverflow.com/comment/90457014
upvote count: 3
answers question: http://stackoverflow.com/q/51748072

http://stackoverflow.com/a/51761482
has body: Socket is not the problem here. But reading from the terminal in multi-processing is hazardous if you do not setup some synchronization. When multiple threads or processes write on the same stream, the worse possible behaviour is a strange mix of all the outputs. But when multiple threads of processes compete for reading on same input stream one (at random) will get some input and others will not even see it. The rule is one single reader per input stream.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51761269
downvote count: 0
score: 1

http://stackoverflow.com/a/51796330
score: 0
has body: OR: s = "I am not beautiful" news=''.join(i+' ' if i != 'not' else i for i in s.split()) print(news) Output: I am notbeautiful If you care about the space at the end do: print(news.rstrip())
answers question: http://stackoverflow.com/q/51796280
type: Answer

http://stackoverflow.com/a/51789079
has comment: http://stackoverflow.com/comment/90535583
upvote count: 4
has body: What do you expect this to do? The solution to your problem is to try to understand what the code does, instead of just throwing stuff together. (Don't worry; at least 80% of us were at that stage at one point!) As an aside, I strongly recommend using Python 3 instead of Python 2; they made a new version of Python because Python 2 was full of really strange, confusing stuff like input causing security vulnerabilities and 10 / 4 equalling 2. What do you want this to do? Repeatedly ask the user whether they are ready to begin until they answer "yes". Call start_adventure(). Ok. Let's put what we've got so far into a function: def begin(): while something: raw_input("Are you ready to begin? &gt; ") start_adventure() There are a lot of gaps in here, but it's a start. Currently, we're getting the user's input and throwing it away, because we're not storing it anywhere. Let's fix that. def begin(): while something: answer = raw_input("Are you ready to begin? &gt; ") start_adventure() This is starting to take shape. We only want to keep looping while answer != "yes"... def begin(): while answer != "yes": answer = raw_input("Are you ready to begin? &gt; ") start_adventure() Hooray! Let's see if this works! Traceback (most recent call last): File "example", line 2, in &lt;module&gt; while answer != "yes": NameError: name 'answer' is not defined Hmm... We haven't set a value for answer yet. In order to make the loop run, it has to be something that isn't equal to "yes". Let's go with "no": def begin(): answer = "no" while answer != "yes": answer = raw_input("Are you ready to begin? &gt; ") start_adventure() This will work!
has comment: http://stackoverflow.com/comment/90536394
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/51788857
has comment: http://stackoverflow.com/comment/90536603
type: Answer
has comment: http://stackoverflow.com/comment/90535539

http://stackoverflow.com/comment/92650960
type: Comment
comment on: http://stackoverflow.com/a/51740594
has text: Thanks amon; I didn't understand that, but from the link I just posted it got clear to me.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51769200
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90533696
tagged with: python
has answer: http://stackoverflow.com/a/51779559
score: 2
tagged with: conv-neural-network
tagged with: pytorch
tagged with: machine-learning
has title: Change dimensions of image when creating custom dataloader in pytorch
type: Question
tagged with: deep-learning
downvote count: 0
has body: I was training my CNN on the CIFAR10 dataset. I extracted the 50,000 images of dimensions (32 x 32 x 3) and read them in a list. I converted them into numpy arrays and stored them in a list. I did the same with the labels for my training and testing. I then constructed my CNN of two layers and a single FC in pytorch. Before doing this I created my own custom data loader. While doing so, the dimensions of the image that I am feeding in it are changing. The dimensions (32 x 32 x 3) are changing to (3 x 32 x 32) and I am not being able to train my neural network. tensor_x = torch.stack([torch.Tensor(i) for i in train_images]) tensor_y = torch.stack([torch.Tensor(i) for i in train_labels]) dataset = data_utils.TensorDataset(tensor_x , tensor_y) train_dataloader = data_utils.DataLoader(dataset=dataset) tensor_x = torch.stack([torch.Tensor(i) for i in test_images]) tensor_y = torch.stack([torch.Tensor(i) for i in test_labels]) dataset = data_utils.TensorDataset(tensor_x , tensor_y) test_dataloader = data_utils.DataLoader(dataset=dataset) RuntimeError: Given groups=1, weight[64, 3, 3, 3], so expected input[1, 32, 32, 3] to have 3 channels, but got 32 channels instead
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90504250
type: Comment
type: QuestionComment
has text: @vasia oh I just realized the key was that first string.
score: 0
comment on: http://stackoverflow.com/q/51772724

http://stackoverflow.com/q/51683553
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/51683621
answer count: 1
tagged with: nlp
favorite count: 0
linked to: http://stackoverflow.com/q/41170726
tagged with: spacy
has body: There is ONE word not being recognized as stopword, despite being on the list. I'm working with spacy 2.0.11, python 3.7, conda env, Debian 9.5 import spacy from spacy.lang.es.stop_words import STOP_WORDS nlp = spacy.load('es', disable=['tagger', 'parser', 'ner']) STOP_WORDS.add('y') Doing some tests: &gt;&gt;&gt; word = 'y' &gt;&gt;&gt; word in STOP_WORDS True &gt;&gt;&gt; nlp(word)[0].is_stop False &gt;&gt;&gt; len(STOP_WORDS) 305 &gt;&gt;&gt; [word for word in STOP_WORDS if not nlp(word)[0].is_stop] ['y'] So, from 305 listed in STOP_WORDS, one is not flagged as such. I don't know what I'm doing wrong... Maybe it's a bug?
has title: SpaCy custom stopwords not working properly
type: UnansweredQuestion
tagged with: python
tagged with: stop-words
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/40845304

http://stackoverflow.com/q/51714499
tagged with: python
has comment: http://stackoverflow.com/comment/90391081
has comment: http://stackoverflow.com/comment/90391719
has comment: http://stackoverflow.com/comment/90391627
has comment: http://stackoverflow.com/comment/90390550
linked to: http://stackoverflow.com/q/488366
has comment: http://stackoverflow.com/comment/90390664
has comment: http://stackoverflow.com/comment/90394577
upvote count: 1
linked to: http://stackoverflow.com/q/5971312
downvote count: 1
has comment: http://stackoverflow.com/comment/90390533
type: Question
linked to: http://stackoverflow.com/q/30006722
has answer: http://stackoverflow.com/a/51714821
has body: I've recently started coding in python. I am trying to create an environment variable and assign list to it using python. So when I try to read my environment variables through command line like printenv it will be listed there. This is my code in python: from API_CALLS import Post_Request as Request import os class VTM_Config: @staticmethod def validate_pool_nodes(url, headers, expected_num_of_active_nodes): try: print('\nNow Executing Validate VTM Configs...\n') # validate that vtm api works by sending a get_session_with_ssl call to the url vtm_get_session_response = Request.get_session_with_ssl(url=url, headers=headers) data = vtm_get_session_response active_nodes = [ n['node'] for n in data['properties']['basic']['nodes_table'] if n['state'] == 'active' ] actual_num_of_active_nodes = len(active_nodes) if expected_num_of_active_nodes != actual_num_of_active_nodes: print("Number of Active Nodes = {}".format(actual_num_of_active_nodes)) raise Exception("ERROR: You are expecting : {} nodes, but this pool contains {} nodes".format( expected_num_of_active_nodes, actual_num_of_active_nodes)) else: print("Number of Active Nodes = {}\n".format(actual_num_of_active_nodes)) print("Active servers : {}\n".format(active_nodes)) os.environ["ENABLED_POOL_NODES"] = active_nodes return os.environ["ENABLED_POOL_NODES"] except Exception as ex: raise ex I am trying to create an environment variable using os.environ["ENABLED_POOL_NODES"] = active_nodes and trying to return it. When I run this code, I am getting an error like this: raise TypeError ("str expected, not %s % type(value).name) TypeError: str expect, not list. Question: How do I assign list to an environment variable.
linked to: http://stackoverflow.com/q/4651437
has comment: http://stackoverflow.com/comment/90394701
has comment: http://stackoverflow.com/comment/90390490
has title: how to set env variables in python code
has answer: http://stackoverflow.com/a/51751939
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90390733
has comment: http://stackoverflow.com/comment/90390432
has comment: http://stackoverflow.com/comment/90411084
favorite count: 0
has comment: http://stackoverflow.com/comment/90392928
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90390467
has comment: http://stackoverflow.com/comment/90390471

http://stackoverflow.com/comment/90258486
comment on: http://stackoverflow.com/q/51646185
score: 0
type: Comment
type: QuestionComment
has text: > have a look at procedural noise textures and related topics. Could you please point to the related reference as a starting point?

http://stackoverflow.com/q/51773724
has answer: http://stackoverflow.com/a/56888984
favorite count: 0
type: Question
has title: Python list in double index How to split it ety.origin list
answer count: 2
tagged with: python
tagged with: indexing
tagged with: list
score: 0
upvote count: 1
has body: Hi Everyone I have python to find origin of a word so I got result in list's How I want it to separate or split it with comma (,). origin=ety.origins(wordtodo) print(origin) &gt;&gt;[Word(how, Middle English (1100-1500) [enm]), Word(haugr, Old Norse [non])] in the result I want text inside (...) braket's and store into different variable e.g. forigin=(how, Middle English (1100-1500) [enm]) and sorigin=(haugr, Old Norse [non])
downvote count: 1
tagged with: split
has answer: http://stackoverflow.com/a/51774259
type: UnansweredQuestion

http://stackoverflow.com/q/51689114
tagged with: dictionary
linked to: http://stackoverflow.com/q/43123408
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51689258
accepted answer: http://stackoverflow.com/a/51689258
upvote count: 1
type: Question
score: 1
tagged with: dataframe
answer count: 1
downvote count: 0
tagged with: data-structures
has title: Best way to get data from excel and sort it using Python 3.6
favorite count: 0
has body: I am in need of some major help as I am relatively new to Python. I need to perform a task which will read data from Excel, and then allow me to sort it out in descending order. I have initially started working to put into a dictionary as the Excel File has a header row, and then thousands of rows after which contain data. I know dictionaries are not "sortable" per se, but I thought a dictionary would be the best approach, given what I need. However, I'm wondering if maybe a dataframe would work, but need any and all guidance as I'm struggling to figure this out. I need to get the 3 largest commodities by share for each county, including the commodity name. For instance, for the first row, Lynd County, I want the following returned - Corn - 19.52, Cattle - 13.68, Strawberry - 12.31. It could also be like this Corn: 19.52, Cattle: 13.68, Strawberry: 12.31. However, I need to sort the data by the values for each commodity. I found the following code online and used it to read Excel Data into a list structure that consisted of dictionaries, but I'm not really sure if this is the best approach. import xlrd from xlrd import open_workbook book = open_workbook('DictionaryProject.xlsx') sheet = book.sheet_by_name('Sheet1') keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)] dict_list =[] for row_index in range(1, sheet.nrows): d= {keys[col_index]: sheet.cell(row_index, col_index).value for col_index in range(sheet.ncols)} dict_list.append(d) print(dict_list)
tagged with: python

http://stackoverflow.com/a/51667866
upvote count: 1
answers question: http://stackoverflow.com/q/51667829
score: 1
has comment: http://stackoverflow.com/comment/90299405
has comment: http://stackoverflow.com/comment/90298625
downvote count: 0
has comment: http://stackoverflow.com/comment/90298830
has body: I think the below three are the best: if s in ('one', 'two', 'three'): pass if s in ['one', 'two', 'three']: pass if s in {'one', 'two', 'three'}: pass But maybe still: if s in {'one', 'two', 'three'}: pass Is still the best Timing %timeit if 'one' in ('one', 'two', 'three'):pass Output: The slowest run took 21.60 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 63.4 ns per loop &amp; %timeit if 'one' in ['one', 'two', 'three']:pass Output: 10000000 loops, best of 3: 50.7 ns per loop &amp; %timeit if 'one' in {'one', 'two', 'three'}:pass Output: 10000000 loops, best of 3: 50.3 ns per loop At the end i prefer set({}) because it is the fastest and the tuple is the slowest it what i least prefer (in the tuple, list and set)
type: Answer

http://stackoverflow.com/comment/90553781
type: Comment
has text: The python doc page I referenced uses `@C.x.setter`, so I followed the example. I guess the doc is wrong then. Btw, while this removes the error, it doesn't force the subclass to implement the setter, which is the whole point of using the abstract methods in the first case. If I comment out the setter in `B` and its usage in `__main__`, the code runs without any error, but I want it to complain that the abstract setter was not implemented by `B`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51798390

http://stackoverflow.com/comment/90553791
has text: Thank you for your response. It helped me.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51788767

http://stackoverflow.com/q/51770248
tagged with: qstandarditemmodel
has comment: http://stackoverflow.com/comment/90500850
score: 0
has answer: http://stackoverflow.com/a/51771705
accepted answer: http://stackoverflow.com/a/51771705
tagged with: python
tagged with: qtableview
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90500788
type: Question
tagged with: pyside
has comment: http://stackoverflow.com/comment/90500817
has title: QTableview Select Item from filtered model
answer count: 1
has body: I have a QTableView which is using a QStandardItemModel. How can I select a specific row in the table with/without a search applied. For example I typed 'y' in the search bar to filter the list to only display rows that contain the letter 'y'. When I click the button 'Select Emily' how can i make it select the correct row in the tableview, considering users can change the sort order? import sys from PySide import QtCore, QtGui class Example(QtGui.QWidget): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.resize(400,400) # controls model = QtGui.QStandardItemModel(5, 3) model.setHorizontalHeaderLabels(['NAME', 'AGE', 'CAREER']) people = [ {'name': 'Kevin', 'age': 5, 'career': 'athlete'}, {'name': 'Maggie', 'age': 13, 'career': 'banker'}, {'name': 'Leslie', 'age': 32, 'career': 'banker'}, {'name': 'Abby', 'age': 32, 'career': 'marketing'}, {'name': 'Emily', 'age': 45, 'career': 'athlete'}, {'name': 'David', 'age': 27, 'career': 'banker'}, {'name': 'Johnny', 'age': 27, 'career': 'soccer'}, {'name': 'Marie', 'age': 63, 'career': 'secretary'} ] for row, obj in enumerate(people): item = QtGui.QStandardItem(obj['name']) model.setItem(row, 0, item) item = QtGui.QStandardItem(str(obj['age'])) model.setItem(row, 1, item) item = QtGui.QStandardItem(obj['career']) model.setItem(row, 2, item) proxy_model = QtGui.QSortFilterProxyModel() proxy_model.setSourceModel(model) # controls self.ui_table = QtGui.QTableView() self.ui_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.ui_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) self.ui_table.setModel(proxy_model) self.ui_table.setSortingEnabled(False) self.ui_table.setSortingEnabled(True) self.ui_table.sortByColumn(0, self.ui_table.horizontalHeader().sortIndicatorOrder()) self.ui_search = QtGui.QLineEdit() self.ui_selected = QtGui.QPushButton('Select Emily') # lay main lay_main = QtGui.QVBoxLay…

http://stackoverflow.com/a/51708446
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90378107
has body: Sorting with sorted method: import operator para = [] class Parameters(): def __init__(self): self.att1 = random.randint(5, 125) self.att2 = random.randint(5, 125) self.att3 = random.randint(30, 360) self.aa4 = random.randint(2, 24) self.score = random.randint(0, 100) for i in range(0, 19): para.append(Parameters()) # using lambda para_sorted = sorted(para, key=lambda x: x.score) # using attrgetter para_sorted2 = sorted(para, key=operator.attrgetter("score")) If you want to write your own sorting algorithm would look at: https://www.tutorialspoint.com/python/python_sorting_algorithms.htm
has comment: http://stackoverflow.com/comment/90378687
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51708044
answers question: http://stackoverflow.com/q/51708044

http://stackoverflow.com/comment/90292263
comment on: http://stackoverflow.com/q/51664240
score: 0
has text: @Amadan Ok, but only if the brace at the end of the string or with look-ahead.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90333587
score: 1
comment on: http://stackoverflow.com/q/51685765
has text: "I don't want to pass variable 'a' as an arugement."—why not? That's the right way to do this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51768081
type: Question
has answer: http://stackoverflow.com/a/67726016
answer count: 1
linked to: http://stackoverflow.com/q/39566809
score: 4
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
upvote count: 4
favorite count: 0
tagged with: python-3.x
tagged with: dask
downvote count: 0
has comment: http://stackoverflow.com/comment/90496716
type: UnansweredQuestion
has body: I can write a massive dask data frame to disk like so: raw_data.to_csv(r'C:\Bla\SubFolder\*.csv') This produces chunked data of the original (massaged) dataset in the subfolder: C:\Bla\SubFolder\ Just wondering, can I force dask to write the data as one file?
has comment: http://stackoverflow.com/comment/90499377
has title: write dask dataframe to one file

http://stackoverflow.com/comment/90372623
type: QuestionComment
comment on: http://stackoverflow.com/q/51705206
has text: I have added the model. Yes all of the classes have less than 100 images.
score: 0
type: Comment

http://stackoverflow.com/comment/90323808
has text: Another question, With this option, how would I write the variables within the word doc. Is it '%DOB%' as well? or is it something different. Thank you
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51666127

http://stackoverflow.com/q/51682818
has comment: http://stackoverflow.com/comment/91780357
has title: Dateparser date parsing strange issue
type: Question
has answer: http://stackoverflow.com/a/51683081
score: 0
has body: dateparser.parse("03 AUGUST 2018, 00:26 AM IST") Try parsing the above date with dateparser. I have been using dateparser from 3 months, I choose these module because it supports multi languge. But I have faced something strange today. It could parse anything but not this. I have changed the months, but no luck. Can anyone say, why is this? how to approach to solve the problem? It works only when I remove "AM/PM" from this kind of format.
answer count: 1
has comment: http://stackoverflow.com/comment/90346150
tagged with: date-parsing
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/138831108
type: AnswerComment
type: Comment
has text: just call it with `powerBySquaring(0, -1)` and this thing would cry bloody murder by the 3rd row
score: 0
comment on: http://stackoverflow.com/a/51686329

http://stackoverflow.com/q/51724748
has answer: http://stackoverflow.com/a/51724928
has comment: http://stackoverflow.com/comment/90409881
has comment: http://stackoverflow.com/comment/90410015
tagged with: python
has title: Pair each list element with unique combination of state
score: -1
has body: I'm trying to learn a bit of python 3 with something that i thought was trivial, but is actually winding me up a bit.. i have two lists.. items=['a','b','c'] states=[0, 1, -1] and i want to generate all unique combinations of state, that those items can have... so for this example it would start as.. 1, 1, 1 1, 1, 0 1, 1,-1 .. Note: The ordering matters, and 1, 0, 0, is not the same as 0, 1, 0 then, if we added another item, it would end up being.. 1, 1, 1, 1 1, 1, 1, 0 1, 1, 1,-1 .. i am getting a bit frustrated with syntax at the moment, and am not 100% sure what is possible, but have been trying to get this working with itertools.permutations, and also the concept of a 'generator' ?? So, i started off trying to get the permutations of the states.. itertools.permutations(states) [(0, 1, -1), (0, -1, 1), (1, 0, -1), (1, -1, 0), (-1, 0, 1), (-1, 1, 0)] and then join them up with the item list.. [(x,items) for x in itertools.permutations(states)] [((0, 1, -1), ['a', 'b', 'c']), ((0, -1, 1), ['a', 'b', 'c']), ((1, 0, -1), ['a', 'b', 'c']), ((1, -1, 0), ['a', 'b', 'c']), ((-1, 0, 1), ['a', 'b', 'c']), ((-1, 1, 0), ['a', 'b', 'c'])] but all this does is randomise the state list i currently have in a list.. i.e. i have no 1,1,1, or 0,0,0 Can anyone offer me some pointers.. i'm sure this must have been done before!
type: AnsweredQuestion
downvote count: 1
accepted answer: http://stackoverflow.com/a/51724928
type: Question
has comment: http://stackoverflow.com/comment/90409953
has comment: http://stackoverflow.com/comment/90410390
upvote count: 0
has comment: http://stackoverflow.com/comment/90409895
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51657496
score: 7
has comment: http://stackoverflow.com/comment/90301161
upvote count: 7
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51655597
downvote count: 0
answers question: http://stackoverflow.com/q/51655597
has body: Doesn't transform do that? &gt;&gt;&gt; from sklearn.feature_extraction.text import CountVectorizer &gt;&gt;&gt; from sklearn.decomposition import LatentDirichletAllocation &gt;&gt;&gt; from sklearn.datasets import fetch_20newsgroups &gt;&gt;&gt; &gt;&gt;&gt; n_samples = 2000 &gt;&gt;&gt; n_features = 1000 &gt;&gt;&gt; n_components = 10 &gt;&gt;&gt; &gt;&gt;&gt; dataset = fetch_20newsgroups(shuffle=True, random_state=1, ... remove=('headers', 'footers', 'quotes')) &gt;&gt;&gt; data_samples = dataset.data[:n_samples] &gt;&gt;&gt; &gt;&gt;&gt; tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, ... max_features=n_features, ... stop_words='english') &gt;&gt;&gt; tf = tf_vectorizer.fit_transform(data_samples) &gt;&gt;&gt; &gt;&gt;&gt; lda = LatentDirichletAllocation(n_components=n_components, max_iter=5, ... learning_method='online', ... learning_offset=50., ... random_state=0) &gt;&gt;&gt; &gt;&gt;&gt; lda.fit(tf) LatentDirichletAllocation(batch_size=128, doc_topic_prior=None, evaluate_every=-1, learning_decay=0.7, learning_method='online', learning_offset=50.0, max_doc_update_iter=100, max_iter=5, mean_change_tol=0.001, n_components=10, n_jobs=1, n_topics=None, perp_tol=0.1, random_state=0, topic_word_prior=None, total_samples=1000000.0, verbose=0) &gt;&gt;&gt; &gt;&gt;&gt; print(lda.transform(tf_vectorizer.transform(dataset.data[-3:]))) [[0.0142868 0.63695359 0.01428674 0.01428686 0.01428606 0.01429304 0.014286 0.24874298 0.01429136 0.01428656] [0.01111385 0.45234109 0.01111409 0.45875254 0.01111215 0.01111384 0.01111214 0.01111282 0.01111441 0.01111307] [0.001786 0.68840635 0.00178639 0.00178615 0.00178625 0.00178627 0.00178587 0.00178627 0.29730378 0.00178667]]

http://stackoverflow.com/comment/90724229
comment on: http://stackoverflow.com/a/51746074
has text: ok this means that your pip is working ok but I think pygame doesn't have a version for python 3.7 try using some other library that you know supports python 3.7 32 bit version such as numpy or cv2 let me know what happens cuz I have another way to install libraries using brute force on windows
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51757491
has comment: http://stackoverflow.com/comment/90475411
answers question: http://stackoverflow.com/q/51757402
has comment: http://stackoverflow.com/comment/90476756
has comment: http://stackoverflow.com/comment/90514140
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90549697
has comment: http://stackoverflow.com/comment/90491107
has body: I believe you meant to do the formatting only once import subprocess cmc_list='c:\cmc_list.txt' racadm_command_template = "racadm -r {} -u root -p calvin getslotname" with open(cmc_list,'r') as f: for ip in f: cmd = racadm_command_template.format(ip) output = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell=True).communicate() print(cmd, output[0]) I also suggest using getpass for your password prompt, or import from an environment variable. Additionally, don't print out the password and please change it from the default

http://stackoverflow.com/comment/90498370
has text: Unfortunately many people who come here don't even have basic python, and what seems obvious to a seasoned programmer will be like black magic to a newbie. Often people will just copy and paste an answer without understanding what's going on in the code, and they're the ones who will be back again with very similar questions because they didn't learn anything from the previous answer they used. The commented answer is excellent -- upvoted. :)
comment on: http://stackoverflow.com/a/51766098
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/tag/zip
tags question: http://stackoverflow.com/q/51755825
tags question: http://stackoverflow.com/q/51718917
tags question: http://stackoverflow.com/q/51784433
type: Tag
tags question: http://stackoverflow.com/q/51679881
tag name: zip
tags question: http://stackoverflow.com/q/51792923
tags question: http://stackoverflow.com/q/51695968

http://stackoverflow.com/q/51667809
has comment: http://stackoverflow.com/comment/90298743
upvote count: 1
tagged with: python
has body: I am trying to use the fixer.io API but I can't understand how to submit my access key! I have been trying with these code snippets: https://pypi.org/project/fixerio/ For example: from fixerio import Fixerio fxrio = Fixerio() fxrio.latest() but then I receive: 404 Client Error: Not Found for url: http://api.fixer.io/latest I have also tried the examples found here: http://fixerio.readthedocs.io/en/latest/ from fixerio import Fixerio fxrio = Fixerio(access_key='513eb....') fxrio.latest() but there is no kwarg "access_key". The only kwarg's are base, symbols and secure. Finally I have also tried editing my client.py(with no success) but I assume that is wrong. I am using version 0.1.1 Thankful for any support!
score: 1
has comment: http://stackoverflow.com/comment/90299202
type: Question
has title: Setting up Fixer.io, Python
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51702684
favorite count: 0
tagged with: fixer.io
type: UnansweredQuestion

http://stackoverflow.com/q/51718533
tagged with: python-3.x
has body: I have a file with every zip code in the US and its respective latitude and longitude. The file format is "ZIP/LAT/LNG\n" I am going to save each of those values to a database. So I wrote the following code to test if I could properly split the values: zip_code_file = open('zipcode.rtf') for s in zip_code_file.read().split(','): print(s) But this prints "00602" "18.361945" "-67.175597\" How can I remove that '\' from the longitude so I can properly save the number to my database? I tried the following, but it did not work: for s in zip_code_file.read(): if s == '\\': s.replace('\]', '') print(s)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51718564
has answer: http://stackoverflow.com/a/51720154
tagged with: python
has comment: http://stackoverflow.com/comment/90397928
has comment: http://stackoverflow.com/comment/90397914
type: Question
has title: Remove backslash character from string
score: 0
answer count: 2
tagged with: string

http://stackoverflow.com/q/51665110
type: Question
has answer: http://stackoverflow.com/a/51665212
has title: Adding zeroes to date for numbers less than 10
score: 0
has answer: http://stackoverflow.com/a/51665238
answer count: 3
has body: I am trying to add zeroes to a date if the day/month is less than 10. For example, if 2/12/200 is entered, convert it to 02/12/2000. userDate = input("What is the date? Please enter in MM/DD/YYYY format") newDate = '' newDate = userDate[3:5]+ "."+userDate[0:2]+"."+ userDate[6:] print (newDate)
favorite count: 0
has answer: http://stackoverflow.com/a/51665257
tagged with: python
linked to: http://stackoverflow.com/q/339007
duplicate of: http://stackoverflow.com/q/339007
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/51737108
has body: You can use the Bing web search api, if the list of blocked sites is small. You can use the -site:www.xyz.com as a query parameter. Here is the link to the API: https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/.
accepted answer of: http://stackoverflow.com/q/51735374
score: 0
answers question: http://stackoverflow.com/q/51735374
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90818833
type: AnswerComment
type: Comment
has text: @Maksim, try to uninstall Python completely and install the newest version. After create new virtual environments for your projects.
comment on: http://stackoverflow.com/a/51927483
score: 0

http://stackoverflow.com/q/51694887
type: Question
has body: I am using win32gui to move a Notepad window to the origin of the screen (0, 0) with width and height equal to 500. The result is that the window is not moved to the true left border but ~10 px. to the right. Also the width and height do not equal 500 px. (~620 px. instead). I am using the following code to produce my results. import win32gui from PIL import ImageGrab # Open notepad.exe manually. hwnd = win32gui.FindWindow(None, "Untitled - Notepad") win32gui.MoveWindow(hwnd, 0, 0, 500, 500, True) bbox = win32gui.GetWindowRect(hwnd) img = ImageGrab.grab(bbox) Here a screenshot of the overall position of the window on the screen: And here a picture of img:
has title: win32gui MoveWindow() not aligned with left edge of screen
upvote count: 11
tagged with: pywin32
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/90353688
type: AnsweredQuestion
tagged with: python-imaging-library
tagged with: win32gui
has answer: http://stackoverflow.com/a/51756022
accepted answer: http://stackoverflow.com/a/51756022

http://stackoverflow.com/q/51675105
answer count: 1
has answer: http://stackoverflow.com/a/51675997
tagged with: serialization
has comment: http://stackoverflow.com/comment/90313550
has comment: http://stackoverflow.com/comment/90315413
tagged with: python
has body: I am getting a json message/event with messed up types like: { "AdminCreateUserConfig": { "UnusedAccountValidityDays": "7", "AllowAdminCreateUserOnly": "true" } ... } I figured out that the best way is to serialize and deserialize using a custom serializer code: event = json.loads( json.dumps(event, mySerializer) ) def mySerializer(o): if isinstance(o, unicode): if o in ["true", "True"]: return True elif o in ["false", "False"]: return False else: try: return int(o) except: return o else: return o.__dict__ But my problem is that after the serialization and deserialization I still get the same strings/unicodes: AdminCreateUserConfig.UnusedAccountValidityDays: 7, type: &lt;type 'unicode'&gt; AdminCreateUserConfig.AllowAdminCreateUserOnly: true, type: &lt;type 'unicode'&gt; What should I change? TLDR: I am in AWS Lambda, and I have the json Object, this is why I need to do the conversion two more times.
has comment: http://stackoverflow.com/comment/90314192
type: AnsweredQuestion
has title: Python serialization issue
type: Question
accepted answer: http://stackoverflow.com/a/51675997
score: 0

http://stackoverflow.com/q/51651732
has comment: http://stackoverflow.com/comment/90266999
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51653074
has title: How to type like a human via Actionchains send_keys
tagged with: selenium
has comment: http://stackoverflow.com/comment/90273250
downvote count: 1
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/90266666
has comment: http://stackoverflow.com/comment/90267265
tagged with: sendkeys
has body: I know how to type slowly with the next code: elem = driver.find_element_by_id("mainCommentForm") text = "To type text here" for character in text: elem.send_keys(character) time.sleep(random.uniform(0.2,0.5)) Unfortunately, the website where I work with does not allow to type text via the normal send_keys option, as it gives an error message. It is like I select the element, then I want to send_keys but it cannot find the element as it is deselected or something. It has something to do with typing in Java. Please do not ask why this is not working as that is not my question.. Fact is, I need to use the Actionchains send_keys option as seen below. But how do I simulate typing as a human now, same as example above? By human typing I mean typing it in letter by letter instead of just copy/paste.. elem = driver.find_element_by_id("mainCommentForm") actions = ActionChains(driver) actions.move_to_element(elem) actions.click() actions.send_keys("This text must be typed in slower..") actions.perform()
possible better answer: http://stackoverflow.com/a/59472635
has answer: http://stackoverflow.com/a/59472635
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90267530
has answer: http://stackoverflow.com/a/51653074
tagged with: python
has comment: http://stackoverflow.com/comment/90266674
has comment: http://stackoverflow.com/comment/90270764

http://stackoverflow.com/q/51656874
has comment: http://stackoverflow.com/comment/90277505
score: 1
upvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90277708
has comment: http://stackoverflow.com/comment/90278036
tagged with: function
tagged with: pandas
has title: Function that determines if a value crosses above another value
answer count: 1
downvote count: 0
has body: I'm working with some data in a dataframe and I find myself writing code that includes this a lot: def entry_signal(y): conditions1 = [np.logical_and(y &gt; 0, y.shift(1) &lt; 0),np.logical_and(y &lt; 0, y.shift(1) &gt; 0)] values1 = ['LongEntry','ShortEntry'] return np.select(conditions1, values1, '') Essentially if the value crosses above 0 and the previous value is less than 0 than it should be true. I tried to create a function that did this but I keep getting an error: def cross_above(x,y): if np.logical_and(x&gt;y, x.shift(1)&lt;y): return True else: return False I then tried to use it here: def entry_signal(y): conditions1 = [cross_above((y,0), y.shift(1) &lt; 0),np.logical_and(y &lt; 0, y.shift(1) &gt; 0)] values1 = ['LongEntry','ShortEntry'] return np.select(conditions1, values1, '') But I keep getting an truth of value of a series is ambiguous. What am i doing wrong?
favorite count: 0
linked to: http://stackoverflow.com/q/36921951
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51657288
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90298243
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51659161
score: 0
has text: Ah yes I have tried this and get the same error... I have also tried running the cmd prompt as administrator, but neither work...

http://stackoverflow.com/a/51767838
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51767644
has body: You could try this using an inner join with merge: df1[['1','3']].merge(df2, left_on=['1','3'], right_on=['0','2'], suffixes=('_x',''))\ .drop(['1_x','3_x'], axis=1)
answers question: http://stackoverflow.com/q/51767644
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/51765827
upvote count: 0
has body: I have been trying to build a search form , to read isbn , author , year and title from the database that i have created locally using mysqldb. Even tho i pondered along several websites , trying out tutorials to make it happen , I cannot find an optimum way to do this. Right now What i have done is this. Python Code @app.route('/search_results/<query>', methods = ['GET','POST']) @is_logged_in def search_results(query): cur=mysql.connection.cursor() likeString = "'%%" + query + "%%'" result = cur.execute("SELECT * FROM books WHERE %s LIKE %s;", (query, likeString)) if result > 0: data = cur.fetchall() return render_template('search_results.html' , data = search) else: error = 'Nothing found' return render_template('dashboard.html' , error = error) return render_template('dashboard.html') @app.route('/dashboard') @is_logged_in def dashboard(): search = SearchForm(request.form) if request.method == 'POST': select = form.select.data search = form.search.data query = select + search return redirect((url_for('search_results', query = query))) return render_template('dashboard.html', form = search) and my html code as follows:- {% extends 'layout.html' %} {% block body %} Dashboard Welcome {{session.username}} {% from "includes/_formhelpers.html" import render_field %} {{ render_field(form.select) }} {{ render_field(form.search) }} {% for message in get_flashed_messages() %} {{ message }} {% endfor %} {% endblock %} Ive created a seperated search_results.html as well , which does not contain anything except a header H1 that displays search as follows {{search}}
score: -1
tagged with: flask
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/94251676
favorite count: 0
tagged with: flask-wtforms
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51765942
tagged with: python
has title: How to build a simple search form in flask using mysqldb
has answer: http://stackoverflow.com/a/51779969
tagged with: mysql
downvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/q/51762835
accepted answer: http://stackoverflow.com/a/51763444
upvote count: 8
type: Question
tagged with: ttk
has title: Remove header row in tkinter treeview
has answer: http://stackoverflow.com/a/51763444
answer count: 1
score: 8
favorite count: 0
has body: Can anyone tell me how to remove the header row in a tkinter Treeview? from tkinter import * from tkinter import ttk root = Tk() NewTree= ttk.Treeview(root) NewTree.pack() NewTree.heading("#0", text="How to remove this row?") NewTree.insert("", "0", 'item1',text='Item number 1') root.mainloop()
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: treeview

http://stackoverflow.com/comment/90530329
score: 1
comment on: http://stackoverflow.com/a/51780317
type: AnswerComment
has text: That seems like the right idea, but i got an error: stating "TypeError: 'NoneType' object is not subscriptable," remember that there are about 50 other script tags without any unique identifier on the site sometimes, so i think I need to find this unique one with the variable meta in it. Don't know if that's the problem, thanks
type: Comment

http://stackoverflow.com/q/51782761
tagged with: python
accepted answer: http://stackoverflow.com/a/51783539
has body: I'm pretty sure it's due to a circular import but I'm not too sure how to solve my issue in mysite/shifts/models.py from django.db import models class Shift(models.Model): # defines a shift` in mysite/shifts/scrapes.py from shifts.models import Shift I can share more code if you need but I believe the issue is here, I've added my apps to settings.py and I get this error when I run scrapes.py as a django-admin command from shifts.models import Shift ImportError: No module named 'shifts' project_structure
has comment: http://stackoverflow.com/comment/90522949
tagged with: django
has comment: http://stackoverflow.com/comment/90523307
type: AnsweredQuestion
has title: Django Import Error: cannot import name "Shift"
type: Question
has answer: http://stackoverflow.com/a/51783539
answer count: 2
possible better answer: http://stackoverflow.com/a/51783393
has answer: http://stackoverflow.com/a/51783393
has comment: http://stackoverflow.com/comment/90535030
score: 0

http://stackoverflow.com/comment/90341224
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51667854
type: Comment
has text: which version of etree/python are you using?

http://stackoverflow.com/comment/90297339
type: Comment
type: QuestionComment
score: 1
has text: use tuples instead of cramming both coords into a string.
comment on: http://stackoverflow.com/q/51667176

http://stackoverflow.com/comment/90431995
score: 1
has text: Use `df's1', 's2','s3', 's4','s5', 's6' = df['state'].apply(pd.Series)`.
comment on: http://stackoverflow.com/q/51735608
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51758698
has comment: http://stackoverflow.com/comment/90476940
downvote count: 0
has body: Here's a simple (but probably suboptimal) solution: people = [ [1, [2,3,4]], [2, [1,3,4]], [3, [1,2,4]], [4, [1,2,3]] ] meetings = set(tuple(sorted([meeter, meetee])) for meeter, meetees in people for meetee in meetees) current = [] schedule = [] busy = set() while meetings: for meeting in meetings: meeter, meetee = meeting if meeter in busy or meetee in busy: continue current.append(meeting) meetings.remove(meeting) busy.add(meeter) busy.add(meetee) break else: schedule.append(current) current = [] busy = set() if current: schedule.append(current) num_slots = len(schedule) personal_schedule = {meeter: [None] * num_slots for meeter, meetees in people} for slot_index, slot in enumerate(schedule): for meeting in slot: meeter, meetee = meeting personal_schedule[meeter][slot_index] = meetee personal_schedule[meetee][slot_index] = meeter personal_schedule = [list(items) for items in personal_schedule.items()] print(personal_schedule) First construct the list of all meetings. Then we try to stuff as many meetings in the current timeslot such that none of the people in that meeting are already busy in that timeslot. When we can't find such a meeting any more, we move onto the next timeslot. At the end, transform the meeting schedule into the personal schedule format as asked in OP.
type: Answer
answers question: http://stackoverflow.com/q/51758406
upvote count: 2
score: 2

http://stackoverflow.com/comment/119200669
comment on: http://stackoverflow.com/a/52735662
has text: THIS was my problem!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90360364
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51699211
has text: Let me know if I am understanding your example. It would appear that it is creating tuples of 3 up to, but not including, the number 15. It makes sense from a reverse engineering standpoint, but I guess I am not understanding why that specific syntax works that way. Why does multiplying by three at the end create groups?
score: 0

http://stackoverflow.com/comment/90508797
score: 0
has text: If you have Imagemagick installed is it version 7 or 6? If it is installed, then doing `convert -version` for IM 6 or `magick -version` for IM 7, should now tell you more about the delegates installed. Sorry I do not know Python.
type: Comment
comment on: http://stackoverflow.com/q/51752073
type: QuestionComment

http://stackoverflow.com/q/51737696
tagged with: javascript
favorite count: 0
has comment: http://stackoverflow.com/comment/90436070
answer count: 1
tagged with: python
has title: How to create API page using Python
upvote count: 0
tagged with: vuejs2
type: UnansweredQuestion
score: -4
has body: I'm a new to Vue js and Python. I have question here. I have to create a simple page using Vue.js and python for backend. I use Heidi sql. My team asked me to create an API page that I've never do it before, and yea I searched on Internet and found that API page is used to create JSON response, so that I can call it from Vue.js using axios So, i created file named api.py and in this file I made a code to connect with database and some query and it works fine when I run on my terminal. Ex: python api.py. My question is how do i create a json response from that so that the result will be in json and I can just axios.get('api.py') from my Vue js. Please explain details to me me as I'm a very very beginner for this. I show you my python file and example of vue js file that I will call the python file (api.py) api.py vue file
tagged with: http://stackoverflow.com/tag/json
type: Question
downvote count: 4
tagged with: vue.js
has answer: http://stackoverflow.com/a/51737936

http://stackoverflow.com/a/51648337
type: AcceptedAnswer
downvote count: 0
has body: You may use import re f="some test {Value1,Value2} more text {Value3} more text {Value4, Value1, Value5, Value9, Value11, Value21}" rec=re.sub(r"{([^{}]*)}", lambda x: "{{'{}'}}".format("', '".join(re.split(r'\s*,\s*', x.group(1)))) ,f) print(rec) # =&gt; some test {'Value1', 'Value2'} more text {'Value3'} more text {'Value4', 'Value1', 'Value5', 'Value9', 'Value11', 'Value21'} See the Python demo Notes: {([^{}]*)} - matches {, then captures 0+ chars other than { and } into Group 1, and then matches a }. re.sub passes the match data object to a lambda expression the Group 1 value is split with \s*,\s* - a comma enclosed with optional whitespaces (you may a string split operation if the spacing is consistent, something like x.group(1).split(',')) and then joined with ', '.
type: Answer
answers question: http://stackoverflow.com/q/51648244
accepted answer of: http://stackoverflow.com/q/51648244
upvote count: 3
score: 3

http://stackoverflow.com/a/51654320
has comment: http://stackoverflow.com/comment/90272199
has comment: http://stackoverflow.com/comment/90272469
type: Answer
has body: Try to use WebDriverWait: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "Password"))) Note: you have to add some imports: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By WebDriverWait will wait at least 10 seconds until element will be clickable and only then clicks on it. The whole code will be like this: inputuser = driver.find_element_by_id("userFake2") inputuser.send_keys('email@email.com') password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "Password"))) password.click() sleep(1); # make sure, that you really need this pause password.send_keys('password') EDIT: you can try also to use JavaScript: inputuser = driver.find_element_by_id("userFake2") inputuser.send_keys('email@email.com') password = driver.find_element_by_id("password") driver.execute_script("arguments[0].click();", password) sleep(1); # make sure, that you really need this pause password.send_keys('password')
score: 0
answers question: http://stackoverflow.com/q/51654287
has comment: http://stackoverflow.com/comment/90274457
has comment: http://stackoverflow.com/comment/90272249
has comment: http://stackoverflow.com/comment/90273403
has comment: http://stackoverflow.com/comment/90272913
has comment: http://stackoverflow.com/comment/90275354
has comment: http://stackoverflow.com/comment/90276198
has comment: http://stackoverflow.com/comment/90273032

http://stackoverflow.com/q/51755500
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90470825
downvote count: 5
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90470787
has title: String indeces must be integers not str
has answer: http://stackoverflow.com/a/51755554
favorite count: 0
has comment: http://stackoverflow.com/comment/90470772
has body: I have the following dictionary event = {'records': {'recordId': 1, 'data': 'logHere'}, {'recordId': 2, 'data': 'logHere2'}} I want to print the recordId using this loop for record in event['records']: print(record['recordId']) I get the String indeces must be integers not str error on print(record['recordId']) I understand why I'm getting this error, but I want to know how can I reformat my dictionary so the loop will print the recordId. I don't want to change the loop, I want to change the dictionary.
has comment: http://stackoverflow.com/comment/90470818
upvote count: 2
score: -3
accepted answer: http://stackoverflow.com/a/51755554
has comment: http://stackoverflow.com/comment/90470855
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90470836
possible better answer: http://stackoverflow.com/a/51755921
has answer: http://stackoverflow.com/a/51755921

http://stackoverflow.com/comment/98538901
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51690935
has text: @greybeard What kind of typing errors do you mean?
type: QuestionComment

http://stackoverflow.com/q/51758697
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90476699
tagged with: http://stackoverflow.com/tag/json
score: -1
type: Question
has body: I load a list from a windows INI file via simplejson. The list is read in as a string and I need to convert it back into an proper list so arr[0] = [30, 40, 80] and arr[1] = [90, 255, 255] config.ini: Advanced Settings tlhsv = "[30, 40, 80], [90, 255, 255]" Main.py tlhsv = self.config.get('Advanced Settings', 'tlhsv') print(tlhsv) u'"[30, 40, 80], [90, 255, 255]"' How on earth am I suppose to do this? Or even better is there a way I can format the INI file so its automatically read in correctly by simplejson. I have tried to format the ini differently but having a [], () or comma give a ValueError and explaining nothing. Reading it in as a string was all that worked.
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90492842
has answer: http://stackoverflow.com/a/51758771
favorite count: 0
tagged with: python-2.7
has title: Python2.7 json loaded text list back into an int list
has comment: http://stackoverflow.com/comment/90515058
tagged with: python
has comment: http://stackoverflow.com/comment/90476915
accepted answer: http://stackoverflow.com/a/51758771
downvote count: 1

anaconda
tags question: http://stackoverflow.com/q/51750396
tags question: http://stackoverflow.com/q/51779112
type: Tag
tags question: http://stackoverflow.com/q/51735862
tags question: http://stackoverflow.com/q/51797312
tags question: http://stackoverflow.com/q/51794528
tags question: http://stackoverflow.com/q/51683574
tags question: http://stackoverflow.com/q/51712693
tags question: http://stackoverflow.com/q/51691172
tags question: http://stackoverflow.com/q/51784198
tags question: http://stackoverflow.com/q/51719951
tags question: http://stackoverflow.com/q/51687757
tags question: http://stackoverflow.com/q/51736615
tags question: http://stackoverflow.com/q/51671910
tags question: http://stackoverflow.com/q/51765519
tags question: http://stackoverflow.com/q/51735140
tags question: http://stackoverflow.com/q/51710014
tags question: http://stackoverflow.com/q/51708784
tags question: http://stackoverflow.com/q/51778034
tags question: http://stackoverflow.com/q/51792167
tags question: http://stackoverflow.com/q/51695857
tags question: http://stackoverflow.com/q/51768403
tag name: anaconda
tags question: http://stackoverflow.com/q/51722339
tags question: http://stackoverflow.com/q/51664771
tags question: http://stackoverflow.com/q/51689035
tags question: http://stackoverflow.com/q/51670412
tags question: http://stackoverflow.com/q/51661037
tags question: http://stackoverflow.com/q/51732854
tags question: http://stackoverflow.com/q/51798050
tags question: http://stackoverflow.com/q/51753825
tags question: http://stackoverflow.com/q/51753988
tags question: http://stackoverflow.com/q/51727805

http://stackoverflow.com/comment/90434233
has text: @eyllanesc wow I forgot very simple thing.. thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51720725
type: QuestionComment

http://stackoverflow.com/q/51644378
has comment: http://stackoverflow.com/comment/90252844
tagged with: shell
has answer: http://stackoverflow.com/a/51644489
favorite count: 0
has title: Python: Extract matching word starts with number from a line using python
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51644429
has body: I want to read text file and find the words that starts with 5 in below text. "Status": "OK"}], "PhysicalLocationString": "rack1/chassis_u1/cpu0/pcie_slot3", "Physloc": "0003000101010005", "PlaceholderNetworkDeviceFunctions": [{"FC HBA 1": "51:40:2E:C0:01:C9:53:E8"}, {"FC HBA 2": "51:40:2E:C0:01:C9:53:EA"}]}}, "PartNumber": "P9D94A", "SerialNumber": "MY57470DS8", "Status": {"Health": "OK", "HealthRollup": "OK", "State": "Enabled"}} My output in another file should be 51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA here is my code : import re import sys import os #get line with open('/root/SDFlex/work/cookbooks/ilorest/files/OP.txt', 'r') as file: for line in file: re.findall(r'\b[s]:\w+', line) matchedLine = line break #and write it to the file with open('/root/SDFlex/work/cookbooks/ilorest/files/file.txt', 'w') as file: file.write(matchedLine) please help
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51644464
accepted answer: http://stackoverflow.com/a/51644489
upvote count: 2
possible better answer: http://stackoverflow.com/a/51644429
answer count: 3

http://stackoverflow.com/comment/90348224
score: 0
type: Comment
type: QuestionComment
has text: @JohnZwinck I edited my question by adding some data.
comment on: http://stackoverflow.com/q/51693383

http://stackoverflow.com/q/51795161
upvote count: 1
favorite count: 0
score: 0
downvote count: 1
tagged with: python
tagged with: bottle
has body: I am very new this so I would appreciate if someone could clarify this to me. I recently started tinkering with web apps and have a small web app that is written in python and cgi. I wanted to try bottle but i am hosting on shared server. If I SSH to my server i am able to start : python2.7 exi.py exi.py: from bottle import * @route('/login') def login(): return ' Oh no ' if __name__ == '__main__': run() this gives me : Bottle v0.13-dev server starting up (using WSGIRefServer())... Listening on http://127.0.0.1:8080/ Hit Ctrl-C to quit. but if i go to $mydomain$:8080/login it is connecting...but eventually i will get ERR_CONNECTION_TIMED_OUT is it even possible to run my own server on these services or am I beeing too naive? Thank you, Jakub
has answer: http://stackoverflow.com/a/51795171
has title: Running bottle server on shared webhosting
has answer: http://stackoverflow.com/a/51795231
accepted answer: http://stackoverflow.com/a/51795231
type: AnsweredQuestion
tagged with: web-hosting
possible better answer: http://stackoverflow.com/a/51795171
type: Question
answer count: 2

http://stackoverflow.com/a/60371514
has comment: http://stackoverflow.com/comment/131068830
answers question: http://stackoverflow.com/q/51712693
has comment: http://stackoverflow.com/comment/123619107
type: Answer
score: 3
upvote count: 3
has body: I met the same problem in my window1 10. pls change the env to base, because the package "conda" only can be updated in base. regards!
downvote count: 0

http://stackoverflow.com/comment/90493908
has text: What do '+' and '-' represent?
type: QuestionComment
comment on: http://stackoverflow.com/q/51766367
score: 0
type: Comment

http://stackoverflow.com/comment/90409953
has text: @RoryDaulton what is the correct terminology please? Combinations?!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51724748

plotly
tags question: http://stackoverflow.com/q/51731623
tags question: http://stackoverflow.com/q/51712718
type: Tag
tags question: http://stackoverflow.com/q/51662614
tags question: http://stackoverflow.com/q/51692672
tags question: http://stackoverflow.com/q/51641741
tag name: plotly
tags question: http://stackoverflow.com/q/51663834
tags question: http://stackoverflow.com/q/51712433
tags question: http://stackoverflow.com/q/51660998
tags question: http://stackoverflow.com/q/51691172
tags question: http://stackoverflow.com/q/51691287
tags question: http://stackoverflow.com/q/51748964
tags question: http://stackoverflow.com/q/51778301
tags question: http://stackoverflow.com/q/51725474
tags question: http://stackoverflow.com/q/51766989

http://stackoverflow.com/comment/90466226
comment on: http://stackoverflow.com/q/51753067
type: QuestionComment
type: Comment
has text: Ok, maybe you're right. I can't read Java for the life of me.
score: 0

matrix
tags question: http://stackoverflow.com/q/51711790
tag name: matrix
tags question: http://stackoverflow.com/q/51748939
tags question: http://stackoverflow.com/q/51728783
tags question: http://stackoverflow.com/q/51714914
tags question: http://stackoverflow.com/q/51744093
tags question: http://stackoverflow.com/q/51663236
tags question: http://stackoverflow.com/q/51755027
tags question: http://stackoverflow.com/q/51693837
tags question: http://stackoverflow.com/q/51726531
tags question: http://stackoverflow.com/q/51782321
tags question: http://stackoverflow.com/q/51778732
tags question: http://stackoverflow.com/q/51731187
tags question: http://stackoverflow.com/q/51794208
tags question: http://stackoverflow.com/q/51788625
tags question: http://stackoverflow.com/q/51734780
type: Tag

http://stackoverflow.com/a/51750581
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use the following list comprehension: l = [('3604', 0.7113370895385742), ('63', 0.6787939071655273), ('6566', 0.6688929796218872), ('6406', 0.6664271354675293), ('15', 0.6614164113998413)] print([(log[int(i)], n) for i, n in l])
accepted answer of: http://stackoverflow.com/q/51750512
answers question: http://stackoverflow.com/q/51750512

http://stackoverflow.com/q/51740012
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51740089
tagged with: pandas
has body: I want to create and add one column year-month as index. so how to do it ? my dataset is contain 168 raws. 23.59 26.931 24.740 25.806 24.364 24.477 23.901 . . i want dataset which is look like this: Year-Month product 1990-1 23.59 1990-2 26.931 1990-3 24.740 ... ... 1991-1 ... how to do this please help..
tagged with: python
favorite count: 0
has title: how to add column as year-month using pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51740089
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/51799274
type: Answer
answers question: http://stackoverflow.com/q/51714108
has body: Figured out a solution, For sending and receiving: reqSend1 = self.comm.isend(data, dest=((self.size+self.rank+1)%self.size), tag=self.rank) reqRecv2 = self.comm.irecv(source=((self.size+self.rank-1)%self.size), tag=self.rank-1) dataPrev = reqRecv2.wait() reqSend1.wait() And for Gather and scatter for python dictionaries, code logic is as follows: Gather function: if rank == 0: comm.Gather(data, root=0) Scatter function: if rank == 0: comm.Scatter(data, root=0)
score: 0

http://stackoverflow.com/q/51777546
tagged with: nltk
has title: How to See Python Error Messages for Scripts Running on Apache Server?
score: 1
has comment: http://stackoverflow.com/comment/90513432
type: Question
upvote count: 1
tagged with: apache
answer count: 1
has body: I have a server side Python script that imports a big package called nltk. It ran at a command prompt, but would not run in Apache server. I tried the logging and put it as the first import and created a log file immediately after. But nothing is written to the file before the script crashes. Is there a way to see the "ImportError: no module ..." when the script runs on Apache?
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90513307
has comment: http://stackoverflow.com/comment/129274174
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73199785
tagged with: server

http://stackoverflow.com/comment/90462523
comment on: http://stackoverflow.com/q/51751108
type: Comment
type: QuestionComment
has text: I've closed this as a dupe of a related "why don't these eigenvectors from different sources agree?" question because my answer would be exactly the same. There's no guarantee that two separately implemented functions will use the same normalization, and that's what's happened here.
score: 3

http://stackoverflow.com/q/51778413
upvote count: 9
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51778426
linked to: http://stackoverflow.com/q/56011
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51778441
downvote count: 0
type: Question
duplicate of: http://stackoverflow.com/q/56011
score: 9
has answer: http://stackoverflow.com/a/51778441
answer count: 2
accepted answer: http://stackoverflow.com/a/51778426
has body: I declare a python dictionary like this using double quotes; { "Name":"John", "Date":"2/18/1998", "Profit":25.12 } The same python dictionary can be written like this using single quotes; { 'Name':'John', 'Date':'2/18/1998', 'Profit':25.12 } What is the difference, if any, between the two? What is the best practice in python? Practical-wise, I encounter no difference so far. I'm not sure if I missed out anything.
has title: What is the difference, if any, between using single quote and double quote in a python dictionary?
has comment: http://stackoverflow.com/comment/90514881
favorite count: 0

http://stackoverflow.com/comment/90368960
type: QuestionComment
comment on: http://stackoverflow.com/q/51704027
score: 0
type: Comment
has text: @joaquin KeyError: 'Geolocation_correct'

http://stackoverflow.com/comment/90293241
comment on: http://stackoverflow.com/a/51664849
type: AnswerComment
score: 0
has text: Also i wanted to add that there is a documentation on how to do so: https://cloud.google.com/functions/docs/concepts/python-runtime Please do specify there that this isn't supported yet in the docs.
type: Comment

http://stackoverflow.com/a/51669320
has body: I suggest create new helper column for count id values by cumcount and then merge by this values: df1['g'] = df1.groupby('id').cumcount() df2['g'] = df2.groupby('id').cumcount() merged_table = pd.merge(df1,df2,on=["id", 'g'],how='outer') print (merged_table) Name amount_x id g Category amount_y 0 John 500.25 GH10 0 Food 500.25 1 Helen 1250.00 GH11 0 Travel 1250.00 2 Adam 432.54 GH11 1 Food 432.54 3 Sarah 567.12 GH12 0 NaN NaN And last remove id: merged_table = pd.merge(df1,df2,on=["id", 'g'],how='outer').drop('g', axis=1) print (merged_table) Name amount_x id Category amount_y 0 John 500.25 GH10 Food 500.25 1 Helen 1250.00 GH11 Travel 1250.00 2 Adam 432.54 GH11 Food 432.54 3 Sarah 567.12 GH12 NaN NaN Detail: print (df1) Name amount id g 0 John 500.25 GH10 0 1 Helen 1250.00 GH11 0 2 Adam 432.54 GH11 1 3 Sarah 567.12 GH12 0 print (df2) Category amount id g 0 Food 500.25 GH10 0 1 Travel 1250.00 GH11 0 2 Food 432.54 GH11 1
has comment: http://stackoverflow.com/comment/90303329
answers question: http://stackoverflow.com/q/51669232
accepted answer of: http://stackoverflow.com/q/51669232
upvote count: 14
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90303007
has comment: http://stackoverflow.com/comment/90302951
score: 14
downvote count: 0

http://stackoverflow.com/a/54582701
has comment: http://stackoverflow.com/comment/107111814
has comment: http://stackoverflow.com/comment/100233254
has comment: http://stackoverflow.com/comment/96110182
upvote count: 38
answers question: http://stackoverflow.com/q/51646558
downvote count: 0
has comment: http://stackoverflow.com/comment/100232990
has comment: http://stackoverflow.com/comment/115677769
has comment: http://stackoverflow.com/comment/103130998
has comment: http://stackoverflow.com/comment/96102054
has body: The SSLError occurs because system OpenSSL library version (the one linked to your Python upon compilation) was below 1.0.1 the day when Python has been installed or your current Python version is below 2.7.9 / 3.4, because neither of these really support TLS 1.2 protocol version which the Python Package Index (PyPI) now requires from pip to connect. Distributions usually cannot easily upgrade old openssl and system Python without undergoing a full OS upgrade, which is not always desirable. You could compile your own 'non-system' OpenSSL from recent sources and then try to compile a standalone 'non-system' Python linking it against the OpenSSL you have just compiled, but sometimes this approach is also unfeasible due to various limitations. Solution Popular recommendations, such as to pip install requests[secure] or urllib3[secure], often cannot help fix pip because pip itself is affected and won't be able to connect to PyPI to install anything. We cannot ask pip to connect to PyPI to fix pip's inability to connect to PyPI. :) To fix it without upgrading Python, we need to install relevant packages manually, resolving dependencies: PyOpenSSL and cryptography (its manylinux1 wheel ships newer openssl library); their dependencies: asn1crypto, cffi, enum34, idna, ipaddress, pycparser, six; any pip 10+ version, because older pip versions did not really use cryptography - only the standard library's ssl module (you don't require a new pip version if yours is already 10 or above, any pip v10+ will do) Tested on ancient Ubuntu with old non-working pip and outdated system openssl version. Step 1 - Download Download the following packages from Python Packing Index (pypi.org) via your web browser of choice -- choose recent manylinux1 wheels (.whl) for your OS/platform: pip, asn1crypto, enum34, idna, six, ipaddress, pyOpenSSL, cffi, cryptography wheels; and also pycparser (a non-wheel, it will be a tar.gz) cp27- stands for Python 2.7, cp36- for Python 3.6; mu- type manylinux w…
has comment: http://stackoverflow.com/comment/100248363
type: Answer
score: 38
has comment: http://stackoverflow.com/comment/96098320

http://stackoverflow.com/comment/90423767
has text: Please provide the full code you are using as I still don't understand what you need.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51730997
type: Comment

http://stackoverflow.com/comment/90467637
has text: Users in here will *help* you, but will not write the whole thing for you. Add your code and what is wrong with it, we can help after. See [ask] and [mcve]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51753750
score: 3

http://stackoverflow.com/comment/90342270
type: QuestionComment
type: Comment
has text: Your first function can (and probably should) be rewritten as `return random.choice(["run","kayak"])`. Same with the second function.
score: 0
comment on: http://stackoverflow.com/q/51690184

http://stackoverflow.com/a/51740038
has comment: http://stackoverflow.com/comment/90440707
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51739940
has body: If you want to tweak the regex you linked to work in a string like that, change the three ^ and $s to word boundaries (\b) instead: \b(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))\b|\b(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})\b https://regex101.com/r/WX5Itv/1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90292421
score: 0
type: Comment
type: QuestionComment
has text: My suspicion is that you’re on Windows, where there is no `fork`, so the default start method is `"spawn"`. What this does is launch a whole new Python interpreter and import your module—which means top-level code like that `ids = []` and `ids.extend(…)` gets run in the child process (but code protected by that `__main__` guard does not get run), so you end up with an equal list, but it’s not actually copied from the parent, it’s just created the same way.
comment on: http://stackoverflow.com/q/51664487

http://stackoverflow.com/q/51750501
answer count: 1
downvote count: 1
tagged with: qt
score: 0
tagged with: background-image
upvote count: 1
tagged with: stylesheet
has body: run file code: from PyQt5 import QtCore, QtGui, QtWidgets import subprocess, re, shlex, json, test_fon_cod, os, sys, random, threading, time, glob, math, help, http.client, urllib.request, urllib.parse, urllib.error class Ui_Frame(QtWidgets.QMainWindow, test_fon_cod.Ui_test_fon): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.setupUi(self) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) window = Ui_Frame() window.show() sys.exit(app.exec_()) Running a file obtained by converting from a "ui" file via pyuic5.bat: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_test_fon(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(541, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(18, 21, 190, 154)) self.widget.setStyleSheet("border-image: url(E:\image\fon.png);") self.widget.setObjectName("widget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 541, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) He tried to load the picture differently, not how it does not work out. At start, there is nothing to swear at, but also does not load
tagged with: pyqt
type: UnansweredQuestion
has title: Do not insert a background picture into widget.setStyleSheet
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51751103
tagged with: python

http://stackoverflow.com/comment/90441672
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51740700
score: 1
has text: Python doesn't use two's complement in its integers, `0b10001111111 == 2303`.

http://stackoverflow.com/q/51783664
tagged with: python
has body: pytest does not capture print() statements (stdout output) which are located in pytest_sessionfinish() or code which is called in there. What's best practice to get same or similar behavior like print() statements located in tests, fixtures, etc.? # conftest.py def pytest_sessionfinish(session, exitstatus): print('This wont be captured (like in tests) but output independent of pytest exit status (exitstatus).') if exitstatus == 0: print('stdout shall be captured/suppressed in case of overall test PASS.') else: print('stdout shall be output in case of overall test FAIL and any other error.')
linked to: http://stackoverflow.com/q/51711988
tagged with: pytest
upvote count: 3
linked to: http://stackoverflow.com/q/13250050
has title: How to capture print statements in pytest_sessionfinish()?
has comment: http://stackoverflow.com/comment/90526098
has comment: http://stackoverflow.com/comment/90532261
answer count: 0
type: UnansweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90525628
downvote count: 0
has comment: http://stackoverflow.com/comment/90532699
has comment: http://stackoverflow.com/comment/90526154
favorite count: 0
type: Question

http://stackoverflow.com/q/51794693
has answer: http://stackoverflow.com/a/51794755
tagged with: string
favorite count: 0
score: -1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51794755
downvote count: 2
upvote count: 1
type: Question
has title: Find unique substring of String s with given length
has comment: http://stackoverflow.com/comment/90547047
has body: I am trying to solve this question. For example, the string equals "caaab" and the length K=2, the return substrings should be "aa","ab","ca" in an alphabetic order. I prefer the solution in python
answer count: 1

http://stackoverflow.com/comment/90535830
type: Comment
comment on: http://stackoverflow.com/a/51789051
has text: Sorry. Missed that line. Adding an edit to my answer.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51707233
has comment: http://stackoverflow.com/comment/90375789
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90376528
score: 1
has comment: http://stackoverflow.com/comment/90378027
accepted answer of: http://stackoverflow.com/q/51704619
answers question: http://stackoverflow.com/q/51704619
upvote count: 1
has comment: http://stackoverflow.com/comment/90375524
has body: From what I can tell pd.DataFrame(responsedata.json())['results'].to_dict() gives you {0: (first data set), 1: (second data set)}, while responsedata.json()['results'] gives you a list of [(first data set), (second data set)]. In order to turn the list into a dictionary like the first, use sample_object = {i: data for i, data in enumerate(responsedata2)} enumerate is a generator that takes an iterable such as ['a', 'b', 'c', ...] and returns tuples (0, 'a'), (1, 'b'), etc.

http://stackoverflow.com/q/51780235
has comment: http://stackoverflow.com/comment/90518066
favorite count: 0
duplicate of: http://stackoverflow.com/q/1009860
has comment: http://stackoverflow.com/comment/90518199
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90518088
tagged with: python
has title: How to pass python command line argument?
has comment: http://stackoverflow.com/comment/90518087
downvote count: 1
tagged with: command-line-arguments
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51780342
answer count: 1
linked to: http://stackoverflow.com/q/1009860
has body: I am a python beginner. Trying to pass some command line arguments. I have used the following codes. But getting errors... transaction_file = argv[1] IndexError: list index out of range. import itertools import re from sys import argv print ('Computing frequent item sets.') transaction_file = argv[1] parameter_file = argv[2] output_file = argv[3] Any help is greatly appreciated. Thanks......

dll
tags question: http://stackoverflow.com/q/51760616
type: Tag
tags question: http://stackoverflow.com/q/51657542
tags question: http://stackoverflow.com/q/51667821
tag name: dll

http://stackoverflow.com/comment/90454975
comment on: http://stackoverflow.com/q/51746303
score: 0
type: QuestionComment
type: Comment
has text: I wasn't able to find this on stackoverflow using keywords in title. The linked answer explains filtering, not how to convert dictionary items to list, specifically.

http://stackoverflow.com/comment/90558252
type: Comment
has text: I can reproduce the issue in a fresh Ubuntu container, let me try it out.
type: QuestionComment
comment on: http://stackoverflow.com/q/51756910
score: 0

http://stackoverflow.com/q/51716606
answer count: 1
has body: im starting to learn PyQt5 and Qthread and im trying to do a simple QThread implementation, i know it's obvious but i can't really get why it dosen't work my code : from PyQt5 import QtCore class WorkingThread(QtCore.QThread): def __init__(self): super().__init__() def run(self): print(" work !") class MainWindow(QtCore.QObject): worker_thread = WorkingThread() def engage(self): print("calling start") self.worker_thread.start() if __name__ == "__main__": main = MainWindow() main.engage() the output: calling start Process finished with exit code 0 no "work !" printed
has title: PyQt5.QThread's start() méthod don't execute the run() méthod
type: AnsweredQuestion
tagged with: pyqt
has answer: http://stackoverflow.com/a/51717293
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51717293
type: Question
tagged with: python
tagged with: qthread
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/comment/90547803
has text: I guess I figured it out why it wasnt defined, because I havent defined it. However when I tried defined it with logg=pd.read_csv('data_log.log') then it said TypeError: initial_value must be str or None, not DataFrame. How can I solve it?
comment on: http://stackoverflow.com/a/51794717
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90476317
score: 2
has text: As per standard Python behavior, the 3 arguments are evaluated (in full) before being passed to the `where` function. Consider using the `where` parameter of the `np.log10` `ufunc` instead.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51758332

http://stackoverflow.com/q/51715879
has comment: http://stackoverflow.com/comment/90393251
tagged with: tkinter
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90393322
tagged with: pyautogui
has body: I am working on the learning project similar to TeamViewer but very simple. I am establishing a connection between two PCs with socket. In each PS I am opening two threads: one thread couple is for receiving the image of the screen from one PC and displaying on the other with tkinter, the other thread couple is for sending keyboard and mouse commands from one PC to the other for performing the commands. However, I am facing a problem that my tkinter is not opening from thread. Here is my code for one PC: from socket import * import _thread as thread import tkinter, pickle class TeamVieverServer: port = 50004 host = '' def __init__(self): conn = self.connector() self.dispacher(conn) def connector(self, port=port, host=host): sock = socket(AF_INET,SOCK_STREAM) sock.bind((host, port)) sock.listen(5) conn, addr = sock.accept() data = conn.recv(1024) print(b'Received data from the client is [%s]' % data) conn.send(b'Prion') return conn def dispacher(self, conn): thread.start_new_thread(self.recv_thread,(conn,)) thread.start_new_thread(self.send_thread,(conn,)) def send_thread(self, conn): pass def recv_thread(self, conn): screen_size = conn.recv(1024) width, height = pickle.loads(screen_size) root = tkinter.Tk() tkinter.Frame(root, width=width, height=height).pack() root.mainloop() if __name__ == '__main__': TeamVieverServer() In here I am receiving some info from the other PS to open corresponding tkinter window. Here is my code for other PC: from socket import * import _thread as thread import tkinter, pickle import pyautogui class TeamVieverClient: port = 50004 host = '***************' def __init__(self): conn = self.connector() self.dispacher(conn) def connector(self, port=port, host=host): sock = socket(AF_INET,SOCK_STREAM) sock.connect((host, port)) sock.send(b'Connection is estalished') data = sock.recv(1024) print('Server:[%s]' % data) return sock def dispacher(self, conn): thread.start_new_thread(self.recv_thread,(conn,)) thread.start_new_thread(self.send_thread…
has title: Tkinter window is not opening from thread, using data from the socket connection
score: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python

http://stackoverflow.com/q/51716616
has comment: http://stackoverflow.com/comment/90394602
answer count: 2
tagged with: finance
has comment: http://stackoverflow.com/comment/90394465
possible better answer: http://stackoverflow.com/a/51716766
has comment: http://stackoverflow.com/comment/90410058
favorite count: 0
has answer: http://stackoverflow.com/a/51716675
accepted answer: http://stackoverflow.com/a/51716675
upvote count: 2
tagged with: python
has title: Function to calculate months required to save for house deposit
score: 2
type: AnsweredQuestion
has body: Full disclosure this is for an assignment, but I am having some discrepancy between my outputs and the assignment given test cases. The function takes your annual salary, portion of your salary you'll save per month as a percentage, and the cost of the house. It's assumed I will need 25% of the total cost of the house. A percentage of my salary goes to my savings each month, I also earn 4% interest per month on my savings. def house_hunting(annual_salary, portion_saved, total_cost): portion_down_payment = 0.25 * total_cost current_savings = 0 r = 0.04 months = 0 while current_savings &lt; portion_down_payment: current_savings += (annual_salary * portion_saved) / 12 current_savings += current_savings * r / 12 months += 1 return months print( house_hunting(120000,0.1,1000000) ) print( house_hunting(80000,0.15,500000) ) The first call gives me 182 months, when the test case says 183. The second call gives me 105 months, which is correct according to the test case. So my math is wrong somewhere; can anyone see where I'm going wrong?
tagged with: math
has comment: http://stackoverflow.com/comment/90394712
has answer: http://stackoverflow.com/a/51716766
has comment: http://stackoverflow.com/comment/90394652
has comment: http://stackoverflow.com/comment/90429574
type: Question
tagged with: function
downvote count: 0

http://stackoverflow.com/comment/90312463
comment on: http://stackoverflow.com/q/51674730
score: 0
type: Comment
type: QuestionComment
has text: Have you checked the [documentation](https://docs.python.org/3/library/csv.html#csv.reader) for the `csv` package? The `csv.reader` will help you achieve what you want and there is an example included as well.

http://stackoverflow.com/q/51733668
tagged with: pyqt
has answer: http://stackoverflow.com/a/51786631
has comment: http://stackoverflow.com/comment/90428510
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90433694
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I am making a Python GUI using PyQt5 and its editor. Trying to put some colors to the thing I played around with styleSheet. But I encountered a different result when using it in a QMainQindow(left side of the image and a QDialog(right side [desired look]). It is like it creates the same effect to every other widget. [![enter image description here][1]][1] Code from the QMainWindow MainWindow <widget class="QWidget" name="centralwidget"> QWidget{ background-color:qlineargradient(spread:repeat, x1:0, y1:1, x2:1, y2:0, stop:0 rgba(39, 21, 103, 255), stop:1 rgba(94, 94, 140, 255)) } QPushButton{ background-color: qlineargradient(spread:pad, x1:0.915, y1:0.227273, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(56, 56, 140, 255)); font: 75 8.5pt "Sitka Small"; } QToolButton{background-color: qlineargradient(spread:pad, x1:0.915, y1:0.227273, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(56, 56, 140, 255)); font: 75 8.5pt "Sitka Small"; } QLabel{ color: rgb(255, 255, 255); } font: 75 8.5pt "Sitka Small" Code from QDialog Dialog QDialog{ background-color:qlineargradient(spread:repeat, x1:0, y1:1, x2:1, y2:0, stop:0 rgba(39, 21, 103, 255), stop:1 rgba(94, 94, 140, 255)) } QPushButton{ background-color: qlineargradient(spread:pad, x1:0.915, y1:0.227273, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(56, 56, 140, 255)); font: 75 8.5pt "Sitka Small"; } QToolButton{background-color: qlineargradient(spread:pad, x1:0.915, y1:0.227273, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(56, 56, 140, 255)); font: 75 8.5pt "Sitka Small"; } QLabel{ color: rgb(255, 255, 255); } font: 75 8.5pt "Sitka Small" How can I have the look of the QDialog on the right at the QMainWindow?
tagged with: qtstylesheets
tagged with: pyqt5
type: Question
has title: PyQt5 styleSheet different results

http://stackoverflow.com/q/51798276
upvote count: 3
score: 1
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/51798389
answer count: 2
has answer: http://stackoverflow.com/a/51799057
has title: Checking input in a one line for loop, python
possible better answer: http://stackoverflow.com/a/51798389
favorite count: 0
tagged with: python-3.x
has body: lines = [input("Enter the number") for i in range(0,100)] I want to break the loop if user enter 7 or any higher number. Assume the loop to be infinite. Looking for a way to check the input while the user enters it. I am looking for one line code. o/p: 1 4 5 2 3 4 2 4 5 6 5 7
has comment: http://stackoverflow.com/comment/90554524
downvote count: 2
tagged with: input
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51799057

http://stackoverflow.com/q/51721119
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/51721514
linked to: http://stackoverflow.com/q/51737769
has comment: http://stackoverflow.com/comment/90402865
has answer: http://stackoverflow.com/a/51721514
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90402736
has title: python web scraping tab pane
has body: hey i am trying to extract some information for a webstie the information is like the players age, height and weight the information is in a table below is the link to the website http://www.ultimatetennisstatistics.com/playerProfile?playerId=4742 the source page looks like this the information i am trying to extract is in the <div id="profile" class="tab-pane fade" however when i inspect the page it looks different for what is in the source page Age 32 (03-06-1986) Country Spain Birthplace Manacor, Mallorca, Spain Residence Manacor, Mallorca, Spain Height 185 cm Weight 85 kg Plays Left-handed Backhand Two-handed Favorite Surface Clay Coach Carlos Moya Turned Pro 2001 Seasons 17 Active Yes Prize Money US$100,564,598 3rd all-time leader in earnings that is what shows up when i inspect the page but it is not in the source page can someone help me figure out how i can extract the information in the table here is my code so far import urllib import urllib.request from bs4 import BeautifulSoup url = "http://www.ultimatetennisstatistics.com/playerProfile?playerId=4742" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, 'html.parser') link = soup.find('body', attrs={'class': 'container'}) mk = link.find('div', attrs={'class':'tab-content'}) print(mk) new = mk.find('div' , {'class': 'tab-pane fade'}) print(new) and it outputs
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/51670299
tagged with: sqlalchemy
type: Question
upvote count: 2
tagged with: flask
favorite count: 0
has title: sqlalchemy model instance with contains_eager submited as arg to ThreadPoolExecutor
score: 2
answer count: 0
downvote count: 0
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
has body: I have two models as follows class User(db.Model, CreatedAtMixin, ModifiedAtMixin): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) class Balance(db.Model, ModifiedAtMixin): __tablename__ = "billing_balance" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship("User", backref=backref("balance", uselist=False)) I need to select some Balances with joined load of User to them (to minimize number of db queries) and process each balance asynchronously in non-blocking way. Here's how i did it: def pmap(fn, iterable, max_workers=20): def _ensure_arg_is_iterable(arg): if type(arg) in (list, tuple): return arg return (arg,) futures = [] pool = ThreadPoolExecutor(max_workers=max_workers) for params in iterable: futures.append(pool.submit(fn, *_ensure_arg_is_iterable(params))) return futures def some_func(balance): print(balance.user) def main(): balances = db.session.query(Balance).outerjoin( User, Balance.user_id == User.id ).filter( # conditions ).options( contains_eager(Balance.user) ) ready_to_process = [] for balance in balances: some_irrelevant_method(balance) # print(balance.user) ready_to_process.append(balance) pmap(some_func, ready_to_process) Problem is that balance.user is None in some_func(balance) as print statement shows, unless I explicitly call balance.user in main(). Consequently, I can't call any method or get any attribute of balance.user in some_func without getting an AttributeError. Any suggestions on how to solve this problem or hits about why it goes that way would be appreciated.

http://stackoverflow.com/comment/90473423
type: Comment
type: QuestionComment
score: 0
has text: Thanks. I tried that, now getting different error. Please see edit above. Should I do something like this maybe,and what path do I use? https://askubuntu.com/questions/175514/how-to-set-java-home-for-java
comment on: http://stackoverflow.com/q/51756910

http://stackoverflow.com/comment/90553517
has text: the second one is Python, which I want to convert to C++ and the third one is Swift. Do you know of any suitable links for contours in C++?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51798006

http://stackoverflow.com/comment/90339820
type: AnswerComment
has text: @jpp thanks man ! I like your solution too :) retributed the favor !
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51688918

http://stackoverflow.com/comment/90540774
has text: your urls.py missing a parenthesis in `as_view()` (>> `ContactFormView.as_view`) ....Is that a typo?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51791632
score: 1

http://stackoverflow.com/a/51706262
accepted answer of: http://stackoverflow.com/q/51685660
answers question: http://stackoverflow.com/q/51685660
downvote count: 0
type: AcceptedAnswer
has body: The key point is that in Python 2.x, the str type is (sometimes!) a series of bytes and so not interpreted any further unless you explicitly ask it to be so. In Python 3.x, the str type is interpreted, and as UTF-8 I believe as standard. Therefore you want, on Python 3.x, to use the byte type. The natural way to do this is to encode the string to a series of bytes: fromstring( data.encode('raw_unicode_escape'), dtype='int32' ) As others mention, String to Bytes Python without change in encoding &amp; Python: Convert Raw String to Bytes String without adding escape chraracters you need to be careful but in this case I understand it is just transformed binary data so we do not expect any Unicode characters outside of the range raw_unicode_escape will successfully de/encode. So it is okay.
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/90346576
has text: I would guess the `func` itself might be important for us to know how to help.If it worked and now does no longer, you should also check your data. If thats some kind of webscrapy things, chances are, the websites no longer as it was or scrapeprotected.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51692526
type: QuestionComment

http://stackoverflow.com/a/51718057
has comment: http://stackoverflow.com/comment/90397824
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90397562
answers question: http://stackoverflow.com/q/51717984
type: Answer
accepted answer of: http://stackoverflow.com/q/51717984
upvote count: 6
has comment: http://stackoverflow.com/comment/90397780
score: 6
has comment: http://stackoverflow.com/comment/90397672
has comment: http://stackoverflow.com/comment/90397708
has comment: http://stackoverflow.com/comment/90397620
has body: Essentially, you want a difference operation on a multi-set, i.e. a bag. Python implements this for the collections.Counter object: Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less. So, for example: &gt;&gt;&gt; list1 = ["25","+","7","*","6","/","7"] &gt;&gt;&gt; list2 = ["7","*","6"] &gt;&gt;&gt; list((Counter(list1) - Counter(list2)).elements()) ['25', '+', '7', '/'] In Python 3.6+ this will be ordered (although this is not currently guaranteed, and should probably be considered an implementation detail). If order is important, and you are not using this version, you may have to implement an ordered counter. Indeed, the docs themselves provide just such a recipe: &gt;&gt;&gt; from collections import Counter, OrderedDict &gt;&gt;&gt; class OrderedCounter(Counter, OrderedDict): ... 'Counter that remembers the order elements are first encountered' ... def __repr__(self): ... return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) ... def __reduce__(self): ... return self.__class__, (OrderedDict(self),) ... &gt;&gt;&gt; list((OrderedCounter(list1) - OrderedCounter(list2)).elements()) ['25', '+', '/', '7']

http://stackoverflow.com/comment/90379852
type: Comment
comment on: http://stackoverflow.com/a/51709057
score: 0
type: AnswerComment
has text: not sure that solves your problem, but everytime you use the function you 'reset' `U` and `U1` and return `U`, which is zeros only

http://stackoverflow.com/comment/90346497
type: QuestionComment
comment on: http://stackoverflow.com/q/51691563
score: 14
has text: This is an error with your target labels: `t >= 0 && t < n_classes`. print your labels and make sure that they are positive and smaller than the number of outputs of your last layer.
type: Comment

http://stackoverflow.com/comment/90461367
type: AnswerComment
comment on: http://stackoverflow.com/a/51750075
type: Comment
has text: I'm not sure if this delves off topic but there is missing data so if we do nlargest out to 10 I get a blank answer in the top 10. If I changed the the .name to .value, I get the true top 10. Is there a way to print out the name along with the code?
score: 0

http://stackoverflow.com/comment/90445799
has text: I edited the question by adding a sample of the data.
type: Comment
comment on: http://stackoverflow.com/q/51741605
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90375645
has text: What datatype are your Tables? Can you show us the code for them? The code you have written here does not run, and I do not know how even a single process is able to complete this as the tables are not defined anywhere In general, you have to feed the table(s) you want to update to your processes as they do not implicitly share memory. Also the tables need to be a thread/process safe data structure
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51707288

http://stackoverflow.com/a/51758309
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90802627
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/90475989
answers question: http://stackoverflow.com/q/51758237
accepted answer of: http://stackoverflow.com/q/51758237
type: Answer
has body: Create a module with the common code and import it into the notebooks that need it. Jupyter can export a Python notebook as a Python module. File &gt; Download as &gt; Python (.py). Put that file on your kernel's path and then you can import it. With a Python kernel, you can see your path with import sys sys.path If you put the module in any of those directories, you can import it. You can also append a new path string, either using sys.path.append(...) (just for that session) or by updating the relevant environment variable in your operating system (usually PYTHONPATH). It is possible to import an .ipynb, but it's not as straightforward as converting it first. IPython cells can use extended syntax like the %-magics etc. IPython includes all the tools necessary to load an .ipynb file programmatically (See nbformat.read() and IPython.core.interactiveshell.InteractiveShell), then it's just a matter of using the standard library import hooks. That's a little too involved to reproduce here, but the Jupyter documentation explains how to do it. Is there a way to import only certain cells from another notebook? I can't seem to find it. Yes, it should be be possible to import individual cells, though beware that a cell may not work right if it assumes a cell that you did not import has already run. The relevant snippet from the linked docs is for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) Notice how this just runs each code-type cell in turn using a loop. You could run a particular cell (or cells) here instead of all of them. Then the imported module would have only run that code. The tricky part might be identifying the cell you want. The obvious approach is to count, but you could also mark the cell somehow, e.g. in the loop, only run a cell if the cell.source starts with a certain comment or something.
upvote count: 4
has comment: http://stackoverflow.com/comment/90476087

http://stackoverflow.com/comment/90355597
comment on: http://stackoverflow.com/q/51697061
type: Comment
type: QuestionComment
has text: Be careful about the order in which you do things. If you have five files numbered from 1 through 5, for example, and your offset is 3, then if you start from the lowest number (1), you'll overwrite files 4 and 5 by renaming them, and end up with copies at the tail. Start at the tail and work backwards.
score: 0

http://stackoverflow.com/a/51713383
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use any sort algorithm you want, as long as you implement it right. But the problem is calling out for a radix sort. In particular, the dumbest kind of radix sort, a bucket-counter. You have N=10,000,000 total values and a range of M=100 distinct values. A bucket counter will take O(N+M) time, which is better than O(N*log N), and O(M) space,1 which is negligible—and. best of all, it's dead simple: def bucketsorted100(xs): buckets = [0] * 101 for x in xs: buckets[x] += 1 for x, count in enumerate(buckets): yield from [x] * count You can obviously extend this to not be hardcoded for numbers from 1-100 (actually, I hardcoded it for numbers from 0-100, wasting 1% space, but who cares?). Or you can add support for a key function. Or you can make it even simpler by using a Counter instead of a list. 1. Technically, it's O(logN * M) space, because the counts range up to N, which takes logN bits, which the values only range up to 100, which takes a constant number of bits. But practically, all of the counts fit into a single 30-bit "digit" in CPython, so the logN factor never comes up.
has comment: http://stackoverflow.com/comment/90389644
upvote count: 2
answers question: http://stackoverflow.com/q/51712020
accepted answer of: http://stackoverflow.com/q/51712020
has comment: http://stackoverflow.com/comment/90389489

http://stackoverflow.com/comment/90480432
type: Comment
comment on: http://stackoverflow.com/a/51760270
score: 0
type: AnswerComment
has text: @Allan: Errors in pure python code should never cause a segmentation fault. That kind of error only happens if you either have a broken python installation or in poorly written third party libraries that uses C extensions.

http://stackoverflow.com/comment/90447358
type: Comment
has text: That's what the preview pane is for ;)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51742148

reindex
tag name: reindex
type: Tag
tags question: http://stackoverflow.com/q/51790793

http://stackoverflow.com/q/51666604
tagged with: mouseevent
linked to: http://stackoverflow.com/q/22052532
has title: how can I grab all the points plotted on the curve if I click on the curve in python matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/90296707
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/129698755
type: Question
linked to: http://stackoverflow.com/q/45222774
has body: I have worked with the mouse events where, if I click on the particular point on the scatter plot, I get the coordinates of that particular point. Is the same possible to grab the points on that particular curve if I click on that curve using matplotlib events? This is the code I use to get the mouse coordinates: import matplotlib.pyplot as plt def onclick(event): print(event.xdata, event.ydata) fig,ax = plt.subplots() ax.plot(range(10)) fig.canvas.mpl_connect('button_press_event', onclick) plt.show()
has comment: http://stackoverflow.com/comment/90302579

http://stackoverflow.com/a/51677593
type: Answer
answers question: http://stackoverflow.com/q/51677024
score: 0
has body: I think one of the most straightforward solutions here is to implement like to_dict and get_csv_fields methods for myInvoice class and then write each object into csv with built-in csv.DictWriter. Of course, if you're on Python 3.6 and higher, data classes are much more elegant way to do it, but the idea remains the same. class myInvoice(object): number = "" date = "" close_date = "" amount = "" def __init__(self, number, date, close_date, amount, formatted_records_list = None): self.number = number self.date = date self.close_date = close_date self.amount = amount if formatted_records_list is None: self.formatted_records_list = [] else: self.formatted_records_list = formatted_records_list @staticmethod def get_csv_fields(): return ['number', 'date', 'close_date', 'amount', 'formatted_records_list'] def to_dict(self): return {el: getattr(self, el) for el in self.get_csv_fields()} Then you can write the objects to csv like following: import csv ... imvoices = [] # list of myInvoice instances with open('names.csv', 'w', newline='') as csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=myInvoice.get_csv_fields()) writer.writeheader() for invoice in invoices: writer.writerow(invoice.to_dict())

http://stackoverflow.com/q/51749143
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51749579
favorite count: 0
has body: Here is my data: Identification Req RCFD1797 Violet BHCKK085 Green RCFD1797 Green BHCKK085 Orange RCFD1797 Blue BHCKK085 Yellow BHCKK085 Red WRSS1797 Green WRSS1797 Violet WRSS1797 Blue RCON1797 Violet RCON1797 Green RCON1797 Blue RCON1797 Indigo BHDM1797 Violet BHDM1797 Green BHDM1797 Blue BHDM1797 Indigo The first column is filled with duplicate ID numbers. So for example, "RCFD1797" shows up three times with one requirement on each row. This is what I need it to look like: Identification Req_1 Req_2 Req_3 Req_4 RCFD1797 Violet Green Blue BHCKK085 Green Orange Yellow Red WRSS1797 Green Violet Blue RCON1797 Violet Green Blue Indigo BHDM1797 Violet Green Blue Indigo I have no problem importing my Excel file using Pandas, but I have no idea how to define my dataframe to yield the second table above. Any ideas? Thanks!
tagged with: python
has title: Move a column with duplicate values into a single row Pandas
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51749474
possible better answer: http://stackoverflow.com/a/51749579
type: Question
has answer: http://stackoverflow.com/a/51749474
upvote count: 2

http://stackoverflow.com/q/51766387
type: UnansweredQuestion
tagged with: python
has title: Does python releases the memory used in the code when the terminal/IDLE is closed?
downvote count: 0
score: 1
has body: When a python session/terminal is closed or killed forcefully does the memory occupied by lists other data structures in the code released automatically (I mean the garbage collection)?
type: Question
has answer: http://stackoverflow.com/a/51767124
has comment: http://stackoverflow.com/comment/90491399
has answer: http://stackoverflow.com/a/51766477
answer count: 2
upvote count: 1
favorite count: 0
tagged with: memory-management

http://stackoverflow.com/a/51662386
has comment: http://stackoverflow.com/comment/90288551
upvote count: 2
answers question: http://stackoverflow.com/q/51662270
has comment: http://stackoverflow.com/comment/90288349
has body: Use the flag delim_whitespace my_data = pd.read_csv('filename', delim_whitespace=True)
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90444089
score: 1
comment on: http://stackoverflow.com/q/51740396
has text: You can try to get the pids and use the wait command. See this answer to underrstand what I mean: https://unix.stackexchange.com/questions/340077/how-do-i-wait-for-a-background-process-to-complete#340086
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90336612
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51687305
has text: May I suggest that you use pandas instead of CSV reader? That would save you 50% of your code... Please include the first several lines of your CSV file into the question.

http://stackoverflow.com/comment/90372852
has text: @joaquin responsedata Is a {Response} <Response [200]> object it gives: https://textuploader.com/dz3u0 sample_object is a dictionary as: https://textuploader.com/dz3uj This conversion is done by my code successfuly. responsedata2 is https://textuploader.com/dz3ux
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51704619
score: 0

http://stackoverflow.com/a/52123000
type: Answer
has body: Something like the following works for what I was trying to do. # Find Target 7 years after Each Training Sample indicesOfTrainSamples=trainSamples.index indicesOfTarget=indicesOfTrainSamples + pd.Timedelta(weeks=7*52) targets=[] for i in indicesOfTarget: targets.append(toLearn.loc[i]) targetSlices=pd.DataFrame(targets,index=indicesOfTarget) targetFeature=targetSlices['targetValues']
accepted answer of: http://stackoverflow.com/q/51689738
answers question: http://stackoverflow.com/q/51689738
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/90346176
type: Comment
comment on: http://stackoverflow.com/a/51692306
has text: You could sort `fruits.items()` like so: `sorted(fruits.items(), key=lambda x: x[1], reverse=True)`
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90326544
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51681499
has text: This code seems pointlessly overcomplicated. Why loop over `for digit in bitStr(1, s)` when, as the book directly explains, this is always going to be `s`? It’s also pretty misleading to refer to the list of generated strings as “the final string”. Maybe this just isn’t a very good book, and that’s why you’re struggling to follow it? (Or maybe it’s a good book in general, but the author was having an off day when writing this example and its explanation?)

http://stackoverflow.com/comment/90516940
comment on: http://stackoverflow.com/a/51779552
type: AnswerComment
has text: I wrote this code but my code prints something else: `def main(): def add_numbers(x, y): return x + y print(add_numbers) if __name__ == '__main__': main()` I got this: `<function main.<locals>.add_numbers at 0x7f21d39f40d0>`
score: 0
type: Comment

http://stackoverflow.com/comment/90374728
type: QuestionComment
comment on: http://stackoverflow.com/q/51706390
type: Comment
has text: For now, it doesn't ; it just stores the data, that will be used later on. Having the name stored as a string would be completely fine I guess
score: 0

http://stackoverflow.com/comment/90521001
comment on: http://stackoverflow.com/a/51781478
type: AnswerComment
score: 0
type: Comment
has text: is it possible to make it in csv file? I would like to learn as well to understand how it works

http://stackoverflow.com/a/51743905
type: Answer
accepted answer of: http://stackoverflow.com/q/51743483
score: 0
answers question: http://stackoverflow.com/q/51743483
type: AcceptedAnswer
has body: Really a small error. When you do plt.savefig, matplotlib looks for the last called figure. Replace the plt.savefig('plot_'+str(i)+'_'+str(j)+'.png') with fig.savefig('plot_'+str(i)+'_'+str(j)+'.png'). And replace plt.savefig('multiPlots.png') by figComb.savefig('multiPlots.png').

http://stackoverflow.com/q/51784170
type: Question
has answer: http://stackoverflow.com/a/51785746
tagged with: python
has title: How to avoid sdl2.SDL_Event().window.windowID from always returning value 2?
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51785746
has body: Issue: I wrote the following test code to illustrate my issue. Whenever there is a sdl2 window event, sdl2.SDL_Event().window.windowID always returned a value of 2, which means the window is hidden and this is incorrect. The value 2 is also returned when the mouse pointer moves in and out of the window, when the window is moved, resized, minimized, maximized, ...... Question: How do I get it to work correctly? Test code: #!/bin/env python3.5 ''' test sdl2 event.window.windowID values ''' # Python3 modules import ctypes # PyPI module import sdl2 class Window (object): '''Create SDL2 WINDOW.''' def __init__(self, title='SDL2 Window', width=400, height=400): self.title = title self.width = width self.height = height self.window = None # SDL2 Window Object self.event =sdl2.SDL_Event() # SDL2 Event object if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: err = 'sdl2.SDL_Init failed: {}'.format(sdl2.SDL_GetError()) print(err) flags = sdl2.SDL_WINDOW_RESIZABLE self.window = sdl2.SDL_CreateWindow(self.title.encode('utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, ctypes.c_int(self.width), ctypes.c_int(self.height), ctypes.c_uint32(flags)) def end(self): '''Method to destroy SDL2 window and clean up SDL2''' sdl2.SDL_DestroyWindow(self.window) #Close and destroy SDL2 window. sdl2.SDL_Quit() #Clean up SDL2 print('Ended Window') def mainloop(): running = True print('sdl2.SDL_WINDOWEVENT ', sdl2.SDL_WINDOWEVENT) print('sdl2.SDL_WINDOWEVENT_SHOWN ', sdl2.SDL_WINDOWEVENT_SHOWN) print('sdl2.SDL_WINDOWEVENT_HIDDEN ', sdl2.SDL_WINDOWEVENT_HIDDEN) print('sdl2.SDL_WINDOWEVENT_EXPOSED ', sdl2.SDL_WINDOWEVENT_EXPOSED) print('sdl2.SDL_WINDOWEVENT_MOVED ', sdl2.SDL_WINDOWEVENT_MOVED) print('sdl2.SDL_WINDOWEVENT_RESIZED ', sdl2.SDL_WINDOWEVENT_RESIZED) print('sdl2.SDL_WINDOWEVENT_SIZE_CHANGED ', sdl2.SDL_WINDOWEVENT_SIZE_CHANGED) print('sdl2.SDL_WINDOWEVENT_MINIMIZED ', sdl2.SDL_WINDOWEVENT_MINIMIZED) print('sdl2.SDL_WINDOWEVENT_MAXIMIZED ', sdl2.SDL_WINDOWEVENT_MAXIMIZED) pri…
tagged with: pysdl2
tagged with: sdl-2
type: AnsweredQuestion
tagged with: events

http://stackoverflow.com/q/51786324
has answer: http://stackoverflow.com/a/51786577
has comment: http://stackoverflow.com/comment/90534274
has comment: http://stackoverflow.com/comment/90536891
has answer: http://stackoverflow.com/a/51786517
favorite count: 0
tagged with: binary
has answer: http://stackoverflow.com/a/51787245
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: numbers
linked to: http://stackoverflow.com/q/27936699
has body: For example &gt;&gt;&gt; two_powers(42) &gt;&gt;&gt; (2, 8, 32) My current naive implementation (taken from here) looks like that def two_powers(num): return tuple(2 ** i for i, j in enumerate(bin(num)[-1: 1: -1]) if j == '1') But I hope there're faster ways to do this.
has title: What is the fastest way to represent number as the sum of powers of two in python
has comment: http://stackoverflow.com/comment/90555233
has answer: http://stackoverflow.com/a/51786440
has answer: http://stackoverflow.com/a/51859187
has answer: http://stackoverflow.com/a/51786751
linked to: http://stackoverflow.com/q/30226094
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/51786889
has answer: http://stackoverflow.com/a/51786397
downvote count: 0

http://stackoverflow.com/comment/90508011
type: AnswerComment
type: Comment
has text: Yes, I've seen that quite often too. In that case it seems to be more of an error prevention mechanism, no? If you misspell key1, it'll end up in the kwargs.
comment on: http://stackoverflow.com/a/51774228
score: 0

http://stackoverflow.com/q/51717874
tagged with: pytorch
tagged with: machine-learning
type: Question
score: 4
has title: Why is it in Pytorch when I make a COPY of a network's weight it would be automatically updated after back-propagation?
accepted answer: http://stackoverflow.com/a/51722020
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51722020
has body: I wrote the following code as a test because in my original network I use a ModuleDict and depends on what index I feed it would slice and train only parts of that network. I wanted to make sure that only the sliced layers would update their weight so I wrote some test code to double check. Well I am getting some weird results. Say if my model has 2 layers, layer1 is an FC and layer 2 is Conv2d, if I slice the network and ONLY use layer2 I would expect layer1's weight to be unchanged because they are unused and layer2's weight will get updated after 1 epoch. So my plan was to used a for loop to grab all the weights from the network Before training then I would do it AFTER 1 optimizer.step(). Both times I would store those weights completely separate in 2 Python lists so I can compare their results later. Well for some reason the two lists are completely the same if I compare them with torch.equal() I thought its because maybe there is still some sort of hidden link in memory? So I tried to use .detach() on the weights when I grab them from the loop and the result is still the same. Layer2's weight should be different in this case because it should contain weights from the network before training. Noted in the code below I am actually using layer1 and ignoring layer2. Full code: class mymodel(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Linear(10, 5) self.layer2 = nn.Conv2d(1, 5, 4, 2, 1) self.act = nn.Sigmoid() def forward(self, x): x = self.layer1(x) #only layer1 and act are used layer 2 is ignored so only layer1 and act's weight should be updated x = self.act(x) return x model = mymodel() weights = [] for param in model.parameters(): # loop the weights in the model before updating and store them print(param.size()) weights.append(param) critertion = nn.BCELoss() #criterion and optimizer setup optimizer = optim.Adam(model.parameters(), lr = 0.001) foo = torch.randn(3, 10) #fake input target = torch.randn(3, 5) #fake target result = model(foo)…
tagged with: backpropagation

http://stackoverflow.com/comment/90411089
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51710290
has text: Yes, you can have, you need to install pygame in all environments, say you have two Venv in which you need pygame or any other package, you have to install it on both Venv. Installing in one virtual environment won't let you acess that package in another Venv, that's what I meant.

http://stackoverflow.com/comment/112354135
comment on: http://stackoverflow.com/a/51674892
has text: @MartijnPieters this doesn't appear to work for nested objects - is there a nifty generic way to achieve this and have it work for any object? e.g. I have an Author object that has a Publications property which is an array of publication objects... anybody?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90485888
score: 2
comment on: http://stackoverflow.com/q/51763570
has text: what error? show the full traceback
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51764143
tagged with: python
score: -2
downvote count: 2
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51764314
answer count: 2
has title: Splitting an array in python using numpy library
upvote count: 0
has comment: http://stackoverflow.com/comment/90486992
has body: I am a beginner in python and I want to know the purpose of [3,5] in np.split(x, [3, 5]) x = [1, 2, 3, 99, 99, 3, 2, 1] x1, x2, x3 = np.split(x, [3, 5]) print(x1, x2, x3) Output: [1 2 3] [99 99] [3 2 1]
favorite count: 0
has answer: http://stackoverflow.com/a/51764323
type: UnansweredQuestion

http://stackoverflow.com/q/51692823
has answer: http://stackoverflow.com/a/51693002
has answer: http://stackoverflow.com/a/51692983
has comment: http://stackoverflow.com/comment/90347222
has comment: http://stackoverflow.com/comment/90347295
upvote count: 1
has body: I have two lists where each element is a tuple that should be interpreted as x = [(x1_begin, x1_end), (x2_begin, x2_end), ... , (xn_begin, xn_end)] y = [(y1_begin, y1_end), (y2_begin, y2_end), ... , (yn_begin, yn_end)] In one figure, I would like to plot all these points and draw lines only between (yi_begin, yi_end) vs (xi_begin, xi_end) for all i. The following code manages to plot all the points. But I'm not sure how to draw the lines properly between the points. Any help is much appreciated. import matplotlib.pyplot as plt x = [(1, 27), (32, 55), (56, 80), (84, 103)] y = [(5, 7), (3, 6), (4, 9), (6, 11)] fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x, y, color='black') plt.show()
has comment: http://stackoverflow.com/comment/90347275
linked to: http://stackoverflow.com/q/35363444
has title: How to plot two lists of tuples with Matplotlib
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90347194
possible better answer: http://stackoverflow.com/a/51692983
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90347303
has comment: http://stackoverflow.com/comment/90347432
downvote count: 0
accepted answer: http://stackoverflow.com/a/51693002
score: 1
tagged with: matplotlib
type: Question
answer count: 2

http://stackoverflow.com/comment/90366927
type: QuestionComment
comment on: http://stackoverflow.com/q/51701986
has text: Hi, the sleep in the example is just to simulate if processing the data takes longer than the creation rate. If there's no way to know how much data is available, how can I analyze if processing will keep up in realtime? Thanks!
score: 0
type: Comment

http://stackoverflow.com/a/51668989
has body: You just add a check before printing: result = detecteur_FR(message) if result is not None: print(result)
accepted answer of: http://stackoverflow.com/q/51668931
score: 5
answers question: http://stackoverflow.com/q/51668931
has comment: http://stackoverflow.com/comment/90300883
upvote count: 5
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90528896
has text: @Paulo - Yes , used text plugin ( added under source tab )
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51739682

http://stackoverflow.com/a/51729498
has comment: http://stackoverflow.com/comment/90420376
answers question: http://stackoverflow.com/q/51728957
has comment: http://stackoverflow.com/comment/123177686
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51728957
type: Answer
downvote count: 0
has body: A solution using imshow from Matplotlib: import numpy as np import matplotlib.pyplot as plt %matplotlib inline palette = [(82, 129, 169), (218, 223, 224), (147, 172, 193), (168, 197, 215), (117, 170, 212)] palette = np.array(palette)[np.newaxis, :, :] plt.imshow(palette) plt.axis('off') plt.show() gives:
score: 6
has comment: http://stackoverflow.com/comment/90419913
has comment: http://stackoverflow.com/comment/90420179
upvote count: 6

http://stackoverflow.com/q/51730539
has answer: http://stackoverflow.com/a/51730648
has body: I know the issue around setting the value of a slice of a df has been addressed thoroughly here. However, as far as I can tell, I'm assigning the value correctly to not trigger the warning - what is going on here? Is it just the use of the original value + 1 that is causing the warning? df.iloc[df_row_idx]['n_sites_recruiting'] = df.iloc[df_row_idx]['n_sites'] + 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90421819
possible better answer: http://stackoverflow.com/a/51731143
score: 0
answer count: 2
has title: Pandas dataframe value set with a copy warning despite assignment with .iloc
tagged with: pandas
has comment: http://stackoverflow.com/comment/90423256
tagged with: python
has answer: http://stackoverflow.com/a/51731143
accepted answer: http://stackoverflow.com/a/51730648
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/90493971
type: Comment
type: QuestionComment
score: 2
has text: When you update your `FirstName` variable the entry is still empty, you should get the content after the user has inserted its name, otherwise it's empty.
comment on: http://stackoverflow.com/q/51767164

http://stackoverflow.com/q/51701051
has title: error install mysqlclient with pip, library not found for -lssl
tagged with: mysql
type: Question
upvote count: 4
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90363747
has comment: http://stackoverflow.com/comment/90363429
has body: I am running mysql@8.x version on my MacOS, I have installed mysql and mysql-connector-o with brew. Currently brew link with mysql. Running Django project on my python3 virtual env I am receiving following error - django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? and on installing the mysqlclient using pip, I am reciving following error clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 -I/usr/local/Cellar/mysql/8.0.12/include/mysql -I/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c _mysql.c -o build/temp.macosx-10.13-x86_64-3.6/_mysql.o clang -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk build/temp.macosx-10.13-x86_64-3.6/_mysql.o -L/usr/local/Cellar/mysql/8.0.12/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.13-x86_64-3.6/_mysql.cpython-36m-darwin.so ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'clang' failed with exit status 1 ---------------------------------------- Command "/Volumes/Samsung_T5/Work/python/repos/venv3/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-kf2fkhtc/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-qwpjjw3e/install-record.txt --single-versi…
possible better answer: http://stackoverflow.com/a/55296514
has answer: http://stackoverflow.com/a/55296514
has comment: http://stackoverflow.com/comment/90363463
has answer: http://stackoverflow.com/a/51701291
favorite count: 0
tagged with: pip
linked to: http://stackoverflow.com/q/26288042
tagged with: python
type: AnsweredQuestion
score: 4
accepted answer: http://stackoverflow.com/a/51701291

http://stackoverflow.com/q/51792988
has title: cannot install spacy package while trying to create python 3.6 azure function
type: Question
has answer: http://stackoverflow.com/a/51866272
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52326842
answer count: 2
has comment: http://stackoverflow.com/comment/91557369
has body: I had an error while trying to install spacy package on python 3.6 azure function as it needs a c++ compiling as a prerequisite for installation so I got this error: fatal error C1510: Cannot load language resource clui.dll. error: command 'D:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Bin\amd64\cl.exe' failed with exit status 4 Running setup.py clean for spacy Failed building wheel for spacy I've tried to use wheel but it's not supported for this package.
score: 0
tagged with: azure
tagged with: python
has comment: http://stackoverflow.com/comment/91600413
has answer: http://stackoverflow.com/a/52326842
tagged with: python-3.x
tagged with: spacy
possible better answer: http://stackoverflow.com/a/51866272

http://stackoverflow.com/a/51678765
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51678541
has body: What you're looking to do here is to call the unbound method Child2.foo with a self that isn't a Child2. This is illegal, and Python 2 will detect that and raise a TypeError that explains exactly what's wrong: TypeError: unbound method foo() must be called with Child1 instance as first argument (got Child2 instance instead) In Python 3, there are no unbound method objects; unbound methods are just plain old functions. So they can't check that you're trying to do anything illegal. And then, because you aren't actually using the fact that self is a Child2 inside the foo method, you get away with it. But you can't inject methods that actually use the Child2-ness of Child2 this way; they'll just end up raising a TypeError or AttributeError or calling the wrong methods. It will only work for methods that had no reason to be methods in the first place. If you really want this behavior in Python 2 anyway, you can get it by extracting the function out of the unbound method: self.d['foo'] = Child1.foo.__func__ (If you want to work with even older 2.x, use im_func instead of __func__ there.) Now, it's not a method at all—and if you tried to actually bind it to self with the descriptor protocol or by constructing a MethodType instead, you'd get the same old TypeError. But it is a function, and you can call it with whatever argument you want as a function. And, because your function doesn't do anything with that self parameter that requires it to be a Child2, it will work. While we're at it, you almost certainly want Parent to be a new-style class here. And you probably want to use the same code in Python 2 and Python 3, not different code for the same behavior in both. So: class Parent(object): # makes it a new-style class in 2.x as well as 3.x def foo(self): print("foo of class Parent: instance " + self.__class__.__name__) def __init__(self): self.d = {"foo": self.__class__.foo} def bar(self): self.d['foo'](self) # Gets __func__ if it's an unbound method (2.x), leaves it alon…
answers question: http://stackoverflow.com/q/51678541
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/51648893
accepted answer of: http://stackoverflow.com/q/51648785
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51648785
has body: If you try using a WHILE loop instead of FOR loop, the break statement would be check if the loop is on the last item in 'networks' collection. This way the network length would be calculated in each loop iteration

http://stackoverflow.com/a/56072491
answers question: http://stackoverflow.com/q/51652269
type: Answer
has body: I faced this same issue in Ubuntu. First, check the version of the JDK and JRE that are installed on your machine by running java --version and javac --version. Each should have a version greater than 7. Then use pip3 to install tabula. it started reading but showd following error WARNING: Using fallback font 'LiberationSerif' for 'TimesNewRomanPSMT' May 10, 2019 12:36:29 PM org.apache.pdfbox.pdmodel.font.PDTrueTypeFont
score: 0

http://stackoverflow.com/q/51675927
has answer: http://stackoverflow.com/a/51676899
has body: One of the visualizations I find myself doing most often is the following: I have x,y Data, labeled in categories. I need to plot this in a scatterplot, automatically coloring the dots according to the label, and generating a legend. The visualization should then be interactive (zoomable, hovering over points shows Metadata, etc...) This is the perfect example of what I am looking for - something that was existent in the now-deprecated bokeh.charts library: I know I can do this non-interactively with seaborn: fig = sns.lmplot(x="Length", y="Boot", hue="class", fit_reg=False, data=df) I can plot interactively with bokeh, but only on a low level, without colors or legend: p = Scatter(df, x="Length", y="Boot", plot_width=800, plot_height=600, tooltips=TOOLTIPS, title="Cars") I also know there exist various workarounds, manually defining color palettes, for example this one. However, this is ridiciously convoluted for something that used to be a simple oneliner (and still is, in R). The replacement, Holoview, does not seem to support coloring in scatterplots: Source So, any recommendations for a Python package that supports this out-of-the-box in a oneliner, instead of manually writing this code on a low-level basis?
favorite count: 0
tagged with: scatter-plot
has comment: http://stackoverflow.com/comment/90315105
tagged with: python
has comment: http://stackoverflow.com/comment/90414500
tagged with: plot
possible better answer: http://stackoverflow.com/a/51676899
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58600053
accepted answer: http://stackoverflow.com/a/58600053
has title: bokeh.charts is gone - what library can do interactive, colored scatterplots?
has comment: http://stackoverflow.com/comment/99490044
tagged with: bokeh
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/43983039
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90779616

http://stackoverflow.com/comment/90419078
comment on: http://stackoverflow.com/q/51728482
has text: @Rishi No. When you make a selection in the `OptionMenu`, the `OptionMenu` calls the function you passed to it with `command=` and it will automatically pass the selected value as the first argument to that function. Therefore, the function that is called should accept one argument. What name you give to that argument is up to you.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51755488
has body: I was typing the commands to install Beautiful Soup. I never knew what -m does in the command, so I got curious but I couldn't find much results online.
answer count: 0
type: UnansweredQuestion
has title: what does "-m" do in this command "python -m pip install beautifulsoup"
type: Question
tagged with: command-prompt
duplicate of: http://stackoverflow.com/q/7610001
has comment: http://stackoverflow.com/comment/90470694
linked to: http://stackoverflow.com/q/7610001
upvote count: 2
score: 0
downvote count: 2
duplicate of: http://stackoverflow.com/q/22241420
favorite count: 0
has comment: http://stackoverflow.com/comment/90470698
tagged with: python
linked to: http://stackoverflow.com/q/22241420

http://stackoverflow.com/comment/90545901
comment on: http://stackoverflow.com/q/51793874
has text: Well I initially replied stating I just started programming so I am not sure 90% of stuff. so I am not even sure what `requests` and etc on other questions you asked. Based on my input. you think you can help me make GET call to 1 of the API end point URL in just general programming with Python 3.7? I know I might not be making much sense I am learning how to ask questions and such...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51695617
type: Question
has title: Bayesian optimisation for parameters tuning for XGBoostRegressor in python
tagged with: bayesian
tagged with: optimization
upvote count: 1
answer count: 1
downvote count: 0
tagged with: xgboost
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54407063
tagged with: python
score: 1
has body: I'm trying to perform Bayesian optimization for tuning parameters for XGBoost Regressor, following this code: def xgboostcv(max_depth, learning_rate, n_estimators, gamma, min_child_weight, max_delta_step, subsample, colsample_bytree, reg_alpha, reg_lambda, silent=True, nthread=-1, random_state=1): return cross_val_score(xgb.XGBRegressor(max_depth=int(max_depth), learning_rate=learning_rate, n_estimators=int(n_estimators), silent=silent, nthread=nthread, gamma=gamma, min_child_weight=min_child_weight, max_delta_step=max_delta_step, subsample=subsample, colsample_bytree=colsample_bytree, reg_alpha=reg_alpha, reg_lambda = reg_lambda), train, y_train, "mean_squared_error", cv=5).mean() xgboostBO = BayesianOptimization(xgboostcv, {'max_depth': (2, 5), 'learning_rate': (0.01, 0.3), 'n_estimators': (1000, 2500), 'gamma': (1., 0.01), 'min_child_weight': (1, 10), 'max_delta_step': (0, 0.1), 'subsample': (0.5, 0.8), 'colsample_bytree' :(0.1, 0.99), 'reg_alpha':(0.1, 0.5), 'reg_lambda':(0.1, 0.9) }) xgboostBO.maximize() print('Final Results') print('XGBOOST: %f' % xgboostBO.res['max']['max_val']) This optimisation is used instead of GridSearchCV and RandomizedSearchCV for finding optimal parameters for learning model. It must outperform GridSearchCV in time of finding optimal parameters. But I receive an error and cann't figure out what is the problem. Anybody have suggestions?: Initialization -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Step | Time | Value | colsample_bytree | gamma | learning_rate | max_delta_step | max_depth | min_child_weight | n_estimators | reg_alpha | reg_lambda | subsample | --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-90-397f04e73c8f&gt; in &lt;module&gt;() 12 }) 13 ---&gt; 14 xgboostBO.maximize() 15 16 print('F…

http://stackoverflow.com/q/51732843
has body: I have a Spark DataFrame like this one: +-----+--------+-------+-------+-------+-------+-------+ | Type|Criteria|Value#1|Value#2|Value#3|Value#4|Value#5| +-----+--------+-------+-------+-------+-------+-------+ | Cat| 1| 1| 2| 3| 4| 5| | Dog| 2| 1| 2| 3| 4| 5| |Mouse| 4| 1| 2| 3| 4| 5| | Fox| 5| 1| 2| 3| 4| 5| +-----+--------+-------+-------+-------+-------+-------+ You can reproduce it with the next code: data = [('Cat', 1, 1, 2, 3, 4, 5), ('Dog', 2, 1, 2, 3, 4, 5), ('Mouse', 4, 1, 2, 3, 4, 5), ('Fox', 5, 1, 2, 3, 4, 5)] columns = ['Type', 'Criteria', 'Value#1', 'Value#2', 'Value#3', 'Value#4', 'Value#5'] df = spark.createDataFrame(data, schema=columns) df.show() My task is to add Total column that is a sum of all Value columns with # no more then Criteria for this Row. In this example: For row 'Cat': Criteria is 1, so Total is just Value#1. For row 'Dog': Criteria is 2, so Total is the sum of Value#1 and Value#2. For row 'Fox': Criteria is 5, so Total is the sum of all columns (Value#1 through Value#5). Result should look like this: +-----+--------+-------+-------+-------+-------+-------+-----+ | Type|Criteria|Value#1|Value#2|Value#3|Value#4|Value#5|Total| +-----+--------+-------+-------+-------+-------+-------+-----+ | Cat| 1| 1| 2| 3| 4| 5| 1| | Dog| 2| 1| 2| 3| 4| 5| 3| |Mouse| 4| 1| 2| 3| 4| 5| 10| | Fox| 5| 1| 2| 3| 4| 5| 15| +-----+--------+-------+-------+-------+-------+-------+-----+ I can do it using Python UDF, but my datasets are large, and Python UDF are slow because of serialization. I'm looking for pure Spark solution. I'm using PySpark and Spark 2.1
favorite count: 0
linked to: http://stackoverflow.com/q/40874657
has answer: http://stackoverflow.com/a/51736020
tagged with: python
score: 2
has title: Sum of variable number of columns in PySpark
upvote count: 2
accepted answer: http://stackoverflow.com/a/51736020
type: AnsweredQuestion
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/90427939
tagged with: pyspark
type: Question
tagged with: apache-spark
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90388045
type: Comment
comment on: http://stackoverflow.com/q/51712916
has text: What is *full_path, profile_name* in `load_arrays()`?
score: 0
type: QuestionComment

http://stackoverflow.com/a/51755287
has body: Not sure about windows, but if you have installed Anaconda prompt for windows, then you can install different versions of python on Anaconda prompt and give them specific names. Like for me, I have python3.6.5 version named as base version and the python2.7 version as py27. Whenever I need to switch to either of them, I just use activate command: activate py27 //to switch to python2.7 activate base //to switch to python3.6.5 This automatically switches me to specified version of python in the anaconda prompt and then you can work it whichever way you like.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51751847
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51751847

http://stackoverflow.com/comment/90520902
type: Comment
comment on: http://stackoverflow.com/a/51749574
has text: Yeah, depending on the background and monitors sizes, it can grow rapidly. If you want to try something, you could check to add a JPG compressor to MSS :) Else you should remove the background when you are using via RDP. It will greatly help reducing the size.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51748631
has body: I'm new to python and I 'm struggling with filtering. I'm running the following in python: DataFrame[(DataFrame.column1&lt;2 &amp; DataFrame.column2=='text')] and the error I get is cannot compare a dtyped [object] array with a scalar of type [bool] Column1 is a float64 type and column2 is object. The filter must be a combination of both of them. Any ideas?
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90457082
linked to: http://stackoverflow.com/q/33957720
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51748788
has title: filtering using columns of different types
has answer: http://stackoverflow.com/a/51748744
tagged with: python
tagged with: indexing
type: Question
tagged with: filtering
tagged with: dataframe

http://stackoverflow.com/a/74381342
type: Answer
answers question: http://stackoverflow.com/q/51775950
upvote count: 3
has body: I am not sure if this helps, but instead of the illegal f'{"new\nline"}' one could use f'{"new"+chr(10)+"line"}'
score: 3
downvote count: 0

http://stackoverflow.com/q/51775402
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/90605980
has comment: http://stackoverflow.com/comment/90509569
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/90510767
has comment: http://stackoverflow.com/comment/90606041
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90509806
type: Question
has comment: http://stackoverflow.com/comment/90510008
has body: I'm attempting to parse the following website using BeautifulSoup: https://www.treasurydirect.gov/instit/annceresult/press/press_secannpr.htm Expanding the Bills -> Term:52- Week will show 1 row of a multi-index Pandas dataframe I am building, where the first index will be the Term:Horizon and the second will be Announcement Dates. My issue lies in using BeautifulSoup to find these values because I can't seem to find any unique identifiers by reading the HTML. I assume I would iterate over Bills, then over Term-52Week and build a dictionary, but I'm not sure how to begin the process. Where should I begin? (Is there perhaps a better library?)
has comment: http://stackoverflow.com/comment/90510317
tagged with: pandas
downvote count: 0
score: 1
has title: parsing html using beautifulsoup and storing in pandas
has comment: http://stackoverflow.com/comment/90517017
has comment: http://stackoverflow.com/comment/90509662
favorite count: 0
has comment: http://stackoverflow.com/comment/90605509

http://stackoverflow.com/comment/90440526
type: Comment
type: QuestionComment
has text: how does you call your method for search?
score: 0
comment on: http://stackoverflow.com/q/51740218

http://stackoverflow.com/a/51870199
answers question: http://stackoverflow.com/q/51659237
type: Answer
has body: As I answered here.You are using python 3.7. As far as I have tested , modules like pyinstaller and cx_freeze don't seem to be working in this version. Try uninstalling your python (don't forget to backup your files before), and installing python 3.6.3 or any other python 3 version except python 3.7.
score: 0

http://stackoverflow.com/comment/90399984
score: 0
type: Comment
type: QuestionComment
has text: I have sovled my problem. Thank you for your concern
comment on: http://stackoverflow.com/q/51718025

http://stackoverflow.com/comment/90474557
score: 0
type: Comment
has text: Do you think it would be viable to keep a list of all the losses and accuracies of all batches in each epoch, and then calculate the average accuracy and total loss for each epoch?
comment on: http://stackoverflow.com/a/51757163
type: AnswerComment

http://stackoverflow.com/comment/90514722
type: Comment
has text: @ myheartsgoon idk what else to do - this is my code: (base) C:\Users\Patrick\Python364\Python36>python.exe -m pip install pyinstaller
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51759851

http://stackoverflow.com/a/51674871
has body: get_word_counts(sys.argv[1]) Should be get_word_counts(sys.argv[0]) Indexes start at zero in most languages (including python)
has comment: http://stackoverflow.com/comment/90313627
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51674712
downvote count: 0

http://stackoverflow.com/comment/90467954
has text: Then just don't drop `0` first
comment on: http://stackoverflow.com/a/51753675
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51790809
has body: Please, can you be more specific about what you are trying to do? The error you see is normal, because the code immediately below class foo will be executed during the definition of foo and therefore the class is not defined yet. If I understand well you want to define some method foobar of the class foo, which will use a foo instance. The correct procedure would then be class foo: def foobar(self,): f = foo() ... Again, with more details about what you are trying to do it would be easier to help you.
answers question: http://stackoverflow.com/q/51790676
has comment: http://stackoverflow.com/comment/90539328
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90539421
has comment: http://stackoverflow.com/comment/90539137
downvote count: 0
score: 1

http://stackoverflow.com/q/51642097
downvote count: 0
has comment: http://stackoverflow.com/comment/90277927
accepted answer: http://stackoverflow.com/a/51658605
answer count: 1
linked to: http://stackoverflow.com/q/47162334
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90251109
linked to: http://stackoverflow.com/q/42798634
tagged with: python
tagged with: opencv
tagged with: video
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51658605
upvote count: 3
has body: I'm trying to grab specific frames (e.g. frame 0, 10, 20, ...) within a video and save them as images using Python and CV2. For some reasons, my code only saves the first frame. All other frames are created, but with size 0 (they are corrupt). How can I fix the problem? import cv2 from numpy import integer number = 10; filename = "18s.mp4"; def uniform(): cap = cv2.VideoCapture(filename); frame_count= int(cap.get(cv2.CAP_PROP_FRAME_COUNT)); print(frame_count) for x in range(0, number): frame_no = 1*(x/number) frame_no_int=int(frame_no*frame_count) cap.set(2,frame_no); ret, frame = cap.read() cv2.imwrite(filename+'_frame_'+str(frame_no_int)+'.jpg', frame); # When everything done, release the capture cap.release() if __name__ == '__main__': uniform()
type: Question
has title: My python code doesn't save video frames as images

http://stackoverflow.com/comment/90387405
comment on: http://stackoverflow.com/q/51712930
score: 0
type: QuestionComment
type: Comment
has text: @esqew there is no decode attribute to a list object, how would I decode the b from the list?

http://stackoverflow.com/comment/90434391
type: Comment
has text: It might be relevant to tell us what your data source is. There's a good chance you will be limited by I/O in any case.
score: 0
comment on: http://stackoverflow.com/q/51736860
type: QuestionComment

http://stackoverflow.com/q/51641812
tagged with: string
possible better answer: http://stackoverflow.com/a/51641959
has answer: http://stackoverflow.com/a/51641911
has title: Dictionary just show key and count
type: Question
has comment: http://stackoverflow.com/comment/90248203
favorite count: 0
score: -1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51641947
answer count: 3
has comment: http://stackoverflow.com/comment/90248075
has body: I have a dictionary with two keys. my_dict = {"Hello": {'count': 2, 'distance': 6}, "Clear": {'count': 8, 'distance': 8}} and I am using a = ''.join(''.join((k, str(v))) for k,v in my_dict.items()) to convert it to string to print: "Hello" {'count': 2, 'distance': 6L} "Clear" {'count': 8, 'distance': 9L} I was wondering how I would be able to just get the key and the count to print: "Hello" - count: 2 "Clear" - count: 8
has answer: http://stackoverflow.com/a/51641959
upvote count: 4
has comment: http://stackoverflow.com/comment/90248090
has comment: http://stackoverflow.com/comment/90248038
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51641947
downvote count: 5

http://stackoverflow.com/comment/90415121
type: QuestionComment
comment on: http://stackoverflow.com/q/51724472
score: 0
has text: @ibodi do you have a server that is running selenium with ip 127.0.0.1 on your machine ? because normally 127.0.0.1 for servers on local machine so you don't need to use webdriver.remote
type: Comment

http://stackoverflow.com/comment/90361015
type: QuestionComment
comment on: http://stackoverflow.com/q/51699816
score: 0
has text: And if you put the `#noqa` after the `.getOrCreate()`?
type: Comment

http://stackoverflow.com/q/51715423
has answer: http://stackoverflow.com/a/51715734
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has title: Raspberry and Arduino talking back and forth
score: 1
tagged with: arduino
type: Question
tagged with: raspberry-pi
answer count: 1
has body: I'm working on a project in which I am using an Arduino to simulate another device that will be connected to the Raspberry. I have managed to do get the Raspberry to control the Arduino (by blinking some LED's in a pattern the Pi controlled). Now I'm looking to exchange data back and forth and have written programs for the Pi and Arduino that should have them receiving a number and then adding 1 to that number and send it back. Raspberry Pi: import serial import time ser = serial.Serial('/dev/ttyACM0',9600) time.sleep(1) var = b'0' var2 = b'1' while 1: time.sleep(0.5) ser.write(var) var = ser.read(ser.inWaiting()) #Wait for Arduino to respond print(var) var = var + var2 print('2') #Check print Arduino: const int ledPin = 12; const int ledPin2 = 11; int n; void setup() { pinMode(ledPin, OUTPUT); pinMode(ledPin2, OUTPUT); digitalWrite(ledPin2, LOW); Serial.begin(9600); n = 0; } void loop() { while(Serial.available() == 0){ digitalWrite(ledPin, HIGH); //Check LED } n = Serial.read() - '0'; digitalWrite(ledPin, LOW); n = n + 1; Serial.print(n); } The resulting print out in python is: b'' 2 b'1' 2 b'2' 2 b'22' 2 b'32' 2 b'332' 2 b'432' 2 And so on. This is not really the sequence I was expecting (1,3,5,7,9,11... Because we start at 0 and print when Arduino have added). Hope that someone can help. Thank you in advance ^^
upvote count: 1

pipe
tags question: http://stackoverflow.com/q/51680479
tags question: http://stackoverflow.com/q/51740396
tags question: http://stackoverflow.com/q/51735207
tags question: http://stackoverflow.com/q/51643451
tag name: pipe
type: Tag

http://stackoverflow.com/q/51650039
has answer: http://stackoverflow.com/a/51820531
has body: I have a new relic agent configured like so: newrelic==2.56.0.42 newrelic.agent.initialize(newrelic_ini_file, newrelic_env) logging.info('NewRelic initialized with newrelic_env '+repr(newrelic_env)) logging.info('NewRelic config name is '+repr(newrelic.agent.application().name)) It's logging the "right" things in staging, but it's not sending. NewRelic initialized with newrelic_env 'staging' NewRelic config name is 'My Service (Staging)' The agents send data from localhost and production. This is some configs from the newrelic.ini file [newrelic] license_key = xxxxx app_name = My Service monitor_mode = true log_file = /tmp/newrelic-python-agent.log log_level = info This is my staging config in newrelic.ini [newrelic:staging] app_name = My Service (Staging) monitor_mode = true log_level = debug One log that I think is suspicious is this (14/NR-Harvest-Thread) newrelic.core.agent DEBUG - Completed harvest of all application data in 0.00 seconds. I think the agent not collecting any data due to the 0.00 seconds part. What debug logs should I look for, for validating actual data being sent and received 200 from new relic. Additional details: staging is running on Docker alpine:3.6
upvote count: 7
tagged with: newrelic
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51820531
has comment: http://stackoverflow.com/comment/90350152
has comment: http://stackoverflow.com/comment/90350064
type: Question
answer count: 2
downvote count: 0
tagged with: flask
favorite count: 0
has title: newrelic agent is not sending data to newrelic servers at staging only
possible better answer: http://stackoverflow.com/a/51700198
has comment: http://stackoverflow.com/comment/90350186
has answer: http://stackoverflow.com/a/51700198
tagged with: python
score: 7

http://stackoverflow.com/q/51663867
type: Question
has comment: http://stackoverflow.com/comment/90291157
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90291403
score: 0
linked to: http://stackoverflow.com/q/38095436
linked to: http://stackoverflow.com/q/26678467
tagged with: pandas
has body: Is there a way to export a DataFrame with applied styles from a Jupyter notebook to an image file, with the styles applied?
has comment: http://stackoverflow.com/comment/90291179
duplicate of: http://stackoverflow.com/q/26678467
has title: Export Pandas DataFrame with Applied Syles to pdf or png
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90291136

http://stackoverflow.com/comment/90330675
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51684046
has text: @PM2Ring Yes, "output" is the name of that array which contains the other arrays. I will add the original function above in a second.

http://stackoverflow.com/comment/90759509
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51728785
type: Comment
has text: @AlexHurst My goal was to provide a general solution to OP's problem. I mean, what would you consider a _super long float_ ? Not to mention that I'm not sure that the workload of my loop is _trouble_ as you implied. OP could run this utility method once and store the returned value. I would actually argue that it represent a negligible computation.

http://stackoverflow.com/a/51713302
has comment: http://stackoverflow.com/comment/90388330
accepted answer of: http://stackoverflow.com/q/51713229
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51713229
score: 2
has comment: http://stackoverflow.com/comment/90388295
has body: You need to use columnconfigure and rowconfigure to set the grid columns and rows to expand with the window. Also: don't use wildcard imports use the sticky argument to keep a widget sized to the grid cell don't layout a Frame inside the same frame. IOW don't use self.grid(), always initialize and use instance.grid() on the outside. be sure to pass the kwargs anytime you subclass a tkinter widget check out more beginner oriented forums, like learnpython.reddit.com All that together: import tkinter as tk class Window(tk.Frame): # Inherits Frame methods def __init__(self, master=None, **kwargs): tk.Frame.__init__(self, master, bg='LightBlue', **kwargs) # Initializes the frame root = tk.Tk() # Creates a master root.geometry('200x200') # set initial size app = Window(root) # Initializes app using root as master app.grid(sticky='nsew') # set this widget to keep the size of the grid cell root.columnconfigure(0, weight=1) # Set the first column to expand with the window root.rowconfigure(0, weight=1) # Set the first row to expand with the window root.mainloop() # Runs window You could also use pack to do the same thing with less code: import tkinter as tk class Window(tk.Frame): # Inherits Frame methods def __init__(self, master=None, **kwargs): tk.Frame.__init__(self, master, bg='LightBlue', **kwargs) # Initializes the frame root = tk.Tk() # Creates a master root.geometry('200x200') # set initial size app = Window(root) # Initializes app using root as master app.pack(fill=tk.BOTH, expand=True) # set this widget to fill all available space root.mainloop() # Runs window Re your edit: You need to set rowconfigure on the Widget's master, not the Widget itself. The master decides how much space the Widget gets. So you could use self.master.rowconfigure(0, weight=1) if you wanted, but the structure I showed is much better for reading code. Code gets confusing if you modify the master from within a child Widget.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90355079
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51663834
has text: Those are the starting values, not the fitted parameters. The fitted parameters will be different from the starting values, because that's the hole idea behind a *fit*.

http://stackoverflow.com/comment/90431420
comment on: http://stackoverflow.com/q/51734811
type: Comment
type: QuestionComment
has text: I also saw this questions but thought it was unrelated. After your comment I've tried setting unicode_decode_error_handler='ignore' and tried downgrading to pymongo2.8. Neither made any difference and I get the problem on the exact same spot of the loop. Difference with pymongo2.8 is that it hangs indefinitely and returns no error.
score: 0

http://stackoverflow.com/comment/90447942
comment on: http://stackoverflow.com/a/51743849
score: 0
type: AnswerComment
has text: You're assuming it's an animated gif, but [Tkinter PhotoImage](http://effbot.org/tkinterbook/photoimage.htm) only accepts GIF and PGM/PPM images, so using a static gif in Tkinter is not uncommon.
type: Comment

http://stackoverflow.com/q/51796348
has answer: http://stackoverflow.com/a/51831717
score: 0
has comment: http://stackoverflow.com/comment/90561381
answer count: 2
tagged with: sympy
has body: By double "for" loops,and performing algebraic operations on an array of numbered_symbols [x1,x2,x3,..]) and some given numpy nd_arrays (here: A(2,4) and B(4)),a number of expressions (here: D1[0],D1[1],D2[0],D2[1]) were generated. The aim is that,these sympy expressions containing unknown variables[x1,x2,x3,..] must be solved by method : "linsolve" of sympy. In the more general case,i have to use a large number of symbols and name them by this way. Elements of nd_arrays (here: A(2,4) and B(4)), could be complex. For some reason I should not use matrix in numpy and sympy. Here is the minimum code that explains the problem: import sympy as sp import numpy as np from sympy.solvers.solveset import linsolve x = sp.symbols('x1:5') A = np.array([[3,2,4,6],[1,3,4,3]]) #A = np.array([[3+5j,2-1j,4+1j,6+4j],[1-6j,3+1j,4+7j,3-2j]]) B = np.array([5,8,1,4]) C1 = np.zeros ((2,4), dtype=object) C2 = np.zeros ((2,4), dtype=object) D1 = np.zeros (2, dtype=object) D2 = np.zeros (2, dtype=object) for i in range (2): for j in range (4): C1[i,j] = x[j]*A[i,j] + 2*B[j] C2[i,j] = x[j]/(4*A[i,j])-B[j] D1 = np.ndarray.tolist(np.sum (C1,axis=1)) D2 = np.ndarray.tolist(np.sum (C2,axis=1)) ans = linsolve (D1[0],D1[1],D2[0],D2[1],x1,x2,x3,x4) print(C1) print(C2) print(D1) print(D2) print(ans) The problem appears here: although x1,x2,x3,x4 have already been introduced as Symbol,this error appears: NameError: name 'x1' is not defined How to fix the Error? Another question : when (A) is selected as a Complex 2d array, then sympy expressions which are elements of lists:D1,D2 ( D1[0],D1[1],D2[0],D2[1] ) appear as complex combinations of the form 'I' Instead of 1j. How to fix the Error? Another question : Because of the large number of equations and unknowns, it is not possible for me to write "linsolve" as : ans = linsolve (D1[0],D1[1],D2[0],D2[1],x1,x2,x3,x4) And i need to write it as : ans = linsolve (D1,D2,x1:x4) Or a form like that. What should i do? thanks.
favorite count: 0
has title: Solving the large system of equations , N equations_N unknowns (as numbered_symbols [x1,x2,x3,..] ) with complex coefficients
has comment: http://stackoverflow.com/comment/90560256
has answer: http://stackoverflow.com/a/51829000
tagged with: python
has comment: http://stackoverflow.com/comment/90559650
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51829000
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/90561298
has comment: http://stackoverflow.com/comment/90560414
type: Question
tagged with: numpy-ndarray
possible better answer: http://stackoverflow.com/a/51831717

http://stackoverflow.com/comment/90333567
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51658791
score: 0
has text: Wow, thank you so much Rolf! It works.

http://stackoverflow.com/q/51766679
has body: Please look at this piece of code : sig_array=[] ... for i in range (0, 2): .... temp=[] for k in range (0, len (sig)): #print (k) temp.append(downsample(sig[k],sampl, new_freq)) sig_array.append(temp) In other words, tempis a list of arrays (my downsamplefunction, as its name may suggest, return an array) and then the temp will be agregated so it would be a list of lists of arrays ! My questions are : How to deal with that (indexing, ...) and is there simplest way to proceed, by generating list of arrays in a loop but how to keep it in a data structure ? Thanks
score: 0
has comment: http://stackoverflow.com/comment/90492295
has comment: http://stackoverflow.com/comment/90491967
answer count: 1
has comment: http://stackoverflow.com/comment/90492267
has comment: http://stackoverflow.com/comment/90492005
has comment: http://stackoverflow.com/comment/90492161
linked to: http://stackoverflow.com/q/42049147
has comment: http://stackoverflow.com/comment/90492337
has title: What will it give me and how to access the elements?
has answer: http://stackoverflow.com/a/51766884
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90492103
has comment: http://stackoverflow.com/comment/90492169
type: Question
tagged with: python
tagged with: list

http://stackoverflow.com/q/51716541
has title: compare password between form and database is invalid always
type: Question
tagged with: mongodb
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51718650
has body: Im trying to create a login system with Python/Django/MongoDB. This is my code from django.shortcuts import render from pymongo import MongoClient import bcrypt def login( req ): response = { 'error': 'Error' } if req.POST['username'] and req.POST['password']: u = req.POST['username'] p = req.POST['password'].encode('utf8') client = MongoClient() result = client['db']['users'].find_one({'name': u}) if result: hashed = bcrypt.hashpw( result['password'].encode('utf8'), bcrypt.gensalt() ) if bcrypt.checkpw( p, hashed ): response = { 'error': 'Welcome!' } else: response = { 'error': 'Invalid password' } else: response = { 'error': 'Invalid username' } else: response = { 'error': 'Password/Username empty' } return render( req, 'crawler/login.html', response ) How must I use bcrypt.checkpw() I Stored the password like this $2b$12$tapbosJdMHGCnO6zb.n7Wu3acXyBh4Cj2jdJGv.1TmMBWYtd.nnWW and the test real password is 'password' How must I store the passwords? How must I compare the passwords? (From DB against Form incoming values) Thank you for your guidance
type: UnansweredQuestion
tagged with: bcrypt
tagged with: django
tagged with: python

http://stackoverflow.com/comment/90494211
comment on: http://stackoverflow.com/q/51767723
type: Comment
type: QuestionComment
score: 1
has text: For the first part, what's wrong with `arr[[1, 3, 7, 11]]`? For the second, what have you tried? [And why do you think it's possible to do in-place?]

http://stackoverflow.com/comment/90326157
comment on: http://stackoverflow.com/q/51681527
has text: Side note: that bunch of code using `enumerate` to build the value for `key` can be written simply as `{i: 'var{}'.format(i) for i in range(rnd.randint(1, 4))}`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91608528
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51713671
has text: This worked for me; installing scipy
score: 0

http://stackoverflow.com/comment/90372896
type: AnswerComment
score: 0
type: Comment
has text: Because `gse` is a function. Try writing it out as a single custom loss function as above.
comment on: http://stackoverflow.com/a/51705576

http://stackoverflow.com/q/51650006
type: Question
upvote count: 2
has body: I'm reading a fairly small NetCDF file (5.4MB) with xarray, and want to convert it to a Pandas data frame: import xarray as xr f = xr.open_dataset('file.nc') Up to this point Python uses very little memory (~75 MB), but once I call: f2 = f.to_dataframe() The memory usage explodes (>12 GB). Does anyone know why this happens? I tried using to_dask_dataframe(), but that gives me errors on some of the data types in the NetCDF file. I uploaded the NetCDF file here, with the original data replaced by random numbers as I can't distribute the original data. As requested in the comments: In [3]: f Out[3]: &lt;xarray.Dataset&gt; Dimensions: (day_in_time_interval: 3652, nv: 2, time: 175296) Coordinates: * time (time) datetime64[ns] 2001-01-01 2001-01-01T00:30:00 ... Dimensions without coordinates: day_in_time_interval, nv Data variables: iso_dataset |S1 ... product |S1 ... station_details |S1 ... date (time) int32 ... valid_dates (day_in_time_interval) int8 ... time_bnds (time, nv) float32 ... C020 (time) float32 ... C060 (time) float32 ... C120 (time) float32 ... C200 (time) float32 ... Attributes: institution: Royal Netherlands Meteorological Institute (KNMI) comment: none Conventions: CF-1.4 location: CESAR observatory, the Netherlands file_creation_date_time: 20161130 09:34:56 (UTC) And the ncdump of the original file: netcdf ecnco2 { dimensions: time = UNLIMITED ; // (175296 currently) nv = 2 ; day_in_time_interval = 3652 ; variables: char iso_dataset ; iso_dataset:hierarchyLevel = "dataset" ; iso_dataset:url = "http://www.cesar-database.nl" ; iso_dataset:protocol = "website" ; iso_dataset:topic = "climatologyMeteorologyAtmosphere" ; iso_dataset:westbound_longitude = "4.926" ; iso_dataset:eastbound_longitude = "4.926" ; iso_dataset:southbound_latitude = "51.97" ; iso_dataset:northbound_latitude = "51.97" ; iso_dataset:datasetDateType = "publication" ; iso_dataset:code = "28992" ; iso_dataset:codeSpace = "EPSG" ; iso_dataset:accessConstraints = "CESAR data policy" ; iso_da…
tagged with: pandas
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90278004
tagged with: python-xarray
tagged with: python
has title: Excessive memory usage xarray `to_dataframe()`
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90276325
tagged with: netcdf
has answer: http://stackoverflow.com/a/51658009
accepted answer: http://stackoverflow.com/a/51658009
type: AnsweredQuestion

http://stackoverflow.com/q/51670562
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90305445
favorite count: 0
tagged with: pandas
tagged with: lxml
has body: I am working though a jupyter notebook on udemy, this topic is on pandas, on one of the questions I get this error message: ImportError Traceback (most recent call last) &lt;ipython-input-6-dc8b64eb545d&gt; in &lt;module&gt;() ----&gt; 1 df = pd.read_html('http://www.fdic.gov/bank/individual/failed/banklist.html') c:\users\phillip.desktop-did4ci8\appdata\local\programs\python\python37-32\lib\site-packages\pandas\io\html.py in read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, tupleize_cols, thousands, encoding, decimal, converters, na_values, keep_default_na, displayed_only) 985 decimal=decimal, converters=converters, na_values=na_values, 986 keep_default_na=keep_default_na, --&gt; 987 displayed_only=displayed_only) c:\users\phillip.desktop-did4ci8\appdata\local\programs\python\python37-32\lib\site-packages\pandas\io\html.py in _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs) 791 retained = None 792 for flav in flavor: --&gt; 793 parser = _parser_dispatch(flav) 794 p = parser(io, compiled_match, attrs, encoding, displayed_only) 795 c:\users\phillip.desktop-did4ci8\appdata\local\programs\python\python37-32\lib\site-packages\pandas\io\html.py in _parser_dispatch(flavor) 749 else: 750 if not _HAS_LXML: --&gt; 751 raise ImportError("lxml not found, please install it") 752 return _valid_parsers[flavor] 753 ImportError: lxml not found, please install it (I am using python 3.7, I have downloaded anaconda) I then tried to install lxml in the command prompt using: pip3 install lxml however I get this error message: Command "c:\users\phillip.desktop-did4ci8\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PHILLI~1.DES\\AppData\\Local\\Temp\\pip-install-i762jowc\\lxml\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\PHILLI~1.DES\AppData\Local\Temp\pip-recor…
has comment: http://stackoverflow.com/comment/90305727
tagged with: python
has comment: http://stackoverflow.com/comment/90303779
has title: ImportError: lxml not found, please install it
possible better answer: http://stackoverflow.com/a/67983054
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67983054
downvote count: 0
has answer: http://stackoverflow.com/a/51671754
accepted answer: http://stackoverflow.com/a/51671754

http://stackoverflow.com/q/51700689
has answer: http://stackoverflow.com/a/76627825
has body: am trying to login to odoo through the controller @http.route('/ehs/login', methods=['POST'], auth='public', csrf=False) def login(self,**kwargs): username = kwargs.get('username') password = kwargs.get('password') db = kwargs.get('db') uid = request.session.authenticate(db, username,password) if uid: user_id=request.env['res.partner'].search([('id','=',int(uid))]) data={'uid':uid,'company_number':user_id.company_id.phone} jsondata = json.dumps(data) return jsondata else: return "wrong credential" the above service is work fine if am having only One DB, it will show error when I try to log in to different Db in the same instance Can any One help me? any help would be appreciated . ThankYou
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: odoo
score: 1
upvote count: 1
type: Question
has title: login to specific db via controller for odoo
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90381900
score: 0
type: Comment
type: QuestionComment
has text: I think I would ignore the IDE warning. Mammal is essentially an abstract class as well.
comment on: http://stackoverflow.com/q/51710188

http://stackoverflow.com/comment/90543294
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51788427
has text: You're welcome, the keras api is indeed lovely to work with.
score: 0

http://stackoverflow.com/comment/90369922
comment on: http://stackoverflow.com/q/51704378
score: 0
has text: When ever am running the manage.py file I get the information from some external url. How to store that information in memory and how to use that throughout the application in django
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90292716
score: 1
type: AnswerComment
has text: @scamander `*content` is only valid in Python3. However, my solution below it will work for both versions.
comment on: http://stackoverflow.com/a/51664649
type: Comment

http://stackoverflow.com/a/78551705
answers question: http://stackoverflow.com/q/51679863
score: 1
upvote count: 1
has body: Thanks to @alexpotato for a great starting point. I'm running this in a deployment pipeline, so I needed to run pipenv first (otherwise the site packages didn't exist). I'm also depending on the Pipfile.lock (a common deployment pipeline practice). I dynamically determine the path, and I exclude some things from the zip file. #!/bin/bash set -e pipenv install --deploy --ignore-pipfile SITE_PACKAGES=$(pipenv --venv)/lib/python$($(pipenv --py) --version | sed 's/.*\(3\.[0-9]*\).*/\1/')/site-packages's/.*\(3\.[0-9]*\).*/\1/')/site-packages echo "Library location: $SITE_PACKAGES" DIR=$(pwd) cd $SITE_PACKAGES zip -r9 $DIR/lambda_function_payload.zip * -x "pip/*" "pip-*/*" "__pycache__/*" cd $DIR zip -r9 lambda_function_payload.zip . echo "Package created at $DIR/lambda_function_payload.zip"
downvote count: 0
type: Answer

http://stackoverflow.com/a/51646063
has comment: http://stackoverflow.com/comment/90259899
type: AcceptedAnswer
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51645417
has comment: http://stackoverflow.com/comment/90265863
has comment: http://stackoverflow.com/comment/90362174
has comment: http://stackoverflow.com/comment/90362131
score: 1
has comment: http://stackoverflow.com/comment/90258428
accepted answer of: http://stackoverflow.com/q/51645417
has comment: http://stackoverflow.com/comment/90350205
has body: The code snippet that you are using was from 2013; the Google API has changed and 'postal_town' is no longer available. You can use the following code which takes advantage of the requests library and places a guard in the case of no results being returned. In [48]: def location(lat, long): ...: url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&amp;sensor=false'.format(lat, long) ...: r = requests.get(url) ...: r_json = r.json() ...: if len(r_json['results']) &lt; 1: return None, None ...: res = r_json['results'][0]['address_components'] ...: country = next((c['long_name'] for c in res if 'country' in c['types']), None) ...: locality = next((c['long_name'] for c in res if 'locality' in c['types']), None) ...: return locality, country ...: In [49]: location(28.512889, 77.088154) Out[49]: ('Gurugram', 'India') This function searches 'locality' and actually doesn't return anything for the 2nd row of the DataFrame. You can choose what fields you want by inspecting the results (this is with a lat, long value of 30.314368, 76.384381) [{'long_name': 'Udyog Vihar', 'short_name': 'Udyog Vihar', 'types': ['political', 'sublocality', 'sublocality_level_2']}, {'long_name': 'Kapas Hera Estate', 'short_name': 'Kapas Hera Estate', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'Gurugram', 'short_name': 'Gurugram', 'types': ['locality', 'political']}, {'long_name': 'Gurgaon', 'short_name': 'Gurgaon', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Haryana', 'short_name': 'HR', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '122016', 'short_name': '122016', 'types': ['postal_code']}] To apply this to your DataFrame, you can use numpy's vectorize like so (remember that the second row won't return anything) In [71]: import numpy as np In [72]: df['locality'] = np.vectorize(location)(df['latitude'], df['longitude…
downvote count: 0

http://stackoverflow.com/q/51683413
has comment: http://stackoverflow.com/comment/90329632
has answer: http://stackoverflow.com/a/51683695
has comment: http://stackoverflow.com/comment/90329431
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90348079
tagged with: python
has comment: http://stackoverflow.com/comment/90329335
has comment: http://stackoverflow.com/comment/90329714
score: 0
has body: When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this? The output should look like this Hello Megan the four games avaliable are: 0 Mario Cart 1 Minecraft 2 Angry Birds 3 Grabd Theft Auto What number game do you want? h Please choose a valid number What number game do you want? 23 Please choose a number between 0 and 3 What number game do you want? 1 You have chosen Minecraft Instead, the output is Hello the four games avaliable are: 0 Mario Cart What number game do you want? 2 1 Minecraft What number game do you want? h Please enter a valid value The code i am using is: #Ask user what game they would like to play def game () : global gametype,gamelist gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"] gamecount = 0 print ("Hello the four games avaliable are:") while gamecount &lt; 4: print (gamecount," ",gamelist[gamecount]) gamecount = gamecount + 1 try: gametype = int(input("What number game do you want? ")) while gametype &lt;0 or gametype &gt;3: print (" Please enter a value between 0 and 3") except ValueError: print ("Please enter a valid value " ) return gametype game () I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax. SECOND TRY I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red. #Ask user what game they would like to play def game () : global gametype,gamelist gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"] gamecount = 0 print ("Hello the four games avaliable are:") while gamecount &lt; 4: print (gamecount," ",gamelist[gamecount]) gamecount = gamecount + 1 while True: try: gametype = int(input("What number game do you want? ")) if 0 &lt;= gametype &lt;= 3 : return game print ("Please enter a value b…
has comment: http://stackoverflow.com/comment/90329750
type: Question
has title: Fixing invalid syntax errors in try and except
has comment: http://stackoverflow.com/comment/90329456
has comment: http://stackoverflow.com/comment/90329514
has comment: http://stackoverflow.com/comment/90329367
has comment: http://stackoverflow.com/comment/90329856
has comment: http://stackoverflow.com/comment/90329344
answer count: 1

http://stackoverflow.com/a/51786036
accepted answer of: http://stackoverflow.com/q/51784840
has comment: http://stackoverflow.com/comment/90532087
answers question: http://stackoverflow.com/q/51784840
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90532481
has comment: http://stackoverflow.com/comment/90531815
has body: This will delete folders in old_path if they exist do not in new_path: import os import shutil old_path = r"old file path" new_path = r"old file path" for folder in os.listdir(old_path): if folder not in os.listdir(new_path): shutil.rmtree(os.path.join(old_path, folder)) This will find the matching shape files and pass them to arcpy.Append_management(): import os import arcpy for dir_path, dir_names, file_names in arcpy.da.Walk(workspace=new_path, datatype="FeatureClass"): for filename in file_names: new_file_path = os.path.join(dir_path, filename) folder = os.path.basename(os.path.dirname(new_file_path)) old_file_path = os.path.join(old_path, folder, filename) if os.path.exists(old_file_path): arcpy.Append_management(inputs=[new_file_path], target=old_file_path, schema_type="NO_TEST")
score: 1
has comment: http://stackoverflow.com/comment/90532652
has comment: http://stackoverflow.com/comment/90531558
has comment: http://stackoverflow.com/comment/90531438
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90530603

http://stackoverflow.com/q/51644736
tagged with: python
linked to: http://stackoverflow.com/q/32957441
has title: xlsxwriter and pandas for reporting
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/51644990
accepted answer: http://stackoverflow.com/a/51644990
has body: I am trying to create a basic excel report. I am trying display a dataframe as well as some custom text/titles, not part of the dataframe. However, I can only get one or the other. I don't really understand the end of the code that is needed for the dataframe to appear (workbook = writer.book and worksheet = writer.sheets['Reports']. Here is my code: writer = pd.ExcelWriter('reportTemplate.xlsx', engine='xlsxwriter') workbook = xlsxwriter.Workbook('reportTemplate.xlsx') worksheet = workbook.add_worksheet('Reports') # REPORT TITLE worksheet.write('D2','Daily In-Store Report') workbook = xlsxwriter.Workbook('reportTemplate.xlsx') worksheet = workbook.add_worksheet('Reports') worksheet.write('D2','Daily In-Store Report') reportTimes = ['Day','Week','Period','Quarter','Year'] cityList = ['ontario','bayshore','ottawa','limeridge','oshawa','scarborough','sherway','massonville','gatineau', 'quebec','anjou','dix30','Fairview','laval','mtltrust','stbruno','gcapitale','stefoy','rivieres','chicoutimi','sherbrooke','canada'] # LOOP THROUGH FILES rowNb = 4 for time in reportTimes: # TITLE tableTitle = time + ' report as of ...' worksheet.write('A'+str(rowNb),tableTitle) rowNb += 1 headRow, secondHead = createHeadings(time) worksheet.write_row('B' + str(rowNb), headRow) worksheet.write_row('B' + str(rowNb), secondHead) rowNb += 2 df = pd.read_csv('fy_' + time.lower() + '.csv') df.set_index('legacy_id',inplace=True) df = df.reindex(cityList) print(df) df.to_excel(writer,sheet_name='Reports',startrow = rowNb,header=False) workbook = writer.book worksheet = writer.sheets['Reports'] writer.save() As the code is right now, it only displays the dataframe
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/51742203
score: 0
type: Answer
has body: Still not clear, but try: if sys.argv[1] == 10: sys.exit(0)
answers question: http://stackoverflow.com/q/51738813

http://stackoverflow.com/q/51648172
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90259971
has comment: http://stackoverflow.com/comment/90260048
type: UnansweredQuestion
tagged with: python
has title: Pandas - How it is possible to generate trees out of 2 column file
tagged with: directed-acyclic-graphs
score: 2
has comment: http://stackoverflow.com/comment/90260686
answer count: 0
has comment: http://stackoverflow.com/comment/90260550
type: Question
has comment: http://stackoverflow.com/comment/90260004
tagged with: dataframe
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90260003
has body: My data file looks like the following: 1 2 3 4 4 5 5 7 1 8 8 20 Note that the data consists of "edges" of directed acyclic graph, left to right (e.g. (4,5) is a directed edge in the graph). What I want, by using only Pandas tools is to receive the following file: 1 2 3 4 5 7 1 8 20 Which represents the full graph or the "forest" of the data. Note - There is no bound for the number of children.

http://stackoverflow.com/comment/90269276
has text: One question, the position of the lines as they are determined ?, I ask you because I am seeing 2 possibilities: the first is to try to use your QRangeSlider, but in a certain way it is complicated to implement it, although we should not lose hope, since the other option that I'm thinking about is to create a new QRangeSlider from scratch. :)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51652527
score: 0

http://stackoverflow.com/comment/90281998
type: QuestionComment
comment on: http://stackoverflow.com/q/51645244
score: 0
has text: I wrote an answer explaining how to get it to run the method's code—but if that's your actual question, please edit the question to say that, rather than leave it in a comment. Meanwhile, I still have no idea what you're trying to extract and print out here, but I took some guesses and added that to the answer as well.
type: Comment

http://stackoverflow.com/a/51661785
has comment: http://stackoverflow.com/comment/90315843
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90306759
has body: You can try something like this: make a generator, that will yield values from XML file stored in dictionary. The missing values from XML file will be stored as 'Blank' in this dictionary: from bs4 import BeautifulSoup data = """&lt;CI_INFO&gt; &lt;CI_JOURNAL&gt; &lt;CI_AUTHOR&gt;CAMPBELL D&lt;/CI_AUTHOR&gt; &lt;CI_VOLUME&gt;0079&lt;/CI_VOLUME&gt; &lt;CI_PAGE&gt;00034&lt;/CI_PAGE&gt; &lt;CI_YEAR&gt;2013&lt;/CI_YEAR&gt; &lt;CI_TITLE&gt; &lt;![CDATA[ ALASKA MAGAZINE FEB ]]&gt;&lt;/CI_TITLE&gt; &lt;/CI_JOURNAL&gt; &lt;CI_JOURNAL&gt; &lt;CI_AUTHOR&gt;BURKE CH&lt;/CI_AUTHOR&gt; &lt;CI_YEAR&gt;1961&lt;/CI_YEAR&gt; &lt;CI_TITLE&gt; &lt;![CDATA[ DOCTOR HAP ]]&gt; &lt;/CI_TITLE&gt; &lt;/CI_JOURNAL&gt; &lt;CI_JOURNAL&gt; &lt;CI_YEAR&gt;1905&lt;/CI_YEAR&gt; &lt;CI_TITLE&gt; &lt;![CDATA[ REPORT GOVERNOR ALAS ]]&gt;&lt;/CI_TITLE&gt; &lt;/CI_JOURNAL&gt; &lt;/CI_INFO&gt;""" def parse_data(soup): _text = lambda soup, name: soup.find(name).text.strip() if soup.find(name) else 'Blank' for j in soup.select('CI_JOURNAL'): d = {} d['author'] = _text(j, 'CI_AUTHOR') d['vol'] = _text(j, 'CI_VOLUME') d['page'] = _text(j, 'CI_PAGE') d['year'] = _text(j, 'CI_YEAR') d['title'] = _text(j, 'CI_TITLE') yield d for info in parse_data(BeautifulSoup(data, 'xml')): print(info['author']) print(info['vol']) print(info['page']) print(info['year']) print(info['title']) print('-' * 80) This will print: CAMPBELL D 0079 00034 2013 ALASKA MAGAZINE FEB -------------------------------------------------------------------------------- BURKE CH Blank Blank 1961 DOCTOR HAP -------------------------------------------------------------------------------- Blank Blank Blank 1905 REPORT GOVERNOR ALAS -------------------------------------------------------------------------------- EDIT: If you want separated columns, you can do this: author, vol, page, year, title = [], [], [], [], [] for d in parse_data(BeautifulSoup(data, 'xml')): author.append(d['author']) vol.append(d['vol']) page.append(d['page']) year.append(d['y…
downvote count: 0
has comment: http://stackoverflow.com/comment/90309695
answers question: http://stackoverflow.com/q/51660134
type: Answer
has comment: http://stackoverflow.com/comment/90318563

http://stackoverflow.com/q/51719623
tagged with: ssl
has comment: http://stackoverflow.com/comment/90402345
has body: I have intergrated SSL certificate in my application and i have https in my site but in django social auth the Request URL goes only with http. I know the Twitter does not allow requests from http. Link : http://humbusy.tk/social-auth/login/twitter/ My site has https but the request goes with http .Why ? and How do i resolve it ? Thanks .
has comment: http://stackoverflow.com/comment/90402635
has comment: http://stackoverflow.com/comment/90401441
downvote count: 0
has comment: http://stackoverflow.com/comment/90402772
answer count: 1
has answer: http://stackoverflow.com/a/51721287
has comment: http://stackoverflow.com/comment/90402917
has comment: http://stackoverflow.com/comment/90401623
has title: Django - Social Auth (Request URL is showing http instead of https)
has comment: http://stackoverflow.com/comment/90403377
favorite count: 0
has comment: http://stackoverflow.com/comment/90402453
accepted answer: http://stackoverflow.com/a/51721287
tagged with: python
has comment: http://stackoverflow.com/comment/90401914
has comment: http://stackoverflow.com/comment/90402159
has comment: http://stackoverflow.com/comment/90401346
has comment: http://stackoverflow.com/comment/90401276
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90400889
tagged with: authentication
has comment: http://stackoverflow.com/comment/90400027
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/90402808
tagged with: twitter-oauth
type: Question
has comment: http://stackoverflow.com/comment/90400010
has comment: http://stackoverflow.com/comment/90402524

http://stackoverflow.com/q/51697030
has answer: http://stackoverflow.com/a/51697096
has comment: http://stackoverflow.com/comment/90355467
downvote count: 0
has answer: http://stackoverflow.com/a/51697104
favorite count: 0
accepted answer: http://stackoverflow.com/a/51697096
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51697247
has answer: http://stackoverflow.com/a/51697198
answer count: 5
has body: I'm working my way through the MIT Open Courseware class Introduction to Computer Science and Programming in Python and I've spent an embarrassing amount of time trying to wrap my head around the "Finger Exercise" from the textbook: Write a program that examines three variables—x, y, and z—and prints the largest odd number among them. If none of them are odd, it should print a message to that effect. I wrote a couple of solutions that didn't quite work, missing odd numbers if there were larger even numbers. I finally threw in the towel and searched here for solutions that others people working on this class had asked. This solution from AFDev seemed to be the simplest to me (in the context of what the intent of the exercise was and how concise the solution was.) I combined that with my user input to get the following: x=int(input('Enter your first number:')) y=int(input('Enter your second number:')) z=int(input('Enter your third number:')) largest = None if x%2: largest = x if y%2: if y &gt; largest: largest = y if z%2: if z &gt; largest: largest = z if largest: print ('The largest odd number is', largest) else: print ('There are no odd numbers.') This works great, as long as x is an odd number. If x is zero or an even number, I get the following error: TypeError: '&gt;' not supported between instances of 'int' and 'NoneType' The little bit of Googling I did said that Python 2 was a little more liberal in allowing comparisons between NoneType and integers. I changed the line to initialize largest = 0, but then realized that this would give invalid results if the user input a negative number. I tweaked the code to the following: x=int(input('Enter your first number:')) y=int(input('Enter your second number:')) z=int(input('Enter your third number:')) largest = None if x%2: largest = x if y%2: if largest == None: largest = y if y &gt; largest: largest = y if z%2: if largest == None: largest = z if z &gt; largest: largest = z if largest: print ('The largest odd number …
tagged with: python
possible better answer: http://stackoverflow.com/a/51697247
has title: Initializing integer variables for comparisons
linked to: http://stackoverflow.com/q/15732805
has answer: http://stackoverflow.com/a/51697291
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90355619
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90355488
has comment: http://stackoverflow.com/comment/90355549
type: Question

url
tags question: http://stackoverflow.com/q/51757421
tag name: url
tags question: http://stackoverflow.com/q/51755692
type: Tag

http://stackoverflow.com/q/51678520
has answer: http://stackoverflow.com/a/51678604
has body: I'm trying to use a github repo and having some issues with the argparse part of the project. The repo starts like this: import markdown, sys, csv, getpass, smtplib, argparse from email.mime.text import MIMEText from jinja2 import Template parser = argparse.ArgumentParser() parser.add_argument('-m', '--markdown', help='Path to Markdown Template', required=True) parser.add_argument('-c', '--csv', help='Path to CSV file', required=True) parser.add_argument('-v', '--verbose', help='Write out emails') args = parser.parse_args() I've entered both the relative and absolute path to both the markdown and CSV files... and I get in return this error: usage: mass-email.py [-h] -m MARKDOWN -c CSV mass-email.py: error: the following arguments are required: -m/--markdown, -c/--csv Process finished with exit code 2 I can't find any specific help with this. Any advice would be much appreciated.
answer count: 2
has title: Python Argparse 'following arguments are required' error
has comment: http://stackoverflow.com/comment/90320638
favorite count: 0
has comment: http://stackoverflow.com/comment/124966755
linked to: http://stackoverflow.com/q/33102272
tagged with: argparse
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51678855
tagged with: pycharm
upvote count: 2
score: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/51709652
has comment: http://stackoverflow.com/comment/90405301
has comment: http://stackoverflow.com/comment/90381109
downvote count: 0
has title: matplotlib: plot and fill high resolution coastline
linked to: http://stackoverflow.com/q/15968762
favorite count: 0
has body: I have (lon,lat) data that mark a high resolution coastline. It is a very irregular coastline (estuary) and so when I use matplotlib's fill or fill_between functions, it does not work as it is supposed to, as it also fills parts outside the coast, inside the estuary, as well. I cannot use cartopy or basemap since their "full" resolution is not enough for what I need... I have read a bunch of other posts (e.g.): shapefile and matplotlib: plot polygon collection of shapefile coordinates https://gis.stackexchange.com/questions/131716/plot-shapefile-with-matplotlib That had the same issue as I do, but they work with shapefile, so I am not sure how can I use it with my data. For what I have read so far, I think the answer to my problem is to create a closed polygon using path where one side is the coastline (from the data I have), and the others can be straight lines outside of my boundaries...I have read the documentation for path and Patch but have not been able to make it work. How can I do this? Here is what I get using: plt.plot(lonc,latc,'.') and plt.fill(lonc,latc) (I am sorry I cannot provide the actual data I am working with)...
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90417543
answer count: 0
score: 1
tagged with: matplotlib
tagged with: fill
upvote count: 1
type: Question
tagged with: polygon

http://stackoverflow.com/comment/90425691
type: AnswerComment
comment on: http://stackoverflow.com/a/51732367
score: 0
type: Comment
has text: Simple but enough for me :)

http://stackoverflow.com/a/51844175
has body: I just realized where I screwed up. I had an additional groupby and sum() that converted the nan to a 0
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51776362

http://stackoverflow.com/comment/90339073
type: Comment
comment on: http://stackoverflow.com/a/51688405
score: 0
type: AnswerComment
has text: This worked for, but saw another follow up after running this. My Var2 is actually a dictionary with two parts, so `print(*var4, sep='\n')` prints my dictionary list into two lines. Can the * be used to isolate which ones I want to break apart in that manner? I ended up just making a long list of variables and text to get it working for now.

http://stackoverflow.com/comment/90390664
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51714499
has text: @Jean-FrançoisFabre can you elaborate in code how I could write to the console and parse? in python?

http://stackoverflow.com/a/51775669
answers question: http://stackoverflow.com/q/51692003
type: Answer
has body: If your input is always expected to have a significant outlier, I would recommend an iterative filtering approach. Here is your data plotted along with the mean, 1-sigma, 2-sigma and 3-sigma lines: I would start by removing everything above and below 2-sigma from the mean. Since that will tighten the distribution, I would recommend doing the iterations over and over until the size of the un-trimmed data remains the same. I would recommend increasing the threshold geometrically to avoid trimming "good" data. Finally, you can fill in the missing points with the mean of the remainder or something like that. Here is a sample implementation, with no attempt at optimization whatsoever: data = np.loadtxt('data.txt', skiprows=1) x = np.arange(data.size) loop_data = data prev_size = 0 nsigma = 2 while prev_size != loop_data.size: mean = loop_data.mean() std = loop_data.std() mask = (loop_data &lt; mean + nsigma * std) &amp; (loop_data &gt; mean - nsigma * std) prev_size = loop_data.size loop_data = loop_data[mask] x = x[mask] # Constantly expanding sigma guarantees fast loop termination nsigma *= 2 # Reconstruct the mask mask = np.zeros_like(data, dtype=np.bool) mask[x] = True # This destroys the original data somewhat data[~mask] = data[mask].mean() This approach may not be optimal in all situations, but I have found it to be fairly robust most of the time. There are lots of tweakable parameters. You may want to change your increase factor from 2, or even go with a linear instead of geometrical increase (although I tried the latter and it really didn't work well). You could also use IQR instead of sigma, since it is more robust against outliers. Here is an image of the resulting dataset (with the removed portion in red and the original dotted): Another artifact of interest: here are the plots of the data showing the trimming progression and how it affects the cutoff points. Plots show the data, with cut portions in red, and a the n-sigma line for the remainder. The title sh…
score: 0

http://stackoverflow.com/a/51680380
answers question: http://stackoverflow.com/q/51679962
downvote count: 0
score: 1
has body: Your exception comes from here: if patterns: if args: arg_msg = "arguments '%s'" % (args,) elif kwargs: arg_msg = "keyword arguments '%s'" % (kwargs,) else: arg_msg = "no arguments" msg = ( "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % (lookup_view_s, arg_msg, len(patterns), patterns) ) else: msg = ( "Reverse for '%(view)s' not found. '%(view)s' is not " "a valid view function or pattern name." % {'view': lookup_view_s} ) This means that Django couldn't even find your url to try to reverse to it. Thus you probably included it incorrectly in core app's urls.py for the way you try to reference it. Probably fxgx's comment is correct.
upvote count: 1
type: Answer

http://stackoverflow.com/a/55062693
score: 0
type: Answer
has body: My suggestion would be to convert the .hdf5 file to a .tfrecord file, you can find examples of how to do this here.
answers question: http://stackoverflow.com/q/51676257

http://stackoverflow.com/q/51732488
upvote count: 4
duplicate of: http://stackoverflow.com/q/26079392
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51732694
downvote count: 0
has title: Why are Unicode strings having a different memory footprint in Python 2 and 3?
type: Question
type: AnsweredQuestion
has body: In Python 2, an empty string occupy exactly 37 bytes, &gt;&gt;&gt;&gt; print sys.getsizeof('') 37 In Python 3.6, the same call would output 49 bytes, &gt;&gt;&gt;&gt; print(sys.getsizeof('')) 49 Now I thought that this was due to the fact that in Python 3, all strings are now Unicode. But, to my surprise here are some confusing outputs, Python 2.7 &gt;&gt;&gt;&gt; print sys.getsizeof(u'') 52 &gt;&gt;&gt;&gt; print sys.getsizeof(u'1') 56 Python 3.6 &gt;&gt;&gt;&gt;print(sys.getsizeof('')) 49 &gt;&gt;&gt;&gt;print(sys.getsizeof('1')) 50 An empty string is not the same size. 4 additional bytes are needed when adding a character in Python 2 and only one for Python 3 Why is the memory footprint different between the two versions ? EDIT I specified the exact version of my python environment, because between different Python 3 builds there are differences.
linked to: http://stackoverflow.com/q/26079392
tagged with: memory
tagged with: python-2.7
answer count: 2
score: 4
tagged with: unicode
has comment: http://stackoverflow.com/comment/90426131
favorite count: 0
accepted answer: http://stackoverflow.com/a/51732694
possible better answer: http://stackoverflow.com/a/51732593
has answer: http://stackoverflow.com/a/51732593
tagged with: python

http://stackoverflow.com/comment/90549105
has text: Prime is greater than `1`, `1` is not prime. Note: `else:` clause on the `for` loop would also work instead of the `is_prime` flag.
type: AnswerComment
comment on: http://stackoverflow.com/a/51795834
type: Comment
score: 1

http://stackoverflow.com/a/51757878
has body: Use pd.DataFrame on a list images to put each image on a separate row. Since there is only one image here, adding [] is enough depending on the output you want. df = pd.DataFrame([img]) will give 0 1 2 3 4 0 1.0 1.0 1.0 1.0 1.0 while df = pd.DataFrame(img) gives 0 0 [1.0, 1.0, 1.0, 1.0, 1.0] The second output is most probably what you want if the array is long.
has comment: http://stackoverflow.com/comment/90499019
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51757759
has comment: http://stackoverflow.com/comment/90513567
answers question: http://stackoverflow.com/q/51757759
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51643831
tagged with: python
has body: There is a set of snmp trap OID's, from different vendor devices like Cisco/Juniper/Arista etc... For example: 1.3.6.1.4.1.6101.1.8.8.2.1 We would like to know the trap names for each OID. There are more than 300 OID's. Programmatically we store all trap OID's in set, using python. What is the best approach to retrieve trap names? Does any public repository provide mapping of trap OID to trap name?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/68674702
has answer: http://stackoverflow.com/a/68674702
accepted answer: http://stackoverflow.com/a/51646752
tagged with: pysnmp
type: Question
answer count: 2
tagged with: snmp-trap
score: 0
has title: Trap OID to trap name - snmp
tagged with: snmp
has answer: http://stackoverflow.com/a/51646752

http://stackoverflow.com/comment/90519952
has text: Yes final column in datetime format
comment on: http://stackoverflow.com/q/51781019
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90421265
comment on: http://stackoverflow.com/a/51728860
score: 5
type: AnswerComment
type: Comment
has text: Hmmm, "Python only prints a decimal approximation to the true decimal value of the binary _approximation_ stored by the machine" seems amiss. The value in the binary float I'd call exact, not a binary _approximation_. "...to the true decimal value of the binary stored by the machine" sounds clearer. The way the float was assigned may have incurred some rounding, yet the stored value itself is exact.

http://stackoverflow.com/comment/90306542
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51671855
has text: Because if not, is possible first filtr only `boolean` columns - `cols = df.select_dtypes(bool).columns` `df[cols] = df[cols].astype(int)`
score: 0

http://stackoverflow.com/comment/99107355
type: Comment
has text: thanks dude for this example.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51710459

http://stackoverflow.com/q/51708453
has body: I'm trying to represent a binary tree using class. Here's what i've got: class Tree: def __init__(self, cargo, parent=None, left=None, right=None): self.cargo = cargo self.parent = parent self.left = left self.right = right self.path = '' def giveChild(self, child, sub): child.parent = self.cargo if sub == 'left': self.left = child child.path += 'l' if sub == 'right': self.right = child child.path += 'r' I use path to store a path from a root to a certain leaf like 'llrlr' (left-left-right-left-right). When I add new nodes to a tree, I go from bottom-to-top. First I create leaves, then I give them a parent node. Ok, now I create two leaves: r = Tree('r') p = Tree('p') The I create the next node, which is a parent for r and p: rp = Tree('rp') rp.giveChild(r, 'left') Now since r is a left node of rp, r's path becomes 'l'. The problem is how to change r's path when rp gets a parent node? My codes doesn't change the path to '...ll' or '...rl', it's still just 'l'.
has comment: http://stackoverflow.com/comment/90380533
has comment: http://stackoverflow.com/comment/90379165
score: 0
has comment: http://stackoverflow.com/comment/90378166
has title: classes - make parent changes affect children
has comment: http://stackoverflow.com/comment/90378061
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90379268
type: Question

http://stackoverflow.com/a/75091378
has body: Very short code that should work for easy coping-pasting. output_path = "/data/meow/my_output.jsonl" with open(output_path, "w") as f: f.write(df_result.to_json(orient='records', lines=True, force_ascii=False)) If you are using jupyter notebook, you should use with open(output_path, "w") as f instead of f = open(output_path, "w") to make sure file is saved (correctly close) and ready to read in next cell.
score: 8
downvote count: 0
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/51775175

http://stackoverflow.com/comment/90361070
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51699802
has text: I'm pretty sure you want the test at a deeper level in the code. You should really know where you're getting an `IndexError`, and what you want to do about it. For example, if it's that `header = jsonObj["value"][0].keys()`, because sometimes `value` is an empty list, then you want to check that—probably before you open and start writing any files—and just `return`. But meanwhile, you _also_ shouldn't be using threads like this, as Chris Johnson says. Just use a `while True:` loop and a `sleep` call.

http://stackoverflow.com/a/55915586
has body: You may write as below.It will be a easy fix and work almost appropriate every time. lr.summary2()
upvote count: 4
answers question: http://stackoverflow.com/q/51734180
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/a/51714554
type: Answer
accepted answer of: http://stackoverflow.com/q/51680468
answers question: http://stackoverflow.com/q/51680468
score: 0
has body: Finally figured out my code: import csv d = { ('High', 'High'): 'Operation group HIGH', ('Medium', 'Medium'): 'Operation group MEDIUM', ('Low', 'Low'): 'Operation group LOW', } class DevicePriority: def __init__(self, fqdn, priority): self.fqdn = fqdn self.priority = priority @property def priorities(self): return self.priority @property def fqdns(self): return self.fqdn def initializefile(file): with open('1stcsv.csv', 'r') as f: return convertrows(csv.DictReader(f)) def convertrows(rows): return [DevicePriority(row['Device'], row['Priority']) for row in rows] file = r"My\1stcsv.csv" devices = initializefile(file) class MHTs: def __init__(self, FQDN, MessageType1): self.FQDN = FQDN self.MessageType1 = MessageType1 @property def devicename(self): return self.FQDN @property def MessageType1(self): return self.MessageType1 def get_validgroups(self): if 'Operation' not in self.MessageType1: return 'Not Found' else: return self.MessageType1 def get_comparison(self): if device.priorities.upper() in group.get_validgroups(): return '' else: return device.priorities def onlychanged(self): if group.get_validgroups() == 'Not Found': return '' else: return group.get_comparison() def finalchanged(self): if device.priorities == 'Not Found': return '' else: return group.onlychanged() def finalmhts(self): return d[device.priorities, group.onlychanged()] def mht2(self): if group.get_comparison() == 'High': return 'Layer 2 group HIGH elif group.get_comparison() == 'Medium': return 'Layer 2 group MEDIUM' else: group.get_comparison() == 'Low': return 'Layer 2 group LOW' def mht3(self): if group.get_comparison() == 'High': return 'Layer 3 group HIGH' elif group.get_comparison() == 'Medium': return 'Layer 3 group MEDIUM' else: group.get_comparison() == 'Low' return 'Layer 3 group LOW' def initializefile2(file): with open('2ndcsv.csv', 'r', newline='') as i: return convertmhts(csv.DictReader(i)) def convertmhts(rows): return [MHTs(row['FQDN'], row['MHT_1']) for row in rows] file = r"My\2…
type: AcceptedAnswer

http://stackoverflow.com/comment/90462589
has text: So the inner loop produces `array[:,x,y,z]`
comment on: http://stackoverflow.com/q/51750872
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90470068
type: Comment
comment on: http://stackoverflow.com/a/51755175
has text: Also, doesn't it have multiple loops just put in a 1-liner?
type: AnswerComment
score: 1

http://stackoverflow.com/comment/90496839
comment on: http://stackoverflow.com/q/51751032
score: 0
type: Comment
type: QuestionComment
has text: How are you setting the initial conditions for your state variables `TR, TRL, and TW`?

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/51690339
type: Tag

http://stackoverflow.com/comment/90476612
type: Comment
has text: Try running your pandas script from this newly activated(I'm assuming this is the 3.6.4) environment. Pandas is already installed here and so it should work. Post the error you're getting while running that script.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51758419

http://stackoverflow.com/comment/90538194
score: 0
type: Comment
has text: Expected output is the new column (new_col), create another column new_col and make it first value to 1, then consider that 1 for second value of new_col, then consider previous value for third value of new_col, so on.
type: QuestionComment
comment on: http://stackoverflow.com/q/51790351

http://stackoverflow.com/comment/90356435
type: Comment
comment on: http://stackoverflow.com/a/51697385
has text: So am I right to say that copy.deepcopy is slower because it copies each int object, whereas the code in my question doesn't?
type: AnswerComment
score: 0

http://stackoverflow.com/a/51766868
answers question: http://stackoverflow.com/q/51766602
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Yes, I would leave a script in your template lineoee/index.html: &lt;script&gt; setTimeout(function reload() {location.reload()}, 2000) &lt;/script&gt;

http://stackoverflow.com/a/51646260
accepted answer of: http://stackoverflow.com/q/51646055
answers question: http://stackoverflow.com/q/51646055
has body: The 'reshaping problem' stems from a lack of understanding of your own data and prediction goals. LSTMs (and RNNs in general) expect a sequence-of-vectors data structure. Essentially, you want to model some function f(x) where your features are time varying, x=x(t), therefore f(x) may be rewritten as f(t). This is not particularly evident in your sample dataset, as only a small subset of your features (the sales) are time-varying. What you could do would be to consider a single time slice as a vector whose elements are the static features (color, store id, whatever) PLUS a single instance of sales. Then a full sample would be a matrix consisting of N vertically stacked time slices, where N the count of time slices you have. Many instances of these samples would be a batch, i.e. a 3-dimensional tensor which is the expected input of a recurrent network. If you're not just doing this for the sake of experimentation and learning, you should keep in mind that this is a bad approach. Your features do not have any sort of temporal structure and, intuitively, they should not have any predictive potential of next week's sales. Additionally, using a RNN here is an overkill and you will certainly be overfitting your dataset.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90256694
has comment: http://stackoverflow.com/comment/90256792
type: Answer
has comment: http://stackoverflow.com/comment/90258395
score: 2
has comment: http://stackoverflow.com/comment/90256425
upvote count: 2
has comment: http://stackoverflow.com/comment/90908006
has comment: http://stackoverflow.com/comment/90261353

http://stackoverflow.com/comment/90393429
type: Comment
comment on: http://stackoverflow.com/a/51715837
has text: Whoa, thank you very much. I am saving this snippet! This will come in handy for something later on in the process, I used Prune's solution below which barely modifies what I have to make it work. Thanks for your time!
score: 0
type: AnswerComment

http://stackoverflow.com/a/51733793
score: 1
has comment: http://stackoverflow.com/comment/90545362
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90546760
has comment: http://stackoverflow.com/comment/90485825
has body: I think Heroku Scheduler is a better fit here. Based on the log output (specifically, the "State changed from up to crashed"), I think "Process Scheduler" expects your script to stay alive until the scheduler kills it, most likely via a scale API call (noting that the log starts with API calls to scale from 0 to 1 instance) If your script exits on its own, the scheduler thinks it has crashed and tries to restart it. By contrast, Heroku Scheduler expects tasks to run in burst mode - run to completion and exit. Things may get more complicated if you expect your script to take longer than 10 minutes (not a hard limit, but a recommendation in the Scheduler docs) You could stick with Process Scheduler and simply make it so your script never exits - put the call to main() in a while True: loop, with an optional time.sleep() interval that fits your need. The scale call from Process Scheduler will kill the process with a signal. However, you'll be consuming more dyno hours that way vs. the Heroku Scheduler approach.
type: Answer
accepted answer of: http://stackoverflow.com/q/51684413
downvote count: 0
answers question: http://stackoverflow.com/q/51684413

http://stackoverflow.com/q/51684393
score: 0
answer count: 1
has body: I am trying to use the django.contrib.auth views to allow website users to reset their password. However, the email field for users to enter their email address to reset password is not showing. The form tag is showing instead: This is how it looks like screenshot The following is what I have implemented, mainly only changes made in urls.py and templates. How can I solve this error? Thank you. urls.py from django.urls import path, include, re_path from django.contrib.auth import views as authViews urlpatterns = [ re_path(r'^account/password_reset/$', authViews.password_reset, {'template_name' : 'accounts/reset_password.html' }, name='password_reset'), re_path(r'^account/password_reset/done/$', authViews.password_reset_done, {'template_name': 'accounts/reset_password_done.html'}, name='password_reset_done'), re_path(r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', authViews.password_reset_confirm, {'template_name': 'accounts/reset_password_confirm.html'}, name='password_reset_confirm'), re_path(r'^account/reset/done/$', authViews.password_reset_complete, {'template_name': 'accounts/reset_done.html'}, name='password_reset_complete'), ] reset_password.html If you have forgotten your password, please type your email address so we can send you a reset link. {% csrf_token %} {‌{ form | crispy }} Reset Password And the forms.py file is below, although I don't think it's related. Additional information, just in case. forms.py from django import forms from django.forms import ModelForm from .models import Product, Category from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = forms.EmailField(max_length=254, help_text='eg. youremail@anyemail.com') class Meta: model = User fields = ('first_name','last_name','username','passwo…
has title: Django built in auth views for password reset - Form not showing
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: passwords
tagged with: change-password
has answer: http://stackoverflow.com/a/51684641
accepted answer: http://stackoverflow.com/a/51684641
type: Question

http://stackoverflow.com/comment/90389478
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51713790
has text: Yup, JSON is not a valid data type. I wanted to convert it to plain simple Python list where I can perform some operations on it (For example - Sum / concatenate values in JSON, or joining it with other data frame and check equality of attributes) I am trying to avoid using `eval`
type: Comment

http://stackoverflow.com/a/51645016
score: 0
has body: Other than the formatting I'm pretty sure your problem comes from this portion: while count &lt; len(answer): guess = input("please take a guess: ") guess = guess.lower() print (count) count is set to 0 and never changes therefore the while loop will continue on forever.
type: Answer
answers question: http://stackoverflow.com/q/51644786

http://stackoverflow.com/comment/90484994
type: Comment
has text: When i've tried this, with a "print" , it gives me two ids which are 1 and 50 (two iterations) , even if i'm in the form view of the supplier which has the id "50". I don't know why i get the id 1 too!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51752267

http://stackoverflow.com/comment/122601441
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment
comment on: http://stackoverflow.com/a/69363141
score: 0
type: Comment

http://stackoverflow.com/comment/90505862
has text: __A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.__ I feel like the docs suggest that the `ExitStack` solution is perfectly Pythonic.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51649361

http://stackoverflow.com/q/51789837
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/51789919
upvote count: 1
has comment: http://stackoverflow.com/comment/90537158
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51789854
has answer: http://stackoverflow.com/a/51789854
score: 1
has answer: http://stackoverflow.com/a/51789910
type: Question
has comment: http://stackoverflow.com/comment/90537085
has answer: http://stackoverflow.com/a/51789931
accepted answer: http://stackoverflow.com/a/51789910
downvote count: 0
has body: What I have as input: list: [[2, 4], [2, 6], [2, 8]] What I want as output: set: 2,4,6,8 What I'm currently doing(not working): def convert(input_list): all_nums = set([arr[0], arr[1]] for arr in input_list) return all_nums I know I can manually iterate through parent array and add contents of child array to the set like this: def convert(input_list): all_nums = set() for inner_list in input_list: all_nums.add(inner_list[0]) all_nums.add(inner_list[1]) return all_nums How to do do that in pythonic way? In second approach can I do something like all_nums.add(inner_list[0], inner_list[1])?
has answer: http://stackoverflow.com/a/51789920
linked to: http://stackoverflow.com/q/30565759
has comment: http://stackoverflow.com/comment/90537169
has comment: http://stackoverflow.com/comment/90537385
tagged with: python
duplicate of: http://stackoverflow.com/q/30565759
has title: How to convert array of array into set in Python 3?
has comment: http://stackoverflow.com/comment/90537141
favorite count: 0

http://stackoverflow.com/comment/90419900
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51729524
has text: Please *do include* your imports as well!
type: Comment

http://stackoverflow.com/a/51666840
has body: I think need select by loc with tuple, for return one row DataFrame add []: df = df.loc('bar','two') print (df) A B first sec bar two -0.67369 0.113648 Or for Series: s = df.loc[('bar','two')] #alternative #s = df.xs(('bar','two')) print (s) A -0.67369 B 0.113648 Name: (bar, two), dtype: object But if need position by tuple use Index.get_loc: i = df.index.get_loc(('bar','two')) print (i) 1
upvote count: 1
answers question: http://stackoverflow.com/q/51666771
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90407937
comment on: http://stackoverflow.com/q/51723451
score: 0
has text: Good. Now figure out what you want your program to do if that happens. Maybe display an error message?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90507495
type: Comment
comment on: http://stackoverflow.com/a/51774222
type: AnswerComment
score: 0
has text: What do you mean by don't know how far?

http://stackoverflow.com/a/51674360
type: Answer
answers question: http://stackoverflow.com/q/51673541
has comment: http://stackoverflow.com/comment/90312538
has body: I'm going to assume a few things that aren't entirely clear in your question. arr is 2 dimensional with shape: (gridsize, gridsize) i1 i2 and d are all 1 dimensional and the same length Given these conditions you can fairly straightforwardly use numpy's integer array indexing to directly slice arr using i1 and i2 and assign d to the slice: d #data array i1 #first 1D numpy index array i2 #second 1D numpy index array gridsize = 1000 arr = np.zeros((gridsize,gridsize)) arr[i1,i2] = d
has comment: http://stackoverflow.com/comment/90312453
score: 0
has comment: http://stackoverflow.com/comment/90312309
has comment: http://stackoverflow.com/comment/90312364

http://stackoverflow.com/comment/90298258
comment on: http://stackoverflow.com/q/51667703
has text: You should return proper error messages if the `if` conditions were not met.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51711757
has comment: http://stackoverflow.com/comment/90395043
type: Answer
has comment: http://stackoverflow.com/comment/90386008
has body: You can create a nested dictionary with defaultdict, then call list() on its values: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; interface_data = defaultdict(list) &gt;&gt;&gt; for i in s: ... key = i['NodeID'], i['Name'] ... interface_data[key].append(i) &gt;&gt;&gt; list(interface_data.values()) [[{'NodeID': 1563, 'Name': 'GigabitEthernet1/1/1', 'InAveragebps': 0.03555526, 'OutAveragebps': 64.50593, 'DateTime': '2018-05-29T01:10:00.0000000'}, {'NodeID': 1563, 'Name': 'GigabitEthernet1/1/1', 'InAveragebps': 0.04555526, 'OutAveragebps': 6456.50593, 'DateTime': '2018-05-29T01:11:00.0000000'}], [{'NodeID': 1788, 'Name': 'GigabitEthernet2/1/2', 'InAveragebps': 0.03554479, 'OutAveragebps': 64.7012558, 'DateTime': '2018-05-16T01:01:00.0000000'}, {'NodeID': 1788, 'Name': 'GigabitEthernet2/1/2', 'InAveragebps': 0.03555063, 'OutAveragebps': 64.62538, 'DateTime': '2018-05-17T01:011:00.0000000'}]] It is perhaps a bit of a roundabout way to get back to a list result, but ultimately you want to do some type of membership testing (or, more like a lookup, in this case), and a dictionary is well-suited for that in the first place. Before calling list(), interface_data is a nested dictionary; its keys are 2-tuples of (NodeID, Name) and its values are the dictionaries themselves. &gt;&gt;&gt; interface_data.keys() dict_keys([(1563, 'GigabitEthernet1/1/1'), (1788, 'GigabitEthernet2/1/2')])
has comment: http://stackoverflow.com/comment/90409725
accepted answer of: http://stackoverflow.com/q/51711660
has comment: http://stackoverflow.com/comment/90386197
score: 4
has comment: http://stackoverflow.com/comment/90386155
upvote count: 4
has comment: http://stackoverflow.com/comment/90414116
answers question: http://stackoverflow.com/q/51711660
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51739680
has answer: http://stackoverflow.com/a/51741074
has body: e.g. Let's say I have following in tox.ini [tox] envlist = py27, py35, testenv2 [testenv] # settings related to "default" testenv - includes deps, commands [testenv:testenv2] # settings related to testenv2 - includes deps, commands Now when I run tox command, it invokes testenv commands with python 2.7 and 3.5 interpreter but testenv2 commands only with base python installed on the machine (in my case 2.7). How to get tox to also test a "named" (non-default) test environment like testenv2 to be tested with multiple python versions?
type: Question
has answer: http://stackoverflow.com/a/51751134
tagged with: testing
upvote count: 5
accepted answer: http://stackoverflow.com/a/52468970
score: 5
tagged with: tox
downvote count: 0
has answer: http://stackoverflow.com/a/52468970
favorite count: 0
has title: How to get tox to test "named" test environments with different python versions?
possible better answer: http://stackoverflow.com/a/51751134
tagged with: python
has answer: http://stackoverflow.com/a/73867314
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/51731383
downvote count: 1
has comment: http://stackoverflow.com/comment/90423974
has comment: http://stackoverflow.com/comment/90423795
favorite count: 0
possible better answer: http://stackoverflow.com/a/51731618
has body: Let's say I have a class defined by : class Wall(object): def __init__(self, color): self.color = color I would like to keep track automatically of color transitions. That is , if I instanciate my class as follows : wall = Wall('red') and then change color : wall.color = 'green' I would like to automatically get a list ['green', 'red'] created, in a way that if I continue as: wall.color = ['yellow'] I obtain the list : ['yellow', 'green'] and so on. What I have tried so far does not work : class Wall(object): def __init__(self, color): self.color = color self._last_two_colors = [self.color, None] def change_color(self, color): self._last_two_colors[1] = self._last_two_colors[0] self._last_two_colors[0] = self.color return self._last_two_colors My initial version, not working unfortunately : class Wall(object): def __init__(self, color): self._last_two_colors = [] self.color = color @property def last_two_colors(self): return self._last_two_colors @last_two_colors.setter def last_two_colors(self): self._last_two_colors = [self.color]+self._last_two_colors self._last_two_colors = self._last_two_colors[:2] return self._last_two_colors It should be noted that I do not wish to call the method change_color , it would have to be called automatically whenever the color is updated. Any ideas? Thanks in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/90423616
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90423726
has comment: http://stackoverflow.com/comment/90424043
type: Question
has answer: http://stackoverflow.com/a/51731618
has answer: http://stackoverflow.com/a/51731608
accepted answer: http://stackoverflow.com/a/51731608
has comment: http://stackoverflow.com/comment/90423606
score: 0
answer count: 2
has title: Automatically keeping track of attributes' values
upvote count: 1

http://stackoverflow.com/comment/90491869
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51765496
score: 0
has text: I cannot reproduce that error. Which python version are you using?

yaml
tags question: http://stackoverflow.com/q/51654379
tags question: http://stackoverflow.com/q/51757460
tags question: http://stackoverflow.com/q/51650938
tags question: http://stackoverflow.com/q/51789905
tags question: http://stackoverflow.com/q/51783818
tag name: yaml
type: Tag
tags question: http://stackoverflow.com/q/51654373

http://stackoverflow.com/comment/90625878
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51725832
type: Comment
has text: Do be aware that ``populate() isn't reentrant`` error is a subsequent error, and not root cause of problem. You need to find the first error in the logs after processes startup. Not sure if that is what you are referring to as permissions problem. If you are using SQLite, be aware that database file and directory must both be writable to user Apache runs your code as.

http://stackoverflow.com/a/51788497
upvote count: 5
answers question: http://stackoverflow.com/q/51755160
type: Answer
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/96648980
type: AcceptedAnswer
has body: Your numpy arrays (both for inputs and outputs) should contain a batch dimension. If your labels are currently of shape (2,), you can reshape them to include a batch dimension as follows: label_array = label_array.reshape(1, -1)
accepted answer of: http://stackoverflow.com/q/51755160

http://stackoverflow.com/q/51689948
has comment: http://stackoverflow.com/comment/90350905
upvote count: 1
downvote count: 1
has body: I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary. Based on answers to Replacing words in text file using a dictionary and How to search and replace text in a file using Python? As like: # edit print line to print (line) import fileinput text = "sample file.txt" fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"} for line in fileinput.input(text, inplace=True): line = line.rstrip() for field in fields: if field in line: line = line.replace(field, fields[field]) print (line) My file is encoding in utf-8. When I run this, the console shows this error: UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to &lt;undefined&gt; When add: encoding = "utf8" to fileinput.FileInput() its show an error: TypeError: __init__() got an unexpected keyword argument 'encoding' When add: openhook=fileinput.hook_encoded("utf8") to fileinput.FileInput() it show error: ValueError: FileInput cannot use an opening hook in inplace mode I do not want to insert a subcode 'ignore' ignoring errors. I have file, dictionary and want replace values from dictionary into file like stdout. Source file in utf-8: Plain text on the line in the file. This is a greeting to the world. Hello world! Here's another plain text. And here too! I want to replace the word world with the word earth. In dictionary: {"world": "earth"} Modified file in utf-8: Plain text on the line in the file. This is a greeting to the earth. Hello earth! Here's another plain text. And here too!
linked to: http://stackoverflow.com/q/43139174
has comment: http://stackoverflow.com/comment/90350840
has comment: http://stackoverflow.com/comment/90350781
type: Question
has title: Replacing words with a dictionary in text file encoded for example in UTF-8
has answer: http://stackoverflow.com/a/51734513
has comment: http://stackoverflow.com/comment/90341699
tagged with: replace
tagged with: runtime-error
answer count: 2
has comment: http://stackoverflow.com/comment/90350842
has comment: http://stackoverflow.com/comment/90350740
favorite count: 0
has comment: http://stackoverflow.com/comment/90350732
tagged with: file-io
has comment: http://stackoverflow.com/comment/90350864
linked to: http://stackoverflow.com/q/17140886
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51694813
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90350712
score: 0

http://stackoverflow.com/comment/90487497
score: 0
comment on: http://stackoverflow.com/q/51764151
has text: Then don't convert your image to grayscale. You're losing all your colour information! Keep it as RGB/BGR or convert into LUV colour space and just look for pixels that are blue
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90558837
type: Comment
comment on: http://stackoverflow.com/a/51799057
score: 0
type: AnswerComment
has text: @JonClements Thanks a lot. It really helped a lot. Please keeping helping me further. Means a lot.

http://stackoverflow.com/comment/90421755
score: 1
has text: although that works, I think you're getting some downvotes because `range(len(x)-1)` is horribly unpythonic compared to `zip`
type: AnswerComment
comment on: http://stackoverflow.com/a/51729267
type: Comment

http://stackoverflow.com/q/51649079
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51652083
tagged with: memory-management
has title: additional parenthesis when allocating a space
type: AnsweredQuestion
type: Question
has body: I have the following line in a code. I know more or less what it does - allocates some memory for an array of buffers. I am trying to investigate the meaning of the syntax - what are the additional parenthesis used for? The content inside the first parenthesis doesn't look like a function. I saw that the construct of double parentheses is used if one function is embedded in another one, but it still doesn't look like that. Moreover when deleting no_ofBuffers variable (as if it was just 1) does not make a 1 - buffer array, the variable itself is necessary, otherwise in next parts of the code the application crashes. buffers = (ct.POINTER(ct.c_int8*buf_size)*no_ofBuffers)() Does somebody have more experience with constructs like that?
tagged with: ctypes
tagged with: pointers
has answer: http://stackoverflow.com/a/51652083
score: 0

http://stackoverflow.com/a/51686366
answers question: http://stackoverflow.com/q/51686143
score: 14
accepted answer of: http://stackoverflow.com/q/51686143
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90334774
type: Answer
has body: The map iterator doesn't have elements first and second. Instead it has a operator* which returns a pair reference. In C++ you can use it-&gt;first to do this in one go, but that syntax doesn't work in Cython (and it isn't intelligent enough to decide to use -&gt; instead of . itself in this case). Instead you use cython.operator.dereference: from cython.operator cimport dereference # ... print(dereference(it).first) Similarly, it++ can be done with cython.operator.postincrement
upvote count: 14

http://stackoverflow.com/q/51682492
favorite count: 0
has comment: http://stackoverflow.com/comment/90416443
tagged with: python
has body: I'm using the tf.profiler.Profiler trying to get some insight of my model and hopefully to improve its performance. But both of profiler.profile_operations(options=opts) and profiler.profile_name_scope(options)'s output is missing the GPU timing stats. Here is some excerpt of the operation profile's output: Found accelerator operation but misses accelerator stream stats! It's likely a gpu tracing issue rather than tf-profiler issue. If you found your operation missing accelerator time, consider filing a bug to xprof-dev@! Doc: op: The nodes are operation kernel type, such as MatMul, Conv2D. Graph nodes belonging to the same type are aggregated together. requested bytes: The memory requested by the operation, accumulatively. total execution time: Sum of accelerator execution time and cpu execution time. cpu execution time: The time from the start to the end of the operation. It's the sum of actual cpu run time plus the time that it spends waiting if part of computation is launched asynchronously. accelerator execution time: Time spent executing on the accelerator. This is normally measured by the actual hardware library. Profile: node name | requested bytes | total execution time | accelerator execution time | cpu execution time TensorArrayScatterV3 50.66MB (100.00%, 6.21%), 3.49sec (100.00%, 39.64%), 0us (0.00%, 0.00%), 3.49sec (100.00%, 39.64%) LogicalAnd 0B (0.00%, 0.00%), 1.86sec (60.36%, 21.11%), 0us (0.00%, 0.00%), 1.86sec (60.36%, 21.11%) Merge 690.95KB (93.79%, 0.08%), 675.01ms (39.25%, 7.66%), 0us (0.00%, 0.00%), 675.01ms (39.25%, 7.66%) TensorArrayReadV3 0B (0.00%, 0.00%), 487.78ms (31.58%, 5.54%), 0us (0.00%, 0.00%), 487.78ms (31.58%, 5.54%) Less 22.08MB (93.70%, 2.71%), 397.04ms (26.05%, 4.51%), 0us (0.00%, 0.00%), 397.04ms (26.05%, 4.51%) TensorArrayWriteV3 0B (0.00%, 0.00%), 336.87ms (21.54%, 3.82%), 0us (0.00%, 0.00%), 336.87ms (21.54%, 3.82%) Switch 0B (0.00%, 0.00%), 333.95ms (17.71%, 3.79%), 0us (0.00%, 0.00%), 333.95ms (17.71%, 3.79%) Add 1.11KB (9…
score: 2
has title: Why my tf.profiler.Profiler complains "Found accelerator operation but misses accelerator stream stats"
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90653721
downvote count: 0
tagged with: profiler

http://stackoverflow.com/a/51712418
has comment: http://stackoverflow.com/comment/90390719
upvote count: 1
answers question: http://stackoverflow.com/q/51696860
has comment: http://stackoverflow.com/comment/90402916
score: 1
has body: Is there any way to go to the entry_points without entering the command? - You need some event for bot to recognize that it needs to invoke conversation handler. You can make it to react to just any message with a Handler, for example MessageHandler, but then you will need to check a message and decide whether bot in fact needs to continue reacting to it or simply ignore. The problem with it is that bot will do some work for each message user typed. If it is what you want then go for it, otherwise it's just a lot of overhead and that's why it's common to use commands so that bot only reacts to selected message. Is there a way to send all users a message to notify them to enter the command? - Unfortunately bots can not initiate conversations with users, so you will need some other way to do it. /start command is global command in Telegram that indicates to start interaction with a user. From docs: Users will see a Start button when they first open a conversation with your bot. Maybe you can set welcome message in your group by using /setdescription or /setabouttext commands to provide more info if you want.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51709190
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51709405
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: Analyzing data for a member's conversations
type: Question
has body: I have a discord bot that is analyzing the positivity of every user's conversations within a discord server. I want to find a way to add all the results of instances where a user has gotten a rating on their message, and then find their average positivity within say like a period of an hour. here is my code... @bot.event async def on_message(message): if message.author == bot.user: return with open('data.txt', 'a') as f: positivity = {} member = message.author response = requests.post('http://text-processing.com/api/sentiment/', { 'text': message.content }).json() pos = response["probability"]["pos"] positivity[member] = pos for key, value in positivity.items(): print(key, value, file=f) f.close() await bot.process_commands(message) The value for each messages positivity is referenced at... pos = response["probability"]["pos"] So now my only question is how can I pull an individual members total sum of positive ratings of all their messages and then average it out. Just for reference, the for key, value in positivity.items(): print(key, value, file=f) Prints out as something like: EnzoWork#8248 0.46118706992711267 (it is a rating out of a scale of 0-1)
tagged with: discord.py
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51709405
tagged with: python

http://stackoverflow.com/comment/90477849
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51759314
score: 1
has text: @AlistairCarscadden How is that a duplicate? One question is about using `requests` and feeding the result to `pandas`; the other is about using `httplib2`.

http://stackoverflow.com/q/51786039
has answer: http://stackoverflow.com/a/51786180
has answer: http://stackoverflow.com/a/51786191
has answer: http://stackoverflow.com/a/51786370
has answer: http://stackoverflow.com/a/51786452
has answer: http://stackoverflow.com/a/51786227
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51786189
accepted answer: http://stackoverflow.com/a/51786180
tagged with: python
has title: Trouble with tricky Python condition
has comment: http://stackoverflow.com/comment/90529256
answer count: 9
has answer: http://stackoverflow.com/a/51786202
score: 0
has comment: http://stackoverflow.com/comment/90529245
has answer: http://stackoverflow.com/a/51786256
has body: I'm having a little trouble with selecting numbers from two arrays based on a condition. The thing is I can't seem to write the condition in a way that Python understands. The task (school) is to create two vectors with 2000 random numbers uniformly distributed between -10 and 10. import numpy as np x = np.random.uniform(low=-10, high=10, size=2000) y = np.random.uniform(low=-10, high=10, size=2000) The next step is to isolate the x,y co/ordinates (from the vectors x and y) that fulfill the following two conditions: (max(|x|, |y|) > 5) and (sqrt(x^2 + y^2) &lt; 10) For starters, I want to try solving it with a for loop filling in two empty vectors for every time the conditions are true. But the first condition is causing me a lot of trouble. To be precise, I can't seem to find a way to implement this condition: (max(|x|, |y|) > 5) Any help will be greatly appreciated! EDIT: Thanks guys for helping me out. You contributed with some solutions that taught me a lot! As some of you suggested, looping over large data sets is not ideal, but my mind was kind of set on making a loop, since it had failed so many times for me. Anyway, here is the code I ended up going with - including a plot that was also part of the task. Thanks again. import numpy as np import math import matplotlib.pyplot as plt np.random.seed(0) # Same "random" values every time x = np.random.uniform(low=-10, high=10, size=2000) y = np.random.uniform(low=-10, high=10, size=2000) x_matches = [] y_matches = [] for i in range(2000): if (max(abs(x[i]), abs(y[i])) &gt; 5) and (math.sqrt(x[i]**2 + y[i]**2) &lt; 10): x_matches.append(x[i]) y_matches.append(y[i]) # Scatter plot plt.plot(x_matches, y_matches, "bo") # Scatter plot with blue circles plt.title("Exercise 7B Scatter plot") # Set the title of the graph plt.xlabel("x-values") # Set the x-axis label plt.ylabel("y-values") # Set the y-axis label plt.xlim([-10, 10]) # Set the limits of the x-axis plt.ylim([-10, 10]) # Set the limits of the y-axis plt.show()
has answer: http://stackoverflow.com/a/51786222
possible better answer: http://stackoverflow.com/a/51786370
type: AnsweredQuestion

opengl
tags question: http://stackoverflow.com/q/51698806
type: Tag
tags question: http://stackoverflow.com/q/51708980
tags question: http://stackoverflow.com/q/51642339
tags question: http://stackoverflow.com/q/51768385
tag name: opengl

http://stackoverflow.com/a/51688748
answers question: http://stackoverflow.com/q/51688333
has body: Your map statement is correct for a list. Since you have a 2D array, pass each element of your array (a 1D list) to your map &gt;&gt;&gt; arr [[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]] &gt;&gt;&gt; print('\n'.join(" ".join(map("{:.2f}".format, lst)) for lst in arr)) 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 &gt;&gt;&gt;
score: 0
type: Answer

http://stackoverflow.com/q/51758370
has answer: http://stackoverflow.com/a/51758424
has title: Appending a key to a dictionary (Python)
tagged with: python
tagged with: dictionary
tagged with: append
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51758423
accepted answer: http://stackoverflow.com/a/51758424
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51758423
score: -1
answer count: 2
has body: I try to update a key in a dictionary. I use .aapend() method but i get following error: AttributeError: 'str' object has no attribute 'append' Here is the code: class FileOwners: @staticmethod def group_by_owners(files): fileName=[] tempName=[] final={} for i in files: for j in files: if files.get(j) not in tempName: tempName.append(files.get(j)) fileName.append(i) final.update({files.get(j):i}) break else: final.setdefault(files.get(j), []).append(i) return final files = { 'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy' } print(FileOwners.group_by_owners(files))
upvote count: 0
favorite count: 0

http://stackoverflow.com/q/51795074
type: UnansweredQuestion
has title: Django sqlite denied permissions
has answer: http://stackoverflow.com/a/51796118
linked to: http://stackoverflow.com/q/1733050
linked to: http://stackoverflow.com/q/40959337
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90547936
has answer: http://stackoverflow.com/a/54815585
type: Question
has body: I'm trying to run a Django project on my raspberry pi. I'm having some trouble transferring the database that I had on the previous computer though. I tried running the server and everything ran smoothly until I attempted to log in. Django reported that it could read but not write/edit the file. I made sure all the permissions on the db.sqlite3 is set correctly, yet Django still can't modify it. It can only read it. -rwxr-xr-x 1 pi pi 200704 Aug 10 04:13 db.sqlite3 The above code is the permissions I have set for the file. When I try to log in, it also says it can't read or write. Any suggestions to fix this would be appreciated, I can also post other information if needed. Thanks EDIT My settings file for this are (the database part) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } with my base_dir set as BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
score: 0
answer count: 2

http://stackoverflow.com/q/51644524
tagged with: keras
tagged with: lstm
score: 0
tagged with: deep-learning
answer count: 1
has body: My data set is composed of sequences and each time step in a sequence has 4 features. Like so S0: t0 -&gt; f1, f2, f3, f4 t1 -&gt; f1, f2, f3, f4 t2 -&gt; f1, f2, f3, f4 t3 -&gt; f1, f2, f3, f4 S1: t0 -&gt; f1, f2, f3, f4 t1 -&gt; f1, f2, f3, f4 t2 -&gt; f1, f2, f3, f4 t3 -&gt; f1, f2, f3, f4 t4 -&gt; f1, f2, f3, f4 t5 -&gt; f1, f2, f3, f4 t6 -&gt; f1, f2, f3, f4 t7 -&gt; f1, f2, f3, f4 etc... As you see each sequence is variable in length and the variability is large (anywhere from 10-500) My goal is to input t0 and use each prediction to aid in the next prediction and do so until a goal is reached. i0 -&gt; [t0] - predicts &gt; t1 i1 -&gt; [t0, t1] - predicts &gt; t2 i2 -&gt; [t0, t1, t2] - predicts &gt; t3 and so on I'm not sure how to structure my data for training in Keras. I currently have the following for my 'x' [ [[f1, f2, f3, f4], [f1, f2, f3, f4]] , f1, f2, f3, f4 ] ... Questions: How do you handle variable length sequences in Keras? How do I format my 'y' expected output data? Would it be possible to have a start timestep and an end timestep and then fill in timesteps between the two?
accepted answer: http://stackoverflow.com/a/51648771
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/51648771
type: AnsweredQuestion
has title: Keras predict next time series item
type: Question

package
tags question: http://stackoverflow.com/q/51748058
tags question: http://stackoverflow.com/q/51745894
tag name: package
tags question: http://stackoverflow.com/q/51776981
tags question: http://stackoverflow.com/q/51695857
tags question: http://stackoverflow.com/q/51650710
type: Tag
tags question: http://stackoverflow.com/q/51762565
tags question: http://stackoverflow.com/q/51695434
tags question: http://stackoverflow.com/q/51676014
tags question: http://stackoverflow.com/q/51769509
tags question: http://stackoverflow.com/q/51776054
tags question: http://stackoverflow.com/q/51721061
tags question: http://stackoverflow.com/q/51662776
tags question: http://stackoverflow.com/q/51736219
tags question: http://stackoverflow.com/q/51725466

http://stackoverflow.com/comment/90379827
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51709199
type: Comment
has text: It says that [Guild Add Member](https://discordapp.com/developers/docs/resources/guild#add-guild-member) should be used instead, how would I do that?

slider
tags question: http://stackoverflow.com/q/51674388
tags question: http://stackoverflow.com/q/51664545
tag name: slider
type: Tag
tags question: http://stackoverflow.com/q/51785007

http://stackoverflow.com/comment/102990186
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51701040
has text: @CozyAzure, read the PEP, which is the only justification for this change you'll' get. Before this change, `StopIteration` _was_ silently swallowed by generators, as the original generator PEP (255) specified must happen. So the suggested code merely restores the behavior generators had for years.

http://stackoverflow.com/a/51741884
accepted answer of: http://stackoverflow.com/q/51741691
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90443834
type: Answer
score: 2
upvote count: 2
has body: This should work &gt;&gt;&gt; c = b'\xce\xe4\xe8\xed\xf6\xee\xe2\xf1\xea\xe0\xff \xd0\xdd\xd1' &gt;&gt;&gt; c b'\xce\xe4\xe8\xed\xf6\xee\xe2\xf1\xea\xe0\xff \xd0\xdd\xd1' &gt;&gt;&gt; c.decode('unicode_escape') 'Îäèíöîâñêàÿ ÐÝÑ' The b'' prefix denotes sequence of 8-bit bytes. Take a look at SO read russian characters
answers question: http://stackoverflow.com/q/51741691

http://stackoverflow.com/a/53475871
has body: Most attacks in CleverHans do not allow the user to specify which features of the input should be modified. It is however possible to adapt some existing attacks to have this behavior. For instance, in the JSMA attack, you can mask some of the features when computing the saliency maps to have the attack only consider a specific subset of features when constructing the perturbation of the input (a specific subset of pixels in your case). You would have to modify the following snippet of code in the jsma_symbolic function found in cleverhans/attacks_tf.py: # Create a mask to only keep features that match conditions if increase: scores_mask = ((target_sum &gt; 0) &amp; (other_sum &lt; 0)) else: scores_mask = ((target_sum &lt; 0) &amp; (other_sum &gt; 0)) You can also find an example of this type of behavior in the adversarial patch work by Brown et al. where they constrained the perturbation added to an image to create an adversarial example to be a small patch in the image: https://github.com/tensorflow/cleverhans/tree/master/examples/adversarial_patch
has comment: http://stackoverflow.com/comment/93879152
has comment: http://stackoverflow.com/comment/93839911
upvote count: 1
has comment: http://stackoverflow.com/comment/93879203
answers question: http://stackoverflow.com/q/51679955
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/93921801

http://stackoverflow.com/comment/90437956
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51738699
has text: While this question may not be an exact duplicate of the linked question, it's not one I'm willing to vote to reopen because you haven't show us any effort to solve the problem on your own. Asking Stack Overflow to answer your homework for you is cheating yourself out of a chance to learn how Python works (and may also be cheating in a more literal sense according to the rules of your school). Make an attempt to solve the problem on your own, and then if you run into a specific problem, ask us about that instead of just dropping the assignment on us. (It may even allowed by your instructors!)

http://stackoverflow.com/a/51700995
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90408576
has comment: http://stackoverflow.com/comment/90426378
score: 2
has comment: http://stackoverflow.com/comment/90426159
has comment: http://stackoverflow.com/comment/90364244
has comment: http://stackoverflow.com/comment/90412609
accepted answer of: http://stackoverflow.com/q/51700876
has body: In python strings are iterables. So, your line for i in s will run n times, one for every letter in the string, and will print "not found". The first time the loop runs, it replaces a with*. So, for all subsequent runs, it will print "not found". If I understand what you are trying to do, it would be something like first_letter = s[0] rest_string = s[1:].replace(first_letter, '*') new_string = first_letter + rest_string
answers question: http://stackoverflow.com/q/51700876
has comment: http://stackoverflow.com/comment/90420301
type: AcceptedAnswer

http://stackoverflow.com/comment/90390007
type: QuestionComment
score: 2
has text: What is the purpose of this generator? Why is it a generator at all? It's rather unusual to have a generator where you don't use the yielded values *or* `send` values in.
comment on: http://stackoverflow.com/q/51714251
type: Comment

http://stackoverflow.com/a/51782326
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90523851
has comment: http://stackoverflow.com/comment/90522271
has comment: http://stackoverflow.com/comment/90522892
upvote count: 2
has comment: http://stackoverflow.com/comment/90522662
answers question: http://stackoverflow.com/q/51781985
type: Answer
accepted answer of: http://stackoverflow.com/q/51781985
score: 2
has comment: http://stackoverflow.com/comment/90524570
downvote count: 0
has body: There are several problems: Do not use _ as a variable name it's for variables you won't reuse. You are getting this problem because of this line: p.extend(L for _ in range(10)) p is a list of references to L. So when you do: p[_][i] = (_+1)*p[_][i] you modify L, and thus all the lists in p. Your code fixed: p = [] p.extend(list(range(1,11)) for _ in range(10)) for i in range(10): for j in range(10): p[i][j] = (i+1)*p[i][j] print(p) However, there is a simpler way to do it: p = [ list(range(i, i*11, i )) for i in range(1,10)]
has comment: http://stackoverflow.com/comment/90526830
has comment: http://stackoverflow.com/comment/90524471

http://stackoverflow.com/comment/90292975
type: AnswerComment
comment on: http://stackoverflow.com/a/51664849
type: Comment
has text: Oh well. But they seem to work when the same is deployed using the inline code editor. Any idea when this would be supported. I know as you say there is no commitments and timelines, but i felt this is a basic feature which seems missing
score: 0

http://stackoverflow.com/a/51678586
type: Answer
accepted answer of: http://stackoverflow.com/q/51678585
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: A solution to prevent these false positives, via pylint plugins: pylintplugins.py import sys from astroid import MANAGER, scoped_nodes, extract_node from astroid.builder import AstroidBuilder def register(_linter): pass def transform(f): if f.name == 'logger': for prop in ['debug', 'info', 'warning', 'error', 'addHandler']: f.instance_attrs[prop] = extract_node('def {name}(arg): return'.format(name=prop)) MANAGER.register_transform(scoped_nodes.FunctionDef, transform) This workaround prevents linting errors on app.logger.debug, app.logger.info, app.logger.warning, app.logger.error and app.logger.addHandler. In order to be used, the pylintplugins.py file needs to be loaded using the --load-plugins command line option: PYTHONPATH="." pylint -E app --load-plugins pylintplugins or by including the following line in the pylintrc configuration file: load-plugins=pylintplugins
answers question: http://stackoverflow.com/q/51678585

http://stackoverflow.com/q/51763447
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Partitioned Observable second stream never reached
has answer: http://stackoverflow.com/a/52936623
accepted answer: http://stackoverflow.com/a/52936623
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: reactive-programming
tagged with: rx-py
has body: I have an Observable handling a web request, where I want to handle a success or failure in separate streams, very similar to this example. The main difference between my script and the example is that I do not want merge the streams and then subscribe. I'm using RxPY 1.6.1 with Python 2.7. request = Observable.of(requests.get(self.URL, params=request_params)) request_success, request_failed = request.partition(lambda r: r.status_code == requests.codes.ok) request_failed.subscribe(lambda r: print_msg('failure!')) request_success.subscribe(lambda r: print_msg('success!')) When the request fails, the script prints failure! as expected. However, when the response is OK, the script does not print success!. Interestingly, when you switch around the order of the subscriptions, success! does get printed, while failure! is never reached instead. I figured maybe request could not be multicasted, so I tried adding publish() to the request observable and calling connect() after creating the subscriptions. That did not help (so I left it out of my minimal example above). What am I missing?

http://stackoverflow.com/q/51749235
favorite count: 0
has body: I am working with a pandas DataFrame looking as follows: df = pd.DataFrame( [['There are # people', '3', np.nan], ['# out of # people are there', 'Five', 'eight'], ['Only # are here', '2', np.nan], ['The rest is at home', np.nan, np.nan]]) resulting in: 0 1 2 0 There are # people 3 NaN 1 # out of # people are there Five eight 2 Only # are here 2 NaN 3 The rest is at home NaN NaN I would like to replace the # placeholders with the varying strings in columns 1 and 2, resulting in: 0 There are 3 people 1 Five out of eight people are there 2 Only 2 are here 3 The rest is at home How could I achieve this?
possible better answer: http://stackoverflow.com/a/51749557
has answer: http://stackoverflow.com/a/51749503
answer count: 3
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51749503
score: 2
upvote count: 2
tagged with: string-formatting
type: Question
type: AnsweredQuestion
has title: Pandas: filling placeholders in string column
has answer: http://stackoverflow.com/a/51749557
downvote count: 0
has answer: http://stackoverflow.com/a/51749472

http://stackoverflow.com/a/51769046
has body: You can use GroupBy + cumcount followed by pd.Series.where: df['C'] = df.groupby('B').cumcount() + 1 df['C'].where(df['B'] == 'yes', 0, inplace=True) print(df) A B C 0 Tony no 0 1 Mike yes 1 2 Jen no 0 3 Anna yes 2
has comment: http://stackoverflow.com/comment/115038762
answers question: http://stackoverflow.com/q/51768947
upvote count: 3
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/a/51665835
has body: You can split the items in each line into frozensets and put them into a set for each file, so that you can use set.difference to obtain what isn't in child.txt efficiently: print(' '.join({frozenset(l.split()) for l in open("master.txt")} - {frozenset(l.split()) for l in open("child.txt")}))
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90294954
score: 1
answers question: http://stackoverflow.com/q/51665542

http://stackoverflow.com/a/51790601
score: 10
upvote count: 10
has body: They don't return lists or sets; they return views. Key views are set-like, and item views are set-like as long as the values are hashable, but value views cannot be set-like, as there can be duplicate values. Before Python 3, they returned lists, but those methods predated the introduction of sets. Sets were introduced in Python 2.4, while keys/values/items have been around since at least 1.4, and probably before 1.0.
answers question: http://stackoverflow.com/q/51790555
type: Answer
has comment: http://stackoverflow.com/comment/90573045
downvote count: 0

http://stackoverflow.com/q/51656818
has comment: http://stackoverflow.com/comment/90278558
has comment: http://stackoverflow.com/comment/90280506
has comment: http://stackoverflow.com/comment/90279433
tagged with: eigen
has comment: http://stackoverflow.com/comment/90278091
has comment: http://stackoverflow.com/comment/90279263
has comment: http://stackoverflow.com/comment/90279458
has comment: http://stackoverflow.com/comment/90278028
has comment: http://stackoverflow.com/comment/90278044
has comment: http://stackoverflow.com/comment/90280838
has comment: http://stackoverflow.com/comment/90286208
has comment: http://stackoverflow.com/comment/90280876
type: Question
has comment: http://stackoverflow.com/comment/90279386
upvote count: 9
has title: Benchmarking matrix multiplication performance: C++ (eigen) is much slower than Python
linked to: http://stackoverflow.com/q/25100079
has comment: http://stackoverflow.com/comment/90279388
has answer: http://stackoverflow.com/a/51675509
has comment: http://stackoverflow.com/comment/90280607
has comment: http://stackoverflow.com/comment/90282865
has comment: http://stackoverflow.com/comment/90278435
tagged with: numpy
tagged with: benchmarking
has comment: http://stackoverflow.com/comment/90279572
answer count: 1
has comment: http://stackoverflow.com/comment/90279978
downvote count: 0
has comment: http://stackoverflow.com/comment/90279614
has comment: http://stackoverflow.com/comment/90278170
has comment: http://stackoverflow.com/comment/90277729
has comment: http://stackoverflow.com/comment/90278262
has comment: http://stackoverflow.com/comment/90277793
has comment: http://stackoverflow.com/comment/90280532
favorite count: 0
has comment: http://stackoverflow.com/comment/90277846
has comment: http://stackoverflow.com/comment/90279496
has comment: http://stackoverflow.com/comment/90314218
has comment: http://stackoverflow.com/comment/90278128
score: 9
has comment: http://stackoverflow.com/comment/90279115
accepted answer: http://stackoverflow.com/a/51675509
has comment: http://stackoverflow.com/comment/90314543
tagged with: python
has body: I am trying to estimate how good is Python performance comparing to C++. Here is my Python code: a=np.random.rand(1000,1000) #type is automaically float64 b=np.random.rand(1000,1000) c=np.empty((1000,1000),dtype='float64') %timeit a.dot(b,out=c) #15.5 ms ± 560 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) And here is my C++ code that I compile with Xcode in release regime: #include &lt;iostream&gt; #include &lt;Dense&gt; #include &lt;time.h&gt; using namespace Eigen; using namespace std; int main(int argc, const char * argv[]) { //RNG generator unsigned int seed = clock(); srand(seed); int Msize=1000, Nloops=10; MatrixXd m1=MatrixXd::Random(Msize,Msize); MatrixXd m2=MatrixXd::Random(Msize,Msize); MatrixXd m3=MatrixXd::Random(Msize,Msize); cout &lt;&lt; "Starting matrix multiplication test with " &lt;&lt; Msize &lt;&lt; "matrices" &lt;&lt; endl; clock_t start=clock(); for (int i=0; i&lt;Nloops; i++) m3=m1*m2; start = clock() - start; cout &lt;&lt; "time elapsed for 1 multiplication: " &lt;&lt; start / ((double) CLOCKS_PER_SEC * (double) Nloops) &lt;&lt; " seconds" &lt;&lt;endl; return 0; } And the result is: Starting matrix multiplication test with 1000matrices time elapsed for 1 multiplication: 0.148856 seconds Program ended with exit code: 0 Which means that C++ program is 10 times slower. Alternatively, I've tried to compile cpp code in MAC terminal: g++ -std=c++11 -I/usr/local/Cellar/eigen/3.3.5/include/eigen3/eigen main.cpp -o my_exec -O3 ./my_exec Starting matrix multiplication test with 1000matrices time elapsed for 1 multiplication: 0.150432 seconds I am aware of very similar question, however, it looks like there the issue was in matrix definitions. In my example I've used default eigen functions to create matrices from uniform distribution. Thanks, Mikhail Edit: I found out, that while numpy uses multithreading, Eigen does not use multiple threads by default (checked by Eigen::nbThreads() function). As suggested, I used -march=native option which…
has comment: http://stackoverflow.com/comment/90277306
has comment: http://stackoverflow.com/comment/90277934
tagged with: c++
type: AnsweredQuestion

http://stackoverflow.com/a/51732050
type: Answer
has body: def compute_precent(row): return(float(row[1]-row[0])/row[0]) df['percentage_change']=df.apply(lambda x:compute_precent(x),axis=1)
answers question: http://stackoverflow.com/q/51731947
has comment: http://stackoverflow.com/comment/90424948
score: 0

http://stackoverflow.com/a/51789910
has comment: http://stackoverflow.com/comment/90537426
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90538014
has body: Simply: my_list = [[2, 4], [2, 6], [2, 8]] my_set = {e for l in my_list for e in l} This is using a "set comprehension", which is a squashed down version of: my_list = [[2, 4], [2, 6], [2, 8]] my_set = set() for l in my_list: for e in l: my_set.add(e) Alternatively, you could do: my_list = [[2, 4], [2, 6], [2, 8]] my_set = set() for l in my_list: my_set.update(l) (Variable names shamelessly stolen from modesitt.)
type: Answer
has comment: http://stackoverflow.com/comment/90538426
downvote count: 0
has comment: http://stackoverflow.com/comment/90538461
score: 6
has comment: http://stackoverflow.com/comment/90538291
upvote count: 6
answers question: http://stackoverflow.com/q/51789837
has comment: http://stackoverflow.com/comment/90537351
accepted answer of: http://stackoverflow.com/q/51789837

http://stackoverflow.com/a/51735734
has comment: http://stackoverflow.com/comment/90433239
score: 2
answers question: http://stackoverflow.com/q/51735660
downvote count: 0
has body: You haven't told Perl your script is saved in UTF-8. Just add use utf8; somewhere near the beginning of the script (best place is right after use strict; and use warnings;). See utf8.
upvote count: 2
has comment: http://stackoverflow.com/comment/90433774
type: Answer

http://stackoverflow.com/comment/90391446
type: Comment
comment on: http://stackoverflow.com/q/51714885
type: QuestionComment
has text: You need to upgrade your `pip` to at least 10.0.1 (also `setuptools` to at least… I think 30.0.0, but I'm not sure). You can do this by reinstalling them from scratch, or, more simply, by running `pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip setuptools`.
score: 0

http://stackoverflow.com/comment/90334417
type: Comment
score: 0
has text: Sure, why not. I added a slightly less trivial example.
type: AnswerComment
comment on: http://stackoverflow.com/a/51686034

http://stackoverflow.com/a/54086444
type: Answer
has body: Some additions to @Sunitha answer, the first time formatting is {}, second is {{}}, the third time is not {{{}}}, but it is {{{{}}}}. Four curly braces, because every time you format, the curly braces will be reduced for every place.
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51727274

http://stackoverflow.com/comment/90417677
type: QuestionComment
has text: @DanielMöller Different models as a result. I don't know if the order of training samples is different. But as the set of training samples is the same and the initial model is the same, and the training algorithm is the same, I think it has to be the order of training samples, right? With this question I only want to see it so that I can make sure I'm at the right point
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51728071

http://stackoverflow.com/a/51691111
has comment: http://stackoverflow.com/comment/90343923
downvote count: 0
answers question: http://stackoverflow.com/q/51690935
has body: read_count = 0 largest_odd = None while read_count &lt; 10: user_input = input('Enter any number') try: user_input = int(input('Enter a number')) except ValueError: print("user input {} is not a number".format(user_input)) continue if user_input &amp; 1: if largest_odd is None: largest_odd = user_input largest_odd = max(largest_odd, user_input) read_count += 1 if largest_odd is None: print("No odd numbers found") else: print("Largest odd number found was {}".format(largest_odd)) Now let's dissect that a little bit, we declared variables read_count and largest_odd to track how many numbers we've seen and what the largest odd was. Note, I specifically chose, to make largest_odd = None in the case where we don't see an odd number. Next, we loop until the user has entered a valid number 10 times. The try-catch logic is overkill for you sake but it helps protect the program from crashing because of bad input from the user. Try opening up a Python shell and running int('x'). You'll see why I want to catch a ValueError after doing that. At first, the line if user_input &amp; 1 might be confusing but it's a very quick way to determine if a number is odd or not. Of course, you could do user_input % 2 == 1 but all you really need to check is if the first (Least Significant Bit or LSB) is set which we do by using a bitwise AND with the number 1.
accepted answer of: http://stackoverflow.com/q/51690935
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90404510
type: Comment
has text: This creates a similar password, but will not draw them from the same distribution as the OP's current logic. Not that I think the OP cares, I'm just a pedant. :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51721979

http://stackoverflow.com/q/51681966
has comment: http://stackoverflow.com/comment/90326930
has title: Are tuples faster than list because they are hashable?
has comment: http://stackoverflow.com/comment/90326962
downvote count: 4
has comment: http://stackoverflow.com/comment/90327047
answer count: 1
has body: My teacher says that tuples are faster than lists because tuples are immutable, but I don't understand the reason. I personally think that tuples are faster than lists because tuples are hashable and lists are not hashable. Please tell me if I am right or wrong.
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90326916
type: Question
has comment: http://stackoverflow.com/comment/90327033
has answer: http://stackoverflow.com/a/51682052
accepted answer: http://stackoverflow.com/a/51682052
score: -2

http://stackoverflow.com/q/51767644
type: AnsweredQuestion
has body: I am having trouble merging these two dataframes to give the expected results. I would like to check both dataframes and if column 1 and 3 of dataframe 1 match column 0 and 2 of dataframe 2 then return the last dataframe. df1 0 1 2 3 4 5 4 4133 43 192.168.0.1 dt1 default 5 4134 43 192.168.0.2 dt2 t2 6 4135 43 192.168.0.3 dt3 t3 df2 0 1 2 3 4 5 4134 43 192.168.0.2 dt2 t2 4136 43 192.168.0.4 dt4 default 4137 43 192.168.0.5 dt5 default result 0 1 2 3 4 5 5 4134 43 192.168.0.2 dt2 t2
type: Question
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51767838
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51767843
has answer: http://stackoverflow.com/a/51767843
has title: joining two panda dataframes
tagged with: python
accepted answer: http://stackoverflow.com/a/51767838

http://stackoverflow.com/comment/121818853
type: QuestionComment
comment on: http://stackoverflow.com/q/51666361
has text: @cjm You *can* do that, but I expect that you'll find it annoying to not be able to use the normal syntax to set & get your class attributes. But do you really need classes for this? Why not just use dicts & lists, like you'd use If you were loading data from JSON?
score: 0
type: Comment

http://stackoverflow.com/q/51774885
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/51775342
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90508591
has answer: http://stackoverflow.com/a/51775342
tagged with: python
has body: I want to scrape through the loop and output a list of lists but the error I keep getting is "list index is out of range" or "'list' object cannot be interpreted as an integer" #BEGIN LOOP SCRAPE studentIDs=[1,2,3] for i, val in enumerate(studentIDs): #Begin scraping out_data=[pd.read_html(browser.page_source)] #Clicking to another student webpage browser.find_element_by_xpath('returns to another page that needs to be scraped').click()
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90508620
tagged with: loops
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/90508880
type: Question
has comment: http://stackoverflow.com/comment/90508923
has title: How to scrape lists into a list pandas

http://stackoverflow.com/q/51736043
possible better answer: http://stackoverflow.com/a/51736127
has body: I used to be a heavy R programmer and really used to the Rstudio's "highlight and run" feature. I just wonder if there any python IDE that has similar feature that allows you to select part of the code in a script and run and show the results in a console?
has answer: http://stackoverflow.com/a/51736127
tagged with: ide
has comment: http://stackoverflow.com/comment/90472839
tagged with: http://stackoverflow.com/tag/r
has title: Is there any python IDE that supports "highlight and run"?
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51736200
linked to: http://stackoverflow.com/q/25669809
tagged with: rstudio
tagged with: python
has answer: http://stackoverflow.com/a/51736200
type: AnsweredQuestion
upvote count: 0
score: -1
type: Question
answer count: 2

http://stackoverflow.com/comment/90410517
comment on: http://stackoverflow.com/q/51724962
has text: @MadhanVaradhodiyil it reads all the td tags, since the file doesn't have separate blocks.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51640004
type: Answer
score: 3
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/90249427
has body: Use stack for MultiIndex Series with to_dict: d = df.stack().to_dict() print (d) {(0, 1): 1, (0, 2): 2, (0, 3): 3, (1, 1): 4, (1, 2): 5, (1, 3): 6, (2, 1): 7, (2, 2): 8, (2, 3): 9} But if want tuples: s = df.stack() L = list(zip(s.index.tolist(), s)) print (L) [((0, 1), 1), ((0, 2), 2), ((0, 3), 3), ((1, 1), 4), ((1, 2), 5), ((1, 3), 6), ((2, 1), 7), ((2, 2), 8), ((2, 3), 9)]
accepted answer of: http://stackoverflow.com/q/51639984
downvote count: 0
answers question: http://stackoverflow.com/q/51639984

http://stackoverflow.com/a/70081053
type: Answer
answers question: http://stackoverflow.com/q/51699443
has body: I found a way to do it, actually: The plan is to create a macro in a second presentation that you call from within python and that is, with the help of tlbinf32.dll, able to get all members of an object. The Second Presentation To start, you want to download the tlbinf32.dll. FOR 64-bit SYSTEMS: Follow this guide to properly set up the 32-bit-DLL! I also had problems with the HP Print Scan Doctor Service: I needed to disable that service and uninstall HP Smart. (and reboot) Create a new .pptm file (pptx with macros) and open it (I named it GetMembersUtil.pptm) In that presentation, create a new macro (the name is irrelevant) and edit it (View->Macros) Add a reference to your tlbinf32.dll that you just downloaded (Tools->References) Paste the following function after the macro Function GetMembers(obj) ' Declare vars Dim TLI Dim TypeInfo Dim Members ' Create new ArrayList since we don't know how many Members obj has Set Members = CreateObject("System.Collections.ArrayList") ' Initialize tlbinf Set TLI = CreateObject("TLI.TLIApplication") Set TypeInfo = TLI.InterfaceInfoFromObject(obj) ' iterate over each Member For Each MemberInfo In TypeInfo.Members Members.Add MemberInfo.Name Next ' Convert ArrayList back to native vba Array because you can't return an ArrayList GetMembers = Members.ToArray() End Function this function takes an object as input and returns all the members of that object Save your presentation in the local directory of your python file The Python Side To be able to use the macro we need to make sure that the presentation we just created is openend def vba_get_members(app: win32com.client.CDispatch, obj: win32com.client.CDispatch) -> tuple[str, ...]: # os.path.abspath is very important ensure_opened(app, os.path.abspath("GetMembersUtil.pptm")) return app.Run("GetMembersUtil.pptm!GetMembers", obj) def ensure_opened(app: win32com.client.CDispatch, file_path): # check if presentation is already opened for presentation in app.Presentations: pp_filepath = o…
score: 0

http://stackoverflow.com/a/51722304
score: 0
answers question: http://stackoverflow.com/q/51722146
type: Answer
has body: I believe the func needs to return the jobs_to_delete value. The shortest (2 lines) way i can think of is: jobs_to_delete = AsyncJob.objects.filter(created_at__lte=date_to_delete_from) return jobs_to_delete.filter(name=job_name) if job_name else jobs_to_delete This way you use an 'inline' if statement that would shorten the code written and keep everything readable and simple
has comment: http://stackoverflow.com/comment/90405775

http://stackoverflow.com/comment/90538831
type: Comment
type: QuestionComment
score: 1
has text: Does it work for you? I have tested it and it's working as expected.
comment on: http://stackoverflow.com/q/51789543

http://stackoverflow.com/comment/90306081
comment on: http://stackoverflow.com/a/51657992
score: 1
type: AnswerComment
type: Comment
has text: @root-11 It's covered quite well, I think, in the [official Python tutorial](https://docs.python.org/3/tutorial/classes.html#iterators) and also briefly in the [documentation for standard types](https://docs.python.org/3/library/stdtypes.html#typeiter); finding the right documentation can sometimes be surprisingly hard. I personally like to re-read, or at least browse through, the official Python tutorial every few years - I pick up something new every time, either because I simply missed some detail the previous times or because new features were introduced in the meantime.

http://stackoverflow.com/comment/90565968
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51795811
has text: I did it and I still can't see the traceback messages. It looks like this: * Serving Flask-SocketIO app "main.py" * Forcing debug mode on * Restarting with stat * Debugger is active! * Debugger PIN: 399-480-796 127.0.0.1 - - [2018-08-12 04:55:32] "POST / HTTP/1.1" 405 323 0.001283 127.0.0.1 - - [2018-08-12 04:55:51] "POST / HTTP/1.1" 405 323 0.001800
type: AnswerComment

http://stackoverflow.com/comment/90532693
has text: I would accept [@chris's answer](https://stackoverflow.com/a/51787013/1126841) instead, as it delays the call to `int` until you have an input you know won't raise an exception.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51786992

http://stackoverflow.com/a/51642766
answers question: http://stackoverflow.com/q/51642699
has body: This should do it: df.drop(to_remove.column_name, axis=1, inplace=True)
score: 0
type: Answer

http://stackoverflow.com/q/51729217
upvote count: 2
has title: Partitioning a list into sublists with offset 1
has comment: http://stackoverflow.com/comment/90419159
tagged with: python
has comment: http://stackoverflow.com/comment/90419253
linked to: http://stackoverflow.com/q/21303224
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/51710490
has answer: http://stackoverflow.com/a/51729287
score: 1
has comment: http://stackoverflow.com/comment/90419202
downvote count: 1
has answer: http://stackoverflow.com/a/51729267
type: Question
has body: I have the following list: x=["A", "B", "B", "C", "B", "A", "D", "D", "A", "B", "A", "D"] I wonder how does one partition into sublists of length 2 with offset 1 such that one gets: #[["A", "B"], ["B", "B"], ["B", "C"], ["C", "B"], ["B", "A"], ["A", # "D"], ["D", "D"], ["D", "A"], ["A", "B"], ["B", "A"], ["A", "D"]] Also is there a generalised method for this? For example for different size of partition and different offsets? Suppose I want to partition into sublists of 3 with offset 2: for which I'd get #[["A", "B", "B"], ["B", "C", "B"], ["B", "A", "D"], ["D", "D", # "A"], ["A", "B", "A"]] Is it possible to write this as a function, so for a given list, with given partition size and given number of offset it finds the sublists?
possible better answer: http://stackoverflow.com/a/51729287
has comment: http://stackoverflow.com/comment/90419364
tagged with: arrays
has comment: http://stackoverflow.com/comment/90419212
answer count: 2
has comment: http://stackoverflow.com/comment/90419940
accepted answer: http://stackoverflow.com/a/51729267
favorite count: 0

http://stackoverflow.com/comment/90379649
type: Comment
has text: Two things I don't like about this. One: by using `[[3]]` to define `c` you make it necessary to use `all()` later on to reduce the dimensions of `(1, n)` to `(n,)`. Two: Though it's clever that the definition of `c` contains the index information `3` which provides a convenience when using `loc` in the second line, it also makes it confusing if you aren't intimately aware of how the indexing will resolve. My two cents. Still a good answer (-:
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51708678

http://stackoverflow.com/comment/90368657
type: Comment
type: QuestionComment
has text: Please provide a minimal, complete and reproducible example for your problem. Check https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/51703860
score: 0

http://stackoverflow.com/q/51676804
tagged with: css
type: UnansweredQuestion
has title: Selecting inner text when using find element by css selector python, selenium and create a loop
tagged with: selenium
upvote count: 1
type: Question
has body: im trying to get all link text from a tag p and with a specific class. Then create a loop to find all other similar elements. how it looks so far i am using this : the value i want is in &lt;div class='some other class'&gt; &lt;p class='machine-name install-info-entry x-hidden-focus'&gt; text i want &lt;/p&gt; ==$0 installations = browser.find_elements_by_css_selector('p.machine-name.install-info-entry.x-hidden-focus') any help is appreciated. thanks.
has answer: http://stackoverflow.com/a/51677047
tagged with: find
downvote count: 0
has comment: http://stackoverflow.com/comment/90317203
answer count: 1
has comment: http://stackoverflow.com/comment/90317678
score: 1
favorite count: 0
tagged with: element
tagged with: python

http://stackoverflow.com/comment/90267958
type: QuestionComment
has text: Ok everything should now be correct and clear
comment on: http://stackoverflow.com/q/51650641
score: 0
type: Comment

http://stackoverflow.com/comment/90512780
type: QuestionComment
has text: Hi userP520, it's much easier for us to help you if write the error you received into the body of the question (with a strong preference towards using "code markdown" where appropriate) instead of posting a picture
score: 1
comment on: http://stackoverflow.com/q/51777232
type: Comment

http://stackoverflow.com/comment/90527925
type: AnswerComment
comment on: http://stackoverflow.com/a/51785357
type: Comment
has text: @ascii_walker: clearly, the emoji package doesn't see it as an emoji; if you paired it up with a supporting emoji, it would be removed. `` for example, is removed as that's a pairing of U+1F91F U+1F3FC, which is how the pattern is to be used.
score: 1

http://stackoverflow.com/a/51745109
answers question: http://stackoverflow.com/q/51742871
score: 4
has comment: http://stackoverflow.com/comment/126607778
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: If we start by analyzing the postscript contents, we see that it does a scaling by 0.7498 to the dimensions of your canvas %%Page: 1 1 save 306.0 396.0 translate 0.7498 0.7498 scale 3 -241 translate -244 483 moveto 239 483 lineto 239 0 lineto -244 0 lineto closepath clip newpath gsave grestore gsave 0 239 moveto 0 339 lineto 1 setlinecap 1 setlinejoin 1 setlinewidth [] 0 setdash 0.000 0.000 0.000 setrgbcolor AdjustColor stroke grestore gsave grestore gsave 0 339 moveto -5 330 lineto 0 332 lineto 5 330 lineto 0 339 lineto 0.000 0.000 0.000 setrgbcolor AdjustColor eofill 0 339 moveto -5 330 lineto 0 332 lineto 5 330 lineto 0 339 lineto 1 setlinejoin 1 setlinecap 1 setlinewidth [] 0 setdash 0.000 0.000 0.000 setrgbcolor AdjustColor stroke grestore restore showpage After some digging done on postscript I came across a perl/Tk reference guide on postscript conversion from tkinter's canvas here What you actually can do is to set not only colormode but also pagewidth/pageheight. This resulted in the following line being changed from ps = cv.postscript(colormode='mono') to ps = cv.postscript(colormode='mono', pagewidth=wd-1, pageheight=ht-1) Result: If you have any questions feel free to leave a comment and I will try my best to reply! PS: Don't ask me about the -1 part, it wouldn't give me anything other that 501x501 pixels so I compensated for that. I do not know why it still didn't work though.
type: Answer
accepted answer of: http://stackoverflow.com/q/51742871

http://stackoverflow.com/comment/90554906
has text: Good point, unfortunately, there is not form builders for wxErlang. But it still could be better rewrite GUI with wxErlang than use port, especially if GUI isn't big.
comment on: http://stackoverflow.com/q/51754172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51645086
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90255138
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/90254933
has answer: http://stackoverflow.com/a/51645210
has comment: http://stackoverflow.com/comment/90254691
type: Question
has body: windows 7 python 2.7 when I use popen to open a process： from ctypes import * dldtool = cdll.LoadLibrary(r'main.dll') cmd = "dld_tool -c {} -r programmer.bin -f {}".format(port,file) print cmd with LOCK: process = Popen(cmd, stdout=PIPE) while process.poll() is None: out = process.stdout.readline() if out != '': print out error occurs： process = Popen(cmd, stdout=PIPE) File "C:\Python27\lib\subprocess.py", line 390, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 640, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified The main.dll is in the working directory. should I change the code in python or change the any config?
has comment: http://stackoverflow.com/comment/90254195
score: 0
has comment: http://stackoverflow.com/comment/90254258
has title: using popen shows WindowsError: [Error 2] The system cannot find the file specified
answer count: 1
has comment: http://stackoverflow.com/comment/90254221

http://stackoverflow.com/comment/90431079
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51734500
has text: Are your zeros strings or integers..

http://stackoverflow.com/comment/113822250
type: Comment
comment on: http://stackoverflow.com/a/51716940
has text: ^^ Also, the import time might be expensive. It's generally advisable to pay the cost at module import time rather than function call.
score: 3
type: AnswerComment

http://stackoverflow.com/q/51661907
has answer: http://stackoverflow.com/a/51663202
has title: How to generate HTML file from Excel file, or parse excel graph into python?
has body: I have a lot of reports in Excel form, that I want to change into html. So, I can have live graph. Currently I am using python jinja2 template to build the HTML, but I was wondering if there is any other easier way to build HTML from Excel. Also I want wondering if you can parse excel graph into python ! I tried to: Import pandas as pd file_link = r"C:\Users\XXX\Desktop\Primire HT ML output testing\Panasonic BR2330 html.xlsx" data_file = pd.ExcelFile(file_link) chartAt24C = data_file.parse(sheet_name="VVC") print(chartAt24C) It's throwing me error: xlrd.biffh.XLRDError: No sheet named &lt;'VVC'&gt; This is the graph I want to parse into python:
type: UnansweredQuestion
type: Question
tagged with: http://stackoverflow.com/tag/html
score: 0
tagged with: python
answer count: 1
tagged with: excel

http://stackoverflow.com/comment/90453015
type: Comment
comment on: http://stackoverflow.com/a/51745493
score: 0
type: AnswerComment
has text: What's problem now?

http://stackoverflow.com/a/51785016
answers question: http://stackoverflow.com/q/51781864
accepted answer of: http://stackoverflow.com/q/51781864
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: The problem was with... xx = MinutenWert() for x in xx: print x It returns None because the Yield isn't called. To get Yield values one have to use next(). The updated version.... xx = Minutenwert() while 1: y = next(xx) print y returns the values and doesn't give back an error.

http://stackoverflow.com/comment/90358265
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51697262
has text: Working in scrapy as well.

http://stackoverflow.com/q/51777429
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: Pandas shift based on different values to calculate percentages
possible better answer: http://stackoverflow.com/a/51777505
has answer: http://stackoverflow.com/a/51779219
has answer: http://stackoverflow.com/a/51777467
has answer: http://stackoverflow.com/a/51777505
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51777467
downvote count: 0
has comment: http://stackoverflow.com/comment/90513374
has answer: http://stackoverflow.com/a/51777452
tagged with: pandas
has comment: http://stackoverflow.com/comment/90513128
has body: I am trying to calculate percentages of first down from a dataframe. Here is the dataframe down distance 1 1.0 10.0 2 2.0 13.0 3 3.0 15.0 4 3.0 20.0 5 4.0 1.0 6 1.0 10.0 7 2.0 9.0 8 3.0 3.0 9 1.0 10.0 I would like to calculate the percent from first down, meaning for second down, what is the percent of yards gained. For third down, perc of third based on first. For example, I would like to have the following output. down distance percentage 1 1.0 10.0 NaN 2 2.0 13.0 (13-10)/13 3 3.0 15.0 (15-10)/15 4 3.0 20.0 (20-10)/20 5 4.0 1.0 (1-10)/20 6 1.0 10.0 NaN # New calculation 7 2.0 9.0 (9-10)/9 8 3.0 3.0 (3-10)/3 9 1.0 10.0 NaN Thanks Current solutions all work correctly for the first question.
answer count: 4

http://stackoverflow.com/comment/90547827
comment on: http://stackoverflow.com/q/51789823
type: Comment
type: QuestionComment
has text: for `voxelGrid` I use `defaultdict`s and I can do 1000 `Grid()` calls in 0.25s. How many calls do you need because you say it is slow? Using the line_profiler I found that any line in the inner while takes about the same time. If you go multi core you need an expensive merge operation of all the individual `voxelGrid` variables.
score: 0

http://stackoverflow.com/q/51794954
has answer: http://stackoverflow.com/a/51818560
upvote count: 11
answer count: 2
has comment: http://stackoverflow.com/comment/90582833
tagged with: python
has title: How to make a python mocked out function return a specific value conditional on an argument to the function?
has comment: http://stackoverflow.com/comment/90581910
tagged with: mocking
has answer: http://stackoverflow.com/a/51823211
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51823211
score: 11
has body: I have a python 2.7x Tornado application that when run serves up a handful of RESTful api endpoints. My project folder includes numerous test cases that rely on the python mock module such as shown below. from tornado.testing import AsyncHTTPTestCase from mock import Mock, patch import json from my_project import my_model class APITestCases(AsyncHTTPTestCase): def setUp(self): pass def tearDown(self): pass @patch('my_project.my_model.my_method') def test_something( self, mock_my_method ): response = self.fetch( path='http://localhost/my_service/my_endpoint', method='POST', headers={'Content-Type': 'application/json'}, body=json.dumps({'hello':'world'}) ) The RESTful endpoint http://localhost/my_service/my_endpoint has two internal calls to my_method respectively: my_method(my_arg=1) and my_method(my_arg=2). I want to mock out my_method in this test-case such that it returns 0 if it is called with my_arg==2, but otherwise it should return what it would always normally return. How can I do it? I know that I should do something like this: mock_my_method.return_value = SOMETHING But I don't know how to properly specify that something so that its behavior is conditional on the arguments that my_method is called with. Can someone show me or point me to an example??
type: Question
has comment: http://stackoverflow.com/comment/90583693
has comment: http://stackoverflow.com/comment/90583012
possible better answer: http://stackoverflow.com/a/51818560

http://stackoverflow.com/a/58899387
has body: The Shape of the training data should be in the format of:(num_samples,num_features,num_signals/num_vectors). Following this convention, try passing the training data in the form of an array with the reshaped size in convention described above, along with that ensure to add the validation_data argument in the model.fit command. An example of this is: model.fit(x=X_input ,y=y_input,batch_size=2,validation_data=(X_output, y_output),epochs=10) where both X_input, y_input are training data arrays with shape (126,711,1) and (126,1) respectively and X_output, y_output are validation/test data arrays with shapes (53,711,1) and (53,1) respectively. In case you find a shuffling error try setting the value of shuffle argument as True after following the above methodology.
has comment: http://stackoverflow.com/comment/104450258
type: Answer
has comment: http://stackoverflow.com/comment/104470216
upvote count: 1
answers question: http://stackoverflow.com/q/51763983
score: 1
downvote count: 0

http://stackoverflow.com/a/51717573
has body: sum is a lot clearer about your intention, and a lot shorter. Reading the reduce version, I can see that you're reducing a list with some function. Then I read that function, and see that it's adding the values. So, I can figure out that you're summing up numbers. And then I still may have to verify that you implemented it correctly. Reading the sum version, I immediately know that you're summing numbers, and doing it right. sum is faster. In [905]: %timeit sum(orderItemsMap) 173 ns ± 3.13 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [906]: %timeit reduce(lambda total , element : total +element , orderItemsMap) 601 ns ± 8.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) The reduce version has to do a generic loop, while the sum version can do something optimized. Also, the reduce version has to call your lambda for every pair of values, while the sum version can jump right to __add__. And, at least in CPython, sum has further optimizations for summing small integers. sum works for empty lists. In [907]: sum([]) Out[907]: 0 In [908]: reduce(lambda total , element : total +element, []) TypeError: reduce() of empty sequence with no initial value Of course you can make reduce work for empty lists, by adding a third argument: In [909]: reduce(lambda total , element : total +element, [], 0) Out[909]: 0 … but that makes it even longer and less obvious. sum discourages you from accidentally doing things you didn't want. In [911]: sum(["abc", "def", "ghi"]) TypeError: unsupported operand type(s) for +: 'int' and 'str' In [912]: sum(["abc", "def", "ghi"], '') TypeError: sum() can't sum strings [use ''.join(seq) instead] In [913]: reduce(lambda total , element : total +element, ["abc", "def", "ghi"]) Out[913]: 'abcdefghi' With reduce, I just concatenated a bunch of strings, which can take quadratic time, when what I really wanted to do was call ''.join, which takes linear time. OK, CPython 3.7 and PyPy 3.5/6.0 happen to optimize this case to …
has comment: http://stackoverflow.com/comment/90396159
has comment: http://stackoverflow.com/comment/90396428
has comment: http://stackoverflow.com/comment/90396544
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51717509
downvote count: 0
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51717509
type: Answer

http://stackoverflow.com/a/51764068
has body: I tried this: data1 = pd.DataFrame({"Country":["India","UK","USA","UAE","India","UK"], "Pos_id":[1,2,3,4,5,6], "level": [2,2,4,5,1,3]}) data2 = pd.DataFrame({"Country":["UK", "UK","USA", "Singapore","India"],"Emp_id":[11,12,13,14,15], "level":[3,4,4,5,2]}) def get_df(country,pos_id,min,max): lev = data1.loc[(data1.Country==country) &amp; (data1.Pos_id==pos_id)]["level"] data = data2.loc[(data2.Country==country) &amp;(data2["level"].isin(list(range(int(lev)-min,int(lev)+max))))] return data print(get_df("UK",6,1,1))
answers question: http://stackoverflow.com/q/51763088
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/55427647
answers question: http://stackoverflow.com/q/51731623
type: Answer
upvote count: 1
has body: Late reply: subplots may be the answer to this problem. For example, to create a subplots of 2 rows and 2 columns, from plotly import tools plots = tools.make_subplots(rows=2, cols=2, print_grid=True)
score: 1
downvote count: 0

http://stackoverflow.com/q/51715988
has comment: http://stackoverflow.com/comment/90393415
tagged with: python
has comment: http://stackoverflow.com/comment/90393409
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51716073
score: 1
has body: I'd like to make a new column in dataframe df that will fill all rows with [np.nan] df['new'] = [np.nan] I get ValueError: Length of values does not match length of index If I try test['new'] = np.nan test['new'] = test['new'].astype('object') test['new'] = [np.nan] I get ValueError: Length of values does not match length of index I'd like to be sure that all rows are filled with a list containing nan
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51716073
has title: python pandas add list in dataframe column as default value
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90393438
has comment: http://stackoverflow.com/comment/90393384
favorite count: 0

http://stackoverflow.com/q/51734814
accepted answer: http://stackoverflow.com/a/51734908
favorite count: 0
possible better answer: http://stackoverflow.com/a/51734885
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/90430922
tagged with: python
has comment: http://stackoverflow.com/comment/90439230
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90431022
linked to: http://stackoverflow.com/q/13269890
upvote count: 1
has comment: http://stackoverflow.com/comment/90432364
has answer: http://stackoverflow.com/a/51734908
downvote count: 1
tagged with: combinations
has comment: http://stackoverflow.com/comment/90431009
has comment: http://stackoverflow.com/comment/90470518
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90430529
has body: I have two dataframes with thousands of rows, I need to combine both into one dataframe without duplicate and reversion. for example: Dataframe 1 drug1 drug2 drug3 Dataframe 2 disease1 disease2 disease3 So, the output dataframe will be: output-dataframe drug1 disease1 drug1 disease2 drug1 disease3 drug2 disease1 drug2 disease2 drug2 disease3 drug3 disease1 drug3 disease2 drug3 disease3 I don't want the output combination containing something like: disease1 drug1 drug1 drug1 disease1 disease1 I actually try it using pd.merge but it return duplicate and reversion and also took long time because I have thousands in Dataframes 1 and 2 Any help please ?
has comment: http://stackoverflow.com/comment/90430796
has title: Combination of two dataframes without duplicate and reversion in efficient way | python
has answer: http://stackoverflow.com/a/51734907
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51734885

http://stackoverflow.com/q/51695071
linked to: http://stackoverflow.com/q/51769336
tagged with: visual-c++
accepted answer: http://stackoverflow.com/a/51695108
has body: I am trying to install the fancyimpute in my anaconda using pip install. but the error shows fail to install the ecos due to " Microsoft Visual C++ 14.0 is required." the link provided is expired. Does anyone know how to fix this? Thank you! (py36) C:\Users\chenl&gt;pip install ecos Collecting ecos Using cached https://files.pythonhosted.org/packages/b6/b4/988b15513b13e8ea2eac65e97d84221ac515a735a93f046e2a2a3d7863fc/ecos-2.0.5.tar.gz Requirement already satisfied: numpy&gt;=1.6 in c:\users\chenl\anaconda3\envs\py36\lib\site-packages (from ecos) (1.14.3) Requirement already satisfied: scipy&gt;=0.9 in c:\users\chenl\anaconda3\envs\py36\lib\site-packages (from ecos) (1.1.0) Building wheels for collected packages: ecos Running setup.py bdist_wheel for ecos ... error Complete output from command c:\users\chenl\anaconda3\envs\py36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\chenl\\AppData\\Local\\Temp\\pip-install-omudd71s\\ecos\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\chenl\AppData\Local\Temp\pip-wheel-7kzas5zm --python-tag cp36: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 copying src\ecos.py -&gt; build\lib.win-amd64-3.6 running build_ext building '_ecos' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- Failed building wheel for ecos
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: ecos
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/44951456
tagged with: python
tagged with: installation
upvote count: 3
has answer: http://stackoverflow.com/a/51695108
answer count: 1
has title: pip install ecos errors with "Microsoft Visual C++ 14.0 is required."
linked to: http://stackoverflow.com/q/44951456

http://stackoverflow.com/comment/90494042
has text: which command did you use to install ldap? Maybe you installed the wrong package? python-ldap VS ldap
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51767675
score: 0

http://stackoverflow.com/q/51767675
has title: Python: ldap AttributeError
has comment: http://stackoverflow.com/comment/90494138
has comment: http://stackoverflow.com/comment/90495214
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90494197
favorite count: 0
has comment: http://stackoverflow.com/comment/90494190
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51767820
tagged with: pip
tagged with: python
downvote count: 0
score: 1
has body: When I write in cmd: ldap.initialize() I got the communicate : AttributeError: module 'ldap' has no attribute 'initialize' I searched throught posts and I have read that it should be a problem with ldap package. I followed the tips and I uninstalled ldap with pip (varsion 18.0) command and then I installed it again, but nothing changed. I have ldap version 2.5.1 and ldap3 0.4.4
has comment: http://stackoverflow.com/comment/90494042
type: Question

http://stackoverflow.com/comment/90547508
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51794963
has text: You can use `plt.gca().yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())` and `plt.gca().xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())` if you want

http://stackoverflow.com/a/51681138
has body: A one-liner df.types.str.replace('~', '|').agg(lambda k: df2.loc[df2.type.str.contains(k)].description.str.cat(sep=', ') Explained: You can use replace to replace ~ to |. That way, you get strings such as A1|B1 which are easily searchable using str.contains, e.g. df2.loc[df2.type.str.contains('A1|B1')] returns type description 0 A1 This is good 2 B1 This is not good To concatenate these description values into {}, {} , just use str.cat. So the above gives ...description.str.cat(sep=', ') 'This is good, This is not good'
upvote count: 2
answers question: http://stackoverflow.com/q/51680548
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90399578
has text: you will probably get more help using one of the more recent releases from https://pypi.org/simple/setuptools/
type: Comment
comment on: http://stackoverflow.com/q/51718908
score: 0
type: QuestionComment

http://stackoverflow.com/a/56151494
upvote count: 3
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51700018
downvote count: 0
has body: When entering the command to run your file, make sure you specify which version of python you're using. For example, instead of python filename.py, use python3 filename.py or python2 filename.py

http://stackoverflow.com/comment/90471821
score: 0
comment on: http://stackoverflow.com/q/51755907
has text: @Isaac is right. See also https://stackoverflow.com/a/10588342/1076479
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51728639
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51726062
type: Answer
has body: Just for future readers who are following Andrew's Course: K-Fold is Not practically applicable to this purpose, because we mainly want to evaluate the Thetas (i.e. Weights) produced by a certain algorithm with some parameters on the Cross-Validation Set by using those Thetas in a comparison between both Cost-Functions J(train) vs J(CV) to determine if the model suffers from bias, variance or it's O.K. Nevertheless, K-Fold is mainly for testing the prediction on the CV using the weights produced from training the Model on Training Set.

excel
tags question: http://stackoverflow.com/q/51711256
tags question: http://stackoverflow.com/q/51747535
tags question: http://stackoverflow.com/q/51775708
tag name: excel
tags question: http://stackoverflow.com/q/51788896
tags question: http://stackoverflow.com/q/51682938
tags question: http://stackoverflow.com/q/51733620
tags question: http://stackoverflow.com/q/51673981
tags question: http://stackoverflow.com/q/51736793
tags question: http://stackoverflow.com/q/51761786
tags question: http://stackoverflow.com/q/51661907
tags question: http://stackoverflow.com/q/51659240
tags question: http://stackoverflow.com/q/51776107
tags question: http://stackoverflow.com/q/51794559
tags question: http://stackoverflow.com/q/51739941
tags question: http://stackoverflow.com/q/51661980
tags question: http://stackoverflow.com/q/51768192
tags question: http://stackoverflow.com/q/51754578
tags question: http://stackoverflow.com/q/51772333
tags question: http://stackoverflow.com/q/51711527
tags question: http://stackoverflow.com/q/51742362
tags question: http://stackoverflow.com/q/51742709
tags question: http://stackoverflow.com/q/51737655
tags question: http://stackoverflow.com/q/51656948
tags question: http://stackoverflow.com/q/51748031
type: Tag
tags question: http://stackoverflow.com/q/51749448
tags question: http://stackoverflow.com/q/51739488
tags question: http://stackoverflow.com/q/51792576
tags question: http://stackoverflow.com/q/51687559
tags question: http://stackoverflow.com/q/51696940
tags question: http://stackoverflow.com/q/51743275
tags question: http://stackoverflow.com/q/51657853
tags question: http://stackoverflow.com/q/51707544
tags question: http://stackoverflow.com/q/51713916
tags question: http://stackoverflow.com/q/51678110
tags question: http://stackoverflow.com/q/51676251
tags question: http://stackoverflow.com/q/51757735
tags question: http://stackoverflow.com/q/51719948
tags question: http://stackoverflow.com/q/51732854

http://stackoverflow.com/comment/90515743
score: 1
comment on: http://stackoverflow.com/a/51778254
type: AnswerComment
type: Comment
has text: FYI, you can find a whole bunch with the same hash code by building singleton frozensets with the integers `2**i` for, say, `i in range(300)` :-)

http://stackoverflow.com/q/51688492
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51688493
type: Question
answer count: 1
has title: I have 2 columns of data that I need to compare. If the values in column 1 match I need to add their corresponding column 2 values
has body: So I have a very large data set that looks like this. 1 1.05 1 0.95 1 1.00 2 1.02 2 1.03 3 .97 If the values in the first column match then I need to add their corresponding column 2 values. In the case all the 1s match so I would add (1.05 +.95 +1) = 3. Then the 2s match, so it would go (1.02 + 1.03) = 2.05. And the 3 is fine. I need help writing a code to compare numbers and if the number in column 1 matches the number above or below it, add their corresponding column 2 values. After all that is done I need it to plot the newfound values (3, 2.05, and .97 in this case). I already have import pandas as pd import numpy as np import matplotlib.pyplot as plt data = np.loadtxt(fname='Project2-3.dat') df = pd.DataFrame(data=data) energy = df[6]*1000 plt.hist(energy, bins=250) plt.show() But I don't know Python well enough to add the if command. Any help would be appreciated.
upvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90355662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51697061
has text: When coding this, I suggest writing in code that does a "dry run", so that you see what operations take place in what order, or to copy files with a new name to a separate directory. You want to help avoid problems with overwriting files in place.
score: 0

http://stackoverflow.com/comment/90368802
type: QuestionComment
comment on: http://stackoverflow.com/q/51704003
has text: Can you give the output of `which pip` and `which python`?
type: Comment
score: 0

http://stackoverflow.com/a/51681892
score: 0
has body: This should work: In [19]: class Survivor: ...: def __init__(self, name, strength=None, intelligence=None, charisma=None, luck=None): ...: self.name = name ...: self.strength = strength ...: self.intelligence = intelligence ...: self.cha = charisma ...: self.luk = luck In [21]: TribeA = [] ...: John = Survivor('John', 50, 40, 55, 20) ...: Bob= Survivor('Bob', 55, 40, 80, 25) ...: Joe= Survivor('Joe', 60, 10, 65, 10) ...: Tyler= Survivor('Tyler', 56, 30, 15, 25) ...: TribeA.extend([John, Bob, Joe, Tyler]) In [25]: strongest = max(TribeA, key=lambda x: x.strength) In [26]: strongest.name Out[26]: 'Joe' To remove the strongest player from TribeA, use this: TribeA = list(filter(lambda x: x != strongest, TribeA)) # or going by name # TribeA = list(filter(lambda x: x.name != strongest.name, TribeA))
type: Answer
has comment: http://stackoverflow.com/comment/90326997
answers question: http://stackoverflow.com/q/51681833

http://stackoverflow.com/comment/101118696
type: AnswerComment
has text: @NeStack Yes, you got it correctly... if transforming the image does not mean creating a new image ;)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51748870

http://stackoverflow.com/comment/90468065
has text: @taras , ok.. how to access them here
comment on: http://stackoverflow.com/q/51753809
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90535404
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51788983
type: AnswerComment
has text: @J0hn but string_dictable ="{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"", ""YOB"":1835,""Citizen"":""Scottish""}" is not a correct Python expression... It means that the questions makes no sence.

http://stackoverflow.com/comment/90429625
score: 1
has text: Please check [How do I ask a good question](https://stackoverflow.com/help/how-to-ask)
comment on: http://stackoverflow.com/q/51734382
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90469214
type: Comment
has text: @ScottSkiles sorry for the confusion, I edited the question. My issue is with the y axis, not the x axis.
type: QuestionComment
comment on: http://stackoverflow.com/q/51754469
score: 0

http://stackoverflow.com/comment/90319449
score: 0
type: AnswerComment
has text: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' @wen
type: Comment
comment on: http://stackoverflow.com/a/51677840

http://stackoverflow.com/comment/90249452
type: QuestionComment
has text: Thanks! I want to note that page is not reloading, just scroll up and shows new results
score: 0
comment on: http://stackoverflow.com/q/51642133
type: Comment

http://stackoverflow.com/q/51660889
has comment: http://stackoverflow.com/comment/91529128
has comment: http://stackoverflow.com/comment/90323121
tagged with: python
tagged with: jinja2
has title: Jinja2 not work on flask/glitch.me deployment
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52182927
type: Question
has comment: http://stackoverflow.com/comment/90285638
answer count: 2
tagged with: flask
favorite count: 0
possible better answer: http://stackoverflow.com/a/51769012
tagged with: web-deployment
has answer: http://stackoverflow.com/a/51769012
has body: I have a deployment of a tiny Flask app on Glitch. It seems to be working... sort of. However, the Jinja2 template engine is clearly not working, since all Jinja2 tags are being read into the browser as text. The application, which I have up on my GitHub page, works fine on the localhost. Can I fix this somehow?
has answer: http://stackoverflow.com/a/52182927
upvote count: 2
downvote count: 2

http://stackoverflow.com/comment/90365289
type: QuestionComment
has text: Because date row is index. You may try reset_index method. Check documentation.
score: 4
comment on: http://stackoverflow.com/q/51702138
type: Comment

http://stackoverflow.com/q/51739525
has comment: http://stackoverflow.com/comment/90458219
answer count: 3
has answer: http://stackoverflow.com/a/51739636
favorite count: 0
has answer: http://stackoverflow.com/a/51739586
has comment: http://stackoverflow.com/comment/90475898
score: -3
has comment: http://stackoverflow.com/comment/90464301
tagged with: python
type: AnsweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/51739594
has body: I am at a loss trying to figure out how to achieve the following in Python. I have a variable that has a string inside it variable = "Normal" or variable = "Unknown" I just want to write an If statement that will check the value of the variable and execute some code based on it. In Perl i'd simply write if ( $variable =~ /Normal/ ) { dosomething() } elsif ( $variable =~ /Unknown/ ) { dosomething() } else { raiseerror() } How do I achieve the same in Python ?
accepted answer: http://stackoverflow.com/a/51739594
type: Question
possible better answer: http://stackoverflow.com/a/51739586
upvote count: 0
has comment: http://stackoverflow.com/comment/90439166
has title: How to match a variable with value in Python

http://stackoverflow.com/q/51788736
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51789316
has title: Pandas assign categories to numbers in dataframe
has comment: http://stackoverflow.com/comment/90544858
tagged with: python
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90535856
has body: I have this dataframe: +----------+----------+------------+------------+ | values_A | values_B | values_A_r | values_B_r | +----------+----------+------------+------------+ | 1.623 | 1.91232 | 1.6 | 1.9123 | | 1.582 | 1.32154 | 1.6 | 1.3215 | +----------+----------+------------+------------+ I want to find the difference between values_A (rounded to 1 digit) and values_A_r, as well as the difference between values_B (rounded to 4 digit) and values_B_r. Assign the categories "Same", "More", or "Less" depending on the difference. If all the differences are "Same", print out a message. This is my current code. def test_func(): check['A_check'] = np.where(abs(round(check.values_A,1) - check.values_A_r)&lt;1**-10, 'Same', np.where(round(check.values_A,1) &gt; check.values_A_r, 'Less', 'More')) check['B_check'] = np.where(abs(round(check.values_B,4) - check.values_B_r)&lt;1**-10, 'Same', np.where(round(check.values_B,4) &gt; check.values_B_r, 'Less', 'More')) if (set([len(check.index)])==set([check.A_check.value_counts().Same, check.B_check.value_counts().Same])): return print('Correct!') else: raise SystemExit('Incorrect.') test_func() I'm currently using nested np where statements to assign the categories and it looks really messy. Additionally, I have to use &lt;1**-10 instead of ==0 because sometimes when the numbers are the "Same", the difference is calculated to be something like 8**-12 instead of just 0. This process seems really simple and the code makes it look complicated. Is there a neater way to do this?
has answer: http://stackoverflow.com/a/51789202
tagged with: if-statement
tagged with: categories
tagged with: numpy
score: 0

http://stackoverflow.com/q/51733496
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51735259
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90427779
type: Question
possible better answer: http://stackoverflow.com/a/51735259
has comment: http://stackoverflow.com/comment/90427831
has answer: http://stackoverflow.com/a/51733556
downvote count: 0
has title: Python - Replace regular expression match with a matching pair value
answer count: 2
has body: Let's say I have a list of aliases tied to 5 digit codes available at runtime: aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')] I want to find a terse way to express: replace the id in the line with the matching alias, e.g. : line = "hey there 12345!" line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line) print line Should output: hey there bob! How do Python pros write enumerative expressions in a terse manner? Thanks and cheers!
has comment: http://stackoverflow.com/comment/90427684
tagged with: enumeration
favorite count: 0
accepted answer: http://stackoverflow.com/a/51733556
linked to: http://stackoverflow.com/q/22586895
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/90320531
score: 0
type: Comment
type: QuestionComment
has text: Are you aware that `3**3` evaluates to 27 in the Python interpreter? What are you trying to do here?
comment on: http://stackoverflow.com/q/51678572

http://stackoverflow.com/comment/90612796
type: Comment
has text: is `r` the path to your xml file?...You need to provide the full path to your xml file Ex: `getMetrics(r"C:\Users\User\Desktop\testFiles\A.xml")`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51816249

http://stackoverflow.com/comment/90942360
type: Comment
type: QuestionComment
has text: You can redirect the output of your process to a file, like `python myprog.py 1>output.file`
comment on: http://stackoverflow.com/q/51778888
score: 0

http://stackoverflow.com/a/51764766
has body: IPython will not generate any output for figures that do not contain an axes. If you add an axes to your figure, the figure will show fine. %matplotlib inline import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.show() or %matplotlib inline import matplotlib.pyplot as plt plt.gca() plt.show() If you then remove the axes, it will again show the returned python string again. The solution to show a completely empty figure with the inline backend is hence to add an axes but then turn it invisible. %matplotlib inline import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_visible(False) plt.show()
type: Answer
answers question: http://stackoverflow.com/q/51759921
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/90545216
has text: Not really related, but important. The usual issue when copying some "expert’s" code: **NEVER** use [tf.Variable](https://stackoverflow.com/a/51167774/7443104). And some point you will shoot yourself in the foot.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51790721
score: 0

http://stackoverflow.com/a/51713163
answers question: http://stackoverflow.com/q/51712269
type: Answer
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/90388039
has body: TA-Lib is expecting floating point data, whereas yours is integral. As such, when constructing your dataframe you need to coerce the input data by specifying dtype=numpy.float64: import pandas import numpy import talib d = {'security1': [1,2,8,9,8,5], 'security2': [3,8,5,4,3,5]} df = pandas.DataFrame(data=d, dtype=numpy.float64) # note numpy.float64 here TA-Lib expects 1D arrays, which means it can operate on pandas.Series but not pandas.DataFrame. You can, however, use pandas.DataFrame.apply to apply a function on each column of your dataframe df.apply(lambda c: talib.EMA(c, 2)) security1 security2 0 NaN NaN 1 1.500000 5.500000 2 5.833333 5.166667 3 7.944444 4.388889 4 7.981481 3.462963 5 5.993827 4.487654
upvote count: 8
has comment: http://stackoverflow.com/comment/119504102
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51712269

http://stackoverflow.com/q/51768403
tagged with: jupyter-notebook
has title: XGBoost crashing kernel in jupyter notebook
has answer: http://stackoverflow.com/a/57023839
has body: I don't know how to make the XGBoost classifier work. I am running the code below on Jupyter notebook, and it always generates this message "The kernel appears to have died. It will restart automatically." from xgboost import XGBClassifier model = XGBClassifier() model.fit(X, y) There is no problem with importing the XGBClassifier, but it crashes upon fitting it to my data. X is a 502 by 33 all-numeric dataframe, y is the set of 0 or 1 labels for each row. Does anyone know what could be the problem here? I downloaded the newest version of XGBoost through pip3 install, and also through Conda install.
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/53194761
answer count: 2
downvote count: 0
tagged with: xgboost
linked to: http://stackoverflow.com/q/51164771
favorite count: 0
has comment: http://stackoverflow.com/comment/90495971
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6

http://stackoverflow.com/q/51677887
upvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/51678309
type: AnsweredQuestion
tagged with: design-decisions
has answer: http://stackoverflow.com/a/51678309
possible better answer: http://stackoverflow.com/a/56826493
type: Question
score: 3
has title: Rationale for numpy.split returning a list and not an array
has comment: http://stackoverflow.com/comment/90319003
has comment: http://stackoverflow.com/comment/90319198
tagged with: numpy
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90319674
has body: I was surprised that numpy.split yields a list and not an array. I would have thought it would be better to return an array, since numpy has put a lot of work into making arrays more useful than lists. Can anyone justify numpy returning a list instead of an array? Why would that be a better programming decision for the numpy developers to have made?
favorite count: 0
has answer: http://stackoverflow.com/a/56826493

http://stackoverflow.com/q/51783694
tagged with: argmax
answer count: 0
has comment: http://stackoverflow.com/comment/90524734
type: Question
has comment: http://stackoverflow.com/comment/90527297
has comment: http://stackoverflow.com/comment/90534473
has body: I am trying to use the argmax function of numpy to take two argument. Here is the code: UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 actlist = [UP, DOWN, LEFT, RIGHT] a = numpy.argmax(actlist, lambda a: expected_utility(a,i,j,U)) The problem is, one of the arguments is the return value of a function. It returns an integer. The function expected_utility(a,i,j,U) looks like: def expected_utility(a,i,j,U): return sum(p*U[i][j] for (k,l,p) in T(i,j,a)) If I use lambda with the second parameter of the argmax function, I am getting an error: TypeError: 'function' object cannot be interpreted as an integer If I don't use lambda with the second parameter of the argmax function, I am getting the error: UnboundLocalError: local variable 'a' referenced before assignment I am using Python 3.6.5 Now I am even confused with how argmax function even works. What is the role of lambda here.
has comment: http://stackoverflow.com/comment/90524933
tagged with: numpy
score: 0
has title: Numpy argmax function error
has comment: http://stackoverflow.com/comment/90524920
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90524914
tagged with: python

http://stackoverflow.com/comment/90531676
type: Comment
type: QuestionComment
has text: Thank you, @Quickbeam2k1, I did not know that the topic had an actual name. I'll try searching for it.
comment on: http://stackoverflow.com/q/51784222
score: 0

http://stackoverflow.com/comment/90262993
score: 0
type: Comment
has text: sorry for the bad format i dont know what happened to that. the traceback ends at **KeyError**, instead of **(roibd)**
type: QuestionComment
comment on: http://stackoverflow.com/q/51649833

http://stackoverflow.com/comment/90445097
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51742328
has text: This works but seems to be a very complex, non-generic solution to me
type: AnswerComment

http://stackoverflow.com/a/51666893
type: Answer
score: 0
has body: The latter is Pythonic. Don't use classes when you don't need instance data; use modules.
answers question: http://stackoverflow.com/q/51666871

http://stackoverflow.com/q/51739255
has title: Python subclassing - how to update class attribute that is used by another class attribute
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51739370
downvote count: 0
has comment: http://stackoverflow.com/comment/123928545
tagged with: attributes
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51739378
tagged with: subclass
score: 5
has answer: http://stackoverflow.com/a/51739378
tagged with: python
answer count: 3
has body: Say if there's a class attribute that is calculated depending on another class attribute: class ClassA(object): attr1=5 attr2=attr1+10 &gt;&gt;ClassA.attr2 15 And then in a child class I want to update the first class attribute to cause a change in the second one, without re-defining the second. e.g: class ClassB(ClassA): attr1=10 What I would like to happen is: &gt;&gt;ClassB.attr2 20 However this isn't the case since attr2 gets calculated before attr1 is re-defined. Is there a way to obtain this behaviour without redefining the second attribute? (My particular use case is defining WTForms with Field attributes (format, choices, etc) that are derived from the Form class attributes, so I can subclass a base Form and change these attributes without having to re-define the entire Field.)
has answer: http://stackoverflow.com/a/51739370
has answer: http://stackoverflow.com/a/51739674
upvote count: 5
tagged with: wtforms
tagged with: inheritance

http://stackoverflow.com/comment/90546895
has text: @AzatIbrakov postgres, but it doesn't matter. We don't need UPSERT feature, because it will increase database requests.count
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51785928
type: QuestionComment

http://stackoverflow.com/comment/92111782
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51729619
has text: Just use a Taylor expansion and ignore any terms beyond the quadratic ones.
score: 0

http://stackoverflow.com/q/51793459
tagged with: python
has comment: http://stackoverflow.com/comment/90545091
answer count: 0
has comment: http://stackoverflow.com/comment/90545044
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90545013
has body: I've written a program that generates a random name and displays a random image along with it using Python and tkinter. However, I want the user to be able to add and remove pictures as well as edit the names of students. That being said, I don't want to package these inside the executable where it can't be changed by the user. To use PyInstaller, I go into the command prompt and navigate to the working directory and type: pyi-makespec --windowed --onefile --icon=Assets\\icon.ico random_student.py Then, in the spec file I change datas to: datas=[('Assets\\icon.ico', 'Assets')], Then, I run pyinstaller random_student.spec The program runs just fine using PyCharm. And I've done this exact same method on a couple of other .py files an it works. However, they don't need to pull images/text into their programs. This will create an executable, but I can't run it. It gives me a Fatal Error "Failed to execute script random_student". I've tried placing the executable in the working directory and in the pictures folder, but neither work. I'm currently using Windows 10 64-bit and Python 3.6.6 I'd appreciate any kind of help I can get with this! SOLUTION: I removed the --windowed option so I could actually read the error. Then realized I didn't have Pillow installed so it was unable to be packaged. Thank you for the help.
has comment: http://stackoverflow.com/comment/90545092
has title: Pyinstaller exectuable using data from other folders?
has comment: http://stackoverflow.com/comment/90545052
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90544908
has comment: http://stackoverflow.com/comment/90544762
type: UnansweredQuestion
tagged with: pyinstaller

http://stackoverflow.com/comment/90577960
type: Comment
comment on: http://stackoverflow.com/a/51715475
type: AnswerComment
has text: Did you add quotes inside the copy function for your String?
score: 0

http://stackoverflow.com/a/51645116
answers question: http://stackoverflow.com/q/51644769
type: Answer
has body: If it is in the same location as the script, you can try: import os path = os.path.abspath('credentials.json') with open(path,'r'): //code
score: 0

http://stackoverflow.com/q/51663957
tagged with: variables
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/90291330
score: 0
has answer: http://stackoverflow.com/a/51664121
has answer: http://stackoverflow.com/a/51664103
type: UnansweredQuestion
has title: Python check for NULL values from user input and do not include in sql update
tagged with: python
type: Question
has body: In my function I am asking for input from the user for different variables and then updating the DB. The issue is if they do not input anything is there a way I can not push anything to the DB? At the moment when they do not enter a value for the var, the value in the DB will get wiped out. db_root = '/var/lib/mysql/' db_to_create = 'students' db_to_use = 'students' conn = pymysql.connect(host='localhost', user='root', passwd='dbadmin', cursorclass=pymysql.cursors.DictCursor) print('Connection successful!!') def modify_student(): student_id = input("Enter the id of the student record you wish to modify: ") student_info = input("Is this student personal information you want to modify - y or n: ") if student_info == 'y': firstname = input("Enter the first name: ") lastname = input("Enter the last name: ") email = input("Enter the email address: ") address = input("Enter the address: ") DOB = input("Enter the DOB in YYYY-MM-DD: ") cur = conn.cursor() command = "use %s; " %db_to_use cur.execute(command) sql = "UPDATE students_info SET firstname = %s, lastname = %s, email = %s, address = %s, DOB = %s WHERE ID = %s;" cur.execute(sql, [firstname, lastname, email, address, DOB, student_id]) print(cur.execute) conn.commit() cur.close() conn.close() else: print("else") modify_student() ######## SCHEMA ################## MariaDB [students]&gt; DESCRIBE students_info; +-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | ID | int(11) | NO | PRI | NULL | auto_increment | | firstname | varchar(255) | YES | | NULL | | | lastname | varchar(255) | YES | | NULL | | | email | varchar(255) | YES | | NULL | | | address | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | english | varchar(255) | YES | | NULL | | | maths | varchar(255) | YES | | NULL | | | history | varchar(255) | YES | | NULL | | | science | varchar(255) | YES | | NULL | | …
answer count: 2
tagged with: null
tagged with: database

http://stackoverflow.com/q/51694376
has answer: http://stackoverflow.com/a/51694426
favorite count: 0
has answer: http://stackoverflow.com/a/51694523
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90351118
possible better answer: http://stackoverflow.com/a/51694426
has body: I have a numpy array (say xs), for which I am writing a function to create another array (say ys), which has the same values as of xs until the first half of xs and two times of xs in the remaining half. for example, if xs=[0,1,2,3,4,5], the required output is [0,1,2,6,8,10] I wrote the following function: import numpy as np xs=np.arange(0,6,1) def step(xs): ys1=np.array([]);ys2=np.array([]) if xs.all() &lt;=2: ys1=xs else: ys2=xs*2 return np.concatenate((ys1,ys2)) print(xs,step(xs)) Which produces output: `array([0., 1., 2., 3., 4., 5.]), ie the second condition is not executed. Does anybody know how to fix it? Thanks in advance.
answer count: 2
upvote count: 1
has title: Python- Numpy array in function with conditions
tagged with: function
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/51694523

http://stackoverflow.com/q/51652649
tagged with: pepper
has body: I have a problem with reading the date value from Pepper robot log. I use Python to fetch the log messages from a remote robot. See an example code: def onMessage(mess): print mess # mess is a dictionary with all known LogMessage information. def main(): app = qi.Application(url="tcp://10.0.11.252:9559") app.start() logmanager = app.session.service("LogManager") listener = logmanager.getListener() listener.onLogMessage.connect(onMessage) app.run() if __name__ == "__main__": main() Тhis is how one log message looks like: { 'category': 'ALMemory', 'level': 5, 'source': ':notify:0', 'location': '7b5400e2-18b1-48e4-1127-g4e6544d0621b:3107', 'date': 11112334305291, 'message': 'notifying module: _WholeBodyLooker for datachange for key: ALTracker/ObjectLookAt', 'id': 5599547, 'systemDate': 1533208857670649344, } The problem is that I don't know the date value meaning. I didn't find any documentation for this value. When I try to covert 11112334305291 to date the result is not meaningful: Sunday, February 19, 2322 11:31:45.291 PM. Does anyone have any idea what this might mean?
tagged with: date
has comment: http://stackoverflow.com/comment/90268779
tagged with: datetime-format
answer count: 1
downvote count: 0
favorite count: 0
tagged with: unix-timestamp
upvote count: 2
has title: Pepper Linux log date format looks meaningless
has answer: http://stackoverflow.com/a/51654856
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51654856

http://stackoverflow.com/q/51716398
has body: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. I tried something like this : class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ has = dict() l = list() for c in s: if c not in has: has[c] = 1 else: has[c] += 1 for k in sorted(has,key = has.get, reverse = True): for i in range(has[k]): l.extend(k) return ("".join(l)) but its O(n * m) n = length of string, m = maximum occurrence of a character How can i improve this to order of n?
linked to: http://stackoverflow.com/q/23429426
has answer: http://stackoverflow.com/a/51716430
has comment: http://stackoverflow.com/comment/90394106
duplicate of: http://stackoverflow.com/q/23429426
answer count: 1
downvote count: 0
favorite count: 0
has title: Sort characters by frequency
accepted answer: http://stackoverflow.com/a/51716430
has comment: http://stackoverflow.com/comment/90394054
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: algorithm

http://stackoverflow.com/comment/90502392
type: QuestionComment
comment on: http://stackoverflow.com/q/51771831
has text: `if 0` evaluates to `False` - change the conditon to `if check.get(letter) is not None`
score: 1
type: Comment

http://stackoverflow.com/q/51792627
downvote count: 0
tagged with: sorting
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51792693
upvote count: 2
possible better answer: http://stackoverflow.com/a/51793573
has answer: http://stackoverflow.com/a/51793573
tagged with: python
type: AnsweredQuestion
score: 2
has title: Sorting list of strings by their length and the last N characters
tagged with: list
has body: I'm trying to solve a problem, where I have to sort a list of strings by the length of the string as well as the last characters in the string. In the case of the string having the same length and same last character, they should be sorted by second to last character and so on. I have this code, but I'm not clear on why it does not work as I intend. Could someone point me in the right direction? My code: import sys word_lists = [line.split(' ') for line in ' '.join([x.strip() for x in sys.stdin.readlines()]).split(' ')] for i in range(0, len(word_lists)): word_lists[i] = sorted((word_lists[i]), key=lambda x: (x[:-1], len(x))) Input: apple banana grape kiwi pear airplane bicycle boat car Output: [['apple', 'banana', 'grape', 'kiwi', 'pear'], ['airplane', 'bicycle', 'boat', 'car']] Expected Output: [['banana', 'apple', 'grape', 'kiwi', 'pear'], ['bicycle', 'airplane', 'car', 'boat']]
accepted answer: http://stackoverflow.com/a/51792693
has comment: http://stackoverflow.com/comment/90543407
type: Question
answer count: 2

http://stackoverflow.com/q/51741865
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51742328
tagged with: python
has answer: http://stackoverflow.com/a/51742328
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Operate on columns based on other column contents in pandas
has answer: http://stackoverflow.com/a/51742534
type: Question
tagged with: dataframe
has body: Coming from R, I cannot figure out how to make kinda vectorized operations on one dataframe column by utilizing other columns, e.g.: import pandas as pd df = pd.DataFrame({'s':['Big bear eats cat','cute cat sleeps'],'a':['bear','cat']}) Now I just want to replace (other operations could be split) rowwise the occurrence of a in s with ANIMAL so it looks like this: 0 Big ANIMAL eats cat 1 cute ANIMAL sleeps In R data.table (with vectorized functions) I would just write something like df[,s:=str_replace(s,a,"ANIMAL")] I saw I might be able to use apply but that still seemed very complex for such an easy case
answer count: 2
accepted answer: http://stackoverflow.com/a/51742534
tagged with: pandas
downvote count: 0
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/90356080
type: Comment
comment on: http://stackoverflow.com/a/51696260
has text: ok, all other commands in the bot is using on_message but i'l try.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/105430101
type: Comment
comment on: http://stackoverflow.com/q/51676464
score: 0
type: QuestionComment
has text: is there an explanation of this insane behaviour anywhere? (the flattening that is)

http://stackoverflow.com/comment/90935010
comment on: http://stackoverflow.com/a/51927483
type: AnswerComment
has text: Had you another version of Python on the same PC? For example 2.7?
score: 0
type: Comment

http://stackoverflow.com/a/51754631
has comment: http://stackoverflow.com/comment/90506552
upvote count: 1
has comment: http://stackoverflow.com/comment/90508123
has comment: http://stackoverflow.com/comment/90469531
has comment: http://stackoverflow.com/comment/90469612
answers question: http://stackoverflow.com/q/51754413
has body: This is a pretty simple thing to do using the datetime package. It has a function called strptime which takes in a string and converts it to a datetime. Then there is another function called strftime which will output the datetime in a specific format (in your case the day of the year). You can look at the documentation for more info about datetimes here. Example of getting the day of the year: def get_DOY(date_string): # First convert string to datetime object parsed_datetime = datetime.datetime.strptime(date_string, '%m/%d/%Y') # Then get day of year from datetime day_of_year = parsed_datetime.timetuple().tm_yday return day_of_year Edit: Simpler approach is to get the day of year from a timetuple so that it outputs it directly as an int I am not experienced in arcgis, but assuming the function is .getValue to get the value based on the field name: import arcpy import datetime # You should only import datetime once fcList = arcpy.ListFeatureClasses() for fc in fcList: field_list = arcpy.ListFields(fc) if "DOY" not in field_list: arcpy.AddField_management(fc,"DOY","SHORT") date_string = None # Assuming .getValue is how you get a value from the fc if "Date" in field_list: date_string = fc.getValue("Date") elif "Sample_Date" in field_list: date_string = fc.getValue("Sample_Date") elif "T0_Date" in field_list: date_string = fc.getValue("T0_Date") if date_string is not None: day_of_year = get_DOY(date_string) # call function as listed above else: # handle when no date value found here
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90507121
has comment: http://stackoverflow.com/comment/90469794
has comment: http://stackoverflow.com/comment/90470899
has comment: http://stackoverflow.com/comment/90506801

http://stackoverflow.com/a/51661254
type: Answer
upvote count: 1
downvote count: 1
has body: Here is code to fit a surface equation "z = f(x,y)", plot the raw data 3D scatterplot, plot the 3D fitted surface, and graph a contour plot. This should at least give you the graphics you need. import numpy, scipy, scipy.optimize import matplotlib from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm # to colormap 3D surfaces from blue to red import matplotlib.pyplot as plt graphWidth = 800 # units are pixels graphHeight = 600 # units are pixels # 3D contour plot lines numberOfContourLines = 16 def SurfacePlot(func, data, fittedParameters): f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100) matplotlib.pyplot.grid(True) axes = Axes3D(f) x_data = data[0] y_data = data[1] z_data = data[2] xModel = numpy.linspace(min(x_data), max(x_data), 20) yModel = numpy.linspace(min(y_data), max(y_data), 20) X, Y = numpy.meshgrid(xModel, yModel) Z = func(numpy.array([X, Y]), *fittedParameters) axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True) axes.scatter(x_data, y_data, z_data) # show data along with plotted surface axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot axes.set_xlabel('X Data') # X axis data label axes.set_ylabel('Y Data') # Y axis data label axes.set_zlabel('Z Data') # Z axis data label plt.show() plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems def ContourPlot(func, data, fittedParameters): f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100) axes = f.add_subplot(111) x_data = data[0] y_data = data[1] z_data = data[2] xModel = numpy.linspace(min(x_data), max(x_data), 20) yModel = numpy.linspace(min(y_data), max(y_data), 20) X, Y = numpy.meshgrid(xModel, yModel) Z = func(numpy.array([X, Y]), *fittedParameters) axes.plot(x_data, y_data, 'o') axes.set_title('Contour Plot') # add a title for contour plot axes.set_xlabel('X Data') # X axis data label axes.set_ylabel('Y Data') # Y axis data lab…
score: 0
answers question: http://stackoverflow.com/q/51659957
has comment: http://stackoverflow.com/comment/90286257

http://stackoverflow.com/q/51706118
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51706311
possible better answer: http://stackoverflow.com/a/51706139
has answer: http://stackoverflow.com/a/51706139
has comment: http://stackoverflow.com/comment/90372919
has answer: http://stackoverflow.com/a/53627632
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/53627632
has body: I Have a python file named myfile.py that I want to run it every 1 minute. When I use this command : 'python myfile.py' It Runs Correctly. But when I set time for it and put it in crontab it doesn't work. What the hell is my problem? my crontab -e configurations: 1 * * * * python /home/myuser/Desktop/myfile.py
favorite count: 0
has title: Python Script Doesn't Work After Put It On Crontab

http://stackoverflow.com/comment/90552897
has text: @AlekPiasecki, Correct.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51793625

http://stackoverflow.com/q/51696004
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51696085
accepted answer: http://stackoverflow.com/a/51696085
has body: I'm having a Numpy shape issue. I have a batch of 128x128x3 images and I am trying to reshape my list to be of shape batch_size x 128 x 128 x 3. Let's walk through what I have so far. We have a batch of 3 lists that include the image and some other meta data. Visually: my_data |row|raw_image|meta_data1|meta_data2| ------------------------------------- |1 |128x128x3|8685 |'here' | ------------------------------------- |2 |128x128x3|8402 |'there' | ------------------------------------- |3 |128x128x3|5498 |'where' | print(my_data.shape) #(3,4) We only want to grab the raw_image data: image_data = my_data[:, 1] print(image_data.shape) #(3,) print(image_data[0].shape) #(128,128,3) I would think that image_data would already be in 3x128x128x3, however I am getting errors, such as: ValueError: Error when checking: expected input_1 to have 4 dimensions, but got array with shape (384, 128, 3) or ValueError: Error when checking: expected input_1 to have 4 dimensions, but got array with shape (3, 1) I've tried reshaping, like so: np.reshape(image_data, (3, 128, 128, 3)) But get the following error: ValueError: cannot reshape array of size 3 into shape (3,128,128,3) So, how should I proceed? I've tried combinations with vstack, reshape, extend dim, removing a dim...
has comment: http://stackoverflow.com/comment/90353615
score: 1
has comment: http://stackoverflow.com/comment/90353476
type: Question
type: AnsweredQuestion
has title: Numpy reshape image data into batches
tagged with: numpy
upvote count: 1
answer count: 1
downvote count: 0
tagged with: keras

http://stackoverflow.com/a/51671754
type: Answer
has comment: http://stackoverflow.com/comment/90306074
answers question: http://stackoverflow.com/q/51670562
has body: Open Anaconda Navigator from there click Environments select one that you are working on currently and install package from there. The reason is that your jupyter notebook does not use your default python installation. And using only pip3 command in terminal without switching to correct environment won't work. Plus I had my share of problems with installing from Anaconda terminal. EDIT Installing from navigator will also install all needed dependencies including C libraries. It really is the easiest way of managing packages in your jupyter/Anaconda project. EDIT2 From your comments I have a feeling your jupyter notebook uses different python environment. Anaconda comes with python 3.6 not 3.7. Plus the path in your error: Command "c:\users\phillip.desktop-did4ci8\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\PHILLI~1.DES\\AppData\\Local\\Temp\\pip-install-i762jowc\\lxml\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\PHILLI~1.DES\AppData\Local\Temp\pip-record-z7kvhhca\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\PHILLI~1.DES\AppData\Local\Temp\pip-install-i762jowc\lxml\ suggest different environment than the Anaconda base(root). Try lunching jupyter from navigator this will ensure you are using the correct environment
accepted answer of: http://stackoverflow.com/q/51670562
has comment: http://stackoverflow.com/comment/90306144
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90309170
has comment: http://stackoverflow.com/comment/90306207
score: 0
has comment: http://stackoverflow.com/comment/90309244

http://stackoverflow.com/a/51696678
has body: You delete the message the Embed is in, not the Embed itself. sent = await self.bot.say(embed=embed) await asyncio.sleep(3) await self.bot.delete_message(sent)
accepted answer of: http://stackoverflow.com/q/51696533
downvote count: 1
has comment: http://stackoverflow.com/comment/90354760
answers question: http://stackoverflow.com/q/51696533
score: -1
upvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90354740
type: Answer

http://stackoverflow.com/q/51695023
tagged with: python
has answer: http://stackoverflow.com/a/51696373
linked to: http://stackoverflow.com/q/43167867
has body: Given a bounding box for an image in OpenCV, is there a way to return all the colors inside the box? Ideally, the output would give the information along the lines of "In the bounding box, it is 50% white, 25% blue, 15% green, 10% red." Is there any way to do this? At the very least, is there some function that could tell me all the colors in the box? (without percentages or how much of it there is). Any indication would be huge help Thanks in advance
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90352619
tagged with: opencv
has title: Determine all colors in bounding box in OpenCV/Python
type: Question
has comment: http://stackoverflow.com/comment/90353985
score: 0
has comment: http://stackoverflow.com/comment/90501102
answer count: 1
tagged with: colors

http://stackoverflow.com/comment/90358582
type: QuestionComment
has text: Hello @bazza1988 and welcome to stackoverflow, without having a concrete, concise and minimal code example that shows off your problem, it's hard to tell what your issue could be.
comment on: http://stackoverflow.com/q/51698157
score: 0
type: Comment

http://stackoverflow.com/comment/90422724
comment on: http://stackoverflow.com/a/51725678
type: Comment
has text: Investigating and trying to map your code to my logic helped to find the culprit buddy, now the graphs are much better, without deviating much from my logic. I will post the updated code, Please review if conceptually ok.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51736715
has comment: http://stackoverflow.com/comment/90434772
upvote count: 2
tagged with: dynamic
has comment: http://stackoverflow.com/comment/90460348
tagged with: slice
answer count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/51745402
has body: How do I dynamically slice each row given a starting and ending index without using a for loop. I can do it with loop listed below, but it is way too slow for something where the x.shape[0] > 1 mill x= np.arange(0,100) x = x.reshape(20,5) s_idx = np.random.randint(0,3,x.shape[0]) e_idx = np.random.randint(3,6,x.shape[0]) print(s_idx) &gt;&gt;&gt; array([2, 1, 2, ..., 1, 0, 2]) print(e_idx) &gt;&gt;&gt; array([3, 4, 5, ..., 3, 3, 3]) print(x) &gt;&gt;&gt; array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], ..., [85, 86, 87, 88, 89], [90, 91, 92, 93, 94], [95, 96, 97, 98, 99]]) x_indexed = [] for idx,value in enumerate(s_idx): x_indexed.append(x[idx][s_idx[idx]:e_idx[idx]]) print(x_indexed) &gt;&gt;&gt; [array([2]), array([6, 7, 8]), array([12, 13, 14]), array([15, 16, 17]), array([20, 21, 22, 23]), array([26, 27, 28, 29]), array([30, 31, 32, 33]), array([35, 36, 37, 38, 39]), array([40, 41, 42]), array([46, 47, 48]), array([52, 53, 54]), array([56, 57]), array([62, 63, 64]), array([67]), array([70, 71, 72, 73]), array([77]), array([80, 81, 82, 83, 84]), array([86, 87]), array([90, 91, 92]), array([97])]
has comment: http://stackoverflow.com/comment/90434665
has title: Numpy Dynamic Slicing Per Row
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51745402
tagged with: python

http://stackoverflow.com/q/51717208
has comment: http://stackoverflow.com/comment/90398644
has title: How to run a non-exe app without typing its extension in CMD? (i.e environment path variable)
answer count: 0
downvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
tagged with: environment-variables
tagged with: windows
has comment: http://stackoverflow.com/comment/90396592
tagged with: cmd
score: 1
has comment: http://stackoverflow.com/comment/90419929
has body: I've got a python application that is located in O:\Apps\Python\myapp.py I added this into my Windows Path O:\Apps\Python\ so I can run it anywhere with CMD as so &gt; myapp someArg1 someArg2 But It turns out that I need to type its extension (unlike .exe files) like this &gt; myapp.py someArg1 someArg2 How can I run it by just the name?
tagged with: path
has comment: http://stackoverflow.com/comment/90411350
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90411207

http://stackoverflow.com/a/51772629
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: OK I found it out, posting an answer for future generations: It seems that seaborn's kdeplot() utilizes matplotlib's contourf(), and as one can see in the documentation it fills the areas between specified ranges [min,max], so I was missing an upper bound on my densities, to begin with. Secondly, the colors are adjusted depending on the upper bound one provides. That is because kdeplot() takes a color map by default and stretches your [min,max] range accordingly onto the color space. If the maximal value is far away from the rest of the isolines one gets an intense center with very vague areas around. The solution for this is to provide colors manually with the "colors" parameter and turn off the color map: fifty_shades_of_grey = ["#f3f3f3","#e6e6e6","#d9d9d9","#cccccc","#bfbfbf"] sns.palplot(sns.color_palette(fifty_shades_of_grey)) g = sns.jointplot("s_zscore","p_zscore", data=scatter_all, kind="kde",levels=density_levels+[1],colors=fifty_shades_of_grey,cmap=None) Case closed, Watson.
score: 2
accepted answer of: http://stackoverflow.com/q/51743690
upvote count: 2
answers question: http://stackoverflow.com/q/51743690

http://stackoverflow.com/comment/90280506
score: 3
has text: I'm observing eigen being more than ten times *faster* than numpy, with `-Ofast -march=native` flags. (55 vs 700 ms per iteration)
comment on: http://stackoverflow.com/q/51656818
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51653887
score: 1
has body: Not sure if you can do logical indexing in pandas DataFrames with non-numeric or string values. Heres a simple one-line workaround that compares strings instead of lists. df.loc[df['col1'].apply(str) == str([0,1])]['col2'][0] Essentially what you're doing is all the lists in column 1 to strings, and then comparing them to the string: str([0,1]). Note the [0] at the end of my second line of the solution. This is because more than one of the rows might contain the list [0,1]; I select the first value that shows up.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51653110
downvote count: 0

http://stackoverflow.com/q/51716723
favorite count: 0
type: Question
tagged with: python
has title: Xlsxwriter change format colour based on if statement
has answer: http://stackoverflow.com/a/51717357
upvote count: 2
tagged with: xlsxwriter
answer count: 1
has body: I have a python script that creates a report. I would like to apply colour a to row a and then colour b to row b, ... I could create a variable formatA = workbook.add_format({'bg_color': 'red'}) and formatB = workbook.add_format({'bg_color': 'blue'}) and so on. However, I think it would be easier to do format = workbook.add_format({'bg_color': 'red'}) and then when I loop through the rows I want to use, do format.set_bg_color('blue') and apply it. However, it does not change the background colour and only applies blue to every row.
accepted answer: http://stackoverflow.com/a/51717357
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/51755772
answers question: http://stackoverflow.com/q/51755504
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Try the following: column_groups = [A, B, C] masks = [(df[cols] != 0).any(axis=1) for cols in column_groups] full_mask = np.logical_and.reduce(masks) full_df = df[full_mask]

http://stackoverflow.com/a/51684273
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51683391
accepted answer of: http://stackoverflow.com/q/51683391
type: Answer
has comment: http://stackoverflow.com/comment/90662030
has body: You can try and use the alias shown below, but before you do so you should upgrade to oitnb&gt;0.1.3 or use the following replacement for omeld.py: import sys import os def main(): # print('omeld:', os.getcwd(), sys.argv[1:]) assert len(sys.argv) == 3, 'omeld: expecting two arguments' runs = 0 for idx, arg in enumerate(sys.argv[1:]): assert os.path.exists(sys.argv[1]), f'omeld: parameter {idx}, cannot find "{arg}"' rp = os.path.realpath(arg) # check if you are on a temporary directory, so there is less chance to screw up if rp.startswith('/tmp/') or rp.startswith('/var/tmp/'): runs += 1 os.system('oitnb -q ' + rp) if runs &gt; 0: os.system('meld ' + ' '.join(sys.argv[1:])) else: print('could not run oitnb on "{}" or "{}"'.format(*sys.argv[1:])) if __name__ == '__main__': main() because the version distributed with oitnb=0.1.3 can format files in your source directory if you compare on old version against the current state. In git this seems to happen more often (it seems optimized to not create a temporary file, even e.g. if the current version of a file has not changed since the commit of the second revision). The alias: alias gomeld='git difftool --extcmd=/path/to/omeld -y' I have looked at changing the config, but have not got that to work either.
upvote count: 1
score: 1

http://stackoverflow.com/a/51708978
answers question: http://stackoverflow.com/q/51708778
accepted answer of: http://stackoverflow.com/q/51708778
has body: The global seem cannot receive the same context in the other files. Maybe some "cyclical dependencies" problem. Once you imported it, ABC_ACTIVATE becomes local in the context of that script. Therefore, mutating the variable in build.py won't reflect in your other module. So my question is: Is there any better structure solution? One thing you could is create an intermediary method that return the ABC_ACTIVATE Boolean in your build.py. def is_abc_activated(): return ABC_ACTIVATE and then importing it like so, from build import activate_abc, is_abc_activated print(is_abc_activated()) activate_abc() print(is_abc_activated()) &gt;&gt;&gt;&gt; False True Basically, this will remove your unconditional import from build import * which is an anti-idiom in Python. Also, it will increase readability since accessing ABC_ACTIVATE can be confusing on what exactly you're doing.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90341646
type: QuestionComment
has text: [One more dupe](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly)
type: Comment
comment on: http://stackoverflow.com/q/51689901
score: 0

http://stackoverflow.com/q/51764009
tagged with: nested-lists
upvote count: 2
accepted answer: http://stackoverflow.com/a/51764187
has answer: http://stackoverflow.com/a/51764086
has answer: http://stackoverflow.com/a/51764195
has title: Creating a list of the minimum values of a nested list by index
answer count: 4
tagged with: min
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51764187
favorite count: 0
has answer: http://stackoverflow.com/a/51764160
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/51764160
has body: I have a series of nested lists of the same length (the number of lists varies): list1=[[5.5,4,6.21,3.4,8.1,3.8],[3.8,2.1,5.1,4,12.3,2.4],[4,2.11,8.2,3.6,4.5,2]] I'm trying to create a list of the smallest number per index of each list, i.e. list2=[3.8,2.1,5.1,3.4,4.5,2] Really unsure of where to start, other than the answer being either a list comprehension or for loop...
tagged with: list

http://stackoverflow.com/a/51676680
has body: @model.Constraint(model.TASKS, model.TASKS, model.MODELS) def rest1(m, i, p, j): if p in predecessor[i]: return sum(t * m.x[i, t, j] for t in m.PERIODS) &gt;= ( sum(t * m.x[p, t, j] for t in m.PERIODS) + model.timepo[p]) else: return Constraint.NoConstraint
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51675781
has comment: http://stackoverflow.com/comment/90356646
answers question: http://stackoverflow.com/q/51675781
type: AcceptedAnswer

http://stackoverflow.com/a/51714409
accepted answer of: http://stackoverflow.com/q/51714189
answers question: http://stackoverflow.com/q/51714189
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can pass a dictionary to pandas.DataFrame.astype d = {k: v.astype({'col1': float}) for k, v in d.items()}
upvote count: 2

http://stackoverflow.com/a/51690030
type: Answer
has comment: http://stackoverflow.com/comment/90342582
has comment: http://stackoverflow.com/comment/90342197
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90341916
has comment: http://stackoverflow.com/comment/90341977
answers question: http://stackoverflow.com/q/51690006
has body: You gave your blueprint a URL prefix: api_bp = Blueprint('api', __name__, template_folder='templates', url_prefix='/api') and again with app.register_blueprint(api_bp, url_prefix='/api') That means you need to use hostname/api/ to get to get_monkey_api() view function, or hostname/api/xxxx to get to the monkey_api() view function. Remove the URL prefixes if you want the routes to be found at the site root. If you want the blueprint to work for a separate subdomain, then use the subdomain='api' option, not a URL prefix. Note that for subdomains to work, you need to configure the SERVER_NAME config option so that subdomains can be detected. If you want to test this locally, edit your /etc/hosts file to add some development aliases that point to your server, then set SERVER_NAME to match.
downvote count: 0

wikipedia-api
tag name: wikipedia-api
type: Tag
tags question: http://stackoverflow.com/q/51688163

http://stackoverflow.com/q/51705871
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/90372467
type: AnsweredQuestion
has body: I am trying to write a simple program which will turn lights on and off based on the time of day, in Python 3. I keep on getting a syntax error when try and use except KeyboardInterrupt: in a while loop. This is the error: except KeyboardInterrupt: ^ SyntaxError: invalid syntax As I have doubled checked the syntax with online documentation I am at a loss as to what I am doing wrong and I guess I am missing some piece of understanding here. Here is the full code for reference: #!/usr/bin/python import time import datetime TimeStart = datetime.time(17, 0, 0) TimeEnd = datetime.time(18, 30, 0) def onoff(): while True: if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time(): print("Pin 18 High") else: print("Pin 18 Low") except KeyboardInterrupt: pass print("Error..... Quiting.....") raise sys.exit() time.sleep(30) onoff()
has title: Why is this usage of "except" a syntax error in Python 3?
tagged with: syntax
upvote count: 2
accepted answer: http://stackoverflow.com/a/51705979
linked to: http://stackoverflow.com/q/730764
tagged with: except
type: Question
downvote count: 5
has comment: http://stackoverflow.com/comment/90372460
answer count: 1
has comment: http://stackoverflow.com/comment/90372589
favorite count: 0
has answer: http://stackoverflow.com/a/51705979
has comment: http://stackoverflow.com/comment/90372469

http://stackoverflow.com/q/51797422
has answer: http://stackoverflow.com/a/51800985
favorite count: 0
has body: This is my code to generate all the Hamming Numbers (aka 5-smooth-Numbers) under a given limit. https://en.wikipedia.org/wiki/Smooth_number In number theory, a smooth (or friable) number is an integer which factors completely into small prime numbers. For example, a 7-smooth number is a number whose prime factors are all at most 7, so 49 = 7^2 and 15750 = 2 × 32 × 53 × 7 are both 7-smooth, while 11 and 702 = 2 × 33 × 13 are not I know of other ways to generate the numbers, however the function I first made makes sense to me and was wondering how to expand this to 7-smooth, 11-smooth, ..., n-smooth-numbers. Is there a simpler way to change my function to loop through the primes below the limit without adding lines of very similar code? import math def HammingFiveUnder(limit): hammings = [] exp2 = int(math.log(limit, 2)) exp3 = int(math.log(limit, 3)) exp5 = int(math.log(limit, 5)) for i in range(0, exp2+1): for j in range(0, exp3+1): for k in range(0, exp5+1): poss_ham = 2**i * 3**j * 5**k if poss_ham &lt;= limit: hammings.append(poss_ham) return sorted(hammings) print(HammingFiveUnder(100))
type: Question
possible better answer: http://stackoverflow.com/a/51801036
has answer: http://stackoverflow.com/a/51801036
tagged with: python
has comment: http://stackoverflow.com/comment/90552803
has title: Produce Generalised Hamming Numbers Python
upvote count: 3
accepted answer: http://stackoverflow.com/a/51800985
downvote count: 1
tagged with: number-theory
has answer: http://stackoverflow.com/a/51799244
answer count: 3
has comment: http://stackoverflow.com/comment/90552855
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/90519090
score: 0
has text: Hi krishna, the columns C and D are extracted from df2 by the index 5. it is a bit misleading, I'll edit the example
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51780710

http://stackoverflow.com/q/51716239
has answer: http://stackoverflow.com/a/51716413
type: UnansweredQuestion
has title: How to append http to text file for each url
has comment: http://stackoverflow.com/comment/90393751
has comment: http://stackoverflow.com/comment/90393805
type: Question
has answer: http://stackoverflow.com/a/51716715
has comment: http://stackoverflow.com/comment/90393794
score: 0
answer count: 2
has body: I have a large list of URLs without the http header. I am trying to accomplish two things: Read the text file of URLs that do not have the HTTP header exp (www.google.com) and split them into 1000 chunk text files. Append "http://" to each link exp (http://www.google.com) Currently I am only able to accomplish the first step. from itertools import zip_longest def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx args = [iter(iterable)] * n return zip_longest(fillvalue= fillvalue, *args) n = 1000 with open('sites.txt') as f: for i, g in enumerate(grouper(n, f, fillvalue=''), 1): with open('s_{0}'.format(i), 'w') as fout: fout.writelines(g)
tagged with: python

http://stackoverflow.com/q/51640496
accepted answer: http://stackoverflow.com/a/51640754
linked to: http://stackoverflow.com/q/39155242
linked to: http://stackoverflow.com/q/30487380
has comment: http://stackoverflow.com/comment/90278674
has body: I am matching digits in str using a regex in Python. My desire is to capture numbers that might have a thousands separator (for me, a comma or a space) or can just be a string of numbers. The following shows what my regex captures &gt;&gt;&gt; import re &gt;&gt;&gt; test = '3,254,236,948,348.884423 cold things, ' + \ '123,242 falling birds, .84973 of a French pen , ' + \ '65 243 turtle gloves, 8 001 457.2328009 units, and ' + \ '8d523c.' &gt;&gt;&gt; matches = re.finditer(ANY_NUMBER_SRCH, test, flags=re.MULTILINE) &gt;&gt;&gt; for match in matches: ... print (str(match)) ... &lt;_sre.SRE_Match object; span=(0, 24), match='3,254,236,948,348.884423'&gt; &lt;_sre.SRE_Match object; span=(27, 34), match='123,242'&gt; &lt;_sre.SRE_Match object; span=(37, 43), match='.84973'&gt; &lt;_sre.SRE_Match object; span=(46, 52), match='65 243'&gt; &lt;_sre.SRE_Match object; span=(55, 72), match='8 001 457.2328009'&gt; &lt;_sre.SRE_Match object; span=(73, 74), match='8'&gt; &lt;_sre.SRE_Match object; span=(75, 78), match='523'&gt; This is the matching behavior I want. Now, I want to take each of the matched numbers and remove the thousands separators (',' or ' ') if they exist. This should leave me with '3254236948348.884423 cold things, ' + \ '123242 falling birds, .84973 of a French pen ,' + \ '65243 turtle gloves, 8001457.2328009 units, ' + \ 'and 8d523c.' Basically, I have one regex to capture the number. This regex is used in multiple places, e.g. to find dollar amounts, to get ordinal numbers, ... For this reason, I've named the regex, ANY_NUMBER_SRCH. What I want to do is something like the following: matches = some_method_to_get_all_matches(ANY_NUMBER_SRCH) for match in matches: corrected_match = re.sub(r"[, ]", "", match) change_match_to_corrected_match_in_the_test_string As things are, I can not use substitution groups. If you just want to see the regex, you can check out https://regex101.com/r/AzChEE/3 Basically, part of my regex is as follows r"(?P&lt;whole_number_w_thou…
linked to: http://stackoverflow.com/q/1327369
has title: re.sub after matching. all instances of a repeated matching group, python
tagged with: python
tagged with: string-matching
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: replace
linked to: http://stackoverflow.com/q/39213585
tagged with: string
has comment: http://stackoverflow.com/comment/90245640
upvote count: 1
has comment: http://stackoverflow.com/comment/90278227
answer count: 1
tagged with: regex
has answer: http://stackoverflow.com/a/51640754

http://stackoverflow.com/a/51675252
score: 2
accepted answer of: http://stackoverflow.com/q/51675198
has body: You need below to get the first date of the month. df['date'] = df['date'].dt.to_period('M').dt.to_timestamp() Output: date arb1 arb2 amount 0 2018-02-01 Z F 5 1 2018-01-01 G H 10 2 2018-02-01 V T 51 3 2018-03-01 R S 54
has comment: http://stackoverflow.com/comment/90313600
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90314952
has comment: http://stackoverflow.com/comment/90314328
has comment: http://stackoverflow.com/comment/90314908
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51675198

http://stackoverflow.com/q/51723380
has answer: http://stackoverflow.com/a/51723906
possible better answer: http://stackoverflow.com/a/51723506
has title: How to know the occurrence of a text in row of data frame pandas python
tagged with: python
type: AnsweredQuestion
tagged with: row
has body: C1 0 John 1 John 2 John 3 Michale 4 Michale 5 Newton 6 Newton 7 John 8 John 9 John I want to know how many time John occurred row wise. Suppose John occurred from 0 to 2 In result i want from 0 to 2 John. from 3 to 4 Michel from 5 to 6 Newton Result I want in this format: Start End Name 0 2 John 3 4 Michale 5 6 newton 7 9 John
type: Question
accepted answer: http://stackoverflow.com/a/51723906
tagged with: dataframe
has answer: http://stackoverflow.com/a/51723506
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/90302674
type: Comment
comment on: http://stackoverflow.com/a/51648297
score: 0
type: AnswerComment
has text: @AbhijitGhate : Great!! You can replace lines 9-14 to just `k= map(lambda x:{'id':x, 'count':count_dict[x]}, count_dict)`

http://stackoverflow.com/a/51776632
answers question: http://stackoverflow.com/q/51776507
score: 1
has comment: http://stackoverflow.com/comment/90511758
upvote count: 1
has comment: http://stackoverflow.com/comment/90512772
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90513195
accepted answer of: http://stackoverflow.com/q/51776507
has body: Your problem is that global CurrentID. That means there's a single value shared by all users. Consider this flow: User 1 starts an offer, and the ID gets bumped to 23. While you're waiting for user 1's price, user 2 starts an offer, and the ID gets bumped to 24. While you're waiting for user 1's price and for user 2's price, one of them responds, and you update the price for item 24. Then the other one responds, and you update the price for item 24 again. So, item 24 ends up with the price set by whichever user came last, and meanwhile, item 23 never gets updated at all, so its price is presumably still NULL (or whatever your default is). So, first, you need to change get_item_price to take an ID as a parameter, instead of using the global: def get_item_price(ItemID, message): # now use ItemID instead of CurrentID And then you need to pass in the right value: bot.register_next_step_handler(msg, functools.partial(get_item_price, ItemID)) But how do you get that ItemID in a way that can't be interfered with by anyone else working at the same time? I actually know nothing about Telegram. If it works by coroutines, you can be sure that you haven't been interrupted between that CurrentID = CurrentID + 1 and the first potentially blocking call, which presumably is the message send, so you can just do this: def get_item_name(message): global CurrentID CurrentID = CurrentID + 1 ItemID = CurrentID # now use ItemID instead of CurrentID If, on the other hand, it works by threads, where you can be interrupted at any time, you need some kind of synchronization mechanism, like a lock: id_lock = threading.Lock() def get_item_name(message): global CurrentID with id_lock: CurrentID = CurrentID + 1 ItemID = CurrentID # now use ItemID instead of CurrentID As suggested by the OP in a comment, there's an even better solution here if you can change the database schema—just make the ItemID auto-incrementing. In MySQL, that's: ItemID INTEGER PRIMARY KEY AUTO_INCREMENT Then, change your INS…
type: Answer

http://stackoverflow.com/q/51717210
tagged with: python-3.x
tagged with: binary
upvote count: 3
type: Question
type: AnsweredQuestion
score: 3
has body: I am generating the input for an FPGA program to use the trapezoidal integration method. Basically, the functions of interest here are the invert() and twos_comp() functions; the rest is just testing (creating a square wave signal, and then iterating through and converting it into two's complement). signals = [] bit_signals = [] def invert(bit_val): new_val = [] for i in bit_val: new_val.append(str(int(not(int(i))))) return ''.join(new_val) def twos_comp(val): if val &lt; 0: bin_val = format(val, '08b')[1:] return format(int(invert(bin_val),2) + int('1', 2), '08b') else: bin_val = format(val, '08b')[1:] return bin_val x = 0 signal = 1 while x &lt;= 25: if x % 2 == 0: signal*=-1 signals.append(signal) x+=1 print(signals) for i in signals: bit_signals.append(twos_comp(i)) print(bit_signals) The problem here is that this outputs the two's complement for 1 as 01111111, not 1111111. The output of invert() seems to be correct, the output for twos_comp() for positive numbers seems to be correct, and the generation of the signal also appears to be correct, so I think it must be something with the line return format(int(invert(bin_val),2) + int('1', 2), '08b') but looking around on SO and google this is how other people have handled adding in binary. Please note that all inputs to twos_comp() will be 8 bits. Any help would be appreciated as to why this is not working. There are no outright errors, just an incorrect output. You can run the code here.
tagged with: 8-bit
tagged with: twos-complement
has title: Two's complement function outputs wrong result for -1
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51717242
accepted answer: http://stackoverflow.com/a/51717242
tagged with: python

http://stackoverflow.com/comment/90559658
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51784570
has text: Yes, an MCVE is hard to produce.
score: 0

http://stackoverflow.com/comment/90424109
type: Comment
type: QuestionComment
score: 0
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. There is no attribute `probability` in your class; the code is hardly minimal; you've used a variety of one-letter and other generic names that don't facilitate others debugging your code.
comment on: http://stackoverflow.com/q/51731403

http://stackoverflow.com/comment/90388812
type: Comment
has text: Wow, thank you for all that research! I'm grateful for your time on this, but it's convinced me that I ought to just put the contents of `functions.py` into `__init__.py` and be done with it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51664031
score: 0

http://stackoverflow.com/q/51792291
tagged with: python
answer count: 4
has title: Dataframe: select different index for each columns
type: AnsweredQuestion
score: 2
has body: Suppose I have the following pandas DataFrame: from pandas import DataFrame from numpy import arange lst = [ range(10), range(11,21), range(21,31) ] df = DataFrame(lst).T.set_index(arange(0.1, 1.1, 0.1)) 0 1 2 0.1 0 11 21 0.2 1 12 22 0.3 2 13 23 0.4 3 14 24 0.5 4 15 25 0.6 5 16 26 0.7 6 17 27 0.8 7 18 28 0.9 8 19 29 1.0 9 20 30 I would like to select each column using a different index range. For example for the column: 0: I would like to have only the row with index 0.6 to 0.9 1: I would like to have only the row with index 0.2 to 0.3 2: I would like to have only the row with index 0.1 to 0.3 So my DataFrame should be like this: 0 1 2 0.1 NaN NaN 21.0 0.2 NaN 12.0 22.0 0.6 5.0 NaN NaN 0.7 6.0 NaN NaN 0.8 7.0 NaN NaN 0.9 8.0 NaN NaN My current solution is this one: idx = array([ [0.6, 0.9], [0.2, 0.3], [0.1, 0.3] ]) df2 = DataFrame((df[col][i[0]:i[1]] for i, col in zip(idx, df))).T Maybe is not the better solution. Thanks everybody for the answers. Comparison I wrote a script to benchmark each answer. The benchmark is divided in two: STD: answer that works only with standard index (0,1,2,3,...) GEN: answer that works with a general index from numpy import arange, array, linspace from numpy.random import rand, randint from pandas import DataFrame from timeit import Timer # yellowhat def yellowhat(df, idx): df2 = DataFrame((df[col][i[0]:i[1]] for i, col in zip(idx, df))).T return df2 # user3483203 def user3483203(df, idx): from numpy import arange r = arange(df.shape[0])[:, None] m = (idx[:,0] &lt;= r) &amp; (idx[:,1] &gt; r) df2 = df.mask(~m).dropna(how='all') return df2 def user3483203_2(df, idx): from numpy import zeros, bool8, arange def foo(a, idx): out = zeros(a, dtype=bool8) for (i, j), k in zip(idx, arange(a[1])): out[i:j, k] = True return out df2 = df.mask(~foo(df.shape, idx)).dropna(how='all') return df2 def user3483203_mod(df, idx): r = df.index.values[:,None] m = (r &gt;= idx[:,0]) &amp; (r &lt;= idx[:,1]) df2 = df.mask(~m).dropna(how='all') return df2 # d…
has answer: http://stackoverflow.com/a/51792647
has answer: http://stackoverflow.com/a/51793259
type: Question
possible better answer: http://stackoverflow.com/a/51792431
has answer: http://stackoverflow.com/a/51792431
downvote count: 0
has answer: http://stackoverflow.com/a/51793033
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51793259
linked to: http://stackoverflow.com/q/51793486
favorite count: 0
upvote count: 2

http://stackoverflow.com/a/51664849
has comment: http://stackoverflow.com/comment/90293241
has comment: http://stackoverflow.com/comment/97959352
has comment: http://stackoverflow.com/comment/90292989
has comment: http://stackoverflow.com/comment/90293055
score: 1
has comment: http://stackoverflow.com/comment/90293107
upvote count: 1
has body: Firebase-specific triggers (including Firestore) are currently not supported for python and gcloud. EDIT gcloud now has support for writing and deploying Firestore triggers in all supported languages.
has comment: http://stackoverflow.com/comment/90293408
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90293166
has comment: http://stackoverflow.com/comment/90293350
has comment: http://stackoverflow.com/comment/90292975
accepted answer of: http://stackoverflow.com/q/51664813
type: Answer
answers question: http://stackoverflow.com/q/51664813

http://stackoverflow.com/comment/90489633
score: 0
type: AnswerComment
type: Comment
has text: It works fine like this for csv files thank you! Would you have a similar solution for pickle files? As I write and read the files a lot of times, pickle yield faster performances.
comment on: http://stackoverflow.com/a/51764089

http://stackoverflow.com/q/51657361
has body: I've created a class called Colors() that has some lists defined in it. I have a method in it called set_alpha() that has to append the index 3 of the list with the parameter provided. Here's the block of code: class Colors(): self.red = (255, 0, 0) self.blue = (0, 0, 255) self.green = (0, 255, 0) def set_alpha(self, alpha): self[3] = alpha I knew this would be wrong before I even typed it because I do not understand the self thing well. It gives an error saying self is not defined. What I want the result of my class is something like this - When I do- Colors.red.set_alpha(128) I want red to become- red = (255, 0, 0, 128) Please explain EDIT: How do I solve my problem now? How do I use the method set_alpha() on a variable in the class?
tagged with: python
has title: What exactly does self variable do? How do I use it in this case?
accepted answer: http://stackoverflow.com/a/51657408
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/2709821
tagged with: class
score: 0
has answer: http://stackoverflow.com/a/51657408
duplicate of: http://stackoverflow.com/q/2709821
answer count: 1
tagged with: self

http://stackoverflow.com/a/51681397
has comment: http://stackoverflow.com/comment/90356459
upvote count: 1
has comment: http://stackoverflow.com/comment/90339145
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51679932
has comment: http://stackoverflow.com/comment/90356683
has comment: http://stackoverflow.com/comment/90327854
has body: You are defining a method that contains the chromedriver launch and then running through the method once (not looping) so each method call generates a new browser instance. Instead of doing that, do something more like this... url = 'https://www.nike.com/launch/?s=in-stock' driver.get(url) # toggle grid view WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='Show Products as List']"))).click(); # wait for shoes to drop while not driver.find_elements((By.XPATH, "//div[@class='figcaption-content']//h3[contains(.,'MOON RACER')]")) print("SNKR has not dropped") time.sleep(300) // 300s = 5 mins, don't spam their site driver.get(url) print("SNKR has dropped") I simplified your code, changed the locator, and added a loop. The script launches a browser (once), loads the site, clicks the grid view toggle button, and then looks for the desired shoe to be displayed in this list. If the shoes don't exist, it just sleeps for 5 mins, reloads the page, and tries again. There's no need to refresh the page every 1s. You're going to draw attention to yourself and the shoes aren't going to be refreshed on the site that often anyway.
type: Answer
has comment: http://stackoverflow.com/comment/90356439
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90334360
accepted answer of: http://stackoverflow.com/q/51679932

http://stackoverflow.com/comment/90415647
comment on: http://stackoverflow.com/a/51727375
type: AnswerComment
score: 0
type: Comment
has text: Thanks so much for answer, it's working. I have to read up on nested list comprehension though, as i can't really write any just out of my head.

http://stackoverflow.com/comment/90555230
has text: Reuse the driver. You're basically using 10000 different ones. That takes a lot of time. So instantiate driver before your for-loop. And move the quit-command down at the bottom. You could consider reverse engimeering the site and see if it's possible to extract the data without selenium. Use chrome and imspect what happens in the networls tab once you click the bm-element. Perhaps you can fetch the data from the same endpoimt directly - like the site does. That's most often possible and much faster than browser automation...
comment on: http://stackoverflow.com/q/51792222
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91054100
type: AnswerComment
has text: Following this, add 'smart_selects' in settings.py and add 'from smart_selects.db_fields import ChainedForeignKey' in models.py. Use ChainedForeignKey as illustrated in the question.
type: Comment
comment on: http://stackoverflow.com/a/51775564
score: 1

http://stackoverflow.com/q/51738793
tagged with: numpy
tagged with: sparse-matrix
has body: I have numpy boolean matrix which contain about 2,000 slices and it's width, height is 512x512. print(bool_matrix.shape) #(512, 512, 2000) Some slices are all False matrix and I want to filter it out. I have wrote code below but I am wondering if there any faster way to do this? %%timeit _idx = np.any(bool_matrix, axis=(0,1)) result = np.compress(_idx, bool_matrix, axis=2) print(result.shape) #(512, 512, 457), filter out 1543 all False matrix 281 ms ± 2.95 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
tagged with: boolean
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has title: Fastest way to filter out all False matrix
upvote count: 1
type: Question

http://stackoverflow.com/comment/90433410
score: 0
type: Comment
has text: If you don't mind me asking, i've barely worked with the try and except functions. Would it be simple to add another ValueError for if the number inputted isn't 8-bit?
comment on: http://stackoverflow.com/a/51736337
type: AnswerComment

http://stackoverflow.com/comment/90504809
type: Comment
has text: I'd suggest saving a simple dataframe, and the look at file with `h5dump`(or other general purpose viewer) to get an idea of the structure pytables uses. `h5py` makes HDF5 groups to dictionary like, and datasets like numpy arrays.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51771889

http://stackoverflow.com/comment/90540535
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51789077
has text: @MariaPantsiou You are correct, pprint sorts your keys, I'll update the answer.
type: AnswerComment

http://stackoverflow.com/comment/90381713
has text: Use `for child in reversed(self.container.children):`. Please check out my solution at [TextInputs Validation](https://stackoverflow.com/questions/50153595/python-add-validation-in-form/50160963#50160963)
type: Comment
comment on: http://stackoverflow.com/a/51687001
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90458563
type: Comment
type: QuestionComment
has text: This makes sense, as the serial monitor you are opening in the Arduino IDE is the same serial interface that is being used by your python program, so you can't use them at the same time. Have you tried doing a read on the python side to see if the byte is being sent back from your `println`?
score: 1
comment on: http://stackoverflow.com/q/51749228

http://stackoverflow.com/comment/90331163
score: 0
type: Comment
type: QuestionComment
has text: Check your soup response it created correctly or not, it works for me.
comment on: http://stackoverflow.com/q/51682151

http://stackoverflow.com/a/72769558
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51649109
downvote count: 0
has body: Two steps - Save Keras model into text files in python In C++/C, read those text files, and run the model in a multithreading environment. Above Steps in detail For first step, call save_keras_model_as_text from keras2cpp.py on Github- save_keras_model_as_text(model, open('/content/modeltext.txt', 'w') ) save_keras_model_as_text(model, open('/content/modellayersonlytext.txt', 'w') , noweight=True) In c++/c projects, include keras.h /keras.cpp files. convert input image into Keras format or read input image into Keras format from a file. ''' //assume dst is pointer to an image object. This //can be of CxImage / CImg /OpenCV or of any other //library. int h = dst->GetHeight(); int w= dst->GetWidth();; int *img = new int[h*w*3]; int *img_r = img, *img_g =&img[h*w], *img_b=&img[2*h*w]; for (int y = 0; y < h; y++) { for (int x = 0; x < w;x++) { RGBQUAD rgb= dst->GetPixelColor(x,y); *img_r= rgb.rgbRed; img_r++; *img_g= rgb.rgbGreen; img_g++; *img_b = rgb.rgbBlue; img_b++; } } ''' Call ExecuteKerasSegmentation. ''' //text files in which keras model is saved. char *modelfile ="modellayersonlytext.txt"; char *weightfile="modeltext.txt"; int *result = ExecuteKerasSegmentation(img, h, w, 3, modelfile, weightfile); ''' result contains the segmentation result. You may save it into pgm file or convert it into your image library object and use it further. ''' save_image_pgm("segmentation_map.pgm",result,h,w,127); //127 is scaling factor for binary images. '''
type: Answer

http://stackoverflow.com/comment/90429932
score: 0
comment on: http://stackoverflow.com/q/51712989
type: Comment
type: QuestionComment
has text: Ah -- yep, that's it. Converted i to a float and data_out.max() returns 1000000.0. Changing a couple of other terms to make sure everything falls into the interpolation domain, and I get exactly the output that I'm looking for. Modifying the input to contourf so that I'm not trying to broadcast from target_grid into the function gives me the contour plot that I want as well. Time to try and replicate this in my other code. Thanks!

http://stackoverflow.com/comment/90399943
has text: Yes, you are right. I have always ignored this issue. It sovled my problem. Thank you very much
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51718067

http://stackoverflow.com/q/51789623
answer count: 1
tagged with: nose
accepted answer: http://stackoverflow.com/a/51789835
upvote count: 1
has body: Hello I am trying to CD into a specific path and run my nosetests through crontab. I have tried a bunch of stuff and none of it has worked yet: MAILTO = mail@yahoo.com * * * * * . /Users/pamili/resources/tests ; nosetests MAILTO = mail@yahoo.com Path = /Users/pamili/resources/test * * * * * Path/nosetests MAILTO = mail@yahoo.com Path = /Users/pamili/resources/test * * * * * Path =. nosetests None of it seems to work. Any suggestions are really helpful! Thanks
has title: Crontab- run nosetests from a specific path
tagged with: cron
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51789835
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/90420933
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51728054
has text: In your second edit, are you sure your indentation is correct? As presented, your while loop is going to run to completion before iterating over `p_rows`. I assume that `for packet in p_rows` is supposed to be under your `while self.running`
score: 0

http://stackoverflow.com/comment/90293107
has text: I'm not very familiar with gcloud, but I can tell you that it's not yet intended for developers to write Firebase-specific triggers in python.
comment on: http://stackoverflow.com/a/51664849
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51754897
has comment: http://stackoverflow.com/comment/96669911
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I am trying to train a 3D convnet with 3D spatial data using mxnet. When I run the program the loss decreases normally over epochs but the training accuracy and the test accuracy is staying exactly the same. I am very new to neural networks and I have no idea why this is happening. I am not sure if it is because my network parameters are bad or if my data isn't preprocessed properly, or if the code for training the network has problems, or something else entirely. Here is the code I am currently using for the convnet and the output it produces: train_data = mx.gluon.data.DataLoader(train_dataset, batch_size= 64,shuffle= True, num_workers = cpucount) test_data = mx.gluon.data.DataLoader(test_dataset,batch_size= 64,shuffle= True, num_workers = cpucount) batch_size = 64 num_inputs = 2541 num_outputs = 2 num_fc = 635 net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Conv3D(channels=1, kernel_size=3, activation='relu')) net.add(gluon.nn.MaxPool3D(pool_size=2, strides=2)) net.add(gluon.nn.Conv3D(channels=1, kernel_size=3, activation='relu')) net.add(gluon.nn.MaxPool3D(pool_size=2, strides=2)) net.add(gluon.nn.Flatten()) net.add(gluon.nn.Dense(num_fc, activation="relu")) net.add(gluon.nn.Dense(num_outputs)) net.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx) softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': .0001}) def evaluate_accuracy(data_iterator, net): acc = mx.metric.Accuracy() for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(ctx) label = label.as_in_context(ctx) output = net(data) predictions = nd.argmax(output,axis = 1) label = label.reshape(len(label)) acc.update(preds=predictions, labels=label) return acc.get()[1] epochs = 100 smoothing_constant = .01 for e in range(epochs): for i, (data, label) in enumerate(train_data): data = data.as_in_context(ctx) label = label.as_in_context(ctx) with autograd.record(): output = n…
has comment: http://stackoverflow.com/comment/92383967
tagged with: conv-neural-network
tagged with: mxnet
type: Question
has title: loss decreasing but accuracy stays the same for 3D convnet

http://stackoverflow.com/comment/90371258
type: Comment
type: QuestionComment
score: 2
has text: Have you tried the naive aproach of just looping over the whole image and collecting every unique color (i.e. keep a list/dict/whatever with every color seen so far)
comment on: http://stackoverflow.com/q/51705187

http://stackoverflow.com/q/51746788
tagged with: multithreading
has comment: http://stackoverflow.com/comment/90453752
tagged with: python
has body: I have a code like this: from twisted.internet import task from twisted.internet import reactor def Fun1(): print('No') communicate1 = task.LoopingCall(Fun1) communicate1.start(0.1) reactor.run() while True: print('yes') time.sleep(1) Shouldn't it run Func1 and the while loop simultaneously? What's wrong with it? It only prints No.
score: 0
type: Question
tagged with: multiprocessing
has title: Multi Processing in python with reactor
has comment: http://stackoverflow.com/comment/90453863
tagged with: twisted
answer count: 1
has comment: http://stackoverflow.com/comment/90453672
has answer: http://stackoverflow.com/a/51747165
type: UnansweredQuestion

http://stackoverflow.com/comment/90286718
comment on: http://stackoverflow.com/q/51661522
has text: Are your objects sprites in pygame? If so, there is better collision detection. Please be more specific about the data types and environment you are using.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51771418
answers question: http://stackoverflow.com/q/51771128
score: 1
downvote count: 0
has body: A little bit hard to understand,I think this should be slightly faster than apply By using reindex and repeat df.reindex(df.index.repeat(df['end']-df['start']+1)).assign(year=lambda x : x['start']+x.groupby('id').cumcount()) Out[453]: id start end year 0 1 2009 2014 2009 0 1 2009 2014 2010 0 1 2009 2014 2011 0 1 2009 2014 2012 0 1 2009 2014 2013 0 1 2009 2014 2014 1 2 2010 2012 2010 1 2 2010 2012 2011 1 2 2010 2012 2012
type: Answer
upvote count: 1

http://stackoverflow.com/q/51714019
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51714137
has answer: http://stackoverflow.com/a/51714173
possible better answer: http://stackoverflow.com/a/51714231
has answer: http://stackoverflow.com/a/51714231
has comment: http://stackoverflow.com/comment/90389565
has comment: http://stackoverflow.com/comment/90389659
score: 0
has comment: http://stackoverflow.com/comment/90389501
tagged with: pandas
has body: I have a datagram like below lable unigrams ham [ive, searching, right, word, thank, breather, i, promise, wont] spam [free, entry, 2, wkly, comp, win, fa, cup, final, tkts, 21st, may] I want to count the distinct/ unique ham unigrams and distinct spam unigrams. I can count the distinct values in a column using df.unigrams.nunique(). I can count the number of occurrences of a given unigram in ham using unigramCount = unigramCorpus.loc["ham", "unigrams"].count('ive') But how can I count the number of distinct values in a given list? Ex: ["ham", "spam"] Expected output: ham = 9 spam = 12
has answer: http://stackoverflow.com/a/51714137
tagged with: python
has comment: http://stackoverflow.com/comment/90389600
tagged with: nlp
answer count: 4
has answer: http://stackoverflow.com/a/51714166
has title: Count distinct values in Python list
type: Question

http://stackoverflow.com/a/51677761
type: Answer
accepted answer of: http://stackoverflow.com/q/51677539
has body: What you're asking for doesn't really make sense with the way classes work in Python. vars already does filter out inherited attributes from base classes. But self.a isn't inherited. It's explicitly added to your self instance, because your __init__ explicitly calls super().__init__(). There's really nothing special about that call—if your __init__ called self.addx() and a Derived.addx method did a self.x = 0, it would work exactly the same way as what you're doing here. You could write a decorator to do what you're trying to do, but maybe it's better to take a step back. Why not store the list of fields you expect each class to provide as part of the class? Or, since you seem to be trying to simulate something more like Java-style classes, where the set of attributes is fixed per class, why not just use @dataclass (or, if you need pre-3.7 compatibility or extra features, the third-party @attr.s)? That automatically takes care of keeping track of which fields belong to which class, and a whole lot of other things along with it. &gt;&gt;&gt; from dataclasses import dataclass, fields &gt;&gt;&gt; &gt;&gt;&gt;&gt; @dataclass ... class Base: ... a: int = 0 ... &gt;&gt;&gt; @dataclass ... class Derived(Base): ... b: int = 1 ... &gt;&gt;&gt; derived = Derived() &gt;&gt;&gt; derived Derived(a=0, b=1) &gt;&gt;&gt; def ownfields(obj): ... fs = fields(obj) ... for base in type(obj).__bases__: ... basefs = set(fields(base)) ... fs = [f for f in fs if f not in basefs] ... return fs ... &gt;&gt;&gt; ownfields(derived) [Field(name='b',type=&lt;class 'int'&gt;,default=1,default_factory=&lt;dataclasses._MISSING_TYPE object at 0x10571ca58&gt;,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)] &gt;&gt;&gt; def ownvars(obj): ... return {field.name: getattr(obj, field.name) for field in ownfields(obj)} ... &gt;&gt;&gt; ownvars(derived) {'b': 1} (With attrs instead of dataclasses, you can do effectively the same thing—but it might be clearer to wri…
has comment: http://stackoverflow.com/comment/90319420
has comment: http://stackoverflow.com/comment/90319723
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51677539

http://stackoverflow.com/comment/90330080
type: Comment
type: QuestionComment
has text: `(tensorflow_p36) ubuntu@ip-xx:~/xx/xx$ python --version Python 3.6.6 :: Anaconda, Inc.` `(tensorflow_p36) ubuntu@ip-xx:~/xx/xx$ source deactivate` `ubuntu@ip-xx:~/xx/xx$ python --version Python 3.6.4 :: Anaconda, Inc.`
score: 0
comment on: http://stackoverflow.com/q/51683574

lxml
tags question: http://stackoverflow.com/q/51715352
tags question: http://stackoverflow.com/q/51679188
tags question: http://stackoverflow.com/q/51685551
type: Tag
tags question: http://stackoverflow.com/q/51655130
tags question: http://stackoverflow.com/q/51689111
tags question: http://stackoverflow.com/q/51760142
tags question: http://stackoverflow.com/q/51642426
tags question: http://stackoverflow.com/q/51743583
tags question: http://stackoverflow.com/q/51663687
tags question: http://stackoverflow.com/q/51658528
tag name: lxml
tags question: http://stackoverflow.com/q/51748942
tags question: http://stackoverflow.com/q/51679512
tags question: http://stackoverflow.com/q/51660134
tags question: http://stackoverflow.com/q/51699180
tags question: http://stackoverflow.com/q/51670562
tags question: http://stackoverflow.com/q/51643332

http://stackoverflow.com/comment/90340809
has text: The command "break" will cause the loop to terminate. Simply place it under whatever conditional you want to cause the loop to end. Realize, any code after the while loop _will_ execute (there is no code after it in your example though).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51689442

http://stackoverflow.com/a/51734632
has body: Store your model fit as a variable results, like so: import statsmodels.api as sm model = sm.OLS(y,x) results = model.fit() Then create a a function like below: def results_summary_to_dataframe(results): '''take the result of an statsmodel results table and transforms it into a dataframe''' pvals = results.pvalues coeff = results.params conf_lower = results.conf_int()[0] conf_higher = results.conf_int()[1] results_df = pd.DataFrame({"pvals":pvals, "coeff":coeff, "conf_lower":conf_lower, "conf_higher":conf_higher }) #Reordering... results_df = results_df"coeff","pvals","conf_lower","conf_higher" return results_df You can further explore all the attributes of the results object by using dir() to print, then add them to the function and df accordingly.
score: 27
has comment: http://stackoverflow.com/comment/90548627
has comment: http://stackoverflow.com/comment/122419008
type: Answer
answers question: http://stackoverflow.com/q/51734180
has comment: http://stackoverflow.com/comment/90471042
upvote count: 27
downvote count: 0

http://stackoverflow.com/comment/90377380
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51708044
has text: Also give your class a `__repr__` method so you can print instances of the class and see what the values of its attributes are.

http://stackoverflow.com/q/51742293
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90444842
has answer: http://stackoverflow.com/a/51742430
downvote count: 3
has body: I know this might be a simple question but I can't seem to figure how to put a string after the for loop variable stud_num = int(input("How many students do you have? ")) test_num = int(input("How many test for your module? ")) score = 0 for i in range(stud_num): print("******** Student #", i+1, "********") for s in range(test_num): print("Test number ", end="") score1 = float(input(s+1)) score += score1 My sample output for asking the question would be Test number 1 : but now my current output from print("Test number ", end="") score1 = float(input(s+1)) is Test number 1 I can't figure out how to put the ": " into the input because it gives me an error saying that it expects an int but gets a str
type: Question
has comment: http://stackoverflow.com/comment/90444790
has comment: http://stackoverflow.com/comment/90444762
has comment: http://stackoverflow.com/comment/90444724
has comment: http://stackoverflow.com/comment/90444771
accepted answer: http://stackoverflow.com/a/51742430
has title: Python 3 Input(prompt) function
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/51742617
has comment: http://stackoverflow.com/comment/90444670
has answer: http://stackoverflow.com/a/51742617
linked to: http://stackoverflow.com/q/20449427
favorite count: 0
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/90444540

http://stackoverflow.com/q/51701542
has body: Given the following models: from django.db import models class FooQuerySet(models.QuerySet): def with_baz(self): return self.annotate(baz=models.F('pk')) class Foo(models.Model): objects = FooQuerySet.as_manager() class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) And the following setup: In[2]: from main.models import * In[3]: f = Foo.objects.create() In[4]: b = Bar.objects.create(foo=f) How can I build query which orders Bar objects by Foo.baz field? Tried the following: In[5]: from django.db.models import Prefetch In[6]: Bar.objects.prefetch_related(Prefetch('foo', queryset=Foo.objects.with_baz())).order_by('foo__baz') Error: Traceback (most recent call last): File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/core/formatters.py", line 224, in catch_format_error r = method(self, *args, **kwargs) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/core/formatters.py", line 702, in __call__ printer.pretty(obj) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/lib/pretty.py", line 400, in pretty return _repr_pprint(obj, self, cycle) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/IPython/lib/pretty.py", line 695, in _repr_pprint output = repr(obj) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 248, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __iter__ self._fetch_all() File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 1179, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/soon/anaconda3/envs/django-main/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.ch…
score: 2
has comment: http://stackoverflow.com/comment/90364862
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90364784
has title: How can I order by nested annotated field?
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python

io
tags question: http://stackoverflow.com/q/51749747
tags question: http://stackoverflow.com/q/51664405
tags question: http://stackoverflow.com/q/51731125
tag name: io
tags question: http://stackoverflow.com/q/51745110
tags question: http://stackoverflow.com/q/51792126
tags question: http://stackoverflow.com/q/51652586
tags question: http://stackoverflow.com/q/51766677
tags question: http://stackoverflow.com/q/51750967
type: Tag
tags question: http://stackoverflow.com/q/51682092
tags question: http://stackoverflow.com/q/51662181
tags question: http://stackoverflow.com/q/51743671
tags question: http://stackoverflow.com/q/51745485
tags question: http://stackoverflow.com/q/51747315

http://stackoverflow.com/comment/90399366
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51718908
has text: that doesn't explain why you are using such an old version

http://stackoverflow.com/comment/90355636
type: AnswerComment
score: 0
type: Comment
has text: `.pyx` files are just a special case of this problem. They're Cython files, which Cython can compile to C source code—and that part could work on Pythonista—but that C source needs to be compiled to native code and built into an extension, and that part _can't_ work on Pythonista.
comment on: http://stackoverflow.com/a/51679635

http://stackoverflow.com/comment/90821641
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51826289
type: Comment
has text: FYI, I am having this issue in ver `10.13.3`.

http://stackoverflow.com/comment/90394927
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51716854
has text: It sounds like you want a `list` of dictionaries. Why don't you create a new list and use `list.append(your_dictionary)` to add the dicts to the list?
type: Comment

http://stackoverflow.com/q/51713535
favorite count: 0
has comment: http://stackoverflow.com/comment/90388782
tagged with: python
downvote count: 0
score: 1
tagged with: scipy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/56165106
has comment: http://stackoverflow.com/comment/90392060
tagged with: weibull
tagged with: statistics
type: Question
has answer: http://stackoverflow.com/a/56165106
upvote count: 1
answer count: 1
has body: I have a set of integer values, and I want to set them to Weibull distribution and get the best fit parameters. Then I draw the histogram of data together with the pdf of Weibull distribution, using the best fit parameters. This is the code I used. from jtlHandler import * import warnings import numpy as np import pandas as pd import scipy.stats as st import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def get_pdf(latencies): a = np.array(latencies) ag = st.gaussian_kde(a) ak = np.linspace(np.min(a), np.max(a), len(a)) agv = ag(ak) plt.plot(ak,agv) plt.show() return (ak,agv) def fit_to_distribution(distribution, data): params = distribution.fit(data) # Return MLEs for shape (if applicable), location, and scale parameters from data. # # MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, self._fitstart(data) is called to generate such. return params def make_distribution_pdf(dist, params, end): arg = params[:-2] loc = params[-2] scale = params[-1] # Build PDF and turn into pandas Series x = np.linspace(0, end, end) y = dist.pdf(x, loc=loc, scale=scale, *arg) pdf = pd.Series(y, x) return pdf latencies = getLatencyList("filename") latencies = latencies[int(9*(len(latencies)/10)):len(latencies)] data = pd.Series(latencies) params = fit_to_distribution(st.weibull_max, data) print("Parameters for the fit: "+str(params)) # Make PDF pdf = make_distribution_pdf(st.weibull_max, params, max(latencies)) # Display plt.figure() ax = pdf.plot(lw=2, label='PDF', legend=True) data.plot(kind='hist', bins=200, normed=True, alpha=0.5, label='Data', legend=True, ax=ax) ax.set_title('Weibull distribution') ax.set_xlabel('Latnecy') ax.set_ylabel('Frequency') plt.savefig("image.png") This is the resulting figure. As it is seen, the Weibull approximation is not simmilar to the original distribution of data. How can I get the best Weibull approximation to my data?
has title: Fitting data to weibull distribution

http://stackoverflow.com/a/51723439
score: 0
type: Answer
has body: The input shape is only needed for the first layer because this adds information about the input to the model,which cannot be inferred by Keras, as the data is given by you. Subsequent layers can have their output shape inferred by Keras as they usually represent fixed transformations, so only the input shape to the first layer is needed.
answers question: http://stackoverflow.com/q/51722790

http://stackoverflow.com/a/51735282
downvote count: 0
score: 1
has body: Unfortunately, you cannot load native MXNet models into Keras. You can try to convert your model using MMdnn, but depending on complexity of your model it might not work.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51732258

http://stackoverflow.com/q/51794872
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51794929
accepted answer: http://stackoverflow.com/a/51794929
favorite count: 0
tagged with: python
tagged with: web-scraping
upvote count: 1
has body: I'm trying to improve the speed of my web scraper, and I have thousands of sites I need to get info from. I'm trying to get the ratings and number of ratings for sites in Google search webpages from Facebook and Yelp. I would just use an API normally, but because I have a huge list of sites to search for and time is of the essence, Facebook's small request limits per hour make this not feasible to use their Graph API (I've tried...). My sites are all in Google search pages. What I have so far (I have provided 8 sample sites for reproducibility): from multiprocessing.dummy import Pool import requests from bs4 import BeautifulSoup pools = Pool(8) #My computer has 8 cores proxies = MY_PROXIES #How I set up my urls for requests on Google searches. #Since each item has a "+" in between in a Google search, I have to format #my urls to copy it. site_list = ['Golden Gate Bridge', 'Statue of Liberty', 'Empire State Building', 'Millennium Park', 'Gum Wall', 'The Alamo', 'National Art Gallery', 'The Bellagio Hotel'] urls = list(map(lambda x: "+".join(x.split(" ")), site_list) def scrape_google(url_list): info = [] for i in url_list: reviews = {'FB Rating': None, 'FB Reviews': None, 'Yelp Rating': None, 'Yelp Reviews': None} request = requests.get(i, proxies=proxies, verify=False).text search = BeautifulSoup(search, 'lxml') results = search.find_all('div', {'class': 's'}) #Where the ratings roughly are for j in results: if 'Rating' in str(j.findChildren()) and 'yelp' in str(j.findChildren()[1]): reviews['Yelp Rating'] = str(j.findChildren()).partition('Rating')[2].split()[1] #Had to brute-force get the ratings this way. reviews['Yelp Reviews'] = str(j.findChildren()).partition('Rating')[2].split()[3] elif 'Rating' in str(j.findChildren()) and 'facebook' in str(j.findChildren()[1]): reviews['FB Rating'] = str(j.findChildren()).partition('Rating')[2].split()[1] reviews['FB Reviews'] = str(j.findChildren()).partition('Rating')[2].split()[3] info.append(reviews) return info results…
type: Question
type: AnsweredQuestion
has title: Am I setting my multithreading web scraper properly?
tagged with: google-search
score: 1

http://stackoverflow.com/a/51743078
answers question: http://stackoverflow.com/q/51734169
has comment: http://stackoverflow.com/comment/90540921
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90619162
downvote count: 0
has body: flow.redirect_uri = 'http://localhost:8000' This uri means after user authenticate successfully, google IDP would redirect to. Apparently, you make it redirect to http://localhost:8000 in google identity provider. It's "NPS Survey". You should set as flow.redirect_uri = 'http://yourhostip:8000'. And also set http://yourhostip:8000 on google oauth side about redirect url.
score: 1
has comment: http://stackoverflow.com/comment/90609689
has comment: http://stackoverflow.com/comment/90583321

http://stackoverflow.com/comment/90352849
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51695651
has text: Use `census_df.pct_change()` or `.diff()` and check this difference :)

http://stackoverflow.com/q/51739531
type: Question
has answer: http://stackoverflow.com/a/51745943
score: -2
tagged with: implicit
tagged with: arrays
has comment: http://stackoverflow.com/comment/90446646
has body: edit: In short way: I have three pictures: reference image, and two others. The reference image is used for adjust the other two to proper values. - this part should be ok. Then I subtract the other two pictures(arrays) from each other and I receive some array in which my pixels are hidden - also done and now the tricky part: this is my equation which I would like to solve in each pixel separately and my result should be "h" in a new array which I will export to excel Thanks a lot for help. import scipy import numpy as np from PIL import Image from scipy.optimize import fsolve P0 = Image.open('3kanaly0.tif') m = scipy.misc.imread("3kanaly0.tif") P0 = m[:,:,0] print(P0) P0_T = np.array(P0)/4 #1image m = scipy.misc.imread("3.tif") P1 = m[:,:,0] print(P1) P1_T = np.array(P1)/4 print(P1_T.shape) print("P1_T (z)",type(P1_T)) print(P1_T) #adjust Texp = input() Texp = int(Texp) print("Start beta") def beta(Texp,Tcal = 20): return Texp/Tcal b = beta(Texp) print("beta :", b) print(" beta") print("Start alfa") def alfa(A,B,C,D,b): return A*b**3+B*b**2+C*b+D wynik_alfa = alfa(0.0097,-0.08,-0.038,1.016,b) print("alfa i:",wynik_alfa) print(" alfa") # Tcal = 20 a = -10.978 b = 22.76 c = -19.317 d = 8.4634 Temp_T = Tcal*(a*(wynik_alfa*P1_T/P0_T)**3+b*(wynik_alfa*P1_T/P0_T)**2+c*wynik_alfa*P1_T/P0_T+d) #2image m = scipy.misc.imread("3kanaly2.tif") P2 = m[:,:,0] Temp_T2 = Tcal*(a*(wynik_alfa*P2_T/P0_T)**3+b*(wynik_alfa*P2_T/P0_T)**2+c*wynik_alfa*P2_T/P0_T+d) r = np.subtract(Temp_T,Temp_T2) a = 20 k = 400 Tpow = 80.0 ro = 8920 cp = 384 t = 2 print(type(k)) print(type(Tpow)) print(type(ro)) print(type(cp)) print(type(t)) print(type(P1_T)) print(type(r)) for i in range(len(Temp_T)): for j in range(len(Temp_T2[0])): fsolve((r[i][j] + (Tpow -Temp_T[i][j])*(1-exp(h**2)*exp(a*t/k**2)*h*(a**0.5*t**0.5)/k)))
has comment: http://stackoverflow.com/comment/90445527
answer count: 2
has comment: http://stackoverflow.com/comment/90448648
upvote count: 0
has comment: http://stackoverflow.com/comment/90448094
has title: Modifying pixels by implicit equation
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51748071
has comment: http://stackoverflow.com/comment/90447154
tagged with: image-processing
has comment: http://stackoverflow.com/comment/90448369

http://stackoverflow.com/comment/90627305
score: 0
type: Comment
has text: @A.Yadav : I tried something similar. Maybe this could help..??? pl check edited ans
comment on: http://stackoverflow.com/a/51723906
type: AnswerComment

http://stackoverflow.com/comment/90510837
has text: (...as an aside, I strongly advise against using `shlex.split()` when you could instead be hardcoding an explicit argv -- like a shell, it's an abstraction layer that's adding complexity without any benefit for same; passing an explicit list is what the OS actually does under-the-hood when it invokes the `execve()` syscall, so if you want to have as much as control as possible over what's *actually* going on when you invoke a program, an explicit list is the way to go).
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51774248

http://stackoverflow.com/q/51781416
score: 0
has comment: http://stackoverflow.com/comment/90540588
tagged with: python-sockets
has comment: http://stackoverflow.com/comment/90520729
type: UnansweredQuestion
tagged with: sockets
has comment: http://stackoverflow.com/comment/90520659
tagged with: python
answer count: 0
type: Question
tagged with: network-programming
has comment: http://stackoverflow.com/comment/90520579
has body: I know that to connect to a socket over the internet you have to enable port-forwarding in your router. However, I wonder how instant messengers e.g Whatsapp work without port-forwarding?. I was trying to connect to another device but failed I set my host as 0.0.0.0 and port to 1803 and it works perfectly over LAN but not over the internet. Help please? Edit: My code: import socket,sys server_socket = socket.socket() host = socket.gethostname() port = 1803 server_socket.bind((host, port)) server_socket.listen(1) while True: client, address = server_socket.accept() received_data = client.recv(1024).decode('ascii') print(received_data) sending_data = input('&gt;').encode('ascii') client.send(sending_data) server_socket.close() break sys.exit()
has title: How to successfully transmit a message over the internet with python sockets?
has comment: http://stackoverflow.com/comment/90520409

http://stackoverflow.com/a/51651813
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90266861
score: 2
has comment: http://stackoverflow.com/comment/90267096
upvote count: 2
has comment: http://stackoverflow.com/comment/90267138
answers question: http://stackoverflow.com/q/51651757
has comment: http://stackoverflow.com/comment/90267969
has body: You can use split and take the second argument: split('-')[1].strip() Example: f = "Session #1 - ABC" s = f.split('-')[1].strip() Output: ABC
has comment: http://stackoverflow.com/comment/90266952

http://stackoverflow.com/q/51780856
type: Question
has body: n_lines = int(input('How many lines do you want to input?')) lines = [input() for i in range(n_lines)] I want to break the loop if user hits 5 or any higher number.
has comment: http://stackoverflow.com/comment/90519500
has comment: http://stackoverflow.com/comment/90519242
has comment: http://stackoverflow.com/comment/90520060
has comment: http://stackoverflow.com/comment/90520081
has comment: http://stackoverflow.com/comment/90519612
has comment: http://stackoverflow.com/comment/90520028
has comment: http://stackoverflow.com/comment/90519351
has comment: http://stackoverflow.com/comment/90519193
answer count: 2
has comment: http://stackoverflow.com/comment/90522860
tagged with: for-loop
upvote count: 0
has answer: http://stackoverflow.com/a/51781293
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/90519203
tagged with: input
has comment: http://stackoverflow.com/comment/90519388
tagged with: python
has comment: http://stackoverflow.com/comment/90519422
has title: Check multiple inputs in the for loop
tagged with: list
has comment: http://stackoverflow.com/comment/90521920
downvote count: 3
has answer: http://stackoverflow.com/a/51781546
has comment: http://stackoverflow.com/comment/90519912
has comment: http://stackoverflow.com/comment/90519854
has comment: http://stackoverflow.com/comment/90519584
has comment: http://stackoverflow.com/comment/90520091
has comment: http://stackoverflow.com/comment/90519999
has comment: http://stackoverflow.com/comment/90519895
has comment: http://stackoverflow.com/comment/90519955

http://stackoverflow.com/comment/90319258
score: 0
comment on: http://stackoverflow.com/q/51677828
type: Comment
type: QuestionComment
has text: I copied `X` to a variable called `data` and then added `y` to `data`. What do you mean regarding the first comment?

http://stackoverflow.com/comment/90308714
has text: If the answer provided helped, please mark it as accepted.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51662181
score: 0

http://stackoverflow.com/q/51680616
linked to: http://stackoverflow.com/q/34352197
has answer: http://stackoverflow.com/a/51680699
type: Question
answer count: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/15888648
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51680700
tagged with: insert
favorite count: 0
possible better answer: http://stackoverflow.com/a/51680699
has title: Insert multiple rows to index
duplicate of: http://stackoverflow.com/q/34352197
has answer: http://stackoverflow.com/a/51680700
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I'm looking for a concise way of inserting rows in the middle of a DataFrame so that the rows after the insertion point are pushed forward. It would look something like this: Data Frame A Data Frame B Idx | C1 | C2 Idx | C1 | C2 ----+----+---- ----+----+---- 0 | 12 | 31 0 | 49 | 67 1 | 64 | 98 1 | 25 | 63 2 | 47 | 10 Inserting B to A[2]: Idx | C1 | C2 ----+----+---- 0 | 12 | 31 1 | 64 | 98 2 | 49 | 67 # B[0] 3 | 25 | 63 # B[1] 4 | 47 | 10 This would have to be done for multiple data frames, or rather slices of the original. There's always the option of looping through with pd.concat and the slice and insert indices, but for a library like pandas I'd expect someone to already have come up with an answer I haven't come across. append doesn't quite work, but it's close. There actually exists df.insert, but it's for columns. I'd appreciate any pointers even to helpful documentation. Sandbox: a = pd.DataFrame([[1, 2], [2, 3], [3, 4]]) b = pd.DataFrame([[4, 5], [5, 6]])

http://stackoverflow.com/comment/90329750
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51683413
score: 1
has text: @michelle It looks like you're a bit lost. But I can tell that you're trying hard to make this work, so I'll post an answer shortly. In future, please post the _exact_ code that you're trying to run, and make sure the indentation is _identical_ to what's on your machine. And when you get an error message please include the full error message in your question, starting from the Traceback line. Put the error message into a code block to preserve the formatting.

http://stackoverflow.com/comment/90256697
comment on: http://stackoverflow.com/q/51646342
score: 0
has text: ı understand now update
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90401218
score: 0
comment on: http://stackoverflow.com/q/51719517
type: Comment
type: QuestionComment
has text: Access how? In JavaScript? Or in Python? If the latter that is only possible via a Bokeh server application. The script above generates a standalone HTML page with no connection to any python runtime.

http://stackoverflow.com/a/51693002
has body: Iterate over your tuples: import matplotlib.pyplot as plt x = [(1, 27), (32, 55), (56, 80), (84, 103)] y = [(5, 7), (3, 6), (4, 9), (6, 11)] fig = plt.figure() ax = fig.add_subplot(111) for xt, yt in zip(x,y): ax.plot(xt, yt, color='black') plt.show()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51692823
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51692823

http://stackoverflow.com/a/51691081
type: Answer
accepted answer of: http://stackoverflow.com/q/51690950
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90343876
has body: tmp_t is a two-element array. (You can see for yourself by executing the first call to iteration by hand, one line at a time.) When you call iteration again, t is not a float anymore; you compare a number (abs(...)) to an array, which raises the original error. As far as I understand the logic of your program, you should change tmp_var = np.var(tmp_data) to tmp_var = np.var(tmp_data)[1].
answers question: http://stackoverflow.com/q/51690950

http://stackoverflow.com/a/51748489
answers question: http://stackoverflow.com/q/51747985
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51747985
has body: The problem is that get_vertices() returns the local coordinates. You need to manually account for rotation and global displacement, like in the following def draw_poly(shape): verts = [] for v in shape.get_vertices(): x = v.rotated(shape.body.angle)[0] + shape.body.position[0] y = v.rotated(shape.body.angle)[1] + shape.body.position[1] verts.append((x, y)) pygame.draw.polygon(screen, [255, 255, 255], verts)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51782224
tagged with: python
possible better answer: http://stackoverflow.com/a/51784278
has answer: http://stackoverflow.com/a/51782492
upvote count: 1
has body: Consider a NumPy ndarray A of floats, with a dimension of n and an arbitrary shape of D=[d1,...,dn] (dis are nonnegative integers). How can I populate A to have for example: A[j1,...,jn]=sqrt(j1*...*jn) where 0&lt;=ji&lt;=di. If I knew n and it was fixed then I could nest n for loops to simply populate the ndarray. however in my program that's not the case, apart from the fact that will not be efficient. I was wondering if there is any way to populate the ndarray A of the given arbitrary shape D (for example with the formula above or any other nonthrivial function of the indices). preferably avoid using python for loops and take advantage of NumPy's underlying functionality. Thanks for your help in advance.
linked to: http://stackoverflow.com/q/47624948
linked to: http://stackoverflow.com/q/51821540
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90522027
accepted answer: http://stackoverflow.com/a/51782492
type: Question
tagged with: numpy
has title: populating a numpy ndarray of an arbitrary shape (preferably without using for loops)
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90522149
favorite count: 0
has answer: http://stackoverflow.com/a/51784278
linked to: http://stackoverflow.com/q/51794274

http://stackoverflow.com/comment/90284123
comment on: http://stackoverflow.com/q/51656758
has text: The problem is simple: for you to be able to use `self.listbox` you must create `self.listbox`. This isn't unique to tkinter, it's just how python works.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90465572
comment on: http://stackoverflow.com/q/51750894
score: 0
type: Comment
type: QuestionComment
has text: @AniketPadwal please include your code *in your question*. It is impossible to comprehend it in the comments.

http://stackoverflow.com/comment/90520984
score: 0
has text: @Hearner like that "0.9986130595207214","26.41608428955078","39.44521713256836","250.2412109375","112.84327697753906","120.34269714355469","260.63800048828125","15.424667358398438","273.6199645996094","249.74160766601562"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51781648

http://stackoverflow.com/a/51665850
type: Answer
has comment: http://stackoverflow.com/comment/90360531
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51657950
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51657950
has body: Remove celery.conf.update(app.config) line from make_celery() function, hence it will be like, def make_celery(app): # create context tasks in celery celery = Celery( app.import_name, broker=app.config['BROKER_URL'] ) celery.conf.update(app.config) # remove this line. celery.config_from_object(celeryconfig) TaskBase = celery.Task and, copy paste contents of flask-proj/config.py to flask-proj/celeryconfig.py. Hence he flask-proj/celeryconfig.py will be like, from celery.schedules import crontab import os REDIS_HOST = "127.0.0.1" REDIS_PORT = 6379 BROKER_URL = os.environ.get( 'REDIS_URL', "redis://{host}:{port}/0".format( host=REDIS_HOST, port=str(REDIS_PORT))) CELERY_RESULT_BACKEND = BROKER_URL CELERY_IMPORTS = ('app.tasks.test') CELERY_TASK_RESULT_EXPIRES = 30 CELERY_TIMEZONE = 'UTC' CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYBEAT_SCHEDULE = { 'test-celery': { 'task': 'app.tasks.test.print_hello', # Every minute 'schedule': crontab(minute="*"), } }

http://stackoverflow.com/comment/90273082
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51654794
has text: @Dyno Seems so.
type: Comment

http://stackoverflow.com/comment/90346512
comment on: http://stackoverflow.com/a/51692327
score: 1
has text: @tpk Hmm, I couldn't find any with considerable info. At its core. it operates on 1D arrays and sums values based on the bins.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90319758
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51676842
has text: As i am submitting this in online assignments, it won't allow other modules.
score: 0

http://stackoverflow.com/a/51645349
answers question: http://stackoverflow.com/q/51643158
has comment: http://stackoverflow.com/comment/90290019
has body: tf.constant currently does not support instantiation in coordinate format (indices and values) so the numpy/scipy workaround is actually not a bad one: import scipy.sparse as sps A = sps.coo_matrix((values, (indices[0,:], indices[1,:])), shape=your_shape) tensor_A = tf.constant(A.to_dense()) If having a non-trainable tf.Variable can be an option (see here for the differences with tf.constant), you could use tf.sparse_to_dense tensor_A = tf.Variable( \ tf.sparse_to_dense(indices, your_shape, values), \ trainable=False \ )
type: Answer
score: 0

http://stackoverflow.com/comment/90377370
type: QuestionComment
has text: I wasn't really sure, just wanted to clarify. I have seen some ways to apply Cross-validation like train_test_split or some Kaggle competitions where they use cross_validate multiple times and I was a bit confused. For a small dataset (120 samples) do you recommend any methodology to avoid overfitting? or the one that I posted would be enough? Thank you!
score: 0
comment on: http://stackoverflow.com/q/51707968
type: Comment

http://stackoverflow.com/a/51787467
answers question: http://stackoverflow.com/q/51683952
upvote count: 2
type: AcceptedAnswer
has body: See the answer below along with the links at the bottom to nx_to_rdkit functions SMILES from graph
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51683952

http://stackoverflow.com/comment/90337147
comment on: http://stackoverflow.com/q/51687103
has text: Yes, I have done that in the full code. There is even code to remove all the commas, semicolons, etc and also the redundant words. I have just posted the main part of the code here since the full code is a bit long. I am getting the desired output, but I don't understand what the error means.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90324041
type: AnswerComment
comment on: http://stackoverflow.com/a/51680280
type: Comment
score: 1
has text: You posted x seconds before me. I guess, I should be fast. @sacul. :P

http://stackoverflow.com/q/51660119
type: AnsweredQuestion
score: 1
tagged with: dataframe
has title: Pandas - set value in row to itself multiplied by another value
type: Question
has body: Let's say I have the following table: multiply total tax Y 500 .1 Y 250 .5 N 300 .5 I want to set the total to total * tax only if the value of multiply is Y Final output: multiply total tax Y 50 .1 Y 125 .5 N 300 .5
downvote count: 0
has answer: http://stackoverflow.com/a/51660206
accepted answer: http://stackoverflow.com/a/51660210
favorite count: 0
possible better answer: http://stackoverflow.com/a/51660177
tagged with: pandas
has answer: http://stackoverflow.com/a/51660177
tagged with: python
has answer: http://stackoverflow.com/a/51660225
answer count: 4
upvote count: 1
has answer: http://stackoverflow.com/a/51660210

http://stackoverflow.com/a/51671499
has body: If you have your data in a pandas DataFrame (let's say df), it's rather easy: import seaborn as sns sns.barplot(x='config names', y='value', data='df') I'm not sure what you mean by one bin per month. The bins here are your x axis. If you mean you want to split different months into different bins then you should just add them to the hue parameter. import seaborn as sns sns.barplot(x='config names', y='value', data='df', hue='month')
downvote count: 0
answers question: http://stackoverflow.com/q/51671327
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/51671327
type: Answer
upvote count: 1

http://stackoverflow.com/q/51711082
has answer: http://stackoverflow.com/a/51711650
type: Question
has title: Python, pandas: How to append a series to a dataframe
has answer: http://stackoverflow.com/a/51711271
downvote count: 0
has body: I have the following dataframe df1: import pandas as pd data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy', 'Lisa', 'Molly', 'Lisa', 'Molly', 'Fred'], 'gender': ['m', 'f', 'f', 'm', 'f', 'f', 'f', 'f','f', 'm'], } df1 = pd.DataFrame(data, index = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) I want to create a table with some standard and some custom summary statistics df2. df2 = df1.describe() df2.rename(index={'top':'mode'},inplace=True) df2.rename(index={'freq':'mode freq'},inplace=True) df2 df2: gender name count 10 10 unique 2 7 mode f Molly mode freq 7 3 I want to append one row to df2 for the second mode and one for the frequency of the second mode: Example: gender name count 10 10 unique 2 7 mode f Molly mode freq 7 3 2nd mode m Lisa 2nd freq 3 2 I figured out that you can get the second mode &amp; frequency by doing this: my_series for column in df1: my_series=df1[column].value_counts()[1:2] print(my_series) But how do I append this to df2?
answer count: 2
tagged with: pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/51711271
tagged with: python
accepted answer: http://stackoverflow.com/a/51711650
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/51696635
has comment: http://stackoverflow.com/comment/90386677
has body: You can use regular expressions to extract the prefix, given the list of all possible suffixes: pattern = '(\w+)(USDT|BTC|ETH|BNB)$' df'Asset','Quote' = df['symbol'].str.extract(pattern)
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51696579
accepted answer of: http://stackoverflow.com/q/51696579
type: Answer

http://stackoverflow.com/a/51731526
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90424083
has comment: http://stackoverflow.com/comment/90424075
has body: string_list = [temp.replace('bcd','') for temp in string_list]
has comment: http://stackoverflow.com/comment/90424095
downvote count: 0
answers question: http://stackoverflow.com/q/51731483
type: Answer

http://stackoverflow.com/q/51663572
possible better answer: http://stackoverflow.com/a/51663638
has answer: http://stackoverflow.com/a/51663688
has comment: http://stackoverflow.com/comment/90292469
has answer: http://stackoverflow.com/a/51663638
type: Question
has comment: http://stackoverflow.com/comment/105190375
has answer: http://stackoverflow.com/a/51663851
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/77905640
has title: Add/fill pandas column based on range in rows from another dataframe
has comment: http://stackoverflow.com/comment/90290588
favorite count: 0
has body: Working with pandas, I have df1 indexed by time samples: data = '''\ time flags input 8228835.0 53153.0 32768.0 8228837.0 53153.0 32768.0 8228839.0 53153.0 32768.0 8228841.0 53153.0 32768.0 8228843.0 61345.0 32768.0''' fileobj = pd.compat.StringIO(data) df1 = pd.read_csv(fileobj, sep='\s+', index_col='time') df2 indicates time ranges with start and end to define ranges where the state of 'check' is True: data = '''\ check start end 20536 True 8228837 8228993 20576 True 8232747 8232869 20554 True 8230621 8230761 20520 True 8227351 8227507 20480 True 8223549 8223669 20471 True 8221391 8221553''' fileobj = pd.compat.StringIO(data) df2 = pd.read_csv(fileobj, sep='\s+') What I need to do is add a column for 'check' to df1 and fill out the actual time ranges defined in df2 with the value of True. All others should be False. An example result would be: flags input check time 8228835.0 53153.0 32768.0 False 8228837.0 53153.0 32768.0 True 8228839.0 53153.0 32768.0 True 8228841.0 53153.0 32768.0 True 8228843.0 61345.0 32768.0 True .... 8228994.0. 12424.0. 32768.0. False
linked to: http://stackoverflow.com/q/51825533
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/51663851
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90290621
upvote count: 3

http://stackoverflow.com/comment/90288632
has text: @MatthewMankiewicz I don't know what the first half of that is about or why it's relevant. But if you don't have a GUI, then what are you expecting to do with the clipboard? As-is, what you're asking to do just doesn't make sense. But I'm sure you're trying to do something that makes perfect sense, and if you can explain what it is, we can probably tell you a way to accomplish it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51662312
type: Comment

http://stackoverflow.com/comment/90372335
type: Comment
type: QuestionComment
has text: could you add your gse function?
comment on: http://stackoverflow.com/q/51705464
score: 0

http://stackoverflow.com/a/51698666
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90370889
has body: If you need only specific fileds, you can do it like so: request_data = { 'id': request.form['id'], 'data_start': request.form['data_start'], 'ora_start': request.form['ora_start'], 'data_stop': request.form['data_stop'], 'M1': request.form['M1'], 'M2': request.form['M2'], 'M3': request.form['M3'], 'M4': request.form['M4'], 'M5': request.form['M5'], } # or dicitionary comprehension # relevant_keys = ['id','data_start','ora_start','data_stop', 'M1', 'M2', 'M3', 'M4', 'M5'] # requst_data = {key: request.form[key] for key in relevant_keys} return render_template('ordine_macchine_necessarie.html', **request_data) If you want all the data from form you do this: return render_template('ordine_macchine_necessarie.html', **request.form) As of Flask/Tornado/aiohttp/Falcon they are all good to know, before you go into Django, it is worth to at least write some small project with them.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90371685
accepted answer of: http://stackoverflow.com/q/51698417
downvote count: 0
answers question: http://stackoverflow.com/q/51698417
has comment: http://stackoverflow.com/comment/90377160
has comment: http://stackoverflow.com/comment/90381320
upvote count: 2
has comment: http://stackoverflow.com/comment/90378825

http://stackoverflow.com/comment/90316693
type: Comment
comment on: http://stackoverflow.com/a/51675724
type: AnswerComment
has text: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/20491059)
score: 0

pytest
tags question: http://stackoverflow.com/q/51760917
tag name: pytest
tags question: http://stackoverflow.com/q/51797134
tags question: http://stackoverflow.com/q/51783757
tags question: http://stackoverflow.com/q/51737334
tags question: http://stackoverflow.com/q/51783664
tags question: http://stackoverflow.com/q/51737378
tags question: http://stackoverflow.com/q/51666621
tags question: http://stackoverflow.com/q/51711988
tags question: http://stackoverflow.com/q/51682413
tags question: http://stackoverflow.com/q/51710083
tags question: http://stackoverflow.com/q/51762886
tags question: http://stackoverflow.com/q/51765191
tags question: http://stackoverflow.com/q/51678972
tags question: http://stackoverflow.com/q/51713849
tags question: http://stackoverflow.com/q/51703577
tags question: http://stackoverflow.com/q/51663326
tags question: http://stackoverflow.com/q/51662884
tags question: http://stackoverflow.com/q/51778482
tags question: http://stackoverflow.com/q/51781785
tags question: http://stackoverflow.com/q/51658866
type: Tag

http://stackoverflow.com/q/51693590
has title: error condition "user not found" on twitter with python
upvote count: 1
has body: I want to find user identity in twitter from their username which the data is already saved on my database I made a condition like this #get data from database cur.execute("SELECT user FROM `rt6`") row = cur.fetchall() for text in row: #Get Identity of BMKG in Twitter user = api.get_user(text) try: print ("Name:", user.name) print ("Name:", user.screen_name) print ("Number of tweets: " + str(user.statuses_count)) print ("followers_count: " + str(user.followers_count)) print ("Account location: ", user.location) print ("Account created at: ", user.created_at) print ("Account geo enabled: ", user.geo_enabled) except ValueError: print("user not found") and my target is when the user not found with one of the usernames on my database, just skip to the next row on the database. and I got an error like this, anyone could solve my problem?
type: Question
accepted answer: http://stackoverflow.com/a/51694313
has comment: http://stackoverflow.com/comment/90349527
tagged with: database
tagged with: twitter
has comment: http://stackoverflow.com/comment/90349015
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51694313
tagged with: python
tagged with: tweepy
type: AnsweredQuestion

http://stackoverflow.com/comment/90411945
type: Comment
type: QuestionComment
has text: @wogsland Is that the snippet which is reproducible ? Cannot reproduce it to..
comment on: http://stackoverflow.com/q/51725602
score: 0

http://stackoverflow.com/comment/90529627
has text: I was wondering if the full standard library was available for micropython. Oh, well.
type: AnswerComment
comment on: http://stackoverflow.com/a/51778471
score: 0
type: Comment

http://stackoverflow.com/comment/90430834
has text: @calvert Take a look at my answer.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51733288

http://stackoverflow.com/comment/90334004
has text: Some brackets were missing, I added them `crawler()` please try again. KyrSt solution is more pythonic but its a bit harder to read than my naive approach.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51685086
type: Comment

http://stackoverflow.com/q/51742459
has title: json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
has comment: http://stackoverflow.com/comment/90445510
has body: I am receiving this error. I am using Python 3.6.5. json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1) mycode is here: import json filename = 'btc_close_2017.json' with open(filename) as f: btc_data = json.load(f) for btc_dict in btc_data: date = btc_dict['date'] month = int(btc_dict['month']) week = int(btc_dict['week']) weekday = btc_dict['weekday'] close = int(float(btc_dict['close'])) print("{} is month {} week {}, {}, the close price is {} RMB".format( date, month, week, weekday, close))
type: UnansweredQuestion
answer count: 0
tagged with: python-3.x
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90445151
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90445236

http://stackoverflow.com/a/51790125
has body: From looking at Selenium documentation for Python, it seems you need to pass in a webdriver object to WebDriverWait(...). And you're passing in self, rather than self.driver, into the function call. So this vvvv element = WebDriverWait(self, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]'))) needs to be this element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]')))
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90545908
answers question: http://stackoverflow.com/q/51784033
downvote count: 0
score: 4

http://stackoverflow.com/q/51748679
score: 4
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53067821
tagged with: python
has body: I have a 2-column Pandas data frame composed of tweets: the second column is the tweets themselves. I want to get a word count of all the tweets together. Data Frame looks like so: RT @PaulHaleAndMom: Four Hours After #Piedmont... RT @NatPoliceAssoc: Body camera video shows At... RT @XLNB: When Spanish Drake and Jamaican Drak... I almost cried this morning. My babies are ... @SebastianDanzig Hey Bassy are tickets and VIP... The following is giving me the count by row. wc_DF = tweets_DF['text'].apply(lambda x: Counter(x.lower().split())) i.e. {'rt': 1, '@paulhaleandmom:': 1, 'four': 1, 'h... What would be a good vectorized implementation in Pandas be for this?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51748745
accepted answer: http://stackoverflow.com/a/53067821
type: Question
has title: Getting total word count from a string series in a Pandas Data Frame
possible better answer: http://stackoverflow.com/a/51748745

http://stackoverflow.com/q/51755825
type: Question
has answer: http://stackoverflow.com/a/51755890
has title: Create encrypted Zip file from multiple files on Python
answer count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/zip
score: 0
type: UnansweredQuestion
tagged with: encryption
has body: I want to create an encrypted zip file which inlcudes 3 files. For now I have this solution which allows me to create an encrypted zip with only one file. loc_7z = r"C:\Program Files\7-Zip\7z.exe" archive_command = r'"{}" a "{}" "{}"'.format(loc_7z, 'file.zip', 'file_name.xls') subprocess.call(archive_command, shell=True) When I try to pass a list of files as the third parameter it crashes. What format should the list of files have? I'm open to try different approaches as well. Thank you.

http://stackoverflow.com/q/51658531
downvote count: 0
favorite count: 0
tagged with: python
score: 2
tagged with: python-3.x
upvote count: 2
has title: Scrapy CrawlSpider doesn't quit
tagged with: scrapy
has answer: http://stackoverflow.com/a/51658846
type: Question
type: AnsweredQuestion
has body: I have a problem with scrapy Crawlspider: basically, it doesn't quit, as it is supposed to do, if a CloseSpider exception is raised. Below is the code: from scrapy.spiders import CrawlSpider, Rule from scrapy.exceptions import CloseSpider from scrapy.linkextractors import LinkExtractor import re class RecursiveSpider(CrawlSpider): name = 'recursive_spider' start_urls = ['https://www.webiste.com/'] rules = ( Rule(LinkExtractor(), callback='parse_item', follow=True), ) miss = 0 hits = 0 def quit(self): print("ABOUT TO QUIT") raise CloseSpider('limits_exceeded') def parse_item(self, response): item = dict() item['url'] = response.url item['body'] = '\n'.join(response.xpath('//text()').extract()) try: match = re.search(r"[A-za-z]{0,1}edical[a-z]{2}", response.body_as_unicode()).group(0) except: match = 'NOTHING' print("\n") print("\n") print("\n") print("****************************************INFO****************************************") if "string" in item['url']: print(item['url']) print(match) print(self.hits) self.hits += 10 if self.hits &gt; 10: print("HITS EXCEEDED") self.quit() else: self.miss += 1 print(self.miss) if self.miss &gt; 10: print("MISS EXCEEDED") self.quit() print("\n") print("\n") print("\n") The problem is that, although I can see it enters in the conditions, and I can see the Eception raised in the log, the crawler continues crawling. I run it with: scrapy crawl recursive_spider
tagged with: web-crawler
possible better answer: http://stackoverflow.com/a/51659020
has answer: http://stackoverflow.com/a/51659020
answer count: 2
accepted answer: http://stackoverflow.com/a/51658846

http://stackoverflow.com/a/76160818
has body: If you are using SQLAlchemy you can try setting the parameter method='multi' df.to_sql('table_name', con=con, index=False, if_exists='append', schema=schema, method='multi', chunksize=10000)
type: Answer
answers question: http://stackoverflow.com/q/51745657
score: 0

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/51742561
tags question: http://stackoverflow.com/q/51665542
tags question: http://stackoverflow.com/q/51644416

http://stackoverflow.com/q/51747470
tagged with: performance
has body: Why is swaplevel() slow in Pandas? In fact, why wouldn't it simply swap the two relevant lists in the index levels and labels (and swap level names)? The slowness is obvious, with about 100,000 columns in a MultiIndex, but is it necessary? The documentation for swaplevel() doesn't indicate that this method does anything special in addition to swapping the levels.
has comment: http://stackoverflow.com/comment/90455336
has comment: http://stackoverflow.com/comment/90456183
tagged with: pandas
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90456576
has comment: http://stackoverflow.com/comment/90456868
has title: Why is swaplevel() slow in Pandas?
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90456343
type: Question

http://stackoverflow.com/q/51675429
score: -1
upvote count: 0
tagged with: email
answer count: 1
has answer: http://stackoverflow.com/a/51675671
favorite count: 0
accepted answer: http://stackoverflow.com/a/51675671
tagged with: python
has comment: http://stackoverflow.com/comment/90314138
has body: Please help me I want to create an AI which can send emails using python but when I run my code it says: Traceback (most recent call last): File "c:\Users\zigzag\Desktop\email.py", line 1, in <module> import smtplib File "B:\Python36\lib\smtplib.py", line 47, in <module> import email.utils File "c:\Users\zigzag\Desktop\email.py", line 3, in <module> mail = smtplib.SMTP('smtp.gmail.com', 587) AttributeError: module 'smtplib' has no attribute 'SMTP' here is my code: import smtplib mail = smtplib.SMTP('smtp.gmail.com', 587) mail.starttls() mail.login('myemail@myemail.com', 'mypassword') mail.sendmail('myemail@myemail.com', 'anotheremail@anotheremail.com', " Hello World ") mail.close()
has comment: http://stackoverflow.com/comment/90315298
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16512256
downvote count: 1
type: Question
has title: Cannot send and email via python
has comment: http://stackoverflow.com/comment/90314119

http://stackoverflow.com/a/51680393
has body: 1) You might want to try using the retrying library and try a few times within the given run. 2) You might want to add the stocks to a job queue, have something consume from the queue, and upon failure add it back to the queue. There are various sorts of job queues out there you can look into: redis pubsub, kafka, celery, etc
type: Answer
answers question: http://stackoverflow.com/q/51680334
score: 0

lambda
tags question: http://stackoverflow.com/q/51671021
tags question: http://stackoverflow.com/q/51797718
tags question: http://stackoverflow.com/q/51789766
tags question: http://stackoverflow.com/q/51669831
tags question: http://stackoverflow.com/q/51728621
tag name: lambda
tags question: http://stackoverflow.com/q/51770552
tags question: http://stackoverflow.com/q/51787247
type: Tag
tags question: http://stackoverflow.com/q/51670194
tags question: http://stackoverflow.com/q/51777932
tags question: http://stackoverflow.com/q/51700857
tags question: http://stackoverflow.com/q/51694375
tags question: http://stackoverflow.com/q/51717236
tags question: http://stackoverflow.com/q/51745439

vectorization
tags question: http://stackoverflow.com/q/51691465
tags question: http://stackoverflow.com/q/51711607
tags question: http://stackoverflow.com/q/51697644
tags question: http://stackoverflow.com/q/51660066
tags question: http://stackoverflow.com/q/51640628
tags question: http://stackoverflow.com/q/51708902
tag name: vectorization
type: Tag
tags question: http://stackoverflow.com/q/51679898
tags question: http://stackoverflow.com/q/51701334
tags question: http://stackoverflow.com/q/51650166

http://stackoverflow.com/a/51657163
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/90278523
has body: When you specify chunksize in a call to pandas.read_csv you get back a pandas.io.parsers.TextFileReader object rather than a DataFrame. Try this to go through the chunks: reader = pd.read_csv('Training.csv',chunksize=500) for chunk in reader: print(type(chunk)) # chunk is a dataframe Or grab all the chunks (which probably won't solve your problem!): reader = pd.read_csv('Training.csv',chunksize=500) chunks = [chunk for chunk in reader] # list of DataFrames Depending on what is in your dataset a great way of reducing memory use is to identify columns that can be converted to categorical data. Any column where the number of distinct values is much lower than the number of rows is a candidate for this. Suppose a column contains some sort of status with limited values (e.g. 'Open','Closed','On hold') do this: chunk['Status'] = chunk.assign(Status=lambda x: pd.Categorical(x['Status'])) This will now store just an integer for each row and the DataFrame will hold a mapping (e.g 0 = 'Open', 1 = 'Closed etc. etc.) You should also look at whether or not any of your data columns are redundant (they effectively contain the same information) - if any are then delete them. I've seen spreadsheets containing dates where people have generated columns for year, week, day as they find it easier to work with. Get rid of them!
answers question: http://stackoverflow.com/q/51656554
has comment: http://stackoverflow.com/comment/90295484
upvote count: 3
type: Answer

http://stackoverflow.com/comment/90403041
type: Comment
type: QuestionComment
has text: And have a look at other people's code in the tag [tag:adventure]
comment on: http://stackoverflow.com/q/51669423
score: 0

http://stackoverflow.com/q/51654074
has comment: http://stackoverflow.com/comment/90377986
tagged with: bllip-parser
answer count: 1
tagged with: macos
favorite count: 0
linked to: http://stackoverflow.com/q/20112989
tagged with: lldb
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90362464
tagged with: python
has body: I am working on code that includes bllipparser Python module, among other things. Feeding it the same dataset, it will intermittently crash (maybe once in three to ten runs). Going through lldb, I found that the public field weights of RerankerModel (source), that is apparently only set once (in the constructor), randomly becomes NULL (I only have one RerankerModel for the duration of my run, so there should be exactly one weights, that persists unchanged throughout). So I set up an ambush (I mean, a watchpoint: I stopped the code in the constructor and watchpoint set expression -w write -- &amp;weights), and apparently the culprit that nulls the pointer is tiny_malloc_from_free_list from libsystem_malloc.dylib. Here's the relevant top of the backtrace: * thread #1, queue = 'com.apple.main-thread', stop reason = watchpoint 4 * frame #0: 0x00007fff61caf22a libsystem_malloc.dylib`tiny_malloc_from_free_list + 151 frame #1: 0x00007fff61cae3bf libsystem_malloc.dylib`szone_malloc_should_clear + 422 frame #2: 0x00007fff61cae1bd libsystem_malloc.dylib`malloc_zone_malloc + 103 frame #3: 0x00007fff61cad4c7 libsystem_malloc.dylib`malloc + 24 frame #4: 0x00007fff5faac628 libc++abi.dylib`operator new(unsigned long) + 40 frame #5: 0x00000001133c904c _CharniakParser.cpython-36m-darwin.so`std::__1::__split_buffer&lt;short, std::__1::allocator&lt;short&gt;&amp;&gt;::__split_buffer(unsigned long, unsigned long, std::__1::allocator&lt;short&gt;&amp;) [inlined] std::__1::__allocate(__size=4) at new:226 frame #6: 0x00000001133c9040 _CharniakParser.cpython-36m-darwin.so`std::__1::__split_buffer&lt;short, std::__1::allocator&lt;short&gt;&amp;&gt;::__split_buffer(unsigned long, unsigned long, std::__1::allocator&lt;short&gt;&amp;) [inlined] std::__1::allocator&lt;short&gt;::allocate(this=0x0000000135316448, __n=2, (null)=0x0000000000000000) at memory:1747 frame #7: 0x00000001133c8f44 _CharniakParser.cpython-36m-darwin.so`std::__1::__split_buffer&lt;short, std::__1::allocator&lt;short&gt;&a…
upvote count: 16
has answer: http://stackoverflow.com/a/52314406
has comment: http://stackoverflow.com/comment/91574651
has comment: http://stackoverflow.com/comment/90621343
tagged with: memory-management
has comment: http://stackoverflow.com/comment/91574303
downvote count: 1
has comment: http://stackoverflow.com/comment/91574425
type: Question
has comment: http://stackoverflow.com/comment/90568171
has comment: http://stackoverflow.com/comment/90375485
has comment: http://stackoverflow.com/comment/90366399
has comment: http://stackoverflow.com/comment/90362293
has title: `tiny_malloc_from_free_list` made my pointer `NULL`?
score: 15

http://stackoverflow.com/a/51700334
type: Answer
has comment: http://stackoverflow.com/comment/90362170
has body: There is a big difference between an undefined variable and a defined variable set to None. An undefined variable doesn't have a value because it doesn't exist yet. The Var1 in your example code is local to __init__, not a global. You could add another global statement in __init__ to make it global. You could instead move the Var1 = None to the toplevel of your script (outside the class definition) to define a global Var1. Then it will be None until it gets set to something else. Since your functions are nested inside __init__ you don't have to use globals at all. You could use nonlocal instead of global to refer to a containing function's local. This is only required in func1 because it is assigning to Var1. (You can read nonlocals and globals without declaring them as such.)
score: 0
answers question: http://stackoverflow.com/q/51700305

http://stackoverflow.com/comment/90504896
has text: You're shooting darts at a unit circle. The circumscribing square is over the range [-1, 1].
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51773034

http://stackoverflow.com/q/51774759
has body: I have a python project with a lot of dependencies (around 30 or so python packages) that i want to deploy on aws using lambda function. Right now i have about 30 custom python packages in my VS solution that i import into the main function - there is a lot of code. What is the best way to build a deployment package and how would i go about doing this? I watched a few tutorials but i am new to this, so im not sure exactly what concrete steps to take. If i use something like zappa and create a virtual environment how would i then get my project there and install all the dependencies and then zip the file? Thanks so much, sorry for the stupid questions, i couldn't find a stackoverflow post that covered this
tagged with: visual-studio
score: 1
type: Question
has answer: http://stackoverflow.com/a/51776075
has title: Python project in visual studio deployed on AWS using lambda?
tagged with: amazon-web-services
downvote count: 0
answer count: 1
tagged with: deployment
tagged with: aws-lambda
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/51706068
has comment: http://stackoverflow.com/comment/90373953
has comment: http://stackoverflow.com/comment/90373044
has comment: http://stackoverflow.com/comment/90374195
has body: def var_map_lower(var_map): return {x.lower(): y for (x,y) in var_map.items()} df['var_map'] = df['var_map'].apply(var_map_lower) Can you try this?
score: 0
answers question: http://stackoverflow.com/q/51705977
has comment: http://stackoverflow.com/comment/90372931
type: Answer
has comment: http://stackoverflow.com/comment/90372861

http://stackoverflow.com/a/51729636
type: Answer
answers question: http://stackoverflow.com/q/51729203
has comment: http://stackoverflow.com/comment/90420976
has body: folderlist=["folder1","folder2","folder3","folder4"] #i=0 #unneeded counter for i in range(4): os.chdir(r"//Desktop/foldersforreading/"+folderlist[i]) #os.chdir(r"//Desktop/foldersforreading"+"//"+folderlist[i]) #Alternative if above fails file=pd.read_table('file.txt',sep=',',header=0, index_col=None) #do something #move to next one #i=i+1 #Commented out since you don't need to iterate your counter Give the above code a try, it should fix your problem and be of simple syntax similar to what you requested.
score: 0
has comment: http://stackoverflow.com/comment/90421283

http://stackoverflow.com/comment/90329769
type: QuestionComment
type: Comment
has text: I have a workaround changing the IP at OS Level that works like a charm. Let me know if you would like that approach.
score: 1
comment on: http://stackoverflow.com/q/51651412

http://stackoverflow.com/comment/90283333
type: AnswerComment
comment on: http://stackoverflow.com/a/51645395
score: 0
type: Comment
has text: Thanks. You are correct. Shortly after I posted this I realised I had to map each column to variable one by one like above

http://stackoverflow.com/q/51703568
type: AnsweredQuestion
score: -1
type: Question
has answer: http://stackoverflow.com/a/51927048
has comment: http://stackoverflow.com/comment/90370219
upvote count: 0
has comment: http://stackoverflow.com/comment/90368082
answer count: 1
has body: I have read PEP 257. But it does not say anything on how to specify the type of a function argument. Is the below one recommended - def decrypt_and_verify_bundle(bundle_file): """ Decrypts and verifies a bundle :param bundle_file: string absolute path to the bundle file :return: string tar file present in the bundle """
has comment: http://stackoverflow.com/comment/90368887
favorite count: 0
has title: Python 2.7.1 - How to document method argument type?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90768726
has comment: http://stackoverflow.com/comment/90370466
tagged with: python
accepted answer: http://stackoverflow.com/a/51927048
downvote count: 1

http://stackoverflow.com/q/51726506
downvote count: 0
has comment: http://stackoverflow.com/comment/114895197
favorite count: 0
answer count: 0
tagged with: python-sphinx
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90509188
tagged with: python
tagged with: git
tagged with: git-submodules
has comment: http://stackoverflow.com/comment/114841220
score: 3
upvote count: 3
type: Question
has title: How do I structure a "sphinx" documentation git repo to document other repos as submodules?
has body: I have multiple git repos that make up a larger library. I want to create a "sphinx" documentation repo that references the other repos as submodules, and build the documentation in the "sphinx" repo. The sphinx repo documentation tree will be published as the documentation for the larger library. It will be regenerated whenever any of the constituent repos are updated. I'm also using the autodoc and napoleon extensions. I have a shell script that walks through the submodules running sphinx-apidoc, then runs make html in the top directory: SPHINX_APIDOC_OPTIONS='members,undoc-members,inherited-members,show-inheritance' for dir in `find * -type d | egrep -v "(^_)|(^\.)"`; do sphinx-apidoc -f -e -a -o _build/docs/${dir} ${dir}; done make html The top level index.rst file: .. toctree:: :maxdepth: 1 :caption: Contents: _build/docs/module1/modules.rst _build/docs/module2/modules.rst (The submodules don't have index.rst files.) The submodules only get linked in shallowly, so class folders in a submodule don't show up. I've tried variations, but each one is flawed in a different way. Does someone have a simple example how to put this together? Surely I'm missing something fundamental? Update: Added screenshot of first page. Requirement: Create a Sphinx "project" folder, including any build scripts and index.rst files, with softlinks to local git project folders, so that all of the documentation of all linked projects can be stitched together automatically in one place? The built documentation folder can then be published, such as to AWS S3, as part of the automated build flow.
has comment: http://stackoverflow.com/comment/90524675

http://stackoverflow.com/comment/90469240
type: Comment
type: QuestionComment
has text: Do you want to convert the string to bytes? It is not clear what the desired solution is... if you know it is a byte string without the b, you can do some string formatting. If you need it in bytes, you can call `bytes(string)`. Does this help: https://stackoverflow.com/questions/606191/convert-bytes-to-a-string ?
comment on: http://stackoverflow.com/q/51754731
score: 0

http://stackoverflow.com/a/51791423
has comment: http://stackoverflow.com/comment/90543510
has comment: http://stackoverflow.com/comment/90542290
has comment: http://stackoverflow.com/comment/90543530
has comment: http://stackoverflow.com/comment/90541644
has comment: http://stackoverflow.com/comment/90542051
score: 0
has body: In your for loop, add the new column to the array 'row', then write that row to the csv. for row in reader: row.insert(9, phone_list[i]) writer.writerow(row)
answers question: http://stackoverflow.com/q/51791299
type: Answer
has comment: http://stackoverflow.com/comment/90541506
has comment: http://stackoverflow.com/comment/90541891

http://stackoverflow.com/comment/90335044
comment on: http://stackoverflow.com/a/51686513
type: Comment
has text: Sorry, he can fill it with any value.
score: 0
type: AnswerComment

wamp
tag name: wamp
tags question: http://stackoverflow.com/q/51693055
type: Tag

http://stackoverflow.com/comment/90293193
comment on: http://stackoverflow.com/q/51664941
score: 0
type: Comment
type: QuestionComment
has text: That's not a question. Please understand that SO is a Q&A site. If you do not ask a question (with a question mark, "?"), you will not get an answer.

http://stackoverflow.com/comment/90387261
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51712930
score: 0
has text: The json you want to obtain is invalid, use https://jsonlint.com/

http://stackoverflow.com/comment/90273407
type: QuestionComment
comment on: http://stackoverflow.com/q/51654961
score: 4
has text: You really should be using `models.ForeignKey()`s (to `User` and `Books` [sic]) instead of poorly emulating them with CharFields.
type: Comment

http://stackoverflow.com/comment/90360004
comment on: http://stackoverflow.com/q/51698528
score: 0
type: QuestionComment
type: Comment
has text: How do you define "adaptable"?

http://stackoverflow.com/q/51678763
has answer: http://stackoverflow.com/a/51678895
has title: How can I make this loop continue when there is an error?
tagged with: exception
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90320804
tagged with: loops
has body: def encryption_process(startpath=None): for filename in glob.iglob(os.path.join(startpath, '**'), recursive=True): if(os.path.isfile(filename)): print('Encrypting&gt; ' + filename) encrypt_file(key, filename) os.remove(filename) Occasionally I'll get a Windows permission error from this, is there a way I can make it continue with the list when an error is raised and just skip the file giving the error?
type: Question
score: 0
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/comment/90545527
score: 1
type: Comment
type: QuestionComment
has text: Not the cause of your problem, but have you heard of `elif`? If not, you should check it out.
comment on: http://stackoverflow.com/q/51793808

http://stackoverflow.com/comment/90386771
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51712395
type: Comment
has text: I just started learning it today so i don't know much about it. It is nearly same as `tkinter`. However thanks.

http://stackoverflow.com/comment/90400170
has text: @Ciasto piekarz To start, implement linear approach (I just added "simple way")
comment on: http://stackoverflow.com/a/51719100
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51766469
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90491578
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51766603
has comment: http://stackoverflow.com/comment/90492207
has comment: http://stackoverflow.com/comment/90491632
has body: I have a file like the one given below, and I'm looking for a way to read line 2 to line 7 and write it to a new file using Python. 16 processes; 52 threads; CPU states: 0.0% user, 0.0% kernel CPU 0 Idle: 99.9% CPU 1 Idle: 99.7% CPU 2 Idle: 100.0% CPU 3 Idle: 100.0% Memory: 1024M total, 854M avail, page size 4K PID TID PRI STATE HH:MM:SS CPU COMMAND 1 15 10 Run 0:00:00 0.03% kernel 28688 1 10 Rply 0:00:00 0.02% top 11 2 21 Rcv 0:00:00 0.00% io-pkt-v6-hc 4 2 10 NSlp 0:00:00 0.00% random 6 1 24 Rcv 0:00:00 0.00% devc-serscif 1 18 10 Rcv 0:00:00 0.00% kernel 28686 1 10 SigW 0:00:00 0.00% devb-sdmmc-rcar_mmcif 28684 1 10 SigW 0:00:00 0.00% qconn 1 16 10 Rcv 0:00:00 0.00% kernel 2 1 10 Rcv 0:00:00 0.00% slogger2 Min Max Average CPU 0 idle: 99% 99% 99% CPU 1 idle: 99% 99% 99% CPU 2 idle: 100% 100% 100% CPU 3 idle: 100% 100% 100% Mem Avail: 854MB 854MB 854MB Processes: 16 16 16 Threads: 52 52 52 i want to find a way to save this part in new text file. CPU states: 0.0% user, 0.0% kernel CPU 0 Idle: 99.9% CPU 1 Idle: 99.7% CPU 2 Idle: 100.0% CPU 3 Idle: 100.0% Memory: 1024M total, 854M avail, page size 4K i ma not familier with python and not a programmer, can anybody help me? best regards
answer count: 3
has answer: http://stackoverflow.com/a/51766594
accepted answer: http://stackoverflow.com/a/51766603
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51766594
has answer: http://stackoverflow.com/a/51766570
tagged with: python
has comment: http://stackoverflow.com/comment/90492006
has title: extract date from one text file and write to new file using python
type: AnsweredQuestion

http://stackoverflow.com/comment/90327981
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51682341
has text: as I said, complete beginner - how do I do this?

http://stackoverflow.com/comment/114841220
has text: Have you found out how to do that by now?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51726506
score: 0

http://stackoverflow.com/a/51756695
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51756613
has body: There is no semicolon in python statements and no braces in the loops your code doesn't check any condition it will lead to a indefinite loop. just change the code factor = 1 ness = "yes" while factor&lt;=10: factor += 1 print (ness*factor) and the output is yesyes yesyesyes yesyesyesyes yesyesyesyesyes yesyesyesyesyesyes yesyesyesyesyesyesyes yesyesyesyesyesyesyesyes yesyesyesyesyesyesyesyesyes yesyesyesyesyesyesyesyesyesyes yesyesyesyesyesyesyesyesyesyesyes

http://stackoverflow.com/comment/90387367
has text: Sure even then how do I convert the python input to that type of JSON structure @MaNKuR
comment on: http://stackoverflow.com/q/51712930
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/55392237
answers question: http://stackoverflow.com/q/51714358
score: 0
type: Answer
has body: I had the same problem when I tried to install Sklearn and I modified the packaging_tool.py: add this from pip import __main__ change the line 109: return pip.__main__._main(['install'] + pkgs) It works!

http://stackoverflow.com/q/51740396
has body: In my current application, I have a Python 2.7 script called main.py that launches another Python 2.7 script called calculator.py using GNU Parallel like the following: os.system("seq 10000 | parallel -N0 -j 50 nohup python calculator.py &amp;") print "Done" This works pretty well, with one exception: I need to resume executing other commands in main.py (that is, after the os.system call, e.g. the print "Done" line) just after all the 10000 instances spawned with GNU Parallel finish running. Is there a proper way to do that? Solutions with os.spawn and Python 2.7 subprocess are both welcome, but using GNU Parallel is absolutely mandatory. EDIT: Here are my requirements: 1) it is crucial to me that the many instances of calculator.py that are spawned keep running if the terminal closes (hence the nohup) 2) I need it to not block current terminal session (hence the &amp;) 3) I need it to print "Done" in the example above gets executed only after the 10000 jobs finish If achieving all above at the same time is not possible, I think I could then manually keep a log of all launched processes and then manually force the rest of the code "main.py" code to continue after all those processes end. This, of course, is a cumbersome last-resource option.
answer count: 0
has comment: http://stackoverflow.com/comment/90441696
score: 1
has title: Waiting for GNU Parallel processes to finish when using & and spawning via Python
upvote count: 1
type: Question
tagged with: pipe
tagged with: gnu-parallel
has comment: http://stackoverflow.com/comment/90463402
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90593229
downvote count: 0
has comment: http://stackoverflow.com/comment/90582309
has comment: http://stackoverflow.com/comment/90466160
favorite count: 0
has comment: http://stackoverflow.com/comment/90441313
has comment: http://stackoverflow.com/comment/90518377
tagged with: terminal
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90444089
has comment: http://stackoverflow.com/comment/90442036
has comment: http://stackoverflow.com/comment/90465892
tagged with: python

http://stackoverflow.com/q/51654821
tagged with: multiple-columns
has answer: http://stackoverflow.com/a/51655232
has comment: http://stackoverflow.com/comment/90273796
tagged with: pandas
upvote count: 1
has body: I have a dataframe like this: a1 a2 a3 a4 4 4 4 4 4 4 4 4 2 3 2 3 2 3 3 3 2 2 2 2 2 2 2 2 Desired output: a1 a2 a3 a4 max_freq 4 4 4 4 4 4 4 4 4 4 2 3 2 3 3 2 3 3 3 3 2 2 2 2 2 2 2 2 2 2 I want to return the element from column, that occurs the most horizontally in columns a1,a2,a3,a4. e.g. 4 freq -4, so max_freq=4 and so on. In case of ties, return a4. I started off with something like: def get_max_freq(row): unique, counts = np.unique(np.array(row), return_counts=True) print (unique,counts) df_temp.apply(get_max_freq, axis=1) I am able to get frequency of items row wise. i can go on and try converting them into a dataframe, sort by count and select first element and return from function, but it seems to be a slow method. Is there any pythonic way to address this problem? (which can address the speed on a ~1m rows dataframe)
tagged with: python
favorite count: 0
has title: getting item with max frequency from multiple columns in a dataframe
tagged with: frequency
accepted answer: http://stackoverflow.com/a/51655400
score: -3
downvote count: 4
possible better answer: http://stackoverflow.com/a/51655232
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51655400
has comment: http://stackoverflow.com/comment/90273255
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90273990
has comment: http://stackoverflow.com/comment/90273974
tagged with: function
has comment: http://stackoverflow.com/comment/90274077
has comment: http://stackoverflow.com/comment/90273307
has comment: http://stackoverflow.com/comment/90273547

http://stackoverflow.com/comment/90287618
has text: How are the classes in the dataset distributed? This could be a sign of a poor dataset. It is mentioned in the tutorial that "drama" is overrepresented. Try to see what your model actually predicts.
type: Comment
comment on: http://stackoverflow.com/q/51657456
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90521421
type: Comment
type: QuestionComment
has text: just filter it with last date and sort in ascending order on date column
score: 0
comment on: http://stackoverflow.com/q/51781909

http://stackoverflow.com/a/51678885
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: APP_SETTINGS it's not Flask variable, it's just for this Huey example. Looking at the source here, you need to supply enviromental variable APP_SETTINGS, that contains your configuration settings (docs here). Example (from the documentation): export APP_SETTINGS="yourapplication.default_settings"
answers question: http://stackoverflow.com/q/51678831
accepted answer of: http://stackoverflow.com/q/51678831

http://stackoverflow.com/q/51789536
type: Question
score: 0
has title: Process next iteration of loop while 'await'ing
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/90538428
type: UnansweredQuestion
tagged with: python
has body: I'm working on figuring out the new async keywords added in Python 3.5+ and I had a problem I am trying to solve using async. Here's a simple example: from aiohttp import ClientSession session = ClientSession() for x in data: # x=LOTS OF POST DATA async with session.post("my-url.com", data=x) as response: # START THE NEXT ITERATION OF THE LOOP NOW rep = await response.read() ... # DO SOME WORK WITH THE RESPONSE The problem here is instead of moving to the next iteration, it will halt the thread. I know of ways to run through all the URLs at once and put them into futures for looping through all of them later for post processing, however I want to do work on the response after it's ready, not all at once later on. Is there anyway to prevent wasted time when it is waiting for the response to be ready? Ideally while it's waiting for the network IO I would want the script to start queuing up some more responses to run. Since the data being posted takes awhile to upload. If anything is unclear please let me know and I'll do my best to answer. Thank you!
has comment: http://stackoverflow.com/comment/90537992
answer count: 0
has comment: http://stackoverflow.com/comment/90539128

http://stackoverflow.com/a/51709383
answers question: http://stackoverflow.com/q/51708962
type: Answer
has body: You are opening the file in each iteration of the loop which removes the previous values. Just move the open and close statement out of the loop. def yaml_processor(period): filepath_reg = "../public/log/testing.log.yaml" data = yaml_loader(filepath) data = data.get(period) file = open("test.log.yaml", 'w') for team, key in data.iteritems(): file.write('%team %period\n') print(team, period) file.close()
score: 0

http://stackoverflow.com/a/51751007
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51749613
answers question: http://stackoverflow.com/q/51749613
has body: aux3[col] = pd.to_numeric(aux3[col].str.replace(',','.')) this line is the reason you are getting a warning. Accessing the "col" using indexing may result in unpredictable behavior since it may return view or copy of original data. it depends on the memory layout of the array, about which pandas makes no guarantees pandas documentation advises users to use .loc instead. Example: In: df Out: one two first second first second 0 a b c d 1 e f g h 2 i j k l 3 m n o p dfmi.loc[:,('one','second')] = value # becomes dfmi.loc.__setitem__((slice(None), ('one', 'second')), value) dfmi['one']['second'] = value # becomes dfmi.__getitem__('one').__setitem__('second', value) In the second case __getitem__ is unpredictable. It may return view or copy of the data. Modifying a view and copy works differently. Making change on copy is not reflected on the original data where as a change on a view does. Note: So the warning is present to warn users, even if you get the expected output there is a chance it might causes some unpredictable behavior.
type: AcceptedAnswer

http://stackoverflow.com/comment/90502950
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51772051
score: 0
has text: @Zonk can you show a few rows where the code is empty?

python-3.7
tags question: http://stackoverflow.com/q/51700960
tags question: http://stackoverflow.com/q/51762032
tags question: http://stackoverflow.com/q/51743776
tags question: http://stackoverflow.com/q/51759798
tags question: http://stackoverflow.com/q/51676128
tags question: http://stackoverflow.com/q/51692037
tags question: http://stackoverflow.com/q/51671699
tags question: http://stackoverflow.com/q/51777823
tags question: http://stackoverflow.com/q/51691240
tags question: http://stackoverflow.com/q/51707435
tags question: http://stackoverflow.com/q/51679648
tag name: python-3.7
type: Tag
tags question: http://stackoverflow.com/q/51742092
tags question: http://stackoverflow.com/q/51647255
tags question: http://stackoverflow.com/q/51713847
tags question: http://stackoverflow.com/q/51699025
tags question: http://stackoverflow.com/q/51739251

jython
tags question: http://stackoverflow.com/q/51715687
tag name: jython
type: Tag
tags question: http://stackoverflow.com/q/51639929

http://stackoverflow.com/q/51714031
type: AnsweredQuestion
tagged with: pyqt5
has title: QMDISubWindow Beneath QMenuBar
downvote count: 1
type: Question
answer count: 1
score: 0
tagged with: pyqt
has answer: http://stackoverflow.com/a/51717353
favorite count: 0
accepted answer: http://stackoverflow.com/a/51717353
has body: In my PyQt program, I have a QMenuBar that launches QMDISubWindow widgets. By default that launches it around (0, 0). I modified it so that it automatically moves the widget down (as shown below). def check_position(self, y, width, height, sub_window): if y &lt;= 40: sub_window.move(randint(0, self.width - width), randint(0, self.height - height)) print("Sub Window Moved") That moves the QMDISubWindow Down, but when in Full Screen or when dragged up, the QMDISubWindow gets (may get) underneath the QMenuBar. How would you fix that issue? F.Y.I. Full code is available at Github.
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51662950
answer count: 0
tagged with: django
type: Question
tagged with: django-models
has comment: http://stackoverflow.com/comment/90295209
score: 0
has comment: http://stackoverflow.com/comment/90292637
type: UnansweredQuestion
has title: how can I do a following system with just a manytomanyfield?
has body: I am doing a following system for a django project. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followers = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='followers_profile') following = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='following_profile') biography = models.TextField(max_length=500, blank=True, null=True) profile_picture = models.ImageField(blank=True, null=True) def __str__(self): return self.user.username And I want to know if I can do this with just a followers field.
tagged with: python

http://stackoverflow.com/comment/90599058
type: Comment
has text: in this script i want to filtering results in three diferent columns. self.proxy.setFilterKeyColumn(1) wich this code i search one column(secund in my case) but i need three columns to search. Sorry and thanks
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51787985

http://stackoverflow.com/comment/90276325
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51650006
has text: Can you share the repr of the xarray dataset (`f`) and the output of `ncdump -s -h file.nc`?

http://stackoverflow.com/q/51736120
has comment: http://stackoverflow.com/comment/90434369
has body: I'm relatively new to machine / Deep Learning. I have decent experience in using API's such as Scikit- Learn, Tensor flow and Keras to develop supervised learning models. So, I wanted to implement one on my own to get better experience. I tried to implement a Basic Deep Neural Network Algorithm for a classification problem on my own. I have used an iris data set for this test but, my implementation has been giving me very poor results, it's heavily under-fitting the data, the best accuracy I get is 66 % and the least even goes to 0 %, for every run of my algorithm , I get heavily varying results even after I've set a low randomness seed. I've chosen a tanh activation function, a learning rate of 0.01, a softmax activation for the output layer and a Standard Scalar normalization on the input variables. So, I'm wondering whether I'm doing any of the math part wrong, or missing any fundamental part of this algorithm, I'd really appreciate if anyone can run this code and instruct me on possible changes. Thank you so much in advance. Here's the code: data = load_iris() X = data.data y = data.target class Neural_Network: def __init__(self, n_hlayers, n_nodes, lr): #No. of hidden layers self.n_layers = n_hlayers #No. of nodes in each of the hidden layer self.n_nodes = n_nodes #Learning rate of the algorithm self.lr = lr # Dictionary to hold the node values of all the layers self.layers = { } # Dictionary to hold the weight values of all the layers self.weights = { } def _softmax(self,values): '''Function to perform softmax activation on the node values returns probabilities of each feature''' exp_scores = np.exp(values) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) return probs def _derivate_tanh(self,values): '''Function that performs derivative of a tanh activation function''' #Derivative of tanh is 1 - tanh^2 x return (1 - np.power(values, 2)) def fit(self,X,y): '''This function constructs a Neural Network with given hyper parameters and then runs it fo…
answer count: 1
tagged with: neural-network
has title: Own Implementation of Neural Networks in Python heavily under fitting the data
favorite count: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90437773
has comment: http://stackoverflow.com/comment/93608692
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51739066
tagged with: python
downvote count: 3
score: -1
type: Question
tagged with: numpy

http://stackoverflow.com/q/51740818
has body: def ask_choice_question(prompt, options): func = tkinter.Tk() v = tkinter.IntVar() v.set(-1) if(prompt): tkinter.Label(func, text=prompt).pack() for i, option in enumerate(options): tkinter.Radiobutton(func, text=option, variable=v, value=i).pack(anchor="w") tkinter.Button(func, text="Submit", command=func.destroy).pack() func.mainloop() print(v.get()) if(v.get()== -1): return None print(options[v.get()]) return options[v.get()] By throughly looking through this website I have found something like the example above, and modified it slightly. However, when calling func.destroy it seems the func doesn't return anything, neither do "print()"-s do anything. What do? EDIT: Actually, something I might add, that this question is asked inside of another Tkinter window, and it actually outputs what needed when that window is closed. EDIT2: It also may be useful to say, that the menu I'm getting looks something like this: http://prntscr.com/kg516z
has answer: http://stackoverflow.com/a/51745637
has title: Python Single Choice Questions
has comment: http://stackoverflow.com/comment/90446964
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90448902
has comment: http://stackoverflow.com/comment/90448802
favorite count: 0
accepted answer: http://stackoverflow.com/a/51745637
tagged with: tkinter
type: Question
has comment: http://stackoverflow.com/comment/90442618
upvote count: 1
tagged with: python
answer count: 1
tagged with: tkinter-menu

http://stackoverflow.com/comment/90386475
score: 0
has text: @eyllanesc You are right. Execute the script in terminal totally helped. Turns out write() argument must be str. Thank you!
comment on: http://stackoverflow.com/q/51711631
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51695716
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51695880
has comment: http://stackoverflow.com/comment/90352847
type: Question
has answer: http://stackoverflow.com/a/51695758
score: -2
tagged with: inheritance
possible better answer: http://stackoverflow.com/a/51695758
tagged with: class
answer count: 2
accepted answer: http://stackoverflow.com/a/51695880
has comment: http://stackoverflow.com/comment/90352877
has title: Class Inheritance Error: Child object has no attribute 'a'
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: oop
has body: Consider the following code snippet class parent(object): def __init__(self): self.a = 0 class child(parent): def __init__(self): super(parent, self).__init__() self.b = 9 def func(self): print(self.a, self.b) c = child() print(c.b) print(c.a) The output that I expected was: 9 0 But the error message states that 'child' object does not have attribute 'a'. If I instead use the parents init method instead of super, I get my desired output. parent.__init__(self) I have read from other posts, super is the recommended way to implement inheritance. My question is how do I inherit parent class attributes initialized by the init method into child class by using super method?

http://stackoverflow.com/comment/106673836
score: 0
type: AnswerComment
has text: @pault is there an approach to performing the split so this warning does not occur? "WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation"
comment on: http://stackoverflow.com/a/51773836
type: Comment

http://stackoverflow.com/q/51643559
upvote count: 0
has title: Running python flask gunicorn app from shell script
accepted answer: http://stackoverflow.com/a/51661984
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/90286807
has answer: http://stackoverflow.com/a/51661984
type: Question
downvote count: 2
answer count: 1
tagged with: shell
tagged with: flask
favorite count: 0
tagged with: gunicorn
tagged with: python
has body: I build my flask app, it requires external files through the runtime. when I build the app, meaning I run > gunicorn app:app (the app startup file is called app.py but that didn't bother). It runs awesomely. Now when I decided to make a sort of shell script to execute it (actually to make a couple of dependencies and environment checking but for the sake of simplifying, I created startup.sh in the same directory as app.py and it contains only the following instruction unquoted: "gunicorn app:app"), it just throws errors. and this is the last one ... Please help..

http://stackoverflow.com/comment/90329563
has text: Legend @jezrael
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51683202
type: Comment

http://stackoverflow.com/comment/90332580
has text: So all these different variables in your code are same then? `latest_non_empty`,`latest_non_empty_file`,`lastest_none_empty`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51665107

http://stackoverflow.com/q/51763982
tagged with: python
has answer: http://stackoverflow.com/a/57193054
has comment: http://stackoverflow.com/comment/91639844
has body: I am facing a coding error in FEniCS when I run the heat equation code it’s fail with, error = np.abs(u_e.vector().array() - u.vector().array()) AttributeError: 'dolfin.cpp.la.PETScVector' object has no attribute 'array’ I believe the idea is to calculate the difference between u and the exact solution for each time level and put them in array then we going to take the maxium value.(if not, correct me please!) the Original code for computing the error is u_e = interpolate(u_D, V) error = np.abs(u_e.vector().array() - u.vector().array()).max() print('t = %.2f: error = %.3g' % (t, error)) Where u_D is the boundary condition. I am not sure how I can make it works so any advice from you would appreciated. Thanks in advance
type: UnansweredQuestion
upvote count: 7
has title: Solving the heat equation by FEniCS
type: Question
score: 7
has comment: http://stackoverflow.com/comment/97611709
has comment: http://stackoverflow.com/comment/96127897
answer count: 2
downvote count: 0
favorite count: 0
tagged with: fenics
has answer: http://stackoverflow.com/a/60987416

http://stackoverflow.com/a/51658523
has comment: http://stackoverflow.com/comment/90290018
answers question: http://stackoverflow.com/q/51650591
has comment: http://stackoverflow.com/comment/90325724
has comment: http://stackoverflow.com/comment/90298763
type: Answer
has body: Inkscape uses Python 2.7, which it brings with it, unless you set that differently in the settings file (edit manually). If you want to write an Inkscape extension, you can learn how to do this by: reading https://inkscape.org/develop/extensions/ following the examples in other extensions that work (e.g. for running additional Inkscape instances, you could follow this one: https://gitlab.com/su-v/inx-pathops/blob/master/src/pathops.py)
has comment: http://stackoverflow.com/comment/90289941
has comment: http://stackoverflow.com/comment/90289983
has comment: http://stackoverflow.com/comment/90298735
has comment: http://stackoverflow.com/comment/90393534
has comment: http://stackoverflow.com/comment/90441514
has comment: http://stackoverflow.com/comment/90281520
has comment: http://stackoverflow.com/comment/90371112
score: 0
has comment: http://stackoverflow.com/comment/90281551

http://stackoverflow.com/comment/90360115
comment on: http://stackoverflow.com/a/51699290
score: 0
type: Comment
has text: Also, the case of `valid and i == 0` looks like it will cause a similar problem.
type: AnswerComment

http://stackoverflow.com/q/51654599
tagged with: python
has body: I am trying to code seq2seq example with Tensorflow with Beam Search and Attention. Till now I have found no concrete example which explains the both the decoding and/or attention together using current tf version. Either the previous versions have an issue with the beam search decoder which will tell you to do a batch_tile. I have a working example of simple decoder example, which for time being is Ok but I want to use Beam Search inference_decoder = tf.contrib.seq2seq.BeamSearchDecoder(cell = dec_cell, embedding = embedings, start_tokens = starting_id_vec, end_token = word_to_id['&lt;EOS&gt;'], initial_state = enc_states,#dec_cell.zero_state(config.BATCH_SIZE * config.BEAM_SIZE,tf.float32).clone(cell_state=enc_states), beam_width = config.BEAM_SIZE, output_layer = output_layer ) I am getting this error ValueError: Cannot reshape a tensor with 32768 elements to shape [64,10,512] (327680 elements) for 'decoder_1/Reshape' (op: 'Reshape') with input shapes: [64,512], [3] and with input tensors computed as partial shapes: input[1] = [64,10,512]. I believe the beam_width is adding extra dimension which changes the rank of the tensor as the code works without BeamSearch with BasicDecoder. If I set the beam_size =1 (fun sake) it throws this error ValueError: Shape must be rank 3 but is rank 2 for 'decoder/decoder/while/BasicDecoderStep/decoder/Attention_Wrapper/concat_3' (op: 'ConcatV2') with input shapes: [64,?,512], [64,512], []. I would be glad if anyone can help me this error. If I set the
answer count: 0
tagged with: seq2seq
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: deep-learning
downvote count: 0
score: 1
has title: Tensorflow Beamsearch Decoder unable to decode the value
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90387442
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51677917
type: Comment
has text: more info....when I modified my simple test script that works from print(data) to print(type(data)), I can see the data type is <class 'dict'> not <class 'str'>. So apparently I need to convert my string into a 'dict'? Thanks in advance....

http://stackoverflow.com/q/51750492
answer count: 1
score: -1
tagged with: boto3
tagged with: amazon-web-services
tagged with: python-2.7
upvote count: 1
tagged with: aws-lambda
favorite count: 0
has title: i am getting following error when i am trying to run lambda function,error is indentation error at line no7
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51750827
has body: i am getting indentation error at line no.7 for s3 bucket saying syntax error,i am tryiing to run lambda function which basically copy s3 bucket data from source to destination when ever a new object is uploaded to s3 bucket based on sns topic and cloudwatch logs. import urllib import boto3 import ast import json print('Loading function') def lambda_handler(event, context): s3 = boto3.client('s3') sns_message = ast.literal_eval(event['Records'][0]['Sns']['Message']) target_bucket = context.function_name source_bucket = str(sns_message['Records'][0]['s3']['bucket']['name']) key = str(urllib.unquote_plus(sns_message['Records'][0]['s3']['object']['key']).decode('utf8')) copy_source = {'Bucket':source_bucket, 'Key':key} print ("Copying %s from bucket %s to bucket %s ..." % (key, source_bucket, target_bucket)) sts_client = boto3.client('sts') assumedRoleObject = sts_client.assume_role( RoleArn="arn:aws:iam::lambdadestd3s:role/lambdasource", RoleSessionName="AssumeRoleSession1" ) credentials = assumedRoleObject['Credentials'] #use of temporary credentials for sts role s3 = boto3.client( 's3', aws_access_key_id = credentials['AccessKeyId'], aws_secret_access_key = credentials['SecretAccessKey'], aws_session_token = credentials['SessionToken'], ) s3.copy_object(Bucket=target_bucket, Key=key, CopySource=copy_source)
tagged with: python
has comment: http://stackoverflow.com/comment/90461195
has comment: http://stackoverflow.com/comment/90460923
type: Question

http://stackoverflow.com/q/51780924
linked to: http://stackoverflow.com/q/252703
answer count: 6
has answer: http://stackoverflow.com/a/51781112
type: Question
has comment: http://stackoverflow.com/comment/90519423
has answer: http://stackoverflow.com/a/51780998
has answer: http://stackoverflow.com/a/51781431
has comment: http://stackoverflow.com/comment/90519745
linked to: http://stackoverflow.com/q/2022031
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/11177533
upvote count: 11
linked to: http://stackoverflow.com/q/11177533
has answer: http://stackoverflow.com/a/51781311
possible better answer: http://stackoverflow.com/a/51780998
has body: I don't know what is difference between f() and g(). In function f, list L is accumulated whenever function is called.. but in function g, it does not.. def f(a, L=[]): L.append([2]); print(L); def g(a, L=[]): L = L+[2]; print(L); print("f:") f(1) # [[2]] f(2) # [[2], [2]] f(3) # [[2], [2], [2]] print("g:") g(1) # [2] g(2) # [2] g(3) # [2]
downvote count: 1
duplicate of: http://stackoverflow.com/q/2022031
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90519599
has answer: http://stackoverflow.com/a/51781300
has title: What is the difference between "append" and "+" in python?
has answer: http://stackoverflow.com/a/51781266
accepted answer: http://stackoverflow.com/a/51781431
score: 10

http://stackoverflow.com/comment/90260550
score: 0
has text: Where does the `5 6` line come from in your example output?
comment on: http://stackoverflow.com/q/51648172
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51714413
type: Answer
upvote count: 2
has body: See the documentation. In your example, the node labels would actually be a, b, d and e. The last token(s) on the line (c and f in your case) would be the edge attribute(s). In order to parse the edge attributes, you need to provide a list of tuples with attribute names and types: read_edgelist(..., data=(('my_edge_label', str),)) Not sure you need the quotes in csv. Hope this helps.
score: 2
answers question: http://stackoverflow.com/q/51712821
downvote count: 0

http://stackoverflow.com/comment/90466168
score: 0
type: Comment
type: QuestionComment
has text: Why are you passing `bot=False` to `run`? Self bots are against the Discord terms of service, and they're pretty good at detecting them. It's very possible that they've limited your connection in some way. I would recommend switching to a regular token setup, and seeing if that improve the performance.
comment on: http://stackoverflow.com/q/51752903

content-length
type: Tag
tag name: content-length
tags question: http://stackoverflow.com/q/51790944

http://stackoverflow.com/comment/90464859
comment on: http://stackoverflow.com/q/51750894
score: 0
type: Comment
has text: def fuzzy_match(x, choices, scorer, cutoff): return process.extractOne( x, choices = choices, scorer = scorer, score_cutoff = cutoff) FuzzyWuzzyResults = Data.loc[:, DBAName].apply(fuzzy_match, args= (Data.loc[:, OriginatorName], fuzz.token_set_ratio, 50))
type: QuestionComment

http://stackoverflow.com/a/51743816
has comment: http://stackoverflow.com/comment/90470217
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/99013374
answers question: http://stackoverflow.com/q/51737946
has comment: http://stackoverflow.com/comment/90468088
upvote count: 1
has comment: http://stackoverflow.com/comment/90505337
has body: The sns.choose_colorbrewer_palette() returns the the colorscheme you want to use. Depending on whether the as_cmap argument is true or false it will either return a list of colors ("seaborn palette") or a matplotlib colormap.
type: Answer

http://stackoverflow.com/a/51720650
downvote count: 0
has comment: http://stackoverflow.com/comment/90443981
has comment: http://stackoverflow.com/comment/90443865
has comment: http://stackoverflow.com/comment/90418494
type: Answer
accepted answer of: http://stackoverflow.com/q/51720345
has comment: http://stackoverflow.com/comment/90444826
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90402404
answers question: http://stackoverflow.com/q/51720345
has body: You can use dict.get method with a default value of empty dict to get the top level dict and then convert its values to a iter, use next to get the first value &gt;&gt;&gt; check_con = 'Neal' &gt;&gt;&gt; next(iter(tree.get(check_con, {}).values()), '') {'Joseph'} &gt;&gt;&gt; &gt;&gt;&gt; check_con = 'xxx' &gt;&gt;&gt; next(iter(tree.get(check_con, {}).values()), '') '' &gt;&gt;&gt;
type: AcceptedAnswer

http://stackoverflow.com/q/51757274
has body: I trained a simple neural network in keras. The training loss and validation loss shows regular spikes after certain epochs. The x-axis of the figure is epochs, and the y-axis is loss. Notice the large validation loss spike correspond with small training loss spike. I used fit_generator. I tried optimizer SGD and Adam, and the spikes still appear. Interestingly, changing batch size doesn't influence the shape or period of the spike. Changing optimizer influences spike magnitude, but doesn't influence the repeating period. Any thoughts on why this happens?
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90475438
tagged with: deep-learning
tagged with: keras
has comment: http://stackoverflow.com/comment/90474345
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: keras neural network training and validation loss with regular spikes
answer count: 0
upvote count: 2
score: 1
downvote count: 1
type: Question

http://stackoverflow.com/a/51659156
answers question: http://stackoverflow.com/q/51658925
has body: In general looping through data in pyspark will not be very efficient. When possible use native pyspark functions. For your specific question you can use the filter function that will filter your DataFrame by names in the student list: df_names.filter(col("name").isin(students)).select("name") In your example the only return value will be John.
upvote count: 9
type: AcceptedAnswer
downvote count: 0
score: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/51658925

http://stackoverflow.com/comment/90455675
type: Comment
type: QuestionComment
has text: You need to use a lambda statement when you assign the function for the button, so that it reevaluates the value in the dropdown each time the button is pressed. If you don't want it to just print the drop down selection, you need to use the selection to find your data, I don't know how your data is set up so I can't help you with that
score: 0
comment on: http://stackoverflow.com/q/51744012

http://stackoverflow.com/a/51705025
has body: Your problem is probably that list_gw.index(letter) only returns the first index and not all indexes! Instead of using index, you could loop through the word, checking each character one by one and update the player_guess accordingly.
score: 0
answers question: http://stackoverflow.com/q/51704901
type: Answer

http://stackoverflow.com/comment/90464492
has text: Will check this out when I get home. But what this be called that I can look further into it to understand it better?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51751967
type: AnswerComment

http://stackoverflow.com/a/65849625
upvote count: 2
answers question: http://stackoverflow.com/q/51699443
downvote count: 0
has body: For posterity here, I found what I needed in the AppointmentItem object on this page: Outlook Visual Basic for Applications (VBA) reference Just expand that object on the left side of the page, and then expand properties. Found everything I needed there. Also a MeetingItem object, still in the process of figuring out the difference (which sounds like it's obvious, but a lot of the appointments I'm getting back are actually meetings (i.e. have attendees).
type: Answer
score: 2

http://stackoverflow.com/comment/90247641
type: QuestionComment
comment on: http://stackoverflow.com/q/51641313
score: 1
has text: This is what I got : [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Amine\\Desktop\\omp\\media\\remix.mp3'
type: Comment

http://stackoverflow.com/q/51724309
favorite count: 0
possible better answer: http://stackoverflow.com/a/61081373
has answer: http://stackoverflow.com/a/54138575
has answer: http://stackoverflow.com/a/61081373
tagged with: python
has answer: http://stackoverflow.com/a/60901505
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51724531
has answer: http://stackoverflow.com/a/61507990
has answer: http://stackoverflow.com/a/64264684
tagged with: tensorflow
type: Question
has title: AttributeError: module 'tensorflow' has no attribute 'name_scope' with Keras
has body: I am trying to run a script, but I struggle already at the imports. This import from keras.preprocessing.image import save_img raises the following error: AttributeError: module 'tensorflow' has no attribute 'name_scope'. I am using the following packages. Keras 2.2.2, Keras-Applications 1.0.4, Keras-Preprocessing 1.0.2, tensorflow 1.9.0, tensorflow-gpu 1.9.0
upvote count: 12
downvote count: 0
tagged with: keras
score: 12
has answer: http://stackoverflow.com/a/51724531
has answer: http://stackoverflow.com/a/60662693
answer count: 7

http://stackoverflow.com/a/51729499
score: 0
accepted answer of: http://stackoverflow.com/q/51716954
answers question: http://stackoverflow.com/q/51716954
has body: The combination of nonzero and roll can be used for this purpose. For example, if k=0 in the loop shown below, then np.any will identify the rows that are not identically zero. The first and last such rows are noted, and the shift along the axis is computed so that after the shift, (first+last)/2 will move to the middle row of the array. Then the same is done for columns. import numpy as np my_array = np.array([[1, 1, 0, 0], [2, 4, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) print(my_array) # before for k in range(2): nonempty = np.nonzero(np.any(my_array, axis=1-k))[0] first, last = nonempty.min(), nonempty.max() shift = (my_array.shape[k] - first - last)//2 my_array = np.roll(my_array, shift, axis=k) print(my_array) # after Before: [[1 1 0 0] [2 4 0 0] [0 0 0 0] [0 0 0 0]] After: [[0 0 0 0] [0 1 1 0] [0 2 4 0] [0 0 0 0]] Alternative: np.count_nonzeros can be used in place of np.any, which allows to potentially set some threshold for the number of nonzero pixels that are deemed "enough" to qualify a row as a part of the image.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51682653
has comment: http://stackoverflow.com/comment/130950302
downvote count: 0
has comment: http://stackoverflow.com/comment/90328056
has comment: http://stackoverflow.com/comment/107734743
has comment: http://stackoverflow.com/comment/126986963
has comment: http://stackoverflow.com/comment/90328033
score: 10
has comment: http://stackoverflow.com/comment/130950340
accepted answer of: http://stackoverflow.com/q/51682594
has body: You can use standard CharField. To store hash value use make_password method before saving: from django.contrib.auth.hashers import make_password password = models.CharField(max_length=256) def save(self, **kwargs): some_salt = 'some_salt' password = make_password(self.password, some_salt) if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs)
answers question: http://stackoverflow.com/q/51682594
type: AcceptedAnswer
upvote count: 10
has comment: http://stackoverflow.com/comment/107734686
has comment: http://stackoverflow.com/comment/90328095
type: Answer

http://stackoverflow.com/comment/90444873
comment on: http://stackoverflow.com/q/51742453
has text: So what have you tried, and what exactly is the problem with it?
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51747965
type: Answer
upvote count: 6
has body: I think, the below would be helpful. &gt;&gt;&gt; printt=[1,4,2,3,5] &gt;&gt;&gt; for numm in printt: ... print('-----------------------------------------') ... print('output%d' % (numm)) ... ----------------------------------------- output1 ----------------------------------------- output4 ----------------------------------------- output2 ----------------------------------------- output3 ----------------------------------------- output5 &gt;&gt;&gt;
downvote count: 1
has comment: http://stackoverflow.com/comment/90455733
score: 5
answers question: http://stackoverflow.com/q/51747854

http://stackoverflow.com/comment/90541166
score: 0
type: Comment
has text: This will fail when I try to append another tuple to this list. When i try that, I get `[None, tuple]`
comment on: http://stackoverflow.com/a/51791836
type: AnswerComment

http://stackoverflow.com/q/51738372
favorite count: 0
has body: I'm working with bokeh to generate stock data, whereby the user selects a tickername and start/end dates to generate a graph. However, when selecting certain stocks, the y axis becomes distorted (See my previous question: Bokeh plot becomes distorted when certain stocks are inputted). I've tried to mitigate this by manually setting the y range as the min and max values of a stock upon selection, however, the new range does not update and the y axis does not change. How can I fix this issue? Any suggestions would be appreciated. p=figure( height=400, x_axis_type='datetime', title=(company+' ('+tickerstring+') '), tools='pan, box_zoom, wheel_zoom, reset', ) x = np.array(sandpdates, dtype=np.datetime64) y=sandpclose r=p.line(x, y) p.grid.grid_line_color="white" p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.add_tools(HoverTool( tooltips=[ ("Date", "@x{%F}"), ('Close',"@y") ], formatters={ 'x':'datetime', # use 'datetime' formatter for 'date' field }, mode='vline' )) def update(f, startyear=2015, startmonth=1, startday=1, endyear=current_year, endmonth=current_month, endday=current_day): fstocksymbol=str(f.upper()) starts=dt.datetime(startyear,startmonth,startday) end = dt.datetime(endyear,endmonth,endday) if int(startyear)&gt; int(endyear): print('Please ensure the starting date does not exceed the end date') elif int(startyear)==int(endyear): if startmonth&gt;endmonth: print('Please ensure the starting date does not exceed the end date') elif startmonth==endmonth: if startday&gt;endday: print('Please ensure the starting date does not exceed the end date') else: print('') if fstocksymbol in stocksymbols: p.title.text = (symbolsdictionary[fstocksymbol]).upper()+' ('+fstocksymbol+')' tickerstring=fstocksymbol firstfunction=stockname(tickerstring, starts, end) secondfunction=stockdata(firstfunction) stockdates=[] stockcloseprices=[] for value in secondfunction: stockdates.append(value[0]) stockcloseprices.append(float(value[4])) finaldate=np.array(stockdates, …
tagged with: range
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53335551
upvote count: 1
tagged with: plot
score: 1
tagged with: bokeh
has title: Python Bokeh Range Does Not Change Upon Update
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51768622
answers question: http://stackoverflow.com/q/51757421
has comment: http://stackoverflow.com/comment/90510037
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90505873
type: Answer
has body: In your URLs you have \n. This needs to be stripped out. There is no pre tag in the HTML so in this example I have found the second h1 tag to test with. import requests from bs4 import BeautifulSoup # In your function you need to strip out "\n" as it has no place in your URLs. def build_url(gene): return 'https://www.ncbi.nlm.nih.gov/nuccore/' + gene.rstrip() + '.1?report=fasta' csv = open("C:/Projects/NCBI Scraper project/geneAccNumbers.txt", 'r') genes_urls = [build_url(gene) for gene in csv] results = [] for url in genes_urls: r = requests.get(url) # Using html.parser but you can use lxml if you like. soup = BeautifulSoup(r.text,"html.parser") # there is no &lt;pre&gt; tag in the soup so we will find the second occurrence of H1 for testing. result = soup.find_all('h1')[1].text print (result) results +=[result] print (results) Outputs: Impatiens amoena internal transcribed spacer 1, 5.8S ribosomal RNA gene, and internal transcribed spacer 2, complete sequence Impatiens amphorata internal transcribed spacer 1, 5.8S ribosomal RNA gene, and internal transcribed spacer 2, complete sequence Impatiens andohahelae internal transcribed spacer 1, 5.8S ribosomal RNA gene, and internal transcribed spacer 2, complete sequence Impatiens andringitrensis internal transcribed spacer 1, 5.8S ribosomal RNA gene, and internal transcribed spacer 2, complete sequence Impatiens angulata voucher S.X. Yu 3777 internal transcribed spacer 1, partial sequence; 5.8S ribosomal RNA gene, complete sequence; and internal transcribed spacer 2, partial sequence Impatiens angulata voucher S.X. Yu 3777 atpB-rbcL intergenic spacer, partial sequence; chloroplast Impatiens angulata voucher S.X. Yu 3777 tRNA-Leu (trnL) gene, partial sequence; trnL-trnF intergenic spacer, complete sequence; and tRNA-Phe (trnF) gene, partial sequence; plastid Impatiens anovensis internal transcribed spacer 1, 5.8S ribosomal RNA gene, and internal transcribed spacer 2, complete sequence Impatiens apalophylla voucher S.X. Y…
has comment: http://stackoverflow.com/comment/90511984
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51757421
score: 1

http://stackoverflow.com/q/51790062
answer count: 1
has answer: http://stackoverflow.com/a/51790310
has title: Heatmap plot of a pandas dataframe - TypeError
tagged with: typeerror
tagged with: pandas
tagged with: python
has body: I have two pandas dataframes that on inspection look identical. One was created using the Pandas builtin: df.corr(method='pearson') While the other was created with a custom function: def cor_matrix(dataframe, method): coeffmat = pd.DataFrame(index=dataframe.columns, columns=dataframe.columns) pvalmat = pd.DataFrame(index=dataframe.columns, columns=dataframe.columns) for i in range(dataframe.shape[1]): for j in range(dataframe.shape[1]): x = np.array(dataframe[dataframe.columns[i]]) y = np.array(dataframe[dataframe.columns[j]]) bad = ~np.logical_or(np.isnan(x), np.isnan(y)) if method == 'spearman': corrtest = spearmanr(np.compress(bad,x), np.compress(bad,y)) if method == 'pearson': corrtest = pearsonr(np.compress(bad,x), np.compress(bad,y)) coeffmat.iloc[i,j] = corrtest[0] pvalmat.iloc[i,j] = corrtest[1] return (coeffmat, pvalmat) Both look identical and have same type (pandas.core.frame.DataFrame) and their entries are also of same type (numpy.float64) However when I try to plot these using: import matplotlib.pyplot as plt plt.imshow((df)) Only the dataframe created with the pandas builtin function works. For the other dataframe I receive the error: TypeError: Image data cannot be converted to float. Can anyone explain what is going on, how the two dataframes are different and what can be done to address the error? Edit - It looks as though there is one difference, when I convert the dataframes to a numpy array, the one that doesn't work has dtype = object at the end. Is there a way to remove this?
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90537997
tagged with: matplotlib
score: 0

http://stackoverflow.com/comment/90493478
type: QuestionComment
comment on: http://stackoverflow.com/q/51756391
has text: I doubt that all the stuff is part of single, large string (as shown). I want to know the Python data structure you're using.
score: 0
type: Comment

http://stackoverflow.com/comment/90473939
comment on: http://stackoverflow.com/q/51757233
has text: 1. The `r` is a piece of syntax for a string literal. The string object does not have or not have an `r`, so you can't add one.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51798304
accepted answer: http://stackoverflow.com/a/51801898
type: Question
has comment: http://stackoverflow.com/comment/90559107
has body: I want to send a simple SYN request to my router to get an ACK response in a bid to learn network (TCP/IP) using python and scapy. But scapy is taking a long time of getting any answer. script- #!/usr/bin/env python from scapy.all import * pack=TCP(sport=22,dport=80,flags='S')/IP(src="192.168.0.13",dst="192.168.0.1") # tried with retry and timeout options using both sr() and sr1() # but it comes with no answer from the router. # ran this with sudo and iptables policy is default [ACCEPT] ans = sr1(pack) What is the solution ?
has title: scapy takes infinite time sending TCP SYN packet with no reply.
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90559980
has answer: http://stackoverflow.com/a/51801898
has comment: http://stackoverflow.com/comment/90559091
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/90560071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90558453
tagged with: tcp
tagged with: scapy

http://stackoverflow.com/comment/90272774
type: AnswerComment
score: 0
type: Comment
has text: I know this way to configure the interpreter. But in this case cygwin comes first and the python config does not get used. I updated the question to make this more clear.
comment on: http://stackoverflow.com/a/51652159

http://stackoverflow.com/q/51676052
accepted answer: http://stackoverflow.com/a/51678111
tagged with: python
tagged with: dictionary
has title: Pandas: Combining DataFrames with nested arrays or merging the JSON output
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90315951
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51678111
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90315821
has body: I'm taking a standard data frame and creating various sub-set data frames of summary data with nested arrays. I then need to combine the sub-set data frames in a way that gives me the intended JSON output. (I used MaxU's answer to format most of my code; Convert Pandas Dataframe to nested JSON) First few rows of my standard data frame (If necessary I could give all 58 rows from this example): df ID PRI_AFF PRI_DEP LOA STATE 0 5571 M Basic A 1 5030 T 14700000 Blue A 2 5030 T 14700000 Blue A 3 5030 T 14700000 Blue A 4 4014 T 14700000 Blue A 5 2230 T 14700000 UFM A 6 2230 T 14700000 UFM A 7 2150 F 95011000 Bronze A 8 2150 F 95011000 Bronze A 9 2150 F 95011000 Bronze A 10 2150 F 95011000 Bronze A From here I use the following Python: PAFF_df = pd.DataFrame(df.groupby(['PRI_DEP','PRI_AFF'])['ID'].nunique().unstack().reset_index().fillna(0)) LOA_df = pd.DataFrame(df.groupby(['PRI_DEP','LOA'])['ID'].nunique().unstack().reset_index().fillna(0)) ST_df = pd.DataFrame(df.groupby(['PRI_DEP','STATE'])['ID'].nunique().unstack().reset_index().fillna(0)) Nested_PAFF_df = (PAFF_df.groupby(['PRI_DEP'], as_index=True) .apply(lambda x: x'A','E','F','L','M','T'.to_dict('r')) .reset_index() .rename(columns={0:'Primary_Affiliation'})) Nested_LOA_df = (LOA_df.groupby(['PRI_DEP'], as_index=True) .apply(lambda x: x'Basic','Blue','Bronze','Invalid','UFM'.to_dict('r')) .reset_index() .rename(columns={0:'LOA'})) Nested_ST_df = (ST_df.groupby(['PRI_DEP'], as_index=True) .apply(lambda x: x'A','E'.to_dict('r')) .reset_index() .rename(columns={0:'STATE'})) Which gives me the appropriate nested JSONs using: .to_json(orient='records') Primary Affiliation JSON: [{"PRI_DEP":" ","Primary_Affiliation":[{"A":0.0,"E":0.0,"F":0.0,"M":2.0,"L":0.0,"T":0.0}]},{"PRI_DEP":"14700000","Primary_Affiliation":[{"A":0.0,"E":3.0,"F":0.0,"M":1.0,"L":1.0,"T":19.0}]},{"PRI_DEP":"95011000","Primary_Affiliation":[{"A":0.0,"E":0.0,"F":1.0,"M":0.0,"L":0.0,"T":0.0}]},{"PRI_DEP":"Null","Primary_Affiliation":[{"A":0.…
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/40470954
tagged with: pandas

http://stackoverflow.com/q/51643689
answer count: 1
tagged with: speech-recognition
has title: Python Speech Recognition: AttributeError: module 'speech_recognition' has no attribute 'Recognizer'
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51643826
has comment: http://stackoverflow.com/comment/90251782
has body: I know there are several threads of my question, but no answer of it helped me and I tried anything I can think of and saw here. The error code im getting: Traceback (most recent call last): File "/home/pi/Documents/SB/sp_recog.py", line 4, in &lt;module&gt; import speech_recognition as sr File "/home/pi/Documents/SB/speech_recognition.py", line 59, in &lt;module&gt; data = recordAudio() File "/home/pi/Documents/SB/speech_recognition.py" line 20, in recordAudio r = sr.Recognizer() AttributeError: module 'speech_recognition' has no attribute 'Recognizer' And the Python Script im using: #!/usr/bin/env python3 # Requires PyAudio and PySpeech. import speech_recognition as sr import vlc import time import os from time import ctime from gtts import gTTS def speak(audioString): print(audioString) tts = gTTS(text=audioString, lang='de') tts.save("audio.mp3") os.system("mpg321 audio.mp3") def recordAudio(): # Record Audio r = sr.Recognizer() p = vlc.MediaPlayer("PRIVATE") with p.play() as source: print("Say something!") audio = r.listen(source) # Speech recognition using Google Speech Recognition data = "" try: # Uses the default API key # To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` data = r.recognize_google(audio) print("You said: " + data) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) return data def PRIVATE(data): if "PRIVATE" in data: speak("PRIVATE") if "PRIVATE" in data: speak(ctime()) if "PRIVATE" in data: data = data.split(" ") location = data[2] speak("PRIVATE") # initialization time.sleep(2) speak("PRIVATE") while 1: data = recordAudio() PRIVATE(data) I changed some of the code because I don't want it to be read. I copied the script from a site and modified it so I can work with it. Things I tried: Changing the filename Compiling the script to a executable …
type: Question
accepted answer: http://stackoverflow.com/a/51643826
score: 0
has comment: http://stackoverflow.com/comment/90251726

http://stackoverflow.com/a/53837519
downvote count: 0
score: 37
answers question: http://stackoverflow.com/q/51734180
has comment: http://stackoverflow.com/comment/135232534
upvote count: 37
has body: An easy solution is just one line of code: LRresult = (result.summary2().tables[1]) As ZaxR mentioned in the following comment, Summary2 is not yet considered stable, while it works well with Summary too. So this could be correct answer: LRresult = (result.summary().tables[1]) This will give you a dataframe object: type(LRresult) pandas.core.frame.DataFrame To get the significant variables and run the test again: newlist = list(LRresult[LRresult['P&gt;|z|']&lt;=0.05].index)[1:] myform1 = 'binary_Target' + ' ~ ' + ' + '.join(newlist) M1_test2 = smf.logit(formula=myform1,data=myM1_1) result2 = M1_test2.fit(maxiter=200) LRresult2 = (result2.summary2().tables[1]) LRresult2
has comment: http://stackoverflow.com/comment/94538287
type: Answer
has comment: http://stackoverflow.com/comment/110052721

http://stackoverflow.com/comment/90337921
has text: @KennyOstrom no, if I wanted to set `{'A': 110, 'C': 0, 'B': 0, 'D': 21}` to some parameter obj, it would be easy. But what I am looking for is some method(if there is one) to set this parameter as init: which would eventually do the following: sum values of this dict, if their first index is equal of this parameters index.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51686199

http://stackoverflow.com/a/51795473
accepted answer of: http://stackoverflow.com/q/51794733
type: AcceptedAnswer
downvote count: 0
has body: You cannot use an image as a background in a text widget. The best you can do is to create a canvas, place an image on the canvas, and then create a text item on top of that. Text items are editable, but you would have to write a lot of bindings, and you wouldn't have nearly as many features as the text widget. In short, it would be a lot of work.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51794733

http://stackoverflow.com/q/51768755
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90496299
has comment: http://stackoverflow.com/comment/90496187
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90496267
has comment: http://stackoverflow.com/comment/90496192
type: Question
possible better answer: http://stackoverflow.com/a/51768814
has body: So I have a dictionary which needs to be sorted by values. I sort them with below Python3 function which returns sorted data as a list of tuples. def sorter(data): return sorted(data.items(), key=lambda kv: kv[1], reverse=True) It sorts the data perfectly, but when I convert this list back to dictionary by dict(sorter(data)) It loses the order and returns a dictionary in a completely random order. What am I missing here?
tagged with: sorting
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51768808
has answer: http://stackoverflow.com/a/51768814
has title: Losing sort order in python dictionary after converting from list of tuples
has answer: http://stackoverflow.com/a/51768808
tagged with: python

http://stackoverflow.com/comment/90424355
type: QuestionComment
type: Comment
has text: change to `btn.clicked.connect(lambda x, text=ch['info'] : self.btn_clicked(text))`
score: 1
comment on: http://stackoverflow.com/q/51696185

http://stackoverflow.com/comment/90337557
comment on: http://stackoverflow.com/a/51687459
has text: @Harry_pb I edited my answer, hope that this will help!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90287859
comment on: http://stackoverflow.com/q/51658287
type: Comment
type: QuestionComment
has text: Applying `astype('object')` to the categorical column at least seems to solve the problem.
score: 0

http://stackoverflow.com/a/51749514
has comment: http://stackoverflow.com/comment/90460591
score: 0
accepted answer of: http://stackoverflow.com/q/51749388
has body: It's not required, but your queries become easier if you define a ManyToManyField from Room to User. This can use your existing RoomMember model as a through table, so doesn't need any database changes, but you should drop the members related_name so that you can use that name for the m2m: class Room(DateTimeModel): ... members = models.ManyToManyField(User, through='RoomMember') Now you can do: Room.objects.filter(member=foo).filter(member=bar)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51749388
type: Answer

http://stackoverflow.com/comment/90553031
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51798058
type: Comment
has text: Please post your attempted code.

http://stackoverflow.com/comment/90295526
type: Comment
comment on: http://stackoverflow.com/a/51666099
score: 0
type: AnswerComment
has text: bbb.index = pd.to_datetime(bbb.pop('Date')) + pd.to_timedelta(bbb.pop('Time')) print (bbb) my dataFrame is bbb 'KeyError: 'Date'

http://stackoverflow.com/q/51710490
has comment: http://stackoverflow.com/comment/90382282
duplicate of: http://stackoverflow.com/q/2400840
has answer: http://stackoverflow.com/a/51710619
has comment: http://stackoverflow.com/comment/90382266
has answer: http://stackoverflow.com/a/51710576
tagged with: python
tagged with: list
downvote count: 0
score: 1
has body: here is my code. A = [86.14803712, 85.25496701, 86.50334271, 86.0266668, 86.61455594, 86.90445213, 86.65519315, 87.10116762, 87.08173861] B = [] i = 0 for i in range(len(A)): c = A[i]-A[i-1] B.append(c) print(c) I want to get the differences between two continuous numbers in this list, eg,(85.25496701-86.14803712). So in the results, I should have eight numbers as results. But the results I get are: -0.9337014900000042 -0.8930701099999965 1.2483756999999969 -0.4766759099999973 0.5878891400000015 0.2898961899999932 -0.24925897999999336 0.4459744699999959 -0.019429009999996083 I don't need -0.9337014900000042 since it comes from the first number subtract the last number in the list. What should I do the fix it? Thanks
has answer: http://stackoverflow.com/a/51710586
has comment: http://stackoverflow.com/comment/90383063
has answer: http://stackoverflow.com/a/51710558
type: Question
linked to: http://stackoverflow.com/q/2400840
duplicate of: http://stackoverflow.com/q/5314241
answer count: 6
has title: How to calculate numbers in a list
upvote count: 1
linked to: http://stackoverflow.com/q/6822725
has answer: http://stackoverflow.com/a/51710572
favorite count: 0
has answer: http://stackoverflow.com/a/51710569
has comment: http://stackoverflow.com/comment/90382291
type: UnansweredQuestion

http://stackoverflow.com/a/51709302
has comment: http://stackoverflow.com/comment/90384348
type: Answer
accepted answer of: http://stackoverflow.com/q/51705712
score: 3
upvote count: 3
has body: You can take advantage of CSS selector span[id$=lblResultsRaceName], which finds all spans that's id ends with lblResultsRaceName and 'td &gt; span', which finds all spans that have direct parent &lt;td&gt;: This code snippet will go through all racing result and prints all races: import requests from bs4 import BeautifulSoup url = "https://www.thedogs.com.au/Racing/Results.aspx?SearchDate=3-Jun-2018" def get_info(session,link): session.headers['User-Agent'] = "Mozilla/5.0" res = session.get(link) soup = BeautifulSoup(res.text,"lxml") formdata = {i['name']: i['value'] for i in soup.select('input[type=hidden]')} for race_name, i in zip(soup.select('span[id$=lblResultsRaceName]'), soup.select('input[id$=btnViewResults]')): print(race_name.text.strip()) formdata[i['name']] = 'Results' req = session.post(link,data = formdata) soup = BeautifulSoup(req.text,"lxml") for panel in soup.select('div[id^=ctl00_ContentPlaceHolder1_tabContainerRaces_tabRace]'): print(panel.select('td &gt; span')[0].text.strip(), panel.select('td &gt; span')[1].text.strip()) print('#' * 80) if __name__ == '__main__': with requests.Session() as session: get_info(session,url) Prints: Healsville Race 1 Grade: M 300 metres Race 2 Grade: M 350 metres Race 3 Grade: 6/7 350 metres Race 4 Grade: R/W 300 metres Race 5 Grade: 5 350 metres Race 6 Grade: SE 350 metres Race 7 Grade: 4/5 350 metres Race 8 Grade: SE 350 metres Race 9 Grade: 7 300 metres Race 10 Grade: 6/7 300 metres Race 11 Grade: 4/5 300 metres Race 12 Grade: 5 300 metres ################################################################################ Sale Race 1 Grade: M 440 metres Race 2 Grade: M 440 metres Race 3 Grade: R/W 520 metres Race 4 Grade: 7 440 metres Race 5 Grade: R/W 440 metres Race 6 Grade: 4/5 520 metres Race 7 Grade: R/W 440 metres Race 8 Grade: 4/5 440 metres Race 9 Grade: 6/7 440 metres Race 10 Grade: R/W 440 metres Race 11 Grade: R/W 440 metres Race 12 Grade: 5 520 metres ####################################################…
answers question: http://stackoverflow.com/q/51705712
has comment: http://stackoverflow.com/comment/90381375
has comment: http://stackoverflow.com/comment/90384769
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90381578

http://stackoverflow.com/comment/90282518
score: 0
type: QuestionComment
type: Comment
has text: I believe the problem is that the libusb0-dll is attempting to claim an interface that is already being used. Humor me and try: endpoint2 = device2[1][(0,0)][0]
comment on: http://stackoverflow.com/q/51656023

http://stackoverflow.com/comment/90380979
type: QuestionComment
comment on: http://stackoverflow.com/q/51709412
score: 0
has text: Another approach could concatenate the columns first and use lambda but it will require to iterate over the previous df again and again and hence the earlier approach should be better.
type: Comment

http://stackoverflow.com/q/51763696
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90486454
has answer: http://stackoverflow.com/a/51766498
linked to: http://stackoverflow.com/q/37580151
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51763844
has title: Extract digits from currency symbol and format it
has comment: http://stackoverflow.com/comment/90486172
score: 0
answer count: 2
has body: +---------+---------+------------+-----------+ | Input | Excepted | +---------+---------+------------+-----------+ | EUR 1.409,00 | 1409 | | $ 409,05 | 409.05 | | ￥409.50 | 409.5 | | CNY 1,000 | 1000 | +---------+---------+------------+-----------+ The first thought came into my mind is regular expression. I can't write it though. How do you figure this out?
has comment: http://stackoverflow.com/comment/90489180
favorite count: 0
tagged with: currency

http://stackoverflow.com/comment/90245234
has text: @ConradSelig Good catch...I wonder why that's not the default behavior for OP
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51640350
score: 0

http://stackoverflow.com/q/51756049
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51770414
tagged with: elementtree
favorite count: 0
has comment: http://stackoverflow.com/comment/90498689
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90471826
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90475112
has title: Need help replacing text in a sub-element with text from multiple sub-elements in an XML
upvote count: 1
has answer: http://stackoverflow.com/a/51770414
type: Question
has body: I am trying to replace the Value text in an XML tree with the text from other sub-elements in the tree. I am new to Python need some help with how to write this. Example of my XML with some elements omitted for length: 1 4.00 <ConfigurationAttribute> ConfigurationModel HV </ConfigurationAttribute> <ConfigurationAttribute> EXWidth 59.5 </ConfigurationAttribute> <ConfigurationAttribute> EXHeight 59.5 </ConfigurationAttribute> <ConfigurationAttribute> Handing XO </ConfigurationAttribute> <ConfigurationAttribute> LongDescription This is a long paragraph of text i want to replace with the above text for the Value sub-element </ConfigurationAttribute> Here is my first attempt Python code using the ElementTree library: import xml.etree.ElementTree as ET from tkinter import Tk from tkinter.filedialog import askopenfilename, asksaveasfilename Tk().withdraw() file = askopenfilename() tree = ET.parse(file) root = tree.getroot() def model(): for ConfigurationAttribute in root.iter('ConfigurationAttribute'): descrip = ConfigurationAttribute.find('Name').text model = '' if descrip == 'ConfigurationModel': model = ConfigurationAttribute.find('Value').text def handing(): for ConfigurationAttribute in root.iter('ConfigurationAttribute'): descrip = ConfigurationAttribute.find('Name').text handing = '' if descrip == 'Handing' and ConfigurationAttribute.find('Value') is not None: handing = ConfigurationAttribute.find('Value').text def width(): for ConfigurationAttribute in root.iter('ConfigurationAttribute'): descrip = ConfigurationAttribute.find('Name').text width = '' if descrip == 'EXWidth': width = ConfigurationAttribute.find('Value').text def height(): for ConfigurationAttribute in root.iter('ConfigurationAttribute'): descrip = ConfigurationAttribute.find('Name').text height = '' if descrip == 'EXHeight': height = ConfigurationAttribute.find('Value').text for ConfigurationAttribute in root.iter('ConfigurationAttribute'): descrip = ConfigurationAttribute.find('Name').text if descri…
tagged with: xml-parsing

http://stackoverflow.com/a/51715702
has comment: http://stackoverflow.com/comment/90395109
has comment: http://stackoverflow.com/comment/90393363
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90393171
answers question: http://stackoverflow.com/q/51714694
has body: You might be being rejected by the server in your first example due to not pretending to be an ordinary browser. You should try combining the user agent code from the second example with the Beautiful Soup code from the first: import urllib.request from bs4 import BeautifulSoup user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' url = "https://www.nissanusa.com/dealer-locator.html" headers={'User-Agent':user_agent,} request=urllib.request.Request(url,None,headers) #The assembled request response = urllib.request.urlopen(request) text = response.read() soup = BeautifulSoup(text, "lxml") data = soup.findAll('div',attrs={'class':'dealer-info'}) for div in data: links = div.findAll('a') for a in links: print(a['href']) Keep in mind that if the web site is explicitly trying to keep Beautiful Soup or other non-recognized user agents out, they may take issue with you scraping their web site data. You should consult and obey https://www.nissanusa.com/robots.txt as well as any terms of use or terms of service agreements you may have agreed to.

http://stackoverflow.com/a/51779969
has body: I've never seen @Bendebaria 's pattern for GET and POST routes, but haven't tested so I can't confirm it doesn't work (although I suspect it won't if you have multiple routes defined that way). The official Flask docs (http://flask.pocoo.org/docs/1.0/quickstart/#http-methods) say to do it like this: from flask import request @app.route('/search', methods=['GET', 'POST']) def search(): if request.method == 'POST': return do_the_db_search() else: return show_the_search_form() But, indeed like he says, you don't need the redirect, in fact you can just call a regular function as part of your existing routing then return a render_template within those.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90520462
has comment: http://stackoverflow.com/comment/94251761
answers question: http://stackoverflow.com/q/51765827
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90396761
type: QuestionComment
score: 1
has text: Is a recursive solution required? Mine is iterative.
comment on: http://stackoverflow.com/q/51717675
type: Comment

http://stackoverflow.com/comment/90528312
score: 0
comment on: http://stackoverflow.com/q/51785355
type: Comment
type: QuestionComment
has text: Yes, they are individual dicts apologies for the lack of clarity.

http://stackoverflow.com/comment/90450113
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51745203
has text: I will try this, but how come a regular model function won't work? `def finish(self): return timezone.now + timezone.timedelta(hours=self.duration)` ?

http://stackoverflow.com/q/51693792
downvote count: 1
answer count: 1
tagged with: cudnn
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90350232
tagged with: python
has body: I have a GPU of NVIDIA GeForce 940mx GDDR5 2GB on my laptop. I want to use TensorFlow with GPU support. I tried steps of installing tensorflow from the link https://www.tensorflow.org/install/install_windows I have installed : CUDA 9.0 toolkit with all three patches updates available on https://developer.nvidia.com/cuda-90-download-archive?target_os=Windows&amp;target_arch=x86_64&amp;target_version=10&amp;target_type=exelocal cuDNN 7.1.4 for CUDA toolkit 9.0 from https://developer.nvidia.com/rdp/cudnn-download pip install tensorflow-gpu While import tensorflow using: import tensorflow as tf I got an error: ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 9.0 from this URL: https://developer.nvidia.com/cuda-toolkit I have that file in 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin' and my system environment path variable has also been configured to this directory, what else could be the issue?
upvote count: 0
has title: Error while importing tensorflow library for deep learning GPU?
has comment: http://stackoverflow.com/comment/90350504
tagged with: machine-learning
tagged with: tensorflow
type: Question
score: -1
has comment: http://stackoverflow.com/comment/90350275
has answer: http://stackoverflow.com/a/51694295
has comment: http://stackoverflow.com/comment/90349760

http://stackoverflow.com/q/51645273
has comment: http://stackoverflow.com/comment/90254642
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51645319
tagged with: pandas
has body: Here's my dataset body customer_id name 14828 Thank you to apply to us. 5458 Sender A 23117 Congratulation your application is accepted. 5136 Sender B 23125 Your OTP will expire in 10 minutes. 5136 Sender A Here's my code import pandas as pd from sklearn.feature_extraction.text import CountVectorizer b = a['body'] vect = CountVectorizer() vect.fit(b) X_vect=vect.transform(b) pd.DataFrame(X_vect.toarray(), columns=vect.get_feature_names()) The output is 10 application apply ... your 0 0 0 1 0 1 0 1 0 1 2 1 0 0 1 What I need is body customer_id name 10 application apply ... your 14828 Thank you to apply to us. 5458 Sender A 0 0 1 0 23117 Congratulation your application is accepted. 5136 Sender B 0 1 0 1 23125 Your OTP will expire in 10 minutes. 5136 Sender A 1 0 0 1 How suppose I do this? I'm still hoping to use CountVectorizer so I can modify the function in the future
downvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: countvectorizer
favorite count: 0
has answer: http://stackoverflow.com/a/51645319
has comment: http://stackoverflow.com/comment/90254627
tagged with: python
type: AnsweredQuestion
has title: How do I merge data with CountVectorizer features
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/a/51733159
has body: The error will get raised here: if any(s for s in pygame.sprite.spritecollide(self, fences, False) if s != self): print("RISK_LEVEL: ", fences.risk_level) fences is a sprite group and it doesn't have a risk_level attribute, only the GeoFence sprites in this group have this attribute. So you need to figure out which sprites have collided with the worker and then access the risk_level of these sprites. The simplest solution would be to iterate over the collided sprites with a for loop (replace the two lines above with): for s in pygame.sprite.spritecollide(self, fences, False): print("RISK_LEVEL: ", s.risk_level)
accepted answer of: http://stackoverflow.com/q/51731348
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51731348
type: AcceptedAnswer

http://stackoverflow.com/a/51784435
has comment: http://stackoverflow.com/comment/90527629
has comment: http://stackoverflow.com/comment/90525974
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51784307
accepted answer of: http://stackoverflow.com/q/51784307
has body: Python 3.6 will be great. It will definitely work, but yeah be careful while setting the path.
type: Answer

http://stackoverflow.com/comment/90509250
score: 0
comment on: http://stackoverflow.com/q/51775175
type: Comment
type: QuestionComment
has text: @MichaelB, thanks, I tried, but it does not create '[ ]' after "pattern". Basically, 'pattern' values should be a list.

http://stackoverflow.com/a/51673224
has body: You can actually read your file directly with Pandas to simplify the program. I can reproduce the output you are expecting with: import pandas as pd df = pd.read_csv('data.txt', engine='python' header=1,sep=r'\s{2,}') period = input('Enter the period: ') lower_energy = float(input('Enter the lower energy value: ')) higher_energy = float(input('Enter the higher energy value: ')) # select the channels within the ranges provided lo_e_range = (df[period] &gt; lower_energy) hi_e_range = (df[period] &gt; higher_energy) # Indices of the lower and higher energy channels lec = df[period][lo_e_range].index[0] hec = df[period][hi_e_range].index[0] print('The lower energy channel is {}'.format(df['CHANNELS'][lec])) print('The higher energy channel is {}'.format(df['CHANNELS'][hec])) I have edited the code to take into account your comment.
answers question: http://stackoverflow.com/q/51672531
has comment: http://stackoverflow.com/comment/90309192
upvote count: 1
has comment: http://stackoverflow.com/comment/90310378
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90407085
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51723241
type: QuestionComment
has text: You need to improve this question, is not clear what you want to achieve. If you say that `backward(number): return a "random" number between 0 and 9`, why you need a `number` argument in the first place? seems not related. *Just what do you think you're doing, Jonas?*

http://stackoverflow.com/q/51682060
tagged with: space
tagged with: python
has answer: http://stackoverflow.com/a/51682068
score: 2
has title: Using regular expression to count the number of spaces at the beginning of a string
duplicate of: http://stackoverflow.com/q/13241399
has comment: http://stackoverflow.com/comment/90327041
upvote count: 2
tagged with: whitespace
linked to: http://stackoverflow.com/q/13241399
type: Question
has body: How can I use regex to count the number of spaces beginning of the string. For example: string = ' area border router' count_space variable would return me a value of 1 since there is 1 whitespace at the beginning of the string. If my string is: string = ' router ospf 1' count_space variable would return me a value of 2 since there is 2 whitespace at the beginning of the string. And so on.... I thing the expression would be something like RE = '^\s' ? But not sure how to formulate it.
answer count: 1
has comment: http://stackoverflow.com/comment/90327010
downvote count: 0
linked to: http://stackoverflow.com/q/2378962
tagged with: string
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90294814
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51653379
has text: why if I run dependency.py as `python dependency.py` at the entrypoint folder or dependency_resolver parent folder will get ImportError, but run as `python -m dependency_resolver.entrypoint.dependency` at dependency_resolver parent folder will be fine. Now my python version is 3.5 and import code is `import dependency_resolver.util.kube_util as kube_util`@Jean-François Corbett
score: 0

google-app-engine-python
type: Tag
tags question: http://stackoverflow.com/q/51748195
tag name: google-app-engine-python

http://stackoverflow.com/comment/90455163
type: AnswerComment
comment on: http://stackoverflow.com/a/51747428
score: 0
type: Comment
has text: @Daniel hey i updated the code, now for country I am checking the images, since the image is their country flag and we can get the country name from the title of the image

http://stackoverflow.com/comment/90460205
type: Comment
type: QuestionComment
score: 0
has text: The time, do you do 11:12, then 12:13, then 13:14 or??
comment on: http://stackoverflow.com/q/51750164

http://stackoverflow.com/q/51698624
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51702148
has title: repeated FeatureUnion in scikit-learn
has body: I am learning Pipelines and FeatureUnions in scikit-learn and thus wondering whether it is possible to repeated apply 'make_union' on a class? Consider the following code: import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.linear_model import LogisticRegression import sklearn.datasets as d class IrisDataManupulation(BaseEstimator, TransformerMixin): """ Raise the matrix of feature in power """ def __init__(self, power=2): self.power = power def fit(self, X, y=None): return self def transform(self, X): return np.power(X, self.power) iris_data = d.load_iris() X, y = iris_data.data, iris_data.target # feature union: fu = FeatureUnion(transformer_list=[('squared', IrisDataManupulation(power=2)), ('third', IrisDataManupulation(power=3))]) QUESTION Any neat way to create the FeatureUnion without repeating the same transformer, but rather passing a list of parameters? For example: fu_new = FeatureUnion(transformer_list=[('raise_power', IrisDataManupulation(), param_grid = {'raise_power__power':[2,3]})
type: Question
tagged with: pipeline
answer count: 1
accepted answer: http://stackoverflow.com/a/51702148
downvote count: 0
score: 1
tagged with: scikit-learn

http://stackoverflow.com/q/51641281
linked to: http://stackoverflow.com/q/13960326
score: 0
answer count: 1
has body: I want to access my business' database on some site and scrape it using Python (I'm using Requests and BS4, I can go further if needed). But I couldn't. Can someone provide us with info and simple resources on how to scrape such sites. I'm not talking about providing usernames and passwords. The site requires much more than this. How do I know the info I am required to provide for my script aside of UN and PW(e.g. how do I know that I must provide, say, an auth token)? How to deal with the site when there are no HTTP URLs, but hrefs in the form of javascript:__doPostBack? And in this regard, how do I transit from the logging in page to the page I want (the one contained in the aforementioned mentioned javascript:__doPostBack)? Are the libraries I'm using enough? or do you recommend using—and learning in my case—something else? Your help is greatly appreciated and thanked.
type: UnansweredQuestion
tagged with: python
has title: What information do I need when scraping a website that requires logging in?
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/51641462

http://stackoverflow.com/comment/90432372
type: QuestionComment
has text: FWIW, at the time of posting, this question was the one millionth question in the `python` tag. It may no longer be question #1000000 due to older questions being deleted or undeleted.
score: 2
comment on: http://stackoverflow.com/q/51710087
type: Comment

http://stackoverflow.com/comment/90549715
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51775918
has text: Again, see the first link... Big long list of Python libraries to interact with HDFS. However, `saveAsTable` works fine in PySpark, so I ask - what have you tried? What errors are you getting?

http://stackoverflow.com/comment/90371162
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51694806
has text: pleaaaaaaaaaaaaaaaaase help me guys !! networking experts, python experts where are you !!!!!!!

http://stackoverflow.com/q/51640978
has comment: http://stackoverflow.com/comment/90246444
possible better answer: http://stackoverflow.com/a/51641052
linked to: http://stackoverflow.com/q/40587320
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90246580
has answer: http://stackoverflow.com/a/51641060
accepted answer: http://stackoverflow.com/a/51641060
type: Question
has answer: http://stackoverflow.com/a/51641052
answer count: 2
has body: Let's say I have the following list ['house', 'John', 'garden']and a string 'MynameisJohn'. Is there a way in Python to check if any of the words in the list are part of the string even when there are no white spaces? The goal would finally be to have a function which returns the words which are part of the string and maybe something that describes where in the string the words start. So something like this: def function(list, string): returns [(word, position in the string)] I tried some things but essentially nothing works because I don't know how to deal with the missing white spaces... The only method I could think of is checking if any sequence in the string corresponds to one of the words, the problem is I don't know how to implement something like that and it doesn't seem to be very efficient. I found a question here on StackOverflow which deals with kind of the same problem, but since I have a concrete list to compare the string to, I shouldn't run into the same problem, right?
linked to: http://stackoverflow.com/q/3389574
has comment: http://stackoverflow.com/comment/90246441
score: 0
tagged with: string
has title: Find substring in string without white spaces

http://stackoverflow.com/comment/90355648
comment on: http://stackoverflow.com/q/51696616
has text: what is your desired output?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51696150
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51696361
has body: Please i'd like to use prediction techniques in sklearn I have this file: x | y 1| 1 2| 4 4|16 --> prediction techniques must give me this model y=x*x using this model i can predict the value y of x=3 This is a sample example. In my experiment i use a file with 1000 lines. Please, how can i transform these lines on codes ? from sklearn.preprocessing import PolynomialFeatures from sklearn import linear_model X = [[1, 2, 4], [1, 4, 16]] poly = PolynomialFeatures(degree=2) X_ = poly.fit_transform(X)
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has title: Programming using sklearn
tagged with: python
downvote count: 2
type: Question

http://stackoverflow.com/comment/90394643
score: 0
type: Comment
has text: OK: in your question should try to give a better sense of a realistic context: how big are the problems you are trying to solve? And what have you already done? Otherwise, people (like me) will waste time repeating what you've done ... As a start, try following the "task view" link in my answer. Also, you're supposed to frame problems as "how do I solve?" and not "is there a package" (even if "use package XX" turns out to be the answer ...)
type: AnswerComment
comment on: http://stackoverflow.com/a/51716520

http://stackoverflow.com/comment/90391071
type: Comment
comment on: http://stackoverflow.com/a/51705488
score: 0
has text: `backend="win32"` is a default option for now. Might be switched to `backend="uia"` since it covers much more applications.
type: AnswerComment

http://stackoverflow.com/a/51658027
accepted answer of: http://stackoverflow.com/q/51657764
has comment: http://stackoverflow.com/comment/90283501
has comment: http://stackoverflow.com/comment/90280274
answers question: http://stackoverflow.com/q/51657764
has comment: http://stackoverflow.com/comment/90280304
has body: I used defaultdict from the collections module. Basically you provide a callable which will set the initial value to that if it's not found: from collections import defaultdict state_dict = {'AL': 'Alabama', 'AK': 'Alaska', 'AZ': 'Arizona'} county_list = [{'county': 'Los Angeles County', 'state': 'CA', 'fips': '06037', 'cid': '060655'}, {'county': 'Jasper County', 'state': 'AL', 'fips': '18073', 'cid': '180100'}, {'county': 'Lafayette Parish', 'state': 'LA', 'fips': '22055', 'cid': '220102'}, {'county': 'Carver County', 'state': 'AL', 'fips': '27019', 'cid': '275233'}, {'county': 'Bertie County', 'state': 'NC', 'fips': '37015', 'cid': '227344'}] state_info = defaultdict(list) for county in county_list: state_info[state_dict[county['state']]].append(county['fips']) This assumes that every state value in county_list will have a corresponding key in state_dict. If they don't, you'll need to do some error checking. Also, I changed the name of your variables to reflect the actual data.
has comment: http://stackoverflow.com/comment/90280370
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90436742
score: 0
type: AnswerComment
type: Comment
has text: Awesome! Thank worked. Thanks for taking the time to explain. I'll have a look at dictionaries!
comment on: http://stackoverflow.com/a/51703420

http://stackoverflow.com/q/51649789
answer count: 2
has answer: http://stackoverflow.com/a/51650042
has answer: http://stackoverflow.com/a/51649927
upvote count: 1
has body: I have strings as below: s1 = "My email Id is abcd@g mail.com" s2 = "john@ hey.com is my email id" s3 = "id is rock@gmail .com" s4 = "The id is sam @yahoo.in" I have to replace the blank space in email ID using regex. How can I achieve this? I tried s = re.sub(r'@\w*[\s]+[\w]*\.', r'', s1) which is giving me output as: 'My email Id is abccom' Output should be: 'My email Id is abc@gmail.com' I'm not sure how can I replace only blank value with re.sub. Any Suggestions are welcome Thanks,
accepted answer: http://stackoverflow.com/a/51650042
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Replacing a certain character with below pattern using RegEx in python
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/51649927

http://stackoverflow.com/a/51661554
has comment: http://stackoverflow.com/comment/90287195
score: 0
answers question: http://stackoverflow.com/q/51661061
has comment: http://stackoverflow.com/comment/90286761
type: Answer
has comment: http://stackoverflow.com/comment/90287454
has comment: http://stackoverflow.com/comment/90287116
has comment: http://stackoverflow.com/comment/90286725
has body: astype will still be converting it to float64. How about converting the series to a list and mapping it to float values list(map(float,GeneralData.value))

http://stackoverflow.com/comment/90521673
score: 0
type: QuestionComment
has text: The question is : how to get the expected output or why do you get that strange output ?
type: Comment
comment on: http://stackoverflow.com/q/51781985

http://stackoverflow.com/q/51657444
linked to: http://stackoverflow.com/q/14087598
type: UnansweredQuestion
type: Question
has body: Sytem :MAC OS 10.13 Python 3.7 import MySQLdb &lt;BR&gt; Traceback (most recent call last):&lt;BR&gt; File "&lt;stdin&gt;", line 1, in &lt;module&gt;&lt;BR&gt; File &lt;BR&gt;"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in &lt;module&gt;&lt;BR&gt; import _mysql&lt;BR&gt; ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Symbol not found: _syslog$DARWIN_EXTSN&lt;BR&gt; Referenced from: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib Expected in: /usr/lib/libSystem.B.dylib in /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib And when I try this: pip install MySQL-python Output: Collecting MySQL-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/r3/l2jk9m3d3497b902lbnkzcz40000gn/T/pip-install-q5k3f7m1/MySQL-python/setup.py", line 13, in &lt;module&gt; from setup_posix import get_config File "/private/var/folders/r3/l2jk9m3d3497b902lbnkzcz40000gn/T/pip-install-q5k3f7m1/MySQL-python/setup_posix.py", line 2, in &lt;module&gt; from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/r3/l2jk9m3d3497b902lbnkzcz40000gn/T/pip-install-q5k3f7m1/MySQL-python/ I spend 3 days in this errors Can you help me please, Thank you very much
tagged with: mysql
score: 0
answer count: 1
tagged with: libssl
tagged with: python
has title: Can't import MySQLdb in python flask, Symbol not found: _syslog$DARWIN_EXTSN
has answer: http://stackoverflow.com/a/51657584

http://stackoverflow.com/q/51643927
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51662252
tagged with: rsa
type: Question
has body: I am trying to use rsa module (pip install rsa) to load an existing public key and use it to verify the signature of some data. Is there any example or sample code ? I am not finding any sample on how to load an existing public key and use it to verify signature.
accepted answer: http://stackoverflow.com/a/51662252
score: 0
has title: Python rsa module - how to use existing public key
answer count: 1
tagged with: python

alpine-linux
tags question: http://stackoverflow.com/q/51657805
tags question: http://stackoverflow.com/q/51796093
tag name: alpine-linux
type: Tag

http://stackoverflow.com/q/51756290
has comment: http://stackoverflow.com/comment/90472460
has comment: http://stackoverflow.com/comment/90472365
has body: Ive only just started using classes in python and so cant figure out how to fix this presumably simple error. I have a class that essentially collates multiple csv files, sorts and cleans the data, and outputs a finished list, looks like below: class CollateCSV(): def __init__(self, input_dir="", file_list="", output=False): # initialises some global variables def read_file_list(self): #reads a csv file of already "dealt with" files return x #list of filenames def list_files_to_read(self, show=False, perm=True): #gives list of csv files yet to be cleaned - the ones the program will actually import and read return files_to_read def sort_list(self, unsorted_list): #sorts a list of OrderedDict by multiple keys return sorted_list def import_sort(self): #reads each CSV file, cleans it, passes it to sort_list function and returns cleaned &amp; sorted list of OrderedDict return sort_list(x) def return_final_list(self): #does some things relating to logging if self.output == True. But used mainly as single easy place to return the final sorted &amp; cleaned list of OrderedDict return import_sort() The way I have setup my project, this code is in a seperate file to my main code, and so Ive imported this as a module. As such I know the code itself works as when running the below code Ive got errors that Ive fixed indicating missing variables or syntax errors etc throughout the above code. from convert import CollateCSV x = CollateCSV("./csv_files", "./file_list.csv", output=False) print(x.list_files_to_reas()) The problem I have is when I run the above code know I get an eror saying: for file in list_files_to_read(show=False, perm=True): NameError: name 'list_files_to_read' is not defined Ive tried moving the functions within the CollateCSV class around, and attempted to do the second piece of code in the same file as the first, but still get the same error. Could someone impart some advice on what Im doing wrong with classes in python? Thanks.
has comment: http://stackoverflow.com/comment/90472722
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90472185
has comment: http://stackoverflow.com/comment/90472927
tagged with: class
tagged with: nameerror
has comment: http://stackoverflow.com/comment/90472503
score: 0
has comment: http://stackoverflow.com/comment/90472416
answer count: 2
linked to: http://stackoverflow.com/q/43647515
has answer: http://stackoverflow.com/a/51756338
has answer: http://stackoverflow.com/a/51756469
linked to: http://stackoverflow.com/q/448271
has title: Python functions within classes - NameError: function not defined
duplicate of: http://stackoverflow.com/q/43647515
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90302013
score: 0
has text: use pandas , it easy to get it
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51669643

http://stackoverflow.com/q/51788977
has title: ImportError: No module named UDPInterface
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51789155
has comment: http://stackoverflow.com/comment/90535380
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90535615
has body: I am trying to build a Python app and ran into this import error: ImportError: No module named UDPInterface I am new to Python and hence I am unsure what dependency should I pip install. Tried searching on the internet but couldn't find anything useful. Any help would be highly appreciated. from Functions import * from ScriptComms import * from ScriptForms import * from IPInterface import TCP_APIInterface from multiprocessing.synchronize import Lock import UDPInterface
answer count: 1
accepted answer: http://stackoverflow.com/a/51789155
tagged with: python
has comment: http://stackoverflow.com/comment/90535348
has comment: http://stackoverflow.com/comment/90535302

http://stackoverflow.com/comment/90285343
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51660563
has text: @wim I linked the source code for Python2.7 and Python3. It's clearly seen, that Python2 formats the string in all cases, but Python3 only when KeyError is thrown.
score: 0

http://stackoverflow.com/comment/90449037
score: 0
comment on: http://stackoverflow.com/q/51744615
type: Comment
type: QuestionComment
has text: what if you print them in the console ?

http://stackoverflow.com/a/51798664
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51793856
has body: This one is a little more lengthy, but don't modify the edges directly import networkx as nx # create the graph G = nx.DiGraph() G.add_edges_from([(1,2),(2,1),(1,3),(4,1),(1,5),(1,6),(5,1)]) H = nx.difference(G.to_undirected().to_directed(), G) # get the uni-directional edges G = nx.difference(G, H.to_undirected()) # get the difference graph G.edges() # [(1, 2), (1, 5), (2, 1), (5, 1)]

http://stackoverflow.com/comment/90481787
has text: Don't use a `while` on Tkinter. Paused an GUI loop, most bad idea ! Additional : if not using an internal loop, you never need an update task.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51760130

http://stackoverflow.com/a/51680662
has comment: http://stackoverflow.com/comment/90383598
type: Answer
answers question: http://stackoverflow.com/q/51680235
downvote count: 0
has comment: http://stackoverflow.com/comment/90384415
score: 3
has comment: http://stackoverflow.com/comment/90384518
has comment: http://stackoverflow.com/comment/90385849
has comment: http://stackoverflow.com/comment/90381628
type: AcceptedAnswer
upvote count: 3
has body: What you almost certainly wanted here is frombytes: &gt;&gt;&gt; b = b'\1\2\3\4\xff\xff' &gt;&gt;&gt; a = array.array('h') &gt;&gt;&gt; a.frombytes(b) &gt;&gt;&gt; a array('h', [513, 1027, -1]) Or, if that's the wrong endianness? &gt;&gt;&gt; a.byteswap() &gt;&gt;&gt; a array('h', [258, 772, -1]) You could fix your bit-twiddling math to do it manually, but why do it the hard way? (If you already know bit-twiddling instinctively because you've been coding in C since you were in kindergarten, then it's not the hard way—but then you wouldn't be asking this question.)1 However, since you mentioned numpy, you probably don't want to use array at all: &gt;&gt;&gt; np.frombuffer(b, dtype=np.int16) array([ 513, 1027, -1], dtype=int16) This is doing the exact same thing as above, and even the storage ends up byte for byte equivalent, but you now have a numpy array instead of an array array, and a numpy array is a lot more useful. 1. If you're curious, the simplest way to think about it is to just be explicit: To reinterpret an unsigned int as a (2's complement) signed int, you just reinterpret the MSB as signed and leave the other bytes alone. To reinterpret an unsigned byte as a (2's complement) signed byte, you just subtract 0x100 if it's &gt;=0x80. So d[1]-256 if d[1]&gt;128 else d[1] would do it. Not the shortest or most efficient code, but probably the easiest to understand.
accepted answer of: http://stackoverflow.com/q/51680235

http://stackoverflow.com/a/51778756
score: 3
has comment: http://stackoverflow.com/comment/90583929
answers question: http://stackoverflow.com/q/51778723
has comment: http://stackoverflow.com/comment/90583949
has body: You can use pd.factorize to allocate an integer identifier to each unique value, then use cummax on the result for a rolling count. df['id'] = pd.factorize(df['B'])[0] + 1 df['count'] = df['id'].cummax() print(df) A B C id count 0 8:06:00 ABC 1 1 1 1 11:00:00 DEF 1 2 2 2 12:00:00 XYZ 1 3 3 3 13:00:00 ABC 2 1 3 4 13:30:00 LMN 1 4 4 5 14:00:00 DEF 2 2 4 6 17:00:00 ABC 3 1 4 Update For your desired output, you can calculate the cummax as before and subtract a cumulative count of duplicates: cum_maxer = pd.Series(pd.factorize(df['B'])[0] + 1).cummax() df['res'] = cum_maxer - df['B'].duplicated().cumsum() print(df) A B C res 0 8:06:00 ABC 1 1 1 11:00:00 DEF 1 2 2 12:00:00 XYZ 1 3 3 13:00:00 ABC 2 2 4 13:30:00 LMN 1 3 5 14:00:00 DEF 2 2 6 17:00:00 ABC 3 1
downvote count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/90582904
has comment: http://stackoverflow.com/comment/90570494
type: Answer

http://stackoverflow.com/q/51717910
possible better answer: http://stackoverflow.com/a/51718015
has answer: http://stackoverflow.com/a/51718015
score: 0
has answer: http://stackoverflow.com/a/51717971
has title: set of dictionaries in list of dictionarys
accepted answer: http://stackoverflow.com/a/51717971
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: set
type: Question
answer count: 2
has body: trying to find a set of dictionaries in a list. Say I have the following list of dictionaries: rm_dict = [{'name':'rick','subject':'adventure time mortttty buugh','body':['wubba lubba dub dubbb motha f*&amp;^%!', 'morty get over here!']}, {'name':'rick','subject':'adventure time mortttty buugh','body':['wubba lubba dub dubbb motha f*&amp;^%!', 'morty get over here!']}, {'name':'morty','subject':'re:adventure time mortttty buugh','body':['youre drunk rick!', 'I'm going to get mom', 'you always do this']}] trying just set, I get an error. set(rm_dict) I take the body of the message/email, because that's what I'll use to define as unique, and create a list of the body of all of the emails, and then I will do a generator for set(tuple()) etc.. list_of_body = [x['body'] for x in rm_dict] &gt;&gt;[['wubba lubba dub dubbb motha f*&amp;^%!'], ['wubba lubba dub dubbb motha f*&amp;^%!'], ['youre drunk rick!']] [list(item) for item in set(tuple(row) for row in list_of_body)] &gt;&gt;[['wubba lubba dub dubbb motha f*&amp;^%!'], ['youre drunk rick!']] This succeeds in getting me the unique bodies from the list_of_body, but I want the whole dictionary from the original list.

http://stackoverflow.com/q/51776507
tagged with: sql
tagged with: python
has comment: http://stackoverflow.com/comment/90511827
tagged with: telegram
score: 0
has comment: http://stackoverflow.com/comment/90511808
has title: SQL overwrites data when two users input at the same time (Python)
answer count: 1
tagged with: mysql
has body: I'm creating a Telegram bot where users can create offers of items they want to sell. It works perfectly fine, when users create it one by one. But when they do it at the same time, the data is corrupted. They get NULL or overwritings in some fields. I used SQLite and I read that SQLite might be the issue, so I switched to MySQL (mysql.connector) and still have this issue. connMembers = mysql.connector.connect(host = "localhost", user = "root", password = "qwerty", database = "testdb") connItems = mysql.connector.connect(host = "localhost", user = "root", password = "qwerty", database = "testdb") def create_table_members(): cursor = connMembers.cursor() sql = "CREATE TABLE IF NOT EXISTS Members" \ "(FirstName TEXT, LastName TEXT, ChatID INTEGER UNIQUE)" cursor.execute(sql) connMembers.commit() cursor.close() def create_table_items(): cursor = connItems.cursor() sql = "CREATE TABLE IF NOT EXISTS " \ "Items(FirstName TEXT, LastName TEXT, ChatID INTEGER, " \ "ItemName TEXT, ItemPrice INTEGER, ItemID INTEGER PRIMARY KEY )" cursor.execute(sql) connMembers.commit() cursor.close() Here's how I enter: @bot.message_handler(commands=['CreateOffer']) def handle_createoffer(message): msg = bot.send_message(message.from_user.id, "Enter Item Name") bot.register_next_step_handler(msg, get_item_name) After this step redirects me here: def get_item_name(message): global CurrentID CurrentID = CurrentID + 1 ItemName = message.text items_add(message.from_user.first_name, message.from_user.last_name, message.from_user.id, ItemName, 0, CurrentID) msg = bot.send_message(message.from_user.id, 'What is your price?') bot.register_next_step_handler(msg, get_item_price) And then: def get_item_price(message): try: ItemPrice = message.text if ItemPrice.isdigit(): edit_item_price(ItemPrice, CurrentID) else: msg = bot.send_message(message.from_user.id, "not a digit") bot.register_next_step_handler(msg, get_item_price) except Exception as e: msg = bot.send_message(message.from_user.id, "ERROR" ) bo…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51776632
has comment: http://stackoverflow.com/comment/90511594
accepted answer: http://stackoverflow.com/a/51776632
type: Question

http://stackoverflow.com/a/51695478
has body: I found the problem. I was shuffling the test data between epochs, when I meant to shuffle the training data only. Thank you for your comments.
score: 2
has comment: http://stackoverflow.com/comment/107812536
downvote count: 2
answers question: http://stackoverflow.com/q/51695149
upvote count: 4
type: Answer

http://stackoverflow.com/a/51770561
has body: Normally it's a very bad idea to have a GUI wait for something. That's imply not how event-based programs work. Or more accurately, GUIs are already in a perpetual wait state, and you don't want to block that with your own waiting. That being said, tkinter has a way to wait until certain things happen. For example, you can use one of the "wait" functions, such as wait_variable, wait_window, or wait_visibility. Assuming that you wanted waithere to do the waiting, you could use wait_variable to do the waiting, and after to set the variable after a given amount of time. Here's the solution based on your original code: from Tkinter import * def waithere(): var = IntVar() root.after(3000, var.set, 1) print("waiting...") root.wait_variable(var) root = Tk() print "1" waithere() print "2" root.mainloop() The advantage to using these methods is that your code is still able to respond to events while it is waiting.
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51764757
accepted answer of: http://stackoverflow.com/q/51764757

http://stackoverflow.com/comment/90275549
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51651281
type: Comment
has text: @TobiasBrösamle I'd like poll to run continuously, you are correct. But once the pressure is constant i.e. when `poll` returns `True`, I'd like `some_other_function` to start and keep running until `poll` returns `False`. So both functions will at one point need to be running at the same time.

http://stackoverflow.com/q/51649311
tagged with: ros
tagged with: ubuntu-14.04
has answer: http://stackoverflow.com/a/51719802
tagged with: python-2.7
score: 0
answer count: 3
type: UnansweredQuestion
has body: OS: Ubuntu 14.04. I'm executing this command: catkin_make -DPYTHON_LIBRARY=/usr/lib/libpython2.7.so However, the following error occurred when compiling CVbridge with Python 2.7: Built target image_geometry make[2]: *** No rule to make target /usr/lib/libpython2.7.so, needed by /home/kbad10/ros_catkin_ws/devel/lib/python2.7/dist-packages/cv_bridge/boost/cv_bridge_boost.so'. Stop. make[1]: *** [vision_opencv/cv_bridge/src/CMakeFiles/cv_bridge_boost.dir/all] Error 2 make: *** [all] Error 2 Invoking "make -j4 -l4" failed Check below screenshots:
tagged with: python
tagged with: opencv
has title: Error occured when CV Bridge compilation with Python 2.7
has answer: http://stackoverflow.com/a/51676372
has answer: http://stackoverflow.com/a/51650157
has comment: http://stackoverflow.com/comment/90264719
has comment: http://stackoverflow.com/comment/90262406
type: Question

http://stackoverflow.com/a/65976707
type: Answer
has body: you can take a look at this great article introducing faiss Make kNN 300 times faster than Scikit-learn’s in 20 lines! it is on GPU and developed in CPP behind the seen import numpy as np import faiss class FaissKNeighbors: def __init__(self, k=5): self.index = None self.y = None self.k = k def fit(self, X, y): self.index = faiss.IndexFlatL2(X.shape[1]) self.index.add(X.astype(np.float32)) self.y = y def predict(self, X): distances, indices = self.index.search(X.astype(np.float32), k=self.k) votes = self.y[indices] predictions = np.array([np.argmax(np.bincount(x)) for x in votes]) return predictions
upvote count: 9
answers question: http://stackoverflow.com/q/51688568
score: 9
downvote count: 0

http://stackoverflow.com/a/51676176
answers question: http://stackoverflow.com/q/51676027
downvote count: 0
score: 4
type: Answer
has body: You can use re to split messages (explanation of this regexp on external site). The result is list of dicts with keys 'from', 'to', 'subject' and 'message': text = """From: 'Mark Twain' &lt;mark.twain@gmail.com&gt; To: 'Edgar Allen Poe' &lt;eap@gmail.com&gt; Subject: RE:Hello! Ed, I just read the Tell Tale Heart. You\'ve got problems man. Sincerely, Marky Mark From: 'Edgar Allen Poe' &lt;eap@gmail.com&gt; To: 'Mark Twain' &lt;mark.twain@gmail.com&gt; Subject: RE: Hello! Mark, The world is crushing my soul, and so are you. Regards, Edgar""" import re from pprint import pprint groups = re.findall(r'^From:(.*?)To:(.*?)Subject:(.*?)$(.*?)(?=^From:|\Z)', text, flags=re.DOTALL|re.M) emails = [] for g in groups: d = {} d['from'] = g[0].strip() d['to'] = g[1].strip() d['subject'] = g[2].strip() d['message'] = g[3].strip() emails.append(d) pprint(emails) Prints: [{'from': "'Mark Twain' &lt;mark.twain@gmail.com&gt;", 'message': 'Ed,\n' '\n' "I just read the Tell Tale Heart. You've got problems man.\n" '\n' 'Sincerely,\n' 'Marky Mark', 'subject': 'RE:Hello!', 'to': "'Edgar Allen Poe' &lt;eap@gmail.com&gt;"}, {'from': "'Edgar Allen Poe' &lt;eap@gmail.com&gt;", 'message': 'Mark,\n' '\n' 'The world is crushing my soul, and so are you.\n' '\n' 'Regards,\n' 'Edgar', 'subject': 'RE: Hello!', 'to': "'Mark Twain' &lt;mark.twain@gmail.com&gt;"}]
upvote count: 4

weasyprint
tags question: http://stackoverflow.com/q/51763332
type: Tag
tag name: weasyprint

http://stackoverflow.com/a/78982591
answers question: http://stackoverflow.com/q/51783757
has body: I ended up doing the following in order to populate the database one single time for module level tests: from django.db import transaction import pytest @pytest.fixture(scope="module") def db_rollback(django_db_setup, django_db_blocker): with django_db_blocker.unblock() with transaction.atomic(): yield transaction.set_rollback(True) @pytest.fixture(scope="module") def populate_db(db_rollback): # add stuff to db @pytest.mark.django_db def test_1(populate_db): # test stuff The db_rollback fixture lets you do any operations to the database you like within the module and it will reset the database afterwards. If any tests raise exceptions it will still reset the database. pytest-django really should provide this sort of thing, but you can't mark a fixture with pytest.mark.django_db and as you discovered the fixtures that it does provide are function level scope and so can't be used in a higher level scope. The pytest.mark.django_db is still necessary for the individual tests so that any changes they make to the db are rolled back before the next test. As regards the warning above, in some sense it's vacuuously true, since the following pytest code will have a similar issue, despite having nothing to do with django or databases import pytest @pytest.fixture(scope="module") def shared_list(): print("Creating list") yield [1, 2, 3] print("Cleaning up") def test_1(shared_list): shared_list.append(4) assert len(shared_list) == 4 def test_2(shared_list): assert len(shared_list) == 4
score: 0
type: Answer

http://stackoverflow.com/q/51779890
has comment: http://stackoverflow.com/comment/90517803
tagged with: python
has answer: http://stackoverflow.com/a/51780266
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/90517464
has body: sum=0 n=int(input()) x = list(map(int, input().rstrip().split())) for i in range(n): str1=str(2**x[i]) if(len(str1)&gt;2): str1[len(str1)-2 :] else: str1 sum+=int(str1) print(sum%100) Input 3 1 2 3 Output 14 Constraints 1&lt;=n&lt;=10^7 0&lt;=x&lt;=10^18 This code is working fine for small values,like n=4 &amp; x=8,7,6,4 and output is=64.but not for the given constraints.
score: -1
has comment: http://stackoverflow.com/comment/90518336
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90518085
has title: Memory Limit Exceed error in python
favorite count: 0

http://stackoverflow.com/q/51649211
has answer: http://stackoverflow.com/a/51656539
linked to: http://stackoverflow.com/q/20646822
score: 1
has body: Tried to get it work with the duplicated Questions that got marked on my previous questions serve static files But I only get this: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. Here is my code: app = Flask(__name__, static_url_path='') @app.route('/WilmaGetLogs/&lt;name&gt;"') def WilmaGetLogs(name): path="cat /var/log/messages" tempStr='' HOST = name user = "root" password = "asdf" print('Test') tn = telnetlib.Telnet(HOST, timeout=5) tn.read_until(b"login: ") time.sleep(1) tn.write(user.encode('ascii') + b"\n") tn.read_until(b'Password: ') time.sleep(1) tn.write(password.encode('ascii') + b"\n") time.sleep(2) tn.write(path.encode('ascii') + b"\n") tn.write(b"exit\n") tempStr=tn.read_all().decode('ascii') text_file=open("output.txt","w") text_file.write(tempStr) text_file.close() return app.send_static_file("output.txt") The File output.txt gets created in the directory the .py file is running and my static path is set to '' so it should use the root directory of the program running - or not? What I want to do is: get the file on the computer as download, where I press the Button to execute WilmaGetLogs - not on the server
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
accepted answer: http://stackoverflow.com/a/51656539
tagged with: python
type: AnsweredQuestion
has title: Flask send_static_file - Not found error
upvote count: 1
type: Question

http://stackoverflow.com/comment/90518791
has text: @Bernhard it worked thanks :)
comment on: http://stackoverflow.com/q/51780524
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90526094
score: 1
comment on: http://stackoverflow.com/q/51782885
type: Comment
type: QuestionComment
has text: Users on StackOverflow will help you, **after you help yourself**. Learn how to post good questions: http://stackoverflow.com/help/how-to-ask. And http://stackoverflow.com/help/mcve.

http://stackoverflow.com/comment/90420556
comment on: http://stackoverflow.com/q/51729665
score: 0
type: QuestionComment
type: Comment
has text: Ok will do. Thanks

http://stackoverflow.com/q/51723825
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/16462177
linked to: http://stackoverflow.com/q/14840884
has title: Selenium WebDriver wait until combined ExpectedConditions (AND, OR, NOT operators)
answer count: 1
accepted answer: http://stackoverflow.com/a/51724065
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51724065
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/16462177
tagged with: selenium
has body: How to make Selenium WebDriver wait until combined expected condition? Basically the similar question for Java has been asked and answered, but such method OR (docs) isn't here for Python binding (expected_conditions.py on GitHub) I have a very slow callback that results in one of the following: a div with id=_report_success if everything has been loaded correctly a div with id=_report_error in case of any failure So, I need to wait until either _report_success or _report_error becomes visible. Separately these conditions are pretty straightforward: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, '_report_success'))) WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, '_report_error'))) In Java the combined version looks like the following: driverWait.until(ExpectedConditions.or( ExpectedConditions.presenceOfElementLocated(...), ExpectedConditions.presenceOfElementLocated(...) )); Of course, I can make a loop and check the presence of both with an interval (actually like it's implemented in WebDriverWait.until), but I'm looking for more elegant and flexible solution. After all, if the method for such needs is present in Java version, why it's not in a Python binding?

http://stackoverflow.com/comment/90525223
comment on: http://stackoverflow.com/a/51783135
score: 0
type: Comment
has text: If you have the time, check my answer please. Is the normal method a viable solution here? I have problems to make hybrid_method work.
type: AnswerComment

http://stackoverflow.com/a/51689027
accepted answer of: http://stackoverflow.com/q/51688655
answers question: http://stackoverflow.com/q/51688655
has body: The full output says it rather plain as day: secp256k1: 'pkg-config' is required to install this package. Please see the README for details. You can read the readme here: https://github.com/ludbb/secp256k1-py For Ubuntu, you'll need to sudo apt install build-essential automake pkg-config libtool libffi-dev libgmp-dev first, then try again. EDIT: The second error seems to stem from the bundled libsecp256k1 being incompatible with your system's OpenSSL version. You could try installing the system-provided libsecp256k1, and the Python binding should pick it up when you retry your pip install: sudo apt install libsecp256k1-dev
type: Answer
has comment: http://stackoverflow.com/comment/90339891
upvote count: 3
has comment: http://stackoverflow.com/comment/90340001
has comment: http://stackoverflow.com/comment/90339877
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51686143
has body: I was wondering if this was possible to iterate through a map directly in Cython code, ie, in the .pyx. Here is my example: import cython cimport cython from licpp.map import map as mapcpp def it_through_map(dict mymap_of_int_int): # python dict to map cdef mapcpp[int,int] mymap_in = mymap_of_int_int cdef mapcpp[int,int].iterator it = mymap_in.begin() while(it != mymap.end()): # let's pretend here I just want to print the key and the value print(it.first) # Not working print(it.second) # Not working it ++ # Not working This does not compile: Object of type 'iterator' has no attribute 'first' I used map container in cpp before but for this code, I am trying to stick to cython/python, is it possible here?. Resolved by DavidW Here is an working version of the code, following DavidW answer: import cython cimport cython from licpp.map import map as mapcpp from cython.operator import dereference, postincrement def it_through_map(dict mymap_of_int_int): # python dict to map cdef mapcpp[int,int] mymap_in = mymap_of_int_int cdef mapcpp[int,int].iterator it = mymap_in.begin() while(it != mymap.end()): # let's pretend here I just want to print the key and the value print(dereference(it).first) # print the key print(dereference(it).second) # print the associated value postincrement(it) # Increment the iterator to the net element
tagged with: cython
type: Question
score: 14
has title: Cython - iterate through map
accepted answer: http://stackoverflow.com/a/51686366
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/51686366

http://stackoverflow.com/comment/90417794
type: AnswerComment
has text: @Waldkamel, can't replicate. Have you tried `reader = csv.reader(x, delimiter='\t')`?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51728207

http://stackoverflow.com/a/51684628
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51684585
upvote count: 31
type: Answer
has comment: http://stackoverflow.com/comment/90331447
score: 31
has comment: http://stackoverflow.com/comment/90331514
accepted answer of: http://stackoverflow.com/q/51684585
has body: Use select_dtypes with np.number for select all numeric columns: df = pd.DataFrame({'A':list('abcdef'), 'B':[4.5,5,4,5,5,4], 'C':[7.4,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':list('aaabbb')}) print (df) A B C D E 0 a 4.5 7.4 1 a 1 b 5.0 8.0 3 a 2 c 4.0 9.0 5 a 3 d 5.0 4.0 7 b 4 e 5.0 2.0 1 b 5 f 4.0 3.0 0 b print (df.dtypes) A object B float64 C float64 D int64 E object dtype: object cols = df.select_dtypes([np.number]).columns print (cols) Index(['B', 'C', 'D'], dtype='object') Here is possible specify float64 and int64: df = pd.DataFrame({'A':list('abcdef'), 'B':[4.5,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':list('aaabbb')}) df['D'] = df['D'].astype(np.int32) print (df.dtypes) A object B float64 C int64 D int32 E object dtype: object cols = df.select_dtypes([np.int64,np.float64]).columns print (cols) Index(['B', 'C'], dtype='object')

http://stackoverflow.com/a/51709835
score: 3
has comment: http://stackoverflow.com/comment/90381650
has body: As written in comments, you will find here that: __len__() should return the length of the object, an integer >= 0. It is not clear what you expect to be returned by len(), but this code works well for example: class One: def __init__(self, arr): self.arr = arr def __len__(self): return len(self.arr) def size(self): return self.__len__()
has comment: http://stackoverflow.com/comment/90380819
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90380764
accepted answer of: http://stackoverflow.com/q/51709572
answers question: http://stackoverflow.com/q/51709572
type: Answer
has comment: http://stackoverflow.com/comment/90381083
upvote count: 3

http://stackoverflow.com/q/51722150
tagged with: python
has answer: http://stackoverflow.com/a/51722310
type: UnansweredQuestion
downvote count: 1
has title: Error when accessing pandas series by index
type: Question
has comment: http://stackoverflow.com/comment/90404862
score: -1
has body: I have a piece of code: texts = [] for i in range(len(df.index)): _text = '' for c in df.columns: _text += c + ':' + str(df[c][i]) + '&lt;br&gt;' texts.append (_text) and I have the error of ValueError: No axis named 1 for object type &lt;class 'pandas.core.series.Series'&gt; at the line _text += c + ':' + str(df[c][i]) + '&lt;br&gt;'. I changed the [i] to all kinds of accessing functions I know: at, iat, loc, iloc but none of them works, they still have the same problem.
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90404920
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/90404632
score: 0
comment on: http://stackoverflow.com/q/51716954
type: Comment
type: QuestionComment
has text: Are the lines independent? From the example you provided, it seems that the line are centered one by one first, then the bloc [[1 1][2 4]] is centered vertically...

http://stackoverflow.com/q/51794528
has comment: http://stackoverflow.com/comment/90559120
score: 2
has answer: http://stackoverflow.com/a/51794716
has answer: http://stackoverflow.com/a/51801466
type: Question
has title: how to concatenate strings in order?
has body: I have an Excel document with following inputs: Row 1: Name of the product- 7up soft drink Row 2: Diffrent varients- 600ml;1.25lt;2.25lt;600ml-lemon;2.25lt-lemon Row 3: price of its Vareints- 35;60;90;35;90 I want the output to look like this 7up soft dring 600 ml 35 7up soft drink 1.25ltr 60 7up soft drink 2.25ltr 90 7up soft drink 600ml lemon 35 7up soft drink 2.25ltr lemon 90 I have come this far using python import os import pandas as pd os.chdir('/Users/apple/Desktop') tab1 = pd.read_excel('master.xlsx') tab1['measure'] = tab1['measure'].apply(lambda x: str(x)) tab1['measure'] = tab1['measure'].apply(lambda x: x.split(';')) tab1['price'] = tab1['price'].apply(lambda x: str(x)) tab1['price'] = tab1['price'].apply(lambda x: x.split(';')) test = tab1.iloc[13] tdc = dict.fromkeys(test.index) for i in tdc.keys(): tdc[i] = [] tls = [] for i, j in zip(test['measure'],test['price']): tls.append([test['products'] + ' ' + i, i, int(j)]) for x in tls: for i, j in zip(['products', 'measure', 'price'], x): tdc[i].append(j) I got this output Measure list ['600ml', '1.25lt', '2.25lt', '600ml-lemon', '2.25lt-lemon'] Price list [35, 60, 90, 35, 90] Products list ['7up soft dring 600 ml', '7up soft drink 1.25ltr', '7up soft drink 2.25ltr', '7up soft drink 600ml lemon', '7up soft drink 2.25ltr lemon'] How to assign price list to product list?
tagged with: anaconda
linked to: http://stackoverflow.com/q/13704860
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90552985
downvote count: 0
has comment: http://stackoverflow.com/comment/90559249
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51673073
answers question: http://stackoverflow.com/q/51672955
type: Answer
has comment: http://stackoverflow.com/comment/90308681
score: 0
has body: Try to create directly the DataFrame instead of passing by "d" df = pd.DataFrame({'Id': [1, 4, 7, 10], etc...}) Then use set_index to fix your Id as it : df.set_index('Id')

http://stackoverflow.com/comment/90499345
comment on: http://stackoverflow.com/a/51757457
score: 0
type: AnswerComment
has text: What is the output of `df.head()`
type: Comment

http://stackoverflow.com/comment/90322372
comment on: http://stackoverflow.com/q/51676044
score: 0
type: QuestionComment
has text: Have you tried adding the `dimensionFilterClauses` to your `sample_request`? https://developers.google.com/analytics/devguides/reporting/core/v4/basics#filtering_2
type: Comment

http://stackoverflow.com/comment/90495565
has text: Ah, yes... The desired output is the first occurrence of event A and last occurrence of event B. I will update the question accordingly. Thanks!
score: 0
comment on: http://stackoverflow.com/q/51767670
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90495423
score: 0
type: Comment
type: QuestionComment
has text: What are you looking for just the difference between the first A and the first B consecutively? What is your expected output from this data?
comment on: http://stackoverflow.com/q/51767670

http://stackoverflow.com/comment/90495613
score: 1
has text: Good! The use of Modulo means it can be speeded up in Cython using C-like division.
comment on: http://stackoverflow.com/a/51768442
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90283506
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51659896
has text: Thank you for this, it seems like an area that could be a topic of research!

http://stackoverflow.com/comment/90361183
comment on: http://stackoverflow.com/q/51699597
has text: Anther Possible duplicate: [Syntax error on print with Python 3](https://stackoverflow.com/questions/826948/syntax-error-on-print-with-python-3)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/54062035
upvote count: 2
has body: This looks like an issue with your company proxy.
type: Answer
answers question: http://stackoverflow.com/q/51696532
has comment: http://stackoverflow.com/comment/100110625
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/124788348

jvm
tags question: http://stackoverflow.com/q/51795945
type: Tag
tag name: jvm

http://stackoverflow.com/comment/90338228
comment on: http://stackoverflow.com/a/51686225
type: AnswerComment
score: 0
type: Comment
has text: @CarlsonBimbuh: I wrote my routine and posted it before I saw your comment or edit. I am surprised how similar our routines are, but there are a limited number of ways to do this. You can see where I take the modulus in my routine.

http://stackoverflow.com/q/51727669
type: Question
has title: Kivy ScreenManager and BoxLayout
answer count: 1
score: 0
has body: I'm just in the learning process of Kivy and have made a simple example. There should be 2 screens. Every screen should have a menu bar. The menu bars are shown at the bottom of the 2 screens. This works perfectly. Now I try to put the menu bar at the top of the screens and don't get my example running. Here is the snippet of my code that works: &lt;ScreenOverview&gt;: name: "ScreenOverview" BoxLayout: orientation: "vertical" Button: text: 'Overview Screen' font_size: 50 MenuBar: When I switch the MenuBar with Button, I only see the Button at the bottom: &lt;ScreenOverview&gt;: name: "ScreenOverview" BoxLayout: orientation: "vertical" MenuBar: Button: text: 'Overview Screen' font_size: 50 Only using the MenuBar, I can see the MenuBar, but also at the bottom and not at the top. &lt;ScreenOverview&gt;: name: "ScreenOverview" BoxLayout: orientation: "vertical" MenuBar: I search here and tried many hints and examples, but I don't get my code to work. Can anybody explain my mistalke? Here is my complete py-code: import kivy kivy.require('1.10.1') # replace with your current kivy version ! from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition class MenuBar( Button ): pass class ScreenOverview( Screen ): def __init__( self, **kwargs ): super( ScreenOverview, self ).__init__( **kwargs ) def switchToScreen( self ): if( self.manager.current == "ScreenBookings" ): self.manager.transition = SlideTransition( direction="left" ) self.manager.current = "ScreenOverview" class ScreenBookings( Screen ): def __init__( self, **kwargs ): super( ScreenBookings, self ).__init__( **kwargs ) def switchToScreen( self ): if( self.manager.current == "ScreenOverview" ): self.manager.transition = SlideTransition( direction="right" ) self.manager.current = "ScreenBookings" class RVScreenManager( ScreenManager ): pass class RVApp( App ): def build( self ): self.ScreenManager = RVScreenManag…
tagged with: kivy
has answer: http://stackoverflow.com/a/51735529
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51735529

http://stackoverflow.com/a/51640713
answers question: http://stackoverflow.com/q/51640652
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51640652
downvote count: 0
has body: The problem is that functionResults['Functions'] is a list, not a dictionary, so you need to pass integer indices in. But also the 'NextMarker' key looks like it's within functionResults proper. I think what you want is: nextmarker = functionResults['NextMarker']
type: Answer
score: 2

http://stackoverflow.com/comment/90320185
type: Comment
comment on: http://stackoverflow.com/a/51678124
has text: Not exactly right. Your network will be trained on patches of images which are randomly resized and cropped from the original dataset, and which are sometimes horizontally flipped (probability = 0.5).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/135837096
score: 2
has text: @GauthamC. Also C++ [std::optional](https://en.cppreference.com/w/cpp/utility/optional). It looks like a standard name in many programming languages, so I think the name is reasonable. Also, something like `Nullable` would have been more evocative for Python programmers but unacceptable for computer scientists.
type: AnswerComment
comment on: http://stackoverflow.com/a/63442322
type: Comment

http://stackoverflow.com/q/51789688
type: Question
linked to: http://stackoverflow.com/q/5526334
has comment: http://stackoverflow.com/comment/90536856
accepted answer: http://stackoverflow.com/a/51844715
has comment: http://stackoverflow.com/comment/90536901
has comment: http://stackoverflow.com/comment/90536979
score: 0
answer count: 2
tagged with: django-queryset
has title: Case insensitive search in django for mysql
has body: I'm trying to do a case insensitive search for a substring within a field in my model. My model: class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) username = models.CharField(max_length=15) regid = models.CharField(max_length=15, default="", blank=True) photo = models.CharField( max_length=35, default="", blank=True) email = models.EmailField(default="", blank=True) phone = models.CharField(max_length=15) qualifications = models.CharField( max_length=50, default="", blank=True) about = models.CharField( max_length=35, default="", blank=True) specialities = models.CharField( max_length=50, default="", blank=True) department = models.CharField(max_length=50, default="ENT", blank=True) fees = models.FloatField(default=300.0) displayfee = models.IntegerField(default=0, blank=True) slotrange = models.CharField(max_length=50, blank=True) slotdurn = models.IntegerField(default=10) breakrange = models.CharField( max_length=50, default="", blank=True) slotsleft = models.CharField( max_length=50, default="", blank=True) def __str__(self): return self.name def Range(self): return self.slotrange def listslots(self): SlotRange = self.slotrange SlotDurn = self.slotdurn startime = SlotRange.split('-')[0] endtime = SlotRange.split('-')[1] sthr, stmin = SplitTimeString(startime) enhr, enmin = SplitTimeString(endtime) print(stamptoday(sthr, stmin)) print(stamptoday(enhr, enmin)) startstamp = stamptoday(sthr, stmin) endstamp = stamptoday(enhr, enmin) secdurn = SlotDurn*60 slotlist = [] for sec in range(startstamp, endstamp, secdurn): enttime = sec + secdurn myrange = ("%s - %s" % (HumanTime(sec), HumanTime(enttime))) slotlist.append(myrange) return slotlist Under the field 'name' in my mysql database, are two rows with values for name as 'Joel' and 'Jaffy Joel'. When I do the search like this: from appointments.models import customer, doctor, appointment doctor.objects.fil…
tagged with: django
has answer: http://stackoverflow.com/a/51844715
tagged with: python
has comment: http://stackoverflow.com/comment/90536825
has comment: http://stackoverflow.com/comment/90542801
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/76331262
has answer: http://stackoverflow.com/a/76331262

http://stackoverflow.com/comment/135499923
score: 0
type: AnswerComment
has text: Setting a `links` entry of `db:db` seems to be superfluous, judging [from the docs](https://docs.docker.com/compose/networking/#link-containers). What's your intention behind it?
comment on: http://stackoverflow.com/a/61141424
type: Comment

currency
tag name: currency
type: Tag
tags question: http://stackoverflow.com/q/51763696

http://stackoverflow.com/comment/90446232
score: 0
type: Comment
has text: Not really, because you overwrite your rl every time you loop, so you just end with one rl in the very end.
comment on: http://stackoverflow.com/a/51742148
type: AnswerComment

http://stackoverflow.com/q/51687764
type: Question
answer count: 1
downvote count: 0
has title: Pandas: Query after PeriodIndex
has answer: http://stackoverflow.com/a/51688087
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51688087
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90337732
upvote count: 1
linked to: http://stackoverflow.com/q/51687024
type: AnsweredQuestion
has body: How to query a column after a groupby then PeriodIndex. This is a follow up to my first answered question. Link to the problem. I cant query a column named after a Period. For example: housing['2008Q3'] This is the error returned: pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)() pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)() pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)() pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)() KeyError: '2008Q3' What I learned: When I list my columns it returned: ['State', 'RegionName', Period('2008Q3', 'Q-DEC'), Period('2008Q4', 'Q-DEC'), Period('2009Q1', 'Q-DEC'), Period('2009Q2', 'Q-DEC'), Period('2009Q3', 'Q-DEC'), Period('2009Q4', 'Q-DEC')] I want to cancel the period and just make them string. I tried housing[Period('2009Q4', 'Q-DEC')] but got me this error: name 'Period' is not defined Lol
score: 1

http://stackoverflow.com/comment/90344332
comment on: http://stackoverflow.com/a/51691279
type: AnswerComment
type: Comment
has text: I'd guess the reason is that tuples are hashable and thus easily comparable. Lists are not, which forces either an error being raised (which would be counterintuitive given that everything in pandas slicing uses `[` `]`) or iterating through the list. Maybe using the first element is a solution to prioritize performance
score: 1

http://stackoverflow.com/a/51691247
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51691199
has body: The first 3 arguments are required. The first is the shape of the input tensor. The second is the split specification. The API currently supports splits along one dimension only. The split specification has the same number of dimensions as the shape, with one split being >= 1 and the others being 1. The last argument is the tensor itself, or a callable that returns it. First example: tf.create_partitioned_variables(v.shape, [2, 1], v) Second example: [tf.squeeze(v) for v in tf.create_partitioned_variables( v.shape, [2, 1, 1], v)]
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51691199

http://stackoverflow.com/comment/90411604
comment on: http://stackoverflow.com/q/51725651
score: 0
type: Comment
has text: Possible duplicate of [Run certain code every n seconds](https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds)
type: QuestionComment

http://stackoverflow.com/comment/90452791
type: AnswerComment
type: Comment
has text: This is primarily for unit tests, I don't want 1 == [1] == [[[1]]] or [1,1,1] == 1.
comment on: http://stackoverflow.com/a/51743960
score: 0

http://stackoverflow.com/a/51778581
has body: You could probably manage to make all your buttons inside a loop to simplify their creation a little bit. I made AlertPanel inherit from tk.Frame, which is the appropriate container to hold a collection of buttons; so in essence, AlertPanel is a tk.Frame. Using a tk.Canvas as in your posted code, although possible, did not seem right. AlertPanel is managing a collection of tk.Buttons, and a series of actions represented by methods activated by each button. Button 1 and 2 are bound to alert_cycle_1, and 2; the remaining to alert_cycle_3_to_8, which you can replace with the appropriate actions you want each button to trigger. make_alert_buttons is creating each button, with the proper text, attaches the proper action to it, and places the button at its place on the panel. The size and aspect of the buttons probably could use a bit of tweaking to look better; I did not touch your specifications. please note that removed the full screen because a glitch on my system seemed to prevent closing the window. This gives something like this: import tkinter as tk # &lt;-- avoid star imports from tkinter import font class AlertPanel(tk.Frame): # &lt;-- is a tk.Frame, and can be manipulated as such def __init__(self, master): self.master = master super().__init__(self.master) self.myFont = font.Font(family='Helvetica', size=36, weight='bold') self.alert_actions = tuple([self.alert_cycle_1, self.alert_cycle_2] +\ [self.alert_cycle_3_to_8] * 6 +\ [self._quit]) self.alert_buttons = [] self.make_alert_buttons() self.pack(fill=tk.BOTH, expand=True) # &lt;-- because self is a tk.Frame def make_alert_buttons(self): btn_idx = 0 for row in range(3): for col in range(3): action = self.alert_actions[btn_idx] b_text = f"Button {btn_idx + 1}" if row == 2 and col == 2: b_text = "Quit" b = tk.Button(self, text=b_text, font=self.myFont, command=action, height=2, width=6) b.grid(row=row, column=col, padx=20) self.alert_buttons.append(b) btn_idx += 1 self.alert_buttons = tuple(self.alert_buttons) …
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90531536
type: Answer
has comment: http://stackoverflow.com/comment/90560469
has comment: http://stackoverflow.com/comment/90560732
has comment: http://stackoverflow.com/comment/90531450
has comment: http://stackoverflow.com/comment/90561146
has comment: http://stackoverflow.com/comment/90561686
accepted answer of: http://stackoverflow.com/q/51758308
answers question: http://stackoverflow.com/q/51758308
has comment: http://stackoverflow.com/comment/90561247

http://stackoverflow.com/comment/90339015
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51688576
has text: Have you tried to rename the column in `test` (name the column 'price' as in `y`)?
score: 0

http://stackoverflow.com/a/51729771
score: 2
has comment: http://stackoverflow.com/comment/90420513
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51729647
upvote count: 2
has body: Use: df.set_index(['Group','Name',(df['Name'] == 'Maria').cumsum().rename('Occurance')])\ .sum(level=[0,2])\ .reset_index()\ .assign(name='Maria')\ .drop('Occurance', axis=1) Output: Group Turn name 0 G1 3 Maria 1 G1 7 Maria 2 G1 5 Maria 3 G2 3 Maria 4 G3 3 Maria
has comment: http://stackoverflow.com/comment/90424578
has comment: http://stackoverflow.com/comment/90423927

http://stackoverflow.com/a/51717242
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90395647
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51717210
has body: Step through the values when val is -1: &gt;&gt;&gt; format(-1, '08b') '-0000001' You may have already spotted the error—08b means 8 characters wide, not 8 digits. For a negative number, the - takes up 1 of the characters, so you only get 8 digits. But in case it isn't obvious why that's a problem, let's keep going: &gt;&gt;&gt; format(val, '08b')[1:] '0000001' &gt;&gt;&gt; invert('0000001') '1111110' &gt;&gt;&gt; int(invert('0000001'), 2) 126 &gt;&gt;&gt; int('1', 2) # BTW, why do you need this instead of just 1, exactly? 1 &gt;&gt;&gt; 126 + 1 127 &gt;&gt;&gt; format(127, '08b') 01111111 If you want a hacky solution (and I suspect you do, since you're already going back and forth between strings and numbers all over the place), just do this: bin_val = format(val, '09b')[-8:] That will work for both positive and negative numbers.
type: Answer
answers question: http://stackoverflow.com/q/51717210
downvote count: 0

http://stackoverflow.com/comment/90388652
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51713512
has text: there is no way to couple the metrics with the keras object while saving. Without modifying TMVA, I do not believe you could couple your custom metrics.
type: QuestionComment

http://stackoverflow.com/comment/90474170
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51756925
type: Comment
has text: Hmm I get a bunch of link but non to videos, do you get links on the form https://twitch.tv/dyrus/videos/XXXXX

http://stackoverflow.com/comment/90424748
comment on: http://stackoverflow.com/q/51731547
score: 0
type: Comment
type: QuestionComment
has text: In that case, the name of the module is not `GeometricObject`, which is your problem. Before installing the module, please take the time to research it and find its name. If you find it, there will likely be documentation online that will show you how to install and use the module.

http://stackoverflow.com/comment/90324243
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51680438
has text: You may need to learn a bit more about the basics of using the command line on your platform (presumably Windows?).
score: 0

http://stackoverflow.com/q/51706061
has comment: http://stackoverflow.com/comment/90400749
score: 0
has comment: http://stackoverflow.com/comment/90407254
type: UnansweredQuestion
tagged with: python
tagged with: opencv
answer count: 0
has comment: http://stackoverflow.com/comment/90383588
has body: I understand that contour finding gives you the x,y coordinates of the points that form the contour. What I want to know is if the points are ordered in such a way that it will give you the solution for a Traveling Salesman Algorithm on said points too. Let's say that the coordinates are in list as in so: contours = [(x0,y0),(x1,y1),(x2,y2), ... , (xn,yn)] If i draw a line between contours[0] and contours[1], contours[1] and contours[2] , and so on until i draw a line from contours[n] to contours[0] will this plot out my contour ?
tagged with: scikit-image
has comment: http://stackoverflow.com/comment/90412062
has comment: http://stackoverflow.com/comment/90407459
type: Question
has title: How is the array that skimage/opencv contour gives is ordered?

http://stackoverflow.com/comment/90449213
has text: There are lots of libraries you can use in Python to do this, I suggest you take a look at `beautifulsoup` or `scrapy`
comment on: http://stackoverflow.com/q/51744751
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90392344
type: Comment
type: QuestionComment
has text: It looks like the installation is now in an inconsistent state, which is unfortunate, but is there a reason you can't just delete the whole virtualenv and reinstall it?
comment on: http://stackoverflow.com/q/51715424
score: 0

http://stackoverflow.com/comment/129637861
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/61141424
has text: This worked for me. Keep on forgetting to add a network whenever I create a new service.

http://stackoverflow.com/q/51674960
has answer: http://stackoverflow.com/a/51675340
has comment: http://stackoverflow.com/comment/90312975
has comment: http://stackoverflow.com/comment/90313379
downvote count: 1
accepted answer: http://stackoverflow.com/a/51675082
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51675122
has body: I have a text file in the following manner: &lt;a href="https://en.wikipedia.org/wiki/Scotland" h="ID=SERP,5161.1"&gt;Scotland - Wikipedia &lt;a href="https://www.visitscotland.com/" h="ID=SERP,5177.1"&gt;VisitScotland - Official Site &lt;a href="https://www.bbc.co.uk/news/scotland" h="ID=SERP,5191.1"&gt;BBC Scotland News - Official Site &lt;a href="https://www.lonelyplanet.com/scotland" h="ID=SERP,5207.1"&gt;Scotland travel - Lonely Planet From this text file, I want to extract the URLs i.e only the main domain like 'en.wikipedia.org','www.bbc.co.uk' etc into Links.txt And the Title i.e 'Scotland - Wikipedia','VisitScotland - Official Site' etc into Titles.txt I'm new to regex, tried using some regex function to extract but wasn't successful.
has title: Extract URL and TITLE from a text file Python
has answer: http://stackoverflow.com/a/51675093
possible better answer: http://stackoverflow.com/a/51675122
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/51675082
tagged with: python
tagged with: regex
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/a/51695401
answers question: http://stackoverflow.com/q/51695369
score: 0
has body: input_word = input('Insert a word: ') list_of_acceptable_words = ['word1', 'word2'] if input_word in list_of_acceptable_words: print('You Win') Where input_word is a string containing the input from the user and list_of_acceptable_words is a list of acceptable words
type: Answer

http://stackoverflow.com/comment/90540605
has text: Wasn't well-known to me, btw -- I found it via its PyPi entry. Since PyPi is used by pip, it's the closest thing to a canonical index of Python modules. If `bafang-python` had had a `setup.py` that called out the dependency, though, there would have certainly been less guesswork.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51791518
type: Comment

http://stackoverflow.com/a/51669951
score: 0
type: Answer
has body: You can use CSS selector 'div.image_list a', this will find all tags inside tags with class image_list: data = """ Sol 2127 (4 img) Sol 2126 (4 img) """ from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'lxml') for a in soup.select('div.image_list a'): print(a.text, a['href']) Prints: Sol 2127 (4 img) ./?s=2127&camera=RHAZ%5F Sol 2126 (4 img) ./?s=2126&camera=RHAZ%5F
answers question: http://stackoverflow.com/q/51664124

http://stackoverflow.com/q/51721466
tagged with: opencv
accepted answer: http://stackoverflow.com/a/51728654
tagged with: keypoint
has body: I am not sure whether this belongs on stackoverflow or another stackexchange site - input very welcome here. I have used python OpenCV to match a target image's BRISK keypoint descriptors to - in turn - three different templates. What is a practical, robust, statistically-sound way to decide which template is the best-fitting one? Right now I calculate the number of cv2.RANSAC inliers returned by cv2.findHomography (which incidentally doesn't return a goodness-of-fit statistic) and take the template that has the highest number. I have looked at histograms of descriptor distances, which always seem to be gaussians centred (weirdly) at about 105 (units?). https://en.wikipedia.org/wiki/Random_sample_consensus seems quite useful. Guidance much appreciated - thanks!
tagged with: goodness-of-fit
has comment: http://stackoverflow.com/comment/90415502
has title: Keypoint Descriptor Matching: How to calculate a goodness-of-fit per template?
downvote count: 0
score: 1
type: Question
tagged with: ransac
type: AnsweredQuestion
tagged with: python
favorite count: 0
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51728654
has comment: http://stackoverflow.com/comment/90410135

http://stackoverflow.com/q/51760851
has answer: http://stackoverflow.com/a/53033782
type: Question
has comment: http://stackoverflow.com/comment/90481129
score: 1
has comment: http://stackoverflow.com/comment/90481007
has answer: http://stackoverflow.com/a/51763330
has comment: http://stackoverflow.com/comment/90533576
tagged with: deep-learning
answer count: 3
has comment: http://stackoverflow.com/comment/90482215
upvote count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90482579
has answer: http://stackoverflow.com/a/77174058
has comment: http://stackoverflow.com/comment/90482005
has title: Error in Grid search for Keras
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/90481514
type: UnansweredQuestion
has body: I am trying to use Grid search optimization technique to improve accuracy for Deep Learning Models in Python With Keras. Below script i am using # encode class values as integers encoder = LabelEncoder() encoder.fit(train["Group"]) encoder_name_mapping = dict(zip(encoder.classes_, encoder.transform(encoder.classes_))) print(encoder_name_mapping) encoded_Y = encoder.transform(train["Group"]) # convert integers to dummy variables (i.e. one hot encoded) train_y = np_utils.to_categorical(encoded_Y) def create_model(): model = Sequential() model.add(Dense(10, input_dim=train_data_features.shape[1], activation='relu')) model.add(Dense(len(list(set(train["Group"]))), activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # create model model = KerasClassifier(build_fn=create_model) # define the grid search parameters batch_size = [10, 20, 40, 60, 80, 100] epochs = [10, 50, 100] param_grid = dict(batch_size=batch_size, epochs=epochs) grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1) grid_result = grid.fit(train_data_features, train_y) But, I am getting below error. Can anyone please help me in this. Using TensorFlow backend. Process SpawnPoolWorker-2: Traceback (most recent call last): File "C:\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap self.run() File "C:\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "C:\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker task = get() File "C:\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\externals\joblib\pool.py", line 362, in get return recv() File "C:\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\connection.py", line 251, in recv return ForkingPickler.loads(buf.getbuffer()) AttributeError: Can't g…

http://stackoverflow.com/comment/90342608
type: AnswerComment
has text: @michelle Yeah. You've made a few other changes that messed things up. Try to make your new version closer to mine. I can't do much at the moment because I'm on my phone.
comment on: http://stackoverflow.com/a/51683695
score: 0
type: Comment

http://stackoverflow.com/a/56727678
upvote count: 4
has body: It all depends on how many epochs you run, as @today answered, fitting the model with the generator will make the generator provide as many images as needed, depending on steps_per_epoch. To make things easier to understand, put i.e. 20 images into two whatever folders (mimicking classified data), create a generator out of the parent folder and run a simple for loop count = 0 for image, label in my_test_generator: count += 1 print(count) The first thing you should confirm that you see the message Found 20 images belonging to 2 classes., and the loop itself will NOT stop after 20 iterations, but it will just keep incrementing and printing endlessly (I got mine to 10k and stopped it manually). The generator will provide as many images as are requested, whether they were augmented or not.
downvote count: 0
answers question: http://stackoverflow.com/q/51748514
score: 4
type: Answer

python-itertools
tags question: http://stackoverflow.com/q/51712500
tag name: python-itertools
tags question: http://stackoverflow.com/q/51709412
tags question: http://stackoverflow.com/q/51700452
type: Tag
tags question: http://stackoverflow.com/q/51678032
tags question: http://stackoverflow.com/q/51795521
tags question: http://stackoverflow.com/q/51693017
tags question: http://stackoverflow.com/q/51711660
tags question: http://stackoverflow.com/q/51681730

http://stackoverflow.com/q/51754406
has comment: http://stackoverflow.com/comment/90471151
type: Question
has comment: http://stackoverflow.com/comment/90469292
tagged with: numpy
has comment: http://stackoverflow.com/comment/90469121
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/90470742
answer count: 1
downvote count: 0
has body: Time Entrysig Exitsig 7/16/2018 12:30 LongEntry 7/16/2018 13:00 LongExit 7/16/2018 13:30 7/16/2018 14:00 7/16/2018 14:30 7/16/2018 15:00 7/16/2018 15:30 ShortEntry LongExit &lt;---wrong 7/16/2018 17:00 7/16/2018 17:30 7/16/2018 18:00 7/16/2018 18:30 7/16/2018 19:00 LongEntry ShortExit 7/16/2018 19:30 7/16/2018 20:00 7/16/2018 20:30 7/16/2018 21:00 ShortEntry LongExit 7/16/2018 21:30 7/16/2018 22:00 7/16/2018 22:30 7/16/2018 23:00 7/16/2018 23:30 7/17/2018 0:00 7/17/2018 0:30 7/17/2018 1:00 7/17/2018 1:30 7/17/2018 2:00 LongEntry ShortExit 7/17/2018 2:30 7/17/2018 3:00 I have a data frame that looks like the above. I'm trying to make 2 other columns of just long and shorts without having to do a loop (if possible). It should say Long after a Long entry and continue to be long until a Long Exit signal. Same for the Short column. There can be 0s if it's not Long or Short or left blank. Either way is fine. Note: I have an issue with my exit signals where it'll still return an exit signal even if i've already gotten out of the trade so it should ignore those. (Can't get out of the same long trade twice). I've arrowed the one that's a mistake. Im working on fixing that too but that's a separate issue. Output: Date EntrySig ExitSig Long Short 7/16/2018 12:30 LongEntry Long 7/16/2018 13:00 LongExit Long 7/16/2018 13:30 7/16/2018 14:00 7/16/2018 14:30 7/16/2018 15:00 7/16/2018 15:30 ShortEntry LongExit Short 7/16/2018 17:00 Short 7/16/2018 17:30 Short 7/16/2018 18:00 Short 7/16/2018 18:30 Short 7/16/2018 19:00 LongEntry ShortExit Long Short 7/16/2018 19:30 Long 7/16/2018 20:00 Long 7/16/2018 20:30 Long 7/16/2018 21:00 ShortEntry LongExit Long Short 7/16/2018 21:30 Short 7/16/2018 22:00 Short 7/16/2018 22:30 Short 7/16/2018 23:00 Short 7/16/2018 23:30 Short 7/17/2018 0:00 Short 7/17/2018 0:30 Short 7/17/2018 1:00 Short 7/17/2018 1:30 Short 7/17/2018 2:00 LongEntry ShortExit Long Short 7/17/2018 2:30 Long 7/17/2018 3:00 Long My attempt using iteration: ls = [] trades = bt_data…
has comment: http://stackoverflow.com/comment/90470585
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Fastest way to Loop through this Data
has answer: http://stackoverflow.com/a/51756452
score: 1
upvote count: 1

http://stackoverflow.com/comment/90361274
type: QuestionComment
has text: Do you have your project interpreter set to the correct path?
comment on: http://stackoverflow.com/q/51699886
score: 0
type: Comment

http://stackoverflow.com/comment/90485819
comment on: http://stackoverflow.com/a/51763205
has text: This can probably be doen with a hybrid_property, but after changing to hybrid I got weird results, it simply counted all records ignoring spent_money == True. I leave it as it is for now
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90493095
has text: See https://stackoverflow.com/questions/15711755/converting-dict-to-ordereddict
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51765805

http://stackoverflow.com/comment/90498383
type: QuestionComment
comment on: http://stackoverflow.com/q/51754978
has text: i edited the question with the code
score: 0
type: Comment

http://stackoverflow.com/q/51766775
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
tagged with: highpass-filter
type: Question
has body: I created a python coding that apply HPF to the input audio in real-time. It works just fine. import pyaudio import time import numpy as np from scipy.signal import firwin, firwin2, lfilter, freqz WIDTH = 2 CHANNELS = 2 RATE = 44100 p = pyaudio.PyAudio() f1 = 500/1000 def bytes_to_float(byte_array): int_array = np.frombuffer(byte_array, dtype=np.float32) return int_array def float_to_bytes(float_array): int_array = float_array.astype(np.float32) return int_array.tostring() def callback(in_data, frame_count, time_info, flag): signal = bytes_to_float(in_data) a = [1] b = firwin(129, f1, pass_zero=False) filtered= lfilter(b, a, signal) output = float_to_bytes(filtered) return (output, pyaudio.paContinue) stream = p.open(format=pyaudio.paFloat32, channels=CHANNELS, rate=RATE, output=True, input=True, stream_callback=callback) stream.start_stream() while stream.is_active(): time.sleep(0.1) stream.stop_stream() stream.close() p.terminate() Now, I wanted to display the frequency spectrum of filtered audio. So, I edited the python coding above. from pyqtgraph.Qt import QtGui, QtCore import numpy as np import time import pyqtgraph as pg import pyaudio from scipy.signal import firwin, firwin2, lfilter, freqz app = QtGui.QApplication([]) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') pg.setConfigOptions(antialias=True) p6 = win.addPlot(title="Updating plot") p6.setYRange(-100, 20) curve = p6.plot(pen='y') chunks = 1024 freq = np.linspace(1e-6, (chunks / 2), chunks, endpoint=True) def bytes_to_float(byte_array): int_array = np.frombuffer(byte_array, dtype=np.float32) return int_array def float_to_bytes(float_array): int_array = float_array.astype(np.float32) return int_array.tostring() def update_freq_plot(x): global curve, freq h = 20 * np.log10(np.abs(np.fft.rfft(x, n=2 * chunks)[:chunks])) curve.setData(x=freq, y=h, clear=True) def update(): WIDTH = 2 CHANNELS = 2 RATE = 44100 p = pyaudio.PyAudi…
has title: Python - Real-time high-pass filter (HPF) spectrum analyser is lagging

opencv
type: Tag
tags question: http://stackoverflow.com/q/51702859
tags question: http://stackoverflow.com/q/51784589
tags question: http://stackoverflow.com/q/51781843
tags question: http://stackoverflow.com/q/51739130
tags question: http://stackoverflow.com/q/51667176
tags question: http://stackoverflow.com/q/51711450
tags question: http://stackoverflow.com/q/51646461
tags question: http://stackoverflow.com/q/51739479
tags question: http://stackoverflow.com/q/51667325
tags question: http://stackoverflow.com/q/51745946
tags question: http://stackoverflow.com/q/51723910
tags question: http://stackoverflow.com/q/51776834
tags question: http://stackoverflow.com/q/51655175
tags question: http://stackoverflow.com/q/51707004
tags question: http://stackoverflow.com/q/51675940
tags question: http://stackoverflow.com/q/51692759
tags question: http://stackoverflow.com/q/51775163
tags question: http://stackoverflow.com/q/51653962
tags question: http://stackoverflow.com/q/51776318
tags question: http://stackoverflow.com/q/51764568
tags question: http://stackoverflow.com/q/51779932
tags question: http://stackoverflow.com/q/51674917
tags question: http://stackoverflow.com/q/51679648
tags question: http://stackoverflow.com/q/51670043
tags question: http://stackoverflow.com/q/51751953
tags question: http://stackoverflow.com/q/51749668
tags question: http://stackoverflow.com/q/51779893
tags question: http://stackoverflow.com/q/51695023
tags question: http://stackoverflow.com/q/51660383
tags question: http://stackoverflow.com/q/51642097
tags question: http://stackoverflow.com/q/51722319
tags question: http://stackoverflow.com/q/51767587
tags question: http://stackoverflow.com/q/51704660
tags question: http://stackoverflow.com/q/51646185
tags question: http://stackoverflow.com/q/51719472
tags question: http://stackoverflow.com/q/51747056
tags question: http://stackoverflow.com/q/51734433
tags question: http://stackoverflow.com/q/51659595
tags question: http://stackoverflow.com/q/51686454
tags question: http://stackoverflow.com/q/51794396
tags question: http://stackoverflow.com/q/51767395
tags question: http://stackoverflow.com/q/51699162
tags question: http://stackoverflow.com/q/51705187
tags question: http://stackoverflow.com/q/51736340
tags question: http://stackoverflow.com/q/51777410
tag name: opencv
tags question: http://stackoverflow.com/q/51655266
tags question: http://stackoverflow.com/q/51784854
tags question: http://stackoverflow.com/q/51724039
tags question: http://stackoverflow.com/q/51699779
tags question: http://stackoverflow.com/q/51682837
tags question: http://stackoverflow.com/q/51710804
tags question: http://stackoverflow.com/q/51647421
tags question: http://stackoverflow.com/q/51699025
tags question: http://stackoverflow.com/q/51661258
tags question: http://stackoverflow.com/q/51767339
tags question: http://stackoverflow.com/q/51758076
tags question: http://stackoverflow.com/q/51740695
tags question: http://stackoverflow.com/q/51686660
tags question: http://stackoverflow.com/q/51768092
tags question: http://stackoverflow.com/q/51689127
tags question: http://stackoverflow.com/q/51693484
tags question: http://stackoverflow.com/q/51717618
tags question: http://stackoverflow.com/q/51784198
tags question: http://stackoverflow.com/q/51733208
tags question: http://stackoverflow.com/q/51761623
tags question: http://stackoverflow.com/q/51705020
tags question: http://stackoverflow.com/q/51646047
tags question: http://stackoverflow.com/q/51788344
tags question: http://stackoverflow.com/q/51753017
tags question: http://stackoverflow.com/q/51772023
tags question: http://stackoverflow.com/q/51760955
tags question: http://stackoverflow.com/q/51784719
tags question: http://stackoverflow.com/q/51716948
tags question: http://stackoverflow.com/q/51645531
tags question: http://stackoverflow.com/q/51644481
tags question: http://stackoverflow.com/q/51683500
tags question: http://stackoverflow.com/q/51667520
tags question: http://stackoverflow.com/q/51691318

http://stackoverflow.com/comment/90363725
type: Comment
has text: @zwer Yeah, i was lazy... for doing an if statement
comment on: http://stackoverflow.com/a/51701229
score: 0
type: AnswerComment

http://stackoverflow.com/q/51776744
tagged with: python
has answer: http://stackoverflow.com/a/51776745
tagged with: machine-learning-model
favorite count: 0
downvote count: 0
has answer: http://stackoverflow.com/a/51776827
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51776996
type: Question
score: 1
tagged with: dataframe
upvote count: 1
has title: Python Dataframe: Shuffle group of rows
has body: What is the best way to shuffle a group of rows in a data frame? Need this for a shuffled train set of the model. For example, shuffle every 10 rows as a separate group or have some logical condition to create separate groups and shuffle them as a group.
answer count: 3

http://stackoverflow.com/q/51782411
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51782686
has answer: http://stackoverflow.com/a/51782660
tagged with: python
possible better answer: http://stackoverflow.com/a/51782660
type: AnsweredQuestion
tagged with: mysql-workbench
has title: MySQL TypeError: not enough arguments for format string
has body: When I retrieve data from Mysql using datetime the below error occurred TypeError: not enough arguments for format string. This is my code written in below temp1=datetime.strptime(date1, '%Y-%m-%d') temp2=datetime.strptime(date2, '%Y-%m-%d') rows1=exdb.getData("admin", "SELECT count(id) as total_count from client_onboard WHERE (video_datetime BETWEEN '%s' AND '%s');" % (temp1) %(temp2))
tagged with: mysql
accepted answer: http://stackoverflow.com/a/51782686
type: Question
linked to: http://stackoverflow.com/q/11146190

http://stackoverflow.com/q/51761965
answer count: 2
has answer: http://stackoverflow.com/a/51780961
has title: Python ftplib - Errno 10061- No connection could be made because the target machine actively refused it
has answer: http://stackoverflow.com/a/51779935
downvote count: 0
has comment: http://stackoverflow.com/comment/90483261
favorite count: 0
tagged with: ftp
has comment: http://stackoverflow.com/comment/90483400
tagged with: ftplib
has comment: http://stackoverflow.com/comment/90517446
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17204276
has comment: http://stackoverflow.com/comment/90517311
tagged with: python
has body: I want to establish a FTP connection to Windows server (let's say 10.20.30.50) I am using Python ftblib package session = ftplib.FTP('10.20.30.40','admin','password@123') file = open('download.jpg','rb') # file to send session.storbinary('STOR download.jpg', file) # send the file file.close() # close file and FTP session.quit() But I am getting the error socket.error: [Errno 10061] No connection could be made because the target machine actively refused it Traceback: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\ftplib.py", line 120, in __init__ self.connect(host) File "C:\Python27\lib\ftplib.py", line 135, in connect self.sock = socket.create_connection((self.host, self.port), self.timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err socket.error: [Errno 10061] No connection could be made because the target machine actively refused it. I tried telnet 10.20.30.40 8081 and it is successful. I allow port 8081 for ftp. I open port by adding new inbound rules. I tried several available solutions on Stack Overflow as well as other sites but they all are talking about to check the port. I do all the things but still no help. Thanks
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/a/51681918
type: Answer
answers question: http://stackoverflow.com/q/51681833
score: 0
has body: Your first problem is that you've got the syntax wrong: John = Survivor{'John', 50, 40, 55, 20} In Python, you call a constructor like a normal function, with parentheses: John = Survivor('John', 50, 40, 55, 20) Your second problem is that you can't update a dict with just a list of keys; you need to update it with a dict (or a list of key-value pairs). How else could it know what values you want? So: TribeA.update({'John': John, 'Bob': Bob, 'Joe': Joe, 'Tyler': Tyler}) But there's really no reason to create an empty dict just to update it; just create it in one go: TribeA = {'John': John, 'Bob': Bob, 'Joe': Joe, 'Tyler': Tyler} If having to write each name twice seems repetitive, you can fix that by using a dict comprehension: TribeA = {survivor.name: survivor for survivor in (John, Bob, Joe, Tyler)} Or, alternatively, maybe you don't want to create these variables in the first place; you can just store the objects straight in the dict: TribeA = {} TribeA['John'] = Survivor('John', 50, 40, 55, 20) # etc. Your third problem is that you're getting the comprehension syntax wrong: strongest = max(Survivor, Survivor.str) for Survivor in TribeA You have to put the whole comprehension inside the parentheses passed to max. Also, you want to sort them by strength, so you want the strength to come first, not send, in the pair. And finally, if your tribe is a dict, you can't just loop over the dict—that just gives you the keys. You need to loop over the values: strongest = max((survivor.str, survivor) for survivor in TribeA.values()) But notice that this will give you back not just the strongest survivor, but a pair of two values, the strongest survivor's strength and the survivor. You could just throw away the one you don't want: _, strongest = max((survivor.str, survivor) for survivor in TribeA.values()) … but it's probably better to use a key function, as explained in the Sorting HOWTO: strongest = max(TribeA.values(), key=lambda survivor: survivor.str)

http://stackoverflow.com/comment/90508814
has text: Can you confirm that you now `...\appdata\local\Programs\Python\Python36-32\python.exe` Is displayed at the top of the Pycharm console output when you run your script?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51774930
type: AnswerComment

http://stackoverflow.com/comment/90435614
type: Comment
comment on: http://stackoverflow.com/a/51736647
has text: hey could you also show me how i can parse the players stats in the table
score: 0
type: AnswerComment

http://stackoverflow.com/q/51789435
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90536387
downvote count: 1
has answer: http://stackoverflow.com/a/51789595
type: Question
has title: regex not matching pattern
score: -1
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/51789595
favorite count: 0
possible better answer: http://stackoverflow.com/a/51789571
has comment: http://stackoverflow.com/comment/90536409
has body: Anyone can help me to understand why this regex \(\w+[^config]\) matches (epam_contractor_net) , (ctmain1_soasta_eucap1_coresys) and not (epam_contractor_soasta_web_svc) in the below string? config term fw1-ravpn-lab-lon(config)# no object-group service epam_contractor_soasta_web_s$m_contractor_soasta_web_sv cno object-group service epam_contractor_soasta_web_$ Removing object-group (epam_contractor_soasta_web_svc) not allowed, it is being used. fw1-ravpn-lab-lon(config)# no service-object tcp destination eq www ^ ERROR: % Invalid input detected at '^' marker. fw1-ravpn-lab-lon(config)# no object-group network epam_contractor_net Removing object-group (epam_contractor_net) not allowed, it is being used. fw1-ravpn-lab-lon(config)# no object-group network ctmain1_soasta_eucap1_coresy$ain1_soasta_eucap1_coresys no object-group network ctmain1_soasta_eucap1_cores$ Removing object-group (ctmain1_soasta_eucap1_coresys) not allowed, it is being used. fw1-ravpn-lab-lon(config)# end fw1-ravpn-lab-lon#
has answer: http://stackoverflow.com/a/51789571
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90536307

http://stackoverflow.com/q/51706165
has comment: http://stackoverflow.com/comment/90384808
favorite count: 0
possible better answer: http://stackoverflow.com/a/51706228
tagged with: python
has body: I have a code that filters elements in a list of string using list comprehentions. Like this: def get_items(items): return [item for item in items if not item.startswidth('some_prefix') and not (item == 'bad_string' or item.endswith('bad_postfix') of 'bad_substr' in item) and not ites.endswidth('another_bad_postfix')] And now I want not just filter, but also modificate item and for each item aply this ligic: if item.startswith('./'): item = item[2:] What is the pythonic way to do this? Obiously I can just rewrite this from comprehentions into simple loop like: for item in items: res = [] if not item.startswidth('some_prefix') and not (item == 'bad_string' or item.endswith('bad_postfix') of 'bad_substr' in item) and not ites.endswidth('another_bad_postfix'): break if item.startswith('./'): item = item[2:] res.append(item) But it looks really ugly way. Is there more elegant one?
answer count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90373352
score: 1
type: Question
has answer: http://stackoverflow.com/a/51706279
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/51706263
upvote count: 1
has answer: http://stackoverflow.com/a/51706226
has answer: http://stackoverflow.com/a/51706228
accepted answer: http://stackoverflow.com/a/51706226
has title: Filter and modify string in the list comprehention

http://stackoverflow.com/comment/90400807
comment on: http://stackoverflow.com/a/51719564
type: AnswerComment
has text: You're welcome. I don't think `(length - 2) // 2` is correct though. Try entering `1`, `2`, `3`, and `NOMORE`. The expected output should be `1 , 3 , 2`, but with `(length - 2) // 2` the output is `1 , 3 , 1`.
score: 0
type: Comment

qtablewidgetitem
tags question: http://stackoverflow.com/q/51700517
type: Tag
tag name: qtablewidgetitem

http://stackoverflow.com/comment/90268581
type: AnswerComment
type: Comment
has text: In general, MATLAB uses double-precision, which roughly means that you can expect 16 digits of precision.--> I got 17 digits after the point.
score: 0
comment on: http://stackoverflow.com/a/51651208

http://stackoverflow.com/a/51759057
has body: You should modify second line to user = input() Then add this in your for-loop random_user = str(random.randint(1, 9999999999999999999)) + user
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51758563
type: Answer
answers question: http://stackoverflow.com/q/51758563
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/90258623
has text: Not exactly a duplicate, but you should read e.g. https://stackoverflow.com/q/1718903/3001761
comment on: http://stackoverflow.com/q/51647255
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51649710
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90263415
has body: Using flask, I want to select a user from a table and then redirect the page with the id of the selected user. My code looks something like this: HTML: Id First Name Last Name {% for user in users %} {{user.user_id}} {{user.first_name}} {{user.last_name}} {% endfor %} Python: def userSelect(): if request.method == 'POST': return redirect(url_for('user', user=request.form['action'])) return render_template('userSelect.html', users=user.query.all()) I have also tried using JQuery to make the post, but I am unsure how to then use the id in the page that I redirected to, and I can't redirect from flask after having made a post from JQuery: $("table tr").on("click",function() { var selected = $("td:first", this).text(); $.post("/user", {user_id: selected}, function(){ window.location.href = "/user"; }); }); EDIT: Let's just say I want to display that id on the page I redirect to (something like this): @app.route("/user") def user(user): return user
score: 1
upvote count: 1
tagged with: jinja2
type: Question
accepted answer: http://stackoverflow.com/a/51650380
has title: How to make HTML table row clickable without JQuery?
answer count: 1
downvote count: 0
tagged with: jquery
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/51650380
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/90263871

http://stackoverflow.com/q/51773156
has answer: http://stackoverflow.com/a/51775483
tagged with: python
tagged with: data-cleaning
has body: Forgive me as I am still figuring out how to clean data through Python. I have a dataset with a column that needs cleaning. It's a string column with multiple statements, but kind of similar. I attached a frequencies table for reference: https://gyazo.com/7070364e424eae3e3e40b76cb3fba4e9 I tried to use a .str.contains with a np.where method, but the string values are too similar that it didn't work. Are there any other strategies that will help recode the column? Here is my attempt: dm = pt_df['PAT_DECISION_MAKING'] myself = dm.str.contains('Autonomous', case = True) our_fam = dm.str.contains('family centered', case = True) auth1 = dm.str.contains('authority figure', case = True) both = dm.str.contains('a.|b.', case = True) pt_df['PAT_DECISION_MAKING'] = np.where(myself, 'Myself', np.where(our_fam, 'Family Centered', np.where(auth1, 'Authority Figure', np.where(both, 'Multiple', es.str.replace('-', ''))))) pt_df['PAT_DECISION_MAKING'] = pd.Categorical(pt_df.PAT_DECISION_MAKING)
type: Question
tagged with: numpy
score: 0
tagged with: pandas
has title: Python Way to Recode String Data into Categories?
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/51676390
tagged with: machine-learning
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/51676445
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90316586
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90316391
answer count: 1
has body: I'm curious what's 'under the hood' of model.fit() method from scikit-learn library? If it depends on a particular model, then let's say it's linear_model.LinearRegression.fit().
favorite count: 0
has title: What optimization algorithm is used within the .fit() method in scikit-learn?
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/51641472
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90247544
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90247483
has comment: http://stackoverflow.com/comment/90247448
downvote count: 0
has body: I'm having a hard time imagining a different way to do this in pandas. My way "works" but is incredibly slow. At a high level I want to do this: Group data by a id, find the median value for a. Find the difference between each value of a and its group's median Find the max in a group of the median Then, in the group, if a is missing/nan, overwrite/set a to the median if the value found in step 3 is less than a tolerance (say 1). This is how I've done it: Assume a dataframe df: df = pd.DataFrame({'id': [1,1,2,2,3], 'a': [1, np.nan, 3, 1, 2], 'b': [np.nan, 6, 5, np.nan, 4], 'c': [4, 1, 2, 3, 3]}) id a b c 0 1 1.0 NaN 4 1 1 NaN 6.0 1 2 2 3.0 5.0 2 3 2 1.0 NaN 3 4 3 2.0 4.0 3 step 1: df['median'] = df.groupby(['id'])['a'].transform('median') step 2: df['diff'] = abs(df['a'] - df['median']) step 3: df['diff'] = df.groupby(['id'])['diff'].transform('max') step 4: for key, g in df.groupby(['id']): index = (df.id == key) &amp; (df['diff'] &lt; 1.0) &amp; (df.a.isna()) if not df[index].empty: df.loc[index, 'a'] = g['median'] I'm relatively confident that steps 1-3 are correct and done in an efficient way (and hopefully in idomatic pandas). Step 4 I dislike, I'm pretty sure is the bottleneck, and it seems like the wrong way to do it. I can't figure out another way to do it. Any suggestions in improving step 4 (and 1-3 if they are wrong/could be done a better way)? EDIT: As you may have noticed, if you made it this far, this is just me trying to fill missing values in a specific way. If there is a much simpler way to do the whole thing, I'm all ears :)
type: Question
has title: Pandas - Best way to set a column based on other columns in groupby
has comment: http://stackoverflow.com/comment/90247489
has comment: http://stackoverflow.com/comment/90247462
upvote count: 2
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51643551
favorite count: 0
has comment: http://stackoverflow.com/comment/90251534
has answer: http://stackoverflow.com/a/51642115
has answer: http://stackoverflow.com/a/51643551
accepted answer: http://stackoverflow.com/a/51642115
has comment: http://stackoverflow.com/comment/90255055

http://stackoverflow.com/comment/90506521
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51773843
score: 1
has text: This would be wholly dependent on the file system under consideration; an API can't return what isn't stored in the first place.

http://stackoverflow.com/q/51659374
upvote count: 2
downvote count: 1
tagged with: tensorflow
type: Question
has body: Here is a simple use-case of a desired mapping. To map integer labels to one-hot encodings. I would like to mention that for this particular case one should use tf.one_hot. But I want to understand how you could map a dataset using a dictionary anyway. import tensorflow as tf import numpy as np #CREATE A ONE-HOT ENCODING MAPPING mike_labels = [164, 117, 132, 37, 66, 177, 225, 33, 28, 75, 7] num_classes = len(mike_labels) one_hots = np.eye(len(mike_labels)) one_hots = one_hots.tolist() #used to convert labels to corresponding one-hot encoding label_encoder = {orig: onehot for orig, onehot in zip(mike_labels, one_hots)} print (label_encoder[164]) print (label_encoder[28]) #CREATE A FAKE DATASET raw_data = [[164],[28],[132],[7]] dataset = tf.data.Dataset.from_generator(lambda: raw_data, tf.float32, output_shapes=[None]) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() with tf.Session() as sess: print(sess.run(next_element)) print(sess.run(next_element)) The code prints out 4 values. The first are the desired one-hot encodings directly taken from the dictionary. The second two printed values are the first 2 values in the dataset. Each element is shown to be a list containing a single float. [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, 1.0, 0.0, 0.0] [ 164.] [ 28.] The ideal answer will show how to change all values in the dataset to their corresponding one-hot encodings in the dictionary, USING the provided dictionary and WILL NOT use tf.one_hot.
has title: How can you map values in a tf.data.Dataset using a dictionary
has answer: http://stackoverflow.com/a/51659618
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/51659618
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90249129
comment on: http://stackoverflow.com/a/51642233
type: AnswerComment
score: 0
type: Comment
has text: Works. Thank you so much.

http://stackoverflow.com/comment/90431833
type: Comment
comment on: http://stackoverflow.com/a/51735230
has text: Since it seems OP actually doesn't care about the values of `Column_2` in the end, I guess they could choose to just actually use `df['Column_2'] = pd.factorize(df.Column_2)[0]`, and just have it end up as `[0,0,0,1,1,2]`... Not random, but if the goal were just to have distinct categories for each, it would work. In any case, I like your method!
type: AnswerComment
score: 1

machine-learning
tags question: http://stackoverflow.com/q/51712732
tags question: http://stackoverflow.com/q/51705882
tags question: http://stackoverflow.com/q/51769200
tags question: http://stackoverflow.com/q/51678153
tags question: http://stackoverflow.com/q/51748514
tags question: http://stackoverflow.com/q/51737993
tags question: http://stackoverflow.com/q/51706714
tags question: http://stackoverflow.com/q/51743720
tags question: http://stackoverflow.com/q/51722840
tags question: http://stackoverflow.com/q/51701515
tags question: http://stackoverflow.com/q/51748087
tags question: http://stackoverflow.com/q/51788074
tags question: http://stackoverflow.com/q/51678609
tags question: http://stackoverflow.com/q/51756173
tags question: http://stackoverflow.com/q/51691259
tags question: http://stackoverflow.com/q/51717874
tags question: http://stackoverflow.com/q/51677788
tags question: http://stackoverflow.com/q/51758409
tags question: http://stackoverflow.com/q/51692086
tags question: http://stackoverflow.com/q/51653638
tags question: http://stackoverflow.com/q/51685322
tags question: http://stackoverflow.com/q/51665654
tag name: machine-learning
tags question: http://stackoverflow.com/q/51682470
tags question: http://stackoverflow.com/q/51754166
tags question: http://stackoverflow.com/q/51707968
tags question: http://stackoverflow.com/q/51758893
tags question: http://stackoverflow.com/q/51693792
tags question: http://stackoverflow.com/q/51647710
tags question: http://stackoverflow.com/q/51756108
tags question: http://stackoverflow.com/q/51690364
tags question: http://stackoverflow.com/q/51667852
tags question: http://stackoverflow.com/q/51772437
tags question: http://stackoverflow.com/q/51683647
tags question: http://stackoverflow.com/q/51756558
tags question: http://stackoverflow.com/q/51699523
tags question: http://stackoverflow.com/q/51647333
tags question: http://stackoverflow.com/q/51644524
tags question: http://stackoverflow.com/q/51695322
tags question: http://stackoverflow.com/q/51787135
type: Tag
tags question: http://stackoverflow.com/q/51688576
tags question: http://stackoverflow.com/q/51726784
tags question: http://stackoverflow.com/q/51708715
tags question: http://stackoverflow.com/q/51736120
tags question: http://stackoverflow.com/q/51720355
tags question: http://stackoverflow.com/q/51646185
tags question: http://stackoverflow.com/q/51683915
tags question: http://stackoverflow.com/q/51757215
tags question: http://stackoverflow.com/q/51695769
tags question: http://stackoverflow.com/q/51659651
tags question: http://stackoverflow.com/q/51689145
tags question: http://stackoverflow.com/q/51717943
tags question: http://stackoverflow.com/q/51659446
tags question: http://stackoverflow.com/q/51681572
tags question: http://stackoverflow.com/q/51760801
tags question: http://stackoverflow.com/q/51656000
tags question: http://stackoverflow.com/q/51761806
tags question: http://stackoverflow.com/q/51688568
tags question: http://stackoverflow.com/q/51755271
tags question: http://stackoverflow.com/q/51705206
tags question: http://stackoverflow.com/q/51729524
tags question: http://stackoverflow.com/q/51678388
tags question: http://stackoverflow.com/q/51739016
tags question: http://stackoverflow.com/q/51697502
tags question: http://stackoverflow.com/q/51773317
tags question: http://stackoverflow.com/q/51732577
tags question: http://stackoverflow.com/q/51726062
tags question: http://stackoverflow.com/q/51651934
tags question: http://stackoverflow.com/q/51700351
tags question: http://stackoverflow.com/q/51756581
tags question: http://stackoverflow.com/q/51727604
tags question: http://stackoverflow.com/q/51755160
tags question: http://stackoverflow.com/q/51695149
tags question: http://stackoverflow.com/q/51676390
tags question: http://stackoverflow.com/q/51755742
tags question: http://stackoverflow.com/q/51732258
tags question: http://stackoverflow.com/q/51686489
tags question: http://stackoverflow.com/q/51650209
tags question: http://stackoverflow.com/q/51730484

http://stackoverflow.com/a/51641060
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51640978
answers question: http://stackoverflow.com/q/51640978
type: Answer
has body: For finding position of some string in other string, you can use str.index() method. This function() accepts list and string and yield words that match and position of the word in the string: def function(lst, s): for i in lst: if i not in s: continue yield i, s.index(i) lst = ['house', 'John', 'garden'] s = 'MynameisJohn' for word, position in function(lst, s): print(word, position) Output: John 8

http://stackoverflow.com/comment/90280273
has text: No. This has nothing to do with inheritance. You have things backwards in your head. The base URL calls the index view, which renders the template. Your notify view is never called, because the only thing that calls a view is a URL.
score: 1
comment on: http://stackoverflow.com/a/51657878
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90294835
comment on: http://stackoverflow.com/q/51665386
type: QuestionComment
has text: So If the isn't a value beneath Value `X` in `Col A` I want to delete all those rows until there is a value underneath Value `X`
score: 0
type: Comment

http://stackoverflow.com/a/51695925
has body: It seems Python automatically takes the value type as "String" No. The value type is string, until you convert it to something else. There is no secret magic that guesses possible variable types from the user's input. There is a helper function isdigit you can use to check if a string only consists of digits. response = input("enter the string: ") if str.isdigit(response): ...
answers question: http://stackoverflow.com/q/51695894
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90355236
type: Answer

http://stackoverflow.com/q/51650679
favorite count: 0
tagged with: python
has body: I am trying to download pdf report from web using python, however the code is returning a blank pdf report at the end, may i know whats wrong with the code and where i am going wrong. ============================================= from BeautifulSoup import BeautifulSoup import urllib2 import re html_page = urllib2.urlopen("http://www.imd.gov.in/Welcome%20To%20IMD/Welcome.php") soup = BeautifulSoup(html_page) b = soup.findAll('a', attrs={'href': re.compile("^http://hydro.imd.gov.in/hydrometweb/")}) c = b[0]['href'] d = c[0:len(c)-12] e = d + "PdfReportPage.aspx?ImgUrl=PRODUCTS/Rainfall_Statistics/Cumulative/District_RF_Distribution/DISTRICT_RAINFALL_DISTRIBUTION_COUNTRY_INDIA_cd.PDF" def download_file(download_url): response = urllib2.urlopen(download_url) file = open("document.pdf", 'w') file.write(response.read()) file.close() print("Completed") download_file(e)
type: AnsweredQuestion
tagged with: web-scraping
type: Question
has title: web scraping to download pdf file from web using python but getting blank file
accepted answer: http://stackoverflow.com/a/51650842
score: -1
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51650842
answer count: 1

http://stackoverflow.com/q/51761345
has answer: http://stackoverflow.com/a/51763267
type: Question
tagged with: numpy
tagged with: arrays
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90485379
type: UnansweredQuestion
tagged with: columnsorting
tagged with: python
has title: Sorting arrays in NumPy by column wrong
has comment: http://stackoverflow.com/comment/90481587
has body: I have tested the following code a=np.array([[1,5],[2,4]]) a[a[:,1].argsort()] print(a) And i receive [[1,5],[2,4]] I am supposed to obtain [[2,4],[1,5]] Numpy is imported as np. What is going on?

http://stackoverflow.com/a/51750300
upvote count: 3
has comment: http://stackoverflow.com/comment/90462132
has comment: http://stackoverflow.com/comment/90461306
score: 3
has comment: http://stackoverflow.com/comment/90461612
has body: Try this: dataForModel=np.insert(dataForModel, dataForModel.size, sampling_times, axis=1) Example: &gt;&gt;&gt; a = np.array([2, 56, 4, 8, 564]) &gt;&gt;&gt; np.insert(a, -1, [1,2,3]) array([ 2, 56, 4, 8, 1, 2, 3, 564]) &gt;&gt;&gt; np.insert(a, a.size, [1,2,3]) array([ 2, 56, 4, 8, 564, 1, 2, 3]) Update: &gt;&gt;&gt; dataForModel=[np.array([2,15,-3,4]), np.array([12,1,3,42]),np.array([6,8,21,-5])] &gt;&gt;&gt; dataForModel=np.array(dataForModel) &gt;&gt;&gt; dataForModel array([[ 2, 15, -3, 4], [12, 1, 3, 42], [ 6, 8, 21, -5]]) &gt;&gt;&gt; output_recoded= [101,47,82] &gt;&gt;&gt; dataForModel=np.insert(dataForModel, dataForModel.shape[1], output_recoded, axis=1) &gt;&gt;&gt; dataForModel array([[ 2, 15, -3, 4, 101], [ 12, 1, 3, 42, 47], [ 6, 8, 21, -5, 82]]) If you are trying to add an ending column, keep in mind the data added needs to match the dimensions of (dataForModel.shape[1],1) dimension
has comment: http://stackoverflow.com/comment/90462534
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90462196
has comment: http://stackoverflow.com/comment/90461068
accepted answer of: http://stackoverflow.com/q/51750212
type: Answer
answers question: http://stackoverflow.com/q/51750212
has comment: http://stackoverflow.com/comment/90460979

http://stackoverflow.com/q/51741056
tagged with: python
has comment: http://stackoverflow.com/comment/90442633
has comment: http://stackoverflow.com/comment/90442962
tagged with: loops
upvote count: 1
type: Question
has title: Saving values in an array using loops
has body: My program was working perfectly; then, it would give me an error that states the following: Traceback (most recent call last): File "K:\56_CRT\1 PST EEIC\2_Projects\InternetOfTests\Project_Jacob\Full Program (Testing).py", line 228, in &lt;module&gt; inputSamplesm[idx] = [data[0], data[1]] IndexError: list index out of range I don't know what that is. I've been trying to manipulate the arrays and indices, but I seem to fail to solve the problem. Please advise. Find my code below: with open('MagnaDC Set Points.csv', 'r') as csvfile1, open('Amatek Set Points.csv', 'r') as csvfile2: dataset = csv.reader(csvfile1, csvfile2, delimiter=',') next(dataset) rows = list(dataset) inputSamplesm = np.empty([len(rows), 2], dtype=float) outputSamplesm = np.empty([1,3], dtype=float) inputSamplesa = np.empty([len(rows), 2], dtype=float) outputSamplesa = np.empty([1,3], dtype=float) testStartTime = time.time() for idx, data in enumerate(rows): inputSamplesm[idx] = [data[0], data[1]] inputSamplesa[idx] = [data[0], data[1]] s.sendall('VOLT {0}\n'.format(data[0]).encode('utf-8')) conn.write('VOLT {0}\n'.format(data[0]).encode('utf-8')) stopTime = testStartTime + int(data[1]) while time.time() &lt; stopTime: s.sendall('MEAS:VOLT?\n'.encode('utf-8')) voltm = s.recv(1024) voltm = float(voltm)
score: 1
has comment: http://stackoverflow.com/comment/90442605
has comment: http://stackoverflow.com/comment/90442367
has comment: http://stackoverflow.com/comment/90442622
tagged with: for-loop
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90442792
favorite count: 0
has comment: http://stackoverflow.com/comment/90442278
has answer: http://stackoverflow.com/a/51741399
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/90487174
has text: @9769953 I'am using Sphinx 1.7.6 and python 3.6.5
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51742596

http://stackoverflow.com/a/51657204
type: Answer
has body: Here's a little function that can achieve this for you on a row by row basis (keeps appending new rows to the data frame) df = pd.DataFrame({'hours':[1,2,3,4], 'cumulative value':[1,2,3,6], 'Value to add': [1,1,3,1]}) def add_row(dataframe, numtimes): #adds new row 'numtimes' many times for i in range(numtimes): # Get values to put in new row new_hour = dataframe['hours'].iloc[-1]+1 new_cumulative_value = dataframe['cumulative value'].iloc[-1]+dataframe['Value to add'].iloc[-1] if new_hour % 3 == 0: new_val_to_add = 3 else: new_val_to_add = 1 #Create new row and add to DataFrame new_row = pd.DataFrame({'hours':[new_hour], 'cumulative value':[new_cumulative_value], 'Value to add': [new_val_to_add]}, index=[new_hour-1]) dataframe = dataframe.append(new_row) return dataframe df =add_row(df, 50)
has comment: http://stackoverflow.com/comment/90298417
downvote count: 0
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51656402
upvote count: 1
answers question: http://stackoverflow.com/q/51656402

http://stackoverflow.com/comment/90277006
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51656665
type: AnswerComment
has text: Yeah, I've fixed it. It was a lack of attention on my part. Thanks .

http://stackoverflow.com/q/51739565
type: UnansweredQuestion
has body: Since I guess importing google.cloud.storage might be a very first step to set API connecting the firebase storage, what I did first is to install google-cloud on Ubuntu like this: $ pip install --upgrade google-cloud and it told me: Successfully installed google-cloud Then I tried to import storage from google.could on Jupyter Notebook like: from google.cloud import storage but it gave me an error message, says: ModuleNotFoundError: No module named 'google' so I am wondering what are the necessary steps to do this.
tagged with: python
has answer: http://stackoverflow.com/a/51740212
type: Question
tagged with: google-cloud-storage
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51745397
tagged with: api
tagged with: jupyter-notebook
has title: How to upload local files to Firebase storage from Jupyter Notebook using Python
tagged with: firebase-storage

http://stackoverflow.com/comment/90295074
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51664486
type: Comment
has text: Edited in accordance to new info.

http://stackoverflow.com/comment/126290023
type: AnswerComment
type: Comment
has text: nice! +1 - thanks for posting + details
comment on: http://stackoverflow.com/a/71444318
score: 0

http://stackoverflow.com/comment/90540644
comment on: http://stackoverflow.com/q/51789088
score: 0
has text: Are you have tried Xpath and CSS selector rather than class_name?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90545563
type: QuestionComment
type: Comment
has text: Under the assumption that `bal` starts as a positive integer and the function returns a non-negative integer, the only difference should be in readability. If you are having problems with this code, try printing all variables at every step to see what's going on.
comment on: http://stackoverflow.com/q/51793905
score: 0

http://stackoverflow.com/q/51702208
has title: Python dataframe value insertion to database table column
has answer: http://stackoverflow.com/a/51708062
upvote count: 2
answer count: 2
tagged with: sql
favorite count: 0
tagged with: snowflake-cloud-data-platform
tagged with: python
has answer: http://stackoverflow.com/a/55346227
has comment: http://stackoverflow.com/comment/90366551
score: 2
has body: Is it possible to insert python dataframe values to database table column? I am using snowflake as my database. CommuteTime is the table which contains the StudentID column. "add_col" is the python dataframe. I need to insert the df values to StudentID column. Below is my code which i have tried to insert df values to table column. c_col = pd.read_sql_query('insert into "SIS_WIDE"."PUBLIC"."CommuteTime" ("StudentID") VALUES ("add_col")', engine) When I execute the above its not accepting the dataframe. Its throwing the below error. ProgrammingError: (snowflake.connector.errors.ProgrammingError) 000904 (42000): SQL compilation error: error line 1 at position 68 invalid identifier '"add_col"' [SQL: 'insert into "SIS_WIDE"."PUBLIC"."CommuteTime" ("StudentID") VALUES ("add_col")'] (Background on this error at: http://sqlalche.me/e/f405) Please provide suggestions to fix this..
downvote count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/90529517
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51786190
has text: Looks like you are decoding something as JSON, which is not JSON or even text at all, but a binary file.
score: 1

http://stackoverflow.com/comment/90364245
type: QuestionComment
comment on: http://stackoverflow.com/q/51701515
score: 0
has text: Please format your code and add an error message.
type: Comment

http://stackoverflow.com/comment/90470503
score: 1
has text: The error says it all. you have mismatch type of object and datetime.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51755268

http://stackoverflow.com/q/51733447
tagged with: django
tagged with: python
has title: My Third "Grab Object in Django" Post
type: Question
score: 0
has answer: http://stackoverflow.com/a/51734529
has body: Clearly I am struggling with various permutations of grabbing objects in Django. Here's another. This is for the same library app I've been working on (in case you have seen my other questions). On the home page, I display the active user's name and information (this works fine). Then I wish to display all of the reviews that the active user has written. I am basically able to do this as well, except it just shows the reviews with no reference to the books they are supposed to describe. So... I need to be able to grab the Book object by its Review object. In other words, each time I display a Review, I want to be able to grab the Book (title and author) that it pertains to. Keep in mind that I can't grab the Book by the User (using created_by), because a user can write reviews for books that they did not add to the db. I hope this makes sense but I'm sure you can see that I am struggling with such problems. In models.py, I set up my tables like this (keep in mind that the User table is in a different app): class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey("Author", on_delete=models.CASCADE, related_name="books") created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="books_added") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = AuthorManager() class Review(models.Model): rating = models.IntegerField() comments = models.TextField() book = models.ForeignKey("Book", on_delete=models.CASCADE, related_name="reviews") created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviews_added") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=T…
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/90492258
score: 0
has text: Yeah. `pgrep` is smart enough to ignore itself, but there's no way for it to know to ignore the script.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51766384

http://stackoverflow.com/q/51672938
has comment: http://stackoverflow.com/comment/90308457
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90308937
has body: I have searched and found that using annotate in matplotlib for jupyter, we can name the x and y of a point. I have retried doing as you suggested. import matplotlib.pyplot as plt import pandas as pd def fit_data(): fig = plt.figure(1,figsize=(20,6)) plt.subplot(111) data1 = pd.DataFrame({"ID" : list(range(11)), "R" : list(range(11)), "Theta" : list(range(11))}) plt.scatter(data1['R'], data1['Theta'], marker='o', color='b', s=15) for i, row in data1.iterrows(): plt.annotate(row["ID"], xy=(row["R"],row["Theta"])) plt.xlabel('R',size=20) plt.ylabel('Theta',size=20) plt.show() plt.close() fit_data() It still doesn't take the ID from my data. It is still plotting an arbitrary plot. this is the image after using the revised code My data is as follows 1 19.177 24.642 2 9.398 12.774 3 9.077 12.373 4 15.287 19.448 5 4.129 5.41 6 2.25 3.416 7 11.674 15.16 8 10.962 14.469 9 1.924 3.628 10 2.087 3.891 11 9.706 13.186
has answer: http://stackoverflow.com/a/51673381
accepted answer: http://stackoverflow.com/a/51673381
tagged with: annotations
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has title: Matplotlib Name points on plots

http://stackoverflow.com/a/51775727
score: 3
accepted answer of: http://stackoverflow.com/q/51774735
downvote count: 0
answers question: http://stackoverflow.com/q/51774735
type: AcceptedAnswer
upvote count: 3
has body: Do this: {% if condtion_a and condition_b %} (Add | Edit) {% elif condition_a %} (Add) {% elif condition_b %} (Edit) {% endif %} Don't spread out your code between that many lines wrapped in parentheses. Just add them directly inside the tag instead. And to clean up your code, I also suggest putting the condition_a and condition_b up top first so you don't have to start and stop so many if statements (you have 3 endif's, that's not a good habit to follow when it can be done more cleanly). You could also put a and b in an else statement at the bottom, but I don't know the code in your view so that might not be a good idea.
type: Answer

http://stackoverflow.com/a/51653508
has comment: http://stackoverflow.com/comment/90271122
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51653419
has comment: http://stackoverflow.com/comment/90270307
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51653419
has body: Change the line where you open the file as: with open('file.csv', 'w', newline='') as f: Adding the newline argument as '' will remove the new lines from your output file.
type: Answer
score: 3
upvote count: 3

dashboard
tags question: http://stackoverflow.com/q/51786144
type: Tag
tag name: dashboard

http://stackoverflow.com/comment/90476685
comment on: http://stackoverflow.com/a/51758419
type: Comment
type: AnswerComment
has text: Traceback (most recent call last): File "C:\Users\Patrick\Python364\Python36\test.py", line 1, in <module> import pandas ModuleNotFoundError: No module named 'pandas' @Shashank Verma - that is the error in IDLE, I my script is just import pandas
score: 0

http://stackoverflow.com/a/51749503
has body: A more concise way to do it. cols = df.columns df[cols[0]] = df.apply(lambda x: x[cols[0]].replace('#',str(x[cols[1]]),1) if x[cols[1]]!=np.NaN else x,axis=1) print(df.apply(lambda x: x[cols[0]].replace('#',str(x[cols[2]]),1) if x[cols[2]]!=np.NaN else x,axis=1)) Out[12]: 0 There are 3 people 1 Five out of eight people are there 2 Only 2 are here 3 The rest is at home Name: 0, dtype: object If you need to do this for even more columns cols = df.columns for i in range(1, len(cols)): df[cols[0]] = df.apply(lambda x: x[cols[0]].replace('#',str(x[cols[i]]),1) if x[cols[i]]!=np.NaN else x,axis=1) print(df[cols[0]])
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51749235
downvote count: 1
answers question: http://stackoverflow.com/q/51749235
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51669572
has body: I am working in Python with a JSON file. When I print date it comes out like this : print (date['slot']) [{'slot': 1, 'type': {'url': 'https://pokeapi.co/api/v2/type/11/', 'name': 'water'}}] But I just want to get 'water'. I have been using different methods and it did not work. Can someone please help me to get just 'water' from the code?
has answer: http://stackoverflow.com/a/51669636
has comment: http://stackoverflow.com/comment/90302331
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90302109
has comment: http://stackoverflow.com/comment/90301826
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90301806
downvote count: 0
has title: how to get Parameters from a json file with python
type: UnansweredQuestion
score: 1
tagged with: python-requests
type: Question

http://stackoverflow.com/q/51645151
accepted answer: http://stackoverflow.com/a/51645207
tagged with: python
type: AnsweredQuestion
tagged with: build
tagged with: tkinter
tagged with: site-packages
type: Question
has answer: http://stackoverflow.com/a/51645207
has title: build is successful but code doesn't work, throwing ImportError
score: 0
answer count: 1
has body: My issue is little different from existing ones on the WEB. Let me try highlighting it in detail. I have this code to do some plotting by reading a .txt file specified. I was going to build it as usually as I did before. My setup.py is supposed to do the job. The content of setup.py is here As you can observe I have no any package related to tkinter in both my above files. I did python setup.py build in terminal and it executed well. But can't use my actual code with windows command script build\\exe.win-amd64-3.5\\draw_precision_recall_curve.exe D:\dataset\Fire_Smoke\Train\filelist.txt pause It throws this trace: Traceback (most recent call last): File "C:\python354\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run module.run() File "C:\python354\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run exec(code, m.__dict__) File "draw_precision_recall_curve.py", line 3, in &lt;module&gt; import matplotlib.pyplot as plt File "C:\python354\lib\site-packages\matplotlib\pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "C:\python354\lib\site-packages\matplotlib\backends\__init__.py", line 62, in pylab_setup [backend_name], 0) File "C:\python354\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 4, in &lt;module&gt; from . import tkagg # Paint image to Tk photo blitter extension. File "C:\python354\lib\site-packages\matplotlib\backends\tkagg.py", line 5, in &lt;module&gt; from six.moves import tkinter as Tk File "C:\python354\lib\site-packages\six.py", line 92, in __get__ result = self._resolve() File "C:\python354\lib\site-packages\six.py", line 115, in _resolve return _import_module(self.mod) File "C:\python354\lib\site-packages\six.py", line 82, in _import_module __import__(name) ImportError: No module named 'tkinter' I was not able to solve this looking at the related posts here and there. Any help is appreciated.

web-services
type: Tag
tags question: http://stackoverflow.com/q/51643168
tag name: web-services

http://stackoverflow.com/comment/90359471
comment on: http://stackoverflow.com/q/51698528
has text: use the `fill` and `expand` parameters of the `pack()` method, or the `grid()` equivalents. Only use `place()` for **special** situations, this is not one of them. Use `ttk` and set a custom style Label.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90659297
has text: This way dose not work.Because what I want is keeping the special section code in the baseWithSection.html so that it can apply to many other template,but your way will let me repeat the code,so this does not solve my question.
comment on: http://stackoverflow.com/a/51780298
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90315568
score: 0
type: Comment
type: QuestionComment
has text: Actually, I need to check all the fields like below with a AND condition in between.df_a['TOTAL_NO_OF_RECORDS'].all() == transaction_count and df_a['TOTAL_QUANTITY'] == quantity_count
comment on: http://stackoverflow.com/q/51675723

http://stackoverflow.com/comment/90381077
has text: Hi i have added the code. Thanks.
comment on: http://stackoverflow.com/q/51709918
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/51709831
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51709719
type: Answer
has body: It reads the file twice: Firstly it reads all lines, then counts the lines and initializes the matrix: fr = open(filename) numberOfLines = len(fr.readlines()) returnMat = zeros((numberOfLines,3)) Secondly it reads the file again to fill the matrix: fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() ... And it needs to open the file again, to start reading from its beginning again. It's not an effective code. Since fr.readlines() reads the whole file, there's no need to read the file again, instead the result (list of lines) should be stored in a variable and reused when filling the matrix. Also close() should be called when finished dealing with the file.
downvote count: 0
has comment: http://stackoverflow.com/comment/90381049
has comment: http://stackoverflow.com/comment/90381310

http://stackoverflow.com/comment/90474076
has text: Possible duplicate of [How to check if a file is a valid image file?](https://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file)
comment on: http://stackoverflow.com/q/51757305
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51687624
has body: I'm trying to convert my dataframe which is of the format: file config value name1 a 123 name1 b 123 name1 c 123 name2 a 456 name2 b 789 name2 c 123 As to have the following format: file a b c name1 123 123 123 name2 456 789 123 I want my 'config' values to become columns with the values equivalent to the 'value' column for each file. Any hints on how I might achieve this?
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51687660
linked to: http://stackoverflow.com/q/47152691
tagged with: python
duplicate of: http://stackoverflow.com/q/47152691
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51687660
has title: Reorganising dataframe by grouping two columns
possible better answer: http://stackoverflow.com/a/51687680
tagged with: dataframe
has answer: http://stackoverflow.com/a/51687680
type: Question
answer count: 2

http://stackoverflow.com/comment/90424107
type: Comment
has text: Yes you should use graphs. I would create a `Node` class that holds a list of Nodes that it is adjacent to. When you traverse, you can say at each given node, attempt to travel to adjacent nodes (depending on your algorithm). If you want shortest path, use Dijkstra's algorithm or A* search.
score: 0
comment on: http://stackoverflow.com/q/51731605
type: QuestionComment

http://stackoverflow.com/comment/90510346
comment on: http://stackoverflow.com/q/51758674
score: 0
type: Comment
type: QuestionComment
has text: @StephenRauch yes, that was what I was getting at.

http://stackoverflow.com/comment/90329990
score: 0
type: Comment
type: QuestionComment
has text: Wiggy: thank you. I see what you mean now. Satendra: I've added them in.
comment on: http://stackoverflow.com/q/51683492

http://stackoverflow.com/q/51694073
has comment: http://stackoverflow.com/comment/90349488
linked to: http://stackoverflow.com/q/4800419
has comment: http://stackoverflow.com/comment/90349505
type: Question
score: -1
linked to: http://stackoverflow.com/q/30534377
has answer: http://stackoverflow.com/a/51694121
linked to: http://stackoverflow.com/q/3989016
has title: Finding the largest in a list (string,number) python
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51694108
tagged with: string
favorite count: 0
duplicate of: http://stackoverflow.com/q/4800419
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5292303
has body: I have a list in the following format: [('car crash killed', 95), ('car accident crash', 86), ('disaster police car', 45)] I want to extract the string/sentence with the largest number and print it in a text file. In this case, the output will be: car crash killed If there two or more strings/sentences with the same largest number, I want to extract all of them.For example: [('car crash killed', 95), ('car accident crash', 95), ('disaster police car', 45)] Output: car crash killed car accident crash How to extract?
tagged with: python
duplicate of: http://stackoverflow.com/q/3989016
downvote count: 2
has answer: http://stackoverflow.com/a/51694174

http://stackoverflow.com/q/51737192
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51737226
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51737226
score: 1
has comment: http://stackoverflow.com/comment/90435035
type: Question
tagged with: infinite-loop
has body: I have a file with all zip codes in the US with their latitude and longitude. The file is in the format ZIP,LAT, LONG\n. I plan on saving these to a database, so I have looped through the file word by word and set a counter variable. If the counter == 1 it should assign the value to zip_codes[] if counter == 2 assign the value to latitude[] and if counter == 3 assign the value to longitude[], but when I run the following code to test if it properly added the zip code values it becomes an infinite loop and I have to force quit IDLE (file can be viewed at here) zip_code_file = open('zip_codes.txt') zip_codes=[] latitude=[] longitude = [] counter = 1 for s in zip_code_file.read().split(','): s = s.strip() if counter ==1: zip_codes.append(s) counter = counter +1 elif counter == 2: latitude.append(s) counter = counter+1 elif counter == 3: longitude.append(s) counter = 1 print(zip_codes) anyone know whats going on here?
tagged with: counter
possible better answer: http://stackoverflow.com/a/51737315
has title: Assigning list items with for loop causing infinite loop
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/51737315
upvote count: 1
has comment: http://stackoverflow.com/comment/90435081

http://stackoverflow.com/comment/90606340
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51794624
has text: Hi @nnnmmm thanks for your comments, I was using a subprocess just because that's the way I found into this community. my sub-test are written in python. When you refer to create a function do you refer a " def rf(): " am I right ?

http://stackoverflow.com/a/55032925
answers question: http://stackoverflow.com/q/51657097
score: 2
downvote count: 0
type: Answer
has body: Use raw connection (or raw cursor) to execute the fetch. import mysql.connector conn = mysql.connector.connect(database='test', user='test',raw=True) cursor = conn.cursor() cursor.execute("SELECT * FROM foo") cursor.fetchall() By default, python fetch command tries to convert the binary data to a string. When it tries this, it encounters a byte sequence which is not allowed in utf-8-encoded strings. Setting raw mode to True overrides this behaviour and makes the results be returned as is, rather than converted to Python types.
upvote count: 2

http://stackoverflow.com/q/51753809
tagged with: python
tagged with: dictionary
upvote count: 3
has comment: http://stackoverflow.com/comment/90467419
has answer: http://stackoverflow.com/a/51754001
has answer: http://stackoverflow.com/a/51754112
type: Question
has answer: http://stackoverflow.com/a/65828480
has comment: http://stackoverflow.com/comment/90469300
score: 3
answer count: 6
has comment: http://stackoverflow.com/comment/90467435
has title: Accessing nested keys in Python
has comment: http://stackoverflow.com/comment/90467530
tagged with: nested
downvote count: 0
has answer: http://stackoverflow.com/a/75829441
has answer: http://stackoverflow.com/a/51754103
has comment: http://stackoverflow.com/comment/90468065
has comment: http://stackoverflow.com/comment/116389258
favorite count: 0
has answer: http://stackoverflow.com/a/51753991
type: UnansweredQuestion
has body: I have a nested dictionary as below entry = { 0: {"Q": 0}, 1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, 2: { "N": { "Q": {"E"} } }, } When I try to access only the keys for the key 1, I get the following: &gt;&gt;&gt; print(entry[1].keys()) dict_keys(['W', 'E', 'N', 'S', 'Q']) But for key 2 it only returns the top key and not the nested key. &gt;&gt;&gt; print(entry[2].keys()) dict_keys(['N']) Why is it not returning the nested key of the dictionary?

http://stackoverflow.com/a/51738444
accepted answer of: http://stackoverflow.com/q/51737548
upvote count: 14
answers question: http://stackoverflow.com/q/51737548
has comment: http://stackoverflow.com/comment/90438654
has body: While I'm not sure about the pattern you are using, (manually mapping to your table classes) I think you would have a much easier time making use of declarative_base which does this for you. from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() Then make sure your models inherit Base from sqlalchemy import ( Column, Integer, String ) class Customers(Base): __tablename__ = 'customer' id = Column(Integer, primary_key=True) # Auto-increment should be default name = Column(String(20)) # Etc. def __repr__(self): return "&lt;Customer(name='%s', phone='%s', address='%s', " \ "source_from='%s')" % (self.name, self.phone, self.address, self.source_from) And finally use Base to create your table: Base.metadata.create_all(engine) Here is a good reference to basic declarative use cases. It gets a little more complicated depending on how you are scaffolding your app but its a great starting point: http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90443491
type: Answer
score: 14

http://stackoverflow.com/q/51716134
has body: Here's my problem. I am creating a parser for a movie-type script (not a computer script, but a screenplay), and I need to select all of the lines underneath a certain scene heading. Here's an example script from Shakespeare's Hamlet. #Scene 1# Bernardo: Who's there? Francisco: Nay, answer me: stand, and unfold yourself. #Scene 2# Horatio: Tis now struck twelve; get thee to bed, Francisco. Marcellus: Peace, break thee off; look, where it comes again! I need a way to select everything between "#Scene 1#" and '#Scene 2#'. Bernardo and Francisco should match, but Horatio and Marcellus should not. I've tried using lookahead and lookbehind, but apparently they don't work across multiple lines. /(?&lt;=#Scene 1#)(.*)(?=#Scene 2#)/gim If it's important, I'm using Python 2.7.
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/51716181
has answer: http://stackoverflow.com/a/51716181
has comment: http://stackoverflow.com/comment/90393574
favorite count: 0
has title: Select a group of lines in regex that are under a heading line
has answer: http://stackoverflow.com/a/51716187
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/159118
has comment: http://stackoverflow.com/comment/90393619
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/159118
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51716187
score: -1

http://stackoverflow.com/comment/90291135
has text: @Bazingaa I have added the data.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51663834

http://stackoverflow.com/a/51689911
type: Answer
has comment: http://stackoverflow.com/comment/90341735
has comment: http://stackoverflow.com/comment/90341809
score: 3
has comment: http://stackoverflow.com/comment/90341682
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51689892
upvote count: 3
has body: You can use a set comprehension with string slicing: L = ['2018-07-29T15:58:22.111904Z', '2018-07-29T15:59:22.033263Z', '2018-07-29T16:01:22.103157Z', '2018-07-30T11:41:22.032661Z', '2018-07-30T11:42:22.042215Z', '2018-07-31T12:31:21.062671Z'] res = {i[:10] for i in L} Result: print(res) {'2018-07-30', '2018-07-31', '2018-07-29'} If you need a list and do not care about order, use list(res). If you need a sorted list, use sorted(res). If you wish to work with datetime objects, which is highly recommended, you should convert to datetime and use the date method. Here's one way with the 3rd party dateutil module: from dateutil import parser res = {parser.parse(i).date() for i in L} print(res) {datetime.date(2018, 7, 29), datetime.date(2018, 7, 30), datetime.date(2018, 7, 31)} List conversion and sorting are possible, exactly as before.
accepted answer of: http://stackoverflow.com/q/51689892

http://stackoverflow.com/q/51650634
has answer: http://stackoverflow.com/a/51652577
accepted answer: http://stackoverflow.com/a/51652577
type: AnsweredQuestion
tagged with: dataframe
type: Question
has body: Let's say I have data like this id Date Time_Start Time_End start stop split 0 011 2017-08-01 20:20 21:40 2017-08-01 20:20:00 2017-08-01 21:40:00 False 1 012 2017-08-01 17:15 19:12 2017-08-01 17:15:00 2017-08-01 19:12:00 True 2 013 2017-08-01 15:46 16:20 2017-08-01 15:46:00 2017-08-01 16:20:00 False and the cut time is at 18:00 of each day. So, for example, "012" should be split to two rows and the stop column of the first one should update to 2017-08-01 17:59:00 while the start of second row will be 2017-08-01 18:00:00 and the rest stay the same id Date Time_Start Time_End start stop split birth_date 0 011 2017-08-01 20:20 21:40 2017-08-01 20:20:00 2017-08-01 21:40:00 False 2017-08-01 1 012 2017-08-01 17:15 19:12 2017-08-01 17:15:00 2017-08-01 17:59:00 True 2017-08-01 1 012 2017-08-01 17:15 19:12 2017-08-01 18:00:00 2017-08-01 19:12:00 True 2017-08-02 2 013 2017-08-01 15:46 16:20 2017-08-01 15:46:00 2017-08-01 16:20:00 False 2017-08-01 Note that I also want to create a new column call "birth_date" at the end if the stop time before 18:00 the "birth_date" will be the same day as "date" but if after the cut, the "birth_date" will be the following day. below are the code that I've been working with thus far and I'm stuck where I am asking. So, any help will be appreciated. import pandas as pd from datetime import datetime, time def make_date_time(df): df["start"] = pd.to_datetime(df["Date"].apply(str) + " " + df["Time_Start"]) df["stop"] = pd.to_datetime(df["Date"].apply(str) + " " + df["Time_End"]) def check_date_time(df): if df["start"] &gt; df["stop"]: df["stop"] += pd.Timedelta(days=1) return df["stop"] df["stop"] = df.apply(check_date_time, axis=1) return df def in_cut(df): reference = df["start"].replace(hour=18, minute=0, second=0) if df["start"] &lt;= df["stop"]: return df["start"] &lt;= reference &lt; df["stop"] else: return df["start"] &lt;= reference or reference &lt; df["stop"] data = {"id":["011","012","013"], "Date": ["2017-08-01", "2017-08-01", "2017-08…
answer count: 1
score: 0
tagged with: pandas
tagged with: datetime
has title: How to split a line of a Pandas dataframe to two lines on a specific condition
tagged with: python

http://stackoverflow.com/q/51738838
upvote count: 3
tagged with: xlsxwriter
tagged with: jira
type: Question
has body: I am creating one .xlsx file using xlsxwriter ByteIO object, Using same object I want to create .CSV file. is it possible? Here is my code: outputStr=BytesIO() workbook = xlsxwriter.Workbook(outputStr,{'in_memory': True}) worksheet = workbook.add_worksheet() # Some data we want to write to the worksheet. row = 0 col = 0 expenses=(['OriginalURL','NormalizedURL','Response','DuplicateOf','SourceId', 'RelatedSources'],) for OriginalURL,NormalizedURL,Response,DuplicateOf,SourceId,RelatedSources in (expenses): worksheet.write(row, col, OriginalURL) worksheet.write(row, col+1, NormalizedURL) worksheet.write(row, col+2, Response) worksheet.write(row, col+3, DuplicateOf) worksheet.write(row, col+4, SourceId) worksheet.write(row, col+5, RelatedSources) row += 1 workbook.close() Without storing the file, Using "outputStr" object I am attaching the ".xlsx" file in JIRA cloud. Here is the Jira Code(working with .xlsx file): thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='Result.xlsx') I want to attach CSV file with same result(Same code I tried with .csv but it not working): thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='CopyResult.csv') I am getting this error in CSV file: "The file format and extension of ".xls" don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?" Help me ! Thank you.
has title: Write CSV file using xlsxwriter ByteIO object
score: 3
answer count: 1
has answer: http://stackoverflow.com/a/51739600
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51739600

http://stackoverflow.com/comment/90273850
type: Comment
comment on: http://stackoverflow.com/q/51654961
has text: @Ali: using *singular* model names. That is basically it. `ForeignKey`s are not only a more direct mapping to what it is, it also offers a lot of convenience to obtain, query, modify `Book`s and `UserRating`s.
score: 0
type: QuestionComment

header
type: Tag
tags question: http://stackoverflow.com/q/51772199
tag name: header

http://stackoverflow.com/q/51749548
has answer: http://stackoverflow.com/a/51749776
tagged with: python
has comment: http://stackoverflow.com/comment/90458988
score: 2
has comment: http://stackoverflow.com/comment/90459044
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90458919
has body: So I was looking at the help() documentation of a module but soon realized it was very tedius to read the documentation in the small output box. So therefore I tried pasting the help() documentation to another file for more clearer reading. myfile = open("file.txt","w") myfile.write(str(help(random))) myfile.close() Instead of the documentation being written, it instead pasted in None. Any ideas how to do this?
downvote count: 0
linked to: http://stackoverflow.com/q/4675728
linked to: http://stackoverflow.com/q/11265603
has comment: http://stackoverflow.com/comment/90458936
has answer: http://stackoverflow.com/a/51749689
duplicate of: http://stackoverflow.com/q/11265603
favorite count: 0
has title: How to write help() documentation to a file Python?
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90459045

http://stackoverflow.com/q/51746659
has answer: http://stackoverflow.com/a/51749354
tagged with: python
has title: Matplotlib offsetbox fails to show grayscaled image
type: AnsweredQuestion
has body: As title says, I'm trying to show 8-bit grayscaled .bmp image in matplotlibs annotationbbox but for some reason the result is undesired. I also resized the image with skimage's function called resize which can also affect to the result. The reason for failed result is that annotated image is normalized so that the darkest pixel get color black and lightest pixel gets color white. Here are example code, original image and the result of the plot. import matplotlib.pyplot as plt from matplotlib import offsetbox import numpy as np from PIL import Image from skimage.transform import resize image = np.array(Image.open('testimage.bmp')) #Black color is converted to white color for i in range(image.shape[0]): for j in range(image.shape[1]): image[i][j] = 255 - image[i][j] fig, ax = plt.subplots(figsize=(300, 200),dpi=40) shown_images = np.array([[1., 1.]]) # just something big imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(resize(image, (540,940), order=1, preserve_range=True),cmap="Greys"),[0.5,0.5]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) plt.show() Original image Annotated image Hopefully I'm just missing something obvious...
accepted answer: http://stackoverflow.com/a/51749354
type: Question
tagged with: matplotlib
tagged with: scikit-image
score: 0
answer count: 1

http://stackoverflow.com/q/51773732
has title: MetPy: Station plot contrast
has body: I am wondering if it is possible to add some sort of a text shadow to the station plots to increase their contrast when overlaid on other fields. I am having a lot of trouble finding colors that work well when overlaid on visible satellite imagery This is what I've gotten so far: stationplot_al = StationPlot(ax, data_als.lon.values, data_als.lat.values, clip_on=True, transform=ccrs.PlateCarree(), fontsize=30) stationplot_al.plot_parameter('NW', temp_al_c, color='mediumvioletred', weight='demibold') stationplot_al.plot_parameter('SW', td_al_c, color='mediumvioletred', weight='demibold') stationplot_al.plot_parameter('NE', data_als.mslp, formatter=lambda v: format(10 * v, '.0f')[-3:],color='orangered',fontsize=32, weight='demibold') stationplot_al.plot_symbol('C', cf_al_all, sky_cover,color='mediumslateblue') stationplot_al.plot_barb(u_al, v_al,length=11,linewidth=3.5,barbcolor='mediumslateblue')
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51778594
answer count: 1
downvote count: 0
favorite count: 0
tagged with: metpy
tagged with: python
has answer: http://stackoverflow.com/a/51778594

http://stackoverflow.com/q/51792964
has body: Is there a way to write an If (or equivalent) statement that can have many arguments, and if any of those satisfy the logic, use that variable? For instance if len(x) == 1 or len(y) == 1 or len(z) == 1 or ... len(zz) == 1: # do something with the variable that met the condition So say only z has length 1, could I write above idea/formula in a way that takes the first True answer and use that? So something like x = "123" y = "234" z = "2" xx = "1234" yy = "12345" if len(x) == 1 or len(y) == 1 or len(z) == 1 or len(xx) == 1 or len(yy) == 1: #do something with the variable that satisfies the condition, so `z` in this case. Does that make any sense? The variables' lengths could change any time, so I'd like to be able to say "If any of the conditions are met, use the variable that met the condition"...? In the above, I don't know beforehand that zwill be the only one to meet the criteria, so my Then statement can't be z = "new value" or whatever I want to do with it. Edit: Sorry, per comments I know checking for len on integers isn't okay. This is solely for illustration purposes and it was the first thing I thought of to "test". Sorry if the len bit is confusing. I'm mainly just trying to see if I can use If statements (or related ones) where I don't know which of my many variables will meet a condition. (I'm still new regarding python, so my sincere apologies for my lack of semantics or proper terms). I'd like to avoid elif if at all possible just because it can get stringy. (But if that's the most pythonic way, then so be it!)
type: UnansweredQuestion
has title: If X or Y or Z then use *that* one?
has answer: http://stackoverflow.com/a/51793034
has comment: http://stackoverflow.com/comment/90543487
tagged with: python
answer count: 4
score: 8
linked to: http://stackoverflow.com/q/2361426
has comment: http://stackoverflow.com/comment/90543493
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51793135
has comment: http://stackoverflow.com/comment/90543532
has answer: http://stackoverflow.com/a/51793017
has comment: http://stackoverflow.com/comment/90543579
has comment: http://stackoverflow.com/comment/90543505
favorite count: 0
upvote count: 9
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51792992

http://stackoverflow.com/comment/90495958
type: Comment
type: AnswerComment
has text: I'm consuming from a API that I don't have the control. And why other softawers can't make a HTTPS requests ?
comment on: http://stackoverflow.com/a/51768580
score: 0

http://stackoverflow.com/q/51666771
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90297585
tagged with: python
has comment: http://stackoverflow.com/comment/90296455
downvote count: 1
has comment: http://stackoverflow.com/comment/90297423
has title: How to get the index values of two in level sec to subtract A & B using iloc
score: -1
type: Question
tagged with: numpy-ndarray
has body: How to get the index values of two in level sec to subtract A &amp; B for every level in first bar two -0.673690 0.113648 first sec A B bar one -0.424972 0.567020 two -0.673690 0.113648 baz one 0.404705 0.577046 two -0.370647 -1.157892 foo one 1.075770 -0.109050 two 0.357021 -0.674600 qux one -1.294524 0.413738 two -0.013960 -0.362543`
upvote count: 0
has comment: http://stackoverflow.com/comment/90296678
has answer: http://stackoverflow.com/a/51666840

http://stackoverflow.com/a/51679315
accepted answer of: http://stackoverflow.com/q/51677943
upvote count: 1
answers question: http://stackoverflow.com/q/51677943
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90322977
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90322224
has comment: http://stackoverflow.com/comment/90341173
type: Answer
has body: The easiest way is to use string slices. Since the lowest byte is on the far right and the highest is on the left, we can utilise negative indexes. def sub_bytes(i, start=0, end=0): i_str = hex(i)[2:] # skip 0x part i_sub = i_str[-end * 2: len(i_str) - start * 2] # get the bytes we need return int(i_sub or '0', 16) # convert to back int len(i_str) is here for better start=0 handling Let's try with your value In [2]: value = 0x1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF In [3]: sub_bytes(value, 0, 3) Out[3]: 11259375 In [4]: hex(sub_bytes(value, 0, 3)) Out[4]: '0xabcdef' In [6]: hex(sub_bytes(value, 10, 20)) Out[6]: '0x90abcdef1234567890ab' In [7]: hex(sub_bytes(value, 45)) Out[7]: '0x123456' If a requested slice is empty or out of range I return 0x0 here, but you may raise IndexError if you like. UPDATE In Python 3.2+ there are to_bytes and from_bytes defined on int that are more efficient and more handy for this case import math def slice_bytes(value, a=None, b=None, byteorder='little'): size = math.ceil(value.bit_length() / 8) value_bytes = value.to_bytes(size, byteorder) return int.from_bytes(value_bytes[a: b], byteorder) And after some performance testing on a number 7 ** 7 ** 7 which has 288998 bytes, I found slice_bytes to be faster than the direct approach by Karl. sub_bytes is apparently slower.

http://stackoverflow.com/comment/90259458
type: Comment
has text: still the same error as when i first try" attempted relative import beyond top-level package" :(
comment on: http://stackoverflow.com/a/51647564
score: 0
type: AnswerComment

http://stackoverflow.com/q/51676669
type: Question
has title: Python: extract a column of data from several text files
has answer: http://stackoverflow.com/a/51676787
upvote count: 1
answer count: 1
has body: I have been scratching my head pretty hard on this one. I have several text files, all in the same format: 99.00% 2874 2874 U 0 unclassified 1.00% 29 0 R 1 root 1.00% 29 0 R1 131567 cellular organisms 1.00% 29 0 D 2759 Eukaryota 1.00% 29 0 D1 33154 Opisthokonta 1.00% 29 0 K 4751 Fungi 1.00% 29 0 K1 451864 Dikarya I want to extract the 6th column from all these files and print it to a new file. Here is the code I have so far: import sys import os import glob # Usage: python extract_species.py path/to/folder &gt; output.txt def extractSpecies(fileContent, allSpecies): for line in fileContent.split('\n'): allSpecies.append(line.split('\t')[0]) def file_get_contents(filename): with open(filename) as f: return f.read() def listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)] allFiles = listdir_fullpath(sys.argv[1]) # List all files in the folder provided by system arg. # Read all files and store content in memory filesContent = [] # a list is created with one item per file. for filePath in allFiles: filesContent.append(file_get_contents(filePath)) # Extract all species and create a unique list allSpecies = [] for fileContent in filesContent: extractSpecies(fileContent, allSpecies) print(allSpecies) But this code provides only the values of the first column of data: 99.00% 1.00% 1.00% 1.00% 1.00% 1.00% 1.00% If I remove the [0] argument in line 7 (after "allSpecies.append(line.split('\t')"), then the object allSpecies contains all the data in the files. [' 99.00%', '2874', '2874', 'U', '0', 'unclassified'] [' 1.00%', '29', '0', 'R', '1', 'root'] [' 1.00%', '29', '0', 'R1', '131567', ' cellular organisms'] [' 1.00%', '29', '0', 'D', '2759', ' Eukaryota'] [' 1.00%', '29', '0', 'D1', '33154', ' Opisthokonta'] etc I thought I could simply change the [0] by the number of the column I am interested in (from 1 to 5), but no, if I do that I get an error saying: IndexError: list index out of range Which really baffles me. There must be something I really don't g…
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: parsing
downvote count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/90508641
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51740196
has text: Thanks, it works. I tried to give your comment +1 but it seems like my account is too young to do so.

http://stackoverflow.com/comment/90280991
type: QuestionComment
has text: Please share your attempts.
score: 3
comment on: http://stackoverflow.com/q/51658729
type: Comment

http://stackoverflow.com/q/51776799
has answer: http://stackoverflow.com/a/51776992
score: 2
has answer: http://stackoverflow.com/a/51776824
type: AnsweredQuestion
has title: Python: How to sort list of dictionaries by value and index
possible better answer: http://stackoverflow.com/a/51776992
accepted answer: http://stackoverflow.com/a/51776924
type: Question
downvote count: 0
tagged with: sorting
answer count: 3
has answer: http://stackoverflow.com/a/51776924
favorite count: 0
upvote count: 2
has body: I have a list of a dictionary of data that is in order in some places and out of order in others: Eg: data = [{"text":'a', "value":1}, {"text":'b', "value":1}, {"text":'j', "value":2}, {"text":'k', "value":50}, {"text":'b', "value":50}, {"text":'y', "value":52}, {"text":'x', "value":2}, {"text":'k', "value":3}, {"text":'m', "value":3}] I want to sort them as: o = [{"text":'a', "value":1}, {"text":'b', "value":1}, {"text":'j', "value":2}, {"text":'x', "value":2}, {"text":'k', "value":3}, {"text":'m', "value":3}, {"text":'k', "value":50}, {"text":'b', "value":50}, {"text":'y', "value":52}] wherein my sorting is some combination of the index of the item and the 2nd value, I was thinking sort with: key=[(2nd value)&lt;&lt;len(closest power of 2 to len(index)) + index] I can sort by the list of dicts by the 2nd value with: data.sort(key= lambda x:x['value']) How do I also add the index of the dictionary? And is there a better sorting key I could use?
tagged with: python

http://stackoverflow.com/comment/90270799
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51650209
has text: You can include more feature to the dataset from day of year like Season, Month, Weekday/weekend, Holiday. This can help in identifying trend among users.
score: 0

http://stackoverflow.com/a/51661800
score: -1
has body: You can also add param: def do_somthing(dict_of_dicts): """ :param dict_of_dicts: A dictionary of dictionaries. :type dict_of_dicts: dict of dict """ for key, value in dict_of_dicts.items(): for key2, value2 in value.items(): print('Key') I suggest reading this article: https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html
type: Answer
answers question: http://stackoverflow.com/q/51661560
downvote count: 1
upvote count: 0

http://stackoverflow.com/a/67528214
has body: import numpy as np import tables as tb class NumpyTable(tb.IsDescription): """ define a table with cells of 84 x 84""" numpy_cell = tb.Float32Col(shape=(84, 84)) """ open a file and create the table """ fileh = tb.open_file('numpy_cell.h5', mode='w') group = fileh.create_group(fileh.root, 'group') filters = tb.Filters(complevel=5, complib='zlib') np_table = fileh.create_table('/group', 'numpy_table', NumpyTable, "group: NumpyTable", filters=filters) """ get the last row """ row = np_table.row """ add a row """ row['numpy_cell'] = np.zeros((84, 84), dtype=np.float32) row.append() """ add another row """ row['numpy_cell'] = np.ones((84, 84), dtype=np.float32) row.append() """ write to disk and close the file""" np_table.flush() fileh.close() """ check it """ fileh = tb.open_file('numpy_cell.h5', mode='r') assert np.allclose( fileh.root.group.numpy_table[0]['numpy_cell'], np.zeros((84, 84), dtype=np.float32) ) assert np.allclose( fileh.root.group.numpy_table[1]['numpy_cell'], np.ones((84, 84), dtype=np.float32) ) fileh.close()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51771889
upvote count: 1
score: 1

http://stackoverflow.com/comment/90470506
type: Comment
comment on: http://stackoverflow.com/a/51735129
type: AnswerComment
score: 0
has text: yeah i got that. Would it be a way to keep all the nodes in the same graph while getting relationships contained on the edges so i don't get that error?

http://stackoverflow.com/comment/90472225
has text: Because they are both assuming different timezones. See the python docs I linked to. The timezone in both cases isn't explicitly determined. For example on my python program, `pandas.to_datetime()` seems to give me UTC and `datetime.datetime()` seems to assume local time.
comment on: http://stackoverflow.com/a/51756295
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51730480
linked to: http://stackoverflow.com/q/44385999
has title: Why is that slicing expression generating that output
has comment: http://stackoverflow.com/comment/90421876
has answer: http://stackoverflow.com/a/51730519
tagged with: slice
duplicate of: http://stackoverflow.com/q/44385999
answer count: 2
accepted answer: http://stackoverflow.com/a/51730519
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90422107
duplicate of: http://stackoverflow.com/q/509211
tagged with: python
possible better answer: http://stackoverflow.com/a/51730549
upvote count: 6
has answer: http://stackoverflow.com/a/51730549
type: AnsweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/90422388
type: Question
has body: I got this: #slicing: [start:end:step] s = 'I am not the Messiah' #s[0::-1] = 'I' So in this case start=0, end=0, step=-1 Why is s[0::-1] == 'I' &gt;&gt;&gt;&gt; True

http://stackoverflow.com/comment/90512044
type: AnswerComment
comment on: http://stackoverflow.com/a/51776659
type: Comment
has text: also, "Functional programming doesn't mean "use map and reduce everywhere possible"." It's like you know me personally :')
score: 1

http://stackoverflow.com/a/51718681
has comment: http://stackoverflow.com/comment/90437044
has body: Try python3 --version. Usually you need to add 3 on the end to anything you do with Python in the terminal.
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90398213
score: 2
accepted answer of: http://stackoverflow.com/q/51718671
downvote count: 0
has comment: http://stackoverflow.com/comment/90398194
answers question: http://stackoverflow.com/q/51718671

http://stackoverflow.com/a/51684660
has comment: http://stackoverflow.com/comment/90337256
score: 2
downvote count: 0
has body: Your input data is a plain Python list of Numpy arrays of unequal length, thus it can't be simply converted to a 2D Numpy array, and so it can't be directly processed by Numpy. But it can be process using the usual Python list processing tools. Here's a list comprehension that uses numpy.isin to test if a row contains any of (3, 7, 8). We first use simple == testing to see if the row contains 10, and only call isin if it does so; the Python and operator will not evaluate its second operand if the first operand is false-ish. We use np.any to see if any row item passes each test. np.any returns a Boolean value of False or True, but we can pass those values to int to convert them to 0 or 1. import numpy as np data = [ np.array([10, 1, 7, 3]), np.array([0, 14, 12, 13]), np.array([3, 10, 7, 8]), np.array([7, 5]), np.array([5, 12, 3]), np.array([14, 8, 10]), ] mask = np.array([3, 7, 8]) result = [int(np.any(row==10) and np.any(np.isin(row, mask))) for row in data] print(result) output [1, 0, 1, 0, 0, 1] I've just performed some timeit tests. Curiously, Reblochon Masque's code is faster on the data given in the question, presumably because of the short-circuiting behaviour of plain Python any, and &amp; or. Also, it appears that numpy.in1d is faster than numpy.isin, even though the docs recommend using the latter in new code. Here's a new version that's about 10% slower than Reblochon's. mask = np.array([3, 7, 8]) result = [int(any(row==10) and any(np.in1d(row, mask))) for row in data] Of course, the true speed on large amounts of real data may vary from what my tests indicate. And time may not be an issue: even on my slow old 32 bit single core 2GHz machine I can process the data in the question almost 3000 times in one second. hpaulj has suggested an even faster way. Here's some timeit test info, comparing the various versions. These tests were performed on my old machine, YMMV. import numpy as np from timeit import Timer the_data = [ np.array([10, 1, 7, 3]), np.array([0…
upvote count: 2
answers question: http://stackoverflow.com/q/51684046
type: Answer
has comment: http://stackoverflow.com/comment/90338056

http://stackoverflow.com/a/52598269
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51645934
has body: For context, the dataframe consists of stock return data for the S&amp;P500 over approximately 4 years def get_top_n(prev_returns, top_n): # generate dataframe populated with zeros for merging top_stocks = pd.DataFrame(0, columns = prev_returns.columns, index = prev_returns.index) # find top_n largest entries by row df = prev_returns.apply(lambda x: x.nlargest(top_n), axis=1) # merge dataframes top_stocks = top_stocks.merge(df, how = 'right').set_index(df.index) # return dataframe replacing non_zero answers with a 1 return (top_stocks.notnull()) * 1
type: Answer

http://stackoverflow.com/comment/90400059
has text: each process takes constant memory refers to constant disk space in the available storage
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51718642

pose-estimation
tag name: pose-estimation
tags question: http://stackoverflow.com/q/51671500
type: Tag

http://stackoverflow.com/a/51689772
answers question: http://stackoverflow.com/q/51689760
type: Answer
has comment: http://stackoverflow.com/comment/90341635
upvote count: 1
downvote count: 1
score: 0
has body: Try this code: digits = [i for i in str(num)]

http://stackoverflow.com/comment/90554073
score: 0
comment on: http://stackoverflow.com/q/51798338
type: Comment
type: QuestionComment
has text: I Added docker file.

http://stackoverflow.com/a/51691171
accepted answer of: http://stackoverflow.com/q/51691149
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4
downvote count: 0
has body: Per PEP8 "Programming Recommendations": Don't compare boolean values to True or False using ==. Yes: if greeting: No: if greeting == True: Worse: if greeting is True: Both of your tests happen to work here, but in general, using the implicit booleanness is considered more "Pythonic", since "truthy" vs. "falsy" is usually more important than True vs. False; if not var: will accurately identify var as falsy when it is None, or an empty sequence, which is usually what you want. As far as performance goes, if not var: will be faster; if var == False: must load var and False, perform the comparison, then perform the implicit boolean test that if always performs; if not var: performs the implicit boolean test directly with no preamble.
answers question: http://stackoverflow.com/q/51691149

http://stackoverflow.com/a/51727919
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51727560
has body: sections is a generator object. To get the first item from it you can use next() function: sections = Tree(db).execute('$.books[@.name is "Mark"].sections') print(sections) # will show that it's a generator for section in next(sections): print(section) print("----\n") This first item will be the list with individual sections. Now you can iterate over each section using for loop.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/115505606
type: Answer
accepted answer of: http://stackoverflow.com/q/51727560

http://stackoverflow.com/q/51788442
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51788506
tagged with: python
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51788506
has body: I have an Dataframe like this: Col1 Col2 A Foo1 A Foo3 B Foo1 B Foo3 B Foo4 C Foo1 D Foo3 D Foo4 And I need an output like this: Foo1 Foo3 Foo4 A 1 1 0 B 1 1 1 C 1 0 0 D 0 1 1 What is the simplest way in pandas to reach this, without using foreach loops in python.
has title: Pivottable in Pandas
tagged with: pandas

http://stackoverflow.com/comment/90537076
comment on: http://stackoverflow.com/q/51789766
type: Comment
type: QuestionComment
score: 0
has text: This isn't a problem with `if/else` or `lambda`, but of how a series of values should be treated as a boolean.

http://stackoverflow.com/comment/90552124
has text: How are we supposed to answer your question with knowing anything about your data? Please post a [mcve]
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51797523

http://stackoverflow.com/comment/90376660
type: QuestionComment
comment on: http://stackoverflow.com/q/51707847
has text: @Chris_Rands with `random.sample(range(1,100), 10000)` you will get error `ValueError: Sample larger than population or is negative`
score: 0
type: Comment

http://stackoverflow.com/q/51642102
has answer: http://stackoverflow.com/a/51642157
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/90248737
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90248659
has answer: http://stackoverflow.com/a/51642152
duplicate of: http://stackoverflow.com/q/39922986
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/90248751
type: Question
has title: How can I add the values in the dataset together in Python?
tagged with: numpy
answer count: 2
has body: I am trying to add values together for each year in my dataset. The dataframe looks like.. I'd like to add the values in NUMBER OF MOSQUITOES column, collect them in the year to which it belongs. For example, 2007 395 2008 154 2009 353 ... ... ... Which methods in pandas or numpy can I use? Thank you for your help in advance
linked to: http://stackoverflow.com/q/39922986
tagged with: pandas
downvote count: 1
tagged with: python

http://stackoverflow.com/q/51718642
has answer: http://stackoverflow.com/a/51719100
accepted answer: http://stackoverflow.com/a/51719100
tagged with: python
has comment: http://stackoverflow.com/comment/90400059
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90399991
type: Question
has title: Calculating time to disk full for n processes downloading to available storage
tagged with: algorithm
has body: I am working out a puzzle given by office leads to work out a solution. The puzzle is: n number of processes are running on the computer. They run forever, never die, and no new processes get spawned. Each process takes memory at a constant, individual rate - process p_i (with 0 &lt;= i &lt; n) consumes 1 byte after every d(p_i) seconds. The total amount of available disk space is denoted by X. Calculate the time to fill up available storage in seconds. The bare logic I have written below doesn't seem to be correct solution; I am little confused by process with different rate at which disk can get full. number_of_processes = 3 available_storage = 6 # in bytes write_speed_x = 1 #(byte/ p_i second) write_speed_y = 3 write_speed_z = 2 timeTaken = 0 pr_i = [write_speed_x, write_speed_y, write_speed_z] for i in pr_i: timeTaken += available_storage/i print timeTaken
score: 0
answer count: 1
tagged with: python-2.x

http://stackoverflow.com/a/51664761
has comment: http://stackoverflow.com/comment/90293993
has comment: http://stackoverflow.com/comment/90312198
accepted answer of: http://stackoverflow.com/q/51664618
has body: Just slicing: s = ''.join(b for a,b,c in list_of_list) list_of_list[s.find('|'):s.rfind('|')+1]
has comment: http://stackoverflow.com/comment/90292867
answers question: http://stackoverflow.com/q/51664618
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90292948
has comment: http://stackoverflow.com/comment/90310817
type: Answer
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/comment/90291614
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51664042
has text: A generator is different from a range object, though. ranges are sized (len) and support O(1) membership test.

http://stackoverflow.com/comment/90401376
type: Comment
type: AnswerComment
has text: Sorry I'll update the orginal post. I'm trying to iterate through column C in the excel sheet. And the data will always be either 1's or 2's.
score: 0
comment on: http://stackoverflow.com/a/51720314

http://stackoverflow.com/a/51737838
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51737329
type: Answer
has comment: http://stackoverflow.com/comment/90440554
has comment: http://stackoverflow.com/comment/90436798
has body: Since you've mentioned that this is for an assignment, I thought I'd show you how this is done more 'directly' using a dictionary / without using Counter, so you actually understand what's going on under the hood. d = {} # initialise a dictionary with open(file_path, 'r') as f: # open the file, call it 'f' for line in f: # read through each line in the file for c in line: # read through each character in that line if c in d: # check if character is in dictionary d[c] += 1 # if it's been seen before, increment counter else: d[c] = 1 # otherwise, insert it into the dictionary
accepted answer of: http://stackoverflow.com/q/51737329
score: 4
upvote count: 4

http://stackoverflow.com/a/51773071
answers question: http://stackoverflow.com/q/51772935
has body: First fit data to train model and then predict from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import make_regression X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) regr = RandomForestRegressor(max_depth=2, random_state=0) regr.fit(X, y) regr.predict([[0, 0, 0, 0]])
score: 0
type: Answer

http://stackoverflow.com/comment/90347384
score: 0
type: Comment
has text: Thanks! This is exactly what I needed ! Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/51692973

http://stackoverflow.com/q/51701626
downvote count: 0
has title: How to extract text from a text shape within a Group Shape in powerpoint, using python-pptx
has body: My PowerPoint slide has a number of group shapes in which there are child text shapes. Earlier I was using this code, but it doesn't handle Group shapes. for eachfile in files: prs = Presentation(eachfile) textrun=[] for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): print(shape.text) textrun.append(shape.text) new_list=" ".join(textrun) text_list.append(new_list) I am trying to extract the text from these child text boxes. I have managed to reach these child elements using GroupShape.shape, but I get an error, that these are of type 'property'. So I'm not able to access the text or iterate (TypeError: 'property' object is not iterable) over them. from pptx.shapes.group import GroupShape from pptx import Presentation for eachfile in files: prs = Presentation(eachfile) textrun=[] for slide in prs.slides: for shape in slide.shapes: for text in GroupShape.shapes: print(text) I would then like to catch the text and append to a string for further processing. So my question is, how to access the child text elements and extract the text from them. I have spent a lot of time going though the documentation and source code, but haven't been able to figure it out. Any help would be appreciated.
has answer: http://stackoverflow.com/a/51711507
has answer: http://stackoverflow.com/a/66228725
accepted answer: http://stackoverflow.com/a/51711507
type: Question
possible better answer: http://stackoverflow.com/a/56415888
upvote count: 6
has answer: http://stackoverflow.com/a/56415888
answer count: 3
favorite count: 0
tagged with: python-pptx
score: 6
tagged with: powerpoint
tagged with: python
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/comment/90391041
has text: So you want a Conda environment that can be set up in one place, and then still work when you move the whole environment to another place? It looks like you may want this uninplemented conda feature: https://github.com/conda/conda/issues/3097
comment on: http://stackoverflow.com/q/51714605
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51664588
type: Answer
has body: Following @MaxU's suggestion of vectorized solution in this answer ndf = pd.DataFrame({'a':np.repeat(df.cost_col.values, df.names_col.str.len()), 'b':np.concatenate(df.names_col.values)}) yields a b 0 3 milk 1 3 eggs 2 3 cookies 3 5 water 4 5 milk 5 5 yogurt 6 7 cookies 7 7 diaper 8 7 yogurt Then just plain groupy+mean ndf.groupby('b').mean() a b cookies 5 diaper 7 eggs 3 milk 4 water 5 yogurt 6
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51664482
score: 1
answers question: http://stackoverflow.com/q/51664482
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90386367
has text: In the mapping table, I only need a reference of the object that is type=1 from the type table. Yes, mapping table does have related(relationship) information.
type: Comment
comment on: http://stackoverflow.com/a/51712163
score: 0
type: AnswerComment

http://stackoverflow.com/q/51643451
has comment: http://stackoverflow.com/comment/110229322
has body: When downloading Python packages with pip, a progress bar is displayed by default. Using --progress-bar I can choose between different styles or turn the progress bar off entirely. If I pipe the output of a pip command, this progress bar is automatically disabled. E.g. python3 -m pip download --no-cache-dir scipy==1.1.0 # Progress bar python3 -m pip download --no-cache-dir scipy==1.1.0 | tee log # No progress bar (if you run both commands in turn, remember to remove the downloaded files in between). I'm sure that pip disables the progress bar because it detects that the output is not going to a TTY. I seek a way to ignore this cleverness of pip and force it to write out the progress bar anyway. The naïve guess would be to supply the --progress-bar argument, e.g. python3 -m pip download --no-cache-dir --progress-bar=on scipy==1.1.0 | tee log However, the non-TTY disabling of the progress bar overrules this. Note: A similar story exists for wget. Here, the progress bar can be forced using wget --progress=bar:force ...
tagged with: pipe
has title: Python pip: Forcing the progress bar
has comment: http://stackoverflow.com/comment/90251368
has comment: http://stackoverflow.com/comment/90251930
score: 0
tagged with: python
tagged with: python-3.x
answer count: 0
tagged with: tty
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/90251309
type: Question

seq2seq
tag name: seq2seq
tags question: http://stackoverflow.com/q/51658685
type: Tag
tags question: http://stackoverflow.com/q/51654599

http://stackoverflow.com/comment/90450011
type: QuestionComment
comment on: http://stackoverflow.com/q/51744642
score: 0
has text: that's all info that i'm using
type: Comment

http://stackoverflow.com/comment/108906188
type: Comment
score: 8
has text: @pooria Not necessarily. The purpose of data augmentation is trying to get an upper bound of the data distribution of unseen (test) data in a hope that the neural nets will be approximated to that data distribution with a trade-off that it approximates the original distribution of the train data (the test data is unlikely to be similar in reality). There's no one size fits all data augmentation approach or definition.
comment on: http://stackoverflow.com/a/54460259
type: AnswerComment

http://stackoverflow.com/comment/90340714
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51684546
has text: You're absolutely right. I adapted the code, now it should work. Sorry for this

http://stackoverflow.com/comment/90281081
comment on: http://stackoverflow.com/a/51657878
score: 0
type: AnswerComment
type: Comment
has text: No you still haven't understood. Even if you did do that it wouldn't help, because the index view needs the data at the time it renders the template. I told you the way to do this: contact l context processors or template tags.

http://stackoverflow.com/q/51798537
has body: I have dataframe in pandas with columns. I want list only the unique combinations .How can do it. **Input** data'Month','Ratio' Month Ratio 3 0.7169653 3 0.7169653 3 0.7169653 6 0.6789213 6 0.6789213 7 0.2345671 7 0.2345671 7 0.2345671 7 0.2345671 12 0.5623451 12 0.5623451 12 0.5623451 1 0.9808901 **Expected Output** Month Ratio 3 0.7169653 6 0.6789213 7 0.2345671 12 0.5623451 1 0.9808901 How to do this in python
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90553938
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90553917
tagged with: python
has title: How to list unique combinations in a pandas dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51798659
accepted answer: http://stackoverflow.com/a/51798659
linked to: http://stackoverflow.com/q/23667369
type: Question
duplicate of: http://stackoverflow.com/q/23667369
answer count: 1

http://stackoverflow.com/q/51777361
tagged with: web-scraping
linked to: http://stackoverflow.com/q/42422360
has body: I want to use Selenium to scrape a portion of HTML code (not all) from a complete web page for use in my current project. I do not want the inner text of the HTML, but the actual code and store it in an external text file or a new HTML file. Limitation: I cannot use any other library because the website is dynamic and rich in J.S only Selenium will work.
type: Question
score: -2
has comment: http://stackoverflow.com/comment/90519518
has comment: http://stackoverflow.com/comment/90520850
has comment: http://stackoverflow.com/comment/90521186
has answer: http://stackoverflow.com/a/51777490
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90515898
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90520912
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51777490
has title: Scraping the portion of HTML code (not text) using selenium in python
downvote count: 2
tagged with: selenium

http://stackoverflow.com/comment/90527741
has text: each of them is probably an individual dict.
score: 0
comment on: http://stackoverflow.com/q/51785355
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90512737
comment on: http://stackoverflow.com/a/51777177
type: AnswerComment
score: 0
type: Comment
has text: I just saved it as BMP and it worked well. I don't see any noise anymore. Thank you so much

http://stackoverflow.com/q/51785048
tagged with: python
type: AnsweredQuestion
has title: PolynomialFeatures Sklearn (many parameters)
has answer: http://stackoverflow.com/a/51789578
accepted answer: http://stackoverflow.com/a/51789578
has body: Here is my code. import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression X=np.array([[1, 2, 4]]).T print(X) y=np.array([1, 4, 16]) print(y) X_poly = PolynomialFeatures(degree=2).fit_transform(X) print(X_poly) # fit_intercept = False since PolynomialFeatures will create a 0-order polynomial as well. model = LinearRegression(fit_intercept = False) model.fit(X_poly,y) print('Coefficients: \n', model.coef_) print('Others: \n', model.intercept_) Please, how can change this code to use many parameters. Example of models: y=a*x*x+b * z+ c* t (we have y, x, z and t) Thanks a lot for help. Kind regards.
type: Question
has comment: http://stackoverflow.com/comment/90536094
score: 0
upvote count: 1
downvote count: 1
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90533693
favorite count: 0

http://stackoverflow.com/comment/90402260
type: Comment
has text: @R4nsomW4re it says that the image is empty... so make sure img was loaded correctly :)
comment on: http://stackoverflow.com/a/51702767
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90355991
score: 0
comment on: http://stackoverflow.com/q/51697299
type: Comment
has text: Why do you think it's a *deep* copy of each row? Would you see different results from a shallow copy of each row?
type: QuestionComment

http://stackoverflow.com/a/52908533
type: Answer
has body: Currently, (as of version 0.95.4), this is not possible from within AutoKey, because it can’t handle mouse buttons as hotkeys. This stackoverflow question may be of help: Triggering AutoKey Script via Mouse Button - How To?
upvote count: 1
answers question: http://stackoverflow.com/q/51770016
score: 1
downvote count: 0

http://stackoverflow.com/comment/90270507
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51653415
has text: As per my worked example, you shou'd get `ID_` if you don't `reset_index`. You can do this as a final step: `df = df.reset_index()`.
type: Comment

http://stackoverflow.com/comment/90528483
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51784299
has text: Welcome to Stack Overflow! Please take the [tour] and visit the [help] to get the most out of this site.
score: 0

http://stackoverflow.com/comment/90474058
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51756833
has text: Is `x[ui]` the current index of the sequence? I'm getting an error getting an index of a tensor if it is.
score: 0

http://stackoverflow.com/a/51745981
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90475585
accepted answer of: http://stackoverflow.com/q/51741591
type: Answer
score: 2
has body: I do not quite understand how the dictionary is meant to produce the shown colors. In any case it seems that using just a list of those colors is much easier. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap x,y = np.meshgrid(np.arange(11), np.arange(11)) data = np.linspace(0,50e-8,100).reshape(10,10) colors = [(255,255,255),(237,250,194),(205,255,205), (153,240,178),(83,189,159),(50,166,150), (50,150,180),(5,112,176),(5,80,140), (10,31,150),(44,1,70)] cm_rgb = LinearSegmentedColormap.from_list('', np.array(colors)/255.) cs = plt.pcolormesh(x, y, data, vmin=0, vmax=50e-8, shading='flat', cmap=cm_rgb) tick_levels = [0, 2e-8, 3e-8, 4e-8, 5e-8, 6e-8, 8e-8, 10e-8, 15e-8, 20e-8, 30e-8, 50e-8] bar = plt.colorbar(cs, orientation='vertical', shrink=0.5) bar.set_ticks(tick_levels) plt.show()
upvote count: 2
answers question: http://stackoverflow.com/q/51741591

http://stackoverflow.com/comment/90441247
comment on: http://stackoverflow.com/a/51729479
type: AnswerComment
has text: `webbrowser.open(auth_url)` is working for me, the problem is that after I log into Spotify I'm redirected to some url that I need to paste in the console, I still haven't figured how to automatically get that url
score: 0
type: Comment

http://stackoverflow.com/q/51719465
has title: Get intersections of all linestrings within a GeoDataFrame (geopandas) in python
downvote count: 0
has comment: http://stackoverflow.com/comment/90427854
has body: I have a GeoDataFrame containing some streets of a city (every row is a linestring). I would like to obtain another GeoDataFrame with all the intersections between those streets (as Points). All I can see is how to intersect 2 different GeoDataFrames. Is there any way to do it other than looping over the streets and intersecting with the rest? Thanks!
has answer: http://stackoverflow.com/a/79321536
type: Question
tagged with: intersection
score: 4
tagged with: geopandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4

union
type: Tag
tag name: union
tags question: http://stackoverflow.com/q/51700173
tags question: http://stackoverflow.com/q/51698925

http://stackoverflow.com/q/51645973
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/90256919
has title: Why there is an attributeError in MongoDB's collection?
tagged with: mongodb
has comment: http://stackoverflow.com/comment/90257692
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90257460
has body: After running a script, I'm getting this error while I'm successful in yielding the data in .csv file.Here is the error Traceback (most recent call last): File "f:\softwares\anaconda\lib\site-packages\twisted\internet\defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "C:\Users\Danial Taimoor\Desktop\facebook\facebook\pipelines.py", line 21, in process_item self.collection.insert(dict(item)) AttributeError: 'MongoDBPipeline' object has no attribute 'collection' 2018-08-02 10:06:04 [scrapy.extensions.logstats] INFO: Crawled 1 pages (at 0 pages/min), scraped 0 items (at 0 items/min) And here is the settings.py code ITEM_PIPELINES = { 'facebook.pipelines.MongoDBPipeline': 300, } MONGODB_SERVER='localhost' MONGODB_PORT = 27017 MONGODB_DB= 'posts' MONGODB_COLLECTION='fb_posts' pipeline.py from pymongo import MongoClient from scrapy.conf import settings class MongoDBPipeline(object): def __init_(self): connection=MongoClient( settings['MONGODB_SERVER'], settings['MONGODB_PORT'] ) db=connection[settings['MONGODB_DB']] self.collection=db[settings['MONGODB_COLLECTION']] def process_item(self,item,spider): self.collection.insert(dict(item)) return item This is my first try with mongodb!
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/90257576
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90257977

http://stackoverflow.com/a/51736686
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51728359
has body: Your code would need to assume a role in each sub-account. This will then provide temporary credentials that can be used to make API calls in the sub-account. From Accessing and Administering the Member Accounts in Your Organization - AWS Organizations: When you create an account in your organization, AWS Organizations automatically creates a root user and an IAM role for the account. ... If you create an account in your organization, you can access the account by using the preconfigured role that exists in all new accounts that are created this way. ... When you create a member account using the AWS Organizations console, AWS Organizations automatically creates an IAM role in the account. This role has full administrative permissions in the member account. The role is also configured to grant that access to the organization's master account.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51728359

http://stackoverflow.com/a/51787300
type: Answer
upvote count: 1
score: 1
has body: Take a look at the documentation, particularly labels and scale. This is one solution: # Set up window and scale from psychopy import visual win = visual.Window() scale = visual.RatingScale(win, labels=['Not at all confident', 'Extremely confident'], # End points scale=None, # Suppress default low=1, high=100, tickHeight=0) # Show scale while scale.noResponse: scale.draw() win.flip() # Show response print scale.getRating(), scale.getRT()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51785194
answers question: http://stackoverflow.com/q/51785194
has comment: http://stackoverflow.com/comment/90534116

http://stackoverflow.com/q/51681075
tagged with: python
has body: I'm trying to understand the proper way to use multiprocessing.Pipe to communicate two processes. I've come up with the following code, which seems to work: import multiprocessing def f(parent_conn, child_conn): parent_conn.close() while True: cmd, data = child_conn.recv() if cmd == "f1": child_conn.send("f1!") elif cmd == "f2": child_conn.send("f2!") else: raise NotImplementedError if __name__ == "__main__": parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=f, args=(parent_conn, child_conn)) p.start() child_conn.close() parent_conn.send(("f1", None)) parent_conn.send(("f2", None)) print(parent_conn.recv()) print(parent_conn.recv()) But it's not clear to me what parent_conn and child_conn really mean and why I have to call child_conn.close() and parent_conn.close() (assuming it's correct to close these connections in the first place). What are parent_conn and child_conn exactly? Does my code contain any error or bad practice?
upvote count: 1
answer count: 1
tagged with: python-multiprocessing
type: UnansweredQuestion
has title: return values of multiprocessing.Pipe()
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51681352
favorite count: 0
type: Question

http://stackoverflow.com/a/51665270
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90352379
answers question: http://stackoverflow.com/q/51657950
upvote count: 1
has body: amqp is rabbitmq not redis. Redis is typically redis://:password@hostname:port/db_number I would manually the config to see if it works. flask_app.config.update( CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379' )

http://stackoverflow.com/q/51734416
tagged with: python
possible better answer: http://stackoverflow.com/a/51734483
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51734483
downvote count: 0
has title: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe'
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51734831
upvote count: 6
has answer: http://stackoverflow.com/a/51734831
answer count: 3
has body: I have a numpy array like result = np.array([[[289, 354, 331], [291, 206, 66], [242, 70, 256]], [[210, 389, 342], [273, 454, 218], [255, 87, 256]], [[127, 342, 173], [450, 395, 147], [223, 228, 401]]]) and i'm trying to mask the array if an element is greater than 255. i.e i assume it to be of range 0-1024 and divide my value by 4 result = np.putmask(result, result &gt; 255, result/4) NOTE: result is the previous 3D array.And i'm getting this error TypeError: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe' What am i doing wrong? Thanks in advance
has answer: http://stackoverflow.com/a/78270846
favorite count: 0
score: 6

http://stackoverflow.com/comment/90489734
has text: it seems that serial_no does not exist in your code. Did you define it?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51765475

http://stackoverflow.com/q/51757711
downvote count: 4
has body: I have searched about how to plot the graph by matplotlib or ggplot but I couldn't figure out how to make it. from Nature 500(7463):415-421 August 2013. so I wanna plot in dots and with a mark for median, kind of showing distribution. million thanks for any help!
answer count: 1
favorite count: 0
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/51759307
has title: How to plot in this kind of graph in Python or R?
upvote count: 1
has comment: http://stackoverflow.com/comment/90475319
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90475142
has comment: http://stackoverflow.com/comment/90475110
accepted answer: http://stackoverflow.com/a/51759307
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90474913
type: Question
tagged with: http://stackoverflow.com/tag/r

http://stackoverflow.com/comment/90357779
has text: Good catch, I did not think there'd be issues, but I guess it makes sense since the list loaded at the beginning of the iteration kept changing. I would possibly expect some kind of exception. Great for learning though!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51698130
score: 0

http://stackoverflow.com/comment/90283555
has text: But what I am confused about also is - should the connection be opened and then closed in each function in a program?
comment on: http://stackoverflow.com/a/51645395
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51751900
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: output
tagged with: python
has comment: http://stackoverflow.com/comment/90463711
score: 1
type: Question
has title: Trying to get multiple variable outputs in Python
downvote count: 0
tagged with: dataset
tagged with: variables
has answer: http://stackoverflow.com/a/51751967
answer count: 1
has body: I have this problem with trying to figure how to change this code to something useable for me. I have created this combination below that gives me ADABTC, ADAETH, ADAUSDT, BCCBTC,...... and so on. I'm trying to have each one of these feed into a reference field to pull this information. alt = ["ADA", "BCC", "EOS"] base = ["BTC", "ETH", "USDT" alt_base = [] for x in alt: for y in base: alt_base.append(x + y) I'm trying to get this to feed into as an independent into feeding for some data calls. "Variable" = client.get_orderbook_ticker(symbol = alt_base) where I need this to basically end up with multiple version to be pulled from the source. Didn't know if I could try something like ada_btc = client.get_orderbook_ticker(symbol = "ADABTC") ada_eth = client.get_orderbook_ticker(symbol = "ADAETH") It doesn't have to list these out, but the variables would need to have those meanings. So I could parse data from these feeds to get the info I need. Figured something like this, but that doesn't work. I'm new to coding, but can't see some of the things that I need or what they are called to look them up. coin[] = client.get_orderbook_ticker(symbol = alt_base)

http://stackoverflow.com/comment/118295179
comment on: http://stackoverflow.com/q/51710037
score: 3
has text: @gohu - You are correct. For keyword args, both `mypy` and IDEs are able to assume the obvious and automatically treat them as `Optional`. See my answer below.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90277708
type: QuestionComment
has text: then i get: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
score: 0
comment on: http://stackoverflow.com/q/51656874
type: Comment

http://stackoverflow.com/comment/90386342
score: 0
comment on: http://stackoverflow.com/q/51712467
type: Comment
type: QuestionComment
has text: You're not calling `nine`. Try `four(plus(nine()))`

http://stackoverflow.com/a/51733492
has body: I think you forget reasign DataFrame: df = df.drop_duplicates(subset=['CONTRACT_ID'], keep=False)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90427731
accepted answer of: http://stackoverflow.com/q/51733483
answers question: http://stackoverflow.com/q/51733483
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51682118
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90395782
has comment: http://stackoverflow.com/comment/90386933
downvote count: 0
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/47036409
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90396735
tagged with: python
has body: I am trying to replicate old code that I had in tensorflow but in Keras format. For some reason my loss is always nan. I think the error is in the loss that I am using ('categorical_crossentropy' in keras vs 'tf.nn.softmax_cross_entropy_with_logits' in tensorflow) Keras code: import keras from keras.models import Sequential from keras.layers import Dropout, Dense, Activation from keras.regularizers import l2 from keras.layers.normalization import BatchNormalization # Keras items from keras.optimizers import Adam, Nadam from keras.activations import relu, elu from keras.losses import binary_crossentropy, categorical_crossentropy from keras import metrics import pandas as pd import numpy as np x_main = pd.read_csv("glioma DB X.csv") y_main = pd.read_csv("glioma DB Y.csv") from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x_main, y_main, test_size=0.3) x_test, x_val, y_test, y_val = train_test_split(x_test, y_test, test_size=0.5) # train shape np.shape(x_train), np.shape(y_train) ((132, 47), (132, 1)) # Normalize training data; will want to have the same mu and sigma for test def normalize_features(dataset): mu = np.mean(dataset, axis = 0) # columns sigma = np.std(dataset, axis = 0) norm_parameters = {'mu': mu, 'sigma': sigma} return (dataset-mu)/(sigma+1e-10), norm_parameters # Normal X data; using same mu and sigma from test set; x_train, norm_parameters = normalize_features(x_train) x_val = (x_val-norm_parameters['mu'])/(norm_parameters['sigma']+1e-10) x_test = (x_test-norm_parameters['mu'])/(norm_parameters['sigma']+1e-10) params = {'lr': 0.001, 'batch_size': 30, 'epochs': 8000, 'dropout': 0.5, 'weight_regulizer':['l2'], 'optimizer': 'adam', 'losses': 'categorical_crossentropy', 'activation':'relu', 'last_activation': 'softmax'} from keras.utils.np_utils import to_categorical #categorical_labels = to_categorical(int_labels, num_classes=None) if params['losses']=='categorical_crossentropy': y_train = to_categori…
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90373909
upvote count: 1
has title: loss: nan using Keras vs non-nan (working) output using tensorflow

http://stackoverflow.com/comment/90384759
score: 0
type: Comment
type: QuestionComment
has text: @jpp Are you referring to `merge` function in `pandas`? If yes, `pandasql` comes handy when I am making sql joins with multiple tables involving renaming column names.
comment on: http://stackoverflow.com/q/51686216

http://stackoverflow.com/q/51771812
accepted answer: http://stackoverflow.com/a/51771905
type: AnsweredQuestion
tagged with: dataframe
type: Question
answer count: 1
has body: I have a dataframe with 3 variables (id, V1, V2), I would like to create another variable according to variables V1 and V2 which will be called V3 and which will take 2 modalities ("LISTED" and "UN_LISTED"). Here is my data frame: print(df) id V1 V2 0 1 NaN NaN 1 2 QSINTSTK NaN 2 3 1111GHGKJKIUH 122354H 3 4 FGHKLIH 123456K 4 5 FDUL12 237899M 5 6 VHKIOY3 784236A 6 7 NaN Nan Here is the condition to create V3: If V1 and V2 is null then it is "UN_LISTED" If V2 is not null then it is "LISTED" If V1 is start with "QS" or "1111" then it is "UN_LISTED" otherwise it is "LISTED". Here is my code : def label_list (row): if row['V1'] == np.NaN and row['V2'] == np.NaN: return 'UN_LISTED' elif row['V2'] != np.NaN: return 'LISTED' elif row['V1'] == "^QS" or row['V1'] == "^(1){4}" : return 'UN_LISTED' else : return "LISTED" datatest.apply(lambda row : label_list(row), axis = 1) datatest['V3'] = datatest.apply(lambda row : label_list(row), axis = 1) But the result is wrong : print(df) id V1 V2 V3 0 1 NaN NaN LISTED 1 2 QSINTSTK NaN LISTED 2 3 1111GHGKJKIUH 122354H LISTED 3 4 FGHKLIH 123456K LISTED 4 5 FDUL12 237899M LISTED 5 6 VHKIOY3 784236A LISTED 6 7 NaN Nan LISTED Thanks for your help
score: 0
tagged with: pandas
tagged with: python
has title: Add column in a dataframe
has answer: http://stackoverflow.com/a/51771905

http://stackoverflow.com/q/51785209
has comment: http://stackoverflow.com/comment/90531391
has comment: http://stackoverflow.com/comment/90531510
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90530863
tagged with: python
has comment: http://stackoverflow.com/comment/90527319
has comment: http://stackoverflow.com/comment/90527383
answer count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90527759
has title: Python 'pandas' has no attribute 'ewm' on version 0.23.0 but ok on version 0.18.0
has body: The below codes are currently work with Pandas 0.18.0 and below but it doesn't work on newer version of Pandas such as Pandas 0.23.0. Please advise on how I can get it running with the latest Pandas 0.23.0 version. from binance.client import Client import numpy as np import pandas as pd import smtplib import time import yaml CONFIG = yaml.load(open('./CONFIG.yml')) API_KEY = CONFIG['binance_api']['key'] API_SECRET = CONFIG['binance_api']['secret'] user = CONFIG['gmail']['user'] passwd = CONFIG['gmail']['password'] client = Client(API_KEY, API_SECRET) # against ETH SYMBOLS = ('ADA', 'ADX', 'BAT', 'BCC', 'DASH', 'EOS', 'IOTA', 'LTC', 'NEO', 'OMG', 'STORJ', 'XLM', 'NANO', 'XRP', 'XVG', 'ZEC') RSI_N = 14 RSI_THRESHOLD = 8 RUN_INTERVAL_MINS = 30 def send_email(rsi_values): if len(rsi_values) &gt; 0: message = '\n'.join('{0:&gt;8} {1:.2f}'.format(symbol, rsi) for (symbol, rsi) in rsi_values) email_text = 'From: {0}\nTo: {1}\nSubject: Stock Recommendations\n\n{2}'.format(user, user, message) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(user, passwd) server.sendmail(user, user, email_text) server.close() except: pass while True: rsi_values = [] for SYMBOL in SYMBOLS: klines = client.get_historical_klines(SYMBOL + 'ETH', Client.KLINE_INTERVAL_30MINUTE, '{} hours ago UTC'.format((RSI_N + 3) // 2)) closings = np.asarray(klines, dtype=np.float)[-RSI_N - 1:, 4] diffs = np.diff(closings) ups = diffs.clip(min=0) downs = diffs.clip(max=0) ups_avg = pd.ewma(ups, span=RSI_N)[-1] downs_avg = -pd.ewma(downs, span=RSI_N)[-1] rs = ups_avg / downs_avg rsi = 100 - 100 / (1 + rs) rsi_values.append((SYMBOL, rsi)) print('\n'.join('{0:&gt;8} {1:.2f}'.format(symbol, rsi) for (symbol, rsi) in rsi_values)) rsi_values = list(filter(lambda x: x[1] &lt; RSI_THRESHOLD, rsi_values)) send_email(rsi_values) time.sleep(60 * RUN_INTERVAL_MINS) Warning message I'm getting with Pandas 0.18.0, but it's working: min_candle.py:73: FutureWarning: pd.ewm_mean is deprecated for…
type: Question
has comment: http://stackoverflow.com/comment/90528236
has comment: http://stackoverflow.com/comment/90528470
has comment: http://stackoverflow.com/comment/90531259
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90527744
has comment: http://stackoverflow.com/comment/90527415
favorite count: 0

http://stackoverflow.com/comment/90653721
type: QuestionComment
has text: This looks like a bug, it would help to file a github issue on TensorFlow with a reproducible example.
type: Comment
comment on: http://stackoverflow.com/q/51682492
score: 0

http://stackoverflow.com/comment/90435081
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51737192
has text: ive updated it to include the link to the file

http://stackoverflow.com/a/51687660
downvote count: 0
has body: Thats pivot_table df.pivot_table(index='file', columns='config', values='value') config a b c file name1 123 123 123 name2 456 789 123
accepted answer of: http://stackoverflow.com/q/51687624
upvote count: 2
answers question: http://stackoverflow.com/q/51687624
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/90435946
type: QuestionComment
type: Comment
has text: could you explain what you want for those of us not acclimated with Excel?
score: 0
comment on: http://stackoverflow.com/q/51737655

http://stackoverflow.com/comment/90354740
type: Comment
score: 0
has text: I already tried this and I get this error `NameError: name 'sent' is not defined` @Patrick Haugh (correction I forgot `sent = await` all this time. Apologies and thank you
comment on: http://stackoverflow.com/a/51696678
type: AnswerComment

set
tags question: http://stackoverflow.com/q/51749631
tags question: http://stackoverflow.com/q/51765551
tags question: http://stackoverflow.com/q/51686618
type: Tag
tags question: http://stackoverflow.com/q/51748890
tag name: set
tags question: http://stackoverflow.com/q/51656681
tags question: http://stackoverflow.com/q/51681730
tags question: http://stackoverflow.com/q/51717910
tags question: http://stackoverflow.com/q/51644115
tags question: http://stackoverflow.com/q/51664607
tags question: http://stackoverflow.com/q/51649572
tags question: http://stackoverflow.com/q/51727147
tags question: http://stackoverflow.com/q/51764091
tags question: http://stackoverflow.com/q/51719225
tags question: http://stackoverflow.com/q/51747902

http://stackoverflow.com/comment/90521028
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51778896
type: QuestionComment
has text: and also if I ask "what is ohms law" it answers "Ohm's law states that the current through a conductor between two points is directly proportional to the voltage across the two points. Introducing the constant of proportionality, the resistance, the relationship: I = V R , {\displaystyle I={\frac {V}{R}},}". see the formula is not is its regular shape. what should i do to turn it into its regular shape?

http://stackoverflow.com/comment/90366036
has text: You don't use `payload` in the request. Did you try to do this? What happens?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51702498

http://stackoverflow.com/comment/90485547
type: Comment
comment on: http://stackoverflow.com/a/51763150
type: AnswerComment
score: 0
has text: is there a way to start with 0 and not with 1?

http://stackoverflow.com/q/51725602
has comment: http://stackoverflow.com/comment/90411502
type: Question
tagged with: python
answer count: 1
tagged with: url-encoding
tagged with: urlencode
has comment: http://stackoverflow.com/comment/90411945
score: 0
tagged with: urllib
has title: urllib.quote_plus doesn't encode plus
has answer: http://stackoverflow.com/a/51725750
type: UnansweredQuestion
tagged with: python-2.7
has body: Here's what I'm doing: from urllib import quote_plus email = quote_plus('name+other@gmail.com') but print email &gt; name+other%40gmail.com so if I put it in a URL the + becomes a space when I pull it out. But I want it to stay a plus. What am I doing wrong?

http://stackoverflow.com/comment/90271300
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51652083
has text: Thank you, very well explained. The most confusing operation I find multiplication of a type and the magical result - an array out of it. But maybe this is a common trick in python.
type: AnswerComment

setuptools
tags question: http://stackoverflow.com/q/51763405
tags question: http://stackoverflow.com/q/51792993
tags question: http://stackoverflow.com/q/51714605
tag name: setuptools
tags question: http://stackoverflow.com/q/51655058
tags question: http://stackoverflow.com/q/51718908
type: Tag

http://stackoverflow.com/a/51734690
has body: You can build a new dictionary in the shape you want like this: ... data = { element["Name"]: { key: value for key, value in element.items() if key != "Name" } for element in json.loads(output) } fdata = json.dumps(data, indent=4) ... Result: { "Memory": { "SensorType": "Load", "Value": 53.3276978 }, "CPU Core #2": { "SensorType": "Clock", "Value": 2700.00073 }, (and so on) }
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90430312
answers question: http://stackoverflow.com/q/51733698
has comment: http://stackoverflow.com/comment/90439937

http://stackoverflow.com/comment/90545516
type: Comment
has text: ^ But won't we reach zero before reaching a negative value? In which case the expression should evaluate to false
type: QuestionComment
comment on: http://stackoverflow.com/q/51793905
score: 0

http://stackoverflow.com/a/51668859
type: Answer
has body: I think you try to find the value of selected option, as from html string. May be this help.. from bs4 import BeautifulSoup html_str = """ 09 10 11 """ soup = BeautifulSoup(html_str, 'html.parser') select = soup.find('select') for option in select.find_all('option'): if option.has_attr('selected'): print('Value:', option.get('value'))
score: 0
has comment: http://stackoverflow.com/comment/90301580
answers question: http://stackoverflow.com/q/51667938
has comment: http://stackoverflow.com/comment/90301727

http://stackoverflow.com/a/51763300
answers question: http://stackoverflow.com/q/51762200
has body: maybe DataFrame.rank() method is which you needed. examples: import pandas as pd df = pd.DataFrame({'id1':[1,1,1,2,2,2,3,3],'id2':[0,0,0,0,0,0,0,0]}) df['dummy_rank'] = df['id2'].groupby(df['id1']).rank(method='first').apply(int) the key point is 'method' argument, u can learn more info with document pandas.
downvote count: 0
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/51724242
favorite count: 0
has answer: http://stackoverflow.com/a/51725050
tagged with: python
type: AnsweredQuestion
score: 1
has body: I have a pandas dataframe. Some columns have only 2 unique values (such as GOOD/BAD, HIGH/LOW, FAIL/PASS). Their dtypes are object because the dataframe is loaded from a CSV file. I want to convert these columns into True/False, and automatic change the column name to is_FIRST_VALUE. For instance, X1 X2 X3 HIGH FAIL GOOD HIGH PASS GOOD LOW FAIL BAD should be converted: X1_is_HIGH X2_is_FAIL X3_is_GOOD True True True True False True False True False
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51724392
has answer: http://stackoverflow.com/a/51724445
accepted answer: http://stackoverflow.com/a/51724445
possible better answer: http://stackoverflow.com/a/51724392
answer count: 3
tagged with: pandas
downvote count: 0
has title: pandas: converting all columns with 2 values to True/False

http://stackoverflow.com/q/51644941
has body: #!/usr/bin/python # -*- coding: utf-8 -*- import csv la = open('loginscruz.csv', 'r') listaluno = csv.reader(la,delimiter=';') for alunos in listaluno[1:]: num = 1 aluno = str(alunos[3]) if (aluno != ''): print (aluno + " batata") The error is in the line for alunos in listaluno[1:]: I'm pretty new on Python so im asking your help guys
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/51645068
type: Question
accepted answer: http://stackoverflow.com/a/51645068
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/90253981
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51645042
has title: TypeError: '_csv.reader' object is not subscriptable
has answer: http://stackoverflow.com/a/51645042
tagged with: python-3.x
has answer: http://stackoverflow.com/a/56732635

http://stackoverflow.com/comment/90405685
has text: I cannot reproduce your error with this dataset. Please give us easy-to-import data. E.g. output of `toy_data.to_json()`
comment on: http://stackoverflow.com/q/51722468
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51762930
score: 1
has comment: http://stackoverflow.com/comment/90484662
has comment: http://stackoverflow.com/comment/90484935
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90485801
has body: Pytest provides a feature to manage dependencies of tests. You can create a separate test and set dependency on successive tests. You need to install pytest-dependency. pip install pytest-dependency Example: class TestExample(object): @pytest.mark.dependency() def test_func(self): assert False @pytest.mark.dependency(depends=["TestExample::test_func"]) def test_setting_value(self): print("Hello I am in testcase")
answers question: http://stackoverflow.com/q/51760917
upvote count: 1
has comment: http://stackoverflow.com/comment/90484843

http://stackoverflow.com/comment/90298716
type: Comment
type: QuestionComment
has text: Can you provide a minimal architecture that reproduces the error?
score: 0
comment on: http://stackoverflow.com/q/51662840

http://stackoverflow.com/q/51719954
tagged with: python
tagged with: recurrent-neural-network
has body: I'm trying to learn RNN and LSTM with tensorflow by following https://medium.com/@erikhallstrm/using-the-tensorflow-lstm-api-3-7-5f2b97ca6b73. I encountered with error that I have no idea to correct it which is ValueError: Input 0 of layer basic_lstm_cell_23 is incompatible with the layer: expected ndim=2, found ndim=1. Full shape received: [5] Can you guys look at this and help me? The line I'm having trouble is `states_series, current_state = tf.contrib.rnn.static_rnn(cell = cell,inputs = inputs_series,initial_state = init_state)` And this line below is the code I have. from __future__ import print_function, division import numpy as np import tensorflow as tf import matplotlib.pyplot as plt num_epochs = 100 total_series_length = 50000 truncated_backprop_length = 15 state_size = 4 num_classes = 2 echo_step = 3 batch_size = 5 num_batches = total_series_length//batch_size//truncated_backprop_length def generateData(): x = np.array(np.random.choice(2, total_series_length, p=[0.5, 0.5])) y = np.roll(x, echo_step) y[0:echo_step] = 0 x = x.reshape((batch_size, -1)) # The first index changing slowest, subseries as rows y = y.reshape((batch_size, -1)) return (x, y) batchX_placeholder = tf.placeholder(tf.float32, [batch_size, truncated_backprop_length]) batchY_placeholder = tf.placeholder(tf.int32, [batch_size, truncated_backprop_length]) cell_state = tf.placeholder(tf.float32, [batch_size, state_size]) hidden_state = tf.placeholder(tf.float32, [batch_size, state_size]) init_state = tf.nn.rnn_cell.LSTMStateTuple(cell_state, hidden_state) W2 = tf.Variable(np.random.rand(state_size, num_classes),dtype=tf.float32) b2 = tf.Variable(np.zeros((1,num_classes)), dtype=tf.float32) # Unpack columns inputs_series = tf.unstack(batchX_placeholder, axis=1) labels_series = tf.unstack(batchY_placeholder, axis=1) # Forward passes cell = tf.contrib.rnn.BasicLSTMCell(state_size, state_is_tuple=True) states_series, current_state = tf.contrib.rnn.static_rnn(cell = cell,inputs = inputs_series,in…
tagged with: tensorflow
has answer: http://stackoverflow.com/a/53706236
type: Question
has title: Input 0 of layer basic_lstm_cell_23 is incompatible with the layer: expected ndim=2, found ndim=1. Full shape received: [5]
tagged with: lstm
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/90459287
type: QuestionComment
comment on: http://stackoverflow.com/q/51749448
has text: In my excel table I have two lines for one team and I want to extract the data so that I have only one line per team. I'm trying to write the code but I have no idea. If anyone can offer me a code or guide me it will make me happy. thank you in advance
score: 0
type: Comment

http://stackoverflow.com/a/59133861
score: -6
has body: This works for me: source active &lt;your python env&gt;
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51712693
downvote count: 6

http://stackoverflow.com/a/51722578
downvote count: 0
has comment: http://stackoverflow.com/comment/90549178
has comment: http://stackoverflow.com/comment/90407517
answers question: http://stackoverflow.com/q/51721895
accepted answer of: http://stackoverflow.com/q/51721895
upvote count: 2
type: AcceptedAnswer
has body: The problem with your code is two-fold: You use getLogger(__name__) in the main module log_try_main.py, but __main__ evauates to the string "__main__" when the main module is called from Python on the command line, not to "log_try_main". You configure a root logger. If you add another handler to root logger, the logs logged by module will display twice. So here I write an example which I think runs as you expect: main.py: import logging import logging.config import module logging.config.dictConfig(dict( version=1, disable_existing_loggers=False, handlers={ 'hr': {'class': 'logging.StreamHandler', 'level': logging.DEBUG}, 'hm': {'class': 'logging.StreamHandler', 'level': logging.INFO} }, loggers={ 'module': {'handlers': ['hm'], 'level': logging.INFO}, 'main': {'handlers': ["hr"], 'level': logging.DEBUG} }, )) log = logging.getLogger("main") log.debug("This is mainly to DEBUG.") log.info("This is mainly to INFO.") log.warning("This is mainly to WARN.") module.do_something() moduel.py: import logging log = logging.getLogger("module") def do_something(): log.debug("This is something to DEBUG.") log.info("This is something to INFO.") log.warning("This is something to WARN.") Output: This is mainly to DEBUG. This is mainly to INFO. This is mainly to WARN. This is something to INFO. This is something to WARN. I explicitly name the two loggers instead of using __name__. I think this is more controllable and does not give different results when log_try_module.py is run on the command line.
has comment: http://stackoverflow.com/comment/90549088
type: Answer
score: 2

http://stackoverflow.com/a/51777505
upvote count: 2
has comment: http://stackoverflow.com/comment/90513333
answers question: http://stackoverflow.com/q/51777429
downvote count: 0
has body: Using groupby and transform: s = df.groupby(df.down.eq(1).cumsum()).distance.transform('first') s = df.distance.sub(s).div(df.distance) df['percentage'] = s.mask(s.eq(0)) down distance percentage 1 1.0 10.0 NaN 2 2.0 13.0 0.230769 3 3.0 15.0 0.333333 4 3.0 20.0 0.500000 5 4.0 1.0 -9.000000 6 1.0 10.0 NaN 7 2.0 9.0 -0.111111 8 3.0 3.0 -2.333333 9 1.0 10.0 NaN
has comment: http://stackoverflow.com/comment/90516235
type: Answer
score: 2

http://stackoverflow.com/q/51655058
has comment: http://stackoverflow.com/comment/90273977
tagged with: setuptools
type: Question
has comment: http://stackoverflow.com/comment/90273732
tagged with: gcc
score: 0
has title: Setuptools generated compilation command incorrectly specifying library directories
answer count: 0
type: UnansweredQuestion
has body: After running python3 setup.py build_ext, the following command is generated throughout the build sequence: arm-poky-linux-gnueabi-g++ ... \ -L=/opt/cortexa9hf-neon-poky-linux-gnueabi/usr/lib/ \ -L=/opt/cortexa9hf-neon-poky-linux-gnueabi/lib/ \ -lpython3.5m \ -o build/lib.linux-x86_64-3.5/kiwisolver.cpython-35m-x86_64-linux-gnu.so which produces the following errors: /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crti.o: No such file or directory /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crtbeginS.o: No such file or directory /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lpython3.5m /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lstdc++ /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lm /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lgcc_s /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lc /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find -lgcc_s /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crtendS.o: No such file or directory /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crtn.o: No such file or directory However, when I replace the -L= with -L, the errors are reduced down to: /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crti.o: No such file or directory /opt/x86_64-linux/usr/libexec/arm-poky-linux-gnueabi/gcc/arm-poky-linux-gnueabi/5.4.0/real-ld: cannot find crtbeginS.o: No such file or directory /opt/x86_6…
tagged with: python
has comment: http://stackoverflow.com/comment/90278989
has comment: http://stackoverflow.com/comment/90279043

http://stackoverflow.com/comment/90495059
type: Comment
comment on: http://stackoverflow.com/a/51765552
type: AnswerComment
has text: Thanks for the tip, I have amended my answer!
score: 0

http://stackoverflow.com/a/51777738
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51777724
has body: You can use the text attribute: &gt;&gt;&gt; import requests &gt;&gt;&gt; page = requests.get('https://fasttrack.grv.org.au/RaceField/ViewRaces/338181522') &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup(page.content, 'html.parser') &gt;&gt;&gt; print([ i.text for i in soup.select("div#DogName_1_1 a")]) ['MERCURY RISING [M]'] If it is just one element you are interested in, you may want to do something like: &gt;&gt;&gt; soup.find(id='DogName_1_1').text '\nMERCURY RISING [M]\n' If you want to get rid of the trailing/leading \ns you can use strip: &gt;&gt;&gt; soup.find(id='DogName_1_1').text.strip() 'MERCURY RISING [M]'
answers question: http://stackoverflow.com/q/51777724
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51717268
tagged with: datetime
favorite count: 0
linked to: http://stackoverflow.com/q/19231871
type: UnansweredQuestion
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/19231871
has answer: http://stackoverflow.com/a/51717311
has title: How to convert timestemp to readable values? [Pandas Dataframe]
has body: Here is an dataframe I'm working with: date price trade size 1417412036 300.0 0.010000 1417412423 300.0 0.010000 1417415048 370.0 0.010000 1417416612 370.0 0.026556 1417498166 377.0 0.010000 How do I convert the values of index to human readable dates? For example 1420705427 should change to 2015-01-08T03:23:47
score: 1
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51717328
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/51728668
has comment: http://stackoverflow.com/comment/90418238
type: Answer
has body: This is because of conflicting keys between the p_data df and pkt data in your append statement - you need to ensure that the keys in pkt match the column headings in the p_data dataframe you are appending to. Fix this by either re-naming the columns in the p_data dataframe to the numbers you are seeing in the pkt, or by re-naming the keys in pkt before you append the data. Edit: Following further discussion, agreed column names will not come into it as the incoming data is in the same order as the existing df. Simply wrap pd.DataFrame() around the pkt object and make sure the row of data is in the right shape when appending to achieve desired result. import pandas as pd import numpy as np # Set initial df with data d = pd.DataFrame(['f1:07:ad:6b:97:c8', '-23', '2900', '24.00', '17962371', '25509685', 'None']).T p_data = pd.DataFrame(data=d, dtype='str') # Parse new incoming data output = "f1:07:ad:6b:97:c8;-24;2800;23.00;17962365;25509655;None" pkt = output.split(";") # Append new data to existing dataframe p_data = p_data.append(pd.DataFrame(data=p_rows).T, ignore_index=True)
score: 0
has comment: http://stackoverflow.com/comment/90418529
answers question: http://stackoverflow.com/q/51728054

http://stackoverflow.com/a/51736019
answers question: http://stackoverflow.com/q/51735951
has body: Try Django As I understand it, Python does not natively have any database functionality. There are many different libraries/frameworks/etc. that can be used to provide database functionality to Python. I recommend taking a look at Django. With Django, you create a class for each database table and Django hides a LOT of the details, including allowing using with multiple database engines such as MySQL and PostgreSQL. Django handles Foreign Key relationships very well. Every table normally has a primary key, by default an auto-incremented id field. If you add a field like activity = models.ForeignKey(Activity) then you now have a foreign key field activity_id in one table referencing the primary key field id in the Activity table. The Admin page will take care of cascading deletion of records if you delete an Activity record, and in general things "just work" the way you might expect them to.
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51735951

http://stackoverflow.com/a/51789632
downvote count: 0
answers question: http://stackoverflow.com/q/51784864
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51784864
has comment: http://stackoverflow.com/comment/94836355
type: AcceptedAnswer
has body: The way your hook is set up right now you are essentially trying to create new variables/ops after each session run. Instead, you should define the tf.assign op beforehand and pass it to the hook so that it can run the op itself if necessary, or define the assign op in the hook's __init__. You can access the session inside after_run via the run_context argument. So something like class DynamicWeightingHook(tf.train.SessionRunHook): def __init__(self, epoch_size, gamma_value, lambda_tensor): self.gamma = gamma_value self.epoch_size = epoch_size self.steps = 0 self.update_op = tf.assign(lambda_tensor, self.gamma_placeholder) def before_run(self, run_context): self.steps += 1 def after_run(self, run_context, run_values): if self.steps % epoch_size == 0: # epoch run_context.session.run(self.update_op) self.gamma += 0.1 There are some caveats here. For one, I'm not sure whether you can do tf.assign with a Python integer like this, i.e. whether it will update properly once gamma is changed. If this doesn't work, you could try this: class DynamicWeightingHook(tf.train.SessionRunHook): def __init__(self, epoch_size, gamma_value, lambda_tensor): self.gamma = gamma_value self.epoch_size = epoch_size self.steps = 0 self.gamma_placeholder = tf.placeholder(tf.float32, []) self.update_op = tf.assign(lambda_tensor, self.gamma_placeholder) def before_run(self, run_context): self.steps += 1 def after_run(self, run_context, run_values): if self.steps % epoch_size == 0: # epoch run_context.session.run(self.update_op, feed_dict={self.gamma_placeholder: self.gamma}) self.gamma += 0.1 Here, we use an additional placeholder to be able to pass the "current" gamma to the assign op at all times. Second, since the hooks needs access to the variables, you would need to define the hook inside the model function. You can pass such hooks to the training process in the EstimatorSpec (see here).

http://stackoverflow.com/q/51698528
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90360004
type: Question
has comment: http://stackoverflow.com/comment/90359471
has title: Tkinter: How do I build an application for several different screen resolutions
tagged with: python
accepted answer: http://stackoverflow.com/a/51700562
has comment: http://stackoverflow.com/comment/90361480
answer count: 1
has body: So I'm working on an application in Python with Tkinter as the GUI framework. The first picture is a screenshot from my coworkers computer, the second is a screenshot from my computer. How can I make widgets(buttons, labels, entries, etc) adaptable for any screen resolution? Sample of my code self.e_fname = Entry(self) self.e_fname.place(relx=0.21, rely=0.18, height=40, relwidth=0.27) self.l_fname = Label(self, text='''First Name:''', font=font9,bg='#0066AB') self.l_fname.place(relx=0.055, rely=0.13, height=40, width=514) # last name self.e_lname = Entry(self) self.e_lname.place(relx=0.55, rely=0.18, height=40, relwidth=0.27) self.l_lname = Label(self, text='''Last Name:''', font=font9,bg='#0066AB') self.l_lname.place(relx=0.395, rely=0.13, height=40, width=514) # email self.e_mail = Entry(self) self.e_mail.place(relx=0.21, rely=0.29,height=40, relwidth=0.57) self.l_mail = Label(self, text='''Email Address:''', font=font9, bg='#0066AB') self.l_mail.place(relx=0.06, rely=0.24, height=31, width=514) # phone number self.e_phone = Entry(self) self.e_phone.place(relx=0.21, rely=0.40, height=40, relwidth=0.57) self.l_phone = Label(self, text= '''Phone Number:''', font=font9, bg='#0066AB') self.l_phone.place(relx=0.06, rely=0.36, height=31, width=514) # Address self.e_saddress = Entry(self) self.e_saddress.place(relx=0.21, rely=0.51, height=40, relwidth=0.57) self.adress = Label(self, text='''Address:''', font=font9, bg='#0066AB') self.adress.place(relx=0.05, rely=0.46, height=31, width=514) # Address Line 2 self.e_saddress2 = Entry(self) self.e_saddress2.place(relx=0.21, rely=0.62, height=40, relwidth=0.57) self.adress2 = Label(self, text='''Address Confirmation:''', font=font9, bg='#0066AB') self.adress2.place(relx=0.075, rely=0.57, height=31, width=514) # State self.state = Label(self, text='''State:''', font=font9, bg='#0066AB')
tagged with: tkinter
upvote count: 1
has answer: http://stackoverflow.com/a/51700562
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90495795
has text: Using datetime, you can know the current date time and you know the date from your CSV file. Keep a check on date and you are good to go.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51768418
type: Comment

http://stackoverflow.com/comment/90294318
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51665087
has text: @AdriVelaz thanks, that's typo while posting here

http://stackoverflow.com/q/51729266
tagged with: spotipy
tagged with: spotify
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90419624
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm writing a console application to create a playlist on Spotify according to a list of song. I'm using Spotipy and I'm trying with util.prompt_for_user_token(), the problem is that after I grant access I have to manually paste the redirect link into the console. User authentication requires interaction with your web browser. Once you enter your credentials and give authorization, you will be redirected to a url. Paste that url you were directed to to complete the authorization. Is there a way to automate this process? The solution here didn't help me
score: 2
has answer: http://stackoverflow.com/a/51729479
upvote count: 2
has title: Spotify authorization code - get token [ console application ]
type: Question
linked to: http://stackoverflow.com/q/38133520

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
tags question: http://stackoverflow.com/q/51665563
type: Tag
tags question: http://stackoverflow.com/q/51794156
tags question: http://stackoverflow.com/q/51657638
tags question: http://stackoverflow.com/q/51651093

http://stackoverflow.com/q/51771344
has answer: http://stackoverflow.com/a/51771528
tagged with: image
type: Question
answer count: 2
downvote count: 0
favorite count: 0
tagged with: cross-correlation
has body: I am new in Python. I have an image of size 8*8, and when flattened = 64. Is there any function that measures the correlation between the pixel i and all the other pixels in this image ? So at the end I want to plot a 64*64 matrix of correlation. Thanks !
tagged with: python
tagged with: correlation
has title: Pixel correlation / similarity in an image Python
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/65495171
score: 1
linked to: http://stackoverflow.com/q/42579908

http://stackoverflow.com/q/51654739
has answer: http://stackoverflow.com/a/51654861
downvote count: 4
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90273613
favorite count: 0
has body: A company decides to give bonus to the employees. A 5% bonus is given to the male worker and 10% to female worker. If the salary of the employee is less than 10000 then the employee gets a 2% extra bonus. Calculate the salary along with bonus that has to be given. My code looks like this: a = input('Enter your name here: ') b = int(input('your salary here: ')) c = input('your gender here (M/F) : ') if b &lt; 10000 and c == 'M': print(str(a) + ' your salary with bonus is ' + str(b * 1.07)) elif b &lt; 10000 and c == 'F': print(str(a) + ' your salary with bonus is ' + str(b * 1.12)) if b &gt;= 10000 and c == 'M': print(str(a) + ' your salary with bonus is '+ str(b * 1.05)) elif b &gt;= 10000 and c=='F': print(str(a) + ' your salary with bonus is '+ str(b * 1.1))
tagged with: python
tagged with: python-3.x
has title: What is the mistake in the given code?
type: UnansweredQuestion
score: -4
type: Question

http://stackoverflow.com/a/51665107
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90320532
has comment: http://stackoverflow.com/comment/90310757
has comment: http://stackoverflow.com/comment/90315039
has body: Seems like you are already using all the tools needed to answer your question. latest_non_empty = None path="C:\Users\\" for f in os.listdir(path): file=path+'\\'+f if (os.stat(file).st_size &gt; 0): if latest_none_empty: if lastest_none_empty[0] &lt; os.stat(file).st_mtime: latest_non_empty_file = (os.stat(file).st_mtime, file) else: latest_non_empty_file = (os.stat(file).st_mtime, file)
has comment: http://stackoverflow.com/comment/90332580
type: Answer
accepted answer of: http://stackoverflow.com/q/51664941
has comment: http://stackoverflow.com/comment/90341296
has comment: http://stackoverflow.com/comment/90315585
has comment: http://stackoverflow.com/comment/90310775
score: 0
answers question: http://stackoverflow.com/q/51664941

http://stackoverflow.com/a/51675900
has comment: http://stackoverflow.com/comment/90379209
accepted answer of: http://stackoverflow.com/q/51672485
type: Answer
answers question: http://stackoverflow.com/q/51672485
upvote count: 1
has body: This should work df[df&gt;df.mean(axis=1).tolist()] = 0 Or if you want to use the mean column df[df&gt;df['Mean'].tolist()] = 0
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/51789147
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51789120
upvote count: 11
has body: That's an example of a variable annotation, which wasn't introduced until Python 3.6. A variable annotation, defined by PEP-526, is distinct from a function annotation. Type hints are just one possible use for either type of annotation.
answers question: http://stackoverflow.com/q/51789120
type: Answer
score: 11

http://stackoverflow.com/comment/90341518
type: QuestionComment
comment on: http://stackoverflow.com/q/51689736
score: 1
type: Comment
has text: You might be looking at the wrong direction. `pre_save` is called AFTER the user changes the value (somewhere in your code `example.save()`, such as [here](https://docs.djangoproject.com/en/2.0/ref/models/instances/#updating-attributes-based-on-existing-fields)) and BEFORE the data reach the database.

http://stackoverflow.com/comment/106678061
comment on: http://stackoverflow.com/a/51710151
has text: @MartijnPieters Don't we need to import `Dict` and `List` from typing and write `Optional[Dict]` and `Optional[List]` instead of `Optional[dict]`...
type: Comment
score: 1
type: AnswerComment

code-generation
tag name: code-generation
tags question: http://stackoverflow.com/q/51681457
tags question: http://stackoverflow.com/q/51746824
type: Tag

http://stackoverflow.com/comment/90404537
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51703420
has text: Thanks. This looks like a simple solution. I tried and got the following error. I'm not very sure why: raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: {'Project Title': 'LS003942_EP - 5 Random Road, Sunny Place, SA 5000'}

http://stackoverflow.com/a/51793259
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90544953
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/51792291
has comment: http://stackoverflow.com/comment/90544357
answers question: http://stackoverflow.com/q/51792291
score: 2
has comment: http://stackoverflow.com/comment/90551331
has comment: http://stackoverflow.com/comment/90544978
has comment: http://stackoverflow.com/comment/90544891
has body: Update: I asked another question about how to vectorize an approach to this question and @Divakar posted an excellent answer which can be applied here: r = np.arange(df.shape[0])[:, None] m = (idx[:,0] &lt;= r) &amp; (idx[:,1] &gt; r) df.mask(~m).dropna(how='all') 0 1 2 1 NaN NaN 22.0 2 NaN 13.0 23.0 6 6.0 NaN NaN 7 7.0 NaN NaN 8 8.0 NaN NaN Old non-vectorized approach: This approach uses the underlying numpy array to create a mask: def foo(a, idx): out = np.zeros(a, dtype=np.bool8) for (i, j), k in zip(idx, np.arange(a[1])): out[i:j, k] = True return out df.mask(~foo(df.shape, idx)).dropna(how='all') Output: 0 1 2 1 NaN NaN 22.0 2 NaN 13.0 23.0 6 6.0 NaN NaN 7 7.0 NaN NaN 8 8.0 NaN NaN

http://stackoverflow.com/comment/90279971
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51654453
has text: DATABASE_URL=postgresql://localhost:5432/database

http://stackoverflow.com/comment/90552771
comment on: http://stackoverflow.com/q/51797718
has text: ¿¿¿ `s(a,b,c)*c` ??? isn't it `s(a,b,c)-c` ???
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90278599
type: QuestionComment
comment on: http://stackoverflow.com/q/51657192
score: 0
has text: in your try block, before forming fullName, print out `row`. I suspect it's not what you expect. Otherwise, simplify your question, provide exact error (w/traceback).
type: Comment

http://stackoverflow.com/comment/90412023
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51724120
type: Comment
has text: But in my case this operation seems not to be necessary.Any reasons why this is a better way?I want to know some deeper level details about this.

http://stackoverflow.com/q/51756672
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51765413
has title: Get the latest FTP folder name in Python
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/8990598
favorite count: 0
has body: I am trying to write a script to get the latest file from the latest sub- directory of FTP server in Python. My problem is I am unable to figure out the latest sub-directory. There are two options available, sub-directories have ctime available. Also in directory name date is mentioned that on which date directory was created. But I do not know how to get the name of the latest directory. I have figured out the following way (hoping for the server side to be sorted by latest ctime). I have done it the following way which will work if first object is the latest directory. import ftplib import os import time ftp = ftplib.FTP('test.rebex.net','demo', 'password') ftp.cwd(str((ftp.nlst())[0])) #if directory is sorted in descending order by date. But is there any way where I will find the exact directory by ctime or by date in directory name ? Thanks a lot guys.
linked to: http://stackoverflow.com/q/44666592
has answer: http://stackoverflow.com/a/51765413
tagged with: python
tagged with: ftp
tagged with: ftplib
score: 1
upvote count: 1

http://stackoverflow.com/comment/90549069
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51779708
type: Comment
has text: how to re-index the date, with start and end date. why i am asking this because panda automatically detect some dates which data has not register and panda remove them...

http://stackoverflow.com/comment/90484388
has text: Could you go to the Data Tab and take a screenshot of what your table looks like?
type: AnswerComment
comment on: http://stackoverflow.com/a/51762291
score: 0
type: Comment

http://stackoverflow.com/q/51704784
tagged with: beautifulsoup
tagged with: python
has answer: http://stackoverflow.com/a/51775606
type: AnsweredQuestion
has title: Unable to find xml tag using Beautiful Soup in a loop
type: Question
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/51775606
has body: I have a block of xml content that varies depending on a code I submit through an API. The fetching process works fine. The xml tags I want to extract vary depending on the code. The function that determines the list of tags also works correctly. I have been successful in extracting information from a block of content in xml, however in a certain report that I fetch there are multiple items in the content block with the same tags I wish to extract. I have split the content into several items by the tag &lt;item&gt; and removed the first index as it is not useful to me. Now I want to search each item by my list of tags (which previously worked fine until I introduced multiple items and looped over them). I have checked that each item i can be 'seen' in the for n in list loop by printing i and it appears correctly. But when it comes to searching the string it doesn't seem to be recognised since printing each var just shows as 'None' (on the note I have confirmed that each i is a string). The terms I am searching are 100% in the content, this process works until I introduce the for i in items loop. def parser(content, report_code ): list = list_type(report_code) items = content.split('&lt;item&gt;') items.pop(0) for i in items: arr = [] for n in list: print i var = BeautifulSoup(i, "xml").find(n) var = str(var).split('&gt;')[1].split('&lt;')[0].strip() print var arr.append(var) return arr
score: 0
answer count: 1
tagged with: parsing

http://stackoverflow.com/comment/90395390
type: QuestionComment
has text: https://pastebin.com/BFHmx0AZ here the log - ikolim
comment on: http://stackoverflow.com/q/51716272
score: 0
type: Comment

http://stackoverflow.com/q/51699746
has answer: http://stackoverflow.com/a/51700257
has body: I'm trying to write an API for my Python app using Falcon WSGI Framework. Usually, my code goes like this: class Main: def __init__(self): self.name = 'Main' def on_post(self, req, resp): data = urlparse.parse_qs(req.stream.read()) x = data['x'][0] y = data['y'][0] z = data['z'][0] result = main(x,y,z) resp.body = json.dumps(result) def main(x,y,z): sum=x+y+z return sum api = falcon.API(middleware=[cors.middleware]) api.add_route('/', Main()) In such case, I can return only a single response. However, I want to display additional info like console output in a Linux shell like view. For this purpose, I would change my main method as given below. def main(x,y,z): yield "X: " + str(x)+"\n" yield "Y: " + str(y)+"\n" yield "Z: " + str(z)+"\n" sum=x+y+z yield "SUM: " + str(sum)+"\n" But resp.body in on_post method above would return just one value. How can I display my desired data in a console output stream like manner?
tagged with: falconframework
has title: HTTP Response Generator using Falcon Python and Gunicorn
tagged with: wsgi
type: UnansweredQuestion
type: Question
tagged with: python
answer count: 1
score: 0

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/51768414
tag name: lemmatization
tags question: http://stackoverflow.com/q/51658153

visual-studio-code
tags question: http://stackoverflow.com/q/51792387
tags question: http://stackoverflow.com/q/51753825
tags question: http://stackoverflow.com/q/51716465
tags question: http://stackoverflow.com/q/51698949
tags question: http://stackoverflow.com/q/51674029
tag name: visual-studio-code
tags question: http://stackoverflow.com/q/51727785
tags question: http://stackoverflow.com/q/51669589
type: Tag

http://stackoverflow.com/comment/90487131
type: Comment
comment on: http://stackoverflow.com/a/51764010
has text: @V.Sel No problem :)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90484070
comment on: http://stackoverflow.com/q/51762528
score: 1
has text: Why do you feed tf.tensor1d() with an array of arrays? Shouldn't it just take [form.value.p, form.value.glu, ...]? I may be completely misunderstanding your code, cause I usually do this in python, but that bit looks odd to me. It looks like you're giving the 1d tensor a 2d data chunk.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51781513
has body: Seems like my driver object management was incorrect. I was creating the driver in the wrong place. Defining the driver above the __init__ method at class definition time created one driver instance that was shared over all instances of my class. Moving the driver object creation inside the _init_ method solved the problem.
score: 0
answers question: http://stackoverflow.com/q/51768181
type: Answer

http://stackoverflow.com/comment/90480948
type: Comment
type: QuestionComment
has text: oh, i was plotting dict on matplotlib. How can i extract predicted values from dict and store them in a string or int. I want to plot test data and predicted values on graph
comment on: http://stackoverflow.com/q/51760801
score: 0

http://stackoverflow.com/a/51798640
score: 0
type: Answer
has body: f = open('my_file.txt', 'r+') my_file_data = f.read() f.close() The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. The read function reads the whole file at once. You can use the following to read the file line by line and store it in a list: f = open('my_file', 'r+') lines = [line for line inf.readlines()] f.close()
answers question: http://stackoverflow.com/q/51795890

http://stackoverflow.com/q/51762848
tagged with: python
tagged with: kivy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51771446
type: Question
has title: Python Kivy. How to change the Label text to the text on the button that have been pressed?
score: 0
answer count: 2
has body: I have some buttons, if I press the button - then the screen changes and on the new screen there is a label that shows the text that was on the button that has been pressed. It does not work when everything looks right. Python from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.lang import Builder from kivy.uix.button import Button class ScreenOne(Screen): pass class ScreenTwo(Screen): def on_pre_enter(self, *args): btn = Button(text = "word is here", on_release =self.pressedFunction) self.ids.container.add_widget(btn) btn1 = Button(text = "another word is here", on_release =self.pressedFunction) self.ids.container.add_widget(btn1) def pressedFunction(self, instance, *args): self.manager.current= "three" screenThree = ScreenThree() text = str(instance.text) screenThree.changing_label(text) class ScreenThree(Screen): def changing_label(self, text): self.ids.my_label.text = text class ScreenManagement(ScreenManager): pass presentation = Builder.load_file("example.kv") class MainApp(App): def build(self): return presentation if __name__ == "__main__": MainApp().run() Kivy ScreenManagement: ScreenOne: ScreenTwo: ScreenThree: &lt;ScreenOne&gt;: BoxLayout: Button: text: "press me" on_release: app.root.current = "two" &lt;ScreenTwo&gt;: name: "two" BoxLayout: id: container &lt;ScreenThree&gt;: name: "three" BoxLayout: id: labelContainer Label: text: "" Output File "example.py", line 28, in changing_label self.ids.my_label.text = text File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__ AttributeError: 'super' object has no attribute '__getattr__'
has answer: http://stackoverflow.com/a/51763268

http://stackoverflow.com/comment/90537920
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51785021
has text: Ok, just to confirm, are you using windows system?
score: 0

http://stackoverflow.com/comment/90426246
comment on: http://stackoverflow.com/a/51732708
type: AnswerComment
has text: Hi @jezrael , I want to perform regressions on the sub df via statmodels. On the sub df I want to save the coefs of the regression into some general df where I want to store them. Do you think it will work via your code? Please, can you explain me the apply? I am a bit lost with apply. THANKS!
score: 0
type: Comment

http://stackoverflow.com/q/51798462
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90554465
has comment: http://stackoverflow.com/comment/90554007
tagged with: floating-point
has body: My question is: Given a float point number, what is the minimal type in numpy in order to hold it? Consider the flowing example: dt = datetime.datetime(2018, 8, 1, 17, 32, 53, 966819) dt_unix = dt.timestamp() print(dt_unix) print(np.float32(dt_unix)) print(np.float64(dt_unix)) print(np.finfo(np.float32).precision) The output is: 1533115973.966819 1533116000.0 1533115973.966819 6 Obviously, np.float32 seems not able to hold it, but how do I know that in previous? After all, the suggested precision is 6. So in general, what is the range of a particular type, e.g. np.float32, and what real precision is that type.
tagged with: numpy
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51811523
has comment: http://stackoverflow.com/comment/90554169
type: AnsweredQuestion
tagged with: types
has comment: http://stackoverflow.com/comment/90554185
has comment: http://stackoverflow.com/comment/90554133
tagged with: precision
favorite count: 0
has title: How do I know what types of float to use?
type: Question
accepted answer: http://stackoverflow.com/a/51811523

http://stackoverflow.com/comment/90398194
comment on: http://stackoverflow.com/a/51718681
score: 0
type: Comment
has text: Actually this worked when I tried it, I knew it was installed on my system because I did this and saw "Python 3.7.0", so I guess my question is, is this new version my default version now? I don't know anything about Python, but it seems that if I have to specify python3 to get the newest version, that it isn't going to be used by default.
type: AnswerComment

http://stackoverflow.com/q/51732475
score: 1
has comment: http://stackoverflow.com/comment/90426186
tagged with: urllib
answer count: 2
has title: How to achieve this python post and get?
downvote count: 0
has answer: http://stackoverflow.com/a/51798622
tagged with: python
has comment: http://stackoverflow.com/comment/90426167
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90426230
type: UnansweredQuestion
has body: I've been trying for hours using requests and urllib. I'm so lost, misunderstood by google too. Some tips, or even anything would be useful. Thank you. Goals: Post country code and phone numbers, then get mobile carrier etc. Problem: Not printing anything. Variable "name" prints out None. def do_ccc(self): #Part of bigger class """Phone Number Scan""" #prefix=input("Phone Number Prefix:") #number=input("Phone Number: ") url=("https://freecarrierlookup.com/index.php") from bs4 import BeautifulSoup import urllib data = {'cc' : "COUNTRY CODE", 'phonenum' : "PHONE NUMBER"}#.encode('ascii') data=json.dump(data,sys.stdout) page=urllib.request.urlopen(url, data) soup=BeautifulSoup(page, 'html.parser') name=soup.find('div', attrs={'class': 'col-sm-6 col-md-8'}) #^^^# Test(should print phone number) print(name)
upvote count: 1
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/90426398
has answer: http://stackoverflow.com/a/51732817

http://stackoverflow.com/comment/90296455
has text: Please provide the data that created this frame, or else it's too much work to create it again.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51666771

http://stackoverflow.com/q/51641854
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90248486
score: 0
tagged with: shiny
type: UnansweredQuestion
has body: I'm trying to run Task1.py via Shiny framework of R in Task1.r. Python code is successfully running. But it is giving me error in some line. Task1.py: ... ... params.override(...) //This line is running fine and giving desired output params.process() //This line is giving error that file doesn't exists ... ... Task1.r: observeEvent(input$action_retrain_1,{ ... ... py_run_file("D:/..../Task1.py") ... ... }) Previously asked question that I'm following to resolve error: How to open CSV file in R when R says "no such file or directory"? Effort to resolve error: I used following two lines before py_run_file(), but it is still giving me same error. What should I do? What am I missing? setwd('D:/PycharmProjects/.../sample') myfile = read.csv('D:/PycharmProjects/.../sample/parameters.yaml') Error: Warning: Error in py_run_file_impl: SystemExit: [Errno 2] No such file or directory: 'D:/PycharmProjects/.../sample/parameters.yaml' 76: <Anonymous> parameters.yaml file exists in folder named sample, but I don't know why it is giving me error. I'm running this in Pycharm, there it works well. But it is giving me problem in R. Anyone know how can I resolve this issue?
tagged with: python
linked to: http://stackoverflow.com/q/5568847
tagged with: shiny-server
answer count: 0
tagged with: reticulate
has title: Error in py_run_file_impl: System Exit: No such file or directory
type: Question
has comment: http://stackoverflow.com/comment/90248657

http://stackoverflow.com/comment/90401618
has text: `list(tree[input()].values())`, it will return list of values in last set.
comment on: http://stackoverflow.com/q/51720345
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51749919
answers question: http://stackoverflow.com/q/51749886
has body: You can use .*?: import re contents = [re.findall('"(.*?)"', i.strip('\n'))[0] for i in open('filename.txt')] Output: ['hello', 'Hello! How are you doing today', 'I am doing good thank you', 'Good to know']
upvote count: 2
type: Answer
score: 1
downvote count: 1

http://stackoverflow.com/comment/90434442
comment on: http://stackoverflow.com/a/51736750
score: 1
has text: AMAZING. Understood the explanation completely. Thank you very much sir!
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51768103
has body: I have this dataframe: identifier_1 measure Value identifier_2 abc height 12 oii abc weight 122 oii abc eye_color green Oii cde height 43 lkj cde weight 123 lkj cde eye_color blue lkj fgh height 32 mnb fgh weight 125 mnb fgh eye_color black mnb I want to transform the column "measure" into a table header, and the corresponding cell in column value, to be its value, like: identifier_1 height weight eye_color identifier_2 abc 12 122 green oii cde 43 123 blue lkj fgh 32 125 black mnb I tried the pivot function in pandas but couldn't reach the required result.
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51768308
has comment: http://stackoverflow.com/comment/90495265
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90494938
type: AnsweredQuestion
score: 2
has title: convert column to table header in pandas dataframe
accepted answer: http://stackoverflow.com/a/51768308
type: Question
downvote count: 0
tagged with: dataframe

http://stackoverflow.com/comment/90504285
comment on: http://stackoverflow.com/a/51737571
type: Comment
has text: This has been submitted and we'll be working on providing a patch.
score: 1
type: AnswerComment

http://stackoverflow.com/q/51710987
has comment: http://stackoverflow.com/comment/90383586
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51711151
tagged with: dataframe
has body: I have two data frames with many columns, D1 (with columns: V1_1, V1_2....) and D2 (with columns: V2_1, V2_2...). But I'm not interested in all the columns, I only want the columns that other third data frame indicates. This third data frame has two columns, the first one is the name of a data frame, and the second one is a list with the name of some variables. Something like that: DataFrame | Vbles D1 | ['V1_1','V1_27','V1_30'] D2 | ['V2_2','V2_3'] Suposse that its name is var_sel and the index is 'DataFrame'. Now I want to extract from D1 the variables from var_sel[Vbles][var_sel.index=='D1'], but I don't know how. I have tried doing: col=var_sel[Vbles][var_sel.index=='D1'] col= col[D1] And I obtain: "['V1_1','V1_27','V1_30']" Now, I want that columns from D1, so I try: D1[col] and D1col too. But I get an Error... Could someone help me, please? Thanks.
has title: select some columns in a pandas dataframe
answer count: 2
has answer: http://stackoverflow.com/a/51711152
accepted answer: http://stackoverflow.com/a/51711152
score: 0
possible better answer: http://stackoverflow.com/a/51711151
tagged with: pandas
tagged with: python
tagged with: select
has comment: http://stackoverflow.com/comment/90383349

http://stackoverflow.com/comment/90466896
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51753074
type: AnswerComment
has text: @ThierryLathuille let me help you what answer would you expect from `aaaabbbbaaabbbaabb`????

http://stackoverflow.com/q/51753668
duplicate of: http://stackoverflow.com/q/12943819
has comment: http://stackoverflow.com/comment/90468008
has comment: http://stackoverflow.com/comment/136986567
tagged with: formatting
tagged with: output
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51755096
tagged with: http://stackoverflow.com/tag/json
score: -1
has comment: http://stackoverflow.com/comment/90467392
tagged with: pprint
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
has body: # -*- coding: utf-8 -*- import json from pprint import pprint drink_list = [23,601,633,673,607,662,6622,6014,6104,615,038,606,607,627,6094] filename = (r'C:\Users\desktop\pizza\123template.json') with open(filename, 'r') as f: data = f.read() try: template = json.loads(data) except Exception: # this file can also be here print('json exception') raise for output in drink_list: print(output) temp = template.copy() temp["meta"]["sodanumber"] = output with open(r'C:\Users\desktop\pizza\123\{}.json'.format(output, indent=40), 'w', encoding='cp1252') as f: data = json.dumps(temp) f.write(data) # pprint.pprint(temp, width=60) IndentationError: unindent does not match any outer indentation level. But I think it's more than a simple indention. I can get my console to change formatting, but need the formatting to be changed in the actual output file. But where would I add my additional formatting to my "with open" line? Have been reading material for 4 hours on this, and simple examples, but does the pprint do most of the work? Current output is tons of work-wrapped text. Output needs to look like below. How can I get it to look like this?: { "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" }, "documents": [ { "code": "Checkout2", "name": "Printer 2", "port": "COM2", "type": "LABEL", Current Output: { "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{ "code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL",
type: UnansweredQuestion
has title: Python formatting my json output
tagged with: python

http://stackoverflow.com/comment/90453229
score: 1
has text: Which problem are you having writing this code yourself? It seems like most of this should be fairly trivial to convert to Python code (if you understand Python, that is - if you don't, you can find plenty of tutorials and code samples online to help with that). If you don't know what a specific part of this should look like, asking about that will probably lead to a question that's more useful for others and where you'll get answers that focus more on explaining the parts you don't understand (instead of just getting "here is the code" answers).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51746218

http://stackoverflow.com/q/51757993
has comment: http://stackoverflow.com/comment/90497882
tagged with: distribution
upvote count: 0
type: UnansweredQuestion
downvote count: 1
type: Question
score: -1
has title: Code a probability distribution function within a range, i.e., high and lows (PYTHON)
has comment: http://stackoverflow.com/comment/90475531
has answer: http://stackoverflow.com/a/51758108
has comment: http://stackoverflow.com/comment/90475545
answer count: 1
favorite count: 0
tagged with: exponential
has body: I am new in Python and I have been looking how to solve the following issue. I want to code a function that will receive the inputs: minimum, maximum, scale(mean) and size for an exponential distribution. For example: FunctionExponentialPDF(minimum=0.05, maximum=0.30, scale=0.2, size=1000). Result: an exponential distribution, with a minimum value of 0.05, a maximum of 0.30, it has an average of 0.20 and it contains 1000 data points. How can I extend the code for other probability distribution functions, e.g. normal, poisson, etc.? Thank you all!
tagged with: python
has comment: http://stackoverflow.com/comment/90475780

http://stackoverflow.com/comment/90365210
comment on: http://stackoverflow.com/a/51701800
has text: @NabihBawazir - I think `ascending=False` is missing.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90405898
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51718283
has text: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/177548/discussion-on-answer-by-jerin-peter-george-how-change-json-response-result-in-po).
score: 0

http://stackoverflow.com/q/51640652
has comment: http://stackoverflow.com/comment/90245700
accepted answer: http://stackoverflow.com/a/51640713
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51640719
has title: list indices must be integers, not str -Python
possible better answer: http://stackoverflow.com/a/51640719
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51640713
tagged with: http://stackoverflow.com/tag/json
has body: I'm trying to modify this python function to monitor Lambda functions in Zabbix (automatically create items/triggers for every lambda function) https://github.com/omni-lchen/zabbix-cloudwatch/blob/master/awsLLD.py#L182 import re import json from optparse import OptionParser from awsAccount import awsAccount from awsConnection import awsConnection def config_parser(): parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0") parser.add_option("-a", "--account", dest="accountname", help="account name", metavar="ACCOUNT") parser.add_option("-r", "--region", dest="region", help="region", metavar="REGION") parser.add_option("-q", "--query", dest="query", help="specify a query", metavar="QUERY") parser.add_option("-c", "--component", dest="component", help="component name", metavar="COMPONENT") return parser def get(a, r): account = a aws_account = awsAccount(account) aws_access_key_id = aws_account._aws_access_key_id aws_secret_access_key = aws_account._aws_secret_access_key aws_region = r #component = c # Init LLD Data lldlist = [] llddata = {"data":lldlist} # Connect to Lambda service conn = awsConnection() conn.lambdaConnect(aws_region, aws_access_key_id, aws_secret_access_key) lambdaConn = conn._aws_connection # Save Lambda function results in a list functionResultsList = [] # Save topic names in a list tdata = [] # Get a list of Lambda Functions functionResults = lambdaConn.list_functions() functionResultsList.append(functionResults) print functionResults nextmarker = functionResults['Functions']['NextMarker'] if __name__ == '__main__': parser = config_parser() (options, args) = parser.parse_args() account = options.accountname region = options.region query = options.query get(account,region) print functionResults gives these results (2 functions) {u'Functions': [{u'Description': u'', u'LastModified': u'2018-08-01T18:50:04.214+0000', u'ConfigurationId': u'e97b805a-c947-4c56-9a2e-5bef3c4cc6c5', u'CodeSize': 222, u'FunctionARN': u'arn:aws:lambda:eu-we…
type: Question

http://stackoverflow.com/comment/90287936
has text: The rewrite version has reconnection logic for connecting to discord again if you lose connection: https://discordpy.readthedocs.io/en/rewrite/migrating.html#connection-improvements
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51662110

http://stackoverflow.com/comment/90524529
type: QuestionComment
has text: use requests - http://docs.python-requests.org/en/master
comment on: http://stackoverflow.com/q/51770883
score: 0
type: Comment

http://stackoverflow.com/q/51776923
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/51777038
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90512226
has comment: http://stackoverflow.com/comment/90512317
tagged with: dataframe
downvote count: 1
has title: Cleaning a dataframe in function and returning the dataframe in python
type: Question
answer count: 2
tagged with: function
upvote count: 0
has body: Hello i am new to Python and i have been trying to write a function to clean a text data which is stored in a dataframe. def clean(dataset): dataset = dataset.apply(lambda x: " ".join(x.lower() for x in x.split())) dataset = dataset.str.replace('[^\w\s]','') from nltk.corpus import stopwords stop = stopwords.words('english') dataset = dataset.apply(lambda x: " ".join(x for x in x.split() if x not in stop)) so when i call the above function like " clean(df['comments'] " i want the comments column with dataframe to be replaced with the cleaned text from the function. TIA.
score: -1
has answer: http://stackoverflow.com/a/51777032
tagged with: series

http://stackoverflow.com/q/51794274
has body: I'm trying to implement the idea I have suggested here, for Cauchy product of multivariate finite power series (i.e. polynomials) represented as NumPy ndarrays. numpy.convolve does the job for 1D arrays, respectively. But to my best knowledge there is no implementations of convolution for arbitrary dimensional arrays. In the above link, I have suggested the equation: for convolution of two n dimensional arrays Phi of shape P=[p1,...,pn] and Psi of the shape Q=[q1,...,qn], where: omegas are the elements of n dimensional array Omega of the shape O=P+Q-1 &lt;A,B&gt;_F is the generalization of Frobenius inner product for arbitrary dimensional arrays A and B of the same shape A^F is A flipped in all n directions {A}_[k1,...,kn] is a slice of A starting from [0,...,0] to [k1,...,kn] Psi' is Psi extended with zeros to have the shape O as defined above I tried implementing the above functions one by one: import numpy as np def crop(A,D1,D2): return A[tuple(slice(D1[i], D2[i]) for i in range(D1.shape[0]))] as was suggested here, slices/crops A from D1 to D2, def sumall(A): sum1=A for k in range(A.ndim): sum1 = np.sum(sum1,axis=0) return sum1 is a generalization of numpy.sum for multidimensional ndarrays, def flipall(A): A1=A for k in range(A.ndim): A1=np.flip(A1,k) return A1 flips A is all existing axises, and finally def conv(A,B,K): D0=np.zeros(K.shape,dtype=K.dtype) return sumall(np.multiply(crop(A,np.maximum(D0,np.minimum(A.shape,K-B.shape)) \ ,np.minimum(A.shape,K)), \ flipall(crop(B,np.maximum(D0,np.minimum(B.shape,K-A.shape)) \ ,np.minimum(B.shape,K))))) where K=[k1,...,kn] and for all 0&lt;=kj&lt;=oj, is a modified version of formula above which only calculate the non-zero multiplications to be more efficient. Now I'm trying to populate the Omega array using fromfunction or meshgrid in combination to vectorize as suggested here, but I have failed so far. Now my questions in prioritized order are: how can I implement the final step and populate the final array in an e…
tagged with: python
has comment: http://stackoverflow.com/comment/90555126
linked to: http://stackoverflow.com/q/51782224
has comment: http://stackoverflow.com/comment/90594578
has comment: http://stackoverflow.com/comment/90554307
answer count: 0
has comment: http://stackoverflow.com/comment/90594706
score: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51788492
linked to: http://stackoverflow.com/q/51821540
has comment: http://stackoverflow.com/comment/90589412
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90597200
has comment: http://stackoverflow.com/comment/90555643
has comment: http://stackoverflow.com/comment/90594755
tagged with: arrays
has title: Convolution of NumPy arrays of arbitrary dimension for Cauchy product of multivariate power series
tagged with: polynomials
has comment: http://stackoverflow.com/comment/90594396
tagged with: convolution

http://stackoverflow.com/comment/90326783
comment on: http://stackoverflow.com/q/51681907
has text: Why can you not just warp this function in another function and call that wrapper when you need it and it won't affect the legacy code?
type: Comment
score: 6
type: QuestionComment

http://stackoverflow.com/q/51699140
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/51699203
accepted answer: http://stackoverflow.com/a/51699203
has title: Consolidating redundant parameters in requests
answer count: 1
downvote count: 0
favorite count: 0
tagged with: arguments
has body: I'm using the requests module in my code (obviously to do requests), and my code is quickly getting out of hand because of redundant parameters that I need to include for each request: def one(url, data, headers, cert): ... return requests.post(url, json=data, headers=headers, verify=cert) def two(otherurl, otherheaders, cert): ... response = requests.get(otherurl, headers=otherheaders, verify=cert).json() Is there a way to tell every request to use verify=cert without having to include it within every request statement? I'm thinking session() should be able to do this, although I have no idea how to use it. I'm just trying to minimize the repeating of things that maybe could be set globally within my script. Maybe this is not possible or how it actually works? thanks in advance.
upvote count: 1
tagged with: python
tagged with: request
tagged with: parameter-passing

http://stackoverflow.com/q/51753220
answer count: 3
has answer: http://stackoverflow.com/a/51755998
tagged with: readfile
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51753670
has body: Date,Time,Ref,Sen,ATN,Flow,PCB temp,Status,Battery,BC 2015/04/23,12:30:00,779581,908043,"-15,254",49,31,0,100, 2015/04/23,12:35:00,778715,907084,"-15,259",49,31,0,100,-127 2015/04/23,12:40:00,778299,906419,"-15,239",49,32,0,100,461 (...) Hi, I have an ascii file like the one above where I am trying to replace the commas for semicolon. This is the code I am using: filein = open('Prueba1.txt') fileout = open('Fin.txt', 'wt') for line in filein: if line.startswith('20'): fileout.write( line.replace(',', ';') ) filein.close() fileout.close() The problem is that now I want to maintain the commas for the 5th column and also take of the quotation marks. Any ideas?
tagged with: python
score: 2
downvote count: 0
has title: Replace commas except those in quotation marks
type: Question
has answer: http://stackoverflow.com/a/51753368
tagged with: replace
upvote count: 2

http://stackoverflow.com/q/51641518
has body: I have two data sets, group A has hundreds numbers and group B have eight numbers. I want to find another eight numbers in group A that are closest to the four numbers in group B. Now I take one number from group B each time and compared it with group A. Is there other better way to do this? A = [762.859793, 763.544183, 764.272883, 766.190053, 767.108693, 767.123893, 768.933893, 770.619013, 771.375173, 771.522083, 774.9478730000001, 775.138843, 775.463863, 776.332693, 776.466303, 777.650083, 778.3751129999999, 781.922783, 782.592033, 784.224423, 784.779903, 785.2743429999999, 787.098133, 787.8258030000001, 787.8593030000001, 788.194393, 790.939383, 791.379753, 793.572803, 796.093073, 796.720693, 796.852473, 798.519643, 800.145803, 800.758723, 801.239613, 801.332453, 801.819333, 805.290823, 806.404353, 807.995663, 808.683403, 810.0645030000001, 810.695673, 810.7933929999999, 811.150203, 814.270803, 814.706783, 815.6527629999999, 819.127253, 819.820733, 821.030753, 821.166193, 823.111683, 824.637013, 826.707083, 826.997243, 827.441463, 828.529713, 830.364193, 831.241203, 831.2571929999999, 832.635243, 832.9749730000001, 834.222713, 837.932063, 838.250483, 838.695363, 840.0615730000001, 841.246143, 841.300043, 841.5062230000001, 844.7620730000001, 845.1879230000001, 846.261283, 847.139523, 849.0279429999999, 850.5646929999999, 850.726553, 851.8736529999999, 853.9559830000001, 854.171933, 857.674983, 858.035633, 858.327443, 858.9393230000001, 859.365103, 860.0646929999999, 861.035573, 861.496883, 864.127743, 866.558833, 867.0207429999999, 868.135673, 869.329093, 870.5860529999999, 871.1149230000001, 871.691343, 872.156483, 875.2681230000001, 875.921803, 876.6624029999999, 879.2358929999999, 879.7697029999999, 880.6190730000001, 882.563473, 883.1651529999999, 883.6522130000001, 884.311393, 886.585383, 888.0967929999999, 889.6549630000001, 890.564143, 891.0488230000001, 892.887933, 893.3944630000001, 896.817743, 897.9441429999999, 898.577573, 898.681813, 900.280573, 901.3…
answer count: 4
tagged with: closest
upvote count: 1
has answer: http://stackoverflow.com/a/51641669
has answer: http://stackoverflow.com/a/51641568
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/90247432
possible better answer: http://stackoverflow.com/a/51641723
type: Question
has answer: http://stackoverflow.com/a/51641723
tagged with: arrays
accepted answer: http://stackoverflow.com/a/51641568
downvote count: 0
has answer: http://stackoverflow.com/a/51641916
favorite count: 0
has title: Find the closest numbers in a data set based on target data set
tagged with: python

http://stackoverflow.com/q/51721618
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: constraints
has comment: http://stackoverflow.com/comment/90406756
upvote count: 2
has answer: http://stackoverflow.com/a/51757217
tagged with: pulp
type: Question
has body: Suppose I have a set of decision variables in my PuLP definition: vals = [-v for k, v in (DecisionVars.items())] And I want to create a constraint related to the absolute value of the sum of all constraints. So something like: for i in range(len(DecisionVars)): prob += lpSum(abs(vals[:i+1])) &lt;= some_limit, "Absolute constraint" But I cant seem to apply the abs() operator to my constraints? UPDATE Ok, if I make use of the information in this post sum of absolute values constraint in semi definite programming then my question can be formulated differently. I am now trying to evaluate: abs(x1) + abs(x2) + abs(x3) &lt;= some_limit As pointed out in the link above, the answer might be to create a 1-norm of the vector x (where x is the vector of decision variables as above). I can see that numpy has numpy.linalg.norm but I cannot see how this can recursively create my set of constraints in PuLP. I'm struggling to create the correct syntax using lpSum.
answer count: 2
accepted answer: http://stackoverflow.com/a/51757217
downvote count: 0
linked to: http://stackoverflow.com/q/29795632
favorite count: 0
possible better answer: http://stackoverflow.com/a/54266949
has title: Python Pulp absolute constraints
has comment: http://stackoverflow.com/comment/90405974
has answer: http://stackoverflow.com/a/54266949

http://stackoverflow.com/q/51752666
upvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: output
tagged with: python
has title: change font in python output
has comment: http://stackoverflow.com/comment/90466772
downvote count: 0
has comment: http://stackoverflow.com/comment/90465261
score: 1
has body: I'm starting to code in Python and I just bought a bluetooth printer, I connected it on my raspberry pi and wrote a code to print things on it. I would like to know if it is possible to change the font family and size for example? Here follows the code: #! /usr/bin/python import serial from time import sleep bluetoothSerial = serial.Serial("/dev/rfcomm0", baudrate=9600) testS = "Raspberry-PI Project \nPrinter Test" testV = input() bluetoothSerial.write(bytes(testS, 'UTF-8')) bluetoothSerial.write(bytes(testV, 'UTF-8'))
type: Question
tagged with: printers
has comment: http://stackoverflow.com/comment/90467132

http://stackoverflow.com/comment/90434259
type: AnswerComment
comment on: http://stackoverflow.com/a/51736829
type: Comment
has text: This is also working but it was OK to convert to pandas and return it back. Thx
score: 1

http://stackoverflow.com/q/51650395
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51657487
has title: How to scrape from a span subclass using scrapy
tagged with: scrapy
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51657487
score: 0
has answer: http://stackoverflow.com/a/51650940
accepted answer: http://stackoverflow.com/a/51650940
tagged with: http://stackoverflow.com/tag/html
has body: &lt;span class="price-box"&gt; &lt;span class="price"&gt;&lt;span data-currency-iso="PKR"&gt;Rs.&lt;/span&gt; &lt;span dir="ltr" data-price="16999"&gt;&amp;nbsp;16,999&lt;/span&gt; &lt;/span&gt; &lt;span class="price -old "&gt;&lt;span data-currency-iso="PKR"&gt;Rs.&lt;/span&gt; &lt;span dir="ltr" data-price="50000"&gt;&amp;nbsp;50,000&lt;/span&gt; &lt;/span&gt; &lt;/span&gt; Hello. I need some help in extracting the "data-price with "span dir = ""ltr"". I cannot determine how to extract it using scrapy.
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/90432769
comment on: http://stackoverflow.com/a/51735938
type: AnswerComment
score: 0
type: Comment
has text: I am hoping to collect as much data as possible before performing anything! However, thank you for guiding me in some direction! I appreciate it.

http://stackoverflow.com/comment/90303443
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51670148
has text: Wat did you expect?

http://stackoverflow.com/comment/90510992
comment on: http://stackoverflow.com/a/51776233
has text: Thanks @Vlad, this worked. This is like the linux style wildcards
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51797550
has comment: http://stackoverflow.com/comment/90554297
has comment: http://stackoverflow.com/comment/90554055
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90554006
has comment: http://stackoverflow.com/comment/90554622
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51795743
answers question: http://stackoverflow.com/q/51795743
type: Answer
has body: As per the your question the website https://www.energisa.com.br/Paginas/login.aspx the dropdown menu is not with in a Select tag, so Select class won't work here. Once the url is accessed, you need to induce WebDriverWait for the desired element to be clickable and you can use the following solution: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.energisa.com.br/Paginas/login.aspx") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[@class='estado']/div[@class='select2-container' and @id='s2id_ddlEstado']"))).click() driver.find_element_by_xpath("//ul[@class='select2-results' and @id='select2-results-1']//li/div[normalize-space()='MG']").click()

http://stackoverflow.com/a/51795015
downvote count: 0
has comment: http://stackoverflow.com/comment/90547745
has comment: http://stackoverflow.com/comment/90547658
type: Answer
upvote count: 3
has body: Here's a simple way to plot implicit equations by using numpy+matplotlib: import matplotlib.pyplot from numpy import arange, meshgrid, sqrt delta = 0.025 x, y = meshgrid( arange(0, 10, delta), arange(0, 10, delta) ) matplotlib.pyplot.contour( x, y, sqrt((-6 - x) ** 2 + (4 - y) ** 2) - sqrt((1 - x) ** 2 + y ** 2) - 5, [0] ) matplotlib.pyplot.show() Output: This method is really handy to analize closed forms, for instance, a circle of radius 3 would look like: matplotlib.pyplot.contour( x, y, x**2+y**2-9, [0] )
score: 3
accepted answer of: http://stackoverflow.com/q/51794943
answers question: http://stackoverflow.com/q/51794943
type: AcceptedAnswer

http://stackoverflow.com/q/51771039
type: UnansweredQuestion
upvote count: 7
has title: Error Compiling Tensorflow From Source - No module named 'keras_applications'
downvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52110645
has comment: http://stackoverflow.com/comment/90502234
has comment: http://stackoverflow.com/comment/90508323
tagged with: compilation
score: 6
tagged with: bazel
has body: I am attempting to build tensorflow from source with MKL optimizations on an Intel CPU setup. I have followed the official instructions here up until the command bazel build --config=mkl --config=opt //tensorflow/tools/pip_package:build_pip_package. Unfortunately, the compilation runs for some period of time and then fails. I'd appreciate any help with this matter. Updated Output log (using bazel --verbose_failures): ERROR: /home/jok/build/tensorflow/tensorflow/BUILD:584:1: Executing genrule //tensorflow:tensorflow_python_api_gen failed (Exit 1): bash failed: error executing command (cd /home/jok/.cache/bazel/_bazel_jok120/737f8d6dbadde71050b1e0783c31ea62/execroot/org_tensorflow &amp;&amp; \ exec env - \ LD_LIBRARY_PATH=LD_LIBRARY_PATH:/usr/local/cuda-9.0/lib64/:/usr/local/cuda-9.0/extras/CUPTI/lib64 \ PATH=/home/jok/.conda/envs/tf_mkl/bin:/home/jok/bin:/opt/anaconda3/bin:/usr/local/bin:/bin:/usr/bin:/snap/bin:/home/jok/bin \ /bin/bash -c 'source external/bazel_tools/tools/genrule/genrule-setup.sh; bazel-out/host/bin/tensorflow/create_tensorflow.python_api --root_init_template=tensorflow/api_template.__init__.py --apidir=bazel-out/host/genfiles/tensorflow --apiname=tensorflow --apiversion=1 --package=tensorflow.python --output_package=tensorflow bazel-out/host/genfiles/tensorflow/__init__.py bazel-out/host/genfiles/tensorflow/app/__init__.py bazel-out/host/genfiles/tensorflow/bitwise/__init__.py bazel-out/host/genfiles/tensorflow/compat/__init__.py bazel-out/host/genfiles/tensorflow/data/__init__.py bazel-out/host/genfiles/tensorflow/debugging/__init__.py bazel-out/host/genfiles/tensorflow/distributions/__init__.py bazel-out/host/genfiles/tensorflow/dtypes/__init__.py bazel-out/host/genfiles/tensorflow/errors/__init__.py bazel-out/host/genfiles/tensorflow/feature_column/__init__.py bazel-out/host/genfiles/tensorflow/gfile/__init__.py bazel-out/host/genfiles/tensorflow/graph_util/__init__.py bazel-out/host/genfiles/tensorflow/image/__init__.py bazel-out/host/genfiles…
has answer: http://stackoverflow.com/a/51774943
answer count: 2
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51776922
has comment: http://stackoverflow.com/comment/90518196
downvote count: 0
answer count: 0
type: Question
score: 3
upvote count: 3
has body: I have a CNN that I made using character embedding on my windows 10 machine using python 3.6 and keras 2.2.0. I put that same version on my mac, and whether I use python 2.7 or 3.6, I get an embedding error. My embedding layer uses an input dim of 101, which is the size of my weights matrix; I also use zero masking. Everything works perfectly within windows, but on my mac, when it gets to a character that is indexed at 101, I get the following error: InvalidArgumentError: indices[26,6] = 101 is not in [0, 101) Any ideas what is going on, and what I can do about it? more details: here is info about the weights matrix and how I use it weights.shape = (101,101) inputs=L.Input(shape=(length,)) ` embedding=L.Embedding(input_dim=weights.shape[0], output_dim=weights.shape[1], input_length=length, weights=[weights], mask_zero=True,trainable=False)(inputs) The error: InvalidArgumentError: indices[31,60] = 101 is not in [0, 101) [[Node: embedding_2/embedding_lookup = GatherV2[Taxis=DT_INT32, Tindices=DT_INT32, Tparams=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_2/embeddings/read, embedding_2/Cast, embedding_2/embedding_lookup/axis)]]
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90525021
has title: InvalidArgumentError in Keras embedding; works in Python3.6 on Windows, not on Mac

http://stackoverflow.com/q/51715923
has comment: http://stackoverflow.com/comment/90644646
answer count: 0
has body: Has there been work in featuretools (or an additional Python package) that would integrate it with a common ML library, such as sklearn? E.g., it would be nice to test a feature for its predictive power, and if it's high enough, generate more features like it (e.g., use the same initial variable). In other words, can the process of generating new features be guided by their predictive power?
tagged with: scikit-learn
favorite count: 0
has title: sklearn and featuretools integration?
tagged with: featuretools
type: Question
tagged with: python
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91103289
type: UnansweredQuestion

http://stackoverflow.com/comment/90308015
score: 2
has text: Full traceback where?
comment on: http://stackoverflow.com/q/51672709
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90274384
type: QuestionComment
comment on: http://stackoverflow.com/q/51655285
score: 1
has text: plase post the full error traceback formatted, it is likely to show the line where the error comes from
type: Comment

http://stackoverflow.com/q/51723000
downvote count: 0
tagged with: drop-down-menu
has comment: http://stackoverflow.com/comment/90409470
answer count: 3
has answer: http://stackoverflow.com/a/51725219
has comment: http://stackoverflow.com/comment/90406873
tagged with: python
has body: I'm trying to scrape this website using Python and Selenium, it requires you to select a date from drop-down box then click search to view the planning applications. URL: https://services.wiltshire.gov.uk/PlanningGIS/LLPG/WeeklyList. I have the code working to select the first index of the drop-down box and press search. How would I open multiple windows for all the date options in the drop-down box or go through them one by one so I can scrape it? from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome('/Users/weaabduljamac/Downloads/chromedriver', chrome_options=options) url = 'https://services.wiltshire.gov.uk/PlanningGIS/LLPG/WeeklyList' driver.get(url) select = Select(driver.find_element_by_xpath('//*[@id="selWeek"]')) select.select_by_index(1) button = driver.find_element_by_id('csbtnSearch') button.click() app_numbers = driver.find_element_by_xpath('//*[@id="form1"]/table/tbody/tr[1]/td[1]/a').text print(app_numbers) Drop-down box HTML: Week commencing Monday 30 July 2018 Week commencing Monday 23 July 2018 Week commencing Monday 16 July 2018 Week commencing Monday 9 July 2018 Week commencing Monday 2 July 2018 Week commencing Monday 25 June 2018 Week commencing Monday 18 June 2018 Week commencing Monday 11 June 2018 Week commencing Monday 4 June 2018 Week commencing Monday 28 May 2018
linked to: http://stackoverflow.com/q/17325629
favorite count: 0
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/51723049
has answer: http://stackoverflow.com/a/51723482
tagged with: selenium
upvote count: 7
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/51725219
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51723049
score: 7
has title: How to open the option items of a select tag (dropdown) in different tabs/windows?
type: Question

http://stackoverflow.com/q/51752861
type: Question
has body: I seem to be having trouble with running a python app on my shiny server with rPython. I set my python sys path, Sys.setenv(PATH = paste("/Users/timmcwilliams/anaconda2/bin/", Sys.getenv("PATH"),sep=":")) Then I checked if it worked with, system("python --version") Python 2.7.14 :: Anaconda, Inc. Finally, I also check my PATH, Sys.getenv("PATH") [1] "/Users/timmcwilliams/anaconda2/bin/:/Users/timmcwilliams/anaconda2/bin/:/Users/timmcwilliams/anaconda2/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin" So, I figured it worked correctly. But it seems to not have worked. runApp('app') Listening on http://127.0.0.1:4062 Warning: Error in python.exec: No module named pandas Stack trace (innermost first): 39: python.exec 38: python.load 37: server [/Users/timmcwilliams/Code/Scripts/search-microwave/app/server.R#10] 1: runApp Error in python.exec(code, get.exception) : No module named pandas But I have pandas installed. I am really not sure why this is happening. Both python versions are the same 2.7.14 and I am positive I have Pandas installed because I use it on daily.
tagged with: http://stackoverflow.com/tag/r
score: 0
has comment: http://stackoverflow.com/comment/90465606
tagged with: shiny
tagged with: pandas
tagged with: rpython
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90468671
has title: rPython can't find Pandas

http://stackoverflow.com/comment/90344948
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51679237
has text: Here's an example: https://gist.github.com/hoffrocket/8050711
type: Comment

http://stackoverflow.com/comment/90343686
has text: What is `tmp_t`? How do you define it?
type: QuestionComment
comment on: http://stackoverflow.com/q/51690950
type: Comment
score: 0

http://stackoverflow.com/comment/90276232
score: 0
has text: What is `GeneralData`? Is it a pandas dataframe?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51656264

http://stackoverflow.com/q/51771003
tagged with: python
score: -1
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51771096
type: Question
has title: Algorithm about sum of powers
has body: I'm working on the question shown below, part 2. However when I implement it in python, it fails with "RecursionError: maximum recursion depth exceeded". Here's my algorithm: import math def sumofpowers2(x): count = 1 if math.isclose(x ** count,0,rel_tol=0.001): return 0 count += 1 return 1 + x * sumofpowers2(x) print(sumofpowers2(0.8)) Edited.
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90500776
answer count: 2
has answer: http://stackoverflow.com/a/51771421
favorite count: 0
has comment: http://stackoverflow.com/comment/90501042
type: UnansweredQuestion

http://stackoverflow.com/comment/90303046
comment on: http://stackoverflow.com/a/51670032
has text: @Al. you're welcome. And you very certainly want to read this: https://nedbatchelder.com/text/names.html
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51673472
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90312528
has comment: http://stackoverflow.com/comment/90312390
tagged with: python
type: AnsweredQuestion
score: 3
has body: So I have a for loop that goes through data frame columns starting at 2: for col in basis.columns[2:]: I want to turn it into an enumerate for loop. Kinda like this: for col, x in enumerate(basis): So that I can access the next values in the loop. (not sure if this is the best way to do it, but that's what I think works lol) The thing is- I want to start the enumerate at the second column (The 2: part) like in the first example. I'm not really sure how to do that :/ Any help would be really helpful! Thanks
upvote count: 3
has comment: http://stackoverflow.com/comment/90312550
type: Question
has answer: http://stackoverflow.com/a/51673531
accepted answer: http://stackoverflow.com/a/51673531
has title: Is there a way to use enumerate starting at a certain column?
has comment: http://stackoverflow.com/comment/90312448
tagged with: pandas
has comment: http://stackoverflow.com/comment/90312186

http://stackoverflow.com/comment/90391722
comment on: http://stackoverflow.com/q/51715077
has text: Then write your own `defaultdict` equivalent; you can see the existing API [in the docs](https://docs.python.org/3/library/collections.html#collections.defaultdict), and there's no `.magic`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51710164
downvote count: 0
has body: The Django ORM aims to construct database queries. As a result, you can only query on what a database "knows". Methods, properties, or attributes you added yourself are unknown to the database. The .order_by thus has no effect, since you "patched" the objects in the instances queryset. If you however call an instances.order_by you construct a new queryset. This queryset takes the context of the parent, and thus represents a (slightly) modified query, but again, a query. Whether the old queryset is already evaluated or patched, is of no importance. Furthermore even if there was a column foo, it would not help, since the instance.order_by does not order the instance queryset, it constructs a new one, one that looks approximately like the old one, except that the rows are ordered. You thus will have to sort in Python now. You can for example construct a list of ordered elements with sorted(..), like: from operator import attrgetter def view(request): instances = Model.objects.all() for counter, instance in enumerate(instances): instance.foo = 'bar' + str(counter) mydata = sorted(instances, key=attrgetter('foo')) return render(request, 'template.html', {'instances': mydata}) So now mydata is no longer a QuerySet, but a vanilla list. Furthermore note that ordering in a database might be slightly different than ordering in Python. In Python exceptions can occur if not all elements have the same type, and furthermore it is not guaranteed that the semantics behind the order relation is exactly the same.
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90383795
has comment: http://stackoverflow.com/comment/90387728
accepted answer of: http://stackoverflow.com/q/51709984
score: 2
answers question: http://stackoverflow.com/q/51709984
type: AcceptedAnswer

http://stackoverflow.com/q/51677283
type: Question
has answer: http://stackoverflow.com/a/59260862
upvote count: 5
has answer: http://stackoverflow.com/a/55402987
accepted answer: http://stackoverflow.com/a/55402987
score: 4
answer count: 2
has title: TesseractNotFoundError: tesseract is not installed or it's not in your path
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/59260862
tagged with: python
type: AnsweredQuestion
has body: I am trying to use tesseract-OCR to print text from the image. But I am getting the above error. I have installed tesseract OCR using https://github.com/UB-Mannheim/tesseract/wiki and pytesseract in the anaconda prompt using pip install pytesseract but its not working. Please help if anyone has faced the similar issue. Collecting pytesseract Downloading https://files.pythonhosted.org/packages/13/56/befaafbabb36c03e4fdbb3fea854e0aea294039308a93daf6876bf7a8d6b/pytesseract-0.2.4.tar.gz (169kB) 100% |████████████████████████████████| 174kB 288kB/s Requirement already satisfied: Pillow in c:\users\500066016\appdata\local\continuum\anaconda3\lib\site-packages (from pytesseract) (5.1.0) Building wheels for collected packages: pytesseract Running setup.py bdist_wheel for pytesseract ... done Stored in directory: C:\Users\500066016\AppData\Local\pip\Cache\wheels\a8\0c\00\32e4957a46128bea34fda60b8b01a8755986415cbab3ed8e38 Successfully built pytesseract Below is the code: import pytesseract import cv2 import numpy as np def get_string(img_path): img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) kernel = np.ones((1,1), np.uint8) dilate = cv2.dilate(img, kernel, iterations=1) erosion = cv2.erode(img, kernel, iterations=1) cv2.imwrite('removed_noise.jpg', img) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) cv2.imwrite('thresh.jpg', img) res = pytesseract.image_to_string('thesh.jpg') return res print('Getting string from the image') print(get_string('quotes.jpg')) Below is the error: Traceback (most recent call last): File "<ipython-input-2-cf6e0fca14b4>", line 1, in <module> runfile('C:/Users/500066016/.spyder-py3/project1.py', wdir='C:/Users/500066016/.spyder-py3') File "C:\Users\500066016\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\500066016\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\…
tagged with: python-tesseract
tagged with: image-processing
downvote count: 1

http://stackoverflow.com/comment/90405391
has text: The format is a dictionary of a list of dictionaries. I'm having trouble drilling down to the lower values. I've added an sample of what the data might look like normally.
comment on: http://stackoverflow.com/q/51722218
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51656788
has comment: http://stackoverflow.com/comment/90277475
upvote count: 3
answers question: http://stackoverflow.com/q/51656681
has comment: http://stackoverflow.com/comment/90277433
has body: You can not the set comprehension that you are using here {small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set} these comprehensions are for creating sets of objects. You are using it to assign a value to an array - which is invalid syntax. Instead, for pos_x, pos_y in position_set: small_mask[pos_x][pos_y] = 1 However, if you are trying to make this more efficient, you can complitly vectorize your random selection of the pos_x, pos_y pairs and vectorize the access on small_mask. def _get_positions(self): small_shape = int(self._width / MACROPIXEL_SIZE) small_mask = numpy.zeros((small_shape, small_shape), dtype=numpy.uint8) #how many macropixel we will pick nb_pick = int((small_shape * small_shape) * self._alter_percentage) nx, ny = small_shape, small_shape xy = np.mgrid[:nx,:ny].reshape(2, -1).T pos = xy.take(np.random.choice(xy.shape[0], nb_pick, replace=False), axis=0) small_mask[pos] = 1 self.mask = numpy.kron(small_mask, numpy.ones(self._height, self._width))
accepted answer of: http://stackoverflow.com/q/51656681
has comment: http://stackoverflow.com/comment/90277460
downvote count: 0
has comment: http://stackoverflow.com/comment/90277335
score: 3
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51675198
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51675252
has comment: http://stackoverflow.com/comment/90313416
score: 1
has comment: http://stackoverflow.com/comment/90313631
type: Question
linked to: http://stackoverflow.com/q/43636171
has body: (You can assume the date column is datetime) This may be relevant to the problem, but I also have a list of dates with the following values: ['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01'] I have the following table: date arb1 arb2 amount 2018-01-02 Z F 5 2018-01-03 G H 10 2018-02-04 V T 51 2018-03-03 R S 54 I want this output, where each date has been set to the first of its corresponding month: date arb1 arb2 amount 2018-01-01 Z F 5 2018-01-01 G H 10 2018-02-01 V T 51 2018-03-01 R S 54 Bonus (not required): What I'm actually trying to do is add up the amounts after grouping by date (the month), arb1, and arb2, and the final output has each date as the first of the month. I figured an easy way to get here would be to first change each date to the first of the month, but if there is an easy way to do this in pandas then the above steps aren't required and you can skip to this instead
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51675252
has comment: http://stackoverflow.com/comment/90315049
duplicate of: http://stackoverflow.com/q/43636171
has title: Pandas - changing each date in a date column
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90314671
favorite count: 0
duplicate of: http://stackoverflow.com/q/45304531
upvote count: 1
tagged with: python

http://stackoverflow.com/a/51722310
answers question: http://stackoverflow.com/q/51722150
upvote count: 1
has body: This works for me: i inserted iloc[i] in line 5: texts = [] for i in range(len(df.index)): _text = '' for c in df.columns: _text += c + ':' + str(df[c].iloc[i]) + '&lt;br&gt;' texts.append (_text)
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/68864336
answers question: http://stackoverflow.com/q/51795667
type: Answer
has body: prime number count in python list def countPrimeNumbers(numbers): count=0 for num in numbers: if(num&lt;2): continue else: for i in range(2,num): if(num%i==0): break else: count+=1 return count
score: 0

http://stackoverflow.com/comment/90557778
type: Comment
comment on: http://stackoverflow.com/a/51694319
score: 0
type: AnswerComment
has text: @Camilo Andres Perez Sanchez. Please mark my answer as correct if it solved your issues. It'll make the solution clearer to others with the same problem.

http://stackoverflow.com/comment/90347726
type: QuestionComment
has text: Yes. I thought doing that will not directly convert it into 255 but to a certain relateable value . but putting it as 255 is easier
comment on: http://stackoverflow.com/q/51693017
score: 0
type: Comment

http://stackoverflow.com/a/51746339
type: Answer
downvote count: 0
score: 1
has body: You need to use special key function for sorting: months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] month_num = dict(zip(months, range(12))) def compare(date): month, year = date.split(' ') return (year, month_num[month]) dates = { 'February 2017': {'a': 1.0, 'b': 683.01}, 'March 2018': {'a': 0.0, 'b': 623.79}} dict(sorted(dates.items(), key=lambda x: compare(x[0])))
answers question: http://stackoverflow.com/q/51746035
upvote count: 1

http://stackoverflow.com/a/51767948
answers question: http://stackoverflow.com/q/51766963
score: 6
has body: Indeed there is no option to define the metric_params as in the other cases. For example other pairwise distance based classes provide a metric_params parameter to pass additional params to the distance function. Like KNeighborsClassifier NearestNeighbors have this: metric_params : dict, optional (default = None) Additional keyword arguments for the metric function. This answer here shows how to use this param. But TSNE has no way to send the additional parameters. So for now, you need to extend the class and over-ride the __init__() to send the parameters and then _fit() method to actually use them. We can do this: from time import time import numpy as np import scipy.sparse as sp from sklearn.manifold import TSNE from sklearn.externals.six import string_types from sklearn.utils import check_array, check_random_state from sklearn.metrics.pairwise import pairwise_distances from sklearn.manifold.t_sne import _joint_probabilities, _joint_probabilities_nn from sklearn.neighbors import NearestNeighbors from sklearn.decomposition import PCA class MyTSNE(TSNE): def __init__(self, n_components=2, perplexity=30.0, early_exaggeration=12.0, learning_rate=200.0, n_iter=1000, n_iter_without_progress=300, min_grad_norm=1e-7, metric="euclidean", metric_params=None, #&lt;=ADDED init="random", verbose=0, random_state=None, method='barnes_hut', angle=0.5): self.n_components = n_components self.perplexity = perplexity self.early_exaggeration = early_exaggeration self.learning_rate = learning_rate self.n_iter = n_iter self.n_iter_without_progress = n_iter_without_progress self.min_grad_norm = min_grad_norm self.metric = metric self.metric_params = metric_params #&lt;=ADDED self.init = init self.verbose = verbose self.random_state = random_state self.method = method self.angle = angle def _fit(self, X, skip_num_points=0): if self.method not in ['barnes_hut', 'exact']: raise ValueError("'method' must be 'barnes_hut' or 'exact'") if self.angle &lt; 0.0 or self.angle &gt; 1.0: raise Value…
has comment: http://stackoverflow.com/comment/90526193
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90523492
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/90523612
accepted answer of: http://stackoverflow.com/q/51766963

http://stackoverflow.com/a/51778524
accepted answer of: http://stackoverflow.com/q/51664477
has comment: http://stackoverflow.com/comment/90515236
has comment: http://stackoverflow.com/comment/90517064
has body: My guess would be you are getting this error because you are passing a pandas Series object to the translate function (docs) instead of a str (string) object. Try using apply: from googletrans import Translator translator = Translator() df['English'] = df['Review to Translate'].apply(translator.translate, src='id', dest='en') If I run this example at repl.it: from googletrans import Translator import pandas as pd translator = Translator() df = pd.DataFrame({'Spanish':['piso','cama']}) df['English'] = df['Spanish'].apply(translator.translate, src='es', dest='en').apply(getattr, args=('text',)) It works as expected.
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/110347321
upvote count: 6
has comment: http://stackoverflow.com/comment/116416132
answers question: http://stackoverflow.com/q/51664477
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/121417172
has comment: http://stackoverflow.com/comment/110347810

http://stackoverflow.com/comment/90371615
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51705106
type: QuestionComment
has text: You could start by eliminating unused function parameters and useless statements like `abloese = abloese or 0`. Using `float()` all the time also seems unnecessary. In my opinion it also makes the code less readable if german variable names are mixed with english language keywords.

http://stackoverflow.com/q/51660481
has title: How to resolve pymysql.err.ProgrammingError: 1064 - save data on mysql?
has body: I'm trying to save the data scraped with scrapy to mysql. But, I have these issues: No more support for MySQLdb. So, I have to use import pymysql pymysql.install_as_MySQLdb() on settings.py file On python 3 %s is deprecated and I have to use .format with the following code: def close(self, reason): csv_file = max(glob.iglob('*.csv'), key=os.path.getctime) mydb = MySQLdb.connect(host='localhost', user='demo', passwd='123456', db='testdb') cursor = mydb.cursor() csv_data = csv.reader(open(csv_file)) row_count = 0 for row in csv_data: if row_count != 0: cursor.execute("INSERT IGNORE INTO testtb(product, category) VALUES('{}','{}')".format(*row)) row_count += 1 mydb.commit() cursor.close() I have the following error &lt;bound method AutorSpider.close of &lt;AutorSpider 'autor' at 0x7f64725d29b0&gt;&gt; Traceback (most recent call last): File "/home/pc/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 151, in maybeDeferred result = f(*args, **kw) File "/home/pc/.local/lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply return receiver(*arguments, **named) File "/home/pc/Escritorio/fpyautor/fpyautor/spiders/autor.py", line 109, in close cursor.execute("INSERT IGNORE INTO autortb(frase, categoria) VALUES({},'{}')'".format(*row)) File "/home/pc/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/home/pc/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/home/pc/.local/lib/python3.6/site-packages/pymysql/connections.py", line 516, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/pc/.local/lib/python3.6/site-packages/pymysql/connections.py", line 727, in _read_query_result result.read() File "/home/pc/.local/lib/python3.6/site-packages/pymysql/connections.py", line 1066, in read first_packet = self.connection._read_packet() File "/home/pc/.local/lib/python3.6/site-packages/pymysql/conne…
has comment: http://stackoverflow.com/comment/90288271
has comment: http://stackoverflow.com/comment/90287846
has comment: http://stackoverflow.com/comment/90288034
has comment: http://stackoverflow.com/comment/90288257
has comment: http://stackoverflow.com/comment/90284922
tagged with: python
has comment: http://stackoverflow.com/comment/90286058
accepted answer: http://stackoverflow.com/a/51660671
score: 2
has comment: http://stackoverflow.com/comment/90285454
upvote count: 2
has comment: http://stackoverflow.com/comment/90285132
tagged with: mysql
has comment: http://stackoverflow.com/comment/90284637
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/90286723
has comment: http://stackoverflow.com/comment/90285772
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90286919
has comment: http://stackoverflow.com/comment/90284838
has comment: http://stackoverflow.com/comment/90284587
has comment: http://stackoverflow.com/comment/90288128
has comment: http://stackoverflow.com/comment/90285829
has answer: http://stackoverflow.com/a/51660671
has comment: http://stackoverflow.com/comment/90285755
has comment: http://stackoverflow.com/comment/90288563
has comment: http://stackoverflow.com/comment/90285656
has comment: http://stackoverflow.com/comment/90287499
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90284674
has comment: http://stackoverflow.com/comment/90284569
has comment: http://stackoverflow.com/comment/90288516
favorite count: 0

http://stackoverflow.com/a/51721566
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51710014
has body: Try change your cron to: 1 11 * * * /home/ubuntu/ga_data/gaV4/tva_gaApiUpdate.sh &gt; /dev/null 2 &gt;&gt; tvaUpdater.log and script to #!/bin/bash cd /home/ubuntu/ga_data/gaV4 /home/ubuntu/anaconda3/bin/python gaAPIWorkingVersion.py echo "ran cron at" | tee -a "$tvaUpdater.log" echo $(date) | tee -a "$tvaUpdater.log" Make sure that user under which scipt is running directly is same as the one of cronjob. If you still have problems, check Cannot Import Python MySQL module when running a script using crontab
accepted answer of: http://stackoverflow.com/q/51710014
type: AcceptedAnswer

arima
tags question: http://stackoverflow.com/q/51693773
tag name: arima
tags question: http://stackoverflow.com/q/51743303
type: Tag

http://stackoverflow.com/comment/90326733
score: 0
type: Comment
type: QuestionComment
has text: Is it a javascript or html popup? Also, you should share some code snippet for what have you tried so far and html for the alert if its an html popup
comment on: http://stackoverflow.com/q/51681276

http://stackoverflow.com/q/51684664
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51684803
type: Question
has answer: http://stackoverflow.com/a/51684698
has answer: http://stackoverflow.com/a/51684725
favorite count: 0
score: 0
answer count: 3
has title: how to print next line of the match string in python3 (If i give Tea , it should print next line too)
has body: BANL16fd1c9a1:file_exceptions jjimmy$ python3 search_cofee_records.py Please enter an item name:-Tea Description will be :- Tea QUANTITY will be :- 500 BANL16fd1c9a1:file_exceptions jjimmy$ BANL16fd1c9a1:file_exceptions jjimmy$ cat search_cofee_records_for.py def main(): infile=open('coffee.txt','r') search=input("Please enter an item :-") for line in infile: line=line.rstrip('\n') if (line==search): print("Description:-",line) infile.close() main()
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90466002
comment on: http://stackoverflow.com/q/51752911
has text: @Srini I had already tried that with Resume Program (F9) when it hits the first breakpoint and it does not work. By executing normally, do you mean some other way to run the function call?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51708529
type: AnsweredQuestion
tagged with: solver
downvote count: 0
has body: I have some problems when I want to print some concrete values with the Solver Results. This is my objective function: def obj2_rule(model): return sum(sum(model.htotal1[k] + model.htotal2[k] + model.htotal3[k] - sum(sum(model.hreq1[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) + model.hreq2[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) + model.hreq3[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) for j in model.MODELS) for p in jobs_per_station[k]) for k in model.ESTATIONS) for t in model.PERIODS) model.obj2 = Objective(rule=obj2_rule) Within that objective function, I want to print separately this "extra variables" because the objective function returns the sum of them for every t in model.PERIODS: h_idle[t] = sum(model.htotal1[k] + model.htotal2[k] + model.htotal3[k] - sum(sum(model.hreq1[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) + model.hreq2[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) + model.hreq3[p,j] * (sum(model.x[p,k,j] for k in sequence(t)) - sum(model.x[p,k,j] for k in sequence(t - model.time[p,j]))) for j in model.MODELS) for p in jobs_per_station[k]) for k in model.STATIONS) for each t in model.PERIODS I want to print these "variables" : h_idle[1], h_idle[2].... Please, some idea how to do it? Thanks in advance.
score: 1
type: Question
tagged with: pyomo
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51709512
accepted answer: http://stackoverflow.com/a/51709512
tagged with: python
has title: Print Solver Results of terms from an objective function Pyomo
tagged with: python-3.x

http://stackoverflow.com/q/51721056
possible better answer: http://stackoverflow.com/a/51721374
has answer: http://stackoverflow.com/a/51721374
tagged with: image-uploading
type: AnsweredQuestion
has title: when i upload a image if it be big i got this message 403 Forbidden when i want to show it
upvote count: 2
has comment: http://stackoverflow.com/comment/90403138
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/54157961
has body: my model is this class Image (model.Model): Image = models.ImageField(upload_to='pic_folder/', default='', help_text='') my form is this class Image(form.Form): Image = form.ImageField() my view is this def Image(request): if request.method=="POST": form =Image(request.POST,request.FILES) if form.is_valid(): cd =form.cleaned_data t = Image(Image=cd["Image"]) t.save() else: form=Image() return render(request,"template.html",{'form':form} template &lt;form method="post" enctype="multipart/form-data"&gt;{%csrf_token%} &lt;input type="file" name="Image" &gt; &lt;input type="submit" name="" valu="ok"&gt; &lt;/form&gt; if the image be small it will be ok but if it be large i got this
answer count: 2
score: 2
downvote count: 0
tagged with: web
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/54157961
tagged with: python

http://stackoverflow.com/q/51669224
downvote count: 1
has title: for loop when reading lines from a list
has body: I have a list which has used regular express to extract, the list will be like the following: SRM Video Dest UDP QAM QAM PID In Out Detected Input Output PSI Uptime Session ID ID Intf IpAddress Port Chan Domain Remap ProgNo ProgNo Bitrate State State Detected (s) Encryption -------------------- --- ----- --------------- ----- -------- ------ ----- ------ ------ -------- ----- ------ -------- ------ ---------- 000a000905000176794c 1 1 232.232.40.1 55000 0/0/48 2 No 62351 62351 46000 Off On Yes 3175405 Clear 000a000905000176794d 1 1 232.232.40.1 55000 0/0/49 2 No 62351 62351 46000 On On Yes 3175405 Clear 000a000905000176794e 1 1 232.232.40.1 55000 0/0/50 2 No 62351 62351 46000 Off Off Yes 3175405 Clear The reading logic is as belows where w00 and w0 are two commands line. I extracted the content between two commands. with open(file, 'r', encoding='UTF-8') as fp_nei: fp_reader = fp_nei.read() pat = re.compile(w00 + '(.*?)' + w0, re.S) videosession = pat.findall(fp_reader) I want to filter the line when "Detected Bitrate" is zero or "Input State" is "Off". Like the following: SRM Video Dest UDP QAM QAM PID In Out Detected Input Output PSI Uptime Session ID ID Intf IpAddress Port Chan Domain Remap ProgNo ProgNo Bitrate State State Detected (s) Encryption -------------------- --- ----- --------------- ----- -------- ------ ----- ------ ------ -------- ----- ------ -------- ------ ---------- 000a000905000176794c 1 1 232.232.40.1 55000 0/0/48 2 No 62351 62351 46000 Off On Yes 3175405 Clear 000a000905000176794e 1 1 232.232.40.1 55000 0/0/50 2 No 62351 62351 46000 Off Off Yes 3175405 Clear I tried to useee a simple way like the following, but it seems that the output show all the lines instead of lines with "Off". for line in videosession: if "Off" in line: print(line) Would you please shed some lights on it? Thank you very much!
has comment: http://stackoverflow.com/comment/90301082
has answer: http://stackoverflow.com/a/51669457
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51669533
score: -1
has comment: http://stackoverflow.com/comment/90301121
answer count: 3
has answer: http://stackoverflow.com/a/51684305
favorite count: 0
has comment: http://stackoverflow.com/comment/90327532
has comment: http://stackoverflow.com/comment/90326986
tagged with: extract
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51762025
duplicate of: http://stackoverflow.com/q/70576382
linked to: http://stackoverflow.com/q/70576382
type: Question
has body: I recently tried to install Flake8 for Python3 and since then I'm getting the following error message: /Users/dorsam/.atom/packages/linter/lib/linter-registry.js:159 [Linter] Error running Flake8 Error: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pycodestyle.py:113: FutureWarning: Possible nested set at position 1 EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]') at ChildProcess.&lt;anonymous&gt; (/Users/dorsam/.atom/packages/linter-flake8/node_modules/sb-exec/lib/index.js:56:20) at emitTwo (events.js:126:13) at ChildProcess.emit (events.js:214:7) at maybeClose (internal/child_process.js:925:16) at Socket.stream.socket.on (internal/child_process.js:346:11) at emitOne (events.js:116:13) at Socket.emit (events.js:211:7) at Pipe._handle.close [as _onclose] (net.js:554:12)
upvote count: 5
score: 5
tagged with: flake8
has comment: http://stackoverflow.com/comment/90515272
has answer: http://stackoverflow.com/a/61791199
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Error running flake8
tagged with: python

http://stackoverflow.com/a/51755313
downvote count: 1
has comment: http://stackoverflow.com/comment/90470423
has body: You can create a new dictionary with decoded keys and values like so: x = {b'cf1:c1': b'test-value'} y = {k.decode("utf-8"):v.decode("utf-8") for k,v in x.items()} Then you should be able to display y as you desire.
accepted answer of: http://stackoverflow.com/q/51755232
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51755232
type: Answer
upvote count: 2
score: 1

http://stackoverflow.com/q/51686045
upvote count: 1
has comment: http://stackoverflow.com/comment/90334081
type: Question
has title: django-admin startproject does not create manage.py
answer count: 2
accepted answer: http://stackoverflow.com/a/51687261
downvote count: 0
possible better answer: http://stackoverflow.com/a/69748075
linked to: http://stackoverflow.com/q/36488571
favorite count: 0
has answer: http://stackoverflow.com/a/69748075
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90335221
type: AnsweredQuestion
has body: I am trying to create a new Django 1.5 project. I just installed Python 2.7.15, created a virtualenv, and installed Django 1.5. I don't have any other version installed. When I run python django-admin.py startproject myproject it creates a new folder: myproject/ myproject/ __init__.py ... But manage.py is missing in the top folder. What am I doing wrong?
score: 1
has answer: http://stackoverflow.com/a/51687261

http://stackoverflow.com/comment/90340089
comment on: http://stackoverflow.com/q/51689120
has text: In your question, you said "`except 6 & 9`" so for your desired output use `and` operation!
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90288699
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51662486
has text: @user2357112 I think they want to make an equivalent coroutine using generator function (yield statement)
score: 0

http://stackoverflow.com/comment/90362464
has text: @UlrichEckhardt: Look at my rep, do you think I haven't tried? If I could, I would. I ran the function where the segfault occurs in an infinite loop for a long time - no error. The example turned out not to be an example. But as I said the problem is intermittent, even I can't consistently generate it on the code I have. If I could consistently replicate it in a controlled environment, it might be I wouldn't need to post a question at all. I'm looking for advice from experts in assembly on how to find the problem in the first place and how to explain the results my experiments so far produced.
comment on: http://stackoverflow.com/q/51654074
score: 5
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51781293
has comment: http://stackoverflow.com/comment/90520127
has comment: http://stackoverflow.com/comment/90520376
has comment: http://stackoverflow.com/comment/90520801
has comment: http://stackoverflow.com/comment/90520201
has comment: http://stackoverflow.com/comment/90520382
has comment: http://stackoverflow.com/comment/90520219
upvote count: 1
has comment: http://stackoverflow.com/comment/90520250
has comment: http://stackoverflow.com/comment/90520120
has comment: http://stackoverflow.com/comment/90520839
type: Answer
answers question: http://stackoverflow.com/q/51780856
has comment: http://stackoverflow.com/comment/90520262
has body: This should give you the desired output: n_lines = int(input('How many lines do you want to input?')) lines = [] for i in range(n_lines): x = input() lines.append(x) if int(x) >= 5: break print(lines)
downvote count: 0
score: 1

http://stackoverflow.com/q/51662153
has body: I have two data frames df1: and df2: I want to join these two data frames to get df3: Here is the logic that I am trying to build: df1 is the primary table. The first row of DF3 is populated by searching DF2 for the same ID. The logic finds ID 1 at location A with a value of 50. The second row of DF3 is populated by searching for ID 1 in DF2. 50 is already found , so the remaining 50 is allocated to location D. 3.The third row of DF3 is populated because there is an exact match with location C of 200 THe fourth row of DF3 is populated with an amount of 250 in location A. The fifth row of DF3 is populated with the remaining 50 in DF1 ( not 100) IF there is no location match, DF3 location should be null / unknown. Is there a join that i can perform to do this ?
has comment: http://stackoverflow.com/comment/90287783
score: -1
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51670823
has title: Merging Two Data Frames With Matching
downvote count: 1
type: Question

http://stackoverflow.com/comment/90489810
type: QuestionComment
type: Comment
has text: can you provide an example of `object_1`, ... and define *uniqueness*?
comment on: http://stackoverflow.com/q/51765551
score: 7

http://stackoverflow.com/a/51679635
has comment: http://stackoverflow.com/comment/90352071
has comment: http://stackoverflow.com/comment/90355636
has comment: http://stackoverflow.com/comment/90355587
has comment: http://stackoverflow.com/comment/90352046
downvote count: 0
has comment: http://stackoverflow.com/comment/90355603
has body: serpscrap evidently requires lxml, even though for some reason it only documents that requirement for Windows, rather than for all platforms. You can't install packages that need C extension modules, like lxml, in Pythonista. You seem to have somehow gotten the pure-Python part of lxml installed,1 but that won't do any good without the C extension modules. There's an open issue, #245, to add lxml as a pre-installed package with Pythonista, which would probably fix your problem. So, your options are: Help Pythonista get lxml building so they can close that bug and add lxml to the next version. Modify serpscrap to work without lxml (if it's just using lxml.etree, it's possible that it would work with the stdlib ETree implementation). File a feature request with serpscrap and hope someone else does it. Switch to a different scraper that doesn't require lxml. 1. I'm not sure how that could happen; the install should just fail. But maybe serpscrap does some weird thing that happens to work on Linux and macOS but not iOS, and that's why they only list lxml as a dependency on Windows in the first place?
has comment: http://stackoverflow.com/comment/90358176
type: Answer
has comment: http://stackoverflow.com/comment/90322849
upvote count: 1
has comment: http://stackoverflow.com/comment/90334383
score: 1
has comment: http://stackoverflow.com/comment/90340405
has comment: http://stackoverflow.com/comment/92451710
has comment: http://stackoverflow.com/comment/90352117
answers question: http://stackoverflow.com/q/51679512
has comment: http://stackoverflow.com/comment/90353125
has comment: http://stackoverflow.com/comment/90322671

http://stackoverflow.com/comment/90535294
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51788981
type: Comment
has text: That may just be a representational issue. You should really check the two dataframes and compare their values (for not-NaN cells) whether these are still equal. Just subtract the old and new columns and see what the resulting column values are.

http://stackoverflow.com/q/51794084
score: 2
has comment: http://stackoverflow.com/comment/90579726
answer count: 0
upvote count: 2
has body: I downloaded the official Tensorflow MNIST models (from https://github.com/tensorflow/models), and I have run them successfully in an Anaconda Prompt. However, I would like to run them through a Colaboratory Notebook but I am having trouble getting the script to recognize the "official" directory that contains all the necessary files to import. I have tried to add the "official" directory to my google drive, and also to the python installation directory in my hard drive without success. Thank you for the help!
tagged with: tensorflow
type: Question
tagged with: mnist
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/90579691
downvote count: 0
has title: ModuleNotFoundError: No module named 'official' error when running Tensorflow Official MNIST Model in a Colaboratory notebook?
has comment: http://stackoverflow.com/comment/90546338
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90520956
comment on: http://stackoverflow.com/q/51781648
score: 0
type: Comment
has text: @deceze Oh thanks, yes it's json data that i dump (save) at a file.Any suggest ?
type: QuestionComment

http://stackoverflow.com/q/51703688
linked to: http://stackoverflow.com/q/14220321
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/14220321
has body: I'm new to javascript and can't get my head around asyn functions. As a hobbyist I'm making a web application in node.js, express. The server side is using a python-shell to execute some more advanced calculations. After performing the calculations the python-shell returns roughly 1000 times a number which I would like to store in my javascript array (myArr). After finishing this process I would like to send my array to the client side (for illustration purposes). The code below runs fine, meaning python returns the numbers one by one (checked by the console.log), and my javascript sends my array to the client side. Unfortunately, my results array (myArr) is empty. This has probably something to do with the asyn function. Hopefully some one can help me out, How can I first fill myArr with data from the python-shell and afterwards rendering my page? Below are the relevant parts of my code. var myArr = []; var count = 0; var python = new PythonShell('majorPythonFile.py'); python.send(JSON.stringify([x1, x2,path, analyseType])); python.on('message', function (message) { myArr[count] = message; count++; console.log(message + ' ' + count); }); # end the input stream and allow the process to exit python.end(function(err){ if (err){ throw err; } console.log('finished'); }); res.render("home",{results:myArr});
type: Question
has title: How to store asynchronous callback values in an variable?
has comment: http://stackoverflow.com/comment/90372001
tagged with: javascript
score: 0
has comment: http://stackoverflow.com/comment/90369833
tagged with: python
has comment: http://stackoverflow.com/comment/90381239
tagged with: asynchronous

http://stackoverflow.com/a/51743746
answers question: http://stackoverflow.com/q/51743607
score: 0
type: Answer
has body: Seems like it is a job for defaultdict: It acts like a dictionary but instead of raising an error if you access an element that was never set, it sets it to an instance of the chosen default object (here a list) on the first access. The issue in your case is that you override the content associated with the key in your final dict when you want to add an element. You are probably looking for something like that: from collections import defaultdict result = defaultdict(list) for d in top: result[d[u'parent_label']].append([d[u'label'], d[u'url']]) print(result) Result: defaultdict(list, {'About Us': 'News', '/news', 'Drilling Tools': 'HSS Center Drill Bits', '/hss-tools/hss-center-drill', 'Lathe Tools': [['Square HSS Tool Bits', '/hss-tools/hss-square-tool-bits'], ['Carbide Square Tool Bits', '/carbide-square-tool-bits'], ['Rectangular HSS Tool Bits', '/rectangular-hss-tool-bits']], 'Milling Tools': 'Carbide Radius End Mills', '/carbide-radius-end-mills', 'Press Tools': [['HSS Tapped Punches', '/hss-tapped-punches'], ['HSS Mini Straight Punches', '/hss-mini-straight-punches']]})

http://stackoverflow.com/a/51736902
downvote count: 1
type: Answer
has body: You can try this, a = list(set(data)) A List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.
upvote count: 0
answers question: http://stackoverflow.com/q/51736860
score: -1
has comment: http://stackoverflow.com/comment/90434473

http://stackoverflow.com/comment/90395524
has text: Thanks! The only problem is I need to do this based off user input. How would I do that? Also, if it matters, I'm going to write remove() and markDone() methods after I figure this out. Not sure if that affects how this has to be written...
comment on: http://stackoverflow.com/a/51717006
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/51688546
type: AnsweredQuestion
type: Question
score: 0
has answer: http://stackoverflow.com/a/51690216
accepted answer: http://stackoverflow.com/a/51690216
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/51684658
favorite count: 0
has comment: http://stackoverflow.com/comment/90339177
has body: I cannot get my code to pass the pop up text entry to a global variable i am also attempting to set this global variable as the default text in the entry field in all future instances. Pop up -> Enter Filepath -> accept&amp;close -> Re-open shows last filepath present as default -> if changed new filepath entry becomes default in future. import tkinter as tk from tkinter import ttk from tkinter import * master = tk.Tk() Var1 = StringVar() Filepath_Var = None def A_Connect(): root = Tk() root.title("Entry Field") def entry_field(): global Filepath_Var Filepath_Var = Var1.get() tk.Label(root, text="filepath: ").grid(row=0) e1 = tk.Entry(root, textvariable=Var1) tk.Label(root, text="Item Number: ").grid(row=1) e2 = tk.Entry(root) #e1.insert(0, r"C:\Users\zxy\ghj\iugf\Bea\something.xlsx") e1.insert(0, Var1.get()) e1.grid(row=0, column=1) e2.grid(row=1, column=1) Button(root, text = 'Accept', command = entry_field).grid(row=3, column=1, sticky=W, pady=4) root.mainloop() note = ttk.Notebook(master) tab1 = tk.Frame(note) canvas7 = Canvas(tab1, width=520, height=350) canvas7.pack() A_Button = tk.Button(tab1, text="A", width=12, height=3,command=A_Connect, anchor = 'w') A_Button_Window = canvas7.create_window(20, 120, anchor = 'sw', window = A_Button) note.add(tab1, text = " Main ") note.pack() master.mainloop()
has title: How to retain the value of an entry field acquired in a popup toplevel window in tkinter?
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/90342242
has comment: http://stackoverflow.com/comment/90338925
downvote count: 1
has comment: http://stackoverflow.com/comment/90339491

http://stackoverflow.com/comment/90523568
comment on: http://stackoverflow.com/a/51770377
has text: @Andersson yes, it's fixed, by I guess that fix was overriden by someone else if it was landed. Master branch of the py selenium doesn't have that change: https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/remote/webelement.py .
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90474464
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51756833
type: Comment
has text: You need to have a list of placeholders (x) instead of one. The list needs `num_unroll` placeholders. Then you can get the i th placeholder with x[i]. At every step of unroll, you need to fill in all the placeholder in that list.

http://stackoverflow.com/a/60495343
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51759222
has body: In C++ std::vector&lt;std::string&gt; addBorder(std::vector&lt;std::string&gt; picture) { for(auto &amp;p: picture) p = "*"+p+"*"; picture.insert(picture.begin(), string(picture[0].size(),'*')); picture.insert(picture.end(), string(picture[0].size(),'*')); return picture; }

http://stackoverflow.com/comment/90484513
type: QuestionComment
has text: are you talking about functions parameters or something else?
comment on: http://stackoverflow.com/q/51762646
score: 0
type: Comment

http://stackoverflow.com/comment/90518278
type: QuestionComment
comment on: http://stackoverflow.com/q/51780312
score: 3
has text: you seem to be familiar with `collections.OrderedDictionary`, so have you tried using it?
type: Comment

http://stackoverflow.com/q/51736279
has title: Python - Convert 8 bit binary number to decimal
accepted answer: http://stackoverflow.com/a/51736337
answer count: 1
has comment: http://stackoverflow.com/comment/90433259
has comment: http://stackoverflow.com/comment/90433287
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51736337
type: Question
has body: import math while True: try: user_bin = int(input('\nPlease enter binary number: '), 2) except ValueError: print('Please make sure your number contains digits 0-1 only.') else: print(user_bin) I've just been browsing this site looking for tips on how to complete an assignment, the basics of the assignment is to have the user input an 8 bit binary number, and convert it to decimal. Or pop up an invalid input error in situations where it doesn't fit the requirements. The code above seemed interesting so I tested it and I genuinely don't understand which part of the code converts the binary to decimal. Any tips for the assignment as well as explanations would be appreciated.
has comment: http://stackoverflow.com/comment/90433718

lldb
tags question: http://stackoverflow.com/q/51654074
type: Tag
tag name: lldb

http://stackoverflow.com/q/51689594
upvote count: 11
favorite count: 0
tagged with: python-3.x
answer count: 9
has title: How to round away from 0 in Python 3.x?
has answer: http://stackoverflow.com/a/51727430
has answer: http://stackoverflow.com/a/51728032
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51727824
linked to: http://stackoverflow.com/q/10825926
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/70990954
type: Question
has answer: http://stackoverflow.com/a/51727464
has comment: http://stackoverflow.com/comment/90414815
has comment: http://stackoverflow.com/comment/90414888
has answer: http://stackoverflow.com/a/51727397
has answer: http://stackoverflow.com/a/62166086
has answer: http://stackoverflow.com/a/51727799
has answer: http://stackoverflow.com/a/71648055
has body: In Python 2 rounding is done away from 0, so, for example, round(0.5) is 1.0. In Python 3.x, however, rounding is done toward the even choice, so round(0.5) is 0. What function can I use in Python 3.x to get the old behavior?
downvote count: 0
linked to: http://stackoverflow.com/q/13479163

http://stackoverflow.com/q/51647773
has comment: http://stackoverflow.com/comment/90298877
has body: I am new to python and I'm trying to plot an overlaid histogram for a manipulated data set from Kaggle. I tried doing it with matplotlib. This is a dataset that shows the history of gun violence in USA in recent years. I have selected only few columns for EDA. import pandas as pd data_set = pd.read_csv("C:/Users/Lenovo/Documents/R related Topics/Assignment/Assignment_day2/04 Assignment/GunViolence.csv") state_wise_crime = data_set'date', 'state', 'n_killed', 'n_injured' date_value = pd.to_datetime(state_wise_crime['date']) import datetime state_wise_crime['Month']= date_value.dt.month state_wise_crime.drop('date', axis = 1) no_of_killed = state_wise_crime.groupby(['state','Year']) ['n_killed','n_injured'].sum() no_of_killed = state_wise_crime.groupby(['state','Year'] ['n_killed','n_injured'].sum() I want an overlaid histogram that shows the no. of people killed and no.of people injured with the different states on the x-axis
has comment: http://stackoverflow.com/comment/90259584
tagged with: kaggle
type: Question
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90289641
has answer: http://stackoverflow.com/a/51673578
accepted answer: http://stackoverflow.com/a/51673578
answer count: 1
has title: Using matplotlib to obtain an overlaid histogram
score: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/106430203
type: AnswerComment
has text: Some of this code is outdated, you should definitely try and keep it up to date because it's useful. Just not at the moment
comment on: http://stackoverflow.com/a/51702647
type: Comment
score: 0

http://stackoverflow.com/q/51677489
has answer: http://stackoverflow.com/a/51677591
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/90318417
has answer: http://stackoverflow.com/a/51677600
has answer: http://stackoverflow.com/a/51677522
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/51677630
has body: Newbie here, so apologies for a duplicate/silly question but I can't find the answer. I am trying to store the contents of a list (of dictionaries) into a new dictionary. a={} b=[] c={"Name":"Claude","Surname":"Verde","Age":"35","City":"Paris"} b.append(c) c={"Name":"Jean","Surname":"Claude","Age":"22","City":"Paris"} b.append(c) c={"Name":"Sam","Surname":"Smith","Age":"42","City":"London"} b.append(c) c={"Name":"James","Surname":"Jones","Age":"44","City":"London"} b.append(c) for i in range(len(b)): if b[i]['City'] == 'Paris': a["Paris"]=([b[i]]) elif b[i]['City'] == 'London': a["London"]=([b[i]]) a Result: {'Paris': [{'Name': 'Jean', 'Surname': 'Claude', 'Age': '22', 'City': 'Paris'}], 'London': [{'Name': 'James', 'Surname': 'Jones', 'Age': '44', 'City': 'London'}]} However, I want a dictionary containing all residents of a city. The code above only stores the second, not the first, resident in the list. i.e. hoping for the below output. How can I achieve this? Any help greatly appreciated. Thanks {'Paris': [{'Name': 'Claude', 'Surname': 'Verde', 'Age': '35', 'City': 'Paris'},{'Name': 'Jean', 'Surname': 'Claude', 'Age': '22', 'City': 'Paris'}], 'London': [{'Name': 'Sam', 'Surname': 'Smith, 'Age': '42', 'City': 'London'},{'Name': 'James', 'Surname': 'Jones', 'Age': '44', 'City': 'London'}]}
downvote count: 0
has title: dictionary containing a list of dictionaries
favorite count: 0

http://stackoverflow.com/a/51718464
type: Answer
answers question: http://stackoverflow.com/q/51644623
score: 0
has body: Does this do what you want? from bs4 import BeautifulSoup import urllib.request for numb in ('1', '100'): resp = urllib.request.urlopen("https://edition.cnn.com/search/?q=%20news&amp;size=10&amp;from=5540&amp;page=555") soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset')) for link in soup.find_all('a', href=True): print(link['href']) Or, maybe this? from bs4 import BeautifulSoup from bs4.dammit import EncodingDetector import requests resp = requests.get("https://edition.cnn.com/search/?q=%20news&amp;size=10&amp;from=5540&amp;page=555") http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True) encoding = html_encoding or http_encoding soup = BeautifulSoup(resp.content, from_encoding=encoding) for link in soup.find_all('a', href=True): print(link)
has comment: http://stackoverflow.com/comment/90439372

http://stackoverflow.com/comment/90302978
score: 1
has text: @robavioH `file.write()` does NOT "removes" anything from the file by itself. What "removes all data" is opening the file in write ("w") mode. Also if you want to write a csv file, use the `csv` module from the stdlib.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51669848

http://stackoverflow.com/q/51704927
has comment: http://stackoverflow.com/comment/90373237
score: 2
has comment: http://stackoverflow.com/comment/90373311
upvote count: 2
has comment: http://stackoverflow.com/comment/90374764
has comment: http://stackoverflow.com/comment/90374118
has title: BeautifulSoup's find_all method going in loop
type: Question
has comment: http://stackoverflow.com/comment/90373701
has comment: http://stackoverflow.com/comment/90372189
has comment: http://stackoverflow.com/comment/90371787
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51706586
has body: I'm doing some scraping exercises with BeautifulSoup, but I've generated an event that seem going in loop. This is my code: from bs4 import BeautifulSoup import requests # Print all links in the page linkpage = "https://automatetheboringstuff.com/chapter12/" page = requests.get(linkpage) page.econding = "utf-8" data = page.text html = BeautifulSoup(data, "html5lib") for link in html.find_all("a"): print(link) When I execute this script CPU goes to max, nothing is printed and execution going in loop. Why? Two important consideration: This happens only under Linux (both with Python 2 and 3). I do not get the same behavior under Windows: there works good and all links is printed correctly! :‑| This happens only with URL indicated in the variable linkpage. When I change it with others (i.e. https://stackoverflow.com/) it works properly. Edit: Changing parser to xlml it works. Why with html5lib I've this problem (for now only on this specific page)?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51775692
answers question: http://stackoverflow.com/q/51774318
score: 0
type: Answer
has body: You can get access to the indices by using the expanding, but if the indices have the same type as values. For example it works: s1 = pd.Series(index = range(10)).fillna(1) s1.expanding(5).agg(lambda x: x.index[-1]) But it doesn't work: srs = pd.Series(index = pd.date_range('2013-01-01','2013-01-10' )).fillna(1) srs.expanding(5).agg(lambda x: x.index[-1])

http://stackoverflow.com/a/51785130
score: 2
upvote count: 2
downvote count: 0
type: Answer
has body: You have a lot of NaN values in your dataframe, so that it can't draw a line (the actual points aren't following each other). What you can do is drop the nan values like this: df.B.dropna().plot() df.A.dropna().plot()
answers question: http://stackoverflow.com/q/51784884

http://stackoverflow.com/q/51757004
tagged with: python
accepted answer: http://stackoverflow.com/a/51757430
tagged with: python-3.x
downvote count: 0
tagged with: logging
has title: python logging debug to file errors to stdout
has answer: http://stackoverflow.com/a/51757430
type: AnsweredQuestion
score: 1
has body: Is there any way in python logging module to send info &amp; errors to stdout and debug to file. Some commands in my script produce a long output which I don't want to send to stdout. I am using the following logging function which writes logs to file and stdout def mylog(release_num, logdir='/tmp'): applog = logging.getLogger() applog.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%b %d %Y %H:%M:%S") logfile = "{}/{}.log".format(logdir, release_num) if not os.path.exists(logdir): os.makedirs(logdir) fileHandler = logging.FileHandler(logfile, 'ab') fileHandler.setLevel(logging.DEBUG) fileHandler.setFormatter(formatter) applog.addHandler(fileHandler) cformat = logging.Formatter("[%(levelname)8s] : %(message)s") consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(cformat) log.addHandler(consoleHandler) return applog
type: Question
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90502306
type: Comment
has text: This isn't what they want.
type: AnswerComment
comment on: http://stackoverflow.com/a/51771815
score: 0

http://stackoverflow.com/comment/90266686
type: AnswerComment
score: 0
has text: As for the explicit is better than implicit, it all depends. Resources cleanup is one of those areas where the more automatic the better, as developers are notoriously bad at it, especially in a language with exceptions. It's not a chance that Python has automatic memory management, even if "explicit is better than explicit".
type: Comment
comment on: http://stackoverflow.com/a/51650607

http://stackoverflow.com/a/51783539
accepted answer of: http://stackoverflow.com/q/51782761
score: 0
type: AcceptedAnswer
has body: Use the following line in mysite/shifts/scrapes.py from .models import Shift
type: Answer
answers question: http://stackoverflow.com/q/51782761

http://stackoverflow.com/q/51734126
has comment: http://stackoverflow.com/comment/90429624
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90431262
has body: I am trying to run a python pipeline through Mac OS Terminal. I am using Python 2.7.15 because newer versions of Python gave me error messages with this file. I keep getting the following error message: $ python ../../../scripts/gemmaPipeline.py ../../../data/all.fixGL.Q10.ap.bi.MAF5.vcf.gz outfile Results Traceback (most recent call last): File "../../../scripts/gemmaPipeline.py", line 5, in import utils, vcf, genomes100, gemma ImportError: No module named genomes100 The modules listed in the import command are present under the "scripts" folder in a subfolder "modules". For each of the four modules, I have a .py and .pyc file in this subfolder. I cannot get Python to find this path. I have tried running the same script within a virtualenv but to no avail. I even tried moving the "modules" subfolder to the Python "site-packages" folder in hopes that it would work but failed. Finally, I tried including an init.py file (blank) in the "script" folder, but that didn't work either. I am an utter novice and am pretty much learning as I go.Please help.
has comment: http://stackoverflow.com/comment/90429526
has comment: http://stackoverflow.com/comment/90428978
type: Question
has title: Custom modules not read by Python, generating ImportError
score: 0

http://stackoverflow.com/comment/90311976
score: 1
has text: You can first create a matrix of zeros and then use `int(a[-1])` as the indices of your matrices where `a` is `'obj1'`, `'obj2'` etc. and store the distance values in that array
comment on: http://stackoverflow.com/q/51674401
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51791295
answers question: http://stackoverflow.com/q/51791240
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90540202
has comment: http://stackoverflow.com/comment/90540160
upvote count: 2
type: AcceptedAnswer
has body: You are missing an | (OR) after \% in the Regex pattern: (\!|\@|\#|\$|\%|\^) But rather than OR-ing and needness grouping (as you are not referring it afterwards), you can use the character class: [!@#$%^] you can get rid of the \ escapes as well inside [].
has comment: http://stackoverflow.com/comment/90541332
accepted answer of: http://stackoverflow.com/q/51791240

http://stackoverflow.com/comment/90289241
has text: I am just inputting data from a csv file but this is it: df1 = pd.read_csv("1_.csv",error_bad_lines=False, header=0, dtype={"Total_Sales_y": float,"SKU_DESCRIPTION": str, "Vendor": float, "Dpt": str, "Dpt Description": str, "Sub_Dpt": str, "Sub_Dpt_Description":str, "Class":str,"Class_Description":str,"Sub_Class":str, "Sub_Class_Description":str,"SKU_Type":str,"Week":str,"Season":str,"Discount":str,"Sales_Non_AD":float,"Sales_AD":float,"Previous_Week":float}) df1 = df1[np.isfinite(df1['SKU_number'])]
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51662838

http://stackoverflow.com/comment/90550419
score: 0
type: Comment
has text: @user466130 - Also there are another way for turn off this warning, [`pd.options.mode.chained_assignment = None`](https://stackoverflow.com/a/45110013/2901002)
comment on: http://stackoverflow.com/a/51796502
type: AnswerComment

http://stackoverflow.com/a/51792674
score: 0
has body: The "find" method returns only the first match. Try "findAll" instead. See the documentation here
type: Answer
answers question: http://stackoverflow.com/q/51792571

http://stackoverflow.com/q/51774826
tagged with: pandas
has answer: http://stackoverflow.com/a/71065496
accepted answer: http://stackoverflow.com/a/71065496
favorite count: 0
tagged with: python-3.x
score: 142
tagged with: python
has answer: http://stackoverflow.com/a/74416656
answer count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/79057202
has title: append dictionary to data frame
type: AnsweredQuestion
has body: I have a function, which returns a dictionary like this: {'truth': 185.179993, 'day1': 197.22307753038834, 'day2': 197.26118010160317, 'day3': 197.19846975345905, 'day4': 197.1490578795196, 'day5': 197.37179265011116} I am trying to append this dictionary to a dataframe like so: output = pd.DataFrame() output.append(dictionary, ignore_index=True) print(output.head()) Unfortunately, the printing of the dataframe results in an empty dataframe. Any ideas?
upvote count: 142
possible better answer: http://stackoverflow.com/a/51775051
tagged with: dataframe
has answer: http://stackoverflow.com/a/51775051
type: Question
has comment: http://stackoverflow.com/comment/90509006
has comment: http://stackoverflow.com/comment/90508878

http://stackoverflow.com/a/51699980
score: 3
answers question: http://stackoverflow.com/q/51699923
has comment: http://stackoverflow.com/comment/90361375
accepted answer of: http://stackoverflow.com/q/51699923
has comment: http://stackoverflow.com/comment/90361433
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90361330
has body: Your T function sometimes returns a tuple of three tuples: return (0,0,0.8),(1,0,0.1),(1,0,0.1) … and sometimes just a tuple of three ints: return (-1,-1,1) When you try to iterate over the three values and unpack each one as a 3-tuple, sometimes those are going to be ints instead of 3-tuples. Which obviously isn't going to work. Unfortunately, I can't tell you how to fix this, because I have no idea what this function is supposed to be doing. Maybe you wanted this: return (-1,-1,1), (-1,-1,1), (-1,-1,1) … or maybe this: return (-1,-1,1), … or maybe something entirely different. But I do know that you wanted to return some kind of iterable of 3-tuples. But meanwhile, you have at least three other serious errors in your program. First, what happens if none of those elif conditions is true? You just fall off the end of the function, which means you return None, which is not an iterable of 3-tuples. Second: elif(actions == "LEFT"): All of your other tests are against some constant named LEFT. Unless that constant happens to have the value 'LEFT', this will not match. Third: if (actions == UP or DOWN or LEFT or RIGHT and i == 0 and j == 3): … means: if (actions == UP) or (DOWN) or (LEFT) or (RIGHT and i == 0 and j == 3): Even if you fix the precedence issues by adding parentheses: if actions == (UP or DOWN or LEFT or RIGHT) and i == 0 and j == 3: … that still isn't useful, because UP or DOWN or LEFT or RIGHT is just the first one of those that's truthy (non-zero). You probably wanted something like this: if actions in {UP, DOWN, LEFT, RIGHT} and i == 0 and j == 3:
type: Answer
has comment: http://stackoverflow.com/comment/90361443
upvote count: 3

http://stackoverflow.com/comment/90545962
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51794078
has text: Side note: you can just do `df.plot(y='average_ridership', use_index=True)` to get the plot you want without assigning the series `dfyear` or `dfridership` I think (not seeing the plot or the data I can't say for sure).

http://stackoverflow.com/comment/90441666
score: 0
has text: The only solution I can think of is to convert them to positive numbers before making the shift and then back to negative. [This wikipedia page](https://en.wikipedia.org/wiki/Two's_complement) provides a good explanation of how two's compliment works.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51740700

http://stackoverflow.com/q/51675618
tagged with: installation
score: 0
has answer: http://stackoverflow.com/a/51837242
answer count: 1
type: UnansweredQuestion
tagged with: cx-freeze
tagged with: linux
type: Question
tagged with: python
has body: Hi I try to install cx_Freeze on my linux but I can't install it. I want to install it to convert my python app (.py) in an executable app. I download the sources from this website : https://sourceforge.net/projects/cx-freeze/?source=typ_redirect and extract it in a folder. I follow the install instructions by issuing in console python setup.py build and get the following error: python setup.py build Traceback (most recent call last): File "setup.py", line 138, in &lt;module&gt; finder = cx_Freeze.ModuleFinder(bootstrap = True) File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 160, in __init__ self._AddBaseModules() File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 187, in _AddBaseModules self.IncludeModule("traceback") File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 678, in IncludeModule namespace = namespace) File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 346, in _ImportModule deferredImports, namespace = namespace) File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 436, in _InternalImportModule parentModule, namespace) File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 502, in _LoadModule self._ScanCode(module.code, module, deferredImports) File "/home/calbert/Téléchargements/cx_Freeze-4.3.3/cx_Freeze/finder.py", line 588, in _ScanCode arguments.append(co.co_consts[opArg]) IndexError: tuple index out of range Thank you for your help because I'm not a professionnal of programs installation in linux ;)
has title: Install of cx_Freeze

http://stackoverflow.com/q/51688333
has comment: http://stackoverflow.com/comment/90338739
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/21008858
has answer: http://stackoverflow.com/a/51688399
type: Question
has body: I tried print("%.2f" % myArray) and got TypeError: must be real number, not list and then I tried print(map(lambda a: map(lambda x: "%.3f" % x, a), myArray)) and got SyntaxError: invalid syntax
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/51688399
has answer: http://stackoverflow.com/a/51688640
answer count: 3
has comment: http://stackoverflow.com/comment/90338677
has title: What's the shortest syntax to format a 2d array of floats into 2 decimals?
possible better answer: http://stackoverflow.com/a/51688640
favorite count: 0
tagged with: python-3.x
tagged with: string-formatting
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51688748

http://stackoverflow.com/a/51757291
score: 0
answers question: http://stackoverflow.com/q/51757162
type: Answer
has body: If you just want to get common elements, then try sets: list(set(strings).intersection(set(ngramSet)))

http://stackoverflow.com/a/51755531
score: 6
has body: You can't import or directly, even when doing from... import... as. Instead, you will need to use the function-based import mechanism supplied in importlib. This will work: import importlib _or = importlib.import_module('states.or') and you can refer to the module as _or.
downvote count: 0
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/103214468
answers question: http://stackoverflow.com/q/51755091

http://stackoverflow.com/q/51698483
has title: Pandas Merging Mismatch: Second dataframe never merges?
tagged with: pandas
has comment: http://stackoverflow.com/comment/90358664
type: Question
has comment: http://stackoverflow.com/comment/90359123
has comment: http://stackoverflow.com/comment/90358472
tagged with: python
has comment: http://stackoverflow.com/comment/90359134
has body: I've two dataframes X and Y of 10 columns each. The first column of both dataframes are the same,called A. I want to merge the data in X and Y on the column A, and tried doing the below: Z = X.merge(Y, on = 'A') X A B C D E F G 0 y z a b c d 3 k l m n o p 7 o p q r s t Y A H J K L M N 0 1 2 3 4 5 6 7 8 9 1 4 5 7 3 1 2 3 4 5 6 Z A B C D E F G H J K L M N 0 y z a b c d 1 2 3 4 5 6 3 k l m n o p 8 9 1 4 5 7 7 o p q r s t 1 2 3 4 5 6 expected: Z A B C D E F G H J K L M N 0 y z a b c d 1 2 3 4 5 6 3 k l m n o p 1 2 3 4 5 6 7 o p q r s t 8 9 1 4 5 7 The values in X perfectly merge and align with A whereas the half of Y is just there as it was and doesn't merge at all. Why is this happening? In my real table, all the values are integers, so the data type isn't an issue (I used decoy characters for the example)
has comment: http://stackoverflow.com/comment/90358561
has comment: http://stackoverflow.com/comment/90359121
score: 0
has comment: http://stackoverflow.com/comment/90359032
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90359081

http://stackoverflow.com/comment/90487252
comment on: http://stackoverflow.com/a/51764086
type: AnswerComment
score: 0
type: Comment
has text: What do you mean by "per index"?

http://stackoverflow.com/comment/90323770
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51680000
has text: @JoelBerkeley thanks for pointing it out. yes it's a typo. Fixing it now
score: 0

http://stackoverflow.com/a/58391845
score: 3
upvote count: 3
downvote count: 0
has body: df is your raw dataframe, we can also use MultiLabelBinarizer in sklearn.preprocessing. Before execution, df is: -------------------------- | | text | labels | -------------------------- | 0 | A | a, b, c | -------------------------- | 1 | B | a, c | -------------------------- | 2 | C | a, b, f | -------------------------- do as follows: from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() mlb_result = mlb.fit_transform([str(df.loc[i,'labels']).split(',') for i in range(len(df))]) df_final = pd.concat([df['text'],pd.DataFrame(mlb_result,columns=list(mlb.classes_))],axis=1) After execution, df_final is: ------------------------------------ | | text | a | b | c | d | e | f | ------------------------------------ | 0 | A | 1 | 1 | 1 | 0 | 0 | 0 | ------------------------------------ | 1 | B | 1 | 0 | 1 | 0 | 0 | 0 | ------------------------------------ | 2 | C | 1 | 1 | 0 | 0 | 0 | 1 | ------------------------------------ df_final will be what you want.
type: Answer
answers question: http://stackoverflow.com/q/51780470

http://stackoverflow.com/comment/90332486
type: AnswerComment
has text: Ok, Now I'm trying some tests. I'll give it to you some feedback asap
type: Comment
comment on: http://stackoverflow.com/a/51684997
score: 0

http://stackoverflow.com/q/51732145
has title: Passing arguments to cell magic %%script
type: Question
has comment: http://stackoverflow.com/comment/90425282
has body: Closest related question is this one: In Ipython, how can I pass arguments to a cell as though it were its own script? I am writing an ipython notebook to make simulations and then create an animation in paraview. The way I do this is run a cell with the magic command %%script pvpython since paraview has its own interpreter. The problem is that I need it to pass it the directory of the vtu files as an argument (which are a variable in the IPython kernel). So far I have been unable to figure this out. I have tried: %%script pvpython path/to/files import argparse parser = argparse.ArgumentParser() parser.add_argument('foo') args = parser.parse_args() print(args.foo) But this gives an error: `Got unknown argument: path/to/files because the argument is being passed to the magic command not the python script. Is there a way to get around this? Edit: This is different from the linked question because I am using a cell magic not line magic. I would prefer to have all my code visible in the notebook alone.
tagged with: paraview
score: 7
linked to: http://stackoverflow.com/q/38755864
tagged with: ipython
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/63330559
linked to: http://stackoverflow.com/q/51551056
favorite count: 0
tagged with: python
type: UnansweredQuestion
upvote count: 7
has comment: http://stackoverflow.com/comment/90425841

http://stackoverflow.com/q/51716331
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90548268
score: 1
has body: I am running python3 inside a virtualenv which I created as follows ==&gt; python3 -m venv venv ==&gt; source venv/bin/activate ==&gt; python Python 3.6.5 (default, Apr 25 2018, 14:23:58) [GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. My web-app has a requirements file with the python package dependencies What is the difference between using pip3 vs pip to install the dependencies i.e. ==&gt; pip3 install -r requirements vs ==&gt; pip install -r requirements
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51754409
accepted answer: http://stackoverflow.com/a/51754409
has comment: http://stackoverflow.com/comment/90393953
has comment: http://stackoverflow.com/comment/90468429
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2
has title: What is the difference between using pip3 vs pip when running python3 virtualenv
tagged with: python
has comment: http://stackoverflow.com/comment/90467840

http://stackoverflow.com/a/51732374
has comment: http://stackoverflow.com/comment/90426080
type: Answer
accepted answer of: http://stackoverflow.com/q/51732039
score: 1
upvote count: 1
has body: You can try using tf.variable_scope instead. tf.name_scope is ignored by variables created via tf.get_variable() which is usually used by tf.layers functions. This is in contrast to variables created via tf.Variable. See this question for an (albeit somewhat outdated) explanation of the differences.
has comment: http://stackoverflow.com/comment/100602422
has comment: http://stackoverflow.com/comment/90425836
answers question: http://stackoverflow.com/q/51732039
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90425653

http://stackoverflow.com/comment/90383938
comment on: http://stackoverflow.com/q/51707773
score: 0
has text: @CrisLuengo: I'm perfectly aware of this. The machines were not calibrated, we have several different samples scanned at several energies and magnification settings. k-means segmentation is fairly robust to apply to all samples in our setting.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51703367
tagged with: convolution
has answer: http://stackoverflow.com/a/51717536
tagged with: python
possible better answer: http://stackoverflow.com/a/64457058
type: AnsweredQuestion
tagged with: conv-neural-network
type: Question
accepted answer: http://stackoverflow.com/a/51717536
tagged with: neural-network
downvote count: 0
score: 4
upvote count: 4
has title: col2im implementation in ConvNet
answer count: 2
tagged with: deep-learning
has body: I'm trying to implement a CNN only using numpy. While doing the backpropagation, I found out that I had to use col2im in order to reshape dx, so I checked the implementation from https://github.com/huyouare/CS231n/blob/master/assignment2/cs231n/im2col.py. import numpy as np def get_im2col_indices(x_shape, field_height, field_width, padding=1, stride=1): # First figure out what the size of the output should be N, C, H, W = x_shape assert (H + 2 * padding - field_height) % stride == 0 assert (W + 2 * padding - field_height) % stride == 0 out_height = (H + 2 * padding - field_height) / stride + 1 out_width = (W + 2 * padding - field_width) / stride + 1 i0 = np.repeat(np.arange(field_height), field_width) i0 = np.tile(i0, C) i1 = stride * np.repeat(np.arange(out_height), out_width) j0 = np.tile(np.arange(field_width), field_height * C) j1 = stride * np.tile(np.arange(out_width), out_height) i = i0.reshape(-1, 1) + i1.reshape(1, -1) j = j0.reshape(-1, 1) + j1.reshape(1, -1) k = np.repeat(np.arange(C), field_height * field_width).reshape(-1, 1) return (k, i, j) def im2col_indices(x, field_height, field_width, padding=1, stride=1): """ An implementation of im2col based on some fancy indexing """ # Zero-pad the input p = padding x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant') k, i, j = get_im2col_indices(x.shape, field_height, field_width, padding, stride) cols = x_padded[:, k, i, j] C = x.shape[1] cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1) return cols def col2im_indices(cols, x_shape, field_height=3, field_width=3, padding=1, stride=1): """ An implementation of col2im based on fancy indexing and np.add.at """ N, C, H, W = x_shape H_padded, W_padded = H + 2 * padding, W + 2 * padding x_padded = np.zeros((N, C, H_padded, W_padded), dtype=cols.dtype) k, i, j = get_im2col_indices(x_shape, field_height, field_width, padding, stride) cols_reshaped = cols.reshape(C * field_height * field_width, -1, N) cols_reshaped = cols_re…
favorite count: 0
has answer: http://stackoverflow.com/a/64457058

http://stackoverflow.com/comment/90507745
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51774267
has text: thanks, this works. can you explain what `sum` is doing?
score: 0

http://stackoverflow.com/a/51654159
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51653495
answers question: http://stackoverflow.com/q/51653495
has comment: http://stackoverflow.com/comment/90272673
type: Answer
has comment: http://stackoverflow.com/comment/90271754
has body: You can remove the entire widget parts in forms.py Your form should just be : class CreateWorkorder(forms.ModelForm): class Meta: model = models.Workorder fields = ['WO_ID', 'WO_DateDefWO', 'WO_Type_ID', 'WO_DateSched', 'WO_Status_ID', 'WO_Nav_ReasonCompl', 'WO_Nav_CustAdr', 'WO_Nav_Name', 'WO_Nav_PhoneNo', 'WO_MapUrl'] Since you have choices specified in models.py, the WO_Type_ID would automatically get rendered as a select tag in html
score: 0

http://stackoverflow.com/a/51690876
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90343496
accepted answer of: http://stackoverflow.com/q/51690770
has comment: http://stackoverflow.com/comment/90343504
answers question: http://stackoverflow.com/q/51690770
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90343847
has body: You cannot restrict what the user inputs, but you can convert a float to have 2 decimal points: value = float(input("Input your number: ")) print ("You inputted " + str(value)) new_value = "{:.2f}".format(value) print ("After formatting, your number has become: " + str(new_value))

http://stackoverflow.com/q/51745485
type: Question
has comment: http://stackoverflow.com/comment/90450622
tagged with: export-to-csv
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: io
has body: What I want to do is to have keys of the first dictionary on the first row and the values of each dictionary be under the first row. like a sql table something like this : title | director | year | genre movie1 director1 1999 Drama movie2 director2 2001 Fantasy movie3 director3 2018 Action movie4 director4 2011 Adventure here is the code : from imdb import IMDb import csv from datetime import datetime startTime = datetime.now() movie_id = 1 for i in range(1, 6): movie = ia.get_movie(movie_id) movie_id += i print(datetime.now() - startTime) print (movie_id) print ('\n') with open('dict.csv', 'a') as csv_file: writer = csv.writer(csv_file) for key, value in movie.items(): writer.writerow([key, value]) here in each loop each dictionary will be appended to csv
tagged with: python
has title: How to write python dictionary to the csv file in sql databases format?
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51752581
downvote count: 0
score: 1
tagged with: multiple-matches
type: Question
has comment: http://stackoverflow.com/comment/90466448
has comment: http://stackoverflow.com/comment/90465010
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90465560
has title: Storing Python RegEx multiple groups
linked to: http://stackoverflow.com/q/19871253
has answer: http://stackoverflow.com/a/51753905
accepted answer: http://stackoverflow.com/a/51753905
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I'm webscraping a site using python. The returned results have the following format, ( https://regex101.com/r/irr14u/10 ), where everything works ok apart from the last occassion where i get 2 matches for the dates (1st match:Thur.-Sun., Tue., Wed. and second match: Mon.) I'm using the following code to get the values that i want. I use BeautifoulSoup to get movieDate string, but here i hardcoded it. movieDate="Thur.-Sun., Tue., Wed.: 20.50/ 23.00, Mon. 23.00" weekDays=re.match(',? *(?P<weekDays>[^\d:\n]+):? *(?P<startTime>[^,\n]+)', movieDate).groupdict()['weekDays'] startTime=re.match(',? *(?P<weekDays>[^\d:\n]+):? *(?P<startTime>[^,\n]+)', movieDate).groupdict()['startTime'] I want to create a dictionary as following (it has two keys because the are two startTime values); The first key will be Thur.-Sun., Tue., Wed. with value =20.50/ 23.00 and the second key will be Mon. with value=23:00. There might be occassions with one or more than two keys. So the dictionary will be as following; dictionary={ Thur.-Sun., Tue., Wed.: 20.50/ 23.00, Mon.: 23.00} Any suggestions to achieve that in a non boggy way?

http://stackoverflow.com/q/51762805
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: def bubble_sort(alist): i = 0 j = 0 while i&lt;len(alist): while j&lt;(len(alist)-1-i): if alist[j]&gt;alist[j+1]: temp = alist[j] alist[j] = alist[j+1] alist[j+1] = temp j = j+1 i = i + 1 return alist abc = [54,26,93,17,77,31,44,55,20] alist1 = bubble_sort(abc) print(alist1) I have no idea why this only undergoes one pass. Can someone pls help??
score: -3
has comment: http://stackoverflow.com/comment/90484773
tagged with: python
has answer: http://stackoverflow.com/a/51762969
accepted answer: http://stackoverflow.com/a/51762969
type: AnsweredQuestion
upvote count: 0
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/90484657
has title: Stuck on a bubble sort (only using while loops) in python
downvote count: 3

http://stackoverflow.com/comment/90521755
type: QuestionComment
comment on: http://stackoverflow.com/q/51782044
has text: Update what every ten minutes? Which array? Do you want to scrape every 10 minutes and update the dataframe? Also, what do you want to push/pop, which recent record do you want to display?
score: 0
type: Comment

http://stackoverflow.com/q/51783658
upvote count: 6
type: AnsweredQuestion
tagged with: jinja2
has title: url_for creates a url query string with &amp;
type: Question
has answer: http://stackoverflow.com/a/51784328
answer count: 2
downvote count: 0
has body: Lets say i have the following script in a html template of a flask application &lt;script type="text/javascript"&gt; console.log('{{ url_for('root', arg1='hello', arg2='world') }}') &lt;script&gt; and i have a flask endpoint root() @app.route('/', methods=['GET']) def root(): print(print(request.args)) when i call my page the internal script is rendered to console.log('/api/art_structure?arg2=world&amp;amp;arg1=hello') When I call this url my request.args dict is: ImmutableMultiDict([('amp;arg1', 'hello'), ('arg2', 'world')]) Which is not correct since the key of arg1 is wrong. Any clues how I can prevent jinja2 from converting &amp; to &amp;amp;?
tagged with: flask
tagged with: query-string
accepted answer: http://stackoverflow.com/a/51784328
has answer: http://stackoverflow.com/a/51783778
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/39214564
score: 6
possible better answer: http://stackoverflow.com/a/51783778
tagged with: python

http://stackoverflow.com/q/51788716
tagged with: if-statement
has title: python if does not equal with beautifulsoup and urllib
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/90535605
answer count: 1
has comment: http://stackoverflow.com/comment/90535485
tagged with: beautifulsoup
score: 0
tagged with: operators
has answer: http://stackoverflow.com/a/51790875
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90534986
tagged with: python
has comment: http://stackoverflow.com/comment/90535287
has body: Here is yet another problem I am over thinking. I want the code to only print when the time that I scrape changes. All it does now is just keep printing the current price and never changes. What am I doing wrong? import urllib.request import bs4 as bs while True: # Request Webpage url = urllib.request.urlopen('https://markets.businessinsider.com/index/realtime-chart/dow_jones').read() # Raw Webpage rawpage = bs.BeautifulSoup(url, 'lxml') price = rawpage.find_all('span', class_='push-data')[0] change = rawpage.find_all('span', class_='push-data')[1] currenttime = rawpage.find_all('span', class_='push-data')[3] new_time = "" if new_time != currenttime: print(price.text) print(change.text) print(currenttime.text)

http://stackoverflow.com/a/51733143
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 14
has comment: http://stackoverflow.com/comment/90447536
accepted answer of: http://stackoverflow.com/q/51733114
score: 14
answers question: http://stackoverflow.com/q/51733114
has body: If you're using ax.scatter (or similar) methods, the keyword-argument is s. See the documentation. Alternatively, if you're using ax.plot, and using markers, the keyword-argument is markersize or ms (documentation).

http://stackoverflow.com/q/51764732
downvote count: 2
answer count: 3
possible better answer: http://stackoverflow.com/a/51764912
upvote count: 1
has answer: http://stackoverflow.com/a/51764912
favorite count: 0
tagged with: text-files
has body: I would like to know, how can I extract some data from a specific range in a big data file? Is there a way to read the content beginning and ending with "buzzwords". I would like to read line per line between *NODE and ** *NODE 13021145, 2637.6073002472617, 55.011929824413045, 206.0394346892517 13021146, 2637.6051226039867, 55.21115693303926, 206.05686503802065 13021147, 2634.226986419154, 54.98263035830583, 205.9520084547658 13021148, 2634.224808775879, 55.181857466932044, 205.96943880353476 ** Before *NODE and after ** there are thousand of lines... I know it should look something similar like: a = [] with open('file.txt') as file: for line in file: if line.startswith('*NODE'): # NOW THERE SHOULD FOLLOW SOMETHING LIKE: # Go to next line and "a.append" till there comes the "magical" # "**" Any idea? I am totally new to python. Thanks for help! I hope u know what i mean.
tagged with: input
tagged with: python
tagged with: with-statement
has comment: http://stackoverflow.com/comment/90488185
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90488141
accepted answer: http://stackoverflow.com/a/51764900
type: Question
has answer: http://stackoverflow.com/a/51764900
has title: Extract a part from a file between specific lines
score: -1
has answer: http://stackoverflow.com/a/51764941

http://stackoverflow.com/comment/90553837
comment on: http://stackoverflow.com/a/51798290
has text: can u please explain a little
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51714446
accepted answer of: http://stackoverflow.com/q/51714253
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/51714253
downvote count: 1
has comment: http://stackoverflow.com/comment/90390704
has body: If you are new to programming then this might not be clear but if you think about how you would implement a max() function you only need to iterate through the list one time, a list of n elements. So the complexity would be at most O(n). However you have to assume that whoever wrote any built-in method has optimized it. Hence O(n) is an upper bound on the complexity. The best thing you can do now or in the future is to look at the documentation about the function you are using, either it will tell you the complexity or by looking at the code you will be able to extrapolate it yourself.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51728654
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90485796
has body: This started as a comment but was getting a bit too long. Indeed OpenCV computes the reprojection error internally and does not return it. But you could do the same by yourself once you obtain the homography, no? As a matter of fact the algorithm minimizes the sum of the reprojection error over all the points. A quite complete description of the process is in the OpenCV docs Since you have the matches (hence the image coordinates of both source and template points). You can compute the average reprojection error, possibly only using points that are treated as inliers, for each of the templates and choose the lowest one. From a similar answer on another site: computed_pt = H * source_pt error_pt = sqrt( (computed_pt.x - dst_pt.x)*(computed_pt.x - dst_pt.x) + (computed_pt.y - dst_pt.y)*(computed_pt.y - dst_pt.y) ) to compute the euclidean distance between the two points.
type: Answer
has comment: http://stackoverflow.com/comment/90590797
downvote count: 0
has comment: http://stackoverflow.com/comment/90456200
accepted answer of: http://stackoverflow.com/q/51721466
has comment: http://stackoverflow.com/comment/90441172
answers question: http://stackoverflow.com/q/51721466

http://stackoverflow.com/q/51657097
has title: How can I retrieve binary data using Mysql Python connector?
score: 2
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/99038852
type: UnansweredQuestion
tagged with: python
upvote count: 2
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/55032925
has body: If I create a simple table in MySQL with binary data: CREATE TABLE foo ( bar binary(4) ) INSERT INTO foo (bar) VALUES ( UNHEX('de12') ) Then try to read it using the MySQL Connector/Python: import mysql.connector conn = mysql.connector.connect(database='test', user='test') cursor = conn.cursor() cursor.execute("SELECT * FROM foo") cursor.fetchall() I get this error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xde in position 0: invalid continuation byte I don't understand why the Python MySQL connector is trying to decode the column as UTF-8. I just want to get the raw binary data, how can I do this? (Python 2.7.10, Mysql 5.7.22, MySQL Connector/Python 8.0.12)

http://stackoverflow.com/q/51660449
type: UnansweredQuestion
tagged with: multithreading
tagged with: pickle
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/90350918
has answer: http://stackoverflow.com/a/51673467
has body: I am working with a decent amount finacial data that I store in a python collection of objects. I am initially getting the data from text files, creating the objects and then pickeling them, so that I do bot have to go through the process of creating the objects again. The pickle size is close to 1 gb. Loading the pickle takes about 1 min 30 seconds. I need to reduce the amount it takes the pickle to load. I am running diferent simulations stopping and starting the runs. Therefore everytime I re run the simulation, I need to reload the pickle. I tried to solve the issue by creating a singleton and hopefully load the pickle just once. Afterwards I hoped that I could access the singleton in other “runs” and not have the need to reload it as it was already in memory. However, that is not working. I am lookimg for a solution to keep the object in memory without the need to reload the pickle. Any suggestions?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has title: Keep object in memory and avoid reloading pickle
score: 2
tagged with: memory-management
upvote count: 2

http://stackoverflow.com/q/51772148
score: 0
has title: Trying to learn how to calculate variance by myself, however don't understand this error
answer count: 3
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51772313
tagged with: python
has comment: http://stackoverflow.com/comment/90503049
has comment: http://stackoverflow.com/comment/90503109
has comment: http://stackoverflow.com/comment/90503071
has answer: http://stackoverflow.com/a/51772230
type: Question
has body: investment2 = [12, -2, 10, 0, 7, 3] investment2_mean = sum(investment2)/len(investment2) print(investment2_mean) for x in investment2: squaring_step = (x-investment2_mean)**2 variance = sum(squaring_step) print(variance) variance = sum(squaring_step) TypeError: 'float' object is not iterable
has answer: http://stackoverflow.com/a/51772330
tagged with: statistics

http://stackoverflow.com/q/51667115
has comment: http://stackoverflow.com/comment/90297288
type: Question
answer count: 2
downvote count: 0
tagged with: bootstrap-4
favorite count: 0
has answer: http://stackoverflow.com/a/51667337
has title: Django, Running 'createsuperuser' on Visual Studio Command-line Error
has body: Hi, I want to user Python 3.7 and Django 2.1 in Visual Studio. I just create a new Django project from Visual Studio. It creates the Python-Django project. But when I try to run 'createsuperuser' command from command-line on Visual Studio, I am getting this long error text. I have the Python 3.7 and Django 2.1 version on my computer so I think It is not about the version. How can I solve this problem? Traceback (most recent call last): File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\manage.py", line 17, in &lt;module&gt; execute_from_command_line(sys.argv) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebPr…
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51667364
score: 1

http://stackoverflow.com/a/51721575
accepted answer of: http://stackoverflow.com/q/51721499
score: 0
answers question: http://stackoverflow.com/q/51721499
type: Answer
has body: Try this: EntDicts = {} for Ent in Ents: EntDicts[Ent] = {} Then use EntDicts at will...
type: AcceptedAnswer

window
tags question: http://stackoverflow.com/q/51647603
tags question: http://stackoverflow.com/q/51797925
tags question: http://stackoverflow.com/q/51730930
tags question: http://stackoverflow.com/q/51760955
tag name: window
type: Tag

http://stackoverflow.com/comment/90303717
comment on: http://stackoverflow.com/q/51668485
type: Comment
type: QuestionComment
has text: @hoefling python -V ----> Python 3.6.3 / pip -V ----> pip 9.0.1... (python 3.6)
score: 0

qt
tags question: http://stackoverflow.com/q/51665100
type: Tag
tags question: http://stackoverflow.com/q/51784299
tags question: http://stackoverflow.com/q/51750501
tags question: http://stackoverflow.com/q/51686198
tags question: http://stackoverflow.com/q/51644481
tag name: qt
tags question: http://stackoverflow.com/q/51670832

http://stackoverflow.com/comment/90383797
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51711188
has text: file = 'C:\\mydocuments\\RCExport.rar'
score: 0

http://stackoverflow.com/q/51722449
favorite count: 0
has comment: http://stackoverflow.com/comment/90405299
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90405999
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90405297
has comment: http://stackoverflow.com/comment/90405853
answer count: 0
has comment: http://stackoverflow.com/comment/90405735
upvote count: 3
has comment: http://stackoverflow.com/comment/90405418
tagged with: namespace-organisation
downvote count: 1
has title: Any way for python file name to not end up in fully qualified name?
has comment: http://stackoverflow.com/comment/90405650
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90406108
has comment: http://stackoverflow.com/comment/90409558
has comment: http://stackoverflow.com/comment/90405427
score: 2
has comment: http://stackoverflow.com/comment/90405549
has comment: http://stackoverflow.com/comment/90405578
has comment: http://stackoverflow.com/comment/90405698
has body: Say we have this file structure: project/ - ticklers/ - kitten_tickler.py - class KittenTickler - puppy_tickler.py - class PuppyTickler Assume KittenTickler has enough complexity to not want to share its file with PuppyTickler. The fully qualified names of the defined classes become project.ticklers.kitten_tickler.KittenTickler and project.ticklers.puppy_tickler.PuppyTickler. This is, obviously, redundant. It works well with the usual Python policy of stuffing multiple classes into one file, but it doesn't fit my project. Is there any way to "skip" the file name in the module chain, aggregating puppy_tickler and kitten_tickler contents into ticklers module? Ultimately, I'm interested in having just project.ticklers.PuppyTickler and project.ticklers.KittenTickler. I tried putting this into project/ticklers/__init__.py: from .kitten_tickler import KittenTickler from .puppy_tickler import PuppyTickler which results in them being accessible in both packages, but KittenTickler.__module__ still ends up being project.ticklers.kitten_tickler (whereas I'd want it as project.ticklers). Additionally, if I do from project.ticklers import KittenTickler I will also inadvertently import PuppyTickler as well. So I am not too happy with this approach. Finally, it is not very maintainable. Am I fighting a losing battle here, or is there a way for me to declare these classes to my satisfaction?
has comment: http://stackoverflow.com/comment/90405467

http://stackoverflow.com/a/51777192
has body: The applicationform.wsgi: application in your command line actually tells gunicorn to run the function named application() in the Python module applicationform/wsgi.py. In your case there is no applicationform directory under your working directory, which is ~/applicationform/newProject. You should run it from the ~/applicationform directory and the app name would then be newProject.wsgi, i.e.: ~/applicationform$ gunicorn --bind 0.0.0.0:8000 newProject.wsgi:application
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51757619
type: Answer
accepted answer of: http://stackoverflow.com/q/51757619
score: 0

http://stackoverflow.com/comment/90343239
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51690628
has text: because i want to make it ready to train a keras model classifier

http://stackoverflow.com/q/51739187
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51739338
tagged with: python
has comment: http://stackoverflow.com/comment/90438531
type: UnansweredQuestion
has title: How to get the name of a variable through its value
score: -1
has body: I would like to be able to generate a dictionary contains the value of the variable and the name of the variable. Therefore I also have to get the name of a variable through the value of the variable. For example, there's a list named my_list. my_list = ["foo", "egg"] then there are variables like this. foo = "What the foo" egg = "My egg is big" Finally, I tried this code: def return_string(name): return name GetNameFromStr = {} for i in range(len(my_list)): GetNameFromStr[exec("return_string(my_list[i])")] = my_list[i] print(GetNameFromStr) But it is not working for me. output: {'foo': 'foo', 'egg': 'egg'}. And this is the dictionary I want: {'What the foo': 'foo', 'My egg is big': 'egg'}
has answer: http://stackoverflow.com/a/51739256
type: Question
has comment: http://stackoverflow.com/comment/90438633
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/90327965
comment on: http://stackoverflow.com/q/51681276
score: 0
has text: It's very interesting question but I think it's not possible via Selenium.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53304095
type: Answer
has body: Basically, The entities of a list are pointers to a particular memory location. When one assigns list(a) to list(b) It implies that list(b) points to the same memory location as the list(a). a = [1, 2, 3] b = a a = [3, 4, 5] print(a, b) [3, 4, 5] [1, 2, 3] In the above-asked question if the inside of the nested list is multiplied by 4 times then all the sublists point to the same memory location. so, If one of the sublists is changed then the change is propagated to all of the sublists, Which basically creates unexpected results upon code execution. For anyone interested to know more, the video sums up all the basic features of lists that are not obvious. It also explains the above question in further detail. https://www.youtube.com/watch?v=_AEJHKGk9ns
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51741054
accepted answer of: http://stackoverflow.com/q/51741054
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51716063
favorite count: 0
type: Question
tagged with: seaborn
tagged with: python
has title: Seaborn Heatmap Y-tick Labels Stacked
tagged with: heatmap
upvote count: 1
type: UnansweredQuestion
has body: I'm working with biological data, and am using the heatmap from Seaborn to plot Pearson R values so I can visually compare expression of each of 22 cell types with every other cell type (making a 22x22 heatmap). I've had two separate problems. Here is what my plots looked like the other day: You can see that in one plot the y-tick labels are spaced, but the last label is clipped off. Then in the other plot, all of the y-tick labels are present, but are spaced too tightly. Here's what my plots look like today. I foolishly am not sure what I changed when trying to fix the issue in the first image (aside from changing vmin and vmax, and the color scheme), but now the y-tick labels are all on top of each other. The y-ticks are all on top of each other. Here is my code to generate the heatmaps: def cancerHeatmap(patients, cancer): x_labels = ['Naive B','Memory B','Plasma','CD8 T','CD4 T Naive','CD4 T MR', 'CD4 T MA','FH T','Tregs','GD T', 'NK resting','NK activated','Monos','Macros M0','Macros M1','Macros M2', 'Dendritic resting','Dendritic activated','Mast resting','Mast activated','Eosinophils','Neutrophils'] pearsonrs = getPearsons(patients, cancer) axs = sns.heatmap(pearsonrs, cmap = 'RdYlBu', vmin=-0.6, vmax=0.6) axs.set_yticklabels(x_labels, rotation = 0, fontsize = 10) axs.set_xticklabels(x_labels, rotation = 90) axs.xaxis.set_ticks_position('top') axs.set_xlabel(cancer) return axs sns.set_style("whitegrid") sns.despine() plt.figure(figsize=(12,70)) plt.suptitle('Subtitle') for i, cancer in enumerate(cancer_types): print cancer plt.subplot((len(cancer_types)/2)+1,2, i+1) ax = cancerHeatmap(patients, cancer) plt.tight_layout(rect=[0, 0, 1, 0.97]) plt.savefig('outfile.pdf', dpi=200) The important details of this are: "pearsonrs" is a function that generates the numpy array of all of the values that go directly into the heatmap "cancer_types" is a list of the different cancer types that I'll be generating heatmaps for I have no idea why this is happening, especially …
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51793103
type: UnansweredQuestion
tagged with: python
has title: Python3 move mouse in DirectX games
has body: I'm trying to build create a script that does a few action inside an DirectX game. I've got everything working exept for moving the mouse. Is there any module avalable that can move the mouse, for windows (python 3) Thanks!
score: 2
type: Question
has answer: http://stackoverflow.com/a/51793361
has answer: http://stackoverflow.com/a/51793147
tagged with: directx
answer count: 2
tagged with: windows
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2

apache
tag name: apache
tags question: http://stackoverflow.com/q/51778133
tags question: http://stackoverflow.com/q/51705552
tags question: http://stackoverflow.com/q/51694915
tags question: http://stackoverflow.com/q/51713115
tags question: http://stackoverflow.com/q/51774703
tags question: http://stackoverflow.com/q/51747454
tags question: http://stackoverflow.com/q/51777546
tags question: http://stackoverflow.com/q/51645608
tags question: http://stackoverflow.com/q/51725832
tags question: http://stackoverflow.com/q/51690304
tags question: http://stackoverflow.com/q/51698649
type: Tag
tags question: http://stackoverflow.com/q/51715469
tags question: http://stackoverflow.com/q/51713414
tags question: http://stackoverflow.com/q/51741037

http://stackoverflow.com/a/51746511
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The in operator can help you determine if something is in another thing, as shown below: for line in file: if "desired string" in line: print("It's here") Some examples from IDLE: &gt;&gt;&gt; s = "this is a string" &gt;&gt;&gt; a = s.split() &gt;&gt;&gt; a ['this', 'is', 'a', 'string'] &gt;&gt;&gt; t = (1, 3, 32, 4) &gt;&gt;&gt; 'is' in s True &gt;&gt;&gt; 'is' in a True &gt;&gt;&gt; 'is' in a[0] True &gt;&gt;&gt; 'is' in t False &gt;&gt;&gt; 1 in t True &gt;&gt;&gt; 32 in t True
answers question: http://stackoverflow.com/q/51746376

http://stackoverflow.com/comment/90485369
has text: It's correct and you can mark it as answer. However, in some cases you should call [`Gtk.Widget.add_events()`](http://lazka.github.io/pgi-docs/index.html#Gtk-3.0/classes/Widget.html#Gtk.Widget.add_events) first.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51755893
type: Comment

http://stackoverflow.com/a/51671360
type: Answer
score: 1
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51670451
answers question: http://stackoverflow.com/q/51670451
type: AcceptedAnswer
has body: Well, it's the usual tradeoff between performances and flexibility. With the first approach you get better performances (your schema is taylored for the exact queries you want to run) but lacks flexibility (if you need to add more queries the scheam might not match so well - or even not match at all - in which case you'll have to repopulate the database, possibly from raw sources, with an updated schema), with the second one you (hopefully) have a well normalized schema but one that makes queries much more complex and much more heavy on the database server. Now the question is: do you really have to choose ? You could also have both the fully normalized data AND the denormalized (pre-processed) data alongside. As a side note: Django ORM is indeed most of a "80/20" tool - it's designed to make the 80% simple queries super easy (much easier than say SQLAlchemy), and then it becomes a bit of a PITA indeed - but nothing forces you to use django's ORM for everything (you can always drop down to raw sql or use SQLAlchemy alongside). Oh and yes: your problem is nothing new - you may want to read about OLAP
has comment: http://stackoverflow.com/comment/90312499

http://stackoverflow.com/comment/90438965
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51739398
has text: i already tried it. but if the image is to sparse its return as blur.
type: Comment

http://stackoverflow.com/comment/90320397
has text: if you change your variables to be consistent (*e.g.* make sure you always use `X` or `x`, capitalization matters), your code would be fine
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51678572

http://stackoverflow.com/a/51653175
answers question: http://stackoverflow.com/q/51653124
score: 0
type: Answer
has body: If you are creating the file use the write mode w or use a+ f = open(nameDir, 'w') f = open(nameDir, 'a+') Use only a append if the file already exist.

http://stackoverflow.com/q/51772199
has title: Scrapy-Splash doesn't set custom request headers
downvote count: 0
score: 4
has body: I am trying to scrape a website using Scrapy + Splash in Python 2.7. The website uses JavaScript to generate most of the HTML, which is why I need Splash. First, I make a FormRequest with Scrapy to login to a website. It is successful. I then extract "access_token" from JSON response, because it should be used in the next request as an "Authorization" header - to confirm to the website that I am logged in. jsonresp = json.loads(response.body_as_unicode()) self.token = 'Bearer ' + jsonresp['access_token'] self.my_headers['Authorization'] = self.token Before proceeding with SplashRequest, I decided to test the session with scrapy.Request. I passed cookies and the new headers: yield scrapy.Request('https://www.example.com/products', cookies=self.cookies, dont_filter=True, callback=self.parse_pages, headers=self.my_headers) The HTML from result.body confirmed that I was logged in. Great! Calling response.request.headers showed that 'Authorization' header was also sent. {'Accept-Language': ['en-US,en;q=0.5'], 'Accept-Encoding': ['gzip,deflate'], 'Accept': ['application/json, text/plain, */*'], 'User-Agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'], 'Connection': ['keep-alive'], 'Referer': ['https://www.example.com/Web'], 'Cookie': ["___cookies___"], 'Content-Type': ['application/x-www-form-urlencoded'], 'Authorization': ['Bearer Zyb9c20JW0LLJCTA-GmLtEeL9A48se_AviN9xajP8NZVE8r6TddoPHC6dJnmbQ4RCddM8QVJ2v23ey-kq5f8S12uLMXlLF_WzInNI9eaI29WAcIwNK-FixBpDm4Ws3SqXdwBIXfkqYhd6gJs4BP7sNpAKc93t-A4ws9ckpTyih2cHeC8KGQmTnQXLOYch2XIyT5r9verzRMMGHEiu6kgJWK9yRL19PVqCWDjapYbtutKiTRKD1Q35EHjruBJgJD-Fg_iyMovgYkfy9XtHpAEuUvL_ascWHWvrFQqV-19p-6HQPocEuri0Vu0NsAqutfIbi420_zhD8sDFortDmacltNOw-3f6H1imdGstXE_2GQ']} Cookie DEBUG showed that all cookies were sent without issues. After that I substituted scrapy.Request with SplashRequest: yield SplashRequest('https://www.example.com/products', cookies=self.cookies, callback=self.parse_pages, args={"lua_source…
tagged with: header
tagged with: splash-screen
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: request
tagged with: scrapy
type: Question
upvote count: 4

http://stackoverflow.com/q/51650325
has body: I'm currently processing images that consist of a stack, 18 images per stack. I then deconvolve these images to produce cleaner sharper images. However when doing this I get border artifacts. I have spent some time writing code so as to determine how wide a pad I would need to pad these images, however I am unsure of how to use np.pad so that I may produce padded images. This is my code so far: xextra = pad_width_x / 2 yextra = pad_width_y / 2 print (xextra) print (yextra) Where xextra and yextra are the pad widths I will be using. I understand that I will need to use this line of code to pad the array: no_borders = np.pad(sparsebeadmix_sheet_cubic_deconvolution, pad_width_x, mode='constant', constant_values=0) However how will I be able to process my stack of images (18 images) through this and save them as outputs? I hope this makes sense!
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/76123172
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to pad an image using np.pad in python?
score: 3
has answer: http://stackoverflow.com/a/51662925
tagged with: image-processing
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/90329742
type: Comment
type: QuestionComment
score: 1
has text: Why you not added full string? I mean output should be `['python prog', 'prog', 'programming', 'python programming']`, no?
comment on: http://stackoverflow.com/q/51683606

http://stackoverflow.com/comment/90272386
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51653316
has text: @Eugene Do you know why is this all of the sudden necessary for the app to run on my local server just for development? I wasn't having this problem before...
score: 0

http://stackoverflow.com/q/51748513
has answer: http://stackoverflow.com/a/51749109
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
downvote count: 0
type: Question
has body: Is it possible to use a passed parameter as a value in a django query string? So, let's pretend I want to search for specific terms (in term_list) in different fields, like username, display_name or name. Instead of doing this multiple times: q1_username = Q(username__icontains=term_list[0]) q1_email = Q(email__icontains=term_list[0]) q2_username = Q(display_name__icontains=term_list[0]) q2_email = Q(e_mail__icontains=term_list[0]) q3_username = Q(name__icontains=term_list[0]) q3_email = Q(emailaddress__icontains=term_list[0]) I want to be able to do this in a more generic way for different cases: q1_username = "display_name" q1_email = "emailaddress" q1 = build_query(term_list, q1_username, q1_email) def build_query(term_list, passed_username, passed_email): q_username = Q(insert_passed_username_here__icontains=term_list[0]) q_email = Q(insert_passed_email_here__icontains=term_list[0]) # ... return query If I try it like that, I get, not surprisingly, the following error message: Cannot resolve keyword 'insert_passed_username_here' into field. How can I use the passed_username and passed_email to replace the insert_passed_username_here and insert_passed_email_here in the function? EDIT: According to the answer from @Tsang-Yi Shen I updated my function but I'm still getting errors. So let's edit my question like this, to make my case more clear: I have several usernames and emails in different databases like this: """query 1""" q1_username = Q(username__icontains=term_list[0]) q1_email = Q(email__icontains=term_list[0]) special_q1 = q1_username | q1_email for term in term_list[1:]: special_q1.add((Q(username__icontains=term) | Q(email__icontains=term)), special_q1.connector) """query 2""" q2_username = Q(name__icontains=term_list[0]) q2_email = Q(email__icontains=term_list[0]) special_q2 = crimenetwork_username | crimenetwork_email for term in term_list[1:]: special_q2.add((Q(name__icontains=term) | Q(email__icontains=term)), special_q2.connector) After building thi…
upvote count: 2
has title: Use passed parameter as a value in query string in django
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90324119
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51680235
type: QuestionComment
has text: Taking the 2nd byte as the msb

http://stackoverflow.com/comment/90287174
has text: ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'>
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51661859
type: AnswerComment

http://stackoverflow.com/comment/119226827
comment on: http://stackoverflow.com/a/51715793
score: 0
type: AnswerComment
has text: It works if the object is near to a perfect rectangle. Thinking on captured images with a camera, it could have a perspective distortion. Then the rectangle doesn't fit
type: Comment

http://stackoverflow.com/q/51743690
tagged with: dataframe
has title: python pandas dataframe KDEplot density levels coloring issue
score: 0
tagged with: pandas
answer count: 1
has body: I Have a pandas df and I want to create a KDE plot. At first when I call g = sns.jointplot("s_zscore","p_zscore",s=2, data=scatter_all, kind="scatter") That is OK and as we see the data is scatterted to 4 2D clusters. Regular KDE plot confirms this: g = sns.jointplot("s_zscore","p_zscore",s=2, data=scatter_all, kind="kde") But now when I provide my own density levels weird things happen - for some reason in the subspace with the highest density I get a white circle: g = sns.jointplot("s_zscore","p_zscore",s=2, data=scatter_all, kind="kde",levels=density_levels) This is clearly wrong. Does anyone know what the hell is happening here? ======================================= EDIT: Ok I figured it has something to do with the levels I provide: g = sns.jointplot("s_zscore","p_zscore",s=2, data=scatter_all, kind="kde",levels=density_levels+[0.03]) g = sns.jointplot("s_zscore","p_zscore",s=2, data=scatter_all, kind="kde",levels=density_levels+[0.09]) So now - How should I choose the maximal value for the largest isoline? The density_levels contain percentiles At which I want to make a boundary.
tagged with: seaborn
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51772629
type: Question
tagged with: kernel-density
has answer: http://stackoverflow.com/a/51772629

http://stackoverflow.com/comment/90533005
type: Comment
has text: Go ahead, you can edit my post, as long as you make sure you don't break the code, and that the next poster can still use it. It is all yours to play with.
comment on: http://stackoverflow.com/a/51786751
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90397718
comment on: http://stackoverflow.com/a/51717789
score: 0
has text: I doubt it's a caching issue. in your manage.py file, are you referencing the correct settings.py as the root of your project? What happens if you run `python manage.py shell` and run `from django.conf import settings; print(settings.SECRET_KEY)`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/135043398
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/66442394
type: Comment
has text: Starting with Python 3.12 your first code snippet [works](https://peps.python.org/pep-0701/)

http://stackoverflow.com/comment/90423272
comment on: http://stackoverflow.com/q/51731220
type: QuestionComment
type: Comment
score: 0
has text: "Please note that I used () instead of <> above": ah: those `<>` in examples represent placeholders, to indicate the actual value should be changed, *and* the `<>` discarded. You certainly *cannot* replace them by parentheses at will. Instead, ignore the `<>`, use the correct file name, and certainly don't use `()`.

http://stackoverflow.com/comment/90547761
score: 0
comment on: http://stackoverflow.com/q/51795062
type: Comment
has text: Oops just realized that >_< What you've posted is definitely not a csv file and as such probably can't be parsed easily with `read_csv`
type: QuestionComment

http://stackoverflow.com/q/51702259
has answer: http://stackoverflow.com/a/51702333
type: Question
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/90365504
accepted answer: http://stackoverflow.com/a/51702333
upvote count: 0
answer count: 1
tagged with: python
tagged with: python-2.x
linked to: http://stackoverflow.com/q/21122540
favorite count: 0
has comment: http://stackoverflow.com/comment/90365590
downvote count: 2
duplicate of: http://stackoverflow.com/q/21122540
has body: So im trying to make a conversation generator in python using the fashion of an AI where the user will say something like 'hi' and then the machine replies 'hello how are you' and as you can guess, this will need alot of user input but every time i input ANYTHING, i get the output: Traceback (most recent call last): File "main.py", line 4, in &lt;module&gt; talk=input('') File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name '___' is not defined heres my code: #Modules import os #Getting User Input talk=input('') #Machine responding if talk == "Hi": print('Hey, how are you?') feeling=input('') if feeling == "good": print('Thats good!') if feeling == "bad": print('aww thats bad, maybe chatting with me will help?') #Restarting The script os.system('python main.py') Just for some extra info, im using python 3 running scripts via ubuntu root terminal All help is greatly appreciated. Thanks.
has comment: http://stackoverflow.com/comment/90365551
has title: python problems with getting user input

http://stackoverflow.com/q/51703269
score: 1
has comment: http://stackoverflow.com/comment/90367445
has comment: http://stackoverflow.com/comment/90369335
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51703420
answer count: 3
has comment: http://stackoverflow.com/comment/90367771
has comment: http://stackoverflow.com/comment/90367558
downvote count: 0
tagged with: string
has title: Find a string within a string using pattern matching in python
has comment: http://stackoverflow.com/comment/90367411
favorite count: 0
has body: I'd like to use part of a string ('project') that is returned from an API. The string looks like this: {'Project Title': 'LS003942_EP - 5 Random Road, Sunny Place, SA 5000'} I'd like to store the 'LS003942_EP... ' part in a new variable called foldername. I'm thought a good way would be to use a regex to find the text after Title. Here's my code: orders = api.get_all(view='Folder', fields='Project Title', maxRecords=1) for new in orders: print ("Found 1 new project") print (new['fields']) project = (new['fields']) s = re.search('Title(.+?)', result) if s: foldername = s.group(1) print(foldername) This gives me an error - TypeError: expected string or bytes-like object. I'm hoping for foldername = 'LS003942_EP - 5 Random Road, Sunny Place, SA 5000'
accepted answer: http://stackoverflow.com/a/51703420
has answer: http://stackoverflow.com/a/51704184
possible better answer: http://stackoverflow.com/a/51703365
has comment: http://stackoverflow.com/comment/90367875
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51703365
has comment: http://stackoverflow.com/comment/90367501
type: AnsweredQuestion

http://stackoverflow.com/q/51730056
has comment: http://stackoverflow.com/comment/90421577
type: Question
has comment: http://stackoverflow.com/comment/90421055
has title: Battleship: How to automate instances creation?
answer count: 2
has comment: http://stackoverflow.com/comment/90421144
tagged with: class
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: I'm making a game of battleships. I created a Ship class to give the ships a location. After making the class, I had to create all the instances, and I was wondering if there is a way to automate that. Most of the program is irrelevant, but I'm leaving it in just in case it might affect whether or not it can be automated. import random class Ship(object): def __init__(self, length): self.length = length def direction(self): vh = random.choice(['v','h']) return vh def location(self): space = [] row = random.randint(0, 10-self.length) column = random.randint(0, 10-self.length) if self.direction == 'v': for x in range(self.length): space.append(f'{column}{row+x}') else: for x in range(self.length): space.append(f'{column}{row+x}') return space ships_amount = { 'carrier' : 1, 'battleship' : 2, 'cruiser' : 3, 'destroyer' : 4 } ships_length = { 'carrier' : 5, 'battleship' : 4, 'cruiser' : 3, 'destroyer' : 2 } I want to do this: carrier1 = Ship(ships_length['carrier']) battleship1 = Ship(ships_length['battleship']) battleship2 = Ship(ships_length['battleship']) cruiser1 = Ship(ships_length['cruiser']) cruiser2 = Ship(ships_length['cruiser']) cruiser3 = Ship(ships_length['cruiser']) destroyer1 = Ship(ships_length['destroyer']) destroyer2 = Ship(ships_length['destroyer']) destroyer3 = Ship(ships_length['destroyer']) destroyer4 = Ship(ships_length['destroyer']) but automated
tagged with: python
has comment: http://stackoverflow.com/comment/90420869
tagged with: oop
score: 1
has comment: http://stackoverflow.com/comment/90420883
has answer: http://stackoverflow.com/a/51730479
has answer: http://stackoverflow.com/a/51730247
downvote count: 1

http://stackoverflow.com/comment/90497059
comment on: http://stackoverflow.com/q/51768192
has text: `to_excel` can be quite a slow operation, particularly with large amounts of data. Could you try writing to a csv instead?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51772961
type: Answer
has body: If one one the dict does not have a seq key, you will have the KeyError. You can prevent this by giving a default return value to pop(): i.pop("seq", None)
answers question: http://stackoverflow.com/q/51772851
accepted answer of: http://stackoverflow.com/q/51772851
has comment: http://stackoverflow.com/comment/90505204
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90505226
has comment: http://stackoverflow.com/comment/90505142
score: 0

http://stackoverflow.com/a/51650915
has comment: http://stackoverflow.com/comment/90275009
has body: You can use relative imports as it presented in documentation. So you can try something like this in your preprocess module: from ..utils import config
has comment: http://stackoverflow.com/comment/90287445
answers question: http://stackoverflow.com/q/51650710
has comment: http://stackoverflow.com/comment/90278513
upvote count: 1
has comment: http://stackoverflow.com/comment/90269137
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51752918
type: Question
tagged with: matplotlib
linked to: http://stackoverflow.com/q/25538520
score: 4
has body: I am trying get daily data plot. I have 3 months of data and its really hard to point out each day. How can I format x axis, so that I can get every date?
upvote count: 4
answer count: 1
downvote count: 0
tagged with: xticks
favorite count: 0
type: UnansweredQuestion
tagged with: datetime
has answer: http://stackoverflow.com/a/51813974
tagged with: python
has title: Formatting x axis with per day frequency

http://stackoverflow.com/a/51745362
accepted answer of: http://stackoverflow.com/q/51745197
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51745197
has body: If you are 100% sure that the data is "safe", you could eval it as the parameters to dict: &gt;&gt;&gt; key_val = "count=2, name=['hello', 'hi'], word='Dial::100', roll=12" &gt;&gt;&gt; eval("dict(%s)" % key_val) {'count': 2, 'name': ['hello', 'hi'], 'roll': 12, 'word': 'Dial::100'} If you are not sure, better don't use eval, though. Alternatively, you could use your regex and use ast.literal_eval to evaluate the value: &gt;&gt;&gt; regx = r'(?P&lt;key&gt;\w+)=(?P&lt;value&gt;\[.+?\]|\d+|\S+)' &gt;&gt;&gt; {k: ast.literal_eval(v) for k, v in re.findall(regx, key_val)} {'count': 2, 'name': ['hello', 'hi'], 'roll': 12, 'word': ('Dial::100',)} (Note: I did not check your regex in detail.) You could also try to apply ast.literal_eval to the entire expression, instead of the less safe eval, but this would require some preprocessing, e.g. replacing = with : and adding quotes to the keys, that might not work well with e.g. string values containing those symbols.

http://stackoverflow.com/comment/90504716
comment on: http://stackoverflow.com/a/51772313
has text: Thanks Matina for the answer, I'm still super beginner and it helped me alot
score: 0
type: AnswerComment
type: Comment

arp
tags question: http://stackoverflow.com/q/51792539
type: Tag
tag name: arp

http://stackoverflow.com/comment/90461053
type: Comment
comment on: http://stackoverflow.com/a/51750535
has text: I like this, but when I generalize your solution to `s = sum([df[column].astype(str) for column in df])`, why am I getting the unsupported type exception again?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/120598439
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51645550
has text: Really good answer. just one small correction in the explanation of second example of 'right' join -- "Rows with labels `3` and `4` have been added to df1, filled with `Nan`."
type: AnswerComment

http://stackoverflow.com/q/51738274
has title: Tornado server on Heroku. Error R10 (Boot Timeout)
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51738304
tagged with: heroku
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0
has body: I am trying to deploy a web app that I wrote in Python using tornado server. In my app.py I have if __name__ == '__main__': server = tornado.httpserver.HTTPServer(Application()) server.listen(4200, address='0.0.0.0') tornado.ioloop.IOLoop.instance().start() I then have a Procfile that has web: python app.py When I check the logs I see the error 2018-08-08T02:20:54.117821+00:00 heroku[web.1]: Starting process with command `python app.py` 2018-08-08T02:20:57.000000+00:00 app[api]: Build succeeded 2018-08-08T02:21:54.891301+00:00 heroku[web.1]: Error R10 (Boot timeout) -&gt; Web process failed to bind to $PORT within 60 seconds of launch 2018-08-08T02:21:54.891301+00:00 heroku[web.1]: Stopping process with SIGKILL 2018-08-08T02:21:55.027586+00:00 heroku[web.1]: Process exited with status 137 2018-08-08T02:21:55.049407+00:00 heroku[web.1]: State changed from starting to crashed 2018-08-08T02:21:55.051776+00:00 heroku[web.1]: State changed from crashed to starting 2018-08-08T02:21:59.562357+00:00 heroku[web.1]: Starting process with command `python app.py` I don't know too much of what I'm doing, especially with the Procfile so I'm guessing the issue lies there.
favorite count: 0
has answer: http://stackoverflow.com/a/51738304
tagged with: procfile
answer count: 1
tagged with: deployment

http://stackoverflow.com/q/51700590
has title: How to store the data in little endian format in a binary file in Python
has comment: http://stackoverflow.com/comment/90363251
tagged with: endianness
score: 0
tagged with: binaryfiles
answer count: 1
type: UnansweredQuestion
tagged with: binascii
tagged with: python
has answer: http://stackoverflow.com/a/78171692
has comment: http://stackoverflow.com/comment/90363792
tagged with: file
has body: I have a binary file. I want to read hexadecimal data from the terminal in my python code. I am executing the program as follows: python hello.py "2DB6C" "CDEF" "2DB6C" :- (Address in hex) Indicates GoTo address &lt;2DB6C> in the temp.bin file, where I want to start writing the data. "CDEF" :- Data to be written in binary file. Remember the data is given in the hex format. I want to write the data in the small endian format. But it is not working for me. file = open("temp.bin", "r+b") file.seek(4) datatomodify = "CDEF" data = binascii.unhexlify(datatomodify) print ("data :", data, "offset addr :", hex(file.tell())) file.write(data) print ("after writing addr :", hex(file.tell())) file.close() It is writing in the file as "CDEF". But I want to write the data in the little endian format. Kindly help me in fixing it.
linked to: http://stackoverflow.com/q/13155570
type: Question

confluent-schema-registry
tags question: http://stackoverflow.com/q/51686422
tag name: confluent-schema-registry
tags question: http://stackoverflow.com/q/51710462
type: Tag

http://stackoverflow.com/comment/90542821
comment on: http://stackoverflow.com/q/51792369
type: Comment
type: QuestionComment
score: 2
has text: If you want to be able to import each package separately... maybe they should be separate packages?

http://stackoverflow.com/a/51728809
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51685200
upvote count: 3
downvote count: 1
has body: Further to @Reblochon Masque's answer, I wrote his code in a loop just to make it look nicer and you can sample as many arrows as you like (for anyone who wants to use it): arrows = 6 # Number of arrows we want p = [] # Coordinates for arrow xs_ = [] ys_ = [] dxs_ = [] dys_ = [] for i in range(arrows): p.append(int(i/arrows*len(t))) # Equally spaced intervals ys_.append(y[p[i]+1]) xs_.append(x[p[i]+1]) dys_.append(y[p[i]]-y[p[i]+1]) dxs_.append(x[p[i]]-x[p[i]+1]) plt.arrow(xs_[i],ys_[i],dxs_[i],dys_[i],shape='full', lw=0, length_includes_head=True, head_width=0.12)

http://stackoverflow.com/q/51745600
tagged with: string
has answer: http://stackoverflow.com/a/51746224
tagged with: byte
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51746207
score: 2
has title: Delete some specific content from byte in python 3
type: Question
answer count: 2
has body: I have no idea of how to delete '\x00' from the following byte.Currently, I am trying to write this byte to a text file in python 3. b'Today, in the digital age, any type of data, such as text, images, and audio, can be\r\ndigitized, stored indefinitely, and transmitted at high speeds. Notwithstanding these\r\nadvantages, digital data also have a downside. They are easy to access illegally, tamper\r\nwith, and copy for purposes of copyright violation.\r\nThere is therefore a need to hide secret identification inside certain types of digital\r\ndata. This information can be used to prove copyright ownership, to identify attempts\r\nto tamper with sensitive data, and to embed annotations. Storing, hiding, or embedding\r \nsecret information in all types of digital data is one of the tasks of the field of\r\nsteganography.\r\nSteganography is the art and science of data hiding. In contrast with cryptography,\r\nwhich secures data by transforming it into another, unreadable format, steganography\r\nmakes data invisible by hiding (or embedding) them in another piece of data, known\r\nalternatively as the cover, the host, or the carrier. The modified cover, including the\r\nhidden data, is referred to as a stego object. It can be stored or transmitted as a message.\r\nWe can think of cryptography as overt secret writing and of steganography as covert\r\nsecret writing.\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00' I want to delete multiple \x00 from the end of the sentence. Please help me!
downvote count: 0

http://stackoverflow.com/comment/90512634
type: QuestionComment
comment on: http://stackoverflow.com/q/51777082
type: Comment
has text: Change this particular piece of code `bytes.decode('utf-8')` to exactly `x = x.decode('utf-8')` (which it does not sound like you've tried at all. As @dgan alluded to, you need to actually DO something with the result of decoding your bytestring. x.decode('utf-8') just creates an unnamed variable that gets tossed. Again, change this line `bytes.decode('utf-8')` to *exactly* `x = x.decode('utf-8')`. It does not seem like you've tried this at all.
score: 0

http://stackoverflow.com/q/51740218
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90440526
has answer: http://stackoverflow.com/a/51740406
has body: For example, if I have 2 strings [Mandzukic 18' (o.g.) Griezmann 38' (pen.) Pogba 59' Mbappe 65'; Perisic 28' Mandzukic 69'] and [Samuel Umtiti 51'] How can I write a single regex that can extract [Mandzukic, 18, Griezmann, 38, Pogba, 59, Mbappe, 65, Perisic, 28, Mandzukic, 69] from the first string and [Samuel Umtiti, 51] from the second string? This is what I have so far: (\w\s*\w+)\s(\d+) but I don't know how to get it to extract more than 1 instance of this pattern
type: Question
has comment: http://stackoverflow.com/comment/90440653
score: 0
answer count: 3
has title: How can I extract more than 1 match of the same pattern with regular expression?
has answer: http://stackoverflow.com/a/51740475
has answer: http://stackoverflow.com/a/51740317

http://stackoverflow.com/a/51772622
has comment: http://stackoverflow.com/comment/90505457
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90504977
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51768266
answers question: http://stackoverflow.com/q/51768266
has body: The solution is to promote the Labella to be used in Qt Designer, for this you must first create the file labella.py. labella.py from PyQt5 import QtCore, QtGui, QtWidgets class Labella(QtWidgets.QLabel): def __init__(self, parent): super().__init__(parent=parent) self.setStyleSheet('QFrame {background-color:white;}') self.resize(300, 300) self.begin = QtCore.QPoint() self.end = QtCore.QPoint() def paintEvent(self, event): super().paintEvent(event) qp = QtGui.QPainter(self) br = QtGui.QBrush(QtGui.QColor(100, 10, 10, 40)) qp.setBrush(br) qp.drawRect(QtCore.QRect(self.begin, self.end)) def mousePressEvent(self, event): self.begin = event.pos() self.end = event.pos() self.update() print("beegin = ", self.begin) print("end 1 = ", self.end) def mouseMoveEvent(self, event): self.end = event.pos() self.update() def drawRectangles(self, qp): qp.setBrush(QColor(255, 0, 0, 100)) qp.save() # save the QPainter config qp.drawRect(10, 15, 20, 20) qp.setBrush(QColor(0, 0, 255, 100)) qp.drawRect(50, 15, 20, 20) qp.restore() # restore the QPainter config qp.drawRect(100, 15, 20, 20) Then we place in the same folder the labella.py and the .ui that will call mainwindow.ui . ├── labella.py └── mainwindow.ui You open the .ui file by obtaining the following: Press the right click on the QLabel and select the option: Promote to ... Fill in the fields as shown in the following image, then press the Add button and then the Promote button: and finally generate the .py again with the help of pyuic5: pyuic5 mainwindow.ui -o mainwindow.py -x

http://stackoverflow.com/comment/103700621
type: AnswerComment
score: 4
type: Comment
has text: May you explain why the issue is not present when using the StandardScaler?
comment on: http://stackoverflow.com/a/51744034

http://stackoverflow.com/a/51784745
upvote count: 4
answers question: http://stackoverflow.com/q/51783628
has comment: http://stackoverflow.com/comment/90565653
has body: regstr = ".*([0-9０-９]{3}[-ー]{1}[0-9０-９]{4}).*" In Python 3, regstr would be a unicode string containing some non-ascii characters. In Python 2, it is a string encoded in some encoding, which depends on what you declared at the beginning of the module (see PEP 263) and the encoding actually used to save the file. To avoid such problems, I suggest you should never use unicode characters in regex. That is just too difficult to debug. Escape them instead. The characters ０１２３４５６７８９ are unicode characters '０' to '９', so I suggest you should use them as such. Furthermore, If you are using unicode regex, you should define it as such, using the u prefix for unicode strings: regstr = u".*([0-9０-９]{3}[-ー]{1}[0-9０-９]{4}).*" Later, when you are matching this regex to some string, that other string should also be a unicode string, rather than a plain str. For that, you have to know in which encoding the input is. For instance, if the input is utf-8, use: input_string_as_unicode = unicode(input_string_as_utf8, 'utf-8') re.match(regstr, input_string_as_unicode) Note that you possibly already have the input as unicode, if there is some framework behind doing that for you. Check type(input_string) if you are not sure.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90594423
accepted answer of: http://stackoverflow.com/q/51783628
type: Answer
score: 4

http://stackoverflow.com/a/51793696
answers question: http://stackoverflow.com/q/51793677
has body: Instead of joining the list of names, find all words in the string, and check if each word found belongs in names: import re test = 'Testes huius rey sunt hij, videlicet, Magnificus Dominus Periohannes de Mazara, nobilis Georgius de la Chabica, Nicolaus Manfridus de Caxario et alij.' new_test = re.sub('\w+', lambda x:'PERSON' if x.group() in names else x.group(), test)
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/90642720
score: 0
comment on: http://stackoverflow.com/q/51712693
type: Comment
type: QuestionComment
has text: I installed both Anaconda2 and 3 and now I see conda_console option only under Anaconda2. Why? Is it just one console for both Anaconda2 and 3

http://stackoverflow.com/q/51745858
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51745938
tagged with: python-3.x
linked to: http://stackoverflow.com/q/46589831
has body: I need to create another column with the Unique records from an existing column. Here is what I have done and the results are satisfactory. However for a table which has more than 2 million records it takes lot of time to process. I wish to find out if there is a faster way to achieve this. Code: import pandas as pd df=pd.DataFrame({'RecordSku':["JQUZJM", "JQUZJM", "RTSHQN", "HLDPJP", "HLDPJP", "UCJXWO", "JAOKYL", "JAOKYL", "IVEMZB", "NTHNOW", "JAIFQI", "JAIFQI", "KPMXBI", "SNAFIC", "RTSHQN", "FJRCAY", "NAYGXF", "PSJFEU", "MMBNMW", "MMBNMW", "MMBNMW", "MMBNMW", "ZWVPLB", "KDARIS", "KDARIS"]}) df['Unique'] ="" # Create a column to populate the unique status for x in range(0,len(df)): df['Unique'].iloc[x] = df.iloc[0:x].RecordSku.str.count(df.RecordSku[x]).sum() if df['Unique'][x]==0: df['Unique'][x]=1 else: df['Unique'][x]=0 Output: RecordSku Unique --------------------- 0 JQUZJM 1 1 JQUZJM 0 2 RTSHQN 1 3 HLDPJP 1 4 HLDPJP 0 5 UCJXWO 1 6 JAOKYL 1 7 JAOKYL 0 8 IVEMZB 1 9 NTHNOW 1 10 JAIFQI 1 11 JAIFQI 0 12 KPMXBI 1 13 SNAFIC 1 14 RTSHQN 0 15 FJRCAY 1 16 NAYGXF 1 17 PSJFEU 1 18 MMBNMW 1 19 MMBNMW 0 20 MMBNMW 0 21 MMBNMW 0 22 ZWVPLB 1 23 KDARIS 1 24 KDARIS 0 The output mentioned is exactly what I am looking for. All the first unique records should have 1 and the next time the record appears it should be 0. I am just trying to find a more efficient way to handle this.
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/46589831
type: Question
has answer: http://stackoverflow.com/a/51745938
has title: Create a new column in pandas dataframe with the unique records from another column
score: 0

http://stackoverflow.com/comment/90432565
comment on: http://stackoverflow.com/a/51735677
has text: Or `df.drop('state', 1).join(pd.DataFrame(df.state.tolist(), df.index).rename(columns=lambda x: f"s{x + 1}"))` This is just a variant of yours.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51754422
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90468937
has comment: http://stackoverflow.com/comment/90469100
has comment: http://stackoverflow.com/comment/90468872
type: Answer
has body: I do not know your specific application, however sending only one timestep of data in is surely not a good idea. You should instead, give the LSTM the entire sequence of previously given one-hot vectors (presumably words), and pre-pad (with zeros) if necessary as it appears you are working on sequences of varying length. Consider also using an embedding layer before your LSTM if these are indeed words. Read the documentation carefully. The utilization of your GPU being low is not a problem. You simply do not have enough data to fully utilize all resources in each batch. Training with batches is a sequential process, there is no real way to parallelize this process, at least a way that is introductory and beneficial to what your goals appear to be. If you do give the LSTM more data per timestep, however, this surely will increase your utilization. statefull in an LSTM does not do what you think it does. An LSTM always remembers the sequence it is iterating over as it updates it's internal hidden states, h and c. Furthermore, the weight transformations that "build" those internal states are learned during training. What stateful does is preserve the previous hidden state from the last batch index. Meaning, the final hidden state at the third element in the batch is sent as the initial hidden state in the third element of the next batch and so on. I do not believe this is useful for your applications. There are downsides to training the LSTM with one sample per batch. In general, training with min-batches increases stability. However, you appear to not be training with one sample per batch but instead one timestep per sample. Edit (from comments) If you use stateful and send the next 'character' of your sequence in the same index of the previous batch this would be analogous to sending the full sequence timesteps per sample. I would still recommend the initial approach described above in order to improve the speed of the application and to be in more line with other LS…
has comment: http://stackoverflow.com/comment/90468921
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51754166
has comment: http://stackoverflow.com/comment/90468811
answers question: http://stackoverflow.com/q/51754166
upvote count: 1

http://stackoverflow.com/q/51761786
has comment: http://stackoverflow.com/comment/90482973
accepted answer: http://stackoverflow.com/a/51762364
tagged with: seaborn
has comment: http://stackoverflow.com/comment/90482938
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/90483175
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90483052
has comment: http://stackoverflow.com/comment/90483324
has comment: http://stackoverflow.com/comment/90483110
has comment: http://stackoverflow.com/comment/90483283
type: Question
has body: I'm trying to create a heatmap, with the x axis being time, the y axis being detectors (it's for freeway speed detection), and the colour scheme and numbers on the graph being for occupancy or basically what values the csv has at that time and detector. My first thought is to use matplotlib in conjunction with pandas and numpy. I've been trying lots of different approaches and feel like i've hit a brickwall in terms of getting it working. Does anyone have a good idea about using these tools? Cheers! Row Labels 14142OB_L1 14142OB_L2 14140OB_E1P0 14140OB_E1P1 14140OB_E2P0 14140OB_E2P1 14140OB_L1 14140OB_L2 14140OB_M1P0 14140OB_M1P1 14140OB_M2P0 14140OB_M2P1 14140OB_M3P0 14140OB_M3P1 14140OB_S1P0 14140OB_S1P1 14140OB_S2P0 14140OB_S2P1 14140OB_S3P0 14140OB_S3P1 14138OB_L1 14138OB_L2 14138OB_L3 14136OB_L1 14136OB_L2 14136OB_L3 14134OB_L1 14134OB_L2 14134OB_L3 14132OB_L1 14132OB_L2 14132OB_L3 00 - 01 hr 0.22 1.42 0.29 0.29 0.59 0.59 0.17 1.47 0.38 0.38 0.56 0.6 0.08 0.1 0.67 0.7 0.88 0.9 0.15 0.17 0.17 1.66 0.47 0.16 1.6 0.49 0.14 0.94 1.21 0.21 1.22 0.44 01 - 02 hr 0.08 0.77 0.08 0.07 0.24 0.24 0.1 0.73 0.08 0.09 0.21 0.23 0.05 0.06 0.21 0.23 0.29 0.29 0.1 0.1 0.08 0.83 0.17 0.1 0.77 0.18 0.08 0.4 0.57 0.07 0.64 0.18 02 - 03 hr 0.08 0.73 0.06 0.06 0.23 0.23 0.06 0.73 0.07 0.07 0.23 0.24 0.02 0.02 0.16 0.17 0.32 0.34 0.06 0.07 0.06 0.77 0.16 0.06 0.78 0.17 0.07 0.3 0.66 0.06 0.68 0.19 03 - 04 hr 0.05 0.85 0.06 0.06 0.22 0.23 0.04 0.86 0.05 0.05 0.2 0.21 0.1 0.11 0.11 0.12 0.32 0.33 0.15 0.16 0.03 0.93 0.14 0.03 0.89 0.15 0.03 0.41 0.61 0.02 0.73 0.21 04 - 05 hr 0.13 1.25 0.09 0.09 0.24 0.24 0.12 1.25 0.11 0.11 0.2 0.21 0.08 0.09 0.19 0.2 0.32 0.34 0.15 0.15 0.1 1.33 0.18 0.11 1.35 0.19 0.11 0.52 1 0.07 1.08 0.29 05 - 06 hr 0.91 2.87 0.08 0.08 0.66 0.69 0.8 2.96 0.15 0.17 0.43 0.45 0.32 0.33 0.39 0.41 0.76 0.82 0.47 0.49 0.59 3.27 0.51 0.58 3.19 0.56 0.45 1.85 2.19 0.43 2.52 0.79 06 - 07 hr 3.92 5.44 1.29 1.14 4.03 4.12 3.19 6.03 1.66 1.69 3.26 3.44 1.84 1.93 13.03 14.97 1…
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51762364
has title: Creating a heatmap using python and csv file
has comment: http://stackoverflow.com/comment/90482734
has comment: http://stackoverflow.com/comment/90482835
score: 0
has comment: http://stackoverflow.com/comment/90482972
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/90349617
comment on: http://stackoverflow.com/q/51693837
score: 1
has text: In Python 3, `/` gives a non-integer result, but if you are using Python 2 then `/` works. Another way to find `x` is to do operations on `x-1` then adjust the result. Yet another way is to use [the ternary `if` operator](https://stackoverflow.com/a/394814/6246044), which is closer to my earlier hint. There are multiple ways to do this--you choose which is best for your situation. I chose my hint to be the one closest to what you had already tried.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51692278
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51692370
tagged with: web-scraping
tagged with: python-requests
type: Question
has body: This code gets the information from the site perfectly fine: url = 'https://www.vogue.com/article/mamma-mia-2-here-we-go-again-review?mbid=social_twitter' headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "lxml") title = soup.find("meta", {"name": "twitter:title"}) title2 = soup.find("meta", property="og:title") title3 = soup.find("meta", property="og:description") print("TITLE: "+str(title['content'])) print("TITLE2: "+str(title2['content'])) print("TITLE3: "+str(title3['content'])) However, when I replace the url with this shortened link it returns: print("TITLE: "+str(title['content'])) TypeError: 'NoneType' object has no attribute '__getitem__'
has title: Shortened link not working with BeautifulSoup Python
has comment: http://stackoverflow.com/comment/90346067
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/4201062
tagged with: beautifulsoup

http://stackoverflow.com/q/51764568
tagged with: numpy
answer count: 2
has title: How to select a single object in video frame clicking mouse on it?
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90488637
has comment: http://stackoverflow.com/comment/90489070
type: UnansweredQuestion
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/58382753
has answer: http://stackoverflow.com/a/51765025
has body: I'm working on a project in which I have to select an object using a mouse click on it and then I have to find the distance between the object and camera. here is my code : import numpy as np import cv2 from imutils.video import VideoStream import argparse import imutils import time import datetime def find_marker(image): # convert the image to grayscale, blur it, and detect edges gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 35, 125) # find the contours in the edged image and keep the largest one; # we'll assume that this is our piece of paper in the image _, cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) c = max(cnts, key=cv2.contourArea) # compute the bounding box of the of the paper region and return it return cv2.minAreaRect(c) def distance_to_camera(knownWidth, focalLength, perWidth): # compute and return the distance from the maker to the camera return (knownWidth * focalLength) / perWidth # initialize the known distance from the camera to the object, which #, in this case, is 24 inches KNOWN_DISTANCE = 24.0 # initialize the known object width, which in this case, the piece of # paper is 12 inches wide KNOWN_WIDTH = 11.0 ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") args = vars(ap.parse_args()) # if the video path was not supplied, grab the reference to the # camera if not args.get("video", False): vs = VideoStream(src=0).start() time.sleep(2.0) # otherwise, load the video else: vs = cv2.VideoCapture(args["video"]) # loop over the frames from the video stream frame = vs.read() marker = find_marker(frame) # otherwise, load the video focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH while (1): # grab the frame from the threaded video stream and resize it # to have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) if frame is None: break marker = find_marke…

http://stackoverflow.com/comment/90410448
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51724928
type: Comment
has text: ahhh, excellent.. thank you, that is superb! i think my main failing here is terminology in being able to search the internet for what i *actually* was after. i am (kinda) pleased i wasn't really all that far off.. :)

http://stackoverflow.com/q/51753539
has comment: http://stackoverflow.com/comment/90471093
upvote count: 1
answer count: 1
tagged with: clion
favorite count: 0
has comment: http://stackoverflow.com/comment/90471032
has comment: http://stackoverflow.com/comment/90468978
tagged with: linux
has body: I'm trying to import the tensorflow project into the CLion IDE (on Linux) so that I can run various cc tests for example this. I've built tensorflow from source using Bazel following the instructions from here . Now, I'm trying to import the bazel project into the CLion IDE by following the steps listed here. I'm not able to select an initial project view file of .bazelproject type since it does not exist in my tensorflow directory. Am I missing something or is there another way so that I can run tensorflow test files on my ide?
tagged with: python
has comment: http://stackoverflow.com/comment/90472878
has title: Importing Bazel Build Tensorflow
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90470733
has answer: http://stackoverflow.com/a/51758543
accepted answer: http://stackoverflow.com/a/51758543

http://stackoverflow.com/comment/90619075
comment on: http://stackoverflow.com/a/51827450
score: 0
type: AnswerComment
has text: I updated my question again. I think I got it this time. Happy to hear your thoughts.
type: Comment

http://stackoverflow.com/a/51698953
upvote count: 2
has body: IIUC df['score'] = df.freq * np.log(df.dollars).fillna(0) df.sort_values(by='score', ascending=False) Letter freq dollars score 4 e 9 3214.0 72.677444 1 b 3 32.0 10.397208 2 c 2 97.4 9.157652 0 a 1 421.0 6.042633 3 d 0 -40.0 0.000000
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51698931
answers question: http://stackoverflow.com/q/51698931
type: Answer
score: 2

for-loop
tags question: http://stackoverflow.com/q/51668502
tags question: http://stackoverflow.com/q/51735607
tags question: http://stackoverflow.com/q/51780856
tags question: http://stackoverflow.com/q/51729203
tags question: http://stackoverflow.com/q/51741056
tags question: http://stackoverflow.com/q/51678121
tags question: http://stackoverflow.com/q/51692080
tags question: http://stackoverflow.com/q/51773532
tags question: http://stackoverflow.com/q/51798276
tags question: http://stackoverflow.com/q/51736293
tags question: http://stackoverflow.com/q/51733107
tags question: http://stackoverflow.com/q/51681563
tags question: http://stackoverflow.com/q/51677492
tags question: http://stackoverflow.com/q/51795644
tags question: http://stackoverflow.com/q/51695331
tag name: for-loop
tags question: http://stackoverflow.com/q/51755131
tags question: http://stackoverflow.com/q/51671877
tags question: http://stackoverflow.com/q/51709938
tags question: http://stackoverflow.com/q/51657764
tags question: http://stackoverflow.com/q/51776219
tags question: http://stackoverflow.com/q/51763141
tags question: http://stackoverflow.com/q/51661522
tags question: http://stackoverflow.com/q/51742698
tags question: http://stackoverflow.com/q/51671855
tags question: http://stackoverflow.com/q/51767793
tags question: http://stackoverflow.com/q/51748786
tags question: http://stackoverflow.com/q/51739253
tags question: http://stackoverflow.com/q/51795486
tags question: http://stackoverflow.com/q/51763172
type: Tag
tags question: http://stackoverflow.com/q/51700876
tags question: http://stackoverflow.com/q/51668240
tags question: http://stackoverflow.com/q/51650933
tags question: http://stackoverflow.com/q/51775953
tags question: http://stackoverflow.com/q/51693022
tags question: http://stackoverflow.com/q/51737192
tags question: http://stackoverflow.com/q/51704784
tags question: http://stackoverflow.com/q/51753964
tags question: http://stackoverflow.com/q/51772519
tags question: http://stackoverflow.com/q/51717924
tags question: http://stackoverflow.com/q/51750164
tags question: http://stackoverflow.com/q/51679291
tags question: http://stackoverflow.com/q/51725743
tags question: http://stackoverflow.com/q/51797491
tags question: http://stackoverflow.com/q/51747961

http://stackoverflow.com/q/51640790
has answer: http://stackoverflow.com/a/51641007
type: Question
score: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/51640944
has answer: http://stackoverflow.com/a/51641085
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51640993
has body: I have a pandas dataframe which looks like this: colour points 0 red 1 1 yellow 10 2 black -3 Then I'm trying to do the following algorithm: combos = [] points = [] for i1 in range(len(df)): for i2 in range(len(df)): colour_main = df['colour'].values[i1] colour_secondary = df['colour'].values[i2] combo = colour_main + "_" + colour_secondary point1 = df['points'].values[i1] point2 = df['points'].values[i2] new_points = point1 + point2 combos.append(combo) points.append(new_points) df_new = pd.DataFrame({'colours': combos, 'points': points}) print(df_new) I want to get all combinations and sum points: if the colour is used as main I want to sum his value if the colour is used as a secondary I want to sum opposite value Example: red_yellow = 1 + (-10) = -9 red_black = 1 + ( +3) = 4 black_red = -3 + ( -1) = -4 The output I currently get: colours points 0 red_red 2 1 red_yellow 11 2 red_black -2 3 yellow_red 11 4 yellow_yellow 20 5 yellow_black 7 6 black_red -2 7 black_yellow 7 8 blac_kblack -6 The output I'm looking for: red_yellow -9 red_black 4 yellow_red 9 yellow_black 13 black_red -4 black_yellow -13 I don't know how to apply my logic to this code, also I bet there is a more simplest way to get all combinations without doing two loops, but currently, that's the only thing that comes to my mind. I would like to: get deserved output improve the performance in cases when we get like 20 input colours remove duplicates like red_red
tagged with: python
accepted answer: http://stackoverflow.com/a/51640993
answer count: 4
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/51641007
has title: Python pandas dataframe get all combinations of column values?

http://stackoverflow.com/q/51705552
tagged with: sys
upvote count: 1
tagged with: django
linked to: http://stackoverflow.com/q/436198
has title: 'execfile' not defined in apache2 config
has comment: http://stackoverflow.com/comment/90399003
has body: I want to deploy two different Django apps in the same host with the different virtual environment (python2.7 and python 3.6). I had followed the tutorial https://www.thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ to deploy. one of my WSGI scripts is import os import sys import site site.addsitedir('~/.virtualenvs/myprojectenv/local/lib/python2.7/site-packages') sys.path.append('/home/django_projects/MyProject') sys.path.append('/home/django_projects/MyProject/myproject') os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' activate_env=os.path.expanduser("~/.virtualenvs/myprojectenv/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() when I run apache server I get an error ---> Nameserver: name 'execfile' is not defined When I searched for this error I found execfile is not supported in Python 3.X. But I have 2 Django app to deploy. Please help me to find the solution. Is there any detail you need let me know
score: 1
has comment: http://stackoverflow.com/comment/90379108
has comment: http://stackoverflow.com/comment/90372355
type: Question
tagged with: apache
downvote count: 0
duplicate of: http://stackoverflow.com/q/436198
has comment: http://stackoverflow.com/comment/90372868
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90372295
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90252249
type: Comment
type: QuestionComment
has text: yes, I just want it to be more efficient. or if we can find any other way to solve it?
comment on: http://stackoverflow.com/q/51644051
score: 0

http://stackoverflow.com/comment/90484660
score: 0
has text: @jpp: and I also confirm that a fresh install with pandas==0.19 does NOT reproduce the issue.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51761498

http://stackoverflow.com/comment/90293598
comment on: http://stackoverflow.com/q/51665048
type: Comment
type: QuestionComment
score: 0
has text: The combination if +, local/global and mutable/immutable is something which even many veterans doesnt understand. Like you said, I dont think this is the exact duplicate of other existing answers because other answers are missing the + part etc. So can you not mark it as duplicate since then nobody can post an answer. @Zizouz212 was about to write an answer before you closed this thread. Hope you understand.

http://stackoverflow.com/comment/90872894
type: Comment
has text: Yes, I think gtk-3 is the way to go. If PyGI all-in-one-installer does not get developed, then I will use msys2. Thank you for your answer.
comment on: http://stackoverflow.com/a/51959831
score: 1
type: AnswerComment

http://stackoverflow.com/comment/98717183
type: AnswerComment
has text: Can you explain that further? What does that code do, and why should one use it?
type: Comment
comment on: http://stackoverflow.com/a/56037105
score: 1

http://stackoverflow.com/comment/90278036
type: Comment
type: QuestionComment
has text: Post the `.head().to_dict()` of your data so we can reproduce?
comment on: http://stackoverflow.com/q/51656874
score: 0

http://stackoverflow.com/a/51713342
has body: You can shorten the expression to: ^A\S+\s([^:(]*)(?=:|\s\() ^A Assert position beginning of string. \S+ Any non whitespace characters. \s Whitespace character. ([^:(]*) Capture group. Match and capture anything other than a ( bracket or ] bracket. (?=:|\s\() Positive lookahead for : or whitespace followed by (. Try it live here. Python snippet: import re string1 = 'A1 muscle pain: immunotherapy' string2 = 'A2B_45 muscle pain: topical medicine e.g. ....' string3 = 'A2_45 muscle pain (pain): topical medicine e.g. ....' print(re.match(r'^A\S+\s([^:(]*)(?=:|\s\()',string3).group(1))
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/90388283
upvote count: 4
type: Answer
has comment: http://stackoverflow.com/comment/90459323
answers question: http://stackoverflow.com/q/51713273
has comment: http://stackoverflow.com/comment/90392067
has comment: http://stackoverflow.com/comment/90388559

http://stackoverflow.com/comment/90518125
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51712215
has text: Thank you! Now I understand. But are you doing with norm? I read it in the dokumentation but I don't understand it

http://stackoverflow.com/comment/90276202
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51656247
type: QuestionComment
has text: How would the variable change? Is there anything asynchronous involved? Are you using any framework that would make that easier with some existing timeout function?

http://stackoverflow.com/comment/90278303
has text: KeyError("None of [Index([(8.1, 11.7, 13.475, 14.855, 15.125, 17.465, 19.82, 22.5)], dtype='object', name='Time')] are in the [index]",)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51656851
type: Comment

http://stackoverflow.com/q/51647981
type: Question
has body: from lab10_classes import Pharmacy def costliest_drug(pharmacy): drug_list = [] cost_list = [] drug_list3 = [] most_expensive = 0 for name in pharmacy.inventory: drug_list.append(name) for key in pharmacy.unit_prices and pharmacy.inventory: cost1 = pharmacy.unit_prices[key] cost2 = pharmacy.inventory[key] cost = cost1 * cost2 cost_list.append(cost) for i in range(len(cost_list)): if cost_list[i] &gt; most_expensive: most_expensive = cost_list[i] drug_list3.append(drug_list[i]) continue return drug_list3[len(drug_list3)-1] My return value is correct, it is the word, 'Hydrochlorothiazide'; and this is what my return value looks like: Hydrochlorothiazide However, I need my return value to look like this: [’Hydrochlorothiazide’] It needs to be a string inside a list. How do i do that?
upvote count: 1
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/90259490
has answer: http://stackoverflow.com/a/51648013
score: 0
has comment: http://stackoverflow.com/comment/90259554
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90259763
favorite count: 0
has title: How do I return a list with only one stringed element? Python
tagged with: list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90259696

http://stackoverflow.com/q/51707004
accepted answer: http://stackoverflow.com/a/51707112
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Python OpenCV Stitcher Class documentation
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/51707112
tagged with: opencv-stitching
answer count: 1
downvote count: 0
has body: Could you please give me some hint where can I find a detailed documentation for the Python Stitcher Class? I was able to find examples, and implemented them but I'd like to know more about this class and its capabilities.
favorite count: 0
tagged with: image-stitching
tagged with: python

http://stackoverflow.com/comment/90503847
score: 3
has text: Hi Paul, I don't post enough in CR to recommend migration, but usually StackOverflow is for *bugs* or *problems* in code. Check out CodeReview if your code is working and you just want feedback. If this is about a bug or problem, then it's not particularly clear to me what that is, as written
comment on: http://stackoverflow.com/q/51772473
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51707448
has comment: http://stackoverflow.com/comment/90376533
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51707313
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90376790
answers question: http://stackoverflow.com/q/51707313
type: Answer
has body: In your case you can access the arguments using: As you suggested in comment all you want is to access --output or -o change your add_argument for output to something like i added below pars.add_argument("-o", "--output", default=destination_file, help="the destination dirctory is the curently working dirctory") platform = args.platform architecture = args.arch output = args.output so on and so forth, for any other arguments you want to access should be available in args variable. Go through the documentation for more info Documentation
score: 1

http://stackoverflow.com/a/51741833
answers question: http://stackoverflow.com/q/51741177
accepted answer of: http://stackoverflow.com/q/51741177
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90443735
type: Answer
has body: &gt;&gt;&gt; datetime.fromtimestamp(1000000000).replace(tzinfo=our_timezone) datetime.datetime(2001, 9, 9, 3, 46, 40, tzinfo=&lt;DstTzInfo 'Asia/Jerusalem' LMT+2:21:00 STD&gt;) &gt;&gt;&gt; datetime.fromtimestamp(1000000000, tz=our_timezone) datetime.datetime(2001, 9, 9, 4, 46, 40, tzinfo=&lt;DstTzInfo 'Asia/Jerusalem' IDT+3:00:00 DST&gt;) Notice the odd timezone offset in the first case. Timezones are a bundle of multiple offsets. A timezone offset changes over time. Not only does it vary within a year based on summer and winter time, it varied historically when timezone data was revised and updated. You can inspect the timezone object to get some interesting historical data, reaching back many decades: &gt;&gt;&gt; our_timezone._utc_transition_times [datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1901, 12, 13, 20, 45, 52), datetime.datetime(1917, 12, 31, 21, 39, 20), datetime.datetime(1940, 5, 31, 22, 0), datetime.datetime(1942, 10, 31, 21, 0), datetime.datetime(1943, 4, 1, 0, 0), datetime.datetime(1943, 10, 31, 21, 0), datetime.datetime(1944, 3, 31, 22, 0), datetime.datetime(1944, 10, 31, 21, 0), datetime.datetime(1945, 4, 15, 22, 0), datetime.datetime(1945, 10, 31, 23, 0), datetime.datetime(1946, 4, 16, 0, 0), datetime.datetime(1946, 10, 31, 21, 0), datetime.datetime(1948, 5, 22, 22, 0), datetime.datetime(1948, 8, 31, 20, 0), datetime.datetime(1948, 10, 31, 23, 0), datetime.datetime(1949, 4, 30, 22, 0), datetime.datetime(1949, 10, 31, 23, 0), datetime.datetime(1950, 4, 15, 22, 0), datetime.datetime(1950, 9, 15, 0, 0), datetime.datetime(1951, 3, 31, 22, 0), datetime.datetime(1951, 11, 11, 0, 0), datetime.datetime(1952, 4, 20, 0, 0), datetime.datetime(1952, 10, 19, 0, 0), datetime.datetime(1953, 4, 12, 0, 0), datetime.datetime(1953, 9, 13, 0, 0), datetime.datetime(1954, 6, 12, 22, 0), datetime.datetime(1954, 9, 11, 21, 0), datetime.datetime(1955, 6, 11, 0, 0), datetime.datetime(1955, 9, 10, 21, 0), datetime.datetime(1956, 6, 2, 22, 0), datetime.datetime(1956,…
upvote count: 11
score: 11

http://stackoverflow.com/comment/90559731
score: 0
type: Comment
type: QuestionComment
has text: Yes, an MCVE is hard to produce. I could make minimal code, but I guess the problem is in the conda environment interacting not correctly with sphinx. Hard to think about an MCVE that reflects that. I could however provide the conda package list and the environment variables (on Monday) maybe that gives a clue. I was just hoping one of the sphinx or conda experts here have encountered that problem already.
comment on: http://stackoverflow.com/q/51784570

http://stackoverflow.com/comment/90300527
type: QuestionComment
has text: @shamilpython Windows 10
score: 0
comment on: http://stackoverflow.com/q/51668485
type: Comment

http://stackoverflow.com/a/51798013
has comment: http://stackoverflow.com/comment/90553778
score: 2
answers question: http://stackoverflow.com/q/51797957
has comment: http://stackoverflow.com/comment/90553729
downvote count: 0
has body: One way is to use sys.exit() in lieu of quit() import sys ... # code that executes sys.exit() ... # this code won't execute However, as noted by @AranFey in the comments, your code will throw an error if it attempts to execute the last part where the variable read is not defined.
type: Answer
upvote count: 2

http://stackoverflow.com/a/51679264
has comment: http://stackoverflow.com/comment/90324927
type: AcceptedAnswer
downvote count: 0
has body: This code shows one way of adding things to the Notebook tabs. It implements some of abarnert's suggestions, plus a few of my own ideas. I've separated the Notebook off into its own class, and moved the Tk root initialization code into the main GUI class. I don't claim that this is the best way to do these things, I'm just illustrating a few possibilities to inspire you. ;) import tkinter as tk from tkinter import ttk class GUI(tk.Tk): def __init__(self): super().__init__() self.title("SC") self.geometry('400x500') self.resizable(width=False, height=False) names = ['Title', 'Graphs', 'Messages', 'Instructions'] self.nb = self.create_notebook(names) self.menu = self.create_menus() # We can also add items to the Notebook here tab = self.nb.tabs['Instructions'] tk.Label(tab, text='You should\nread these\ninstructions').pack() self.mainloop() def create_notebook(self, names): nb = MyNotebook(self, names) nb.pack() def add_label(parent, text, row, column): label = tk.Label(parent, text=text) label.grid(row=row, column=column, sticky=tk.N, pady=10) return label # Add some labels to each tab tab = nb.tabs['Title'] for i in range(3): add_label(tab, 't' + str(i), i, 0) tab = nb.tabs['Graphs'] for i in range(3): add_label(tab, 'g' + str(i), 0, i) tab = nb.tabs['Messages'] for i in range(3): add_label(tab, 'm' + str(i), i, i) return nb def create_menus(self): menu = tk.Menu(self, tearoff=False) self.config(menu=menu) subMenu = tk.Menu(menu, tearoff=False) menu.add_cascade(label="File", menu=subMenu) subMenu.add_separator() subMenu.add_command(label='Exit', command=self.destroy) return menu class MyNotebook(ttk.Notebook): ''' A customised Notebook that remembers its tabs in a dictionary ''' def __init__(self, master, names): super().__init__(master, width=390, height=470) # Create tabs &amp; save them by name in a dictionary self.tabs = {} for name in names: self.tabs[name] = tab = ttk.Frame(self) self.add(tab, text=name) GUI() I do most of the work of creating the Notebook and…
has comment: http://stackoverflow.com/comment/90322374
has comment: http://stackoverflow.com/comment/90336287
has comment: http://stackoverflow.com/comment/90323026
has comment: http://stackoverflow.com/comment/90336490
has comment: http://stackoverflow.com/comment/90323007
answers question: http://stackoverflow.com/q/51678141
type: Answer
has comment: http://stackoverflow.com/comment/90324702
has comment: http://stackoverflow.com/comment/90336709
has comment: http://stackoverflow.com/comment/90336364
upvote count: 1
has comment: http://stackoverflow.com/comment/90324644
has comment: http://stackoverflow.com/comment/90324775
score: 1
accepted answer of: http://stackoverflow.com/q/51678141

http://stackoverflow.com/comment/90443486
type: Comment
comment on: http://stackoverflow.com/a/51721374
score: 1
type: AnswerComment
has text: @rezayousofvand permission denied is raised from nginx, add nginx log error to your question

http://stackoverflow.com/q/51749350
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: What is the preferred way to run TensorFlow model inference on Raspberry Pi?
downvote count: 0
score: 1
tagged with: tensorflow-serving
has answer: http://stackoverflow.com/a/51754830
tagged with: tensorflow
type: Question
tagged with: raspberry-pi
has body: I'd like to run model inference of a Convolutional Neural Network using Tensorflow on Raspberry Pi (RPI). Running the model in a Cloud isn't an option at the moment. I imagine that there are two different ways how this can be done: 1) running tensorflow code directly on RPi. (it is now possible to directly pip install tensorflow on the RPi, see here. 2) running an instance of ModelServer using the tensorflow serving(official docs). Now, what I'd like to have is an app running on RPi that reads live sensor data (in my case audio from microphone) und runs a classification algorithm. I assume that querying a ModelServer would be the preferred option (and I won't even need to install tensorflow on RPi), but I could'n find any examples of this anywhere. Has anybody have any experience with/knowledge of deploying tensorflow models on RPi?
upvote count: 1
answer count: 1

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/51659338
type: Tag

http://stackoverflow.com/comment/90293754
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51665278
has text: It does not get reassigned in the second case. The initial value is never changed, only locally replaced. By the time it runs again, the value is still the same. That‘s what immutability means.

http://stackoverflow.com/q/51797080
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51802238
has body: TLDR i am looking to use Frida to call an unused method in an Android app and get back its value. Currently, I am not getting any return in my scripts output. Code for the Android app: package securisec.com.methods; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public static String strings(){ return "This is a string method"; } } As you can see, the strings method is never used. I want to be able to call this method using Frida and get the return value back. Here is my python script that is not working. import frida from time import sleep call_back_message = '' def on_message(message, payload): global call_back_message if message['type'] == 'send': call_back_message = message['payload'] return call_back_message def object_hooking(comName, className, method): process = frida.get_usb_device() pid = process.spawn([comName]) process.resume(pid) sleep(1) js = """ Java.perform(function() { var getVal = Java.use('%s.%s'); console.log(getVal) var cons = getVal.$new(); console.log(cons) var solution = cons.%s; var send_it = solution.toString(); send(send_it); });""" % (comName, className, method) session = process.attach(pid) script = session.create_script(js) script.on('message', on_message) script.load() return call_back_message print(object_hooking( comName='securisec.com.methods', className='MainActivity', method='strings()' ))
favorite count: 0
tagged with: android
tagged with: python
score: 2
tagged with: frida
upvote count: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51802238
has title: How to get the return value of a Java method using Frida

http://stackoverflow.com/q/51658919
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51659081
has body: I have a list, categories, which stores some different values. I'm using a dictionary, my_dict to see if there are specific values within categories that match. If there are, a unique function would be performed for each key in the dictionary. My code currently looks like: categories = ['Creams', 'Bath', 'Personal Care'] my_dict = { 'Conditioners': lambda: print(1), 'Bath': lambda: print(2), 'Shaving Gels': lambda: print(3) } for category in categories: fn = my_dict.get(category, lambda: None) fn() Which outputs: 2 What I would like to now do is, if in any case, I had 2 or more values in the dictionary which were in categories I would like to do a unique function, different than the ones specified for them individually. For example: categories = ['Creams', 'Bath', 'Personal Care'] my_dict = { 'Creams': lambda: print(1), 'Bath': lambda: print(2), 'Shaving Gels': lambda: print(3) } for category in categories: fn = my_dict.get(category, lambda: None) fn() Instead of it printing 1 and 2, I would like to do perform a different function, for example, print('ABC'). Any direction on how I might achieve this would be appreciated.
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90281839
tagged with: list
has comment: http://stackoverflow.com/comment/90281787
type: Question
has title: Searching List with Dictionary, Conditional Function
has comment: http://stackoverflow.com/comment/90281582
tagged with: search

http://stackoverflow.com/q/51767167
favorite count: 0
has comment: http://stackoverflow.com/comment/90494583
has comment: http://stackoverflow.com/comment/90495255
has comment: http://stackoverflow.com/comment/90494269
has answer: http://stackoverflow.com/a/51767867
has comment: http://stackoverflow.com/comment/90493755
has answer: http://stackoverflow.com/a/51769241
tagged with: python
has body: I'm trying to implement the loss function of the classic Image Colorization paper by Levin et al (2004) in Tensorflow/Keras: This is the weights equation (correlation between intensities): y is every neighboring pixel of x in a 3x3 window and w is the weight for each of these pixels. The weights require computing the mean and variance for the neighborhood of every pixel. I couldn't find a function that would allow me to write this loss function in a symbolic way, and I'm thinking I should write it in a loop where I calculate the w for each window. How can I write this Loss function in Tensorflow In a Symbolic way or in loops? Thanks so much. EDIT: Here's the code I've come up for calculating the weights in Numpy: import cv2 import numpy as np im = cv2.resize(cv2.imread('./Image.jpg', 0), (256, 256)) / np.float32(255.0) M = 3 N = 3 # Split the image into 3x3 windows windows = [im[x:x + M, y:y + N] for x in range(0, im.shape[0], M) for y in range(0, im.shape[1], N)] # Calculate the correlation for each window weights = [1 + np.corrcoef(tile) for tile in windows]
has comment: http://stackoverflow.com/comment/90496113
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90493597
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90495461
has title: Tensorflow - Get Neighborhood of Pixel
score: 1
tagged with: loss-function
answer count: 2
downvote count: 0
tagged with: keras

http://stackoverflow.com/comment/90534910
score: 1
type: Comment
type: QuestionComment
has text: Does this work? `A[tuple(slice(D1[i], D2[i]) for i in range(D1.shape[0]))]`
comment on: http://stackoverflow.com/q/51788492

http://stackoverflow.com/comment/90384979
has text: I tried the code you posted. But I guess the treading scheduler does not suport Lock. `AttributeError: '_thread._local' object has no attribute 'execution_state'` ... `ValueError("No workers found")` I am going to ask a new question.
comment on: http://stackoverflow.com/a/51697346
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90506451
type: Comment
type: QuestionComment
has text: but explain your issue..
score: 1
comment on: http://stackoverflow.com/q/51773764

http://stackoverflow.com/comment/90267064
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51651812
has text: Run `python3 -m pip list`. Does it still list simpy?
type: Comment

http://stackoverflow.com/comment/90433023
type: Comment
has text: First, `INFO` message is not an error... Second, that is a very odd HDFS path... `/user/local/hadoop_data/hdfs/hduser`... Why didn't you upload to `hdfs:///user/hduser/` directly? And have you tried the `pyspark` REPL?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51733797

http://stackoverflow.com/q/51663038
favorite count: 0
tagged with: python-3.x
tagged with: python-requests-html
has answer: http://stackoverflow.com/a/51663099
has answer: http://stackoverflow.com/a/51663111
tagged with: python
tagged with: css
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51663099
has title: Cannot find css class using Request HTML
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51663111
answer count: 2
downvote count: 0
has body: After following this tutorial on finding a css class and copying the text on a website, I tried to implement this into a small text code but sadly it didnt work. I followed the tutorial exactly on the same website and did get the headline of the webpage, but cant get this process to work for any other class on that, or any other , webpage. Am I missing something? I am a beginner programmer and have never used Request HTML or anything similar before. Here is an example of the code I'm using, the purpose being to grab the random fact that appears in the "af-description" class when you load the webpage. from requests_html import HTMLSession session = HTMLSession() r = session.get('http://mentalfloss.com/amazingfactgenerator') r.html.find('.af-description', first=True) description = r.html.find('.af-description', first=True) print("Fun Fact:" + description.text) No matter how hard I try and no matter how I rearrange things or try different code, I cant get it to work. It seems to not be able to find the class or the text the class contains. Please help.

http://stackoverflow.com/comment/90458763
score: 0
type: Comment
type: QuestionComment
has text: Thank you @ W Stokvis. This is very helpful! But how to code them... I am a newbie...
comment on: http://stackoverflow.com/q/51749364

http://stackoverflow.com/a/51755967
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51749957
has body: Do this: import re input_regex = re.compile("\\(3doors\\)", re.IGNORECASE) subset_regex = "Hardtop 2 Door" input_text = "cooper s (3doors)" result = input_regex.sub(subset_regex, input_text) Skip the part where you do re.search. It's not needed. The result is: cooper s Hardtop 2 Door Note: Do not give the entire text in regex variables. It's of no use. That's not how regex works

http://stackoverflow.com/a/51672036
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90313486
answers question: http://stackoverflow.com/q/51669785
type: Answer
accepted answer of: http://stackoverflow.com/q/51669785
has body: What you are missing is the threshold of the magnitude. With the magnitude you can know if it actually has any relevant orientation... in a way it is kind of filtering the orientations to give only the ones with a strong response, which in most of the cases are edges. If this step is not done, then you will have at least one of your 4 colors for EVERY pixel, which I think it is not what you intended. Here is a sample code to illustrate my point: import numpy as np import cv2 # reads the image img = cv2.imread("lena.png", 0 # sobel derivatives derivX = cv2.Sobel(img, cv2.CV_32F, 1, 0) derivY = cv2.Sobel(img, cv2.CV_32F, 0, 1) # orientation and magnitude orien = cv2.phase(derivX, derivY, angleInDegrees=True) mag = cv2.magnitude(derivX, derivY) # thresholding of the magnitude values, play with the thresh value adjust it too your liking thresh = 50 _, mask = cv2.threshold(mag, thresh, 255, cv2.THRESH_BINARY) # I used OpenCV imshow instead of matplotlib, so the colors are in BGR (use yours) red = np.array([0, 0, 255]) cyan = np.array([255, 255, 0]) green = np.array([0, 255, 0]) yellow = np.array([0, 255, 255]) # for the same reason I use np.uint8 image_map = np.zeros((orien.shape[0], orien.shape[1], 3), dtype=np.uint8) # setting the colors, maybe there is a better way, my numpy skills are rusty # it checks that magnitude is above the threshold and that the orientation is in range image_map[ (mask == 255) &amp; (orien &lt; 90) ] = red image_map[(mask == 255) &amp; (orien &gt; 90) &amp; (orien &lt; 180)] = cyan image_map[(mask == 255) &amp; (orien &gt; 180) &amp; (orien &lt; 270)] = green image_map[(mask == 255) &amp; (orien &gt; 270)] = yellow # just for showing it with opencv, replace it with matplotlib if you prefer cv2.imshow("frame", image_map) cv2.waitKey(0) The result is:

http://stackoverflow.com/a/51726083
type: Answer
has body: Here is some code. This is considered more "pythonic" than iterating over indices--this iterates over consective-triples, using the zip function. This will give an error if the list has fewer than three items--you can add that error check. The zip function stops when one of the iterables runs out of values, which is exactly what we want here. def three_evens_or_odds(alist): for a, b, c in zip(alist, alist[1:], alist[2:]): if (((a &amp; 1) and (b &amp; 1) and (c &amp; 1)) or ((a &amp; 1 == 0) and (b &amp; 1 == 0) and (c &amp; 1 == 0))): return True return False print(three_evens_or_odds([2, 1, 3, 5])) print(three_evens_or_odds([2, 1, 2, 5])) print(three_evens_or_odds([2, 4, 2, 5])) Or, even shorter (borrowing an idea from @jdehesa which I should have thought of on my own, so upvote his answer as I did), def three_evens_or_odds(alist): for a, b, c in zip(alist, alist[1:], alist[2:]): if a &amp; 1 == b &amp; 1 == c &amp; 1: return True return False print(three_evens_or_odds([2, 1, 3, 5])) print(three_evens_or_odds([2, 1, 2, 5])) print(three_evens_or_odds([2, 4, 2, 5])) The printout from that is True False True
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51725921
downvote count: 0

http://stackoverflow.com/comment/90500543
type: QuestionComment
score: 2
has text: You can't use beautifulsoup to fill out a form. Beautifulsoup is for parsing HTML/XML/etc.
comment on: http://stackoverflow.com/q/51770883
type: Comment

http://stackoverflow.com/comment/90416221
score: 0
type: Comment
has text: It's strange but I haven't got a **compat** in **Lib/site-package/pip**
comment on: http://stackoverflow.com/a/51726543
type: AnswerComment

http://stackoverflow.com/comment/90585447
has text: @JeremyAlexander Yes it does.. I have added a solution, hope it helps
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51778723
score: 0

http://stackoverflow.com/comment/90266340
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51651281
type: QuestionComment
has text: Why can't you just put it into one loop in `Some_other_function`? And don't use upper case naming for functions.

http://stackoverflow.com/a/51653264
has body: The problem seems to be here: f = open(nameDir, 'a') 'a' stands for append, which means: the file should already exist, you get an error message because it doesn't. Use 'w' (write) instead, Python will create the file in that case.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51653124

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

http://stackoverflow.com/a/54266949
has body: You will need to have another variable and two sets of constraints for each of your absolute variables. m += xn &lt;= tn m += -xn &lt;= tn then the sum of tn is the sum of the absolute value of xn.
answers question: http://stackoverflow.com/q/51721618
type: Answer
score: 0

http://stackoverflow.com/q/51748545
favorite count: 0
tagged with: python
has title: Django CMS - Structure mode does not have scroll bar
tagged with: django-cms
type: UnansweredQuestion
downvote count: 1
type: Question
score: -1
has body: I created a Django CMS based website and created pages then added elements (plugins). Python 2.7.15, Django&lt;2.0, django-cms>=3.5,&lt;3.6 The default requirements.txt file generated had the following dependencies in it. django-cms&gt;=3.5,&lt;3.6 djangocms-admin-style&gt;=1.2,&lt;1.3 django-treebeard&gt;=4.0,&lt;5.0 djangocms-text-ckeditor&gt;=3.6.0 djangocms-link&gt;=2.1 djangocms-style&gt;=2.0 djangocms-googlemap&gt;=1.1 djangocms-snippet&gt;=2.0 djangocms-video&gt;=2.0 djangocms-column&gt;=1.7 djangocms-file&gt;=2.0,&lt;3.0 djangocms-picture&gt;=2.0,&lt;3.0 easy_thumbnails django-filer&gt;=1.3 Django&lt;2.0 pytz django-classy-tags&gt;=0.7 html5lib&gt;=0.999999,&lt;0.99999999 Pillow&gt;=3.0 django-sekizai&gt;=0.9 six I was able to see/edit etc. In latest version of Django CMS, it has an icon on far right corner to toggle between Structure/Content mode. The main problem that I faced is, when the structure mode is filled with number of elements (plugins), I was unable to edit the elements available at very bottom as there is no scroll bar to visit those elements (Like they are jsut below &amp; behind the taskbar). It is clear in the below image link. Structure mode issue I searched for solutions but I failed. Can someone please help me in fixing this issue or suggest me any other Django CMS version that I should go with?
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51768201
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/90308065
type: Comment
has text: another error , a bytes-like object is required, not 'str'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51670603

http://stackoverflow.com/comment/90537720
type: Comment
type: QuestionComment
has text: @schwobaseggl I was importing signals inside `models.py`, and later moved it in my `celery.py` file. I am not doing anything with it other than import.
score: 0
comment on: http://stackoverflow.com/q/51789799

http://stackoverflow.com/q/51684594
upvote count: 1
linked to: http://stackoverflow.com/q/17192158
has comment: http://stackoverflow.com/comment/90331467
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90331507
tagged with: python
has answer: http://stackoverflow.com/a/51684654
accepted answer: http://stackoverflow.com/a/51684654
has comment: http://stackoverflow.com/comment/90331559
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90331539
downvote count: 3
has comment: http://stackoverflow.com/comment/90331419
has comment: http://stackoverflow.com/comment/90331471
duplicate of: http://stackoverflow.com/q/17192158
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90331532
type: Question
has body: I run python object_detection/builders/model_builder_test.py with Tensorflow 1.9 of CPU version and Python 3.6 under Ubuntu system, there is NameError: name 'xrange' is not defined, does someone know why this happens and how to deal with it? Thanks. Here is the guide i follow. https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md Traceback (most recent call last): File "object_detection/builders/model_builder_test.py", line 311, in test_create_ssd_resnet_v1_fpn_model_from_config model = model_builder.build(model_proto, is_training=True) File "/home/tensorflow/models/research/object_detection/builders/model_builder.py", line 110, in build add_background_class) File "/home/tensorflow/models/research/object_detection/builders/model_builder.py", line 214, in _build_ssd_model ssd_config.anchor_generator) File "/home/tensorflow/models/research/object_detection/builders/anchor_generator_builder.py", line 91, in build cfg.normalize_coordinates File "/home/tensorflow/models/research/object_detection/anchor_generators/multiscale_grid_anchor_generator.py", line 61, in __init__ for scale in xrange(scales_per_octave)] NameError: name 'xrange' is not defined
has comment: http://stackoverflow.com/comment/90409483
score: -2
has title: NameError: name 'xrange' is not defined when running tensorflow object detection api
has comment: http://stackoverflow.com/comment/90331453

http://stackoverflow.com/q/51647380
answer count: 1
downvote count: 0
tagged with: pandas-groupby
tagged with: python
accepted answer: http://stackoverflow.com/a/51647949
favorite count: 0
has title: Grouping a dataframe and reordering based on date and counts
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/51647949
has body: I have the following dataframe, that is grouped according to the invoice cycle first, then added to a count of clinics in each invoice cycle. Dataframe after groupby function I used the following code to add the count column: df5 = df4.groupby(['Invoice Cycle', 'Clinic']).size().reset_index(name='counts') and then this code to set the index and get the dataframe, as seen in the image above: df5 = df5.set_index(['Invoice Cycle','Clinic']) Now, I want to reorder the Invoice Cycle column so the dates are in order 16-Dec, 17-Jan, 17-Feb, 17-Mar, etc. Then I want to reorder the clinics in each invoice cycle so clinic with the highest count is on the top and the clinic with the lowest count is on the bottom. Given the values in Invoice Cycle are strings, and not timestamps, I can't seem to do both of the above tasks. Is there a way to reorder the dataframe?
type: Question

http://stackoverflow.com/comment/90392085
type: Comment
has text: One way is to have a find function to first find the account object before transferring. After you find the object, you can pass it in transfer() method. If not found, you can create an object and pass it in siddarth.transfer()
comment on: http://stackoverflow.com/q/51714783
score: 0
type: QuestionComment

http://stackoverflow.com/a/54261113
answers question: http://stackoverflow.com/q/51716272
score: 0
type: Answer
has body: I'm not sure about this but you can try removing everything except kivy from requirements in the buildozer.spec file

http://stackoverflow.com/q/51674644
downvote count: 3
type: Question
upvote count: 0
tagged with: stock
has body: I'm trying to improve a stock_market prediction model using LinearRegression() on sklearn. First of all, I'm new to machine learning and I am kind of struggling on how the code works here it is: df = df"Adj Close" #price of closing df["prediction"]=df"Adj Close".shift(-int(30)) #creating just for 30 days X=df.drop(["prediction"],1) X=preprocessing.scale(X) X_forecast=X[-int(30):] X=X[:-int(30)] y=np.array(df["prediction"]) y=y[:-int(30)] X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.2) #on fait un test en limitant les données connues et celles inconnues pour eviter l'overfitting reg=LinearRegression() reg.fit(X_train,y_train) forecast_prediction=reg.predict(X_forecast) print(forecast_prediction) I don't understand how is it possible to predict something with this kind of linear regression because we are only using one data here: np.array(df["prediction"])
has answer: http://stackoverflow.com/a/51676622
has title: Stock_Market prediction using Linear regression
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/q/51740214
type: Question
tagged with: numpy
has title: Find the max from each row in Python
accepted answer: http://stackoverflow.com/a/51740298
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90440607
has comment: http://stackoverflow.com/comment/90440545
upvote count: 13
has answer: http://stackoverflow.com/a/51740298
has body: How to find the max from each row in Python and store it in a NumPy array or Pandas DataFrame and store it in a NumPy array, i.e. the output below? 0.511474 0.488526 0.468783 0.531217 0.35111 0.64889 0.594834 0.405166 Output: 0.511474 0.531217 0.64889 0.594834
score: 13
type: AnsweredQuestion
tagged with: dataframe

http://stackoverflow.com/a/51789578
score: 1
has comment: http://stackoverflow.com/comment/90554535
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51785048
answers question: http://stackoverflow.com/q/51785048
has body: Just use multiple lists in X. X = np.array([[1, 2, 4], [2, 3, 9]]).T #&lt;== Added a second list print(X) # Output feature1 feature2 1 2 2 3 4 9 y = np.array([1, 4, 16]) So here your data have two features. Now you can simply use the same code you are using before: X_poly = PolynomialFeatures(degree=2).fit_transform(data) print(X_poly) # Output [[ 1. 1. 2. 1. 2. 4.] [ 1. 2. 3. 4. 6. 9.] [ 1. 4. 9. 16. 36. 81.]] model = LinearRegression(fit_intercept = False) model.fit(X_poly,y) print('Coefficients: \n', model.coef_) # Output ('Coefficients: \n', array([-0.10133796, 0.1456888 , -0.01660059, 0.54831516, 0.45019822, -0.11496531])) print('Others: \n', model.intercept_) # Output ('Others: \n', 0.0)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90553751
type: Answer

http://stackoverflow.com/a/51711782
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51711607
score: 5
has body: You can simply add a dimension to the comparison array, so that the comparison is "stretched" across all values along the new dimension. &gt;&gt;&gt; np.sum(comparison_array[:, None] &lt; base_array) 228 This is the fundamental principle with broadcasting, and works for all kinds of operations. If you need the sum done along an axis, you just specify the axis along which you want to sum after the comparison. &gt;&gt;&gt; np.sum(comparison_array[:, None] &lt; base_array, axis=1) array([15, 15, 14, 14, 13, 13, 13, 13, 13, 12, 10, 10, 10, 10, 10, 7, 7, 7, 6, 6, 3, 2, 2, 2, 1, 0])
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90384862
accepted answer of: http://stackoverflow.com/q/51711607

http://stackoverflow.com/comment/90661589
comment on: http://stackoverflow.com/q/51646568
score: 0
type: QuestionComment
has text: Sorry, my bad. I meant using a lossless image type. You tried from your code or from the tester I linked? If it's the former, try also [using the Beta library](https://cloud.google.com/vision/docs/beta-libraries#installing_the_client_library) Maybe something changed in the model?
type: Comment

http://stackoverflow.com/a/51667568
has body: Is there any risks, or is it considered bad practice using class names with white space? It is absolutely considered bad practice, since PEP8 advises to use CapWords style for class names. The only technical difficulty you'll encounter is that such a whitespace-named class can't be instanciated with the usual syntax: x = Foo Bar() # SyntaxError But the actual problem will always be that it is very unusual and any human reading your code or debugging your bugs will have a hard time. If I imagine seeing something like AttributeError: 'Foo Bar' object has no attribute 'x', I'd first try to find out what went wrong with the class name, because there is no way someone included a whitespace there.. right? So please, just don't.
has comment: http://stackoverflow.com/comment/90316564
upvote count: 3
has comment: http://stackoverflow.com/comment/90298288
has comment: http://stackoverflow.com/comment/90316509
answers question: http://stackoverflow.com/q/51666361
has comment: http://stackoverflow.com/comment/90297991
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90298663
has comment: http://stackoverflow.com/comment/90298594

http://stackoverflow.com/q/51794147
has answer: http://stackoverflow.com/a/51794186
has answer: http://stackoverflow.com/a/51794193
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51794193
tagged with: pandas
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/51794186
upvote count: 2
has body: I have a data frame like this: pd.DataFrame([ [1, None, 'a'], [1, 3.3, None], [2, 1.7, 'c'] ], columns=['unique_id', 'x', 'target']) I want to drop one of the rows where unique_id is 1, but take the union of their values. That is, I want to produce this: pd.DataFrame([ [1, 3.3, 'a'], [2, 1.7, 'c'] ], columns=['unique_id', 'x', 'target']) Can this be done efficiently in Pandas? Assume this data frame has between 10k and 100k rows, with maybe 10% being duplicates I want to eliminate. There will only be 2 or 3 duplicates of each unique_id. Edit: when both rows have disagreeing entries, just taking the first one is fine in my case. But I'm open to solutions where, e.g. both values are collected in a list.
has comment: http://stackoverflow.com/comment/90545985
type: AnsweredQuestion
has title: Drop duplicate rows, but keep the union of their data
has comment: http://stackoverflow.com/comment/90546195
type: Question
answer count: 2
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/90546365

http://stackoverflow.com/q/51765519
has comment: http://stackoverflow.com/comment/90489760
answer count: 2
score: 5
has title: Error importing tensorflow in anaconda on Mac OSX
has answer: http://stackoverflow.com/a/71675302
has comment: http://stackoverflow.com/comment/90538409
favorite count: 0
has body: I am trying to import tensorflow using python and anaconda on Mac OSX 10.11.6 (El Capitan). I have followed the instructions on tensorflow.org relating to installation with anaconda as follows: conda create -n tensorflow pip python=3.6 source activate tensorflow sudo -H pip3 install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py3-none-any.whl And then starting python, and typing import tensorflow, produces an error: ImportError: dlopen(/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 6): Symbol not found: _SecKeyCopyExternalRepresentation Followed by more similar errors which resulted in a failure to load the native tensorflow runtime. Any assistance would be much appreciated!
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51850106
type: UnansweredQuestion
downvote count: 1
tagged with: tensorflow
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90530907

http://stackoverflow.com/comment/90328271
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51645621
has text: @Alesh Why you can't use ? could u tell me the erorr ?
type: Comment

http://stackoverflow.com/comment/90528266
type: QuestionComment
has text: Don't post images of code.
score: 1
comment on: http://stackoverflow.com/q/51783922
type: Comment

http://stackoverflow.com/comment/90493362
type: Comment
comment on: http://stackoverflow.com/a/51765627
type: AnswerComment
has text: This also works well - but any help converting the output to a DataFrame rather than a dict?
score: 0

coordinates
tags question: http://stackoverflow.com/q/51693837
tags question: http://stackoverflow.com/q/51675775
tags question: http://stackoverflow.com/q/51740003
tag name: coordinates
type: Tag
tags question: http://stackoverflow.com/q/51716479

http://stackoverflow.com/comment/90428982
comment on: http://stackoverflow.com/a/51733812
type: Comment
score: 1
type: AnswerComment
has text: @tobsecret you are right! This seems to be related to changes made in the Pandas' handling of boolean! Edited the answer to reflect this!

http://stackoverflow.com/comment/90470585
type: Comment
comment on: http://stackoverflow.com/q/51754406
type: QuestionComment
has text: @ialarmedalien added some code
score: 0

http://stackoverflow.com/q/51701531
type: Question
has body: Here's my dataset id feature_1 feature_2 feature_3 feature_4 feature_5 1 10 15 10 15 20 2 10 NaN 10 NaN 20 3 10 NaN 10 NaN 20 4 10 46 NaN 23 20 5 10 NaN 10 NaN 20 Here's what I need, I want to sort data based on completeness level (the higher percentage data is not nan, is higher the completeness level) of the dataset, the str is will be ascending so make me easier impute the missing value id feature_1 feature_2 feature_3 feature_4 feature_5 2 10 NaN 10 NaN 20 3 10 NaN 10 NaN 20 5 10 NaN 10 NaN 20 4 10 46 NaN 23 20 1 10 15 10 15 20 Best Regards,
tagged with: dataframe
has answer: http://stackoverflow.com/a/51701653
has title: How to sort to know sort data by completeness rate level on pandas
score: 0
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51701653
has comment: http://stackoverflow.com/comment/90365037
has comment: http://stackoverflow.com/comment/90364662
possible better answer: http://stackoverflow.com/a/51701800
tagged with: python
has answer: http://stackoverflow.com/a/51701800
type: AnsweredQuestion

http://stackoverflow.com/q/51782885
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/90526094
upvote count: 1
type: Question
tagged with: numpy
has body: I have this numpy array: sample= [[0.8 0.2 0.7 0.1] [0.7 0.5 0.5 0.0] [0.7 0.5 0.5 0.1] [0.7 0.5 0.3 0.3] [0.9 0.6 0.2 0.1] [0.8 0.6 0.5 0.0]] I want split it based on the rows(6) as well put those values into different numpy arrays. For example: sample_row_1 = [0.8 0.2 0.7 0.1] sample_row_2 = [0.7 0.5 0.5 0.0] sample_row_3 = [0.7 0.5 0.5 0.1] sample_row_4 = [0.7 0.5 0.3 0.3] sample_row_5 = [0.9 0.6 0.2 0.1] sample_row_6 = [0.8 0.6 0.5 0.0]
has title: How to split numpy array based on rows and keep those values into different arrays
tagged with: arrays
has comment: http://stackoverflow.com/comment/90528508
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51782998
favorite count: 0
has answer: http://stackoverflow.com/a/51783358
type: UnansweredQuestion

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/51719138

http://stackoverflow.com/q/51754338
tagged with: pandas
has title: MySQL / Python Display the level of an user_id for each day the user had that level
favorite count: 0
has comment: http://stackoverflow.com/comment/90468629
answer count: 0
has comment: http://stackoverflow.com/comment/90468336
has comment: http://stackoverflow.com/comment/90468434
has comment: http://stackoverflow.com/comment/90468680
has comment: http://stackoverflow.com/comment/90468894
type: UnansweredQuestion
has body: By selecting user_id, date(timestamp) as date, level from a table i have the following output: user_id date level 112 2017-10-13 16 112 2017-10-20 17 112 2017-10-22 18 112 2017-10-23 19 112 2017-10-30 20 112 2017-11-06 21 112 2018-05-17 22 I'm in a little bit of pickle and i can't find a way to achieve the following output. I'm trying to display the level of an user_id for each that user had a certain level. The desired output for user_id 112 for example should be something like this: user_id date level 112 2017-10-13 16 112 2017-10-14 16 112 2017-10-15 16 112 2017-10-16 16 112 2017-10-17 16 112 2017-10-18 16 112 2017-10-19 16 . . . . and so on for every user_id, dates interval and level. Basically each user_id, having it's attributed level and each day it had that certain level Could someone please help me? I'm open to a resolve in both MySql and Python. Thanks, George
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90468735
has comment: http://stackoverflow.com/comment/90469208
has comment: http://stackoverflow.com/comment/90473406
tagged with: dataframe
tagged with: mysql
has comment: http://stackoverflow.com/comment/90469040
type: Question
has comment: http://stackoverflow.com/comment/90468472
has comment: http://stackoverflow.com/comment/90469025
has comment: http://stackoverflow.com/comment/90468969
has comment: http://stackoverflow.com/comment/90469118
tagged with: sorting
has comment: http://stackoverflow.com/comment/90468939
has comment: http://stackoverflow.com/comment/90468382
score: 0

http://stackoverflow.com/comment/90337558
type: Comment
has text: @DanielRoseman I need to import many variables from many different files in one project, and i want do not want to type this try... else... so many times
type: QuestionComment
comment on: http://stackoverflow.com/q/51687684
score: 0

http://stackoverflow.com/comment/90469794
type: AnswerComment
comment on: http://stackoverflow.com/a/51754631
type: Comment
has text: It's hard to really help without seeing your code or the data. But from a high level view you probably just need to loop through all your features, try to extract the date field from each one using any of the possible field names, and then use the above code to convert it to the day of the year.
score: 0

http://stackoverflow.com/a/51688493
answers question: http://stackoverflow.com/q/51688492
score: 0
has comment: http://stackoverflow.com/comment/90338825
has comment: http://stackoverflow.com/comment/90338823
type: Answer
has comment: http://stackoverflow.com/comment/90338824
has body: I would suggest putting your data into a Pandas DataFrame. This will, amongst many many others, allow access to the groupby function. You can then group rows together that have the same index value (your first column). Then on each of those groups, you simply compute the sum. Here is an example: In [1]: import pandas as pd, matplotlib.pyplot as plt In [2]: index_values = [1, 1, 1, 2, 2, 3] In [3]: values = [1.05, 0.95, 1.00, 1.02, 1.03, 0.97] In [4]: df = pd.DataFrame(values, index=index_values) In [5]: df Out[5]: 0 1 1.05 1 0.95 1 1.00 2 1.02 2 1.03 3 0.97 In [6]: grouped = df.groupby(by=df.index).sum() In [7]: grouped.plot() Out[7]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x7fcb2a35db38&gt; In [8]: plt.show() This then gives me:

http://stackoverflow.com/comment/90251268
score: 2
type: Comment
has text: Search for `args =` before the line 127 and make sure you're not overwriting it.
type: QuestionComment
comment on: http://stackoverflow.com/q/51643430

http://stackoverflow.com/comment/90353277
comment on: http://stackoverflow.com/a/51695787
type: Comment
has text: I just tested it and it stills produces duplicate numbers. Try using a list with every number you selected and check if the new random number is inside that list (if it has been selected before).
score: 0
type: AnswerComment

http://stackoverflow.com/a/51773545
answers question: http://stackoverflow.com/q/51752289
has body: This works fine: import numpy as np import pandas as pd import dask.dataframe as dd df = pd.DataFrame(dict(x=np.random.normal(size=100), y=np.random.normal(size=100))) ddf = dd.from_pandas(df, chunksize=40) cat = ddf.map_partitions(lambda d: pd.Series(np.digitize(d['x'] + d['y'], [.3,.9])), meta=('x', int)) cat.to_hdf('cat.h5', '/cat') You were missing the pd.Series wrapper around the call to np.digitize, which meant the output of map_partitions was a numpy array instead of a pandas series (an error). In the future when debugging it may be useful to try computing a bit of data from steps along the way to see where the error is (for example, I found this issue by running .head() on cat).
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51752289
upvote count: 1

http://stackoverflow.com/comment/90274425
score: 0
has text: `os.walk('/')` means to search recursively from the root directory. You can replace `'/'` with the path you want to start the search from.
type: Comment
comment on: http://stackoverflow.com/a/51655363
type: AnswerComment

http://stackoverflow.com/a/51662655
has comment: http://stackoverflow.com/comment/90289039
has body: first read all text. check if modification is needed and append if so. path='/path/to/file' content = open(path, 'r').read() to_add='foo' if to_add not in content: with open(path, 'a') as fh: fh.write(to_add)
answers question: http://stackoverflow.com/q/51662544
type: Answer
score: -1
downvote count: 2
has comment: http://stackoverflow.com/comment/90288981
upvote count: 1

http://stackoverflow.com/q/51694687
tagged with: beautifulsoup
has title: I want my code to not extract links with 0 seeders using python
has comment: http://stackoverflow.com/comment/90351314
accepted answer: http://stackoverflow.com/a/51695238
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: i wrote my code but it extract all links no matter what value is the seeders count, here is the code i wrote: from bs4 import BeautifulSoup import urllib.request import re class AppURLopener(urllib.request.FancyURLopener): version = "Mozilla/5.0" url = input('What site you working on today, sir?\n-&gt; ') opener = AppURLopener() html_page = opener.open(url) soup = BeautifulSoup(html_page, "lxml") pd = str(soup.findAll('td', attrs={'align':re.compile('right')})) for link in soup.findAll('a', attrs={'href': re.compile("^magnet")}): if not('0' is pd[18]): print (link.get('href'),'\n') and this is the html am working on : https://i.sstatic.net/ImjPG.jpg in this case it's 0 seeders but it still gives me the magnet link.. HELP
upvote count: 1
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90351382
has comment: http://stackoverflow.com/comment/90351134
score: 1
has answer: http://stackoverflow.com/a/51695238
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90351360

http://stackoverflow.com/a/51710255
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: You already have the last value. If neither the if clause nor the elif clause are true, then subject hasn't been set this iteration. That means it will still hold the same value it held last iteration. sentence_list=['Dogs are great', 'They are so awesome'] for sentence in sentence_list: if 'Dog' in sentence: subject= 'Dog' elif 'Cat' in sentence: subject='Cat' print(subject) Will result in: Dog Dog
answers question: http://stackoverflow.com/q/51710105

http://stackoverflow.com/comment/90382059
comment on: http://stackoverflow.com/a/51710422
type: AnswerComment
has text: But I want to test for the number of instances of the number "1" in `dicevalues`. Like if `dicevalues = [1, 4, 3, 1, 2]`, detect that `1` occurs twice and assign two points to `score`.
score: 0
type: Comment

http://stackoverflow.com/a/51666069
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90344347
upvote count: 1
has body: I actually had to do a similar thing myself. This is what you would put at the bottom: while running: event = pygame.event.wait() if event.type == pygame.MOUSEBUTTONUP: if event.button == 1: x,y = pygame.mouse.get_pos() if 300 &lt;= x &lt;= 505 and 300 &lt;= y &lt;= 380: #change stuff here running = False #insert code here \/ for the next screen This can be used universally for every button. If you need more buttons, just copy and paste the third if statment and change as needed. Don't forget to do 'pygame.display.update()' to refresh the screen; else, you will see nothing change (which is what happened to me). I hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/51664709

http://stackoverflow.com/q/51769336
type: Question
tagged with: visual-c++
upvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/29846087
has body: I am trying to install new modules of Python on my PC running Windows 8.1 and Python 3.7 I found a solution saying "Ïnstall Microsoft Build Tools 2015". I install this package and still facing this error. Here is a screenshot(Visual c++ 14.0 error): Please help me to sort this out, now its causing headache.
has title: python modules installing Error "Visual c++ 14.0" is required
duplicate of: http://stackoverflow.com/q/51695071
tagged with: c++
has answer: http://stackoverflow.com/a/51866314
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pip
tagged with: python
downvote count: 1
duplicate of: http://stackoverflow.com/q/29846087
score: -1
has comment: http://stackoverflow.com/comment/90552686

http://stackoverflow.com/comment/90464526
comment on: http://stackoverflow.com/q/51752140
score: 1
type: QuestionComment
has text: The comment by @Onyambu is probably the right way to do this. But, if you really want a one liner of what you are doing, then you need to use reduce from functools as `final_qry = reduce((lambda x, y: x.replace(y, ' ')), clean_spaces, final_qry)`
type: Comment

http://stackoverflow.com/comment/90496412
type: Comment
type: QuestionComment
has text: you can also use pip2 and pip3 to install to the respective versions (check the names of the pip executables in both distributions to make sure)
comment on: http://stackoverflow.com/q/51768009
score: 0

pyqt5
tags question: http://stackoverflow.com/q/51686635
tags question: http://stackoverflow.com/q/51716606
tags question: http://stackoverflow.com/q/51645592
type: Tag
tags question: http://stackoverflow.com/q/51755336
tags question: http://stackoverflow.com/q/51701986
tags question: http://stackoverflow.com/q/51672962
tags question: http://stackoverflow.com/q/51657157
tags question: http://stackoverflow.com/q/51640798
tags question: http://stackoverflow.com/q/51770282
tags question: http://stackoverflow.com/q/51764272
tags question: http://stackoverflow.com/q/51769828
tags question: http://stackoverflow.com/q/51705314
tags question: http://stackoverflow.com/q/51667355
tags question: http://stackoverflow.com/q/51787641
tags question: http://stackoverflow.com/q/51696185
tags question: http://stackoverflow.com/q/51771935
tags question: http://stackoverflow.com/q/51687692
tags question: http://stackoverflow.com/q/51768588
tags question: http://stackoverflow.com/q/51687495
tags question: http://stackoverflow.com/q/51768933
tags question: http://stackoverflow.com/q/51784783
tags question: http://stackoverflow.com/q/51660453
tags question: http://stackoverflow.com/q/51784292
tags question: http://stackoverflow.com/q/51733668
tags question: http://stackoverflow.com/q/51686198
tags question: http://stackoverflow.com/q/51700517
tags question: http://stackoverflow.com/q/51768266
tags question: http://stackoverflow.com/q/51755187
tags question: http://stackoverflow.com/q/51767578
tags question: http://stackoverflow.com/q/51658170
tag name: pyqt5
tags question: http://stackoverflow.com/q/51659335
tags question: http://stackoverflow.com/q/51707681
tags question: http://stackoverflow.com/q/51644685
tags question: http://stackoverflow.com/q/51714031
tags question: http://stackoverflow.com/q/51787219

http://stackoverflow.com/q/51778914
has comment: http://stackoverflow.com/comment/90515696
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51779781
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51779781
has answer: http://stackoverflow.com/a/51779645
type: Question
score: 0
has body: Trying to make a gtraph for a dataframe: year month k_mean k_min k_max k_count 0 1994 1 3.548387 2.0 5.0 9.0 1 1994 2 4.500000 2.0 7.0 15.0 2 1994 3 4.387097 2.0 7.0 16.0 3 1994 4 4.433333 1.0 9.0 16.0 4 1994 5 4.806452 2.0 7.0 20.0 The x-axis shows the index number of the record, not the value of the year column. My code is: import matplotlib.pyplot as plt x0=result.year.astype(np.int32).unique() y1=result.k_max.astype(np.int32) x0, y1.plot(label='1') y2=result.k_count.astype(np.int32) x0, y2.plot(label='2') plt.legend(loc='best') plt.show() What's wrong ? Ideally, I would like the YEAR and the Month. Thanks.
answer count: 2
accepted answer: http://stackoverflow.com/a/51779645
has title: year values on the X axis
tagged with: python

http://stackoverflow.com/q/51706256
tagged with: python
score: 11
has body: I would like to send a :heart: emoji with selenium's send_keys() from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome('./chromedriver') driver.get("https://web.whatsapp.com/") wait = WebDriverWait(driver, 600) message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0] message.send_keys(":heart:") However, this does not work and sends a string ':heart:'. Could you please suggest how to do it correctly?
has title: Sending emojis with selenium's send_keys()
has comment: http://stackoverflow.com/comment/90373267
has answer: http://stackoverflow.com/a/70915646
has comment: http://stackoverflow.com/comment/90373685
has answer: http://stackoverflow.com/a/79316828
type: Question
has answer: http://stackoverflow.com/a/52311893
answer count: 8
has answer: http://stackoverflow.com/a/62649489
downvote count: 0
has answer: http://stackoverflow.com/a/65174202
has answer: http://stackoverflow.com/a/70161788
has answer: http://stackoverflow.com/a/67747143
favorite count: 0
upvote count: 11
has answer: http://stackoverflow.com/a/77371495
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90373479
tagged with: selenium

http://stackoverflow.com/comment/90512793
type: QuestionComment
has text: @MarkGinsburg I have answered below :) Thanks !
score: 0
comment on: http://stackoverflow.com/q/51777204
type: Comment

http://stackoverflow.com/comment/90513172
score: 1
comment on: http://stackoverflow.com/a/51776659
type: AnswerComment
type: Comment
has text: @WilliamPapsco Or even `";".join('abc')`, because strings are iterable too.

http://stackoverflow.com/q/51732680
tagged with: python
has comment: http://stackoverflow.com/comment/90426513
has answer: http://stackoverflow.com/a/51768943
has title: Adding LSTM layers before the softmax layer
has comment: http://stackoverflow.com/comment/90427244
has comment: http://stackoverflow.com/comment/90426301
type: Question
has comment: http://stackoverflow.com/comment/90426197
has comment: http://stackoverflow.com/comment/90427054
has body: I would like to add an LSTM layer before the softmax layer so that I can keep track of the context of a sequence and use it for prediction. Following is my implementation but I get every time the following error. Please help me to solve this error. ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=2 common_model = Sequential() common_model.add(Conv2D(32, (3, 3), input_shape=self.state_size, padding='same', activation='relu')) common_model.add(Dropout(0.2)) common_model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) common_model.add(MaxPooling2D(pool_size=(2, 2))) common_model.add(Flatten()) common_model.add(Dense(512, activation='relu')) common_model.add(Dropout(0.5)) common_model.add(Dense(512, activation='relu')) common_model.add(Dropout(0.5)) common_model.add(Dense(512, activation='relu')) common_model.add(Dropout(0.5)) agent_model = Sequential() agent_model.add(common_model) agent_model.add(LSTM(512, return_sequences=False)) agent_model.add(Dense(self.action_size, activation='softmax')) agent_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=self.agent_learning_rate)) critic_model = Sequential() critic_model.add(common_model) critic_model.add(Dense(1, activation='linear')) critic_model.compile(loss="mse", optimizer=Adam(lr=self.critic_learning_rate))
tagged with: lstm
has comment: http://stackoverflow.com/comment/90426361
score: 0
tagged with: reinforcement-learning
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90426500
has comment: http://stackoverflow.com/comment/90426206
answer count: 1
has comment: http://stackoverflow.com/comment/90439761
tagged with: keras
has comment: http://stackoverflow.com/comment/90426314
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42714688

http://stackoverflow.com/comment/90350467
type: Comment
comment on: http://stackoverflow.com/a/51685498
score: 0
type: AnswerComment
has text: Thanks so much! Exactly what I was looking for

http://stackoverflow.com/q/51683771
tagged with: python-3.x
has title: How to plot a histogram with uniform space between uneven data points?
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/90330909
score: 2
has comment: http://stackoverflow.com/comment/90342806
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90342530
downvote count: 0
has body: So I have an array y that contains powers of 2, like 1, 2, 4, 8, 16,... and I want to put them in a histogram to see how many of each shows up. But when I plot them they turn out like this: My question is: how do I get them close together, with 1,2,4,8,... all evenly spaced instead of 32 and 64 being way further like this. My sample code is: import matplotlib.pyplot as plt y=(2,1,8,1,64,8,2,8,32,0) plt.hist(y,bins=128) plt.xlabel('Power of 2') plt.ylabel('Number of times show up') plt.show() Thank you!
has comment: http://stackoverflow.com/comment/90334655
has comment: http://stackoverflow.com/comment/90334756
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51690655
upvote count: 2
tagged with: bar-chart
answer count: 1
has answer: http://stackoverflow.com/a/51690655
favorite count: 0

http://stackoverflow.com/q/51730994
possible better answer: http://stackoverflow.com/a/51731030
has answer: http://stackoverflow.com/a/51741265
upvote count: 1
has answer: http://stackoverflow.com/a/51731030
tagged with: sqlalchemy
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51741265
downvote count: 0
has title: Return value for sqlalchemy db.execute() in Flask?
favorite count: 0
has body: My Flask app is hooked up to my postgres database in Heroku like so: from flask import Flask, render_template, session, request, url_for, redirect, flash from flask_session import Session from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import os app = Flask(__name__) # Check for environment variable if not os.getenv("DATABASE_URL"): raise RuntimeError("DATABASE_URL is not set") # Configure session to use filesystem app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Set up database engine = create_engine(os.getenv("DATABASE_URL")) db = scoped_session(sessionmaker(bind=engine)) My Flask methods run various SQL statements. The syntax I'm using is typically like bk = db.execute("SELECT * FROM books WHERE isbn=:isbn", {"isbn": isbn}). I thought the return value of such a statement would be a list of dictionaries, however, when I coded a method to check for len(bk) it said the object had no length even when it should have. So, what's the return value that I'm receiving, and why doesn't it seem to have a discernible length to Python? Couldn't find a straight answer anywhere.
tagged with: python
type: AnsweredQuestion
score: 1

apache-spark
tags question: http://stackoverflow.com/q/51774686
tags question: http://stackoverflow.com/q/51774796
tags question: http://stackoverflow.com/q/51749784
tags question: http://stackoverflow.com/q/51704898
tags question: http://stackoverflow.com/q/51732843
tags question: http://stackoverflow.com/q/51759042
tags question: http://stackoverflow.com/q/51790382
tags question: http://stackoverflow.com/q/51752286
tags question: http://stackoverflow.com/q/51789864
tags question: http://stackoverflow.com/q/51725436
tag name: apache-spark
tags question: http://stackoverflow.com/q/51680106
tags question: http://stackoverflow.com/q/51680000
tags question: http://stackoverflow.com/q/51772350
tags question: http://stackoverflow.com/q/51729097
tags question: http://stackoverflow.com/q/51644273
tags question: http://stackoverflow.com/q/51707674
tags question: http://stackoverflow.com/q/51768033
tags question: http://stackoverflow.com/q/51640623
tags question: http://stackoverflow.com/q/51706383
tags question: http://stackoverflow.com/q/51726029
tags question: http://stackoverflow.com/q/51751499
tags question: http://stackoverflow.com/q/51662071
tags question: http://stackoverflow.com/q/51640063
type: Tag
tags question: http://stackoverflow.com/q/51639796
tags question: http://stackoverflow.com/q/51658925
tags question: http://stackoverflow.com/q/51695976
tags question: http://stackoverflow.com/q/51736050
tags question: http://stackoverflow.com/q/51777112

http://stackoverflow.com/a/51668434
has body: It might have been because I quit my script. When the script is contentiously running, it's fine.
type: Answer
answers question: http://stackoverflow.com/q/51653673
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51653673
type: AcceptedAnswer
downvote count: 0

ftplib
tags question: http://stackoverflow.com/q/51756672
tags question: http://stackoverflow.com/q/51761965
tag name: ftplib
type: Tag
tags question: http://stackoverflow.com/q/51684008

http://stackoverflow.com/comment/90490233
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51764738
has text: @Dev-iL Thanks for your comment. I have just added my MATLAB code to the post. I hope you can be able to help me now.
type: Comment

http://stackoverflow.com/comment/90352180
type: Comment
type: QuestionComment
has text: Changed the title to reduce the confusion around why I asked this question. Thanks guys for the complete answers. I am sad because the damage of downvoting the question is done, though the answers below are of super high quality.
score: 0
comment on: http://stackoverflow.com/q/51695133

http://stackoverflow.com/comment/90464430
has text: maybe you would use `re.sub("\\s+","",final_qry)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51752140
score: 1

http://stackoverflow.com/comment/90463339
score: 2
has text: jack-gore's answer addresses your question. One approach for your diagnosis could have been to use a known good 2nd container to access the `db`. See the image's documentation on docs.docker.com and the use of the `adminer` image (https://docs.docker.com/samples/library/postgres/#-via-docker-stack-deploy-or-docker-compose). Second, the Dockerfile would benefit from reducing the number of layers created by reducing the number of `RUN` commands. For example `RUN apt-get update && apt-get -y install python-pip` (you don't need the final `apt-get update`).
comment on: http://stackoverflow.com/q/51750715
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51775601
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: 'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'
has body: I am trying to sort numbers column in dataframe but getting this error 'id' column has count of id's at specific stations. e.g. 2272, 2202, 1855, etc. df.sort_values(by=['id']) However, I am getting this error: 'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'
score: 3
downvote count: 0
type: Question
tagged with: numpy
tagged with: group-by
has answer: http://stackoverflow.com/a/51775676
upvote count: 3

http://stackoverflow.com/a/51733133
has comment: http://stackoverflow.com/comment/113060541
has comment: http://stackoverflow.com/comment/105938101
has comment: http://stackoverflow.com/comment/125946462
has comment: http://stackoverflow.com/comment/90427717
has body: The following should work in the latest version of seaborn (0.9.0) import matplotlib.pyplot as plt import seaborn as sns First we concatenate the two datasets into one and assign a dataset column which will allow us to preserve the information as to which row is from which dataset. concatenated = pd.concat([set1.assign(dataset='set1'), set2.assign(dataset='set2')]) Then we use the sns.scatterplot function from the latest seaborn version (0.9.0) and via the style keyword argument set it so that the markers are based on the dataset column: sns.scatterplot(x='Std', y='ATR', data=concatenated, hue='Asset Subclass', style='dataset') plt.show()
score: 19
has comment: http://stackoverflow.com/comment/113357737
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90427923
has comment: http://stackoverflow.com/comment/90427327
type: Answer
accepted answer of: http://stackoverflow.com/q/51732867
has comment: http://stackoverflow.com/comment/90428089
has comment: http://stackoverflow.com/comment/105970094
upvote count: 19
answers question: http://stackoverflow.com/q/51732867
has comment: http://stackoverflow.com/comment/126279420
has comment: http://stackoverflow.com/comment/90427284

http://stackoverflow.com/q/51660777
tagged with: space-complexity
has answer: http://stackoverflow.com/a/51660957
possible better answer: http://stackoverflow.com/a/51660850
accepted answer: http://stackoverflow.com/a/51660957
has title: Space-Time complexity in variation of Dutch National Flag
type: AnsweredQuestion
tagged with: time-complexity
downvote count: 0
score: 1
tagged with: dutch-national-flag-problem
has comment: http://stackoverflow.com/comment/90285110
has body: A variation of the DNF is as follows: def dutch_flag_partition(pivot_index , A): pivot = A[pivot_index] # First pass: group elements smaller than pivot. for i in range(len(A)): # Look for a smaller element. for j in range(i + 1, len(A)): if A[j] &lt; pivot: A[i], A[j] = A[j], A[i] break # Second pass: group elements larger than pivot. for i in reversed(range(len(A))): if A[i] &lt; pivot: break # Look for a larger element. Stop when we reach an element less than # pivot , since first pass has moved them to the start of A. for j in reversed(range(i)): if A[j] &gt; pivot: A[i], A[j] = A[j], A[i] break The additional space complexity is given as O(1). Is that because the swapping doesn't depend on the input length? And time complexity, given as O(N^2), is it so due to the nested loops? Thanks
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51660850
answer count: 2
upvote count: 1

http://stackoverflow.com/q/51690823
answer count: 3
has title: Calculate non-integer frequency with NumPy FFT
downvote count: 0
has comment: http://stackoverflow.com/comment/90347663
has comment: http://stackoverflow.com/comment/90344838
favorite count: 0
tagged with: fft
tagged with: python
has comment: http://stackoverflow.com/comment/90344398
score: 2
has body: I would like to calculate the frequency of a periodic time series using NumPy FFT. As an example, let's say my time series y is defined as follows: import numpy as np freq = 12.3 x = np.arange(10000) y = np.cos(x * 2 * np.pi * freq / 10000) If the frequency is an integer, I can calculate it using np.argmax(np.abs(np.fft.fft(y))). However, in case the frequency is not an integer, how do I calculate the frequency with more precision? EDIT: To clarify, we are not supposed to know how the time series y is generated. The above code snippet is just an artificial example of how a non-integer frequency could come up. Obviously if we already know the function that generates the time series, we don't need FFT to determine the frequency.
upvote count: 2
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51695295
has comment: http://stackoverflow.com/comment/90345487
has answer: http://stackoverflow.com/a/51691759
has answer: http://stackoverflow.com/a/51690939
tagged with: numpy

http://stackoverflow.com/comment/90456696
type: QuestionComment
comment on: http://stackoverflow.com/q/51744012
has text: I've edited my answer
score: 0
type: Comment

http://stackoverflow.com/comment/90393960
type: Comment
type: QuestionComment
has text: Please note that syntax errors and debugging help are off-topic for StackOverflow.
comment on: http://stackoverflow.com/q/51716345
score: 0

http://stackoverflow.com/a/51788557
type: Answer
answers question: http://stackoverflow.com/q/51788445
has body: Assuming you wish to drop rows where any column except for energy_100g has a value > 100. In this case, you can use pd.DataFrame.any to create a Boolean mask: data = data[~(data[data.columns.difference(['energy_100g'])] &gt; 100).any(1)] Equivalently, you can use all without negation and the reverse comparison: data = data[(data[data.columns.difference(['energy_100g'])] &lt;= 100).all(1)] In each case, we use pd.Index.difference to exclude the specified column for our comparisons.
score: 1
accepted answer of: http://stackoverflow.com/q/51788445
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51750670
has body: Your problem is using pandas.to_parquet() to write the data. This creates a single massive row-group out of the data, which becomes one partition when Dask reads it - Dask follows whatever partitioning is in the data. Conversely, Dask automatically partitions CSV input, not assuming that the data has inherent partitioning. Since you are already using Dask, you should use it for writing the parquet data too, using dask.DataFrame.to_parquet, the analogue of the Pandas method. It will produce multiple files in a directory, which will be read independently and in parallel.
accepted answer of: http://stackoverflow.com/q/51749914
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51749914
downvote count: 0
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/90275851
type: Comment
has text: @Pier-OlivierMarquis What you're saying makes no sense to me, can you create a minimal example that illustrates this behaviour?
comment on: http://stackoverflow.com/a/51655368
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90318628
type: QuestionComment
has text: I used urltools.compare which compares 2 urls and tells whether they match or not.
comment on: http://stackoverflow.com/q/51677550
score: 0
type: Comment

http://stackoverflow.com/comment/90394092
type: AnswerComment
score: 0
type: Comment
has text: @abarnet Thanks so much for this answer, its very illuminating. In light of what @hoelfling just suggested, I feel like there is something else happening with the `-U` flag, do you think you could see the above `EDIT` I made.
comment on: http://stackoverflow.com/a/51715882

http://stackoverflow.com/comment/90335711
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51685330
has text: @cruisepandey Unfortunately that is not the case. The user can close the browser anytime he/she desire. I can think of a few 'ugly' 'roundabout' solution like having `win32gui` check if the window still exist or through `tasklist` check if the browser window is still running but I am searching for the most _selenium-ish_ way of solving this.

http://stackoverflow.com/q/51768972
score: -2
tagged with: pyspark
upvote count: 0
accepted answer: http://stackoverflow.com/a/51769398
answer count: 1
has body: I want to extract the key for my dictionary but the problem is that the key is enclosed in single quotes. from pyspark import SparkContext, SparkConf import collections,shutil,os conf = SparkConf().setMaster("local").setAppName("Word_count") sc=SparkContext(conf=conf) rdd=sc.textFile("/home/karan/dummy files/patient.csv") rdd2=sc.textFile("/home/karan/dummy files/doctors.csv") def nameOfDoc(): names={} with open("/home/karan/dummy files/doctors.csv") as l: for x in l: nameExt=x.split('\t') names[int(nameExt[0])]=nameExt[1] return names docName=sc.broadcast(nameOfDoc()) docId=rdd.map(lambda x:x.split(",")).\ map(lambda x:(x[3],1)).\ reduceByKey(lambda x,y:x+y).\ map(lambda x:(x[1],x[0])).\ sortByKey(ascending=False).\ map(lambda x:(x[1],x[0])) rs=docId.collect() if os.path.exists("/home/karan/output2"): shutil.rmtree("/home/karan/output2") for x in rs: print(docName.value[x[0]],end=" -&gt; ") print(x[1]) sc.parallelize(rs).saveAsTextFile("output2") My code is giving me this error File "/home/karan/hospitalsDemo.py", line 28, in print(docName.value[x[0]],end=" -> ") KeyError: '2'
favorite count: 0
has comment: http://stackoverflow.com/comment/90496936
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51769398
type: Question
has title: How to extract single quoted number from the list in python
has comment: http://stackoverflow.com/comment/90499907

http://stackoverflow.com/q/51746426
has body: How can I check whether a line in my text file contains letters? I am trying below code, but unable to check: with open(inputfile,'r') as f: for line in f: if re.search(r'[a-zA-Z0-9]',str(line)): print( "line contains letters" )
has comment: http://stackoverflow.com/comment/90452561
has comment: http://stackoverflow.com/comment/90452775
has comment: http://stackoverflow.com/comment/90452796
score: 0
has comment: http://stackoverflow.com/comment/90452474
tagged with: nlp
linked to: http://stackoverflow.com/q/9072844
has comment: http://stackoverflow.com/comment/90452529
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/9072844
tagged with: python
tagged with: regex
has title: Check whether a line in my text file contains letters
has comment: http://stackoverflow.com/comment/90452840
type: Question

http://stackoverflow.com/q/51715782
has body: I want a data frame consisting of numeric values transformed into three specific symbols depending on whether the value is negative, zero or positive. In addition, the check should be influenced by an epsilon value to control what is considered zero. csv = pd.read_csv('filename.csv') df = csv.iloc[:, :].diff() df = df.iloc[1:,:] # remove the first row of nans I tried the following neg = df &lt; -eps zer = abs(df) &lt;= eps pos = df &gt; eps df[neg] = 'neg' df[zer] = 'zer' df[pos] = 'pos' Which worked for some time, but when eps reached a certain value, the following error was thrown TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value I then tried the following: df.transform(lambda x: ('neg' if x &lt; -eps else 'zer') if abs(x) &lt;= eps else 'pos') Resulting error ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0') I have two questions: Why do I get a TypeError only when eps becomes large, but works for, e.g eps = 0? How to perform this transformation?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51715936
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
has title: Conditional transformation of Pandas DataFrame into negative, zero, and positive with epsilon precision
tagged with: transformation
accepted answer: http://stackoverflow.com/a/51715936
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90392967

http://stackoverflow.com/comment/90331303
type: Comment
has text: Works perfectly. Thanks!!
comment on: http://stackoverflow.com/a/51684364
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90392088
type: Comment
comment on: http://stackoverflow.com/a/51714864
has text: Thank you very much. I made this example just so I could understand the basics of mocking in Python and your explanation helped perfectly.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51697727
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51714698
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90438029
has comment: http://stackoverflow.com/comment/90357591
has comment: http://stackoverflow.com/comment/90357023
tagged with: python
has comment: http://stackoverflow.com/comment/90361147
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90390784
accepted answer: http://stackoverflow.com/a/51714698
has body: I have around 13 NumPy arrays stored as files that take around 24 gigabytes on disk. Each file is for a single subject and consists of two arrays: one containing input data (a list of 2D matrices, rows represent sequential time), and the other one containing labels of the data. My final goal is to feed all the data to a deep learning network I've written in Keras to classify new data. But I don't know how to do it without running out of memory. I've read about Keras's data generators, but cannot find a way to use it for my situation. I've also looked up HDF5 and h5py, but I don't know how can add all the data to a single array(dataset in HDF5) without running out of memory.
tagged with: hdf5
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90358621
has title: How to feed multiple NumPy arrays to a deep learning network in Keras?

http://stackoverflow.com/comment/90313047
type: Comment
type: QuestionComment
has text: I've rolled back your edit where you've removed the URL since the information which site you are trying to access is essential for answering the question. And the problem is not TLS 1.0 as you've tried to suggest in your edit.
comment on: http://stackoverflow.com/q/51661796
score: 0

http://stackoverflow.com/comment/90476270
comment on: http://stackoverflow.com/a/51718688
has text: https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py this code is what you need to import inception_resnet_v2. First copy the code and paste it in your project dir, you should be able to run the code above.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51728593
upvote count: 2
linked to: http://stackoverflow.com/q/46853629
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
downvote count: 0
has title: RelatedField Serializer Django Rest Framework
has body: I have this tables store in a Postgres DB users | id | email | password | gender | | 01 | user1@email.com | pass1 | male | | 02 | user2@email.com | pass3 | female | | 03 | user3@email.com | pass2 | male | marks | id | school_mark | subject | user_id | status | | 01 | 9 | history | 01 | True | | 02 | 8 | english | 02 | True | | 03 | 7 | math | 01 | True | | 02 | 7 | english | 01 | False | | 03 | 6 | math | 03 | False | ... user_id is a foreign key that links the marks element to each user id (in both table) are primary keys # api/models.py from django.db import models class User(models.Model): email = models.EmailField() password = models.CharField(max_length=100) gender = models.CharField(max_length=100) class Mark(models.Model): school_mark = models.IntegerField() subject = models.CharField(max_length=100) user_id = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) I want my final result to be like this /api/marks/male [ {"id" : 01, "marks": [ {"id": 01, "subject": "history", "school_mark": 9}, {"id": 03, "subject": "history", "school_mark": 7}]} {"id" : 03, "marks": []} ] First select only 'male' form user, then search marks for selected users but return in the response only the marks that have status=TRUE I start to think the serializers.py like this: # api/serializers.py from rest_framework import serializers from .models import User, Mark class MarkSerializer(serializers.ModelSerializer): class Meta: model = Mark exclude = ('status', 'user_id') class UserSerializer(serializers.ModelSerializer): marks = MarkSerializer(many=True, read_only=True) class Meta: model = User fields = ('id', 'marks') But then I'm stuck on views.py # api/views.py from rest_framework import generics from .models import User, Mark from .serializers import UserSerializer class MarkList(generics.ListAPIView): serializer_class = UserSerializer def get_queryset(self): # "/api/marks/&lt;str:gender&gt;/" gender = kwargs['gender'] ??? Any idea how to g…
type: Question
has answer: http://stackoverflow.com/a/51730569
tagged with: django-rest-framework

http://stackoverflow.com/q/51654924
has body: I should be seeing a value displayed right next to "Notifications" and before the exclamation symbol. Just as it sounds, I cannot display a context variable "{{ var }}" provided in a view. I've tried cbv and function based views. In this project I am using Django 2.1 and Python alias is set as 3.6 This is the first sort of view I used, simply to display a number: class NotificationView(DetailView): template_name = "base.html" def get_context_data(self, **kwargs): message_count = Message.objects.filter(recipient=self.request.user).count() safeTrans_count = SafeTransaction.objects.filter(trans_recipient=self.request.user).count() context = super().get_context_data(**kwargs) context["Notify"] = message_count + safeTrans_count return context This is the second sort of view, I tried to make the simplest possible function that would display a context: def NotifyView(request): title = "Notification View %s" % (request.user) context = { "Notification_Count": 10, "Notification_Title": title, } return render(request, "base.html", context) This is a snippet of the template used to display (Variables such as {{Notification_Title}} simply do not display at all) : {% if user.is_authenticated %} Notifications{{Notification_Title}} {% else %} Any ideas as to what I could be overlooking would be very much appreciated. ::: Here is my solution for this particular problem. Please let me know if there is a better way to display the values without having to pass user in the actual template tag on the template as:{% notify user %}
has comment: http://stackoverflow.com/comment/90278346
has answer: http://stackoverflow.com/a/51657878
has comment: http://stackoverflow.com/comment/90273296
tagged with: python
has comment: http://stackoverflow.com/comment/90273695
has title: Why is my view context not displaying in this case?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90278374
has comment: http://stackoverflow.com/comment/90279365
has comment: http://stackoverflow.com/comment/90278545
tagged with: django
accepted answer: http://stackoverflow.com/a/51657878
type: Question
has comment: http://stackoverflow.com/comment/90273997
has comment: http://stackoverflow.com/comment/90273274
has comment: http://stackoverflow.com/comment/90276455
has comment: http://stackoverflow.com/comment/90273357
has comment: http://stackoverflow.com/comment/90279412
score: 0
has comment: http://stackoverflow.com/comment/90273830
has comment: http://stackoverflow.com/comment/90279243
answer count: 1

http://stackoverflow.com/comment/90431304
has text: I use the **Setup** section so that anyone reading can reproduce my results. I don't expect that you (the OP) needs to use it. You should be able to skip right to the solution. However, my solution assumes the column names `'col1'` and `'col2'`. You could replace those with your own column names since you did not provide them. That said, my third solution should work on any dataframes given that their resprective indices are unique.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51734907
type: Comment

http://stackoverflow.com/a/51766897
downvote count: 0
answers question: http://stackoverflow.com/q/51761009
has comment: http://stackoverflow.com/comment/90504708
has body: You could subclass tempfile._TemporaryFileWrapper, then monkey-patch the name so that NamedTemporaryFile returns an instance of your subclass. class TempFile(tempfile._TemporaryFileWrapper): ... tempfile._TemporaryFileWrapper = TempFile x = NamedTemporaryFile(...) This should work (untested), since NamedTemporaryFile is hard-coded to return an instance of _TemporaryFileWrapper, whatever that name is bound to.
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90504416
upvote count: 1

http://stackoverflow.com/comment/90397246
has text: Is there a question in here?
comment on: http://stackoverflow.com/q/51718118
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90521754
comment on: http://stackoverflow.com/q/51782114
score: 2
type: QuestionComment
has text: `text_it = text_it.replace('\0', 'null')` ?
type: Comment

http://stackoverflow.com/comment/90284282
score: 0
has text: You should really make an effort to format for readability.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51660134

http://stackoverflow.com/a/51672518
has body: List slicing will work if you know how many characters you want to replace. From IDLE: &gt;&gt;&gt; longstr = "this is a somewhat lengthy string" &gt;&gt;&gt; longstr[:5] 'this ' &gt;&gt;&gt; longstr[5:] 'is a somewhat lengthy string' &gt;&gt;&gt; longstr[:-5] 'this is a somewhat lengthy s' &gt;&gt;&gt; longstr = longstr[:-6] + "road" &gt;&gt;&gt; longstr 'this is a somewhat lengthy road'
answers question: http://stackoverflow.com/q/51672437
type: Answer
score: 0

http://stackoverflow.com/comment/90388726
score: 0
has text: You are right that the lock is appropriate for use with the distributed scheduler, so this is not an error. You can use the distributed scheduler locally too, if you wish.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51711953

http://stackoverflow.com/comment/90294236
type: Comment
type: QuestionComment
has text: Thank You guys I learned to use it using a normal text editor.....
comment on: http://stackoverflow.com/q/51645246
score: 0

http://stackoverflow.com/a/51784129
has comment: http://stackoverflow.com/comment/90525712
has comment: http://stackoverflow.com/comment/90526486
has comment: http://stackoverflow.com/comment/90525803
answers question: http://stackoverflow.com/q/51783628
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90526008
has body: I've just tried your tests on Python 3.6.6 and it worked as expected. The only different thing I did was the use of re.compile instead. Look: Python 3.6.6 (default, Jul 19 2018, 14:25:17) [GCC 8.1.1 20180712 (Red Hat 8.1.1-5)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import re &gt;&gt;&gt; zipcode = re.compile(r'.*([0-9０-９]{3}[-ー]{1}[0-9０-９]{4}).*') &gt;&gt;&gt; zipcode.match("this is obviously not going to work") &gt;&gt;&gt; zipcode.match("this is going to work 123-4567") &lt;_sre.SRE_Match object; span=(0, 30), match='this is going to work 123-4567'&gt; &gt;&gt;&gt; zipcode.match("this is going to work 123-4567").group(0) 'this is going to work 123-4567' &gt;&gt;&gt; zipcode.match("this is going to work 123-4567").group(1) '123-4567' &gt;&gt;&gt; zipcode.match("this is going to work too １２３ー４５６７").group(1) '１２３ー４５６７' &gt;&gt;&gt; zipcode.match("This should not work, but it does : １２３４ー５６７").group(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'NoneType' object has no attribute 'group' &gt;&gt;&gt; zipcode.match("This should not work, but it does : １２３４ー５６７") &gt;&gt;&gt; zipcode.match("Now just seems crazy ....... 京都府") &gt;&gt;&gt; zipcode.match("京都府") &gt;&gt;&gt; EDIT Here is what I have so far: $ cat ziptest.py # -*- coding: utf-8 -*- import re zipcode = re.compile(r'.*([0-9０１２３４５６７８９]{3}[-ー]{1}[0-9０１２３４５６７８９]{4}).*') tests = ( "this is obviously not going to work", "this is going to work 123-4567", "this is going to work too １２３ー４５６７", "This will not work, as it should not : 1234-567", "This should not work, but it does : １２３４ー５６７", "Now just seems crazy ....... 京都府", "京都府", "\xe4\xba\xac\xe9\x83\xbd\xe5\xba\x9c" ) for test in tests: print('%s: %s' % (test, "Match" if zipcode.match(test) else "No match")) $ And here are the results: $ python2.7 ziptest.py this is obviously not going to work: No match this is going to work 123-4567: Match this is going t…
has comment: http://stackoverflow.com/comment/90525545
upvote count: 1

http://stackoverflow.com/comment/90422855
comment on: http://stackoverflow.com/a/51729808
score: 0
type: AnswerComment
has text: @Wem You are right. It does not work yet and i am trying to find why. I understood that when Maria is the first and the last in a group, it does not work
type: Comment

http://stackoverflow.com/comment/90309547
score: 1
comment on: http://stackoverflow.com/q/51659185
type: Comment
type: QuestionComment
has text: I am curious what the content of the SVG looks like. Can you include it in your question please?

http://stackoverflow.com/comment/90413159
score: 2
comment on: http://stackoverflow.com/q/51726307
has text: Perform an absdiff on the before and after images. If there is no change, the difference image will be entirely black. If there is a change the difference image will be non-black in that region. Then detect the region of non-black images. The shift will be at most half the horizontal and vertical dimensions of the roi.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51698417
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51698484
has comment: http://stackoverflow.com/comment/90379364
tagged with: post
type: Question
has answer: http://stackoverflow.com/a/51698666
accepted answer: http://stackoverflow.com/a/51698666
has comment: http://stackoverflow.com/comment/90358354
answer count: 2
tagged with: variables
tagged with: flask
possible better answer: http://stackoverflow.com/a/51698484
score: 0
tagged with: python
has title: The easiest way to pass multiple variable from 2 files html with Flask
has body: I'm triyng to understand how Flask works. I have this script running on my local machine: @app.route('/ordini', methods=['GET', 'POST']) def ordini(): global data_start, ora_start, data_stop, id, M1, M2, M3, M4, M5 if request.method == 'POST': id = request.form['id'] data_start = request.form['data_start'] ora_start = request.form['ora_start'] data_stop = request.form['data_stop'] M1 = request.form['M1'] M2 = request.form['M2'] M3 = request.form['M3'] M4 = request.form['M4'] M5 = request.form['M5'] return render_template('ordine_macchine_necessarie.html', id=id, data_start=data_start, data_stop=data_stop, ora_start=ora_start, M1=M1, M2=M2, M3=M3, M4=M4, M5=M5) return render_template('ordine.html') Every thing works just fine, I get the values from the ordine.html and I pass them to ordine_macchine_necessarie.html but in my opinion I'm not passing the values in the correct way. Do I really have to set all the variables like id = request.form['id'] and then pass all of them like id=id ? I can imagine forms composed by 50 or more values, I'm pretty sure that I'm not doing something correctly.. Maybe is better if I start to learn Django instad Flask? some users says that it is better!

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/51776054
type: Tag

http://stackoverflow.com/a/51733351
upvote count: 4
has comment: http://stackoverflow.com/comment/90436916
downvote count: 0
has body: I'm going to demonstrate the structured array approach: I'm guessing you are starting with a csv file 'table'. If not it's still the easiest way to turn your sample into an array: In [40]: txt = '''col1, col2, col3, col4, col5 ...: 1.31 1 2 3 "a" ...: 2.33 3 5 4 "b" ...: ''' In [42]: data = np.genfromtxt(txt.splitlines(), names=True, dtype=None, encoding=None) In [43]: data Out[43]: array([(1.31, 1, 2, 3, '"a"'), (2.33, 3, 5, 4, '"b"')], dtype=[('col1', '&lt;f8'), ('col2', '&lt;i8'), ('col3', '&lt;i8'), ('col4', '&lt;i8'), ('col5', '&lt;U3')]) With these parameters, genfromtxt takes care of creating a structured array. Note it is a 1d array with 5 fields. Fields dtype are determined from the data. In [44]: import h5py ... In [46]: f = h5py.File('struct.h5', 'w') In [48]: ds = f.create_dataset('data',data=data) ... TypeError: No conversion path for dtype: dtype('&lt;U3') But h5py has problems saving the unicode strings (default for py3). There may be ways around that, but here it will be simpler to convert the string dtype to bytestrings. Besides, that'll be more compact. To convert that, I'll make a new dtype, and use astype. Alternatively I could specify the dtypes in the genfromtxt call. In [49]: data.dtype Out[49]: dtype([('col1', '&lt;f8'), ('col2', '&lt;i8'), ('col3', '&lt;i8'), ('col4', '&lt;i8'), ('col5', '&lt;U3')]) In [50]: data.dtype.descr Out[50]: [('col1', '&lt;f8'), ('col2', '&lt;i8'), ('col3', '&lt;i8'), ('col4', '&lt;i8'), ('col5', '&lt;U3')] In [51]: dt1 = data.dtype.descr In [52]: dt1[-1] = ('col5', 'S3') In [53]: data.astype(dt1) Out[53]: array([(1.31, 1, 2, 3, b'"a"'), (2.33, 3, 5, 4, b'"b"')], dtype=[('col1', '&lt;f8'), ('col2', '&lt;i8'), ('col3', '&lt;i8'), ('col4', '&lt;i8'), ('col5', 'S3')]) Now it saves the array without problem: In [54]: data1 = data.astype(dt1) In [55]: data1 Out[55]: array([(1.31, 1, 2, 3, b'"a"'), (2.33, 3, 5, 4, b'"b"')], dtype=[('col1', '&lt;f8'), ('col2', '&lt;i8'), ('col3', '&lt;i8'), ('col4', '&lt;i8'), ('col5', 'S3…
has comment: http://stackoverflow.com/comment/90436691
has comment: http://stackoverflow.com/comment/90536985
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51729840
has comment: http://stackoverflow.com/comment/90461891
answers question: http://stackoverflow.com/q/51729840
type: Answer

http://stackoverflow.com/comment/90261550
type: Comment
type: QuestionComment
has text: I would like to store it that way, but for now I'm a bit newbie at writing in Python3 and I don't know how to mix using dictionaries with other equipment mechanics I used so far. So I will try to make it that way in the future, but for now I wanted to have at least well-working mechanics for one item.
score: 0
comment on: http://stackoverflow.com/q/51648835

http://stackoverflow.com/a/64790325
answers question: http://stackoverflow.com/q/51784495
downvote count: 0
has body: In general just add one extra argument to your plot call: secondary_y=['size']. In this case a separate plot is easier though, because of line vs bars etc.
type: Answer
score: 14
upvote count: 14

http://stackoverflow.com/comment/110167333
comment on: http://stackoverflow.com/a/51735766
type: Comment
has text: I do not understand. This does not explain why the heapify() takes O(log(N)). TH(n) = c, if n=1 worst case when the largest if never root: TH(n) = c + ? * TH( ? ) how to write the recursive expression?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51787248
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/28569461
has body: Does pandas have any function that can be used to select data that belongs to a certain month. If I would like data for January then based on the Series below it would be 4654.92 and 5922.55. 2008-01-31 4654.921202 2008-02-29 4405.907331 2008-03-31 5277.126015 2008-04-30 3814.353624 2008-05-31 909.466583 2008-06-30 498.991260 2008-07-31 95.671703 2008-08-31 26.762731 2008-09-30 303.874072 2008-10-31 2219.250418 2008-11-30 3562.633841 2008-12-31 5669.641461 2009-01-31 5922.555024 2009-02-28 4990.197616 Best Smail
type: Question
has title: Python pandas, select data by month
has comment: http://stackoverflow.com/comment/90531605
duplicate of: http://stackoverflow.com/q/28569461
score: 0
has answer: http://stackoverflow.com/a/51787285

http://stackoverflow.com/q/51755652
has body: I have shared hosting for my website at Godaddy with shared hosting in cpanel. I made a python script that print hello and I even tried with the GUI too but it is not printing. It is only showing the code. I called GoDaddy and they said to do print("Hello World") but even though I did it is still not working. Right now my code is print("Hello World"). Printing hello world like that normally works but it is not working. I need to use python 2.6.6 because that's what GoDaddy gives as the version number for python. Please can somebody help? You can check out my python script in my website at My python script in my website.
tagged with: python
has comment: http://stackoverflow.com/comment/90471221
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51868345
tagged with: web-hosting
upvote count: 1
downvote count: 1
type: Question
tagged with: cpanel
accepted answer: http://stackoverflow.com/a/51868345
score: 0
has comment: http://stackoverflow.com/comment/90476292
answer count: 2
possible better answer: http://stackoverflow.com/a/51756023
has title: Why is my python script not running in shared hosting cpanel GoDaddy
has answer: http://stackoverflow.com/a/51756023
tagged with: web
favorite count: 0

http://stackoverflow.com/q/51707847
answer count: 1
has answer: http://stackoverflow.com/a/51708007
has comment: http://stackoverflow.com/comment/90376525
has body: I want to create 10,000 random numbers withing the range of 1 to 100. How can I do with python? I can use for loop and with each for loop I can use random.sample() or random.random() function. Is there any other way, without using any for loop I can generate it with built-in function ?
favorite count: 0
has comment: http://stackoverflow.com/comment/90376777
score: 0
tagged with: python
has title: Creating random list of number in python within certain range
accepted answer: http://stackoverflow.com/a/51708007
has comment: http://stackoverflow.com/comment/90376795
upvote count: 3
has comment: http://stackoverflow.com/comment/90376660
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90376579
has comment: http://stackoverflow.com/comment/90376859
downvote count: 3
has comment: http://stackoverflow.com/comment/90376521
type: Question
tagged with: random

http://stackoverflow.com/q/51673310
has title: Remote ray call not detecting function arguments
has comment: http://stackoverflow.com/comment/90309523
has answer: http://stackoverflow.com/a/54285771
tagged with: python
tagged with: parallel-processing
score: 2
has comment: http://stackoverflow.com/comment/90310428
upvote count: 3
downvote count: 1
has body: When executing a @ray.remote function, the following exception is being thrown, even though I am supplying all the arguments set in the function definition: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ray/signature.py in extend_args(function_signature, args, kwargs) 208 raise Exception("No value was provided for the argument " 209 "'{}' for the function '{}'.".format( --&gt; 210 keyword_name, function_name)) 211 212 no_positionals = len(arg_is_positionals) == 0 or not arg_is_positionals[-1] Exception: No value was provided for the argument 'phones' for the function 'compile_file'. Edit: A minimal example of my remote function definition and remote call is as follows: import ray ray.init(num_cpus=4, num_gpus=1, include_webui=False) #initialize ray with 4 CPUs @ray.remote def compile_file(self, rgx_patts, phones): # method for my Case class self._phones = self.phonelist(rgx_patts, phones) def compile_all(inputDirectory='C/TODOS', phones = ['10002000']): d = {} file_lst = pdfLister(inputDirectory, termin) for i, file in enumerate(file_lst): doc = Case(file) doc.compile_file.remote(rgx_patts, phones) # exception thrown here d[i] = doc case_dic = {k: ray.get(dic_id) for k, dic_id in d.items()} return case_dic Edit: Full exception below --------------------------------------------------------------------------- Exception Traceback (most recent call last) &lt;timed exec&gt; in &lt;module&gt;() ~/compile_files.py in compile_all(pckle, inputDirectory, pickle_op_file, termin, rgx_patts, ceav_phones) 111 prm._rgx_patts, prm._ceav_phones) 114 d[i] = doc 115 ceav_dic = {k: ray.get(dic_id) for k, dic_id in d.items()} /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ray/remote_function.py in remote(self, *args, **kwargs) 103 def remote(self, *args, **kwargs): 104 """This runs immediately when a remote function is called.""" --&gt; 105 return self._submit(args=args, kwargs=kwargs) 106 107 def _submit(self, /Library/Fram…
type: Question
has comment: http://stackoverflow.com/comment/90325106
has answer: http://stackoverflow.com/a/52903322
has comment: http://stackoverflow.com/comment/90320110
answer count: 2
favorite count: 0
tagged with: ray
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/51685601
type: Answer
answers question: http://stackoverflow.com/q/51685322
upvote count: 34
score: 34
has body: Try to convert your ndarray with tolist() method: prediction = model.predict(np.array(X).tolist()).tolist() return jsonify({'prediction': prediction}) Example with json package: a = np.array([1,2,3,4,5]).tolist() json.dumps({"prediction": a}) That should output: '{"prediction": [1, 2, 3, 4, 5]}'
accepted answer of: http://stackoverflow.com/q/51685322
has comment: http://stackoverflow.com/comment/90335622
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90333624

http://stackoverflow.com/q/51754074
has comment: http://stackoverflow.com/comment/90493419
tagged with: interception
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90494432
has title: how to get specific cookies from requests when the library doesn't handle them for you
accepted answer: http://stackoverflow.com/a/51773147
downvote count: 3
tagged with: python-requests
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90468111
has comment: http://stackoverflow.com/comment/90468268
linked to: http://stackoverflow.com/q/12737740
answer count: 1
has answer: http://stackoverflow.com/a/51773147
favorite count: 0
has body: So I have this page I need to make login in constantly, but I can't even make login in the page if I don't use some cookies in the headers. The problem is if I use the cookies postman gives me, they will eventually expire and I have to replace all of them again in the code. #####this makes the login url = "https://www.APAGE.com"#login url payload = "user="+dude["user"]+"&amp;password="+dude["password"]+"&amp;action=login" headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0", #for some reason i need this or the page returns error 'Content-Type': "application/x-www-form-urlencoded", 'X-Requested-With': "XMLHttpRequest", 'Cookie': "ASP.NET_SessionId=&lt;an usually expirable cookie&gt;; __RequestVerificationToken_L0NvbnN1bHRhV2Vi0=&lt;another expirable cookie&gt;",#i need THESE! 'Cache-Control': "no-cache", } login = session.post(url, data=payload, headers=headers)# makes the login print "Login open" cookie = session.cookies.get_dict() #get the recursive cookie #this here is me trying to grab the request-cookies just after the login so i can repass them so they don't expire print '================' print login.request.headers print '================' print '\n\n\n' cookie2 = login.headers.get('Set-Cookie') print login.headers print cookie2 print login.cookies.get_dict() #makes a get request to change to the initial page url = "www.APAGE-after-login.com" headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0", 'Referer': "www.APAGE-after-login.com", 'Cookie': "ASP.NET_SessionId=&lt;the cookie again&gt;.; __RequestVerificationToken_L0NvbnN1bHRhV2Vi0=&lt;the other cookie&gt;; .ASPXAUTH="+str(cookie['.ASPXAUTH']), #here i need to repost the .ASPAUTH cookie every time after a request or the session expires 'Upgrade-Insecure-Requests': "1", 'Cache-Control': "no-cache", } moving = session.get(url,headers=headers) cookie = session.cookies.get_dict() I need help here to get t…
has comment: http://stackoverflow.com/comment/90468030
has comment: http://stackoverflow.com/comment/90493317
score: -3
tagged with: python

http://stackoverflow.com/a/51654179
has comment: http://stackoverflow.com/comment/90272340
has comment: http://stackoverflow.com/comment/90272354
has comment: http://stackoverflow.com/comment/90272200
answers question: http://stackoverflow.com/q/51653603
type: AcceptedAnswer
downvote count: 0
has body: as jasonharper indicated in the comments, you need to un-disable your text box before you can add text to it. Additionally, displayText.insert(window,result) is not the correct way to call it. insert's first argument should be an index, not the window object. Try: def Response(): #no need to use global here result = myText.get() displayText.configure(state='normal') displayText.insert(END, result) displayText.configure(state='disabled') (You may need to do tk.END or tkinter.END instead of just END, depending on how you originally imported tkinter. It's hard to tell since you didn't provide that part of your code)
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51653603
upvote count: 2

pycharm
tags question: http://stackoverflow.com/q/51664225
tags question: http://stackoverflow.com/q/51645855
tags question: http://stackoverflow.com/q/51678520
tags question: http://stackoverflow.com/q/51725200
tags question: http://stackoverflow.com/q/51702078
tags question: http://stackoverflow.com/q/51669527
tags question: http://stackoverflow.com/q/51776054
tag name: pycharm
tags question: http://stackoverflow.com/q/51745342
tags question: http://stackoverflow.com/q/51797190
tags question: http://stackoverflow.com/q/51726577
tags question: http://stackoverflow.com/q/51731291
tags question: http://stackoverflow.com/q/51730826
tags question: http://stackoverflow.com/q/51697302
tags question: http://stackoverflow.com/q/51790721
tags question: http://stackoverflow.com/q/51720624
tags question: http://stackoverflow.com/q/51755136
tags question: http://stackoverflow.com/q/51731420
tags question: http://stackoverflow.com/q/51767596
tags question: http://stackoverflow.com/q/51750056
tags question: http://stackoverflow.com/q/51787630
tags question: http://stackoverflow.com/q/51699886
tags question: http://stackoverflow.com/q/51672903
tags question: http://stackoverflow.com/q/51689464
tags question: http://stackoverflow.com/q/51689573
tags question: http://stackoverflow.com/q/51651420
tags question: http://stackoverflow.com/q/51752911
tags question: http://stackoverflow.com/q/51724303
tags question: http://stackoverflow.com/q/51725802
type: Tag
tags question: http://stackoverflow.com/q/51688219
tags question: http://stackoverflow.com/q/51720866
tags question: http://stackoverflow.com/q/51761768
tags question: http://stackoverflow.com/q/51760911
tags question: http://stackoverflow.com/q/51661560
tags question: http://stackoverflow.com/q/51658181

http://stackoverflow.com/q/51781507
has title: a simplified signature in functools.partial
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: In the official docs to explain functools 10.2. functools — Higher-order functions and operations on callable objects — Python 3.7.0 documentation The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two: I could understand most of the statement and admit the "freeze" is a delicate and accurate word to describe the context. What I cannot follow is "a simplified signature", What kind of signature it refers for?
type: Question
possible better answer: http://stackoverflow.com/a/51781612
accepted answer: http://stackoverflow.com/a/51781611
has answer: http://stackoverflow.com/a/51781612
answer count: 3
has answer: http://stackoverflow.com/a/51781621
upvote count: 1
has answer: http://stackoverflow.com/a/51781611

http://stackoverflow.com/a/51778521
has comment: http://stackoverflow.com/comment/90515432
has body: You should escape literal braces by doubling them: json_data_resp = '{{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'.format(activation_code, macaddress) Excerpt from Format String Syntax: Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
answers question: http://stackoverflow.com/q/51778475
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51778475
downvote count: 0
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/90527928
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51785506
has text: It adds each letter to `translation`, except if that letter is present in `"AEIOUaeiou"`, in which case it adds a `"g"` instead.
score: 3

http://stackoverflow.com/comment/90353419
comment on: http://stackoverflow.com/a/51691351
type: Comment
has text: The thing is I have used nested loops so I could not figure out where to initialize empty marker dict. I was having problem in understanding the appending part in loops.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90533654
has text: Ok great thank you - I'm just implementing it now to check - and thanks for the otherwise direction, checking why it doesn't work in my script - and thanks for the Boolean note as well.
type: Comment
comment on: http://stackoverflow.com/a/51788067
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90543940
has text: Thanks @Onyambu `df.dropna()` looks like it could be very useful, but I'm looking for a more nuanced approach. The data set I'm working with may produce results with empty values that are still valid, so I wouldn't want to discard everything with an empty value. What I'm trying to do is find a way to apply a lambda to the group of matches in order to select the best match from that group. The best I've come up with so far is using `df.apply()` to apply a lambda to the individual rows.
comment on: http://stackoverflow.com/q/51775817
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90246488
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51640868
has text: Why do you need a regex? `if 1 <= int(Severity) <= 19:`

http://stackoverflow.com/q/51709724
has answer: http://stackoverflow.com/a/58480514
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90394749
has comment: http://stackoverflow.com/comment/90392951
tagged with: python
answer count: 4
has title: Virtualenv not activating in Windows 10 PowerShell
type: UnansweredQuestion
has body: I'm having trouble activating the virtualenv in Windows as I am going through the basic book of Learning Python the Hard Way. Here is what I am getting: PS C:\Users\Owner> virtualenv --system-site-packages .venvs/lpthw Using base prefix 'c:\users\owner\appdata\local\programs\python\python36' New python executable in C:\Users\Owner.venvs\lpthw\Scripts\python.exe Installing setuptools, pip, wheel...done. PS C:\Users\Owner> ..venvs\lpthw\Scripts\activate ..venvs\lpthw\Scripts\activate : The term '..venvs\lpthw\Scripts\activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ..venvs\lpthw\Scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (..venvs\lpthw\Scripts\activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
upvote count: 1
has answer: http://stackoverflow.com/a/54013881
type: Question
has comment: http://stackoverflow.com/comment/90390905
has answer: http://stackoverflow.com/a/51709889
has answer: http://stackoverflow.com/a/51709871
tagged with: powershell
has comment: http://stackoverflow.com/comment/90381924

http://stackoverflow.com/q/51744306
has answer: http://stackoverflow.com/a/51745269
type: Question
answer count: 1
favorite count: 0
score: 0
has body: I want to send a message to a telegram bot using Telethon and handle its response using an event handler function. Is there a way to set a timeout for the incoming event? For example, If I send "Hi" message to the bot and it doesn't respond to me after 5 seconds, Telethon send the "Hi" message again.
type: UnansweredQuestion
has title: Telethon timeout for resending message
upvote count: 1
tagged with: python
downvote count: 1
tagged with: telethon

http://stackoverflow.com/a/51707204
score: 1
answers question: http://stackoverflow.com/q/51707081
has comment: http://stackoverflow.com/comment/90375375
upvote count: 1
downvote count: 0
has body: Use print(instance.somevar) to get the somevar value, but you change it inside your function, not globally
type: Answer

date
tags question: http://stackoverflow.com/q/51761703
tag name: date
tags question: http://stackoverflow.com/q/51694375
type: Tag
tags question: http://stackoverflow.com/q/51770740
tags question: http://stackoverflow.com/q/51652649
tags question: http://stackoverflow.com/q/51724283
tags question: http://stackoverflow.com/q/51714580

http://stackoverflow.com/a/51752158
type: Answer
has comment: http://stackoverflow.com/comment/90465655
upvote count: 1
has body: Place your script in a function. Default is four retry ;) import subprocess import time def retry_code(n=4): ''' function that attempts to perform a task n times. If fails terminates itself ''' try: WAIT=500 file_name = ("bot.py") while True: process=subprocess.Popen("python "+ file_name) time.sleep(WAIT) process.kill() raise TimeoutError('Took too long') except TimeoutError as e: # We need a condition of numbers of attempts # Else we will have infinite attempts. And see if process failed n-=1 if n &gt; 0: print('trying again!') retry_code(n) # &lt;&lt;-- call function again :) else: print('failed attempts') quit() # terminate
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51751674

http://stackoverflow.com/q/51711962
answer count: 0
has body: "final_counts" is of type "class 'scipy.sparse.csr.csr_matrix'" and of Shape (364171, 115281) "new_column" is of type "class 'numpy.ndarray'" and of Shape (364171,) Here I am not sure why the number of columns is null. Using below code to add a new column "new_column" to "final_counts" merged_data = scipy.sparse.hstack((final_counts, new_column)) Above Code is giving below error kindly help. FYI - Same code on a very small data set is working. File "C:\Python34\lib\site-packages\scipy\sparse\construct.py", line 464, in hstack return bmat([blocks], format=format, dtype=dtype) File "C:\Python34\lib\site-packages\scipy\sparse\construct.py", line 585, in bmat raise ValueError(msg) ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 1, expected 364171.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51700979
tagged with: scipy
type: Question
tagged with: numpy
score: 0
has title: Not able to use hstack on a Sparse CSR Matrix & Pandas Dataframe
has comment: http://stackoverflow.com/comment/90387547
tagged with: python
has comment: http://stackoverflow.com/comment/90387576

http://stackoverflow.com/comment/90487924
type: Comment
comment on: http://stackoverflow.com/q/51734728
type: QuestionComment
has text: So does it have to stay in the same class where it is used, or is it also closed by changing function?
score: 0

http://stackoverflow.com/q/51705106
has title: How can I make this calculation function with a lot of parameters more readable?
has comment: http://stackoverflow.com/comment/90374191
has comment: http://stackoverflow.com/comment/90371909
downvote count: 1
type: Question
score: 0
upvote count: 1
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/51705169
has body: I built a calculator for calculating the sales commission on a certain sale. The value of the commission is depended on a lot of factors. Therefore the parameters to have to be passed to the function in which I calculate the commission is very large too. The function itself is also very confusing, because some of the factors are booleans (new customer, f.e.) and some are floats (transport costs, f.e.). How can I make these kind of "calculation functions" more readable? Should I break them up in smaller pieces? Here is the function, although I am looking also for more general advice how to tackle these kind of functions. def get_provision_sales( verkaufspreis_hw, einkaufspreis_hw, vk_software, ek_software, bonafide, laufzeit, abloese, gebraucht, neukunde, spedition, sonstige_kosten, provision_pct = 0.33, service_pct=0.035, solutions=False ): if spedition: spedition_amount = 89.99 else: spedition_amount = 0 verkaufspreis_hw = verkaufspreis_hw or 0 if vk_software &gt; 0: software_mod = 0.7 else: software_mod = 1 if not bonafide: provision_modifier = 0.76 else: provision_modifier = 1 if neukunde: provision_pct = 0.27 laufzeit = laufzeit or 0 abloese = abloese or 0 if gebraucht: db_modifier = 1 sonstige_kosten = 0 deckungsbeitrag = 0.6 * float(verkaufspreis_hw) else: db_modifier = 0.85 deckungsbeitrag = float(verkaufspreis_hw) - ( float(einkaufspreis_hw) + float(abloese) + float(spedition_amount) ) provision_sales = (deckungsbeitrag * db_modifier + float(sonstige_kosten)) * provision_pct * provision_modifier provision_sales += software_mod*0.15*(float(vk_software)-float(ek_software)) return provision_sales
favorite count: 0
has comment: http://stackoverflow.com/comment/90371615
has comment: http://stackoverflow.com/comment/90373982
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/3898572

cs50
tag name: cs50
type: Tag
tags question: http://stackoverflow.com/q/51689442

http://stackoverflow.com/q/51704539
linked to: http://stackoverflow.com/q/15496051
has body: From my Python code (Flask application, actually), I need to execute sqlite query, of the following structure SELECT some_column FROM My_table WHERE some_column=some_value; Now, some_column recurs twice in the query, one way to execute it is: cursor.execute('SELECT ? FROM Users WHERE ?=?;', (some_column, some_column, some_value)) Which is not very nice/Pythonic. Then I came up with: cursor.execute('SELECT {0} FROM Users WHERE {0}=?;'.format(some_column), (some_value,)) Finally, I ended up using .format() all the way: cursor.execute('SELECT {0} FROM Users WHERE {0}={1};'.format(some_column, some_value), ()) I am wondering if there is prettier and/or more Pythonic way to pass recurring arguments into sqlite's cursor.execute()?
favorite count: 0
duplicate of: http://stackoverflow.com/q/902408
has title: An elegant way to pass repeating argument to sqlite query
upvote count: 2
accepted answer: http://stackoverflow.com/a/51705054
tagged with: python
possible better answer: http://stackoverflow.com/a/51704629
has answer: http://stackoverflow.com/a/51704629
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/5607737
linked to: http://stackoverflow.com/q/51312952
duplicate of: http://stackoverflow.com/q/15496051
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90370065
tagged with: sqlite
has answer: http://stackoverflow.com/a/51705054
score: 1

http://stackoverflow.com/q/51713789
has comment: http://stackoverflow.com/comment/90389419
has body: I got this question in a recent interview, Given a gird of letter and a word find all the possible paths that make a word Directions: horizontal, vertical or diagonal to any coordinate with a distance 1 Constraint: Each path has to be a unique set of coordinates. Example: S T A R A R T Y X K C S T R A P START - &gt; 2 This is my solution, class WordFinder: def __init__(self): self.neighbors = [[-1, 1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1]] def find_all_paths(self, grid, word): count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == word[0]: visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))] result = [] self.helper(grid, 0, 0, visited, word, 0, result) count += len(result) return count def helper(self, grid, row, col, visited, word, index, result): if index == len(word): result.append(1) adjacent = [] for item in self.neighbors: adjacent.append([row + item[0], col + item[1]]) for adj in adjacent: if 0 &lt;= adj[0] &lt; len(grid) and 0 &lt;= adj[1] &lt; len(grid[0]): if not visited[adj[0]][adj[1]]: if index + 1 &lt; len(word) and grid[adj[0]][adj[1]] == word[index + 1]: visited[adj[0]][adj[1]] = True self.helper(grid, adj[0], adj[1], visited, word, index + 1, result) visited[adj[0]][adj[1]] = False if __name__ == '__main__': word_finder = WordFinder() print(word_finder.find_all_paths( [['s', 't', 'a', 'r'], ['a', 'r', 't', 'y'], ['x', 'k', 'c', 's'], ['t', 'r', 'a', 'p']], "start")) This yields the wrong answer. Can someone help understand the problem with my logic.
has comment: http://stackoverflow.com/comment/90389206
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90391328
has comment: http://stackoverflow.com/comment/90389476
accepted answer: http://stackoverflow.com/a/51715070
tagged with: algorithm
upvote count: 0
has comment: http://stackoverflow.com/comment/90389187
tagged with: data-structures
has title: Backtracking to find all possbile paths
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90391450
favorite count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/51715070
tagged with: python
tagged with: backtracking
tagged with: recursive-backtracking

http://stackoverflow.com/comment/90514430
comment on: http://stackoverflow.com/q/51778005
has text: True that it doesnt make sense to have upperbound values smaller than lowerbound values. it's just an example though.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51666700
answers question: http://stackoverflow.com/q/51652937
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I made it work! It was the obvious way: the cast! number = myLib.getNumberFromDict(dict(self.myDict)) Works well, I get the expected result in number.
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51652937

http://stackoverflow.com/a/51698808
has comment: http://stackoverflow.com/comment/90566889
score: 0
has body: Since you have return_sequences=True in model.add(keras.layers.LSTM(250,batch_input_shape=(60,250,1), activation='tanh',return_sequences=True,stateful=True,recurrent_dropout=0.2)) It returns a 3 dimensional tensor of shape [batch_size, time_step, hidden_dim] Now if you want to use a dense layer for such time-series data, you need to use the TimeDistributed in Keras the following way, model.add(TimeDistributed(Dense(4,activation='softmax')))
answers question: http://stackoverflow.com/q/51684041
accepted answer of: http://stackoverflow.com/q/51684041
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51756558
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51757886
answer count: 2
has answer: http://stackoverflow.com/a/51757163
has body: I'm trying to record the training accuracy of the model at the end of each epoch, but I wasn't sure if the training accuracy is calculated on the entire training data or the last mini-batch used for training. For example, if I have 10000 training data and I'm training with mini-batches of 100, would I calculate the training accuracy using the last mini-batch of 100 (the 100th and last mini-batch in that epoch) or use the entire 10000 training data?
downvote count: 0
favorite count: 0
has title: Is training accuracy of a model calculated on the mini-batch?
score: 3
tagged with: python
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/90513379
type: QuestionComment
comment on: http://stackoverflow.com/q/51777395
has text: Ah. Sorry for multiple comments. The only reason I mentioned re.finditer is so that people don't suggest completely different methods that can't yield offsets.
score: 0
type: Comment

http://stackoverflow.com/comment/90392372
score: 0
type: Comment
type: QuestionComment
has text: @abarnert I am on a corporate network but I can view that link, do you recommend then contacting the IT dept and ask them about this error?
comment on: http://stackoverflow.com/q/51714885

http://stackoverflow.com/q/51732854
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/90611181
tagged with: python
has body: The following code executes without error up until the PivotCache.CreatePivotTable() statement. Excel or windows COM is having a problem with something. The error message indicates that the problem is with the parameters passed but that does not appear to be a correct error message. I can execute the same methods in VBA and works without error (syntax is a little different - but passing the same parameter values). Do I need to type the parameters differently? The error is returned from win32com. There are ample code examples for this. Anaconda Python 3.6. Excel 2013. I have reinstalled win32com (conda install win32com). Code Excel = win32com.client.gencache.EnsureDispatch('Excel.Application') win32c = win32com.client.constants ####\#load the workbook wb = Excel.Workbooks.Open('c:\devworkspace\SQL-Pandas-Excel\LargeClaims.xlsx') ####\#create a worksheet object for source data src_sheet = wb.Worksheets('Total Direct Pay') ####\#add the pivot table work sheet and name pvt_sheet = wb.Sheets.Add(After=src_sheet) pvt_sheet.Name = 'Pivot Sheet' ####\#set the source range "Total Direct Pay!R2C2:R162855C19" rng_row = int(largest_claims_df.shape[0]) rng_col = int(largest_claims_df.shape[1]) pvt_src = "%s!R2C2:R%dC%d"%(src_sheet.Name,rng_row+1,rng_col+1) \# offset index and header ####\#Create the Pivot Cache pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase, SourceData=pvt_src) ####\#Create the Pivot Table try: pt = pc.CreatePivotTable(TableDestination='Pivot Sheet!R4C1',TableName='PivotTable1') except pythoncom.com_error as error: print(error.excepinfo[5]) print(win32api.FormatMessage(error.excepinfo[5])) Here is the error code and translated message: -2147024809 The parameter is incorrect. Also the complete stack trace not handled: --------------------------------------------------------------------------- com_error Traceback (most recent call last) <ipython-input-16-6924c75f990d> in <module>() 7 8 ----> 9 pt = pc.CreatePivotTable(TableDestination='Pivot Sheet!R4C1',Ta…
tagged with: excel
has comment: http://stackoverflow.com/comment/90824045
tagged with: anaconda
score: 0
answer count: 1
tagged with: win32com
type: UnansweredQuestion
has title: Python win32com PivotCache.CreatePivotTable() error: 'The parameter is incorrect'
has answer: http://stackoverflow.com/a/51772497
type: Question

http://stackoverflow.com/a/51742379
answers question: http://stackoverflow.com/q/51742072
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90516731
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51742072
type: Answer
score: 2
has body: Replace ax1.xaxis.set_ticks(df['date']) with: ax1.set_xticklabels(df['date']) To have a different date format, you can use this line to change your date column: df['date'] = df['date'].dt.strftime('%d/%m/%Y')

http://stackoverflow.com/comment/90346419
comment on: http://stackoverflow.com/q/51692392
score: 0
type: Comment
type: QuestionComment
has text: Are you sure that `v.upload_time` holds some values?

http://stackoverflow.com/q/51790935
has title: django How to execute a function asynchronously i.e, handover a task to a sub process and return response
type: Question
tagged with: django-views
has body: I am using django 2.0 and python 3.6. The user registration includes sending of a verification mail. And this mail sending process is taking longer and the user is kept waiting. What I need?: If the user registration form is valid, mailing details are sent to another task handler and regardless of whether the mail is sent or not, the function must resume and return a response. def new_user_registration(request): form = CustomUserCreationForm(request.POST or None) if form.is_valid(): user = form.save() send_verification_mail(user) #&lt;= taking more time. return render(request, 'registration/signup.html') i.e, the send_verification_mail must be called asynchronously. How to achieve it? Note: I am new to django and python.
score: 6
has comment: http://stackoverflow.com/comment/117115650
has answer: http://stackoverflow.com/a/51791108
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/127505770
favorite count: 0
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/62390314
upvote count: 6
accepted answer: http://stackoverflow.com/a/51791108
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90539607
tagged with: django
tagged with: django-forms

http://stackoverflow.com/q/51768092
has comment: http://stackoverflow.com/comment/90495440
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90494830
favorite count: 0
accepted answer: http://stackoverflow.com/a/51768795
has comment: http://stackoverflow.com/comment/90495104
score: -3
tagged with: python
has body: I want to extract the date from the following image. I tried using tesseractocr library but I couldn't go any further....
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51768795
has comment: http://stackoverflow.com/comment/90495934
downvote count: 3
tagged with: image-processing
has title: Get a stamp date from a scanned image using python
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/90494858
has comment: http://stackoverflow.com/comment/90495182

http://stackoverflow.com/q/51784299
has comment: http://stackoverflow.com/comment/90527454
tagged with: python
tagged with: qt
has comment: http://stackoverflow.com/comment/90534150
has comment: http://stackoverflow.com/comment/90528192
has comment: http://stackoverflow.com/comment/90552904
score: 0
tagged with: executable
has comment: http://stackoverflow.com/comment/90525793
answer count: 0
has comment: http://stackoverflow.com/comment/90528483
type: UnansweredQuestion
tagged with: ubuntu
tagged with: centos
has title: To create an executable from QT for linux
has body: I am trying to develop a GUI for one of the requirements for daily activities at my workplace. I am using QT creator for it. The problem is that all my team members have Centos machines whereas I have developed in ubuntu system. In QT I am using python coding for the development of code. How do I share it as an executable and make it work on their respective platforms?
type: Question

http://stackoverflow.com/comment/90311601
comment on: http://stackoverflow.com/q/51672398
score: 0
type: Comment
type: QuestionComment
has text: maybe have a look at [sample](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html), it could help you about the random idea

http://stackoverflow.com/q/51652175
has body: basically i have dataframe like this col1 col2 col3 col4 1. 554862122 55110385224 PR 26 2. 5242700637 55110385236 CO 246 3. 560297164 55110385250 CO 109 4. 5651138615 55110385266 PR 26 5. 5242699687 55110385289 CO 109 i convert it to dict like this {554862122: {55110385224: {'PR 26': 2})}, 5242699687: {55110385289: {'CO 109': 6}), 554862121: {55110385224: {'PR 26': 3})}" but now i want this but without loops {'PR 26':[5,[554862122,55110385224],[554862121,55110385224]], 'CO 109':[6,[5242699687,55110385289]]}
has title: get total sum of counts of repeating key in nested dictionary
upvote count: 1
tagged with: python
tagged with: dictionary
answer count: 1
has comment: http://stackoverflow.com/comment/90294062
has comment: http://stackoverflow.com/comment/90267596
downvote count: 4
has comment: http://stackoverflow.com/comment/90267807
type: UnansweredQuestion
score: -3
tagged with: data-science
has answer: http://stackoverflow.com/a/51652397
favorite count: 0
has comment: http://stackoverflow.com/comment/90294123
has comment: http://stackoverflow.com/comment/90267664
type: Question

amd-gpu
tags question: http://stackoverflow.com/q/51729853
type: Tag
tag name: amd-gpu

http://stackoverflow.com/comment/90481943
type: Comment
score: 0
has text: Possible duplicate of [Openpyxl max\_row and max\_column wrongly reports a larger figure](https://stackoverflow.com/questions/46569496/openpyxl-max-row-and-max-column-wrongly-reports-a-larger-figure)
comment on: http://stackoverflow.com/q/51747535
type: QuestionComment

http://stackoverflow.com/comment/90491522
score: 0
has text: Just notice that I used r' in the function call and this option relevant only for python 3.6 + , if you use previous version just put it out and double all the slash instead
type: AnswerComment
comment on: http://stackoverflow.com/a/51766011
type: Comment

http://stackoverflow.com/q/51678823
has body: I have a dataset which contains column with data about seniority in company of the form: '9 years 9 months 14 days' in str format. I transformed them to float by for cycle with regular expression: for row in range(len(df)): target = df['seniority'][row] content = re.findall(r'\d+', target) content[0] = float(content[0]) content[1] = (float(content[1]))/12 content[2] = ((float(content[2]))/30)/12 content = sum(content) df['seniority'][row] = content It works. But I interested in more effective and fast way to do that if it exist.
has comment: http://stackoverflow.com/comment/90337168
score: 1
has title: Change complex str to float in pandas Dataframe
has answer: http://stackoverflow.com/a/51679065
accepted answer: http://stackoverflow.com/a/51679065
tagged with: dataframe
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: string
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90320901
type: Question

http://stackoverflow.com/q/51690304
has body: Using apache web hosting I launched my first web app today and I noticed that if I put examply.com/example.py in my web browser I can see my python source code with my sql password in it. How do I prevent this?
has answer: http://stackoverflow.com/a/61774431
type: Question
answer count: 2
tagged with: apache
has answer: http://stackoverflow.com/a/51690383
accepted answer: http://stackoverflow.com/a/51690383
has title: How to hide serverside python file from web browser?
score: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/61774431
type: AnsweredQuestion

http://stackoverflow.com/comment/90311508
comment on: http://stackoverflow.com/q/51672398
has text: whats your actual wanted output, is it second or third ? if it is third, then what is the condition for that value
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51673950
answers question: http://stackoverflow.com/q/51673769
accepted answer of: http://stackoverflow.com/q/51673769
type: AcceptedAnswer
downvote count: 0
has body: I'm guessing you are looking for something more along the lines of: if row[0] in d['a'].values(): row[1] = d['b'][row[0]] I've done a couple of things here. First of all, dict is a built-in Python function, so I've named your dictionary d to not conflict with it. Secondly, in this expression: d['b'[0]] Reading it from the inside out, it takes the string 'b', takes the first letter of it, then looks that up in the dictionary. If you rewrite that to: d['b'][row[0]] It looks up the key 'b' in the dictionary, then takes the element with key row[0] in the resulting dictionary. Finally, on the left-hand side: [row[1]] = ... isn't a valid assignment. You just want to set the second value of an existing array, so you'd write row[1] = ...
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51746035
answer count: 3
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90452451
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51746333
has comment: http://stackoverflow.com/comment/90451960
has title: I want to sort a dictionary with key being month-year
has comment: http://stackoverflow.com/comment/90451876
score: -2
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/90452306
tagged with: python-2.7
has body: I want to sort a dictionary with key being month-year. Eg: For March 2017,January 2018,May 2017 etc. My dictionary keys should be sorted in this order: March 2017,May 2017,January 2018 What to do ? Eg: {'February 2017': {'a': 1.0, 'b': 683.01}, 'March 2018': {'a': 0.0, 'b': 623.79}, 'March 2017': {'a': 1.0, 'b': 683.01}} NB: Values of Month Year comes dynamically.
linked to: http://stackoverflow.com/q/44861179
has answer: http://stackoverflow.com/a/51746339
has answer: http://stackoverflow.com/a/51746335
has comment: http://stackoverflow.com/comment/90452289
has comment: http://stackoverflow.com/comment/90452177

http://stackoverflow.com/comment/90380636
type: AnswerComment
has text: Awesome, thanks! Indeed, the output still needs cleaning. For instance, a package named `some-package` would be store in the directory `some_package-version.dist-info` (note that the dash has become an underscore). But this can be done manually.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51709735

http://stackoverflow.com/q/51689901
has body: I tried creating Identity matrix, but there was a problem creating a 2D array (list inside a list so to say) that can be determined by an input/parameter. I expected from this:- def eye(limit): lst = [[0] * limit] * limit for i in range(limit): lst[i][i] =1 return lst for item in eye(4): print(item) to output this:- [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1] but instead, go this:- [1, 1, 1, 1] [1, 1, 1, 1] [1, 1, 1, 1] [1, 1, 1, 1] I tried to create a fixed 4x4 array, and it surprisingly worked and out-putted the expected answer. And lead me to think that by multiplying a list won't create another list and concatenate them, but instead printing them by the number they got multiplied of. What do you think and how can i create a variable one.
has comment: http://stackoverflow.com/comment/90341625
has comment: http://stackoverflow.com/comment/90341658
score: 0
linked to: http://stackoverflow.com/q/240178
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90341722
type: Question
has title: Multiplying a list by a number creates items have relation with the original one?
linked to: http://stackoverflow.com/q/18946728
has comment: http://stackoverflow.com/comment/90341641
has comment: http://stackoverflow.com/comment/90341667
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/90341692
has comment: http://stackoverflow.com/comment/90341673
has comment: http://stackoverflow.com/comment/90341646

http://stackoverflow.com/q/51692392
type: Question
has body: views.py def myVideo(request, id): myVideo = MyVideo.objects.filter(id=id) serializerClassVideo = MyVideoSerializer(myVideo,many=True) print(type(myVideo[0].upload_time)) print(myVideo[0].upload_time) myDate = datetime.now() print(type(myDate)) print(myDate) return render(request, 'video.html', { 'myDate': myDate, 'videos': serializerClassVideo.data, } ) in the console, output like this: &lt;class 'datetime.datetime'&gt; 2018-05-30 19:52:20+00:00 # video.upload_time &lt;class 'datetime.datetime'&gt; 2018-08-05 13:47:57.653627 # datetime.now() video.html On the html page, the first line above shows: 2018-08-05 which is great, and the second one, that I need, shows nothing. I thought the issue should be related to the timezone in the "upload_time" field. What should I do if I don't want to change this field (which means I want to keep the timezone of "upload_time")?
possible better answer: http://stackoverflow.com/a/51692475
answer count: 2
has answer: http://stackoverflow.com/a/51692475
has comment: http://stackoverflow.com/comment/90346602
accepted answer: http://stackoverflow.com/a/51692487
tagged with: django-templates
tagged with: django
tagged with: python
has title: How to render datetime.datetime with timezone to the HTML template in Django?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90346419
score: 0
has answer: http://stackoverflow.com/a/51692487

http://stackoverflow.com/q/51772935
tagged with: python
has title: NotFittedError when using RandomForestRegressor
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90504768
downvote count: 1
type: Question
tagged with: random-forest
has body: Python newbie. I'm trying to run simple random forest model with 5 features and one label but when I run RandomForestRegressor I get a NotFittedError (Below) which I do not understand. Any help appreciated... --------------------------------------------------------------------------- NotFittedError Traceback (most recent call last) &lt;ipython-input-86-b670604a6f52&gt; in &lt;module&gt;() ----&gt; 1 predictions = rf.predict(train_features) /anaconda3/lib/python3.6/site-packages/sklearn/ensemble/forest.py in predict(self, X) 677 The predicted values. 678 """ --&gt; 679 check_is_fitted(self, 'estimators_') 680 # Check data 681 X = self._validate_X_predict(X) /anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any) 766 767 if not all_or_any([hasattr(estimator, attr) for attr in attributes]): --&gt; 768 raise NotFittedError(msg % {'name': type(estimator).__name__}) 769 770 NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51773071
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51710462
type: Question
tagged with: apache-kafka
tagged with: avro
answer count: 2
has answer: http://stackoverflow.com/a/51716681
score: 0
possible better answer: http://stackoverflow.com/a/51714654
has answer: http://stackoverflow.com/a/51714654
has body: I'm using python to read messages coming from various topics. Some topics have got their messages encoded in plain JSON, while others are using Avro binary serialization, with confluent schema registry. When I receive a message I need to know if it has to be decoded. At the moment I'm only relying on the fact that the binary encoded messages are starting with a MAGIC_BYTE which value is zero: from confluent_kafka.cimpl import Consumer consumer = Consumer(config) consumer.subsrcibe(...) msg = consumer.poll() # check the msg is not null or error etc if msg.values()[0] == 0: # It is binary encoded else: # It is json I was wondering is there's a better way to do that?
tagged with: python
accepted answer: http://stackoverflow.com/a/51716681
has title: Differentiating between binary encoded Avro and JSON messages
type: AnsweredQuestion
tagged with: confluent-schema-registry

http://stackoverflow.com/comment/90332521
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51684616
has text: Once I click on button then I know that a JS alert will pop up, now I would simply extract the data which is present in alert and match it with my expected text. If both strings are same then my script will get to know that I have clicked on the right button.
type: AnswerComment

http://stackoverflow.com/q/51696767
has comment: http://stackoverflow.com/comment/90354912
has comment: http://stackoverflow.com/comment/90355065
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90355015
has comment: http://stackoverflow.com/comment/90354844
has comment: http://stackoverflow.com/comment/90354991
has comment: http://stackoverflow.com/comment/90355206
tagged with: pylint
tagged with: python
has answer: http://stackoverflow.com/a/51698110
favorite count: 0
has comment: http://stackoverflow.com/comment/90354866
type: UnansweredQuestion
has title: Grouping import statements in python
has body: I have started learning python recently and ran pylint on my python file. I got following comments. from os import listdir from os.path import isfile, join I the above two lines, the Pylinter comment is C: 5, 0: Imports from package os are not grouped (ungrouped-imports) How can I achieve that ? And another comment is in below line import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests C: 5, 0: standard import "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" should be placed before "import mimetypes, time, csv, platform, base64, django, sys, os, math, uuid, linecache, logging, requests" (wrong-import-order) what does the above line mean and why is it required?
type: Question
score: 10
upvote count: 10

http://stackoverflow.com/a/51698732
has body: A literal \t+ from an external source is not the same thing as the literal string "\t+". What does print("\t+") output? What about print(r"\t+")? The latter is equivalent to accepting that literal string as input to be used as a regex. The former is not. However, for this specific situation the distinction does not matter since a literal tab character should behave exactly the same as \t in a regex. Ponder the following examples from an Ipython session: In [24]: re.compile('\t+').findall('^I') Out[24]: ['\t'] In [25]: re.compile('\t+').findall("\t") Out[25]: ['\t'] In [26]: re.compile(r'\t+').findall('^I') Out[26]: ['\t'] In [27]: re.compile(r'\t+').findall("\t") Out[27]: ['\t'] In [28]: re.compile(r'\t+').findall(r"\t") Out[28]: [] I can only conclude your first example, the one which didn't produce the expected output, did not have a literal tab in the quoted string. Also, re.escape() is not appropriate for this situation. Its purpose is to ensure that a string from an untrusted source is treated literally rather than a regex so that it can safely be used as a literal string to be matched.
answers question: http://stackoverflow.com/q/51691270
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51741054
has title: I would expect the output to be like [[0,0,0,0,],[0,1,0,0],[0,2,0,0],[0,3,0,0]]
has answer: http://stackoverflow.com/a/52497544
favorite count: 0
tagged with: assign
tagged with: nested-lists
has body: time_count = [[0, 0, 0, 0]] * 4 j = 0 for i in range(len(time_count)): time_count[i][1] = j j += 1 print(time_count) Output: [[0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0]] I would expect the output to be like: [[0,0,0,0],[0,1,0,0],[0,2,0,0],[0,3,0,0]] can someone explain why every index[1] is 3 ?
tagged with: python
accepted answer: http://stackoverflow.com/a/53304095
has answer: http://stackoverflow.com/a/51741246
score: 4
has comment: http://stackoverflow.com/comment/90442282
tagged with: list
has comment: http://stackoverflow.com/comment/90442562
possible better answer: http://stackoverflow.com/a/51741227
tagged with: loops
has answer: http://stackoverflow.com/a/51741227
upvote count: 4
type: AnsweredQuestion
downvote count: 0
answer count: 5
has answer: http://stackoverflow.com/a/53304095
has answer: http://stackoverflow.com/a/51741377
type: Question

http://stackoverflow.com/q/51762461
has body: Currently my submit button is only on one object which is because its outside the for loop, therefor it will only do the computation on the bottom file. However if I put the button back inside the loop it will put a submit button for every row, but it wont be able to do the computation for multiple files, So I'm wondering how do I get one submit button for all the files, so it will do the computation for each file(which ever is currently checked) (Searched this question before and none of the previously answered questions helped) HTML File (Partially) {% for f in files %} {{ f.key }} {% endfor %} Submit Python File(Partially) @expose('/', methods=['POST', 'GET']) @appbuilder.app.route('/', methods=['POST', 'GET']) def action(self): my_bucket = get_bucket() s = my_bucket.objects.all() t = getmyobject() return render_template( 'page.html', my_bucket=my_bucket, base_template=appbuilder.base_template, appbuilder=appbuilder, page=s, t=t )
answer count: 2
linked to: http://stackoverflow.com/q/247483
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
possible better answer: http://stackoverflow.com/a/51762695
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51763236
tagged with: flask-appbuilder
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51763236
has answer: http://stackoverflow.com/a/51762695
type: Question
has title: Multiple checkboxes one submit button in multiple forms
tagged with: flask

http://stackoverflow.com/comment/90455339
has text: Thanks for checking - but how do I search for that tag within the xml? Is there a namespace that I can reference?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51737825

http://stackoverflow.com/a/70402064
type: Answer
answers question: http://stackoverflow.com/q/51669962
has body: I've implemented the code in Python with parallel processing, which will be much faster than serial computation. Furthermore, where a fuzzy metric score exceeds a threshold, only those computations are performed in parallel. Please see the link below for the code: https://github.com/ankitcoder123/Important-Python-Codes/blob/main/Faster%20Fuzzy%20Match%20between%20two%20columns/Fuzzy_match.py Vesrion Compatibility: pandas version :: 1.1.5 , numpy vesrion:: 1.19.5, fuzzywuzzy version :: 1.1.0 , joblib version :: 0.18.0 Fuzzywuzzy metric explanation: link text Output from code:
score: 0

http://stackoverflow.com/comment/95372296
type: Comment
has text: your guess is correct. `s` is for start and `e` is for end
comment on: http://stackoverflow.com/a/51801596
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90396190
has text: The code I wrote here for the timing used Jeremy Romans code btw.
type: Comment
comment on: http://stackoverflow.com/a/51691711
score: 0
type: AnswerComment

http://stackoverflow.com/q/51728089
has answer: http://stackoverflow.com/a/51728244
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51728207
type: Question
tagged with: boolean
has body: I have a big tab-deltimited csv file: first tab is for emotion words, second for eight basic emotions, plus the values positive and negative, and the last tab is the boolean value if the the second tab-value fits the first. A snippet from the file: snarl anger 1 snarl anticipation 0 snarl disgust 1 snarl fear 0 snarl joy 0 snarl negative 1 snarl positive 0 snarl sadness 0 snarl surprise 0 snarl trust 0 snarling anger 1 snarling anticipation 0 snarling disgust 0 snarling fear 0 snarling joy 0 snarling negative 1 snarling positive 0 snarling sadness 0 snarling surprise 0 snarling trust 0 My code so far to do this: import csv from pprint import pprint from itertools import groupby l = list(csv.reader(open('NRC-Emotion-Lexicon-Wordlevel-v0.92.txt'))) f = lambda x: x[-1] #manipulate number to see different results {k:[tuple(x[0:1]) for x in v] for k,v in groupby(sorted(l[1:], key=f), f)} pprint(l) My current output is not that good looking: ['asylum\tanger\t0'], ['asylum\tanticipation\t0'], ['asylum\tdisgust\t0'], ['asylum\tfear\t1'], ['asylum\tjoy\t0'], ['asylum\tnegative\t1'], ['asylum\tpositive\t0'], ['asylum\tsadness\t0'], ['asylum\tsurprise\t0'], ['asylum\ttrust\t0'], My question is: How do I create a dictionary of lists with one unique key for each of the repeated emotion words (reducing 10 repetitions to 1, each) and only include the second tab elements in the list of that dictionary key, when they have the boolean value of 1? Any kind of help would be appreciated! EDIT: as one of the replies stated, an example of the desired output would look like this: {'snarl': ['anger', 'disgust'], #included in list due to having '1', ignoring 'positve' and 'negative' 'snarling': ['anger'], #etc... } EDIT 2: The first and the last lines of the file are empty, as I mentioned in the answers per comments.
has title: How to create a dictionary of lists with unique mentions from a tab-delimited csv file using boolean values
score: 0
has comment: http://stackoverflow.com/comment/90417092
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51728400
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/51730017
has answer: http://stackoverflow.com/a/51728207
has comment: http://stackoverflow.com/comment/90416857
possible better answer: http://stackoverflow.com/a/51728244

http://stackoverflow.com/comment/90373264
type: QuestionComment
has text: Ok, didn't notice that thanks
comment on: http://stackoverflow.com/q/51705239
score: 0
type: Comment

encoding
tags question: http://stackoverflow.com/q/51709842
type: Tag
tags question: http://stackoverflow.com/q/51787177
tag name: encoding
tags question: http://stackoverflow.com/q/51693909
tags question: http://stackoverflow.com/q/51676365
tags question: http://stackoverflow.com/q/51741691
tags question: http://stackoverflow.com/q/51793846

http://stackoverflow.com/comment/90547433
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51794615
score: 1
has text: So basically you're looking for a way to match either a `|` character or the end of the string? That would be `(?:$|\|)`.

http://stackoverflow.com/q/51680809
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
has title: How to seperate rectangles in tkinter using the canvas function?
has answer: http://stackoverflow.com/a/51680892
upvote count: 0
score: -1
accepted answer: http://stackoverflow.com/a/51680892
has body: I am trying to figure out how to put my rectangle using the canvas tkinter tool in a certain place. I have read many articles that said it does it for you but every time I change the coordinates, my shape either disappears or is stuck right inside and/or next to another shape. I want 3 rectangles the same size to appear next to each other with a little gap between each rectangle and I want them to appear vertically. My current code looks like this: from tkinter import * root = Tk() root.geometry('640x480') c = Canvas(root, height=250, width=300, bg="blue") c.pack(padx=10, pady=20, side=LEFT) r = c.create_rectangle(0,0,100,100, fill="yellow", activefill="grey", disabledfill="grey") f = c.create_rectangle(240,240,100,100, fill="red", activefill="grey", disabledfill="grey") r = Canvas(root) r = c.pack(padx=10) root.mainloop()
answer count: 1
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90332281

http://stackoverflow.com/q/51697784
has comment: http://stackoverflow.com/comment/90357113
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51699774
has comment: http://stackoverflow.com/comment/90357626
has answer: http://stackoverflow.com/a/51699774
downvote count: 1
has answer: http://stackoverflow.com/a/51699729
type: Question
has comment: http://stackoverflow.com/comment/90357297
has body: I want to use the command: subprocess.check_output(["powercfg", "-list"]) which gives me: Existing Power Schemes (* Active) ----------------------------------- Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (Balanced) Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (High performance) Power Scheme GUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (Power saver) * which is good. But, I only want the variables in the middle to go into their own variables without all the extra text. The problem is that the command comes out in multiple lines so I can't use (list[19:55]). I also need to do this with each of the strings inside the parentheses into their own variables but I think I can figure that out. I'm new to Python so I'm open to whatever.
score: 0
answer count: 3
has title: How to skip lines of command into variable in Python
accepted answer: http://stackoverflow.com/a/51699729
tagged with: powercfg
favorite count: 0
has answer: http://stackoverflow.com/a/51717027
has comment: http://stackoverflow.com/comment/90357400
has comment: http://stackoverflow.com/comment/90357450
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90385828
score: 0
type: Comment
type: QuestionComment
has text: @Jimenemex: Can you please explain your second recommendation with an example? Thanks.
comment on: http://stackoverflow.com/q/51712162

http://stackoverflow.com/comment/90344172
has text: Thanks martineau for pointing out, but the post was not what I have in mind. I want to ask whether there is a different way to achieve my goal.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51689458

http://stackoverflow.com/comment/90509326
comment on: http://stackoverflow.com/a/51774930
has text: i have added the environment setting image to the question. I am totally new on python but my base interpreter is showing the location given by you before. thank you
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90384729
comment on: http://stackoverflow.com/q/51711660
score: 0
type: Comment
has text: "I'm not getting anywhere at the moment" is not a problem statement. Surely you have some specific symptoms of "not getting anywhere" you'd like to share and discuss?
type: QuestionComment

http://stackoverflow.com/a/51789854
upvote count: 2
type: Answer
has body: One approach using itertools.chain and set Ex: from itertools import chain l = [[1, 2], [1, 3], [1, 4]] print(set(chain.from_iterable(l))) Output: set([1, 2, 3, 4]) chain to flatten the list
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51789837

http://stackoverflow.com/comment/90550873
has text: Anyway the reason why you are getting positional index error is because you have tried to drop the element in the loop, setting the j=j will not reduce the range of index that you will be looping through.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51796886
score: 0

http://stackoverflow.com/comment/90381860
score: 0
comment on: http://stackoverflow.com/a/51710038
type: AnswerComment
type: Comment
has text: Thanks for your help! I did add a sleep delay and unfortunately I'm getting the same error. I moved the connection code to the two lines directly below try and it's still resulting in the same error. Is that the correct place to put them?

http://stackoverflow.com/a/67735948
answers question: http://stackoverflow.com/q/51648534
score: 0
has comment: http://stackoverflow.com/comment/135210639
has body: withEnv(["HOME=${env.WORKSPACE}"]) {} is the key. Also, it can be used like: node { def customImage = docker.build(...) customImage.inside { withEnv(["HOME=${env.WORKSPACE}"]) { sh '...' } } }
type: Answer

http://stackoverflow.com/comment/90512231
has text: python 3.5 @vishes_shell
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51776014

http://stackoverflow.com/comment/90377514
type: Comment
comment on: http://stackoverflow.com/q/51708202
score: 0
type: QuestionComment
has text: How do you open the file?

http://stackoverflow.com/q/51669589
has comment: http://stackoverflow.com/comment/90503470
tagged with: visual-studio-code
has body: I have followed the steps on the Visual Studio Code Python extension concerning formatting (I have enabled editor.formatOnSave, set a path for the black formatter, switched to black as formatter for the python extension, even made sure that black was in the path for the terminal -- unrelated). But still, there's no message in the Python extension output, and the code keeps being unformatted. I am on macOS, the selected python interpreter is a pipenv 2.7 interpreter (but black is available at a different location, set as python.formatter.blackPath) Thus, how to debug the formatting capability of this extension?
has title: How to debug the Visual Studio Code Python extension formatting capability?
score: 0
has comment: http://stackoverflow.com/comment/90320738
tagged with: python
has comment: http://stackoverflow.com/comment/90320744
has comment: http://stackoverflow.com/comment/90503478
answer count: 0
has comment: http://stackoverflow.com/comment/90589847
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90615666
has comment: http://stackoverflow.com/comment/90591881
has comment: http://stackoverflow.com/comment/90341600
type: Question
has comment: http://stackoverflow.com/comment/90539952

http://stackoverflow.com/q/51755916
accepted answer: http://stackoverflow.com/a/51756551
tagged with: python
type: AnsweredQuestion
has title: Selenium calling class elements doesn't work
score: 1
tagged with: selenium
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51756551
possible better answer: http://stackoverflow.com/a/51764087
answer count: 2
has comment: http://stackoverflow.com/comment/90472155
has answer: http://stackoverflow.com/a/51764087
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I'm trying to push a button on a soccer bookmaker's web page using Selenium's Chromedriver. My problem is that nothing happens when I call Selenium's driver.find_elements_by_class_name('c-events__item c-events__item_col'). Fixed: I was trying to get the info from: a class names 'c-events__more c-events__more_bets js-showMoreBets'. using find_by_class_name() cannot handle spaces as it will think its compound classes, instead I used csselector and it works like a charm now. driver.find_elements_by_css_selector('.c-events__item.c-events__item_col')

http://stackoverflow.com/comment/90513333
comment on: http://stackoverflow.com/a/51777505
type: AnswerComment
has text: Thanks! Already +1 for you :) I think `ffill` is going to be faster than `transform('first')`
type: Comment
score: 1

http://stackoverflow.com/comment/90333945
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51685377
has text: If you get that error when plotting is because you did not assign column names when reading the excel. see Jon Nir answer to see how

http://stackoverflow.com/comment/90285411
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51660537
has text: The connection gets closed? Are you sure? Just because it won’t let you create another cursor doesn’t mean it’s closed. Is there a reason you can’t just reuse the first cursor? And, for that matter, is there a reason you can’t just create another connection object with the same string? Either one should work fine for what you say you want.

http://stackoverflow.com/q/51698662
favorite count: 0
linked to: http://stackoverflow.com/q/65778888
tagged with: pyenv
tagged with: python
accepted answer: http://stackoverflow.com/a/51727036
upvote count: 15
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51727036
type: Question
has comment: http://stackoverflow.com/comment/134652683
score: 15
has body: This just confuses me and I don't know what it means. I have 3.6.4 installed on my computer(MacOS) but it doesn't want to work. I can't think of any solution and don't know what to do.
answer count: 1
has title: pyenv-virtualenv: `3.6.4' is not installed in pyenv

http://stackoverflow.com/q/51784198
type: Question
tagged with: python-2.7
answer count: 1
has answer: http://stackoverflow.com/a/51785958
score: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90525614
tagged with: opencv
tagged with: anaconda
tagged with: opencv3.1
has title: import cv2 ImportError: DLL load failed: %1 is not a valid Win32 application
has comment: http://stackoverflow.com/comment/90528424
linked to: http://stackoverflow.com/q/19019720
has body: I have seen :ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL&#39;s are there And a couple of other solutions that suggest placing the \opencv\build\python\2.7\x86\cv2.pyd to my Anaconda virtual environment's \Lib\site-packages, I am working with Anaconda3 and in my environment I have Python version as below: Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 18:37:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Strangely, despite replacing the file at every possible location of Python in my Windows 10 system, I fail to run the script which uses import to opnecv.

http://stackoverflow.com/a/76325734
upvote count: 3
has comment: http://stackoverflow.com/comment/137216455
type: Answer
has comment: http://stackoverflow.com/comment/134598433
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/51691563
has body: This occurred for me when the length of the input tokens for an instance was greater than the max for the model, and when the input length was greater than the max_output_length prediction param.

http://stackoverflow.com/q/51715089
tagged with: try-except
tagged with: sql
answer count: 1
tagged with: python-3.x
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90391590
has answer: http://stackoverflow.com/a/51715854
has comment: http://stackoverflow.com/comment/90391582
has comment: http://stackoverflow.com/comment/90393105
has comment: http://stackoverflow.com/comment/90391626
has comment: http://stackoverflow.com/comment/90391702
type: Question
has body: I have a python script below that attempts to make a connection to a sql db. The database was having some connection issues and I want the script to try to reconnect to the db so I added try / except. However the script still does not automatically reconnect with the try / except statement. If anyone can help me with getting my script to reconnect to the db automatically I would greatly appreciate it! Code from __future__ import print_function try: import psycopg2 except ImportError: raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n') sys.exit(1) import re import sys import json import pprint import time outfilepath = "crtsh_output/crtsh_flat_file" DB_HOST = 'crt.sh' DB_NAME = 'certwatch' DB_USER = 'guest' DELAY = 8 #conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) #cursor = conn.cursor() def connect_to_db(): filepath = 'forager.txt' # conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) # cursor = conn.cursor() with open(filepath) as fp: unique_domains = '' try: conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) cursor = conn.cursor() for cnt, domain_name in enumerate(fp): print("Line {}: {}".format(cnt, domain_name)) print(domain_name) domain_name = domain_name.rstrip() cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x5$ FROM certificate c, certificate_identity ci WHERE c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) = lower(%s) AND x509_notAfter(c.certificate) &gt; statement_timestamp()''', (domain_name,)) unique_domains = cursor.fetchall() pprint.pprint(unique_domains) outfilepath = "crtsh1" + ".json" with open(outfilepath, 'a') as outfile: outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False)) tim…
score: 0
has title: Python does not automatically reconnect to db using try / except statement like I intended it to

http://stackoverflow.com/q/51756712
has answer: http://stackoverflow.com/a/51842210
tagged with: http://stackoverflow.com/tag/json
has body: I need help to parse a JSON with multiple objects to CSV, any help would be appreciated. I tried to write the code and was able to parse only out object of JSON but not all. I am interested in parsing the inner JSON object "categoryName" : "Databases" import requests import json import csv from requests.auth import HTTPBasicAuth r = requests.get('https://url') properties = r.json()['categories'] # open a file for writing csv_data = open('/home/sourcecode/csv_data.csv', 'w') # create the csv writer object csvwriter = csv.writer(csv_data) count = 0 for temp in properties: if count == 0: header = temp.keys() csvwriter.writerow(header) count += 1 csvwriter.writerow(temp.values()) csv_data.close() I am not posting the complete JSON as its very lengthy, just posting part if it to get better understanding below. { "categories" : [ { "categoryName" : "HDFSEncryptionZones", "metrics" : [ { "metricName" : "EncryptionZone Object Count", "value" : 0 }, { "metricName" : "Out of EncryptionZone Objects Count", "value" : 0 } ] }, { "categoryName" : "Databases", "metrics" : [ { "metricName" : "No. of Databases", "value" : 78 }, { "metricName" : "Top 5 Databases (by no of tables)", "value" : [ { "name" : "abc", "value" : 1234, "id" : 1187422 }, { "name" : "def", "value" : 578, "id" : 8194003 }, { "name" : "ghi", "value" : 241, "id" : 1214282 }, { "name" : "jkl", "value" : 214, "id" : 11677477 }, { "name" : "mno", "value" : 186, "id" : 6716158 }, { "name" : "pqr", "value" : 130, "id" : 59489134 }, { "name" : "stu", "value" : 102, "id" : 59489133 }, { "name" : "xyz", "value" : 96, "id" : 11630638 }, { "name" : "temp", "value" : 80, "id" : 100074536 }, { "name" : "test", "value" : 72, "id" : 59489132 } ] } ] }, { "categoryName" : "Storage", "metrics" : [ { "metricName" : "No. of S3 Objects.", "value" : 0 }, { "metricName" : "No. of HDFS Objects.", "value" : 3097309 } ] }, {...
has title: Parse JSOn multiple objects to CSV
type: Question
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90489315
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51842992
tagged with: python

http://stackoverflow.com/a/51758163
type: Answer
has comment: http://stackoverflow.com/comment/90476128
has comment: http://stackoverflow.com/comment/90476207
has comment: http://stackoverflow.com/comment/90488861
has body: These hash libraries deal with bytes objects, so you should encode your strings to bytes first (assuming the decoding end uses UTF-8): hmac_obj = hmac.new(secret, path.encode('utf-8') + b'\0' + data.encode('utf-8'), hashlib.sha512)
has comment: http://stackoverflow.com/comment/90475787
score: 0
answers question: http://stackoverflow.com/q/51757926

http://stackoverflow.com/q/51673951
score: 2
has answer: http://stackoverflow.com/a/51677095
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51677095
tagged with: ros2
tagged with: rti-dds
type: Question
has body: I am interfacing ROS2 with a native RTI DDS Connector for Python where I am publishing messages in RTI connector and subscribing in ROS2. I have the following message structure for the message named DetectedObjectList: int16 id // An array of objects of another message type DetectedObject[ ] objects This is interpreted as unbounded sequences in IDL. Another message named DetectedObject: int16 id string name int16 x int16 y Let's say the topic used for communication is "objects" and the message type is "DetectedObjectList". Since the subscriber in ROS2 is subscribing to id of type int16 and objects of type DetectedObject[], how can I publish an object from RTI connector? The usual flow in RTI Connector is: Get an instance of the output: output = connector.getOutput("MyPublisher::MyDataWriter") Post an instance: output.instance.setNumber("id", 5) output.write() How can I write an object of type DetectedObject instead of setNumber?
tagged with: ros
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has title: Publishing sequences/objects through RTI Conector to ROS2 applications
tagged with: data-distribution-service

http://stackoverflow.com/comment/90421169
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51728720
has text: you may be interested in this SO question: https://stackoverflow.com/questions/12468179/unicodedecodeerror-utf8-codec-cant-decode-byte-0x9c
score: 0

http://stackoverflow.com/a/51707352
score: 0
answers question: http://stackoverflow.com/q/51707067
type: Answer
upvote count: 1
downvote count: 1
has body: May be this help, s = 'HDCF\xc3\x82\xc2\xae FTAE\xc3\x82\xc2\xae Greater China' d = ''.join([i for i in s if ord(i) &lt; 127]) print(d) # OUTPUT as: HDCF FTAE Greater China

http://stackoverflow.com/comment/90499856
has text: are you watching any save signals or overriding the save method in your models? also it would be a good idea to provide a [mcve] :P
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51770544

http://stackoverflow.com/comment/90254066
has text: I will reopen this since the problem has changed a lot since original post
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51644865
score: 1

http://stackoverflow.com/a/51684803
score: 0
answers question: http://stackoverflow.com/q/51684664
has body: This should do just fine, unless you have a multi-gigabyte file that you don't want to load into the memory (most of the homeworks don't have such files =) def main(): search=input("Please enter an item :-") with open('coffee.txt') as infile : data = [i.strip() for i in infile.readlines()] for a,b in zip(data,data[1:] : if a == search : print("Description:-", a) print("QUANTITY will be :-", b) # the next line main()
type: Answer

http://stackoverflow.com/comment/90397931
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51718131
type: AnswerComment
has text: @blhsing good observation. I think I could misunderstand the problem.

http://stackoverflow.com/comment/90466092
type: AnswerComment
comment on: http://stackoverflow.com/a/51752952
score: 0
type: Comment
has text: Had to modify slightly to my need but your answer got be going. df['Object'] = "Gen '" + df['BusNumber'].astype('str') + "' '99'". Did not realize that double quote can be used to wrap single quote. So hard to find this answer in the forum.

http://stackoverflow.com/q/51733456
tagged with: pandas
score: 2
type: AnsweredQuestion
has body: I'm trying use an interval/date range with the get_group() method. ranges = pd.date_range(start='1/1/1900', periods=12, freq='120M') dates = df.groupby(pd.cut(df['dob'], ranges)) I know typically you can use dates.get_group('groupName'). However, since I'm using a date range, I'm unable to get it to work. Is it possible to use get_group() with a date range/interval? If so, what is the proper syntax? My goal is to be able to select a dataframe from a particular group. Maybe there's another way? Thanks! Sample Data: https://drive.google.com/file/d/1sA_EdrBAVuNCcUQRjj09wmaSCUgiAeif/view?usp=sharing
has comment: http://stackoverflow.com/comment/90430564
downvote count: 0
has comment: http://stackoverflow.com/comment/90428972
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51733593
type: Question
tagged with: python
has title: Pandas - groupby - get_group with interval/date range
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/51733593
has comment: http://stackoverflow.com/comment/90430700
has comment: http://stackoverflow.com/comment/90427705
tagged with: pandas-groupby

http://stackoverflow.com/q/51728242
tagged with: python
type: AnsweredQuestion
tagged with: schema
tagged with: parquet
has answer: http://stackoverflow.com/a/51916227
tagged with: pyarrow
upvote count: 3
type: Question
score: 3
has title: Assign pyarrow schema to pa.Table.from_pandas()
has body: I have a list column in my pandas dataframe along with int, string etc columns. I am able to convert string, date, int and timestamp columns. I want to know how to apply array() to the list column. fields = [ pa.field('id', pa.int64()), pa.field('secondaryid', pa.int64()), pa.field('date', pa.timestamp('ms')), pa.field('emails', pa.array()) ] my_schema = pa.schema(fields) table = pa.Table.from_pandas(sample_df, schema=my_schema, preserve_index=False) It asks for an object to be passed for the array. I want to know how to apply schema for array of type string to 'emails' column, bearing in mind that I was write the table out to parquet format, so an empty array will result in SegFault. What is the best approach?
accepted answer: http://stackoverflow.com/a/51916227
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51761422
tags question: http://stackoverflow.com/q/51648285
tags question: http://stackoverflow.com/q/51677378
type: Tag

http://stackoverflow.com/comment/90350252
type: Comment
comment on: http://stackoverflow.com/a/51693425
score: 0
type: AnswerComment
has text: I am grateful for help, but still this isn't working.

http://stackoverflow.com/q/51676027
tagged with: text
has title: Cleaning email chain for text analysis python
score: 6
has answer: http://stackoverflow.com/a/51676532
type: Question
has comment: http://stackoverflow.com/comment/90315216
has answer: http://stackoverflow.com/a/51687214
has body: I've got some text: text = """From: 'Mark Twain' &lt;mark.twain@gmail.com&gt; To: 'Edgar Allen Poe' &lt;eap@gmail.com&gt; Subject: RE:Hello! Ed, I just read the Tell Tale Heart. You\'ve got problems man. Sincerely, Marky Mark From: 'Edgar Allen Poe' &lt;eap@gmail.com&gt; To: 'Mark Twain' &lt;mark.twain@gmail.com&gt; Subject: RE: Hello! Mark, The world is crushing my soul, and so are you. Regards, Edgar""" Which looks like this: "From: 'Mark Twain' &lt;mark.twain@gmail.com&gt;\nTo: 'Edgar Allen Poe' &lt;eap@gmail.com&gt;\nSubject: RE:Hello!\n\nEd,\n\nI just read the Tell Tale Heart. You've got problems man.\n\nSincerely,\nMarky Mark\n\nFrom: 'Edgar Allen Poe' &lt;eap@gmail.com&gt;\nTo: 'Mark Twain' &lt;mark.twain@gmail.com&gt;\nSubject: RE: Hello!\n\nMark,\n\nThe world is crushing my soul, and so are you.\n\nRegards,\nEdgar" I'm trying to parse out the messages within them. Ultimately I'd like to have a list or dictionary where I have the From and To, and then the message body with which to do some analysis on. I've tried parsing it out by turning everything lower, and then string splitting. text = text.lower() text = text.translate(string.punctuation) text_list = text.split('+') text_list = [x for x in text_list if len(x) != 0] is there a better way to do this?
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51676176
has comment: http://stackoverflow.com/comment/90315150
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 6

http://stackoverflow.com/q/51693037
type: Question
upvote count: 0
has body: im having a problem with the following code. def play(): process = "......" h=subprocess.Popen(process) def stop(): h.terminate() it says that it cannot do this because h is not defined. is this because it isn't global and if so how do i make it global so that it can find it. i have tried using global to define the variable h at the start of the program but it doesn't work. Thanks
score: -1
has title: defining a subprocess inside a function in python?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: subprocess
downvote count: 1
has answer: http://stackoverflow.com/a/51693205

http://stackoverflow.com/q/51788718
has title: Python Format traceback
tagged with: python
has comment: http://stackoverflow.com/comment/90550941
upvote count: 3
has answer: http://stackoverflow.com/a/51788842
answer count: 2
has body: The goal is to print the traceback from a failed python script. I have referenced a ton of stack articles, but I can not find one tailored to my needs. The goal is to email the traceback when there is a failure. I can email everything fine, it is just formating said traceback. To get my traceback: trace = traceback.format_exc() send_email("Python Failure", trace, "bj@mydomain.com") Email is being run through an html emailing with smtpObj and MIMEMultipart: def send_email(subject, message, receivers): sender = "mydomain.com" msg = MIMEMultipart("alternative") msg["Subject"] = subject msg["From"] = sender msg["To"] = ", ".join(receivers) html = """ """ + subject + """ """ + message + """ """ part1 = MIMEText(message, "plain") part2 = MIMEText(html, "html") msg.attach(part1) msg.attach(part2) smtpObj = smtplib.SMTP("thats.not.cheddar") smtpObj.sendmail(sender, receivers, msg.as_string()) smtpObj.quit() When I receive the email, the traceback is there but it is all on one line. I was just wondering if anyone could help format a little bit better.
has answer: http://stackoverflow.com/a/69949863
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/a/73063729
score: 0
answers question: http://stackoverflow.com/q/51648808
type: Answer
has body: I had a responses.py file in my case and was getting same error. I renamed same file post which this issue resolved

http://stackoverflow.com/a/51771384
downvote count: 0
answers question: http://stackoverflow.com/q/51771128
has comment: http://stackoverflow.com/comment/90539122
score: 1
has comment: http://stackoverflow.com/comment/90538954
accepted answer of: http://stackoverflow.com/q/51771128
has comment: http://stackoverflow.com/comment/90540135
upvote count: 1
type: AcceptedAnswer
has body: Use: df1 = (pd.concat([pd.Series(r.id,np.arange(r.start, r.end + 1)) for r in df.itertuples()]) .reset_index()) df1.columns = ['data','id'] df1 = df1'id','data' print (df1) id data 0 1 2009 1 1 2010 2 1 2011 3 1 2012 4 1 2013 5 1 2014 6 2 2010 7 2 2011 8 2 2012
has comment: http://stackoverflow.com/comment/90539185
has comment: http://stackoverflow.com/comment/90769026
has comment: http://stackoverflow.com/comment/90604002
has comment: http://stackoverflow.com/comment/90539095
type: Answer
has comment: http://stackoverflow.com/comment/90532227
has comment: http://stackoverflow.com/comment/90538631

http://stackoverflow.com/q/51750232
has body: Say I have an image array: raster.shape =&gt; (3,100,100) I generate a mask of all the places where red is saturated: mask = np.where(raster[0,:,:] == 255) I want to modify the slice of those locations... Which I can do like this: raster[:,mask[0],mask[1]] = 0 Is there a more pythonic way... or is this the best bet?
type: Question
tagged with: numpy
score: 0
tagged with: array-broadcasting
answer count: 1
tagged with: raster
has title: Using 2d numpy mask np.where to address a 3d numpy array (pythonic??)
has answer: http://stackoverflow.com/a/51750307
accepted answer: http://stackoverflow.com/a/51750307
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90352795
score: 1
comment on: http://stackoverflow.com/q/51694767
has text: Jupyter notebook is a Python module and should also be removed when uninstalling Anaconda. However, it will not remove the notebook files (.ipynb) itself. These will have to be deleted manually.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90379417
score: 0
comment on: http://stackoverflow.com/q/51708838
type: Comment
type: QuestionComment
has text: Can you provide a **[mcve]**? Here, that means no images / links, just text. Some example output would be great too.

http://stackoverflow.com/q/51695678
has body: I have a simple queryset that returns booking objects with a start_time and end_time in utc and have TIME_ZONE set to UTC in settings which I need. I know how to convert a single date time object from UTC to local but I'm struggling to apply it to my queryset of booking objects, so I can show a booking list to my users in their dashboard in local time. bookings = Booking.objects.filter(contractor=contractor).order_by('-booking_start')
score: 0
has comment: http://stackoverflow.com/comment/90354001
has comment: http://stackoverflow.com/comment/90421288
type: UnansweredQuestion
tagged with: datetime
tagged with: django
tagged with: python
has title: Applying Timezone aware to a queryset of objects with datetimes in UTC
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90447768

phpmyadmin
tags question: http://stackoverflow.com/q/51652567
tags question: http://stackoverflow.com/q/51782946
type: Tag
tag name: phpmyadmin

http://stackoverflow.com/a/51753383
upvote count: 2
type: Answer
score: 2
has body: Instead of finding contours, I would suggest applying the Hough circle transform using the appropriate parameters. Finding contours poses a challenge. Once you invert the binary image the circles are in white. OpenCV finds contours both along the outside and the inside of the circle. Moreover since there are letters such as 'A' and 'B', contours will again be found along the outside of the letters and within the holes. You can find contours using the appropriate hierarchy criterion but it is still tedious. Here is what I tried by finding contours and using hierarchy: Code: #--- read the image, convert to gray and obtain inverse binary image --- img = cv2.imread('keypad.png', 1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) #--- find contours --- _, contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) #--- copy of original image --- img2 = img.copy() #--- select contours having a parent contour and append them to a list --- l = [] for h in hierarchy[0]: if h[0] &gt; -1 and h[2] &gt; -1: l.append(h[2]) #--- draw those contours --- for cnt in l: if cnt &gt; 0: cv2.drawContours(img2, [contours[cnt]], 0, (0,255,0), 2) cv2.imshow('img2', img2) For more info on contours and their hierarchical relationship please refer this UPDATE I have a rather crude way to ignore unwanted contours. Find the average area of all the contours in list l and draw those that are above the average: Code: img3 = img.copy() a = 0 for j, i in enumerate(l): a = a + cv2.contourArea(contours[i]) mean_area = int(a/len(l)) for cnt in l: if (cnt &gt; 0) &amp; (cv2.contourArea(contours[cnt]) &gt; mean_area): cv2.drawContours(img3, [contours[cnt]], 0, (0,255,0), 2) cv2.imshow('img3', img3)
downvote count: 0
answers question: http://stackoverflow.com/q/51749668

http://stackoverflow.com/q/51686722
has body: I'm trying to help my son (we're both really new to Python) with some Python homework, he's just started coding, so have I it seems. The question is as follows: Setup one dimensional array/list to store the following: 30 student surnames student marks for test 1 - out of 50 student marks for test 2 - out of 50 Total score for each student Input and score the student's marks for test 1 and 2. All marks must be validated on entry and invalid marks rejected. We are able to create a list for the student surnames but not sure how to go from there when creating two more lists which have marks for test 1 and 2 that need to be linked to a specific surname. They have not learnt about dictionaries yet, during my research I saw that this may be an option but can't be used to solve the problem. Any help would be much appreciated.
has comment: http://stackoverflow.com/comment/90335880
accepted answer: http://stackoverflow.com/a/51686901
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90335541
has comment: http://stackoverflow.com/comment/90335966
tagged with: python
type: AnsweredQuestion
has title: Using Python - setup list to store 30 student surnames as well as test marks for test1 and test2 which are both out of 50
has answer: http://stackoverflow.com/a/51686901
has comment: http://stackoverflow.com/comment/90335827
has comment: http://stackoverflow.com/comment/90335567
type: Question

sqlalchemy
tags question: http://stackoverflow.com/q/51743584
tags question: http://stackoverflow.com/q/51778728
tags question: http://stackoverflow.com/q/51786792
tags question: http://stackoverflow.com/q/51769299
tags question: http://stackoverflow.com/q/51783313
tags question: http://stackoverflow.com/q/51771062
tags question: http://stackoverflow.com/q/51767830
tags question: http://stackoverflow.com/q/51662547
tags question: http://stackoverflow.com/q/51659080
tags question: http://stackoverflow.com/q/51756650
tags question: http://stackoverflow.com/q/51793704
tags question: http://stackoverflow.com/q/51675879
tags question: http://stackoverflow.com/q/51782913
tags question: http://stackoverflow.com/q/51737548
tags question: http://stackoverflow.com/q/51787768
tags question: http://stackoverflow.com/q/51684539
tags question: http://stackoverflow.com/q/51767855
tags question: http://stackoverflow.com/q/51790471
tags question: http://stackoverflow.com/q/51745657
tags question: http://stackoverflow.com/q/51697947
tags question: http://stackoverflow.com/q/51649224
tags question: http://stackoverflow.com/q/51656264
tags question: http://stackoverflow.com/q/51793885
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/51709917
tags question: http://stackoverflow.com/q/51751877
tags question: http://stackoverflow.com/q/51665345
tags question: http://stackoverflow.com/q/51670299
tags question: http://stackoverflow.com/q/51659259
tags question: http://stackoverflow.com/q/51730994
tags question: http://stackoverflow.com/q/51762534
tags question: http://stackoverflow.com/q/51748865
tags question: http://stackoverflow.com/q/51661061
tags question: http://stackoverflow.com/q/51791679
tags question: http://stackoverflow.com/q/51716348
tags question: http://stackoverflow.com/q/51678132
tags question: http://stackoverflow.com/q/51788119
tags question: http://stackoverflow.com/q/51666385
tags question: http://stackoverflow.com/q/51663958
tags question: http://stackoverflow.com/q/51713002
tags question: http://stackoverflow.com/q/51692771
tags question: http://stackoverflow.com/q/51785928
tags question: http://stackoverflow.com/q/51648849
tags question: http://stackoverflow.com/q/51789475
tags question: http://stackoverflow.com/q/51714919
type: Tag
tags question: http://stackoverflow.com/q/51762785

http://stackoverflow.com/comment/90262439
type: Comment
comment on: http://stackoverflow.com/q/51646047
has text: Yeah I get it.. @MarkSetchell is it possible to just paste the pics of dog,monkey,donkey in a new photo with white background ?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90336685
has text: `first3['STNAME'].tolist()`? or with loc you need to add `:` for all rows: `first3.loc[:,'STNAME'].tolist()`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51687318
type: QuestionComment

http://stackoverflow.com/comment/90360167
comment on: http://stackoverflow.com/a/51699290
has text: @chunxu Glad to be of help. Can you mark this answer as accepted if you find it to be correct?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90452796
has text: but, while reading from another text file, it is not able to recognize the letter pattern.
comment on: http://stackoverflow.com/q/51746426
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51743407
has body: I am trying to reduce the number of data points for a 3D curve, currently I have 20000 points and I would like to reduce this to around 2000 without losing much information. I am doing this on python. As a simple example, think of a spiral on the surface of a cylinder. Are there any built-in functions that will do this? I've tried using the Ramer–Douglas–Peucker algorithm to simplify the line, but due to the nature of the curve, for every data point ignored the final plot is undershooting. See picture of a 2D example, orange is what using rdp produces, green is what I want. I would like the output of the program to be an array of ~2000 coordinates that still represent the shape of the 3D curve but they don't necessarily have to be original coordinates, I want some points to overshoot and others to undershoot. Thank you for your help UPDATE: In the end I chose to do something quite involved but gave me exactly what I wanted. I started using the rdp algorithm to reduce the number of points. With this new information I then fit a straight line of best fit to the spread of the original points between the new reduced points: i.e. if the algorithm 'ignored' 13 points, I fit the line from point 0 to point 14, and did the same for the next segment where the algorithm had skipped for example 7 points, so I fit from 14 to 22 etc. Having those lines of best fit, I found the points were the lines intersected or if the lines did not intersect, the closest point on each of the lines to the other line. Due to the nature of my problem, I did not need my data to be continuous, so 2000 "discontinuous" segments were not a problem. Thank you very much for your help!
has answer: http://stackoverflow.com/a/58858342
upvote count: 1
has comment: http://stackoverflow.com/comment/90498477
type: Question
linked to: http://stackoverflow.com/q/21836067
tagged with: spline
has comment: http://stackoverflow.com/comment/90495084
accepted answer: http://stackoverflow.com/a/58858342
answer count: 1
downvote count: 0
has title: 3D curve fitting using python
favorite count: 0
has comment: http://stackoverflow.com/comment/90447719
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/90381075
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51709938
has text: printing is not returning. You mean you've assigned the result of your function and it's `None` ?
score: 0

tcp
type: Tag
tags question: http://stackoverflow.com/q/51798304
tag name: tcp

http://stackoverflow.com/comment/90252375
type: QuestionComment
has text: Try it with a `collections.Counter`.
score: 0
comment on: http://stackoverflow.com/q/51644115
type: Comment

http://stackoverflow.com/a/51740552
type: Answer
score: 0
has body: as @John Anderson said you can use the os module's os.path. if os.path.exists('path/to/your/csvfile/') is True: print("Do something")
accepted answer of: http://stackoverflow.com/q/51740310
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51740310

http://stackoverflow.com/comment/90319175
type: Comment
type: QuestionComment
has text: ... and then take 10*2 digits to get the 10 bytes.
comment on: http://stackoverflow.com/q/51677943
score: 0

http://stackoverflow.com/comment/90368308
has text: If you really need to have both your old and your new model it indeed seems a good way to go to have them both in a same graph. Maybe using a kind of renaming/namescoping to differentiate them. You'll probably need a kind of hacky restore at this point though. TF Sub-graph method is made to extract a sub part of a graph, it's not made in scope way, I don't think it'd be of help here, but who knows....
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51654678
type: Comment

http://stackoverflow.com/comment/90249413
has text: Then maybe do something like `pad_x = (x_max - x_len) // 2`, then call `np.pad` with `(pad_x, x_max - x_len - pad_x)` and similarly for `pad_y`. Note the `//`. This would pad more after for odd `x_max - x_len`.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51641570

http://stackoverflow.com/comment/90347194
type: Comment
comment on: http://stackoverflow.com/q/51692823
type: QuestionComment
has text: I am a bit confused. Is your x and y corresponding to coordinates on the x, y axis?
score: 0

http://stackoverflow.com/q/51737078
tagged with: python
type: AnsweredQuestion
tagged with: list
has body: I have a function that makes a call to a REST API. One of the parameter is a comma-separated list of names. To generate it, I do this: ','.join(names) However, I also want to allow the user to provide a single name. The problem is that if names = ERII, for instance, it results in ['E', 'R', 'I', 'I'], but I need it to be ['ERII'] instead. Now, I could force the user to enter a list with only one value (names=['ERRI'] or names=('ERII',). I would prefer to allow the user to provide a single String. Is there a clever way to do that without a if else statement checking if the provided value is an Iterable? Also, I am uncertain as what would be the best practice here, force to provide a list, or allow a single string?
has answer: http://stackoverflow.com/a/51746502
has comment: http://stackoverflow.com/comment/90434992
score: 9
type: Question
possible better answer: http://stackoverflow.com/a/51746502
upvote count: 9
downvote count: 0
has answer: http://stackoverflow.com/a/51737249
has answer: http://stackoverflow.com/a/51737187
has comment: http://stackoverflow.com/comment/90434955
has title: Python, allowing passing single string and list of string to a function
answer count: 3
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/51737249

http://stackoverflow.com/a/51671087
has comment: http://stackoverflow.com/comment/90304905
has comment: http://stackoverflow.com/comment/90307455
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51670988
has body: You could use the atexit library. From the documentation: The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. This can be implemented like so: #Rest of program... def before_termination(): #Do something... import atexit atexit.register(before_termination) However this is only called during normal program termination, not if keyboard interrupt occurs.
score: 1
accepted answer of: http://stackoverflow.com/q/51670988
upvote count: 1
has comment: http://stackoverflow.com/comment/90305204
has comment: http://stackoverflow.com/comment/90307975

http://stackoverflow.com/q/51657347
tagged with: facebook-graph-api
tagged with: facebook-sdk-3.0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51657668
has title: How to retrieve all users data associated with my Facebook Application via Python code?
type: Question
linked to: http://stackoverflow.com/q/4776881
score: 0
accepted answer: http://stackoverflow.com/a/51657668
answer count: 1
has body: I created an application on Facebook for my research project. I, therefore, submitted some fields that I wanted to collect from the users that are going to associate with my app (e.g., user_likes, user_posts). When they associate with my app, how can I retrieve their information using the Facebook-SDK for Python? Is there a way to get a list of associated users of my Facebook App? I have seen that I can get from the Graph API Explorer all the Test Users of my app using this command: (&lt;&lt;APP-ID&gt;&gt;?fields=accounts) If I turn my app available publicly, this field "accounts" will return all the real users associated with?
tagged with: python

http://stackoverflow.com/q/51719261
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I have a dataframe: df = SomeText 0 foo foo foo bar 1 bar foo buzz 2 bar bar bar 3 buzz buzz buzz buzzer And a JSON: json_dict = { "text": [ { "notes": [], "code": 1, "word": foo, }, { "notes": [], "code": 2, "word": bar, }, { "notes": [buzzer], "code": 3, "word": buzz, } ] } I'll like to parse over the text in the SomeText column and append a new column to df based on data stored in the JSON. If the word appears in the string, append the code. If the word also matches the notes, append the same code. df = SomeText Code 0 foo foo foo bar 1, 1, 1, 2 1 bar foo buzz 2, 1, 3 2 bar bar bar 2, 2, 2 3 buzz buzz buzz buzzer 3, 3, 3, 3 4 not in json - Words not contained within the JSON don't matter. I've got some experience doing this between dataframes but not using JSON files as reference. Any help would be greatly appreciated.
upvote count: 2
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51719338
tagged with: python
has title: Create a new Pandas column based on string matches in a JSON
has answer: http://stackoverflow.com/a/51719338
type: AnsweredQuestion

http://stackoverflow.com/comment/90348219
score: 0
type: AnswerComment
type: Comment
has text: @moonfairy see `django.views.generic.edit.UpdateView`
comment on: http://stackoverflow.com/a/51683838

http://stackoverflow.com/comment/90269056
score: 0
has text: @Goyo I corrected my mistakes and tried to be as clear as possible, might you remove your downvote ? Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51650641

http://stackoverflow.com/a/51790547
downvote count: 0
answers question: http://stackoverflow.com/q/51790518
type: Answer
score: 4
upvote count: 4
has body: The insert() method only inserts the element to the list. It doesn't return any value.

http://stackoverflow.com/comment/90278332
type: QuestionComment
type: Comment
score: 0
has text: Could you try to manually execute `ls -l` in the same directory using the same user?
comment on: http://stackoverflow.com/q/51657307

http://stackoverflow.com/q/51689424
has body: I have the following dataframe id device 814 desktop 814 mobile 236 mobile 498 desktop 348 mobile 287 mobile 287 desktop I want to query the id's where device is both mobile &amp; desktop df.loc[(df['device'] == 'mobile') &amp; (df['device'] == 'desktop'), ['id','device']] The output should be id device 814 desktop 814 mobile 287 desktop 287 mobile Instead I just get an empty dataframe id device
has answer: http://stackoverflow.com/a/51689463
tagged with: pandas
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51689463
score: 2
has title: Pandas not selecting columns based on condition
type: Question
possible better answer: http://stackoverflow.com/a/51689486
answer count: 2
has answer: http://stackoverflow.com/a/51689486
downvote count: 0

http://stackoverflow.com/comment/90298639
comment on: http://stackoverflow.com/q/51667823
score: 0
type: Comment
type: QuestionComment
has text: `def __init__(self, *args, order, **kwargs)`that order worked for me now. Is this the way you meant?

http://stackoverflow.com/comment/90432551
type: QuestionComment
has text: This question has nothing to do with Putty. Putty is simply a tool for logging into a remote server.
score: 1
comment on: http://stackoverflow.com/q/51735899
type: Comment

http://stackoverflow.com/a/51783135
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90525223
has body: As the docs Using Descriptors and Hybrids says you should be using hybrid_property to be able to use them in your queries. Take a look at example in docs: class EmailAddress(Base): __tablename__ = 'email_address' id = Column(Integer, primary_key=True) # name the attribute with an underscore, # different from the column name _email = Column("email", String) # then create an ".email" attribute # to get/set "._email" @property def email(self): return self._email While our EmailAddress object will shuttle the value through the email descriptor and into the _email mapped attribute, the class level EmailAddress.email attribute does not have the usual expression semantics usable with Query. To provide these, we instead use the hybrid extension
upvote count: 2
answers question: http://stackoverflow.com/q/51782913
has comment: http://stackoverflow.com/comment/90523689
type: Answer

http://stackoverflow.com/a/51686542
answers question: http://stackoverflow.com/q/51685244
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: Here's how I would do it. First, the motor task should be a loop so it retrieves more than one item from the Queue when it runs. To tell it when to stop, a special value (marker) can be put into the queue to indicate to the task to do so (break out of the loop and quit). After doing that, you can just wait until it finishes by calling its join() method. This is what I mean: from queue import Queue from threading import Thread import time def sensor(numbers, q): for n in numbers: q.put(n*n) print(n*n) time.sleep(1) # Add some delay here q.put(None) # End marker. def motor(): while True: a = q.get() if a is None: # End marker? break # Quit. if a &lt; 10: print("good") time.sleep(2) # Add some delay here else: print ("bad") time.sleep(2) # Add some delay here if __name__=="__main__": numbers = [1,2,3,4,5,6,7,8] q = Queue() p = Thread(target=sensor, args=(numbers, q)) r = Thread(target=motor) p.start() r.start() r.join() # Wait for consumer thread to finish. print('done')

http://stackoverflow.com/comment/90395260
comment on: http://stackoverflow.com/q/51703670
score: 0
type: QuestionComment
has text: I'm confused. Where is `hand_sizes` in your code? What do you mean by "duplicate card combos" -- `itertools.combinations` does not give you any duplicates. if `combinations` is the list of all cards in your deck, then `itertools.combinations(combinations, 13)` is the list of all 13 card hands available from that deck.
type: Comment

http://stackoverflow.com/comment/90464944
score: 0
type: QuestionComment
has text: .items() is not correct, because i am getting this error: Could not parse the remainder: '()' from 'devDict.items()'
comment on: http://stackoverflow.com/q/51752231
type: Comment

http://stackoverflow.com/comment/90471014
type: Comment
has text: You will have to play with this a bit to make each attr accessible via `g["x"]["y"]["z"]` I hit recursion depth if I try to access an element that isn't at the end. If I have time after work I can come back and try to fix it. Glad to help! really having fun learning the language by trying to help with overflow questions
score: 0
comment on: http://stackoverflow.com/a/51755547
type: AnswerComment

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/51773496
type: Tag
tags question: http://stackoverflow.com/q/51657959

http://stackoverflow.com/a/51784146
answers question: http://stackoverflow.com/q/51784005
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90526922
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/90534238
has comment: http://stackoverflow.com/comment/90537518
downvote count: 1
has comment: http://stackoverflow.com/comment/90537001
has body: You are confusing operator precedence and evaluation order. The expression r = x or y and z is not evaluated as tmp = y and z; r = x or tmp, but just as r = x or (y and z). This expression is evaluated from left to right, and if the result of the or is already decided, then (y and z) will not be evaluated at all. Note that it would be different if or and and were functions; in this case, the parameters of the functions would be evaluated before the function itself is called. Hence, operator.or_(yay(), operator.and_(nay(), nope())) prints yay, nay and nope i.e. it prints all three, but still in order from left to right. You can generalize this to other operators, too. The following two expressions will yield different results due to the different operator precedence (both implicit and explicit by using (...)), but the functions are called from left to right both times. &gt;&gt;&gt; def f(x): print(x); return x &gt;&gt;&gt; f(1) + f(2) * f(3) / f(4) ** f(5) - f(6) # 1 2 3 4 5 6 -&gt; -4.99 &gt;&gt;&gt; (f(1) + f(2)) * (((f(3) / f(4)) ** f(5)) - f(6)) # 1 2 3 4 5 6 -&gt; -17.29 As pointed out in comments, while the terms in between operations are evaluated from left to right, the actual operations are evaluated according to their precedence. class F: def __init__(self,x): self.x = x def __add__(self, other): print(f"add({self},{other})"); return F(self.x+other.x) def __mul__(self, other): print(f"mul({self},{other})"); return F(self.x*other.x) def __pow__(self, other): print(f"pow({self},{other})"); return F(self.x**other.x) def __repr__(self): return str(self.x) def f(x): print(x); return F(x) This way, the expression f(1) + f(2) ** f(3) * f(4) is evaluated as 1, 2, 3, pow(2,3), 4, mul(8,4), add(1,32), i.e. terms are evaluated left-to-right (and pushed on a stack) and expressions are evaluated as soon as their parameters are evaluated.
accepted answer of: http://stackoverflow.com/q/51784005
score: 10

http://stackoverflow.com/a/51744989
type: Answer
score: 7
has body: pd.DataFrame objects don't have a map method. You can instead construct an index from two columns and use pd.Index.map with a function: df_a['deleted'] = df_a.set_index(['number', 'code']).index.map(d.get) df_a['deleted'] = df_a['deleted'].fillna('none') Compatibility note For Pandas versions &gt;0.25, you can use pd.Index.map directly with a dictionary, i.e. use d instead of d.get. For prior versions, we use d.get instead of d because, unlike pd.Series.map, pd.Index.map does not accept a dictionary directly. But it can accept a function such as dict.get. Note also we split apart the fillna operation as pd.Index.map returns an array rather than a series.
upvote count: 7
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51744786
accepted answer of: http://stackoverflow.com/q/51744786

keyboardinterrupt
tag name: keyboardinterrupt
type: Tag
tags question: http://stackoverflow.com/q/51721230

http://stackoverflow.com/comment/90254824
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51645403
has text: Well, how could you execute your app? You haven't even imported `User` in `APP.py`.
type: Comment

http://stackoverflow.com/q/51676700
type: Question
has comment: http://stackoverflow.com/comment/90328051
has answer: http://stackoverflow.com/a/51867194
has title: please what is node.js eqivalent of this python code
answer count: 1
favorite count: 0
type: UnansweredQuestion
has body: What is node.js code equivalent of this python code? python -c 'import pty; pty.spawn("/bin/sh")' I am trying to get a linux shell and I have tried the code below: var exec = require('child_process').exec; exec('/bin/bash', function (error, stdOut, stdErr) {console.log(stdOut);});
tagged with: python
has comment: http://stackoverflow.com/comment/90316642
tagged with: node.js
downvote count: 6
upvote count: 2
score: -4
has comment: http://stackoverflow.com/comment/90318140

http://stackoverflow.com/q/51675442
has answer: http://stackoverflow.com/a/51675488
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/36384760
has title: How to split numpy array into single values?
duplicate of: http://stackoverflow.com/q/36384760
has answer: http://stackoverflow.com/a/51675514
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/95451031
has body: So I currently have a numpy array like [[0, 1, 2, 3, 4]] but I want it to be [[0],[1],[2],[3],[4]] Is there a list comprehension method to do so?
has answer: http://stackoverflow.com/a/51675568
answer count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90531017
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51786751
type: AnswerComment
has text: Thank you! I have already started to make a similar benchmark script when noticed your answer. Maybe you should try it on a set of input values?

http://stackoverflow.com/comment/90460028
type: AnswerComment
type: Comment
has text: Hello! I did that but I got- TypeError: must be str, not list. I have updated my code a little more so you can see exactly what I have before too
comment on: http://stackoverflow.com/a/51749972
score: 1

http://stackoverflow.com/comment/122139825
score: 5
type: AnswerComment
type: Comment
has text: this could be a comment.
comment on: http://stackoverflow.com/a/69105500

http://stackoverflow.com/comment/90318395
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51677550
score: 2
has text: Please, post what have you tried

linux
tags question: http://stackoverflow.com/q/51780920
tags question: http://stackoverflow.com/q/51755148
tags question: http://stackoverflow.com/q/51640572
tags question: http://stackoverflow.com/q/51714499
tags question: http://stackoverflow.com/q/51753539
tags question: http://stackoverflow.com/q/51658184
tags question: http://stackoverflow.com/q/51657307
tags question: http://stackoverflow.com/q/51686440
tags question: http://stackoverflow.com/q/51738460
tags question: http://stackoverflow.com/q/51798701
tags question: http://stackoverflow.com/q/51798251
tags question: http://stackoverflow.com/q/51762454
type: Tag
tags question: http://stackoverflow.com/q/51640672
tags question: http://stackoverflow.com/q/51694562
tags question: http://stackoverflow.com/q/51738059
tags question: http://stackoverflow.com/q/51675618
tags question: http://stackoverflow.com/q/51713414
tags question: http://stackoverflow.com/q/51651083
tag name: linux
tags question: http://stackoverflow.com/q/51685660
tags question: http://stackoverflow.com/q/51752253
tags question: http://stackoverflow.com/q/51784475
tags question: http://stackoverflow.com/q/51749906
tags question: http://stackoverflow.com/q/51758754
tags question: http://stackoverflow.com/q/51720406
tags question: http://stackoverflow.com/q/51796093
tags question: http://stackoverflow.com/q/51662213
tags question: http://stackoverflow.com/q/51798304
tags question: http://stackoverflow.com/q/51767909

http://stackoverflow.com/comment/90342407
score: 0
type: QuestionComment
type: Comment
has text: Sure here's my full code
comment on: http://stackoverflow.com/q/51685860

http://stackoverflow.com/comment/90371604
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51704699
has text: @NationzGG Also, if my solution works for you, please can you accept it (click the tick) and upvote it? (so that people in the future know which solution works for you)

http://stackoverflow.com/q/51768224
tagged with: python
has comment: http://stackoverflow.com/comment/90497048
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has body: I borrowed this example from a link! I would like to understand why dataframe a - after having had column 'category' seemingly added to it, cannot be referenced in a subsequent operation. Is dataframe a somehow immutable? Is there another way to act on dataframe a so that subsequent operations can access column 'category'? Thanks for your help; I am still on the learning curve. Now, it is possible to add all the columns at once to avoid the error, but that isn't what I want to do here. #sample data a= sqlContext.createDataFrame([("A", 20), ("B", 30), ("D", 80),("E",0)],["Letter", "distances"]) label_list = ["Great", "Good", "OK", "Please Move", "Dead"] #Passing List as Default value to a variable def cate( feature_list,label=label_list): if feature_list == 0: return label[4] else: return 'I am not sure!' def cate2( feature_list,label=label_list): if feature_list == 0: return label[4] elif feature_list.category=='I am not sure!': return 'Why not?' udfcate = udf(cate, StringType()) udfcate2 = udf(cate2, StringType()) a.withColumn("category", udfcate("distances")) a.show() a.withColumn("category2", udfcate2("category")).show() a.show() I get the error: C:\Users\gowreden\AppData\Local\Continuum\anaconda3\python.exe C:/Users/gowreden/PycharmProjects/DRC/src/tester.py 2018-08-09 09:06:42 WARN NativeCodeLoader:62 - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). +------+---------+--------------+ |Letter|distances| category| +------+---------+--------------+ | A| 20|I am not sure!| | B| 30|I am not sure!| | D| 80|I am not sure!| | E| 0| Dead| +------+---------+--------------+ Traceback (most recent call last): File "C:\Programs\spark-2.3.1-bin-hadoop2.7\python\pyspark\sql\utils.py", line 63, in deco return f(*a, **kw) File "C:\Programs\spark-2.3.1-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\p…
tagged with: pyspark
linked to: http://stackoverflow.com/q/47906697
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51770735
has title: PySpark - Pass list as parameter to UDF + iterative dataframe column addition

http://stackoverflow.com/a/51701957
type: AcceptedAnswer
downvote count: 0
has body: numpy.ufunc when given an object dtype array, iterate through the array, and try to apply a cooresponding method to each element. For example np.abs tries to apply the __abs__ method. Lets add such a method to your class: In [31]: class ExampleObject(): ...: ...: def __init__(self, r): ...: self.r = r ...: def __abs__(self): ...: return self.r ...: Now create your arrays: In [32]: indexArray = 5 #arbitrary choice of array index ...: sizeArray = 10 ...: ...: exampleList = [] ...: for i in range(sizeArray): ...: r = np.random.rand() ...: exampleList.append( ExampleObject( r ) ) ...: ...: index_list = np.arange(0,sizeArray,1) ...: index_list = np.delete(index_list,indexArray) ...: ...: coords = np.array([h.r for h in exampleList]) and make an object dtype array from the list: In [33]: exampleArr = np.array(exampleList) In [34]: exampleArr Out[34]: array([&lt;__main__.ExampleObject object at 0x7fbb541eb9b0&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eba90&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb3c8&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb978&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb208&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb128&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb198&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb358&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb4e0&gt;, &lt;__main__.ExampleObject object at 0x7fbb541eb048&gt;], dtype=object) Now we can get an array of the r values by calling the np.abs function: In [35]: np.abs(exampleArr) Out[35]: array([0.28411876298913485, 0.5807617042932764, 0.30566195995294954, 0.39564156171554554, 0.28951905026871105, 0.5500945908978057, 0.40908712567465855, 0.6469497088949425, 0.7480045751535003, 0.710425181488751], dtype=object) It also works with indexed elements of the array: In [36]: np.abs(exampleArr[:3]) Out[36]: array([0.28411876298913485, 0.5807617042932764, 0.30566195995294954], dtype=object) This is convenient, but I can't promise s…
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90391092
score: 2
answers question: http://stackoverflow.com/q/51701334
accepted answer of: http://stackoverflow.com/q/51701334
has comment: http://stackoverflow.com/comment/90381359

http://stackoverflow.com/comment/90542958
comment on: http://stackoverflow.com/a/51792693
type: AnswerComment
has text: Thank you for you answer. It might have been a bad example from my side. But in case of to strings having same length and also ending on the same letter this method seems to give me wrong outputs once in a while (i tested earlier). Say the two last words in the second list was `'car'` and `'cer'` then `car` should come before cer as e is before a. Hope it made sense..
type: Comment
score: 0

http://stackoverflow.com/a/51770735
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51768224
score: 1
has body: I think there are two issues with your code: First of all, as @pault said, withColumn is not in-place, and you need to modify your code accordingly. Second, your cate2 function is not correct. In the sense that you apply it to column category and at the same time you request for comparing feature_list.category with something. You may want to get rid of the first function and do the following: import pyspark.sql.functions as F a=a.withColumn('category', F.when(a.distances==0, label_list[4]).otherwise('I am not sure!')) a.show() Output: +------+---------+--------------+ |Letter|distances| category| +------+---------+--------------+ | A| 20|I am not sure!| | B| 30|I am not sure!| | D| 80|I am not sure!| | E| 0| Dead| +------+---------+--------------+ And do something like this for the second function: a=a.withColumn('category2', F.when(a.distances==0, label_list[4]).otherwise(F.when(a.category=='I am not sure!', 'Why not?'))) a.show() Output: +------+---------+--------------+---------+ |Letter|distances| category|category2| +------+---------+--------------+---------+ | A| 20|I am not sure!| Why not?| | B| 30|I am not sure!| Why not?| | D| 80|I am not sure!| Why not?| | E| 0| Dead| Dead| +------+---------+--------------+---------+
upvote count: 1

beautifulsoup
tags question: http://stackoverflow.com/q/51697746
tags question: http://stackoverflow.com/q/51643332
tags question: http://stackoverflow.com/q/51756089
tags question: http://stackoverflow.com/q/51688127
tags question: http://stackoverflow.com/q/51788241
tags question: http://stackoverflow.com/q/51724962
tags question: http://stackoverflow.com/q/51684985
tags question: http://stackoverflow.com/q/51775971
tags question: http://stackoverflow.com/q/51712984
tags question: http://stackoverflow.com/q/51643947
tags question: http://stackoverflow.com/q/51792571
tags question: http://stackoverflow.com/q/51769008
tags question: http://stackoverflow.com/q/51746996
tags question: http://stackoverflow.com/q/51719941
tags question: http://stackoverflow.com/q/51788716
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51679679
tags question: http://stackoverflow.com/q/51685551
tags question: http://stackoverflow.com/q/51664732
tags question: http://stackoverflow.com/q/51786219
tags question: http://stackoverflow.com/q/51714711
tags question: http://stackoverflow.com/q/51754581
tags question: http://stackoverflow.com/q/51676994
tags question: http://stackoverflow.com/q/51757533
tags question: http://stackoverflow.com/q/51757608
tags question: http://stackoverflow.com/q/51777724
tags question: http://stackoverflow.com/q/51702498
tags question: http://stackoverflow.com/q/51675716
tags question: http://stackoverflow.com/q/51704927
tags question: http://stackoverflow.com/q/51687872
tags question: http://stackoverflow.com/q/51667938
tags question: http://stackoverflow.com/q/51782044
tags question: http://stackoverflow.com/q/51777725
tags question: http://stackoverflow.com/q/51775616
tags question: http://stackoverflow.com/q/51704784
tags question: http://stackoverflow.com/q/51755889
tags question: http://stackoverflow.com/q/51690627
tags question: http://stackoverflow.com/q/51657210
tags question: http://stackoverflow.com/q/51694687
tags question: http://stackoverflow.com/q/51745660
tags question: http://stackoverflow.com/q/51796488
tags question: http://stackoverflow.com/q/51657000
tags question: http://stackoverflow.com/q/51776555
tags question: http://stackoverflow.com/q/51688163
tags question: http://stackoverflow.com/q/51775402
tags question: http://stackoverflow.com/q/51688712
tags question: http://stackoverflow.com/q/51796368
tags question: http://stackoverflow.com/q/51740404
type: Tag
tags question: http://stackoverflow.com/q/51678077
tags question: http://stackoverflow.com/q/51699574
tags question: http://stackoverflow.com/q/51757421
tags question: http://stackoverflow.com/q/51653786
tags question: http://stackoverflow.com/q/51659976
tags question: http://stackoverflow.com/q/51664124
tags question: http://stackoverflow.com/q/51789216
tags question: http://stackoverflow.com/q/51688989
tags question: http://stackoverflow.com/q/51764239
tags question: http://stackoverflow.com/q/51692278
tags question: http://stackoverflow.com/q/51704628
tags question: http://stackoverflow.com/q/51689111
tags question: http://stackoverflow.com/q/51644167
tags question: http://stackoverflow.com/q/51756775
tags question: http://stackoverflow.com/q/51731389
tags question: http://stackoverflow.com/q/51785640
tags question: http://stackoverflow.com/q/51759005
tags question: http://stackoverflow.com/q/51674672
tags question: http://stackoverflow.com/q/51697465
tags question: http://stackoverflow.com/q/51701548
tags question: http://stackoverflow.com/q/51787660
tags question: http://stackoverflow.com/q/51692407
tags question: http://stackoverflow.com/q/51705712
tags question: http://stackoverflow.com/q/51660176
tags question: http://stackoverflow.com/q/51744668
tags question: http://stackoverflow.com/q/51732510
tags question: http://stackoverflow.com/q/51656193
tags question: http://stackoverflow.com/q/51748942
tags question: http://stackoverflow.com/q/51740650
tags question: http://stackoverflow.com/q/51681873
tags question: http://stackoverflow.com/q/51675330

http://stackoverflow.com/q/51764219
score: 1
upvote count: 1
has body: i have a csv while has data structure like this image: Now i want to remove duplicates from area column but condition is that it should be key based. Meaning 1 key cannot have duplicates Area. Area can be duplicate in other keys but not in same key. I am trying to create it but not getting the logic behind: These are my codes: import csv OUTPUT_FILE = 'Desired_format.csv' filename = "optionsbook.csv" sublist = [] with open("./"+ filename, "r") as file,open(OUTPUT_FILE, 'w') as f_out: reader = csv.DictReader(file) for line in reader: line["key"] = line["bhk"],line["Area"],line["Property_Type"] if line["Area"] in line: continue else: sublist.append(line["key"])
type: Question
type: AnsweredQuestion
has title: How to remove duplicates basis keys of a csv file
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51764522
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51764522

http://stackoverflow.com/comment/90461063
comment on: http://stackoverflow.com/q/51749888
has text: Can you please give an example of what you expect and what is the current output?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51649833
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90262993
has comment: http://stackoverflow.com/comment/90291711
tagged with: python
tagged with: object-detection
answer count: 0
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90264006
has body: I tried to run python Faster-RCNN based on tensorflow, which clone from https://github.com/smallcorgi/Faster-RCNN_TF I built a dataset by myself and re-write data API to make dataset fit. The images in the dataset are all composed of meaningless background and text. I got a .txt file to record the text location in a image, such as ID_card/train/3.jpg 1 209 39 261 89 And my goal is to find text from a new image. But when I run python ./tools/train_net.py --device cpu --device_id 1 --solver VGG_CNN_M_1024 --weight ./data/pretrain_model/VGG_imagenet.npy --imdb ID_card_train --network IDcard_train I got this KeyError: 'max_overlaps' and here is the terminal record and error traceback. Traceback (most recent call last): File "./tools/train_net.py", line 97, in &lt;module&gt; max_iters=args.max_iters) File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 259, in train_net roidb = filter_roidb(roidb) File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 250, in filter_roidb filtered_roidb = [entry for entry in roidb if is_valid(entry)] File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 239, in is_valid overlaps = entry['max_overlaps'] KeyError: 'max_overlaps' I did googled and tried to delete /cache folder, and it didn't work. Next time i run the code the folder and .pkl file would be created again and then the same error came out. some other answer said delete another folder lib/datasets/VOCdevkit-matlab-wrapper however smallcorgi/Faster-RCNN_TF do not contain this folder, so i have no way to go. I wonder what happened to my code and what would cause this error. I have no idea about what to do. Anyone can give me some help, solution or whatever a piece of idea? edit: I run the demo on @VegardKT 's idea, the demo works good. terminal shows succeed and figure 1-5 shows up.
score: 0
has title: KeyError: 'max_overlaps' on tensorflow ver Faster R-CNN

http://stackoverflow.com/q/51729308
answer count: 4
has answer: http://stackoverflow.com/a/51729735
favorite count: 0
has comment: http://stackoverflow.com/comment/90481295
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51729719
upvote count: 1
has answer: http://stackoverflow.com/a/51729942
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51730197
tagged with: arrays
downvote count: 0
score: 1
has body: I have a numpy array, &gt; [[ 0 0 0 0 0] [ 0 0 0 0 0] [ 0 0 0 0 0] ... [ 0 255 0 255 0] [ 0 255 0 0 0] [ 0 255 0 0 0]] I would like to check values in each column of this 2d numpy array - whether or not there are more than one column with alternating 0 and 255 values Example column &gt; [[ 0 0 0 255 0] [ 0 255 0 0 0] [ 0 255 0 0 0] [ 0 255 0 0 0] [ 0 0 0 0 0] [ 0 0 0 0 0] [ 0 0 0 0 0] [ 0 0 0 0 0] [ 0 255 0 0 0] [ 0 255 0 0 0] [ 0 255 0 0 0] [ 0 255 0 0 0] [ 0 255 0 0 0]] In the above example, column two has alternating 0 and 255 values, hence, the output should be that this numpy array has one column with these alternating values
has comment: http://stackoverflow.com/comment/90420471
has title: How to check values in columns in a numpy array
tagged with: python

http://stackoverflow.com/comment/90459739
comment on: http://stackoverflow.com/q/51748195
score: 0
type: QuestionComment
has text: @Capricorn do you have any idea?
type: Comment

http://stackoverflow.com/comment/90401684
type: QuestionComment
comment on: http://stackoverflow.com/q/51720345
has text: @VikasDamodar , can i have the full code
score: 0
type: Comment

http://stackoverflow.com/comment/90273452
type: Comment
has text: It really depends on what are you doing in that function. Do you close the file you open? Try to create a minimal example so that one could try and reproduce your issue.
comment on: http://stackoverflow.com/q/51654991
score: 0
type: QuestionComment

http://stackoverflow.com/q/51776983
downvote count: 0
has comment: http://stackoverflow.com/comment/90516668
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/21566379
type: UnansweredQuestion
tagged with: python
tagged with: data-fitting
score: 1
upvote count: 1
type: Question
has body: I have multiple images of objects where the object of interest (one per image) is near the center of said image. However, it's not necessarily the brightest source in the image, because some of the images also include sources that I am not interested in, but happen to be brighter/more intense. There is also usually a considerable amount of noise. I would like to fit Gaussians to these 2D numpy image arrays, but am unsure how to effectively do so with these bright sources I don't want. In the end, I'll be stacking all the images (median) with the source of interest centered, so these other bright sources will just disappear. Below is my attempted code so far, where data is a list of multiple 2D arrays (images). import numpy as np import scipy def Gaussian2D(x, y, x_0, y_0, theta, sigma_x, sigma_y, amp): a = np.cos(theta)**2/(2*sigma_x**2) + np.sin(theta)**2/(2*sigma_y**2) b = -np.sin(2*theta)/(4*sigma_x**2) + np.sin(2*theta)/(4*sigma_y**2) c = np.sin(theta)**2/(2*sigma_x**2) + np.cos(theta)**2/(2*sigma_y**2) exp_term = a * (x-x_0)**2 exp_term += 2*b*(x-x_0)*(y-y_0) exp_term += c * (y-y_0)**2 return amp * np.exp(-exp_term) def GaussianFit(data): for data_set in data: y_0, x_0 = (np.shape(data_set)[0]//2, np.shape(data_set)[1]//2) sigma_x, sigma_y = np.std(data_set, axis=1), np.std(data_set, axis=0) fit = scipy.optimize.curve_fit(Gaussian2D(x, y, x_0, y_0, 0, sigma_x, sigma_y, amp), data_set) return fit I've never done function fitting in a code, so I feel pretty lost. My specific questions are: How can I define my parameters correctly? Do I need to flatten by array to get the sigma parameters? Also, I noticed in some example code that people made x and y arrays with linspace, so I'm not sure if I need to do that, and I'm also not sure what to put for the amplitude. How would I handle the fact that I have multiple bright sources per image but only want to fit for the one closest to the center? Can I somehow specify to look near the center of the image? I will also need…
tagged with: arrays
tagged with: gaussian
linked to: http://stackoverflow.com/q/49069219
linked to: http://stackoverflow.com/q/30738008
has answer: http://stackoverflow.com/a/51779465
has title: How to get correct parameters for 2D Gaussian fit to an image with noise

http://stackoverflow.com/q/51787219
type: Question
has comment: http://stackoverflow.com/comment/90532774
has comment: http://stackoverflow.com/comment/90597928
has comment: http://stackoverflow.com/comment/90598006
has comment: http://stackoverflow.com/comment/90531717
has comment: http://stackoverflow.com/comment/90622037
has comment: http://stackoverflow.com/comment/90555811
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90532419
tagged with: qsortfilterproxymodel
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90532337
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51787985
has comment: http://stackoverflow.com/comment/90532567
tagged with: python
has body: I have a QTableWidget with data from database and I want to search its content in real time (when I'm typing a letter he show me results)? Every help is welcome. Thanks a lot. This is my code: class Filter: def __init__(self): object.__init__(self) self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName("baza.db") self.filter_model= QSortFilterProxyModel() def sqlPodaci(self,okvir): okvir.setObjectName("Okvir aplikacije") okvir.resize(700,320) line_edit = QLineEdit(okvir) line_edit.setGeometry(20, 20, 205, 23) self.tableWidget = QtWidgets.QTableWidget(okvir) self.tableWidget.setGeometry(QtCore.QRect(20, 50, 620, 201)) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setRowCount(3) self.tableWidget.horizontalHeader().setVisible(True) self.tableWidget.verticalHeader().setVisible(False) ### self.filter_model.setFilterKeyColumn(1) line_edit.textChanged.connect(self.filter_model.setFilterRegExp) #### self.Ucitavanje_podataka() This is the code for reading data from the database: def Ucitavanje_podataka(self): status = self.db.open() if status == False: QtWidgets.QMessageBox.warning(self, "Error", self.db.lastError().text(), QtWidgets.QMessageBox.Discard) else: self.tableWidget.setColumnCount(6) self.tableWidget.setHorizontalHeaderLabels(['Id','Ime','Prezime','Godine','Adresa','Plata']) row = 0 sql = " SELECT * FROM Zaposleni" query = QtSql.QSqlQuery(sql) while query.next(): self.tableWidget.insertRow(row) ID=QtWidgets.QTableWidgetItem(str(query.value(0))) Ime = QtWidgets.QTableWidgetItem(str(query.value(1))) Prezime = QtWidgets.QTableWidgetItem(str(query.value(2))) Godine = QtWidgets.QTableWidgetItem(str(query.value(3))) Adresa = QtWidgets.QTableWidgetItem(str(query.value(4))) Plata = QtWidgets.QTableWidgetItem(str(query.value(5))) self.tableWidget.setItem(row,0,ID) self.tableWidget.setItem(row, 1, Ime) self.tableWidget.setItem(row, 2, Prezime) self.tableWidget.setItem(row, 3, Godine) self.tableWidget.setItem(row, 4, Adresa) self.tableW…
has title: How use QSortFilterProxyModel in database?
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90532401
has comment: http://stackoverflow.com/comment/90596112
has comment: http://stackoverflow.com/comment/90586996
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/51787985

http://stackoverflow.com/comment/113905688
type: Comment
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/60637493
has text: It will also make your database unsecure.

http://stackoverflow.com/q/51674061
score: 2
has answer: http://stackoverflow.com/a/51675054
tagged with: web-scraping
tagged with: scrapy
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: How to download images without error in Scrapy?
upvote count: 2
type: UnansweredQuestion
has body: I am newbie to scrapy. I am trying to download an image. import scrapy from scrapy.http import Request class PlayerSpider(scrapy.Spider): name = 'player' #allowed_domains = ['nba.com/players'] start_urls = ['http://www.nba.com/players/'] def parse(self, response): Player_Name = response.css('div#content.nba-player-index a ::attr(title)').extract() Player_link = response.css('.nba-player-index__trending-item a::attr(href)').extract() links = [url for url in Player_link if url.startswith("/players")] for link in links: absolute_url = response.urljoin(link) yield Request(absolute_url, callback=self.parse_players) def parse_players(self, response): Player_Name = response.css('section.nba-player-header__details-bottom ::text').extract() items=[] for images in Player_Name: item = PlayerSpider() images_link = response.css('section.nba-detail-header-wrapper .nba-player-header__headshot img::attr(src)').extract_first() image_urls = 'http:{}'.format(images_link) item[image_urls] return item Player_Height = response.css('section.nba-player-vitals__top-left.small-6 p.nba-player-vitals__top-info-imperial ::text').extract() Player_Weight = response.css('section.nba-player-vitals__top-right.small-6 p.nba-player-vitals__top-info-imperial ::text').extract() yield { 'Player_name' : Player_Name, 'Player_Height' : Player_Height, 'Player Weight' : Player_Weight } I think files are good. But I am unable to write correct spider for getting the image. I am able to grab the image URL but don't know how to store the image using imagePipeline. items.py import scrapy from scrapy.item import Item class PlayerSpider(scrapy.Item): image_url = scrapy.Field() images = scrapy.Field() pass
tagged with: python

http://stackoverflow.com/q/51769016
has comment: http://stackoverflow.com/comment/90497030
tagged with: pandas
has comment: http://stackoverflow.com/comment/90496896
has answer: http://stackoverflow.com/a/51769519
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90497482
favorite count: 0
accepted answer: http://stackoverflow.com/a/51769519
has title: How to enumerate rows in pandas with nonunique values in groups
tagged with: python
type: AnsweredQuestion
has body: I am working with expeditions geodata. Could you help with enumeration of stations and records for the same station depending on expedition ID (ID), date (Date), latitude (Lat), longitude (Lon) and some value (Val, it is not reasonable for enumeration)? Assume that station is a group of rows with the same (ID,Date,Lat,Lon), expedition is a group of rows with the same ID. Dataframe is sorted by 4 columns as in example. Dataset and required columns import pandas as pd data = [[1,'2017/10/10',70.1,30.4,10],\ [1,'2017/10/10',70.1,31.4,20],\ [1,'2017/10/10',70.1,31.4,10],\ [1,'2017/10/10',70.1,31.4,10],\ [1,'2017/10/12',70.1,31.4,20],\ [2,'2017/12/10',70.1,30.4,20],\ [2,'2017/12/10',70.1,31.4,20]]; df = pd.DataFrame(data,columns=['ID','Date','Lat','Lon','Val']); Additional (I need it, St for station number and Rec for record number within the same station data; output for example above): df['St'] = [1,2,2,2,3,1,2]; df['Rec'] = [1,1,2,3,1,1,1]; print(df) I tried and used groupby/cumcount/agg/factorize but have not solved my problem. Any help! Thanks!
score: 1
tagged with: geolocation
upvote count: 1
type: Question

http://stackoverflow.com/a/51716536
has comment: http://stackoverflow.com/comment/90407588
has comment: http://stackoverflow.com/comment/90443191
type: Answer
has body: doc.to_disk(fout) must be a path to a directory, which will be created if it doesn't exist. Paths may be either strings or Path-like objects. as the documentation for spaCy states in https://spacy.io/api/doc Try changing fout to a directory, it might do the trick. EDIT: Examples from the spacy documentation: for doc.to_disk: doc.to_disk('/path/to/doc') and for doc.from_disk: from spacy.tokens import Doc from spacy.vocab import Vocab doc = Doc(Vocab()).from_disk('/path/to/doc')
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90412984
answers question: http://stackoverflow.com/q/51711084
upvote count: 1

http://stackoverflow.com/q/51755336
answer count: 0
has body: Background: I'm building this gui dictionary app using python and PyQt5. data.json is the file containing keys and their definitions(data is arranged like a python dictionary). dictionary.ui is the UI that i built in pyqt5 designer app ( widget class="QMainWindow" name="MainWindow"). (widget class="QPushButton" name="pushButton"). (widget class="QLineEdit" name="lineEdit").(widget class="QLabel" name="resultArea") Problem: The program runs after a while showing gui. But when i enter something, the program crashes without an output. I'm having trouble fixing this code. The problem is in this line of code self.resultArea.setText(self.trasnlate(self.lineEdit.text())) The error is Translate is a method not a class instance. I need the user input that is entered in lineEdit label as an argument for translate() method and show the result of the method in resultArea label if the pushButton is clicked. Code: import json from difflib import get_close_matches import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication,QMainWindow from PyQt5.uic import loadUi data = json.load(open("data.json")) class DictionaryApp(QMainWindow) : def __init__(self) : super(DictionaryApp,self).__init__() loadUi('dictionary.ui',self) self.setWindowTitle('Dictionary') self.pushButton.clicked.connect(self.on_pushButton_clicked) @pyqtSlot() def on_pushButton_clicked(self) : self.resultArea.setText(self.trasnlate(self.lineEdit.text())) @staticmethod def translate(w) : w = w.lower() if w in data : return data[w] elif w.title() in data: return data[w.title()] elif w.upper() in data: return data[w.upper()] elif len(get_close_matches(w, data.keys())) > 0 : YN = input("Did you mean {} instead? Enter 'y' for yes, 'n' for no: ".format(get_close_matches(w, data.keys())[0])).lower() if YN == "y" : return data[get_close_matches(w, data.keys())[0]] elif YN == "n" : return "The word doesn't exist. Please double check it. " else : return "Wrong entry. " else : return "The word doesn't ex…
type: UnansweredQuestion
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/90471356
upvote count: 1
has comment: http://stackoverflow.com/comment/90470925
score: 0
has title: Errors Incorporating UI into Python Code
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90471207
has comment: http://stackoverflow.com/comment/90471540
favorite count: 0

http://stackoverflow.com/comment/90314943
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51675950
type: AnswerComment
has text: He needs `1` and `10` as `[1]` and `[10]` and so on. I didn't down vote though.

speech-recognition
tags question: http://stackoverflow.com/q/51757824
tags question: http://stackoverflow.com/q/51654999
tags question: http://stackoverflow.com/q/51643689
tags question: http://stackoverflow.com/q/51664957
tag name: speech-recognition
type: Tag

http://stackoverflow.com/q/51642944
tagged with: pip
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90250341
score: -1
has body: I am trying to install a python package called numba. I want to install it for python2.7, so when I run sudo pip2.7 install numba, it gives a following message. Can anyone let me know what the issue is? Thank you. copying numba/tests/pycc_distutils_usecase/source_module.py -&gt; build/lib.macosx-10.13-intel-2.7/numba/tests/pycc_distutils_usecase running build_ext building 'numba._dynfunc' extension C compiler: cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe creating build/temp.macosx-10.13-intel-2.7 creating build/temp.macosx-10.13-intel-2.7/numba compile options: '-I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c' cc: numba/_dynfuncmod.c cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.13-intel-2.7/numba/_dynfuncmod.o -o build/lib.macosx-10.13-intel-2.7/numba/_dynfunc.so ld: in '/usr/local/lib/libunwind.dylib', file was built for x86_64 which is not the architecture being linked (i386): /usr/local/lib/libunwind.dylib for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) ld: in '/usr/local/lib/libunwind.dylib', file was built for x86_64 which is not the architecture being linked (i386): /usr/local/lib/libunwind.dylib for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) error: Command "cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.13-intel-2.7/numba/_dynfuncmod.o -o build/lib.macosx-10.13-intel-2.7/numba/_dynfunc.so" failed with exit status 1 ---------------------------------------- Command "/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -c "import setuptools, t…
type: Question
has comment: http://stackoverflow.com/comment/91697729
upvote count: 0
answer count: 1
has title: `pip` installation issue for a python package
has comment: http://stackoverflow.com/comment/90250328
has answer: http://stackoverflow.com/a/52575956
favorite count: 0
type: UnansweredQuestion
tagged with: numba

http://stackoverflow.com/a/51715332
answers question: http://stackoverflow.com/q/51711826
type: Answer
has body: It easy to solve without regex: s='|3E 00|redcar|0D|' rslt=[] pipe=0 for ch in s: if ch=='|': pipe+=1 continue if pipe%2: if ch==" ": continue rslt.append(ch) else: rslt.append(f"{ord(ch):02X}") print("".join(rslt)) '3E007265646361720D'
score: 0

http://stackoverflow.com/comment/90401775
type: AnswerComment
score: 0
type: Comment
has text: AttributeError Traceback (most recent call last) <ipython-input-19-b7122418eb20> in <module>() ----> 1 out.columns = out.columns.swaplevel(0,1).to_series().str.join('_') 2 out.columns AttributeError: 'Index' object has no attribute 'swaplevel' error happens.Why does such a thing happen?
comment on: http://stackoverflow.com/a/51720252

http://stackoverflow.com/q/51696226
type: AnsweredQuestion
has title: python3 numpy ndarray does not have consistant dimentions. Encountered odd behavor with shape atribute
tagged with: python-3.x
type: Question
tagged with: shapes
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51696267
score: 0
has comment: http://stackoverflow.com/comment/90354160
has body: I am using the numpy package in python 3. First, here is some code that shows the odd behavior I have encountered with the ndarray shape attribute. threeDndarray = np.ndarray(shape=(2,5,2)) #3d ndarray to showcase behavor print(threeDndarray.shape) **output:** (2, 5, 2) print(threeDndarray[:][:][:].shape) **output:** (2, 5, 2) #now the odd behavor print(threeDndarray[:][1][:].shape) #expected (2,2) **output:** (5, 2) print(threeDndarray[:][:][1].shape) **output:** (5, 2) print(threeDndarray[1][:][:].shape) **output:** (5, 2) I believe this odd .shape behavior is related to the problem that I have. I want to store the values from five separate 2x2 matrices in a 3dndarray with the dimensions (2,5,2). I am unable to perform the operation my3dArray[:][i][:] = my2dMatrix, without getting an error related to dimension mismatching. The specific error is ValueError: could not broadcast input array from shape (2,2) into shape (5,2) I do not understand why I am getting this error or why the shape attribute has such strange behavior.
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51696267

http://stackoverflow.com/a/51792673
has comment: http://stackoverflow.com/comment/90544691
has comment: http://stackoverflow.com/comment/90543286
upvote count: 5
has body: The key is to come up with edge cases. Which relies a lot on experience with the problem domain—what bugs have you seen dealing with datetimes in the past. But fortunately, you can always just add more unit tests as you find and fix bugs or think of odd cases while waiting for a Lyft or whatever. There are some particular things to watch out for with datetimes—but note that many of them, you first have to decide what you want to do, before you can test whether you're doing what you decided to do. Make sure non-strings raise a ValueError, of course. Including bytes. Single-digit days and months—is 2018-3-06 a valid date? Likewise for hours, minutes, and seconds (but sometimes the rule you want is different). Different separators—e.g., 2018-03-06 12:13:14 is a valid ISO timestamp, but not valid by your rule. Same with, for that matter, 20180306T12:13:14, and many other variations. All of the obvious past-the-end values, like month 0 or 13—but see below for the odd exceptions, like second 60. Timestamps too far in the past for other parts of your code to handle. For example, ISO allows dates in 1960, but if your code is going to pass them to an API that deals with uint32 Unix timestamps, they're not valid as far as you're concerned. Year 0000. According to ISO 8601, this means 1 BCE, but you may not want that. Two-digit years. And one-, three-, and five-digit years. And negative years, and years with an explicit + prefix. ISO 8601 recommends four-digit years like 0030, but also recommends allowing + and - prefixes (and that's the only way to handle years before 1 BCE), and allows years like 10010 "by usually agreement of the partners in information interchange. Fractional seconds. Someone will pass you 2018-06-20T15:16:17.890. Time zone/offset indicators. Someone will pass you 2018-06-20T15:16:17Z. 29 Feb on leap years (including 2000) and non-leap-years (including 1900). Leap seconds—e.g., 2005-12-31T23:59:60 UTC or 2006-01-01T08:59:60 local in Japan. Hours that don't…
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90544711
answers question: http://stackoverflow.com/q/51792216
score: 5

http://stackoverflow.com/a/51778522
score: 0
has body: It is trying to insert a variable inside of the curly braces you put around the entire string. If you want to have curly braces in a formatted string, you have to use two. string = "{{test_number: {0}}}".format(37)
type: Answer
answers question: http://stackoverflow.com/q/51778475

http://stackoverflow.com/q/51789735
has answer: http://stackoverflow.com/a/51949037
score: 0
answer count: 1
tagged with: python
tagged with: dask
tagged with: dask-delayed
has body: I have been trying to write custom classes for Preprocessing followed by Feature selection and Machine Learning algorithms as well. I cracked this (preprocessing only) using @delayed. But when I read from the tutorials that the same can be achieved using Client. It caused two problems. Running as a script. Not as a Jupyter notebook First Problem: # Haven't run any scheduler or worker manually client = Client() # Nothing passed as an argument # Local Cluster is not working; Error:... if __name__=='__main__': freeze_support() ... I tried the same in Jupyter Notebook, without running any scheduler or workers in different terminals. It worked!! Now, I triggered 3 terminals with 1 scheduler and 2 workers and changed it to Client('IP') in the script. Error resolved, any reason for this behavior. Second Problem: The error mentioned in the title of the question. Passed the client = Client('IP') as the argument to the constructor and used self.client.submit things to the cluster. But failed with the error message Error: No module name 'diya_info' Here's the code: main.py import dask.dataframe as dd from diya_info import Diya_Info import time # from dask import delayed from dask.distributed import Client df = dd.read_csv( '/Users/asifali/workspace/playground/flask/yellow_tripdata_2015- 01.csv') # df = delayed(df.fillna(0.3)) # df = df.compute() client = Client('192.168.0.129:8786') X = df.drop('payment_type', axis=1).copy() y = df['payment_type'] Instance = Diya_Info(X, y, client) s = time.ctime(int(time.time())) print(s) Instance = Instance.fit(X, y) e = time.ctime(int(time.time())) print(e) # print((e-s) % 60, ' secs') diya_info.py from sklearn.base import TransformerMixin, BaseEstimator from dask.multiprocessing import get from dask import delayed, compute class Diya_Info(BaseEstimator, TransformerMixin): def __init__(self, X, y, client): assert X is not None, 'X can\'t be None' assert type(X).__name__ == 'DataFrame', 'X not of type DataFrame' assert y is not None, 'y can\…
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51949037
tagged with: dask-distributed
has title: Error: No module name 'Custom Class' while passing a Client object in the custom class's constructor in dask

http://stackoverflow.com/comment/90578431
type: Comment
has text: The new version works like a charm! Thank you a lot for effort and time!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51716842

http://stackoverflow.com/comment/90366749
type: Comment
score: 1
has text: @taras Yup! Edited.
type: AnswerComment
comment on: http://stackoverflow.com/a/51702659

http://stackoverflow.com/comment/90587902
comment on: http://stackoverflow.com/a/51806204
type: Comment
has text: If so, is k-means the same as DBSCAN? I don't know how to put the input value when I run k-means in r.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51642193
answers question: http://stackoverflow.com/q/51640866
accepted answer of: http://stackoverflow.com/q/51640866
score: 0
type: AcceptedAnswer
type: Answer
has body: You can't have this: @app.route('/') def my_form(): return render_template('a.html') @app.route('/', methods=['GET', 'POST']) def my_form_post(): You have defined two routes with the same identifier '/'. The latter one will be used and the first one will be completely ignored. When the code is executed first time (as a GET) there is no form to provide a username string so it is not rendered, which explains your output, "Welcome to the quiz Who is the president of India?"

http://stackoverflow.com/q/51747895
score: 0
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/51747999
tagged with: pandas
has title: Pandas: how to fill missing diff value after groupby?
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: I group a set of data with Pandas.groupby. Then I want to calculate the delta value that's given by the difference between the first element of each group to the first element of the next one: import pandas as pd import numpy as np import datetime # dummy set of data np.random.seed(0) SIZE = 25 dt = pd.date_range(datetime.datetime(2018,1,1,10,14,30), freq="1Min", periods=SIZE) wa = (np.random.random(size=SIZE)-.4)*1000 wa = np.cumsum(wa) + 10000 df = pd.DataFrame({"dtime":dt, "value":wa}).set_index("dtime") grouped = df.groupby(pd.Grouper(freq='15Min')) print("\n************\nDataframe:") print df print("\n************\nFirst value of each group:") print(grouped.first()) print("\n************\nDelta value:") print(-grouped.first().diff(periods=-1)) This code returns: ************ Dataframe: value dtime 2018-01-01 10:14:30 10148.813504 2018-01-01 10:15:30 10464.002870 2018-01-01 10:16:30 10666.766246 2018-01-01 10:17:30 10811.649429 2018-01-01 10:18:30 10835.304229 .... 2018-01-01 10:34:30 14209.714833 2018-01-01 10:35:30 14608.873397 2018-01-01 10:36:30 14670.352759 2018-01-01 10:37:30 15050.881935 2018-01-01 10:38:30 14769.156361 ************ First value of each group: value dtime 2018-01-01 10:00:00 10148.813504 2018-01-01 10:15:00 10464.002870 2018-01-01 10:30:00 12350.307746 ************ Delta value: value dtime 2018-01-01 10:00:00 315.189366 2018-01-01 10:15:00 1886.304875 2018-01-01 10:30:00 NaN &lt;===== Here is my problem Of course the last delta is NaN because there is no next group to calculate the diff against. Is there a way to fill this NaN with the difference between the first and the last values of the last group? Being the last row 2018-01-01 10:38:30 14769.156361, it should return: ************ Delta value: value dtime 2018-01-01 10:00:00 315.189366 2018-01-01 10:15:00 1886.304875 2018-01-01 10:30:00 2418.848615 Thank you
type: Question
accepted answer: http://stackoverflow.com/a/51747999

http://stackoverflow.com/a/51725917
has body: After some discussion, my friend found a quite hack solution for it: build.py: ABC_ACTIVATE = False def activate_abc(other_context): other_context.ABC_ACTIVATE = True And in customize.py: from build import * activate_abc(sys.modules[__name__]) print ABC_ACTIVATE It works now.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51708778

http://stackoverflow.com/comment/90393794
comment on: http://stackoverflow.com/q/51716239
score: 1
type: Comment
has text: have you tried adding the `http://` text? I don't see any evidence of it in your code.
type: QuestionComment

postgresql
tags question: http://stackoverflow.com/q/51703185
tags question: http://stackoverflow.com/q/51778765
tags question: http://stackoverflow.com/q/51697947
tags question: http://stackoverflow.com/q/51746423
tags question: http://stackoverflow.com/q/51677027
tags question: http://stackoverflow.com/q/51726782
tags question: http://stackoverflow.com/q/51662445
tags question: http://stackoverflow.com/q/51733152
tags question: http://stackoverflow.com/q/51751943
tags question: http://stackoverflow.com/q/51650485
tags question: http://stackoverflow.com/q/51777543
tags question: http://stackoverflow.com/q/51762534
tags question: http://stackoverflow.com/q/51715089
tag name: postgresql
tags question: http://stackoverflow.com/q/51655297
tags question: http://stackoverflow.com/q/51704315
tags question: http://stackoverflow.com/q/51778645
tags question: http://stackoverflow.com/q/51717977
tags question: http://stackoverflow.com/q/51653316
tags question: http://stackoverflow.com/q/51656756
type: Tag
tags question: http://stackoverflow.com/q/51749603
tags question: http://stackoverflow.com/q/51716121
tags question: http://stackoverflow.com/q/51784817
tags question: http://stackoverflow.com/q/51717561
tags question: http://stackoverflow.com/q/51737912
tags question: http://stackoverflow.com/q/51707677
tags question: http://stackoverflow.com/q/51740197
tags question: http://stackoverflow.com/q/51744615
tags question: http://stackoverflow.com/q/51750715
tags question: http://stackoverflow.com/q/51787907

http://stackoverflow.com/comment/90704239
type: QuestionComment
has text: try to yield request with another callback (don't override ```parse``` method). As long as i remember, ```parse``` method are used by Spider class and can lead to conflicts in some configuration cases, and also add ```dont_filter=True``` option (as @GhasemNaddaf wrote)
comment on: http://stackoverflow.com/q/51744766
score: 0
type: Comment

http://stackoverflow.com/a/51719562
has comment: http://stackoverflow.com/comment/90400074
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/90400064
upvote count: 2
has comment: http://stackoverflow.com/comment/90400131
has comment: http://stackoverflow.com/comment/90400023
downvote count: 1
has body: Use Canny Edge Detection on your image. Then depending how it looks like use Morphological Dilation (cv.dilate()) to make the edges a bit thicker. Afterwards remove the edges from the green channel of the image or reduce the brightness of green channel. Or make the pixels transparent. This post states the following approach: 1.) Convert green pixels to transparency. Basically uses a filtering rule in the HSV color space. 2.) On the hair and some boundary pixels colors are mixed with green. To reduce this problem these pixels are filtered and balanced to reduce their green proportion. 3.) Apply a gradient transparency to all boundary pixels.
has comment: http://stackoverflow.com/comment/90400165
has comment: http://stackoverflow.com/comment/90400438
answers question: http://stackoverflow.com/q/51719472
has comment: http://stackoverflow.com/comment/90399883
has comment: http://stackoverflow.com/comment/90400226

http://stackoverflow.com/comment/90337445
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51687719
has text: It worked. But removed the comma between sentences also. It looks like ' Even my brother is not like to speak with meThey treat me like aids patent'. How can I keep the sentences separated for later processing?

http://stackoverflow.com/comment/90542173
type: AnswerComment
score: 0
has text: Thank you, this is a really good start! I need to be able to take it a step further, however, as eventually the rows will need to be `[0 1 2 ... n]`. I'll update the question.
type: Comment
comment on: http://stackoverflow.com/a/51792140

http://stackoverflow.com/comment/90496464
type: Comment
score: 0
type: QuestionComment
has text: @DanilaGanchar Wouldn't "db.Index('scheduleId', Schedule.taskId)" create it? Or you mean i have to state it as "scheduleId = db.Column(dg.Integer, index=True, unique=True)"? But then it would throw an error when i insert the record to database because i wouldn't know the scheduleId. I want scheduleId to automatically increase each time a record hits the database.
comment on: http://stackoverflow.com/q/51767830

http://stackoverflow.com/q/51730121
tagged with: dataframe
answer count: 3
has title: Filter dataframe rows by index name
downvote count: 0
favorite count: 0
upvote count: 8
tagged with: pandas
has answer: http://stackoverflow.com/a/51730175
tagged with: python
has comment: http://stackoverflow.com/comment/90421031
score: 8
has body: I have a DataFrame where I want to drop elements depending on their index name col1 col2 entry_1 10 11 entry_2_test 12 13 entry_3 14 15 entry_4_test 16 17 Basically I want to drop the ones ending with _test I know how to select them: df.filter(like='_test', axis=0) col1 col2 entry_2_test 12 13 entry_4_test 16 17 Then I can actually get those indexes: df.filter(like='_test', axis=0).index entry_2_test entry_4_test And finally I can drop those indexes and overwrite my dataframe with the filtered one. df = df.drop(df.filter(like='_test', axis=0).index) df col1 col2 entry_1 10 11 entry_3 14 15 My question is if this is the correct way of filtering or there's a more efficient dedicated function to do this?
accepted answer: http://stackoverflow.com/a/51730175
possible better answer: http://stackoverflow.com/a/51730276
has answer: http://stackoverflow.com/a/51730276
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51730324

http://stackoverflow.com/comment/90370858
comment on: http://stackoverflow.com/a/51704908
score: 0
type: AnswerComment
has text: Worked perfectly, thanks. But why isn't the original code working? With mainloop() shouldn't the code print the value again and again each frame?
type: Comment

http://stackoverflow.com/comment/90466926
type: QuestionComment
has text: I edit my code. Left entry field and drop down list. Is it still to much?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51730947

http://stackoverflow.com/q/51770740
tagged with: dataframe
tagged with: date
score: 0
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/90500755
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has title: How “reindexing” the dataframe with min_date and max_date value
type: AnsweredQuestion
has body: Q Mod Date 2007-01-02 8.0 3900.0 2007-01-03 6.5 3950.0 2007-01-04 7.5 3960.0 2007-01-05 8.5 4000.0 2007-01-06 6.0 4000.0 This is my data set. Start Date: 2007-01-02 End Date: 2017-12-31 Data contain missing values, so I am trying to fill with moving average 5. So I crate this new data frame, and how I fill this with moving average window 5?
type: Question
has answer: http://stackoverflow.com/a/51779708
accepted answer: http://stackoverflow.com/a/51779708

string-comparison
tags question: http://stackoverflow.com/q/51756278
tag name: string-comparison
type: Tag

http://stackoverflow.com/comment/90498879
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51769244
has text: I am wondering if it is creating autoincrement for your other column as well. try defining `autoincrement=False` for other field and try again.

http://stackoverflow.com/comment/90542931
score: 6
type: AnswerComment
has text: `x[::-1]` instead of `x[-1]` to deal with ties, rather than just the last character
comment on: http://stackoverflow.com/a/51792693
type: Comment

http://stackoverflow.com/comment/90449805
type: Comment
has text: You can use `beautifulsoup` to get a list of the href of all the a tag in the webpage ending in `csv`. You can then iterate over the list to download each one.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51744751

http://stackoverflow.com/a/51758543
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90476501
has body: Importing the Tensorflow project is no different than any other Bazel Project. It works fine for me when I try the following: Install the Bazel plugin by going to configure -> Plugins -> and searching for Bazel. Install the following plugin: Once installed restart CLion Once restarted click on the open project option in the load screen: This will open and import the tensorflow project with build settings. You can see from this image that the bazel configuration and settings are imported correctly: Note: Bazel builds the entire tensorflow project into an installable python package. If you are purely interested in compiling it for C/C++ then I suggest you look at how to build and use the C++ API as building the entire project for every edit you make will age you very quickly. Recommendation: If you just want to run the test files then install Tensorflow and simply execute the test files like you would run any program with cpp source files.
accepted answer of: http://stackoverflow.com/q/51753539
answers question: http://stackoverflow.com/q/51753539
upvote count: 1

http://stackoverflow.com/comment/90385766
comment on: http://stackoverflow.com/a/51712183
has text: Since Numpy is implemented in C, it makes sense that we'd be seeing a huge improvement over our pure Python Sort
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90539854
comment on: http://stackoverflow.com/q/51790491
type: QuestionComment
has text: Not clear what "the Nth percentile" means for vector-valued samples. Say, X and Y are uniformly distributed over [0, 1] and we want the 50th percentile. Where would that be and why?
type: Comment
score: 1

http://stackoverflow.com/a/51664411
answers question: http://stackoverflow.com/q/51644564
has comment: http://stackoverflow.com/comment/90316357
score: 0
has body: you will have to do cookie management. this website stores your value in a cookie. since you are making a post request, the next time you hit a get request, the values are stored in a cookie in the actual website. The web browsers manage our cookies so the bag has the data added. If you hit the same in incognito mode you will not have any data. refer http://docs.python-requests.org/en/master/user/advanced/ for setting a cookie.
has comment: http://stackoverflow.com/comment/90312423
type: Answer

http://stackoverflow.com/comment/108898095
type: QuestionComment
score: 0
has text: @AKX, thanks so much for mentioning this! I wanted to do the same thing as OP, not aware that the **static** folder is meant to be *static*, :-)
comment on: http://stackoverflow.com/q/51745325
type: Comment

http://stackoverflow.com/q/51658126
tagged with: odoo-11
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90293677
tagged with: odoo
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: I am learning Odoo 11 and want to code a button which will call a python method through a Server action. Here's my button code: Here's my action.server code enviarfactura 1 ir.actions.server code if records: action = records.x_nc_met_fac() And finally here's my python method. @api.multi def x_nc_met_fac(self): for rec in self: self.x_nc_fld_fact = True self.x_nc_fld_det_fact = 'my custom text' Now the logic for this is that, the button will call the server.action which will call the method on my python class. The method will set new values for extended fields on the model account.invoice In theory this should work, but it doesn't. Discarding possible mistakes: -It's might not be the python indentation. The python community on discord help me with it :P -It's not the server.action structure since when I upload my module containing this code it creates the server.action without any problem. -When I click on the button, nothing happens.So i tried changing the type of the button to "type=object" and tell it the name of my method it gives the error. Account.invoice has no attribute "x_nc_met_fac" Any help is appreciated. Thanks in advance.
has answer: http://stackoverflow.com/a/51668259
accepted answer: http://stackoverflow.com/a/51668259
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has title: How to code an update for extended field using server action on Odoo 11?

http://stackoverflow.com/q/51645244
has answer: http://stackoverflow.com/a/51659123
score: 0
tagged with: state
answer count: 1
tagged with: decorator
linked to: http://stackoverflow.com/q/1690400
type: UnansweredQuestion
tagged with: python
has title: Stackable decorator using a Traceback to obtain caller name of function/class?
has comment: http://stackoverflow.com/comment/90281998
has comment: http://stackoverflow.com/comment/90254495
type: Question
has body: So, I'm messing around and created this pseudo State-Machine app sequencing pattern https://github.com/rebelclause/python_legs/blob/master/init_subclass_example.py extending this traceback method by a wide margin: https://stackoverflow.com/a/1690751/7955763 import traceback # for callable name from functools import wraps def tracename(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): (filename,line_number,function_name,text)=traceback.extract_stack()[-2] def_name = text[:text.find('=')].strip() print(def_name) return def_name return wrapper Now, I realize it may not be the right method for the job of making a decorator; after all the traceback has to immediately follow the function whose caller name you want to get. I tried knowing this anyway, but now the fun is over. I'm not sure how I'd use it (even in the framework I've presented), but can someone answer as to how the decorator and the code to capture the caller name can be improved so it'll work as a decorator in a stack of decorators? And maybe how? Edit: Added this while avoiding a coroutine problem... import traceback # for callable name from functools import wraps # this should make you laugh, or not def tracename(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): (filename,line_number,function_name,text)=traceback.extract_stack()[-2] def_name = text[:text.find('=')].strip() # print(def_name) return def_name return wrapper class foo(object): ''' ''' def __init__(self): pass @tracename def _goodbye(self): print("It's been a good run so far, but this decorator might be toast.") print(foo()._goodbye()) # prints wrapper returned var def_name foo()._goodbye() # sits and watches while we patiently wait? # uncomment the print statement in the decorator, then re-run # then comment out the decorator and run it guess_who = foo()._goodbye() print('Guess where def_name went :', guess_who) # would it freak you out if the comment printed, too?
has comment: http://stackoverflow.com/comment/90280993
tagged with: callable

http://stackoverflow.com/a/51718280
type: Answer
has body: The width property of each bar graph will help you set the individual widths. Just keep in mind that if the width is greater than 1 then there is overlap between the adjacent bar graph, so try contraining the value between 1 and 0. Please tryout the below example. import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html from pandas_datareader import data as web from datetime import datetime as dt import plotly.graph_objs as go app = dash.Dash() data = [go.Bar( x = [1], y = [100], width=1, marker=go.Marker( color = 'blue' ) ) , go.Bar( x = [2], y = [200], width=0.6, marker=go.Marker( color = 'red' ) ) ] app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': data, 'layout': { 'title': 'Dash Data Visualization', 'xaxis': { 'range': [0,4], 'nticks':20, 'dticks': 0.5} } } ) ]) if __name__ == '__main__': app.run_server(debug=True)
answers question: http://stackoverflow.com/q/51712718
has comment: http://stackoverflow.com/comment/90457848
has comment: http://stackoverflow.com/comment/90455178
score: 0

http://stackoverflow.com/q/51761961
has answer: http://stackoverflow.com/a/51762055
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90482931
has body: I'm trying to drop all the columns in a pandas dataframe, except for these few, but when I run this code all the columns are dropped. The dataset is so big, that it would be tedious to list them all, any ideas?: for columns in df: if not columns == 'Carbohydrates' or columns == 'Description' or columns == '1st Household Weight' or columns == 'Sugar Total' or columns == 'Kilocalories': df = df.drop(columns, axis = 1)
accepted answer: http://stackoverflow.com/a/51762055
tagged with: pandas
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/45846189
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51762049
has comment: http://stackoverflow.com/comment/90482870
duplicate of: http://stackoverflow.com/q/45846189
has answer: http://stackoverflow.com/a/51762049
has title: Dropping Columns in python pandas
has comment: http://stackoverflow.com/comment/90482858

http://stackoverflow.com/a/51728151
score: 0
has body: Found the source of the error: string.capwords was being run on the setter of the property I was trying to assign this value to, which messed up the encoding. That explains the difference with the example code I posted originally..
type: Answer
answers question: http://stackoverflow.com/q/51709842

http://stackoverflow.com/comment/90442162
type: Comment
score: 1
has text: thanks for you help that seems to work can you recommend any place where i can learn more about selenium?
type: AnswerComment
comment on: http://stackoverflow.com/a/51739643

http://stackoverflow.com/comment/90546142
has text: # execute SQL query using execute() method. ConnectFirm_table = prod_cursor.execute("select * from beta2_Common.ConnectFirm where FirmId = " + prod_source_firm + ";") data = prod_cursor.fetchall() for row in data: ConnectFirmId = row[1] ConnectFirmName = row[2] FirmId = row[3] isDeleted = row[4] tags = row[5] createdDate = row[6] createdBy = row[7] editedDate = row[8] editedBy = row[9]
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51793052

http://stackoverflow.com/comment/90322191
score: 0
type: QuestionComment
has text: Welcome to Stack Overflow. Please read the [How to Ask](https://stackoverflow.com/help/how-to-ask) page before posting
comment on: http://stackoverflow.com/q/51679457
type: Comment

http://stackoverflow.com/q/51700018
has answer: http://stackoverflow.com/a/55591578
has answer: http://stackoverflow.com/a/51700041
has body: I am new to python and I am trying to make a simple stock market program using pandas to import the data. I have installed Anaconda which said that it installed pandas along with it, as well as Python 2.7. I use PyCharm as my IDE. When I run: import pandas as pd from pandas_datareader import data I receive the error message import pandas as pd ImportError: No module named pandas I am not sure why it is giving me this error message so any help would be greatly appreciated
type: Question
has answer: http://stackoverflow.com/a/51700206
tagged with: pandas
score: 3
linked to: http://stackoverflow.com/q/38061426
downvote count: 0
has title: No module named pandas
favorite count: 0
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51700077
tagged with: python
has comment: http://stackoverflow.com/comment/90362102
has answer: http://stackoverflow.com/a/56151494
has comment: http://stackoverflow.com/comment/90361366
upvote count: 3

http://stackoverflow.com/q/51748727
downvote count: 0
has answer: http://stackoverflow.com/a/51749408
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90457975
upvote count: 1
tagged with: django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51749408
score: 1
has comment: http://stackoverflow.com/comment/90457360
has title: How to set Model property, toggle a boolean in Django query?
type: Question
has body: Is it possible in my Detail view below, to set the boolean within a model to be false ? I looked through the django documentation (queryset) for something like a .set() method for this, it seems to exist but not applicable to this particular case. How can I toggle the unread boolean in my Models.py, through my view ? Also, what am I misunderstanding here and what is the better/appropriate way to do this ? Models.py: class Message(models.Model): recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'recipient',null = True) sender = models.ManyToManyField(CustomUser,related_name = 'messages') date = models.DateTimeField(auto_now_add=True, blank=True) subject = models.CharField(max_length = 1000, blank = True) message = models.TextField(blank=True, null=True) unread = models.BooleanField(default = True) Views.py : ### Message detail class class MessageInboxDetail(DetailView): ''' This view lets the user view the details of a message created ''' context_object_name = 'message_detail' model = Message template_name = "myInbox/message_detail.html" def get_context_data(self, **kwargs): context = super(MessageInboxDetail, self).get_context_data(**kwargs) context.update({ 'message_detail': Message.unread.set(False) }) # Message(unread=True/False) return context

http://stackoverflow.com/q/51679735
has body: I'm struggling to try and run gnu parallel. I have a shell script that calls a python program several thousand times with different input params: python /path/to/program/run.py A_02_01 input.fasta &gt; /path/to/output/out.txt python /path/to/program/run.py A_02_02 input.fasta &gt; /path/to/output/out.txt I tried using gnu parallel like so: cat iedb_classi_call.sh | parallel --recstart 'python' --recend '\n' --pipe bash But all my output files are empty. I'm struggling to figure out why. I'm not getting errors from gnu parallel. Before I added the recstart and recend options, I was getting non-empty output files for some python calls, but other program calls weren't executing and getting errors like: run.py: error: incorrect number of arguments bash: line 422: 01_ input.fasta: command not found Usage: run.py allele fasta_file Which made me think parallel was reading in chunks not separated properly and I added the --recstart / --recend parameters to parallel I'm using gnu parallel version 20180722
downvote count: 0
answer count: 1
score: 1
has title: gnu parallel --pipe producing empty output files
favorite count: 0
has comment: http://stackoverflow.com/comment/90324013
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90884804
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90324814
has comment: http://stackoverflow.com/comment/90324054
has answer: http://stackoverflow.com/a/51967504
tagged with: gnu-parallel

http://stackoverflow.com/comment/90390282
type: AnswerComment
comment on: http://stackoverflow.com/a/51714090
type: Comment
has text: No, i did so after your advice, but i have still the same failure, it seems like.
score: 0

http://stackoverflow.com/comment/90314144
type: AnswerComment
has text: error `AttributeError: 'StringMethods' object has no attribute 'unique' `
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51675274

http://stackoverflow.com/a/51739370
has comment: http://stackoverflow.com/comment/90438904
has comment: http://stackoverflow.com/comment/90446924
has comment: http://stackoverflow.com/comment/90438994
downvote count: 0
has comment: http://stackoverflow.com/comment/90438961
has comment: http://stackoverflow.com/comment/90439110
score: 1
has comment: http://stackoverflow.com/comment/90439179
accepted answer of: http://stackoverflow.com/q/51739255
answers question: http://stackoverflow.com/q/51739255
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You can use a @classproperty descriptor (similar to @property) if you don't want to use metaclasses. Here's a simple implementation of a classproperty decorator class classproperty(object): def __init__(self, fget): self.fget = classmethod(fget) def __get__(self, obj, owner): return self.fget.__get__(None, owner)() And some sample usage: class A(object): attr1 = 10 @classproperty def attr2(cls): return cls.attr1 + 10 class B(A): attr1 = 8991 And usage of that: &gt;&gt;&gt; A.attr1 10 &gt;&gt;&gt; A.attr2 20 &gt;&gt;&gt; B.attr2 9001 &gt;&gt;&gt; A().attr2 20 &gt;&gt;&gt; B().attr2 9001

http://stackoverflow.com/a/51696881
answers question: http://stackoverflow.com/q/51695911
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Since the question is tagged with matplotlib, you can do the complete GUI with it. For the input you may use a matplotlib.widgets.TextBox and evaluate some expression with the numbers of the textboxes. import matplotlib.pyplot as plt from matplotlib.widgets import TextBox import numpy as np fig, ax = plt.subplots() ax.set_title("Plot $Ax^2 + Bx + C$") kws = dict(color='.95', hovercolor='1', label_pad=0.01) axA = fig.add_axes([0.7,.9,.05,.05]) txA = TextBox(axA, "A: ", initial='2', **kws) axB = fig.add_axes([0.8,.9,.05,.05]) txB = TextBox(axB, "B: ", initial='2', **kws) axC = fig.add_axes([0.9,.9,.05,.05]) txC = TextBox(axC, "C: ", initial='2', **kws) line, = ax.plot([]) def update(arg=None): A = float(txA.text) B = float(txB.text) C = float(txC.text) x = np.linspace(-4,4) y = A*x**2 + B*x + C line.set_data(x,y) ax.relim() ax.autoscale_view() fig.canvas.draw_idle() txA.on_submit(update) txB.on_submit(update) txC.on_submit(update) update() plt.show()

http://stackoverflow.com/a/51662004
accepted answer of: http://stackoverflow.com/q/51660066
answers question: http://stackoverflow.com/q/51660066
type: Answer
score: 1
has body: Using np.where with .any not any(..) np.where((df.iloc[:,1:4].isin(code_flags)).any(1),1,0)
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/118684872
type: AnswerComment
has text: Thansk for actually telling I had to comment `db.create_all()`.
comment on: http://stackoverflow.com/a/59986736
type: Comment
score: 7

http://stackoverflow.com/a/51691325
has body: Syntax of SQL needs some correction. VARCHAR should have length limit Try this DELIMITER $$ CREATE FUNCTION extract_position_type_1(f_str VARCHAR(500) ) RETURNS VARCHAR(500) BEGIN DECLARE pstr VARCHAR(1600); SET pstr = SUBSTRING(f_str, '|', 4); RETURN pstr; END
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51690943
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51690943

http://stackoverflow.com/comment/90425706
type: Comment
score: 0
has text: your second solution is working perfectly, thank you! I am far from any sort of Python expert, so this is a good learning bit for me.
comment on: http://stackoverflow.com/a/51720093
type: AnswerComment

http://stackoverflow.com/comment/90571152
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51801449
has text: Sorry, I do not know rewrite, and it just made me more confused
type: Comment

http://stackoverflow.com/a/51673934
has body: Just using sum df.sum(level=[0,1],axis=1) Out[14]: year 2016 2017 quater 3 4 1 2 A 0.16 2.32 1.60 1.16 B 0.88 1.44 1.84 1.87 C 0.79 0.88 1.89 2.21
has comment: http://stackoverflow.com/comment/90310743
downvote count: 0
answers question: http://stackoverflow.com/q/51673220
type: Answer
has comment: http://stackoverflow.com/comment/90311185
accepted answer of: http://stackoverflow.com/q/51673220
has comment: http://stackoverflow.com/comment/90311306
score: 5
type: AcceptedAnswer
upvote count: 5
has comment: http://stackoverflow.com/comment/90310793

http://stackoverflow.com/comment/90286063
score: 1
has text: As an aside, the signature should be `__init_subclass__(cls, **kwargs)` and you should be calling `super().__init_subclass__(**kwargs)` at the end of your method. This lets you subclass from multiple parents while respecting their `__init_subclass__` methods.
comment on: http://stackoverflow.com/q/51660663
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90461972
score: 0
type: Comment
type: QuestionComment
has text: Or https://stackoverflow.com/questions/36253182/python-dict-fromkeys-generates-copies-of-list-instead-of-a-new-one
comment on: http://stackoverflow.com/q/51751074

http://stackoverflow.com/comment/90468838
type: Comment
type: QuestionComment
score: 1
has text: and what is your question?
comment on: http://stackoverflow.com/q/51754578

http://stackoverflow.com/q/51737752
score: 1
type: Question
has body: I have a text file with text that looks like this: (49) Sat Jun/30 21:00 Uruguay 2-1 (1-0) Portugal @ Fisht Stadium, Sochi (UTC+3) [Edinson Cavani 7', 62'; Pepe 55'] I have to implement a generator function that extracts data from each line of text according to these rules -read from the input file the 2 lines of text for one game -use 2 regular expressions (1 for each line) to extract the data (color coded here) for one Game object -pass back the data (Note that the extracted data are passed back, don't pass back a Game object) I can extract 1 data value, but I'm having trouble with extracting 5 data values(Game Number, Country1/2, Score1/2) from a line of text with just one regular expression.
answer count: 1
has comment: http://stackoverflow.com/comment/90436267
has comment: http://stackoverflow.com/comment/90436054
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90435985
downvote count: 0
type: UnansweredQuestion
has title: Confused on how to extract multiple data values with a single regular expression
has answer: http://stackoverflow.com/a/51737968

http://stackoverflow.com/q/51664477
has answer: http://stackoverflow.com/a/51778524
score: 2
downvote count: 0
tagged with: google-translate
has title: How to translate a Pandas Series in Python using googletrans?
type: AnsweredQuestion
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51778524
type: Question
upvote count: 2
answer count: 1
has body: I wish to translate a pandas column of text from Bahasa Indonesia to English, and add this translate text as a new column called 'English' in my data frame. Here is my code: from googletrans import Translator translator = Translator() df['English'] = translator.translate(df['Review to Translate'], src='id', dest='en') However, I get this error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-81-0fd41a244785&gt; in &lt;module&gt;() 2 3 translator = Translator() ----&gt; 4 y['Review in English'] = translator.translate(y['Review to Translate'], src='id', dest='en') ~/anaconda3/lib/python3.6/site-packages/googletrans/client.py in translate(self, text, dest, src) 170 171 origin = text --&gt; 172 data = self._translate(text, dest, src) 173 174 # this code will be updated when the format is changed. ~/anaconda3/lib/python3.6/site-packages/googletrans/client.py in _translate(self, text, dest, src) 73 text = text.decode('utf-8') 74 ---&gt; 75 token = self.token_acquirer.do(text) 76 params = utils.build_params(query=text, src=src, dest=dest, 77 token=token) ~/anaconda3/lib/python3.6/site-packages/googletrans/gtoken.py in do(self, text) 179 def do(self, text): 180 self._update() --&gt; 181 tk = self.acquire(text) 182 return tk ~/anaconda3/lib/python3.6/site-packages/googletrans/gtoken.py in acquire(self, text) 145 size = len(text) 146 for i, char in enumerate(text): --&gt; 147 l = ord(char) 148 # just append if l is less than 128(ascii: DEL) 149 if l &lt; 128: TypeError: ord() expected a character, but string of length 516 found Does anyone know how I can go about resolving this? I have a pretty large pandas df.

http://stackoverflow.com/comment/90385273
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51710573
score: 0
has text: You are the best. Thank you very much! This fixed my problem. Can't add you feedback, but would do it if I could!

http://stackoverflow.com/q/51675577
type: Question
has body: I am attempting to modify an open-source python script to accept strings instead of integers. the following is the original python code: def request(self, value): packet='' if self.domain: packet+=self.data[:2] + "\x81\x80" packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00' packet+=self.data[12:] packet+='\xc0\x0c' packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' packet+=str.join('',map(lambda x: chr(int(x)), value.split('.'))) This works for integers and no errors appear. I want to modify it to use strings instead of packets so i have tried to modify the int to str like follows: def request(self, value): packet='' if self.domain: packet+=self.data[:2] + "\x81\x80" packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00' packet+=self.data[12:] packet+='\xc0\x0c' packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' packet+=str.join('',map(lambda x: chr(str(x)), value.split('.'))) return packet However when i input a string as the value of the value parameter i receive the following error: Traceback (most recent call last): File "test.py", line 39, in &lt;module&gt; udps.sendto(p.request(value), addr) File "test.py", line 25, in request packet+=str.join('',map(lambda x: chr(str(x)), value.split('.'))) File "test.py", line 25, in &lt;lambda&gt; packet+=str.join('',map(lambda x: chr(str(x)), value.split('.'))) TypeError: an integer is required How can I modify line 25 to accept strings and not just integers? I still require the string join function.
tagged with: python-2.7
score: 0
has title: TypeError: integer required occuring when sending packet
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/90314326
favorite count: 0
tagged with: packet
type: UnansweredQuestion
tagged with: python
tagged with: integer
has comment: http://stackoverflow.com/comment/90314374
has answer: http://stackoverflow.com/a/51675640
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/51721491
has body: Didn't you installed opencv via terminal? For example, like this. $ pip install opencv-python $ pip install opencv-contrib-python When I installed opencv through terminal, experienced the same problem. If so, please try this. 1.Create new Pycharm Project, with new environment using Virtualenv. 2.Install opencv through Pycharm. File -> Settings... -> Project interpreter -> +
type: Answer
answers question: http://stackoverflow.com/q/51720624
has comment: http://stackoverflow.com/comment/90403681
score: 0

http://stackoverflow.com/comment/90396902
comment on: http://stackoverflow.com/q/51717920
has text: so you want to convert `1.13B` to `1.13e9`? where you got stuck?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51788300
has body: Buy use Google Analytics API (V4) I would like to upload file "Product Data" This is the sample code from GA Documentation from apiclient.http import MediaFileUpload try: media = MediaFileUpload('custom_data.csv', mimetype='application/octet-stream', resumable=False) daily_upload = analytics.management().uploads().uploadData( accountId='123456', webPropertyId='UA-123456-1', customDataSourceId='9876654321', media_body=media).execute() except TypeError, error: # Handle errors in constructing a query. print 'There was an error in constructing your query : %s' % error except HttpError, error: # Handle API errors. print ('There was an API error : %s : %s' % (error.resp.status, error.resp.reason)) This is What I ahve done, but I still have an issue regarding this part - analytics.management().uploads() import argparse from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials import httplib2 from oauth2client import client from oauth2client import file from oauth2client import tools from googleapiclient.http import MediaFileUpload # SET VARS CUSTOM_DATA_SOURCE_ID='_xxxxxxx' WEB_PROPERTY_ID='UA-xxxxx-1' ACCOUNT_ID='xxxxxx' CSV_IMPORT_FILE_LOCATION='test_file.csv' CREDENTIALS_KEY_FILE_LOCATION='key.json' def get_service(api_name, api_version, scope, key_file_location): credentials = ServiceAccountCredentials.from_json_keyfile_name( key_file_location, scopes=scope) http = credentials.authorize(httplib2.Http()) # Build the service object. service = build(api_name, api_version, http=http) return service def uploadCSV(service): try: media = MediaFileUpload(CSV_IMPORT_FILE_LOCATION, mimetype='application/octet-stream', resumable=False) daily_upload = service.management().uploads().uploadData( accountId=ACCOUNT_ID, webPropertyId=WEB_PROPERTY_ID, customDataSourceId=CUSTOM_DATA_SOURCE_ID, media_body=media).execute() except TypeError, error: # Handle errors in constructing a query. print 'There was an error in constructing your que…
upvote count: 1
tagged with: google-analytics-api
accepted answer: http://stackoverflow.com/a/51794307
tagged with: google-analytics
type: AnsweredQuestion
type: Question
downvote count: 0
has title: PYTHON - Google Analytics - Upload Product Data - THROUGH API
answer count: 1
favorite count: 0
tagged with: google-analytics-firebase
has answer: http://stackoverflow.com/a/51794307
tagged with: python
score: 1

http://stackoverflow.com/comment/90294125
type: QuestionComment
has text: `8 * getattr(ureg, input())` ?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51665498

http://stackoverflow.com/q/51642935
favorite count: 0
has answer: http://stackoverflow.com/a/51644142
upvote count: 2
tagged with: python
has title: Pandas: Group by combination of two columns
has answer: http://stackoverflow.com/a/51643085
type: AnsweredQuestion
score: 2
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51643311
accepted answer: http://stackoverflow.com/a/51643085
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51643311
has body: I have data as follows. The score column is the score of x vs y (which is equivalent to y vs x). from collections import Counter import pandas as pd d = pd.DataFrame([('a','b',1), ('a','c', 2), ('b','a',3), ('b','a',3)], columns=['x', 'y', 'score']) x y score 0 a b 1 1 a c 2 2 b a 3 3 b a 3 I want to evaluate the count of the score of each combination, so ('a' vs 'b) and ('b' vs 'a') should be grouped together, i.e. score x y a b {1: 1, 3: 2} c {2: 1} However if I do d.groupby(['x', 'y']).agg(Counter), ('a', 'b') and ('b', 'a') are not combined together. Is there a way to solve this? Thanks! score x y a b {1: 1} c {2: 1} b a {3: 2}

http://stackoverflow.com/comment/90551676
type: QuestionComment
comment on: http://stackoverflow.com/q/51797311
has text: Never fails, when you post on stack overflow 99/100 times you get hit with a [duplicate] or a related xD
score: 0
type: Comment

http://stackoverflow.com/comment/90530981
comment on: http://stackoverflow.com/q/51784897
type: Comment
type: QuestionComment
has text: Not quite optimistic regarding what? That it could work? With k-means you have to set the number of clusters before, not by some certain value in their neighbourhood. You could use a 2d convolution with a growing circular kernel, but this would only consider circular clusters well. I would start with k-means with a for loop over the number of clusters and check them using your sum criteria.
score: 0

http://stackoverflow.com/q/51753852
type: Question
has body: def create_model(input_shape, lr): model = Sequential() model.add(Dense(20, input_shape, 'relu')) opt = optimizers.Adam(lr) model.compile(loss='binary_crossentropy', optimizer=opt) return model clf = KerasClassifier(build_fn= create_model, input_shape=10,batch_size=25) list_of_learning_rates = [1e-3,1e-2] list_of_epochs = [50,100] gridSearch(clf, list_of_learning_rates, list_of_epochs) I wrote my own grid search code due to specific reason and it is written in a way that I have to initialize the classifier I am using and passed the classifier to the grid search function, with a list of parameters.The example is above. How do I specifically set the epochs and lr arguments within my gridSearch function? I am thinking of using functools.partial but I am not sure how, something along the line of: functools.partial(clf, lr=list_of_learning_rates[0], epcohs=list_of_epochs[0]), but clf is not a function so this does not work.
answer count: 1
tagged with: callable
tagged with: scikit-learn
tagged with: keras
score: 0
has answer: http://stackoverflow.com/a/51777973
tagged with: python
has title: How to set arguments of 'build_fn' of Keras's scikit learn API separately?
type: UnansweredQuestion

http://stackoverflow.com/q/51674712
score: 0
has title: Can't run file with sys.arg[1]
has comment: http://stackoverflow.com/comment/90312443
answer count: 1
linked to: http://stackoverflow.com/q/4117530
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90312405
has comment: http://stackoverflow.com/comment/90312389
has comment: http://stackoverflow.com/comment/90312362
has answer: http://stackoverflow.com/a/51674871
type: Question
has body: I'm working through https://testdriven.io/developing-an-asynchronous-task-queue-in-python . I've also taken a look at sys.argv[1] meaning in script for clarification on sys.argv From the former I have: def save_file(filename, data): random_str = uuid.uuid4().hex outfile = f'{filename}_{random_str}.txt' with open(os.path.join(OUTPUT_DIRECTORY, outfile), 'w') as outfile: outfile.write(data) def get_word_counts(filename): wordcount = collections.Counter() # get counts with open(os.path.join(DATA_DIRECTORY, filename), 'r') as f: for line in f: wordcount.update(line.split()) for word in set(COMMON_WORDS): del wordcount[word] # save file save_file(filename, json.dumps(dict(wordcount.most_common(20)))) # simulate long-running task time.sleep(2) proc = os.getpid() print(f'Processed {filename} with process id: {proc}') if __name__ == '__main__': print(sys.argv, len(sys.argv)) # print(sys.argv[1], len(sys.argv)) get_word_counts(sys.argv[1]) When I run it directly with I get: $ python tasks.py ['tasks.py'] 1 Traceback (most recent call last): File "tasks.py", line 46, in &lt;module&gt; get_word_counts(sys.argv[1]) IndexError: list index out of range Given that you can see there is only one element in the list, why did the author write the the code in this way?

http://stackoverflow.com/q/51692368
has comment: http://stackoverflow.com/comment/90348242
has answer: http://stackoverflow.com/a/51697978
tagged with: python-3.x
has title: KeyError: 'data' error in instagram script working with no issues on low numbers but not on numbers above 100-150
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90346205
has comment: http://stackoverflow.com/comment/90348261
has comment: http://stackoverflow.com/comment/90348205
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/90347302
downvote count: 0
has body: I have an Instagram script for generating the list of followers and unfollowers into separate excel files. It works on accounts having 50-60 or fewer followers and following but as soon as I use it on an account with 100+ followers/following it gives me the following error Traceback (most recent call last): File "insta-unfollower.py", line 229, in main() File "insta-unfollower.py", line 183, in main followers_list = get_followers_list() File "insta-unfollower.py", line 140, in get_followers_list for edge in response['data']['user']['edge_followed_by']['edges']: KeyError: 'data' Here is the function def get_followers_list(): followers_list = [] followers_post = { 'query_id': 17851374694183129, 'variables': { 'id': session.cookies['ds_user_id'], 'first': 60 } } followers_post['variables'] = json.dumps(followers_post['variables']) response = session.get(query_route, params=followers_post) response = json.loads(response.text) for edge in response['data']['user']['edge_followed_by']['edges']: followers_list.append(edge['node']) while response['data']['user']['edge_followed_by']['page_info']['has_next_page']: time.sleep(random.randint(5, 15)) followers_post = { 'query_id': 17851374694183129, 'variables': { 'id': session.cookies['ds_user_id'], 'first': 3, 'after': response['data']['user']['edge_followed_by']['page_info']['end_cursor'] } } followers_post['variables'] = json.dumps(followers_post['variables']) response = session.get(query_route, params=followers_post) response = json.loads(response.text) for edge in response['data']['user']['edge_followed_by']['edges']: followers_list.append(edge['node']) return followers_list here is the main function call def main(): if not os.environ.get('USERNAME') or not os.environ.get('PASSWORD'): sys.exit('please provide USERNAME and PASSWORD environement variables. Abording...') is_logged = login() if is_logged == False: sys.exit('login failed, verify user/password combination') time.sleep(random.randint(1, 3)) connected_user = get_us…
favorite count: 0
has comment: http://stackoverflow.com/comment/90346781
tagged with: instagram-api
tagged with: instagram
answer count: 1
has comment: http://stackoverflow.com/comment/90347165

http://stackoverflow.com/comment/90270479
score: 0
type: Comment
has text: Works perfectly,but I am getting `ID_` as a column how do I remove `_` from `ID` column?
type: AnswerComment
comment on: http://stackoverflow.com/a/51653415

http://stackoverflow.com/q/51707070
tagged with: python
has title: Python, Selenium and Chrome: cannot load page, because of "Not secure" warning
tagged with: selenium-chromedriver
score: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/90376793
tagged with: google-chrome
answer count: 1
type: UnansweredQuestion
has body: I am trying to automate a webpage through Python, Selenium and Chrome. The code is: import time from multiprocessing.dummy import Pool as ThreadPool from selenium.webdriver.chrome.options import Options from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType prox = Proxy() prox.proxy_type = ProxyType.MANUAL prox.http_proxy = "http://some-proxy.net:8090" capabilities = webdriver.DesiredCapabilities.CHROME prox.add_to_capabilities(capabilities) chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--disable-web-security') chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("--enable-automation") chrome_options.add_argument("--disable-save-password-bubble") chrome_options.add_argument("test-type") chrome_options.add_argument("start-maximized") chrome_options.add_argument("test-type=browser") chrome_options.add_argument("disable-infobars") chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') driver_path = 'M:/chromedriver/chromedriver.exe' driver = webdriver.Chrome(driver_path, chrome_options=chrome_options,desired_capabilities=capabilities) driver.get('https://somepage.csintra.net/') Chrome will open, but not load the page. Instead, I get the following "Not secure" warning displayed: As per code above, I have tried disabling various Chrome options gathered from various SO answers, but to no avail. I have also tried chrome_options.add_argument('--headless') as suggested here, but this causes the following error in chromedriver.exe: Failed to resolve service name: metrics As visible on the screenshot above, I also cannot unblock notifications, popups and location upon Selenium opening Chrome, since they are blocked by administrator - I am doing this at work (but anyway, in my Chrome settings "[*].csintra.net" is allowed to open popup…
has comment: http://stackoverflow.com/comment/90377127
linked to: http://stackoverflow.com/q/50642308
has answer: http://stackoverflow.com/a/60573348
type: Question

http://stackoverflow.com/comment/90381993
type: QuestionComment
has text: Oh I see. Thanks for the edit. I think any option is fine. Repeat the code (makes it obvious to the reader what you are doing) or make it clear that `Mammal` is an abstract class to by setting it's metaclass to `ABCMeta` (or subclass `ABC`)
comment on: http://stackoverflow.com/q/51710188
score: 0
type: Comment

http://stackoverflow.com/comment/132516387
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56758687
has text: Worked for me by installing missing conda in `problem_env` from base: `conda install --name problem_env conda`

http://stackoverflow.com/comment/90416839
score: 0
has text: What data structure is your `dataset`? It is a defaultdict, a pandas dataframe or something else?
type: Comment
comment on: http://stackoverflow.com/q/51728071
type: QuestionComment

http://stackoverflow.com/comment/90469507
comment on: http://stackoverflow.com/a/51741930
has text: Yes, I need to know how to show the frame durimg a specific time period.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51711880
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90387801
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90388270
tagged with: homebrew
tagged with: python
has comment: http://stackoverflow.com/comment/90385531
has comment: http://stackoverflow.com/comment/90387514
has body: MacOS Sierra 10.12.6 Python 3.7.0 there is a strange mystery with my mac: when doing something as simple as a brew install macvim I get the below popup The operation (brew install macvim) succeeds, but I keep getting these popups. I don't have parental controls enabled. $ ls -ld /usr/local/bin drwxrwxr-x 685 myuser admin 23290 Aug 6 12:21 /usr/local/bin File Permissions ... lrwxrwxr-x 1 myuser admin 34 Aug 6 11:03 /usr/local/bin/python3 -&gt; ../Cellar/python/3.7.0/bin/python3 lrwxrwxr-x 1 myuser admin 55 Aug 6 11:03 /usr/local/Cellar/python/3.7.0/bin/python3 -&gt; ../Frameworks/Python.framework/Versions/3.7/bin/python3 -rwxrwxr-x 1 myuser admin 13620 Aug 6 11:03 /usr/local/Frameworks/Python.framework/Versions/3.7/bin/python3.7 lrwxrwxr-x 1 myuser admin 9 Aug 6 11:03 /usr/local/Frameworks/Python.framework/Versions/3.7/bin/python3 -&gt; python3.7 -rwxrwxr-x 1 myuser admin 13620 Aug 6 11:03 /usr/local/Frameworks/Python.framework/Versions/3.7/bin/python3.7
has title: MacOSX Python3 Permissions
has comment: http://stackoverflow.com/comment/90387565
has comment: http://stackoverflow.com/comment/90385298
has comment: http://stackoverflow.com/comment/90388165
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90385283
tagged with: macos
favorite count: 0

http://stackoverflow.com/a/51654092
has body: You can use parameters marker and linestyle in plt.plot. You can experiment with marker, but if you want to omit lines, linestyle='none' is crucial here. plt.plot(df.x, df.y, marker='.', linestyle='none')
downvote count: 0
score: 20
answers question: http://stackoverflow.com/q/51654037
type: Answer
has comment: http://stackoverflow.com/comment/90274635
has comment: http://stackoverflow.com/comment/90274074
upvote count: 20
has comment: http://stackoverflow.com/comment/90272301

http://stackoverflow.com/q/51675151
has comment: http://stackoverflow.com/comment/90313248
has comment: http://stackoverflow.com/comment/90313303
has title: df ['X'].unique() and TypeError: unhashable type: 'numpy.ndarray'
type: Question
tagged with: group-by
has answer: http://stackoverflow.com/a/51675239
answer count: 3
tagged with: pandas
downvote count: 0
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/90313463
has comment: http://stackoverflow.com/comment/90313290
upvote count: 8
tagged with: python
has answer: http://stackoverflow.com/a/51675383
has comment: http://stackoverflow.com/comment/90313429
possible better answer: http://stackoverflow.com/a/51675274
accepted answer: http://stackoverflow.com/a/51675239
has comment: http://stackoverflow.com/comment/90313391
has answer: http://stackoverflow.com/a/51675274
type: AnsweredQuestion
has body: all, I have a column in a dataframe that looks like this: allHoldingsFund['BrokerMixed'] Out[419]: 78 ML 81 CITI 92 ML 173 CITI 235 ML 262 ML 264 ML 25617 GS 25621 CITI 25644 CITI 25723 GS 25778 CITI 25786 CITI 25793 GS 25797 CITI Name: BrokerMixed, Length: 2554, dtype: object Although the column is an object. I am not able to group by that column or even extract the unique values of that column. For example when I do: allHoldingsFund['BrokerMixed'].unique() I get an error uniques = table.unique(values) File "pandas/_libs/hashtable_class_helper.pxi", line 1340, in pandas._libs.hashtable.PyObjectHashTable.unique TypeError: unhashable type: 'numpy.ndarray' I also get an error when I do group by. Any help is welcome. Thank you

http://stackoverflow.com/comment/90521136
has text: data = data.replace('[','') using replace work. Thankyou very much.
comment on: http://stackoverflow.com/a/51781696
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51743618
accepted answer: http://stackoverflow.com/a/51743849
has title: Background Image not showing in program?
has comment: http://stackoverflow.com/comment/90447782
answer count: 1
downvote count: 0
favorite count: 0
has body: so I'm trying to get this image to load as a background when this class is displayed, however, my program just runs and no image is displayed. I'm new to python and coding in general so I'm probably doing something wrong that's easily fixable but yeah, thanks in advance! (Just some context, I'm making a Memory Game and if more code is needed just request away!) import tkinter as tk # imports tkinter as tk from tkinter import font as tkfont # imports font as tkfont import random import string import sys import time import pygame class SampleApp(tk.Tk): # class - Basically my Main hub def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.geometry("1024x576+155+60") self.title("Memory Mania") self.title_font = tkfont.Font(family='verdana', size=45, weight="bold", slant="italic") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (Login, MainMenu, Tutorial, Tutorial2, Difficulty, Settings, EasyDifficulty, MediumDifficulty, HardDifficulty, InsaneDifficulty,= EnterCharacterScreen, CorrectScreen, IncorrectScreen, Level2, WinGameScreen): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("Login") def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() class Login(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent, bg="#2699C3") self.controller = controller background_image = tk.PhotoImage("giphy.gif") background_label = tk.Label(parent, image=background_image) background_label.place(x=0, y=0, relwidth=1, relheight=1) background_label.image = background_image
tagged with: python-3.x
tagged with: tkinter
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51743849
type: Question
has comment: http://stackoverflow.com/comment/90448034

http://stackoverflow.com/comment/90565047
comment on: http://stackoverflow.com/a/51794707
has text: @YehudaKatz, consider accepting his answer, since it appears to [solve/answer your question](https://stackoverflow.com/help/someone-answers).
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90490638
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51766058
type: Comment
has text: where are the other months?

http://stackoverflow.com/comment/90270258
comment on: http://stackoverflow.com/q/51653379
has text: A useful read: https://realpython.com/python-modules-packages/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90725156
type: QuestionComment
has text: Please don't put the solution inside the question. If you found something that worked for you, please add it as an answer.
score: 0
comment on: http://stackoverflow.com/q/51718341
type: Comment

http://stackoverflow.com/comment/90347337
comment on: http://stackoverflow.com/q/51692872
has text: Consider giving a [minimal example](https://stackoverflow.com/help/mcve) code to play with.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51647301
downvote count: 0
has answer: http://stackoverflow.com/a/51657742
has title: How do PyMySQL prevent user from sql injection attack?
accepted answer: http://stackoverflow.com/a/51657742
type: Question
answer count: 1
tagged with: pymysql
score: 4
has body: Sorry for ask here but I cannot found much reference about pymysql's security guide about how do we prevent sql injection, When I do PHP develope I know use mysql preparedstatement(or called Parameterized Query or stmt),but I cannot found reference about this in pymysql simple code use pymysql like sqls="select id from tables where name=%s" attack="jason' and 1=1" cursor.execute(sqls,attack) How do I know this will prevent sql injection attack or not?if prevent succeed,how do pymysql prevent?Is cursor.execute already use preparedstatement by default?
tagged with: server-side-attacks
tagged with: sql-injection
has comment: http://stackoverflow.com/comment/90280392
favorite count: 0
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/90258217
type: AnsweredQuestion

http://stackoverflow.com/comment/90266634
comment on: http://stackoverflow.com/q/51651627
has text: have a look here, it could be useful for u ;) https://stackoverflow.com/questions/21350605/python-selenium-click-on-button/37279279#37279279
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51664618
has answer: http://stackoverflow.com/a/51664649
answer count: 4
type: AnsweredQuestion
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/51664761
accepted answer: http://stackoverflow.com/a/51664761
type: Question
has body: I have the following list of list: list_of_list = [["-", " ", "P"], ["-", " ", "L"], ["-", " ", "R"], ["K", "|", "K"], ["K", "|", "K"], ["I", " ", "-"], ["K", "|", "K"], ["-", " ", "K"], ["-", " ", "V"], ["-", " ", "D"], ["-", " ", "P"], ["-", " ", "K"], ["-", " ", "K"], ["-", " ", "D"], ["-", " ", "Q"], ["-", " ", "E"], ["A", "|", "A"], ["N", " ", "-"], ["-", " ", "K"], ["-", " ", "E"], ["R", "|", "R"], ["-", " ", "L"], ["-", " ", "K"], ["R", "|", "R"], ["S", " ", "-"], ["N", " ", "-"], ["S", " ", "-"], ["K", "|", "K"], ["-", " ", "I"], ["-", " ", "R"], ["K", "|", "K"], ["-", " ", "L"], ["-", " ", "E"]] Which looks like this: In [48]: list_of_list Out[48]: [['-', ' ', 'P'], # remove this ['-', ' ', 'L'], # remove this ['-', ' ', 'R'], # remove this ['K', '|', 'K'], ['K', '|', 'K'], ['I', ' ', '-'], ['K', '|', 'K'], ['-', ' ', 'K'], ['-', ' ', 'V'], ['-', ' ', 'D'], ['-', ' ', 'P'], ['-', ' ', 'K'], ['-', ' ', 'K'], ['-', ' ', 'D'], ['-', ' ', 'Q'], ['-', ' ', 'E'], ['A', '|', 'A'], ['N', ' ', '-'], ['-', ' ', 'K'], ['-', ' ', 'E'], ['R', '|', 'R'], ['-', ' ', 'L'], ['-', ' ', 'K'], ['R', '|', 'R'], ['S', ' ', '-'], ['N', ' ', '-'], ['S', ' ', '-'], ['K', '|', 'K'], ['-', ' ', 'I'], ['-', ' ', 'R'], ['K', '|', 'K'], ['-', ' ', 'L'], # remove this ['-', ' ', 'E']] # remove this As shown in the output above, what I want to do is to remove the element of the beginning and the end of the list. In the beginning, we remove all the lists where the 2nd element is empty until it finds |. In the end, we remove all the list after the last | found is empty. The desired output is this: [['K', '|', 'K'], ['K', '|', 'K'], ['I', ' ', '-'], ['K', '|', 'K'], ['-', ' ', 'K'], ['-', ' ', 'V'], ['-', ' ', 'D'], ['-', ' ', 'P'], ['-', ' ', 'K'], ['-', ' ', 'K'], ['-', ' ', 'D'], ['-', ' ', 'Q'], ['-', ' ', 'E'], ['A', '|', 'A'], ['N', ' ', '-'], ['-', ' ', 'K'], ['-', ' ', 'E'], ['R', '|', 'R'], ['-', ' ', 'L'], ['-', ' ', 'K'], ['R', '|', 'R'], ['S', ' ', '-'], ['N', ' ', '-'], ['S', ' …
tagged with: conditional-statements
possible better answer: http://stackoverflow.com/a/51664788
has answer: http://stackoverflow.com/a/51664788
has comment: http://stackoverflow.com/comment/90292581
has answer: http://stackoverflow.com/a/51664688
upvote count: 3
has title: How to remove element of list based on condition in the sublist
downvote count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51646238
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51646127
downvote count: 0
has body: You should use regex for this: import re string = "298 Anna salai Chennai 607106" string = re.sub(r'(\d+)$', r'TN \1', string) print(string) If you want to do repeated searching and replacing, you should compile the pattern first. import re string1 = "298 Anna salai Chennai 607106" string2 = "111 ABC 123456" pattern = re.compile(r'(\d+)$') repl = r'TN \1' string1 = re.sub(pattern, repl, string1) string2 = re.sub(pattern, repl, string2) print(string1) print(string2)

http://stackoverflow.com/comment/90330977
type: QuestionComment
comment on: http://stackoverflow.com/q/51684284
has text: You can try to increase recursion depth using [sys.getrecursionlimit](https://docs.python.org/3/library/sys.html#sys.setrecursionlimit). But do it carefully.
score: 0
type: Comment

http://stackoverflow.com/comment/90399268
has text: What have you tried so far? Please post your code.
score: 0
comment on: http://stackoverflow.com/q/51719225
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90506301
score: 0
type: Comment
has text: Just noticed your percentages do not add up to 100%, is thar correct?
type: QuestionComment
comment on: http://stackoverflow.com/q/51773655

http://stackoverflow.com/q/51780470
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/58391845
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/90518999
has answer: http://stackoverflow.com/a/51783725
tagged with: pandas
has comment: http://stackoverflow.com/comment/90518918
has title: Pandas: How to prepare a Multi-Label Dataset?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have function get_tags which returns a list of labels corresponding to a text: def get_tags(text): # Do some analysis and return a list of tags return tags E.g., get_tags(text1) returns ['a', 'b', 'c'] while get_tags(text2) returns ['a', 'b'] I also have a pandas DataFrame df with columns [text, a, b, c, d, e, f] having 500,000 rows. I want to fill 1's as labels to the text in a particular row. Right now, I am executing for i in range(len(df)): df.loc[i, get_tags(df.loc[i, "text"])] = 1 This is painfully slow. I can use joblib but before that I want to see the most efficient way to achieve this. Before execution, df looks like this: text a b c d e f 0 text having a, b, c tags 0 0 0 0 0 0 1 text having a, c tags 0 0 0 0 0 0 2 text having a, b, f tags 0 0 0 0 0 0 After the execution, it should look like this: text a b c d e f 0 text having a, b, c tags 1 1 1 0 0 0 1 text having a, c tags 1 0 1 0 0 0 2 text having a, b, f tags 1 1 0 0 0 1
has comment: http://stackoverflow.com/comment/90518922
type: Question

http://stackoverflow.com/q/51685860
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/90343379
downvote count: 1
linked to: http://stackoverflow.com/q/291978
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90333769
score: 1
has answer: http://stackoverflow.com/a/51692692
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90334323
has body: #campaign module for blunt wars import pygame import time import sys pygame.init() pygame.mixer.music.load("Library\Sound\Light.wav") size = [500, 500] width = size[0] height = size[1] #colors black = (0,0,0) white = (255,255,255) red = (200,0,0) green = (0,200,0) blue = (0,0,255) bright_red = (255,0,0) bright_green = (0,255,0) #end colors screen = pygame.display.set_mode((size), pygame.RESIZABLE) pygame.display.set_caption('Blunt Wars - Campaign') clock = pygame.time.Clock() Icon = pygame.image.load('Library\Image\Icon.png') pygame.display.set_icon(Icon) bg = pygame.image.load('bg.png') text = pygame.font.SysFont('Arial', 30) def text_objects(text, font): textSurface = font.render(text, True, black) # Create the text rect. textRect = textSurface.get_rect() # Return a tuple consisting of the surface and the rect. return textSurface, textRect def button(msg,x,y,w,h,ic,ac,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #print(click) if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(screen, ac,(x,y,w,h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(screen, ic,(x,y,w,h)) smallText = pygame.font.SysFont("comicsansms",20) textSurf, textRect = text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) screen.blit(textSurf, textRect) def intro(): intro = True #screen.fill(white) #screen.blit(bg, (0,0)) pygame.mixer.music.play(-1) hel = False while intro: screen.blit(bg, (0,0)) for event in pygame.event.get(): #print(event) if event.type == pygame.QUIT: pygame.quit() #quit() import Blunt_Wars if event.type == pygame.VIDEORESIZE: surface = pygame.display.set_mode((event.w, event.h),pygame.RESIZABLE) #screen.fill(blue) largeText = pygame.font.SysFont('Castellar',50) textSurf, textRect = text_objects("Blunt Wars - Campaign", largeText) textRect.center = ((700),(100)) screen.blit(textSurf, textRect) button("Start New",650,200,100,50,green,bright_green,game_loop) button("Load Save",650,3…
has title: Pygame Bool error when pressing a button
favorite count: 0
accepted answer: http://stackoverflow.com/a/51692692
has comment: http://stackoverflow.com/comment/90342407
has comment: http://stackoverflow.com/comment/90333735
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/90361480
type: Comment
comment on: http://stackoverflow.com/q/51698528
score: 0
has text: @Bryan Oakley Keeping the same layout on different sized monitors
type: QuestionComment

http://stackoverflow.com/comment/90288354
type: Comment
comment on: http://stackoverflow.com/q/51657192
has text: Everything from `first_row` down should be indented to the right a level. You're closing the file before you even loop through its rows.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51665444
favorite count: 0
has comment: http://stackoverflow.com/comment/90294107
tagged with: python
type: AnsweredQuestion
tagged with: binary
tagged with: list
type: Question
has comment: http://stackoverflow.com/comment/90294158
score: -1
has answer: http://stackoverflow.com/a/51665983
accepted answer: http://stackoverflow.com/a/51665983
has title: Update list of bit using while loop in python
downvote count: 2
upvote count: 1
has body: I have a list of bit. The problem is I need to update the value of the bit according to the new bit that I have. This is the example of my code: count=1 cycle=3 bit_list = ['1','0','1','0'] new_bit=['1','0','1'] no=''.join(bit_list) bit=''.join(new_bit) while (count&lt;=cycle): for b in no: print (b) print ("end of cycle", count) def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:] update=bin_add(no,bit) count=count+1 print ("updated list",update) I need the following output: 1 0 1 0 updated list 1011 #1010 + 1 end of cycle 1 1 0 1 1 updated list 1011 #1011 + 0 end of cycle 2 1 0 1 1 updated list 1100 #1011 + 1 end of cycle 3 Please help me to solve this problem. Thank you.
answer count: 1

http://stackoverflow.com/comment/90390814
score: 0
comment on: http://stackoverflow.com/q/51712989
type: QuestionComment
type: Comment
has text: OK -- updated. Thanks!

http://stackoverflow.com/a/51647699
has comment: http://stackoverflow.com/comment/90259680
has comment: http://stackoverflow.com/comment/90260480
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51647573
has comment: http://stackoverflow.com/comment/90259628
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/90260095
has body: You need to replace for el in elem: print elem.get_attribute("href") with for el in elem: print el.get_attribute("href") Note that elem is the list of WebElements while el is the single WebElement from elem list
has comment: http://stackoverflow.com/comment/90260142

http://stackoverflow.com/comment/90613655
type: Comment
has text: omg you were right since the beginning, "//ul[1]/li[8]/a[1]" is the correct xpath I cant believe i missed that
comment on: http://stackoverflow.com/a/51771086
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90472123
has text: first of all, do you know which version are you using to run your final code?
type: Comment
comment on: http://stackoverflow.com/a/51756182
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90419940
comment on: http://stackoverflow.com/q/51729217
type: Comment
type: QuestionComment
has text: @Jean-FrançoisFabre I have edited the question, please remove duplication as it is way more generalised than the linked post you've put.
score: 0

http://stackoverflow.com/q/51690439
has answer: http://stackoverflow.com/a/51690494
tagged with: python
has title: How to generate a heteroskedastic model in Python?
type: AnsweredQuestion
has body: I am looking to create heteroskedastic data in Python using Numpy. bias=100 N=10 X = np.arange(1,N,0.2).reshape(-1,1) y_true = np.ravel(X.dot(0.3) + bias) noise = np.random.normal(0, 1, (N-1)*5) y = y_true + noise I need each element in noise come from a normal distribution with a different variance for heteroskedasticity. Ideally the variances must be a function of the corresponding value of X. How to ensure this? np.random.normal accepts only scalar variance terms.
accepted answer: http://stackoverflow.com/a/51690494
type: Question
tagged with: numpy
tagged with: statistics
score: 0
answer count: 1

http://stackoverflow.com/comment/90319523
score: 0
type: Comment
has text: 2.0.4. It said this: `?: (2_0.W001) Your URL pattern 'tag/(?P<input_tag>\w+)$' [name='tag'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path().`
comment on: http://stackoverflow.com/a/51677848
type: AnswerComment

http://stackoverflow.com/a/51717550
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90396179
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51717535
has comment: http://stackoverflow.com/comment/90396194
answers question: http://stackoverflow.com/q/51717535
downvote count: 0
has comment: http://stackoverflow.com/comment/90396441
has body: Using pd.concat df1=df.groupby(['pid','year','month']).price.agg(['size','mean']).reset_index() df2=df.groupby(['pid','year']).price.agg(['size','mean']).assign(month='all').reset_index() df3=df.groupby(['pid']).price.agg(['size','mean']).assign(**{'month':'all','year':'all'}).reset_index() pd.concat([df1,df2,df3]) Out[484]: mean month pid size year 0 2450.000000 4 1 2 2017 1 2150.000000 4 1 2 2018 2 1995.000000 5 1 2 2018 3 2283.333333 6 1 3 2018 4 2150.000000 7 1 1 2018 0 2450.000000 all 1 2 2017 1 2161.250000 all 1 8 2018 0 2219.000000 all 1 10 all

http://stackoverflow.com/a/51722192
type: Answer
score: 2
downvote count: 0
has body: There are no time zones in Swatch Internet Time; instead, the new time scale of Biel Meantime (BMT) is used, based on Swatch's headquarters in Biel, Switzerland and equivalent to Central European Time, West Africa Time, and UTC+01. ref https://en.wikipedia.org/wiki/Swatch_Internet_Time But you can achieve this using following steps: 1) - Get the current time in UTC. (Now you dont need to be worried about server location and its time) 2) - Convert the that time to Zurich time, (Zurich time is UTC+2). 3) - Convert Zurich time to datetime.timetuple(). Previously, datetime.localtime was returning you the timetuple object of local time. from datetime import datetime from dateutil import tz def itime(): """Calculate and return Swatch Internet Time :returns: No. of beats (Swatch Internet Time) :rtype: float """ from_zone = tz.gettz('UTC') to_zone = tz.gettz('Europe/Zurich') time = datetime.utcnow() utc_time = time.replace(tzinfo=from_zone) zurich_time = utc_time.astimezone(to_zone) h, m, s = zurich_time.timetuple()[3:6] beats = ((h * 3600) + (m * 60) + s) / 86.4 if beats &gt; 1000: beats -= 1000 elif beats &lt; 0: beats += 1000 return beats print itime() Hope this helps :)
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51721018
answers question: http://stackoverflow.com/q/51721018

http://stackoverflow.com/q/51737488
tagged with: python
has answer: http://stackoverflow.com/a/51737555
linked to: http://stackoverflow.com/q/1373164
has body: In Python how do you split a string into variables when the number of variables depends on the input string. Ex.) I want to split " (1,2,3) (2,3,4) …" into two variables (a=123 b=234)... but if more groups were inputted more variables would be created.
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/90656037
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/1373164
type: UnansweredQuestion
has title: Python: splitting a string into variables

http://stackoverflow.com/a/51698714
accepted answer of: http://stackoverflow.com/q/51698569
has body: As mentioned in the comments, Coinbase Pro API is different from Coinbase API and you must change the package you are importing.
answers question: http://stackoverflow.com/q/51698569
type: Answer
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/51667646
has body: Here is some code that accomplishes what you have set up. It uses your if/else code and the same lists. It is also in a function for you and I show how to use it in the code: #The function: #Input array so function can return all lists def compare(array): #Assign values to specific arrays again g1 = array[0] w1 = array[1] ss1 = array[2] #Use length of one array as all are the same length count = 0 while count &lt; len(g1): if g1[count] == w1[count]: ss1[count] += g1[count]*2 else: w1[count] = -abs(g1[count] - w1[count]) ss1[count] += w1[count] #Count up till end of arrays count += 1 #Return modified arrays array[0] = g1 array[1] = w1 array[2] = ss1 return array How to use it: #Using the function: g1 = [2,0,1,1] w1 = [1,0,3,1] ss1 = [33, 45, 66, 54] #Put values in arary array = [g1, w1, ss1] print array #Prints: [[2, 0, 1, 1], [1, 0, 3, 1], [33, 45, 66, 54]] array = compare(array) print array #Prints: [[2, 0, 1, 1], [-1, 0, -2, 1], [32, 45, 64, 56]] #Putting array back into single arrays g1 = array[0] w1 = array[1] ss1 = array[2] print ss1 #Prints your desired output :D [32, 45, 64, 56]
type: Answer
answers question: http://stackoverflow.com/q/51667086
has comment: http://stackoverflow.com/comment/90298459
score: 0

http://stackoverflow.com/q/51645608
tagged with: python
score: 2
tagged with: mod-wsgi
type: Question
tagged with: apache
tagged with: centos
has body: I want apache to run django mod_wsgi and php application on one server. I have made changes in conf.d file below but its not working. ServerName api.temp.in #Django Application Require all granted ServerName web.temp.in ServerAlias web.temp.in DocumentRoot /var/www/html Currently both the domains are redirecting to api.temp.in(django/mod_wsgi) .Is it even possible with mod_wsgi ?
has title: Apache handling multiple domains with mod_wsgi
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51645733
has comment: http://stackoverflow.com/comment/90255198
favorite count: 0
has comment: http://stackoverflow.com/comment/90255243
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/90296842
type: QuestionComment
comment on: http://stackoverflow.com/q/51665654
type: Comment
has text: sorry, forgot to remove that import.
score: 0

http://stackoverflow.com/a/51765087
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90495566
answers question: http://stackoverflow.com/q/51762534
has body: You can use CTE. http://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.HasCTE.cte apply the limit: cte = session.query(Comment).filter(Comment.id &gt; 5).limit(3).cte() then reverse result = session.query(cte).order_by(cte.c.id.desc()).all()
downvote count: 0

http://stackoverflow.com/q/51775140
tagged with: loops
has answer: http://stackoverflow.com/a/51775226
has comment: http://stackoverflow.com/comment/90509079
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/17778372
linked to: http://stackoverflow.com/q/16996217
has body: I have a task to generate the prime factors of a number I input 396, I expect 2*2*3*3*11 back. I came up with an idea of recursion on a function that takes 2 arguments: the number and the result as a list. I expect the steps to be like this: (396, [empty]) (198,[2]) (99,[2,2]) (33, [2,2,3]) (11, [2,2,3,3]) (1, [2,2,3,3,11]) There we go, when the number reachs 1, it means the job is done, we take the list as a result. Here is my code in Python: import math def list_of_prime(x): filtered_list = list(range(2, x)) for i in range (2, int(round(math.sqrt(x), 0))): filtered_list = list(filter(lambda x: x == i or x % i, filtered_list)) return filtered_list def prime_factor(x,y): if (x-1) != 0: for i in list_of_prime(x): if x % i == 0: y.append(i) x = x // i print(x, y) prime_factor(x, y) return y prime_factor(396,[]) The result is 198 [2] 99 [2, 2] 33 [2, 2, 3] 11 [2, 2, 3, 3] 1 [2, 2, 3, 3, 11] 3 [2, 2, 3, 3, 11, 11] 33 [2, 2, 3, 3, 11, 11, 3] 11 [2, 2, 3, 3, 11, 11, 3, 3] 1 [2, 2, 3, 3, 11, 11, 3, 3, 11] 3 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11] 66 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3] 33 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2] 11 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3] 1 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11] 11 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11, 3] 1 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11, 3, 11] 6 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11, 3, 11, 11] 3 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11, 3, 11, 11, 2] 1 [2, 2, 3, 3, 11, 11, 3, 3, 11, 11, 3, 2, 3, 11, 3, 11, 11, 2, 3] It looks like working, but when x is 1, somehow x still pass the condition check, and the iterator 'i' actually goes from 2 to 11 after the first if, x &amp; i means 1 % 11 can't be 0, but it still got past the second inner if then got added to the list by "y.append(i)" line; hence I see the double '11' in the list. I have no idea how the rest of the result is generated. I ran visual studio code on Windows with Linux for windows enabled, I installed python thr…
answer count: 1
tagged with: python
score: 1
favorite count: 0
type: UnansweredQuestion
has title: Prime factors of a number in Python
upvote count: 1
linked to: http://stackoverflow.com/q/3939660
tagged with: recursion
has comment: http://stackoverflow.com/comment/90508953

http://stackoverflow.com/comment/91871655
type: Comment
comment on: http://stackoverflow.com/q/51640216
score: 0
type: QuestionComment
has text: So now the zip_longest issue is resolved, right? Making it work by switching to python3 makes sense as the method for python 2 is actually [`izip_longest`](https://docs.python.org/2.7/library/itertools.html#itertools.izip_longest). As for the `Malformed URL` I would suggest that you edit your question adding the complete stack trace to show where it's coming from.

http://stackoverflow.com/comment/90410290
has text: Hi @VegardKT, It Worked, Thanks for the quick response. But there is problem for me here. Some of the column has values { "ImageType": null, "ServiceType": null, "VMName": null, "VMProperties": null, "UsageType": "DataTrIn"} ( This is the entire column value) when i am doing the split(',') it is converting this single column into multiple . that is causing my data columns wrong. How can i get this through can you please help me on this.
comment on: http://stackoverflow.com/a/51724871
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90338210
comment on: http://stackoverflow.com/a/51671940
type: Comment
type: AnswerComment
has text: @noname please post whether this helped
score: 0

http://stackoverflow.com/comment/90379139
has text: i am corrected the for loop still facing the same error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51708715

http://stackoverflow.com/q/51784964
has title: Remove Emoji's from multilingual Unicode text
has answer: http://stackoverflow.com/a/73499715
linked to: http://stackoverflow.com/q/33404752
answer count: 3
tagged with: string
tagged with: unicode
possible better answer: http://stackoverflow.com/a/73499715
favorite count: 0
score: 8
has answer: http://stackoverflow.com/a/51785357
tagged with: python
accepted answer: http://stackoverflow.com/a/51785357
tagged with: regex
tagged with: emoji
type: AnsweredQuestion
has body: I'm trying to remove just Emoji from Unicode text. I tried the various methods described in another Stack Overflow post but none of those are removing all emojis / smileys completely. For example: Solution 1: def remove_emoji(self, string): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols &amp; pictographs u"\U0001F680-\U0001F6FF" # transport &amp; map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r'', string) Leaves in in the following example: Input: తెలంగాణ రియల్ ఎస్టేట్ Output: తెలంగాణ రియల్ ఎస్టేట్ Another attempt, solution 2: def deEmojify(self, inputString): returnString = "" for character in inputString: try: character.encode("ascii") returnString += character except UnicodeEncodeError: returnString += '' return returnString Results in removing any non-English character: Input: Testరియల్ ఎస్టేట్ A.P&amp;T.S. Output: Test A.P&amp;T.S. It removes not only all of the emoji but it also removed the non-English characters because of the character.encode("ascii"); my non-English inputs can not be encoded into ASCII. Is there any way to properly remove Emoji from international Unicode text?
downvote count: 1
has comment: http://stackoverflow.com/comment/90526896
type: Question
has comment: http://stackoverflow.com/comment/90527146
upvote count: 9
has answer: http://stackoverflow.com/a/51785859

http://stackoverflow.com/a/51732035
has comment: http://stackoverflow.com/comment/90424986
score: 0
accepted answer of: http://stackoverflow.com/q/51731972
has comment: http://stackoverflow.com/comment/90424972
answers question: http://stackoverflow.com/q/51731972
type: Answer
upvote count: 1
has body: Use str.findall, split is not necessary : y = df['Description'].str.findall('[0-9]{3}') But with some testing general solution is a bit complicated: df = pd.DataFrame({'Description':['354 64 133 5867 4 te345', 'rt34 3tyr 456', '23 gh346h rt 9404']}) print(df) Description 0 354 64 133 5867 4 te345 1 rt34 3tyr 456 2 23 gh346h rt 9404 y = df['Description'].str.findall('(?:(?&lt;!\d)\d{3}(?!\d))') print (y) 0 [354, 133, 345] 1 [456] 2 [346] Name: Description, dtype: object
downvote count: 1
has comment: http://stackoverflow.com/comment/90426915
type: AcceptedAnswer

http://stackoverflow.com/comment/90475411
comment on: http://stackoverflow.com/a/51757491
type: AnswerComment
score: 0
has text: Thank you. Your version of the script runs successfully. This is my first python script. Its purely educational so password handling was not a priority but I do appreciate the tip. I'm assuming you are familiar with the targets here since you know its the default password. I'm curious about your choices to replace cmc_list with f and i with ip; also moving the [0] from the output definition to the print function.Why those choices?
type: Comment

http://stackoverflow.com/a/51742627
has body: If you can't find an element that is supposed to be in a page, I suggest you use view(response). It shows you how the scrapy see the page. In this case, if you use it by yourself, you can see that in fetched HTML, there is no price element. I set a normal user agent in the request and it worked properly request=scrapy.Request('https://in.finance.yahoo.com/quote/ZUO/key-statistics?p=ZUO', headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'}) fetch(request) response.xpath('//*[@id="quote-header-info"]/div[3]/div/div/span[1]').extract() Result: [u'27.40']
type: Answer
answers question: http://stackoverflow.com/q/51734628
score: 0

http://stackoverflow.com/a/51644989
type: Answer
score: 0
has body: I think first you have to understand what's the meaning if one of the objects is None. There are basically three scenarios: One or both objects are None One or both objects does not have sound attribute Both have sound attribute For #1, I'm assuming it should throw an error as there is really no comparison. What your code does is print "Yes they do" if both objects are None. For #2, you can use what ShadowRanger suggests, If both objects have None as sound property, and your think it is a normal behavior, then use ShadowRanger's solution. For #3, just do your normal comparison def do_animals_make_same_sound(first_animal, second_animal): if not first_animal or not second_animal: print("One of the objects is None") elif getattr(first_animal, 'sound', None) == getattr(second_animal, 'sound', None): print("Yes, they do!")
answers question: http://stackoverflow.com/q/51644738

http://stackoverflow.com/q/51771741
possible better answer: http://stackoverflow.com/a/51773888
downvote count: 1
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51773888
has comment: http://stackoverflow.com/comment/90512444
has answer: http://stackoverflow.com/a/51772068
accepted answer: http://stackoverflow.com/a/51772068
type: Question
answer count: 2
has body: I am using R to perform a machine learning analysis and I came across this beautiful data visualization done with Python. I would like to replicate this in R. Is there a specific package in R that can achieve this? Or may be some online examples of the same visualizations with R.
favorite count: 0
tagged with: scatter-plot
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90502239
tagged with: data-visualization
tagged with: python
has title: What is the R equivalent package to achieve this scatterplot visualization between variables?
tagged with: correlation
upvote count: 3

http://stackoverflow.com/a/51797485
has comment: http://stackoverflow.com/comment/90559456
has comment: http://stackoverflow.com/comment/90574589
has comment: http://stackoverflow.com/comment/90572401
answers question: http://stackoverflow.com/q/51774662
score: 0
has body: From @WurzelseppQX's code , I have made a new code that prints a text as long as the button is kept pressed and will stop printing when the button is released. Here is the code: import pygame #importing pygame pygame.init() #initializing pygame width = 100 # width of window height = 100 #height of window pygame.display.set_mode((width, height)) # setting dimensions while True: tbreak = False # to break two loops for event in pygame.event.get(): #getting events if event.type == pygame.KEYDOWN: #see if a button is pressed if event.key == pygame.K_w: # if button is 'W' then while True: # making loop print("Key 'W' pressed") ev = pygame.event.get() #getting events to see if the user just released the key for e in ev: #looping the events if e.type == pygame.KEYUP: #if any key is released #You can also set specific keys tbreak = True #to break the outerloop break #breaking the inner loop if tbreak == True:break #breaking Now the above code blocks the rest of your game when the button is pressed. If you don't want your code to do this then use the following code: global topass topass = 0 def on_press(): #what to do on button press global topass print("Key 'W' pressed") topass = 1 while True: events = pygame.event.get() if len(events) == 0 and topass == 1:on_press() for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_w or topass == 1: on_press() if event.type == pygame.KEYUP: if event.key == pygame.K_w: topass = 0
has comment: http://stackoverflow.com/comment/90575146
type: Answer
has comment: http://stackoverflow.com/comment/90567596

http://stackoverflow.com/comment/90278581
has text: From README.TXT: *With Windows, it is recommended to use MSVC 201x or MinGW, with help of the CMake build system.* As for MacOS — why not, isn't it unixish enough?
type: Comment
comment on: http://stackoverflow.com/a/51654794
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90409107
type: Comment
score: 1
has text: @AndyBrown Thank you! Originally I tried this from the python console in Spyder from the Anaconda Navigator and shell=True did not make a difference there, so when I went over to try this within the CMD prompt, somehow I discarded this parameter altogether..
comment on: http://stackoverflow.com/q/51724247
type: QuestionComment

http://stackoverflow.com/comment/90491426
has text: are you getting an error or any other undesired behavior?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51764789

http://stackoverflow.com/comment/90552420
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51796611
has text: The correct computation is `(year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)`.
type: QuestionComment

http://stackoverflow.com/comment/90618191
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51736750
has text: Will do! Thanks for the advice :)
score: 0

http://stackoverflow.com/q/51789970
score: 0
has title: Display PIL.Image.image to bokeh hoovertool
answer count: 1
has answer: http://stackoverflow.com/a/51790408
type: UnansweredQuestion
tagged with: python
tagged with: bokeh
type: Question
tagged with: python-imaging-library
has body: Trying to displace images to Bokeh hoover pop-ups but could not see the images. The images are stored as PIL.Image.image in a pandas dataframe series The code is as shown source = ColumnDataSource(data=dict(x=tsne_pca[:,0], y=tsne_pca[:,1], desc=df['CAS'], color=df['Property'], imgs=df['images'])) hover = HoverTool(tooltips=""" @desc """ ) p = figure(plot_width=700, plot_height=700, title='T-SNE Molecule Display', tools=['reset,box_zoom,wheel_zoom,zoom_in,zoom_out,pan',hover]) p.circle('x', 'y', size=10, source=source, fill_alpha=0.2, line_color = linear_cmap('color', palette=[colors[0], colors[1]], low=min(y), high=max(y))) show(p) Also tried to decode the images to strings, but also could not see the images but only strings. Any suggestions? Thanks!

http://stackoverflow.com/comment/90470042
score: 0
type: QuestionComment
has text: provide a [mcve]
type: Comment
comment on: http://stackoverflow.com/q/51755187

http://stackoverflow.com/q/51657025
score: 2
has title: Flask - Having more than one static folder (the static folders are actually dynamic)
linked to: http://stackoverflow.com/q/9513072
type: Question
has comment: http://stackoverflow.com/comment/90278096
has body: Im currently working on a project that has the following structure: ROOT -js -dist -index.html -bunch of other files that index.html uses -src -main.py -doc_apps -app1 -index.html -other resources that index.html needs -app2 -index.html -other resources that index.html needs Now my flask configuration is: ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) COMPONENT_FOLDER = os.path.abspath(os.path.join(ROOT_DIR, '../')) DIST_FOLDER = os.path.join(COMPONENT_FOLDER, 'js\\dist') DOCUMENTATION_FOLDER = os.path.join(COMPONENT_FOLDER, 'documentation_data') app = Flask(__name__, static_folder=DIST_FOLDER, template_folder=DIST_FOLDER, static_url_path='') my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(DOCUMENTATION_FOLDER), ]) app.jinja_loader = my_loader @app.route('/') def index(): """ This the main entry to the application Returns ------- out renders the 'index.html' file """ return render_template('index.html') @app.route('/get_index_html', methods=['GET']) def get_index_html(): index_html_path = request.args.get('path') full_root = os.path.join(index_html_path).replace('\\','/') return render_template(full_root) When I start my app and go to the main page im able to render the index.html (the one in the js/dist folder) and everything works great the problem starts when I try to render one of the inner index.html. Im able to render the index.html by itself but I get the following errors 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/css/theme.css HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/pygments.css HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/js/modernizr.min.js HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/jquery.js HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/underscore.js HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/doctools.js HTTP/1.1" 404 - 127.0.0.1 - - [02/Aug/2018 18:08:43] "GET /_static/js/theme.js HTTP/1.1" 404 -…
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/90278725
favorite count: 0
tagged with: static
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51777082
has answer: http://stackoverflow.com/a/51777129
has comment: http://stackoverflow.com/comment/90512839
tagged with: string
favorite count: 0
tagged with: byte
has comment: http://stackoverflow.com/comment/90513390
tagged with: python
has comment: http://stackoverflow.com/comment/90512634
has comment: http://stackoverflow.com/comment/90512701
accepted answer: http://stackoverflow.com/a/51777148
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90512556
has comment: http://stackoverflow.com/comment/90512774
tagged with: netcdf
has title: Getting rid of the 'b' in front of Python strings
duplicate of: http://stackoverflow.com/q/606191
has comment: http://stackoverflow.com/comment/90512536
possible better answer: http://stackoverflow.com/a/51777129
downvote count: 1
has comment: http://stackoverflow.com/comment/90513007
type: Question
has answer: http://stackoverflow.com/a/51777148
upvote count: 5
score: 4
tagged with: python-3.6
answer count: 2
linked to: http://stackoverflow.com/q/606191
has body: EDIT: To save people the trouble of scrolling, the problem stemmed from the "decode" operation needing an output variable; my script failed to do this. I thought that the "for" loop would modify the variable in-situ, but this isn't the case. To make a long story short, I have some netCDF files from which I am generating a series of maps. The script for that works fine, but I am having major issues getting the title to display correctly. I get the variable from the netCDF file that will act as my title (a simple timestamp, basically). First I tried making it a Python variable, then using it as the plot title. Unfortunately, I have learned that it is what is known as a "bytes" string. Which means that the title has a bunch of lowercase 'b's in front of them. Not just one at the start. ie: b'T' b'i' b't' b'l' b'e' This is because the netCDF variable is a masked array. I managed to get some workable code to convert that array into a list, then into a string, and everything seemed like it would work. The linchpin of the entire thing, however, is the "bytes.decode()" operation. As far as I understand it, this operation takes in bytes objects, and then returns them as plain strings. Afaik, these are in utf-8, and I checked the type going in and found they were all classed as "bytes". Yet, when I attempt to use decode, it tells me that the objects are not bytes, literally moments after it told me they were? See code below and the output/error. Code: #check the type, shape, and data of times print(type(times)) print(times.shape) print(times.data) #change the times masked array to a list timeslist = times.tolist(fill_value=-9999) #check to see if elements of the list are bytes for x in timeslist: print(type(x)) #new list for decoded chars fixedtimeslist = [] #decode the bytes list for x in timeslist: bytes.decode('utf-8') fixedtimeslist.append(x) Output/Error: &lt;class 'numpy.ma.core.MaskedArray'&gt; (19,) [b'2' b'0' b'1' b'2' b'-' b'1' b'0' b'-' b'0' b'4' b'_' b'0' b'3' b':…
has comment: http://stackoverflow.com/comment/90512585

group-by
tags question: http://stackoverflow.com/q/51641558
tags question: http://stackoverflow.com/q/51675151
tags question: http://stackoverflow.com/q/51658976
tags question: http://stackoverflow.com/q/51732472
tags question: http://stackoverflow.com/q/51717620
tags question: http://stackoverflow.com/q/51678315
tags question: http://stackoverflow.com/q/51729647
tag name: group-by
tags question: http://stackoverflow.com/q/51692205
tags question: http://stackoverflow.com/q/51775601
type: Tag
tags question: http://stackoverflow.com/q/51733557
tags question: http://stackoverflow.com/q/51676880

http://stackoverflow.com/q/51679228
tagged with: python
has comment: http://stackoverflow.com/comment/90321630
tagged with: nlp
has body: I bumped into some code which uses the modulo operator in a way that I haven't seen before. The line in question is data_index = (data_index + 1) % len(data). I have no idea what this code is trying to do when it updates data_index: def generate_batch(batch_size, num_skips, skip_window): global data_index assert batch_size % num_skips == 0 assert num_skips &lt;= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window target skip_window ] buffer = collections.deque(maxlen=span) for _ in range(span): buffer.append(data[data_index]) # What is this doing? data_index = (data_index + 1) % len(data) # ... More stuff ...
has answer: http://stackoverflow.com/a/51679671
type: UnansweredQuestion
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/90322431
has title: python- modulo operator understanding
upvote count: 1
score: -2
answer count: 1
favorite count: 0
downvote count: 3

http://stackoverflow.com/q/51791616
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51791696
tagged with: python
has comment: http://stackoverflow.com/comment/90540688
tagged with: blackjack
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90540678
score: 0
has body: How can I make it print ace instead of 1, jack instead of 11, queen instead of 12 and king instead of 13, while playing the game, with the python program still working properly. Is there a way I can do this without changing too much. This is my code: import random dealer_cards = [] player_cards = [] while len(dealer_cards) != 2: dealer_cards.append(random.randint(1, 13)) if len(dealer_cards) == 2: print('The dealer has a hidden card and', dealer_cards[1]) while len(player_cards) != 2: player_cards.append(random.randint(1, 11)) if len(player_cards) == 2: print('You have the cards,', player_cards) if sum(dealer_cards) == 21: print('The dealer has the cards,', dealer_cards) print('The dealer has won because he has 21!') exit() if sum(player_cards) == 21 and sum(dealer_cards) == 21: print('draw') exit() elif sum(dealer_cards) &gt; 21: print('The dealer has the cards,', dealer_cards) print('The dealer has bust because he has over 21!') exit() while sum(player_cards) &lt; 21: choice = str(input('Choose twist or stick? ')) if choice == 'twist': player_cards.append(random.randint(1, 11)) print('You now have the cards,', player_cards) else: print('The dealer has the cards,', dealer_cards) print('You have the cards,', player_cards) if sum(dealer_cards) &gt; sum(player_cards): print('The dealer has won!') break else: print('You have won!') break if sum(player_cards) &gt; 21: print('You have bust because you are over 21!') elif sum(player_cards) == 21: print('You have won because you have 21')
tagged with: random
answer count: 1
favorite count: 0
has title: How can I make it print ace for 1, jack for 11, queen for 12 and king for 13 while playing the game

http://stackoverflow.com/comment/90345857
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51691560
has text: Oh, nice, I didn't know about `flat`. Thanks, will update!
type: Comment

http://stackoverflow.com/comment/90427640
type: QuestionComment
comment on: http://stackoverflow.com/q/51733483
has text: Did you reassign to the DataFrame?
score: 1
type: Comment

http://stackoverflow.com/a/51705576
has comment: http://stackoverflow.com/comment/90373421
has comment: http://stackoverflow.com/comment/90372780
has comment: http://stackoverflow.com/comment/90372896
has comment: http://stackoverflow.com/comment/90373014
type: Answer
has comment: http://stackoverflow.com/comment/90373197
has body: Yes, define your own custom loss function and pass that to the loss argument upon compiling: def custom_loss(y_true, y_pred): return (1-alpha) * K.mean(K.square(y_true-y_pred)) + alpha * gse (Not sure what you mean with gse). It can be helpful to have a look at how the vanilla losses are implemented in Keras: https://github.com/keras-team/keras/blob/master/keras/losses.py
has comment: http://stackoverflow.com/comment/90373109
score: 0
answers question: http://stackoverflow.com/q/51705464
has comment: http://stackoverflow.com/comment/90373270
has comment: http://stackoverflow.com/comment/90373520

http://stackoverflow.com/q/51667449
has answer: http://stackoverflow.com/a/51673857
tagged with: python
has title: matplotlib 2.2.2 maximize plot
type: AnsweredQuestion
has body: I am using matplotlib 2.2.2 Maximizing plot window not working after migrating to MPL 2.2.2. I cannot figure out how to overcome this on previous releases my code worked fine from matplotlib.pyplot import * import numpy as np if __name__ == '__main__': x=np.linspace(0,1,100) y=x**2 F1=figure() ax1=subplot(1, 1, 1) ax1.plot(x,y) F1.canvas.manager.window.showMaximized() show() I am getting the blow code and window is not maximized: "Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pydev\pydev_run_in_console.py", line 52, in run_file pydev_imports.execfile(file, globals, locals) # execute the script File "max_fig.py", line 12, in F1.canvas.manager.window.showMaximized() File "C:\IntelPython2\lib\lib-tk\Tkinter.py", line 1903, in getattr return getattr(self.tk, attr) AttributeError: showMaximized"
type: Question
has answer: http://stackoverflow.com/a/51669380
tagged with: matplotlib
linked to: http://stackoverflow.com/q/12439588
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51673857
accepted answer: http://stackoverflow.com/a/51669380

http://stackoverflow.com/q/51652640
downvote count: 1
type: Question
upvote count: 4
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51652683
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58313871
tagged with: python
has title: getting error: TypeError: object of type 'float' has no len() in pandas
has body: I have a pandas dataframe df import numpy as np import pandas as pd df = pd.DataFrame({"ID": [2,3,4,5,6,7,8,9,10], "type" :["A", "B", "B", "A", "A", "B", "A", "A", "A"], "F_ID" :["0", "[7 8 9]", "[10]", "0", "[2]", "0", "0", "0", "0"]}) # convert the string representations of list structures to actual lists F_ID_as_series_of_lists = df["F_ID"].str.replace("[","").str.replace("]","").str.split(" ") #type(F_ID_as_series_of_lists) is pd.Series, make it a list for pd.DataFrame.from_records F_ID_as_records = list(F_ID_as_series_of_lists) f_id_df = pd.DataFrame.from_records(list(F_ID_as_records)).fillna(np.nan) I am getting an error in the line: f_id_df = pd.DataFrame.from_records(list(F_ID_as_records)).fillna(np.nan) Error is: TypeError: object of type 'float' has no len() how can i solve this ?
score: 3

http://stackoverflow.com/comment/90287448
comment on: http://stackoverflow.com/q/51661980
type: Comment
type: QuestionComment
has text: Do the Boolean columns contain missing or blank cells?
score: 0

http://stackoverflow.com/a/67337151
score: 1
answers question: http://stackoverflow.com/q/51752890
upvote count: 1
type: Answer
has body: As @Luke mentioned, heartbeats are useful but if you still want to disable them, just set heartbeat parameter to zero when creating a connection. So, For URL parameters: connection = pika.BlockingConnection(pika.URLParameters("amqp://user:pass@127.0.0.1?heartbeat=0")) For Connection parameters: connection = pika.BlockingConnection(pika.ConnectionParameters(heartbeat=0))
downvote count: 0

http://stackoverflow.com/comment/90318323
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51677160
has text: @Quickbeam2k1 I think `df['Date'] != 'NaT'` works because by that point, that date is actually a string representation. The `.notnull()` doesn't seem to work, and I was getting NaT in my output. Thanks for the modern pandas link. I'll check it out.
score: 0

http://stackoverflow.com/comment/90474287
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51757402
score: 1
has text: What is `racadm_command % i` supposed to do that isn't already done?

http://stackoverflow.com/q/51725642
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-views
tagged with: django-models
type: Question
has body: I'm trying to use a huge request to minimize the number of requests in my app. In my database I have some cards, each card has multiple amounts link to it, and each amount is linked to a category. I try to get the Sum of amounts for a category between 2 dates and the same thing for 2 previous dates (dates are in cards) compare them and get the percentage evolution. Everything works fine for all cases but one: If my sum for a category is 0 for the previous period, I have an error "Divide by 0" when I try to calculate the evolution. So I tried to get the evolution, only if the sum of the previous period is != 0, and return 'N/A' if = 0. For this I use Case(When()). But I have an error and I'm not sure to understand why. Here my request: categories = Category.objects.filter( Q(amount__card__date__range=( start_day_compare, stop_day_compare )) | Q(amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare )) ).annotate( evolution=Case( When( Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) != 0, then=Value( ( ( Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ) - Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ) * 100 ) / Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ) ), default=Value('N/A'), output_field=CharField() ) ).order_by( 'order' ) And this is the error: init() takes either a Q object or lookups as keyword arguments This error is raised when I use previous_stop_day_compare the last time. Thanks a lot for your help
has title: Case() in Django return a Type error
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51726003

http://stackoverflow.com/q/51773930
tagged with: gunicorn
type: UnansweredQuestion
tagged with: python
has title: Making asynchronous HTTP requests from a flask service
linked to: http://stackoverflow.com/q/31866796
type: Question
score: 5
upvote count: 5
tagged with: flask
has answer: http://stackoverflow.com/a/51774321
has body: I have a couple different needs for asynchrony in my Python 3.6 Flask RESTful web service running under Gunicorn. 1) I'd like for one of my service's routes to be able to send an HTTP request to another HTTP service and, without waiting for the response, send a response back to the client that called my service. Some example code: @route def fire_and_forget(): # Send request to other server without waiting # for it to send a response. # Return my own response. 2) I'd like for another one of my service's routes to be able to send 2 or more asynchronous HTTP requests to other HTTP services and wait for them all to reply before my service sends a response. Some example code: @route def combine_results(): # Send request to service A # Send request to service B # Wait for both to return. # Do something with both responses # Return my own response. Thanks in advance. EDIT: I am trying to avoid the additional complexity of using a queue (e.g. celery).
answer count: 1
downvote count: 0
tagged with: asynchronous
favorite count: 0

http://stackoverflow.com/comment/90499047
type: Comment
has text: Btw request.args.get() retruns None if it is not able to get the value based on the key provided. Try updating your requests version
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51769981

http://stackoverflow.com/a/51753991
type: Answer
downvote count: 0
score: 6
has body: keys()doesn't work that way. keys() Return a new view of the dictionary’s keys Your nested dictionnary is a completely separate dict, and you can get its own keys with its own keys() method : entry[2]['N'].keys() If you want to recursively get all the keys inside nested dictionnaries, you will have to implement a method for that : entry = {0: {"Q": 0}, 1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, 2: {"N": { "Q":{"E"}}}, } def rec_keys(dictio): keys = [] for (key,value) in dictio.items(): if isinstance(value, dict): keys.extend(rec_keys(value)) else: keys.append(key) return keys print(rec_keys(entry)) # ['Q', 'Q', 'W', 'N', 'S', 'E', 'Q']
answers question: http://stackoverflow.com/q/51753809
upvote count: 6
has comment: http://stackoverflow.com/comment/90468098

http://stackoverflow.com/q/51693929
favorite count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/90353036
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51693991
tagged with: list
has answer: http://stackoverflow.com/a/51693953
has comment: http://stackoverflow.com/comment/90351615
upvote count: 1
type: Question
tagged with: indexing
possible better answer: http://stackoverflow.com/a/51693953
has answer: http://stackoverflow.com/a/51696215
has answer: http://stackoverflow.com/a/51693971
has title: how to write a function in python to sum up a given set of numbers other than itself?
has body: how to write a function in python to sum up a given set of numbers other than itself Input: An array of n integers nums, Output: An array output such that output[i] is equal to the sum of all the elements of nums except nums[i]. For example, given [1,2,3,4], return [9,8,7,6].
score: -1
accepted answer: http://stackoverflow.com/a/51693991

http://stackoverflow.com/q/51750855
possible better answer: http://stackoverflow.com/a/51751395
has answer: http://stackoverflow.com/a/51751395
has body: I have an array LiveTick = ['ted3m index','US0003m index','USGG3m index'] and I am reading a CSV file book1.csv. I have to find the row which contains the values in csv. For example, 15th row will contain ted3m index 500 | 600 and 20th row will contain US0003m index 800 | 900 and likewise. I then have to get the values contained in the row and parse it for each value contained in array LiveTick. How do I proceed? Below is my sample code: with open('C:\\blp\\book1.csv', 'r') as f: reader = csv.reader(f, delimiter=',') writer = csv.writer(outf) for row in reader: for list in LiveTick: if list in row: print ('Found: {}'.format(row))
has comment: http://stackoverflow.com/comment/90462367
tagged with: python
has answer: http://stackoverflow.com/a/51751325
type: AnsweredQuestion
type: Question
answer count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/90462251
accepted answer: http://stackoverflow.com/a/51751325
score: 0
tagged with: http://stackoverflow.com/tag/csv
has title: Need help in finding the row of CSV which contains the values in array

http://stackoverflow.com/a/51756370
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51756108
answers question: http://stackoverflow.com/q/51756108
has body: See this answer from GitHub. You need to use a CustomObjectScope to import relu6.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/90465257
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51752639
type: AnswerComment
has text: Note also that the `signal` being imported is from `/usr/lib/python3.6/unittest/signals.py`, and is not under my control. So the only choice is to manipulate `sys.path`?

http://stackoverflow.com/comment/90524604
score: 1
comment on: http://stackoverflow.com/q/51783734
has text: what is this trailing coma after `print p` ?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51733742
tagged with: python
has title: Keep x/y axes the same lengths in seaborn/matplotlib
has comment: http://stackoverflow.com/comment/90433145
tagged with: matplotlib
score: 7
upvote count: 7
type: Question
downvote count: 0
has body: I am generating some plots using matplotlib and seaborn, and the x-axis and y-axis are different lengths as shown in an example below. Is there a way to ensure that each axis is of the same scale? My example code is nothing special, but here is an example: # plot data plt.scatter(df['x'], df['y'], color = 'gray', s=5) # s controls point size plt.xlim(-0.0002,0.002) plt.ylim(-0.0002,0.002) # add y=x line plt.plot([0,1],[0,1], lw=2, color='#414242', linestyle='dashed') sns.set_context("paper", font_scale=1.5) plt.xlabel(xlabel, {'size':'20'}) plt.ylabel(ylabel, {'size':'20'}) plt.title(title) sns.set_style('ticks') sns.despine(offset=10, trim=True) plt.xticks(rotation=45) plt.tight_layout() plt.show() Using plt.axis('equal'):
answer count: 1
has answer: http://stackoverflow.com/a/51733804
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90532882
type: QuestionComment
has text: Try `import helpers; print(helpers.__file__)`. This may tell you where Python is looking.
comment on: http://stackoverflow.com/q/51787702
score: 5
type: Comment

http://stackoverflow.com/comment/90353042
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51692893
has text: @CertainPerformance Oh.. actually all I tried to know was finding out where the word 'Home Depot' located when I know what strings are behind it. The first thing came up to my mind was Regex, hence I gave it a shot. Is there any way that you can recommend for me?

http://stackoverflow.com/a/51796696
type: Answer
has body: You can use the following regular expression to obtain numbers assigned to names ending with 'id': import re text = '''var NotificationID = 7427580 var UserID = 1992''' print(re.findall(r'id\s*=\s*(\d+)', text, flags=re.IGNORECASE)) This outputs: ['7427580', '1992']
has comment: http://stackoverflow.com/comment/90550629
downvote count: 1
score: -1
upvote count: 0
accepted answer of: http://stackoverflow.com/q/51796658
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51796658

http://stackoverflow.com/q/51762277
upvote count: 1
has body: I've been trying to calculate historic mailchimp list subscribers count by using the API and can't find an accurate way. Obtaining current subscriber count is easy via getting list stats: Mailchimp list stats List Growth is only monthly: Mailchimp list Growth , I want to obtain/calculate daily. Tried using list activity: Mailchimp List activity but it doesn't add up to list growth for example unless I'm missing something/doing it wrong. Has anyone tried to do something similar and succeeded? Thanks P.S. I've been doing this with python, although it doesn't matter for my question
tagged with: mailchimp-api-v3.0
score: 1
tagged with: mailchimp
type: Question
has comment: http://stackoverflow.com/comment/95015733
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Mailchimp API - Daily historical subscribers count/calculations

http://stackoverflow.com/q/51688125
score: 2
tagged with: django-templates
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
type: Question
has title: How to remove the user if the activation link is not clicked before given time?
tagged with: django-views
tagged with: django-forms
downvote count: 0
favorite count: 0
tagged with: python
has body: I am trying to implement email verification based authentication system in my django app. What exactly I want is, the email link has to expire after sometime. Even though user clicks on it, the link should not work and the user should be deleted from the database. How to do that? forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password',] def clean_email(self): email = self.cleaned_data['email'] print('email cleaned data: ' + self.cleaned_data['email']) try: User.objects.get(email=email) raise forms.ValidationError('Email already exists.') except User.DoesNotExist: return email views.py : def register(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.is_active = False # username = form.cleaned_data['username'] # password = form.cleaned_data['password'] # user.set_password(password) user.save() # user = authenticate(username=username, password=password) # if user is not None: # if user.is_active: # login(request, user) # return render(request, 'set_goals/index.html') # context = { # "form": form, # } current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('registration/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) # email.send() user.email_user(mail_subject,message) return HttpResponse('Please confirm your email address to complete the registration') context = { "form": form, } return render(request, 'set_goals/register.html', context) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotE…

http://stackoverflow.com/comment/90499132
has text: What if you write `limit_choices_to = models.Q(audiobook__titolo=models.F('titolo'))`.
comment on: http://stackoverflow.com/q/51770237
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51650380
has body: With your Jquery's code, it will make an ajax to server $.post("/user", {user_id: selected}, function(){ window.location.href = "/user"; }); so, Flask can not redirect, if you edit code look like: $.post("/user", {user_id: selected}, function(data){ console.log(data); }); you will see Flask had returned HTML of the redirected page. Finally, I think this is help you: Flask: @app.route('/user/&lt;user_id&gt;') def userHasSelected(user_id): .... // I don't know why do you need this return redirect return redirect(url_for('user', user=request.form['action'])) JS: $("table tr").on("click",function() { var selected = $("td:first", this).text(); // {{url_for('user', user_id=selected)}} it will be rending from server window.location.href = {{url_for('user', user_id=selected)}} // or window.location.href = `/user?user_id=${selected}`; });
type: Answer
accepted answer of: http://stackoverflow.com/q/51649710
answers question: http://stackoverflow.com/q/51649710
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/106072189
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90370889
has text: Thankyou for your reply, but instead if i need to get all fields? how can i do it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51698666
score: 0

http://stackoverflow.com/a/51689000
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: According to the docs, to_hdf() uses h5py.File.create_dataset, and arguments are passed to it - i.e., it will append to an existing file/dataset by default. Alternatively, if you want more control over how to write your data, the example under .store() may be illuminating: &gt;&gt;&gt; import h5py &gt;&gt;&gt; f = h5py.File('myfile.hdf5') &gt;&gt;&gt; dset = f.create_dataset('/data', shape=x.shape, ... chunks=x.chunks, ... dtype='f8') &gt;&gt;&gt; store(x, dset) This does essentially the same thing, but you could create your file and dataset in any way convenient to you - store() merely requires something with a numpy array-like interface.
type: Answer
accepted answer of: http://stackoverflow.com/q/51687148
answers question: http://stackoverflow.com/q/51687148

http://stackoverflow.com/comment/90268789
comment on: http://stackoverflow.com/q/51652584
score: 0
type: QuestionComment
type: Comment
has text: {"B49":{ "Time":1533208501.720, "PacketID":2358, "Loss":0, "RSSI":-57, "MagnetometerX":[50.4,49.8,49.8,51,51.7,49.1,49.8,49.8,50.1,48.5], "MagnetometerY":[-10.1,-9.8,-9.8,-7.9,-11.4,-9.2,-9.8,-10.1,-9.5,-9.2], "MagnetometerZ":[-23.6,-21.2,-21.3,-20.9,-20.5,-22.4,-23.8,-23.4,-21.5,-23.9] }}

http://stackoverflow.com/comment/90391710
type: Comment
has text: The benchmark's time also include time for creating the test data. Might fix this later.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51714192

http://stackoverflow.com/a/51706096
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51704754
score: 1
accepted answer of: http://stackoverflow.com/q/51704754
upvote count: 1
has body: You have a number of problems here. First, you should create a cursor object from your connection and use that to execute your query: c = conn.cursor() c.execute(sql,var) Secondly, execute wants a tuple of values to interpolate, not a list, so do this: var = (link_ID,) c.execute(sql,var) Or: c.execute(sql,(link_ID,)) Lastly, c.execute returns the cursor object rather than the success of the query. You should fetch the result of the query using fetchone(), if your query didn't return a row then the return value of fetchone() will be None: result = c.fetchone() if result is not None: print('Success:',result) else: print('No row found for', link_ID)

http://stackoverflow.com/comment/90477272
type: Comment
comment on: http://stackoverflow.com/a/51718851
has text: you can follow this basic but official docs http://selenium-python.readthedocs.io/
score: 0
type: AnswerComment

http://stackoverflow.com/q/51787865
has answer: http://stackoverflow.com/a/51788067
has title: Arithmetic on a Series in Pandas DF With Conditional - Prior Operation Gets Overwritten
has comment: http://stackoverflow.com/comment/90533171
type: Question
tagged with: conditional-statements
upvote count: 2
tagged with: numpy
has body: I'm scraping some salary data that I need to convert to either and hourly or annual rate based on another column. I've researched how to do this - which probably isn't the most efficient - but it works for one line. Data import pandas as pd, numpy as np columns = ['Location','Hourly','Annually','Monthly','Daily','Average','Hourly_Rate','Annual_Rate'] df = pd.DataFrame(columns=columns) df.loc[1] = ['A',True,False,False,False,10.10,np.nan,np.nan] df.loc[2] = ['B',False,True,False,False,50000,np.nan,np.nan] df['Annual_Rate'] = (df['Average'] * 2080).where(df['Hourly'] == True) #need this line to run and not get overwritten df['Annual_Rate'] = df['Average'].where(df['Annually'] == True ) #overwrites prior line df['Annual_Rate'] = df['Average'].where(df['Annually'] == True &amp; pd.isna(df['Annual_Rate'])) #overwrites prior line and is incorrect df['Hourly_Rate'] = (df['Average'] / 2080).where([(df['Annually'] == True) &amp; (pd.isnull(df['Hourly_Rate']))]) df['Hourly_Rate'] = df['Average'].where(df['Hourly'] == True &amp; (pd.isna(df['Hourly_Rate']))) df['Hourly_Rate'] = df['Average'].where(df['Hourly'] == True) df.head(10) These are the lines that should be/I need to work: df['Hourly_Rate'] = (df['Average'] / 2080).where([(df['Annually'] == True) &amp; (pd.isnull(df['Hourly_Rate']))]) df['Annual_Rate'] = (df['Average'] * 2080).where(df['Hourly'] == True) Desired Outcome: +---+----------+--------+----------+---------+-------+---------+-------------+-------------+ | | Location | Hourly | Annually | Monthly | Daily | Average | Hourly_Rate | Annual_Rate | +---+----------+--------+----------+---------+-------+---------+-------------+-------------+ | 1 | A | TRUE | FALSE | FALSE | FALSE | 10.1 | 10.1 | 21008 | | 2 | B | FALSE | TRUE | FALSE | FALSE | 50000 | 24.03846154 | 50000 | +---+----------+--------+----------+---------+-------+---------+-------------+-------------+ Thanks in advance.
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51788067
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90533004

http://stackoverflow.com/comment/90252651
type: Comment
type: QuestionComment
has text: @RyanCyrus: The scenario with 50K sentences and 120 keywords is around the level at which Aho-Corasick (described in [my linked answer](https://stackoverflow.com/a/34820772/364696)) becomes likely to help, reducing 50K * 120 = 6M scans down to 50K scans at the small memory and precompute cost of building the Aho-Corasick automaton. But again, only do this is you think there is a high probability of actually encountering that sort of input size; taking external dependencies and complicating your code, even a little, isn't worth it unless testing shows simple code is too slow on *real* data.
score: 2
comment on: http://stackoverflow.com/q/51644051

http://stackoverflow.com/a/51745367
has comment: http://stackoverflow.com/comment/90456489
has comment: http://stackoverflow.com/comment/90456064
has comment: http://stackoverflow.com/comment/90458471
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90455932
has comment: http://stackoverflow.com/comment/90456566
has comment: http://stackoverflow.com/comment/90455567
has comment: http://stackoverflow.com/comment/90458093
type: Answer
has body: You have to tell TensorFlow that you wanna keep track of your loss. You're only adding the graph to the writer. For example, you can do this to track your loss: loss = ... (your def) tf.summary.scalar('MyLoss', loss) # ... maybe add some other variables (you can also make histograms, images, etc. via tf.summary.historam(...)) summ = tf.summary.merge_all() In your session, you can create the writer as you did. Then you have to eval the summary operation and add it to the writer. You should create the writer outside the training loop, however, as you don't want a writer for every iteration. You provide the iteration as argument in the add_summary method. saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter("outputLogs", sess.graph) for iteration in range(int(n_epochs*train_set_size/batch_size)): x_batch, y_batch = get_next_batch(batch_size) # fetch the next training batch [_, s] = sess.run([training_op, summ], feed_dict={X: x_batch, y: y_batch}) writer.add_summary(s, iteration) if iteration % int(5*train_set_size/batch_size) == 0: mse_train = loss.eval(feed_dict={X: x_train, y: y_train}) mse_valid = loss.eval(feed_dict={X: x_valid, y: y_valid}) print('%.2f epochs: MSE train/valid = %.10f/%.10f'%( iteration*batch_size/train_set_size, mse_train, mse_valid)) save_path = saver.save(sess, "models\\model"+str(iteration)+".ckpt") Your training code should look like this.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90479223
answers question: http://stackoverflow.com/q/51743705
accepted answer of: http://stackoverflow.com/q/51743705

http://stackoverflow.com/comment/90471032
comment on: http://stackoverflow.com/q/51753539
has text: Ok now it makes sense. Did you install the CLion Bazel plugin [here](https://plugins.jetbrains.com/plugin/9554-bazel) and followed the instructions [here](https://ij.bazel.build/docs/bazel-plugin.html). There is a workspace.bzl file in the root of the TF repository. If this doesn't get you going let me know and I will post a detailed step by step instructions.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51747498
downvote count: 0
has comment: http://stackoverflow.com/comment/90454713
score: 1
has body: You should use apply method instead (see doc): def your_function(row): if row['age']&lt;25 and row['Gender']==1: return 1 else: return 0 df['group'] = df.apply(your_function,axis=1)
upvote count: 1
answers question: http://stackoverflow.com/q/51747326
type: Answer

optimization
tags question: http://stackoverflow.com/q/51643726
tags question: http://stackoverflow.com/q/51722727
tags question: http://stackoverflow.com/q/51642745
tags question: http://stackoverflow.com/q/51773317
tags question: http://stackoverflow.com/q/51716404
tags question: http://stackoverflow.com/q/51763381
tags question: http://stackoverflow.com/q/51696853
tags question: http://stackoverflow.com/q/51659140
tags question: http://stackoverflow.com/q/51695617
tags question: http://stackoverflow.com/q/51715182
tags question: http://stackoverflow.com/q/51722860
tags question: http://stackoverflow.com/q/51690935
tags question: http://stackoverflow.com/q/51751032
tags question: http://stackoverflow.com/q/51772001
tag name: optimization
tags question: http://stackoverflow.com/q/51760980
tags question: http://stackoverflow.com/q/51697459
tags question: http://stackoverflow.com/q/51755054
tags question: http://stackoverflow.com/q/51723087
tags question: http://stackoverflow.com/q/51754268
tags question: http://stackoverflow.com/q/51714244
tags question: http://stackoverflow.com/q/51729619
type: Tag

gtk
tags question: http://stackoverflow.com/q/51755244
type: Tag
tag name: gtk

http://stackoverflow.com/q/51775578
type: Question
tagged with: split
score: 0
answer count: 2
tagged with: python
has body: I have a file with very very long string and need to split it using specific value for example #@#@ as my delimiter. After this value I need to move to the new line. I am having trouble to move to the next line and write to a new file.
has answer: http://stackoverflow.com/a/51776183
has title: Split using some value as delimiter and move the the next line (python)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/76296357
tagged with: line

http://stackoverflow.com/q/51684985
has comment: http://stackoverflow.com/comment/90333328
has comment: http://stackoverflow.com/comment/90332177
score: 0
has body: I am trying to login to a site which requires authendication and try to download a file my code: import requests site_url='https://www.example.com' userid='abc' password='abc123' resp = requests.get(site_url, auth=(userid, password)) but I am getting ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) please help.
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/90332113
has comment: http://stackoverflow.com/comment/90332197
type: UnansweredQuestion
tagged with: sockets
has title: unable to get response from a webpage using requests
tagged with: python
has comment: http://stackoverflow.com/comment/90332110
answer count: 0
has comment: http://stackoverflow.com/comment/90332132
has comment: http://stackoverflow.com/comment/90332764
has comment: http://stackoverflow.com/comment/90333307
tagged with: python-requests
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/90332095
has comment: http://stackoverflow.com/comment/90333520
has comment: http://stackoverflow.com/comment/90332166

http://stackoverflow.com/comment/90345483
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51691835
has text: `T1.insert("end", sep_list, 'recent')` attempts to insert a single-element list `sep_list` into `T`. The method `insert` expects the second parameter to be a _string_, not a list. Apparently, the curly braces is `insert`'s idea of how to handle the unexpected parameter. Pass `sep_list[0]` or some other string for best results.

http://stackoverflow.com/q/51760616
tagged with: python
tagged with: cffi
has answer: http://stackoverflow.com/a/51765281
accepted answer: http://stackoverflow.com/a/51765281
type: AnsweredQuestion
tagged with: fortran
has title: Calling a fortran dll from python using cffi
type: Question
tagged with: dll
has comment: http://stackoverflow.com/comment/90480660
has body: I am currently working on a simultion-tool that requires a PDE Solver from a Fortran dll. In order to figure how calling a dll from python I used a simpler function from the same dll but can't get it to work. Systemspecs: Windows 7 Professional (64bit) Spyder 3.2.8 Python 3.6.5 (32bit) I am now using cffi to call the fortran function but it doesn't work either. import cffi as cf ffi=cf.FFI() lib=ffi.dlopen("C:\Windows\SysWOW64\DLL20DDS") ffi.cdef(""" double S01BAF(double X, int IFAIL); """) print (lib) #This works print (lib.S01BAF) #This works x = 1. ifail = 0 print (lib.S01BAF(x,ifail)) #This doesn't work This is the code i am using to call the function with cffi. The dll i am loading contains the function S01BAF which i intend to call. The error message I recieve is: runfile('C:/Users/Student/Desktop/Minimal.py', wdir='C:/Users/Student/Desktop') &lt;cffi.api._make_ffi_library.&lt;locals&gt;.FFILibrary object at 0x0759DB30&gt; &lt;cdata 'double(*)(double, int)' 0x105BBE30&gt; Kernel died, restarting I don't know what that means. To check if the function itself is working I tryed calling it from a different language (VBA) and it worked just fine. Option Base 1 Option Explicit Private Declare Function S01BAF Lib "DLL20DDS.dll" (x As Double, iFail As Long) As Double Sub ln() Dim iFail As Long Dim x As Double Dim y As Double x = 1 iFail = 0 y = S01BAF(x, iFail) MsgBox y End Sub The messagebox displays the correct value for ln(2). I have read the previously asked questions but couldn't apply the answers to my problem. Here is the code that works thanks to @Joe! ffi=cf.FFI() lib=ffi.dlopen("C:\Windows\SysWOW64\DLL20DDS") ffi.cdef("double S01BAF(double *x, int *ifail);") x_1 = np.arange(-0.99,1,0.001) x = ffi.new('double*', 1) ifail = ffi.new('int*', 0) y = (lib.S01BAF(x,ifail)) Cheers, Thilo
score: 0
has comment: http://stackoverflow.com/comment/90488904
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/q/51770334
downvote count: 1
type: AnsweredQuestion
score: 1
type: Question
answer count: 1
has body: so i have this python code written which basically pulls data from an excel sheet using openpyxl and then fills an online web form using selenium. I managed to get the code working when it just pulls data from column B in the sheet but when I add the other columns for it to pull the data from i get this error: Traceback (most recent call last): File "/Users/John/Desktop/run3.py", line 103, in &lt;module&gt; main() File "/Users/John/Desktop/run3.py", line 76, in main first.send_keys(mrn) File "/Library/Python/2.7/site-packages/selenium-3.13.0- py2.7.egg/selenium/webdriver/remote/webelement.py", line 478, in send_keys {'text': "".join(keys_to_typing(value)), File "/Library/Python/2.7/site-packages/selenium-3.13.0- py2.7.egg/selenium/webdriver/common/utils.py", line 150, in keys_to_typing for i in range(len(val)): TypeError: object of type 'long' has no len() I have no idea where im going wrong or even what is producing this error. Here is the code that I have so far: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from tqdm import tqdm import openpyxl import datetime import Tkinter import tkFileDialog import time from time import sleep import re import sys #file selector* Tkinter.Tk().withdraw() file = tkFileDialog.askopenfilename() path = str(file) wk = openpyxl.load_workbook(path) print("Active Sheet: "+ wk.active.title) sh = wk['Sheet1'] #data select ro = raw_input("What is First Cell: ") m = re.sub("\D", "", ro) m2 = int(m) #Total rows and columns rows = sh.max_row - m2 + 1 columns = sh.max_column print("Total Rows: " + str(rows)) print("Total Columns: " + str(columns)) driver = webdriver.Chrome() driver.get("http://www.clickdimensions.com/form/default.html") driver.maximize_window() k2 = -1 def main(): global k2 global rows k2 = k2 + 1 for column in tqdm("B…
has comment: http://stackoverflow.com/comment/90499309
has answer: http://stackoverflow.com/a/51770377
tagged with: python
has title: Python object of type long has no Len() error?
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/51770377
tagged with: openpyxl
tagged with: selenium

http://stackoverflow.com/comment/90361646
type: Comment
has text: Hi @U9-Forward - Now Im reading the file with the output 16 16 011000 id N16 Online FC F-Port 51:40:2e:c0:01:c9:53:e8 26 26 011a00 id N16 Online FC F-Port 56:c9:ce:90:4d:77:c6:03 27 27 011b00 id N16 Online FC F-Port 56:c9:ce:90:4d:77:c6:07 32 32 012000 id N16 Online FC F-Port 51:40:2e:c0:01:c9:54:80 42 42 012a00 id N16 Online FC F-Port 56:c9:ce:90:12:b4:19:01 I want to write the word starting with 56 and not sure what to put end of line to select
comment on: http://stackoverflow.com/a/51644489
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90508099
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51774228
type: Comment
has text: Yes, and something else worth noting is that `key1` and `key2` are required whereas variables in kwargs are usually optional

http://stackoverflow.com/comment/90442278
comment on: http://stackoverflow.com/q/51741056
score: 0
type: QuestionComment
type: Comment
has text: `IndexError: list index out of range` means that the index you are trying to access does not exist. So, either `inputSamplesm[idx]`, `data[0]` or `data[1]` does not exist.

http://stackoverflow.com/comment/90273764
type: QuestionComment
has text: Usually this behaviour is caused by some kind of limit reached by the processes. It could be an open request limit, a open file limit, some wait/join got out of hand, there are really many possible reasons. The best procedure I could suggest you to find the culprit is to try and explore the code dichotomously, by deleting the code until this symptom disappears. If still you'll have not figure the error out, you'll have created a minimum example and we could help you out from there.
comment on: http://stackoverflow.com/q/51654991
score: 0
type: Comment

import
type: Tag
tags question: http://stackoverflow.com/q/51762565
tags question: http://stackoverflow.com/q/51657192
tags question: http://stackoverflow.com/q/51647436
tags question: http://stackoverflow.com/q/51767866
tags question: http://stackoverflow.com/q/51668735
tag name: import
tags question: http://stackoverflow.com/q/51786785
tags question: http://stackoverflow.com/q/51749218
tags question: http://stackoverflow.com/q/51731916
tags question: http://stackoverflow.com/q/51655771
tags question: http://stackoverflow.com/q/51717417
tags question: http://stackoverflow.com/q/51670059
tags question: http://stackoverflow.com/q/51776981

http://stackoverflow.com/q/51691417
tagged with: python
has answer: http://stackoverflow.com/a/51691477
tagged with: nlp
has body: I have a dataframe like this after some preprocessing. I want to create bigrams from each list in the dataframe rows. How I tried is given below. I get an error saying lambda row: list((map(ngrams(2), row)))) TypeError: ngrams() missing 1 required positional argument: 'n' What should be ngrams' first parameter here? How should I modify this code? Also I may be asking questions on my every function. But I am having a hard time understanding the lamda and map functions that I am using. Please explain me how I should apply lamda and map functions on this dataframe in the future? Dataframe [[ive, searching, right, word, thank, breather], [i, promise, wont, take, help, granted, fulfil, promise], [you, wonderful, blessing, time]] [[free, entry, 2, wkly, comp, win, fa, cup, final, tkts, 21st, may, 2005], [text, fa, 87121, receive, entry, questionstd, txt, ratetcs, apply, 08452810075over18s]] nah, dont, think, go, usf, life, around, though [[even, brother, like, speak, me], [they, treat, like, aid, patent]] [[i, date, sunday, will], []] What I need [(even, brother), (brother,like), (like,speak), (speak,me), (they, treat), (treat,like), (like,aid), (aid,patent)] What I tried def toBigram(fullCorpus): bigram = fullCorpus['lemmatized'].apply( lambda row: list((map(ngrams(2), row)))) return bigram
type: AnsweredQuestion
type: Question
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51691477
has title: Create bigrams from list of sentences in pandas dataframe

http://stackoverflow.com/q/51675432
has answer: http://stackoverflow.com/a/51675526
favorite count: 0
has title: "While" loop causing error while finding prime factors of a number. And can't use this program with high numbers
has body: Created a program to find prime factors of a natural number but i get an error: multipliers = [] a = 2 value = input("Put a natural number here: ") value = int(value) for i in range(1, value): if value % i == 0: multipliers.append(i) for x in multipliers: while a &lt; x: if x % a == 0: multipliers.remove(x) else: a += 1 print(multipliers) All I want to do here is: Get an input value, find the multipliers of a value and make a list from them, take theese multipliers 1 by 1 and try to divide by [2, 3, 4, 5...], if a is a multiplier of x delete it from the list and get another value from list as x and do the same. But when I try to run this i get an error message that says ValueError: list.remove(x): x not in list I don't know where am I doing wrong. Can you please help me?
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90313839
has comment: http://stackoverflow.com/comment/90314142
has comment: http://stackoverflow.com/comment/90314024
linked to: http://stackoverflow.com/q/1207406
type: AnsweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/1207406
accepted answer: http://stackoverflow.com/a/51675526
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90314282
tagged with: prime-factoring
answer count: 1

http://stackoverflow.com/comment/134680797
comment on: http://stackoverflow.com/a/51698241
type: Comment
has text: these aren't the same. The lambda function is returning a list containing x, i.e. [x] not a string with braces: '['+str(x)+']'.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51695976
tagged with: python
linked to: http://stackoverflow.com/q/51521655
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51705149
has body: I am using DataFrame to read in HDFS files and extracting the data using regular expressions. The column names are dynamically generated using an index and the column data type is created as string. Is it possible for me to re-define the schema of the DataFrame without renaming or casting the columns individually? My plan is to convert the DataFrame to RDD and convert the RDD back to DataFrame with a schema. I am not sure if this is a good idea.
has comment: http://stackoverflow.com/comment/90356865
type: Question
has answer: http://stackoverflow.com/a/51705149
tagged with: pyspark
score: 0
tagged with: apache-spark
has title: Spark 2 Python Rename columns and set columns data types
answer count: 1

http://stackoverflow.com/comment/90254195
type: QuestionComment
has text: What is `dld_tool`? It needs to be in the current working directory, or in the directory listed in the PATH environment variable. You could also use the full path to `dld_tool`.
score: 0
comment on: http://stackoverflow.com/q/51645086
type: Comment

http://stackoverflow.com/comment/90392985
type: AnswerComment
type: Comment
has text: It appears that Stack Overflow automatically changed my answer before I posted it. You should type pyperclip.copy("Type your text here")
comment on: http://stackoverflow.com/a/51715475
score: 0

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51777324
tags question: http://stackoverflow.com/q/51775531
tags question: http://stackoverflow.com/q/51719075
tags question: http://stackoverflow.com/q/51699746
tags question: http://stackoverflow.com/q/51777367
tags question: http://stackoverflow.com/q/51766208
tag name: wsgi

http://stackoverflow.com/q/51640114
type: Question
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90244854
has comment: http://stackoverflow.com/comment/90244954
has comment: http://stackoverflow.com/comment/90245682
has comment: http://stackoverflow.com/comment/90245686
upvote count: 1
tagged with: python
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90244909
tagged with: loops
has title: Pyspark Dataframe Efficient ways for O(n^2) Complexity Looping
has body: I have a pyspark datafram as the following. I need to check the longest common subsequence between the text field (3rd column) and return a new dataframe that crosses a certain threshold in similarity value. So, the complexity in the simple array would be O(n^2). I was wondering how to get this effect for a distributed system using pyspark. I got one idea by using join on the data frame, however, it is very costly in terms of computation when the dataframe size increases. It would be great if you please provide some information about some efficient or 'right' way to do this. -------------------------- path | startline | text -------------------------- p1 | 15 | hello -------------------------- p2 | 8 | world -------------------------- p3 | 5 | AAA -------------------------- My current code structure is as follows: #convert the pandas dataframe to pyspark dataframe #df was in csv format in pandas dataframe spark_dataframe = sqlContext.createDataFrame(df) def lcs(row): #need to run Longest common subsequence on texts from two rows return (row.path, row.startline, row.text, lcs_sim) transformed_spark_df = spark_df.rdd.map(lcs)
has comment: http://stackoverflow.com/comment/90245741
answer count: 0
downvote count: 0
tagged with: pyspark
type: UnansweredQuestion
tagged with: iteration
has comment: http://stackoverflow.com/comment/90245387
has comment: http://stackoverflow.com/comment/90245106

http://stackoverflow.com/a/51706133
type: Answer
has body: This error message... selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //*[contains(@id,’exportbutton’)] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(@id,’exportbutton’)]' is not a valid XPath expression. ......implies that the Locator Strategy you have constructed was not a valid locator. The main reason of the error is the presence of ’ character. Instead you sould have used the ' character within the xpath. However as per the HTML you have provided to identify the element with text as Export Tickets you can use the following solution: submit_button = driver.find_element_by_xpath("//span[@class='x-btn-inner' and contains(.,'Export Tickets')][starts-with(@id,'exportbutton-')]")
answers question: http://stackoverflow.com/q/51689617
score: 0

http://stackoverflow.com/comment/90293500
score: 0
has text: The only thing missing is the fact that the `+` operator _never_ modifies anything in Python, it _always_ returns a new object. (Technically, you _could_ write a class with an `__add__` method that modifies `self`, but that would be confusing and deeply unpythonic.) So, `l = l + [0]` is just a special case of that general rule: `l + [0]` returns a new object, and then `l =` just assigns that new object to your local variable `l`, the same as if you'd written, say, `l = 2`. I can't find a dup that covers that part.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51665048

http://stackoverflow.com/comment/90528047
comment on: http://stackoverflow.com/q/51777918
score: 0
type: QuestionComment
type: Comment
has text: @ZainPatel `apt-get` on Windows?

http://stackoverflow.com/comment/90561666
score: 0
type: AnswerComment
type: Comment
has text: any ways..thank you so much for this help. is animation is replacement for drawnow?
comment on: http://stackoverflow.com/a/51802210

http://stackoverflow.com/a/51675509
type: AcceptedAnswer
downvote count: 0
score: 18
accepted answer of: http://stackoverflow.com/q/51656818
type: Answer
answers question: http://stackoverflow.com/q/51656818
has comment: http://stackoverflow.com/comment/90314531
has comment: http://stackoverflow.com/comment/90314185
upvote count: 18
has body: After long and painful installations and compilations I've performed benchmarks in Matlab, C++ and Python. My computer: MAC OS High Sierra 10.13.6 with Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz (4 cores, 8 threads). I have Radeon Pro 560 4096 MB so that there was no GPUs involved in these tests (and I never configured openCL and didn't see it in np.show_config()). Software: Matlab 2018a, Python 3.6, C++ compilers: Apple LLVM version 9.1.0 (clang-902.0.39.2), g++-8 (Homebrew GCC 8.2.0) 8.2.0 1) Matlab performance: time= (14.3 +- 0.7 ) ms with 10 runs performed a=rand(1000,1000); b=rand(1000,1000); c=rand(1000,1000); tic for i=1:100 c=a*b; end toc/100 2) Python performance (%timeit a.dot(b,out=c)): 15.5 +- 0.8 I've also installed mkl libraries for python. With numpy linked against mkl: 14.4+-0.7 - it helps, but very little. 3) C++ performance. The following changes to the original (see the question) code were applied: noalias function to avoid unnecessary temporal matrices creation. Time was measured with c++11 chorno library Here I used a bunch of different options and two different compilers: 3.1 clang++ -std=c++11 -I/usr/local/Cellar/eigen/3.3.5/include/eigen3/eigen main.cpp -O3 Execution time ~ 146 ms 3.2 Added -march=native option: Execution time ~ 46 +-2 ms 3.3 Changed compiler to GNU g++ (in my mac it is called gpp by custom-defined alias): gpp -std=c++11 -I/usr/local/Cellar/eigen/3.3.5/include/eigen3/eigen main.cpp -O3 Execution time 222 ms 3.4 Added - march=native option: Execution time ~ 45.5 +- 1 ms At this point I realized that Eigen does not use multiple threads. I installed openmp and added -fopenmp flag. Note that on the latest clang version openmp does not work, thus I had to use g++ from now on. I also made sure I am actually using all available threads by monitoring the value of Eigen::nbthreads() and by using MAC OS activity monitor. 3.5 gpp -std=c++11 -I/usr/local/Cellar/eigen/3.3.5/include/eigen3/eigen main.cpp -O3 -march=native -fopenmp Execution…

http://stackoverflow.com/a/51675671
type: AcceptedAnswer
score: 0
type: Answer
has body: You should change the name of your .py script (email.py) to some different name.
answers question: http://stackoverflow.com/q/51675429
has comment: http://stackoverflow.com/comment/90314389
accepted answer of: http://stackoverflow.com/q/51675429

http://stackoverflow.com/a/51768184
score: 0
type: Answer
has body: You should be uploading the apk version of the code. With python it is not an easy task to do. Maybe you should give kivy a try. Kivy
answers question: http://stackoverflow.com/q/51765961

http://stackoverflow.com/comment/90336562
has text: ... Do the SNMP RFCs declare that a value should not be over a specific size, or is there something else at play here? I have upped the size of the `DisplayString` class to 511 to work round this, but will I break anything else by doing so?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51667591

http://stackoverflow.com/comment/90342301
type: AnswerComment
comment on: http://stackoverflow.com/a/51689799
score: 0
type: Comment
has text: Wow. Thank you so much for your help, especially for the thorough breakdown of the loop. It really made it a lot easier to understand.

http://stackoverflow.com/q/51783342
answer count: 1
favorite count: 0
has body: I have done the procedure to list shapefiles in an environment but it returns the folder names inside the envirnoment: arcpy.env.workspace = r"C:\Users\user\Desktop\results" dd= arcpy.ListFiles() for i in dd: print(i) gives: shapesfiles1 shapefiles2 How to print what is inside these folders?
tagged with: python
has answer: http://stackoverflow.com/a/51783948
linked to: http://stackoverflow.com/q/51784840
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
tagged with: arcpy
has title: List files inside folders in Arcpy?
score: 0
accepted answer: http://stackoverflow.com/a/51783948

http://stackoverflow.com/q/51778005
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51778216
possible better answer: http://stackoverflow.com/a/51778076
has answer: http://stackoverflow.com/a/51778076
score: 0
tagged with: pandas
tagged with: datetime
has body: I have a dataframe with datetime (df1). I want to know if the datetime in a 'col1' in df1 is between any of the pair of the datetime of two columns ('lowerbound' and 'upperbound') in another dataframe (df2). For example: df1 = pd.to_datetime(['2014-04-09 07:37:00','2015-04-09 07:00:00', '2014-02-02 08:31:00','2014-03-02 08:22:00']) df1 = pd.DataFrame(df1,columns = ['col1']) lowerbound = pd.to_datetime(['2014-04-09 07:25:00','2014-02-02 08:30:00', '2015-04-09 06:00:00','2014-03-02 08:12:00']) upperbound = pd.to_datetime(['2014-04-09 07:38:00','2014-04-09 07:48:00', '2015-04-09 08:00:00','2014-02-02 08:33:00') df2 = pd.DataFrame(lowerbound,columns = ['lowerbound']) df2['upperbound'] = upperbound The result shall be [1,1,0,0] since: df1['col1'][0] is between df2['lowerbound'][0] &amp; df2['lowerbound'][0] df1['col1'][1] is between df2['lowerbound'][2] &amp; df2['lowerbound'][2] Although df1['col1'][2] is between df2['lowerbound'][1] &amp; df2['lowerbound'][3], the index for df2['lowerbound'] and df2['lowerbound'] are not the same. Thanks!
has comment: http://stackoverflow.com/comment/90514382
favorite count: 0
has comment: http://stackoverflow.com/comment/90514430
upvote count: 1
tagged with: python
has title: Python Series - if it is between the values of two other series (time)
has comment: http://stackoverflow.com/comment/90514263
type: AnsweredQuestion
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90514364
has answer: http://stackoverflow.com/a/51778216
downvote count: 1

http://stackoverflow.com/comment/90480363
comment on: http://stackoverflow.com/q/51759951
has text: review the [tour], read [ask] and provide a [mcve]
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90436251
type: Comment
type: QuestionComment
has text: yes....I've created the tables in Mysql db.....
comment on: http://stackoverflow.com/q/51737548
score: 0

http://stackoverflow.com/a/51708976
downvote count: 0
has body: You can groupby year and then reindex with the union of existing and missing values: (df.set_index("week") .groupby("year") .apply(lambda x: x.reindex(x.index.union(np.arange(x.index.min(),x.index.max())))) .drop("year", 1) .reset_index() .rename(columns={"level_1":"week"})) year week val1 val2 0 2017 45 10.1 20.2 1 2017 46 nan nan 2 2017 47 nan nan 3 2017 48 10.3 20.3 4 2017 49 10.4 20.4 5 2017 50 nan nan 6 2017 51 nan nan 7 2017 52 10.3 20.5 8 2018 1 10.1 20.2 9 2018 2 10.3 20.3 10 2018 3 nan nan 11 2018 4 nan nan 12 2018 5 10.4 20.4 13 2018 6 nan nan 14 2018 7 nan nan 15 2018 8 nan nan 16 2018 9 10.3 20.5
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51708565
score: 2

http://stackoverflow.com/comment/90391328
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51713789
has text: I added a print in the clause with `result.append(1)`, which I think is your counting mechanism, and it never gets output. Where are you deciding it counted correctly?
score: 0

http://stackoverflow.com/q/51727020
has answer: http://stackoverflow.com/a/51729958
tagged with: python
accepted answer: http://stackoverflow.com/a/51729958
tagged with: f5
tagged with: snmp
score: 0
answer count: 1
tagged with: pysnmp
has body: I'am new in this thing, When I run the following command: snmpwalk -v2c -c public localhost .1.3.6.1.4.1.3375.2.2.5.6.2.1.6 in my F5 LTM I get all my nodes, pools and state like this: F5-BIGIP-LOCAL-MIB::ltmPoolMbrStatusEnabledState."/Common/pool-cnv-proc-financeiro-processamento-was-9169"."/Common/HAPP102".9169 = INTEGER: enabled(1) But when I use the same OID by pysnmp I get this: [ObjectType(ObjectIdentity(&lt;ObjectName value object at 0x6373150 tagSet &lt;TagSet object at 0x4ab5190 tags 0:0:6&gt; payload [1.3.6.1.4.1.3375...80.49.48.52.9144]&gt;), &lt;Integer value object at 0x6373050 subtypeSpec &lt;ConstraintsIntersection object at 0x4ab5c90 consts &lt;ValueRangeConstraint object at 0x4a17c90 consts -2147483648, 2147483647&gt;&gt; tagSet &lt;TagSet object at 0x4aabad0 tags 0:0:2&gt; payload [1]&gt;)] My question: Is there a way to parse this pysnmp response or am I doing something wrong? Here is the python code: from pysnmp.hlapi import * def walk(host, oid): for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget((host, 161)), ContextData(), ObjectType(ObjectIdentity(oid)), lexicographicMode=False): if errorIndication: break elif errorStatus: break else: for varBind in varBinds: print(varBind) walk('10.10.100.89', '1.3.6.1.4.1.3375.2.2.5.6.2.1.6')
has title: Python SNMP with PYSNMP F5 ltm
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/51732847
has body: I am new to Tensorrt and I am not so familiar with C language also. May I ask if there is any example to import caffe modell(caffeparser) and at the same time to use plugin with python. Plugin library example: "https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/_nv_infer_plugin_8h_source.html". I saw an example doing something like the below. Is it necessary to modify the the pluginfactory class? or it has been already done with the python plugin api? import tensorrt import tensorrtplugins from tensorrt.plugins import _nv_infer_plugin_bindings as nvinferplugin from tensorrt.parsers import caffeparser plugin_factory = tensorrtplugins.FullyConnectedPluginFactory() parser = caffeparser.create_caffe_parser() parser.set_plugin_factory(plugin_factory) engine = trt.utils.caffe_to_trt_engine(G_LOGGER, MODEL_PROTOTXT, CAFFE_MODEL, 1, 1 &lt;&lt; 20, OUTPUT_LAYERS, trt.infer.DataType.FLOAT, plugin_factory ) P.s: I am trying to convert YOLO2 to Tensorrt format. Therefore, some layers(e.g kYOLOREORG and kPRELU) can only be supported by the plugin. Another way to do so is to add the plugin during constructing the network, by method network.add_plugin_ext() ?However, I am not so sure how to specify the previous layer that is going to be imported later. Thank you so much for your answer. Your help will be much appreciated!
tagged with: python
tagged with: plugins
tagged with: yolo
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: caffe
type: Question
tagged with: tensorrt
has title: Tensorrt Plugin and caffe parser in python
downvote count: 0
has comment: http://stackoverflow.com/comment/98325543
favorite count: 0

http://stackoverflow.com/q/51681727
has answer: http://stackoverflow.com/a/52597076
tagged with: python
tagged with: macos
answer count: 4
has comment: http://stackoverflow.com/comment/90326965
favorite count: 0
upvote count: 9
downvote count: 0
has answer: http://stackoverflow.com/a/52584016
type: UnansweredQuestion
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90326516
has answer: http://stackoverflow.com/a/56617349
linked to: http://stackoverflow.com/q/40904979
has answer: http://stackoverflow.com/a/56610993
has body: I tried to validate my tensorflow for my mac using these instructions https://www.tensorflow.org/install/install_mac#ValidateYourInstallation but produce this result. is that ok? bad? how can i fix this? thanks sess = tf.Session() Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA print(sess.run(hello)) b'Hello, TensorFlow!' Mac OS version: MacOS High Sierra 10.13.6 here is the full installation and validation output: usermacbook:tensorflowve someuser$ python3 -m venv . usermacbook:tensorflowve someuser$ source bin/activate (tensorflowve) usermacbook:tensorflowve someuser$ pip3 install --upgrade tensorflow Collecting tensorflow Downloading https://files.pythonhosted.org/packages/57/38/96ee343729363297d62311272adc28b466d30f74c87dc645badb0102af56/tensorflow-1.9.0-cp36-cp36m-macosx_10_11_x86_64.whl (48.9MB) 100% |████████████████████████████████| 48.9MB 30kB/s Collecting termcolor&gt;=1.1.0 (from tensorflow) Downloading https://files.pythonhosted.org/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz Collecting protobuf&gt;=3.4.0 (from tensorflow) Downloading https://files.pythonhosted.org/packages/6d/7e/51c91b28cb8446ebd7231d375a2025bca4c59d15ddc0cf2dd0867b400cd7/protobuf-3.6.0-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 986kB/s Collecting absl-py&gt;=0.1.6 (from tensorflow) Downloading https://files.pythonhosted.org/packages/96/5d/18feb90462c8edaae71305716c7e8bac479fc9dface63221f808a6b95880/absl-py-0.3.0.tar.gz (84kB) 100% |████████████████████████████████| 92kB 3.7MB/s Collecting gast&gt;=0.2.0 (from tensorflow) Downloading https://files.pythonhosted.org/packages/5c/78/ff794fcae2ce8aa6323e789d1f8b3b7765f601e7702726f430e814822b96/gast-0.2.0.tar.gz Collecting grpcio&gt;=1.8.6 (from tensorflow) Downloading https://files.pythonhosted.org/packages/c2/bc/31fb22c3dccc…
type: Question
has title: Tensorflow on MacOS: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
score: 9
tagged with: validation

http://stackoverflow.com/comment/90394538
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51716651
has text: If you want to know what's going wrong, don't use a bare `except:` that throws that information away. Either remove the `try:/except:` (at least temporarily, for debugging), or change it to `except Exception as e:` and `print(f"Invalid input: {e!r}")` or something that includes the error message.

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/51788258
tags question: http://stackoverflow.com/q/51797244

http://stackoverflow.com/comment/90261010
comment on: http://stackoverflow.com/a/51646752
type: AnswerComment
score: 0
has text: Does mibbuild rely on sme public source of mibs?
type: Comment

http://stackoverflow.com/comment/90450116
has text: *"Normally, when plotting with matplotlib.pyplot.bar, each bar represents a category"* that is not true. matplotlib bar plots are numeric by default. You do not share any code here which would allow to see where the problem lies. See [mcve].
comment on: http://stackoverflow.com/q/51741786
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90520912
comment on: http://stackoverflow.com/q/51777361
score: 0
has text: @DebanjanB you can check the sample code/
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90547920
type: Comment
type: QuestionComment
has text: This is pretty prominent in the pandas documentation: https://pandas.pydata.org/pandas-docs/stable/missing_data.html -- `df.fillna("")`
score: 1
comment on: http://stackoverflow.com/q/51795186

http://stackoverflow.com/q/51675742
possible better answer: http://stackoverflow.com/a/51677775
has answer: http://stackoverflow.com/a/51681415
has answer: http://stackoverflow.com/a/51676313
type: AnsweredQuestion
score: -2
has title: Removing specific values when a certain value is before
type: Question
downvote count: 2
has answer: http://stackoverflow.com/a/51677775
has body: I have a.csv file that has values that will distort my calculation Approach I want to remove values that exits on rows after specific values in each row, for example, if there is a "(B)" on a row and it's the first before "(D)" and others "(B)" only keep the first "(B)" And same for "+", "++" and "+++", i want to keep only the first one in each line Desired result 1277|2013-12-17 16:00:00|100|+| 1360|2014-01-15 16:00:00|(B)|99|++|E 1402|2014-02-05 20:00:00|(D)|99|++|D 1360|2014-01-29 08:00:00|(D)|99|C 1378|2014-01-21 20:00:00|(B)|100||D Sample of the csv file : 1277|2013-12-17 16:00:00|100|+|++| 1360|2014-01-15 16:00:00|(B)|(D)|99|++|+++||+|E 1402|2014-02-05 20:00:00|(D)|(B)|99|++|+||D 1360|2014-01-29 08:00:00|(D)|(B)|99||C 1378|2014-01-21 20:00:00|(B)|100||D
has comment: http://stackoverflow.com/comment/90318896
favorite count: 0
has comment: http://stackoverflow.com/comment/90383281
answer count: 3
has comment: http://stackoverflow.com/comment/90316925
tagged with: python
accepted answer: http://stackoverflow.com/a/51676313
upvote count: 0
has comment: http://stackoverflow.com/comment/90316075

http://stackoverflow.com/q/51756066
tagged with: gmail
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90482380
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90482770
tagged with: automation
has answer: http://stackoverflow.com/a/51762191
has answer: http://stackoverflow.com/a/51756206
has body: The end goal is to send myself an email if my public ip address changes, as I don't have dynamic dns and have to manually enter the ip addresses myself for my web server. I've done all I possibly can to try and get bash utilities to do the job for me, but CenturyLink is unfortunately out to block me no matter how I configure my outbound mail. So I've turned to graphical python/selenium web page automation, which will sign into my gmail account for me, click the 'compose' button, then enter in the To:, Subject:, and text segments and hit send. Everything is working except for one small part - the To: field. The html/css is different for this than all the others and no matter how I try to select the field using driver.find_element_by_class_name() or driver.find_element_by_id() I just can't seem to fill out the field. Bash will give me an error like :lo cannot be reached by keyboard or textarea#:lo.vO is not a valid selector When I did an inspect element, the element looked like this: &lt;textarea rows="1" id=":lo" class="vO" name="to" spellcheck="false" autocomplete="false" autocapitalize="off" autocorrect="off" tabindex="1" dir="ltr" aria-label="To" role="combobox" aria-autocomplete="list" style="width: 462px;"&gt;&lt;/textarea&gt; My code so far is this: (note: which does not include getting ip info yet, just gmail login / manipulation) from selenium import webdriver import time driver = webdriver.Firefox(); driver.get('https://www.gmail.com'); username = driver.find_element_by_id('identifierId'); username.send_keys("EMAIL"); driver.find_elements_by_class_name('RveJvd.snByac')[1].click(); time.sleep(2); #password not entered in username field password = driver.find_element_by_class_name('whsOnd.zHQkBf'); password.send_keys("PASSWORD"); driver.find_elements_by_class_name('RveJvd.snByac')[0].click(); #end login, start composing time.sleep(5); #wait for sign in driver.find_element_by_class_name('T-I.J-J5-Ji.T-I-KE.L3').click(); to = driver.find_element_by_class_name('t…
has answer: http://stackoverflow.com/a/65362284
answer count: 4
has comment: http://stackoverflow.com/comment/90476135
possible better answer: http://stackoverflow.com/a/51756206
has answer: http://stackoverflow.com/a/51756412
tagged with: selenium
tagged with: python
has title: Python w/ Selenium Gmail Email Send Automating To: Field is Giving Me Trouble
accepted answer: http://stackoverflow.com/a/51762191

http://stackoverflow.com/comment/90341638
score: 0
type: Comment
has text: Thank you for your answer. Yeah, the duplicate links shown me that it's not possible with single regex. I didn't know that you can put `start` to regular expression object, TIL :)
type: AnswerComment
comment on: http://stackoverflow.com/a/51689884

http://stackoverflow.com/comment/90479796
type: Comment
type: QuestionComment
has text: @Catree are there more functions for disparity mapping?
score: 1
comment on: http://stackoverflow.com/q/51758076

http://stackoverflow.com/a/51743236
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51743175
has body: If you don't have to be efficient: from functools import partial import json list(map(json.loads, set(map(partial(json.dumps, sort_keys=True), l)))) If you do have to be efficient: serialized = map(tuple, map(sorted, map(dict.items, l))) unique = set(serialized) result = list(map(dict, unique))
answers question: http://stackoverflow.com/q/51743175
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/90497216
score: 0
type: AnswerComment
type: Comment
has text: The problem still exists, but I think I have found that it happens when the mouse button is clicked too fast in the combobox.
comment on: http://stackoverflow.com/a/51769088

http://stackoverflow.com/q/51696861
tagged with: dataframe
has body: Here is some sample code: import pandas as pd data = {'Date': ['2018-01-01', '2018-01-02'], 'M1': [1, 1]} df = pd.DataFrame.from_dict(data) df.Timestamp = pd.to_datetime(df.Date, format='%Y-%m-%d') df.index = df.Timestamp new_data = pd.DataFrame(df[-1:].values, columns=df.columns) df = df.append(new_data) I would like to copy the last row of the data frame n=5 times (started this crudely at the end) but I would also like to increase the Date + index date by one day. I think this would require something along this lines: df['DATE'] + pd.DateOffset(days=10) Ultimately, the wants should take this shape using above's example: data = {'Date': ['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07'], 'M1': [1, 1, 1, 1, 1, 1, 1]} df = pd.DataFrame.from_dict(data) Any help would be very much appreciated. Thanks!
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51696936
tagged with: python
tagged with: python-3.x
has title: add last row n times to time indexed data frame whilst increasing date by 1 day each time
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51696936
type: AnsweredQuestion

http://stackoverflow.com/a/51734802
type: Answer
has body: How about this? import json orig_list = json.load(&lt;filename&gt;) new_dict = { l['Name']:{k:v for k,v in l.items() if k!='Name'} for l in orig_list} json.dumps(new_dict, &lt;filename&gt;) This way, you won't have to del items from the dicts that you load from the file.
answers question: http://stackoverflow.com/q/51733698
score: 0

http://stackoverflow.com/comment/90491974
has text: I think there was a paranthesis missing, I added the line again and it works fine with strip too as well. I must have messed up something before but I tried again because as you said it had to work, and it does. Thanks!
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51765496

class
tags question: http://stackoverflow.com/q/51677539
tags question: http://stackoverflow.com/q/51724510
tags question: http://stackoverflow.com/q/51793878
tags question: http://stackoverflow.com/q/51796531
tags question: http://stackoverflow.com/q/51644745
tags question: http://stackoverflow.com/q/51712997
tags question: http://stackoverflow.com/q/51711588
tags question: http://stackoverflow.com/q/51689856
tags question: http://stackoverflow.com/q/51738309
tags question: http://stackoverflow.com/q/51756290
tags question: http://stackoverflow.com/q/51691169
tags question: http://stackoverflow.com/q/51684920
tags question: http://stackoverflow.com/q/51794782
tags question: http://stackoverflow.com/q/51750876
tags question: http://stackoverflow.com/q/51758308
tags question: http://stackoverflow.com/q/51722132
tags question: http://stackoverflow.com/q/51686863
tags question: http://stackoverflow.com/q/51720372
type: Tag
tags question: http://stackoverflow.com/q/51657361
tags question: http://stackoverflow.com/q/51717089
tags question: http://stackoverflow.com/q/51660663
tags question: http://stackoverflow.com/q/51765116
tags question: http://stackoverflow.com/q/51721561
tags question: http://stackoverflow.com/q/51777675
tag name: class
tags question: http://stackoverflow.com/q/51790676
tags question: http://stackoverflow.com/q/51708044
tags question: http://stackoverflow.com/q/51705975
tags question: http://stackoverflow.com/q/51690799
tags question: http://stackoverflow.com/q/51681833
tags question: http://stackoverflow.com/q/51731268
tags question: http://stackoverflow.com/q/51715184
tags question: http://stackoverflow.com/q/51746764
tags question: http://stackoverflow.com/q/51691175
tags question: http://stackoverflow.com/q/51763890
tags question: http://stackoverflow.com/q/51695716
tags question: http://stackoverflow.com/q/51666361
tags question: http://stackoverflow.com/q/51714783
tags question: http://stackoverflow.com/q/51712836
tags question: http://stackoverflow.com/q/51730056
tags question: http://stackoverflow.com/q/51752442

http://stackoverflow.com/comment/90245273
type: Comment
type: AnswerComment
has text: Right. Perhaps he has a non-conventional newline pasted after his string.
comment on: http://stackoverflow.com/a/51640350
score: 0

http://stackoverflow.com/a/51786397
answers question: http://stackoverflow.com/q/51786324
upvote count: 1
has comment: http://stackoverflow.com/comment/90531331
score: 1
has comment: http://stackoverflow.com/comment/90530824
has body: You can do this: import math def two_powers(num): # Compute number of bits for big numbers num_bits = math.floor(math.log2(num)) + 1 if num &gt;= (1 &lt;&lt; 32) else 32 # Take those bits where there is a "one" in the number return [1 &lt;&lt; p for p in range(num_bits) if num &amp; (1 &lt;&lt; p)] print(two_powers(42)) # [2, 8, 32] EDIT: Wrt the number of bits, you can make more splits if you are really concerned about performance, either down to save iterations or up to avoid computing the logarithm (or if you know your input numbers are going to be in some particular range): import math def two_powers(num): # Compute number of bits for big numbers if num &lt; (1 &lt;&lt; 8): num_bits = 8 elif num &lt; (1 &lt;&lt; 16): num_bits = 16 elif num &lt; (1 &lt;&lt; 24): num_bits = 24 elif num &lt; (1 &lt;&lt; 32): num_bits = 32 else: num_bits = math.floor(math.log2(num)) + 1 # Take those bits where there is a "one" in the number return [1 &lt;&lt; p for p in range(num_bits) if num &amp; (1 &lt;&lt; p)] print(two_powers(42)) # [2, 8, 32]
downvote count: 0
type: Answer

http://stackoverflow.com/q/51733208
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51733264
linked to: http://stackoverflow.com/q/423379
downvote count: 1
linked to: http://stackoverflow.com/q/291978
possible better answer: http://stackoverflow.com/a/51733290
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/51733290
has title: unable to rewrite the value of a global variable using a function
score: -1
has body: I am trying to implement Scales to adjust threshold values for the canny image detection in python however I am unable to change the values using Scales. the value remains 0 no matter what. please help me out. Here is my code. from tkinter import * import cv2 v1 =0 v2 =0 def print_value1(val1): v1 = val1 print (v1) def print_value2(val2): v2 = val2 print (v2) def edge_detection(): img = cv2.imread("C:/Users/Shah Lamaan Rana/Pictures/modernvsoldforehand.jpg") edges = cv2.Canny(img, v1, v2) cv2.imshow('test image', edges) root =Tk() scale1 = Scale(orient = 'horizontal', from_=0, to=200, command=print_value1) scale1.pack() scale2 = Scale(orient = 'horizontal', from_=0, to=400, command=print_value2) scale2.pack() button = Button(root,text = "find edges", command = edge_detection,bg = 'red' ,height = 1, width = 24, borderwidth=6) button.pack() root.mainloop()
has answer: http://stackoverflow.com/a/51733345
upvote count: 0
has answer: http://stackoverflow.com/a/51733296
favorite count: 0
accepted answer: http://stackoverflow.com/a/51733296
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/90427223

http://stackoverflow.com/comment/90289132
type: AnswerComment
has text: Your call! I hope it helped at least a little. Good luck!
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51662697

http://stackoverflow.com/comment/90365676
type: QuestionComment
has text: @iamanigeeit, it accepts but only creates new column with empty data.
comment on: http://stackoverflow.com/q/51698989
score: 0
type: Comment

http://stackoverflow.com/q/51795285
type: Question
has comment: http://stackoverflow.com/comment/90548065
has comment: http://stackoverflow.com/comment/90550300
has comment: http://stackoverflow.com/comment/90548094
tagged with: perl
tagged with: block
tagged with: http-status-code-403
accepted answer: http://stackoverflow.com/a/51796352
upvote count: 0
answer count: 1
score: -6
favorite count: 0
has body: I have web scraping script (Perl language) in the first time it works perfectly but after ~ 3500 ( GET request ) server return 403 error ( Forbidden | not ip banned ) but when use the same script in ( python language ) i find the same problem work but after ~ 3500 requests i get 403 ( retrun to work after 24 heures ) i don't know what is the problem and how i can fix it i read about libwww-perl : https://cloudkul.com/blog/block-libwww-perl-attack-in-apache-web-server/
tagged with: python
has title: Web Server Block libwww-perl requests
has comment: http://stackoverflow.com/comment/90548073
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51796352
tagged with: web-scraping

http://stackoverflow.com/q/51766031
tagged with: python
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/90491047
type: Question
score: 3
tagged with: matplotlib
linked to: http://stackoverflow.com/q/10481990
has body: I want to plot time-series on a double y-axis with matplotlib and rescale the axis so that the origin (y=0) is aligned for both axis. I have looked at this question but the suggested solutions can cut some data out of the plot. For example: import matplotlib.pyplot as plt import numpy as np import pandas as pd np.random.seed(1) df = pd.DataFrame(np.random.randn(100, 3), columns=['A', 'B', 'C']).cumsum() df['Total'] = df'A', 'B', 'C'.sum(1) fig, ax = plt.subplots(1) df.drop('Total', axis=1).plot(ax=ax) ax2 = ax.twinx() df['Total'].plot(ax=ax2, color='k', linestyle='--') Using @drevicko solution (from the link above), I obtain the chart below. The origin for the two axis is now aligned, but part of the green line is left out of the plot. How can I align the origin and leave all data in the plot frame?
tagged with: pandas
downvote count: 0
has title: Matplotlib - Shared origin for double axis without cutting data
favorite count: 0
has comment: http://stackoverflow.com/comment/90491635
type: UnansweredQuestion

http://stackoverflow.com/q/51719472
tagged with: python
answer count: 4
has title: Remove green background screen from image using OpenCV/Python
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2810970
has body: So I have this image below: As you can see, there is some noisy green outline in the image. This is by far, my latest output with OpenCV with Python. And I'm still a beginner with this so I need your help. Assuming I were to create a completely new script and feed this image and 'clean' the image, how will I do it? EDIT: This is the original image:
has answer: http://stackoverflow.com/a/72279520
tagged with: opencv
has answer: http://stackoverflow.com/a/54435420
downvote count: 0
score: 7
linked to: http://stackoverflow.com/q/47483951
tagged with: image-processing
has comment: http://stackoverflow.com/comment/90400661
type: Question
has answer: http://stackoverflow.com/a/72280828
has answer: http://stackoverflow.com/a/51719562
linked to: http://stackoverflow.com/q/10948589
upvote count: 7

http://stackoverflow.com/q/51661037
tagged with: python
has body: Consider the following interaction: I conda install mysql, the installation succeeds, but python denies ever having heard of this mysterious "mysql". I must be being very dense, but in what way? (base) igor@Ubuntu-1804-bionic-64-minimal:~/rci$ conda install mysql Solving environment: done Package Plan environment location: /home/igor/anaconda3 added / updated specs: - mysql The following packages will be downloaded: package | build ---------------------------|----------------- mysql-5.7.22 | hef7e34c_0 74.3 MB krb5-1.16.1 | hc83ff2d_6 1.4 MB libntlm-1.4 | h14c3975_2 33 KB cyrus-sasl-2.1.26 | h20670df_3 242 KB ------------------------------------------------------------ Total: 75.9 MB The following NEW packages will be INSTALLED: cyrus-sasl: 2.1.26-h20670df_3 krb5: 1.16.1-hc83ff2d_6 libntlm: 1.4-h14c3975_2 mysql: 5.7.22-hef7e34c_0 Proceed ([y]/n)? Downloading and Extracting Packages mysql-5.7.22 | 74.3 MB | #################################################### | 100% krb5-1.16.1 | 1.4 MB | #################################################### | 100% libntlm-1.4 | 33 KB | #################################################### | 100% cyrus-sasl-2.1.26 | 242 KB | #################################################### | 100% Preparing transaction: done Verifying transaction: done Executing transaction: done (base) igor@Ubuntu-1804-bionic-64-minimal:~/rci$ python Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. import MySQLdb import mysql.connector Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'mysql'
type: Question
score: 0
answer count: 1
has title: anaconda python mysql confusion
tagged with: anaconda
has answer: http://stackoverflow.com/a/51661174
tagged with: mysql
accepted answer: http://stackoverflow.com/a/51661174
type: AnsweredQuestion

http://stackoverflow.com/q/51756634
has title: Errno 13 Permission denied. Already in virtual environment
has body: I'm trying to install tensorflow after an OS update. I'm getting an [Errno 13] Permission denied. All the forum posts I've checked recommend solving this using a virtual environment. Problem is I'm already working in a virtual environment. here are the command's I used: user@Computer:~$ cd /tensorflow user@Computer:/tensorflow$ virtualenv --system-site-packages -p python3 venv user@Computer:/tensorflow$ source /tensorflow/venv/bin/activate (venv) user@Computer:/tensorflow$ pip install -U tensorflow-GPU and here's the output I got: (venv) user@Computer:/tensorflow$ pip install -U tensorflow-GPU Using cached https://files.pythonhosted.org/packages/64/ca/830b7cedb073ae264d215d51bd18d7cff7a2a47e39d79f6fa23edae17bb2/tensorflow_gpu-1.10.0-cp36-cp36m-manylinux1_x86_64.whl Collecting gast&gt;=0.2.0 (from tensorflow-GPU) Collecting tensorboard&lt;1.11.0,&gt;=1.10.0 (from tensorflow-GPU) Using cached https://files.pythonhosted.org/packages/c6/17/ecd918a004f297955c30b4fffbea100b1606c225dbf0443264012773c3ff/tensorboard-1.10.0-py3-none-any.whl Collecting grpcio&gt;=1.8.6 (from tensorflow-GPU) Using cached https://files.pythonhosted.org/packages/31/17/0f79ff2f56018aa0e12ffb1cc8086df6bd6cfc71efea0df64fe78d569f71/grpcio-1.14.1-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied, skipping upgrade: six&gt;=1.10.0 in /usr/lib/python3/dist-packages (from tensorflow-GPU) (1.11.0) Collecting astor&gt;=0.6.0 (from tensorflow-GPU) Using cached https://files.pythonhosted.org/packages/35/6b/11530768cac581a12952a2aad00e1526b89d242d0b9f59534ef6e6a1752f/astor-0.7.1-py2.py3-none-any.whl Collecting protobuf&gt;=3.6.0 (from tensorflow-GPU) Using cached https://files.pythonhosted.org/packages/fc/f0/db040681187496d10ac50ad167a8fd5f953d115b16a7085e19193a6abfd2/protobuf-3.6.0-cp36-cp36m-manylinux1_x86_64.whl Requirement already satisfied, skipping upgrade: wheel&gt;=0.26 in ./venv/lib/python3.6/site-packages (from tensorflow-GPU) (0.31.1) Collecting absl-py&gt;=0.1.6 (from tensorflow-GPU) C…
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/19471972
tagged with: ubuntu
answer count: 1
downvote count: 0
tagged with: virtualenv
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51803650
tagged with: python
score: 2
upvote count: 2

text-processing
tags question: http://stackoverflow.com/q/51675700
tag name: text-processing
type: Tag

http://stackoverflow.com/comment/90511808
comment on: http://stackoverflow.com/q/51776507
score: 0
has text: The code you added in the update is fine, as long as you're running that before starting any of the concurrent handlers. There are ways it could be improved (there's no reason to `commit` a transaction that doesn't modify anything, you don't need to use `fetchall` just to ignore everything after the first row, you should almost never check anything `== None`, …), but none of that should make it not work.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51680700
score: 3
has comment: http://stackoverflow.com/comment/90328926
downvote count: 0
has body: I think the best way is just to slice and concatenate: insertion_point = 2 pd.concat([a.iloc[:insertion_point], b, a.iloc[insertion_point:]]).reset_index(drop=True) 0 1 0 1 2 1 2 3 2 4 5 3 5 6 4 3 4
accepted answer of: http://stackoverflow.com/q/51680616
answers question: http://stackoverflow.com/q/51680616
upvote count: 3
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/51758603
upvote count: 1
has answer: http://stackoverflow.com/a/51758677
has title: check if dot is followed by any other regex meta character using REGEX python
answer count: 1
has comment: http://stackoverflow.com/comment/90479534
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: Regex to check if . in the string is followed by any of the other regex meta-characters -> ^ $ * + ? { } [ ] \ | ( ) How to do this? I'm trying to do something like below: foo.bar -> dot is not followed by any other meta characters, so return false foo.*bar -> return true (because . is followed by *) gmail.com -> return false bar.+gmail -> return true bar. -> return false I'm very new to regex. Tried to do something like below: import re pattern = re.compile(r"([.][\^$*+?{}\[\]\|()]+)+") print bool(pattern.match("foo.*bar")) But it's not correct plz help.
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51758677
tagged with: python-2.7
score: 0

http://stackoverflow.com/comment/90503864
type: QuestionComment
comment on: http://stackoverflow.com/q/51772051
has text: If I'm understanding tobsecret correctly, for each unique code, they either have the same name or no name
score: 0
type: Comment

http://stackoverflow.com/comment/90411822
type: AnswerComment
type: Comment
has text: He said do not use sleep()
score: 0
comment on: http://stackoverflow.com/a/51725813

http://stackoverflow.com/q/51669432
answer count: 0
has title: assert : weird comparison result Python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90301578
has comment: http://stackoverflow.com/comment/90301483
score: 1
linked to: http://stackoverflow.com/q/588004
duplicate of: http://stackoverflow.com/q/588004
downvote count: 0
has body: Something weird. I want to test if a sum of a tuple elements is 1 and then assert if not. my_tuple=(0.8,0.2,0) assert((sum(my_tuple)==1)) This works. It works for other tuples like ( 1,0,0) or (0.1,0.2,0.7). But it raises an error for this tuple (0.7,0.2,0.1) eventhough the sum is clearly 1 !! Do you have any idea about this ? Thank you
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90301552

http://stackoverflow.com/q/51776314
type: Question
has answer: http://stackoverflow.com/a/51776373
duplicate of: http://stackoverflow.com/q/22341271
linked to: http://stackoverflow.com/q/44250019
upvote count: 6
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90511211
linked to: http://stackoverflow.com/q/13944078
has comment: http://stackoverflow.com/comment/90511272
tagged with: concatenation
has comment: http://stackoverflow.com/comment/90511193
tagged with: pandas
has comment: http://stackoverflow.com/comment/90511426
answer count: 1
has comment: http://stackoverflow.com/comment/90511120
favorite count: 0
linked to: http://stackoverflow.com/q/22341271
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51776373
downvote count: 0
has body: I have a dataframe like this Have been on it 12 days along with 60 mg prozac 4+ years on that. index sentences 1 I feel the best I have felt in years. 2 "I have taken for over 7 years. 3 I slept 2 hours". 4 IT SAVED MY LIFE 5 IT SAVED MY LIFE" then I want to concatenate them in one array. the problem is that there maybe some sentences reptitive but still I want to keep all of them so the result will be: ["I feel the best I have felt in years", "I have taken for over 7 years." , "I slept 2 hours." , "IT SAVED MY LIFE" , "IT SAVED MY LIFE"] I have tries this link and this which both are in r. I have also tried this approach: dfsent.groupby(['sentences']).apply(','.join) but as some of the rows in my data frame are repetitive it give me only one of them. in case of my example return me this: ["I feel the best I have felt in years", "I have taken for over 7 years." , "I slept 2 hours." , "IT SAVED MY LIFE" ] Thanks in advance :)
has title: how to concatenate all rows of a column of a data frame in pandas without group by
score: 6

http://stackoverflow.com/q/51787660
favorite count: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/51787880
has answer: http://stackoverflow.com/a/51787721
has answer: http://stackoverflow.com/a/51787880
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51787721
type: Question
answer count: 2
downvote count: 0
has title: The pythonic way to parse a small html code with beautifulsoup?
has body: What's the best pythonic way to parse the html-code below using BeautifulSoup? Total Total Over 4.5 3.38 Total Under 4.5 1.34 Total Over 5.5 12.5 Total Under 5 1.04 Total Under 5.5 1.02 I'm trying to get the output: Title: Total Total Over 4.5: 3.88, Total Under 4.5: 1.34 Total Over 5.5: 12.5, Total Under 4.5: 1.02 I've tried with the following code but it doesn't quite get there. soup = BeautifulSoup(html, 'lxml') infos = soup.find_all('span', class_='bet_type') for info in infos: info.get_text() odds = soup.find_all('span', class_='koeff') for odd in odds: odd.get_text()

http://stackoverflow.com/comment/90464030
comment on: http://stackoverflow.com/q/51752046
score: 0
type: Comment
type: QuestionComment
has text: They have to be consecutive.

http://stackoverflow.com/comment/90610827
score: 0
type: Comment
has text: here is a gif showing how does it behave https://media.giphy.com/media/7TbsEvuXNFtPL9BAGF/giphy.gif
type: AnswerComment
comment on: http://stackoverflow.com/a/51771086

http://stackoverflow.com/comment/90500276
type: AnswerComment
score: 0
type: Comment
has text: @JAGS8386 There are multiple ways. You can compile the _WebDriver_ binary i.e. _chromedriver_ binary with a few tweeks or use a _PROXY_. I have updated the answer and added some more references.
comment on: http://stackoverflow.com/a/51740403

http://stackoverflow.com/comment/90326929
has text: Possible duplicate of [Print doesn't print when it's in map, Python](https://stackoverflow.com/questions/7731213/print-doesnt-print-when-its-in-map-python)
comment on: http://stackoverflow.com/q/51671132
score: 0
type: Comment
type: QuestionComment

disable
tag name: disable
type: Tag
tags question: http://stackoverflow.com/q/51730037

http://stackoverflow.com/q/51744751
has answer: http://stackoverflow.com/a/51748309
has comment: http://stackoverflow.com/comment/90449805
answer count: 2
downvote count: 0
favorite count: 0
has body: There is a site named Stockpup that gives to anyone the opportunity to download from its webpage csv files containing fundamentals of companies listed in NYSE. The site is non commercial and does not provide an API as other sites do. This means that one have to download manually the csv files one by one which is very time consuming especially since this should be repeated every quarter. So I wonder if there is a way to automate this process through Python. I provide below an image of the website I am referring to which can be accessed at: http://www.stockpup.com/data/ I used the following code: from bs4 import BeautifulSoup import requests from urllib.parse import urljoin from os.path import basename base = "http://www.stockpup.com/data/" url = requests.get('http://www.stockpup.com/data/').text soup = BeautifulSoup(url) for link in (urljoin(base, a["href"]) for a in soup.select("a[href$=.csv]")): with open(basename(link), "w") as f: f.writelines(requests.get(link)) Which returned the following exception: TypeError Traceback (most recent call last) &lt;ipython-input-12-59ef271e8696&gt; in &lt;module&gt;() 9 for link in (urljoin(base, a["href"]) for a in soup.select("a[href$=.csv]")): 10 with open(basename(link), "w") as f: ---&gt; 11 f.writelines(requests.get(link)) TypeError: write() argument must be str, not bytes I also tried this code: from bs4 import BeautifulSoup from time import sleep import requests if __name__ == '__main__': url = requests.get('http://www.stockpup.com/data/').text soup = BeautifulSoup(url) for link in soup.findAll("a"): current_link = link.get("href") if current_link.endswith('csv'): print('Found CSV: ' + current_link) print('Downloading %s' % current_link) sleep(10) response = requests.get('http://www.stockpup.com/data//%s' % current_link, stream=True) fn = current_link.split('/')[0] + '_' + current_link.split('/')[1] + '_' + current_link.split('/')[2] with open(fn, "wb") as handle: for data in response.iter_content(): handle.write(data) Wh…
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90449647
has answer: http://stackoverflow.com/a/51745740
tagged with: python
linked to: http://stackoverflow.com/q/39033674
has title: Dowloading csv files from a webpage using Python
score: 1
has comment: http://stackoverflow.com/comment/90450405
has comment: http://stackoverflow.com/comment/90449202
tagged with: web-scraping
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90449213

http://stackoverflow.com/comment/90439761
comment on: http://stackoverflow.com/q/51732680
has text: https://github.com/keras-team/keras/issues/4172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51711213
has title: pandas.DataFrame.to_parquet fails when S3 is the destination
tagged with: pandas
has comment: http://stackoverflow.com/comment/90401827
favorite count: 0
tagged with: parquet
upvote count: 2
has body: I'm having a Pandas dataframe which I'm trying to save as parquet file into S3: dftest = pd.DataFrame({'field': [1,2,3]}) dftest.to_parquet("s3://bucket_name/test.parquet", engine='pyarrow', compression='gzip') I'm getting : "FileNotFoundError: bucket_name/test.parquet"
tagged with: pyarrow
has answer: http://stackoverflow.com/a/51721088
accepted answer: http://stackoverflow.com/a/51721088
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90385713
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90312626
has text: @Ray Highly recommended, I'm a SublimeText user but I can grant you a lot of IDEs out there use the awesome jedi library supporting autocompletion behind the curtains, it's a great library. Btw, edited my question... Good thing about this library is the public interface is really thin and you can build these sort of tools by yourself quite easily... give it a try! ;)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51674776

http://stackoverflow.com/comment/90458552
type: Comment
comment on: http://stackoverflow.com/a/51749345
score: 0
type: AnswerComment
has text: They are listing files in a directory then checking through anyway, no need to do an additional check

http://stackoverflow.com/q/51752599
has title: Google cloud functions in python to read firebase realtime data
upvote count: 6
tagged with: firebase
type: Question
has body: I'm writing a simple Google Cloud Function to learn, with the new Python3.7 option, and I would like to read/write some data to Firebase Realtime db. I found some information to use Firestore that worked, but now I need to use the realtime Database. # global import firebase_admin from firebase_admin import db # from firebase_admin import firestore default_app = firebase_admin.initialize_app() def check_prices_updates(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using make_response """ collection = 'pricelist' mybase = db.reference(collection) ....[other code] return "OK" This is an excerpt of my code, the documentation says that the initialize_app() must be left empty to collect the project default credentials. The line where I call db.reference(collection) give me the exception: ValueError: Invalid databaseURL option: "None". databaseURL must be a non-empty URL string. as if the configuration parameters did not show the requested key 'databaseURL'. With Firestore, as example I could call firestore.client(), after the import from firebase_admin, adding 'google-cloud-firestore in requirements.txt. Now, for firebase, what should I fix to read and write on the db? PS. on my db the ".read" rule is true for all so I haven't trouble on auth! UPDATE: After a good sleep I realized that to access the realtime db I need to pass some options to initialize_app, as follow: firebase_admin.initialize_app(options={'databaseURL': 'https://[PROJECT-NAME].firebaseio.com'}) Cheers
answer count: 1
has answer: http://stackoverflow.com/a/73281588
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: firebase-realtime-database
tagged with: google-cloud-functions
score: 6
tagged with: python

http://stackoverflow.com/a/51709024
has body: I'd create a reference dataframe and merge ref = pd.DataFrame( [[y, w] for y, s in df.groupby('year').week for w in range(s.min(), s.max() + 1)], columns=['year', 'week'] ) ref.merge(df, 'left') year week val1 val2 0 2017 45 10.1 20.2 1 2017 46 NaN NaN 2 2017 47 NaN NaN 3 2017 48 10.3 20.3 4 2017 49 10.4 20.4 5 2017 50 NaN NaN 6 2017 51 NaN NaN 7 2017 52 10.3 20.5 8 2018 1 10.1 20.2 9 2018 2 10.3 20.3 10 2018 3 NaN NaN 11 2018 4 NaN NaN 12 2018 5 10.4 20.4 13 2018 6 NaN NaN 14 2018 7 NaN NaN 15 2018 8 NaN NaN 16 2018 9 10.3 20.5
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51708565
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90482501
comment on: http://stackoverflow.com/q/51759921
score: 0
has text: yes, okay, I saw it now; it was buried down. thanks
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51699211
has comment: http://stackoverflow.com/comment/90360317
has comment: http://stackoverflow.com/comment/90361185
has comment: http://stackoverflow.com/comment/90359873
has comment: http://stackoverflow.com/comment/90360438
has title: Trying to understand what the author is conveying here, unzipping a zip with zip(*zip(
type: Question
has comment: http://stackoverflow.com/comment/90360770
has body: I am reading Learning Python and am having a hard time understanding what exactly the author is trying to convey here. He says: because argument-unpacking syntax in calls accepts iterables, it's also possible to use the zip built in call to unzip zipped tuples, by making prior or nested zip results arguments for another zip call. &gt;&gt;&gt; X = (1, 2) &gt;&gt;&gt; Y = (3, 4) &gt;&gt;&gt; list(zip(X, Y)) [(1, 3), (2, 4)] # Zip tuples; returns an iterable. &gt;&gt;&gt; A, B = zip(*zip(X, Y)) # Unzip a zip! &gt;&gt;&gt; A (1, 2) &gt;&gt;&gt; B (3, 4) I do not understand the point of the zip and then *zip? Wouldn't A, B = X, Y do the same thing. Can someone help explain this concept for me?
has comment: http://stackoverflow.com/comment/90360364
score: 0
has comment: http://stackoverflow.com/comment/90360023
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/23286254

http://stackoverflow.com/a/51745781
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90455833
accepted answer of: http://stackoverflow.com/q/51745678
answers question: http://stackoverflow.com/q/51745678
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90454847
downvote count: 0
has body: You can use zip to turn the list into a list of tuples so you can sort the pairs together, and then flatten it with nested list comprehension afterwards: print([a for i in sorted(zip(five_cards_num[::2], five_cards_num[1::2]), reverse=True) for a in i]) This outputs: [14, 'S', 12, 'D', 10, 'D', 9, 'S', 8, 'S']
type: Answer

http://stackoverflow.com/a/51795019
accepted answer of: http://stackoverflow.com/q/51774470
type: Answer
has comment: http://stackoverflow.com/comment/90611622
answers question: http://stackoverflow.com/q/51774470
has body: OK. You may want to avoid unnecessary dependence. I often define has_dask variable try: import dask.array as da has_dask = True except ImportError: has_dask = False and then if has_dask and isinstance(az_, da.Array): --- do some thing --- else --- do some other thing ----
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90313332
has text: Thanks, Can you explain a bit how this line is working print(*i, sep=' ', file=g)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51675130

http://stackoverflow.com/q/51643853
score: 0
has body: I have a file with the following structure: ****** Block 1 text text ... End ****** Block 2 text text ... End ****** Block 3 text text ... End ****** and so on. I want to open the file read each line and save the information of the first block in a string. This is what I have so far. Block = '' with open(File) as file: for line in file: if re.match('\.Block.*', line): Block += line if 'str' in line: break print (Block) However, when I print Block I am getting: Block 1 Block 2 ... How can I use my regex to copy the lines from Block 1 to End? Thank you
answer count: 3
has title: How to use regex to copy section from file?
has comment: http://stackoverflow.com/comment/90251903
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51646646
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51643866
type: Question
has answer: http://stackoverflow.com/a/51643891

http://stackoverflow.com/q/51648244
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51648337
type: Question
possible better answer: http://stackoverflow.com/a/51648498
has answer: http://stackoverflow.com/a/51648498
accepted answer: http://stackoverflow.com/a/51648337
answer count: 2
downvote count: 0
favorite count: 0
has title: Wrap string inside single quotes
has body: I am trying to wrap all individual values which are inside curly braces {} using single quotes ' '. example: some test {Value1,Value2} more text {Value3} more text {Value4, Value1, Value5, Value9, Value11, Value21} Above should convert as below: some test {'Value1','Value2'} more text {'Value3'} more text {'Value4', 'Value1', 'Value5', 'Value9', 'Value11', 'Value21'} I am able to figure out the pattern but not sure how to replace them in file. Source file content: 2321232~CD IN ('JSS12QQ','OQJS','QE9QAA','HAHSS31A','KAA43A','QA00A')~CD IN (JSS12QQ','OQJS','ULOE9Q','HAHSS31A','KAA43A','QA00A','QM34AA','WS2A','JS3QQ')~US~ {QA00A,WS2A,JS3QQ,OQJS,KAA43A,ULOE9Q,QM34AA,HAHSS31A,JSS12QQ}~{KAA43A,QA00A,QM34AA,WS2A,JS3QQ} ~CD IN ('2AA2Q')~CD IN ('2AA2Q')~US~{2AA2Q}~{2AA2Q}~{QM34AA,JSS12QQ} Target files content: 2321232~CD IN ('JSS12QQ','OQJS','QE9QAA','HAHSS31A','KAA43A','QA00A')~CD IN (JSS12QQ','OQJS','ULOE9Q','HAHSS31A','KAA43A','QA00A','QM34AA','WS2A','JS3QQ')~US~ {'QA00A','WS2A','JS3QQ','OQJS','KAA43A','ULOE9Q','QM34AA','HAHSS31A','JSS12QQ'}~{'KAA43A','QA00A','QM34AA','WS2A','JS3QQ'} ~CD IN ('2AA2Q')~CD IN ('2AA2Q')~US~{'2AA2Q'}~{'2AA2Q'}~{'QM34AA,JSS12QQ'} Code to fetch the pattern: import re def parse(file_name): file = open(file_name) file_contents =file.read() f = file_contents rec=re.findall(r"{.*?}",f) print (rec) parse("rule_engine_temp.csv") Please help with explanation so that i can understand and handle its variations.

http://stackoverflow.com/comment/90582357
score: 0
type: AnswerComment
type: Comment
has text: Yes please. What do I have to do to my function to make it work properly?
comment on: http://stackoverflow.com/a/51794929

http://stackoverflow.com/q/51779255
tagged with: performance
has body: def twoSum(self, nums, target): compliments = {} length = len(nums) for i, num in enumerate(nums): compliment_of_num = target-num if compliment_of_num in compliments: return [nums.index(compliment_of_num),i] compliments.update({num:compliment_of_num}) I think its O(n) but I think the line " if compliment_of_num in compliments" is O(n) instead of O(1) which makes the complexity of the whole program to be O(N^2)
has comment: http://stackoverflow.com/comment/90516575
has title: What is the time complexity of the following python code using dictionary?
has comment: http://stackoverflow.com/comment/90517208
has comment: http://stackoverflow.com/comment/90516606
score: 0
tagged with: time-complexity
has comment: http://stackoverflow.com/comment/90516315
has comment: http://stackoverflow.com/comment/90516335
has comment: http://stackoverflow.com/comment/90516383
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90529477
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90516875
has comment: http://stackoverflow.com/comment/90517119
has comment: http://stackoverflow.com/comment/90516333
has comment: http://stackoverflow.com/comment/90516524
has comment: http://stackoverflow.com/comment/90517189
has comment: http://stackoverflow.com/comment/90516299
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90516673

http://stackoverflow.com/q/51680415
has title: display rawqueryset value in a model using django @property field
answer count: 1
has answer: http://stackoverflow.com/a/51680963
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/47255458
type: Question
tagged with: django-admin
score: 0
has body: I am trying to insert a @property field into a django model. However this field gets its value from a RawQuerySet like so; class Medication_List(models.Model): id = models.AutoField(primary_key=True) medication_name = models.CharField(max_length=250, blank=True, editable=True) ... def stock_level(self): # "Returns the totalstock remaining" current_stock = Medications_Bridge.objects.raw("SELECT T3.total_quantity_sold AS total_quantity_sold FROM (SELECT * FROM ... return({'current_stock' : current_stock}) stock = property(stock_level) def __str__(self): return "%s %s %s" % (self.medication_name, self.supplier,self.stock) This works fine with no errors, but django is not showing value for the queryset in the str function, rather it just shows the whole query just as it was written above. i.e. "SELECT T3.total_quantity....." I want to know if it is even possible to use @property field to show a value from another unrelated database table. I have seen some examples on StackOverflow where calculated values are shown using values from the same model with help of self.field_name but i cant find any example where the values for the calculations are derived from another model or from a raw SQL query. Kindly help. Any hint will be very much appreciated. Thanks

http://stackoverflow.com/comment/90342275
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51690184
has text: You can't format text in code. Edited to fix
score: 0

http://stackoverflow.com/a/51762049
upvote count: 1
has body: Just select the columns that you want to keep: df = df'Carbohydrates','Description','1st Household Weight','Sugar Total','Kilocalories'
answers question: http://stackoverflow.com/q/51761961
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/51656674
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90461031
has comment: http://stackoverflow.com/comment/90419183
type: Answer
upvote count: 4
downvote count: 0
has body: To expand on my comment: I'm not sure even SQL case/if statements can get you that result, since the result rows depend on previous rows. This is easy to do procedurally in Python though. The obvious way is to just loop over Ping.objects.all() (or Ping.objects.iterator()) and keep track of the online variable to form the "streaks" you want. This has the downside that you really do need to loop over every object, which will eventually be slow (and/or exhaust your memory). A more complex way, which uses more queries but far less memory, is to find the first Ping object that is offline, then find the next (time-wise) Ping object that is again online -- that'll form one streak. Then rinse and repeat this until you run out of Ping objects to inspect. Edit So yeah, here's a (rather elegant, if you don't mind me saying) concrete implementation of method 2 (find the full test repo at https://github.com/akx/so51656477): class PingQuerySet(models.QuerySet): def streaks(self): queryset = self.values_list('created', 'online').order_by('created') entry = queryset.first() while entry: next_entry = queryset.filter(created__gt=entry[0], online=(not entry[1])).first() yield (entry, next_entry) entry = next_entry It's a generator of 2-tuples of tuples: ((start_timestamp, start_online), (end_timestamp, end_online) | None). For instance, to get the up/down or down/up pairs in the last 10 days, for start, end in Ping.objects.filter(created__gt=now() - timedelta(days=10)).streaks(): print(start, end) will print something like [...snip...] (datetime.datetime(2018, 8, 8, 8, 10, 12, 943500), False) (datetime.datetime(2018, 8, 8, 10, 10, 12, 943500), True) (datetime.datetime(2018, 8, 8, 10, 10, 12, 943500), True) (datetime.datetime(2018, 8, 8, 11, 10, 12, 943500), False) (datetime.datetime(2018, 8, 8, 11, 10, 12, 943500), False) (datetime.datetime(2018, 8, 8, 11, 40, 12, 943500), True) (datetime.datetime(2018, 8, 8, 11, 40, 12, 943500), True) (datetime.datetime(2018, 8, 8, 12, 40, 12, 943500…
accepted answer of: http://stackoverflow.com/q/51656477
has comment: http://stackoverflow.com/comment/90494255
score: 4
answers question: http://stackoverflow.com/q/51656477

http://stackoverflow.com/a/51785692
has comment: http://stackoverflow.com/comment/90531425
score: 1
has comment: http://stackoverflow.com/comment/90528569
has comment: http://stackoverflow.com/comment/90528472
downvote count: 0
type: Answer
has body: Your problem statement reveals an inherent flaw in the design. As you correctly pointed out, you have no way of knowing what the user does, how she has rated other videos, and how she will rate the current video. It would be helpful to explain what your current input values are, and whether they could differ at all. For example, a metric like "time spent watching the video" might be different for different users. On a larger scale, try to answer the question whethre you could answer the rating (with a completely deterministic judgement), i.e. would it be possible for you to come up with the same answer (given the same input), and constantly get the same result? Since that is currently not the case, I would say that you should investigate more time in finding a suitable approach to your problem, like for example recommender systems, but that also requires you to use a lot of different input information. Alternatively, you could try to find more input data, which specifically identifies the users, and allows you to make more suitable predictions; even then, it will be hard to base a reasonable prediction on such proxy metrics, since you might end up creating an unwanted bias in your preprocessing. In any case, getting much better results with the current format of the input is very unlikely.
answers question: http://stackoverflow.com/q/51785432
has comment: http://stackoverflow.com/comment/90560424
upvote count: 1

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/51652872
type: Tag

http://stackoverflow.com/q/51677868
answer count: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90318988
has answer: http://stackoverflow.com/a/51677917
score: 1
favorite count: 0
has body: I'm just looking for a really good hint on solving my problem, not necessarily the complete solution. I can receive the following string over a TCP socket: {"id":"555","jsonrpc":"2.0","result":null,"timestamp":"2018-08-03T17:32:41.894"} this is how I'm reading in the data while True: data = sock.recv(1024).decode('utf-8') if not data: sys.exit(0) I'm trying to parse elements using the following method: if (data["id"] == "555"): print("found it..now call a function!") No matter what I try I get the following TypeError: string indices must be integers I'm using Python version 3.7. I'm new to Python and programming for that matter and I've been at this for days. Thanks in advance!
type: Question
has title: Parse JSON message from socket using Python
tagged with: python

http://stackoverflow.com/comment/90545013
has text: Add `'PIL'` (maybe `'Pillow'`) to `hidden_imports` in the spec file.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51793459

http://stackoverflow.com/a/51773152
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51649361
has comment: http://stackoverflow.com/comment/137424873
downvote count: 1
has body: Well, if you want to process certainly for file handlers, the simplest solution is just to pass filehandlers directly to your class instead of filenames. with open(f1, 'r') as f1, open(f2, 'w') as f2: with MyClass(f1, f2) as my_obj: ... If you don't need custom __exit__ functionality you may even skip nested with. If you really want to pass filenames to __init__, your problem could be solved like this: class MyClass: input, output = None, None def __init__(self, input, output): try: self.input = open(input, 'r') self.output = open(output, 'w') except BaseException as exc: self.__exit___(type(exc), exc, exc.__traceback__) raise def __enter__(self): return self def __exit__(self, *args): self.input and self.input.close() self.output and self.output.close() # My custom __exit__ code So, it really depends on your task, python have plenty options to work with. In the end of the day - pythonic way is to keep your api simple.
score: 4

http://stackoverflow.com/comment/90430148
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51734529
type: AnswerComment
has text: PS, if you;'re using `django,contrib.auth` the current user will be available with `request.user`.

http://stackoverflow.com/comment/90352820
has text: Bazingaa this is almost what I need... I should look exactely how it look like except of the legend. The legend should show the values which are in the array [see above]. It was should show 15, 19, 20, 22 .....It means at a radius of 300 there is the velocity of 15. At radius of 350 is a velocity of 19 and so on... Hope there is a possibiliy with contourplot because I really like how it looks. Best regards and viel spass to you as well !
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51689707

http://stackoverflow.com/q/51669480
has comment: http://stackoverflow.com/comment/90301599
has comment: http://stackoverflow.com/comment/90301670
linked to: http://stackoverflow.com/q/11880430
has comment: http://stackoverflow.com/comment/90301695
type: Question
has comment: http://stackoverflow.com/comment/90301691
has comment: http://stackoverflow.com/comment/90301754
tagged with: if-statement
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90301664
has body: What exactly is wrong with the syntax and why in the following piece of code? I've counted the parentheses among other things yet am unable to figure it out. c = "" print("Yes") if c else print("No") Note: It gives a Syntax error like the one below: print("Yes") if c else print("No") ^ SyntaxError: invalid syntax
linked to: http://stackoverflow.com/q/4728073
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51669723
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/90301712
answer count: 1
linked to: http://stackoverflow.com/q/51342536
favorite count: 0
has comment: http://stackoverflow.com/comment/90301713
has title: Syntax Error in Inline if … else Syntax in Python
has comment: http://stackoverflow.com/comment/90301620
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/90301644
tagged with: python

http://stackoverflow.com/q/51742768
has title: Regex Number - Python
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51742908
has comment: http://stackoverflow.com/comment/90445672
type: Question
has comment: http://stackoverflow.com/comment/90445671
has body: Need to select all the three line numbers 420 1-4094 1,42,100-102,338,420,534,995,999,1050 Regex = (\d+([-,]\d+)+) Regex which i am using is selecting only the last two lines, it need to select even the first line. please help.
score: 0
has comment: http://stackoverflow.com/comment/90445588
answer count: 1
has answer: http://stackoverflow.com/a/51742908

http://stackoverflow.com/comment/90604720
comment on: http://stackoverflow.com/q/51722319
has text: I'm also curious about this, have you tried using the .grab() method? Another option is to use gstreamer source in videocapture and then get gstreamer to drop frames somehow, but not sure.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51650933
score: 0
tagged with: for-loop
answer count: 1
has title: Python template forloop doesn't work more than one time
accepted answer: http://stackoverflow.com/a/51697297
has comment: http://stackoverflow.com/comment/90265343
tagged with: python
tagged with: templates
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90265285
has body: I am new to Python, I am using flask. I am trying to fetch the data from database, which I successfully get. The data is going to be used in multiple place like in different dropdown selects and values in option would be dynamic from database in same index template. But when I run for loop only in template, only the first loop works other doesn't work at all. I have also check the data from database is retrieving. By first loop I mean lets suppose I iterate loop in select dropdown list like this: Python code: def configure_routes(app): @app.route('/') # URL '/' to be handled by main() route handler def main(name=None): ret = class.get_data() return render_template('index.html', name=name, data=ret) HTML markup: Select Target xyz {% for rows in data %} {{rows}} {% endfor %} Now this code works, just next to it there is next select dropdown with the same loop and and the results from same data variable has to be extracted. Select Target tech {% for row2 in data %} {{row2.tech}} {% endfor %} This is my template where i want to add the python code in select options Select Target Technology Choose Expertise Select Target This code or below this any loop doesn't work at all. I would appreciate if someone can help, or someone can guide me how many loops we can use in one html template with Python also how to use them in proper way. THanks.
has comment: http://stackoverflow.com/comment/90265439
has comment: http://stackoverflow.com/comment/90265560
type: Question
has comment: http://stackoverflow.com/comment/90265424
has answer: http://stackoverflow.com/a/51697297
tagged with: flask
has comment: http://stackoverflow.com/comment/90265519

http://stackoverflow.com/q/51653296
possible better answer: http://stackoverflow.com/a/51653416
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90269944
downvote count: 1
has answer: http://stackoverflow.com/a/51653416
type: Question
accepted answer: http://stackoverflow.com/a/51653427
score: -1
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/51653427
has answer: http://stackoverflow.com/a/51653467
favorite count: 0
has title: trying to call python file inside other Python Program
tagged with: python
has body: How to call one python file from another python file Example : I have a file in C:\Python\a1.py Now I am working on a2.py and want to call a1.py from a2.py. How can I achieve that? Also is it mandatory both should be on same location to call other either programs?
has comment: http://stackoverflow.com/comment/90269994

http://stackoverflow.com/comment/90319219
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51677931
type: Comment
has text: Yes, that is how I would do it. HTTP actions taken on /members/ actions should correspond to the corresponding Member class in your backend. This keeps resource actions explicit and distinct. This is a design that is way easier to maintain in the long run.

http://stackoverflow.com/comment/90486657
type: Comment
score: 0
has text: You can just do `df['product'] = df['product'].ffill()`, however, if you want to get back to the grouped df, you can pass the ordinal position of the multi-index: `pd.read_csv(your_file_path, index_col=[0,1])`. So are you wanting to get back a multi-index df?
comment on: http://stackoverflow.com/q/51763941
type: QuestionComment

http://stackoverflow.com/comment/112277682
comment on: http://stackoverflow.com/a/51744034
score: 0
type: AnswerComment
has text: Do you make this before the train_test_split, on the original dataframe, or it should be made after the split on each new X, y set?
type: Comment

http://stackoverflow.com/comment/90521158
type: Comment
type: QuestionComment
has text: do you have some more function definitions in-between generate_dmg and generate_spell_dmg?
comment on: http://stackoverflow.com/q/51781729
score: 0

http://stackoverflow.com/comment/90310154
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51673333
has text: It does work per se. However, I am still not getting the expected channel vaules as output. The period columns are the values of MAXIMUM ENERGY THAT A CHANNEL CAN DETECT. E.g. For Period = 1, Energy = 2.0. Channel 5 can detect only up to 1.76. Whereas, the energy value = 2.0 is greater than. Therefore the correct output should be Channel 6 as it an detect up to 2.02. Right now i am getting the channel number preceding the one i expect.
type: AnswerComment

http://stackoverflow.com/q/51746197
type: Question
has comment: http://stackoverflow.com/comment/90480208
has comment: http://stackoverflow.com/comment/90452426
score: 0
has answer: http://stackoverflow.com/a/51746896
accepted answer: http://stackoverflow.com/a/51746896
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/90452364
has title: TypeError: maketrans() takes exactly 2 arguments (3 given)
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/90452419
has body: The following code adapted from a website for removing punctuations from words. import string filename = 'some_file.txt' file = open(filename, 'rt') text = file.read() file.close() # split the text into words words = text.split() table = str.maketrans('', '', string.punctuation) stripped = [w.translate(table) for w in words] print(stripped[:100]) The error is "TypeError: maketrans() takes exactly 2 arguments (3 given)". I read the Python documentation that says the options for having 1, 2 or 3 arguments of maketrans(). The docs.python.org says: "If there is a third argument, it must be a string, whose characters will be mapped to None in the result". I'm using Python 2. Any idea to clear the error?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90452135
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/51764124
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51764048
answers question: http://stackoverflow.com/q/51764048
type: Answer
upvote count: 3
has body: Use Counter &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c=Counter() &gt;&gt;&gt; for d in l: ... c.update(d) ... &gt;&gt;&gt; dict(c) {'a': 30, 'b': 15}
score: 3
has comment: http://stackoverflow.com/comment/90487278

http://stackoverflow.com/q/51685002
tagged with: regex
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90332637
tagged with: sympy
has answer: http://stackoverflow.com/a/51687488
accepted answer: http://stackoverflow.com/a/51687488
has title: SymPy expression containing function canceled by the inverse of the function
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90337011
has comment: http://stackoverflow.com/comment/90332350
favorite count: 0
has body: from sympy import exp,log import sympy as sym x = sym.Symbol('x') expr = log(exp(x)) print(expr) print(sym.simplify(expr)) diff_expr = x - log(exp(x)) if diff_expr == 0: print('Expression was simplified!') Apparently SymPy can not simplify expressions like these. Is there any way of doing this without having to handle it with string manipulations? I.e. something like this: func_comb = ['exp(log(','cos(acos(','log(exp(','acos(cos(','sin(asin('] # replace string expression with '' and remove surplus ')' expr = str(expr) for func in func_comb: if func in expr: expr = expr.replace(func,'')
tagged with: python

http://stackoverflow.com/q/51733311
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90427439
has comment: http://stackoverflow.com/comment/90427266
has comment: http://stackoverflow.com/comment/90428963
has comment: http://stackoverflow.com/comment/90430266
has comment: http://stackoverflow.com/comment/90427323
linked to: http://stackoverflow.com/q/43839431
accepted answer: http://stackoverflow.com/a/51735513
answer count: 2
has comment: http://stackoverflow.com/comment/90431732
has comment: http://stackoverflow.com/comment/90428499
score: 2
downvote count: 0
tagged with: activation-function
has comment: http://stackoverflow.com/comment/90429737
favorite count: 0
has comment: http://stackoverflow.com/comment/90429980
has title: what activation function should I use to enforce rounding like behaviour
upvote count: 2
has comment: http://stackoverflow.com/comment/90428461
has comment: http://stackoverflow.com/comment/90430581
tagged with: python
has comment: http://stackoverflow.com/comment/90428676
has comment: http://stackoverflow.com/comment/90429437
type: AnsweredQuestion
has body: I need an activation function that rounds my tensors. the derivative(gradients) of the function round() is 0 (or None in tensorflow) which makes it unusable as an activation function. I am looking for a function that enforce rounding-like behaviour so that the results of my model dont just approximate a number. (as my labels are integers) I know that the formulae: tanh ○ sigmoid was used to enforce {-1, 0, 1} numbers only flowing through the model so is there some combination of function that are derivable that simulate rounding behaviour?
has comment: http://stackoverflow.com/comment/90428058
has comment: http://stackoverflow.com/comment/90428886
has comment: http://stackoverflow.com/comment/90430682
has answer: http://stackoverflow.com/a/51735513
has comment: http://stackoverflow.com/comment/90427790
tagged with: derivative
has comment: http://stackoverflow.com/comment/90427901
possible better answer: http://stackoverflow.com/a/51733987
has comment: http://stackoverflow.com/comment/90427552
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90427331
has answer: http://stackoverflow.com/a/51733987

http://stackoverflow.com/a/65843188
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51657128
downvote count: 0
type: Answer
has body: To also check for diagonals, regarding what Casper Dijkstrao asked, I usually write some code like this: def adj_finder(matrix, position): adj = [] for dx in range(-1, 2): for dy in range(-1, 2): rangeX = range(0, matrix.shape[0]) # X bounds rangeY = range(0, matrix.shape[1]) # Y bounds (newX, newY) = (position[0]+dx, position[1]+dy) # adjacent cell if (newX in rangeX) and (newY in rangeY) and (dx, dy) != (0, 0): adj.append((newX, newY)) return adj The function gets the matrix argument to extract the size of its row and column (I use numpy, so matrix.shape returns (row_size, column_size) tuple). It also gets the current cell as pointer argument (it's like (X,Y)). Then It generate adjacent cells, and if they were legit (1. they were not out of the bound, and 2. not identical to reference position), it adds them to adjacent list, adj. I'd like to emphasize that using the above algorithm, you can easily obtain neighbors in farther distances as well. Just modify the range in the for loops, like this: for v in range(0-distance, 1+distance): for h in range(0-distance, 1+distance): ... Where distance is the maximum distance of adjacent you want to let in.

http://stackoverflow.com/comment/90432174
comment on: http://stackoverflow.com/q/51724999
score: 0
type: Comment
has text: You are passing the root logger instance to the session, so all records emitted there will be handled same way as yours. Why not passing a separate logger instance with own configuration (and possibly without propagation to the root logger)? Unfortunately, the script requires too many dependencies to reproduce the error locally, so it's just a notice from reading its code.
type: QuestionComment

http://stackoverflow.com/a/51756753
has body: Are you using requests? You can get access to the JSON as a dictionary by calling output.json() So I think with your code, it would look something like this: output = requests.post(url, data=apache_data, headers=headers) for result in output.json()['result']: print(result['name'], result['status'], result['templateid']) And here's the output: Windows 3 456434 linux_server 3 456434 In your example, Windows and linux_server are two dictionaries in the result list.
type: Answer
answers question: http://stackoverflow.com/q/51756727
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51657864
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: pyinstaller: webbrowser.open doesn't work in packaged app
has body: I have a simple app that runs a local Flask web server and opens a web browser to show it on start up using the following command: webbrowser.open('http://localhost:%d' % port, new=2, autoraise=True) When I run it in development mode, this works fine. However, when it's packaged using pyinstaller and run as an executable, I get this: gvfs-open: http://localhost:5000: error opening location: No application is registered as handling this file The order of the browser's web browser will try is the same in both instances: 'xdg-open', 'gvfs-open', 'gnome-open', 'x-www-browser', 'firefox' I tried using specific commands using webbrowser.get(NAME).open but none worked (except Firefox). It seems like this is a problem with pyinstaller. Is it possible some sort of environment variables are being lost or not exported to executable? I'm using Python 3.5.2 and pyinstaller 3.3.1 on Ubuntu 16.04 with the command pyinstaller --add-data="static:static" app.py EDIT: I have confirmed that the environment variables are indeed being changed: print('XDG_DATA_DIRS: ' + os.environ.get('XDG_DATA_DIRS', 'not found')) yields /usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop in development mode and SOURCE_DIR/dist/linux/app/share in the packaged executable. I'm going to create an issue on the pyinstaller github.
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/123310020
tagged with: ubuntu
score: 5
tagged with: python-3.5

http://stackoverflow.com/a/51705573
has comment: http://stackoverflow.com/comment/90372167
has comment: http://stackoverflow.com/comment/90373556
type: AcceptedAnswer
downvote count: 0
has body: Specify a custom function for the loss: model = Model(inputs=image, outputs=output) alpha = 0.2 model.compile( loss=lambda y_true, y_pred: (1 - alpha) * mse(y_true, y_pred) + alpha * gse(y_true, y_pred), ...) Or if you don't want an ugly lambda make it into an actual function: def my_loss(y_true, y_pred): return (1 - alpha) * mse(y_true, y_pred) + alpha * gse(y_true, y_pred) model = Model(inputs=image, outputs=output) alpha = 0.2 model.compile(loss=my_loss, ...) EDIT: If your alpha is not some global constant, you can have a "loss function factory": def make_my_loss(alpha): def my_loss(y_true, y_pred): return (1 - alpha) * mse(y_true, y_pred) + alpha * gse(y_true, y_pred) return my_loss model = Model(inputs=image, outputs=output) alpha = 0.2 my_loss = make_my_loss(alpha) model.compile(loss=my_loss, ...)
has comment: http://stackoverflow.com/comment/90374914
score: 17
type: Answer
has comment: http://stackoverflow.com/comment/90374425
has comment: http://stackoverflow.com/comment/90372700
has comment: http://stackoverflow.com/comment/90373144
accepted answer of: http://stackoverflow.com/q/51705464
upvote count: 17
has comment: http://stackoverflow.com/comment/90372087
has comment: http://stackoverflow.com/comment/90372215
answers question: http://stackoverflow.com/q/51705464
has comment: http://stackoverflow.com/comment/90372452

http://stackoverflow.com/q/51715711
accepted answer: http://stackoverflow.com/a/58366633
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/8659808
upvote count: 3
tagged with: python-unittest
tagged with: python-requests
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51737019
has answer: http://stackoverflow.com/a/58366633
has answer: http://stackoverflow.com/a/51737019
has title: How can I use requests_mock to unit test a file upload?
favorite count: 0
has body: I'm writing a Python (3) wrapper for an API, and I'm trying to unit test a part of it that requires a file to be uploaded. I would like to verify the filename and the content are sent properly by my client. I'm using Python's unittest library, along with requests and requests_mock for testing this. The way that I was planning to approach this problem was to have a callback function for validating the file is sent and all the headers are properly set. Here's what I have so far: import unittest import requests import requests_mock from my_class import my_class from my_class.API import API class TestAPI(unittest.TestCase): def setUp(self): self.hostname = 'https://www.example.com' def validate_file_upload(self, request, context, filename, content): # self.assertEqual(something, something_else) # better solution goes here def test_submit_file(self): API_ENDPOINT = self.hostname + '/api/tasks/create/file/' DUMMY_FILE = 'file' DUMMY_CONTENT = 'here is the\ncontent of our\nfile' s = API(self.hostname) with open(DUMMY_FILE, 'w+') as f: f.write(DUMMY_CONTENT) with requests_mock.Mocker() as m: def json_callback(request, context): self.validate_file_upload(request, context, DUMMY_FILE, DUMMY_CONTENT) return {} m.post(API_ENDPOINT, json=json_callback) s.upload_file(DUMMY_FILE) I have determined that, upon successful file upload, the request parameter to the validate_file_upload has a couple relevant bits of data, namely request.headers and request.text. Here is the content of both of them after the validate_file_upload function is called: request.headers {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '171', 'Content-Type': 'multipart/form-data; boundary=e1a0aa05f83735e85ddca089c450a21b'} request.text '--e1a0aa05f83735e85ddca089c450a21b\r\nContent-Disposition: form-data; name="file"; filename="file"\r\n\r\nhere is the\ncontent of our\nfile\r\n--e1a0aa05f83735e85ddca089c450a21b--\r\n' Now…
tagged with: python

http://stackoverflow.com/comment/90420483
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51729665
has text: Pro tip. Do not import `*`. You run the risk of overriding other imports and causing issues with your code. Instead import as something like `import tkinter as tk` to prevent any issues with overriding methods from a library.
score: 0

http://stackoverflow.com/a/51757488
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90475100
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51757402
type: Answer
answers question: http://stackoverflow.com/q/51757402
has body: The string passed to the Popen command has already been formatted, so it has no % left to consume the i. Take away the "% i" and I think you'll be fine.

http://stackoverflow.com/comment/90365103
comment on: http://stackoverflow.com/a/51701800
type: AnswerComment
score: 0
has text: why Id 1 come before Id 4?
type: Comment

http://stackoverflow.com/q/51721185
has answer: http://stackoverflow.com/a/51721605
score: 0
tagged with: python
tagged with: python-3.x
has title: Unable to fetch certain columns out of a table
has body: I've written a script in python in combination with selenium to parse certain fields out of a table from a webpage. The fields I'm after are within the headers Home and Handicap. I can get the content within the header Home but can't get the content within the header Handicap. How may I get it? This is my try so far: import time from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome() driver.get("http://info.nowgoal.com/en/League/2018-2019/36.html") time.sleep(3) #intentional delay to let the webpage load it's content soup = BeautifulSoup(driver.page_source,"lxml") for items in soup.select('table#Table3 tr'): name = items.find_all("td")[2].text # stat = items.find_all("td")[5].text #this is not working print(name) driver.quit()
tagged with: selenium
tagged with: web-scraping
upvote count: 1
accepted answer: http://stackoverflow.com/a/51721605
downvote count: 1
tagged with: selenium-webdriver
type: AnsweredQuestion
type: Question
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/127202946
has text: You completly right, however I don't see any problem if your docker won't be sent to production. Juts put the config file in gitnore and you will be fine.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/62280907
type: Comment

http://stackoverflow.com/comment/90307276
score: 0
has text: If he wants to create a service with python, there is no need for cron, he can just use python for this.
comment on: http://stackoverflow.com/q/51672141
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51774662
has answer: http://stackoverflow.com/a/51775029
type: Question
upvote count: 2
tagged with: python
tagged with: pygame
answer count: 3
has comment: http://stackoverflow.com/comment/90508031
accepted answer: http://stackoverflow.com/a/51775029
has answer: http://stackoverflow.com/a/51797485
possible better answer: http://stackoverflow.com/a/51776965
tagged with: keypress
type: AnsweredQuestion
has title: Intepreting held down keys
score: 2
has answer: http://stackoverflow.com/a/51776965
has body: I am building a Raspberry Pi rover written in Python and I am looking to control the rover via SSH. Hence, I would run the script and then want the rover to move in the directions provided by me in real-time, like an RC car (think key up, key down, key left, key right). I read online that one of the possibilities might be to use the pygame.key.get_pressed() function, but this is not working in my shell. When I run that command in my raspberry pi python shell, I only receive a tuple of zeros that times out after a fraction of a second. My code is the following: speed = input('How fast do you want the rover to go? Give a value lower than 1: ') while True: keys = pygame.key.get_pressed() #checking pressed keys if keys == True: if keys[pygame.K_UP]: fwd(speed) if keys[pygame.K_DOWN]: bwd(speed) if keys == False: MS.motor1off MS.motor2off with fwd and bwd being functions that activate the motors in the forward and backward directions. When I run the script, it goes through the loop fine, but the motors do not respond to the key being held. When I added a print statement, I noticed that this was also not printed onto the console. Does anyone have any idea how to proceed with this, please?
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90346036
comment on: http://stackoverflow.com/a/51688000
score: 0
type: AnswerComment
has text: @ppperry I know, but less typing is always better in my opinion :)
type: Comment

http://stackoverflow.com/q/51736770
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51736795
downvote count: 0
tagged with: duplicates
answer count: 2
has comment: http://stackoverflow.com/comment/90434110
favorite count: 0
has body: I have numpy arrays like this: old=([[5.00000000e+00, 3.39622642e-03], [5.00000000e+00, 5.84905660e-04], [1.00000000e+01, 4.15094340e-04], [1.50000000e+01, 2.26415094e-03], [2.00000000e+01, 4.90566038e-02], [2.50000000e+01, 4.90566038e-01], [3.00000000e+01, 4.90566038e-01], [4.00000000e+01, 8.11320755e-01], [4.00000000e+01, 1.00000000e+00]]) where the first column is depth and second column is some measurements. I need to efficiently (fast as there are many of them) average measurements of duplicate rows (rows with same depth) and replace old row with new calculated average like this: new=([[5.00000000e+00, 1.99056600e-03], [1.00000000e+01, 4.15094340e-04], [1.50000000e+01, 2.26415094e-03], [2.00000000e+01, 4.90566038e-02], [2.50000000e+01, 4.90566038e-01], [3.00000000e+01, 4.90566038e-01], [4.00000000e+01, 9.05660377e-01]])
accepted answer: http://stackoverflow.com/a/51736795
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51736829
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51736829
has comment: http://stackoverflow.com/comment/90434132
has title: averaging numpy array duplicate rows efficiently

http://stackoverflow.com/comment/90461068
has text: For info, 11363840=494080*23 and the size of the arrays is 23 before trying to do the insert
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51750300

http://stackoverflow.com/q/51795093
has body: I'm trying to save file on ec2 instance using Python and flask, path: download/generate_file_name.pdf but I have "[Errno 13] Permission denied:" I tried: gunicorn --user=root --bind 0.0.0.0:8000 wsgi --Error-logfile /var/log/flog/error.log But after this I have an error: OSError: [Errno 1] Operation not permitted: '/tmp/wgunicorn-kKEd4G' sudo gunicorn - also doesn't work! I already shared permissions for this download folder chmod 777 - doesn't work What do I need to do for save file in local folder inside ec2
score: 1
has title: How to start gunicorn with sudo permission on flask
type: Question
answer count: 1
downvote count: 0
tagged with: amazon-ec2
tagged with: flask
tagged with: python
favorite count: 0
tagged with: gunicorn
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51804350

http://stackoverflow.com/q/51694068
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/56202161
upvote count: 2
has title: Python imutils: Illegal instruction
accepted answer: http://stackoverflow.com/a/56202161
answer count: 1
has body: I have a python3 script on my computer that I can run with python3 motion_detection.py and that works, I tried to use it on my Raspberry and something fails with message Illegal instruction. The line that throws this error is: frame = imutils.resize(frame, width=500) Here is the minimalist sample of code: import imutils import cv2 frame = cv2.imread('test.jpg') frame = imutils.resize(frame, width=500) I'm sure that frame is not None because I tried to save it and it worked. I'm a bit confused because there is no more explaination that Illegal instruction I checked the version of imutils that is the same on my computer that on the Raspberry (0.4.6)
tagged with: raspberry-pi
tagged with: imutils
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51748121
favorite count: 0
has comment: http://stackoverflow.com/comment/90457391
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90456250
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/90461002
has comment: http://stackoverflow.com/comment/90456686
has comment: http://stackoverflow.com/comment/90456848
downvote count: 1
has comment: http://stackoverflow.com/comment/90458780
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90457085
has answer: http://stackoverflow.com/a/52032994
answer count: 1
score: -1
has body: I am trying to get a library and install it. For some reasons I just can't get it. When i try to install the package : "Could not find a version that satisfies the requirements setupfiles(from version:) No matching distribution found for setupfiles." Package name : setupfiles Pip version : 18.0 the error is : could not find a version that satisfies the requirements setupfiles(from version ==). for some reason's its had been removed from github (https://libraries.io/pypi/setupfiles/0.0.50). its seems that the library directly effects half of project (get==0.0.21,post=0.0.13,public=0.0.38...) how do i able to get it? and install (env) C:\Users\ido\Desktop\arrowfind&gt; (env) C:\Users\ido\Desktop\arrowfind&gt;pip install setupfiles Collecting setupfiles Could not find a version that satisfies the requirement setupfiles (from versions: ) No matching distribution found for setupfiles upload image not working, link included : https://i.sstatic.net/uffwd.png
has comment: http://stackoverflow.com/comment/90457152
has comment: http://stackoverflow.com/comment/90484789
has comment: http://stackoverflow.com/comment/90457209
has comment: http://stackoverflow.com/comment/90457460
has comment: http://stackoverflow.com/comment/90484855
has title: I am trying to install setupfiles package from pip
has comment: http://stackoverflow.com/comment/90456911

http://stackoverflow.com/q/51711374
accepted answer: http://stackoverflow.com/a/51711612
has body: I have a very basic question (first time i use Flask, i am not used to web frameworks). I would simply like to update variables in a template e.g. hello.html nothing else (i don't care about routes or anything at the moment) i do that according to a tutorial: from flask import Flask, render_template app = Flask(__name__) x=1986 res=render_template('hello.html', myVar = x) print(res) if __name__ == '__main__': app.run(debug = True) Please note that i have a html file name hello.html in a subdir called templates. hello.html: Hello {% print(myVar) %} what am i doing wrong? edit. i get this error message: Traceback (most recent call last): File "flask_test1.py", line 7, in <module> res=render_template('hello.html', myVar = x) File "/root/miniconda3/lib/python3.4/site-packages/flask/templating.py", line 133, in render_template ctx.app.update_template_context(context) AttributeError: 'NoneType' object has no attribute 'app' P.s. sorry about my "clumsyness" with web frameworks...
score: 0
possible better answer: http://stackoverflow.com/a/51711443
downvote count: 1
has answer: http://stackoverflow.com/a/51711443
has title: Python Flask template update
tagged with: flask
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51711612
favorite count: 0
type: Question
answer count: 2
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/93819077
has text: I had the same error message when running `coremltools.converters.keras.convert` to convert a keras model to coreml. The error was resolved by downgrading to `2.1.6` via `pip install keras==2.1.6`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51756108
type: Comment

http://stackoverflow.com/comment/90366709
comment on: http://stackoverflow.com/q/51698989
type: Comment
type: QuestionComment
has text: @iamanigeeit, the trouble is to select only the values of cm_inc vector and ignoring the date column.Any idea?Thanks
score: 0

http://stackoverflow.com/a/51952509
answers question: http://stackoverflow.com/q/51785194
downvote count: 0
has comment: http://stackoverflow.com/comment/90922076
type: Answer
has comment: http://stackoverflow.com/comment/90963807
has comment: http://stackoverflow.com/comment/90987224
upvote count: 1
has comment: http://stackoverflow.com/comment/90855412
has body: Might I extend @hoechenberger's answer to add support for the randomised start on each trial (set markerPos to a random val in units of the tick marks) keypress support (just use keys to adjust markerPos and when you're done assign that to rating) custom step sizes (when you've understood (2) then this is probably obvious) Python2.7 (no need to force Py3.6 here :wink: ) Here's the code: from psychopy import visual from psychopy import event from numpy.random import random stepSize = 2 win = visual.Window() vas = visual.Slider(win, ticks=(0, 1), labels=('Not at all confident', 'Extremely confident'), granularity=1, color='white') for thisTrialN in range(5): vas.reset() vas.markerPos = random() # randomise start while not vas.rating: # check keys keys = event.getKeys() if 'right' in keys: vas.markerPos += stepSize if 'left' in keys: vas.markerPos -= stepSize if 'return' in keys: # confirm as a rating vas.rating = vas.markerPos # update the scale on screen vas.draw() win.flip() print('Rating: {}, RT: {}'.format(vas.rating, vas.rt))
score: 1

http://stackoverflow.com/comment/90288552
comment on: http://stackoverflow.com/q/51662546
has text: All that has been posted is a program description. However, we need you to [ask a question](//stackoverflow.com/help/how-to-ask). We can't be sure what you want from us. Please [edit] your post to include a valid question that we can answer. Reminder: make sure you know [what is on-topic here](//stackoverflow.com/help/on-topic); asking us to write the program for you and suggestions are off-topic.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51739720
linked to: http://stackoverflow.com/q/51720406
type: Question
has comment: http://stackoverflow.com/comment/134115017
tagged with: package-management
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/130446904
type: UnansweredQuestion
tagged with: apt
tagged with: python
tagged with: debian
has title: installing debian packages programmitically using apt_pkg package (python-apt)
answer count: 0
score: 1
has body: I've built some debian packages and put them on my host. I want to install these packages in a python script. So I've written the install function using apt_pkg as follows : #!/usr/bin/env python # -*- coding: utf-8 -*- import apt import apt_pkg import sys class my_pkg_manager: def __init__(self): apt_pkg.init() self.cache = apt_pkg.Cache() self.sources = apt_pkg.SourceList() self.pkg_records = apt_pkg.PackageRecords(self.cache) self.depcache = apt_pkg.DepCache(self.cache) self.pkg_manager = apt_pkg.PackageManager(self.depcache) self.fetcher = apt_pkg.Acquire() def find_my_package(self): for pkg in self.cache.packages: if len(pkg.version_list)&gt;0: package_site = pkg.version_list[0].file_list[0][0].site if package_site == 'my_host_address.com': if pkg.name == 'my_pkg_name': return pkg return None def install_package(self, pkg): self.depcache.mark_install(pkg) self.sources.read_main_list() self.pkg_manager.get_archives(self.fetcher, self.sources, self.pkg_records) log_file = open('install_log','w') res = self.pkg_manager.do_install(log_file.fileno()) if res == self.pkg_manager.RESULT_COMPLETED: print('result completed!') elif res == self.pkg_manager.RESULT_INCOMPLETE: print('result incomplete!') else: print('result failed!') def run(self): my_pkg = self.find_my_package() if my_pkg != None: self.install_package(my_pkg) else: print('Can't find package!') if __name__ == '__main__': my_package_manager = my_pkg_manager() my_package_manager.run() If I use apt-get install, packages will be installed without any problem, but with this script the following error occurs : res = self.pkg_manager.do_install(log_file.fileno()) apt_pkg.Error: E:Internal Error, Pathname to install is not absolute 'myPackage_1.0.0_all.deb' I've placed .deb file and Packages.gz in a directory named 'debian' in my host and added the following line to my sources.list : deb http://my_host_address.com debian/ I don't know what is wrong with my script?
upvote count: 1

http://stackoverflow.com/comment/90502621
type: QuestionComment
comment on: http://stackoverflow.com/q/51715889
has text: Possible duplicate of [Python List Bracket Removal](https://stackoverflow.com/questions/9969099/python-list-bracket-removal)
score: 0
type: Comment

cas
tags question: http://stackoverflow.com/q/51652452
tag name: cas
type: Tag

http://stackoverflow.com/q/51659080
score: 0
has comment: http://stackoverflow.com/comment/90282169
has comment: http://stackoverflow.com/comment/90281737
has body: I have two tables: class Project(DataBase): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True, nullable=False) name = Column(String, nullable=False, unique=True) domain = Column(String, nullable=False) phrases = relationship("Phrase", backref='proj') def __init__(self, name, domain): self.name = name self.domain = domain class Phrase(DataBase): __tablename__ = 'phrases' query_id = Column(Integer, primary_key=True, autoincrement=True, nullable=False) query_text = Column(String, nullable=False) project = Column(Integer, ForeignKey('projects.id'), nullable=False) enable = Column(Boolean, nullable=False, default=True) def __init__(self, query_text, project, city): self.query_text = query_text self.project = project And I have a function: def get_first_query(): session = Session(bind=engine) q = session.query(Phrase).filter(Phrase.enable == True).first() session.close() return q I want to get an object from table 2 and than get its parrent from first table: session = Session(bind=engine) q = get_first_query() print(q.proj) It doesn't work and print this error: sqlalchemy.orm.exc.DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'proj' cannot proceed I can do this: session = Session(bind=engine) q = get_first_query() q_project = session.query(Project).filter(Project.id == q.project) But it's a bad way.
tagged with: sqlite
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51671558
type: UnansweredQuestion
tagged with: orm
has title: How to get parrent of object in session SQLAlchemy
upvote count: 1
downvote count: 1
tagged with: sqlalchemy
type: Question
answer count: 1
tagged with: flask

http://stackoverflow.com/comment/90519955
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51780856
score: 0
has text: @ThijsW Yes, that's how i will reduce the time complexity of the code.

http://stackoverflow.com/comment/90527171
score: 0
type: AnswerComment
has text: IMREAD_UNCHANGED worked for normal image which I converted to grey scale and stored. But, not working for my use case. It is reading as 3 channel only.
comment on: http://stackoverflow.com/a/51784896
type: Comment

http://stackoverflow.com/comment/90251604
comment on: http://stackoverflow.com/a/51643461
score: 0
type: AnswerComment
type: Comment
has text: Only if you are setting the `implicitwait` to more than `0`, which is the default. I will put in a note to be aware of this.

http://stackoverflow.com/a/51659571
has comment: http://stackoverflow.com/comment/90283090
has comment: http://stackoverflow.com/comment/90283252
has comment: http://stackoverflow.com/comment/90283806
has body: IIUUC, within each Trade group you need to find the last index of the occurrence of either Long or Short and then grab the row below that. There are a lot of things that can go wrong, and I don't know how you want to handle that. What happens if a Trade group never contains Long or Short. (Currently this will throw and IndexError) What do you want to do if the last row in your DataFrame is Long or Short So you can add exceptions to deal with these cases separately (like try and except). At least from your sample data, You can do something like: ids = df.reset_index().groupby('Trade').apply(lambda x: x[x.Position.isin(['Long', 'Short'])].index[-1]+1) df.reset_index().reindex(ids)['Date_Time'] Output: 1 2018-07-16 13:30:00 6 2018-07-16 17:00:00 11 2018-07-16 19:30:00 15 2018-07-16 21:30:00 25 2018-07-17 02:30:00 26 NaT Name: Date_Time, dtype: datetime64[ns] Now you can just join these to your aggregation result if needed. As you can see my last line is NaT because there is no row after the last Long value for group 6 in your DataFrame One safer way might be: def next_id(x): try: return x[x.Position.isin(['Long', 'Short'])].index[-1]+1 except IndexError: pass ids = df.reset_index().groupby('Trade').apply(lambda x: next_id(x))
has comment: http://stackoverflow.com/comment/90283176
has comment: http://stackoverflow.com/comment/90311951
answers question: http://stackoverflow.com/q/51658976
has comment: http://stackoverflow.com/comment/90311968
accepted answer of: http://stackoverflow.com/q/51658976
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/90283366
has comment: http://stackoverflow.com/comment/90282870
upvote count: 1

http://stackoverflow.com/a/51735291
has comment: http://stackoverflow.com/comment/117087368
has comment: http://stackoverflow.com/comment/97704767
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/51713059
has comment: http://stackoverflow.com/comment/97720595
answers question: http://stackoverflow.com/q/51713059
downvote count: 0
has body: I've figured it out: just subclass Wagtail's BaseAPIEndpoint. For example: endpoints.py from wagtail.api.v2.endpoints import BaseAPIEndpoint class SpotlightsAPIEndpoint(BaseAPIEndpoint): ... model = Spotlight api.py from .endpoints import SpotlightsAPIEndpoint api_router.register_endpoint('spotlights', SpotlightsAPIEndpoint) Plus there are tons of ways to customize it. Just take a look at the endpoints.py file in the Wagtail repo: https://github.com/wagtail/wagtail/blob/master/wagtail/api/v2/endpoints.py
upvote count: 8
type: AcceptedAnswer

http://stackoverflow.com/comment/90296144
has text: You can get an enormous speedup by **using the 200-year-old heuristic [Warnsdorf's rule](https://en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorf's_rule)**, which says pick the square from which there are fewest onward moves; this nudges you towards edges, corners and areas you've already visited. So instead of having a `isSafe()` returning boolean, you would now have `onwardMoves()` returning int 0..8, and you pick the candidate with the lowest (>=1). Supposedly you can do in this in linear time.
comment on: http://stackoverflow.com/q/51665568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51771585
has body: Problems 1. Switching Screen before populating my_label.text Populating of my_label.text was done after screen is switched, self.manager.current = "three". 2. ScreenThree - Blank/Black Window ScreenThree instantiated twice. The first instance is created in kv file by ScreenThree: (this is equivalent to ScreenThree() in Python Code). The second instance is created in Python code, screenThree = ScreenThree(). The populating of the my_label.text is in the second instance/object and not in the first instance. Therefore, the ScreenThree is blank/black window because app is using the view as per kv file i.e. the first instance of ScreenThree. Note: If you add id() function, it will shows different memory locations for the screens. def pressedFunction(self, instance, *args): self.manager.current = "three" self.debug() screenThree = ScreenThree() print("screenThree={0}, id(screenThree)={1}".format(screenThree, id(screenThree))) self.debug() text = str(instance.text) screenThree.changing_label(text) def debug(self): print("\ndebug:") print("\tself.manager.screen_names=", self.manager.screen_names) print("\tself.manager.screens=", self.manager.screens) for x in self.manager.screens: print("\t\tscreen={0}, id(screen)={1}".format(x, id(x))) Solution kv file Add id: screen_two under ScreenTwo:. This will be used to reference class attributes / methods in ScreenTwo. Replace app.root.current = "two" with root.manager.current = "two" because every screen has by default a property manager Python code Add import statement, from kivy.properties import StringProperty Declare StringProperty inside class ScreenTwo(), text = StringProperty('') so there is no need to pass parameters around and also encapsulation. In pressedFunction() method, replace text = str(instance.text) with self.text = str(instance.text) Populate text before switching screen In class ScreenThree(), rename changing_label() method to on_pre_enter() method, and remove text from the argument list. Replace self.ids.my_lab…
answers question: http://stackoverflow.com/q/51766655
type: Answer
score: 0

http://stackoverflow.com/q/51734041
answer count: 1
downvote count: 0
favorite count: 0
tagged with: exception
tagged with: python
has body: I can't get Warnings module to work in Python 2.7 Inside a user defined function I have: warnings.simplefilter('always', UserWarning) #added after wouldn't work warnings.warn('WARNING: ....') print "Why didn't the warning above show up?" The print statement appears, but not the warning on the terminal. I made sure to do import warnings as well. Not sure what is happening.
has answer: http://stackoverflow.com/a/51734355
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: warnings
accepted answer: http://stackoverflow.com/a/51734355
has title: Warnings module not working in Python 2.7?
type: Question
tagged with: python-2.7

event-sourcing
tags question: http://stackoverflow.com/q/51795961
tag name: event-sourcing
type: Tag

http://stackoverflow.com/q/51787702
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90532806
has title: NameError: name 'my_func' is not defined despite import
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90532882
has body: I'm quite new to Python. I have a file helpers.py (in the root) with def my_func(integer, tokenizer): and another function in models/attention.py (in a models subdirectory) that calls that function: from helpers import my_func .... def another_func(input_seq, tokenizer): some_val = my_func(index, tokenizer) PyCharm is quite happy and I can navigate to the my_func definition by clicking on it. However, when running or debugging I get an error from the import line of attention.py. ImportError: cannot import name 'my_func' Is it because the helpers module is in the root? If it's relevant, I'm running Python 3.6 inside a Conda environment on macOS. Update: there's only one helpers.py in my code, but others in different libraries: Update 2: I'm launching from an evaluate.py in my root. I added the print(helpers.__file__) as suggested and get the expected path: /Users/nic/anaconda2/envs/nmt-keras/bin/python /Users/nic/git/nmt-keras/evaluate.py Using TensorFlow backend. /Users/nic/git/nmt-keras/helpers.py I then changed the call to some_val = helpers.my_func(index, tokenizer) and it works like that! Why?
has comment: http://stackoverflow.com/comment/90532561
upvote count: 1
has comment: http://stackoverflow.com/comment/90532798
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90532596

http://stackoverflow.com/comment/90374505
comment on: http://stackoverflow.com/q/51705792
type: Comment
type: QuestionComment
score: 1
has text: I was just asking to guide me through this problem . Any link any blog would be useful

http://stackoverflow.com/q/51676464
tagged with: append
has answer: http://stackoverflow.com/a/62585909
has comment: http://stackoverflow.com/comment/90317138
downvote count: 0
has answer: http://stackoverflow.com/a/51676857
type: Question
tagged with: numpy
score: 14
has title: Python Numpy append array without flattening
has comment: http://stackoverflow.com/comment/105430101
has answer: http://stackoverflow.com/a/51676708
tagged with: arrays
upvote count: 14
has answer: http://stackoverflow.com/a/65925352
has body: In Python 3 I am importing several data files in a loop, and I would like to be able to store all the data in a single 2-dimensional array. I start with something like data = np.array([]) and on each iteration i want to add a new array datai = np.array([1,2,3]), how can I get my final array to look like this? [[1,2,3],[1,2,3],...,[1,2,3]] I have tried np.append, np.concatenate, and np.stack, but none seem to work. An example code that I'm trying: data = np.array([]) for i in range(datalen): datai = *func to load data as array* data = np.append(data, datai) but of course this returns a flattened array. Is there any way I can get back a 2-dimensional array of length datalen with each element being the array datai? Thanks!
tagged with: flatten
has comment: http://stackoverflow.com/comment/90316629
favorite count: 0
has comment: http://stackoverflow.com/comment/90317999
has answer: http://stackoverflow.com/a/51676921
has comment: http://stackoverflow.com/comment/90316682
answer count: 5
has comment: http://stackoverflow.com/comment/90316147
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51790924
tagged with: parsing
has body: The context is that I have extracted the 'chemical contents' from different forms into free texts. The end goal is to organize the extracted files into a structured database like this: final structured data But the problems is that the extracted text files come in different formats: Some with the chemical &amp; corresponding values lined up row by row (which is good) good example; Some are by column (I guess not too bad) not too good but okay Some are also like this (which is kinda headache) : headache example So my question is: Any suggestions on how to more efficiently read and organize the extracted text into the structured database (as I have shown in the beginning), besides defining all possible templates for reading those extracted texts? I'm really new to text processing, so any help would e greatly appreciated.
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: freeform
score: 0
has comment: http://stackoverflow.com/comment/90559632
has title: python NLP parsing unstructured data
has comment: http://stackoverflow.com/comment/90539860
tagged with: python
tagged with: nlp

http://stackoverflow.com/q/51656942
favorite count: 0
has body: I have tons of json files and I'd like to see their connections with each other on my website as a network graph. There are a lot of tools for that in python, but my extra wish is to manipulate these network graphs: the vertex should be clickable, removable and the user can draw a line between two vertex so a new connection gets created. Similar stuff can be done with vis.js, node.js, neo4j, arangodb, but as I see python libraries for that like seaborn, plotly, bokeh, their graphs are not interactive. Should I go ahead and get to know with js tools mentioned above or are there something like this already written in python? Thanks
has comment: http://stackoverflow.com/comment/90277616
has comment: http://stackoverflow.com/comment/90317804
answer count: 0
type: UnansweredQuestion
has title: editable graph tool in python to website
tagged with: python
has comment: http://stackoverflow.com/comment/90380674
downvote count: 0
has comment: http://stackoverflow.com/comment/90336127
has comment: http://stackoverflow.com/comment/90317317
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90277589
tagged with: graph
upvote count: 1

http://stackoverflow.com/comment/90442036
has text: So you can't change anything inside the `"` symbols?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51740396

http://stackoverflow.com/q/51700493
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/51700609
has title: How many types of pygame display?
has comment: http://stackoverflow.com/comment/90362564
type: Question
upvote count: 0
answer count: 1
tagged with: pygame
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has body: I'm learning about pygame display. Basic of setting display I knew is like this: import pygame pygame.init() display = pygame.display.set_mode((1000, 500)) but, I noticed I can add features in back like this: pygame.FULLSCREEN pygame.RESIZEABLE pygame.DOUBLEBUF Are there anything features I can add? (+Features) pygame.

http://stackoverflow.com/q/51767783
score: 0
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/51767982
has answer: http://stackoverflow.com/a/51767959
has body: I made the following code which generates a random letter from list l every 3 seconds. The first part of my question is how do I terminate this process after 1 minute? import threading import random x = [] def printit(): threading.Timer(3.0, printit).start() l = ['a', 'b', 'c', 'd'] secure_random = random.SystemRandom() print x.append(secure_random.choice(l)) printit() moreover I want to make another list from those randomly chosen letters and call it x the code above does the job, there is a little problem: when I turn the code it starts printing None, and when I interrupt and print x it gives the list of letters and keeps printing None after that, this is because I don't know how to terminate the process after one minute.
has title: Generating a random list and termination of it
possible better answer: http://stackoverflow.com/a/51767959
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51768236
tagged with: list
accepted answer: http://stackoverflow.com/a/51768236
type: Question
tagged with: function

http://stackoverflow.com/q/51659879
has answer: http://stackoverflow.com/a/51660026
accepted answer: http://stackoverflow.com/a/51660026
answer count: 5
has answer: http://stackoverflow.com/a/51660314
has answer: http://stackoverflow.com/a/51659940
tagged with: python
has body: Suppose i have the following tuple as: a = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) What i want to do is reversing certain parts of the tuple. For example 4 elements stays same and then 4 elements will be reversed. I want to get the following result: a = (1,2,3,4,8,7,6,5,9,10,11,12,16,15,14,13,17,18,19,20) How can i achieve that (as pythonian kind of way)? Thanks...
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90283228
has comment: http://stackoverflow.com/comment/90283227
possible better answer: http://stackoverflow.com/a/51659948
type: Question
score: 1
has title: Python Reversing Certain Parts of Tuple
upvote count: 2
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51660086
downvote count: 1
has comment: http://stackoverflow.com/comment/90283626
has answer: http://stackoverflow.com/a/51659948
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51690006
tagged with: api
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: blueprint
score: 1
has body: I'm trying to create a URL prefix for my web app's api. I want the api to return when I enter api.website.com/parameter.I am using Flask and Blueprint api_bp = Blueprint('api', __name__, template_folder='templates', url_prefix='/api') @api_bp.route("/") def get_monkey_api(): address = request.args.get('address', None) if address and is_a_banano_address(address): return monkey_api(banano_address) else: return render_template("NotABananoAddress.html"), 400 @api_bp.route("/&lt;address&gt;") def monkey_api(address): monKey = monkey_data_generator.generate_monKey(address) if monKey.status is not 'Citizen': return "API data on vanity monKeys does not exist" return jsonify(monKey.serialize()) app = Flask(__name__) app.register_blueprint(api_bp, url_prefix='/api') Most of the code in unrelated. The fact is when I I am entering api.website.com?address=xxx or when I am entering api.website.com/xxx I should get my API as JSON back but I'm not. On localhost it doesn't return anything and doesn't show the prints that I even insert into the code and of course on Heroku it does not recognize the project when I using the prefix.
upvote count: 1
type: Question
has title: URL prefix in Flask Python deployed to Heroku using Blueprint
has answer: http://stackoverflow.com/a/51690030
tagged with: flask
tagged with: routes

http://stackoverflow.com/comment/90324630
type: Comment
has text: My intuition says that the errors from the logarithms won't tend to cancel out when summed because of Jensen's Inequality (i.e. log of a mean is not the mean of logs), though I'm happy to be proved wrong here.
type: QuestionComment
comment on: http://stackoverflow.com/q/51679845
score: 0

http://stackoverflow.com/comment/90570395
has text: I haven't explained it very well but it's a cum count of unique values. I'll change the question now.
comment on: http://stackoverflow.com/q/51778723
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51665087
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/90294028
answer count: 4
has answer: http://stackoverflow.com/a/60202484
has answer: http://stackoverflow.com/a/51666746
upvote count: 5
type: Question
score: 5
has answer: http://stackoverflow.com/a/51666289
downvote count: 0
tagged with: flask
has title: Python: Download zip file from RestAPI
has answer: http://stackoverflow.com/a/61073577
has body: Third party RestAPI provides server log file, at a moment we are downloading log file using curl command like curl -H "X-Auth-Token: XXXXXXXXXXXXXXXXXXXXXXXXXX" https://host_address/api/v3.0/admin/logs -o logs.zip but I am trying to create simple dashboard using Flask/Python, Here is my Python/Flask code for the route: @app.route('/download/server/logs') def download_log(): import requests from flask import send_file res = requests.get('http://&lt;rest_api_host&gt;/v1.2/admin/logs', stream=True) return send_file( res.content, attachment_filename='console_log.zip', mimetype='application/zip' ) But when I hit that url from browser I get below error, Traceback (most recent call last): ... ... ... File "/Users/admin/Documents/project/__init__.py", line 940, in download_console_logs res.content, File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/requests/models.py", line 823, in content self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes() File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/requests/models.py", line 745, in generate for chunk in self.raw.stream(chunk_size, decode_content=True): File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/urllib3/response.py", line 436, in stream data = self.read(amt=amt, decode_content=decode_content) File "/Users/admin/Documents/project/venv3/lib/python3.6/site-packages/urllib3/response.py", line 384, in read data = self._fp.read(amt) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 449, in read n = self.readinto(b) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 497, in readinto self._close_conn() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 403, in _close_conn fp.close() AttributeError: 'NoneType' object has no attribute 'close' I put the breakpoint/debugger using PyCharm and able to see that res.content contains …
has comment: http://stackoverflow.com/comment/90362185
favorite count: 0
has comment: http://stackoverflow.com/comment/90294318
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90377608

http://stackoverflow.com/a/51656826
score: 0
has body: from functools import reduce def repeat(df,number): series1 = np.tile(np.array(df['value to add']),number) series2 = reduce((lambda x,y: np.append(x,y+x[-1])),[np.array(df['cumulative value'] for i in range(number)]) series3 = reduce((lambda x,y: np.append(x,y+x[-1])),[np.array(df['hours'] for i in range(number)]) return(pd.DataFrame({'hours':series3,'cumulative value':series2,'value to add':series1}) Running this function with number=3 gives hour cumulative value value to add 0 1 1 1 1 2 2 1 2 3 5 3 3 4 6 1 4 5 7 1 5 6 8 1 6 7 11 3 7 8 12 1 8 9 13 1 9 10 14 1
answers question: http://stackoverflow.com/q/51656402
type: Answer

http://stackoverflow.com/comment/90532333
comment on: http://stackoverflow.com/q/51787400
type: Comment
type: QuestionComment
has text: A decorator would require being added in each concrete subclass. Since you want to guarantee that each subclass does this, adding it in the base class is the way to go - that's what inheritance is there for. In Python, it is absolutely fine for an ABC to be *partially* concrete. The builtin ABCs, such as Set, Mapping and the like, do the same.
score: 0

http://stackoverflow.com/comment/90354866
score: 1
comment on: http://stackoverflow.com/q/51696767
has text: It's not *required*. Pylint is about style issues, that's all.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51691310
answers question: http://stackoverflow.com/q/51691270
downvote count: 1
has comment: http://stackoverflow.com/comment/90344400
type: Answer
has comment: http://stackoverflow.com/comment/90344390
has body: The result of re.escape("\t+") is '\\\t\\+'. Note that the + sign is escaped with a backslash and is not a special character anymore. It does not mean "one or more tabs."
score: 1
upvote count: 2

http://stackoverflow.com/a/64264684
type: Answer
has body: My tensorflow version is 2.1, and I found my tensorflow-estimator version is 2.2 My fix is to downgrade the estimator to the same version
score: 0
answers question: http://stackoverflow.com/q/51724309

qtablewidget
tags question: http://stackoverflow.com/q/51672962
type: Tag
tag name: qtablewidget
tags question: http://stackoverflow.com/q/51763182
tags question: http://stackoverflow.com/q/51700517

http://stackoverflow.com/q/51657000
has title: How to convert an HTML table into a Python dictionary
possible better answer: http://stackoverflow.com/a/51657245
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: dictionary
favorite count: 0
tagged with: python-3.x
score: 15
answer count: 3
has answer: http://stackoverflow.com/a/51657193
downvote count: 1
upvote count: 16
accepted answer: http://stackoverflow.com/a/51657193
has answer: http://stackoverflow.com/a/51657245
has answer: http://stackoverflow.com/a/51657104
has body: I have the following HTML excerpt in a format of a Python list that I'd like to turn into a dictionary. It is a timetable for everyday of the week. [u' \n \n \n Mon \n \n 2:00 pm - 3:00 pm 5:00 pm - 10:00 pm\n \n \n \n \n\n \n Tue \n \n 2:00 pm - 3:00 pm 5:00 pm - 10:00 pm\n \n \n \n \n\n \n Wed \n \n 2:00 pm - 3:00 pm 5:00 pm - 10:00 pm\n \n \n Open now\n \n \n\n \n Thu \n \n 2:00 pm - 3:00 pm 5:00 pm - 10:00 pm\n \n \n \n \n\n \n Fri \n \n 2:00 pm - 3:00 pm 5:00 pm - 10:00 pm\n \n \n \n \n\n \n Sat \n \n 5:00 pm - 10:00 pm\n \n \n \n \n\n \n Sun \n \n Closed\n \n \n \n \n\n \n '] The wishful output is: { 'Mon': ['2:00pm - 3:00pm', '5:00pm - 10:00pm'], 'Tue': ['2:00pm - 3:00pm', '5:00pm - 10:00pm'], 'Wed': ['2:00pm - 3:00pm', '5:00pm - 10:00pm'], 'Thu': ['2:00pm - 3:00pm', '5:00pm - 10:00pm'], 'Fri': ['2:00pm - 3:00pm', '5:00pm - 10:00pm'], 'Sat': '5:00pm - 10:00pm', 'Sun': 'Closed' } How would you achieve this in Python 3.x? I would not mind if the 'Sat' and 'Sun' keys have values in a list format if that'd help at all. Thank you for your thoughts in advance.

http://stackoverflow.com/q/51713803
has comment: http://stackoverflow.com/comment/90389887
has title: django create row on user creation
has body: class Student(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) dob = models.DateField(blank=True, null=True) student_rank = models.OneToOneField( StudentRankSignoff, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.username` When a Student signs up, i want to have the StudentRankSignoff table contain a blank row. How do I go about doing this?
type: Question
has comment: http://stackoverflow.com/comment/90389364
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/90261190
comment on: http://stackoverflow.com/q/51646047
score: 0
type: QuestionComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177261/discussion-between-howard-geng-and-user9538877).

series
tag name: series
tags question: http://stackoverflow.com/q/51693831
tags question: http://stackoverflow.com/q/51720780
type: Tag
tags question: http://stackoverflow.com/q/51644984
tags question: http://stackoverflow.com/q/51782932
tags question: http://stackoverflow.com/q/51776923
tags question: http://stackoverflow.com/q/51778480
tags question: http://stackoverflow.com/q/51776454
tags question: http://stackoverflow.com/q/51672709
tags question: http://stackoverflow.com/q/51650855
tags question: http://stackoverflow.com/q/51708565
tags question: http://stackoverflow.com/q/51780844
tags question: http://stackoverflow.com/q/51658287

http://stackoverflow.com/comment/90247090
type: Comment
type: QuestionComment
has text: Hmm, I just created a new project with the same setup as yours under Django 2.0 and it is working fine
score: 0
comment on: http://stackoverflow.com/q/51640882

http://stackoverflow.com/a/51700889
type: Answer
has comment: http://stackoverflow.com/comment/90388510
answers question: http://stackoverflow.com/q/51698016
has body: Don't know if this solves! If redirecting is the issue you can use: yield scrapy.Request(url=url, callback=self.parse , meta={'dont_redirect': True}) This will prevent spider from redirecting.
score: 0
has comment: http://stackoverflow.com/comment/90388763

http://stackoverflow.com/comment/90542111
has text: "I will not even put what I have tried, since I have failed miserably.". Please post your attempt, and a detailed explanation of the failure.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51791933
score: 0

http://stackoverflow.com/comment/90246433
has text: do you have `polls` added to your INSTALLED_APPS in settings.py? @Encode.to.code
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51640936

http://stackoverflow.com/q/51684920
tagged with: function
tagged with: class
has answer: http://stackoverflow.com/a/51685086
accepted answer: http://stackoverflow.com/a/51685086
score: 0
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/90333022
possible better answer: http://stackoverflow.com/a/51685103
tagged with: python
has title: python class managing in another class
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90332187
upvote count: 1
has comment: http://stackoverflow.com/comment/90332034
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51685103
has body: I have a class called martCrawler which import other 3 crawlers from other files However, the code becomes too long as the crawler imported increased. Is there a better practice managing the code like this? Thanks in advance~ from Scripts_mart.wat_ver2 import crawler_watsons from Scripts_mart.cosmed_ver1 import crawler_cosmed from Scripts_mart.pxmart_ver1 import crawler_pxmart import datetime class martCrawler(): def __init__(self): self.wat = crawler_watsons() self.cos = crawler_cosmed() self.pxm = crawler_pxmart() def crawler_testing(self): result_pack = {} wat_result = self.wat.run_before_insert() cos_result = self.cos.run_before_insert() pxm_result = self.pxm.run_before_insert() result_pack['wat'] = wat_result result_pack['cos'] = cos_result result_pack['pxm'] = pxm_result return result_pack ...

http://stackoverflow.com/q/51654692
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90272732
has answer: http://stackoverflow.com/a/51655138
type: Question
score: 0
has title: How do I get the selected option and store it in variable in python?
has comment: http://stackoverflow.com/comment/90272805
answer count: 1
has body: I want to get the selected option from the dict and manipulate it but when I print the variable it prints none. def play(): switcher = { 1: "Rock", 2: "Paper", 3: "Scissors"} print(switcher) i = input("Enter Your Choice: ") s = switcher.get(i) print(s) play()

http://stackoverflow.com/comment/90548377
has text: https://unix.stackexchange.com/questions/419880/connecting-to-ip-0-0-0-0-succeeds-how-why might help
comment on: http://stackoverflow.com/q/51795408
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90343214
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51665236
type: QuestionComment
has text: Still not working... i dont think the values are particularly large.

http://stackoverflow.com/q/51768418
has body: I am getting the CSV file updated on daily basis. Need to process and create new file based on the criteria - If New data then should be tagged as New against the row and if its an update to the existing data then should be tagged as Update. How to write a Python code to process and output in CSV file as follows based on the date. Day1 input data empid,enmname,sal,datekey 1,cholan,100,8/14/2018 2,ram,200,8/14/2018 Day2 input Data empid,enmname,sal,datekey 1,cholan,100,8/14/2018 2,ram,200,8/14/2018 3,sundar,300,8/15/2018 2,raman,200,8/15/2018 Output Data status,empid,enmname,sal,datekey new,3,sundar,300,8/15/2018 update,2,raman,200,8/15/2018
downvote count: 3
has answer: http://stackoverflow.com/a/51768940
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90495795
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90495560
tagged with: http://stackoverflow.com/tag/csv
has title: Python code to process CSV file
tagged with: python
has comment: http://stackoverflow.com/comment/90498607
type: UnansweredQuestion
score: -3
type: Question

http://stackoverflow.com/comment/90452561
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51746426
has text: @SvenMarnach Indeed, I based that code off the title.
type: Comment

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

http://stackoverflow.com/comment/90362131
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51646063
has text: yaa 2nd part worked out putting the if, else commands but I don't know why fetching from Google API isn't working out, although when I'm printing it by calling just the location function its working out very fast
score: 0

http://stackoverflow.com/q/51732586
accepted answer: http://stackoverflow.com/a/51735359
possible better answer: http://stackoverflow.com/a/51733161
has answer: http://stackoverflow.com/a/51733161
has comment: http://stackoverflow.com/comment/90426268
tagged with: numpy
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51735359
favorite count: 0
type: Question
has title: Set maximum value to one and the rest to zero along an axis in a 3D NumPy array
has comment: http://stackoverflow.com/comment/90429549
tagged with: python
has body: I have a 3D array: volts = np.random.random((3,3,3)).round(decimals=5) &gt;&gt;&gt; volts array([[[0.94785, 0.43955, 0.74527], [0.82098, 0.52509, 0.67954], [0.72355, 0.16252, 0.03184]], [[0.25782, 0.04191, 0.6689 ], [0.18215, 0.63108, 0.52052], [0.81992, 0.36301, 0.66629]], [[0.90585, 0.27223, 0.78807], [0.32251, 0.65861, 0.70398], [0.21687, 0.20798, 0.33868]]]) 5 decimals is enough for my application. &gt;&gt;&gt; volts[0,0,:] array([0.94785, 0.43955, 0.74527]) &gt;&gt;&gt; volts[0,1,:] array([0.82098, 0.52509, 0.67954]) In the above 2 lines I would like to set 0.94785 and 0.82098 to ones and rest all elements to zeros. Not just volts[0,0,:] and volts[0,1,:] but all other volts[x,y,:] also. So I did this: &gt;&gt;&gt; volts = np.random.random((3,3,3)).round(decimals=5) &gt;&gt;&gt; volts1 = deepcopy(volts) &gt;&gt;&gt; vmaxs=volts1.max(axis=2).flatten().tolist() &gt;&gt;&gt; for items in vmaxs: volts1[np.where(volts1==items)]=1 &gt;&gt;&gt; volts1[np.where(volts1!=1)]=0 &gt;&gt;&gt; volts1 array([[[1., 0., 0.], [0., 0., 1.], [0., 1., 0.]], [[0., 1., 0.], [1., 0., 0.], [1., 0., 0.]], [[1., 0., 0.], [0., 0., 1.], [0., 1., 0.]]]) &gt;&gt;&gt; volts[0,0,:] array([0.90763, 0.38579, 0.25768]) &gt;&gt;&gt; volts1[0,0,:] array([1., 0., 0.]) . . . &gt;&gt;&gt; volts[2,2,:] array([0.33343, 0.73859, 0.43735]) &gt;&gt;&gt; volts1[2,2,:] array([0., 1., 0.]) You can see that maximas along axis 2 are set to ones and rest of the elements to zeros. Here, I just iterate over 9 elements but what if I had to iterate over 200-300 elements? How can do it in a less verbose and an efficient fashion?
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/90626717
comment on: http://stackoverflow.com/q/51757233
type: Comment
has text: Can you print the output of direct and liste as text if possible? It will bring more clarity
score: 0
type: QuestionComment

http://stackoverflow.com/a/51768201
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51748545
has body: It may sound a bit silly, but have you tried scrolling with mousewheel while hovering over the structure? The scrollbar is hidden via css so that browser doesn't display two scrollbars. If that doesn't work, it would be great if you could open an issue at github.com/divio/django-cms with details about your browser / setup and maybe a minimal test project to reproduce. In the meantime you could also open structure as a separate view, e.g. "domain/en/my-page?structure".
downvote count: 0
type: Answer

http://stackoverflow.com/q/51688216
has comment: http://stackoverflow.com/comment/90338511
downvote count: 1
has comment: http://stackoverflow.com/comment/90338466
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90338550
score: -1
has title: Python TypeError '_io.TextIOWrapper' object does not support item assignment when getting data from HTML
has answer: http://stackoverflow.com/a/51688270
has comment: http://stackoverflow.com/comment/90338487
answer count: 1
favorite count: 0
has body: When using flask to grab data from HTML and attempt to create a new dict with the data in a json file I am getting [2018-08-04 18:48:46,700] ERROR in app: Exception on /savetask [POST] Traceback (most recent call last): File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "gui.py", line 33, in savetask task['taskid'] = str(request.form['taskid']) TypeError: '_io.TextIOWrapper' object does not support item assignment My Python @app.route('/savetask',methods=['POST']) def savetask(): tasks = json.load(open('tasks/tasks.json')) with open("tasks/tasks.json", "w") as task: task['taskid'] = str(request.form['taskid']) task['profilename'] = str(request.form['profile']) json.dump(task, tasks) return redirect('/') My JSON [ { "taskid": "Task 1", "profilename": "profile1" }, { "taskid": "Task 2", "profilename": "profile2" } ] Help is very appreciated I looked at other posts but I couldn't find an answer
has comment: http://stackoverflow.com/comment/90338483
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90338438
has comment: http://stackoverflow.com/comment/90338304
has comment: http://stackoverflow.com/comment/90338440
has comment: http://stackoverflow.com/comment/90338398
has comment: http://stackoverflow.com/comment/90338349
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/90495934
score: 0
type: Comment
type: QuestionComment
has text: unfortunately this is the image actual size
comment on: http://stackoverflow.com/q/51768092

http://stackoverflow.com/comment/90342467
comment on: http://stackoverflow.com/a/51683695
score: 0
type: AnswerComment
type: Comment
has text: @michelle You have to be careful when coding to make sure you type keywords & variable names *exactly*. You need `while` to be all lower case. You use capital `W`, so here on Stack Overflow it gets printed in light blue instead of dark blue.

http://stackoverflow.com/a/51790864
type: Answer
upvote count: 1
has body: Although it's unclear what you are asking, but the following changes do what you want to have. But the code uses the instance of foo() not the class: class bar: def fooDef(self, fooObj): print fooObj.fooNum class foo: def __init__(self): self.fooNum = 1 b = bar() f = self b.fooDef(f) f = foo() Prints: 1
answers question: http://stackoverflow.com/q/51790676
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90539217

http://stackoverflow.com/comment/90257165
type: Comment
comment on: http://stackoverflow.com/q/51646342
has text: url3= url not error
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90524113
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51783148
has text: Oh, I understand now.

http://stackoverflow.com/comment/91140464
has text: why does the second one have a comma??
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51700754

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

http://stackoverflow.com/a/51646162
answers question: http://stackoverflow.com/q/51645874
score: 2
downvote count: 0
upvote count: 2
has body: We can write sorting key as follows: def sorting_key(element): second_substring = element.split()[1] return second_substring.isdecimal(), element then use it in sorted builtin like &gt;&gt;&gt; list_of_sent = ['a5 abc xyz', 'w1 3 45 7', 'a6 abc deg', 'r4 2 7 9'] &gt;&gt;&gt; sorted(list_of_sent, key=sorting_key) ['a5 abc xyz', 'a6 abc deg', 'r4 2 7 9', 'w1 3 45 7'] or if we don't need old order we can sort list_of_sent in place (may be more efficient, at least will not occupy additional memory for a new list): &gt;&gt;&gt; list_of_sent = ['a5 abc xyz', 'w1 3 45 7', 'a6 abc deg', 'r4 2 7 9'] &gt;&gt;&gt; list_of_sent.sort(key=sorting_key) &gt;&gt;&gt; list_of_sent ['a5 abc xyz', 'a6 abc deg', 'r4 2 7 9', 'w1 3 45 7'] More info about differences between sorted &amp; list.sort could be found in this thread.
type: Answer

http://stackoverflow.com/comment/90402386
has text: Of all the answers, this is the fastest.
comment on: http://stackoverflow.com/a/51720858
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51653415
accepted answer of: http://stackoverflow.com/q/51653170
has comment: http://stackoverflow.com/comment/90270141
has comment: http://stackoverflow.com/comment/90270236
has body: You can use a dictionary to specify aggregation functions for each series: d = {'Balance': ['mean', 'sum'], 'ATM_drawings': ['mean', 'sum']} res = df.groupby('ID').agg(d) # flatten MultiIndex columns res.columns = ['_'.join(col) for col in res.columns.values] print(res) Balance_mean Balance_sum ATM_drawings_mean ATM_drawings_sum ID 1 125 250 41.5 83 2 100 200 100.0 200 Or you can define d via dict.fromkeys: d = dict.fromkeys(('Balance', 'ATM_drawings'), ['mean', 'sum'])
has comment: http://stackoverflow.com/comment/90270479
type: Answer
score: 24
has comment: http://stackoverflow.com/comment/90270507
upvote count: 24
answers question: http://stackoverflow.com/q/51653170
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90311693
comment on: http://stackoverflow.com/a/51673686
type: AnswerComment
has text: @RoadRunner From the question "_using either AND or OR_" - doing both at once doesn't seem necessary.
score: 0
type: Comment

http://stackoverflow.com/comment/90282989
type: QuestionComment
has text: post an image and a logo. As a first guess it appears your image and logo have different datatypes
score: 1
comment on: http://stackoverflow.com/q/51659595
type: Comment

http://stackoverflow.com/comment/90561492
comment on: http://stackoverflow.com/q/51793998
has text: its not working for me and i cannot find a solution
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90380782
type: QuestionComment
comment on: http://stackoverflow.com/q/51707009
score: 0
has text: this thread doesn't have an answer that solves the problem
type: Comment

http://stackoverflow.com/comment/127357283
score: 0
has text: @user40551 and GabrielM, This is the trivial case where we know how many gaussians are present and can guess the initial parameters. Even for two it can easily be unstable. I would be interested to see something that is responsive to the question as asked, i.e. using clustering to ascertain the number of gaussians and the initial guess. It is a very good question.
type: AnswerComment
comment on: http://stackoverflow.com/a/51667198
type: Comment

http://stackoverflow.com/comment/90411386
type: QuestionComment
has text: @ibodi 2 selenium versions `2.50.1` and `3.13.0`; 2 Python versions `python2` and `python3`; still have to say _limited enough_?
comment on: http://stackoverflow.com/q/51724472
score: 0
type: Comment

http://stackoverflow.com/comment/90273830
has text: Looking at the code, there's nothing immediately wrong. Have you configured `TEMPLATES` somehow specially? Are you sure all files you're editing what you expect (for example you're not accidentally editing a wrong copy of a template)?
score: 0
comment on: http://stackoverflow.com/q/51654924
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51659595
score: 2
has comment: http://stackoverflow.com/comment/90286163
has body: I have been doing a tutorial on python OpenCV and am trying to append a logo to the upper right-hand corner of a different image. I used print statements to localize the problem to the bitwise_and lines. I have copied the code verbatim from the site and it still does not work. import numpy as np import cv2 img1 = cv2.imread('C:\\Users\\imaxm\\Downloads\\terryRozier.jpg') img2 = cv2.imread('C:\\Users\\imaxm\\Downloads\\scaryTerryLogo.jpg') rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) img1_bg = cv2.bitwise_and(roi,roi, mask = mask_inv) img2_fg = cv2.bitwise_and(img2,img2,mask = mask) dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows() This code gives me this error: cv2.error: ..\..\..\modules\core\src\arithm.cpp:241: error: (-215) (mtype == CV_8U || mtype == CV_8S) &amp;&amp; _mask.sameSize(*psrc1) in function cv::binary_op Any ideas? Here is the logo Here is the background picture
downvote count: 0
has comment: http://stackoverflow.com/comment/90282989
has comment: http://stackoverflow.com/comment/90283397
favorite count: 0
has title: How do I put a logo on an image using python openCV?
type: Question
upvote count: 2
tagged with: python
tagged with: visual-studio
tagged with: opencv
has comment: http://stackoverflow.com/comment/90285257
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90458092
type: QuestionComment
comment on: http://stackoverflow.com/q/51748904
has text: @Koen `a[:]=0.0` has the same behavior as `a[...]` - object `0.0` is cloned/copied. I used `[...]` only because in my actual code the array is multi-dimensional.
score: 0
type: Comment

http://stackoverflow.com/q/51692299
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51692348
upvote count: 3
type: Question
tagged with: charts
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51692348
has answer: http://stackoverflow.com/a/51692420
answer count: 2
tagged with: pandas
downvote count: 0
has title: How can I plot a bar chart showing total sales for different types of store types in Python?
possible better answer: http://stackoverflow.com/a/51692420
favorite count: 0
tagged with: python
has body: I have a dataset (not the one below, but of a similar kind) from which I am trying to plot a bar chart in Python so that I can visualize the 'Total Sales' made from different kind of 'Outlet Type'. ╔══════════╦════════════════════╦═══════╗ ║ Location ║ Outlet_Type ║ Sales ║ ╠══════════╬════════════════════╬═══════╣ ║ Bandra ║ Supermarket Type 1 ║ 125 ║ ║ Worli ║ Supermarket Type 2 ║ 150 ║ ║ Wadala ║ Supermarket Type 3 ║ 100 ║ ║ Chembur ║ Supermarket Type 2 ║ 100 ║ ║ Kalina ║ Supermarket Type 3 ║ 110 ║ ║ Dadar ║ Supermarket Type 3 ║ 115 ║ ║ Korba ║ Supermarket Type 2 ║ 135 ║ ║ Asavari ║ Supermarket Type 1 ║ 145 ║ ╚══════════╩════════════════════╩═══════╝ So from the above data my bar chart should have on the, X-axis : 'Supermarket Type 1', 'Supermarket Type 2' and 'Supermarket Type 3' Y-axis : Total Sales made from the different type of outlets So the bar of 'Supermarket Type 1' will have a value of 270 'Supermarket Type 2' will have a value of 385 'Supermarket Type 3' will have a value of 325 In SQL terms its similar to doing a 'group by' but in Python I am not able to do so and instead I am using pivot table for the time being. data.pivot_table(values = 'Sales', index = 'Outlet_Type')

http://stackoverflow.com/a/51686513
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51686489
has comment: http://stackoverflow.com/comment/90335068
answers question: http://stackoverflow.com/q/51686489
has comment: http://stackoverflow.com/comment/90345791
score: 0
has comment: http://stackoverflow.com/comment/90335019
has body: You can make the table into a pandas DataFrame then df['item_weight'].fillna(15.5, inplace=True)
has comment: http://stackoverflow.com/comment/90335044

http://stackoverflow.com/q/51715438
score: 0
accepted answer: http://stackoverflow.com/a/51777079
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51777079
has body: Currently I am trying to use the @odata.nextLink to paginate the data I retrieve from graph API. I will need some sort of arrows on html to go back and forth, so i will have to maybe create some function with flask on python code to use the @odata.nextLink value that is in the json file, so it loads the next group of data. What I have been trying to do is something like this but my "Next" function will just retrieve the second group of data, it is missing the functionality for going back and also I created a second html file to display this next chunk of data which is pointless. I would like you guys to give me an idea of how make this work. Python Code: import base64 import mimetypes import os import pprint import uuid import flask from flask_oauthlib.client import OAuth from flask import request import config APP = flask.Flask(__name__, template_folder='static/templates') APP.debug = True APP.secret_key = 'development' OAUTH = OAuth(APP) MSGRAPH = OAUTH.remote_app( 'microsoft', consumer_key=config.CLIENT_ID, consumer_secret=config.CLIENT_SECRET, request_token_params={'scope': config.SCOPES}, base_url=config.RESOURCE + config.API_VERSION + '/', request_token_url=None, access_token_method='POST', access_token_url=config.AUTHORITY_URL + config.TOKEN_ENDPOINT, authorize_url=config.AUTHORITY_URL + config.AUTH_ENDPOINT) @APP.route('/') def homepage(): """Render the home page.""" return flask.render_template('homepage.html') @APP.route('/login') def login(): """Prompt user to authenticate.""" flask.session['state'] = str(uuid.uuid4()) print(config.REDIRECT_URI) return MSGRAPH.authorize(callback=config.REDIRECT_URI, state=flask.session['state']) @APP.route('/login/authorized') def authorized(): """Handler for the application's Redirect Uri.""" if str(flask.session['state']) != str(flask.request.args['state']): raise Exception('state returned to redirect URL does not match!') response = MSGRAPH.authorized_response() flask.session['access_token'] = response['access_token'] …
tagged with: python
type: AnsweredQuestion
tagged with: pagination
has title: Microsoft Graph API Paging interface with python and html
tagged with: microsoft-graph-api
type: Question
answer count: 1
tagged with: flask

http://stackoverflow.com/q/51647264
has body: I'm trying to filter out a link from some java script. The java script part isin't relevant anymore because I transfromed it into a string (text). Here is the script part: &lt;script&gt; setTimeout("location.href = 'https://airdownload.adobe.com/air/win/download/30.0/AdobeAIRInstaller.exe';", 2000); $(function() { $("#whats_new_panels").bxSlider({ controls: false, auto: true, pause: 15000 }); }); setTimeout(function(){ $("#download_messaging").hide(); $("#next_button").show(); }, 10000); &lt;/script&gt; Here is what I do: import re def get_link_from_text(text): text = text.replace('\n', '') text = text.replace('\t', '') text = re.sub(' +', ' ', text) search_for = re.compile("href[ ]*=[ ]*'[^;]*") debug = re.search(search_for, text) return debug What I want is the href link and I kind of get it, but for some reason only like this &lt;_sre.SRE_Match object; span=(30, 112), match="href = 'https://airdownload.adobe.com/air/win/dow&gt; and not like I want it to be &lt;_sre.SRE_Match object; span=(30, 112), match="href = 'https://airdownload.adobe.com/air/win/download/30.0/AdobeAIRInstaller.exe'"&gt; So my question is how to get the full link and not only a part of it. Might the problem be that re.search isin't returning longer strings? Because I tried altering the RegEx, I even tried matching the link 1 by 1, but it still returns only the part I called out earlier.
accepted answer: http://stackoverflow.com/a/51647419
upvote count: 1
has comment: http://stackoverflow.com/comment/90259022
answer count: 1
has title: Python: How to get full match with RegEx
favorite count: 0
has answer: http://stackoverflow.com/a/51647419
score: 0
downvote count: 1
tagged with: python
tagged with: regex
tagged with: python-3.x
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48675282

http://stackoverflow.com/a/51657945
upvote count: 1
has comment: http://stackoverflow.com/comment/90281859
downvote count: 0
has body: You can use the setdefault method for dictionaries to simplify the task stateInfo = {} for k in stateList: if 'state' in k: stateInfo.setdefault(stateDict[k['state']], []).append(v['fips'])
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51657764
has comment: http://stackoverflow.com/comment/90280124

http://stackoverflow.com/a/51706278
downvote count: 0
type: AcceptedAnswer
has body: Not sure if there is a way to get this from the triples directly. But, if I recall correctly, you call deps.triples() on your dependencies to get them in this triple format. On that dependencies object (deps above), you can also call deps.get_by_address(i) to get the word at the specified index. You could try if these are connected (i.e. whatever object you get from .get_by_address(position) and every item in the deps.triples()). If so, you can make a dictionary before from dep triple to position. And .get_by_address() is 1-based (not 0-based), as the 0 is always the root node. EDIT: Just found out that .triples() just seems to return a list of tuples, doesn't look like anything fancy from which you can retrieve for ex. position info. The following may help you though (sorry for the German example): s = 'Ich werde nach Hause gehen .' res = depParser.parse(s.split()) # can use a simple .split since my input is already tokenised deps = res.__next__() traverse(deps, 0) # 0 is always the root node traversing then goes as follows: def traverse(deps, addr): dep = deps.get_by_address(addr) print(dep) for d in dep['deps']: for addr2 in dep['deps'][d]: traverse(deps, addr2) Which should just recursively walk through all dependencies in the graph, and gives me the following output: {'word': None, 'head': None, 'address': 0, 'lemma': None, 'feats': None, 'ctag': 'TOP', 'deps': defaultdict(&lt;class 'list'&gt;, {'root': [3]}), 'tag': 'TOP', 'rel': None} {'word': 'nach', 'head': 0, 'address': 3, 'lemma': '_', 'rel': 'root', 'ctag': 'VBP', 'feats': '_', 'deps': defaultdict(&lt;class 'list'&gt;, {'dobj': [5], 'nsubj': [2]}), 'tag': 'VBP'} {'word': 'gehen', 'head': 3, 'address': 5, 'lemma': '_', 'rel': 'dobj', 'ctag': 'NN', 'feats': '_', 'deps': defaultdict(&lt;class 'list'&gt;, {'amod': [4]}), 'tag': 'NN'} {'word': 'Hause', 'head': 5, 'address': 4, 'lemma': '_', 'rel': 'amod', 'ctag': 'JJ', 'feats': '_', 'deps': defaultdict(&lt;class 'list'&gt;, {}), 'tag': 'JJ'} {'word': 'werde',…
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51706023
score: 1
accepted answer of: http://stackoverflow.com/q/51706023

http://stackoverflow.com/a/51728566
has body: I think there are a number of potential improvements to the architecture of your ANN and some fundamental problem. Fundamental challenge is with the way your training set has been built: black &amp; white background. If the intention was that the background should not play a role, why not making all of them white or black? Mind that ANN, like close to any machine learning algorithm, will attempt to find what differentiates your classes. And in this case it will be simply background. Why look at tiny details of car vs. air plane, when background provides so clear and rewarding differentiation? Solution: Make background uniform for both sets. Then your ANN will be oblivious to it. Why Batch Norm was messing up training accuracy? As you noted yourself, test accuracy was still poor. Batch Norm was fixing covariance shift problem. The "problem" was manifesting later in seemingly great training accuracy - and poor test. Great video on Batch Normalisation, with piece on covaraince shift, from Andrew Ng here. Fixing training should fix the issue. Some other things: At the very end you give 2 dense units, but your classification is binary. Make it a single unit with sigmoid activation. As pointed out by @Upasana Mittal, replace categorical_crossentropy with binary_crossentropy. Consider using smaller dropout rates. Mind you don't have that much data to always discard half of it. Increase dropout only after you have evidence of overfitting. Using Conv2D with strides can be better than simple max pooling. You have a lot of filters for what does not seem to be that super complicated. Consider severe reduction in number of filters and increase the number only when you see that the ANN has not enough capacity for learning. You have only 2 classes here and the features differentiating car from a jet are not that subtle. Consider using smaller number of layers. Same argument. Using at least 2 stacked 3x3 Conv2D layers can yield better results.
type: Answer
has comment: http://stackoverflow.com/comment/90431209
has comment: http://stackoverflow.com/comment/90429289
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51720355

http://stackoverflow.com/q/51695857
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52706986
has answer: http://stackoverflow.com/a/53746575
has body: I successfully install the fancyimpute in my env but the package still shows missing in the current channel, not sure what this means. I tried pip install fancyimpute + conda search fancyimpute, it shows the same error as below: Any idea how to fix this. Appreciate it! (py36) C:\Users\chenl&gt;conda install -c brittainhard fancyimpute Fetching package metadata ............... PackageNotFoundError: Packages missing in current channels: - fancyimpute We have searched for the packages in the following channels: - https://conda.anaconda.org/brittainhard/win-64 - https://conda.anaconda.org/brittainhard/noarch - https://repo.continuum.io/pkgs/main/win-64 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/win-64 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/win-64 - https://repo.continuum.io/pkgs/r/noarch - https://repo.continuum.io/pkgs/pro/win-64 - https://repo.continuum.io/pkgs/pro/noarch - https://repo.continuum.io/pkgs/msys2/win-64 - https://repo.continuum.io/pkgs/msys2/noarch
tagged with: fancyimpute
type: Question
tagged with: package
answer count: 2
tagged with: python
has title: Install fancyimpute in conda, getting "PackageNotFoundError: Packages missing in current channels"
tagged with: anaconda
tagged with: installation
score: 0

http://stackoverflow.com/q/51742281
has body: I have created an auto email using python. Right now,I am trying to remove the nan details in my email as user don't want nan to be in the email. I'm not sure how to do it. Can anyone help me to add or edit the code below This is my code : import pandas as pd import csv from tabulate import tabulate from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib user= 'mahirah.abd.wahab@ericsson.com' password = '--------' server = 'smtp.office365.com:587' recipient = 'nur.suraya.shazwani.kamaru.zaman@ericsson.com,mahirah.abd.wahab@ericsson.com' text = """ This is a test for the data to be sent {table} Regards, Me""" html = """ {table} """ # with open('input.csv') as input_file: # reader = csv.reader(input_file) # data = list(reader) df = pd.read_csv('testcsv2.csv') col_list = list(df.columns.values) to_drop = [] for i in range(len(df)): if df['HOSS1 REVIEWED DATE'][i] == 'nan': to_drop.append(i) df.drop(df.index[to_drop]) df.reset_index(drop=True, inplace=True) data = df # above line took every col inside csv as list text = text.format(table=tabulate(data, headers=col_list, tablefmt="grid")) html = html.format(table=tabulate(data, headers=col_list, tablefmt="html")) message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html,'html')]) message['Subject'] = "Rental PR – Pending HOS Approval" message['From'] = user message['To'] = recipient server = smtplib.SMTP(server) server.ehlo() server.starttls() server.login(user, password) server.sendmail(user, recipient, message.as_string()) server.quit() I also tried using this one line code , but still doesn't work : df = pd.dropna(subset=['HOSS1 REVIEWED DATE']) THis is my output Appreciate if anyone can help.
has comment: http://stackoverflow.com/comment/90445421
type: Question
has comment: http://stackoverflow.com/comment/90445255
score: 0
has title: Removing the nan in python in an email
answer count: 1
tagged with: email
tagged with: nan
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90446614
tagged with: python
has comment: http://stackoverflow.com/comment/90447039
has comment: http://stackoverflow.com/comment/90446388
has comment: http://stackoverflow.com/comment/90445817
has answer: http://stackoverflow.com/a/51743975

http://stackoverflow.com/comment/90472336
type: Comment
score: 0
type: AnswerComment
has text: For pandas you can use `pd.to_datetime(1532329236726000, unit="us", utc=True)`
comment on: http://stackoverflow.com/a/51756295

http://stackoverflow.com/comment/90453377
has text: You can use layer.trainable = False or True to create a trainable layer in Keras. But I think you will find a problem in Gradient calculation because it needs matrix operation and you can find some element changeable and other constant.
comment on: http://stackoverflow.com/q/51745580
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51784570
has comment: http://stackoverflow.com/comment/90529330
type: Question
has comment: http://stackoverflow.com/comment/90559731
has comment: http://stackoverflow.com/comment/90559658
downvote count: 0
has body: I get no errors during make html or sphinx-apidoc. But after sphinx-build -b html ./rst/ ./html/ I get: WARNING: autodoc: failed to import module u'mcp.mcp.ann_mcp'; the following exception was raised: No module named mcp.ann_mcp In config.py I added: import os import sys sys.path.append('/home/neurodad/source') sys.path.append('/home/neurodad/source/mcp') sys.path.append('/home/neurodad/source/mcp/mcp') print "PATH:", sys.path and the print out of sys.path gives me: PATH: ['/home/neurodad/miniconda2/envs/prod_keras/bin', '/home/neurodad/miniconda2/envs/prod_keras/lib/python27.zip', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7/plat-linux2', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7/lib-tk', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7/lib-old', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7/lib-dynload', '/home/neurodad/miniconda2/envs/prod_keras/lib/python2.7/site-packages', '/home/neurodad/source/outlierdetector', '/home/neurodad/source/databalancer', '/home/neurodad/source/datanexus', '/home/neurodad/source/distributiontransformer', '/home/neurodad/source/mcp', '/home/neurodad/source/optimization', '/home/neurodad/source/setmaker', '/home/neurodad/source/zswtools', '/home/neurodad/source/supervisedlearning', '/home/neurodad/source', '/home/neurodad/source', '/home/neurodad/source/mcp', '/home/neurodad/source/mcp/mcp'] I searched the net, but every tip related to my problem was along the lines "add the source path to your conf.py". I'm out of ideas - hope you can help. Thx a lot! Update: I made minimal code: class dummy(object): def __init__(self, d1): self.d1 = d1 def dummy_method(self, d2): """ Args: d2 (str): second test string. Example: '&gt;&gt;&gt; my_dummy = dummy("Hello World!")' '&gt;&gt;&gt; my_dummy.dummy_method("Hello Back.")' Hello World! Hello Back. """ print self.d1, d2 if __name__ == '__main__': my_dummy = dummy("Hello World!") my_dummy.dummy…
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python-sphinx
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51825763
has comment: http://stackoverflow.com/comment/90536440
tagged with: python
has comment: http://stackoverflow.com/comment/90538446
has title: Sphinx doesn't find modules despite em being in $PATH
score: 2

http://stackoverflow.com/q/51768850
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90507300
has comment: http://stackoverflow.com/comment/100100720
tagged with: logging
type: Question
has body: i am implementing logging across a python web flask application. The below is an example structure controller - com.org.python.MainController has routes say /login, /doSomething, /logout each of these routes call separate methods in separate modules say, com.org.python.login.begin() com.org.python.dosomething.execute() com.org.python.logout.end() my maincontroller routes have access to user id who has invoked the transaction and a unique transaction id which is generated. i can log this information easily using loggers. usecase: i need to log user id and transaction id in the lower level modules as well , without passing the details as parameters How can i achieve the same? solution so far class CustomFilter(logger.Filter): def __init__(self, username, trid): self.username = username self.trid = trid def filter(record): record.username = self.username record.trid = self.trid i have added the filter to logger as given above maincontroller.py def login(username): trid = .... log = logger.getLogger("something") log.addFilter(CustomFilter(username, trid)) #handlers, formatters added as used log.info("inside login method") #import login module login.begin() login.py def begin(): log = logger.getLogger("something") log.info("im inside begin method in login module") ### something something the above works fine, username and trid is printed everywhere even across modules. however the same trid and username is being used everywhere. even transactions not initiated by the same user. do we have to clear the filters? how can i achieve my usecase m the desired username and diff trid for diff transactions P.S: for some reason loggerAdaptors are not working. the info in adaptor is not getting transferred across module calls please help.
downvote count: 0
tagged with: flask
favorite count: 0
tagged with: python
score: 2
has title: Provide context information across modules without passing parameters in loggers

http://stackoverflow.com/comment/90529850
comment on: http://stackoverflow.com/a/51786180
type: AnswerComment
has text: Thank you! However I get a VulueError when I execute: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
score: 0
type: Comment

http://stackoverflow.com/comment/90248041
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51641307
type: AnswerComment
has text: I am seeing that in other posts.. I don't know about classes as I am only a week into coding with python but I will continue along my journey of learning. Thanks for your assistance!

http://stackoverflow.com/q/51656554
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90277820
tagged with: bigdata
has comment: http://stackoverflow.com/comment/90278117
tagged with: python
tagged with: large-data
has comment: http://stackoverflow.com/comment/90277450
has comment: http://stackoverflow.com/comment/90277033
has comment: http://stackoverflow.com/comment/90278314
has comment: http://stackoverflow.com/comment/90277674
has answer: http://stackoverflow.com/a/51657163
type: Question
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/90278054
has comment: http://stackoverflow.com/comment/90279296
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have a dataframe that has over 400K rows and several hundred columns that I have decided to read in with chunks because it does not fit into Memory and gives me MemoryError. I have managed to read it in in chunks like this: x = pd.read_csv('Training.csv', chunksize=10000) and afterwards I can get each of the chunks by doing this: a = x.get_chunk() b = x.get_chunk() etc etc keep doing this over 40 times which is obviously slow and bad programming practice. When I try doing the following in an attempt to create a loop that can save each chunk into a dataframe and somehow concatenate them: for x in pd.read_csv('Training.csv', chunksize=500): x.get_chunk() I get: AttributeError: 'DataFrame' object has no attribute 'get_chunk' What is the easiest way I can read in my file and concatenate all my chunks during the import? Also, how do I do further manipulation on my dataset to avoid memory error issues (particularly, imputing null values, standardizing/normalizing the dataframe, and then running machine learning models on it using scikit learn?
has title: How to properly save each large chunk of data as a pandas dataframe and concatenate them with each other
has comment: http://stackoverflow.com/comment/90277611
has comment: http://stackoverflow.com/comment/90277422
favorite count: 0

http://stackoverflow.com/q/51756389
upvote count: 2
has body: I am using a custom function for a weighted average. Like, df.groupby(['group1', 'group2']).apply(weighted_average, 'val', 'wt') The returning series is something like, group1 group2 foo a 8.085493 b 45.610411 c 161.959249 d 85.923614 e 30.953251 Abar a 24.000000 b 11.000000 c 18.723185 However, the weighted average column has no name. How do I explicitly name this column? I don't want to rely on the fact that the column is assigned the name 0 because that could cause failure down the line.
type: Question
has answer: http://stackoverflow.com/a/51756479
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51756479
has title: Pandas: Group weighted average, how to control the name of the output column?
possible better answer: http://stackoverflow.com/a/51756459
has answer: http://stackoverflow.com/a/51756459
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/90349871
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51694227
score: 0
has text: line 25, the insert_many line.

http://stackoverflow.com/q/51708998
has title: How can I create and move a virtual mouse with python?
tagged with: mouse
type: Question
score: 1
upvote count: 2
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/64753120
tagged with: controller
has comment: http://stackoverflow.com/comment/90379127
tagged with: python
has body: I tried pynput, pyautogui and some other modules, everything works perfectly in windows and fortnite's gui, but when I start a game doesn't rotate. I want to use an 'usb xbox 360 pc controller' (actually just a sixaxis controller) to play fortnite. controllers's driver uses directx 7, windows 10 doesn't support this, but pygame detects it. After that I want to make a controller for the game with arduino and sensors!
type: UnansweredQuestion

http://stackoverflow.com/q/51726907
has answer: http://stackoverflow.com/a/51727628
tagged with: python
has title: Compare multiple text files, and save commons values
has comment: http://stackoverflow.com/comment/90414868
has comment: http://stackoverflow.com/comment/90415860
has comment: http://stackoverflow.com/comment/90414278
has comment: http://stackoverflow.com/comment/90415179
type: UnansweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51727539
has body: My actual code : import os, os.path DIR_DAT = "dat" DIR_OUTPUT = "output" filenames = [] #in case if output folder doesn't exist if not os.path.exists(DIR_OUTPUT): os.makedirs(DIR_OUTPUT) #isolating empty values from differents contracts for roots, dir, files in os.walk(DIR_DAT): for filename in files: filenames.append("output/" + os.path.splitext(filename)[0] + ".txt") filename_input = DIR_DAT + "/" + filename filename_output = DIR_OUTPUT + "/" + os.path.splitext(filename)[0] + ".txt" with open(filename_input) as infile, open(filename_output, "w") as outfile: for line in infile: if not line.strip().split("=")[-1]: outfile.write(line) #creating a single file from all contracts, nb the values are those that are actually empty with open(DIR_OUTPUT + "/all_agreements.txt", "w") as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line) #finale file with commons empty data #creating a single file with open(DIR_OUTPUT + "/all_agreements.txt") as infile, open(DIR_OUTPUT + "/results.txt", "w") as outfile: seen = set() for line in infile: line_lower = line.lower() if line_lower in seen: outfile.write(line) else: seen.add(line_lower) print("Psst go check in the ouptut folder ;)") The last lines of my code are checking wether or not, element exists mutliple times. So, may the element exists, once, twice, three, four times. It will add it to results.txt. But the thing is that I want to save it into results.txt only if it exists 4 times in results.txt. Or best scenario, compare the 4 .txt files and save elements in commons into results.txt. But I can't solve it.. Thanks for the help :) To make it easier, with open(DIR_OUTPUT + "/all_agreements.txt") as infile, open(DIR_OUTPUT + "/results.txt", "w") as outfile: seen = set() for line in infile: if line in seen: outfile.write(line) else: seen.add(line) Where can I use the .count() function ? Because I want to do something like xxx.count(line) == 4 then save it into resulsts.txt
type: Question
answer count: 2
downvote count: 0
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/90415835

http://stackoverflow.com/q/51754561
tagged with: python
has comment: http://stackoverflow.com/comment/131903750
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/57197283
tagged with: python-imaging-library
has body: I am trying to make AWS Lambda function, which uses PIL. Hence I installed PIL inside my project directory with pip install Pillow -t . First time it ran on local machine, it caused ImportError: cannot import name '_imaging' I though I did something wrong and deleted PIP and Pillow* directories from project directory and reinstalled PIL. Then it worked. Unfortunately, when I packed everythong into ZIP and posted to AWS, the function started to fail with it again Traceback (most recent call last): File "/var/task/myfile.py", line 9, in lambda_handler from PIL import Image File "/var/task/PIL/Image.py", line 64, in &lt;module&gt; from . import _imaging as core ImportError: cannot import name '_imaging' What is the exact reason of this error and how fix it? Below are file list in my project dir: $ ls bin chardet-3.0.4.dist-info Pillow-5.2.0.dist-info ThumbnailEnergent_Lambda.zip certifi idna requests myfile.py certifi-2018.4.16.dist-info idna-2.7.dist-info requests-2.19.1.dist-info urllib3 chardet PIL tests urllib3-1.23.dist-info
upvote count: 4
has title: Cannot import name '_imaging' while trying to use Pillow inside AWS Lambda
answer count: 1
has answer: http://stackoverflow.com/a/55926496
downvote count: 0
has comment: http://stackoverflow.com/comment/97524654
score: 4
tagged with: amazon-web-services
favorite count: 0
linked to: http://stackoverflow.com/q/45473501

http://stackoverflow.com/q/51731403
type: Question
has title: How do I modify custom object attribute with class method
score: -1
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90424109
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: A class in Python 3.6 that keeps track of a set of counts (via nested dictionaries) and a numpy ndarray of the associated probabilities. When I set an element of self.probability to a new value (initialized to 0.0) the mutable attribute does not change. Using numpy 1.12. import numpy as np class MatrixClass(object): def __init__(self): self.tokens = ['x', 'y', 'z'] self.sequences = [(t1, t2) for t1 in self.tokens for t2 in self.tokens] self.p = np.full((len(self.tokens), len(self.sequences)), 0.0) self.count = {} for t in self.tokens: self.count[t] = {} for s in self.sequences: self.count[t][s] = 0 def update_probability(self): p = self.p for i, t in enumerate(self.tokens): total = 0 for j, s in enumerate(self.sequences): total += self.count[t][s] if total != 0: for s in self.sequences: p[i][j] = self.count[t][s] / float(total) if self.count[t][s] &gt; 0: print('****Prob ' + str(i) + ',' + str(j) + ' inner loop: ' + str(p[i][j])) if i == 1 and j == 8: print(' Prob ' + str(i) + ',' + str(j) + ' outer loop ' + str(p[i][j])) return p def update_count(self, data): for measure0, measure1 in zip(data, data[1:]): token = measure1[0] self.count[token][measure0] += 1 p = self.update_probability() self.p = p m = MatrixClass() data = [('y', 'y'), ('y', 'z')] m.update_count(data) Here is the output: ****Prob 1,8 inner loop: 1.0 Prob 1,8 outer loop 0.0
tagged with: python
has answer: http://stackoverflow.com/a/51732483
downvote count: 1

http://stackoverflow.com/q/51668826
has answer: http://stackoverflow.com/a/51669529
type: UnansweredQuestion
tagged with: python
has body: My classification is a 0-1 classification.So what exactly are the numbers at the bottom telling me [ why are they negative and all] ? Also what do the NAs mean? Do they say that this particular feature is not classified on a numeric comparison hence NA like BreedName? Here are the columns of my data and 'L' is the 0-1 column i.e my y. Ques2- This tree 0 is the main model right since i have done cv(n=3) and i have got 4 trees [0,1,2,3] and whatever i interpret should be based on the 0th tree right?
tagged with: classification
has answer: http://stackoverflow.com/a/51677051
type: Question
tagged with: gbm
has title: What do the leaf numbers represent in the h2o tree plot?
has answer: http://stackoverflow.com/a/51681378
score: 0
answer count: 3
tagged with: h2o
tagged with: xgboost

fwrite
tags question: http://stackoverflow.com/q/51708202
tag name: fwrite
type: Tag

http://stackoverflow.com/q/51775450
has comment: http://stackoverflow.com/comment/90511032
has body: I have a model with a click_time field that is a DateTimeField. In my admin it is displayed as UTC. My goal is to display the click_time in the admin as the logged in users timezone, which is being set in the field user.userprofile.timezone. Currently I created a capture tag that looks like this from django import template from datetime import datetime import pytz register = template.Library() @register.simple_tag def convert_time(user_timezone, click_time): time = datetime.strptime(click_time, '%Y-%m-%d %H:%M:%S') local_tz = pytz.timezone(user_timezone) user_time = time.replace(tzinfo=pytz.utc).astimezone(local_tz) return user_time Also I have created a admin/app/change_list.html that looks like this {% extends "admin/change_list.html" %} {% load i18n admin_static admin_list %} {% load capture_tags %} {% block result_list %} {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %} {% result_list cl %} {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %} {% endblock %} My question is how can I apply my convert_time tag to the result_list cl? Or is there a better way to go about doing this?
has comment: http://stackoverflow.com/comment/90510862
score: 0
has comment: http://stackoverflow.com/comment/90510352
has title: Updating django result_list fields timezone
tagged with: django
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/51717922
answers question: http://stackoverflow.com/q/51717675
has comment: http://stackoverflow.com/comment/90505227
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51717675
has comment: http://stackoverflow.com/comment/90513453
has body: I think this may be closer to what you want: def printC(matrix, i=0, j=0, previous=None): if not previous: previous = [] if matrix[i][j] == '0': print() return None elif matrix[i][j] == 'B': previous_branch = previous[:] printC(matrix, i+1, j, previous) print(''.join(reversed(previous_branch)), end='') printC(matrix, i, j+1, previous) elif matrix[i][j] == 'D': printC(matrix, i+1, j, previous) elif matrix[i][j] == 'R': printC(matrix, i, j+1, previous) elif matrix[i][j] == 'C': previous.append('{}{}'.format((i,j), matrix[i][j])) printC(matrix, i+1, j+1, previous) print((i,j), end='') print(matrix[i][j], end='') The trick is to store previous commands and then reprimt them when traversing another branch. The reason why they have to be reversed is because the backtrace approach you've chosen in the recursion prints the commands after the path is taken, meaning the latest command is printed first because it is resolved first, et cetera. Unfortunately, the code is kind of convoluted because of the recursive approach; in this case I actually think an iterative approach is much better suited. Edit: here's an iterative approach, though I must note that nested lists are probably not the best tree substitute: def printC(matrix, i=0, j=0): trace_root = [(i, j)] current_trace = trace_root trace_waiting = [] while True: if matrix[i][j] == '0': if trace_waiting: current_trace = trace_waiting.pop() i, j = current_trace[-1] else: break elif matrix[i][j] == 'B': current_trace.extend([[(i+1, j)], [(i, j+1)]]) trace_waiting.append(current_trace[-1]) current_trace = current_trace[-2] i, j = current_trace[-1] else if matrix[i][j] == 'D': i += 1 elif matrix[i][j] == 'R': j += 1 elif matrix[i][j] == 'C': i, j = i+1, j+1 current_trace.append((i,j)) return trace_root

http://stackoverflow.com/q/51684867
tagged with: scope
has comment: http://stackoverflow.com/comment/90331871
has body: I'm really new to python or programming in general. I am trying to make a function that draws input from the user and check if it is an integer. However, after checking that the input is an integer, I am unable to use the variable outside of the loop, with an error message shown below: python3.7 new.py How much is your balance in your account? &gt;123 Traceback (most recent call last): File "new.py", line 14, in &lt;module&gt; print(f"Thank you, your account balance is {b}.") NameError: name 'b' is not defined def inputintegertest(): while True: try: a = int(input("&gt;")) b = "${:.2f}".format(a) break except ValueError: print("Please enter a number.") print("How much is your balance in your account?") inputintegertest() print(f"Thank you, your account balance is {b}.")
duplicate of: http://stackoverflow.com/q/291978
has answer: http://stackoverflow.com/a/51684915
tagged with: python
has title: How do I assign a variable to be used outside of the loop?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/291978
type: Question
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51684915

http://stackoverflow.com/a/52021690
answers question: http://stackoverflow.com/q/51746830
type: Answer
upvote count: 5
score: 5
downvote count: 0
has body: This worked for me. How to authenticate user see here https://developers.google.com/photos/library/guides/upload-media def upload(service, file): f = open(file, 'rb').read(); url = 'https://photoslibrary.googleapis.com/v1/uploads' headers = { 'Authorization': "Bearer " + service._http.request.credentials.access_token, 'Content-Type': 'application/octet-stream', 'X-Goog-Upload-File-Name': file, 'X-Goog-Upload-Protocol': "raw", } r = requests.post(url, data=f, headers=headers) print '\nUpload token: %s' % r.content return r.content def createItem(service, upload_token, albumId): url = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate' body = { 'newMediaItems' : [ { "description": "test upload", "simpleMediaItem": { "uploadToken": upload_token } } ] } if albumId is not None: body['albumId'] = albumId; bodySerialized = json.dumps(body); headers = { 'Authorization': "Bearer " + service._http.request.credentials.access_token, 'Content-Type': 'application/json', } r = requests.post(url, data=bodySerialized, headers=headers) print '\nCreate item response: %s' % r.content return r.content # authenticate user and build service upload_token = upload(service, './path_to_image.png') response = createItem(service, upload_token, album['id'])

http://stackoverflow.com/comment/90431331
type: QuestionComment
has text: `k` is a reference to the string `'var1'`; it is not `var1` itself.
comment on: http://stackoverflow.com/q/51735189
score: 0
type: Comment

http://stackoverflow.com/q/51670431
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I want to start a python script (I will call it test.py) in another python script (run_python_script.py). For that I use the subprocess command like shown here: https://stackoverflow.com/a/18422264. So that is run_python_script.py : import subprocess import sys import io import time def runPython(filename, filename_log="log.txt"): with io.open(filename_log, 'wb') as writer, io.open(filename_log, 'rb', 1) as reader: process = subprocess.Popen("python {}".format(filename), stdout=writer) while process.poll() is None: sys.stdout.write(reader.read().decode("utf-8")) time.sleep(0.5) # Read the remaining sys.stdout.write(reader.read().decode("utf-8")) runPython("test.py") And this is test.py : import time sleep_time = 0.0001 start_time = time.time() for i in range(10000): print(i) time.sleep(sleep_time) print(time.time() - start_time) In this setup the live output works, but if sleep_time (in test.py) is to big, for example sleep_time = 1. run_python_script.py only outputs after test.py is finished. I replaced time.sleep(sleep_time) with other functions and every function which takes to long, breaks the live output. Of corse test.py is just an example. I want to use other methods, but the result is the same.
upvote count: 1
tagged with: python
has title: subprocess: can't get live output if time between outputs is too big
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51671449
tagged with: subprocess
score: 1
type: Question
linked to: http://stackoverflow.com/q/18421757
accepted answer: http://stackoverflow.com/a/51671449

http://stackoverflow.com/comment/90455366
type: Comment
has text: Why? It will be a backslash and a newline character.
type: AnswerComment
comment on: http://stackoverflow.com/a/51746482
score: 0

http://stackoverflow.com/a/51789415
score: 2
has comment: http://stackoverflow.com/comment/90568235
has body: Here is a simple algorithm that does it in O(n): string = "aabbbccdddddddd" def get_frequency(string): chars = {} for char in string: chars[char] = chars.get(char, 0) + 1 biggest = [None, 0] second = [None, 0] for entry in chars.items(): char, count = entry if count &gt; biggest[1]: second = biggest biggest = entry elif count &gt; second[1]: second = entry return { "most-occurring": biggest[0], "second-most-occurring": second[0] } print(get_frequency(string)) This prints {'second-most-occurring': 'b', 'most-occurring': 'd'} Note that I added an extra 'b' to string in order to make that the second most frequent letter
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51788672
has comment: http://stackoverflow.com/comment/90600369
answers question: http://stackoverflow.com/q/51788672
has comment: http://stackoverflow.com/comment/90602186
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90550360
has comment: http://stackoverflow.com/comment/90550659

http://stackoverflow.com/comment/90249995
has text: What is the question?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51641918

http://stackoverflow.com/comment/90519663
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51781053
score: 0
has text: with open("output.csv",'wb') as resultFile: wr = csv.writer(resultFile) wr.writerows(l) this I tried but the results are very weird

http://stackoverflow.com/comment/123355884
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51762699
score: 14
has text: But what if the code is already running in an `asyncio.run` call? If you use `asyncio.run` inside a function that is invoked with `asyncio.run` then you get `RuntimeError: asyncio.run() cannot be called from a running event loop`

http://stackoverflow.com/a/51784755
answers question: http://stackoverflow.com/q/51783113
type: Answer
upvote count: 3
has body: After further tinkering I found the following to be working: @patch('sqlite3.connect') def test_shortTest(self, mock_sql): mock_sql.return_value.execute.return_value.fetchone.return_value = ('Test',) test_class = Foo() return_mock = test_class.checkActive() print(return_mock) All the other code remains the same as per the original post. Hope this helps others out if they ever have to come across this!
score: 3
downvote count: 0

http://stackoverflow.com/q/51663651
duplicate of: http://stackoverflow.com/q/6976658
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6976658
has comment: http://stackoverflow.com/comment/90290757
has comment: http://stackoverflow.com/comment/90290751
has body: I spent some time to figure that out, so I post this Q&amp;A. Let's say you have function def my_func(group) which takes an argument group which will be used as positional argument in next function: def set_permission(group_user=None, group_admin=None). So: group = 'group_user' my_func(group): if group == 'group_user': set_permission(group_user='write') if group == 'group_admin': set_permission(group_admin='write') but what if group can be 20 combinations? And more 'real' case from Django: from models import User, Project import mommy def create_instance_of_repetable_model(model, model_field): if model == User: mommy.make(User, user_perm='write') if model == Project: mommy.make(Project, project_perm='write') if model == Project
type: Question
has comment: http://stackoverflow.com/comment/90290699
has title: How to pass positional argument from string in Python
has answer: http://stackoverflow.com/a/51663652
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/comment/90315395
has text: I want to know the Index position of rows A if I get a match with rows of DataFrame-B. A match between TOTAL_NO_OF_RECORDS and TOTAL_QUANTITY VS DatFrame-B (Records and Quantity)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51675723

http://stackoverflow.com/comment/90426378
comment on: http://stackoverflow.com/a/51700995
has text: @MadPhysicist: Correct. I meant the inner `if`. The actual loop, as you mention, is not affected.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90419998
has text: I'm using python 2.7, so pip install django should have worked.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51729386
score: 0

http://stackoverflow.com/comment/90553153
comment on: http://stackoverflow.com/q/51791707
type: Comment
type: QuestionComment
has text: In sum, in the current version, `astype` cannot be used to reorder the fields.
score: 0

http://stackoverflow.com/q/51772023
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90508121
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/90504299
has comment: http://stackoverflow.com/comment/90513064
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90504270
type: Question
has answer: http://stackoverflow.com/a/51777514
has comment: http://stackoverflow.com/comment/90502813
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90504521
has comment: http://stackoverflow.com/comment/90504460
has comment: http://stackoverflow.com/comment/90513020
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90503054
has body: I have a dataset which contains million level images and what I want to do is to do something like Counter(&lt;list of images&gt;) to check duplicates and count for the whole dataset. However, considering the size of images, it seems infeasible to load all into memory. Thus, is there any way to do things like this? Do I need to write my own hash function and reverse dict? Edited for sha1: I did something like image = Image.open("x.jpg") # PIL library hashlib.sha1(image) and got an error like TypeError: object supporting the buffer API required What should I do now?
has comment: http://stackoverflow.com/comment/102488751
has title: How to check duplicate pictures in a very large dataset using Python?
upvote count: 2

http://stackoverflow.com/comment/90511750
type: QuestionComment
comment on: http://stackoverflow.com/q/51776572
score: 4
has text: Also, why are you doing this with `map` and `reduce` in the first place? Your outer `reduce` is just a less efficient and harder to understand `'\n'.join`, your `list(map(lambda…))` is a less efficient and harder to understand list comprehension, and your inner `reduce`… I'm not sure what it's supposed to be doing; why do you call `strxo` on the accumulated value here? And why does this all have to be one monstrous line, instead of breaking it up into smaller pieces you can understand and debug yourself?
type: Comment

http://stackoverflow.com/comment/90460652
has text: @Aran-Fey Edited :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51749982
type: Comment

http://stackoverflow.com/comment/90329745
type: Comment
has text: When you say virtural environment do you mean inside tmux? There is no problem to importing tensorflow outside of tmux.
score: 0
comment on: http://stackoverflow.com/q/51683574
type: QuestionComment

clipper
tags question: http://stackoverflow.com/q/51699682
tag name: clipper
type: Tag

http://stackoverflow.com/comment/90349954
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51694076
has text: Possible duplicate of [ImportError in importing from sklearn: cannot import name check_build](https://stackoverflow.com/q/15274696/5085211).

http://stackoverflow.com/comment/90566889
has text: Thanks a lot ! After couple days,I think I’ve addressed the issues by the method you provided! Thanks for your suggestions and support!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51698808

http://stackoverflow.com/q/51682973
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51683091
tagged with: python
favorite count: 0
has title: Numbers change after reading Pickle data (python) into R
has comment: http://stackoverflow.com/comment/90328652
linked to: http://stackoverflow.com/q/5963269
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51683204
tagged with: pickle
downvote count: 1
has body: I have a large dataset with unix epoch dates embedded in lists/dicts currently stored as a pickle file. I tried to import the pickle file into R using the reticulate package vis py_load_object() function. Other than, the unix epoch dates (in milliseconds), all else seems fine. I get very strange integer conversions. For example, epoch date of 694137600000 is read as -1647101952 in R. I was wondering if there is an explanation and a work-around. Thanks!
score: -1
tagged with: reticulate
type: Question
answer count: 2
upvote count: 0

http://stackoverflow.com/comment/90326338
comment on: http://stackoverflow.com/a/51658303
score: 1
type: AnswerComment
type: Comment
has text: @Chuck , Thank you for accepting the answer guys. You can just do this to get only 'yhat' column : result_df = result'ds', 'yhat' and then append this to results. This should do the trick.

http://stackoverflow.com/comment/90551291
has text: I used retrying (pip install retrying) which supports exponential backoff. Worked great. Thanks @F10
comment on: http://stackoverflow.com/a/51787129
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51793580
has answer: http://stackoverflow.com/a/51793674
linked to: http://stackoverflow.com/q/477486
answer count: 1
has title: Decimal in for python
duplicate of: http://stackoverflow.com/q/477486
tagged with: increment
has body: I have to evaluate a function (3x-2) in a interval [-10,10] with precision increments from 1, 0.1, 0.01, 0.001, 0.0001, etc. I tried this a=1.0 for x in range(1,40): for y in range(-10,10,a): c=3(x)-2 print(c) a=a/10 (The first for is because I need to get 40 decimals) But I got this error for x in range(-10,10,a): TypeError: 'float' object cannot be interpreted as an integer Thanks for the help.
type: UnansweredQuestion
score: 0
tagged with: python
type: Question
tagged with: decimal

http://stackoverflow.com/q/51750036
type: UnansweredQuestion
has title: how to use conditionals (multiple IF and ELSE statements) in a function using PYTHON
downvote count: 2
linked to: http://stackoverflow.com/q/7053652
tagged with: python
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/56716963
has answer: http://stackoverflow.com/a/51750419
type: Question
has comment: http://stackoverflow.com/comment/90460420
upvote count: 0
tagged with: function
score: -2
duplicate of: http://stackoverflow.com/q/7053652
has body: I'm new to programming and i'm taking a course on edx.org. i'm having issues with using conditionals in a function. each time i call the function it gives me the output i desire but also shows "NONE" at the end. is there any way i can use return keyword in the code? below is the question and my code. ###create a functions using startswith('w') ###w_start_test() tests if starts with "w" # function should have a parameter for test_string and print the test result # test_string_1 = "welcome" # test_string_2 = "I have $3" # test_string_3 = "With a function it's efficient to repeat code" # [ ] create a function w_start_test() use if &amp; else to test with startswith('w') # [ ] Test the 3 string variables provided by calling w_start_test() test_string_1='welcome'.lower() test_string_2='I have $3'.lower() test_string_3='With a function it\'s efficient to repeat code'.lower() def w_start_test(): if test_string_1.startswith('w'): print(test_string_1,'starts with "w"') else: print(test_string_2,'does not start with "w"') if test_string_2.startswith('w'): print(test_string_2,'starts with "w"') else: print(test_string_2,'does not starts with "w"') if test_string_3.startswith('w'): print(test_string_3,'starts with "w"') else: print(test_string_3,'does not start with "w"') print(w_start_test())
linked to: http://stackoverflow.com/q/7664779
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/53389034

http://stackoverflow.com/a/56732635
answers question: http://stackoverflow.com/q/51644941
score: 0
has body: you can also use the itertools library, islice function import csv from itertools import islice la = open('loginscruz.csv', 'r') listaluno = iter(csv.reader(la,delimiter=';')) for listaluno in islice(listaluno ,1,None): num = 1 aluno = str(listaluno[3]) if (aluno != ''): print (f'{aluno} batata') I don't know what your using nums = 1 for but if it just for numbering purpose, you can also use enumerate function for the same import csv from itertools import islice la = open('loginscruz.csv', 'r') listaluno = iter(csv.reader(la,delimiter=';')) for count, listaluno in enumerate(islice(listaluno,1,None), start = 1): aluno = str(listaluno[3]) if (aluno != ''): print (f'{count} {aluno} batata')
type: Answer

http://stackoverflow.com/comment/90361859
type: QuestionComment
score: 0
has text: Why is the expected only the words that start with `51` and not the rest that start with `5`? You may want to clarify your question as it doesn't match your wanted output. Also is this just for the port numbers at the end? What if the two digits numbers at the start also start with `5`, would you want to include those?
type: Comment
comment on: http://stackoverflow.com/q/51700282

http://stackoverflow.com/q/51711306
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51711375
type: Question
tagged with: dataset
has body: A TSV file contains some user event data : user_uid category event_type "11" "like" "post" "33" "share" "status" "11" "like" "post" "42" "share" "post" what is the best way to get the number of post events for each category and for each user_id? we should show the following output: user_uid category count "11" "like" 2 "42" "share" 1
has title: Filter , group by and count in pandas?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51711375
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90255167
score: 0
type: QuestionComment
type: Comment
has text: If these deductions regards columns is right, then making Sparse dataframe from the transpose of your matrix should be a bit faster - with only 20,000 columns, rather than 50,000!.
comment on: http://stackoverflow.com/q/51644467

http://stackoverflow.com/q/51661522
downvote count: 1
type: Question
tagged with: for-loop
has body: I'm working on a game where each object should check if it is colliding with any other object. I have a single list of all the objects and a function which can determine if two objects are colliding and destroys them. The current method I'm using is very inefficient. for i in list1: for j in list1: if collide(i, j): i.kill() j.kill() Initially I removed both objects from the list after they were killed, but some collision occurred without detecting so I reverted back to this code. It works, but I'd like something more efficient.
has answer: http://stackoverflow.com/a/51661723
has comment: http://stackoverflow.com/comment/90286751
answer count: 1
has comment: http://stackoverflow.com/comment/90286718
favorite count: 0
has comment: http://stackoverflow.com/comment/90286450
accepted answer: http://stackoverflow.com/a/51661723
tagged with: python-3.x
has title: Python - Checking every item in a list against every other item efficiently
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90286799
type: AnsweredQuestion
tagged with: list
score: 0

http://stackoverflow.com/comment/90313743
score: 0
comment on: http://stackoverflow.com/q/51675246
type: Comment
type: QuestionComment
has text: through windows powershell

http://stackoverflow.com/comment/90326859
type: Comment
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51681919
has text: This is a horrible thing to do in general—but as a solution to an inherently horrible problem, that's kind of unavoidable. I think it's still much better to just create a separate function, as suggested by juanpa, but in the rare cases where you can't do that, this is probably the best alternative.

http://stackoverflow.com/comment/90294935
type: Comment
has text: You can have a list of conditions as well. I have edited code for that as well
comment on: http://stackoverflow.com/a/51658708
score: 0
type: AnswerComment

http://stackoverflow.com/a/51748021
type: AcceptedAnswer
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/90470571
downvote count: 0
has body: You can pass a dict of funcs to agg: In[80]: df.groupby('id').agg({'data':'last', 'value':['first','last']}) Out[80]: data value last first last id 1 2 10 9 2 4 8 7 You can pass a list of funcs if you want to call first and last on the 'value' column. Here pandas is able to deduce which method to call by passing just the string name of the funcs
accepted answer of: http://stackoverflow.com/q/51747979
upvote count: 6
answers question: http://stackoverflow.com/q/51747979

http://stackoverflow.com/q/51729647
has comment: http://stackoverflow.com/comment/90420091
has answer: http://stackoverflow.com/a/51729771
has comment: http://stackoverflow.com/comment/90420178
answer count: 2
has comment: http://stackoverflow.com/comment/90420228
has body: I have this dataframe: Group Turn Name 0 G1 1 Maria 1 G1 2 Sam 2 G1 2 Sara 3 G1 3 Maria 4 G1 4 Mark 5 G1 5 Maria 6 G2 2 Maria 7 G2 1 Ahmad 8 G3 1 Maria 9 G3 2 David I would like to group by my data based on value of column "group" and sort based on their "Turn". So with each group the turns are sorted. Then I would like to sum the value of column "Turn" in each group for the rows where the name is "Maria" and one row after. IF Maria is the last turn in the group then the sum only Maria's turn. So the result looks like this: Group Name Sum G1 Maria 3 G1 Maria 7 G1 Maria 5 G2 Maria 2 G3 Maria 3 I tried group by and apply and shift but none of them gives me the final result I am looking for. df = df.groupby('group').apply(lambda x: x.sort_values('Turn')) Can somebody help me?
accepted answer: http://stackoverflow.com/a/51729808
downvote count: 0
has comment: http://stackoverflow.com/comment/90423313
possible better answer: http://stackoverflow.com/a/51729771
favorite count: 0
has comment: http://stackoverflow.com/comment/90420435
tagged with: pandas
has comment: http://stackoverflow.com/comment/90420077
has comment: http://stackoverflow.com/comment/90420065
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90420546
tagged with: aggregate
upvote count: 2
has answer: http://stackoverflow.com/a/51729808
type: Question
tagged with: group-by
tagged with: sum
has title: Python Pandas: Sort and group by, then sum two consecutive rows of 2nd column for a specific value of a 3rd column

http://stackoverflow.com/comment/90532235
type: Comment
comment on: http://stackoverflow.com/a/51775142
score: 0
type: AnswerComment
has text: It doesn't seem to work either. Besides, I already have command=canvas.yview when I create the scrollbar, which is the same as yscrollbar.config(command=canvas.yview)

http://stackoverflow.com/comment/90335400
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51662423
type: Comment
has text: @Dennissaka: Build your app using Buildozer for Python 2.

http://stackoverflow.com/comment/90422305
comment on: http://stackoverflow.com/q/51670398
has text: What's the version of Pickle on each computer? Run `pip3 freeze | grep pickle`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51701306
answers question: http://stackoverflow.com/q/51701280
has body: Without ../ at the beginning, those folders will be treated as though they're in the CWD. No such folders in the CWD exist. Adjust your code so: path_to_folders = './' folders = [f for f in os.listdir(path_to_folders) if os.path.isdir(path_to_folders . f)] print(folders)
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/51732433
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51732395
accepted answer of: http://stackoverflow.com/q/51732395
has body: You can specify the parameter to supply by using = at the call site: mult(y = 5)
type: Answer

http://stackoverflow.com/comment/90462219
type: AnswerComment
type: Comment
has text: Yes, you can but often it is better to just perform vector operations rather than having any for loops at all.
comment on: http://stackoverflow.com/a/51748272
score: 0

http://stackoverflow.com/comment/90471467
has text: @M.Rau Fixed it for you, productivity at work is low
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51755547
type: Comment

http://stackoverflow.com/a/51761869
downvote count: 0
has comment: http://stackoverflow.com/comment/90483033
score: 6
answers question: http://stackoverflow.com/q/51761836
accepted answer of: http://stackoverflow.com/q/51761836
type: AcceptedAnswer
upvote count: 6
has comment: http://stackoverflow.com/comment/90483002
has body: You should use + operator to concatenate strings, and turn non-string objects (like int) into strings by using str(object): asa = 13 a = "Hello, World! "+ str(asa)+ "Year" print(a) Alternatively you could use string formatting: asa = 13 a = "Hello, World! {n} Year".format(n=asa) print(a)
type: Answer
has comment: http://stackoverflow.com/comment/90482940

http://stackoverflow.com/comment/90515983
has text: Have you tried passing any text e.g. `New York City` or `San Francisco` to the _search box_? Which data from the _dealer-info_ are you looking for?
comment on: http://stackoverflow.com/q/51776223
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90325654
type: Comment
comment on: http://stackoverflow.com/a/51681251
has text: msg should be a list of two MIMEText
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90327548
comment on: http://stackoverflow.com/q/51681821
score: 0
type: Comment
type: QuestionComment
has text: Apologies, I tried to update the original post. am having a hard time shrinking everything down to get the problem across. In as simplistic form as I can (sorry, new to python), I have output from `function1` that updates a global variable. I then have a `dictionary` storing values. I am trying to call `function2` (which uses 2 parameters, the output from 'function1', and my 'dictionary') from a button on tkinter. it goes to a variable, that I am trying to have run the function and gather the previously stored variables to give me output, as semi-shown as `var2`.

http://stackoverflow.com/a/51693482
score: 0
type: Answer
has body: The reason of the error is that Dialog is not available in scope of loginCheck method and need to be passed explicitly as a param in the following line: self.pbtn_signin.clicked.connect(self.loginCheck) Here is the question with the answers, how to do it. One of the options would be import partial from functools: from functools import partial And use this function to pass Dialog to loginCheck: self.pbtn_signin.clicked.connect(partial(self.loginCheck, Dialog))
answers question: http://stackoverflow.com/q/51693045

http://stackoverflow.com/a/51778278
score: 0
has body: I found an answer in here, it's work for me: change the WSGIDaemonProcess like this: myproject python-home=/home/ubuntu/Django/myvenv python-path=/home/ubuntu/Django/myproject
answers question: http://stackoverflow.com/q/51747454
type: Answer

http://stackoverflow.com/comment/90294193
has text: You should add some concrete examples (small examples) and the expected result as it's really confusing as to what you are asking for.
score: 0
comment on: http://stackoverflow.com/q/51665149
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90478937
type: QuestionComment
type: Comment
has text: If you want to evaluate an expression in a string as if it were source code, you have to call [`eval`](https://docs.python.org/3/library/functions.html#eval) on the string. There's a whole host of reasons why that's a bad idea, but if that's really what you want to do, that's the way to do it.
score: 0
comment on: http://stackoverflow.com/q/51759798

http://stackoverflow.com/q/51771714
tagged with: python
type: AnsweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90506978
type: Question
has answer: http://stackoverflow.com/a/51771947
score: -1
has title: When to use string and bytes type in Python3
has body: In Python 3, the difference between string and bytes objects are explicit. But it confuses me when I need to: decide which one to use, and figure out which one is returned or needed as argument by a library function. Is there a rule of thumb?
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51771947

http://stackoverflow.com/comment/90330813
has text: @PM2Ring it matches 10 and 8: `| (output == 10 & output == 8 )`. And I think you are right. It's a list that contains arrays, right?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51684046

http://stackoverflow.com/q/51677160
has comment: http://stackoverflow.com/comment/90317582
answer count: 0
tagged with: pivot-table
type: UnansweredQuestion
tagged with: python
has body: I have a data pipeline that I'm writing in Python with Pandas. It's working, and I mostly like it. Pretty good with Python. Less good with Pandas at this point. As a student of Python, however, I'm always looking to be more idiomatic and not rely on loops and logic that I may use in other languages. Specifically, I'm always amazed at how series and frames can be iterated over using Pandas methods, rather than having to build loops around them. Here is the source file. I also have other demographic information that comes from an API call. This code has been truncated out of my example, but assume that data['record'] has my demographic data, and I can merge that successfully using pd.merge(). +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ |StudentFirstName|StudentMiddleName|StudentLastName|UniqueIdentifier|Grade|GOM |SchoolYear|Fall_September|Fall_SeptemberDateGiven|Fall_SeptemberNationalPercentileRank|Winter_January|Winter_JanuaryDateGiven|Winter_JanuaryNationalPercentileRank|Spring_May|Spring_MayDateGiven|Spring_MayNationalPercentileRank| +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | | | |100 |1 |LNF |2017 |29 |9/11/2017 |14 | | | | | | | | | | |100 |1 |LSF |2017 |31 |9/11/2017 |51 | | | | | | | | | | |100 |1 |M-COMP|2017 |8 |9/20/2017 |48 |15 |2/5/2018 |17 |42 |5/8/2018 |65 | | | | |100 |1 |MNM |2017 |9 |9/11/2017 |36 |7 |2/1/2018 |3 |5 |5/8/2018 |1 | | | | |100 |1 |NIM |2017 |35 |9/11/2017 |34 |62 |2/1/2018 |52 |51 |5/8/2018 |18 | | | | |100 |1 …
has comment: http://stackoverflow.com/comment/90318213
score: 0
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/90317667
has comment: http://stackoverflow.com/comment/90318323
tagged with: pandas
has title: Python Pandas merge, melt, pivot_table for data pipeline
has comment: http://stackoverflow.com/comment/90318950
tagged with: melt

http://stackoverflow.com/q/51735607
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90435197
has comment: http://stackoverflow.com/comment/90435018
type: Question
has body: I'm trying to take from a txt file and put them into a variable. Here's my code: #file_len function, got it from somewhere on stack exchange def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 #various variables, containing names/files #wordList File, stores all the words wordListFileName = '/Users/k/Desktop/Cyber/HashCrack/wordlist.txt' wordListFile = open(wordListFileName) #wordList list, stores all the words from the wordList file wordList = [] #passList file, stores all the passwords passListFileName = '/Users/k/Desktop/Cyber/HashCrack/passlist.txt' passListFile = open(passListFileName, 'w') #for loop, gets all the words in the wordList file, stores them in wordList list for i in range(0, 185051): if wordListFile.readline(i) == '': print('skipped empty line ' + str(i)) else: wordList.append(wordListFile.readline(i).strip('\n')) print('added ' + wordListFile.readline(i).strip('\n') + ' to wordList under number ' + str(i) + ' and word ' + wordList[i-1]) So, the for loop skips any empty lines in the wordlist.txt file and, if they're not empty, adds them to the wordList list. However, for some weird reason, it doesn't like the first three lines and puts them into the variable as blank lines. Why does it do that? sure, they're not the most important words in the world, but I'd still like it to use them.
tagged with: for-loop
score: 0
has comment: http://stackoverflow.com/comment/90432412
answer count: 1
has answer: http://stackoverflow.com/a/51735847
accepted answer: http://stackoverflow.com/a/51735847
tagged with: string
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90432279
has comment: http://stackoverflow.com/comment/90432110
has comment: http://stackoverflow.com/comment/90432013
tagged with: python
has comment: http://stackoverflow.com/comment/90435223
has comment: http://stackoverflow.com/comment/90435209
has title: Python 3 adding empty strings to list via readline

http://stackoverflow.com/a/51696215
downvote count: 0
has body: def add_func(lst): return list(sum(lst)-i for i in lst)) print(add_func([1,2,3,4]))
type: Answer
answers question: http://stackoverflow.com/q/51693929
upvote count: 1
score: 1

http://stackoverflow.com/comment/90538426
has text: is there a way I can get {2, 4, 6, 8} without adding them separately inside for-loop (see the second approach)?
comment on: http://stackoverflow.com/a/51789910
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90401366
has text: @VikasDamodar , yes
type: QuestionComment
comment on: http://stackoverflow.com/q/51720345
type: Comment
score: 0

http://stackoverflow.com/comment/90421892
comment on: http://stackoverflow.com/a/51730247
score: 0
type: AnswerComment
type: Comment
has text: Hacking in a hurry - no excuse though.

modal-dialog
tag name: modal-dialog
type: Tag
tags question: http://stackoverflow.com/q/51713085

http://stackoverflow.com/a/51775701
has comment: http://stackoverflow.com/comment/90509924
has comment: http://stackoverflow.com/comment/90510012
has body: You can find such information on pypi.org, but you can fully count only on well maintained packages, since they usually run all tests against python versions, that they list. e.g. https://pypi.org/project/argparse/ Programming Language Python Python :: 2 Python :: 2.3 Python :: 2.4 Python :: 2.5 Python :: 2.6 Python :: 2.7 Python :: 3 Python :: 3.0 Python :: 3.1 Python :: 3.2 Python :: 3.3 Python :: 3.4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51775587
type: Answer
accepted answer of: http://stackoverflow.com/q/51775587
score: 2
upvote count: 2

http://stackoverflow.com/comment/90370055
comment on: http://stackoverflow.com/a/51704300
type: AnswerComment
has text: Will try this .Thanks. pytest is so vast, Its like I am lost in the waves of pytest
score: 0
type: Comment

http://stackoverflow.com/q/51645862
tagged with: python
has comment: http://stackoverflow.com/comment/90255714
has comment: http://stackoverflow.com/comment/98662780
answer count: 0
score: 1
tagged with: image-processing
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90256519
has title: How to convert an RGB image to stright lines in python?
has comment: http://stackoverflow.com/comment/90255621
has comment: http://stackoverflow.com/comment/90258883
downvote count: 0
favorite count: 0
has body: I am trying to learn python by doing some small projects. one of them is as follows: I want to write a code that converts an image to straight lines. I am actually into string art and want to receive the output in a way that can be used to easily build the string art by using the output of my code. so, I'll try to explain what I'm trying to do: 1. import an image and get the pixel coordinate and save them into an array. 2.get brightness value for each pixel of the image. 3. choose a number of lines that are going to be the "quality" of my output, in reality, they'd be the strings that I use to create the art. 4.draw a random amount of lines through the darkest pixel of the image, and compare each lines total brightness to the others, the darkest (the line hitting the darkest pixels) is chosen and the pixels in that line are removed from the pixel array. 5.save the two x and y coordinate of every line's intersection with the image borders ( my canvas). so I can use this later and know where to start and finish ny strings. 6. repeat the step 4 and 5, for the number of lines chosen. 7. print or save the XY coordinates of the line intersections with image borders. I plan using PIL and numpy to do this, now my question is this: a. do you think there are easier or better ways to active my goal? b. what is the best way to get a clean array of pixels from any given digital image? you can see the kind of image I'm trying to produce at linify.me thanks.
type: UnansweredQuestion

http://stackoverflow.com/q/51726081
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90415601
type: Question
has title: Plotting 3D data as an image in python
answer count: 2
has answer: http://stackoverflow.com/a/51727955
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90412681
has comment: http://stackoverflow.com/comment/90415941
tagged with: data-visualization
possible better answer: http://stackoverflow.com/a/51729377
tagged with: python
has answer: http://stackoverflow.com/a/51729377
has body: I have data in 3 dimensions. I would like to plot the first two dimensions and colorize by the third. I want it show up as an image like hist2d would do, except instead of being colorized by the occupation of the first two dimensions, I want it to be colorized by the third dimension. I think this will require binning everything. How can this be achieved? Example data: x = np.random.normal(loc=10, scale=2, size=100) y = np.random.normal(loc=25, scale=5, size=100) z = np.cos(x)+np.sin(y) I want to plot x vs y and colorize by the intensity z. But, not just a scatterplot, I want it to come out as an image like this.
accepted answer: http://stackoverflow.com/a/51727955
has comment: http://stackoverflow.com/comment/90416000
upvote count: 2
has comment: http://stackoverflow.com/comment/90413692
downvote count: 1
has comment: http://stackoverflow.com/comment/90415906

http://stackoverflow.com/comment/90502278
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51759851
has text: How do I make sure PyInstaller is installed under 3.6.4? I downloaded it while the path was open (user/python364/Pip install PyInstaller ) and it installed

http://stackoverflow.com/q/51733318
has comment: http://stackoverflow.com/comment/90429064
has comment: http://stackoverflow.com/comment/90428197
has comment: http://stackoverflow.com/comment/90428068
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90428250
has comment: http://stackoverflow.com/comment/90428333
has comment: http://stackoverflow.com/comment/90428134
has title: Cython cannot find "__file__"
has comment: http://stackoverflow.com/comment/90427977
has body: I recently started using Cython, and when compiling one of my scripts, the line: Y = str(os.path.dirname(os.path.abspath(__file__ ))) seems to have issues when compiling. Now I understand it cannot find the "file" after it has been compiled with Cython, but I am looking for another way to find the file's local path so that it can be used to reference other files. For example, if the file was stored in C:\Users\example\test.py, I need something that can store that directory in a variable I can use later. The error I receive in the command line: name '__file__' is not defined
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90427444
tagged with: cython
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90427424
tagged with: os.path
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90427821

http://stackoverflow.com/comment/90326348
score: 0
type: AnswerComment
has text: How do I make change my code to make it go to other sites , I am not getting why next page doesnt have the value for another page
type: Comment
comment on: http://stackoverflow.com/a/51678593

http://stackoverflow.com/q/51651633
type: Question
has comment: http://stackoverflow.com/comment/90268336
has answer: http://stackoverflow.com/a/51651912
has body: I have function that includes a while loop that repeatedly reading from serial port. How do I manage to pull those line to another function without breaking the loop ? def reading_from_serial(): while 1: read_line = ser.readline()
score: -1
answer count: 3
has answer: http://stackoverflow.com/a/51651872
tagged with: pyserial
upvote count: 0
favorite count: 0
has title: Python: Can't pull string from while loop to another function
has answer: http://stackoverflow.com/a/51652454
tagged with: while-loop
tagged with: serial-port
has comment: http://stackoverflow.com/comment/90316187
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90305777
has comment: http://stackoverflow.com/comment/90345304
downvote count: 1

http://stackoverflow.com/a/51784689
has comment: http://stackoverflow.com/comment/90527018
has comment: http://stackoverflow.com/comment/90527934
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51784499
accepted answer of: http://stackoverflow.com/q/51784499
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90527656
downvote count: 0
has body: Did you already look into ngx-electron? You can access electron through angular and then call a ChildProcess on NodeJS to spawn/execute your command. Include your script into the bundle, call it from the command using the information provided in the links above.
type: Answer

http://stackoverflow.com/a/71005344
score: 1
answers question: http://stackoverflow.com/q/51762938
downvote count: 0
type: Answer
has body: Palette = ["#090364", "#091e75"] #define your preference sns.set_style("whitegrid") sns.set_palette(Palette) #use the list defined in the function plot = sns.countplot(df['Purchased']) #Enjoy ploting
upvote count: 1

http://stackoverflow.com/comment/90396051
comment on: http://stackoverflow.com/q/51706019
type: Comment
type: QuestionComment
has text: @GiacomoAlzetta If I using shell=False, it give me an error:No such file or directory: 'python a.py'.
score: 0

http://stackoverflow.com/q/51693934
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51694018
accepted answer: http://stackoverflow.com/a/51694018
has comment: http://stackoverflow.com/comment/90349209
downvote count: 1
has comment: http://stackoverflow.com/comment/90349688
type: Question
score: 1
upvote count: 2
tagged with: regex-lookarounds
has comment: http://stackoverflow.com/comment/90349271
has comment: http://stackoverflow.com/comment/90349498
answer count: 1
has body: I am trying to understand re.split() function with non-capturing group to split a comma delimited string. This is my code: pattern = re.compile(r',(?=(?:"[^"]*")*[^"]*$)') text = 'qarcac,"this is, test1",123566' results= re.split(pattern, text) for r in results: print(r.strip()) When I execute this code, the results are as expected. split1: qarcac split2: "this is, test1" split3: 123566 whereas if i add one more double quoted string to the source text, it doesn't work as expected. text = 'qarcac,"this is, test1","this is, test2", 123566, testdata' and produces the below output split1: qarcac,"this is, test1" split2: "this is, test2" split3: 123566 Can someone explain me what's going on here and how non-capturing group works differently in these two cases?
favorite count: 0
linked to: http://stackoverflow.com/q/632475
has comment: http://stackoverflow.com/comment/90349313
tagged with: python
tagged with: regex
has title: Python Regex Non-Capturing Group

http://stackoverflow.com/a/51670278
has comment: http://stackoverflow.com/comment/90303304
answers question: http://stackoverflow.com/q/51669476
downvote count: 0
has comment: http://stackoverflow.com/comment/90303407
type: Answer
score: 1
has body: You can iterate over the rows and group the element by build new array while checking last elements and append only if difference. Function as follow: def groupRow(row): newRow = [row[0]] for elem in row: if elem != newRow[-1]: newRow.append(elem) return newRow Iterate and replace every row in the shape with the newRow from that function
upvote count: 1

http://stackoverflow.com/comment/90478653
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51759688
has text: @Loocid I have tried that there it is fine, why it's working like this in such condition

http://stackoverflow.com/comment/90269525
comment on: http://stackoverflow.com/q/51653070
has text: Split the code in two different loops, first check that all files are here then do your computation. If the other files names are defined inside some files you'll have no other choice, unless I don't understand the question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51646461
favorite count: 0
tagged with: python-3.x
has body: For any of the thermal images, there is a difference between hot and cold regions. Is there any python library that crop or extracts these cold or blue regions from the thermal images. These regions can be at anywhere in the image.
tagged with: python
has answer: http://stackoverflow.com/a/51646631
accepted answer: http://stackoverflow.com/a/51646631
type: AnsweredQuestion
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/90256647
has title: Extract or Crop out the cold or hot region of a Thermal Image
has comment: http://stackoverflow.com/comment/90258266
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90256738

http://stackoverflow.com/q/51772350
type: Question
has body: I want to query a PostgreSQL with pyspark within a jupyter notebook. I have browsed a lot of questions on StackOverflow but none of them worked for me, mainly because the answers seemed outdated. Here's my minimal code: from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() url = 'jdbc:postgresql://host/dbname' properties = {'user': 'username', 'password': 'pwd'} df = spark.read.jdbc(url=url, table='tablename', properties=properties) Running this from a notebook would raise the following error: Py4JJavaError: An error occurred while calling o69.jdbc. : java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(DriverManager.java:315) at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$7.apply(JDBCOptions.scala:85) at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$7.apply(JDBCOptions.scala:85) at scala.Option.getOrElse(Option.scala:121)... The principal tips I have found were summed up in the link below but unfortunately I can't get them to work in my notebook: Pyspark connection to Postgres database in ipython notebook Note: I am using Spark 2.3.1 and Python 3.6.3 and I am able to connect to the database from the pyspark shell if I specify the jar location. pyspark --driver-class-path /home/.../postgresql.jar --jars /home/.../jars/postgresql.jar Thanks to anyone who can help me on this one. EDIT The answers from How to load jar dependenices in IPython Notebook are already listed in the link I shared myself, and do not work for me. I already tried to configure the environment variable from the notebook: import os os.environ['PYSPARK_SUBMIT_ARGS'] = '--driver-class-path /path/to/postgresql.jar --jars /path/to/postgresql.jar' There's nothing wrong with the file path or the file itself since it works fine when I specify it and run the pyspark-shell.
tagged with: pyspark
score: 10
linked to: http://stackoverflow.com/q/33908156
upvote count: 10
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/51986646
has title: How to specify driver class path when using pyspark within a jupyter notebook?
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51986646
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46919791

http://stackoverflow.com/comment/90428623
comment on: http://stackoverflow.com/q/51733931
has text: Depends on your interpreter/compiler. I guess you're asking about CPython?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90375052
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51706408
has text: Thanks for the response! Unfortunately none of those methods worked in displaying the time for me.

http://stackoverflow.com/comment/90345131
type: Comment
has text: andrew,IonicSolutions I have updated the question. please see the end. I'll try to create a sample. but its hard to reproduce the behaviour i'm seeing in a toy sample.
type: QuestionComment
comment on: http://stackoverflow.com/q/51691465
score: 0

http://stackoverflow.com/q/51732834
tagged with: method-resolution-order
answer count: 1
duplicate of: http://stackoverflow.com/q/29214888
tagged with: python-3.6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51733038
has comment: http://stackoverflow.com/comment/90426643
linked to: http://stackoverflow.com/q/47808926
has body: class Base(object): def __init__(self): print ("Base") class childA(Base): def __init__(self): print ('Child A') Base.__init__(self) class childB(Base,childA): def __init__(self): print ('Child B') super(childB, self).__init__() b=childB() Inheritance would go as childB, Base, childA, Base and after applying MRO, it should become childB,childA,Base. But its throwing MRO error. why?
type: Question
accepted answer: http://stackoverflow.com/a/51733038
tagged with: python
duplicate of: http://stackoverflow.com/q/47808926
has title: A consistent Method Resolution Order couldn't be created (MRO error)
score: 0

http://stackoverflow.com/a/75437763
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51733931
type: Answer
has body: As Jean-François Fabre already answered, both variants are equivalent in this very case (i.e., the bytecode is the same). In other cases where the resulting code should be checked for equality, we can do this by comparing its binary representation. A string can be compiled by dis.Bytecode(str), the binary representation is stored in attributes of codeobj.co_code. first = """ x = 'hello joe' if x == 'hello': print('nope') elif x == 'hello joe': print(x) """ second = """ x = 'hello joe' if x == 'hello': print('nope') else: if x == 'hello joe': print(x) """ import dis # binary representation of bytecode of compiled str def str_to_binary(f): return dis.Bytecode(f).codeobj.co_code print(f"{str_to_binary(first) == str_to_binary(second) = }") output: str_to_binary(first) == str_to_binary(second) = True In order to get the bytecode of a function it is not even necessary to import dis, you can access the code object via __code__, see the following example with two functions doing exactly the same thing: 1 def f(a): return a def g(b): return b # binary representation of a function's bytecode def fun_binary(function): return function.__code__.co_code print(f"{fun_binary(f) == fun_binary(g) = }") output: fun_binary(f) == fun_binary(g) = True 1 The functions f and g use different names for local variables which is reflected by the parenthesized information given by dis.dis() but the resulting byte code is identical for both functions.

http://stackoverflow.com/comment/90320030
type: Comment
comment on: http://stackoverflow.com/q/51677207
has text: @WarrenWeckesser, true, A lot can be done with `type`. But a function that works well as a `type`, can be used just as easily after parsing to convert string values. And I think, for a beginner, that will be less confusing. I prefer to focus on `argparse` as a parser. But there are extensions and alternative parsers that try to integrate parsing and execution (e.g. `plac`)
score: 0
type: QuestionComment

http://stackoverflow.com/a/51658111
score: 5
answers question: http://stackoverflow.com/q/51658015
upvote count: 5
has comment: http://stackoverflow.com/comment/90280030
has comment: http://stackoverflow.com/comment/90280667
downvote count: 0
has body: you need, df.loc[(df['Message'].str.contains('|'.join(watchlist), case=False)),'SomeSeries'] = 'SomeUpdate'
type: Answer
has comment: http://stackoverflow.com/comment/90280880

http://stackoverflow.com/q/51771182
tagged with: python
accepted answer: http://stackoverflow.com/a/51771540
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90501862
downvote count: 3
type: Question
has title: Python,file handling
has comment: http://stackoverflow.com/comment/90501242
has answer: http://stackoverflow.com/a/51771540
upvote count: 0
answer count: 1
favorite count: 0
tagged with: file-handling
has body: import csv from _csv import writer f1=open("formatted.txt") with open("write.csv","wb") as f: writer = csv.writer(f, lineterminator='\n') reader=csv.reader(f) for line in f1: writer.writerow(line) I have a text file of some uniform records. When I am trying to get that into an excel file, I am getting each character separate in each cell. How can we make sure that each specified value will go in separate columns? input text file output file
tagged with: http://stackoverflow.com/tag/csv
score: -3

http://stackoverflow.com/a/51772500
score: 0
has body: The problem in your python code is, that you use the global path variable in __del__ instead of self.path. Therefore you get an infinite recursion. Better convert your class into functions: import os def readFile(path, words): with open(path, "r") as new_file: data = new_file.read(8192) for word in words: if word in data: print "name: {} path: {}".format(new_file.name, path) break def search(path, words): files = os.listdir(path) for filename in files: fullname = os.path.join(path, filename) if not os.path.isdir(fullname): readFile(fullname, words) else: search(fullname, words) path = raw_input("input path to start: ") words = [] while True: word = raw_input("input word to search (write //quit to start searching): ") if word == "//quit": break words.append(word) print "start searching for {}...".format(', '.join(words)) search(path, words)
has comment: http://stackoverflow.com/comment/90525768
type: Answer
has comment: http://stackoverflow.com/comment/90505185
answers question: http://stackoverflow.com/q/51772318

http://stackoverflow.com/q/51797751
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/90557911
tagged with: python
type: UnansweredQuestion
has body: I am running Windows 10 and Python 3.6.3 . I am trying to install flask-mysqldb using pip install flask-mysqldb. It fails with the following: Command "c:\users...\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\..~1\AppData\Local\Temp\pip-install-5lp__7r6\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users...~1\AppData\Local\Temp\pip-record-zvpyshav\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users...~1\AppData\Local\Temp\pip-install-5lp__7r6\mysqlclient\ I have tried to install the build tools for Visual Studio, but this doesn't seem to help. Any help or direction would be appreciated. Thank you.
has answer: http://stackoverflow.com/a/55171548
tagged with: mysql
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90552516
type: Question
score: 0
has title: Error Installing flask-mysqldb
answer count: 1

http://stackoverflow.com/comment/90789908
type: QuestionComment
comment on: http://stackoverflow.com/q/51713115
has text: KEEP IN MIND -- IM USING WINDOWS 10
score: 0
type: Comment

bash
tags question: http://stackoverflow.com/q/51640528
tags question: http://stackoverflow.com/q/51668189
tags question: http://stackoverflow.com/q/51697061
tags question: http://stackoverflow.com/q/51732255
tags question: http://stackoverflow.com/q/51766384
tags question: http://stackoverflow.com/q/51644416
tags question: http://stackoverflow.com/q/51660519
tags question: http://stackoverflow.com/q/51767909
tags question: http://stackoverflow.com/q/51640572
tags question: http://stackoverflow.com/q/51789278
type: Tag
tags question: http://stackoverflow.com/q/51653422
tags question: http://stackoverflow.com/q/51747092
tag name: bash
tags question: http://stackoverflow.com/q/51739163
tags question: http://stackoverflow.com/q/51738059

http://stackoverflow.com/comment/90448612
type: AnswerComment
type: Comment
has text: Thanks, buddy. I will see how to handle this!
comment on: http://stackoverflow.com/a/51744291
score: 1

http://stackoverflow.com/comment/90286429
type: Comment
has text: Thank you for the answer. Although now im getting an error stating `MainPageGUI has no attribute 'listbox`. Is their any reason why this may occur?
type: AnswerComment
comment on: http://stackoverflow.com/a/51660909
score: 0

http://stackoverflow.com/comment/90279661
comment on: http://stackoverflow.com/a/51656945
score: 0
type: Comment
has text: With a `ThreadPool` (see for example this question and the answer: https://stackoverflow.com/questions/3033952/threading-pool-similar-to-the-multiprocessing-pool )
type: AnswerComment

http://stackoverflow.com/a/51691351
has body: A list comprehension would be perfect here: &gt;&gt;&gt; [[trip["pickup_latitude"], trip["pickup_longitude"]] for trip in cleaned_trips] [[40.64499, -73.78115], [40.766931, -73.982098], [40.77773, -73.951902], [40.795678, -73.971049]] You're seeing the same location appended 12 times because you only create marker once (on the line reading marker = {}) and then append it multiple times in a loop. To have a new dictionary appended to the list each time, make sure you create a fresh one on each loop: def markers_from_trips(trips): new_list = [] for trip in trips: marker = {"location": [trip["pickup_latitude"], trip["pickup_longitude"]]} new_list.append(marker) return new_list or, use the list comprehension again: &gt;&gt;&gt; [{"location": [trip["pickup_latitude"], trip["pickup_longitude"]]} for trip in cleaned_trips] [{'location': [40.64499, -73.78115]}, {'location': [40.766931, -73.982098]}, {'location': [40.77773, -73.951902]}, {'location': [40.795678, -73.971049]}]
score: 1
accepted answer of: http://stackoverflow.com/q/51691292
answers question: http://stackoverflow.com/q/51691292
has comment: http://stackoverflow.com/comment/90344821
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90353419
has comment: http://stackoverflow.com/comment/90351281
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90412855
has text: Could you please check the socket types as I mentioned in the comment above that? Your client socket appears to be STREAM, your server is DGRAM. That might very well be the issue with your connection ...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51723005

http://stackoverflow.com/a/51691683
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51686199
type: Answer
answers question: http://stackoverflow.com/q/51686199
score: 0
has body: initialize takes a function with signature (parent_block, *indices). That is, for m.param = Param(m.index, initialize=init_func), you would want to have: mydict = { ('A', 'B', 'x', 'y'): 100, ('A', 'C', 'x', 'y'): 10, ('D', 'E', 'x', 'y'): 20, ('D', 'A', 'x', 'y'): 1} def init_func(m, idx): return sum(val for tup, val in mydict.items() if tup[0] == idx)

http://stackoverflow.com/q/51670530
tagged with: python-multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/90303563
favorite count: 0
linked to: http://stackoverflow.com/q/26764978
type: UnansweredQuestion
has title: Python Multithreading COM Objects
downvote count: 1
tagged with: win32com
score: -1
has body: I have 3 python modules, main.py client.py interface.py interface.py is a Qt UI modules so it doesn't have anything related to this question. main.py imports the interface.py and client.py class and execute the main functions of the program. client.py is the core module where all the core functions are located. one of the function in client.py (format_excel function) is to call the win32com.client to execute excel operations, which it will modify the output of the excel from the inputs given. the issue here is when I start a thread in main.py to run the function in client.py (format_excel function) and it gave me and error like this. The application called an interface that was marshalled for a different thread. my code as below (simplified) client.py class Formatter: def __init__(self): self._excel = win32.dynamic.Dispatch('Excel.Application') def format_excel(self, info_list): pythoncom.CoInitialize() self._excel.Workbooks.Add() # other codes main.py self._data contain some info grabbed from GUI so I did not added into the snippet class Main: def __init__(self): self._format = Formatter() self._data = [] def start(self): t = threading.Thread(target=self._format.format_excel, args=[self._data]) t.start() # other codes need some help here.
type: Question
has answer: http://stackoverflow.com/a/73187248
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/90425099
type: Comment
type: QuestionComment
score: 2
has text: I'm voting to close this question as off-topic because this is a google support issue not a programming problem
comment on: http://stackoverflow.com/q/51731943

http://stackoverflow.com/q/51726782
has comment: http://stackoverflow.com/comment/90414936
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90415328
has comment: http://stackoverflow.com/comment/90416868
tagged with: python
has comment: http://stackoverflow.com/comment/90416808
has comment: http://stackoverflow.com/comment/90418205
linked to: http://stackoverflow.com/q/28343240
has comment: http://stackoverflow.com/comment/90415676
answer count: 0
has body: I have a python script below that attempts to make a connection to a sql db. The database was having some connection issues and I want the script to try to reconnect to the db so I added try / except. However the script still does not automatically reconnect with the try / except statement. The connection to the db gets killed after 149 queries and the script doesn't try to reconnect based on what I am seeing on the screen. If anyone can help me with getting my script to reconnect to the db automatically I would greatly appreciate it! from __future__ import print_function try: import psycopg2 except ImportError: raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n') sys.exit(1) import re import sys import json import pprint import time outfilepath = "crtsh_output/crtsh_flat_file" DB_HOST = 'crt.sh' DB_NAME = 'certwatch' DB_USER = 'guest' DELAY = 5 #conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) #cursor = conn.cursor() def connect_to_db(tries=0): filepath = 'forager.txt' # conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) # cursor = conn.cursor() with open(filepath) as fp: unique_domains = '' try: conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) cursor = conn.cursor() for cnt, domain_name in enumerate(fp): print("Line {}: {}".format(cnt, domain_name)) print(domain_name) domain_name = domain_name.rstrip() cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate) FROM certificate c, certificate_identity ci WHERE c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) = lower(%s) AND x509_notAfter(c.certificate) &gt; statement_timestamp()''', (domain_name,)) unique_domains = cursor.fetchall() pprint.pprint(unique_domains) outfilepath = "crtsh1" + ".json" with open(out…
score: 0
has title: Python script does not try to reconnect to sql db after implementing try / exception
type: Question
has comment: http://stackoverflow.com/comment/90420062
has comment: http://stackoverflow.com/comment/90417181
tagged with: try-except
tagged with: sql
has comment: http://stackoverflow.com/comment/90416159
has comment: http://stackoverflow.com/comment/90417391
has comment: http://stackoverflow.com/comment/90416675
tagged with: python-3.x

http://stackoverflow.com/q/51652690
tagged with: python
has answer: http://stackoverflow.com/a/51657144
upvote count: 7
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52137161
has answer: http://stackoverflow.com/a/52198292
answer count: 9
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69279881
has answer: http://stackoverflow.com/a/51743289
has body: I am very new to use github. I have installed github in ubuntu 16.04, I installed python 2.7.12, tensorflow 1.9 and keras. I want to use my own custom activation and optimizer in keras RNN. I searched in web and came to know i need to install keras-contrib package to use advanced activation and custom activation function. So, I install the keras-contrib from github. But I don't know how to work with it and how to run the program using keras-contrib. But i tried with following commands git clone https://www.github.com/keras-team/keras-contrib.git cd keras-contrib python setup.py install then I tried with this following code from keras.models import Sequential from keras.layers import Dense import numpy as np from keras_contrib.layers.advanced_activations import PELU it showing the following error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "keras_contrib/__init__.py", line 4, in &lt;module&gt; from . import layers File "keras_contrib/layers/__init__.py", line 3, in &lt;module&gt; from .convolutional import * File "keras_contrib/layers/convolutional.py", line 15, in &lt;module&gt; from keras.utils.conv_utils import normalize_data_format ImportError: cannot import name normalize_data_format Anyone please check this error and help me to sort out this error.
has answer: http://stackoverflow.com/a/68571995
has title: ImportError: cannot import name normalize_data_format
has answer: http://stackoverflow.com/a/51764828
downvote count: 0
score: 7
tagged with: keras
tagged with: github
favorite count: 0
has answer: http://stackoverflow.com/a/51699872
tagged with: importerror
type: Question
has answer: http://stackoverflow.com/a/57408775

http://stackoverflow.com/a/51661030
upvote count: 6
has comment: http://stackoverflow.com/comment/90289213
has body: Here's a minimal example: class Super(): def __init_subclass__(cls): print(cls) class Sub(Super): pass Running this: $ python test.py &lt;class '__main__.Sub'&gt; Why is that? According to Python's data model docs: Whenever a class inherits from another class, init_subclass is called on that class. Sub inherits from Super, so Super.__init_subclass__() gets called. Specifically, type_new() invokes init_subclass in the cpython implementation. The rationale is detailed in PEP 487.
accepted answer of: http://stackoverflow.com/q/51660663
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51660663
type: Answer
score: 6

http://stackoverflow.com/q/51697919
has comment: http://stackoverflow.com/comment/90362238
score: 0
tagged with: automated-tests
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51700688
tagged with: selenium
has comment: http://stackoverflow.com/comment/90361549
type: Question
has comment: http://stackoverflow.com/comment/90359955
has title: Second element on selenium chromedriver
has body: When trying to automate our application, there are two div with same parameters. I'm not able to find a way to recognize these. Please let me know what could be the other ways to identify these elements in selenium chromedriver in python. I tried it, no it's doesn't work for me. driver.find_element_by_xpath("(//div[@class='c3'])[2]/p").send_keys('text') This is my html code test1 test2 test3 I want add my text after test2
has comment: http://stackoverflow.com/comment/90362042

http://stackoverflow.com/comment/90468030
comment on: http://stackoverflow.com/q/51754074
score: 0
has text: Possible duplicate of [Python Requests and persistent sessions](https://stackoverflow.com/questions/12737740/python-requests-and-persistent-sessions)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51735493
tagged with: python
has title: Why does the python file descriptor 'w+' erase the contents of file when used for reading?
has answer: http://stackoverflow.com/a/51735550
accepted answer: http://stackoverflow.com/a/51735550
has body: contents of foo.txt Hello World! Two functions: def read1(file): with open(file, 'r+') as fp: print fp.read() def read2(file): with open(file, 'w+') as fp: print fp.read() the function read1('foo.txt') outputs: Hello World! the function read2('foo.txt') outputs: It essentially outputs nothing. But why? Not only that, the contents of foo.txt has been erased as well. I thought that w+ means you truncate the file, meaning you write over it. But I did not even use fp.write().
tagged with: file
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90431846
answer count: 1
has comment: http://stackoverflow.com/comment/90431872
score: 0