Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
10,800
31,152,340
Python Dictionary Trouble: Grouping by elements in tuple key
<p>so I have a dictionary that looks something like this, with 4 element tuples as keys, and a list of lists as corresponding values. (yay indexing)</p> <pre><code>{('A002', 'R051', '02-00-00', 'LEXINGTON AVE'): [[datetime.datetime(2015, 6, 20, 0, 0), 750], ...
<p>Yep, just go ahead and make another dictionary. Supposing the data you have above is stored in <code>data</code>, we'll make a dictionary called <code>short_data</code>:</p> <pre><code>short_data = {} for key, value in data.items(): short_key = (key[0], key[1], key[3]) if short_key in short_data: sh...
python|dictionary
3
10,801
40,050,285
do I need another .condarc for each environment
<p>I'm using anaconda and I needed to use <code>.condarc</code> to setup proxy settings.</p> <p>Do I need to put another <code>.condarc</code> somewhere for an environment I created? If so, where?</p>
<p>You don't need a separate <code>.condarc</code> for different environments. As I can tell you are aware, that file is used to store runtime configuration information for conda. In the <a href="http://conda.pydata.org/docs/config.html#the-conda-configuration-file-condarc" rel="nofollow">docs</a>, we see that it is us...
python|virtualenv|anaconda|conda
1
10,802
40,229,029
list organized into columns not rows
<p>I have a list of lists that I am trying to write to columns instead of rows. My list looks like this:</p> <pre><code>['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31'] </code></pre> <p>I want it to llok like this:</p> <pre><code>31 31 31 31 32 31 31 32 31 32 31 31 8 8 8 31 </code></pre> <p>I can get a ni...
<p>You may use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> for this. Firstly convert your <em>list of string</em> to <em>list of list</em> using <code>str.split()</code>, then iterate over <em>zip</em>ed list. Below is the sample code: </p> <pre><code>&gt;&gt;&g...
python|list|rows
2
10,803
28,999,897
Scala "case map" equivalent in python
<p>How to write the following scala code in pyspark?</p> <pre><code>rdd1.join(rdd2.map {case ((t, w), u) =&gt; (t, (w, u))}).map {case (t, (v, (w, u))) =&gt; ((t, w), (u, v))}.collect() </code></pre>
<p>You can use lambda functions for this:</p> <pre><code>rdd1 = sc.parallelize(range(1,10)).map(lambda x: (x, x+1)) rdd2 = sc.parallelize(range(1,10)).map(lambda x: ((x, x*2), x*3))) rdd1.join(rdd2.map(lambda ((t, w), u): (t, (w, u)))).map(lambda (t, (v, (w, u))): ((t, w), (u, v))).collect() </code></pre>
python|scala|apache-spark
3
10,804
28,890,258
Regarding lambdas in python
<p>I am weak in python especially </p> <p>I have a class defined as the following:-</p> <pre><code>class Employee: def __init__(self, id, age): self.age = age self.id = id </code></pre> <p>I have a lambda to read:-</p> <pre><code>expr = (0, lambda acc, e: max(acc, e.age), lambda x: x) </code></pre...
<p>Expanding my comment, that's how you can complete your code using standard Python functions:</p> <pre><code>from functools import reduce # your code maxAge = reduce(expr[1], map(expr[2], employeeList), expr[0]) </code></pre> <p>or even</p> <pre><code>def map_reduce(iterable, initializer, reduce_pred, map_pred):...
python|lambda
2
10,805
52,131,508
How do I extract data from Bokeh Point Draw Tool - generated html table for use in python
<p>After much trouble, I was finally able to get Bokeh's point draw tool to work only to run into another problem: working with the data generated from this tool. The code below generates an interactive plot, and placing/moving points updates the table in real time. However, I cannot figure out how to extract the data...
<p>I ended up just writing the below function to extract the new vertices generated from the point draw tool from the HTML file itself. A tip to anyone else in this predicament, make sure you increase the size of the displayed table such that all vertices are displayed at one time (no vertical scroll bar). Otherwise ...
python|html|bokeh
1
10,806
52,371,310
How can I manage big excel files with python?
<p>I am facing some issues in managing very simple tasks on an excel file with python. The excel file is about 200k rows, around 40 columns and 64 MB.</p> <p>Running the most basics commands are taking entire minutes to run, such as:</p> <pre><code>import openpyxl workbook= openpyxl.load_workbook('filename') sh = wor...
<p>I would suggest <strong>pandas</strong> for this. I have processed 600MB xlsx file in pandas with no issues. <a href="https://realpython.com/working-with-large-excel-files-in-pandas/" rel="nofollow noreferrer">https://realpython.com/working-with-large-excel-files-in-pandas/</a></p>
python|excel|openpyxl
1
10,807
52,337,870
Python OpenCV Error: Current thread is not the object's thread
<p>I'm having an error running simple code using cv2 module.</p> <p>It's just:</p> <pre><code>import cv2 img = cv2.imread('sudoku.png',0) cv2.imshow('image',img) </code></pre> <p>And it fails with the following error:</p> <pre><code>QObject::moveToThread: Current thread (0x1b74720) is not the object's thread (0x1...
<p>As noted already, the basis for this problem is discussed in <a href="https://github.com/skvark/opencv-python/issues/46" rel="noreferrer">opencv-python issue 46</a>, and results from the duplication of the following libraries both on the host and the opencv-python distro <strong>libQtDBus</strong> <strong>libQtCore<...
python|qt|opencv
16
10,808
51,712,766
Date and Time Delta between two Dates
<p>I have a table structure like below for completion of the task against name , I want to take difference between End_Time to Start_time for each name. Can anyone please suggest time how to do this with python code.</p> <pre><code>start_time End_Time Name 2018-08-05T00:15:00+05:30 2018-08-05T00:17:00+05:30 UM6217...
<p>You need to convert your time to <code>pandas.datetime</code> objects, and then simply subtract both. </p> <pre><code>df[['start_time', 'End_Time']] = df[['start_time', 'End_Time']].apply(lambda x: pd.to_datetime(x.str.split('+').str[0])) df['diff'] = (df.End_Time - df.start_time).dt.total_seconds().div(60).astype(...
python|pandas|datetime|array-difference
1
10,809
19,131,237
Protocol for automatic (and possibly fast) user type conversions?
<p>Assume I have performance-oriented type <code>mylib.color.Hardware</code>, and its user-friendly counterparts <code>mylib.color.RGB</code> and <code>mylib.color.HSB</code>. When user-friendly color passed into library functions, it gets converted into <code>color.Hardware</code>. Now it is implemented by examining t...
<p>You are looking for a component architecture and adaptation. The <a href="http://www.muthukadan.net/docs/zca.html" rel="nofollow">Zope Component Architecture</a> lets you register interfaces and adapters; a central registry to look up converters from one type to another. As long as an adapter exists to convert a val...
python|python-2.7|type-conversion
1
10,810
69,019,890
python subprocess.Popen throwing error while after a Thread is activated
<p>I looked around, but I didn't see any information on this particular problem so I thought I'd ask it here:</p> <p>Whenever I try to run a subprocess.Popen call after starting up a random thread, I get an OSError. My assumption is that there is some aspect to subprocess.py that I don't understand in relation to multi...
<p>QNX is not designed to support <code>fork()</code> within a process after the process has already spawned new threads. From the QNX documentation...</p> <blockquote> <p>Suppose you have a process and you haven't created any threads yet (i.e., you're running with one thread, the one that called main()). When you call...
python|subprocess|qnx
0
10,811
62,141,576
How do I store repeated inputs in Python? (read description for better understanding, it's really simple)
<p>I want to make a program that could make you input the number of times you want to input something, then ask you for your input. After the amount of times it is over, it prints all of your inputs. I don't know how to word it correctly, but here is an example. </p> <blockquote> <pre><code>input: 2 hello 1 hello 2 o...
<p>Check with this </p> <pre><code>a = int (input(" No. of inputs: ")) c=[] for x in range (0,a): b = input(" Enter Input: ") c.append(b) print (c) </code></pre>
python|input|user-input
1
10,812
36,612,919
How to find the point pairs in two point lists with min distance in a efficent way?
<pre><code>pointListA = [(13,45),(33,78),...,(360,240)] pointListB = [(20,36),(47,32),...,(265,322)] </code></pre> <p>The length of pointListA and pointListB is almost 5000 or more.My task is to find the the point in pointListB for each point in pointListA,so that the two points have the min distance between each othe...
<p>I'm not sure but you might be able to do this efficiently by taking the <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.diagonal.html" rel="nofollow noreferrer">diagonal</a> from the matrix resulting from using the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.d...
python|math
2
10,813
36,508,632
Convert Array of DataFrames to Single DataFrame
<p><strong>TLDR:</strong> I don't know how to take an array of DataFrames and build a MultiIndex around it.</p> <p><strong>TLDR 2:</strong> From my research, it is recommended to deal with the return result than to try to work off of a global/single/shared DataFrame in <code>Pool().Map()</code>. If somebody has a way ...
<p>There are several good ways to do this:</p> <p>1) If you are starting with a bunch of Series objects : You set the series objects name parameter to be a tuple. Then use pd.concat([series list], axis=1)</p> <p>2) If you have a single level map of dataframes, you can use the fact that pd.concat can accept a dict...
python|python-2.7|pandas|multiprocessing
0
10,814
22,034,961
How do I exclude items created on same day in Django
<p>I'm trying an <code>exclude()</code> query to exclude objects created on the same day as a user's profile. The user's <code>user.created</code> field is a <code>DateTimeField</code>, but I want to exclude all objects created on the same <em>date</em> as the user:</p> <p>I'm trying:</p> <pre><code>my_objects = MyCl...
<p>Compare <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#year" rel="nofollow">year</a>, <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#month" rel="nofollow">month</a>, <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#day" rel="nofollow">day</a>:</p> <pre...
python|django|datetime|django-queryset
3
10,815
43,881,682
Write Python List to file - works on friends computer but not mine
<p>I've written a program in which I need 3 arrays (lists) to write to a txt file. When I run the code on my computer, the txt file is empty. I sent it to a friend, who ran it and the program populated the txt file on his computer.</p> <p>I have next to no experience coding and need the txt file for a homework assignm...
<p>Did you run this in an interactive interpreter (or in a non-CPython interpreter or otherwise crash in some weird way)? If so, the problem is that you didn't actually <code>flush</code>/<code>close</code> the file; you referenced the <code>close</code> method without calling it. You wanted <code>MyFile.close()</code>...
python|python-3.x
2
10,816
43,772,867
Python Tkinter canvas.delete failure
<p>In the experiment below, the tagbox Label should appear when I press the Button1, and it does. But if I follow that with a press on Button2, I get an error referencing a problem in the delete command of the disappear function, then referring to an "invalid boolean operator in tag search expression" in a tk module.</...
<p>The code should remember the return value of the <code>create_window()</code> call. Then pass it to <code>Canvas.delete</code> method:</p> <pre><code>def __init__(self, master): ... self.item = None def appear(self): self.tagbox = Label(self.booking_canvas,text="Hello") self.disappear() # remove ...
python|tkinter
2
10,817
54,516,973
Is it possible to create custom Tensorflow GRU/LSTM cell?
<p>I'd like to modify the <code>tf.nn.rnn_cell.GRUCell</code> and add another gate to it for second input such that in addition to <code>z</code> – update gate and <code>r</code> – reset gate there would be third <code>g</code> - custom gate for the second input to the network similarly to <a href="https://aclweb.org/a...
<p>It is possible. As illustrated by <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/" rel="nofollow noreferrer">this</a> article, LSTM and GRU cells are just arrangements of non-linearities and arithmetic operations.</p> <p><a href="https://github.com/gitabcworld/skiprnn_pytorch" rel="nofollow noref...
tensorflow
1
10,818
71,346,893
List to Numpy Array: How to convert a list of different size elements to a numpy array without adding extra values (e.g., Null or 0)?
<p>I have list with different element size. Here is the attachment for the reference:</p> <p><a href="https://i.stack.imgur.com/ZYWhk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZYWhk.jpg" alt="enter image description here" /></a></p> <p>As can be seen in the image, first list element size is1095...
<p>If you want to use the list as the input for your deep learning model, you can use the mask and padding. You can find it here <a href="https://www.tensorflow.org/guide/keras/masking_and_padding" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras/masking_and_padding</a> Check that it does not change you...
python|arrays|list|numpy
-1
10,819
71,363,050
Function appears two times in Sphinx autodoc generated documentation
<h2>Background information</h2> <p>I generate documentation from docstrings via Sphinx autodoc. There is a function <code>mypackage.mypackage.foo()</code> located in source file <code>mypackage/mypackage.py</code>. It is imported implicite in the <code>__init__.py</code>, so the user can it use as <code>mypackage.foo()...
<p>@mzjn gave me the right direction. He is correct that there are two <code>automodule</code> directives. So the goal is to make <code>sphinx-apidoc</code> (which generates the directives) ignore <code>mypackage/mypackage.py</code>.</p> <p>For that make it a &quot;private module&quot; with modyfing it's filename start...
python|python-sphinx|autodoc
0
10,820
71,126,250
Django Row_Number usage with group_by ORM
<p>I have a database(screenshot attached) and I want to retrieve the average of readings as per the aggregation size provided. Suppose my aggregation size is 2. <a href="https://i.stack.imgur.com/QuHqy.png" rel="nofollow noreferrer">enter image description here</a></p> <p>So, as per the image, there are four readings f...
<p>Somehow, the internals of django are not doing what you think when combining annotation with Window functions. Filtering also doesn't work when combining window annotation.</p> <p>I was trying querying and multiple example, just to see that there is a ticket here still open :</p> <p><a href="https://code.djangoproje...
python|django|django-rest-framework|orm|window
0
10,821
9,119,968
Construct parsing for unaligned int field?
<p>I am using this nice little package "<a href="http://construct.wikispaces.com/" rel="nofollow">construct</a>" for binary data parsing. However, I ran into a case where the format is defined as:</p> <pre><code>31 24 23 0 +-------------------------+ | status | an int number | +----------------------...
<p>This would be easy if construct contained Int24 types, but it doesn't. Instead, you can specify the bit lengths yourself like this:</p> <pre><code>&gt;&gt;&gt; from construct import BitStruct, BitField &gt;&gt;&gt; sample = "\xff\x01\x01\x01" &gt;&gt;&gt; c = BitStruct("foo", BitField("status", 8), BitField("i", 24...
python|construct
2
10,822
39,214,577
(PY)Object has no attribute error
<pre><code># The imports include turtle graphics and tkinter modules. # The colorchooser and filedialog modules let the user # pick a color and a filename. import turtle import tkinter import tkinter.colorchooser import tkinter.filedialog import xml.dom.minidom # The following classes define the different commands tha...
<p>This is fairly straightforward. You initialize <code>theTurtle</code> in the caller to be a <code>turtle.RawTurtle</code>. <code>RawTurtle</code> doesn't have an attribute or method named <code>move</code>, <a href="https://docs.python.org/3/library/turtle.html#turtle-motion" rel="nofollow">it has special purpose me...
python|pycharm
1
10,823
52,593,482
Which point in time does time() measure, relative to execution of a statement it's in?
<p>The question is not about algorithms or fixing an error in code. I just want to make it clear how tracking time works. For example, there's line:</p> <pre><code>x = my_func(4, 2) * time() </code></pre> <p>The line run at 3.0 second and <code>my_func(4, 2)</code> takes 0.5 seconds to return the result.</p> <p>The ...
<p>Like most operators, the operands of the "*" operator are evaluated in left-to-right order. <code>my_func</code> will finish executing before <code>time</code> starts executing. You can test this empirically by using functions that print to stdout as a side-effect, for example:</p> <pre><code>&gt;&gt;&gt; def f(x):...
python|python-3.x
6
10,824
37,269,557
How to use different ip proxy on the same program in urllib2 ?
<p>The following code can use proxy as official documents</p> <pre><code>proxy_handler = urllib2.ProxyHandler({protocol : protocol + '://' + ip_proxies}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre> <p>But I want to use different proxy on different method</p> <p>Use <code...
<p>I have solved this problem. The key is use <code>requests</code> instead of <code>urllib2</code>, my bad.</p> <pre><code>import requests s = requests.Session() proxies = { 'http': 'http://127.0.0.1:8087', 'https': 'http://127.0.0.1:8087', } login_data = { 'email': 'youxiasssssssssssssssssss...
python|proxy|urllib2|urllib
1
10,825
37,391,378
Search list between specific index in Python
<p>I need to create a function that will search for a list-item between specific indexes. </p> <p>I want to have a start and stop index for the list, I want to find the position of the item in the list. </p> <p>For example:</p> <pre><code>def find(list, word, start=0, stop=-1): print("In function find()") f...
<p>Can't you simply add start? </p> <pre><code>def find(list, word, start=0, stop=-1): print("In function find()") for item in list: if item == word: return start + list[start:stop].index(word) </code></pre>
python|list|loops|search
2
10,826
37,144,913
Getting ValueError: The indices for endog and exog are not aligned
<p>I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:</p> <pre><code>y = y...
<p>Try converting <em>y</em> into a list before the <em>sm.Logit()</em> line.</p> <pre><code>y = list(y) </code></pre>
python-3.x|pandas|statsmodels
20
10,827
34,107,659
How can I get the last occurence of a text in a file that is automatically updated - python?
<p><strong>[PROBLEM]</strong></p> <p>In a File that refreshes automatically with new data, I want to get: - the number that corresponds to latest string occcurence. For instance, in the dummy example below above I want to fetch: - last occurence of <strong>stringZ</strong> and afterwards the number inside that text. ...
<pre><code>regex = re.compile(r'Manually launch test ([0-9]+) stringZ') while True: latestOccurrence = None with open(fileName) as tempFile: for line in tempFile: if "stringZ" in line: match = regex.match(line) if match: latestOccurrence = ...
python
0
10,828
7,143,088
How do you set up multiple multithreaded QWebViews in PyQt?
<p>I am trying to make an application in Python using PyQt that can fetch the generated content of a list of URLs and process the fetched source with the help of multiple threads. I need to run about ten QWebViews at once. As ridiculous as that might sound, when it comes to hundreds of URLs, using threaded QWebViews ge...
<p>There are multiple issues with your question and code:</p> <ul> <li>You are talking about <em>QWebFrame</em>, but are actually passing a <em>QWebView</em> to your worker(s). Since this is a <em>QWidget</em>, it belongs to the main (GUI) thread and should not be modified by other threads.</li> <li>One <em>QWebView<...
python|multithreading|qt|pyqt|qwebview
4
10,829
39,433,108
Find when integral of an interpolated function is equal to a specific value (python)
<p>I have arrays <code>t_array</code> and <code>dMdt_array</code> of x and y points. Let's call <code>M = trapz(dMdt_array, t_array)</code>. I want to find at what value of t the integral of dM/dt vs t is equal to a certain value -- say <code>0.05*M</code>. In python, is there a nice way to do this?</p> <p>I was think...
<p>One simple way is to use the CubicSpline class instead. Then it's <code>CubicSpline(x, y).antiderivative().solve(0.05*M)</code> or thereabouts.</p>
python|scipy
1
10,830
39,780,704
Hiding rows in QTableWidget if 1 of the column does not have any values
<p>I had wanted some opinions about a portion of code that I have written. My UI consists of a <code>QTableWidget</code> in which it has 2 columns, where one of the 2 columns are populated with <code>QComboBox</code>.</p> <p>For the first column, it will fill in the cells with the list of character rigs (full path) it...
<p>You can hide rows using <a href="http://doc.qt.io/qt-4.8/qtableview.html#setRowHidden" rel="nofollow">setRowHidden</a>. As for the rest of the code, I don't see much wrong with what you currently have, but FWIW I would write it something like this (completely untested, of course):</p> <pre><code>def populate_table_...
python|pyqt|maya|qtablewidget|qcombobox
2
10,831
39,541,446
import from a folder with dots in name - Python
<p>I have a python package which looks like the following:</p> <pre><code>package/ ├── __init__.py ├── PyMySQL-0.7.6-py2.7.egg ├── pymysql ├── PyMySQL-0.7.x.pth └── tests.py </code></pre> <p>The folder structure cannot be changed because it is from a third party library. </p> <p>The contents of the .pth file are <...
<p>The problem is that the module's .pth file is not being used. Amazon's build instructions for Lambda have you install your dependencies into the same root directory as your Lambda function file. This directory is not configured as a "site directory" (e.g. like <code>lib/pythonX.Y/site-packages/</code> in a virtual...
python|python-2.7|aws-lambda|pymysql
4
10,832
39,555,127
Python deduplicate records - dedupe
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p> <pre><code>data_d = {} for row in data: clean_row = [(k, preProcess(v)) for (k, v) in row.items()] row_id = int(row['id']) ...
<p>It appears that <code>df.to_dict(orient='index')</code> will produce the representation you are looking for:</p> <pre><code>import pandas data = [[1, 2, 3], [4, 5, 6]] columns = ['a', 'b', 'c'] df = pandas.DataFrame(data, columns=columns) df.to_dict(orient='index') </code></pre> <p>results in</p> <pre><code>{0: {...
python|pandas|dictionary|record-linkage|python-dedupe
3
10,833
16,446,151
Move from google app engine to virtual machine
<p>I had as an assignement to create a website. I did it on google app engine. I use jinja2 and google database.</p> <p>Now, my proffesor ask to move it from google app engine to a virtual machine. Probably, I have to rewrite the part of google database with a mySQL for example.</p> <p>How exactly I setup the librari...
<p>The simplest method would be to install the AppEngine SDK on the virtual machine and run your AppEngine app on the local dev server. See:</p> <p><a href="https://developers.google.com/appengine/docs/python/tools/devserver" rel="nofollow">https://developers.google.com/appengine/docs/python/tools/devserver</a></p>
python|google-app-engine|virtual-machine
2
10,834
16,186,583
Retrieving .txt file contents in Google AppEngine
<p>I'm trying to Upload a text file using :</p> <pre><code>&lt;input type="file" name="file"&gt; </code></pre> <p>and this file is retrieved using:</p> <pre><code>class UploadHandler(webapp2.RequestHandler): def post(self): file=self.request.POST['file'] self.response.headers['Content-Type'] = "text/plain"...
<p>The following seems to work, so there must be something else that is happening (<a href="http://form.gae-init.appspot.com/" rel="nofollow">live example</a>):</p> <pre><code>import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = "text/html" self.re...
python|google-app-engine|text|blobstore
4
10,835
38,707,017
How to add more than one feature into the same cell using the grid method, Python Tkinter
<p>There might be question like this, but I can't find it. I want to have more than one entry or label etc. in the same cell without them overlapping. I hope you know what I mean. Any ideas?</p>
<p>Put as many items as you want in a frame, and then put the frame in the grid cell.</p> <h2>Example</h2> <pre><code>import tkinter as tk root = tk.Tk() # some random widgets, for illustrative purposes l0 = tk.Label(root, text="Cell 0,0", borderwidth=1, relief="solid") l1 = tk.Label(root, text="Cell 0,1", borderwi...
python|tkinter|grid
0
10,836
40,708,668
python: the speed of sum
<p>I know the fastest way to sum a list of number is use the built in function <code>sum</code>. Using a <code>for</code> loop could be a slower way to do the sum than using <code>reduce</code>. However when I try it, it is not true. Can someone explain this result?</p> <pre><code>import time, random, operator sample...
<p>Let me show you how to do this more systematically. First, you should use the <code>timeit</code> module for benchmarking. It's a little awkward to use correctly but it is significantly more accurate. Second, make absolutely certain you are not doing any work <em>other</em> than the work you care about benchmarki...
python|performance
5
10,837
32,272,354
regex sbustitute only specific hit sequence
<p>i have multiple string variations: <code>"gr_shoulder_r_tmp"</code>, <code>"r_shoulder_tmp"</code> i need to substitute:</p> <p><strong>"r_"</strong> to <strong>l_</strong>, here:</p> <pre><code>"gr_shoulder_r_tmp" &gt; "gr_shoulder_l_tmp" "r_shoulder_tmp" &gt; "l_shoulder_tmp" </code></pre> <p>in other words i n...
<p>A simple regex will do this job.</p> <pre><code>re.sub(r'(?&lt;![a-zA-Z])r_', 'l_', s) </code></pre> <p><code>(?&lt;![a-zA-Z])</code> negative lookbehind which asserts that the match would be preceeded by any but not a letter.</p> <p><strong>Example:</strong></p> <pre><code>&gt;&gt;&gt; re.sub(r'(?&lt;![a-zA-Z])...
python|regex|split|substitution
2
10,838
32,507,408
Scrapy response is a different language from request and resposne url
<p>I'm trying to scrape search results from this page</p> <p><a href="http://eur-lex.europa.eu/search.html?qid=1437402891621&amp;DB_TYPE_OF_ACT=advGeneral&amp;CASE_LAW_SUMMARY=false&amp;DTS_DOM=EU_LAW&amp;typeOfActStatus=ADV_GENERAL&amp;type=advanced&amp;lang=en&amp;SUBDOM_INIT=EU_CASE_LAW&amp;DTS_SUBDOM=EU_CASE_LAW" ...
<p>In the upper right corner of the webpage there's a drop down field to choose the language of the website. Selecting <code>french</code> there will add another parameter to the url: <code>&amp;locale=fr</code>.</p> <p>So - add that parameter to your <code>start_url</code>.</p>
python|web-crawler|scrapy
1
10,839
54,789,614
SQLAlchemy and SQL Server Datetime field overflow
<p>I'm using SQLAlchemy to connect to a SQL Server database.</p> <p>I'm trying to insert an object into a table from my python script and it's failing. I'm receiving the error:</p> <pre><code>(pyodbc.DataError) ('22008', '[22008] [Microsoft][ODBC SQL Server Driver]Datetime field overflow (0) (SQLExecDirectW)') </cod...
<blockquote> <p>The corresponding date time field in the SQL Server table is of type datetime2.</p> </blockquote> <p>Can it be that SQL Alchemy still builds that value as type DATETIME without taking into account corresponding type in a destination table?</p> <p><a href="https://docs.microsoft.com/en-us/sql/t-sql...
python|sql-server|sqlalchemy
5
10,840
28,194,593
What is the correct way to populate fields from database or session data?
<p>I'm storing some variables in the session when the user logs in, to use later to populate a field.</p> <pre><code>from flask_wtf import Form from wtforms import SelectField from flask import session class InstitutionForm(Form): city = session['city'] city_tuples = [(x, x) for x in city] organisation...
<p>Code in a class definition is executed at import time, not when the class is instantiated. You need to move the access to <code>session</code> to the <code>__init__</code> method so that it will be accessed when creating a form in a view function.</p> <pre><code>class Institution(Form): organization = SelectFie...
python|session|flask|wtforms
7
10,841
28,277,137
How to convert datatype:object to float64 in python?
<p>I am going around in circles and tried so many different ways so I guess my core understanding is wrong. I would be grateful for help in understanding my encoding/decoding issues.</p> <p>I import the dataframe from SQL and it seems that some datatypes:float64 are converted to Object. Thus, I cannot do any calculati...
<p>You can convert most of the columns by just calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html#pandas.DataFrame.convert_objects" rel="noreferrer"><code>convert_objects</code></a>:</p> <pre><code>In [36]: df = df.convert_objects(convert_numeric=True) df.dtyp...
python|pandas
43
10,842
44,230,678
How to change one character of string variable?
<p>Can one character of a string variable be changed?</p> <p>For instance, if # "o" is in position 1, can I change position 1 to something else? Basically, I'm asking for user to input a word via</p> <pre><code>word = input("Please enter your favorite word: ") </code></pre> <p>Then I'm taking that word variable, an...
<p>The string variables are immutable. You cannot change the word after you define them. If you want to change the letters I suggest you convert the word into a list of characters and then perform whatever operation you want to perform.</p> <p>Please refer to <a href="https://stackoverflow.com/questions/5387208/conver...
python|string|variables
0
10,843
44,232,120
python mapreduce - Skipping the first line of the .csv in mapper
<p>I am trying to do mapreduce in python and my csv file looks like below,</p> <pre><code> trip_id taxi_id pickup_time dropoff_time ... total 0 20117 2455.0 2013-05-05 09:45:00 50.44 1 44691 1779.0 2013-06-24 11:30:00 66.78 </code></pre> <p>and my codes are,</p> <pre><code>import pan...
<p>Not sure exactly what content 'line' has. A simple answer to your problem is to just try/except the float.</p> <pre><code>def mapper(self, _, line): datarow = line.replace(' ','').replace('N/A','').split(',') trip_id = datarow[0] total = datarow[14] try: total = np.float(total) except Ty...
python|csv|hadoop|mapreduce|mrjob
2
10,844
33,000,104
decommission host through cm_api (gracefully)
<p>I am trying to decommission host from cloudera manager (gracefully) using cm_api. I tried following but which is deleting the role and abruptly stopping the YARN containers running on it </p> <pre><code>#!/usr/bin/env python2.6 my_cluster = "cluster" cloudera_manager = "1.2.3.4" cloudera_username = "admin" cloudera...
<p>This is because you are only deleting the role in your code. To decommission the host, you need to use the <strong>hosts_decommission</strong> function of the <strong>ClouderaManager</strong> class.</p> <p>Search for the ClouderaManager class and hosts_decommission function in this link <a href="http://cloudera.git...
python|api|automation|cloudera|cloudera-manager
1
10,845
13,981,419
searching substring across a large list
<p>I am trying to find all forms of insertions between 2 strings. So I have a list of 14 million strings and then I have to check for each string what possible insertions can transform one string to another (basically counting insertion frequencies). Say x is one string and y is another string where x is a sub-string o...
<p>Instead of comparing each word to each other (quadratic runtime), take each proper substring of each word (linear runtime, assuming word length is bounded) and check if it is in the set of words (looking up elements of a <code>set</code> is constant time).</p> <p>This ran in less than 2 seconds on my laptop (for 46...
python|full-text-search|substring
1
10,846
27,387,675
Img paths not working in Django
<p><img src="https://i.stack.imgur.com/mXAkt.png" alt="enter image description here"></p> <p>I have a django project with static files as in the screenshot. I notice that a number of the images are not loading . Taking for example ipads.png. The HTML in the index view is:</p> <pre><code> &lt;div class="col...
<p>As the <code>templates</code> and <code>statics</code> are in same directory you need to add root directory at leading of your path :</p> <pre><code>src="../static/img/ipad.png" </code></pre>
python|django
1
10,847
27,163,724
django migrate has error: Specify a USING expression to perform the conversion
<p>I change my model field from Charfiled() to GenericIPAddressField()</p> <pre><code>ip = models.GenericIPAddressField() </code></pre> <p>and use django 1.7 migrate </p> <pre><code>./manage.py makemigrations core ./manage.py migrate </code></pre> <p>But there is error: </p> <pre><code>return self.cursor.execute(s...
<p>one quick fix will be to drop and create the field:</p> <ol> <li>delete the migration what is changing the field type.</li> <li>delete/comment the field <code>ip</code></li> <li>make migrations</li> <li>get back/uncomment the field <code>ip</code> with the new field type</li> <li>make migrations</li> <li>migrate</l...
python|django|postgresql
9
10,848
27,245,022
I want to know how capture RAW data packets in a Queue using Iptables or Nftables
<p>My doubt is I want to captire raw data packets, so that I can use them to built firewall. The following script prints a short description of each packet before accepting it. from netfilterqueue import NetfilterQueue</p> <pre><code>def print_and_accept(pkt): print pkt pkt.accept() nfqueue = NetfilterQue...
<p>According to your comment, by raw packet you mean layer 2. Iptables works at layer 3, you need to use ebtables instead.</p>
python-2.7|iptables|packet|scapy|netfilter
0
10,849
8,002,534
Creating a remote project with PyDev
<p>I'm new to Eclipse/PyDev and have what's probably a really basic question. I want to use it to edit and debug python files on a remote system. I am able to do this using RSE and pydevd, but what I'm doing doesn't really seem integrated with the IDE. That is, I can go to the RSE perspective and edit the files. I ...
<p>OK, it turns out to be not only simple but rather obvious once you find it. From the RSE perspective, right-click the folder containing your source files and select "Create Remote Project." This seems to work fairly well, but I'm still having one problem: It seems the debugger wants a local copy of the file I am de...
python|pydev
6
10,850
41,993,379
Saved txt file weird and now cannot import to Excel
<p>My python code was to append one row at a time of multi-column data into a text file, which i then needed to pull apart column-by-column.. not row by row. It looks like a normal text document with elements split by spaces, meaning:</p> <pre><code>0.00000 107.07925 25.34190 -1.22487 0.63152 1.00000 88.51627 6.54154 ...
<p>As for opening it in Excel since it is split by spaces you might try changing the text to columns option setting to be space instead of the default tab. This option is listed under the data tab(Excel 2013). As far as I know the easiest way to do this would be to open a blank excel sheet type anything into A1 and the...
excel|python-3.x|text-files|notepad
0
10,851
47,355,127
Getting TypeError: While Creating TFRecords for Image input
<p>Creating TFrecords for Image input: as below</p> <pre><code> char_ids_padded, char_ids_unpadded = encode_utf8_string(text) print("char_ids_padded:"+str(char_ids_padded)) print("char_ids_unpadded:"+str(char_ids_unpadded)) tf_example = tf.train.Example(features=tf.train.Features(feature...
<p>You're already passing a list to <code>tf.train.Int64List</code>, so you don't need to create a new list containing the argument of <code>_int64_feature</code>. That is, you should try changing</p> <pre><code>tf.train.Int64List(value=[value]) </code></pre> <p>to</p> <pre><code>tf.train.Int64List(value=value) </co...
tensorflow|tfrecord
1
10,852
46,752,575
gRPC/proto Google cloud client libraries vs GAPIC Google cloud client libraries
<p>I've mostly found working with google's client libraries easy to work with, intuitive, and well suited to idiomatic python, with the notable exception of auth (there is a special place in hell for whoever came up with the oAuth dance) Although in the past, most of my work was on Gsuite, I'm tinkering with the googl...
<p>You really do not ever want or need to install a library with <code>gapic-</code>, <code>proto-</code>, or <code>grpc-</code> at the front of it. At one point, the libraries that you actually want were using these as dependencies. (We have moved away from that behavior, but for historical reasons we are stuck with t...
python|google-api|google-cloud-platform|grpc
2
10,853
46,695,522
Proper use of the * operator in a oneline if statement python
<p>I'd like to know if its possible to use the * operator in a oneline if to achieve the following functionality:</p> <pre><code>if node['args'] != None: return_val = funct(*node['args']) else: return_val = funct() </code></pre> <p>I thought I could just say</p> <pre><code>return_val = funct(*node['args'] if...
<p>Yes, you need to provide an <em>empty sequence</em>, not <code>None</code>:</p> <pre><code>&gt;&gt;&gt; def f(*args): ... for arg in args: ... print(arg) ... &gt;&gt;&gt; x = None &gt;&gt;&gt; y = ('a','b') &gt;&gt;&gt; f(*(y if x is not None else ())) &gt;&gt;&gt; x = object() &gt;&gt;&gt; f(*(y if x i...
python|python-3.x
4
10,854
46,796,943
Converting a row of a pandas dataframe into a dataframe itself (instead of a series)?
<p>I have a df that I'm iterating over, like so</p> <pre><code>for _, row in df.iterrows(): process(row) </code></pre> <p>The function <em>process</em> takes the argument and itself does an iterrows() on it. It does this because it is normally passed a dataframe. However, I'd like to pass a single row to <em>p...
<p>You can transpose the output of <code>to_frame</code>:</p> <pre><code>s.to_frame().T </code></pre> <p>That said, this seems a strange thing to require, a refactor of <code>process</code> may be a good idea. But perhaps you can get away with chunkifying into smaller dataframes:</p> <pre><code>for chunk in np.array...
python|pandas
4
10,855
46,779,046
Correct Type annotation for __init__
<p>What is the correct type annotation for a <code>__init__</code> function in python?</p> <pre><code>class MyClass: ... </code></pre> <p>Which of the following would make more sense?</p> <pre><code>def __init__(self): # type: (None) -&gt; None def __init__(self): # type: (MyClass) -&gt; MyClass def __...
<p><code>self</code> should be omitted from the annotation when it is given as a comment, and <code>__init__()</code> should be marked as <code>-&gt; None</code>. This is all specified explicitly in <a href="https://www.python.org/dev/peps/pep-0484/" rel="noreferrer">PEP-0484</a>.</p>
python|python-2.7|typing
99
10,856
37,965,198
Python Psycopg2 cursor.execute returning None
<p>Hello I'm working on a script in Python that will connect to a db retrieve some information and send emails. I'have a problem with queries done with Psycopg.</p> <p>I'would like to retrieve all the users where <code>created_at = nb_days</code>. My query work very good in navicat/pgadmin and I'have 53 records with t...
<p><a href="http://initd.org/psycopg/docs/cursor.html#cursor.execute"><code>cursor.execute</code></a> allways returns <code>None</code>. You need to <a href="http://initd.org/psycopg/docs/cursor.html#fetch"><code>fetch</code></a> the record set:</p> <pre><code>try: self.cursor.execute(sql,data) records = self....
python|postgresql|psycopg2
22
10,857
37,963,045
How can I convert currency symbol to code?
<p>I am trying to convert some price given in pounds and USD into EURO. Is there a Python package which can convert the symbol to code? Which can replace the following function call <code>convert_sym_to_code(currency_symbol)</code>?</p> <pre><code>from forex_python.converter import CurrencyRates curconv = CurrencyRate...
<p>A naive approach would be to just use a dictionary:</p> <pre><code>CURRENCY_MAPPING = [ '$': 'USD', '£': 'GBP', ] def convert_sym_to_code(currency_symbol): try: CURRENCY_MAPPING[currency_symbol.strip()] except KeyError: raise ValueError('Unknown symbol "%s" % currency_symbol) </code...
python|currency
3
10,858
29,870,629
pip install test dependencies for tox from setup.py
<p>I made my project with <code>setuptools</code> and I want to test it with <code>tox</code>. I listed dependencies in a variable and added to <code>setup()</code> parameter (<code>tests_require</code> and <code>extras_require</code>). My project needs to install all of the dependencies listed in <code>tests_require<...
<p>I've achieved this by committing a slight abuse of <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies" rel="noreferrer">extra requirements</a>. You were almost there trying the extras syntax, just that <code>tests_require</code> deps ar...
python|pip|setuptools|easy-install|tox
59
10,859
27,652,498
Installing an extension from conf.py
<p>I try to build the docs, and use a <a href="http://pythonhosted.org/sphinxjp.themes.basicstrap/" rel="nofollow">custom sphinx extension</a>, but this extension isn't installed by default - so I provide it via <code>conf.py</code>, using this:</p> <pre><code>try: import sphinxjp.themes except ImportError: fr...
<p>When the extension is installed, it creates a <code>.pth</code> file, which would normally be processed during initialization when <a href="https://docs.python.org/2/library/site.html" rel="nofollow">site.py</a> is imported. Amongst other things, the <code>.pth</code> file specifies additional items that must be add...
python|python-sphinx|importerror|easy-install
1
10,860
27,603,067
Python interprocess communictation, huge data
<p>What is the best way to exchange huge amount of data between processes in python. I am working on the image processing algorithms and I would like to send image frames between processes.</p>
<p>For interprocess communication between Python processes you should use the asynchronous message queuing communication protocol. </p> <p>Python has great support for a variety of systems implementing this as <a href="http://zeromq.org/bindings:python" rel="nofollow">ZeroMQ</a> and <a href="http://www.rabbitmq.com/tu...
python|image-processing|ipc
1
10,861
43,384,000
Installing Tensorflow on windows Anaconda2
<p>I am trying to install tensorflow on Ananconda2 in windows 64 bit. I've tried the following steps:</p> <pre><code>conda create --name tensorflow python=3.5 activate tensorflow conda install -c conda-forge tensorflow </code></pre> <p>Tensorflow got installed successfully and i could check that in Anaconda promp...
<p>Solution:- (Note:- This will surely work for all!!)</p> <p>Step 1:- conda search python</p> <p>Step 2:- conda install python=3.5.2</p> <p>Step 3:- pip install tensorflow</p> <p>Step 4:- import tensorflow as tf</p> <p>Done!!</p>
python|windows|tensorflow|anaconda
1
10,862
43,361,791
Converting list of 2D Panda's DataFrame to 3D DataFrame
<p>I am trying to create a Pandas DataFrame that holds label values to a 2D DataFrame. This is what I have done so far:</p> <p>I am reading csv files using <code>pd.read_csv</code> and appending them to list, for the purpose of this question let's consider the following code:</p> <pre><code>import numpy as np import ...
<p>If select with not unique items, get another <code>Panel</code>:</p> <pre><code>np.random.seed(10) labels = [1,1,1,2,2,2] samples = np.random.randn(6, 5, 4) p1 = pd.Panel(samples, items=map(str, labels)) print (p1) &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 6 (items) x 5 (major_axis) x 4 (minor_axis) Items...
python|pandas|dataframe
2
10,863
4,522,767
Creating python c module independent of python version?
<p>In Tcl, there is a concept of stubs, where you can have a C extension that works with any compatible version of Tcl. Is there a comparable concept for Python?</p> <p>I'd like to distribute a binary module that would run on Ubuntu 8.04 (python 2.5), Ubuntu 10.04 (python 2.6), and Centos 5 (python 2.4). I'd like to...
<p>If you distribute your module as source, it can be compiled as necessary.</p> <p>This problem occurs a lot with Windows, for which modules are normally distributed as binaries. <a href="http://www.python.org/dev/peps/pep-0384/" rel="nofollow">PEP 384</a> proposes a solution (a limited interface which is guaranteed ...
python|module|tcl
4
10,864
48,281,851
Pandas: how to select only the duplicate rows that have the same key but different values in a column
<p>I have a dataframe with columns<code>['join key', 'code', 'A', 'B', 'C', 'D']</code>.</p> <p>The <code>join key</code> is a long string of characters while <code>code</code> can either be equal to 521, 539 or a bunch of others numbers.</p> <p>There can be rows with the same <code>join key</code>.</p> <p>I want to...
<p>I believe you need compare <code>set</code>s and filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>mask = exp_csv.groupby('join key')['code'].transform(lambda x: set(x) == set([521, 539])) interi...
python|pandas|pandas-groupby
2
10,865
73,523,942
Gekko - repeat cycle and oxygen step for wastewater modeling
<p>I am moving some wastewater metabolic models across to Python, specifically some on polyphosphate accumulating organisms (PAOs). I have managed to move the model into Python and solving using Gekko which is great! (Still a few tweaks in the equations to be implemented).</p> <p><a href="https://i.stack.imgur.com/n3Fx...
<p>Every time <code>m.solve()</code> is called, the solution is time-shifted to the left by <code>m.options.TIME_SHIFT</code> (default=1). The new initial conditions are taken from the next time step and the problem is solved again. Change <code>m.options.TIME_SHIFT=3</code> to make the 3rd time point the initial condi...
python|modeling|gekko
0
10,866
73,610,416
Creating a Caesar cypher; I do not understand the origin of the indentation issue
<p>I am new to python and currently working on a project that requires me to create a caesar cipher. I have defined a function called caesar as shown. However, I keep getting the error &quot;unexpected indent&quot; after the <strong>else</strong> statement. What I am I doing wrong? '''</p> <pre><code>alphabet = ['a', '...
<p>'''You have done, <i><strong>text_direction == &quot;decode&quot;</strong></i> is wrong because &quot;==&quot; is comparison which can be only be used with <strong>if...else condition</strong>, but you used it wrongly. you can check the output for the confirmation of this program. Also, <strong>I have corrected id...
python|python-3.x|list
0
10,867
51,245,547
Python3 Decimal Point Precision
<p>I am writing a graphing calculator in Python 3</p> <p>However, this code here is giving me problems.</p> <pre><code>def domainGen(start,end,step): #generates a list of points for t, x, or theta to be equal to. #Acts like a floating point equivalent to "range" except it generates a whole list object, not ju...
<p>If someone enters a float or int literal you could do something like this to it:</p> <pre><code>def get_float(s): if '.' in s: return float(s), len(s) - s.index('.') - 1 else: return float(s), 0 </code></pre> <p>This function returns a tuple consisting of the corresponding float and the num...
python|python-3.x|floating-point|precision
1
10,868
17,174,559
How to track down a Python/Django/uwsgi/nginx timeout
<p>I've got the following setup...</p> <ul> <li>nginx listens on public port 80 and proxies requests to <code>localhost:10000</code></li> <li>uwsgi running django site 1 listens on localhost:10000 and generates some webpages. It also makes some calls to a webservice on <code>localhost:10001</code></li> <li>uwsgi runni...
<p>You have a pretty "strange" setup:</p> <p>nginx -> uwsgi http router -> uwsgi</p> <p>instead of</p> <p>nginx -> uwsgi</p> <p>maybe you have some good reason for it, but in such a case you need to set the timeout between uwsgi http router and uwsgi via --http-timeout 1800</p> <p>If the http router is not you wan...
python|django|nginx|timeout|uwsgi
2
10,869
53,157,978
coverting roi pooling in pytorch to nn layer
<p>I have a an mlmodel using ROI pooling for which I am using this (adapted from <a href="https://github.com/longcw/faster_rcnn_pytorch/blob/master/faster_rcnn/roi_pooling/modules/roi_pool_py.py" rel="nofollow noreferrer">here</a>) (non NN layer version)</p> <pre><code>def forward(self, features, rois): batc...
<p>Found the issue - The rois after multiplication with spatial scale were being rounded down and had to call round function before calling long like so </p> <pre><code>rois = rois.data.float() num_rois = rois.size(0) rois[:,1:].mul_(self.spatial_scale) rois = rois.round().long() ## Check this here !! </code></pre> ...
python|machine-learning|neural-network|pytorch
1
10,870
71,467,221
How do I get an output of lines that comes as a result merging lines in 2 files line by line, then save the output in a third file? (Python 3)
<p>I have to take lines from 2 files, put them side by side and write them into a new text file.</p> <p>File 1 &quot;pythonStatements.txt&quot;:</p> <pre><code> enter code hereprint(&quot;Hello World&quot;) # print statement x = x + 1 #Assignment statement for i in range(1,n): #for loop with ra...
<p>The problem was that you open file for rewriting every iteration in the loop.</p> <pre><code>with open(&quot;machineCode.txt&quot;) as mct: with open(&quot;pythonStatements.txt&quot;) as pst: with open(&quot;NewFile&quot;, &quot;w&quot;) as new: for line_x, line_y in zip(mct, pst): ...
python-3.x
0
10,871
61,653,726
Out of memory error while storing multiple arrays together
<p>I am trying to store pixel data of 30227(1024 x 1024) images together by concatenating them in a list to form my training data. But I am receiving Out of memory error while doing so in my Jupyter notebook. Below are the lines of code that I have used.</p> <pre><code> train_data = [] mm_scaler = MinMaxScaler() fo...
<p>Out of memory error comes when there is a limit for a system you can have a look at this <a href="https://stackoverflow.com/questions/5537618/memory-errors-and-list-limits">here</a></p> <p>For storing data you can take help from this <a href="https://pyscience.wordpress.com/2014/09/08/dicom-in-python-importing-medi...
python|pandas|image-processing|jupyter-notebook|numpy-ndarray
0
10,872
60,580,886
How to Access Row in Pandas DataFrame With Boolean-Typed MultiIndex ("IndexError: Item wrong length 2 instead of 3.")
<p>Consider a Pandas DataFrame with a MultiIndex with all boolean-typed levels (example below). Trying to access specific rows of such a DataFrame by using a boolean label leads to an error:</p> <pre><code>df = pd.DataFrame([[False, False, 1], [False, True, 2], [True, False, 3]]...
<p>You can slice using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IndexSlice.html" rel="nofollow noreferrer"><code>pd.IndexSlice</code></a>.</p> <pre><code>&gt;&gt;&gt; df.loc[pd.IndexSlice[False, False]] C 1 Name: (False, False), dtype: int64 </code></pre>
python|pandas
1
10,873
60,429,143
Rotation and turning of marker on right end of line
<p>Having a line in <code>Matplotlib</code> with assigning marker-end. How can I rotate and turn marker symbol at one end.</p> <p>Current line with marker.</p> <p><a href="https://i.stack.imgur.com/fNq41.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fNq41.png" alt="enter image description here"><...
<p>You always could plot line and marker separately:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt from matplotlib.lines import Line2D fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') line = ((0.1, 0.5, 0.9), (0.5, 0.7, 0.5)) linea = Line2D(*line, linewidth=10, color=...
python|python-3.x|matplotlib|markers
1
10,874
68,917,479
python use different decorator parameters dependent on a variable value
<p>Here is the sample code like:</p> <pre><code> @deviceCountAtLeast(1) if NO_DOUBLE: @dtypes(torch.float) else: @dtypes(torch.float, torch.double) def test_requires_grad_factory(self, devices, dtype): fns = [torch.ones_like, torch.testing.randn_like] x = torch.randn(2, 3, dtype=dtype, de...
<p>From Python3.9 you can use any expression as a decorator, see <a href="https://www.python.org/dev/peps/pep-0614/" rel="nofollow noreferrer">PEP 614</a></p> <p>Something like the following should work where the decorator used is the result of a ternary expression</p> <pre><code>@(dtypes(torch.float) if NO_DOUBLE else...
python|python-decorators
4
10,875
63,195,776
Interrupting Python blocks with exception catchers
<p>This appeared to be a very obvious yet annoying issue. Consider the code block here -</p> <pre class="lang-py prettyprint-override"><code>for i in tqdm.notebook.tqdm(range(int(3*len(structures)/4))): try: is_mal=np.array([1.]) if 'Malware' in structure_info[i] else np.array([0.]) target=parse_Str...
<p>You can raise a new exception inside the <code>except</code> block to pass it onwards:</p> <pre class="lang-py prettyprint-override"><code>try: &lt;code&gt; except: raise Exception </code></pre> <p>If you want to reraise the same exception that was caught:</p> <pre class="lang-py prettyprint-override"><code>try:...
python|python-3.x|try-catch|execution|interruption
1
10,876
62,124,320
JSON array convert to Python array
<p>[{ data: "31/05/2010 19:39:00", empresa: { codigo: 1 }, descricao: "teste", tipoEvento: "RHYTHM VARIATION" }, { data: "31/05/2010 18:15:00", empresa: { codigo: 1 }, descricao: "teste ", tipoEvento: "RHYTHM VARIATION" }]</p>
<p>This is an overly simple question, and I would encourage you to read the documentation in the future, but nonetheless:</p> <pre class="lang-py prettyprint-override"><code>import json your_str_data = r''' [{"data":"31/05/2010 19:39:00","empresa":{"codigo":1},"descricao":"teste","tipoEvento":"RHYTHM VARIATION"},{"dat...
python
1
10,877
62,339,013
Best way to output prediction result for a test set from a model with 1 output (binary classification)
<p>This seems simple, but I'm looking for the best way to output the prediction results for a model with 1 output (binary classification model). My labels are 0 and 1 in this example. Now I can just say if model output > 0.5 label is 1. But I'm sort of guessing this is correct. I am hence wondering if there is a better...
<pre><code>test_data = torch.Tensor(test) raw_preds = logreg_clf(test_data) preds = (raw_preds &gt; 0.5).long() </code></pre> <p>To get the predictions for all test data at once, we first convert the test data to a tensor, then we can make a forward pass with that tensor. The raw predictions are something like <code>...
python|machine-learning|pytorch|logistic-regression
1
10,878
59,016,693
pandas to_dict with python native datetime type and not timestamp
<p>I have a <code>pandas</code> <code>DataFrame</code> <code>df</code> that contains <code>Timesatamp</code> columns.</p> <p>I wish to create an iterator of rows (either via the <code>iter..</code> methods or via <code>to_dict</code>) from <code>df</code> where the <code>Timesatamp</code> values are python <code>date...
<p>You can try</p> <pre><code>df[col] = pd.Series(df[col].dt.to_pydatetime(), dtype = object) </code></pre> <p>instead of </p> <pre><code>df[col] = df[col].dt.to_pydatetime() </code></pre>
python|pandas|timestamp|python-datetime
2
10,879
59,820,052
Why is my API note returning all items from the model?
<p>I'm trying to return all items from the <code>User</code> model when a certain API endpoint is navigated to.</p> <p>Here is my Flask route:</p> <pre><code>@app.route('/user/all', methods=['GET']) def get_all_users(): users = User.query.all() output = [] for user in users: output = {'id': user....
<p>you are updating in the same dict</p> <pre><code>@app.route('/user/all', methods=['GET']) def get_all_users(): users = User.query.all() output = [] for user in users: output.append({'id': user.id, 'username': user.username, 'email':user.email}) return jsonify(output) </code></pre>
python|flask|flask-sqlalchemy
0
10,880
59,695,319
Server side previous page call not working
<p>I configured the server-side processing of datatables. On the server side I use <code>python3</code> and <code>mongodb</code>. </p> <p>I think my paging logic is good as you can see from the code:</p> <p><strong>PYTHON</strong>:</p> <pre><code>@bp.route('/_ajax_products', methods=['GET', 'POST']) @login_required ...
<p>I finally found a solution. The error came from a misunderstanding of what the draw option was doing. </p> <p>Indeed I thought that the value of draw corresponded to the page to be displayed, which is not the case. </p> <p>Here is the new version of the code in case it can help someone:</p> <pre><code>@bp.route('...
python-3.x|mongodb|datatables
0
10,881
25,355,006
FIltering more then one string with list comprehension
<p>I am working with a list containing urls and wanting to filter out extentions like .jpg, jpeg and .png. </p> <p>I tried to use list comprehension: [elem for elem in li if elem != ".jpg"] but this would only filter one string.</p> <p>Is there a way to solve this?</p> <p>thanks.</p>
<p>Instead of checking the equality of the element to a single string, check if the element is present in a set, where each member of the set is a string you want to match against:</p> <pre><code>blacklist = set(['.jpg', '.jpeg', '.png']) filtered = [elem for elem in li if elem not in blacklist] </code></pre> <p>Howe...
python|list|filter|list-comprehension
2
10,882
30,745,361
If/ Elses statement not executing properly
<p>I've altered the if/else statements several times and either <strong>only</strong> the if statement will be executed even if it's not true or <strong>only</strong> the else statement will be executed even if it's not true.</p> <pre><code>def interview(): """ NoneType -&gt; NoneType Interview the user. """ name = in...
<p>I can see an issue right away</p> <p><code>if str(unit == 'imperial'):</code> should be <code>if str(unit) == 'imperial':</code></p>
python-3.x|if-statement
2
10,883
50,778,174
Pull headers from a list and create a DataFrame with headers side-by-side to list elements
<p>After scraping a website, I ended up with a list which looks like this:</p> <pre><code>data = ['\xa0header1', 'element1', 'element2', 'element3', '\xa0header2', 'element4', 'element5'] </code></pre> <p>and so on.</p> <p>I want to create a panda dataframe with the data I scraped that looks like this:</p> <pre><co...
<h3>itertools groupby + repeat + chain</h3> <p>This is one solution using the <a href="https://docs.python.org/3/library/itertools.html#module-itertools" rel="nofollow noreferrer"><code>itertools</code></a> module. In essence these are the only operations we need to undertake:</p> <ol> <li><strong>Group</strong> item...
python|list|pandas|dataframe
2
10,884
45,094,041
Matrix multiplication with tf.sparse_matmul fails with SparseTensor
<p>Why does this not work:</p> <pre><code>pl_input = tf.sparse_placeholder('float32',shape=[None,30]) W = tf.Variable(tf.random_normal(shape=[30,1]), dtype='float32') layer1a = tf.sparse_matmul(pl_input, weights, a_is_sparse=True, b_is_sparse=False) </code></pre> <p>The error message is</p> <p><code>TypeError: Faile...
<h1>TL;DR</h1> <p>Use <code>tf.sparse_tensor_dense_matmul</code> in place of <code>tf.sparse_matmul</code>; look at the <a href="https://www.tensorflow.org/api_docs/python/tf/sparse_tensor_dense_matmul" rel="nofollow noreferrer">documentation</a> for an alternative using <code>tf.nn.embedding_lookup_sparse</code>.</p>...
python|tensorflow
3
10,885
53,930,192
AnsibleModule object is not callable error
<p>My playbook is as follows </p> <pre><code>--- - hosts: nodes become: yes tasks: - name: Run Shell Script to get IPs with 4xx and 5xx errors script: /home/ubuntu/ips.sh args: chdir: /home/ubuntu register: ips - set_fact: iperrors: "{{ groups.nodes | map('extract', hostvars, 'ips') ...
<p>Check the "module_stderr" key in the output. Near the end it says "'AnsibleModule' object is not callable\n"</p> <p>I'm not super familiar with custom ansible modules, but it looks like the way to write them has changed, check the new docs here: <a href="https://docs.ansible.com/ansible/latest/dev_guide/developing_...
python|python-3.x|ansible|ansible-inventory
0
10,886
23,729,636
Extracting text between anchor tag in beautifulsoup Python?
<p>I am trying to extract the name of the movies listed on this fandango page.</p> <pre><code>names_tag = soup.findAll('a', {'class': 'dark showtimes-movie-title'}) </code></pre> <p>This is the anchor class the names are withheld in. The issue is, when I run the code, the output is:</p> <pre><code>&lt;a class="dark ...
<p>Use the <code>text</code> property:</p> <pre><code>names_tag = soup.findAll('a', {'class': 'dark showtimes-movie-title'}) names = [name_tag.text for name_tag in names_tag] </code></pre>
python|beautifulsoup
0
10,887
29,385,156
invoking onclick event with beautifulsoup python
<p>I am trying to fetch the links to all accomodations in Cyprus from this website: <a href="http://www.zoover.nl/cyprus" rel="noreferrer">http://www.zoover.nl/cyprus</a></p> <p>So far I can retrieve the first 15 which are already shown. So now I have to invoke the click on the "volgende"-link. However I don't know ho...
<p>While it might be tempting to try to do this using Beautifulsoup's <code>evaluateJavaScript</code> method, in the end Beautifulsoup is a <a href="https://stackoverflow.com/a/23679526/1711232">parser</a> rather than an interactive web browsing client.</p> <p>You should seriously consider solving this with selenium, ...
javascript|jquery|python|beautifulsoup|pyqt4
7
10,888
49,759,662
Deployed Discord bot (discord.py) to Heroku, turned on the Dyno and bot not responding to commands
<p>I've deployed my Discord bot (Discord.py) to Heroku successfully with the build working, I switched on the Dyno and it said the bot has come online and shows as online on Discord's member list on the server. But when I type commands (such as '?help'), the bot doesn't respond at all. Any help would be appreciated, pl...
<p><strong>SOLVED: After another HOUR of trying many things, I removed my .gitignore and renamed my main.py to run.py. I changed the discord.py version in requirements.txt to what Heroku upgraded it to and re-deployed the bot, and I think upgrading it fixed it, so, job done. I updated the Procfile with the name change ...
python|heroku|discord|discord.py
0
10,889
53,441,138
how can i run spesefic migration sector in django
<p>now im trying to migrate empty django project.</p> <p>when enter this command</p> <pre><code>python manage.py showmagrations </code></pre> <p>result is </p> <pre><code>admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_perm...
<p>it's simple you have only put the app name and the migration you want to migrate</p> <p>if you want to migrate the inital of the admin app:</p> <pre><code>$ python manage.py migrate admin 0001_initial </code></pre> <p>NOTE: it will unapply the later migrations</p>
python|django|python-3.x|migration
3
10,890
54,701,115
How to deal with duplicate "unique identifiers" in pandas
<p>I have two tables that both contain an identifier called account code, but the first table can contain multiple occurences of that account code and the other table only has one occurence. My tables originally come from excel so they look like this after putting them into a pandas dataframe</p> <p><strong>base_data<...
<p>This is a good question , you may need using <code>cumcount</code> create the <code>merge</code> helpkey first , this will make sure once the fee item been used , it will not used again.</p> <pre><code>base['helpkey']=base.groupby('AccountNumber').cumcount() fee['helpkey']=fee.groupby('AccountNumber').cumcount() yo...
python|pandas
3
10,891
36,677,321
Tags and element got printed when tried to get only text with web scraping in beatutifulsoap in python
<p>I am currently learning web scraping and I came across a problem in beautiful soap module. I ran the following code:</p> <pre><code>import requests, bs4 res = requests.get('http://www.weather.gov/') res.raise_for_status() soup = bs4.BeautifulSoup(res.text, "html.parser") comicElem = soup.find('#topnews p') print (...
<p>Use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>.get_text()</code></a> to get the inner text of an element:</p> <pre><code>comicElem.get_text() </code></pre> <p>Note that if there are multiple elements, you would need to call <code>get_text()</code> for every elem...
python|python-3.x|web-scraping|beautifulsoup
2
10,892
54,482,939
Pandas - Compare Columns and return False when they are not matching and also when one of the column says "Column not found"
<p>I am comparing two columns using Pandas.</p> <pre><code>Pre_Out_df[res_name] = Pre_Out_df[plain_col] == Pre_Out_df[b_col] </code></pre> <p>The above code returns false. </p> <p>But I want the code to return false when any one of the value between Plain_col and b_col says"Column Not Found".</p> <p>I want to retur...
<p>Use this condition instead, where it checks if <code>plain_col</code> and <code>res_name</code> are same <code>AND</code> if <code>res_name</code> is <code>Not Found</code>. Ideally we need to check if either of them are <code>Not Found</code> but since we have already checked if they are same or not, either one of ...
python|pandas
1
10,893
54,318,686
Is this a valid approach to sharing a function between Python classes?
<p>My goal is to use the same function from multiple classes in Python.</p> <p>I've seen discussion about mixins and inheritance etc but they all seem to come with caveats and cautions about doing things just right.</p> <p>So I wondered if I could just call another plain old function that lives outsides the classes. ...
<p>It's valid, but it's unnecessary to have the extra layer of wrapping. The mix-in approach is the simplest, but yes, it has some caveats (largely related to metaclasses), so if you want to avoid that, you can still set a method in multiple classes by just setting during the definition of each class. Keep the function...
django|python-3.x
4
10,894
47,583,894
Deep Learning with TensorFlow on Compute Engine VM
<p>I'm actualy new in Machine Learning, but this theme is vary interesting for me, so Im using TensorFlow to classify some images from MNIST datasets...I run this code on Compute Engine(VM) at Google Cloud, because my computer is to weak for this. And the code actualy run well, but the problam is that when I each time ...
<p>You can save a trained model in TensorFlow and then use it later by loading it; that way you only have to train your model once, and use it as many times as you want. To do that, you can follow the <a href="https://www.tensorflow.org/programmers_guide/saved_model#overview_of_saving_and_restoring_models" rel="nofollo...
tensorflow|deep-learning|google-compute-engine
1
10,895
40,402,301
ProgrammingError: can't adapt type 'stock.location' - Odoo v9
<p>I'm migrating an Odoo v8 module, which is used to upload .csv's into <code>stock.inventory</code> model.</p> <p>I've fixed a few things, but I still have some bugs on it, like this method:</p> <pre><code>@api.one def action_import(self): """Load Inventory data from the CSV file.""" ctx = self._context ...
<p>A little mistake, you're trying to pass the <code>stock.location</code> object you got directly from your search query instead of the id</p> <p>Change this line</p> <pre><code>if locat_lst: prod_location = locat_lst[0] </code></pre> <p>to</p> <pre><code>if locat_lst: prod_location = locat_lst[0].id </cod...
python|openerp|odoo-9
6
10,896
47,104,797
Indexing from unique values from a different column
<p>I have a dataframe with a bunch of columns and rows, and I want to get the data in one column based on the unique values in another column.</p> <pre><code> flag name 0 1 bob 1 2 larry 2 1 alice 3 1 mary 4 3 peter 5 4 rick </code></pre> <p>if a use</p> <pre><code>df['flag'].unique()...
<p>By using <code>drop_duplicates</code></p> <pre><code>df.drop_duplicates(['flag']) Out[1036]: flag name 0 1 bob 1 2 larry 4 3 peter 5 4 rick </code></pre>
python|pandas
2
10,897
46,873,911
Python OpenCV imwrite 0 bytes image depends on execution dir
<p>I have written a small script to convert a RGB image to grey. When I run the script in terminal form current dir (<code>python3 image.py</code>), it works perfectly fine.</p> <p>But when I rum it from a dir lower like <code>python3 proc/image.py</code> it creates a result image with 0 bytes size.</p> <p>here is th...
<p>You are opening the <code>image</code> that you want to work on with the following line:</p> <pre><code>img = cv2.imread(name, 0) </code></pre> <p>And since your <code>script</code> always calls the <code>function</code> with this line:</p> <pre><code>sw('schwarn.jpeg') </code></pre> <p>you are always trying to ...
python|opencv
1
10,898
64,603,485
google Drive api v3 file upload errors
<p>The google drive api on python is showing the following error. My file upload code is already mentioned on <a href="https://stackoverflow.com/questions/64587769/google-drive-api-v3-file-upload-errors-via-python">Google Drive api v3 file upload errors via python</a></p> <p>I am getting the following errors,</p> <pre...
<p>This issue has been solved by modifying the following connection code too google drive api.</p> <pre><code>SCOPES = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata'] credentials = ServiceAccountCredentials.from_json_keyfile_name('j...
python-3.x|google-api|google-drive-api|google-api-python-client|service-accounts
3
10,899
69,886,992
Unexpected UserDict Behavior
<p>I am working on a project and need to make use of UserDict instead of dict. I am importing a JSON file that is a dictionary with lists containing more dictionaries.</p> <p>Here is some example code and the behavior differences I am seeing:</p> <pre><code>import json from collections import UserDict import pprint p...
<p>Because <em>you created a new dictionary here</em>:</p> <pre><code>user_addr_1 = UserDict(user_addresses[0]) </code></pre> <p>This isn't unexpected at all, indeed, this is how <code>dict</code> works. You would see the same exact behavior if you did:</p> <pre><code>user_addr_1 = dict(user_addresses[0]) </code></pre>...
python|dictionary
3