title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
SQLAlchemy seems to commit within unittests | 38,164,893 | <pre><code>def fixture(self, name):
...
user = User(123)
user.first_name = 'Houman'
db.session.add(user)
db.session.commit()
return news_list, user
def test_update(self):
with app.app_context():
news_list, user = self.fixture('/topnews_id.json')
... | 0 | 2016-07-02T22:14:29Z | 38,165,123 | <p>This is expected as SQLAlchemy will return any value stored on memory, SQLAlchemy is intelligent in that don't do a commit to the database every time you do something.</p>
| 2 | 2016-07-02T22:54:23Z | [
"python",
"sqlalchemy"
] |
Append my python script to work on the web? | 38,164,975 | <p>I just finished building a python script that I would like to deploy for my company on the web, however, I have no knowledge on how to do so unfortunately. If someone could help me it would be much appreciated. I've been looking around at Django and Flask but can't seem to understand it well enough.</p>
<p>What my ... | 0 | 2016-07-02T22:28:59Z | 38,165,095 | <p>What you need is Flask.</p>
<p>You need to take the meat of your script and wrap it around a function that Flask will call when the user visit a given URL on your company's website. I haven't debugged this code so it may contain errors but you will get the idea:</p>
<pre><code>from flask import Flask
from myscript... | 2 | 2016-07-02T22:49:16Z | [
"python"
] |
How can I store already aggregated by time samples in influxdb? | 38,164,976 | <p>I collecting metrics samples from 'clients' in agregated by the time interval format like e.g:
<code>
{ 'interval': 19:50-19:55, 'hits': 55, 'missed': 45}
{ 'interval': 19:55-20:00, 'hits': 23, 'missed': 15}
</code>
How can I store and use it in influxdb? I looked examples of influxdb usage and notice that always us... | 0 | 2016-07-02T22:29:02Z | 38,212,500 | <p>one work-around would be store the starting time point as time stamp, and the duration of the interval as a value. If you intervals are all evenly-spaced and continuous, there's probably no need to store the duration at all.</p>
| 1 | 2016-07-05T20:51:53Z | [
"python",
"metrics",
"influxdb",
"grafana"
] |
Reading json object from serial port | 38,165,017 | <p>I want to use ijson to read an object from a serial port. I can read from the port fine, and I can use ijson to deserialize an object from a stream, but using ijson from a serial port just isn't enumerating anything.</p>
<p>This is an example of my code:</p>
<pre><code> self.serial_port = serial.Serial(
... | 0 | 2016-07-02T22:35:52Z | 38,165,288 | <p>Try doing:</p>
<pre><code>import ijson
import sys
for x in ijson.parse(sys.stdin):
print(x)
</code></pre>
<p>You can type in json but nothing will print out until you press Ctrl-D twice to signal the end of stdin.</p>
<p>I haven't tested it, but I suspect that something similar is happening with your serial p... | 1 | 2016-07-02T23:21:19Z | [
"python",
"json"
] |
Reading json object from serial port | 38,165,017 | <p>I want to use ijson to read an object from a serial port. I can read from the port fine, and I can use ijson to deserialize an object from a stream, but using ijson from a serial port just isn't enumerating anything.</p>
<p>This is an example of my code:</p>
<pre><code> self.serial_port = serial.Serial(
... | 0 | 2016-07-02T22:35:52Z | 38,165,633 | <p>Ok, I figured it out. You have to set the buffer size to 1.
So, this works...</p>
<pre><code>objects = ijson.common.items(ijson.parse(self.serial_port, buf_size=1), 'item')
for o in objects:
print `o`
</code></pre>
<p>My goal was to be able to receive an endless stream of objects. I signal the start of... | 0 | 2016-07-03T00:23:04Z | [
"python",
"json"
] |
Python: Changing the speed of sound during playback | 38,165,103 | <p>This is my first post. Is it possible to change the speed of a playback during playback? I want to simulate a car engine sound and for this the first step is to change the speed of a looped sample according to the RPM of the engine. I know how to increase the speed of a complete sample using pyaudio by changing the ... | 1 | 2016-07-02T22:49:58Z | 38,171,233 | <p>You should be able to do something with numpy. I'm not really familiar with wave etc. and I would expect your play() method to include a readframes() inside the loop in some way (as I attemp to do here) but you can probably get the idea from this</p>
<pre><code>def play(self):
""" Play entire file """
x0 = ... | 1 | 2016-07-03T15:02:57Z | [
"python",
"audio",
"audio-processing",
"pitch"
] |
arguments not being passed through render() argument after * must be an iterable, not pygame.Surface | 38,165,126 | <p>I'm trying to work with pygame and am attempting to create a class like so.</p>
<pre><code>import pygame
from threading import Thread
gameExit = True
class states:
def __init__(self):
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('test')
clock = pygame... | 0 | 2016-07-02T22:55:08Z | 38,165,161 | <p>The issue has to do with the <code>args</code> you're passing to your <code>Thread</code> constructors. The expression <code>(gameDisplay)</code> is a simple reference to the <code>Surface</code> object bound to <code>gameDisplay</code>, not a 1-tuple which I suspect you inteded. You need an extra comma at the end o... | 1 | 2016-07-02T23:00:07Z | [
"python",
"class"
] |
ADXL345 Accelerometer data output conversion | 38,165,136 | <p>I'm using a Synapse wireless module which has a ATMEL ATmega128 on it. I've connected a ADXL345 3 axis accelerometer to it and I'm communicating with it via I2C. The Synapse module uses a subset of python as the scripting language.</p>
<p>When I read the XYZ data I get back an array of 6 bytes.
EC FF EF FF 14 01</... | 0 | 2016-07-02T22:56:24Z | 38,166,077 | <p>I'm not sure what you're doing with <code>ord()</code> there... <code>ord(c)</code> takes <code>c</code>, a single character, and outputs its ASCII character code.</p>
<p>Either way, to convert a number whose representation is in two's complement to a signed integer in Python, one would do something like this:</p>... | 0 | 2016-07-03T01:59:30Z | [
"python",
"accelerometer"
] |
Syntax error at end of if statement | 38,165,173 | <p>When I run this code, I get a syntax error at the : symbol in the following line ==>
if (total_size != ((len(fleet_grid)*len(fleet_grid[0])-total_size)):</p>
<p>Why is that?</p>
<pre><code>def validate_character_count(fleet_grid, ship_characters, ship_sizes):
"""(list of list of str, list of str, list of int) ->... | -5 | 2016-07-02T23:01:46Z | 38,165,198 | <p>possibly missing closing ')' ?
you have 5 '(' but 4 of ')'</p>
| 0 | 2016-07-02T23:06:30Z | [
"python",
"syntax",
"syntax-error"
] |
Syntax error at end of if statement | 38,165,173 | <p>When I run this code, I get a syntax error at the : symbol in the following line ==>
if (total_size != ((len(fleet_grid)*len(fleet_grid[0])-total_size)):</p>
<p>Why is that?</p>
<pre><code>def validate_character_count(fleet_grid, ship_characters, ship_sizes):
"""(list of list of str, list of str, list of int) ->... | -5 | 2016-07-02T23:01:46Z | 38,165,199 | <p>That would be because there is an extra pair of opening braces in the statement</p>
<pre><code>if (total_size != ((len(fleet_grid)*len(fleet_grid[0])-total_size)):
</code></pre>
<p>Here, you have two (( before len.</p>
| 0 | 2016-07-02T23:06:43Z | [
"python",
"syntax",
"syntax-error"
] |
Syntax error at end of if statement | 38,165,173 | <p>When I run this code, I get a syntax error at the : symbol in the following line ==>
if (total_size != ((len(fleet_grid)*len(fleet_grid[0])-total_size)):</p>
<p>Why is that?</p>
<pre><code>def validate_character_count(fleet_grid, ship_characters, ship_sizes):
"""(list of list of str, list of str, list of int) ->... | -5 | 2016-07-02T23:01:46Z | 38,165,320 | <p>Missing closing ')'. I recommend you to read the output when you run the program. Preferably in <code>ipython</code>
If you write something like that: <code>if(some_variable:</code></p>
<p>The output will be
<code>
In [8]: File "your_file.py", line 13
if(some_variable:
^
SyntaxError: inval... | 0 | 2016-07-02T23:27:16Z | [
"python",
"syntax",
"syntax-error"
] |
Scapy Sniff() - Device Is A NoneType | 38,165,178 | <p>So I'm trying to get scapy to work on my windows computer. After a lot of work I finally was able to load the library without any errors. However when I call the function <code>sniff(count=1)</code> I get an error. It seems that a variable called "device" is getting the value <code>None</code>. Here is the error :</... | 1 | 2016-07-02T23:02:59Z | 38,170,451 | <p>After downloading the new development version and tinkering around with the timeouts of some of the powershell commands I fixed it! Guess it was just a bug with the old version. Scapy doesn't have the best Windows support.</p>
| 0 | 2016-07-03T13:33:14Z | [
"python",
"python-3.x",
"scapy",
"packet-sniffers"
] |
Vectorization of raw values to features using Tensorflow Learn (TFLearn) | 38,165,267 | <p>TFLearn <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard1/tf.contrib.learn.LinearClassifier.md" rel="nofollow">has a number of useful utilities</a> for training linear estimators which can make derivative feature columns, however I'd really li... | 1 | 2016-07-02T23:18:26Z | 38,298,253 | <p>Some related and useful methods can be found in its super parent class <code>_DNNLinearCombinedBaseEstimator</code>. </p>
<p>For example, <code>_get_linear_feature_columns</code>, <code>_get_dnn_feature_columns</code>, <code>dnn_weights_</code>, <code>dnn_bias_</code>, <code>linear_bias_</code>, <code>linear_weight... | 0 | 2016-07-11T02:14:18Z | [
"python",
"tensorflow"
] |
sklearn.metrics.precision_recall_curve: Why are the precision and recall returned arrays instead of single values | 38,165,273 | <p>I am calculating the precisions and recall for off-the-shelf algorithms on a dataset that I recently prepared. </p>
<p>It is a binary classification problem and I am looking to calculate the precision, recall and the f-scores for each of the classifier I built. </p>
<pre><code>test_x, test_y, predics, pred_prob,sc... | 1 | 2016-07-02T23:18:57Z | 39,324,229 | <p>In a binary classification problem, pred_prob is the probability of the instance being in each of the classes, so actually the predicted value (classes) depends on this probability and one more value called threshold. All instances with pred_prob bigger than the threshold is classified into one class, and smaller in... | 0 | 2016-09-05T05:06:36Z | [
"python",
"machine-learning",
"scikit-learn",
"precision-recall"
] |
Can't connect to mysql using python's mysql.connector | 38,165,290 | <p>I'm using a Mac (OS 10.10.5), PyCharm, Python 3.5 and MySQL. MySQL has been working with PHP on the same machine. I'm trying to connect to it using Python and getting the error message:
<code>enter code here</code>2003: Can't connect to MySQL server on 'localhost::3306' (8 nodename nor servname provided, or not know... | 0 | 2016-07-02T23:21:37Z | 38,165,312 | <p>You have a colon where there shouldn't be one:</p>
<pre><code>host="localhost:" # remove the : -> host="localhost"
</code></pre>
<p><code>127.0.0.1::3306</code> is not the same as <code>127.0.0.1:3306</code></p>
| 0 | 2016-07-02T23:26:14Z | [
"python",
"mysql"
] |
Can't connect to mysql using python's mysql.connector | 38,165,290 | <p>I'm using a Mac (OS 10.10.5), PyCharm, Python 3.5 and MySQL. MySQL has been working with PHP on the same machine. I'm trying to connect to it using Python and getting the error message:
<code>enter code here</code>2003: Can't connect to MySQL server on 'localhost::3306' (8 nodename nor servname provided, or not know... | 0 | 2016-07-02T23:21:37Z | 39,418,358 | <p>There are somethings I make out from your code.</p>
<ol>
<li>we can provide <code>host="localhost"</code> no semicolons. or we can provide a host/server value like <code>'host':'127.0.0.1:<port name>'</code></li>
<li>Check your port again to connect the database</li>
<li>We should always close the connection ... | 0 | 2016-09-09T19:17:22Z | [
"python",
"mysql"
] |
How to convert an adjacency matrix to an adjacency list with python? | 38,165,292 | <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>... | -3 | 2016-07-02T23:21:58Z | 38,165,410 | <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... | 1 | 2016-07-02T23:41:38Z | [
"python",
"python-3.x",
"matrix",
"adjacency-list",
"adjacency-matrix"
] |
AttributeError: 'Module' object has no attribute 'init' | 38,165,405 | <pre><code>import pygame
pygame.init()
</code></pre>
<p>I get this error</p>
<pre><code>File "C:/Python34/game1.py", line 2, in <module>
pygame.init()
AttributeError: 'Module' object has no attribute 'init'
</code></pre>
<p>Can't post code so here is an image
<a href="https://s31.postimg.org/retln74zf/i... | -2 | 2016-07-02T23:40:49Z | 38,165,542 | <p>Do the following substitution, and follow the idea all along your code:</p>
<pre><code>import pygame
pgame = pygame.init()
gameDisplay = pgame.display.set_mode((800,600))
</code></pre>
| 0 | 2016-07-03T00:04:17Z | [
"python"
] |
AttributeError: 'Module' object has no attribute 'init' | 38,165,405 | <pre><code>import pygame
pygame.init()
</code></pre>
<p>I get this error</p>
<pre><code>File "C:/Python34/game1.py", line 2, in <module>
pygame.init()
AttributeError: 'Module' object has no attribute 'init'
</code></pre>
<p>Can't post code so here is an image
<a href="https://s31.postimg.org/retln74zf/i... | -2 | 2016-07-02T23:40:49Z | 38,165,980 | <p>I'm not sure what Felipe is on about. <code>pygame.init()</code> returns a 2tuple of <code>(int, int)</code>, depending on the amount of successful and unsuccessful module initialisations. It doesn't return anything that has pygame methods or modules on it.</p>
<p>Also, his comment about adding <code>init.py</cod... | 0 | 2016-07-03T01:40:12Z | [
"python"
] |
How to make QLineEdit-QCompleter upperlines automatically | 38,165,425 | <p>I have a list of texts, if the user search for a text in QLineEdit, I print the text. There is a QCompleter in QLineEdit.</p>
<p>The problem is, as we know <code>Text</code> and <code>text</code> are not same, but it's same to the user. So If user starts typing <code>Text</code> or <code>text</code>, I want to chan... | 0 | 2016-07-02T23:44:41Z | 38,165,734 | <p>The <code>QCompleter</code> widget has a <code>setCaseSensitivity</code> property that takes a <code>QtCore.Qt.CaseSensitive</code> / <code>QtCore.Qt.CaseInsensitive</code> or simply a 1 or 0 (<a href="http://doc.qt.io/qt-4.8/qt.html#CaseSensitivity-enum" rel="nofollow">docs</a>). </p>
<p><a href="http://doc.qt.io/... | 1 | 2016-07-03T00:44:08Z | [
"python",
"python-3.4",
"pyqt5",
"qlineedit",
"qcompleter"
] |
QT designer didn't install uic program for view the code from the application | 38,165,430 | <p>i installed Qt designer 4, created a small windows with buttons, now when i click view code...</p>
<p>i get the message</p>
<pre><code>unable to lunch C:Python27/Lib/site-packages/PyQt4\uic.
</code></pre>
<p>i check the folder and i dont see any uic files, i have a uic folder with bunch of python files, want t... | 0 | 2016-07-02T23:45:17Z | 38,165,698 | <p>I don't know what you mean with "when I click view code". So I'm answering two questions.</p>
<p>How do I preview the window in Qt Designer?
Eiter press "Ctrl+R" or in the menu bar navigate to "Form -> Preview..."</p>
<p>How do I use the ui file within a python script?
You need to compile your ui file to a python ... | 0 | 2016-07-03T00:36:14Z | [
"python",
"c++",
"qt",
"user-interface",
"pyqt4"
] |
Pygame Ellipse change color to collide | 38,165,492 | <p>I have a class that ball bounces when it hits the limits of the screen</p>
<p>I am Attempted programming ballchange my color when the collision with the limits, but this does not change color, stays with color_default values and not change, I'm missing?</p>
<p>Here is the code:</p>
<pre><code>from pygame.sprite i... | 0 | 2016-07-02T23:54:35Z | 38,165,950 | <p>Your <code>.draw()</code> function is only drawing the ball with a different colour while it's outside of the bounds of the display, which is never. What you instead want, is within your <code>.check_collisions()</code>, if a collision is detected, set a property on <code>self</code> determining which colour to use... | 1 | 2016-07-03T01:31:58Z | [
"python",
"pygame"
] |
Multiprocessing pool example (parallel) is slower than sequential. Trying to understand pool in python | 38,165,552 | <p>I have been reading and trying to understand how to run python faster with multiprocessing. I found this example: <a href="http://stackoverflow.com/questions/4413821/multiprocessing-pool-example">multiprocessing.Pool example</a>. </p>
<p>I then made up this test and ran in a server with 8 cores. </p>
<pre><code>im... | 2 | 2016-07-03T00:06:53Z | 38,165,597 | <p>You're not doing anything wrong, except <em>perhaps</em> running more processes than you have physical cores to run them on - can't guess from here whether you <em>have</em> at least 8 cores available to run the 8 processes you created.</p>
<p>But even if you do, the time taken to compute one <code>f(x)</code> resu... | 2 | 2016-07-03T00:16:02Z | [
"python",
"performance",
"multiprocessing"
] |
Assigning column names in a txt file in python | 38,165,636 | <p>I have the following code that extracts needed data from a xml file. I can save it to terminal, and open it with no problem. I am in trouble inserting column names to the txt file, however. I have been searching the answer but found no right solution. Would anyone help me here? Thank you!!</p>
<pre><code>import sys... | 0 | 2016-07-03T00:23:41Z | 38,165,919 | <p>The way to write data to a file in Python is to call <code>.write(content)</code> on the file object, not to redirect stdout to it.</p>
<p>Instead of all your lines messing with <code>sys.stdout</code>, try this:</p>
<pre><code>f = open("file.txt", "w") # Open the file in (w)rite mode
f.write("programID,Season\n... | 0 | 2016-07-03T01:24:13Z | [
"python",
"multiple-columns"
] |
Scrape a specific h2 tag inside a div class | 38,165,673 | <p>I am trying to scrape the emojis inside the h2 tag 'Events' from <a href="http://emojipedia.org/food-drink/" rel="nofollow">http://emojipedia.org/food-drink/</a>. I have written the following code, but the head_links is an empty list:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import json
import ... | 0 | 2016-07-03T00:31:28Z | 38,165,899 | <p>The thing you're looking for isn't actually an <code>h2</code> tag with the class <code>Events</code>, you're looking for a <code>div</code> tag that contains an <code>h2</code> tag whose <em>content</em> is "Events".</p>
<p>This should get you started:</p>
<pre><code>div_contents = soup2.find('h2', text='Events')... | 2 | 2016-07-03T01:18:51Z | [
"python",
"web-scraping",
"beautifulsoup",
"emoji"
] |
How do I convert a string into code in Python? | 38,165,708 | <h1>Converting a string to code</h1>
<h3>Noteworthy points:</h3>
<ul>
<li>I'm new to coding and am testing various things to learn;</li>
<li>i.e. yes, I'm sure there are better ways do achieve what I am trying to do; </li>
<li>I would like to know any alternative / more efficient methods, however; </li>
<li>I would... | 3 | 2016-07-03T00:38:03Z | 38,165,787 | <pre><code>string = []
for i in (london.columns.values):
string.append(london[i].isnull())
london[0<sum(string)]
</code></pre>
<p>Since you will have only 1 and 0 and you are looking for at least one 1 then you can just add 1,0's to your list then sum them. if the sum is more than one your if will turn 1 otherw... | 2 | 2016-07-03T00:53:39Z | [
"python",
"string",
"pandas"
] |
How do I convert a string into code in Python? | 38,165,708 | <h1>Converting a string to code</h1>
<h3>Noteworthy points:</h3>
<ul>
<li>I'm new to coding and am testing various things to learn;</li>
<li>i.e. yes, I'm sure there are better ways do achieve what I am trying to do; </li>
<li>I would like to know any alternative / more efficient methods, however; </li>
<li>I would... | 3 | 2016-07-03T00:38:03Z | 38,165,861 | <p>This is the easiest way to select the <code>rows</code> in your dataframe with <code>NaN</code> values:</p>
<pre><code>df[pd.isnull(df).any(axis=1)]
</code></pre>
| 4 | 2016-07-03T01:09:55Z | [
"python",
"string",
"pandas"
] |
ImportError: cannot import name pubnub | 38,165,720 | <p>i have problem with pubhub module in python 2.7.6. </p>
<p>I've installed by <code>sudo pip install pubnub</code></p>
<p>Output: </p>
<pre><code>>>> import pubnub
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pubnub.py", line 3, in <module>
from pu... | 0 | 2016-07-03T00:40:46Z | 38,165,767 | <p>You have a file in your project called <code>pubnub.py</code>, which the importer is finding before your installation of the pubnub module, I think. Rename your file to something else, and everything should work.</p>
| 1 | 2016-07-03T00:50:27Z | [
"python",
"pubnub"
] |
ImportError: cannot import name pubnub | 38,165,720 | <p>i have problem with pubhub module in python 2.7.6. </p>
<p>I've installed by <code>sudo pip install pubnub</code></p>
<p>Output: </p>
<pre><code>>>> import pubnub
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pubnub.py", line 3, in <module>
from pu... | 0 | 2016-07-03T00:40:46Z | 38,167,769 | <p>I renamed file, removed python3(it was installed still :D), and removed every *.pyc files and it is working for now. Thanks</p>
| 1 | 2016-07-03T07:42:39Z | [
"python",
"pubnub"
] |
python 3.5.2 is giving an error 'object does not take any parameter',is there something wrong with my code?i expected my code to run,below is my code | 38,165,732 | <pre><code>from tkinter import*
class ListButtons(object):
def _init_(self,master):
frame = frame(master)
frame.pack()
self.printButton = Button(frame,text = 'print button',command = printMessage)
self.printButton.pack( side = LEFT)
self.quitButton =Button(frame,text = 'ex... | 0 | 2016-07-03T00:43:46Z | 38,165,794 | <p>You are missing the double underscore for the constructor of your class, with your code the compiler thinks it's just any ordinary method (no name mangling). See this post for more info:</p>
<p><a href="http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-... | 1 | 2016-07-03T00:54:19Z | [
"python"
] |
get multiindex value based on row number in Pandas | 38,165,763 | <p>Is there any way to retieve the multiindex value based on the row number?
Like can I use <code>.iloc[0]</code> to retrieve somehow the value of the multiindex in an array form?</p>
<p>For example I have a multiindex [month, day, hour]. Can i use iloc[numRow] and get for exmple (1,1,1) being the multiindex values mo... | 2 | 2016-07-03T00:49:41Z | 38,166,159 | <p>How about:</p>
<pre><code>df.index[numRow]
</code></pre>
<p>(You can always use integer-based slicing on <code>Index</code> objects...)</p>
| 1 | 2016-07-03T02:16:18Z | [
"python",
"pandas"
] |
config file with a dictionary using python | 38,165,792 | <p>So I am trying to use a dictionary inside a config file to store a report name to an API call. So something like this:</p>
<pre><code>report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
</code></pre>
<p>I need to store multiple reports:apicalls to one config value. I am using ConfigOb... | 1 | 2016-07-03T00:54:14Z | 38,165,900 | <p>Your config file <code>settings.ini</code> should be in following format:</p>
<pre><code>[report]
/report1 = /https://apicall...
/report2 = /https://apicall...
</code></pre>
<hr>
<pre><code>from configobj import ConfigObj
config = ConfigObj('settings.ini')
for report, url in config['report'].items():
print r... | 1 | 2016-07-03T01:19:08Z | [
"python",
"python-2.7",
"dictionary",
"config",
"configobj"
] |
config file with a dictionary using python | 38,165,792 | <p>So I am trying to use a dictionary inside a config file to store a report name to an API call. So something like this:</p>
<pre><code>report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
</code></pre>
<p>I need to store multiple reports:apicalls to one config value. I am using ConfigOb... | 1 | 2016-07-03T00:54:14Z | 38,166,116 | <p>This config file used as input is fine:</p>
<pre><code>report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
</code></pre>
<p>This config file used as input </p>
<pre><code>flag = true
report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
</code></pre>
<p>gener... | 1 | 2016-07-03T02:08:36Z | [
"python",
"python-2.7",
"dictionary",
"config",
"configobj"
] |
config file with a dictionary using python | 38,165,792 | <p>So I am trying to use a dictionary inside a config file to store a report name to an API call. So something like this:</p>
<pre><code>report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
</code></pre>
<p>I need to store multiple reports:apicalls to one config value. I am using ConfigOb... | 1 | 2016-07-03T00:54:14Z | 38,166,374 | <p>If you're not obligated to use <code>INI</code> files, you might consider using another file format more suitable to handle <code>dict</code>-like objects. Looking at the example file you gave, you could use <code>JSON</code> files, Python has a <a href="https://docs.python.org/2/library/json.html" rel="nofollow">bu... | 0 | 2016-07-03T03:04:58Z | [
"python",
"python-2.7",
"dictionary",
"config",
"configobj"
] |
creating new tuple with index i from each list of list | 38,165,922 | <p>I have below list of list called mylist and I want to take first element from each list and create a tuple. I want to do this for all n elements from list of list.</p>
<pre><code>mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]
</code></pre>
<p>convert to</p>
<pre><code>mytuple = ((1,'a', 5, 100) ,... | 1 | 2016-07-03T01:25:14Z | 38,165,930 | <p><a href="https://docs.python.org/2/library/functions#zip" rel="nofollow"><code>zip</code></a> is what you need:</p>
<pre><code>>>> mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]
>>> zip(*mylist) # In Python 3.x, this returns an iterator instead of a list
[(1, 'a', 5, 100), (2, 'b... | 3 | 2016-07-03T01:26:40Z | [
"python",
"list",
"tuples",
"list-comprehension"
] |
creating new tuple with index i from each list of list | 38,165,922 | <p>I have below list of list called mylist and I want to take first element from each list and create a tuple. I want to do this for all n elements from list of list.</p>
<pre><code>mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]
</code></pre>
<p>convert to</p>
<pre><code>mytuple = ((1,'a', 5, 100) ,... | 1 | 2016-07-03T01:25:14Z | 38,165,951 | <p>You could use pandas data frame for this.</p>
<pre><code>import pandas as pd
mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]
df = pd.DataFrame(mylist).transpose()
print(df.values)
array([[1, 'a', 5, 100],
[2, 'b', 8, 200],
[3, 'c', 10, 30]], dtype=object)
</code></pre>
<p>For solut... | 1 | 2016-07-03T01:32:16Z | [
"python",
"list",
"tuples",
"list-comprehension"
] |
How to capture division in SQL query | 38,165,936 | <p>I want to capture division whenever they occur in sql query.</p>
<p>so I suppose regex should work</p>
<pre><code>(s+)\/(s+)
</code></pre>
<p>Test is </p>
<pre><code>a/b = b/d and c/e is not equal to b/e
</code></pre>
<p>I used it at <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a> but it seem... | 0 | 2016-07-03T01:27:38Z | 38,165,943 | <ul>
<li>Use <code>\S</code> to match non-space, not <code>\s</code>. Seems you missed backslash.</li>
<li>You don't need to escape <code>/</code> in Python regular expression.</li>
</ul>
<hr>
<pre><code>>>> re.findall(r'(\S+)/(\S+)', 'a/b = b/d and c/e is not equal to b/e')
[('a', 'b'), ('b', 'd'), ('c', 'e... | 0 | 2016-07-03T01:29:39Z | [
"python",
"regex"
] |
how to send data from a python file to html file that are in a separate projects via a url (not having html as a template) | 38,165,993 | <p>how to send data from a python file to html file that has a js code that are in a separate projects via a url (not having html as a template) and vice versa?</p>
<p>i think i need to use AJAX function and json object but I don't know how.</p>
| -1 | 2016-07-03T01:42:39Z | 38,166,398 | <p>You'll want to encode your data as JSON (or something else, but JSON is the easiest) within your Python function, then make that Python function visible visible to the web via something like <a href="http://flask.pocoo.org/" rel="nofollow">Flask</a>, and, as you correctly surmised, pull the data with AJAX in javascr... | 0 | 2016-07-03T03:11:35Z | [
"javascript",
"python",
"html",
"ajax",
"django"
] |
Converting words with String upper() does not work for certain letters? | 38,165,995 | <p>Hello guys I hope you can help me with this problem, I've have hours trying to solve it</p>
<p>Using this code:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: utf-8 -*-
frase = 'La canción de la piña'
print frase.upper()
</code></pre>
<p>I just get "LA CANCIóN DE LA PIñA", the problem is that it does not m... | 5 | 2016-07-03T01:43:14Z | 38,166,008 | <p>Use unicode literal (string literal with leading <code>u</code>) to represent unicode string:</p>
<pre><code>>>> frase = u'La canción de la piña'
>>> print frase.upper()
LA CANCIÃN DE LA PIÃA
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Adding following line at the beginning of the file e... | 6 | 2016-07-03T01:45:33Z | [
"python",
"python-2.7",
"unicode"
] |
Converting words with String upper() does not work for certain letters? | 38,165,995 | <p>Hello guys I hope you can help me with this problem, I've have hours trying to solve it</p>
<p>Using this code:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: utf-8 -*-
frase = 'La canción de la piña'
print frase.upper()
</code></pre>
<p>I just get "LA CANCIóN DE LA PIñA", the problem is that it does not m... | 5 | 2016-07-03T01:43:14Z | 38,166,935 | <p>Unicode Literal:</p>
<p>Try this:</p>
<p>frase = u'La canción de la piña'</p>
| 0 | 2016-07-03T05:10:02Z | [
"python",
"python-2.7",
"unicode"
] |
Making multiple tables based off another table? | 38,166,313 | <p>I have a number of columns that are in the format 'NameX(TypeY)'. The format is like so: </p>
<pre><code>total = pd.DataFrame(table):
NameA(Type1) NameA(Type2) NameA(Type3) NameB(Type1) NameB(Type2) NameB.(Type3)
set1 1 1 1 2 3 ... | 3 | 2016-07-03T02:51:00Z | 38,166,418 | <pre><code>from collections import defaultdict
dfs = defaultdict(pd.DataFrame)
for name_sample, series in df.iteritems():
name, sample = name_sample.split('.')
dfs[name][sample] = series
</code></pre>
<p>The above gives you a dict with one table per unique "Name":</p>
<pre><code> {'NameA': Sampl... | 1 | 2016-07-03T03:15:27Z | [
"python",
"python-3.x",
"pandas",
"filter"
] |
Making multiple tables based off another table? | 38,166,313 | <p>I have a number of columns that are in the format 'NameX(TypeY)'. The format is like so: </p>
<pre><code>total = pd.DataFrame(table):
NameA(Type1) NameA(Type2) NameA(Type3) NameB(Type1) NameB(Type2) NameB.(Type3)
set1 1 1 1 2 3 ... | 3 | 2016-07-03T02:51:00Z | 38,167,219 | <p>Try this:</p>
<p>For one:</p>
<pre><code>df2 = df.filter(like='NameA', axis=1).rename(columns=lambda x: x.replace('NameA', '').replace('(', '').replace(')', ''))
</code></pre>
<p>For List: </p>
<pre><code>Dflist = ['NameA','NameB' ]
DfDict = {}
for e in Dflist:
out = df.filter(like=e, axis=1).rename(colum... | 1 | 2016-07-03T06:09:25Z | [
"python",
"python-3.x",
"pandas",
"filter"
] |
Interpreting the output of SciPy's hierarchical clustering dendrogram? (maybe found a bug...) | 38,166,327 | <p>I am trying to figure out how the output of <code>scipy.cluster.hierarchy.dendrogram</code> works... I thought I knew how it worked and I was able to use the output to reconstruct the dendrogram but it seems as if I am not understanding it anymore or there is a bug in <code>Python 3</code>'s version of this module. ... | 3 | 2016-07-03T02:54:01Z | 38,170,751 | <p><code>icoord</code>, <code>dcoord</code> and <code>color_list</code> describe the <em>links</em>, not the leaves. <code>icoord</code> and <code>dcoord</code> give the coordinates of the "arches" (i.e. upside-down U or J shapes) for each link in a plot, and <code>color_list</code> is the color of those arches. In a... | 1 | 2016-07-03T14:07:08Z | [
"python",
"machine-learning",
"scipy",
"hierarchical-clustering",
"dendrogram"
] |
Where to host a python chat server? | 38,166,331 | <p>I wrote a python app that manage gcm messaging for an android chat app, where could I host this app to be able to work 24/7, <strong>it's not a web app</strong>, Is it safe and reliable to use PythonAnywhere consoles?</p>
| 0 | 2016-07-03T02:55:36Z | 38,166,349 | <p>I've not heard anything bad about PythonAnywhere, and their <a href="https://www.pythonanywhere.com/about/testimonials/" rel="nofollow">testimonials</a> page looks fairly reasonable, if devoid of megahuge company names.</p>
<p>If you're not convinced, try <a href="https://aws.amazon.com/ec2/" rel="nofollow">Amazon ... | 1 | 2016-07-03T03:00:18Z | [
"python",
"server",
"xmpp",
"host"
] |
Where to host a python chat server? | 38,166,331 | <p>I wrote a python app that manage gcm messaging for an android chat app, where could I host this app to be able to work 24/7, <strong>it's not a web app</strong>, Is it safe and reliable to use PythonAnywhere consoles?</p>
| 0 | 2016-07-03T02:55:36Z | 38,188,784 | <p>PythonAnywhere dev here: I wouldn't recommend our consoles as a place to run an XMPP server -- they're meant more for exploratory programming. AWS (like Adam Barnes suggests) or a VPS somewhere like Digital Ocean would probably be a better option.</p>
| 1 | 2016-07-04T16:09:53Z | [
"python",
"server",
"xmpp",
"host"
] |
multiple urwid calls getting terminal size leaves files open | 38,166,385 | <p>If I make the following call:</p>
<pre><code>from urwid import raw_display
cols, rows = raw_display.Screen().get_cols_rows()
</code></pre>
<p>... a file descriptor is left open. Making multiple calls to this function crashes the Python 3 Interpreter; especially if done like I was doing previously:</p>
<pre><code>... | 1 | 2016-07-03T03:08:19Z | 38,166,423 | <p>Create <code>raw_display.Screen()</code> only once.</p>
<p>One way to do it is using default paramter; it's evaluated only once - when the function/lambda is defined:</p>
<pre><code>size = lambda rows=True, scr=raw_display.Screen(): scr.get_cols_rows()[rows]
</code></pre>
| 1 | 2016-07-03T03:16:06Z | [
"python",
"linux",
"python-3.x",
"file-descriptor",
"urwid"
] |
PyQt Application Frozen Screen on Linux, fine on Windows | 38,166,420 | <p>I have been writing a PyQt Application on Windows for awhile, and I wanted to see if it would run properly on Linux. The gui application is basically a shell for a scientific toolkit meant to be used on the qtconsole/notebook. Both Linux and Windows systems are based on Anaconda 3.5, and running PyQt5. It works f... | 0 | 2016-07-03T03:15:51Z | 38,191,538 | <p>The general answer turned out to be that 2 QApplication event loops were being initialized.</p>
<p>The problem code turned out to be in a little module I have been using called <a href="https://github.com/asweigart/pyperclip" rel="nofollow">pyperclip</a> which was being imported first, and then I was instantiating ... | 0 | 2016-07-04T20:02:53Z | [
"python",
"linux",
"windows",
"pyqt",
"pyperclip"
] |
How does Python implement str[::-1]? | 38,166,449 | <p>Consider a python line:</p>
<pre><code>str[::-1]
</code></pre>
<p>I see it's very fast, and way more faster than some <strong>O(n)</strong> solution and also memory saving. What algorithm does Python use in this case?</p>
| 2 | 2016-07-03T03:23:04Z | 38,166,763 | <p>Hmm, have you tried any quick-and-dirty tests? Here is a first-pass:</p>
<pre><code>In [1]: import time
In [2]: def reverse_list_time(my_list):
...: start = time.time()
...: reversed = my_list[::-1]
...: stop = time.time()
...: return stop - start
...:
In [3]: reverse_list_time(li... | 3 | 2016-07-03T04:35:13Z | [
"python",
"slice",
"reverse"
] |
How does Python implement str[::-1]? | 38,166,449 | <p>Consider a python line:</p>
<pre><code>str[::-1]
</code></pre>
<p>I see it's very fast, and way more faster than some <strong>O(n)</strong> solution and also memory saving. What algorithm does Python use in this case?</p>
| 2 | 2016-07-03T03:23:04Z | 38,176,814 | <p>You can use Python's <a href="https://docs.python.org/2.7/library/dis.html#dis.dis" rel="nofollow"><code>dis.dis</code></a> module to disassemble <code>str[::-1]</code>:</p>
<pre><code>>>> import dis
>>> def reverse_(str_):
... return str_[::-1]
...
>>> dis.dis(reverse_)
6 ... | 1 | 2016-07-04T04:06:53Z | [
"python",
"slice",
"reverse"
] |
Python Split individual elements of list into smaller strings | 38,166,458 | <p>I am taking json and converting it to csv.</p>
<p>I might be way off in my approach to this problem, but I'm fairly new.</p>
<p>I am making api calls. </p>
<p>One api call returns 25 results.</p>
<p>If I just take the data I want, I am left with a 25 element list. One job result is one element.</p>
<p>But I nee... | 0 | 2016-07-03T03:24:58Z | 38,166,514 | <p>What you have is indeed a dictionary, not a list, since it consists of key : value pairs. Use Python's for loop to iterate through your dictionary:</p>
<pre><code>for k, v in clean_json.items():
... # do something with your data
</code></pre>
<p><code>clean_json.items()</code> returns a list of key : value pai... | 0 | 2016-07-03T03:38:01Z | [
"python"
] |
How to capture division and ignore when preceded by semicolon | 38,166,490 | <pre><code>pattern = r'(\S+)\s*(![;])/\s*(\S+)'
regex = re.compile(pattern,re.DOTALL)
for result in regex.findall(data):
f.write("Division" + str(result)+ "\n\n\n")
</code></pre>
<p>I am using following expression to capture when division is occurring but want to ignore when division symbol is preceded by ";" . T... | 0 | 2016-07-03T03:33:26Z | 38,166,513 | <p>Use <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">negative look-behind assertion</a>:</p>
<pre><code>pattern = r'(\S+)\s*(?<!;)/\s*(\S+)'
</code></pre>
<ul>
<li><code>(?<!;)/</code> will match <code>/</code> only if <code>/</code> is not preceded by <code>;</code></li>
</ul>
<... | 1 | 2016-07-03T03:37:59Z | [
"python",
"regex"
] |
Python socket connections have one second delay every 9 connections on Ubuntu 16.04 | 38,166,512 | <p>I'm running a data acquisition system on an Ubuntu 16.04 machine. It is deployed at a remote site, so my ability to change the physical configuration is limited. We do have someone on site who has been able to perform simple tests with the configuration.</p>
<p>We're running a python script to do data acquisition. ... | 2 | 2016-07-03T03:37:57Z | 38,191,584 | <p>Thank you for the helpful suggestions. In retrospect, tcpdump is the first thing I should have checked, so thank you Venkat for substituting in for my own judgement.</p>
<p>This appears to be a bug with the vendor software. Tcpdump showed that when running the python test, the device would preempt the handshake and... | 1 | 2016-07-04T20:06:14Z | [
"python",
"linux",
"sockets",
"ubuntu-16.04"
] |
Is there a way to have a mathematical function as the argument of a function in Python 3? | 38,166,547 | <p>Sorry if this is a easy question, or if it has already been answered, but I'm new to programming and I couldn't find a helpful answer to this question (maybe I don't know some terms that would've helped my search).</p>
<p>How can I include a mathematical function as an argument of a function in python?</p>
<p>In m... | 2 | 2016-07-03T03:47:15Z | 38,166,556 | <pre><code># Replace with whatever your function is
def func_x(x):
return x**2
def riemann_sum(func_x(3), minvalue, maxvalue, partitions)
...
return riemannSum
</code></pre>
<p>This should do it. You can create the function elsewhere, then initialize it in your riemann_sum as an input.</p>
| 0 | 2016-07-03T03:49:45Z | [
"python"
] |
Is there a way to have a mathematical function as the argument of a function in Python 3? | 38,166,547 | <p>Sorry if this is a easy question, or if it has already been answered, but I'm new to programming and I couldn't find a helpful answer to this question (maybe I don't know some terms that would've helped my search).</p>
<p>How can I include a mathematical function as an argument of a function in python?</p>
<p>In m... | 2 | 2016-07-03T03:47:15Z | 38,166,721 | <p>In Python functions are first class objects so you can, for example, pass functions as arguments to other functions. That is, the way you wrote your <code>riemann_sum</code> function declaration is fine.</p>
<p>What doesn't work is your definition of <code>func_x</code>, since you need to define <code>func_x</code... | 1 | 2016-07-03T04:25:16Z | [
"python"
] |
Is there a way to have a mathematical function as the argument of a function in Python 3? | 38,166,547 | <p>Sorry if this is a easy question, or if it has already been answered, but I'm new to programming and I couldn't find a helpful answer to this question (maybe I don't know some terms that would've helped my search).</p>
<p>How can I include a mathematical function as an argument of a function in python?</p>
<p>In m... | 2 | 2016-07-03T03:47:15Z | 38,167,107 | <p>I had a similar problem a few years back when I was coding something for my differential equations class. Here is an example of what worked for me:</p>
<pre><code>func_x = "(x**2)+x+1"
paramList = [(1+(1/k),(1/k)-(1/(k+1))) for k in range(1,101)]
# paramList holds the tuple (x,changeInX) for the riemann sum
def rie... | 0 | 2016-07-03T05:49:34Z | [
"python"
] |
Preloading sound in kivy | 38,166,589 | <p>I have a kivy-based game that is supposed to play some sound FX. Sound objects are loaded like this:</p>
<pre><code>self.boombox = {'moved': SoundLoader.load('dshoof.wav'),
'attacked': SoundLoader.load('dspunch.wav')}
</code></pre>
<p>And played whenever appropriate like this:</p>
<pre><code>self.... | 2 | 2016-07-03T03:55:43Z | 38,421,239 | <p>It can be hacked around, as it turned out. All I needed was to set the player to the start of the file explicitly:</p>
<pre><code>self.boombox = {'moved': SoundLoader.load('dshoof.wav'),
'attacked': SoundLoader.load('dspunch.wav')}
for sound in self.boombox.keys():
self.boombox[sound].seek(0)
</... | 0 | 2016-07-17T12:33:56Z | [
"python",
"audio",
"kivy"
] |
Using external .kv file vs doing things internally? | 38,166,665 | <p>I have noticed that most examples I foind online don't have an external <code>.kv</code> file. They define all the instances internally. However they also say that having an external <code>.kv</code> file is a good practice. Which is better to do? If having external <code>.kv</code>files are better, then how am I su... | 0 | 2016-07-03T04:12:46Z | 38,179,543 | <p>"Internal" usage of kv is through <a href="https://kivy.org/docs/api-kivy.lang.builder.html" rel="nofollow"><code>Builder</code></a> class, which allows you even to load external file. Those examples are worded in a <code>Builder.load_string(...)</code> way because it's way simpler to have a small example in one pla... | 0 | 2016-07-04T07:59:18Z | [
"python",
"kivy"
] |
Line Breaks Prevent BeautifulSoup from Extracting Data | 38,166,697 | <p>My script grabs HTML code from an email inbox via <code>imaplib</code>, passes it through <code>BeautifulSoup</code> and tries to extract all the <code>href</code>s in there.</p>
<pre><code>rv, data = M.SEARCH(None, '(FROM "foo@bar.com")')
if rv == 'OK':
for num in data[0].split():
typ, data = M.fetch(n... | 1 | 2016-07-03T04:20:39Z | 38,169,415 | <p>You can use <a href="https://docs.python.org/2/library/quopri.html" rel="nofollow">quopri</a> to decode the <a href="https://en.wikipedia.org/wiki/Quoted-printable" rel="nofollow">Quoted-printable</a> data:</p>
<p><em>Quoted-Printable, or QP encoding, is an encoding using printable ASCII characters (alphanumeric an... | 0 | 2016-07-03T11:17:59Z | [
"python",
"html",
"python-2.7",
"beautifulsoup",
"imaplib"
] |
Issue when building a nested dictionary in Python 3 | 38,166,756 | <p>I wanted to build a nested dictionary based on a text file. for example. (text.txt)</p>
<pre><code>...
hostA hostA.testing.com 192.168.1.101
hostB hostB.testing.com 192.168.1.102
...
</code></pre>
<p>Ideally, I want to get the following nested dictionary</p>
<pre><c... | 1 | 2016-07-03T04:34:20Z | 38,166,857 | <p>This is happening because you are reusing the same dict object for the <code>innerdict</code>. You need create a new dict object within your loop:</p>
<pre><code>myouterdict={}
def main():
my_fh = open('text.txt', 'r')
for line in my_fh:
myinnerdict={}
newline = line.strip().split() # ge... | 1 | 2016-07-03T04:55:47Z | [
"python"
] |
Issue when building a nested dictionary in Python 3 | 38,166,756 | <p>I wanted to build a nested dictionary based on a text file. for example. (text.txt)</p>
<pre><code>...
hostA hostA.testing.com 192.168.1.101
hostB hostB.testing.com 192.168.1.102
...
</code></pre>
<p>Ideally, I want to get the following nested dictionary</p>
<pre><c... | 1 | 2016-07-03T04:34:20Z | 38,166,924 | <p>The problem is that you are reusing the same variable for the dictionary. As <code>myouterdict</code> is storing the reference to the variable <code>myinnerdict</code> instead of the actual data, therefore, both of them are the same. For example, try this:</p>
<pre><code>>>> a = {}
>>> b = {"my a ... | 0 | 2016-07-03T05:07:32Z | [
"python"
] |
Python: Print file names and their directory based on their file size | 38,166,789 | <p>I want to print filenames and their directory if their filesize is more than a certain amount. I wrote one and set the bar 1KB, but it doesn't work even if there are plenty of files larger than 1KB.</p>
<pre><code>import os, shutil
def deleteFiles(folder):
folder = os.path.abspath(folder)
for foldername, ... | 1 | 2016-07-03T04:41:21Z | 38,166,824 | <p>Replace:</p>
<pre><code>deleteFiles('C:\\Cyber\\Downloads')
</code></pre>
<p>with</p>
<pre><code>import os
a = 'c:' # removed slash
b = 'Cyber' # removed slash
c = 'Downloads'
path = os.path.join(a + os.sep, b, c)
deleteFiles(path)
</code></pre>
| 0 | 2016-07-03T04:47:26Z | [
"python"
] |
Python: Print file names and their directory based on their file size | 38,166,789 | <p>I want to print filenames and their directory if their filesize is more than a certain amount. I wrote one and set the bar 1KB, but it doesn't work even if there are plenty of files larger than 1KB.</p>
<pre><code>import os, shutil
def deleteFiles(folder):
folder = os.path.abspath(folder)
for foldername, ... | 1 | 2016-07-03T04:41:21Z | 38,166,832 | <p><code>os</code> can't find the file without a given path, following your code, you have to re-specify the absolute path. Replace</p>
<pre><code>if os.path.getsize(filename) > 1000:
</code></pre>
<p>with</p>
<pre><code>if os.path.getsize(os.path.abspath(foldername + "/" + filename)) > 1000:
</code></pre>
<p... | 0 | 2016-07-03T04:50:39Z | [
"python"
] |
Return each list element on new line (Flask) | 38,166,828 | <p>Here's the current output:
<a href="http://puu.sh/pOsKt/4e4ab1f316.png" rel="nofollow">http://puu.sh/pOsKt/4e4ab1f316.png</a></p>
<p>I'd like it to output 1 address + gps coordinates per line. I assumed the last line in my code would accomplish that but it's not working as you can see.</p>
<p>My code:</p>
<pre><c... | 0 | 2016-07-03T04:48:46Z | 38,166,891 | <p>To make new lines in HTML, you need to use either <a href="http://www.w3schools.com/html/html_paragraphs.asp" rel="nofollow">display:block styled elements or the <code><br/></code> tag</a>. Every major browser adds a <a href="http://www.w3schools.com/cssref/pr_class_display.asp" rel="nofollow">display:block</a... | 0 | 2016-07-03T05:00:39Z | [
"python",
"flask"
] |
How do you keep track of a global variable in python | 38,166,877 | <p>I want to keep track of the variable <code>TOTAL_TRI</code>. <code>TOTAL_TRI</code> contains the number of correctly answered questions from the game. I need to save that value and pass it to the function <code>statistics</code> when <code>statistics</code> is called. Essentially, the player will play the game <c... | -1 | 2016-07-03T04:59:09Z | 38,166,894 | <p>Declare a variable <code>TOTAL_TRI = 0</code> in public scope. Whenever you want to access it in a function, use the <code>global</code> keyword:</p>
<pre><code>TOTAL_TRI = 0
def some_function(...):
global TOTAL_TRI
... # do something
</code></pre>
<p>You could still do this without using the <code>global... | 1 | 2016-07-03T05:02:25Z | [
"python",
"python-3.x"
] |
Extract array indices that contain a specific value | 38,166,890 | <p>I have an array with the shape: <em>(31777, 44, 44)</em></p>
<p>Its <code>sum</code> is 31777.0, and every <code>(44,44)</code> grid contains just one 1.0 entry at some coordinates.</p>
<p>My objective is to obtain an array of shape <em>(31777, 2)</em> where the <code>2</code> are the coordinates of the 1.0 entry ... | 0 | 2016-07-03T05:00:37Z | 38,167,037 | <p>You can use the <code>numpy.where</code> to find the indexes of elements in multidimensional array, for example:</p>
<pre><code>import numpy as np
arr = np.array([[[1,0],[0,0]], [[0,0],[1,0]], [[0,0], [0,1]]])
arr.shape
# (3, 2, 2)
np.array([coord for coord in zip(*np.where(arr == 1)[1:])])
# array([[0, 0],
# ... | 1 | 2016-07-03T05:30:35Z | [
"python",
"arrays",
"numpy"
] |
Extract array indices that contain a specific value | 38,166,890 | <p>I have an array with the shape: <em>(31777, 44, 44)</em></p>
<p>Its <code>sum</code> is 31777.0, and every <code>(44,44)</code> grid contains just one 1.0 entry at some coordinates.</p>
<p>My objective is to obtain an array of shape <em>(31777, 2)</em> where the <code>2</code> are the coordinates of the 1.0 entry ... | 0 | 2016-07-03T05:00:37Z | 38,167,178 | <p>The first answer gave me google material to find what I believe is optimal:</p>
<pre><code>np.vstack(arr.nonzero()[1:][::-1]).T
</code></pre>
| 0 | 2016-07-03T06:02:40Z | [
"python",
"arrays",
"numpy"
] |
Unable to retrieve temperature value from HTML using beautifulsoup module python | 38,166,949 | <p>I am using BeautifulSoup4 to parse this HTML (view-source:<a href="https://weather.com/en-IN/weather/today/l/17.39,78.49" rel="nofollow">https://weather.com/en-IN/weather/today/l/17.39,78.49</a>) and I'm trying to retrieve temperature value. But, the value might be stored in attribute <strong>obs.temperature</strong... | 0 | 2016-07-03T05:13:29Z | 38,167,085 | <p>BS4 is working as expected, as <code>[[ obs.temperature ]]</code> is part of the html templating language they are using the build the page after it is loaded, so you can't grab it straight from the HTML as the full page must be executed. Or:</p>
<p>When you load the page, the temperatures appear to load afterwards... | 1 | 2016-07-03T05:44:00Z | [
"python",
"python-3.x",
"beautifulsoup"
] |
how to solve list index out of range error Python? | 38,167,103 | <p>I'm learning web scraping using python.</p>
<p>Here is my first python code</p>
<pre><code># encoding=utf8
import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("http://www.bcsfootball.org/").read(),"lxml")
for row in soup("table", {'class': "mod-data"})[0].tbody("tr"):
tds = row... | 1 | 2016-07-03T05:48:27Z | 38,167,271 | <p>The error message means <code>soup("table", {'class': "mod-data"})</code> is an empty list, but you want to get the first element in this list. </p>
<p>You should ensure the <code>table</code> element has a node using class <code>"mod-data"</code>.</p>
| 1 | 2016-07-03T06:17:07Z | [
"python"
] |
how to solve list index out of range error Python? | 38,167,103 | <p>I'm learning web scraping using python.</p>
<p>Here is my first python code</p>
<pre><code># encoding=utf8
import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("http://www.bcsfootball.org/").read(),"lxml")
for row in soup("table", {'class': "mod-data"})[0].tbody("tr"):
tds = row... | 1 | 2016-07-03T05:48:27Z | 38,167,544 | <p>This would give you the expected result:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("http://www.bcsfootball.org").read(),"html")
welcome = soup("div", {'class': "col-full"})[1] # we know it's index 1
for item in welcome:
print item.string
</code></pre>
| 0 | 2016-07-03T07:05:45Z | [
"python"
] |
how to extract hour and minute and groupby | 38,167,221 | <p>I have 3 columns</p>
<pre><code>Date A B
1/7/2016 8:00 0 0
1/7/2016 8:30 1 1
1/7/2016 9:00 2 1
2/7/2016 8:00 0 0
2/7/2016 8:30 0 1
</code></pre>
<p>I would like to create a column C that extract only Hour and Minute, column D that groups column C and sums column A, column E t... | 1 | 2016-07-03T06:10:00Z | 38,167,345 | <h3>Alternative #1 (make Date a datetime column)</h3>
<p>Assuming <code>df.Date</code> is <code>datetime</code>, you can access many vectorized datetime functions via the <code>dt</code> attribute.</p>
<pre><code>df.Date = pd.to_datetime(df.Date)
df['C'] = df.Date.dt.strftime('%-H:%M')
df
</code></pre>
<h3>Alternati... | 0 | 2016-07-03T06:31:24Z | [
"python",
"pandas"
] |
Best way to implment timeout for a while loop | 38,167,249 | <p>I have a while loop</p>
<pre><code>while somecondition:
dostuff
</code></pre>
<p>(Sorry. It is hard to give an executable example as this is part of a larger project).</p>
<p>Most of the time the condition is met after a short while and the loop expires. But sometimes the condition will never be met. How can ... | 1 | 2016-07-03T06:14:28Z | 38,167,336 | <p>You can use a timeout using SIGALRM. Here's a little program that demonstrates it. </p>
<pre><code>import sys
import time
import signal
class TimeoutError(Exception):
pass
def _sig_alarm(sig, tb):
raise TimeoutError("timeout")
def main(argv):
timeout = 7
signal.signal(signal.SIGALRM, _sig_alarm... | 4 | 2016-07-03T06:29:16Z | [
"python",
"time"
] |
Best way to implment timeout for a while loop | 38,167,249 | <p>I have a while loop</p>
<pre><code>while somecondition:
dostuff
</code></pre>
<p>(Sorry. It is hard to give an executable example as this is part of a larger project).</p>
<p>Most of the time the condition is met after a short while and the loop expires. But sometimes the condition will never be met. How can ... | 1 | 2016-07-03T06:14:28Z | 38,167,337 | <p>How about writing a for loop? Or you can implement something like timer=0 an increment it every time you pass the loop. For example if you wanted to break after 100 iterations you could write an if statement. If timer == 100 then break.</p>
| 0 | 2016-07-03T06:29:40Z | [
"python",
"time"
] |
Best way to implment timeout for a while loop | 38,167,249 | <p>I have a while loop</p>
<pre><code>while somecondition:
dostuff
</code></pre>
<p>(Sorry. It is hard to give an executable example as this is part of a larger project).</p>
<p>Most of the time the condition is met after a short while and the loop expires. But sometimes the condition will never be met. How can ... | 1 | 2016-07-03T06:14:28Z | 38,167,391 | <p>wait for an hour example</p>
<pre><code>from datetime import timedelta
delete_TO = 1
wait_until = datetime.now() + timedelta(hours=delete_TO)
break_loop = False
while not break_loop:
do-your loop-stuff
if wait_until > datetime.now() or somecondition:
break_loop = True
</code></pre>
| 2 | 2016-07-03T06:38:44Z | [
"python",
"time"
] |
python log() function TypeError | 38,167,253 | <p>i have a data set called "sales" which is a SFrame.
there's a column called "sqft_living" and i want to convert it to log value. data type of column is float. but when i try to convert it with log() function it asks a float although its already a float.
here are the screenshot of codes and error. could you please he... | 1 | 2016-07-03T06:15:06Z | 38,172,463 | <p>Using Python 3.5 on Windows 10 using Python shell</p>
<p>As pointed out by Rahul, <code>a</code> is a list.<br>
You can take an element of the list as shown below and it would work:</p>
<pre><code>>>> import math
>>> train_data=[12.1, 14.5, 56.5, 43.2]
>>> a=train_data
>>> a
[12... | 0 | 2016-07-03T17:21:31Z | [
"python",
"ipython",
"sframe"
] |
python log() function TypeError | 38,167,253 | <p>i have a data set called "sales" which is a SFrame.
there's a column called "sqft_living" and i want to convert it to log value. data type of column is float. but when i try to convert it with log() function it asks a float although its already a float.
here are the screenshot of codes and error. could you please he... | 1 | 2016-07-03T06:15:06Z | 38,172,530 | <p><code>numpy.log</code> can be used with an array</p>
<pre><code>>>> import numpy
>>> a = numpy.array([180.0, 2570.0, 770.0, 1960.0])
>>> b = numpy.log(a)
>>> b
array([ 5.19295685, 7.85166118, 6.64639051, 7.58069975])
</code></pre>
| 2 | 2016-07-03T17:27:48Z | [
"python",
"ipython",
"sframe"
] |
python log() function TypeError | 38,167,253 | <p>i have a data set called "sales" which is a SFrame.
there's a column called "sqft_living" and i want to convert it to log value. data type of column is float. but when i try to convert it with log() function it asks a float although its already a float.
here are the screenshot of codes and error. could you please he... | 1 | 2016-07-03T06:15:06Z | 38,195,911 | <p>In your example, <code>a</code> is an SArray of type float. It cannot be passed to any function that takes a float. You can however apply any function that takes a float to the SArray like this:</p>
<pre><code>import math
log_a = a.apply(math.log)
</code></pre>
| 1 | 2016-07-05T05:42:34Z | [
"python",
"ipython",
"sframe"
] |
Python Regular expression to remove non unicode characters | 38,167,273 | <p>I am trying to use python regular expression to remove some characters looks like non unicode from a string.
here is my code:</p>
<pre><code>xxx='Juliana Gon\xe7alves Miguel'
t=re.sub('\w*','',xxx)
t
</code></pre>
<p>The result is like:</p>
<pre><code>>>> xxx='Juliana Gon\xe7alves Miguel'
>>> t=... | 2 | 2016-07-03T06:17:20Z | 38,167,949 | <p>If the desired output is</p>
<blockquote>
<p>'Juliana Gonalves Miguel'</p>
</blockquote>
<p>then the following regex should do the trick.</p>
<pre><code>re.sub('(?![ -~]).', '', xxx)
</code></pre>
<p><code>[ -~]</code>: short and readable version for all ASCII characters</p>
<p><code>(?!)</code>: negative loo... | 2 | 2016-07-03T08:05:50Z | [
"python"
] |
Showing validation error from m2m_changed signal in django admin | 38,167,275 | <p>I am trying to validate that the variable foo is the same for MyModel and Item before adding it as a m2m. I want to raise a ValidationError in the admin if it is not.</p>
<p>models.py</p>
<pre><code>class Item(models.Model):
foo = models.CharField(max_length=200)
class MyModel(models.Model):
foo = mod... | 0 | 2016-07-03T06:17:26Z | 38,167,329 | <p>Create a <code>form</code> class with <code>clean</code> method and modify your admin class to use the form. Read <a href="https://docs.djangoproject.com/en/1.9/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other" rel="nofollow">this</a>: </p>
<p>Like:</p>
<pre><code>@admin.register(MyMo... | 1 | 2016-07-03T06:27:57Z | [
"python",
"django",
"django-admin",
"django-signals",
"django-validation"
] |
getting python's itertools cycle current element | 38,167,293 | <p>I know you can use <code>c = cycle(['a', 'b', 'c'])</code> to cycle between the elements using <code>c.next()</code>, but is there away to get the iterator's current element?</p>
<p>for example if <code>c.next()</code> returned <code>'c'</code>, it means that iterator was at <code>'b'</code> before. Is there a way ... | 1 | 2016-07-03T06:21:24Z | 38,167,330 | <p>Iterators/generators don't have any way to get the current value. You should either keep a reference to it or create some wrapper that holds onto it for you.</p>
| 1 | 2016-07-03T06:27:59Z | [
"python",
"python-2.7"
] |
Should you use error handling even if your program is static? | 38,167,303 | <p>When designing an application that is static, where no input is coming from outside the program, is it worth while to have error handling even when using a language like python that doesn't need to be compiled? </p>
<p>Is it just a best practice?</p>
<p>I use python as an example because of its duck-typing nature.... | 0 | 2016-07-03T06:23:29Z | 38,167,318 | <p>Definitely, unit testing is to test your own program's logic. If you have a program with functions doing different tasks agnostic to data coming from a user or another function it should be tested. The two points you bring up on if it should be tested or not doesn't affect unit testability.</p>
| 0 | 2016-07-03T06:26:04Z | [
"python",
"error-handling"
] |
Django next with query parameters | 38,167,348 | <p>My website has a list of pages that are under /record and available only with query parameters of type and id. Like so:</p>
<blockquote>
<p>/record?type=poem&id=175</p>
</blockquote>
<p>I am using the django next redirect to go from the login page to the previous page. I initially used <code>href="{% url 'au... | 0 | 2016-07-03T06:31:50Z | 38,167,383 | <p>You can <strong>use <a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpRequest.get_full_path" rel="nofollow"><code>HttpRequest.get_full_path()</code></a></strong> method along with <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#urlencode" rel="nofollow"><code... | 0 | 2016-07-03T06:37:30Z | [
"python",
"django",
"redirect"
] |
Altering the response headers of Flask-Admin views? | 38,167,362 | <p>I am trying to alter the response headers for all the Flask-Admin views on my site. Specifically I want to set caching headers.</p>
<p>For normal blueprints it is pretty straightforward:</p>
<pre><code>@my_blueprint.after_request
def add_my_headers(response):
h = {
'Cache-Control': 'no-cache, no-store,... | 0 | 2016-07-03T06:33:38Z | 38,939,462 | <p>You could change method render() in BaseView to add whatever headers you want:</p>
<pre><code>from flask_admin.base import BaseView
from flask_admin import babel
from flask import current_app, render_template, make_response
from flask_admin import helpers as h
def render(self, template, **kwargs):
kwargs['admi... | 0 | 2016-08-14T05:32:05Z | [
"python",
"flask",
"flask-admin"
] |
AttributeError: 'Tensor' object has no attribute 'shape' | 38,167,388 | <p>Stack trace</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 6, in <module>
connection.start_socket(8089, callback=handler.message_processor)
File "/mnt/d/workspace/SketchRecognitionWithTensorFlow/src/main/python/connection/python_socket_server.py", line 13, in start_socket
p... | 1 | 2016-07-03T06:38:26Z | 39,401,790 | <p>The stack trace doesn't help a lot with code snippets that don't have line numbers. But I can tell you that when I saw that error it was because I used tf.reshape on a numpy array instead of a true tensorflow tensor. The resulting object threw that error when I tried to determine the shape. Hope that helps.</p>
| 1 | 2016-09-08T23:52:14Z | [
"python",
"tensorflow"
] |
AttributeError: 'Tensor' object has no attribute 'shape' | 38,167,388 | <p>Stack trace</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 6, in <module>
connection.start_socket(8089, callback=handler.message_processor)
File "/mnt/d/workspace/SketchRecognitionWithTensorFlow/src/main/python/connection/python_socket_server.py", line 13, in start_socket
p... | 1 | 2016-07-03T06:38:26Z | 39,414,015 | <p>It's hard to see from the code provided, especially since I cannot figure out, where your error occurs. But for what it's worth, I have run into a related problem before:</p>
<p>It looks to me, like some code is trying to handle a tf-tensor as if it was a np-array. Tensors don't have a <code>shape</code> attribute,... | 0 | 2016-09-09T14:33:30Z | [
"python",
"tensorflow"
] |
Show all the Print inside a loop Python | 38,167,506 | <p>I have a print inside a loop, everything goes fine: I can see all.</p>
<pre><code> for in range(0,10000) :
function_using_show()
print 25)
</code></pre>
<p>But, When I put the same code inside a function :</p>
<pre><code>def ff() :
for in range(0,10000) :
function_using_show()
print 25
def ... | -3 | 2016-07-03T06:59:32Z | 38,167,565 | <p>I think you are missing the : at the end of the if statement</p>
| 0 | 2016-07-03T07:08:31Z | [
"python"
] |
Show all the Print inside a loop Python | 38,167,506 | <p>I have a print inside a loop, everything goes fine: I can see all.</p>
<pre><code> for in range(0,10000) :
function_using_show()
print 25)
</code></pre>
<p>But, When I put the same code inside a function :</p>
<pre><code>def ff() :
for in range(0,10000) :
function_using_show()
print 25
def ... | -3 | 2016-07-03T06:59:32Z | 38,167,642 | <p>You're problem is that you try to perform <code>plt.show()</code> in a loop, but the thing you are not considering here is that <strong>this method is blocking</strong>: <br>
quoting the <a href="http://matplotlib.org/faq/howto_faq.html" rel="nofollow">tutorial</a>: <br>
<em>"Because this mainloop is blocking by de... | 0 | 2016-07-03T07:21:29Z | [
"python"
] |
Does C has a "from-import"-like mechanism? | 38,167,594 | <p>I've read <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">here</a> about importing a module in python. There is an option to not import a whole module (e.g. sys) and to only import a part of it (e.g. sys.argv). Is that possible in C? Can I include only the implementation of printf or any oth... | 0 | 2016-07-03T07:14:23Z | 38,167,661 | <p>C does not have anything that is equivalent to, or even similar to Python's "from ... import" mechanism.</p>
<blockquote>
<p>I ask this because it seems very inefficient to include a whole file where I need only several lines of code.</p>
</blockquote>
<p>Actually, what <em>normally</em> happens when you <code>#... | 2 | 2016-07-03T07:23:49Z | [
"python",
"c",
"import",
"include"
] |
Does C has a "from-import"-like mechanism? | 38,167,594 | <p>I've read <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">here</a> about importing a module in python. There is an option to not import a whole module (e.g. sys) and to only import a part of it (e.g. sys.argv). Is that possible in C? Can I include only the implementation of printf or any oth... | 0 | 2016-07-03T07:14:23Z | 38,167,689 | <p><strong>Python</strong>: "<em>There is an option to not import a whole module</em>" : I think you misunderstand what is going on here. When you specify the names to import, it means that only those <em>names</em> go into you namespace. The "whole" module is compiled, and any code outside functions is run, even wh... | 1 | 2016-07-03T07:30:23Z | [
"python",
"c",
"import",
"include"
] |
How to import from both a python file in a folder and a file on the same directory being called? | 38,167,595 | <p>Consider this example:</p>
<pre><code>/project
| main.py
| database.py
L /database
L users.py
</code></pre>
<p>There are variables in both database.py and users.py. users.py is in a folder called database within the project. Is it possible to import both database.py's variables and users.py variables from ... | 2 | 2016-07-03T07:14:30Z | 38,167,654 | <p>Can you be more explicit about your use case?</p>
<p>You can import variables with the normal <code>import</code> statement.</p>
<pre><code>from database import a, b
from lib.users import c, d
if __name__ == '__main__':
print(a, b)
print(c, d)
</code></pre>
<p>Note that there has to be a file called <cod... | 1 | 2016-07-03T07:23:11Z | [
"python"
] |
How to import from both a python file in a folder and a file on the same directory being called? | 38,167,595 | <p>Consider this example:</p>
<pre><code>/project
| main.py
| database.py
L /database
L users.py
</code></pre>
<p>There are variables in both database.py and users.py. users.py is in a folder called database within the project. Is it possible to import both database.py's variables and users.py variables from ... | 2 | 2016-07-03T07:14:30Z | 38,169,130 | <p>If you want to import stuff from the <code>database</code> dir, you need to have an <code>__init__.py</code> file inside it, even if it's empty. <code>database</code> is then said to be a "package".</p>
<p>You can't have <code>database.py</code> and a <code>database</code> dir though, because doing <code>import dat... | 1 | 2016-07-03T10:42:45Z | [
"python"
] |
Referring to object names within its Class itself | 38,167,625 | <p>My code:</p>
<pre><code> import math
class Cal(object):
def __init__(self,precision):
self.precision=precision
def roundTo(self):
if(obj1):
return (round(math.pi,self.precision))
elif(obj2):
return (round(math.e,self.precision))
... | 0 | 2016-07-03T07:18:57Z | 38,169,411 | <p>Trying to identify objects by name looks like bad design, because an object does not know its own name. Look why it is impossible:</p>
<pre><code># let's have two objects with two names
obj1 = Cal()
obj2 = Cal()
# you can swap names
obj1, obj2 = obj2, obj1
# you can have two equally valid names for the same obje... | 0 | 2016-07-03T11:17:26Z | [
"python",
"oop"
] |
Python: Ternary operator syntax error | 38,167,628 | <p>I am trying to use a ternary condition in my program as follows:</p>
<pre><code>c = 12
(print c) if (c == 10) else (print 'c is not 10')
</code></pre>
<p>However, this raises a syntax error. What seems to be wrong here?</p>
| 1 | 2016-07-03T07:19:15Z | 38,167,641 | <p>You would do it like this:</p>
<pre><code>print c if c == 10 else 'c is not 10'
</code></pre>
<p>The parenthesis are unnecessary, and you must start with the "<code>print</code>"; Python cannot make the whole command a conditional the way Perl can.</p>
<p>There is no Python equivalent of Perl's:</p>
<pre><code>p... | 4 | 2016-07-03T07:21:15Z | [
"python",
"python-2.7"
] |
Python: Ternary operator syntax error | 38,167,628 | <p>I am trying to use a ternary condition in my program as follows:</p>
<pre><code>c = 12
(print c) if (c == 10) else (print 'c is not 10')
</code></pre>
<p>However, this raises a syntax error. What seems to be wrong here?</p>
| 1 | 2016-07-03T07:19:15Z | 38,167,695 | <p>you shall do <code>print(c)</code> instead of <code>(print c)</code></p>
| 0 | 2016-07-03T07:31:35Z | [
"python",
"python-2.7"
] |
Connect a Flask webservice from a device which is not on the same network | 38,167,646 | <p>I am not an expert in web programming and know very little about it. I am trying to run a webservice on an EC2 instance (Windows Server 2012R2) and the webservice is written in Python using Flask package. I am able to connect to my webservice from localhost. But what I want to do is to connect it from a remote syste... | -2 | 2016-07-03T07:22:32Z | 38,168,254 | <p>Let A be the server you connecting to. Let B be the server you are connecting from, which, from what I gather, is sometimes localhost.</p>
<h1>Why can't B connect to A?</h1>
<h2>1. Security Settings</h2>
<p>The following is EC2-specific: You have to open up connections to specific IPs. Check your instance's secur... | 1 | 2016-07-03T08:46:24Z | [
"python",
"apache",
"web-services",
"amazon-web-services",
"flask"
] |
pandas append same series to each column | 38,167,738 | <p>Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.random.rand(5, 3),
['p0', 'p1', 'p2', 'p3', 'p4'],
['A', 'B', 'C'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Gnkl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gnkl0.png" alt="df"><... | 4 | 2016-07-03T07:38:09Z | 38,167,804 | <p>You can use double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p>
<pre><code>print (pd.concat([dm] * df.shape[1], axis=1, keys=df.columns))
A B C
m0 0.823788 0.823788 0.823788
m1 0.615354 0.615354 0.6153... | 1 | 2016-07-03T07:46:44Z | [
"python",
"pandas"
] |
pandas append same series to each column | 38,167,738 | <p>Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.random.rand(5, 3),
['p0', 'p1', 'p2', 'p3', 'p4'],
['A', 'B', 'C'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Gnkl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gnkl0.png" alt="df"><... | 4 | 2016-07-03T07:38:09Z | 38,167,809 | <p>Here you go, old sport:</p>
<pre><code>df.apply(lambda S:S.append(dm))
</code></pre>
<p>Initial test has jezrael's answer as faster:</p>
<pre><code>In [5]: timeit pd.concat([df, pd.concat([dm] * 3, axis=1, keys=df.columns)])
100 loops, best of 3: 4.75 ms per loop
In [6]: timeit df.apply(lambda S:S.append(dm))
10... | 1 | 2016-07-03T07:47:29Z | [
"python",
"pandas"
] |
pandas append same series to each column | 38,167,738 | <p>Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.random.rand(5, 3),
['p0', 'p1', 'p2', 'p3', 'p4'],
['A', 'B', 'C'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Gnkl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gnkl0.png" alt="df"><... | 4 | 2016-07-03T07:38:09Z | 38,167,898 | <p>You can create an other datatframe passing a <code>dictionary</code> with the <code>keys</code> as the column names and <code>values</code> as <code>dm</code>. Then you can concatenate the two dataframes:</p>
<pre><code>df2 = pd.DataFrame({'A': dm, 'B': dm, 'C': dm})
con = (df, df2)
df3 = pd.concat(con)
</code></pr... | 1 | 2016-07-03T07:58:40Z | [
"python",
"pandas"
] |
pandas append same series to each column | 38,167,738 | <p>Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.random.rand(5, 3),
['p0', 'p1', 'p2', 'p3', 'p4'],
['A', 'B', 'C'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Gnkl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gnkl0.png" alt="df"><... | 4 | 2016-07-03T07:38:09Z | 38,167,989 | <p>I think I found the answer.</p>
<pre><code>dm3 = pd.DataFrame(dm.values[:, None].repeat(df.shape[1], axis=1),
dm.index, df.columns)
df.append(dm3)
</code></pre>
<p>See updated timings in question. This solution is hands down better at larger scales. I can't accept this answer for 2 days. I'm ... | 1 | 2016-07-03T08:11:55Z | [
"python",
"pandas"
] |
pandas append same series to each column | 38,167,738 | <p>Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.random.rand(5, 3),
['p0', 'p1', 'p2', 'p3', 'p4'],
['A', 'B', 'C'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/Gnkl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gnkl0.png" alt="df"><... | 4 | 2016-07-03T07:38:09Z | 38,171,625 | <p>Roughly the same, maybe depends on scale? If you could insert without converting to dataframe it would be faster... Index would be 0-4... But couldnt find away</p>
<pre><code>%timeit dm3 = pd.DataFrame(dm.values[:, None].repeat(df.shape[1], axis=1),dm.index, df.columns);df.append(dm3)
1000 loops, best of 3: 536 Â... | 1 | 2016-07-03T15:47:20Z | [
"python",
"pandas"
] |
How do I center widgets placed by `tkinter.grid` in Python? | 38,167,753 | <p>I have a GUI. On this I have <code>grid</code>ed many widgets. But the problem is that the widgets placed by gridding always are at the top left. I want them at the center of the screen while still retaining placing them by the <code>grid</code> method. How do I do that? Here's my code:</p>
<pre><code> self.fram... | 1 | 2016-07-03T07:39:46Z | 38,168,474 | <p>You can use the following trick which offers the advantage of not modifying your existing code:</p>
<p>Draw <code>self.frame</code> inside an other <code>tkinter.Frame()</code> instance where it must be centered.</p>
<pre><code>self.main_frame = tkinter.Frame()
self.frame.place(in_=self.main_frame, anchor="c", rel... | 0 | 2016-07-03T09:14:24Z | [
"python",
"python-3.x",
"tkinter"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.