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 |
|---|---|---|---|---|---|---|---|---|---|
Find lost cards (faster solution) | 37,586,034 | <p>We're given N (3 <= N <= 50000) cards with unique numbers from 1 to N.
We lost some 3 cards and our goal is to find them.</p>
<p><em>Input</em>: first line contains number of cards N.
Second line contains 3 numbers: sum of all left cards we have, sum of their squares and sum of their cubes.</p>
<p><em>Output... | 1 | 2016-06-02T08:04:43Z | 37,586,780 | <p>If your unknown numbers are x,y,z, then you have a system of three equations</p>
<pre><code>x + y + z = a //your s_lost
x^2 + y^2 + z^2 = b //your s2_lost
x^3 + y^3 + z^3 = c //your s3_lost
</code></pre>
<p>While direct solution of this system seems too complex, we can fix one unknown and solve simpler system. ... | 2 | 2016-06-02T08:41:41Z | [
"python",
"algorithm",
"optimization"
] |
HttpRequest instance add attribute dynamically in Django? | 37,586,062 | <p>I'm confused with <a href="https://github.com/django/django/blob/master/django/http/request.py#L43" rel="nofollow">HttpRequest</a> object in Django. I know that the <strong>AuthenticationMiddleware</strong> will add a <code>user</code> to <code>request</code> which is an instance of HttpRequest. And the code is <a h... | 0 | 2016-06-02T08:05:45Z | 37,586,361 | <p><code>HttpRequest</code> is a class which inherits from <code>object</code>. In Python attributes can be set on objects at any time.</p>
<p><code>HttpRequest</code> describes a HTTP request, which in its normal state does not include any data about the user. That is why the <code>AuthenticationMiddleware</code> add... | 3 | 2016-06-02T08:21:44Z | [
"python",
"django"
] |
Migrate Stock_quants using stock move openerp7 odoo 8 | 37,586,188 | <p>How to to fill stock.quant and stock_quants_move_rel with stock_move Migration openErp7 to odoo8?
Im trying to reprocess stock move with states done to fill stock quants but I have a lot of data in stock_moves </p>
| 0 | 2016-06-02T08:11:56Z | 37,652,714 | <p>Here is my code </p>
<pre>
from openerp.osv import osv,fields
from openerp import SUPERUSER_ID
from openerp import netsvc
class generation(osv.osv):
_name ="generation.models"
_columns={
"visible":fields.boolean("Visible")
}
_defaults={
'vis... | 0 | 2016-06-06T08:25:11Z | [
"python",
"openerp",
"database-migration",
"odoo-8",
"talend"
] |
Differences in image dimensions from cv2 (python) and torch/image (libpng) | 37,586,190 | <p>I use cv2.imread and cv2.imdecode depending on if I am loading an image from disk or from url. Comparatively, I use image.load to load from disk, which utilizes libpng. When using cv2, my image.shape outputs with (height, width, channels). However when using torch, the shape is (channels, height, width).</p>
<p>I a... | 1 | 2016-06-02T08:12:01Z | 37,586,449 | <p>Different libraries may store the image data in different memory formats - this is completely up to the library and its purpose (speed of traversing the image data, memory efficieny, etc...). </p>
<p>A possible solution (without further 3rd-party tools) for your problem can be the use of <code>transpose</code>. A s... | 1 | 2016-06-02T08:25:55Z | [
"python",
"image",
"opencv",
"lua",
"torch"
] |
Differences in image dimensions from cv2 (python) and torch/image (libpng) | 37,586,190 | <p>I use cv2.imread and cv2.imdecode depending on if I am loading an image from disk or from url. Comparatively, I use image.load to load from disk, which utilizes libpng. When using cv2, my image.shape outputs with (height, width, channels). However when using torch, the shape is (channels, height, width).</p>
<p>I a... | 1 | 2016-06-02T08:12:01Z | 37,586,482 | <p>Check out <a href="https://github.com/imodpasteur/lutorpy" rel="nofollow">lutorpy</a>:</p>
<blockquote>
<p>Lutorpy is a libray built for deep learning with torch in python, by a two-way bridge between Python/Numpy and Lua/Torch, you can use any Torch modules(nn, rnn etc.) in python, and easily convert variables(a... | 0 | 2016-06-02T08:27:38Z | [
"python",
"image",
"opencv",
"lua",
"torch"
] |
Object is not defined | 37,586,218 | <p>I have a problem with my code.
The program is designed to parse the file, select it with the information and save them in the list of objects of the class.</p>
<p>But first - it does not save them correctly. In fact, nothing does save, it returns empty records.</p>
<p>I tried to create a minimum of code entirely ... | 1 | 2016-06-02T08:13:44Z | 37,588,270 | <p>I really like <code>xml.etree</code> for this kind of task. Supposing your xml example has multiple <code>Entry</code> records inside an other element, I used this xml file to test my code:</p>
<pre><code><Records>
<Entry id="AA0003">
<Header>
<Code>AA0003</Code>
</Header>
<Na... | 0 | 2016-06-02T09:46:33Z | [
"python",
"python-3.x",
"xml-parsing",
"minidom"
] |
How do I make two image loops run at the same time in Tkinter | 37,586,226 | <p>Im trying to make two image loops run simultaniously in Tkinter via Labels. I tried with the Process function, but I guess I have to find a way to get out of the first loop and start the second. Is there such a way?</p>
<pre><code>import time
import Tkinter
from multiprocessing import Process
side = Tkinter.Tk()
... | 0 | 2016-06-02T08:14:09Z | 37,600,142 | <p>You don't need to use <code>Process</code> for this simple task. You can just do <code>after</code> method.
Based on your code, <code>anim</code> and <code>anim_1</code> are just loading images, so they can be executed at the beginning. Other 2 <code>anim</code> functions you can call with after method.</p>
<pre><c... | 0 | 2016-06-02T19:03:33Z | [
"python",
"tkinter"
] |
Visual studio completion python | 37,586,246 | <p>I'm new to python in visual studio..I'm trying to have the same environment of sublime text.
I configured everything auto-formatting , auto-completion etc...
But when I write essential keyword like "self", the tool doesn't suggest me the keyword
So if I write "s" in sublime I obtain a suggest for "self".
But this do... | 1 | 2016-06-02T08:15:16Z | 37,868,492 | <p>PTVS will only use autocomplete functionality in certain scenarios. In order for 'self' to display after typing 's' you will need to press CTR+SPACE or CTR+J. These are the default commands for autocomplete. You can learn more at the <a href="https://github.com/Microsoft/PTVS/wiki/Editor-Features#completions" rel... | 0 | 2016-06-16T20:07:23Z | [
"python",
"visual-studio",
"ptvs"
] |
Pandas: how to convert an index of int64 epoc seconds to datetime | 37,586,550 | <p>I have some timezone information stored in a variable called <code>tz_pytz</code> -- I get that form a <code>hdf5</code> file along with the dataframe but this is not important right now.</p>
<p>I have an int64 index representing second values since epoch that I want to treat as a timestamp with time zone informati... | 1 | 2016-06-02T08:30:58Z | 37,586,959 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.tz_localize.html" rel="nofollow"><code>.tz_localize</code></a> to add timezone to your datetime column:</p>
<pre><code>In [12]:
df = pd.DataFrame(index=np.arange(10))
df['timestamp'] = pd.to_datetime(df.index, unit='s')
df['time... | 1 | 2016-06-02T08:49:44Z | [
"python",
"datetime",
"pandas"
] |
How to find some string by regex but when special string doesn't adjoin? | 37,586,572 | <p>Purpose: Find <code>**</code> in string and replace it, but exclude when <code><center></code> and <code></center></code> adjoins.</p>
<p>Example:</p>
<pre><code>**
asdf**adsfds
<cente>**</center>
<center>** </center>
<center> ** </center>
</code></pre>
<p>In this... | 1 | 2016-06-02T08:31:59Z | 37,587,066 | <p>You can go with inverse matching in regex using negative look arounds like below. For further reading <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">check here</a>.</p>
<pre><code>^((?!\<center\>).)*\*\*((?!\<\/center\>).)*
</code></pre>
| 1 | 2016-06-02T08:54:35Z | [
"python",
"regex"
] |
How to find some string by regex but when special string doesn't adjoin? | 37,586,572 | <p>Purpose: Find <code>**</code> in string and replace it, but exclude when <code><center></code> and <code></center></code> adjoins.</p>
<p>Example:</p>
<pre><code>**
asdf**adsfds
<cente>**</center>
<center>** </center>
<center> ** </center>
</code></pre>
<p>In this... | 1 | 2016-06-02T08:31:59Z | 37,587,068 | <p>This could probably be done with negative lookaheads/lookbehinds, but getting those right is tricky. Here's my suggestion:</p>
<pre><code>import re
string = """**
asdf**adsfds
<center>**</center>
<center>** </center>
<center> ** </center>"""
temp = 'specialuniquestring'
string... | 1 | 2016-06-02T08:54:43Z | [
"python",
"regex"
] |
How to add new data from ebay to database in Django? | 37,586,603 | <p>I am using <code>python ebay-sdk</code> library for connection to ebay api.</p>
<p>I want to get some cases from ebay api and save it to the database.</p>
<p>I have one app and models like this:</p>
<pre><code>class Case(models.Model):
# case is not necessarily a listing (often O2M)
STATUS = Choices('new'... | 1 | 2016-06-02T08:33:37Z | 37,586,854 | <p>If your want your data to be saved with the least hassle, then yes, use the same field-names.</p>
<p>You have an example of a model field with a default in your own code:</p>
<pre><code>currency = models.CharField(max_length=3, default='USD')
</code></pre>
<p>You could also override your model's save() method:</p... | 0 | 2016-06-02T08:44:29Z | [
"python",
"django",
"python-3.x"
] |
Replicate a T-SQL random function in Python | 37,586,685 | <p>I have a T-SQL code and I want to run a few simulations in Python. There is a code that includes random functions and I am not sure how I can replicate it.</p>
<p>When I have <code>RAND()</code> in SQL, I just use this in Python:</p>
<pre><code>import random as random
print random.random()
</code></pre>
<p>But, I... | 0 | 2016-06-02T08:37:53Z | 37,587,279 | <p>in Python you need to first call </p>
<p>random.seed() in you program (once only)</p>
<p>then </p>
<p>random.random() </p>
<p>each time you want a random number</p>
<p>to give a pseudo random number from 0 to 1</p>
<hr>
<p>yes RAND(CHECKSUM(NEWID())) appears to be a good trick to get a random value to use as ... | 0 | 2016-06-02T09:03:53Z | [
"python",
"sql",
"tsql",
"random"
] |
Django-Rest-Framework, POST operation: fields is not empty but DRF says is required | 37,586,743 | <p>Well, i have this <strong>model</strong>:</p>
<pre><code>class Application(models.Model):
name = models.CharField("nom", unique=True, max_length=255)
sonarQube_URL = models.CharField("Url SonarQube", max_length=255,
blank=True, null=True)
def __unicode__(self):
... | 0 | 2016-06-02T08:39:59Z | 37,591,554 | <p>Try to keep your code in English, you can use Django's i18n to translate stuff, also use blank and null for your name field:</p>
<pre><code>class Application(models.Model):
name = models.CharField(_('name'), max_length=255, blank=True, null=True)
sonarqube_url = models.CharField(_('SonarQube URL'), max_leng... | 0 | 2016-06-02T12:13:02Z | [
"python",
"django",
"post",
"django-rest-framework"
] |
Django-Rest-Framework, POST operation: fields is not empty but DRF says is required | 37,586,743 | <p>Well, i have this <strong>model</strong>:</p>
<pre><code>class Application(models.Model):
name = models.CharField("nom", unique=True, max_length=255)
sonarQube_URL = models.CharField("Url SonarQube", max_length=255,
blank=True, null=True)
def __unicode__(self):
... | 0 | 2016-06-02T08:39:59Z | 37,598,287 | <p>The error you got is related to the <code>Django Model(Application)</code>. It was failing in model level not in serializer level. Add <code>null=True</code> and <code>blank=True</code> to <code>name</code> field in <code>Application</code> model.</p>
| 0 | 2016-06-02T17:18:06Z | [
"python",
"django",
"post",
"django-rest-framework"
] |
Extract path or position information about all objects in a matplotlibfigure | 37,586,807 | <p>I want to export information about all visible objects in a matplotlib figure, however I can not find the arguments that give me the position. Basically I am trying to serialize it. I already read <a href="http://matplotlib.1069221.n5.nabble.com/matplotlib-figure-serialization-td18587.html" rel="nofollow" title="mat... | 1 | 2016-06-02T08:42:53Z | 37,587,765 | <p>When you use <code>get_children</code> you get only children objects, but these objects may have own children. However not all objects have <code>get_path</code> method:</p>
<pre><code>import matplotlib.pyplot as plt
def get_info(obj):
if 'get_children' in dir(obj):
for o in obj.get_children():
... | 0 | 2016-06-02T09:25:56Z | [
"python",
"serialization",
"matplotlib"
] |
ValueError: No closing quotation | 37,587,028 | <p>I have the following code which returns the public IP's </p>
<pre><code>def gather_public_ip():
ACCESS_KEY = config.get('aws','access_key')
SECRET_KEY = config.get('aws','secret_key')
regions = regions = ['us-west-2','eu-central-1','ap-southeast-1']
# regions = config.get('aws','region').split(',')
... | 0 | 2016-06-02T08:52:58Z | 37,587,282 | <p>Make sure your <code>ip</code> is not <code>""</code> or shlex will fail, cf <a href="http://stackoverflow.com/questions/4047752/which-exception-to-raise-if-a-given-string-does-not-match-some-format">Which exception to raise if a given string does not match some format?</a></p>
| 1 | 2016-06-02T09:04:06Z | [
"python"
] |
find if tinter object overlaps with ball in canvas python | 37,587,127 | <p>If I have a ball in tkinter with radius 20 at coordinates x,y. What's the best method to find out if another object is touching it or partially overlapping it. I tried equating the coordinates of the two objects however that would only happen in very specific cases. Is there a away I can build a list that contains a... | -1 | 2016-06-02T08:57:18Z | 37,589,713 | <p>The circle's circumference consists of all the points that are exactly 20 units from the center. Therefore, if the distance from an edge of your object to the circle's center is less than 20, it will be inside the circle. If it's exactly 20, it will be touching the circle. </p>
| 0 | 2016-06-02T10:48:57Z | [
"python",
"tkinter"
] |
what is the purpose of db=0 when connecting to redis server in python? | 37,587,210 | <p>In the redis python client documentation most examples have db=0 passed in constructor parameters. <a href="https://pypi.python.org/pypi/redis" rel="nofollow">https://pypi.python.org/pypi/redis</a></p>
<p>What is the use of db=0 and in what case should i use other values instead of 0?</p>
<pre><code>import redis
... | 0 | 2016-06-02T09:01:19Z | 37,587,450 | <p>You can have multiple databases in redis. In redis, databases are identified using integers rather than name. So here, 'db' is database number to which you want to connect.</p>
| 0 | 2016-06-02T09:12:25Z | [
"python",
"redis"
] |
what is the purpose of db=0 when connecting to redis server in python? | 37,587,210 | <p>In the redis python client documentation most examples have db=0 passed in constructor parameters. <a href="https://pypi.python.org/pypi/redis" rel="nofollow">https://pypi.python.org/pypi/redis</a></p>
<p>What is the use of db=0 and in what case should i use other values instead of 0?</p>
<pre><code>import redis
... | 0 | 2016-06-02T09:01:19Z | 37,587,454 | <p>There are 16 databases that a redis server starts up with. They are labeled 0-15. If you chose to and organized your data accordingly, you could manipulate data in each of these. When connecting, you need to choose one. The default choice is <code>db=0</code>. However, it could have been any number in the range 0-1... | 1 | 2016-06-02T09:12:38Z | [
"python",
"redis"
] |
Modify only a specific part of a file | 37,587,348 | <p>I have a python script that is supposed to read a file. The issue is that that file is very large so for efficiency I decided that my script should only read from line 650000 and onward, since previous line does not contain relevant information.</p>
<p>Is there any way to only modify lines 650000 till eof, so for e... | 2 | 2016-06-02T09:07:24Z | 37,587,463 | <p>Files are not line-oriented, they are blocks of bytes.</p>
<p>There's no way, short of reading the data in, to figure out how many bytes make up those first 650,000 lines, so you'd have to do that just in order to skip them.</p>
<p>Starting modifying a file at a certain offset is possible, but that offset will be ... | 2 | 2016-06-02T09:12:56Z | [
"python"
] |
how to write a function, it will do the same thing with replace() | 37,587,377 | <p>Can I define a function, that will do the same thing with
<code>string.replace(old,new)</code>?</p>
<p>I wrote a little program:</p>
<pre><code>word = input()
at = "AT"
if at in word:
new = word.replace(at,"IN")
print(new)
</code></pre>
<p>However I don't want to use the <code>replace()</code>, I want t... | -3 | 2016-06-02T09:08:44Z | 37,587,980 | <p>Take a look at this :</p>
<pre><code>def custom_replace(string, old, new):
index = string.find(old)
if index == -1:
return string
return string[:index] + new + string[index + len(old):]
string = 'Hello World !'
old = 'World'
new = 'StackOverflow'
print(custom_replace(string, old, new))
</... | 0 | 2016-06-02T09:35:27Z | [
"python",
"function",
"python-3.x",
"input"
] |
How can I set a default for star arguments? | 37,587,389 | <p>I have a function that accepts <code>*args</code>, but I would like to set a default tuple, in case none are provided. (This is not possible through <code>def f(*args=(1, 3, 5))</code>, which raises a <code>SyntaxError</code>.) What would be the best way to accomplish this? The intended functionality is shown below.... | 4 | 2016-06-02T09:09:12Z | 37,587,548 | <p>You could check whether <code>args</code> are truthy in your function:</p>
<pre><code>def g(*args):
if not args:
args = (1, 2, 3)
return "I received {}!".format(', '.join(str(arg) for arg in args))
</code></pre>
<p>If no <code>args</code> are passed to the function, it will result in a empty tuple,... | 11 | 2016-06-02T09:16:19Z | [
"python",
"python-3.x"
] |
How can I set a default for star arguments? | 37,587,389 | <p>I have a function that accepts <code>*args</code>, but I would like to set a default tuple, in case none are provided. (This is not possible through <code>def f(*args=(1, 3, 5))</code>, which raises a <code>SyntaxError</code>.) What would be the best way to accomplish this? The intended functionality is shown below.... | 4 | 2016-06-02T09:09:12Z | 37,587,594 | <pre><code>def g(*args):
if not args:
args = [1, 3, 5]
return "I received {}!".format(', '.join(str(arg) for arg in args))
</code></pre>
| 3 | 2016-06-02T09:18:07Z | [
"python",
"python-3.x"
] |
How can I set a default for star arguments? | 37,587,389 | <p>I have a function that accepts <code>*args</code>, but I would like to set a default tuple, in case none are provided. (This is not possible through <code>def f(*args=(1, 3, 5))</code>, which raises a <code>SyntaxError</code>.) What would be the best way to accomplish this? The intended functionality is shown below.... | 4 | 2016-06-02T09:09:12Z | 37,587,600 | <p>If no arguments are received, <code>args</code> will be an empty tuple. You can't add a default value in the method signature itself, but you can check if <code>args</code> is empty and replace it with a fallback value inside the function.</p>
<pre><code>def g(*args):
if not args:
args = (1, 2, 3)
... | 6 | 2016-06-02T09:18:17Z | [
"python",
"python-3.x"
] |
Extract URL from .url file | 37,587,405 | <p>Is it possible to read the actual URL from a <code>.url</code>file, as described <a href="http://www.fmtz.com/formats/url-file-format/article" rel="nofollow">here</a>, with Python?</p>
<p>In the following image for instance, I can easily print <em>mapbox-OSM Bright- A Carto template for OpenStreetMap data</em> but ... | -2 | 2016-06-02T09:10:03Z | 37,587,667 | <p>I assume you mean a URL file as described <a href="http://www.fmtz.com/formats/url-file-format/article" rel="nofollow">here</a>. Those files have a syntax similar to .ini-files and can probably be parsed like this:</p>
<pre><code>import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('example.url'... | 4 | 2016-06-02T09:20:53Z | [
"python",
"python-2.7",
"url"
] |
OpenCV: How do I calculate minimum for a window around a central pixel? | 37,587,411 | <p>I am trying to extract features from an image by calculating the minimum of a given window around an image and subtracting it from the original pixel value.
However that is turning out to be very slow, as I am iterating throughout the picture. Is there any optimised way to do it?</p>
<pre><code> f = np.asarray(i... | 1 | 2016-06-02T09:10:23Z | 37,587,702 | <p>I'm not sure if I understand your goal correctly:</p>
<ul>
<li>Input image <code>I</code></li>
<li>for every pixel <code>p</code> in <code>I</code> subtract the minimum of the surrounding windows (including the original pixel)</li>
</ul>
<p>You could then use the morphological filter <code>erode</code> which acts ... | 1 | 2016-06-02T09:22:55Z | [
"python",
"opencv",
"numpy"
] |
Python JSON REST framework with (de)serialiser and schema validation (jsonschema/avro) | 37,587,620 | <p>I think my problem is very common. I want to build a JSON REST API in Python (and possibly R later) to exchange data between applications. (I don't want to use BJSON or other binary formats at this point)</p>
<p>Given the availability of schemas and (de-)serialization frameworks, I thought it would be straightforwa... | 2 | 2016-06-02T09:18:57Z | 37,589,302 | <p>It's not very clear what your problem with serialization and deserialization is. Most web frameworks would not treat URL query parameters as a JSON object, but rather treat each key separately and allow you to access the query string as a dictionary (or as arguments to the request handler, depending on framework). S... | 0 | 2016-06-02T10:30:42Z | [
"python",
"json",
"deserialization",
"avro",
"jsonschema"
] |
Python JSON REST framework with (de)serialiser and schema validation (jsonschema/avro) | 37,587,620 | <p>I think my problem is very common. I want to build a JSON REST API in Python (and possibly R later) to exchange data between applications. (I don't want to use BJSON or other binary formats at this point)</p>
<p>Given the availability of schemas and (de-)serialization frameworks, I thought it would be straightforwa... | 2 | 2016-06-02T09:18:57Z | 37,589,643 | <p>Two things come to my mind.</p>
<p>First, there's an <a href="http://python-eve.org/" rel="nofollow">Eve REST framework</a>, written on top of Flask.</p>
<p>It's author also created (and used in Eve) a schema/validation language, called <a href="http://docs.python-cerberus.org/en/stable/" rel="nofollow">Cerberus</... | 0 | 2016-06-02T10:46:01Z | [
"python",
"json",
"deserialization",
"avro",
"jsonschema"
] |
Python JSON REST framework with (de)serialiser and schema validation (jsonschema/avro) | 37,587,620 | <p>I think my problem is very common. I want to build a JSON REST API in Python (and possibly R later) to exchange data between applications. (I don't want to use BJSON or other binary formats at this point)</p>
<p>Given the availability of schemas and (de-)serialization frameworks, I thought it would be straightforwa... | 2 | 2016-06-02T09:18:57Z | 38,401,233 | <p>I was looking around a lot, not finding what I was looking for. Projects like <a href="http://marshmallow.readthedocs.io/en/latest/" rel="nofollow">Marshmallow</a> came close. They allow specification of schemas and provide for serialization, however I wanted the jsonschema format for interoperability.</p>
<p>So I'... | 0 | 2016-07-15T16:43:12Z | [
"python",
"json",
"deserialization",
"avro",
"jsonschema"
] |
Shell Script: execute & repeat a python program that needs extra input | 37,587,774 | <p>I have to run this python command: <code>python manage.py rebuild_index</code> at a certain time and rerun again. Therefore, I am trying the shell script to run it. However, when run this python command, I have to choose <code>y</code> to continue.</p>
<p><a href="http://i.stack.imgur.com/RucGq.png" rel="nofollow">... | -1 | 2016-06-02T09:26:29Z | 37,587,838 | <p>Try using a <a href="https://en.wikipedia.org/wiki/Pipeline_(Unix)" rel="nofollow">pipe</a> (redirects the output from <code>echo</code> to <code>python</code>'s <code>stdin</code>):</p>
<pre><code>echo "y" | python manage.py rebuild_index
</code></pre>
| 1 | 2016-06-02T09:28:48Z | [
"python",
"bash",
"shell"
] |
Shell Script: execute & repeat a python program that needs extra input | 37,587,774 | <p>I have to run this python command: <code>python manage.py rebuild_index</code> at a certain time and rerun again. Therefore, I am trying the shell script to run it. However, when run this python command, I have to choose <code>y</code> to continue.</p>
<p><a href="http://i.stack.imgur.com/RucGq.png" rel="nofollow">... | -1 | 2016-06-02T09:26:29Z | 37,587,958 | <p>You can use <a href="http://linux.die.net/man/1/yes" rel="nofollow"><code>yes</code></a> for this:</p>
<pre><code>yes | python /manage.py rebuild_index
</code></pre>
<p>One way to run your script every minute:</p>
<pre><code>while yes | python /manage.py rebuild_index; do
sleep 60
done
</code></pre>
<p>The abo... | 1 | 2016-06-02T09:34:03Z | [
"python",
"bash",
"shell"
] |
Shell Script: execute & repeat a python program that needs extra input | 37,587,774 | <p>I have to run this python command: <code>python manage.py rebuild_index</code> at a certain time and rerun again. Therefore, I am trying the shell script to run it. However, when run this python command, I have to choose <code>y</code> to continue.</p>
<p><a href="http://i.stack.imgur.com/RucGq.png" rel="nofollow">... | -1 | 2016-06-02T09:26:29Z | 37,588,700 | <p>You can use <code>echo "y"</code> (as @LogicStuff said) and <code>cron</code> jobs to accomplish this.</p>
<p>Create a script file (let's say <code>your_script.sh</code>) and add your command to it</p>
<pre><code>echo "y" | python manage.py rebuild_index
</code></pre>
<p>To use <code>cron</code> you can use the f... | 1 | 2016-06-02T10:03:56Z | [
"python",
"bash",
"shell"
] |
How to manipulate dict properly? | 37,587,867 | <p>I have this dictionary:</p>
<pre><code>self.rewards = {'D': -1,'0':100,'&':-100}
</code></pre>
<p><code>'D'</code> is a key for a standard reward <code>-1</code>.</p>
<p><code>'0'</code> is a key for a good reward <code>100</code>.</p>
<p><code>'&'</code> is a key for a bad reward <code>-100</code>.</p>
... | 0 | 2016-06-02T09:30:09Z | 37,587,952 | <p>Why not building a function:</p>
<pre><code>def getRewards(val):
return -1 if val=='D' else val
In [195]: getRewards(100)
Out[195]: 100
In [196]: getRewards('D')
Out[196]: -1
</code></pre>
| 1 | 2016-06-02T09:33:44Z | [
"python",
"python-2.7"
] |
How to manipulate dict properly? | 37,587,867 | <p>I have this dictionary:</p>
<pre><code>self.rewards = {'D': -1,'0':100,'&':-100}
</code></pre>
<p><code>'D'</code> is a key for a standard reward <code>-1</code>.</p>
<p><code>'0'</code> is a key for a good reward <code>100</code>.</p>
<p><code>'&'</code> is a key for a bad reward <code>-100</code>.</p>
... | 0 | 2016-06-02T09:30:09Z | 37,587,964 | <p>Yes. That is possible.</p>
<pre><code>>>> keys = ['hello','D']
>>> d = dict()
>>> for k in keys:
... if k == 'D':
... d[k] = -1
... else:
... d[k] = k
...
>>> d
{'hello': 'hello', 'D': -1}
</code></pre>
| 0 | 2016-06-02T09:34:12Z | [
"python",
"python-2.7"
] |
How to manipulate dict properly? | 37,587,867 | <p>I have this dictionary:</p>
<pre><code>self.rewards = {'D': -1,'0':100,'&':-100}
</code></pre>
<p><code>'D'</code> is a key for a standard reward <code>-1</code>.</p>
<p><code>'0'</code> is a key for a good reward <code>100</code>.</p>
<p><code>'&'</code> is a key for a bad reward <code>-100</code>.</p>
... | 0 | 2016-06-02T09:30:09Z | 37,587,970 | <p>With a dict comprehension:</p>
<pre><code> self.rewards = {k: k for k, v in self.rewards.items()}
self.rewards['D'] = -1
</code></pre>
| 0 | 2016-06-02T09:34:59Z | [
"python",
"python-2.7"
] |
How to manipulate dict properly? | 37,587,867 | <p>I have this dictionary:</p>
<pre><code>self.rewards = {'D': -1,'0':100,'&':-100}
</code></pre>
<p><code>'D'</code> is a key for a standard reward <code>-1</code>.</p>
<p><code>'0'</code> is a key for a good reward <code>100</code>.</p>
<p><code>'&'</code> is a key for a bad reward <code>-100</code>.</p>
... | 0 | 2016-06-02T09:30:09Z | 37,587,977 | <p>You can use the <code>get</code>-method of dicts:</p>
<pre><code>reward = int(self.rewards.get(next.tipo, next.tipo))
</code></pre>
| 0 | 2016-06-02T09:35:15Z | [
"python",
"python-2.7"
] |
How to manipulate dict properly? | 37,587,867 | <p>I have this dictionary:</p>
<pre><code>self.rewards = {'D': -1,'0':100,'&':-100}
</code></pre>
<p><code>'D'</code> is a key for a standard reward <code>-1</code>.</p>
<p><code>'0'</code> is a key for a good reward <code>100</code>.</p>
<p><code>'&'</code> is a key for a bad reward <code>-100</code>.</p>
... | 0 | 2016-06-02T09:30:09Z | 37,588,556 | <p>You may use following</p>
<pre><code>t ={v: v for k, v in self.rewards.items() if k is not 'D'}
t['D'] = self.rewards.get('D')
</code></pre>
| 0 | 2016-06-02T09:58:29Z | [
"python",
"python-2.7"
] |
Edit variable of a netcdf file using python | 37,587,921 | <p>I am working with MITgcm to make some simulations, specifically to work with internal waves models; I got .nc files with my results but some variables are not in exactly the same coordinates. I'll explain myself: I want to work out the components of velocity but, for some numerical reasons that I don't fully underst... | 1 | 2016-06-02T09:32:07Z | 37,595,395 | <p>That model is using a <a href="https://en.wikipedia.org/wiki/Arakawa_grids" rel="nofollow">staggered grid</a> where u-velocity is solved on the west/east grid faces, while v-velocity is solved on the north/south faces.</p>
<p>You are right that now you need to post-process the components so that u- and v- are each ... | 2 | 2016-06-02T14:58:02Z | [
"python",
"netcdf"
] |
How to get character level difference using âdifflibâ command in Linux using python? | 37,587,935 | <p>I have two SQL files, one is old.sql and the other one is new.sql.</p>
<p>Suppose old.sql contains a table with three fields, Emp_Id, Name and Address and data stored in old.sql as follows:</p>
<pre><code>Insert into table1 values (101 ,"a", "xyz");
Insert into table1 values (102 ,"b", "pqr");
</code></pre>
<p>Th... | 1 | 2016-06-02T09:32:52Z | 37,588,080 | <p>The problem is that <code>diff</code> doesn't know what part of the line you define as "data" and what as "syntax". If you did a line-wise diff, you would get <code>123");</code> to be the part that is different.</p>
<pre><code>Insert into table1 values (101 ,"a", "xyz");
Insert into table1 values (101 ,"a", "xyz12... | 0 | 2016-06-02T09:39:38Z | [
"python",
"linux"
] |
Python Selenium Failing When Some Threads Create Webdriver | 37,587,942 | <p>I have a thread which takes a URL, requests it in selenium and parses up the data.</p>
<p>Most of the time this thread works fine. But sometimes it seems to hang on creating the webdriver and I can't seem to exception handle it.</p>
<p>This is the start of the thread:</p>
<pre><code>def GetLink(eachlink):
tr... | 1 | 2016-06-02T09:33:13Z | 37,593,609 | <p>I've encountered this with both multithreading and multiprocessing, and when using Firefox, Chrome, or PhantomJS. For whatever reason, the call to instantiate the browser (e.q. <code>driver = webdriver.Chrome()</code>), never returns.</p>
<p>Most of my scripts are relatively short lived with few threads/processes, ... | 1 | 2016-06-02T13:41:06Z | [
"python",
"multithreading",
"selenium"
] |
Python: searching through set of objects | 37,588,200 | <p>I have a set of objects <code>W</code> that have the attributes name and a score. The <code>__hash__()</code> function is based upon the name only, and the <code>__eq__()</code> function is not defined, so it is based upon the <code>__hash__()</code> function.</p>
<p>Now, I want to use the score of the object. Is t... | -1 | 2016-06-02T09:44:13Z | 37,588,296 | <p>You can use the <code>in</code> operator to check for set membership. This is a constant time operation in sets and dictionaries, since they are implemented as hash tables. For lists and tuples <code>in</code> is linear time.</p>
<pre><code>obj = W("myname", 0)
if obj in w_set:
# do something with obj
</code></... | 1 | 2016-06-02T09:47:44Z | [
"python",
"object",
"set"
] |
Python: searching through set of objects | 37,588,200 | <p>I have a set of objects <code>W</code> that have the attributes name and a score. The <code>__hash__()</code> function is based upon the name only, and the <code>__eq__()</code> function is not defined, so it is based upon the <code>__hash__()</code> function.</p>
<p>Now, I want to use the score of the object. Is t... | -1 | 2016-06-02T09:44:13Z | 37,611,889 | <p>You don't say how you set up your object, but why not just use <code>if obj.score == 0</code>?</p>
<pre><code>for obj in w_set:
if obj.score == 0:
break
</code></pre>
<p>Or perhaps your question is about avoiding the linear search?
If you have a lot of objects and you'll be doing a lot of searches by s... | 0 | 2016-06-03T10:24:43Z | [
"python",
"object",
"set"
] |
django rest framework foreign key serializer issue | 37,588,228 | <p>i am new to DJango Python webservices and i am facing small issue with the serializers.here is my code.</p>
<pre><code>**views.py**
@csrf_exempt
@api_view(['GET'])
def sqlservice(request):
if request.method == 'GET':
posts = tbl_dcs.objects.all()
for each in posts:
manid = each.manag... | 0 | 2016-06-02T09:45:08Z | 37,588,391 | <p>use <code>serializers.SerializerMethodField</code> to get manager name like below..</p>
<pre><code>class PostSerializer(serializers.ModelSerializer):
managername = serializers.SerializerMethodField('get_manager_name')
class Meta:
model = tbl_dcs
fields = ('id', 'name','location','address','... | 0 | 2016-06-02T09:51:50Z | [
"python",
"json",
"serializer"
] |
Reduce the program size(bytes) | 37,588,234 | <pre><code>import os
os.system('ffmpeg -i aa.wmv -map 0:1 -c:a aac -b:a 256k -strict experimental -cutoff 22000 m.aac')
os.system('ffmpeg -i aa.wmv -c:v libx264 -an my.mp4')
os.system('ffmpeg -i m.aac -i my.mp4 -c:v copy -c:a copy -bsf:a aac_adtstoasc myq.mp4')
</code></pre>
<p>Is there a way to reduce this program's ... | -2 | 2016-06-02T09:45:16Z | 37,588,557 | <p>147 bytes:</p>
<pre><code>#!/bin/bash
ffmpeg -i aa.wmv -map 0:1 -c:a aac -b:a 256k -strict experimental -cutoff 22000 m.aac
ffmpeg -i aa.wmv -c:v libx264 -an my.mp4
ffmpeg -i m.aac -i my.mp4 -c:v copy -c:a copy -bsf:a aac_adtstoasc myq.mp4
</code></pre>
| 2 | 2016-06-02T09:58:31Z | [
"python"
] |
Reduce the program size(bytes) | 37,588,234 | <pre><code>import os
os.system('ffmpeg -i aa.wmv -map 0:1 -c:a aac -b:a 256k -strict experimental -cutoff 22000 m.aac')
os.system('ffmpeg -i aa.wmv -c:v libx264 -an my.mp4')
os.system('ffmpeg -i m.aac -i my.mp4 -c:v copy -c:a copy -bsf:a aac_adtstoasc myq.mp4')
</code></pre>
<p>Is there a way to reduce this program's ... | -2 | 2016-06-02T09:45:16Z | 37,588,752 | <p>You can gzip (or use any other compression method) and decompress when needed.</p>
| 1 | 2016-06-02T10:06:11Z | [
"python"
] |
Program restarts when a function returns | 37,588,269 | <p>I've made a program which does Pythagoras theorem for you if you just insert the lengths of the sides. </p>
<pre><code>from math import *
def pythag(a , b):
c = sqrt(a^2 + b^2)
return c
print(pythag(3,4)) # added this as recommended in comment
</code></pre>
<p>But when I run it, this happens:</p>
<pre><... | -4 | 2016-06-02T09:46:32Z | 37,588,433 | <p>You've written a function that does what you say but you're not actually calling it anywhere. The top level statements in your program are an <code>import</code> and a <code>def</code> and only those are called when you "run" it. </p>
| 2 | 2016-06-02T09:53:22Z | [
"python",
"python-3.x"
] |
Program restarts when a function returns | 37,588,269 | <p>I've made a program which does Pythagoras theorem for you if you just insert the lengths of the sides. </p>
<pre><code>from math import *
def pythag(a , b):
c = sqrt(a^2 + b^2)
return c
print(pythag(3,4)) # added this as recommended in comment
</code></pre>
<p>But when I run it, this happens:</p>
<pre><... | -4 | 2016-06-02T09:46:32Z | 37,588,481 | <p>You have to run the function after the code you already have (e.g. for values 3 and 4):</p>
<pre><code>from math import *
def pythag (a, b):
c = sqrt(a**2 + b**2)
return c
print(pythag(3,4))
</code></pre>
| 0 | 2016-06-02T09:55:19Z | [
"python",
"python-3.x"
] |
Program restarts when a function returns | 37,588,269 | <p>I've made a program which does Pythagoras theorem for you if you just insert the lengths of the sides. </p>
<pre><code>from math import *
def pythag(a , b):
c = sqrt(a^2 + b^2)
return c
print(pythag(3,4)) # added this as recommended in comment
</code></pre>
<p>But when I run it, this happens:</p>
<pre><... | -4 | 2016-06-02T09:46:32Z | 37,599,758 | <p>Rather than importing math you could use the power signs.</p>
<p>For example:</p>
<pre><code>def pythag(a , b):
c = (a**2 + b**2)**0.5
return c
print(pythag(3,4))
</code></pre>
| 0 | 2016-06-02T18:39:00Z | [
"python",
"python-3.x"
] |
Why next(a) giving error while next(ia) returning first element of the list in Pyhton? | 37,588,311 | <pre><code> >>> a=[1,2,3,4,5,6]
>>> iter(a)
<listiterator object at 0x7f96f3273950>
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
>>> ia=iter(a)
>>>... | -3 | 2016-06-02T09:48:20Z | 37,588,576 | <p>It's literally because of what the exception is telling you:</p>
<blockquote>
<p>list object is not an iterator</p>
</blockquote>
<p>To be able to iterate over a sequence you need to have a current location and a list has no concept of this because that would mean that everyone who shares the list would also sha... | 3 | 2016-06-02T09:59:15Z | [
"python",
"list",
"iterator",
"listiterator"
] |
Deploy Django project on RedHat | 37,588,417 | <p>I'm trying to deploy my local Django project on my RedHat server. So I install all the libraries and dependencies that I needed (also mod_wsgi).</p>
<p>So, I edit my project's settings and move my local project to the server. But I'm facing an issue: when I try to reach the URL of my project, I have the explorer vi... | 3 | 2016-06-02T09:52:51Z | 37,688,157 | <p>Here's a working example Apache config I have on CentOS 6.8 with Apache 2.2; I'd name it something like <code>yourproject.conf</code> and include it in <code>/etc/httpd/conf.d</code> so it is included by the master Apache config file:</p>
<pre><code>LoadModule wsgi_module modules/mod_wsgi.so
LoadModule ssl_module m... | 3 | 2016-06-07T19:53:23Z | [
"python",
"django",
"apache",
"mod-wsgi",
"redhat"
] |
Deploy Django project on RedHat | 37,588,417 | <p>I'm trying to deploy my local Django project on my RedHat server. So I install all the libraries and dependencies that I needed (also mod_wsgi).</p>
<p>So, I edit my project's settings and move my local project to the server. But I'm facing an issue: when I try to reach the URL of my project, I have the explorer vi... | 3 | 2016-06-02T09:52:51Z | 37,757,884 | <p>This is an example <code>/etc/httpd/conf/httpd.conf</code> file:</p>
<pre><code><VirtualHost *:80>
ServerName my.webapp.com
ServerAlias my.webapp.com
ErrorLog /var/www/my.webapp.com/error.log
WSGIDaemonProcess my.webapp.com \
python-path=/var/www/my.webapp.com/my-django-project:/ho... | 0 | 2016-06-10T22:18:43Z | [
"python",
"django",
"apache",
"mod-wsgi",
"redhat"
] |
Django save scientific number | 37,588,432 | <p>I'm trying to find a way to format a scientific number and save it into database. My number is read from a csv file. </p>
<p>model.py</p>
<pre><code>class Doc(models.Model):
....
big=models.BigIntegerField(null=True)
</code></pre>
<p>views.py</p>
<pre><code>for line in csvfile:
data = Doc()
data.big=... | 2 | 2016-06-02T09:53:21Z | 37,588,627 | <p>Your data is malformed. While the int('2,02161E+12') and float('2,02161E+12') would indeed produce that error float('2.02161E+12') would not. So the solution is</p>
<pre><code>int( float('2,02161E+12'.replace(',','.')) )
</code></pre>
| 1 | 2016-06-02T10:00:49Z | [
"python",
"mysql",
"django"
] |
How to remain in python interactive interpreter after running program? | 37,588,467 | <p>I am running python program from terminal</p>
<pre><code>python -i abc.py <test.txt
</code></pre>
<p>but after completion of the program it does not remain in python.</p>
<p>what I want:</p>
<pre><code>Output:
4 21
>>>
</code></pre>
<p>What is happening--</p>
<pre><code>Output:
4 21
>>> &g... | 1 | 2016-06-02T09:54:54Z | 37,589,467 | <p>You redirect the stdin, so when the file ends, the process exits.</p>
<p>What you is read from the file first, then from stdin:</p>
<pre><code>(cat test.txt && cat) | python -i abc.py
</code></pre>
<p>Without any arguments, cat reads from stdin. So in this case, the python process first receives this outp... | 3 | 2016-06-02T10:38:12Z | [
"python",
"python-interactive"
] |
Converting a multidimensional array of strings into a multidimensional array of numbers | 37,588,631 | <p>I am trying to convert this array of strings: </p>
<pre><code>[['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00','0'] ['1', '222.2']]
</code></pre>
<p>into an array that looks the same but is made of numbers because I need to make comput... | 0 | 2016-06-02T10:00:59Z | 37,589,262 | <p>You first have to convert your list of lists to a numpy array.</p>
<pre><code>>>> import numpy as np
>>> list_of_lists = [['1', '1.5'], ['2', '2.5'], ['3', '3.5']]
>>> numpy_array = np.array(list_of_lists)
>>> float_array = numpy_array.astype(np.float)
>>> float_array
ar... | 0 | 2016-06-02T10:28:51Z | [
"python",
"arrays",
"string",
"multidimensional-array",
"data-type-conversion"
] |
Converting a multidimensional array of strings into a multidimensional array of numbers | 37,588,631 | <p>I am trying to convert this array of strings: </p>
<pre><code>[['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00','0'] ['1', '222.2']]
</code></pre>
<p>into an array that looks the same but is made of numbers because I need to make comput... | 0 | 2016-06-02T10:00:59Z | 37,589,300 | <p>Solution with basic python list approach</p>
<pre><code>>>> array_str = [['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00', '0'], ['1', '2']]
>>> array_n = [[float(num) for num in item] for item in array_str]
>>>... | 0 | 2016-06-02T10:30:37Z | [
"python",
"arrays",
"string",
"multidimensional-array",
"data-type-conversion"
] |
Converting a multidimensional array of strings into a multidimensional array of numbers | 37,588,631 | <p>I am trying to convert this array of strings: </p>
<pre><code>[['2014', '913', '5.78254241807211', '52.3749951170618', '2014', '1', '2024448.00', '89316.00', '29187.00', '427000.00', '60.00','0'] ['1', '222.2']]
</code></pre>
<p>into an array that looks the same but is made of numbers because I need to make comput... | 0 | 2016-06-02T10:00:59Z | 37,592,474 | <p>Have you tried the float or int method ?</p>
<pre><code> array = ['2014','913','5.78254241807211','52.3749951170618','2014','1','2024448.00','89316.00' ,'29187.00', '427000.00' ,'60.00'],['1','2','8']]
floatlist=[[float(str) for str in subarray] for subarray in array]
print floatlist
</code></pre>
| 0 | 2016-06-02T12:53:39Z | [
"python",
"arrays",
"string",
"multidimensional-array",
"data-type-conversion"
] |
Create a conda environment offline | 37,588,697 | <p>I have Anaconda2 installed on a remote machine where there is no internet connection.</p>
<p>I am trying to create a <code>conda</code> environment where I would run my application,when I tried :</p>
<pre><code> conda create -n nameofmyenv anaconda
</code></pre>
<p>but since it fetches packages from api.anacon... | 0 | 2016-06-02T10:03:50Z | 37,699,369 | <p>I found a way to get my code working without dependency issues, which is to clear the pythonpath variable, and then make it point to the python of Anaconda like so :
<code>export PYTHONPATH="~/anaconda2/bin/python"</code>. </p>
<p>This way I have no import problems on the remote machine with no internet connection ... | 0 | 2016-06-08T10:03:39Z | [
"python",
"anaconda",
"offline",
"environment",
"conda"
] |
Python 2.7 How to get all residuals out of a list received from Polyfit | 37,588,736 | <p>currently I have big Arrays (1051 Elements) for x,y and z.
My aim is to fit the best polynominal function for x,y,z respective -> t (time = 1051) in steps of 10.</p>
<p>To find out, which degree is the best fit, I gave the polyfit method the parameter full=True. So I get the residuals of the least square fit. I sa... | 0 | 2016-06-02T10:05:34Z | 37,594,776 | <p>I found a solution:</p>
<pre><code> while pos < n:
coeff,bonus = np.polynomial.polynomial.polyfit(t[pos:(pos+steps)],mag[pos:(pos+steps)],deg,full=True)
fkt.append(coeff)
res.append(bonus[0])
pos += steps
print res
</code></pre>
<p>Give me only the first entries of the bonus information I get... | 0 | 2016-06-02T14:30:33Z | [
"python",
"arrays",
"list",
"indexing"
] |
Error connecting py2neo | 37,588,742 | <p>I'm trying to connect my neo4J DB with Python using py2neo.</p>
<p>I'm following the example extracted from py2neo 2 API but there's no way to get it work.</p>
<p>My code:</p>
<pre><code>from py2neo import Graph
graph = Graph("http://neo4j:1234@localhost:7474/C:/Users/htilmatine/Documents/Neo4j/default.graphdb")
... | 0 | 2016-06-02T10:05:47Z | 37,589,439 | <p>The connection docs are <a href="http://py2neo.org/2.0/essentials.html#the-graph" rel="nofollow">here</a>.</p>
<p>If you're just using a default install and default graph data directory, you should be able to connect with:</p>
<pre><code>graph = Graph("http://neo4j:1234@localhost:7474/db/data")
</code></pre>
<p>o... | 2 | 2016-06-02T10:36:57Z | [
"python",
"python-2.7",
"neo4j",
"py2neo"
] |
Error connecting py2neo | 37,588,742 | <p>I'm trying to connect my neo4J DB with Python using py2neo.</p>
<p>I'm following the example extracted from py2neo 2 API but there's no way to get it work.</p>
<p>My code:</p>
<pre><code>from py2neo import Graph
graph = Graph("http://neo4j:1234@localhost:7474/C:/Users/htilmatine/Documents/Neo4j/default.graphdb")
... | 0 | 2016-06-02T10:05:47Z | 37,609,251 | <p>I'm concerned about seeing <code>py2neo-2.0a0</code> in your path name. I'd strongly recommend using a more up-to-date version of py2neo, specifically not an alpha release.</p>
| 0 | 2016-06-03T08:10:37Z | [
"python",
"python-2.7",
"neo4j",
"py2neo"
] |
Python Class and List Filters | 37,588,775 | <p>To get to the point I'm learning how to work classes and list comprehension and I'm running into this problem:</p>
<pre><code>class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def are_in_first_quadrant(listPoint):
newListPoint = filter(lambda pnt: pnt.x > 0 and pnt.y > 0, l... | 0 | 2016-06-02T10:07:10Z | 37,589,179 | <p>You need to provide a <a href="https://docs.python.org/2/reference/datamodel.html#object.__repr__" rel="nofollow"><code>__repr__()</code> method</a> for your <code>Point</code> class: </p>
<pre><code>class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
re... | 2 | 2016-06-02T10:24:35Z | [
"python",
"python-2.7",
"class",
"filter"
] |
python create multiple json objects | 37,588,782 | <p>I am trying to build a list in Python as below. I want to call this function multiple times and build a json array, when i try with <code>json.dumps for p in range (0,10)</code> it adds extra <code>[]</code> for each json object</p>
<pre><code>def buildlist():
objects_list = []
d = collections.OrderedDict()
... | 0 | 2016-06-02T10:07:28Z | 37,589,212 | <p>I'm not exactly sure what your question is. But the function you posted will always return a list containing just a single OrderedDict. Why don't you just return the OrderedDict and build the list outside the function?</p>
<pre><code>def builditem():
d = collections.OrderedDict()
d['batteryLevel'] = random.ra... | 0 | 2016-06-02T10:26:02Z | [
"python",
"json"
] |
seeking a way to initialize dict in a more efficient way | 37,588,793 | <pre><code>prior={}
conditionProb={}
Counts={}
for i in range(len(trainingData)):
label=trainingLabels[i]
prior[label]+=1
datum=trainingData[i]
for j in range(len(datum)):
Counts[(i,j,label)]+=1
if(datum[j]>0):
conditionProb[(i,j,label)]+=1
</code></pre>
<p>when I run th... | 1 | 2016-06-02T10:08:06Z | 37,588,832 | <p>You can use defaultdict from the collections module. You construct it passing the type of values in there, in this case an int, plus a default value if it's not set (default is 0). Do it like this:</p>
<pre><code>from collections import defaultdict
my_dict = defaultdict(int)
my_dict['foo'] += 2
</code></pre>
| 0 | 2016-06-02T10:09:33Z | [
"python",
"dictionary"
] |
seeking a way to initialize dict in a more efficient way | 37,588,793 | <pre><code>prior={}
conditionProb={}
Counts={}
for i in range(len(trainingData)):
label=trainingLabels[i]
prior[label]+=1
datum=trainingData[i]
for j in range(len(datum)):
Counts[(i,j,label)]+=1
if(datum[j]>0):
conditionProb[(i,j,label)]+=1
</code></pre>
<p>when I run th... | 1 | 2016-06-02T10:08:06Z | 37,588,902 | <p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a>:</p>
<pre><code>>>> from collections import Counter
>>> c = Counter()
>>> c['a'] += 2
>>> c
Counter({'a': 2})
</code></pre>
| 0 | 2016-06-02T10:12:55Z | [
"python",
"dictionary"
] |
seeking a way to initialize dict in a more efficient way | 37,588,793 | <pre><code>prior={}
conditionProb={}
Counts={}
for i in range(len(trainingData)):
label=trainingLabels[i]
prior[label]+=1
datum=trainingData[i]
for j in range(len(datum)):
Counts[(i,j,label)]+=1
if(datum[j]>0):
conditionProb[(i,j,label)]+=1
</code></pre>
<p>when I run th... | 1 | 2016-06-02T10:08:06Z | 37,588,915 | <p>You can use <code>defaultdict</code> to initialize keys to <code>0</code>:</p>
<pre><code>from collections import defaultdict
prior = defaultdict(lambda: 0)
conditionProb = defaultdict(lambda: 0)
Counts = defaultdict(lambda: 0)
for i, (label, data) in enumerate(zip(trainingLabels, trainingData)):
prior[label]... | 1 | 2016-06-02T10:13:25Z | [
"python",
"dictionary"
] |
Why runs 'pip' as Python 3 module but not as script? | 37,588,957 | <p>I've installed Lubuntu 16.04 LTS that comes with Python 3.5, but with Python 2.7 as default Python interpreter.<br>
Both versions comes without <code>pip</code> package intalled. I only will use the 3.5 version. So I've installed <code>pip3</code> with:</p>
<pre><code>$ sudo apt-get install python3-pip
</code></p... | 0 | 2016-06-02T10:15:01Z | 37,589,366 | <p>pip3 is in reality the pip package for python3. Since both python2 and python3 can coexist, the pip package for 3.5 is renamed as pip3 to avoid conflict. (By the package manager). </p>
<p>The upgrade syntax for any package is </p>
<pre><code><script_name_for_pip> install --upgrade <package_name>
</code... | 3 | 2016-06-02T10:34:08Z | [
"python",
"python-3.x",
"ubuntu",
"pip"
] |
Why runs 'pip' as Python 3 module but not as script? | 37,588,957 | <p>I've installed Lubuntu 16.04 LTS that comes with Python 3.5, but with Python 2.7 as default Python interpreter.<br>
Both versions comes without <code>pip</code> package intalled. I only will use the 3.5 version. So I've installed <code>pip3</code> with:</p>
<pre><code>$ sudo apt-get install python3-pip
</code></p... | 0 | 2016-06-02T10:15:01Z | 37,589,464 | <p><a href="http://legacy.python.org/dev/peps/pep-0394/" rel="nofollow" title="PEP 394">PEP 394</a> describes naming of Python binaries, and according to its recommendations, you have <code>pip3</code> in system because <code>pip</code> is reserved for Python 2.x pip.</p>
<p>Of course you can alias <code>pip</code> to... | 0 | 2016-06-02T10:38:02Z | [
"python",
"python-3.x",
"ubuntu",
"pip"
] |
open cv : A series of OpenCV convenience functions.s imutils and cvuitls not installing | 37,589,142 | <p>i tried with this link <a href="https://pypi.python.org/pypi/cvutils/0.1" rel="nofollow">https://pypi.python.org/pypi/cvutils/0.1</a></p>
<p>i tried many ways but I'm not getting proper way to install these things. my pip version is 1.5.4 . <code>pip install imutils and cvutils</code> the logon terminal is as foll... | 0 | 2016-06-02T10:22:29Z | 37,589,502 | <p>You must have root permission to install python packages system wide.</p>
<p>Use <code>sudo pip install cvutils</code> or install it in a virtualenv.</p>
| 0 | 2016-06-02T10:39:37Z | [
"python",
"opencv",
"numpy",
"pip",
"ubuntu-14.04"
] |
Drawing an antialiased circle as described by Xaolin Wu | 37,589,165 | <p>I'm tyring to implement the âFast Anti-Aliased Circle Generatorâ routine that was described by Xiaolin Wu in his paper âAn Efficient Antialiasing Techniqueâ from Siggraph '91.</p>
<p>This is the code that I wrote using Python 3 and PySDL2:</p>
<pre><code>def draw_antialiased_circle(renderer, position, radi... | 8 | 2016-06-02T10:23:37Z | 37,712,706 | <p>I got the following to work on my machine:</p>
<pre><code>def draw_antialiased_circle(renderer, position, radius, alpha_max=sdl2.SDL_ALPHA_OPAQUE):
def _draw_points(i, j):
'''Draws 8 points, one on each octant.'''
#Square symmetry
local_coord = [(i*(-1)**(k%2), j*(-1)**(k/... | 1 | 2016-06-08T20:52:50Z | [
"python",
"algorithm",
"geometry",
"sdl",
"sdl-2"
] |
Drawing an antialiased circle as described by Xaolin Wu | 37,589,165 | <p>I'm tyring to implement the âFast Anti-Aliased Circle Generatorâ routine that was described by Xiaolin Wu in his paper âAn Efficient Antialiasing Techniqueâ from Siggraph '91.</p>
<p>This is the code that I wrote using Python 3 and PySDL2:</p>
<pre><code>def draw_antialiased_circle(renderer, position, radi... | 8 | 2016-06-02T10:23:37Z | 37,714,284 | <p>Let's deconstruct your implementation to find out what mistakes you made:</p>
<pre><code>def draw_antialiased_circle(renderer, position, radius):
</code></pre>
<p>First question, what does <code>radius</code> mean? It's impossible to draw a circle, you can only draw an annulus (a ring / donut), because unless you... | 2 | 2016-06-08T22:58:23Z | [
"python",
"algorithm",
"geometry",
"sdl",
"sdl-2"
] |
python - threading and infinite loops | 37,589,193 | <p>inside the main python script, at a point variable <code>VAR</code> is set and thread <code>THR</code> is executed with variable <code>VAR</code> as starting value.<br>
within <code>THR</code> there's an infinite loop, which prints <code>VAR</code> every 500 <em>ms</em>.<br>
meanwhile the main script crunches some m... | 0 | 2016-06-02T10:25:07Z | 37,589,706 | <p>You should use a list with your variable inside.</p>
<p>If you pass the list to the function, you will be able to modify the value of the first position of the list (outside the function) and at the same time you'll see how the thread prints the correct value.</p>
<p>Pseudocode:</p>
<pre><code>(THREAD)
while ... | 1 | 2016-06-02T10:48:45Z | [
"python",
"multithreading"
] |
How to correct the time data from 'csv' file and plot the graph in python | 37,589,198 | <p>I want to use the time data to plot the pictures, I want use the time as <code>x-label</code>. But the time data in the CSV file (automatically generated by Datalogger) includes <code>mS</code>. I want to read the time data and one or two columns data as <code>y</code>.
But the plots cannot be drawn. Since I am a b... | 0 | 2016-06-02T10:25:25Z | 37,590,457 | <p>If you need to plot every column of csv-file, first you have to store data to array or list, and after getting all data plot lines:</p>
<pre><code>from matplotlib.pyplot import *
from collections import namedtuple
import os, sys, glob, math
import random
import csv
import datetime
import pandas as pd
import matplot... | 0 | 2016-06-02T11:23:26Z | [
"python",
"csv",
"pandas",
"matplotlib"
] |
Not able to get_item from AWS dynamodb using python? | 37,589,254 | <p>I am new to dynamodb trying to get data from dynamodb.</p>
<p><a href="http://i.stack.imgur.com/GVoXN.jpg" rel="nofollow">This is my table with "topic" as a primary hash key</a></p>
<p>my python code</p>
<pre><code>import boto3
from boto3 import dynamodb
from boto3.session import Session
from boto3.dynamodb.c... | 0 | 2016-06-02T10:28:14Z | 37,610,132 | <p>The correct syntax is:</p>
<pre><code>response = table.get_item(TableName='Garbage_collector_table', Key={'topic':{'S':str(my_topic)}})
</code></pre>
<p>but personally i recommend to use boto client:</p>
<pre><code>client = boto3.client('dynamodb')
response = client.get_item(TableName='Garbage_collector_table', ... | 0 | 2016-06-03T09:00:07Z | [
"python",
"nosql",
"amazon-dynamodb",
"boto3"
] |
Return variable from a function | 37,589,373 | <p>This section of a program I am writing is supposed to take the random choice and then print it outside the function (I can't print from within as I need the variable later).
I am sure there is a simple solution to this, but I am unsure what it is.</p>
<pre><code>#python2
def CompTurn():
RandTurn = [Column1,Column... | -1 | 2016-06-02T10:34:17Z | 37,589,404 | <p>Add the line </p>
<pre><code>Choice = CompTurn()
</code></pre>
<p>before your print statement. Because the variables you declare within the function are not known outside of it, you have to store (or print directly, but then you cannot store it) the returned variable in a new variable.</p>
| 1 | 2016-06-02T10:35:20Z | [
"python",
"python-2.7",
"variables",
"return"
] |
Return variable from a function | 37,589,373 | <p>This section of a program I am writing is supposed to take the random choice and then print it outside the function (I can't print from within as I need the variable later).
I am sure there is a simple solution to this, but I am unsure what it is.</p>
<pre><code>#python2
def CompTurn():
RandTurn = [Column1,Column... | -1 | 2016-06-02T10:34:17Z | 37,589,493 | <p>You have defined your function correctly, but you never executed it! (You'll see that if you make it print something as a diagnostic.) You must run it to get the result:</p>
<pre><code>chosen = CompTurn()
print chosen
</code></pre>
<p>Note that I used a different variable name. You <em>could</em> use the same vari... | 1 | 2016-06-02T10:39:16Z | [
"python",
"python-2.7",
"variables",
"return"
] |
Return variable from a function | 37,589,373 | <p>This section of a program I am writing is supposed to take the random choice and then print it outside the function (I can't print from within as I need the variable later).
I am sure there is a simple solution to this, but I am unsure what it is.</p>
<pre><code>#python2
def CompTurn():
RandTurn = [Column1,Column... | -1 | 2016-06-02T10:34:17Z | 37,589,534 | <p>About your program, you don't need the brackets for <code>return</code>. It's s statement, not a function.</p>
<pre><code>def CompTurn():
RandTurn = [Column1,Column2,Column3,Column4]
Choice = random.choice(RandTurn)
return Choice
</code></pre>
<p>Shorter:</p>
<pre><code>def CompTurn():
RandTurn = [Co... | 1 | 2016-06-02T10:41:00Z | [
"python",
"python-2.7",
"variables",
"return"
] |
Need help writing a regex | 37,589,447 | <p>I need a regex that reads a file with blast information.
The file looks like:</p>
<pre><code>****ALIGNMENT****
Sequence: gi|516137619|ref|WP_017568199.1| hypothetical protein [Nocardiopsis synnemataformans]
length: 136
E_value: 8.9548e-11
score: 153.0
bit_score: 63.5438
identities: 35
positives: 42
gaps: 6
... | 0 | 2016-06-02T10:37:23Z | 37,590,116 | <p>You no need regexp:</p>
<pre><code>parsed = []
raw_parts = open('tmp9.txt','r').read().split('****ALIGNMENT****')
for raw_part in raw_parts:
parsed_dict = {}
for line in raw_part.split('\n'):
try:
key,value = line.split(':')
parsed_dict[key] = value.strip()
except:
pass
parsed.append(parsed_dict)
pr... | 1 | 2016-06-02T11:07:22Z | [
"python",
"regex",
"expression"
] |
assertTrue() in pytest to assert empty lists | 37,589,745 | <p>is there a way to use assertTrue() or assertFalse() like a function in pytest for python unittests.
I have a function which if returns with list of elements, the test needs to get failed through assertion.</p>
<p>is there anything like below:</p>
<pre><code>assertFalse(function_returns_list()), "the list is non em... | 1 | 2016-06-02T10:50:23Z | 37,589,945 | <p>Why not test for the length of the list:</p>
<pre><code>assert len(function_returns_list()) == 0, "the list is non empty"
</code></pre>
| 2 | 2016-06-02T10:59:22Z | [
"python",
"py.test"
] |
assertTrue() in pytest to assert empty lists | 37,589,745 | <p>is there a way to use assertTrue() or assertFalse() like a function in pytest for python unittests.
I have a function which if returns with list of elements, the test needs to get failed through assertion.</p>
<p>is there anything like below:</p>
<pre><code>assertFalse(function_returns_list()), "the list is non em... | 1 | 2016-06-02T10:50:23Z | 37,604,596 | <p>You can <code>assert list</code> to confirm list is not empty, or <code>assert not list</code> to confirm list is empty:</p>
<pre><code>>>> assert not []
>>> assert []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert [1, 2, 3]
... | 1 | 2016-06-03T01:33:31Z | [
"python",
"py.test"
] |
Pandas Read_CSV quotes issue | 37,589,795 | <p>I have a file that looks like:</p>
<pre><code>'colA'|'colB'
'word"A'|'A'
'word'B'|'B'
</code></pre>
<p>I want to use <code>pd.read_csv('input.csv',sep='|', quotechar="'"</code>) but I get the following output:</p>
<pre><code>colA colB
word"A A
wordB' B
</code></pre>
<p>The last row is not correct, it shou... | 2 | 2016-06-02T10:52:22Z | 37,591,065 | <p>The source of the problem is that ' is defined as quote, and as a regular char.</p>
<p>You can escape it e.g.</p>
<pre><code>'colA'|'colB'
'word"A'|'A'
'word/'B'|'B'
</code></pre>
<p>And then use escapechar:</p>
<pre><code>>>> pd.read_csv('input.csv',sep='|',quotechar="'",escapechar="/")
colA colB
... | 0 | 2016-06-02T11:50:41Z | [
"python",
"csv",
"pandas",
"dataframe",
"quoting"
] |
Pandas Read_CSV quotes issue | 37,589,795 | <p>I have a file that looks like:</p>
<pre><code>'colA'|'colB'
'word"A'|'A'
'word'B'|'B'
</code></pre>
<p>I want to use <code>pd.read_csv('input.csv',sep='|', quotechar="'"</code>) but I get the following output:</p>
<pre><code>colA colB
word"A A
wordB' B
</code></pre>
<p>The last row is not correct, it shou... | 2 | 2016-06-02T10:52:22Z | 37,591,173 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a>:</p>
<pre><code>import pandas... | 1 | 2016-06-02T11:55:06Z | [
"python",
"csv",
"pandas",
"dataframe",
"quoting"
] |
Is it PEP8 compliant to import CamelCase as lowercase? | 37,589,942 | <p>According to <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a> modules should be lowercase. Some popular ones out there (e.g. Gtk) however follow the CamelCase convention.</p>
<p>In order to have a pythonic codebase and mitigate spillage of this policy breach it seems like the following is... | 3 | 2016-06-02T10:59:12Z | 37,590,149 | <p><code>Gtk</code> is a class not a module. <a href="https://www.python.org/dev/peps/pep-0008/#class-names">Class names</a> should use CapWords convention.</p>
<p>You can read more about that <a href="http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules">here</a>.</p>
| 5 | 2016-06-02T11:08:16Z | [
"python",
"pep8"
] |
Is it PEP8 compliant to import CamelCase as lowercase? | 37,589,942 | <p>According to <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a> modules should be lowercase. Some popular ones out there (e.g. Gtk) however follow the CamelCase convention.</p>
<p>In order to have a pythonic codebase and mitigate spillage of this policy breach it seems like the following is... | 3 | 2016-06-02T10:59:12Z | 37,590,235 | <p>I second the answer of Tomasz Plaskota that this indeed is an anti-pattern and I like to amend:</p>
<p>In chapter/section "Public and internal interfaces" of pep8:</p>
<blockquote>
<p>Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such impor... | 3 | 2016-06-02T11:12:46Z | [
"python",
"pep8"
] |
How to split dictionary keys into multiple separate keys in python? | 37,589,975 | <p>In Python I am using the RRDTool Python wrapper to store and read values into / from a RRD-Database.</p>
<p>The RRDTool for Python is a wrapper for the C-based source / command-line utility of rrdtool. </p>
<p>After creating a database I want to read out it's header using the python command: </p>
<pre><code>heade... | 1 | 2016-06-02T11:00:34Z | 37,590,198 | <p>We need to parse the keys to see if they look like <code>ds[some_identifier].type</code> etc.</p>
<pre><code>def process_dict(dictionary):
import re
rgx = re.compile(r"^(ds)\[(.+?)\]\.(index|type)$")
processed = {}
for k, v in dictionary.items():
# does k have the format ds[some_key].i... | 1 | 2016-06-02T11:10:55Z | [
"python",
"string",
"dictionary",
"rrdtool"
] |
Creating refreshable tkinter window without closing | 37,590,185 | <p>I want to make a program which runs for ever and refreshes its information every 10s.</p>
<p>The best solution I got was:</p>
<pre><code>while True:
Gui= GUI()
Gui.after(2000, lambda : Gui.destroy())
Gui.mainloop()
</code></pre>
<p>But that resulted in the window closing and creating awful effect.
He... | 0 | 2016-06-02T11:10:19Z | 37,592,491 | <p>You don't have to delete it every time, just update. Here is you <code>GUI</code> class:</p>
<pre><code>class GUI(Tk):
def __init__(self):
self.tk = Tk()
self.tk.wm_state('zoomed')
self.topFrame = Frame(self.tk)
self.topFrame.pack(side=TOP,fill=Y)
self.label = Label(self.... | 1 | 2016-06-02T12:54:16Z | [
"python",
"user-interface",
"tkinter"
] |
Creating refreshable tkinter window without closing | 37,590,185 | <p>I want to make a program which runs for ever and refreshes its information every 10s.</p>
<p>The best solution I got was:</p>
<pre><code>while True:
Gui= GUI()
Gui.after(2000, lambda : Gui.destroy())
Gui.mainloop()
</code></pre>
<p>But that resulted in the window closing and creating awful effect.
He... | 0 | 2016-06-02T11:10:19Z | 37,612,724 | <p>All I have to do is to delete older labels</p>
<pre><code>for ele in self.label:
self.label[ele].destroy()
self.label= {}
</code></pre>
| 0 | 2016-06-03T11:04:52Z | [
"python",
"user-interface",
"tkinter"
] |
Apache change script without restart | 37,590,188 | <p>I wrote a simple Flask application on a VPS server in Apache</p>
<pre><code>from flask import Flask, render_template, request
import sys
app = Flask(__name__)
@app.route("/")
def hello():
return "123"
if __name__ == "__main__":
app.run()
</code></pre>
<p>When I change the string <code>return "123"</code... | 0 | 2016-06-02T11:10:31Z | 37,590,365 | <p>You can try reloading. Even that will impact the incoming traffic though.If there are more than one servers you can do a rolling reload or restart.</p>
<p>If not you can do a graceful restart of apache where traffic wont be impacted, using </p>
<p><code>apachectl -k graceful</code> </p>
<p>You can do without a re... | 0 | 2016-06-02T11:19:52Z | [
"python",
"apache"
] |
Ping ip's in a dict | 37,590,224 | <p>I have a dict ({'ip': '10.198.0.12'}, {'ip': '10.198.0.91'}) and so on.</p>
<p>I have to ping the ip's in a dict one by one and see if it is pingable.
I am using the <strong>pyping</strong> python library but the i get an error saying
" dict object has no attribute split "</p>
<p>I am fetching the ip's from databa... | 0 | 2016-06-02T11:12:00Z | 37,590,385 | <p>In you question, you don't have "a dict of IPs". What you have is a <code>set</code> of <code>dict</code>s that have a property <code>ip</code> that holds an IP address.</p>
<p>To ping, you only need that <code>ip</code> property of the <code>dict</code>s that are inside the <code>set</code>.</p>
<pre><code>for ip... | 2 | 2016-06-02T11:20:53Z | [
"python",
"dictionary"
] |
Sort list of lists based on a dict values as key | 37,590,236 | <p>I saw this method to sort list based on dict values as key.</p>
<p><a href="http://stackoverflow.com/questions/12987178/sort-a-list-based-on-dictionary-values-in-python">Original Question here</a></p>
<p>Can we use this method to sort list of lists based on first value in each list?</p>
<pre><code>trial_dict = {1... | 0 | 2016-06-02T11:12:47Z | 37,590,389 | <p>You can use <code>sorted()</code> function. </p>
<pre><code>trial_dict = {1:'ABC', 2:'PQR', 3:'DEF'}
trial_dict_inv = {v: k for k, v in trial_dict.items()}
trial_list = [['ABC','-','+','/','+','-','*'],
['DEF','-','+','/','+','-','*'],
['PQR','-','+','/','+','-','*']]
print sorted(trial_list, ... | 1 | 2016-06-02T11:20:59Z | [
"python",
"list",
"sorting",
"dictionary"
] |
map function similar to python in swift | 37,590,340 | <p>I was trying to convert the below <strong>python</strong> code to <strong>swift</strong></p>
<p><strong>Python code</strong></p>
<pre><code>a0,a1,a2= map(int, [1,2,3])
print(a0,a1,a2)
</code></pre>
<blockquote>
<p><strong>Output:</strong> 1 2 3</p>
</blockquote>
<p><strong>Swift code</strong></p>
<pre><code>v... | 0 | 2016-06-02T11:18:12Z | 37,590,591 | <p>You're doing a destructuring assignment in Python there, but Swift <strong>doesn't support it</strong> for arrays. You can only do that with tuples, like Squall pointed out in a comment.</p>
<p>Swift has a map function though, which you can use like so:</p>
<pre><code>let result = [1, 2, 3].map { n in
// `myFu... | 1 | 2016-06-02T11:30:40Z | [
"python",
"ios",
"swift",
"dictionary"
] |
Converting Binary to ASCII, and ASCII to Binary | 37,590,412 | <p>I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.</p>
<p>When running the code in WingIDE, an error occurs:
On the line startin... | 2 | 2016-06-02T11:21:55Z | 37,590,736 | <p>fi.read() returns the whole document the first time and '' next times. So you should do</p>
<pre><code>text = fi.read()
for char in text:
do_stuff()
</code></pre>
<p><strong><em>Edit1</em></strong></p>
<p>You can only read your file once. Thus you have to get your chars one by one. A file.read returns a stri... | 1 | 2016-06-02T11:36:43Z | [
"python",
"binary",
"ascii"
] |
Converting Binary to ASCII, and ASCII to Binary | 37,590,412 | <p>I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.</p>
<p>When running the code in WingIDE, an error occurs:
On the line startin... | 2 | 2016-06-02T11:21:55Z | 37,591,388 | <pre><code># Lets say your filename is stored in fname
def binary(n):
return '{0:08b}'.format(n)
with open(fname) as f:
content = f.readlines()
for i in content:
print(binary(ord(i)), end='')
print('')
</code></pre>
<p>This will give you the integer value(from ascii) of each character in the ... | 1 | 2016-06-02T12:04:50Z | [
"python",
"binary",
"ascii"
] |
Converting Binary to ASCII, and ASCII to Binary | 37,590,412 | <p>I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.</p>
<p>When running the code in WingIDE, an error occurs:
On the line startin... | 2 | 2016-06-02T11:21:55Z | 37,591,617 | <p>If you want to decode and encode, have this solutions</p>
<p>Encode ascii to bin</p>
<pre><code>def toBinary(string):
return "".join([format(ord(char),'#010b')[2:] for char in string])
</code></pre>
<p>Encode bin to ascii</p>
<pre><code>def toString(binaryString):
return "".join([chr(int(binaryString[i:i... | 3 | 2016-06-02T12:15:22Z | [
"python",
"binary",
"ascii"
] |
Matplotlib sometimes adding more plots to a graph than it should | 37,590,475 | <p>I'm currently doing a benchmark project, in which I run different tests and store their runtime in files. I then take those outputs and create a graph, which then compares the test run with its own earlier results. Some of the code is quite complex, and it has been puzzling me for quite a while, as to why I sometime... | 1 | 2016-06-02T11:24:30Z | 37,590,553 | <p>You should clear the plots with <code>plt.clf()</code> after you have saved them or else you will write to the same figure.</p>
<p>See <a href="http://stackoverflow.com/a/8228808/2373926">this answer</a> for more info.</p>
| 1 | 2016-06-02T11:28:08Z | [
"python",
"matplotlib"
] |
Cannot Import MySQLdb in PyCharm, runs fine in terminal. | 37,590,492 | <p>I have problems trying to run a script which imports MySQLdb within PyCharm.
Running the script from terminal works just fine while running within PyCharm fails with</p>
<pre><code>ImportError: No module named MySQLdb
</code></pre>
<p>I have tried <a href="http://stackoverflow.com/questions/6383310/python-mysqldb-... | 0 | 2016-06-02T11:25:28Z | 37,591,480 | <p>As @Dilettant pointed me to <a href="http://stackoverflow.com/a/34992894/1989141">http://stackoverflow.com/a/34992894/1989141</a>,
I realised there are two different places I was supposed to set the Python interpreter in PyCharm.</p>
<p>The first is in the main preferences (as in philâs solution in the link) and ... | 1 | 2016-06-02T12:09:14Z | [
"python",
"import",
"ide",
"pycharm",
"mysql-python"
] |
PyQt4 window disappears when back end runs and re-appears when finished | 37,590,574 | <p>I am very new to PyQt4 and was learning how to integrate it with my Python code at the back-end. The way I did it, the front-end looks just fine and takes all the input I need. When the processing starts, that is when the back-end scripts run, the window disappears and reappears when all my back end scripts have fin... | 1 | 2016-06-02T11:29:43Z | 37,592,475 | <p>You want to use <a href="http://doc.qt.io/qt-4.8/qwidget.html#hide" rel="nofollow"><code>hide()</code></a> not <a href="http://doc.qt.io/qt-4.8/qwidget.html#close" rel="nofollow"><code>close()</code></a>. When you are calling <code>self.close()</code> you are making the <code>QMainWindow</code> stop and potentially ... | 0 | 2016-06-02T12:53:41Z | [
"python",
"user-interface",
"pyqt4"
] |
Split string at word boundaries without losing whitespaces or newlines | 37,590,721 | <p>Suppose I have a string like this which contains (multiple) whitespaces and newlines:</p>
<pre><code>"\n\n\nmy string \n"
</code></pre>
<p>I want this to be split into:</p>
<pre><code>['\n', '\n', '\n', 'my', ' ', ' ', 'string', ' ', '\n']
</code></pre>
<p>How could I get this? I suppose I need a regular expres... | 0 | 2016-06-02T11:35:58Z | 37,590,918 | <p>Use regex <a href="https://regex101.com/r/eQ3yC3/1" rel="nofollow"><code>\w+|\W</code></a> and find matches</p>
<pre><code>>>> import re
>>> p = re.compile('\w+|\W')
>>> p.findall('\n\n\nmy string \n')
['\n', '\n', '\n', 'my', ' ', ' ', 'string', ' ', '\n']
</code></pre>
<hr>
<p><a hr... | 2 | 2016-06-02T11:44:27Z | [
"python",
"regex",
"string",
"text",
"split"
] |
How to exit a python program immediately but still let the thread finish | 37,590,723 | <p>I'm writing some kind of plugin that needs to return fast to avoid timeout of the calling program, which calls it with long enough intervals to prepare the data, but the preparing of the info takes a bit longer than the allowed timeout, so I return the info from a cache file and start a thread which updates the cach... | 1 | 2016-06-02T11:36:06Z | 37,590,950 | <p>It seems to me you need more than threads. If you need from your main program to be terminated quickly and run a long background task, you need to fork. I can't test right now, but I think you should try :</p>
<pre><code>from multiprocessing import Process
#...
def getinfo_fast():
data = getinfofromcachefile(... | 1 | 2016-06-02T11:45:57Z | [
"python",
"multithreading"
] |
How to exit a python program immediately but still let the thread finish | 37,590,723 | <p>I'm writing some kind of plugin that needs to return fast to avoid timeout of the calling program, which calls it with long enough intervals to prepare the data, but the preparing of the info takes a bit longer than the allowed timeout, so I return the info from a cache file and start a thread which updates the cach... | 1 | 2016-06-02T11:36:06Z | 37,591,963 | <p>Arthur's idea "more than threads", made me stumble onto <strong>python-daemon</strong>,
which did the trick for me. My program now executes the getinfo_fast function and then immediately falls back to the prompt, but getfreshinfo() gets executed in the background.</p>
<p><a href="https://pypi.python.org/pypi/python... | 0 | 2016-06-02T12:32:01Z | [
"python",
"multithreading"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.