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 |
|---|---|---|---|---|---|---|
700 | 51,373,953 | Reading and Processing Large CSVs with Python | <p>I have a question that is similar in spirit to this <a href="https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3">previously asked question</a>. Nonetheless, I can't seem to figure out a suitable solution. </p>
<p><strong>Input</strong>: I have CSV data that looks like... | <p>IF you can use pandas, Please try the following. Pandas reads your file and store them in dataframe. It is much faster than our manual file processing using iterator.</p>
<pre><code>import pandas as pd
df = pd.read_csv('sample_data.txt')
columns = ['id','drug_name','drug_cost']
df1 = df[columns]
gd = df1.group... | python|python-3.x | 1 |
701 | 51,407,746 | Installing pyOpt on python in ubuntu | <p>I have downloaded pyOpt from its website and installed it on python in ubuntu, using the instructions on the website. </p>
<p>Still, I cannot import and use it in my pycharm projects.</p> | <p>I had the same problem, but I did not dare to try Akin's solution for my research project (I think it is a good solution if anyone wants to stick to PyOpt package with python3). </p>
<p>I used Pyomo instead.</p>
<p>By the way, Laurent's answer actually points to another package. PyOpt and pyopt are two different p... | python|pycharm | 1 |
702 | 17,495,999 | convert dataframe from wide layout to SQL-style slim layout | <p>How can I convert a dataframe like this:</p>
<pre><code> a b c
0 1.067683 -1.110463 0.208670
1 -1.321405 0.368915 -1.055342
2 -0.807333 0.082980 -0.873361
</code></pre>
<p>into</p>
<pre><code> det value
0 a 1.067683
1 a -1.321405
2 a -0.807333
3 b -1.110463
4 ... | <p>You can do this with <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt" rel="nofollow"><code>melt</code></a>:</p>
<pre><code>In [11]: from pandas.core.reshape import melt
In [12]: melt(df)
Out[12]:
variable value
0 a 1.067683
1 a -1.321405
2 a -0.8073... | python|pandas | 3 |
703 | 64,423,245 | dataframe Sort_values giving improper results | <p><a href="https://i.stack.imgur.com/cwzhx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwzhx.png" alt="enter image description here" /></a></p>
<p>Hi I am trying to get the top 10 values.
I would like to get the top 10 attendance and punctuality by staff.
here's my code for sorting:
newData =dat... | <p>Because values in column <code>Attendance</code> are strings, so sorted in lexicographic order.</p>
<p>So need convert them to numeric:</p>
<pre><code>data['Attendance'] = data['Attendance'].astype(float)
#if possible some non numeric values convert them to NaNs
#data['Attendance'] = pd.to_numeric(data['Attendance']... | pandas|sorting|plotly | 0 |
704 | 64,607,956 | PyGears How to make counter | <p>I want to make a counter which can start counting at posedge of a specific signal (enable signal). And once it counts to 256, stop counting, set the counter to 0 and output something.</p> | <p>When designing with PyGears, you should try to think more in terms of functions (although asynchronous) that are being invoked by receiving commands via input interfaces. Instead of thinking of the <code>enable</code> signal that triggers the counter, try to think of a counter you described as a function that receiv... | python|pygears | 1 |
705 | 64,420,446 | How to open a file in binary mode in google storage bucket from cloud function? | <p>In my cloud function, I need to get a file in cloud storage and send the file to an API through HTTP POST request. I tried the following code:</p>
<pre><code>storage_client = storage.Client()
bucket = storage_client.bucket(BUCKET_NAME)
source_blob_name = "/compressed_data/file_to_send.7z"
blob = bucket.blo... | <p>In your Cloud Functions reference, you don't provide the Blob content to the API call but only the Blob reference (file path + Bucket name).</p>
<p>You can, indeed download the file locally in the in memory file system <code>/tmp</code> directory. and then handle this tmp file as any file. <em>Don't forget to delete... | python|file-io|google-cloud-functions|google-cloud-storage | 2 |
706 | 70,515,842 | Tkinter image application keeps freezing system after it runs | <p>I'm testing an app with the following code:</p>
<pre><code>#!/usr/bin/env python3
import os
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
root = Tk()
root.title("Image Viewer App")
root.withdraw()
location_path = filedialog.askdirectory()
root.resizable(0, 0)
#Load f... | <p>The loading of images may take time and cause the freeze. Better to run <code>load_images()</code> in a child thread instead:</p>
<pre class="lang-py prettyprint-override"><code>import os
import threading
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
root = tk.Tk()
root.geometry... | python-3.x|ubuntu|tkinter|python-imaging-library | 1 |
707 | 55,778,312 | Input Transformation for Keras LSTM | <p>I am working on a project to try to enhance my understanding of LSTM networks. I am following the steps outlined in this blog post <a href="https://towardsdatascience.com/predicting-stock-price-with-lstm-13af86a74944" rel="nofollow noreferrer">here</a>. My dataset looks like the following:</p>
<pre><code> Open ... | <p>The <code>train_test_split</code> function would indeed not give the desired results here. It assumes that each row is an independent data point, which is not the case since you're using a single time series.</p>
<p>The most common option would be to use earlier data points for training and later data points for t... | python|keras|lstm|recurrent-neural-network | 0 |
708 | 55,981,316 | Showing step by step solving of sudoku | <p>Is there any way to show the steps of solving a sudoku? My code just solve it within 0.5 second and I wish to modify it to show the changes on the sudoku grid step by step on processing. (I am using python)</p> | <p>You can store all steps of solving sudoku (e.g. Grid data) into a list. For each step you modify the sudoku state, you clone a copy and append it to the global list. After solved it, you can loop through this list and render each state with some seconds delay.</p> | python|processing|sudoku | 0 |
709 | 49,820,305 | How to put extras_require in setup.cfg | <p><a href="https://setuptools.readthedocs.io/en/latest/history.html#v30-3-0" rel="noreferrer">setuptools 30.3.0</a> introduced declarative package config, allowing us to put most of the options we used to pass directly to <code>setuptools.setup</code> in <code>setup.cfg</code> files. For example, given following setup... | <p>It is supported. You need a config <em>section</em>:</p>
<pre><code>[options.extras_require]
test = faker; pytest
</code></pre>
<p>Syntax is documented <a href="https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html?highlight=options.extras_require#configuring-setup-using-setup-cfg-files" rel... | python|setuptools|declarative | 38 |
710 | 66,531,778 | Change bar order and legend order in plot (matplotlib/pandas) | <p>I would like to have the order of the legend and of the bars as the one defined in label_order</p>
<pre><code>for feat in df.columns:
label_order = ['Very Low', 'Low', 'Average', 'High', 'Very High']
df.groupby('class')[feat].value_counts().unstack(0).plot.bar()
plt.ylabel('Count')
plt.xlabel('Score'... | <p>The order of columns is determined by the column order in the dataframe you are plotting, therefore simply reordering the columns between unstacking and plotting will do the trick:</p>
<pre class="lang-py prettyprint-override"><code>df.groupby('class')[feat].value_counts().unstack(0)[label_order].plot.bar()
</code><... | python|pandas | 1 |
711 | 64,830,528 | rearranging 2*2 pixel images, each given by 1 by 4 numpy vectors, into a single 8 by 8 matrix without using a for loop | <p>in an assignment for a uni class i am given multiple images in vectors, and i need to display multiple of them by rearranging them into a single matrix.</p>
<p>assume the given vectors:</p>
<pre><code>[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]]
</code></pre>
<p>where each pair of 4 values within a vect... | <p>Let's use <code>reshape</code>, and <code>swapaxes</code>:</p>
<pre><code>arrs = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]]
np.array(arrs).reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)
</code></pre>
<p>Output:</p>
<pre><code>array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
... | python|numpy|matrix|reshape|imshow | 1 |
712 | 64,897,011 | python - json keep returning JSONDecodeError when reading from file | <p>I want to write data to a json file. If it does not exists, I want to create that file, and write data to it. I wrote code for it, but I'm getting <code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)</code>.</p>
<p>Here's part of my code:</p>
<pre><code>data = {"foo": "1"... | <p>The problem is that you open the file for write/read therefore once you open the file it will be emptied.</p>
<p>Then you want to load the content with <code>json.load</code> and it obviously fails because the file is not a valid JSON anymore.</p>
<p>So I'd suggest to open the file for reading and writing separately... | python|json|python-3.x | 0 |
713 | 63,741,027 | Regression statistics for subsets of Pandas dataframe | <p>I have a dataframe consisting of multiple years of data with multiple environmental parameters as columns. The dataframe looks like this:</p>
<pre><code>import pandas as pd
import numpy as np
from scipy import stats
Parameters= ['Temperature','Rain', 'Pressure', 'Humidity']
nrows = 365
daterange = pd.date_range('1/... | <p>Here is a bit of code that I have used in the past. I used <code>sklearn.LinearModel</code> because I think its a bit easier to use, but you can change to scipy.stats if you like.</p>
<p>This code uses <code>apply</code> and does the linear regression in the function <code>linear_model</code>.</p>
<pre><code>import... | python|pandas|dataframe|regression | 1 |
714 | 53,290,260 | How do I import a python file using Ansible Playbook? | <p>This is on a Linux machine. I have a run.yml like this</p>
<pre><code>---
- name: Appspec
hosts: localhost
become: true
tasks:
- name: test 1
script: test.py
</code></pre>
<p>test.py uses a python file (helper.py) by 'import helper' which is in the same path as the ansible-playbook and while running t... | <p>Copy both <code>test.py</code> and <code>helper.py</code> over to same directory on the remote machine (possibly to a temporary directory) and run <code>python test.py</code> as a <code>command</code> task. Something like this:</p>
<pre><code>- name: Create temporary directory
tempfile:
state: directory
re... | python|linux|ansible | 1 |
715 | 61,819,812 | How to only create relevant model fields during a django test? | <p>I am testing a method that requires me to create a fake record in my model. The model has over 40 fields. Is it possible to create a record with only the relevant model fields for the test so I don't have to populate the other fields? If so how would I apply it to this test case example. </p>
<p>models.py</p>
<pre... | <p>Try to use <code>model_bakery</code> to make an object record. Just populate fields you want and leave another blank, <code>model_bakery</code> will handle it. For the Detail, you can check this out <a href="https://github.com/model-bakers/model_bakery" rel="nofollow noreferrer">model_bakery</a> </p> | django|python-3.x|unit-testing|django-models | 0 |
716 | 67,600,810 | Find local duplicates (which follow each other) in pandas | <p>I want to find local duplicates and give them a unique id, directly in pandas.</p>
<p><strong>Reallife example:</strong></p>
<p>Time-ordered purchase data where a customer id occures multiple times (because he visits a shop multiple times a week), but I want to identify occasions where the customer purches multiple ... | <p>You can compare whether your column test is not equal to it's shifted version, using <code>shift()</code> with <code>ne()</code>, and use <code>cumsum()</code> on that:</p>
<pre><code>df['out'] = df['test'].ne(df['test'].shift()).cumsum()
</code></pre>
<p>Which prints:</p>
<pre><code>df
test out
0 A 1
1 ... | python|pandas | 2 |
717 | 60,575,408 | Can not connect to smtp.gmail.com in Django | <p>I'm trying to send email using smtp.gmail.com in Django project.
This is my email settings.</p>
<p>settings.py</p>
<pre><code># Email Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myaccount@gmail.com'
EMA... | <p>You may need to do some configuration on Google side.</p>
<p><a href="https://stackoverflow.com/a/31333304/11607969">Reference answer:</a>:</p>
<p>Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option.</p>
<p><a href="https://accounts.google.co... | python|php|django|smtp|gmail | 0 |
718 | 71,370,969 | displaying flask input() to a html template | <p>how can i display an input to my web application? Ive tried many ways but not succesfully...</p>
<pre><code>import random
import re
from flask import Flask, render_template
app = Flask(__name__)
app.debug = True
@app.route("/")
def index():
return render_template("play.html")
@app.route(... | <p>In game.html template you should put an <code>input</code> tag:</p>
<pre><code><form method="post" action="/want-to-play">
<input type="text" placeholder="Do you want to play?" />
<input type="submit" value="OK"/>
</form>
</c... | python|html|flask | 0 |
719 | 71,157,722 | Scraping multiple anchor tags which are under the same header/class | <p>I am trying to scrape the top episode data from IMDB and extract the name of the show and the name of the episode. However I am facing an issue where the show name and episode name are both anchor tags which are under the same header. <a href="https://i.stack.imgur.com/MobsQ.png" rel="nofollow noreferrer">Screenshot... | <p>in the last part you should specify more</p>
<pre><code>for store in episode_data:
h3=store.find('h3', attrs={'class': 'lister-item-header'})
sName =h3.findAll('a')[0].text
series_name.append(sName)
eName = h3.findAll('a')[1].text
episode_name.append(eName)
</code></pre>
<p>note that the name of ... | python|web-scraping|beautifulsoup | 1 |
720 | 10,909,316 | How do I map values to values with a common key in Python | <p>In the dictionaries below I want to check whether the value in aa matches the value in bb and produce a mapping of the keys of aa to the keys of bb. Do I need to rearrange the dictionaries? I import the data from a tab separated file, so I am not attached to dictionaries. Note that aa is about 100 times bigger th... | <pre><code>aa = {1:'a', 3:'c', 2:'b', 4:'d'}
bb = {'apple':'a', 'pear':'b', 'mango': 'g'}
bb_rev = dict((value, key)
for key, value in bb.iteritems()) # bb.items() in python3
dd = dict((key, bb_rev[value])
for key, value in aa.iteritems() # aa.items() in python3
if value in bb_rev)
print dd
</code></pre> | python | 3 |
721 | 72,562,173 | Find most recent date from different dataframe | <p>I have a data frame (df1) and want to get a previous most recent survey_date for the ID and associated score from another data frame (df2)</p>
<pre><code>
df1 = pd.DataFrame({'ID' : [1,2],
'start_date':['2018-08-04','2018-08-09']})
df1
df2 = pd.DataFrame({'ID' : [1,1,2,2],
'su... | <p>You can try <code>merge_asof</code></p>
<pre><code>#df1.start_date = pd.to_datetime(df1.start_date)
#df2.survey_date = pd.to_datetime(df2.survey_date)
out = pd.merge_asof(df1, df2, by = 'ID', left_on = 'start_date', right_on = 'survey_date')
Out[366]:
ID start_date survey_date score
0 1 2018-08-04 2018-08-... | pandas|date | 2 |
722 | 58,653,528 | Return list of all cell addresses within a Range | <p>I have a list of Ranges (loaded from an Excel workbook via openpyxl) in a list (e.g., <code>rng_list = ['$A$1:$A$3', '$B$1:$B$3', '$C$1:$C$3']</code>) and I would like to "unpack" each of those ranges into separate lists within a list of lists (i.e., <code>unpacked_list = [['$A$1','$A$2','$A$3'], ['$B$1','$B$2','$B$... | <p>After correcting syntax error in my original code (thanks, Rahasya Prabhakar!), I modified my original code to work as needed.</p>
<p>Specifically, I needed to redefine the '''temp_list''' as an empty list at the start of the initial For loop, and append to the '''unpacked_list''' at the end of the initial For loop... | python|excel|range|openpyxl | 0 |
723 | 59,699,616 | Pandas Date Time subraction - assigning nan values | <p>If I have code as below, </p>
<pre><code>df['variance'] = (pd.to_datetime(df.last_date) - pd.to_datetime(df.first_date)) / np.timedelta64(1, 'M')
</code></pre>
<p>This gives me number of months, but if one of the columns does not have a date and the result for this code for that value is NaN, is there a way where ... | <p>This should do it:</p>
<pre><code>df = df.fillna(value='Void')
</code></pre> | python|python-3.x|pandas | 2 |
724 | 48,949,022 | Django Filewrapper memory error serving big files, how to stream | <p>I have code like this:</p>
<pre><code>@login_required
def download_file(request):
content_type = "application/octet-stream"
download_name = os.path.join(DATA_ROOT, "video.avi")
with open(download_name, "rb") as f:
wrapper = FileWrapper(f, 8192)
response = HttpResponse(wrapper, content_t... | <p>Try to use <code>StreamingHttpResponse</code> instead, that will help, it is exactly what you are looking for.</p>
<p><em>Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?</em></p>
<pre><code>import os
from django.http import StreamingHttpRes... | python|django|file|download|streaming | 8 |
725 | 60,191,880 | How to use Python to get all cookies from web? | <p>Input </p>
<pre><code>import requests
from http import cookiejar
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64;rv:57.0) Gecko/20100101 Firefox/57.0'}
url = "http://www.baidu.com/"
session = requests.Session()
req = session.put(url = url,headers=headers)
cookie = requests.utils.dict_from_cookieja... | <p>You didn't maintain your session, so it terminated after the second cookie.</p>
<pre><code>import requests
from http import cookiejar
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64;rv:57.0) Gecko/20100101 Firefox/57.0'}
url = "http://www.baidu.com/"
with requests.Session() as s:
req = s.get... | python|python-requests | 0 |
726 | 67,049,558 | How to show only a few Many-to-many relations in DRF? | <p>If for an example I have 2 models and a simple View:</p>
<pre class="lang-py prettyprint-override"><code>class Recipe(model.Model):
created_at = model.DateField(auto_add_now=True)
class RecipeBook(model.Model):
recipes = model.ManyToManyField(Recipe)
...
class RecipeBookList(ListAPIView):
queryset = ... | <p>QuerySet way:</p>
<p>You can specify custom <code>Prefetch</code> operation in your queryset to limit the prefetched related objects:</p>
<pre><code>queryset.prefetch_related(Prefetch('recipes', queryset=Recipe.objects.all()[:5]))
</code></pre>
<p>Docs: <a href="https://docs.djangoproject.com/en/3.2/ref/models/query... | python|django|django-models|django-rest-framework|many-to-many | 2 |
727 | 72,239,073 | Panda dataframe replace() method for row numbers | <p>I need to replace some values in a column with a specific value using the row numbers list of the required values as an array like following array.Can I use <code>dataframe.replace()</code> for that?</p>
<pre><code>row_numbers = [ 4, 7, 15, 18, 49, 60, 78, 80]
</code></pre> | <p>You can use <code>loc</code></p>
<pre class="lang-py prettyprint-override"><code>df.loc[row_numbers, 'col'] = 3
</code></pre>
<p>in case your index is not number</p>
<pre class="lang-py prettyprint-override"><code>df['col'].iloc[row_numbers] = 3
</code></pre> | python|pandas | 0 |
728 | 50,462,322 | How is this Python function read? | <p>Wikipedia has the following example code for <a href="https://en.wikipedia.org/wiki/Softmax_function" rel="nofollow noreferrer">softmax</a>.</p>
<pre><code>>>> import numpy as np
>>> z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0]
>>> softmax = lambda x : np.exp(x)/np.sum(np.exp(x))
>>> ... | <p>Three remarks.</p>
<p>The use of <code>lambda</code> in the example is actually bad style, cf. this paragraph from the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">Python style guide</a>:</p>
<blockquote>
<p>Always use a def statement instead of an assignment statement that
bin... | python|numpy | 1 |
729 | 44,891,294 | Problems with converting a Python script into a Windows service | <p>I already have a python script that runs continuously. It's very similar to this: <a href="https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py" rel="nofollow noreferrer">https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py</a></p>
<p>Simil... | <p><strong><em>Edited</em></strong></p>
<blockquote>
<p><em>"...services can be automatically started when the computer boots, can be
paused and restarted, and do not show any user interface."</em> ~<a href="https://docs.microsoft.com/en-us/dotnet/framework/windows-services/introduction-to-windows-service-applica... | python|windows-services | 2 |
730 | 61,555,726 | I need a HTML front end to test and use a Django API | <p>newbie here. I followed a guide online and successfully deploy a Keras model with Django API. I wanted to create a HTML file which connected to the Django API, where I can load image into the model for processing, and then send back the prediction.</p>
<p>Below are the codes for the API. I need someone to guide me.... | <p>If you just need to test your API, download Postman and make requests from the application. It is much easier than actually making a whole HTML script to test your API. However, if you absolutely need to test your API through a frontend app, try the steps below.</p>
<ol>
<li>You need an image upload function in you... | python|html|django|api|keras | 0 |
731 | 57,894,373 | flask_sqlalchemy create model from different file | <p>I am trying to define and create my models with <code>flask_sqlalchemy</code>.</p>
<p>If I do it all in one script, it works:</p>
<p><strong>all_in_one.py</strong></p>
<pre><code>from config import DevConfig
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_obj... | <p>add <code>import members</code> below <code>db.init_app(app)</code></p>
<pre class="lang-py prettyprint-override"><code>from database import db
from config import DevConfig
from flask import Flask
app = Flask(__name__)
app.config.from_object(DevConfig)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.conf... | python|flask|sqlalchemy|flask-sqlalchemy | 2 |
732 | 53,836,433 | Turning on Jinja2 extensions in Salt | <p>I'm writing a lot of Salt states and I want to use the <a href="http://jinja.pocoo.org/docs/2.10/extensions/#expression-statement" rel="nofollow noreferrer">do tag extension</a> as suggested in <a href="https://stackoverflow.com/a/43265291/1694">this StackOverflow answer</a>.</p>
<p>According to the <a href="https:... | <p>From reviewing the <a href="https://github.com/MadeiraCloud/salt/blame/master/sources/salt/utils/templates.py#L226" rel="nofollow noreferrer">Salt source code</a>, it appears that it applies these extensions automatically if they're available. The error I was getting about the template failing to render appears to ... | python|jinja2|salt-stack | 0 |
733 | 23,985,316 | Auto set field in Django Model, depending on another user submitted field | <p>Say I have this code:</p>
<pre><code>from django.db import models
class Restaurant(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
</code></pre>
<p>then I'm able to create a 'Place':</p>
<pre><code>>>> p1 = Restaurant(name='Demon Dogs', address='94... | <pre><code>AUTOADDRESS = {'Demon Dogs':'944 W. Fullerton', 'Eat attack':'100 Green Meadows', 'Pizza Fast':'50 E. High Hill'}
class Restaurant(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def clean(self):
if not self.address:
self.addre... | python|django | 1 |
734 | 20,875,529 | Realtime list of viewers in a Google Drive document | <p>I'm working on an app which wraps Google Docs (using GAE/Python), and I want to keep track of who is viewing these docs in real-time. I can't find any APIs for this in the Google Drive SDK.</p>
<p>What's a good way to do this? Naively, I might imagine repeatedly polling each document individually and parsing the re... | <p>Realtime api is not for using with gdocs, only for your own custom formats. Instead see the changes api in drive but you wont be able to detect viewers only modifications <a href="https://developers.google.com/drive/manage-changes" rel="nofollow">https://developers.google.com/drive/manage-changes</a></p> | python|google-app-engine|google-drive-api | 2 |
735 | 21,083,772 | How to tell if boto.sqs.Queue.write() succeeded? | <p>All documentation of this method that I can find says that Queue.write returns True or False, depending on whether the write succeeded, but this doesn't square with reality. </p>
<p>The docs say:</p>
<blockquote>
<p>The write method returns a True if everything went well. If the write
didn't succeed it will ei... | <p>The documentation quote you provide comes from the SQS tutorial. The <a href="http://docs.pythonboto.org/en/latest/ref/sqs.html#boto.sqs.queue.Queue.write_batch" rel="noreferrer">SQS API docs</a> correctly describe the current return value. The SQS tutorial is simply out of date and needs to be corrected. I have ... | python|amazon-web-services|boto|amazon-sqs | 6 |
736 | 53,592,140 | What is the difference between timesteps and features in LSTM? | <p>I have a dataframe representing numerical values in many time periods, and I have formatted that dataframe in the way there are represented as a concatenation of previous values. For example:</p>
<pre><code>+------+------+------+
| t1 | t2 | t3 |
+------+------+------+
| 4 | 7 | 10 |
+------+------+--... | <p>I try to explain on example. So assume we have some measurement with temperature and pressure and we want to predict temperature at some point of future. We have two features right(temperature & pressure). So we can use them for feeding LSTM and try to predict. Now I'm not sure how you stand with LSTM theory, bu... | python|neural-network|lstm|timestep | 0 |
737 | 51,808,871 | Python relations between run_until_complete and ensure_future | <p>This is a follow up question to this question:</p>
<p><a href="https://stackoverflow.com/questions/40143289/why-do-most-asyncio-examples-use-loop-run-until-complete">Why do most asyncio examples use loop.run_until_complete()?</a></p>
<p>I'm trying to figure out how asynchronous programming work in python. There's ... | <blockquote>
<p><code>asyncio.ensure_future(someTask)</code>
will this line ALONE actually enqueue the Future returned in the default event loop and start the task?</p>
</blockquote>
<p>It will schedule the coroutine, but it won’t run it. You still need to run the loop to do that. You can do that with </p>
<pre><... | python|python-asyncio | 4 |
738 | 43,623,117 | Cleaner pandas/numpy code to find equivalency matrix? | <p>I have pandas DataFrame and would like to generate an equivalency matrix (or whatever it's called) where each cell has one value if the the df.Col[i] == df.Col[j] and another value when !=.</p>
<p>The following code works:</p>
<pre><code>df = pd.DataFrame({"Col":[1, 2, 3, 1, 2]}, index=["A","B","C","D","E"])
df
... | <pre><code>v = df.values
m = v == v[:, 0]
pd.DataFrame(np.where(m, 1, -1), df.index, df.index)
A B C D E
A 1 -1 -1 1 -1
B -1 1 -1 -1 1
C -1 -1 1 -1 -1
D 1 -1 -1 1 -1
E -1 1 -1 -1 1
</code></pre> | python|pandas|numpy | 3 |
739 | 39,204,113 | Send XML to activeMQ using Django | <p>I am trying to send a XML file generated using 'ElementTree' to activeMQ server using python django 'requests' library .My views.py code is :</p>
<pre><code>from django.shortcuts import render
import requests
import xml.etree.cElementTree as ET
# Create your views here.
def index(request):
return render(reques... | <p>I suggest looking at using the available STOMP protocol instead of HTTP. You'll have more control over message payloads and message headers.</p>
<p>Python library: <a href="https://pypi.python.org/pypi/stomp.py" rel="nofollow">https://pypi.python.org/pypi/stomp.py</a>
ActiveMQ Support: <a href="http://activemq.apac... | python|xml|django|jms|activemq | 1 |
740 | 39,322,967 | Django's runscript: No (valid) module for script 'filename' found | <p>I'm trying to run a script from the Django shell using the Django-extension <a href="http://django-extensions.readthedocs.io/en/latest/runscript.html" rel="noreferrer">RunScript</a>. I have done this before and but it refuses to recognize my new script:</p>
<pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python man... | <p>RunScript has confusing error messages. It gives the same error for when it can't find a script at all and when there's an import error in the script.</p>
<p>Here's an example script to produce the error:</p>
<pre><code>import nonexistrentpackage
def run():
print("Test")
</code></pre>
<p>The example has the ... | python|django | 13 |
741 | 47,957,499 | Multiple filters on exists | <p>I'm trying to filter my <em>exists</em> query set into looking through 3 fields to check if a release date of this game, platform and region already exists. </p>
<p>What I seek to accomplish: </p>
<pre><code>if ReleaseDate.objects.filter(game=game.id).filter(platform=release_date_object['platform']).filter(region=... | <p>Very simple - just put them all together in one filter() with commas:</p>
<pre><code>if ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']).exists():
</code></pre>
<p>Sometimes more complicated queries require Q objects but for a simple multiple-... | python|django|rest | 1 |
742 | 38,517,124 | How to minimize two loss using TensorFlow? | <p>I am working on a project which is to localize object in a image. The method I am going to adopt is based on the localization algorithm in <a href="https://cs231n.stanford.edu/slides/winter1516_lecture8.pdf" rel="nofollow">CS231n-8</a>.</p>
<p>The network structure has two optimization heads, classification head an... | <p>It depends on your network status.</p>
<p>If your network is just able to extract features [you're using weights kept from some other net], you can set this weights to be constants and then train separately the two classification heads, since the gradient will not flow trough the constants.</p>
<p>If you're not us... | tensorflow | 2 |
743 | 26,428,773 | Django - Save a new table1.PK and table2.PK and table2.FK | <p>I created 2 forms based on django-crispy forms. </p>
<ol>
<li>Form1 shows the OrderHeader</li>
<li>Form2 shows the OrderLines in a formset</li>
</ol>
<p>When i open an existing OrderHeader, i see the Header and the Lines, i can adjust and save the open forms just fine. </p>
<p>When i open the form empty, i select... | <p>The error was that i was only saving the formset and not the form. So i changed my views.py to the following; </p>
<pre><code>if request.method == 'POST':
form = OrderHeaderForm(request.POST,instance=orderid)
formset = OrderLineFormSet(request.POST,instance=orderid)
if form.is_valid() and formset.is_val... | python|django|django-crispy-forms | 0 |
744 | 28,252,337 | Use AJAX to display dictionary data returned by Django view in a table on the template | <p>I saw some posts on this topic but none quite similar. I am getting back a dictionary in JSON format from a Django view as shown below:</p>
<pre><code># display game statistics on the developer homepage
def gamestats(request):
countlist = []
datedict = {}
if request.method=='POST' and request.is_ajax:
... | <p>If you want to take a JSON object and put it into a table you can loop over it like so:</p>
<pre><code>var tableData = '<table>'
$.each(data, function(key, value){
tableData += '<tr>';
tableData += '<td>' + key + '</td>';
tableData += '<td>' + value + '</td&g... | jquery|python|ajax|json|django | 2 |
745 | 42,069,025 | Pandas timeseries indexing fails when the index is hierarchical | <p>I tried the following code snippet.</p>
<pre><code>In [84]:
from datetime import datetime
from dateutil.parser import parse
rng = [datetime(2017,1,13), datetime(2017,1,14), datetime(2017,2,15), datetime(2017,2,16)]
s = Series([1,2,3,4], index=rng)
s['2017/1']
Out[84]:
2017-01-13 1
2017-01-14 2
dtype: in... | <p>It seems it is more complicated.</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#partial-string-indexing-on-datetimeindex-when-part-of-a-multiindex" rel="nofollow noreferrer"><code>Partial string indexing on datetimeindex when part of a multiindex</code></a> is implemented in <code>DataFra... | pandas|time-series | 1 |
746 | 47,086,990 | High Scores! From ACM 2017 | <pre><code> testcases = int(input())
for i in range(testcases):
n = int(input())
names = []
for a in range(n):
names.append(input())
prefix = ''
for b in range(len(names[0])):
for c in names:
if c.startswith(prefix) == True:
common = True
el... | <p>If the current prefix matches all the entered names, you add one more character to it. When it fails to match, you break out of the loop - but the character that caused the failure is still attached to the end of <code>prefix</code>.</p>
<p>There are various ways to fix this, but one possibility is to just remove ... | python|python-3.x | 0 |
747 | 62,158,878 | Adding a dimension to an array | <p>If I have an array that I loaded from a nifti file with shape <code>(112, 176, 112)</code> and I want to add a fourth dimension but not be limited to shape <code>(112, 176, 112, 3)</code></p>
<p>Why does this code allow me to add however many layers in the 4th dimension I want:</p>
<pre><code>data = np.ones((112, ... | <p>@hpaulj got it, I was looking this up, and this shows the issue; note the shape of the arrays. I modified the original array so you can see what is being added...</p>
<pre><code>import numpy as np
data = np.ones((112, 176, 115, 20), dtype=np.int16)
data2=np.ones((112, 176, 115), dtype=np.int16)
data2a = data2.re... | python|numpy|concatenation|reshape|nifti | 0 |
748 | 67,324,818 | How can I get the last 10 records of each day? | <p>I have a DataFrame with 96 records each day, for 5 consecutive days.</p>
<p><strong>Data:</strong> {'value': {Timestamp ('2018-05-03 00:07:30'): 13.02657778, Timestamp ('2018-05-03 00:22:30'): 10.89890556, Timestamp ('2018-05-03 00:37:30'): 11.04877222,... (more days and times)</p>
<p><strong>Datatypes:</strong> Da... | <p>I would suggest filter the record by an hour and then group by date.</p>
<p><strong>Data setup:</strong></p>
<pre><code>import pandas as pd
start, end = '2020-10-01 01:00:00', '2021-04-30 23:30:00'
rng = pd.date_range(start, end, freq='5min')
df=pd.DataFrame(rng,columns=['DateTS'])
</code></pre>
<p>set the hour</p>
... | python|time-series|timestamp | 0 |
749 | 63,627,858 | get error when using sum and case in sqlalchemy | <p>I'm using <code>sqlalchemy</code> <code>func.sum</code> with <code>case</code> in a <code>having</code> condition but get below error.
code:</p>
<pre><code>query = query.having(
func.sum(case([(e.c.escalation_type.in_(escalation_types), 1)], else_=0)) > 0
)
</code></pre>
<p><code>escalation_ty... | <p>Looks like there is a bug in one of the libraries of <code>sqlalchemy</code>, <code>asyncpg</code>. I have to cast 1 and 0 to integer to make it work. here is working code:</p>
<pre><code>query = query.having(
func.sum(
case(
[(e.c.escalation_type.in_(escalation_types)... | python|sqlalchemy | 1 |
750 | 36,596,457 | iterate, Nonetype converting to String | <p>I am Scraping Financial Data from "<a href="http://profit.ndtv.com/stock/hindustan-unilever-ltd_hindunilvr/financials-historical" rel="nofollow">http://profit.ndtv.com/stock/hindustan-unilever-ltd_hindunilvr/financials-historical</a>"</p>
<p>Code : </p>
<pre><code>import requests
from bs4 import BeautifulSoup
impo... | <p>You are using the return value of <code>print()</code>:</p>
<pre><code>b = print(periodEnding(1))
</code></pre>
<p><code>print()</code> <strong>always</strong> returns <code>None</code>. You then tried to print each individual character of the string <code>"None"</code> (produced by <code>a = str(b)</code>), so yo... | python|beautifulsoup|python-3.4 | 3 |
751 | 16,937,584 | Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication.views. using django and rss | <p>I'm trying to get RSS to work with django</p>
<p>I have a social bookmarking app.</p>
<p>when I try to access the rss page at localhost:8000/feeds/recent/</p>
<p>I get the following error:</p>
<pre><code>Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndicat... | <p>The book I have been learning Django from is quite old.</p>
<p>I discovered from looking at the Django Documentation that the url pattern that's required can now go straight to RecentBookmarks.</p>
<p>I first looked <a href="https://docs.djangoproject.com/en/1.0/ref/contrib/syndication/" rel="nofollow">here</a></p... | django|python-2.7|rss | 0 |
752 | 71,259,713 | PyQt5 Application Window Not Showing | <p>I am trying to code an application that will allow the user to view a list of Tag IDs, as well as its description, and allow the user to check off each Tag ID that they would like to import data from. At this point I am working on developing the UI only.</p>
<p>The code below worked and would show the application wi... | <p>Header settings that depend on the model <strong>must</strong> always be set when a model is set.</p>
<p>Move <code>table.setModel(filterProxyModel)</code> right after the creation of the table or, at least, before <code>table.horizontalHeader().setSectionResizeMode</code> (the vertical <code>setSectionResizeMode()<... | python|pyqt5 | 1 |
753 | 9,139,287 | Python - store chinese characters read from excel | <p>I am trying to read in an excel sheet using xlrd, but I'm having some problems storing Chinese characters.</p>
<p>I am not sure why values get translated when I store it in a list:</p>
<p>Code:</p>
<pre><code>for rownum in range(sh.nrows):
Temp.append(sh.row_values(rownum))
print Temp
</code></pre>
<p... | <p>First. You XSL parser seem to return <code>unicode</code> values.</p>
<p>Second. When you do <code>print some_complex_object</code> (as you do <code>print Temp</code>), Python usually outputs the result of <code>repr</code> function on the elements of that object. And when you do <code>print repr(some_unicode_st... | python|cjk|xlrd | 2 |
754 | 9,134,553 | Web.py todo list with login | <p>I try to add a login functionality to the <code>web.py</code> <a href="http://webpy.org/src/todo-list/0.3" rel="nofollow">todo example</a>.</p>
<p>This is my code:</p>
<pre><code>""" Basic todo list using webpy 0.3 """
import web
import model
### Url mappings
urls = (
'/', 'Index',
'/login', 'Login',
... | <p>I just fixed it. I was missing some session initialization code.
Here's the working code:</p>
<pre><code>""" Basic todo list using webpy 0.3 """
import web
import model
### Url mappings
urls = (
'/', 'Index',
'/login', 'Login',
'/logout', 'Logout',
'/del/(\d+)', 'Delete',
)
web.config.debug = Fa... | python|session|web.py | 1 |
755 | 52,470,662 | TypeError at /add_team/ 'dict' object is not callable | <p>views.py:</p>
<pre><code>class AddTeamView(View):
template_name = 'add_team.html'
def get (self, request):
form = TeamForm()
context = {'form': form}
return render(request, 'add_team.html', context)
def post(self, request):
form = TeamForm(request.POST)
if form.... | <p>The <code>form.cleaned_data</code> is a dictionary, so you obtain elements by subscripting, or by using the <code>.get(..)</code> method (to return <code>None</code> or a default value in case the key is missing), so you should rewrite:</p>
<pre><code>team.name = form.cleaned_data('name')
team.details = form.cleane... | python|django | 2 |
756 | 37,144,260 | after4 - Simple python task (index and list issues) | <p>this is my first time asking a question on stack overflow. It has been really valuable to me while I have been learning python 2.7</p>
<p>The question is as follows:
<p>"Given a non-empty list numlist of ints, write a function after4(numlist) that returns a new list containing the elements from the original numlist... | <p>You use the name <code>x</code> for two different purposes: as the list parameter for the function <code>after4()</code> and as an integer in the list comprehension for the variable <code>indices</code>.</p>
<p>The interpreter thinks you mean the integer one in the last line, but you mean the list parameter one. Ch... | python | 1 |
757 | 37,169,602 | (1) Running a .py in cmd and (2) with variable in same line | <p><strong>I figured out the zip code in same line out. It's sys.argv[1], I had other code I neglected to comment out when trying out [1] that gave me the error. All I need help with now is getting weather.py to run without having to call the whole file path.</strong></p>
<p>I will preface with I'm not very experience... | <p>Make sure you <code>import sys</code> in your code.</p>
<pre><code>import sys
zipCode = sys.argv[1]
</code></pre>
<p>and actually provide an argument</p>
<p>EDIT:</p>
<p>For clarity, if sys was not imported, you would get <code>NameError</code> and not an <code>IndexError</code>. Additionally, when passing args ... | python|python-2.7 | 4 |
758 | 66,093,871 | Python, range(), double loops, | <p>Codes and result are shown below.</p>
<p>I'm curious about the prints beginning wiht 1 instead of 0 as start.
Where does the program get 1 from?</p>
<p>Can someone please help me here? Thanks!</p>
<pre><code>for i in range(5) :
for j in range(i) :
print(i, end=" ")
print()
</code></pre>
<p>... | <p>Because <code>for j in range(0):</code> loops 0 times, so it never prints <code>i</code> when its 0. If you look closely at your output, you'll see that the first line is actually blank.</p> | python|range | 2 |
759 | 39,687,484 | python error in decoding base64 string | <p>I'm trying to unzip a base64 string,</p>
<p>this is the code I'm using</p>
<pre><code>def unzip_string(s) :
s1 = base64.decodestring(urllib.unquote(s))
sio = StringIO.StringIO(s1)
gzf = gzip.GzipFile(fileobj=sio)
guff = gzf.read()
return json.loads(guff)
</code></pre>
<p>i'm getting error Erro... | <p>This worked for me (Python 3). The padding is indeed important, as you've seen in other answers:</p>
<pre><code>import base64
import zlib
import json
s = b'H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4q... | python|base64|gzip | 0 |
760 | 39,649,551 | Python 3 Sockets - Receiving more then 1 character | <p>So when I open up the CMD and create a telnet connection with:</p>
<p>telnet localhost 5555</p>
<p>It will apear a "Welcome", as you can see on the screen below.
After that every single character I type into the CMD will be printed out/send immediately.
My Question is: Is it, and if yes, how is it possible to type... | <p>You need to keep reading until the stream ends:</p>
<pre><code>string = ""
while True:
# for m in range (0,20): #Disconnects after x chars
data = conn.recv(1) #Receive data from the socket.
if not data:
reply = "Server output: "+ string
conn.sendall(str.encode(reply))
break
els... | python|sockets|python-3.x | 2 |
761 | 39,444,591 | Set handler for GPIO state change using python signal module | <p>I want to detect change in <code>gpio</code> input of raspberry pi and set handler using signal module of python. I am new to signal module and I can't understand how to use it. I am using this code now:</p>
<pre><code>import RPi.GPIO as GPIO
import time
from datetime import datetime
import picamera
i=0
j=0
camera... | <p>I just changed code in a different manner tough you are free to implement same using SIGNAL module.You can start new thread and poll or register call back event their, by using following code and write whatever your functional logic in it's run() method.</p>
<pre><code>import threading
import RPi.GPIO as GPIO
impor... | python|raspberry-pi|interrupt|gpio|django-signals | 0 |
762 | 10,030,042 | rpy + matplotlib + arcpy | <p>I am trying to use ryp with my arcpy scripts but I have the following error:</p>
<pre><code>import rpy2.robjects as robjects Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module> import rpy2.robjects as robjects
File "C:\Python26\ArcGIS10.0\lib\site-packages\rpy2\robjects\__init__.p... | <p>You will need to run these scripts with PROPER Python. It seems to me that the ArcPy distribution does not include the win32api module (It also does not exist from example in Python on Mac or Linux). </p>
<p>I would install <a href="http://code.google.com/p/pythonxy/" rel="nofollow">PythonXY</a> which includes R ... | python|matplotlib|rpy2|arcpy | 2 |
763 | 1,380,860 | Add Variables to Tuple | <p>I am learning Python and creating a database connection.
While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p>
<p><strong>What I am Doing</strong>:
I am taking information from the user and store it in variables.
Can I add these variables into a tuple?... | <p>Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:</p>
<pre><code>a = (1, 2, 3)
b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
c = b[1:] # (2, 3, 4, 5, 6)
</code></pre>
<p>And, of course, build them from existing values:<... | python|tuples | 483 |
764 | 63,169,446 | How to increment a string in python | <p>I was trying this code:</p>
<pre><code>str = input("Enter the string:")
num = input("By how much you want to increment:")
x = int(str) + num
print(char(num))
</code></pre>
<p>but this throws a traceback, What will be the correct code and what if the person enters (z + 1) i.e. how will the code be... | <p>You can use <code>ord</code> to get ascii of them and <code>chr</code> to get back the value using ascii value</p>
<pre><code>def inc_letter(char, inc):
start_char = ord('a') if char.islower() else ord('A')
start = ord(char) - start_char
offset = ((start + inc) % 26) + start_char
result = chr(o... | python|string | 0 |
765 | 28,371,990 | IO error in savetxt while using numpy | <p>Im trying to read a dataset and collect meta features from it.
I get the following error after executing the python file.</p>
<pre><code>Traceback (most recent call last):
File "runmeta.py", line 79, in <module>
np.savetxt('datasets/'+str(i)+'/metafeatures',meta[i],delimiter=',')
File "/usr/lib/py... | <p>the error you're getting is simply telling you it didn't find the file. i would suggest looking into absolute and relative file paths. </p>
<p>advice in error handling:
the error is triggered on this line</p>
<pre><code>fh = open(fname, 'w')
</code></pre>
<p>so as you debug your program, look at the line python s... | python|numpy | 1 |
766 | 14,333,098 | Why this SQL does not work in python | <pre><code>cur.execute("SELECT * FROM `productinfo` WHERE CreateDate > '%s'",kakko)
</code></pre>
<p>where <code>kakko</code> is user input string, for example, 2012-01-15</p>
<p>'%s' is not correct?</p> | <p>So, elaborating from the comments:</p>
<p><code>cursor.execute</code> requires a parameter tuple, and you don't need to quote the <code>%s</code>:</p>
<pre><code>cur.execute("SELECT * FROM `productinfo` WHERE CreateDate > %s", (kakko, ))
</code></pre> | python|mysql|mysql-python | 1 |
767 | 34,766,044 | how to verify connection is reused with python requests.session? | <p>I'd like to use requests 's session to reuse connections in django. </p>
<p><a href="https://stackoverflow.com/questions/30748200/reusing-connections-in-django-with-python-requests">Reusing connections in Django with Python Requests</a> </p>
<p>says I only need to declare it in global and access it.<br>
However I... | <p>You can try increasing your logging verbosity, then look out for logs that look like:</p>
<p><em><code>"Starting new HTTPS connection (1): some.url:port"</code></em></p>
<p>This is how to make global logging more verbose:</p>
<pre><code>import logging
logging.basicConfig(level=logging.DEBUG, format="%... | python|django|python-requests|connection-pooling | 0 |
768 | 23,142,251 | Is there a way to remove all characters except letters in a string in Python? | <p>I call a function that returns code with all kinds of characters ranging from ( to ", and , and numbers.</p>
<p>Is there an elegant way to remove all of these so I end up with nothing but letters?</p> | <p>Given</p>
<pre><code>s = '@#24A-09=wes()&8973o**_##me' # contains letters 'Awesome'
</code></pre>
<p>You can filter out non-alpha characters with a generator expression:</p>
<pre><code>result = ''.join(c for c in s if c.isalpha())
</code></pre>
<p>Or filter with <code>filter</code>:</p>
<pre><code>resu... | python|regex|string|parsing | 27 |
769 | 7,878,064 | how to check if two strings have intersection in python? | <p>For example, a = "abcdefg", b = "krtol", they have no intersection, c = "hflsfjg", then a and c have intersaction.<br>
What's the easiest way to check this? just need a True or False result</p> | <pre><code>def hasIntersection(a, b):
return not set(a).isdisjoint(b)
</code></pre> | python | 11 |
770 | 7,852,249 | Why am i getting error | <p>The error:</p>
<pre><code>Error Traceback (most recent call last):
File "/home/enrique/Dropbox/Public/pygametut3.py", line 41, in <module>
pix = MovingPixel(width/2, height/2)
TypeError: this constructor takes no arguments
</code></pre>
<p>The Code:</p>
<pre><code>#Creat a moving pixel
pix = MovingP... | <p>Because <code>MovingPixel</code> needs to be instantiated with no arguments:</p>
<pre><code>pix = MovingPixel()
</code></pre> | python|pygame | 1 |
771 | 1,173,767 | using pyunit on a network thread | <p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p>
<p>For example: The server it connects to could be on any port, an... | <p>I would try to introduce a factory into your existing code that purports to create socket objects. Then in a test pass in a mock factory which creates mock sockets which just pretend they've connected to a server (or not for error cases, which you also want to test, don't you?) and log the message traffic to prove ... | python|unit-testing|networking|python-unittest | 1 |
772 | 564,469 | What is a good & free game engine? | <p>For C++, Java, or Python, what are some good game + free game engines that are easy to pick up?</p>
<p>Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.</p> | <p>For my Computer Graphics course in College we used the open source <a href="http://www.ogre3d.org/" rel="noreferrer">OGRE 3D</a> engine. Not only is this an extremely robust 3D engine but it was a blast! </p>
<p>Develop a medium sized game using it and you will get a good taste of many of the different <a href="ht... | java|c++|python | 17 |
773 | 41,965,202 | Tensorflow: how to assign variables properly | <p>It's not duplicate of <a href="https://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable">How to assign value to a tensorflow variable?</a></p>
<p>I was trying to do simpliest thing: just swap variables <a href="https://stackoverflow.com/questions/41949633/tensorflow-how-to-swap-vari... | <p>The <a href="https://www.tensorflow.org/api_docs/python/control_flow_ops/control_flow_operations#identity" rel="nofollow noreferrer"><code>tf.identity()</code></a> operation is stateless. When you have a <code>tf.Variable</code> called <code>a</code>, the value of <code>tf.identity(a)</code> will always be the same ... | variables|tensorflow | 1 |
774 | 11,627,362 | How to straighten a rotated rectangle area of an image using OpenCV in Python? | <p>The following picture will tell you what I want.</p>
<p>I have the information of the rectangles in the image (width, height, center point and rotation degree). Now, I want to write a script to cut them out and save them as an image, but straighten them as well. As in, I want to go from the rectangle shown inside ... | <p>You can use the <a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html#rotation" rel="noreferrer"><code>warpAffine</code></a> function to rotate the image around a defined center point. The suitable rotation matrix can be generated using <... | python|image-processing|opencv | 64 |
775 | 33,946,338 | Python + selenium: extract variable quantity of paragraphs between titles | <p>Fellows, assuming the html below how can extract the paragraphs <code><p></code> who belongs to the tile <code><h3></code>.</p>
<pre><code><!DOCTYPE html>
<html>
<body>
...
<div class="main-div">
<h3>Title 1</h3>
&l... | <p>It's easy to be done using BeautifulSoup</p>
<pre><code>import bs4
page = """
<!DOCTYPE html>
<html>
<body>
...
<div class="main-div">
<h3>Title 1</h3>
<p></p>
<h3>Title 2</h3>
<p>... | python|html|selenium|beautifulsoup|urllib2 | 0 |
776 | 46,842,321 | How to print the sum value of gradient in tensorflow? | <pre><code>self.logits = nn_layers.full_connect_(self.wide_deep_embed, config.num_classes, activation='None', use_bn = True, \
keep_prob=self.keep_prob, name='output_layer') # predict prob
## loss and optim
#self.loss = nn_layers.cross_entropy_loss_with_reg(self.labels, self.log... | <p>Here's how you can add the gradients to <a href="https://www.tensorflow.org/get_started/summaries_and_tensorboard" rel="nofollow noreferrer">tensorboard summary</a> on each step:</p>
<pre><code># All gradients of loss function wrt trainable variables
grads = tf.gradients(self.loss, tf.trainable_variables())
# Summ... | python|machine-learning|tensorflow|neural-network|deep-learning | 0 |
777 | 46,821,548 | tensorflow object detection eval error | <p>When I use a model to check the mAP on test datasets, I got the following error:</p>
<pre><code>INFO:tensorflow:Restoring parameters from /home/aurora/workspaces/PycharmProjects/tensorflow/tensorflow_object_detection/outputs/model.ckpt-278075
INFO:tensorflow:Restoring parameters from /home/aurora/workspaces/Pycharm... | <p>I got a similar error and I was stuck for many days on that error.
I could resolve that error by editing my label.pbtxt file. Could you show your label(.pbtxt) file?
My label file was :(containing 3 labels)</p>
<pre><code>item {
id: 1
name: 'tree'
id: 2
name: 'water body'
id: 3
name: 'building'
}
</co... | tensorflow|object-detection|object-detection-api | 0 |
778 | 37,946,663 | Incrementing IntegerField counter in a database | <p>As beginner at Django, i tried to make a simple application that would give Http response of how many times content was viewed.
I have created a new <code>Counter</code> model, and inside, added IntegerField model <code>count</code>.</p>
<pre><code>class Counter(models.Model):
count = models.IntegerField(defaul... | <h2>The problem</h2>
<p>Yes but you are creating a new <code>Counter</code> object on each request, which starts again at 0, that's your problem</p>
<pre><code>def IndexView(response):
counter = Counter() # This creates a new counter each time
counter.count = counter.count + 1
counter.save()
return Ht... | python|django|django-models|models | 2 |
779 | 30,103,029 | Django Celery Directory Structure and Layout | <p>I have a django project using the following directory structure.</p>
<pre><code>project/
account/
models.py
views.py
blog/
models.py
views.py
mediakit/
models.py
views.py
reports/
celery.py <-- new
models.py
tasks.py <-- new
views.py
setti... | <p>The celery app file should live in the core directory of your project, along the settings and all the other things as shown in the documentation that you posted.</p>
<p>To define portable tasks it makes sense to put them in the app that is using them, as you pointed out, in your case the reports app.</p>
<p>The id... | python|django|rabbitmq|celery|django-celery | 4 |
780 | 30,174,841 | How to escape spaces in Bash command line arguments | <p>Does Bash support escaping spaces in command line arguments?</p>
<p>I have a simple Python script using argparse to get arguments passed from Bash, but when I call it like:</p>
<pre><code>myscript.py --name="Some Text With Spaces"
</code></pre>
<p>I get a result like:</p>
<pre><code>args = ['Text', 'With' Spaces... | <p>Coming from the bash end, the most likely cause is that you're not telling us the truth about your bash code. What you're hitting looks a great deal like <A HREF="http://mywiki.wooledge.org/BashFAQ/050" rel="noreferrer">BashFAQ #50</A>.</p>
<p>Running</p>
<pre><code>myscript.py --name="Some Text With Spaces"
</cod... | python|bash | 6 |
781 | 56,939,740 | How do I convert a str list that has phrases to a int list? | <p>I have a script that allows me to extract the info obtained from excel to a list, this list contains str values that contain phrases such as: "I like cooking", "My dog´s name is Doug", etc.</p>
<p>So I've tried this code that I found on the Internet, knowing that the int function has a way to transform an actual ph... | <p>To expand on the <code>bytearray</code> approach you could use <code>int.to_bytes</code> and <code>int.from_bytes</code> to actually get an int back, although the integers will be much longer than you show in your example.</p>
<pre><code>def to_int(s):
return int.from_bytes(bytearray(s, 'utf-8'), 'big', signed=... | python|python-3.x | 2 |
782 | 27,680,866 | Wrong symbol when using escape sequences learn python the hard way ex10 | <p>When i try to print \v or \f i get gender symbols instead:</p>
<p><img src="https://i.imgur.com/NlPLx92.png" alt="screenshot"></p>
<p>Note also that I'm a complete beginner at programming.</p>
<p>edit: Seems like i didnt write clear enough, i <strong>dont</strong> want to write \v or \f but the escape sequence cr... | <p>You are trying to print special characters, e.g., <code>"\n" == new line</code>. You can learn more here: <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">Python String Literals</a>.</p>
<p>Excerpt: </p>
<blockquote>
<p>In plain English: String literals can be en... | python|windows|python-2.7|console|control-characters | 2 |
783 | 27,609,247 | Can tuples implement external data from .txt files? | <p># Defines the variable 'load_words()'.</p>
<pre><code>def load_words():
</code></pre>
<p># Opens and assigns a 'word' file from an external "txt" file.</p>
<pre><code> words_file = open("words.txt", "r")
</code></pre>
<p># Assigns 'words' as the condensed function for lines of coded words in the external "... | <p>If I understood you correctly, yes.</p>
<p>From your question, it sounds like you want to read a file with <code>N</code> lines, and from that file produce an N-tuple of strings, in which each element of the tuple is a line from the file.</p>
<p>So, what you're doing now is reading a file that looks like this:</p>... | python | 1 |
784 | 43,274,901 | How to change timezone in http response (django server)? | <p>I'm running django server without any proxy:</p>
<pre><code>python manage.py runserver 0.0.0.0:80
</code></pre>
<p>I set my local timezone on linux server, it's correct:</p>
<pre><code>root@83b3bf90b5c5:/app# date
Fri Apr 7 12:38:42 MSK 2017
</code></pre>
<p>Also I set local timezone on settings.py of my django... | <p>Using <a href="http://pytz.sourceforge.net/" rel="nofollow noreferrer">pytz</a>, as <code>astimezone</code> method</p>
<pre><code>from pytz import timezone
time_zone = timezone(settings.TIME_ZONE)
currentTime = currentTime.astimezone(time_zone)
</code></pre>
<blockquote>
<p>In your Middleware:</p>
</blockquote>... | python|django|http|datetime|timezone | 1 |
785 | 43,160,597 | Heroku error : Compiled slug size: 624.7M is too large (max is 300M) - using miniconda for scipy and numpy | <p>I am working with Python 2.7.11, Django 1.9 and Heroku.</p>
<p>I need to use scipy and numpy. Everything works well locally but Heroku returns an error when I push the application : "Compiled slug size: 624.7M is too large (max is 300M)"</p>
<p>I therefore deleted the buildpack Heroku/Python and added this one: <a... | <p>Did you use Anaconda? I had the same problem the slug file was 505M, then I created a virtual env with pip and got one only 237M
My requirements.txt:
I created a new virtual env using pip instead of conda. </p>
<pre><code>pip install virtualenv
cd my_project_folder
virtualenv my_project
</code></pre>
<p>Then I ins... | python|django|numpy|heroku|scipy | 0 |
786 | 48,465,648 | How to save training model at each training step instead of periodic save based on time interval.? - in TensorFlow-Slim | <p>slim.learning.train(...) accepts two arguments pertaining to saving the model(<em>save_interval_secs</em>) or saving the summaries(<em>save_summaries_secs</em>). The problem with this API is, it only allows to save the model/summary based on some "time interval" but I need to do this based on "each step" of the trai... | <p>Slim is deprecated, and using Estimator you get full control over saving / summary frequency.</p>
<p>You can also set the seconds to a very small number so it always saves.</p> | tensorflow|tensorflow-slim | 0 |
787 | 48,631,907 | Running CrossValidationCV in parallel | <p>When I run a <strong><code>GridsearchCV()</code></strong> and a <strong><code>RandomizedsearchCV()</code></strong> methods in parallel ( having <strong><code>n_jobs>1</code></strong> or <strong><code>n_jobs=-1</code></strong> options set )<br>
it shows this message:</p>
<blockquote>
<p>ImportError: [joblib] At... | <h2><strong><code>joblib</code></strong> is know for this behaviour and rather explicit in documenting:</h2>
<blockquote>
<p><strong>Warning</strong></p>
<p>Under Windows, it is important to protect the main loop of code to avoid recursive spawning of <code>subprocesses</code> when using <strong><code>joblib.Pa... | python|parallel-processing|scikit-learn|cross-validation | 0 |
788 | 48,519,440 | Validation Error while creating partial invoice from sales order in Odoo 10 | <p>When am creating partial invoice (down payment), I got the below error</p>
<blockquote>
<p>The operation cannot be completed, probably due to the following:- deletion: you may be trying to delete a record while other records still reference it- creation/update: a mandatory field is not correctly set</p>
<p>[object w... | <p>As far as my understanding, I think you have done some customizations in the DB, that's why this error. The error says that there is a mandatory field, but you are not supplied the value into it. The field is shown in the error message, categ_id.</p>
<p>Thanks</p> | python|python-2.7|odoo|odoo-10 | 0 |
789 | 19,960,166 | What are the workaround options for python out of memory error? | <p>I am reading a x,y,z point file (LAS) into python and have run into memory errors. I am interpolating unknown points between known points for a project I am working on. I began working with small files (< 5,000,000 points) and was able to read/write to a numpy array and python lists with no problem. I have rec... | <p>Regardless of the amount of RAM in your system, if you are running 32-bit python, you will have a practical limit of about 2 GB of RAM for your application. There are a number of other questions on SO that address this (e.g., see <a href="https://stackoverflow.com/questions/18282867/python-32-bit-memory-limits-on-64... | python|numpy|scipy|out-of-memory | 5 |
790 | 66,941,321 | Why isn't my label configuring correctly? | <p>I want this label to configure into the text entry after the user enters the text and hits go but the label isn't configuring.</p>
<p>I want the label that says "Hello!" to change into whatever is put in the main entry. I'm looking for an answer written in full code instead of one fixed line.</p>
<p>Here's... | <p>1.Split <code>tk.Label</code> and <code>pack()</code>.</p>
<p>2.Pass the lable.</p>
<pre><code> import tkinter as tk
root = tk.Tk()
root.attributes('-fullscreen', True)
exit_button = tk.Button(root, text="Exit", command = root.destroy)
exit_button.place(x=1506, y=0)
... | python|python-3.x|tkinter|pycharm | 0 |
791 | 48,255,267 | How do I print a local tensor in tensorflow? | <p>I want to print a tensor in my program to see its internal values once it gets evaluated. The problem, however, is that the tensor being declared inside a function. To understand my problem better, here is some example code to better explain what it is I want to do:</p>
<pre><code>a = tf.Variable([[2,3,4], [5,6,7]]... | <p>This will achieve what you want to do:</p>
<pre><code>with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(d))
</code></pre>
<p>Alternatively, you could replace the last line with:</p>
<pre><code>print(sess.run(tf.get_default_graph().get_tensor_by_name('tfdiv/c:0')))
</cod... | python|debugging|variables|tensorflow|local | 2 |
792 | 48,245,809 | How to build a content-based recommender system that uses multiple attributes? | <p>I want to build a content-based recommender system in Python that uses multiple attributes to decide whether two items are similar. In my case, the "items" are packages hosted by the C# package manager (<a href="https://www.nuget.org/packages/EntityFramework" rel="nofollow noreferrer">example</a>) that have various ... | <p>For some context, my work with content-based recommenders has revolved primarily around raw text and categorical data/features. Here's a high-level approach I've taken that has worked out nicely and is pretty simple to implement.</p>
<p>Suppose I have three feature columns that I can potentially use to make recomme... | python|pandas|machine-learning|scikit-learn|recommendation-system | 6 |
793 | 73,548,977 | How to convert voltage (or frequency) floating number read backs to mV (or kHz)? | <p>I am successfully able to read back data from an instrument:</p>
<ul>
<li><p>When the read back is a voltage, I typically read back values such as <code>5.34e-02</code> Volts.</p>
</li>
<li><p>When the read back is frequency, I typically read values like <code>2.95e+04</code>or <code>1.49e+05</code> with units Hz.</... | <p>Well, to convert volts to millivolts, you multiply by 1000. To convert Hz to kHz, you divide by 1000.</p>
<pre><code>>>> reading = 5.34e-02
>>> millivolts = reading * 1000
>>> print(millivolts)
53.400000000000006
>>> hz = 2.95e+04
>>> khz = hz /1000
>>> khz
29.5... | python|floating-point|number-formatting|pyvisa | 2 |
794 | 69,924,897 | How to get the div before a specific div with css selector | <p>There is probably a better way to do this, but I just need this to work for now before I can come up with a better solution.
Im working on a webscraping application with Python and BeautifulSoup. I need to grab a specific div, but the placement of that div changes slightly on different pages (sometimes its the 3rd, ... | <p>Find specific <code>div</code> using <code>id</code> or <code>class</code> and call <code>find_previous()</code> to get appropriate tag</p>
<pre><code>html="""<div id="main-container">
<div></div>
<div></div>
<div>The div I want</div>
... | python|html|css|web-scraping|beautifulsoup | 0 |
795 | 73,451,375 | scrape sports reference table | <p>I have tried the following script to make to grab the table on the webpage.</p>
<pre><code>from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.sports-reference.com/cfb/play-index/rivals.cgi?request=1&school_id=penn-state&opp_id=purdue'
headers = {'User-Agent':
'Mozilla/5.0 (X11... | <p>The desired table data is under html comment. By removing the comment,you can extract the table data using pandas only.</p>
<pre><code>import pandas as pd
import requests
from bs4 import BeautifulSoup
url= 'https://www.sports-reference.com/cfb/play-index/rivals.cgi?request=1&school_id=penn-state&opp_id=purd... | python-3.x|pandas|beautifulsoup | 3 |
796 | 73,267,048 | Can't import a class from a python package | <p>I created a private python package with this structure:</p>
<pre><code> python_package
utils
__init__.py
module1.py
module2.py
</code></pre>
<p>And inside the module1.py file there is a class <code>Class1</code></p>
<p>Now when I download this package in another project using p... | <p>try this if you are not able to access the class directly</p>
<pre><code>import filename
object=filename.class1()
</code></pre> | python|class|package | 1 |
797 | 64,830,998 | Adding an increment to duplicates within a python dataframe | <p>I'm looking to concatenate two columns in data frame and, where there are duplicates, append an integer number at the end. The wrinkle here is that I will keep receiving feeds of data and the increment needs to be aware of historical values that were generated and not reuse them.</p>
<p>I've been trying to do this w... | <p>I'm not completely sure what you want to achieve, but you can update <code>blacklist</code> in the process. <code>blacklist</code> is just a pointer to the actual list data. If you slightly modify <code>gen_summary</code> by adding <code>blacklist.append(summary)</code> before the <code>return</code> statement</p>
<... | python|python-3.x|pandas|dataframe | 0 |
798 | 63,820,615 | Can I optimize this code with an array for it to work on 100 pages in a single loop? | <p>I'm fairly new in writing code in Python. I'm trying website parser with Beautiful Soup and it works fine.
I need guidance in making my code more optimized because I need to parse 100 pages of a single website one by one, and wanted to do it with a single loop + array of pages.
Pages change just by numbers like: <a ... | <p>You can make a loop there like this:</p>
<pre><code>for i in range(1, 101): #goes from 1-100
url = f"https://www.example.com/cat?page{i}" #page1 etc.
urlpage= urlopen(url).read()
bswebpage=BeautifulSoup(urlpage)
results=bswebpage.findAll("div",{'class':"someDiv"})
fo... | python|arrays | 0 |
799 | 52,995,053 | Python 3 inheritance multiple classes with __str__ | <p>How do I use multiple <code>__str__</code> from other classes? For example:</p>
<pre class="lang-py prettyprint-override"><code>class A:
def __str__(self):
return "this"
class B:
def __str__(self):
return "that"
class C(A,B):
def __str__(self):
return super(C, self).__str__() +... | <p>With multiple inheritance, <code>super()</code> searches for the <em>first</em> class that has the attribute, as they appear, from left to right. So, it will stop at <code>A</code>. You can access all the parent classes with the special <code>__bases__</code> attribute, and loop over them, calling <code>str</code> o... | python|string|python-3.x|class|inheritance | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.