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
6,000
57,170,398
Weird error when trying to copy a list and insert an item to the beginning
<p>I have a list of symbols that I use in a for loop. I'm trying to copy that list of symbols to a new list and insert a value in the first position of only the new list. I want the original list to be untouched. </p> <pre><code>self.symbols = ['CLE', 'RBE', 'HOE', 'CLES12Z', 'CLES6M', 'HOES1', 'RBES1', 'EP'] if ...
<p><code>key_list = self.symbols</code> is not a copy. They both hold a reference to the same list.</p> <p>Instead write:</p> <pre><code>key_list = self.symbols.copy() </code></pre>
python|python-3.x|list
2
6,001
44,555,372
Couple 2 different GPU cards for mini batching
<p>I just bought a GTX 1080Ti and I wanted to know if I can use both my old GTX 1070 and GTX 1080Ti in parallel for mini batching with either TensorFlow or PyTorch.</p> <p>My main concern is:</p> <p>Would the GTX 1070 bottleneck the GTX 1080Ti or the power of each cards will be used to their maximum?</p> <p>I know t...
<ol> <li>You can't run SLI for Deep Learning.</li> <li>You are bottlenecked by the PCIe interconnect. If you aren't using both x16 lines, then one will be slower.</li> <li>I'm not really sure what will happen if there are power issues. </li> <li>I can run a GTX 1060 and GTX 970 in parallel for mini-batching.</li> </ol>
multi-gpu|pytorch|tensorflow
0
6,002
54,775,479
Defining the type while passing a function through an argument in Python
<p>I know there is a way to specify the type of argument like this:</p> <pre><code>def f(x: int) return x </code></pre> <p>but what if I want to pass a function as an argument? For example:</p> <pre><code>class Sth: def __init__(self, x: int, f: XXX): self.__x = x self.__f = f def a(): r...
<p>You type 'Callable'. See <a href="https://docs.python.org/3/library/typing.html#typing.Callable" rel="nofollow noreferrer">reference.</a></p> <pre><code>from typing import Callable def __init__(self, x: int, f: Callable): pass </code></pre>
python|function|types|arguments
0
6,003
40,825,043
Query by ids or keys in datastore
<p>Using python, I have a google datastore ndb model like this.</p> <pre><code>class Persona(ndb.Model): name = ndb.StringProperty(repeated=True) names= ndb.StringProperty(default="") address = ndb.StringProperty(indexed=False) city = ndb.StringProperty() count = ndb.IntegerProperty(default=0) ...
<p>You can do this:</p> <pre><code>Person.query().filter(Person.key &lt; ndb.Key(Person, '16.240.886')) </code></pre>
python|google-app-engine|google-cloud-datastore|app-engine-ndb
1
6,004
47,663,378
Django Image Grid Gallery
<p>I am trying to setup a grid gallery in my Django website similar to pinterest.com.</p> <p>I have the following HTML code:</p> <pre><code>&lt;div class="row text-center text-lg-left"&gt; &lt;div class="col-lg-3 col-md-4 col-xs-6"&gt; &lt;a href="#" class="d-block mb-4 h-100"&gt; {% for img in imgs...
<p>I was able to figure it out using another method. Here is the code in case it helps someone else.</p> <pre><code> &lt;div style="width:100%"&gt; {% for img in imgs %} &lt;div style="float:left; width:200px; height:200px;"&gt; &lt;img src="/static/img/{{ img }}" class="img-thumbnail" alt=""&gt; ...
python|html|django
1
6,005
44,311,022
Python 2.7 extract day from Dataframe timestamp
<p>I have a dataframe "signals" like this:</p> <pre><code> Date Object Value \ 0 01/03/2017 00:00:13 Obj1 3.421875 1 01/03/2017 00:01:13 Obj1 3.578934 2 01/03/2017 00:02:13 Obj1 3.437500 3 01/03/2017 00:03:13 Obj1 3.234674 4 02/03/2017 ...
<p>You need to first convert the <code>Date</code> column to date time type, and then use <code>dt.date</code> to access the date info:</p> <pre><code>import pandas as pd df.Date = pd.to_datetime(df.Date) df.groupby(df.Date.dt.date).Value.mean() #Date #2017-01-03 3.418246 #2017-02-03 3.759255 #2017-03-03 ...
python|python-2.7|dataframe|group-by
0
6,006
64,315,184
How to create a second list in python, relative with first list
<p>I have a question, how can we create a second list in python, which every content of this list is about 10 larger than first list. I can't solve it by loop(for). For example:</p> <pre><code>l1[2] = 2 l2[2] = 12 </code></pre> <p>or</p> <pre><code> l1 = [0,1,2,3] l2 = [10,11,12,13] </code></pre> <p>Thank You</p>
<p>Just try (This is a list comprehension, where it iterates over the first list and adds 10 to each item):</p> <pre><code>l2 = [x+10 for x in l1] print(l2) </code></pre> <p>This is the short version of:</p> <pre><code>l2 = [] for i in l1: l2.append(i+10) </code></pre>
python
2
6,007
66,731,265
cx_oracle python and select Like %variable%
<p>I'm trying to execute a query based on &quot;tempo&quot; variable,using %tempo% none of the solution that I found here help my problem</p> <pre><code>import cx_oracle query=&quot;&quot;&quot;SELECT description, local, point, date FROM tbl_ext_tempo WHERE point like '%' || :0 || '%' ...
<p>You can define a list(<code>lst</code>), and append the current string to it as formatted</p> <pre><code>lst = [] tempo = 'someValue' query=&quot;&quot;&quot; SELECT description, local, point, &quot;date&quot; FROM tbl_ext_tempo WHERE point LIKE :0 AND ROWNUM &lt; ...
python|oracle|cursor|cx-oracle|execute
0
6,008
66,424,659
Replacing strings following a certain pattern
<p>I have the following series</p> <pre><code>2 eva.1 3 eva.2 4 eva.3 5 eva.4 ... 1970 normal.793 1971 normal.794 1972 normal.795 1973 normal.796 1974 normal.797 Name: Tipo Burla, Length: 1974, dtype: object </code></pre> <p>and I want to replace...
<p>You could do this: if burla is:</p> <pre><code> id string 0 2 eva.1 1 3 eva.2 2 4 eva.3 3 5 eva.4 4 1970 normal.793 5 1971 normal.794 6 1972 normal.795 7 1973 normal.796 8 1974 normal.797 </code></pre> <p>then replacing <code>eva.</code> by say <code>santan....
python|pandas
1
6,009
64,730,045
How to detect Created Exe's created another exe is closed?
<p>For example, we have 2 executable files on windows. (EXE_1.exe, EXE_2.exe)</p> <p>EXE_1.exe is calling EXE_2.exe with arguments. I want to detect when EXE_2 Closed(Terminated, killed etc.)</p> <p>I can't use WaitForSingleObject in C++ or Psutil process wait in python. Because it is returns when <strong>First</strong...
<pre><code>info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = EmreWin32Con.SW_MINIMIZE EXE = subprocess.Popen([EXE_KONUM], cwd=KLASOR_KONUM_EXE, creationflags=subprocess.CREATE_NO_WINDOW, startupinfo=...
python|c++|windows|exe|psutil
0
6,010
53,106,472
If else fill variable if empty list
<p>I have lists that are empty and filled in the data. I am trying to the store last element of the list into a variable. If there are elements in the list, it is working fine. However, when I pass in a empty [] list, I get error like: <code>IndexError: list index out of range</code>. Which syntax I should be using for...
<p>Here is one way to do this:</p> <pre><code>final = ids[-1] if ids else None </code></pre> <p>(Replace <code>None</code> with the value you'd like <code>final</code> to take when the list is empty.)</p>
python|python-3.x
2
6,011
65,083,159
Updating all documents in a collection (million+) with Date object
<p>I'm trying to update all documents in a collection. (~20m documents). Essentially the date string is stored as a month/day/year, and I want to instead store a date object so that I can sort based on that later. I've tried doing:</p> <pre><code>for document in collection.find({}, no_cursor_timeout=True): date = docum...
<p>Offload conversion to the Database server. Afterall <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/toDate/" rel="nofollow noreferrer">date conversion</a> gives similar results as <code>new Date</code> in Javascript.</p> <pre class="lang-js prettyprint-override"><code>&gt; new Date('04/01/202...
python|mongodb|pymongo
1
6,012
71,871,260
Pytorch DataLoader shuffle=False?
<p>I used Pytorch DataLoader to create My &quot;batch-data&quot; loder,but I got some problem.</p> <p>As the definition of the pytorch DataLoader Shuffer.</p> <pre><code>shuffle (bool, optional) – set to True to have the data reshuffled at every epoch (default: False) </code></pre> <p>the data will be reshuffled after ...
<p>The problem with your code is that you are re-instantiating the same iterator for each step in the for cycle. With <code>shuffle=False</code> the iterator generates the same first batch of images. Try to instantiate the loader outside the cycle instead:</p> <pre class="lang-py prettyprint-override"><code>loader = da...
pytorch|shuffle|dataloader
0
6,013
68,820,111
Preventing duplicate child entries in an ORM relationship
<p>Basically I have a service that reads from a spreadsheet and inserts into database. In SQLAlchemy I have the following relationship</p> <pre><code>class Customer(Base): __tablename__ = 'customers' id = Column(Integer, primary_key=True) name = Column(String) children = relationship('Email', backref=('customer') ...
<blockquote> <p>Setting the Email class to have two primary keys doesn't seem to make SQLAlchemy stop from appending the extra email</p> </blockquote> <p>That's correct. Using a composite primary key on (customer_id, email) does not prevent SQLAlchemy from <em>trying</em> to insert a new object that essentially duplica...
python|sqlalchemy|orm
0
6,014
10,775,746
Embedded IronPython Security
<p>I am embedding IronPython into my game engine, where you can attach scripts to objects. I don't want scripts to be able to just access the CLR whenever they want, because then they could pretty much do anything.</p> <p>Having random scripts, especially if downloaded from the internet, being able to open internet co...
<p>The only way to guarantee it is to use an AppDomain. I don't know what the performance hit is; it depends on your use case, so you should measure it first to make sure that it actually is too slow.</p> <p>If you only need a best-effort system, and if the scripts don't need to import anything, ever, and you supply a...
c#|security|embed|ironpython
3
6,015
61,654,684
showing mnist digits using python, numpy and matplot
<p>Let assume that I have MNIST digits in variable L.</p> <p><code>L[0].reshape(28,28)</code> will give me opportunity to plot this with matplot: <code>plt.matshow(L[0].reshape(28,28))</code>.</p> <p>But what if I want to plot 25 digits in 5x5 grid I cannot figure out how to shuffle L[0:24] to draw it properly with m...
<p>One way to do it would be something like that:</p> <pre><code>fig, axes = plt.subplots(5,5) for i, ax in enumerate(axes.ravel()): ax.imshow(L[i].reshape(28,28)) </code></pre> <p>That way you can loop over your subplots. If you like to shuffle the order of your plots you can use <code>np.random.permutation(25)<...
python|numpy|matplotlib|mnist
0
6,016
67,257,646
Get control over Thorlabs PM100USB from python
<p>I have Thorlabs PM100USB power meter connected to the computer and I want to get the current reading from python. From the following code, the measurement type shows &quot;TEMP&quot;, which gives the current temperature from a temperature sensor. I printed out the list of resources and this is what I'm getting</p> <...
<p>Have a look at the example program on their github. <a href="https://github.com/clade/ThorlabsPM100/blob/master/example.py" rel="nofollow noreferrer">https://github.com/clade/ThorlabsPM100/blob/master/example.py</a></p> <p>It shows some ways of setting the type of measurment to read. Example:</p> <pre><code>power_me...
python|visa|pyvisa
1
6,017
60,514,655
Python: use asyncio module to wait result for 2 independent tasks
<p>For Python 3.4+, I can use <code>asyncio</code> to dispatch independent tasks. <a href="https://i.stack.imgur.com/6LS2d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6LS2d.png" alt="enter image description here"></a></p> <p>Now, I have two long running independent functions. Both functions ret...
<p>If I'm getting what you are trying to do...</p> <p>In order to run both of the function at the same time you can use the <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task" rel="nofollow noreferrer">asyncio.create_task</a> and <a href="https://docs.python.org/3/library/asyncio-task.htm...
python|python-asyncio
0
6,018
71,437,220
How can python handle a messy data format in pandas?
<p>Sometimes I see data posted in a Stack Overflow question formatted like in <a href="https://stackoverflow.com/questions/13295735/how-to-replace-nan-values-by-zeroes-in-a-column-of-a-pandas-dataframe">this question</a>. This is not the first time, so I have decided to ask a question about this topic.</p> <p>I will po...
<p>The way I proceed when I have to deal with this kind of data, which is indeed frequent in SO posts, is to:</p> <ul> <li><p>first, copy (ctrl+c or right click) the data except the header row (<code> itm Date Amount</code> in your example);</p> </li> <li><p>then, run the following code:</p> </li>...
python|pandas
2
6,019
64,447,565
Installing Tensorflow when Python 3.9 is installed on Path?
<p>2 Versions of Python 3.9 and 3.8.6 are installed on Win 10. I Also want Tensorflow installed. But Pip recognises only Py 3.9 and hence does not installs tf locally. Is there a way out for this.</p>
<p>Try this command</p> <p><code>python -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl</code></p>
python|tensorflow|pip
12
6,020
53,305,809
How can I randomly select a question from an external file using python
<p>I want to include questions in an external file using python. Then be able to randomly select a question and let the user enter in the answer, then select another random question? Also with a point system when answer is answered correctly. Any help would be much appreciated. </p>
<p>Supposing your file (<code>questions.txt</code>) has the format:</p> <pre><code>Question1 Question2 Question3 </code></pre> <p>you could use:</p> <pre><code>import random f = open("questions.txt", "r") data = f.readlines() f.close() question = random.choice(data).rstrip() print(question) </code></pre>
python
0
6,021
63,550,093
How to get time object of current time in datetime library python
<p>I need to get the current date and time upon running the program, both as their respective objects in the datetime library. I have been able to get a date object for the current date fine:</p> <pre><code>datetime.date.today() </code></pre> <p>but how can i get a time object for the current time? <code>datetime.time....
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; n = datetime.datetime.now() &gt;&gt;&gt; n datetime.datetime(2020, 8, 23, 12, 37, 51, 595180) &gt;&gt;&gt; n.date() datetime.date(2020, 8, 23) &gt;&gt;&gt; n.time() datetime.time(12, 37, 51, 595180) </code></pre>
python|python-3.x|datetime
0
6,022
63,538,453
Unable to import 'numpy'pylint(import-error)
<p>I was following the tutorial of programming the Monty hall problem in python and all these errors came up and I've looked through the tutorial multiple times and still don't know what I've done wrong.</p> <p>This is where all these errors came up in the same order</p> <pre><code>Unable to import 'numpy'pylint(import...
<p>Be sure to install those packages with pip before importing them. If not installed python would look for the package a not find it. Then you get errors. Check if those packages are installed on your machine.</p> <p>Like pip install matplotlib</p>
python
0
6,023
63,397,246
Time Value of Money NumPy Functions, Working with Varying Floating Rates
<p>I would like to ask about the NumPy functions such as NumPy.fv(). I am aware of how to execute this function but ONLY for interest rates that are fixed. I would like to ask what if the rates are floating/varying interest rate?</p> <p>For example, ABC deposited $1,000,000 into a bank, the bank pays a floating rate an...
<p>I don't think you really need anything complicated for this:</p> <pre><code>principal = 1000000 rates = [0.012, 0.01, 0.018, 0.012, 0.009] for r in rates: principal = principal*(1+r) print(&quot;${:,.2f}&quot;.format(principal)) </code></pre> <p>Output:</p> <pre><code>$1,062,481.42 </code></pre>
python|numpy|finance
0
6,024
56,635,713
How do I UNION the results of two queries in SQLite3 for python?
<p>I'm trying to do multiple search functions for the user, and would like to know how to combine their results.</p> <p>I tried the 'obvious' way to do it, which was just to use the</p> <pre><code>cursor.execute("UNION") </code></pre> <p>between the two methods. But that didn't work, and gave the following error:</p...
<p><code>cursor.execute()</code> does not do batch processing. It takes a single, complete SQL statement and executes it. A lone <code>"UNION"</code> is not a complete SQL statement, it's a syntax error.</p> <p>This would work.</p> <pre><code>cursor.execute(""" SELECT stuff FROM table1 WHERE something = 'this_value' ...
python|sqlite
1
6,025
60,885,379
ValueError: time data '25-08-2012 00:00' does not match format '%m-%d-%Y %H:%M' (match
<pre><code>import pandas as pd import numPy as np # For mathematical calculations import matplotlib.pyplot as pit # For plotting graphs import datetime as dt from datetime import datetime # To access datetime from pandas import Series # To work on series import warnings # To ignore the warnings warnings.filterwarnings(...
<p>Swap <code>d</code> with <code>m</code>, because format of datetimes is <code>DD-MM-YYY HH:MM</code>:</p> <pre><code>train['New_date'] = pd.to_datetime(train.Datetime, format='%d-%m-%Y %H:%M') </code></pre>
pandas|datetime
0
6,026
68,884,242
Odoo how to display many2one inside of order form
<p>I starting to learn odoo framework.</p> <p>I am trying to display carrier_id which lives inside of sale.order model diplay inside of the &quot;sale.view_order_form&quot;</p> <p><strong>Error I get &quot;carrier_id doesnt exist&quot;</strong></p> <p>Here its my code, I hope someone can help me to understand.</p> <...
<p>I think you meant :</p> <pre><code>_inherit = 'sale.order' </code></pre> <p>instead of :</p> <pre><code>_inherit = 'delivery.carrier' </code></pre>
python|xml|odoo|odoo-13
0
6,027
68,973,163
How to get busy days between two datas?
<p>I want get the count of busy days between this two pandas series(&quot;datetime64[ns]&quot;)</p> <pre><code> DT_DEADLINE DT_DELIVERY 0 2021-08-05 2021-08-05 1 2021-08-09 2021-08-16 2 2021-08-10 2021-08-15 3 2021-08-09 2021-08-15 4 2021-08-05 2021-08-10 </code></pre> <p>I try do like that but get th...
<p><strong>Maybe...</strong></p> <pre><code>df['busday_count'] = np.busday_count(df['DT_DEADLINE'].values.astype('datetime64[D]'), df['DT_DELIVERY'].values.astype('datetime64[D]')) print(df) DT_DEADLINE DT_DELIVERY busday_count 0 2021-08-05 2021-08-05 0 1 2021-08-09 2021-08-16...
pandas
0
6,028
68,069,332
Pickling set subclass raises unhashable type: 'list'
<p>This code (using custom <code>list</code> subclass) works well for me:</p> <pre class="lang-py prettyprint-override"><code>import pickle class Numbers(list): def __init__(self, *numbers: int) -&gt; None: super().__init__() self.extend(numbers) numbers = Numbers(12, 34, 56) numbers.append(78) n...
<h2>Summary</h2> <p>Modifying the constructor of a built-in type is hard and error-prone since other methods migth depend on it. Avoid whenever possible.</p> <h2>Error inspection</h2> <p>First, by forcing the <a href="https://github.com/python/cpython/blob/main/Lib/pickle.py" rel="nofollow noreferrer">Python implementa...
python|set|pickle|subclass
0
6,029
59,104,924
NN Digit recognizition - Memory error, any ideas?
<p>im trying to make a trained OCR for digits, but i keep getting a memory allocation error and cant seem to figure out whats going wrong, worked just fine in start, but after 2 runs it suddenly started spiting these errors out, tried deleting zips and re downloading for possible corrupted files but with no results can...
<p>It is possible that your memory error is because you are trying to put <em>all</em> your data through the network at the same time.</p> <p>your code:</p> <pre><code>for step in range(num_training_steps): train_err = train_fn(x_train, y_train) </code></pre> <p>The better way to train is by using mini-batches. ...
python|memory|theano|nonetype|lasagne
1
6,030
73,111,623
Comparing and updating nested dictionaries python
<p>I tried finding many places , but could not find same one, please help in this python code. I have three nested multi level dictionaries, two main (A and B) and one small (temp)</p> <pre><code>A={&quot;X&quot;:{&quot;XX&quot;:1,&quot;XX1&quot;:56},&quot;Y&quot;:{&quot;YY&quot;:2},&quot;Z&quot;:{&quot;ZZ&quot;:{&quot...
<p>Iterate over <code>temp</code>, check if the value matches what's in <code>A</code>, delete (by key) from <code>A</code> and <code>B</code> if so.</p> <pre><code>&gt;&gt;&gt; A={&quot;X&quot;:{&quot;XX&quot;:1},&quot;Y&quot;:{&quot;YY&quot;:2},&quot;Z&quot;:{&quot;ZZ&quot;:3}} &gt;&gt;&gt; &gt;&gt;&gt; B={&quot;X&q...
python|updating
0
6,031
62,313,200
Matplotlib annotate/text: How can I set alpha transparency for facecolor and edgecolor separately?
<p>I'm using the matplotlib <code>plt.text</code> function to add a textbox to my histogram. In the <code>bbox</code> argument I specify the <code>boxstyle</code>, <code>facecolor</code>, <code>edgecolor</code>, and <code>alpha</code>. However when I run this and display the plot, both the face of the box and its edge ...
<p>You can first compute the RGBA sequence of both of your colors, then alter the alpha parameter <strong>only</strong> for the <code>facecolor</code> and then pass the modified RGBA tuples to the <code>text</code> function</p> <pre><code>from matplotlib import colors # Rest of your code fc = colors.to_rgba('lightgr...
python|matplotlib|plot|text|alpha
3
6,032
62,430,475
Several currency symbols in same column?
<p>How can I insert currency symbol (like $, €..) under 'Price' column, when I have different currencies in the same column?</p> <pre><code>data = [['Shampoo', 0.60, 'USD'], ['Soap', 0.19, 'EURO'], ['Pen', 0.1, 'JPY'], ] df = pd.DataFrame(data, columns = ['Stuff', 'Price', 'Currency']) df <...
<p>Create a <code>mapping</code> dictionary that maps each currency to its corresponding symbol then use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> to map the values in <code>currency</code> column, then concatenate the m...
python-3.x|pandas|dataframe|symbols|currency
1
6,033
35,451,866
how to get request HTTP headers in soaplib views file?
<p>i have soaplib for webservice as soap [server], all request route and response as xml by url well.but i can't fetch request http headers, How can i get request HTTP headers for rendering view some method of class ?</p> <blockquote> <p>like this method :</p> </blockquote> <pre><code>def redirect_http(self,request...
<p>problem resolved : change method request (for generate html and get http header most Observe protocol HTTP and structure), so to request and response html content should be send http request and get all headers generated</p>
python|httprequest|soaplib
0
6,034
35,616,756
Trying to exit using a set in python. What am i doing wrong?
<p>I'm trying to exit using the words that are in exit, I am trying to do a program were you can input an integer or a string and if num is in exit it will exit the program.</p> <pre><code>loop = True status = True exit = set(["exit","leave"]) while loop: while status: print ("Any of these commands will qu...
<p>Your indentation is wrong. You are looping and collecting input, but not running your <code>if</code> statements. Try this instead:</p> <pre><code>while loop: while status: print ("Any of these commands will quit the porgram",exit) num = input("Pick a number: ") # Note extra indents belo...
python|python-3.x
1
6,035
58,741,502
Python dataframes: how can I return the number of occurrences in a column?
<p>I am working with a large csv file that has information that looks something like</p> <pre><code>id year decade code type 3366 2014 2010 EM Chemical 3366 2014 2010 EM Chemical 3366 2014 2010 EM Chemical 3366 2014 2010 EM Chemical 3366 2014 2010 EM Chemical ...
<pre><code>df.groupby(list(df.columns)).size().reset_index().rename(columns={0:'count'}) </code></pre> <ul> <li><code>.size()</code> will get you counts, but create a multi-level index</li> <li><code>.reset_index()</code> will get rid of the multi-level index with the counts contained in a column named 0</li> <li><cod...
python|pandas|dataframe|data-science
2
6,036
58,901,690
How to get the maximum value in a list of dictionaries in python
<p>I have a list of dictionaries as follows, with different keys and values.</p> <pre><code>lst = [{'a': 15554}, {'v': 453}, {'a': 441742}, {'vb': 7785}, {'vv': 4275}, {'g': 7822}, {'l': 47537}, {'fg': 1144441565}] </code></pre> <p>I want to find which dictionary contains the highest value using python. Ex: <...
<p>You can use the function <code>max</code>:</p> <pre><code>max(list1, key=lambda x: list(x.values())) # {'fg': 1144441565} </code></pre>
python|python-3.x|dictionary
2
6,037
31,477,495
Delete substring not matching regex in Python
<p>I have a string like: </p> <pre><code>'class="a", class="b", class="ab", class="body", class="etc"' </code></pre> <p>I want to delete everything except <code>class="a"</code> and <code>class="b"</code>.</p> <p>How can I do it? I think the problem is easy but I'm stuck.</p> <p>Here is some one of my attempts but ...
<p>If you only wanted to keep the first two entries, one approach would be to use the <code>split()</code> function. This will split your string into a <code>list</code> at given separator points. In your case, this could be a comma. The first two list elements can then be joined back together with commas.</p> <pre><c...
python|regex
0
6,038
15,507,848
What is the correct way to override the __dir__ method?
<p><em>This question is meant to be more about <code>__dir__</code> than about <code>numpy</code>.</em></p> <p>I have a subclass of <code>numpy.recarray</code> (in python 2.7, numpy 1.6.2), and I noticed <code>recarray</code>'s field names are not listed when <code>dir</code>ing the object (and therefore ipython's aut...
<p>Python 2.7+, 3.3+ class mixin that simplifies implementation of <em>__dir__</em> method in subclasses. Hope it will help. <a href="https://gist.github.com/katyukha/c6e5e2b829e247c9b009" rel="noreferrer">Gist</a>.</p> <pre><code>import six class DirMixIn: """ Mix-in to make implementing __dir__ method in subclas...
python|inheritance|python-2.7|introspection
6
6,039
71,086,717
TypeError: arguments did not match any overloaded call
<p>I'm a beginner with QT Python and I'm trying to run a small program to display a table view with a push button beside each row. I've tried the code shown below but I'm getting the following errors:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/Programs/bottone.py&quot;, line 42, in &lt;module...
<p>The <code>IndexedButtonWidget</code> is instantiated with one argument: <code>'Edit'</code></p> <pre class="lang-py prettyprint-override"><code>self.btn_sell = IndexedButtonWidget('Edit') </code></pre> <p>The documentation shows that there is only one <code>QPushButton.__init__()</code> which takes one argument: <co...
python|qt
0
6,040
3,202,851
Pyttsx not saying all text when using non default voice
<p>I created a small module to speak the text that is sent to it. It works fine if I don't use engine.setProperty to set the voice, but if I set the voice it will only play the first command.</p> <pre><code>import pyttsx def speak( text ): if text != "": engine = pyttsx.init() engine.setProperty('...
<p>I think you should try the following code snippet :</p> <pre><code>import pyttsx engine = pyttsx.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() </code></pre> <p>which is originally from <a href="http://packages.python.org/...
python|text-to-speech
3
6,041
66,799,848
Selenium doesn't find element by id (python)
<p>Here is the html element:</p> <pre><code>&lt;button role=&quot;button&quot; title=&quot;Meeting beitreten&quot; id=&quot;interstitial_join_btn&quot; class=&quot;style-rest-1IrDU style-theme-green-22KBC style-join-button-yqbh_ style-size-huge-3dFcq style-botton-outline-none-1M0ur&quot; tabindex=&quot;1&quot; aria-lab...
<p>It seems synchronization issue.To click Use <code>WebDriverWait()</code> and wait for <code>element_to_be_clickable()</code></p> <pre><code>WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,&quot;pbui_iframe&quot;))) WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.ID,&...
python|html|selenium|webdriver|webdriverwait
0
6,042
66,850,137
Are there any function in python to click on the links to open and extract the email?
<p>I'm looking for a tool that extracts emails from web pages, but with the particularity that the emails are not directly on the page but on the page there is a list of icons with links, and each one links to a popup that contains the emails in practice manually you have to click on each single icon to see the related...
<p>It is a bit hard to understand what you're trying to say, but I've understood that you want to retrieve emails from a webpage. If this is what you're trying to do, then my following answer covers that, hope it helps-</p> <p>Web scraping emails in Python is fairly simple. There are 2 parts you want to figure out- the...
web-scraping|python-requests|html-email|scrapinghub|web-scraping-language
0
6,043
66,952,582
How to click on checkbox with selenium in python
<p>I'm trying to choose a checkbox from a certain website. this is a part of their HTML code.</p> <pre><code>&lt;div class=&quot;deliveryCheckboxContainer&quot;&gt; &lt;input class=&quot;deliveryCheckbox hiddenCheckbox&quot; id=&quot;deliveryCheckbox-684&quot; da...
<p>First, check answer above about timing issue. Second, I think that you are trying to find a dynamic id locator. Try to find by css.</p> <pre><code>browser.find_element_by_css_selector('.deliveryCheckbox.hiddenCheckbox').click() </code></pre> <p>Also, try using the xpath in the case when <code>label</code> is what yo...
python|selenium|checkbox
1
6,044
42,942,751
Custom query filter in django admin
<p>Here is my models code:</p> <pre><code>class Quote(models.Model): """Quote model.""" quote_text = models.TextField(unique=True) author = models.ForeignKey(Author) topic = models.ForeignKey(Topic) tags = models.ManyToManyField(Tag) language = models.ForeignKey(Language) hit = models.Integ...
<p>Say goodbye to <code>extra</code> and say hello to <a href="https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#django.db.models.functions.Length" rel="nofollow noreferrer">Length</a></p> <pre><code>from django.db.models.functions import Length queryset.annotate(len=Length('quote_text').filter(le...
python|django|django-models|django-queryset
3
6,045
65,840,478
Run python script with gdb with alias
<p>When I want to run python into gdb I using</p> <p><code>source /tmp/gdb/tmp/parser.py</code></p> <ol> <li>Can I set an alias so in the next time I want to call this script I use only <code>parser.py</code> or <code>parser</code> (without setting the script into working directory</li> <li>How can I pass args to scri...
<p>These should have been asked as two separate questions, really. But:</p> <ol> <li>Execute command <code>dir /tmp/gdb/tmp/</code>, after that you should be able to run script as <code>source parser.py</code></li> <li>You can't when you are sourcing a script. Rewrite script so that it attaches itself as GDB command vi...
gdb|gdb-python
0
6,046
56,515,675
How to delete list elements in one list based on content of another list?
<p>I have a problem with my list comprehension in python. I have a string variable with search queries, like this:</p> <pre><code>queries = 'news, online movies, weather, golden rush, online sports, price of the golden ring, today weather, python' </code></pre> <p>And I have a list of 2 elements:</p> <pre><code>wor...
<p>try this.</p> <pre class="lang-py prettyprint-override"><code> queries = 'news, online movies, weather, golden rush, online sports, price of the golden ring, today weather, python' queries = queries.split(',') words = [ 'online', 'golden' ] print([x for x in queries if not any(word in x for word in w...
python|dataset|list-comprehension
1
6,047
45,224,943
How do I get a fast return value while calling a slow function?
<p>The slow function (as seen in the code comments) weighs in at a whopping total of 11 seconds for a trivial request right now; an order of magnitude higher than the 10 second time limit the calling API has.</p> <p>Optimizations are not possible as some of these API's are third party. What I believe I need is to get ...
<p>This is how it was resolved:</p> <pre><code>newThread = threading.Thread(target=api_processing_thread, args=[jsonRequest]) newThread.start() </code></pre>
python|api|asynchronous
0
6,048
65,045,713
Comparing Numpy dtypes in sets vs tuples?
<p>So, I happened upon this strange issue where seeing if a set contains a Numpy dtype object vs. seeing if a tuple contains one gives different results:</p> <pre><code>In [1]: x = np.zeros(8) In [2]: x.dtype Out[2]: dtype('float64') In [3]: x.dtype in (np.float32, np.float64) Out[3]: True In [4]: x.dtype in {np.flo...
<p>Checking membership in a set uses <code>__hash__()</code> instead of <code>__eq__()</code>. In this case, it simply turns out that the objects are equal to each other but generate different hashes:</p> <pre><code>In [1]: np.float64 == np.dtype(np.float64) Out[1]: True In [2]: hash(np.float64) Out[2]: 8793996338852 ...
python|numpy
2
6,049
61,296,078
SqlAlchemy Informix Status
<p>Can anyone advise the status of the Sql-Alchemy project for Informix? I am relatively new to Python. I have worked with Dbi and SQL-Alchemy for postgres and made both of those work.</p> <p>I have spend many hours trying to make Informix work. I find the instructions on GitHub for sql-alchemy difficult to follow a...
<p>The Infomix Python driver (IfxPy and IfxPyDbi) is reasonably well tested and Informix team is happy to help you if you face problem. At the same time the Python SQL Alchemy adapter for Informix database it is work in progress and not ready for use; we still need to complete the metadata mapping for the Informix data...
python|sqlalchemy|informix
1
6,050
57,996,930
How to take a column from a txt file and save in a new matrix
<p>I did this code to go through a folder, find all .txt files and take the 4th column from this .txt file (has a lot of columns) and put in a new numpy array (data)</p> <pre><code>import numpy as np from scipy.constants import mu_0 from scipy.interpolate import griddata import matplotlib.pyplot as plt import pandas ...
<p>Try this : </p> <pre><code>import os import pandas as pd workingpath = os.getcwd() files = [] for file in os.listdir(workingpath): if file.endswith(".txt"): files.append(os.path.join(workingpath,file)) data = pd.DataFrame() for col, file in enumerate(files): dados = pd.read_csv(file, header=None)...
python|numpy|indexing
1
6,051
58,141,387
Why python metaclass is not working in this code?
<pre class="lang-py prettyprint-override"><code>class My_meta(type): def hello(cls): print("hey") class Just_a_class(metaclass=My_meta): pass a = Just_a_class() a.hello() </code></pre> <p>Above code is giving:</p> <blockquote> <p>AttributeError: 'Just_a_class' object has no attribute 'hello'</p>...
<p>Methods in a metaclass are inherited by the class object, not class instances. You can call the function this way:</p> <pre><code>Just_a_class.hello() // or a = Just_a_class() a.__class__.hello() </code></pre>
python|python-3.x|metaclass
1
6,052
58,139,003
Bulk insert, update values mongodb
<p>I run a bulk insert cron job everyday. But some values get missed and when I rerun the data, the values are added to the existing data rather than updating. Is there a way to do an insert only documents that have not yet been inserted. </p> <p>My code: </p> <pre><code>query = bigQuery.get_data(query) bulk = col.i...
<p>I obviously dont fully know your data structure, and not fully clear on what you are trying to do, but I think this should do.</p> <pre><code>query = bigQuery.get_data(query) new_things = [] for i, row in enumerate(query): if not col.find_one(your_query): # make sure that the document does not exist already ...
python|mongodb|bulkinsert|bulkupdate|bulk-operations
0
6,053
18,745,864
run python3 from virtualenv
<p>I still can't finally understand how apache understands which version of python it should now run.</p> <p>In virtualenv I install only python3.2 , then I put such code on wsgi wrapper:</p> <pre><code># -*- coding: utf-8 -*- #!/virtualenvs/simpleboard/bin/python import os, sys, site my_virtualenv_path = &quot;/virt...
<p>You can use the virtualenv support of uwsgi (<a href="http://projects.unbit.it/uwsgi/wiki/VirtualEnv" rel="nofollow">http://projects.unbit.it/uwsgi/wiki/VirtualEnv</a>). Adding "H /virtualenvs/simpleboard" to your uwsgi commmand in your uwsgi init script.</p>
django|python-3.x
1
6,054
18,547,147
dbscan - setting limit on maximum cluster span
<p>By my understanding of DBSCAN, it's possible for you to specify an epsilon of, say, 100 meters and — because DBSCAN takes into account <em>density-reachability</em> and <strong>not</strong> <em>direct density-reachability</em> when finding clusters — end up with a cluster in which the maximum distance between any tw...
<p>DBSCAN indeed does not impose a total size constraint on the cluster.</p> <p>The epsilon value is best interpreted as the <strong>size of the gap separating two clusters</strong> (that may at most contain minpts-1 objects).</p> <p>I believe, you are in fact not even looking for clustering: clustering is the task o...
python|algorithm|cluster-analysis|data-mining|dbscan
20
6,055
18,343,444
pandas groupby values in different column
<p>I have this data frame</p> <pre><code>frame = pd.DataFrame({'player1' : ['Joe', 'Steve', 'Bill', 'Doug', 'Steve','Bill','Joe','Steve'], 'player2' : ['Bill', 'Doug', 'Steve', 'Joe', 'Bill', 'Steve', 'Doug', 'Bill'], 'winner' : ['Joe','Steve' , 'Steve','Doug', 'Bill', 'Ste...
<p>It looks like you want a running total of <code>player1's</code> and <code>player2's</code> wins. Here is a pretty mundane way to do it which uses Python more than Pandas. </p> <p>Calculations that require stepping through the rows in sequence and using previous results to calculate the next row tend to not to be c...
python|python-2.7|pandas
1
6,056
71,672,071
Tabular data: Implementing a custom tensor layer without resorting to iteration
<p>I have an idea for a tensor operation that would not be difficult to implement via iteration, with batch size one. However I would like to parallelize it as much as possible.</p> <p>I have two tensors with shape (n, 5) called X and Y. X is actually supposed to represent 5 one-dimensional tensors with shape (n, 1): (...
<p>All operations you need (concatenation and matrix multiplication) can be batched. Difficult part here is, that you want to concatenate features of all items in X with features of all items in Y (all combinations). My recommended solution is to expand the dimensions of X to <code>[batch, features, 5, 1]</code>, expan...
tensorflow|neural-network|tensorflow2.0
1
6,057
42,324,140
How to change Keras optimizer code
<p>I am really new to Keras so forgive me if my query is a bit silly. I installed Keras in my system using the default methods and it works fine. I want to add a new optimizer to Keras so that I can easily mention "optimizer = mynewone " under the model.compile function. How do I go about changing the " optimizer.py " ...
<p>I think your approach is complicated and it doesn't have to be. Let's say you implement your own optimizer by subclassing keras.optimizers.Optimizer:</p> <pre><code>class MyOptimizer(Optimizer): optimizer functions here. </code></pre> <p>Then to instantiate it in your model you can do this:</p> <pre><code>myO...
python|github|neural-network|deep-learning|keras
2
6,058
54,101,999
Read Excel sectioned data, transform, then output to raw format for database
<p>I don't know if this is possible.. haven't come across this on the webs. In excel I have formatted crosstab data sectioned by location/city all in the same spread sheet for thousands of rows. Simple example below.</p> <p><a href="https://i.stack.imgur.com/cTHHK.png" rel="nofollow noreferrer">Example</a></p> <p>I w...
<p>Pandas has a method to read Excel files, which is rather neat, as you get a dataframe out of it and that probably makes it easier for scanning and customized parsing.</p> <pre><code>import pandas as pd # Reads the excel file xl = pd.ExcelFile(file_path) # Parses the desired sheet df = xl.parse(sheet_name) # To ho...
python|excel|database|pandas|xlrd
0
6,059
58,357,698
manual input for (ddd mm.m) convert to radians or decimal degrees? In python
<p>I am writing a Python program for astronomical navigation using sextant observations as manual input. I use an angular form (ddd mm.m) or degrees, minutes and decimal minutes. I'm using the math library for further computations in my code. What would you suggest I do when the Lat/Lon are implemented in the program c...
<p>It depends on what you are wanting to do with the values of latitude and longitude later. Normally they are needed for trigonometric functions (<code>sin</code>, <code>cos</code>, <code>tan</code> etc) which will need the arguments to be in radians. This is easy to do with <code>math.radians()</code> and the result ...
python|if-statement|navigation|latitude-longitude|astronomy
0
6,060
65,480,419
Python Discord Bot 'Event Loop is Closed'
<p>when I run my Discord bot it connects and get <code>RuntimeError: Event loop is closed</code>. This only occurred recently when I was trying to fix my client events not working, and added <code>intents = discord.Intents().all()</code> and then added that into my client initializer <code>client = commands.Bot(command...
<p>As the traceback says it might be error in the token you entered or the intents are not enabled</p> <p>Sorry couldn't add comment because my reputation is low</p> <p>Hope it might help if not just ping me up again</p>
python|python-3.x|discord|discord.py
2
6,061
45,400,456
How to interpret list of jobs returned from get_jobs in APScheduler?
<p>I am trying to figure out whether APScheduler is the tool for my project's needs.</p> <p>I can add a job.</p> <p>I can get a list of jobs -- but I am having trouble interpreting the results. I want to have my program translate this returned job list into a format needed by other parts of the program. I need to ext...
<p>OK, thanks to a previously asked question on the APScheduler Google group, I have a solution!</p> <p>The details have to be accessed through the fields, as I thought. The key to get the information from the individual field is to convert the field value to a string.</p> <p>Here is an example which works:</p> <pr...
python|apscheduler
3
6,062
45,703,291
Parse or view JSON data fields using JQ tool utility where field names have a "-" dash in the key name
<p>I have a JSON data file (as shown below) and I'm trying to find field values using <a href="https://stedolan.github.io/jq/tutorial/" rel="nofollow noreferrer">jq</a> utility. </p> <p>It's working fine except for fields if the key name contains a <code>-</code> dash character in it. </p> <p>How can I get the values...
<p>"-" is used for negation in jq. For key names with special characters such as "-", one cannot use the simplified ".keyname" syntax. There are several alternatives, but the most robust is simply to use the form <code>.["KEY NAME"]</code>, which can be abbreviated to ["KEY NAME"] when chained, e.g. <code>.a["b-c"]</...
python|json|dictionary|jq|jsonparser
6
6,063
14,782,135
Type casting error with numpy.take
<p>I have a look-up table (LUT) that stores 65536 <code>uint8</code> values:</p> <pre><code>lut = np.random.randint(256, size=(65536,)).astype('uint8') </code></pre> <p>I want to use this LUT to convert the values in an array of <code>uint16</code>s:</p> <pre><code>arr = np.random.randint(65536, size=(1000, 1000)).a...
<p>Interesting problem. <code>numpy.take(lut, ...)</code> gets transformed into <code>lut.take(...)</code> whose source can be looked at here:</p> <p><a href="https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/item_selection.c#L28" rel="nofollow">https://github.com/numpy/numpy/blob/master/numpy/core/...
python|numpy|lookup-tables
2
6,064
68,649,662
How do I get data from a table of entries I've generated in Python Tkinter?
<p>I am quite new to using Tkinter in python and I intended to create a table generation function within my software solution using it and what I'm finding issue is finding a way to call on and get the data within the table of entries to put inside a list and then use matplotlib to generate a graph from the table. So f...
<p>Right now inside <code>tcompile</code> cell refers to the last entry that was created. When you are iterating over the list of entries (<code>my_entries</code>) you save each entry in a variable called <code>entries</code> not <code>cell</code>. So I suggest you change the <code>for entries in my_entries</code> =&gt...
python|tkinter|tkinter-entry
1
6,065
68,681,092
typing.NamedTuple and mutable default arguments
<p>Given I want to properly using type annotations for named tuples from the typing module:</p> <pre class="lang-py prettyprint-override"><code>from typing import NamedTuple, List class Foo(NamedTuple): my_list: List[int] = [] foo1 = Foo() foo1.my_list.append(42) foo2 = Foo() print(foo2.my_list) # prints [42] <...
<p>Use a dataclass instead of a named tuple. A dataclass allows a field to specify a default <em>factory</em> rather than a single default value.</p> <pre><code>from dataclasses import dataclass, field @dataclass(frozen=True) class Foo: my_list: List[int] = field(default_factory=list) </code></pre>
python|type-hinting|python-typing|namedtuple
7
6,066
41,566,760
Bug on astype pandas?
<p>I am working with timedeltas and it seems this code</p> <p><code>copy_for_U.Time.astype('timedelta64[m]',copy=False);</code></p> <p>does not change the dataframe - as it should, if I understood correctly from the doc, where it says: </p> <blockquote> <p><code>Signature: full_df.Time.astype(dtype, copy=True, rai...
<p>In order for the changes to be applied to the dataframe, one needs to assign the dataframe to the variable one wants (or pass <code>inplace=True</code> - <a href="https://stackoverflow.com/q/43893457/7109869">this</a> may be a nice thread to read).</p> <p>Also, when doing that, you don't need to pass the <a href="ht...
python|pandas|numpy|timedelta
1
6,067
56,894,332
Best practice when loading and predicting keras model using flask
<p>I deployed a small web service (flask) on Google AppEngine with this config <code>app.yaml</code></p> <pre><code>manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 </code></pre> <p>I have an endpoint for predicting if a sentence is toxic, unfortunately calling the endpoint is so...
<p>From my point of view your main.py code looks fine, I only can see possible improvements in the app.yaml file.</p> <p>Choosing manual_scaling and setting the number of instances to 1 may be limiting the response time of your requests. Depending on the number of requests sent to the instance, it may not be able to h...
python|google-app-engine|machine-learning|flask|keras
0
6,068
61,893,048
Detecting a horizontal line in an image
<p><strong>Problem:</strong> I'm working with a dataset that contains many images that look something like this:</p> <p><a href="https://i.stack.imgur.com/Rio8gm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Rio8gm.jpg" alt="img2"></a> <a href="https://i.stack.imgur.com/k4D6Jm.jpg" rel="noreferrer"><img sr...
<p>You can start by thresholding your image by setting a very high threshold like 250 to take advantage of the property that your lines are white. This will make all the background black. Now create a special horizontal kernel with a shape like <code>(1, 15)</code> and erode your image with it. What this will do is rem...
python|image|opencv|python-imaging-library
1
6,069
71,852,403
matplotlib how to set plot size (with dpi), not figure size
<p>I could find a way to set a figure size with dpi</p> <pre><code>px = 1/plt.rcParams['figure.dpi'] fig = plt.figure(figsize=(1580*px, 25*px)) </code></pre> <p>(reference: <a href="https://matplotlib.org/stable/gallery/subplots_axes_and_figures/figure_size_units.html" rel="nofollow noreferrer">https://matplotlib.org/s...
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np def axes_with_pixels(width, height, margin=0.2): px = 1/plt.rcParams['figure.dpi'] fig_width, fig_height = np.array([width, height]) / (1 - 2 * margin) fig, ax = plt.subplots(figsize=(fig_width*px, fig_heigh...
python|matplotlib|plot
0
6,070
36,024,194
Find identical images in Tkinter?
<p>My Tkinter GUI loads the album cover of a certain song/artist combination directly from the associated last.fm link (looks like this: <code>http://ift.tt/1Jepy2C</code>because it's fetched by ifttt.com and redirects to the png file on last.fm.) When there is no album cover on last.fm, ifttt redirects to this picture...
<p>I've solved it purely on the basis that all album covers coming from last.fm are square 300x300px images. Since the n/a image coming from ifttt is rectangular, wider than it is high, I have a few possibilities:</p> <p>1) Checking the aspect ratio. If it's not 1, I have no cover image.</p> <p>2) Just checking the d...
python|image|tkinter|photoimage
1
6,071
35,993,647
Optimisation Crawler Scrapy
<p>I'm using scrapy to find expired domains, my crawler crawl the web and add every externals domains to the database (MySql) and after I check the availability with a PHP script.</p> <p>The database have around 300k domains and now the crawler is very slow because I check before each insert if the domain is not into ...
<p>You have really bad sql query. Add a unique key for a column url and ignore on duplicate that will speed up inserting. Unique index will work for you.</p> <p>Select is unnecessary.</p>
python|sql|scrapy|web-crawler
0
6,072
35,813,766
How to gain the precise file creation time in Python?
<p>I know that </p> <pre><code>time.time() </code></pre> <p>can be used to make the time system more precise and </p> <pre><code>time.ctime(os.stat("c:/a1.txt").st_ctime) </code></pre> <p>can be used to get the creation time of the file. But it can the precision is too low, only to the unit of second.</p> <p>Can ...
<p>use os.stat("C:/a1.tif").st_ctime_ns can gain nanoseconds level </p>
python
1
6,073
46,467,481
Sparse Tensor in tensorflow DataSets
<p>I have tensorflow program that work with TFRecord and i want to read the data with tf.contrib.data.TFRecordDataset but when i try to parse the example i get an exception: "TypeError: Failed to convert object of type to Tensor" When trying with only</p> <p>The code is: </p> <pre><code>def _parse_function(example_p...
<p>TensorFlow added support for this in v1.5</p> <p><a href="https://github.com/tensorflow/tensorflow/releases/tag/v1.5.0" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/releases/tag/v1.5.0</a></p> <p>"tf.data now supports tf.SparseTensor components in dataset elements."</p>
python|tensorflow
2
6,074
49,532,781
Facebook webhook for page unable to create
<p>Created an app and for that trying to create webhook, but in the droplist the 'Page' object is not showing up, only 'User', 'Application', 'Permission', 'Native Components' and 'Certificate Transperancy'.</p> <p>How can we create a webhook for the Page object?</p> <p><a href="https://i.stack.imgur.com/M3joS.png" r...
<p>There is a bug right now that does not let you subscribe to Pages: <a href="https://developers.facebook.com/bugs/553848658320920" rel="noreferrer">https://developers.facebook.com/bugs/553848658320920</a></p> <p>You should subscribe to the bug to get informed about updates.</p>
python|facebook|facebook-webhooks
6
6,075
70,091,592
ValueError when using json module in discord.py
<p>My intention is to set a channel for welcome messages immediately when the bot joins and to be able to change it using the command assigned. This is my code:</p> <pre class="lang-py prettyprint-override"><code>import discord from discord.ext import commands import json def get_welcomechannel(client, message,): ...
<p>The error is mentioning a circular reference, which is where you try to reference the object that you are inside of. You do this when you write:</p> <pre class="lang-py prettyprint-override"><code>welcomechannel[str(ctx.guild.id)] = welcomechannel </code></pre> <p>As you can see, you are assigning a property of the ...
python|discord.py
0
6,076
53,527,790
Panda Dataframe query
<p>I like to retrieve data based on the column name and its minimum and maximum value. I am not able to figure out how to get that result. I am able to get data based on column name but don't understand how to apply the limit.</p> <p>Column name and corresponding min and max value given in list and tuple.</p> <pre><c...
<p>You can be rather explicit and do the following:</p> <pre><code>lim = [('B',27,78),('E',44,73)] for lim in limiters: df = df[(df[lim[0]]&gt;=lim[1]) &amp; (df[lim[0]]&lt;=lim[2])] </code></pre> <p>Yields:</p> <pre><code> A B C D E F R0 99 78 61 16 73 8 R2 15 53 80 27 44 77 R8 ...
python|pandas
1
6,077
53,499,051
How to clean/fix these bytes without string operations?
<p>I have a <code>bytearray</code>, for example <code>[0x6B, 0x6A, 0x6D, 0x6C]</code>.</p> <p>For reasons out of my control the bytes are 'incorrect', and need to be fixed. The output I want is a <code>bytearray</code> like <code>[0xAB, 0xCD]</code>.</p> <p>So in my example, I want to ignore the '6' part of the byte....
<p>Iterate over the byte array 2 items at a time and use bit operations to combine the least significant 4 bits of each byte:</p> <pre><code>result = bytearray() it = iter([0x6B, 0x6A, 0x6D, 0x6C]) for a, b in zip(it, it): a &amp;= 0x0F b = (b &amp; 0x0F) &lt;&lt; 4 result.append(b|a) &gt;&gt;&gt; result ...
python
3
6,078
53,510,594
with open file - could not convert string to float: '-' - python
<p>I am getting the following error from my code:</p> <pre><code>File "D:/beverages.py", line XX, in &lt;module&gt; relst.append(Residents(float(value[0]),float(value[1]),str(value[2]))) ValueError: could not convert string to float: '-' </code></pre> <p>The code is below:</p> <pre><code>import math class R...
<p>Your problem lies here:</p> <pre><code>with open("surveydata.txt") as file: file1 = file.readline() # &lt;-- read ONE line relst = [] for line in file1 : value = line.split() relst.append(Residents(float(value[0]),float(value[1]),str(value[2]))) </code></pre> <p>The <code>file1</code> v...
python
3
6,079
53,511,406
ImportError: cannot import name 'enums'
<p>I am trying to use Google Speech API to recognize speech from mic input in real time. I have tried <code>https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_mic.py </code> but this error came out. Anybody knows how to solve this?</p> <pre><code>from google...
<p>I got mine working with the following import</p> <pre><code>from google.cloud.speech_v1.gapic import enums </code></pre>
python|speech-recognition|speech-to-text|google-speech-api
0
6,080
54,986,536
Pass objects between libraries in Python cffi
<p>If I make a new struct with <code>cffi.FFI.new</code>, how do I pass it to a function from a different <code>FFI</code> that has the same struct definition?</p> <p>I have a basic C struct that I am using in Python via the cffi package that I want to pass to various functions generated and compiled by cffi at runtim...
<p>You can use <code>FFI.include</code> to include the source and definitions of one <code>FFI</code> instance in another. Objects constructed with the included <code>FFI</code> are passable to functions in the <code>FFI</code> in which it was included.</p> <p>Note that an included definition cannot be duplicated in l...
python|python-cffi
1
6,081
54,829,700
Python RE. excluding some results
<p>I'm new to RE and I'm trying to take song lyrics and isolate the verse titles, the backing vocals, and main vocals:</p> <p>Here's an example of some lyrics:</p> <pre class="lang-none prettyprint-override"><code>[Intro] D.A. got that dope! [Chorus: Travis Scott] Ice water, turned Atlantic (Freeze) Nightcrawlin' in...
<p>You could search for the text between close-brackets and open-brackets, using regex groups. If you have a single group (sub-pattern inside round-brackets) in your regex, re.findall will just return the contents of those brackets. </p> <p>For example, <code>"\[(.*?)\]"</code> would find you just the section labels...
python|regex
1
6,082
54,785,043
how to split huge html to little files
<p>I'm trying to take a massive html file and split it to sections. The file is generated by Jenkins and looks like this:</p> <pre><code>[XXX] text1 [XXX] text2 [YYY] text4 [XXX] text3 [YYY] text5 [ZZZ] text6 ... </code></pre> <p>I tried to do the following:</p> <pre><code>my_dict = {} text, header = re.split('\n\[[...
<p>ok, solved it... I split the loop to 10K steps, and that just made it run crazy fast in comperaion. Guess I was just taking up too much RAM</p>
python|regex|string|python-2.7
1
6,083
21,568,780
Why isn't CSS working with apache2+mod_wsgi+python3+bottle?
<p>Background: I am trying to stand up an Amazon EC2 instance using the ubuntu server. I have installed Python3.3.2, mod_wsgi-3.5, apache2, and bottle and jinja2 for python3. I can get a regular webpage to load using all of these components, e.g. it recognizes the jinja2 templates, and correctly interpolates variables ...
<p>If possible, let Apache serve your css file; don't put it under <code>views</code>. And remember that your stylesheet's href is relative to your web page's URI, not to the directory where Bottle runs.</p> <p>So, if you hit the page at <code>http://myhost/hello</code>, then use this:</p> <pre><code>&lt;link rel="s...
html|css|jinja2|python-3.3|bottle
0
6,084
24,826,978
flask-wtf editing a model using wtform Form constructor: pre-filling the form
<p>I am reading the Flask Web Development book and came across this:</p> <pre><code>def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data ...
<p>Loading in a POST <code>MultiDict</code> is certainly the accepted way to map key/value pairs to your WTForms instance. Even more so, if you are using the Flask-WTF extension, this is automatically done for you, it is one of the perks that this extension brings you.</p> <p>If you would crack open the code of Flask-...
python|flask|wtforms|flask-wtforms
1
6,085
38,165,292
How to convert an adjacency matrix to an adjacency list with python?
<p>I have an adjacency matrix like: </p> <pre><code>[[ 0., 15., 0., 7., 10., 0.], [ 15., 0., 9., 11., 0., 9.], [ 0., 9., 0., 0., 12., 7.], [ 7., 11., 0., 0., 8., 14.], [ 10., 0., 12., 8., 0., 8.], [ 0., 9., 7., 14., 8., 0.]] </code></pre> <p>...
<p>Keep a list of already added edges in a set <code>edges</code>. Those edges are stored in a <code>frozenset</code>, so already added pairs are not replicated. </p> <hr> <p>Then build your graph by <em>enumerating</em> the outer list with a starting index of one, then the inner list also with a starting index of on...
python|python-3.x|matrix|adjacency-list|adjacency-matrix
5
6,086
8,784,396
How to delete the words between two delimiters?
<p>I have a noisy data..something like</p> <pre><code>&lt;@ """@$ FSDF &gt;something something &lt;more noise&gt; </code></pre> <p>Now I just want to extract <code>"something something"</code>. Is there a way on how to delete the text between those two delimiters <code>"&lt;"</code> and <code>"&gt;"</code>?</p>
<p>Use <a href="http://docs.python.org/library/re.html" rel="noreferrer">regular expressions</a>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = '&lt;@ """@$ FSDF &gt;something something &lt;more noise&gt;' &gt;&gt;&gt; re.sub('&lt;[^&gt;]+&gt;', '', s) 'something something ' </code></pre> <p>[Update]</p> <p...
python
98
6,087
58,783,616
pyinstaller questions and issues
<p>I am using python 3.6.8 with Linux ubuntu and I have a py.file (pyinst_tester.py) that I want to test pyinstaller with: I have three files (pyinst_tester.py) (bell.mp3) (filetotestadd.txt) </p> <p>The (pyinst_tester.py), plays a bell sound, only after reading a play command from the text file (filetotestadd.txt)</...
<p>I am closing this question. I have tried everything and i cannot do it. and i am getting no more feedback. therefore i am going to close it.</p> <p>pyinstaller -F --add-data doesnt do it.</p>
python|pyinstaller
0
6,088
52,338,155
Jupyter Notebook Azure Machine Learning Experiment
<p>The following code is provided by my Azure Machine Learning workspace. I have two errors in the output panes. </p> <p><a href="https://europewest.notebooks.azureml.net/n/om0ncnpgsxd7aq/notebooks/Run%20result%209-14-2018%201_15_27%20PM%20Python%203%20notebook.ipynb" rel="nofollow noreferrer">Jupyter Notebook ML Expe...
<p>I'm not being able to check your Notebook. I think you should try to paste some image or instead write the code snippet directly in your post.</p> <p>Independently of this, the best way to access your workspace from a Notebook or a local IDE is by using the 'Generate Data Access Code...', option in the context menu...
python|azure|machine-learning|jupyter-notebook
0
6,089
52,137,837
using more than one find_all
<p>I have just started learning Python and I need to scrape the number of hundreds of congress bills from <a href="https://www.congress.gov/bill/112th-congress" rel="nofollow noreferrer">https://www.congress.gov/bill/112th-congress</a>. For example, I need to get to the H.R.6729 below. The structure of the HTML page to...
<p>you must transform</p> <pre><code>bill_number = bill.find_all("span", {"class":"result-heading"}) </code></pre> <p>to</p> <pre><code>bill_number += bill.find_all("span", {"class":"result-heading"}) </code></pre>
python|beautifulsoup|findall
0
6,090
52,153,966
Realizing a 3D-plot with Python from data stored in 3 matrices
<p>Let M and N be to integers. One is given one vector s of size (M,1), one vector p of size (N,1) and one matrix u0 of size (M,N).</p> <p>Assume one wants to 3D-plot (s,p) as the grid and u0 as the function to plot (the z axis). When one writes:</p> <pre><code>fig = plt.figure() ax = fig.gca(projection='3d') surf = ...
<p>Ok, I am not sure if the output is the correct plot but here is the solution. Add the following line before <code>u0 = np.zeros((M + 1, N + 1))</code></p> <pre><code>sv, pv = np.meshgrid(s, p) # creating a meshgrid of MxN points </code></pre> <p>and replace your plotting command by</p> <pre><code>surf = ax.plot_s...
python|matplotlib|plot|3d
1
6,091
19,126,139
Should I use python on windows or cygwin?
<p>I have a windows 7 computer and was wondering whether to use the windows version of python or the one in cygwin. Especially with regard to modules that do not come pre-installed, which one is easier to install new modules?</p>
<p>ActivePython works just fine on Win7. Cygwin would add an unnecessary layer of complexity.</p>
python
3
6,092
69,170,426
I keep on getting the same error in the newest version of python
<p>So on python (Discord.py mainly) i keep getting the same error on a &quot;$move&quot; command how do i fix it.</p> <p>the error is</p> <pre><code>python -u &quot;/Users/ats/Desktop/bot.py&quot; iMac:~ ats$ python -u &quot;/Users/ats/Desktop/bot.py File &quot;/Users/ats/Desktop/bot.py&quot;, line 8 async def on...
<p>u change your on_ready with this</p> <pre class="lang-py prettyprint-override"><code>@client.event async def on_ready(): print(f&quot;we have logged in as {client.user}&quot;) </code></pre>
python|asynchronous|discord.py|helper
0
6,093
56,092,053
How to fix "IndexError: list index out of range" error of p2p chat application on Python?
<p>I am doing p2p chat application by Python. There is a error at "message = inputt[1]" on client side. Because of this error when i want to send message the program prints "You must write your name "</p> <p>I dont know how to solve because i didnt understand the logic of the mistake. It will be great if i can get th...
<p>I think the clue to what went wrong is in the question itself. The print statement says <code>"You must write your name &lt;name: message &gt;"</code>, so your message will be <code>john : this is a test</code>, but instead you are sending <code>this is a test</code>, which when you split on <code>:</code> will give...
python|python-3.x|network-programming|tcpclient|p2p
0
6,094
67,275,985
what is the meaning of else with string statement when using python if-else ternary operator?
<p>I just have a little bit confusion when I using python ternary operator. The sample code shown below:</p> <pre><code>a = 10 b = 5 if a &lt; 9 else &quot;s&quot; </code></pre> <p>The else can add a string statement like 's' or '#' or ''. What is the meaning of the statement do? How to covert it as a traditional if-el...
<p>It means, if a &lt; 9, the vale of b is 5, else the value is &quot;s&quot;. It's the same with</p> <pre><code>if a &lt; 9: b = 5 else: b = 's' </code></pre>
python
1
6,095
19,751,806
django paginator - how to show all page numbers available
<p>I have simple issue: </p> <p>I have this <code>{{ objects.paginator.num_pages }}</code> in template, which gives me the total number of pages that contain items. </p> <p>now i want to show those page numbers like this </p> <pre><code>1 | 2 | 3 | 4 | 5 </code></pre> <p>to achieve this, i need to make forloop till...
<p>Formatted with twitter bootstrap and with links:</p> <pre><code> &lt;ul class="pagination nav navbar-nav"&gt; {% if objects.has_previous %} &lt;li&gt;&lt;a href="?page={{ objects.previous_page_number }}"&gt;Prev&lt;/a&gt;&lt;/li&gt; {% endif %} {% for page in objects.paginator.page_range %} ...
python|django|pagination
22
6,096
13,280,822
Python: Can i set global variables in a package __init__ module?
<p>So i'm reading Alex Martelli's answer to <a href="https://stackoverflow.com/a/2361278/1658908">other question</a>...</p> <blockquote> <p>"One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which c...
<p>global variables are not global in the sense that every bit of python code sees the same set of globals. the global-ness is really just the 'module scope'; All of the variables and functions defined in a module are already global, and as global as they can possibly be.</p> <p>If you want to see the variables defi...
python|initialization|global-variables|pytables
2
6,097
22,295,190
Cannot set Python path in Aquamacs OSX 10.8
<p>I am using these lines in my Preferences.el</p> <pre><code>(add-to-list 'load-path "~/Library/Enthought/Canopy_64bit/User/bin") (require 'python-mode) (setenv "PYTHONPATH" "~/Library/Enthought/Canopy_64bit/User/bin") </code></pre> <p>But when I do C-c C-c, it is still picking up default Apple Python(2.7.2 instead ...
<p>Use this <a href="https://github.com/purcell/exec-path-from-shell" rel="nofollow">package</a>. And add these lines into Preferences.el</p> <pre><code>(require 'exec-path-from-shell) (exec-path-from-shell-initialize) </code></pre>
python|macos|environment-variables
0
6,098
57,850,309
Why are these two codes different?
<p>Probably a simple question, but I thought I was doing the same thing while instead i get two different answers, I am trying to calculate the sum of all the prime numbers below 2 million.</p> <pre><code>## THIS WORKS ## import sympy ans = 0 for n in range(0, 2000000): if sympy.isprime(n): ans += n print(...
<p>In the first instance you're summing over the value, and the second instance you sum over an integer cast of a boolean.</p> <p>The following code should do what you expect:</p> <pre><code>ans = sum(n for n in range(0, 2000000) if sympy.isprime(n)) </code></pre>
python
3
6,099
43,751,392
Having problems in loading MNIST database
<p>So i am simply trying to load the MNIST database (which i downloaded) and train a classifier and then save the training session to a file for future use. I have tried downloading it directly (through fetch_mldata) but my internet seems to be too slow to go that way,so i am trying to read the database by downloading ...
<p>So , it took some time but i found a fix anyway. Instead of using scipy to load the '.mat' extension file il used the auto downloder or this code to directly download the database:</p> <pre><code>dataset = datasets.fetch_mldata("MNIST Original") </code></pre> <p>and the trick is I placed the externally downloaded...
python|mnist
0