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 |
|---|---|---|---|---|---|---|---|---|---|
Should I handle ajax requests in vanilla Django or rest Django? | 39,608,377 | <p>I have a bunch of ajax requests on my website (ex. upvote sends request to server)</p>
<p>Should I integrate this functionality server side just with another view function </p>
<p>Or is it recommended that I shove all the necessary views into a Django rest framework?</p>
| 0 | 2016-09-21T05:44:29Z | 39,608,464 | <p>I usually follow DDD approach. So all my requests end up being just a CRUD operation for an entity. I always prefer REST APIs, thus I would say if you have DDD approach already in place go with django-rest-framework.</p>
<p>Otherwise, it really does not matter, depends on your need.</p>
| 0 | 2016-09-21T05:52:01Z | [
"python",
"ajax",
"django",
"rest",
"django-rest-framework"
] |
Binary converter alogrithim | 39,608,380 | <p>Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.</p>
<p>For any invalid input, return string Invalid input</p>
<p>Example: For number 5 return string 101</p>
<p>my code</p>
<pre><code>import unittest
... | -2 | 2016-09-21T05:44:35Z | 39,609,447 | <p>Try this code... </p>
<pre><code>def binary_converter(n):
if(n==0):
return "0"
elif(n>255):
print("out of range")
return ""
else:
ans=""
while(n>0):
temp=n%2
ans=str(temp)+ans
n=n/2
return ans
</code></pre>
| 0 | 2016-09-21T06:57:04Z | [
"python"
] |
Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) | 39,608,421 | <p>I am trying to run this code,and the last 2 dot products are showing error as suggested in the heading. I checked the size of the matrices and both are (3, 1), then why it is showing me an error while doing dot product?</p>
<pre><code>coordinate1 = [-7.173, -2.314, 2.811]
coordinate2 = [-5.204, -3.598, 3.323]
coo... | 0 | 2016-09-21T05:47:09Z | 39,608,560 | <p>By converting the matrix to array by using<br>
n12 = np.squeeze(np.asarray(n2))</p>
<p>X12 = np.squeeze(np.asarray(x1))</p>
<p>solved the issue.</p>
| 0 | 2016-09-21T05:59:16Z | [
"python",
"arrays",
"numpy"
] |
Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) | 39,608,421 | <p>I am trying to run this code,and the last 2 dot products are showing error as suggested in the heading. I checked the size of the matrices and both are (3, 1), then why it is showing me an error while doing dot product?</p>
<pre><code>coordinate1 = [-7.173, -2.314, 2.811]
coordinate2 = [-5.204, -3.598, 3.323]
coo... | 0 | 2016-09-21T05:47:09Z | 39,609,781 | <p>Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:</p>
<ul>
<li><code>(X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C)</code>, where <code>...</code> means "0 or more different values</li>
<li><code>(B,) dot (B, C) -> (C,)</code></li>
<li><co... | 0 | 2016-09-21T07:14:33Z | [
"python",
"arrays",
"numpy"
] |
Selenium text not working | 39,608,637 | <p>I have this span tag:</p>
<pre><code><span class="pricefield" data-usd="11000">$11,000</span>
</code></pre>
<p>And I want to get the text for it (<code>$11,000</code>). Naturally I should be using <code>text</code> like so:</p>
<pre><code># empty
print self.selenium.find_element_by_css_selector(".pric... | 0 | 2016-09-21T06:05:44Z | 39,608,816 | <p><code>get_attribute("textContent")</code> or <code>get_attribute("innerText")</code> are the attributes you are looking for.</p>
| 2 | 2016-09-21T06:18:54Z | [
"python",
"selenium"
] |
readable socket times out on recv | 39,608,697 | <p>I have a 'jobs' server which accepts requests from a client (there are 8 clients sending requests from another machine). The server then submits a 'job' (a 'job' is just an executable which writes a results file to disk), and on a 'jobs manager' thread waits until the job is done. When a job is done it sends a messa... | 1 | 2016-09-21T06:10:54Z | 39,684,075 | <p>A solution that was just a guess and seems to work: On the client side, I am using a blocking <code>recv</code> method to get message from the server that the job is done. Since a job can take a long time (e.g if the cluster running the jobs is low on resources), I guessed that maybe the socket waiting was the cause... | 0 | 2016-09-25T06:27:38Z | [
"python",
"sockets",
"client-server"
] |
MySQL database error using scrapy | 39,608,990 | <p>I am trying to save scrapped data in MySQL database. My script.py is</p>
<pre><code> # -*- coding: utf-8 -*-
import scrapy
import unidecode
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from lxml import html
class ElementSpider(scrapy.Spider):
name = 'books'
... | 2 | 2016-09-21T06:31:28Z | 39,612,675 | <p>Your method signature is wrong, it should take item and spider parameters:</p>
<pre><code>process_item(self, item, spider)
</code></pre>
<p>Also you need to have the pipeline setup in your <em>settings.py</em> file:</p>
<pre><code> ITEM_PIPELINES = {"project_name.path.SQLStore"}
</code></pre>
<p>Your syntax is ... | 2 | 2016-09-21T09:31:10Z | [
"python",
"mysql",
"scrapy"
] |
Is there any way to read micr font characters from cheques using tesseract ocr or anyother package for python? | 39,609,054 | <p>When i used the pytesseract for character recognition on cheques, the micr characters are not getting recognized properly.</p>
| 0 | 2016-09-21T06:35:15Z | 39,621,411 | <p>You will need to use the MICR language file in order to properly recognize the MICR characters. See this post:</p>
<p><a href="http://stackoverflow.com/questions/25279271/android-how-to-recognize-micr-codes">Android : How to recognize MICR codes</a></p>
<p>Excerpt from post: </p>
<blockquote>
<p>You can use Tes... | 0 | 2016-09-21T16:01:32Z | [
"python",
"ocr",
"tesseract",
"python-tesseract"
] |
How to do this Class inheritance in Python? | 39,609,108 | <p>I have a Python/<a href="https://github.com/tornadoweb/tornado" rel="nofollow">Tornado</a> application that responds to HTTP requests with the following 3 classes:</p>
<pre><code>import tornado.web
class MyClass1(tornado.web.RequestHandler):
x = 1
y = 2
def my_method1(self):
print "Hello World"... | 0 | 2016-09-21T06:38:47Z | 39,609,254 | <p><code>ReequestHandler</code>'s <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler" rel="nofollow">constructor takes arguments</a>:</p>
<pre><code>class RequestHandler(object):
...
def __init__(self, application, request, **kwargs):
...
</code></pre>
<p>When you inherit... | 0 | 2016-09-21T06:46:37Z | [
"python",
"inheritance",
"tornado"
] |
How to do this Class inheritance in Python? | 39,609,108 | <p>I have a Python/<a href="https://github.com/tornadoweb/tornado" rel="nofollow">Tornado</a> application that responds to HTTP requests with the following 3 classes:</p>
<pre><code>import tornado.web
class MyClass1(tornado.web.RequestHandler):
x = 1
y = 2
def my_method1(self):
print "Hello World"... | 0 | 2016-09-21T06:38:47Z | 39,609,290 | <p>The <code>tornado.web.RequestHandler</code> already has a <code>__init__</code> method and Tornado expects it to take two arguments (plus the <code>self</code> argument of a bound method). Your overridden versions don't take these.</p>
<p>Update your <code>__init__</code> methods to take <em>arbitrary extra argumen... | 4 | 2016-09-21T06:48:41Z | [
"python",
"inheritance",
"tornado"
] |
Login to Odoo from external php system | 39,609,130 | <p>I have a requirement where I need to have a redirect from the external php system to Odoo, and the user should be logged in as well. I thought of the following two ways to get this done:</p>
<ol>
<li><p>A url redirection from the php side which calls a particular controller,and pass the credentials alongiwth the ur... | 1 | 2016-09-21T06:39:58Z | 39,617,759 | <p>In your php code you could make a jsonrpc call to <code>/web/session/authenticate</code> and receive the session_id in the response. You could pass the session_id as the hash of your url in your redirect. Create a page in odoo that uses javascript to read the hash and write the cookie <code>"session_id=733a54f466362... | 2 | 2016-09-21T13:19:44Z | [
"python",
"openerp",
"xml-rpc",
"odoo-9"
] |
Django Ajax response date and time format | 39,609,234 | <p>Got a problem... </p>
<p>I use <code>Django</code>, <code>SQLite</code>, <code>jquery</code> and <code>AJAX</code>.</p>
<p>The problem is that when I get date and time from my database, it looks weird.</p>
<p>Is there any way to display it normally, as <code>dd/mm/yyyy HH:MM</code> ?</p>
<p><strong>Modeles.py</s... | 0 | 2016-09-21T06:45:54Z | 39,610,860 | <p>It's not weird, it's ISO 8601 and it's not a good idea to change it. But you can by defining your own encoder:</p>
<pre><code>import json
from datetime import dateteime
from django.forms.models import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder
class MyEncoder(DjangoJSONEncoder):
... | 0 | 2016-09-21T08:07:54Z | [
"jquery",
"python",
"ajax",
"django",
"response"
] |
Django Ajax response date and time format | 39,609,234 | <p>Got a problem... </p>
<p>I use <code>Django</code>, <code>SQLite</code>, <code>jquery</code> and <code>AJAX</code>.</p>
<p>The problem is that when I get date and time from my database, it looks weird.</p>
<p>Is there any way to display it normally, as <code>dd/mm/yyyy HH:MM</code> ?</p>
<p><strong>Modeles.py</s... | 0 | 2016-09-21T06:45:54Z | 39,628,900 | <p>I came up with my own solution. </p>
<p>to display date in your own format you just need to create a variable <code>new Date</code></p>
<pre><code>var date = new Date();
</code></pre>
<p>after that we parse date from our response to this variable, so change it to:</p>
<pre><code>var date = new Date(ourAjaxRespon... | 0 | 2016-09-22T01:31:50Z | [
"jquery",
"python",
"ajax",
"django",
"response"
] |
Pandas how to split dataframe by column by interval | 39,609,391 | <p>I have a gigantic dataframe with a datetime type column called <code>dt</code>, the data frame is sorted based on <code>dt</code> already. I want to split the dataframe into several dataframes based on <code>dt</code>, each dataframe contains rows within <code>1 hr</code> range.</p>
<p>Split</p>
<pre><code> dt ... | 4 | 2016-09-21T06:53:53Z | 39,609,439 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by difference of first value of column <code>dt</code> converted to <code>hour</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.h... | 3 | 2016-09-21T06:56:35Z | [
"python",
"python-2.7",
"pandas",
"numpy",
"scipy"
] |
Pandas how to split dataframe by column by interval | 39,609,391 | <p>I have a gigantic dataframe with a datetime type column called <code>dt</code>, the data frame is sorted based on <code>dt</code> already. I want to split the dataframe into several dataframes based on <code>dt</code>, each dataframe contains rows within <code>1 hr</code> range.</p>
<p>Split</p>
<pre><code> dt ... | 4 | 2016-09-21T06:53:53Z | 39,609,723 | <p>take the difference of dates with first date and group by total_seconds</p>
<pre><code>df.groupby((df.dt - df.dt[0]).dt.total_seconds() // 3600,
as_index=False).apply(pd.DataFrame.reset_index, drop=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/9MxQ6.png" rel="nofollow"><img src="http://i.stac... | 2 | 2016-09-21T07:11:50Z | [
"python",
"python-2.7",
"pandas",
"numpy",
"scipy"
] |
Pandas: remove encoding from the string | 39,609,426 | <p>I have the following data frame:</p>
<pre><code> str_value
0 Mock%20the%20Week
1 law
2 euro%202016
</code></pre>
<p>There are many such special characters such as <code>%20%</code>, <code>%2520</code>, etc..How do I remove them all. I have tried the following but the dataframe is large and I am not sure how many ... | 3 | 2016-09-21T06:56:08Z | 39,609,639 | <p>You can use the <code>urllib</code> library and apply it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html"><code>map</code></a> method of a series.
Example - </p>
<pre><code>In [23]: import urllib
In [24]: dfSearch["str_value"].map(lambda x:urllib.unquote(x).decode('utf8'... | 7 | 2016-09-21T07:07:57Z | [
"python",
"python-2.7",
"pandas"
] |
how to read binary after resize image on python? | 39,609,455 | <p>i use two packages
<code>from PIL import Image</code> and <code>from resizeimage import resizeimage</code> when i use this packages i should after resize save to other image file, but i need image binary after resize not save to other file ?</p>
<p>code :</p>
<pre><code>with open(imgpath, 'r+b') as f:
with Ima... | 0 | 2016-09-21T06:57:15Z | 39,610,574 | <p>please use this code.</p>
<pre><code>basewidth = 100
hsize = 100
img = Image.open(imgpath)
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
byte_io = io.BytesIO()
img.save(byte_io, format='PNG')
byte_io = byte_io.getvalue()
print byte_io
</code></pre>
| 0 | 2016-09-21T07:53:04Z | [
"python",
"python-2.7",
"opencv"
] |
How to identify ordered substrings in string using python? | 39,609,537 | <p>I am new to python, so my question would be naive but I would appreciate your suggestion that help me get to the solution of it.</p>
<p>For example I have string "aeshfytifghkjgiomntrop" and I want to find ordered substrings from it. How should I approach?</p>
| 0 | 2016-09-21T07:01:56Z | 39,609,623 | <p>Scan the string using <code>enumerate</code> to issue index and value.
Print string parts when chars are decreasing and start a new substring:</p>
<pre><code>s = "aeshfytifghkjgiomntrop"
prev_c = None
prev_i = 0
for i,c in enumerate(s):
if prev_c>c:
print(s[prev_i:i])
prev_i=i
prev_c=c
... | 1 | 2016-09-21T07:07:01Z | [
"python",
"string"
] |
How to set width of Treeview in tkinter of python | 39,609,865 | <p>Recently, I use <code>tkinter</code> <code>TreeView</code> to show many columns in <code>Python</code>. Specifically, 49 columns data in a treeview. I use <code>grid</code> to manage my widgets.</p>
<p>I found out the width of the treeview only depends on the width of columns.</p>
<p>My question is, How can I set ... | 0 | 2016-09-21T07:19:11Z | 39,629,542 | <p>After trying so many ways to solve this problem, I find out a simple but silly solution. After initializing the width of the <code>Treeview</code>, you just need to resize the with of the column and the width of the <code>Treeview</code> will NOT change.</p>
<p>Perhaps, this is the constraint of Tcl/Tk.</p>
| 0 | 2016-09-22T02:57:05Z | [
"python",
"tkinter",
"treeview"
] |
Create a user defined number of loops for quiz in python | 39,609,876 | <p>I need to have a user defined amount of time the questions are asked and keep track of the attempts</p>
<pre><code>def main():
print("Thank you for taking the Quiz")
score= 0
question1 = input("How many donuts are in a dozen? ")
if question1 == "12":
print("Correct")
score = score ... | -4 | 2016-09-21T07:19:42Z | 39,609,967 | <p>I would do something like this:</p>
<pre><code> def main():
print("Thank you for taking the Quiz")
times = input("How many time you'll play? ")
for i in range(int(times))
print("The final score is: " + str(question), "out of 3")
def question():
score= 0
que... | 0 | 2016-09-21T07:23:44Z | [
"python",
"python-3.x"
] |
I got an error while using "git push heroku master" command | 39,609,912 | <p>When I'm trying to push python project on heroku using <code>git push heroku master</code>
command I got an error like this. </p>
<pre><code>Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>... | 0 | 2016-09-21T07:21:26Z | 39,611,081 | <p>You have to add your ssh keys to heroku by running <code>heroku keys:add</code>. Heroku can then verify you and allow access to your repository on heroku. More on this here: <a href="https://devcenter.heroku.com/articles/keys" rel="nofollow">https://devcenter.heroku.com/articles/keys</a></p>
| 1 | 2016-09-21T08:18:32Z | [
"python",
"git",
"heroku"
] |
Tokenizing a concatenated string | 39,609,925 | <p>I got a set of strings that contain concatenated words like the followings:</p>
<pre><code>longstring (two English words)
googlecloud (a name and an English word)
</code></pre>
<p>When I type these terms into Google, it recognizes the words with "did you mean?" ("long string", "google cloud"). I need similar funct... | 1 | 2016-09-21T07:21:54Z | 39,610,850 | <p>Can you also roll your own implementation? I am thinking of an algorithm like this:</p>
<ol>
<li>Get a dictionary with all words you want to distinguish</li>
<li>Build a data structure that allows quick lookup (I am thinking of a <a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow"><code>trie</code></a>)</li... | 1 | 2016-09-21T08:07:21Z | [
"python",
"elasticsearch",
"machine-learning",
"google-bigquery"
] |
Tokenizing a concatenated string | 39,609,925 | <p>I got a set of strings that contain concatenated words like the followings:</p>
<pre><code>longstring (two English words)
googlecloud (a name and an English word)
</code></pre>
<p>When I type these terms into Google, it recognizes the words with "did you mean?" ("long string", "google cloud"). I need similar funct... | 1 | 2016-09-21T07:21:54Z | 39,641,912 | <p>If you do choose to solve this with BigQuery, then the following is a candidate solution:</p>
<ol>
<li><p>Load list of all possible English words into a table called <code>words</code>. For example, <a href="https://github.com/dwyl/english-words" rel="nofollow">https://github.com/dwyl/english-words</a> has list of ... | 1 | 2016-09-22T14:30:37Z | [
"python",
"elasticsearch",
"machine-learning",
"google-bigquery"
] |
How to add dynamically C function in embedded Python | 39,610,280 | <p>I declare a C function as Python prototype</p>
<pre><code>static PyObject* MyFunction(PyObject* self, PyObject* args)
{
return Py_None ;
}
</code></pre>
<p>Now I want to add it into a dynamically loaded module</p>
<pre><code>PyObject *pymod = PyImport_ImportModule("mymodule");
PyObject_SetAttrString( pymod, "... | -1 | 2016-09-21T07:38:19Z | 39,611,394 | <p>You need to construct a new <code>PyCFunctionObject</code> object from the <code>MyFunction</code>. Usually this is done under the hood using the module initialization code, but as you're now doing it the opposite way, you need to construct the <code>PyCFunctionObject</code> yourself, using the undocumented <code>Py... | 0 | 2016-09-21T08:35:13Z | [
"python",
"c",
"function"
] |
Invalid syntax error in for loop pandas | 39,610,336 | <p>I am new to pandas and While trying to iterate over the rows through a for loop I am getting a Invalid syntax error in pandas </p>
<p>Below is the code I tried </p>
<pre><code>for index, row in df.iterrows():
if ((df['c1'] == 'cond1')&(df['c2']=='cond2')):
df['c3']='cond2'
elif ((df['c1'] == 'cond3')&(df[... | -2 | 2016-09-21T07:41:07Z | 39,610,388 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>, but are you sure you need always string <code>cond2</code> get to column <code>c3</code>?</p>
<pre><code>df['c3']='Nan'
df.ix[(df['c1'] == 'cond1')&(df['c2']=='cond2')... | 0 | 2016-09-21T07:43:48Z | [
"python",
"pandas",
"for-loop"
] |
Django rest framework one to one relation Update serializer | 39,610,427 | <p>I'm a beginner to the Django Rest Frame work. I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me </p>
<p>models.py</p>
<pre><code>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db i... | 0 | 2016-09-21T07:45:49Z | 39,611,626 | <p>Your <code>update</code> method is not called, because it is a method of the meta class of the serializer (<code>AccountUpdateSerializer.Meta</code>), not the serializer class <code>AccountUpdateSerializer</code> itself.</p>
<p>Here is how it should look:</p>
<pre><code>class AccountUpdateSerializer(serializers.Mo... | 1 | 2016-09-21T08:45:29Z | [
"python",
"django",
"django-rest-framework"
] |
Nesting item data in Scrapy | 39,610,761 | <p>I'm fairly new to Python and Scrapy and have issues wrapping my head around how to create nested JSON with the help of Scrapy.</p>
<p>Selecting the elements I want from HTML has not been a problem with the help of XPath Helper and some Googling. I am however not quite sure how Iâm supposed to get the JSON structu... | 2 | 2016-09-21T08:02:46Z | 39,612,963 | <p>You just need to find all the uls and then extract the lis to group them, an example using lxml below:</p>
<pre><code>from lxml import html
h = """<ul>
<li class="title"><h2>Monday</h2></li>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</l... | 0 | 2016-09-21T09:44:28Z | [
"python",
"json",
"scrapy"
] |
How to pass value from def to a view openerp | 39,610,896 | <p>This is my code: </p>
<pre><code>def view_purchase(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.act_window',
'name': 'diary_purchase',
'view_mode': 'form',
'view_type': 'form',
'context': "{'name': 'my purchase'}",
'res_model': 'diaries_purchase... | -1 | 2016-09-21T08:09:29Z | 39,619,596 | <p>In your destination model (the on you open with your <code>view_purchase()</code> function). Access the context variable <code>self.env.context</code> there you should find your value. You should use a computed or default value on the field <code>name</code>.</p>
<pre><code>def _get_name(self):
self.name = self... | 0 | 2016-09-21T14:36:32Z | [
"python",
"view",
"openerp"
] |
How to pass value from def to a view openerp | 39,610,896 | <p>This is my code: </p>
<pre><code>def view_purchase(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.act_window',
'name': 'diary_purchase',
'view_mode': 'form',
'view_type': 'form',
'context': "{'name': 'my purchase'}",
'res_model': 'diaries_purchase... | -1 | 2016-09-21T08:09:29Z | 39,619,992 | <p>Pass the context like this, by prefixing the field name with <code>default_</code></p>
<pre><code>def view_purchase(self, cr, uid, ids, context=None):
return {
'type': 'ir.actions.act_window',
'name': 'diary_purchase',
'view_mode': 'form',
'view_type': 'form',
'context': ... | 0 | 2016-09-21T14:55:28Z | [
"python",
"view",
"openerp"
] |
Python script to change dir for user | 39,611,036 | <p>I am trying to create Python script <code>jump.py</code> that allows me to jump to a set of predefined dirs, and looks like it is not possible to do this, because after scripts exits, the previous directory is restored:</p>
<pre><code>import os
print(os.getcwd())
os.chdir('..')
print(os.getcwd())
</code></pre>
<h... | 0 | 2016-09-21T08:15:56Z | 39,612,023 | <p>You can try this;</p>
<pre><code>import os
print(os.getcwd())
os.chdir('..')
print(os.getcwd())
shell = os.environ.get('SHELL', '/bin/sh')
os.execl(shell, shell)
</code></pre>
| 0 | 2016-09-21T09:03:15Z | [
"python",
"shell",
"cd"
] |
Use multi-processing/threading to break numpy array operation into chunks | 39,611,045 | <p>I have a function defined which renders a MxN array.
The array is very huge hence I want to use the function to produce small arrays (M1xN, M2xN, M3xN --- MixN. M1+M2+M3+---+Mi = M) simultaneously using multi-processing/threading and eventually join these arrays to form mxn array. As Mr. Boardrider rightfully sugg... | 8 | 2016-09-21T08:16:21Z | 39,856,310 | <p>The first thing to say is: if it's about multiple cores on the same processor, <code>numpy</code> is already capable of parallelizing the operation better than we could ever do by hand (see the discussion at <a href="https://stackoverflow.com/questions/38000663/multiplication-of-large-arrays-in-python">multiplicatio... | 6 | 2016-10-04T15:30:13Z | [
"python",
"arrays",
"multithreading",
"multiprocessing"
] |
Converting python dictionary to unique key-value pairs | 39,611,077 | <p>I want to convert a python dictionary to a list which contains all possible key-value pair. For example, if the dict is like:</p>
<pre><code>{
"x": {
"a1": { "b": {
"c1": { "d": { "e1": {}, "e2": {} } },
"c2": { "d": { "e3": {}, "e4": {} } }
... | -2 | 2016-09-21T08:18:12Z | 39,612,032 | <pre><code>a = {
"x": {
"a1": { "b": {
"c1": { "d": { "e1": {}, "e2": {} } },
"c2": { "d": { "e3": {}, "e4": {} } }
}
},
"a2": { "b": {
"c3": { "d": { "e1": {}, "e5": {} } },
"c4": { "d": { "e6": {} } }
... | 0 | 2016-09-21T09:03:32Z | [
"python",
"list",
"dictionary",
"flatten"
] |
Converting python dictionary to unique key-value pairs | 39,611,077 | <p>I want to convert a python dictionary to a list which contains all possible key-value pair. For example, if the dict is like:</p>
<pre><code>{
"x": {
"a1": { "b": {
"c1": { "d": { "e1": {}, "e2": {} } },
"c2": { "d": { "e3": {}, "e4": {} } }
... | -2 | 2016-09-21T08:18:12Z | 39,612,229 | <p>Alternative solution:</p>
<pre><code>from pprint import pprint
dic = {
"x": {
"a1": { "b": {
"c1": { "d": { "e1": {}, "e2": {} } },
"c2": { "d": { "e3": {}, "e4": {} } }
}
},
"a2": { "b": {
... | 1 | 2016-09-21T09:12:41Z | [
"python",
"list",
"dictionary",
"flatten"
] |
Converting python dictionary to unique key-value pairs | 39,611,077 | <p>I want to convert a python dictionary to a list which contains all possible key-value pair. For example, if the dict is like:</p>
<pre><code>{
"x": {
"a1": { "b": {
"c1": { "d": { "e1": {}, "e2": {} } },
"c2": { "d": { "e3": {}, "e4": {} } }
... | -2 | 2016-09-21T08:18:12Z | 39,612,796 | <p>You are missing one condition check in the following section in your original solution:</p>
<pre><code>if isinstance(v2, dict):
row.extend(get_list(v2, partial_row))
else:
row.append(partial_row)
</code></pre>
<p>Rather it has to be</p>
<pre><code>if isinstance(v2, dict) and v2:
row.extend(get_list(v2... | 0 | 2016-09-21T09:36:48Z | [
"python",
"list",
"dictionary",
"flatten"
] |
Django: Test content of email sent | 39,611,105 | <p>I'm sending out an email to users with a generated link, and I wanna write a test that verifies whether the link is correct, but I can't find a way to get the content of the email inside the test.</p>
<p>Is there a way to do that?</p>
<p>If it helps at all, this is how I'm sending the email:</p>
<pre><code>conten... | 0 | 2016-09-21T08:20:04Z | 39,611,137 | <p>The docs have <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#email-services" rel="nofollow">an entire section</a> on testing emails.</p>
<pre><code>self.assertEqual(mail.outbox[0].subject, 'Email with link')
</code></pre>
| 1 | 2016-09-21T08:21:54Z | [
"python",
"django",
"django-testing"
] |
Single producer to multi consumers (Same consumer group) | 39,611,124 | <p>I've try before sending message from single producer to 2 different consumer with <strong>DIFFERENT</strong> consumer group id. The result is both consumer able to read the complete message (both consumers getting the same message). But I would like to ask is it possible for these 2 consumers read different messages... | 0 | 2016-09-21T08:21:25Z | 39,652,029 | <p>I found the answer already, just make sure the partition number is not equal to one while creating new topic. </p>
| 0 | 2016-09-23T03:19:29Z | [
"python",
"producer-consumer",
"python-kafka"
] |
Trouble freezing (with PyInstaller) python source including multiprocessing module in Solaris | 39,611,127 | <p>I'm trying to freeze and distribute among my Solaris11 machines the following python code which makes use of multiprocessing module:</p>
<pre><code>import multiprocessing
def f(name):
print 'hello', name
if __name__ == '__main__':
p = multiprocessing.Process(target=f, args=('fer',))
p.start()
p.jo... | 1 | 2016-09-21T08:21:28Z | 39,704,878 | <p>Turned out it wasn't a gcc bug. After analysing in depth both environments, I realized the <code>/lib/libsoftcrypto.so.1</code> libraries differs a lot. As a matter of fact, the library in the compiler machine contains <code>get_fips_mode</code> symbol...</p>
<pre><code>[root@zgv-wodbuild01 pyinstaller]# nm /lib/li... | 0 | 2016-09-26T13:56:58Z | [
"python",
"multiprocessing",
"solaris",
"pyinstaller"
] |
pandas memory consumption hdf file grouping | 39,611,197 | <p>I wrote the following script but I have an issue with memory consumption, pandas is allocating more than 30 G of ram, where the sum of data files is roughly 18 G </p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import time
mean_wo = pd.DataFrame()
mean_w = p... | 2 | 2016-09-21T08:25:05Z | 39,611,770 | <p>I'd do something like this<br>
<strong><em>Solution</em></strong> </p>
<pre><code>data_files=['2012.h5', '2013.h5', '2014.h5', '2015.h5', '2016.h5', '2008_2011.h5']
cols = ['Significance_without_muons', 'Significance_with_muons']
def agg(data_file):
return pd.read_hdf(data_file).groupby('day')[cols].agg(['me... | 2 | 2016-09-21T08:51:43Z | [
"python",
"pandas",
"ram"
] |
Use of Parameter and Signature | 39,611,265 | <p>I am a relatively new Python learner. So, while going through different coding techniques, I came across this:</p>
<pre><code>from inspect import Parameter, Signature
def make_signature(names):
return Signature(Parameter(name, Parameter.POSITIONAL_OR_KEYWORD) for name in names)
class Structure:
list_field... | 2 | 2016-09-21T08:28:50Z | 39,612,065 | <blockquote>
<p>Can anyone please explain to me why & how this happens?</p>
</blockquote>
<p>Both classes <em>only</em> accept positional arguments as dictated by <code>*args</code> in <code>Structure.__init__</code>:</p>
<pre><code>s = Stock('pos_arg1', 'pos_arg2', 'pos_arg3')
p = Point('pos_arg1', 'pos_arg2',... | 2 | 2016-09-21T09:05:00Z | [
"python",
"python-3.x",
"metaprogramming"
] |
How do I get data sensor data from Microsoft band 2 to a Raspberry pi without SDK? (To a programming language) | 39,611,281 | <p>How can I get sensor data from the Microsoft Band 2 to a Raspberry Pi 3 (Raspbian Jessie)? The data should be available in a higher level programming language such as Python, Java or similar.</p>
<p>I want to be able to run a program (Java, Python or similar) that automatically receive data for processing when th... | -1 | 2016-09-21T08:29:35Z | 39,612,102 | <p>You should take a look at the documentation which for some reason is all jammed into a PDF <a href="https://developer.microsoftband.com/Content/docs/Microsoft%20Band%20SDK.pdf" rel="nofollow">here</a>.</p>
<p>It appears at the moment the only supported ways to get data of the band is using the SDK which only has su... | 0 | 2016-09-21T09:06:32Z | [
"java",
"python",
"raspberry-pi3",
"microsoft-band"
] |
How do I get data sensor data from Microsoft band 2 to a Raspberry pi without SDK? (To a programming language) | 39,611,281 | <p>How can I get sensor data from the Microsoft Band 2 to a Raspberry Pi 3 (Raspbian Jessie)? The data should be available in a higher level programming language such as Python, Java or similar.</p>
<p>I want to be able to run a program (Java, Python or similar) that automatically receive data for processing when th... | -1 | 2016-09-21T08:29:35Z | 40,037,325 | <p>I'm trying to achieve a similar result (direct connection via BLE without SDK on Windows/other OS) but even if I managed to connect to the band "manually" it is impossible for me to understand the GATT profiles to read the data from sensors. I can't find any (unofficial) documentation on the web to read data directl... | 0 | 2016-10-14T07:25:16Z | [
"java",
"python",
"raspberry-pi3",
"microsoft-band"
] |
Open files older than 3 days of date stamp in file name - Python 2.7 | 39,611,418 | <p>** Problem **
I'm trying to open (in python) files older than 3 days of the date stamp which is in the current name. Example: 2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply. So far I can create a date variable, however I do not know how to search for this variable in a filename. I presume I need to c... | 0 | 2016-09-21T08:36:30Z | 39,611,676 | <p>You can use <code>strptime</code> for this. It will convert your string (assuming it is correctly formatted) into a datetime object which you can use to compare if your file is older than 3 days based on the filename:</p>
<pre><code>from datetime import datetime
...
lines = []
for filename in os.listdir(path):
... | 0 | 2016-09-21T08:47:49Z | [
"python",
"python-2.7",
"datestamp"
] |
Open files older than 3 days of date stamp in file name - Python 2.7 | 39,611,418 | <p>** Problem **
I'm trying to open (in python) files older than 3 days of the date stamp which is in the current name. Example: 2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply. So far I can create a date variable, however I do not know how to search for this variable in a filename. I presume I need to c... | 0 | 2016-09-21T08:36:30Z | 39,622,972 | <p>To open all files in the given directory that contain a timestamp in their name older than 3 days:</p>
<pre><code>#!/usr/bin/env python2
import os
import time
DAY = 86400 # POSIX day in seconds
three_days_ago = time.time() - 3 * DAY
for filename in os.listdir(dirpath):
time_string = filename.partition(" ")[0]
... | 0 | 2016-09-21T17:28:03Z | [
"python",
"python-2.7",
"datestamp"
] |
__init__ vs __enter__ in context managers | 39,611,520 | <p>As far as I understand, <code>__init__()</code> and <code>__enter__()</code> methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. What is the purpose of separating them into two methods, and what should I put into each?</p>
<... | 0 | 2016-09-21T08:40:39Z | 39,611,597 | <blockquote>
<p>As far as I understand, <code>__init__()</code> and <code>__enter__()</code> methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between.</p>
</blockquote>
<p>And your understanding is incorrect. <code>__init__</code>... | 8 | 2016-09-21T08:44:13Z | [
"python",
"python-3.x",
"contextmanager"
] |
Select Columns in pandas DF | 39,611,568 | <p>Below is my data and I am trying to access a column. It was working fine until yesterday, but now I'm not sure if I am doing something wrong:</p>
<pre><code> DISTRICT;CPE;EQUIPMENT,NR_EQUIPM
0 47;CASTELO BRANCO;17520091VM;101 ... | 2 | 2016-09-21T08:43:14Z | 39,611,585 | <p>You need change sep to <code>;</code>, because separator is changed in <code>csv</code>:</p>
<pre><code>df = pd.read_csv(archiv, sep=";")
</code></pre>
<p>If check last separator of columns, there is <code>,</code>, so you can use two separators - <code>;,</code>, but is necessary add parameter <code>engine='pyth... | 2 | 2016-09-21T08:43:52Z | [
"python",
"csv",
"pandas",
"multiple-columns",
"separator"
] |
Fill area of polygons with python | 39,611,644 | <p>I use this part of a code to plot polygons :</p>
<pre><code>plt.plot(x,y,'k',linewidth=2)
</code></pre>
<p>And I get this image:
<a href="http://i.stack.imgur.com/wqV8n.png" rel="nofollow"><img src="http://i.stack.imgur.com/wqV8n.png" alt="enter image description here"></a></p>
<p>I would like to fill the area of... | 0 | 2016-09-21T08:46:29Z | 39,611,758 | <p>you should consider using matplotlib's <a href="http://matplotlib.org/api/patches_api.html" rel="nofollow">polygon</a></p>
| 1 | 2016-09-21T08:51:07Z | [
"python",
"matplotlib"
] |
Fill area of polygons with python | 39,611,644 | <p>I use this part of a code to plot polygons :</p>
<pre><code>plt.plot(x,y,'k',linewidth=2)
</code></pre>
<p>And I get this image:
<a href="http://i.stack.imgur.com/wqV8n.png" rel="nofollow"><img src="http://i.stack.imgur.com/wqV8n.png" alt="enter image description here"></a></p>
<p>I would like to fill the area of... | 0 | 2016-09-21T08:46:29Z | 39,617,877 | <p>I finally found the solution with plt.fill() instead of plt.plot()</p>
| 0 | 2016-09-21T13:24:19Z | [
"python",
"matplotlib"
] |
python - beautifulsoup find_all() resulting invalid date | 39,611,789 | <p>my code:</p>
<pre><code>import requests
import re
from bs4 import BeautifulSoup
r = requests.get(
"https://www.traveloka.com/hotel/detail?spec=22-9-2016.24-9-2016.2.1.HOTEL.3000010016588.&nc=1474427752464")
data = r.content
soup = BeautifulSoup(data, "html.parser")
ratingdates = soup.find_all("div", {"cla... | 1 | 2016-09-21T08:52:43Z | 39,613,919 | <p>It's really simple if you use Selenium. Here's a basic example with some explanation:</p>
<p>To install selenium run <code>pip install selenium</code></p>
<pre><code>from bs4 import BeautifulSoup
from selenium import webdriver
# set webdriver's browser to Firefox
driver = webdriver.Firefox()
#load page in brows... | 1 | 2016-09-21T10:26:01Z | [
"python",
"beautifulsoup"
] |
how can i change a grayscale pixel value by a colored value given the value of the pixel not the coordiante | 39,611,802 | <p>Hello i want to change a grayscale pixel value by a colored value given the value of the pixel not by the coordiante.
I know how to do it given the coordiante:</p>
<pre><code>I = np.dstack([im, im, im])
x = 5
y = 5
I[x, y, :] = [1, 0, 0]
plt.imshow(I, interpolation='nearest' )
</code></pre>
<p>But how to do it in... | 0 | 2016-09-21T08:53:15Z | 39,613,530 | <p>I suggest this, although it might be dirty :</p>
<pre><code>while [10,10,10] in I:
I[I.index([10,10,10])] = [1,0,0]
</code></pre>
| 0 | 2016-09-21T10:08:10Z | [
"python",
"image",
"image-processing",
"grayscale"
] |
Creating a list where a certain char occur a set number of times | 39,611,916 | <p>I am creating a list in python 2.7
The list consists of 1's and 0's however I need the 1's to appear randomly in the list and a set amount of times.</p>
<p>Here is a way I found of doing this however can take a long time to create the list</p>
<pre><code>numcor = 0
while numcor != (wordlen): #wordlen being ... | 1 | 2016-09-21T08:58:46Z | 39,611,999 | <p>Simpler to way to create the list with <code>0</code>s and '1's is:</p>
<pre><code>>>> n, m = 5, 10
>>> [0]*n + [1]*m
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
</code></pre>
<p>where <code>n</code> is the number of <code>0</code>s and <code>m</code> is the number of <code>1</code>s</p>
<p>Ho... | 1 | 2016-09-21T09:02:24Z | [
"python",
"arrays",
"list",
"python-2.7"
] |
Creating a list where a certain char occur a set number of times | 39,611,916 | <p>I am creating a list in python 2.7
The list consists of 1's and 0's however I need the 1's to appear randomly in the list and a set amount of times.</p>
<p>Here is a way I found of doing this however can take a long time to create the list</p>
<pre><code>numcor = 0
while numcor != (wordlen): #wordlen being ... | 1 | 2016-09-21T08:58:46Z | 39,612,340 | <p>Here is a different approach:</p>
<pre><code>from random import *
# create a list full of 0's
ls = [0 for _ in range(10)]
# pick e.g. 3 non-duplicate random indexes in range(len(ls))
random_indexes = sample(range(len(ls)), 3)
# create in-place our random list which contains 3 1's in random indexes
ls = [1 if (i in ... | 1 | 2016-09-21T09:17:43Z | [
"python",
"arrays",
"list",
"python-2.7"
] |
how to get all the elements of a html table with pagination using selenium? | 39,611,956 | <p>I have a webpage with a table. The table has pagination with 7 entries per page. I want to get access to all the elements of the table. </p>
<pre><code>table_element = driver.find_element_by_xpath(xpath)
for tr in table_element.find_elements_by_tag_name('tr'):
print tr.text
</code></pre>
<p>With the above code... | 0 | 2016-09-21T09:00:11Z | 39,619,105 | <p>You will need a loop outside of the code you provided that clicks the next page link (or the equivalent) until the next page link no longer exists. Without any HTML, we can't provide a more specific answer.</p>
| 0 | 2016-09-21T14:14:04Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Django context variable names for the templates | 39,611,973 | <p>EDIT:
I know I can change the names of the variables. My question is in the case that I don't want to do that. I want to know what are all the variables that django generates automatically.</p>
<hr>
<p>I'm doing Django's getting started tutorial and I'm on the <a href="https://docs.djangoproject.com/en/1.10/intro/... | 1 | 2016-09-21T09:00:53Z | 39,612,425 | <p>I think this default context variable name only applies when dealing with Django's Class Based Views.</p>
<p>E.g. If you are using a DetailView for a Animal model, Django will auto create a context variable called 'animal' for you to use in template. I think it also allows the use of 'object'. </p>
<p>Another exam... | 1 | 2016-09-21T09:20:47Z | [
"python",
"django",
"django-templates",
"django-class-based-views"
] |
Django context variable names for the templates | 39,611,973 | <p>EDIT:
I know I can change the names of the variables. My question is in the case that I don't want to do that. I want to know what are all the variables that django generates automatically.</p>
<hr>
<p>I'm doing Django's getting started tutorial and I'm on the <a href="https://docs.djangoproject.com/en/1.10/intro/... | 1 | 2016-09-21T09:00:53Z | 39,612,452 | <p>You can change the question_list to something else by using the <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.context_object_name" rel="nofollow">context_object_name</a> this isn't explained all that well in that part of th... | 1 | 2016-09-21T09:21:30Z | [
"python",
"django",
"django-templates",
"django-class-based-views"
] |
Not able to convert cassandra blob/bytes string to integer | 39,611,995 | <p>I have a column-family/table in cassandra-3.0.6 which has a column named "value" which is defined as a blob data type.</p>
<p>CQLSH query <code>select * from table limit 2;</code> returns me:</p>
<blockquote>
<p>id | name | value</p>
<p>id_001 | john | 0x010000000000000000</p>
<p>id_002 | terry | 0... | 0 | 2016-09-21T09:02:13Z | 39,628,303 | <ol>
<li><p>Blob will be converted to a byte array in Python if you read it directly. That looks like a byte array containing the Hex value of the blob.</p></li>
<li><p>One way is to explicitly do the conversion in your query.</p>
<p><code>select id, name, blobasint(value) from table limit 3</code></p>
<p>There shoul... | 0 | 2016-09-22T00:09:02Z | [
"python",
"cassandra",
"cqlsh",
"cqlengine"
] |
Parsing NBA reference with python beautiful soup | 39,612,000 | <p>So I'm trying to scrape out the miscellaneous stats table from this site <a href="http://www.basketball-reference.com/leagues/NBA_2016.html" rel="nofollow">http://www.basketball-reference.com/leagues/NBA_2016.html</a> using python and beautiful soup. This is the basic code so far I just want to see if it is even re... | 0 | 2016-09-21T09:02:26Z | 39,612,132 | <p><code><!--</code> is the start of a comment and <code>--></code> is the end in html so just remove the comments before you parse it:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
comm = re.compile("<!--|-->")
html = requests.get("http://www.basketball-reference.com/leagues/NBA_2016.html"... | 1 | 2016-09-21T09:07:59Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
store function values for future integration | 39,612,016 | <p>I have a function H(t) returning a float. I then want to numerically compute several integrals involving this function. However, one of the integrals basically invokes the previous integral, e.g.</p>
<pre><code>from scipy.integrate import quad
def H(t):
return t
def G1(t):
return quad(lambda x: H(x)*H(t-x... | 0 | 2016-09-21T09:02:57Z | 39,613,802 | <p>I guess it's exactly same as lru_cache, but since I already wrote it, might as well share:</p>
<pre><code>def store_result(func):
def remember(t):
if t not in func.results:
func.results[t] = func(t)
return func.results[t]
setattr(func, 'results', {}) # make dictionary to store r... | 0 | 2016-09-21T10:19:58Z | [
"python",
"function",
"store",
"integrate"
] |
python - scatter plot with dates and 3rd variable as color | 39,612,054 | <p>I am trying to plot an x-y plot, with x or y as date variable, and using a 3rd variable to color the points.
I managed to do it if none of the 3 variables are date, using:</p>
<pre><code>ax.scatter(df['x'],df['y'],s=20,c=df['z'], marker = 'o', cmap = cm.jet )
</code></pre>
<p>After searching, I find out that for n... | 1 | 2016-09-21T09:04:44Z | 39,612,731 | <p>As far as I know, one has to use <code>scatter</code> in order to color the points as you describe. One workaround could be to use a <code>FuncFormatter</code> to convert the tick labels into times on the x-axis. The code below converts the dates into numbers, makes the scatter plot, and uses a <code>FuncFormatter</... | 1 | 2016-09-21T09:33:39Z | [
"python",
"date",
"matplotlib",
"scatter"
] |
How do I replace a line in Python | 39,612,059 | <p>I am trying to write a program in Python for an assessment where I have to update a stock file for a shop.</p>
<p><a href="http://i.stack.imgur.com/0OV0L.jpg" rel="nofollow">My instructions</a></p>
<p>My code so far:</p>
<pre class="lang-python prettyprint-override"><code>#open a file in read mode
file = open("da... | 0 | 2016-09-21T09:04:51Z | 39,613,991 | <pre><code>file = open("data.txt", "a")
</code></pre>
<p>Opens the file in append mode, means writing to the end of the file without overwriting data (adding to it, not changing).</p>
<p>Use </p>
<pre><code>file = open("data.txt", "w")
</code></pre>
<p>Instead, to flush the file contents and overwrite them.</p>
<h... | 0 | 2016-09-21T10:28:46Z | [
"python"
] |
How can I convert from Datetime to Milliseconds in Django? | 39,612,125 | <p>I want to convert date (ex: 2016-09-20 22:00:00+00:00) to milliseconds. I will apply this block:</p>
<pre><code>def get_calendar_events(request):
user = request.user
taken_course = Course.objects.get_enrollments(user=user)
homework_list = []
for course in taken_course:
homework_list = cour... | -1 | 2016-09-21T09:07:37Z | 39,612,626 | <p>In python 3, you can use <a href="https://docs.python.org/3/library/datetime.html?highlight=re#datetime.datetime.timestamp" rel="nofollow"><code>timestamp()</code></a> method to get the number seconds elapsed since Jan 1, 1970. </p>
<pre><code>import datetime
d=datetime.datetime.now()
print d.timestamp()
# 14744500... | 0 | 2016-09-21T09:29:23Z | [
"python",
"json",
"django",
"database",
"datetime"
] |
Unable to write a squarefree algorithm | 39,612,207 | <p>I'm trying to write a function that returns true, if an integer is <a href="https://en.wikipedia.org/wiki/Square-free_integer" rel="nofollow">Square-Free</a> - this is what I've tried:</p>
<pre><code>def squarefree(n):
for i in range (2,n-1):
if n%(i**2)==0:
return False
else:
... | -6 | 2016-09-21T09:11:42Z | 39,613,737 | <p><strong>Your loop ends on its first run.</strong> It checks only for divisibility by the first <code>i</code>, i.e. by 4, what is caused by your <code>else</code> statement that makes the function return whether this specific <code>i</code> is a divisor or not.</p>
<p>You should wait until it ends to decide if <co... | 0 | 2016-09-21T10:17:18Z | [
"python"
] |
Writing pandas DataFrame to JSON in unicode | 39,612,240 | <p>I'm trying to write a pandas DataFrame containing unicode to json, but the built in <code>.to_json</code> function escapes the characters. How do I fix this?</p>
<p>Some sample code:</p>
<pre><code>import pandas as pd
df=pd.DataFrame([['Ï','a',1],['Ï','b',2]])
df.to_json('df.json')
</code></pre>
<p>gives:</p>
... | 1 | 2016-09-21T09:13:29Z | 39,612,316 | <p>Opening a file with the encoding set to utf-8, and then passing that file to the <code>.to_json</code> function fixes the problem:</p>
<pre><code>with open('df.json', 'w', encoding='utf-8') as file:
df.to_json(file, force_ascii=False)
</code></pre>
<p>gives the correct:</p>
<pre><code>{"0":{"0":"Ï","1":"Ï"}... | 4 | 2016-09-21T09:16:38Z | [
"python",
"json",
"pandas",
"unicode"
] |
How to use multiprocessing in a for loop - python | 39,612,248 | <p>I have a script that use python mechanize and bruteforce html form. This is a for loop that check every password from "PassList" and runs until it matches the current password by checking the redirected url. How can i implement multiprocessing here</p>
<pre><code>for x in PasswordList:
br.form['passwo... | -1 | 2016-09-21T09:13:50Z | 39,612,504 | <pre><code>from multiprocessing import Pool
def process_bruteforce(PasswordList):
<process>
if __name__ == '__main__':
pool = Pool(processes=4) # process per core
is_connected = pool.map(process_bruteforce, PasswordList)
</code></pre>
<p>I would try something like that</p>
| 0 | 2016-09-21T09:23:55Z | [
"python",
"multiprocessing",
"mechanize-python"
] |
How to use multiprocessing in a for loop - python | 39,612,248 | <p>I have a script that use python mechanize and bruteforce html form. This is a for loop that check every password from "PassList" and runs until it matches the current password by checking the redirected url. How can i implement multiprocessing here</p>
<pre><code>for x in PasswordList:
br.form['passwo... | -1 | 2016-09-21T09:13:50Z | 39,612,552 | <p>I do hope this is not for malicious purposes.</p>
<p>I've never used python mechanize, but seeing as you have no answers I can share what I know, and you can modify it accordingly.</p>
<p>In general, it needs to be its own function, which you then call pool over. I dont know about your br object, but i would proba... | 0 | 2016-09-21T09:26:18Z | [
"python",
"multiprocessing",
"mechanize-python"
] |
How to convert a large Json file into a csv using python | 39,612,262 | <p>(Python 3.5)
I am trying to parse a large user review.json file (1.3gb) into python and convert to a .csv file. I have tried looking for a simple converter tool online, most of which accept a file size maximum of 1Mb or are super expensive.
as i am fairly new to python i guess i ask 2 questions.</p>
<ol>
<li><p>is... | 0 | 2016-09-21T09:14:37Z | 39,612,324 | <p>This is not a JSON file; this is a file containing individual lines of JSON. You should parse each line individually.</p>
<pre><code>for row in infile:
data = json.loads(row)
writer.writerow(data)
</code></pre>
| 0 | 2016-09-21T09:17:05Z | [
"python",
"json",
"csv",
"dictionary"
] |
How to convert a large Json file into a csv using python | 39,612,262 | <p>(Python 3.5)
I am trying to parse a large user review.json file (1.3gb) into python and convert to a .csv file. I have tried looking for a simple converter tool online, most of which accept a file size maximum of 1Mb or are super expensive.
as i am fairly new to python i guess i ask 2 questions.</p>
<ol>
<li><p>is... | 0 | 2016-09-21T09:14:37Z | 39,612,609 | <p>Sometimes it's not as easy as having one JSON definition per line of input. A JSON definition can spread out over multiple lines, and it's not necessarily easy to determine which are the start and end braces reading line by line (for example, if there are strings containing braces, or nested structures). </p>
<p>Th... | 0 | 2016-09-21T09:28:27Z | [
"python",
"json",
"csv",
"dictionary"
] |
Pandas: Change values chosen by boolean indexing in a column without getting a warning | 39,612,300 | <p>I have a dataframe, I want to change only those values of a column where another column fulfills a certain condition. I'm trying to do this with <code>iloc</code> at the moment and it either does not work or I'm getting that annoying warning:</p>
<blockquote>
<p>A value is trying to be set on a copy of a slice fr... | 3 | 2016-09-21T09:16:03Z | 39,612,376 | <p>You are chaining you're selectors, leading to the warning. Consolidate the selection into one.<br>
Use <code>loc</code> instead</p>
<pre><code>DF.loc[DF['A'] == 1, 'B'] = 'X'
DF
</code></pre>
<p><a href="http://i.stack.imgur.com/HX26a.png" rel="nofollow"><img src="http://i.stack.imgur.com/HX26a.png" alt="enter im... | 3 | 2016-09-21T09:18:52Z | [
"python",
"python-2.7",
"pandas",
"indexing",
"condition"
] |
Pandas: Change values chosen by boolean indexing in a column without getting a warning | 39,612,300 | <p>I have a dataframe, I want to change only those values of a column where another column fulfills a certain condition. I'm trying to do this with <code>iloc</code> at the moment and it either does not work or I'm getting that annoying warning:</p>
<blockquote>
<p>A value is trying to be set on a copy of a slice fr... | 3 | 2016-09-21T09:16:03Z | 39,612,385 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p>
<pre><code>import pandas as pd
DF = pd.DataFrame({'A':[1,1,2,1,2,2,1,2,1],'B':['a','a','b','c','x','t','i','x','b']})
DF.ix[DF['A'] == 1, 'B'] = 'X'
print (DF)
0 1 X
1 1 X
2 2... | 3 | 2016-09-21T09:19:05Z | [
"python",
"python-2.7",
"pandas",
"indexing",
"condition"
] |
Ealasticsearch results exactly as parameter | 39,612,301 | <p>I'm trying to filter logs based on the domain name. For example I only want the results of domain: bh250.example.com.</p>
<p>When I use the following query:</p>
<p><a href="http://localhost:9200/_search?pretty&size=150&q=domainname=bh250.example.com" rel="nofollow">http://localhost:9200/_search?pretty&... | 0 | 2016-09-21T09:16:04Z | 39,612,618 | <p>You're almost there, you just need to make a small change:</p>
<pre><code>http://localhost:9200/_search?pretty&size=150&q=domainname:"bh250.example.com"
^ ^
| ... | 0 | 2016-09-21T09:28:56Z | [
"python",
"django",
"elasticsearch"
] |
Evaluating trigonometric expressions in sympy | 39,612,356 | <p>Using python 2.7 with PyCharm Community Edition 2016.2.3 + Anaconda distribution.</p>
<p>I have an input similar to :</p>
<pre><code>from sympy import *
x = symbols('x')
f = cos(x)
print (f.subs(x, 25))
</code></pre>
<p>The output is <code>cos(25)</code>, . Is there a way to evaluate trigonometric identities suc... | 0 | 2016-09-21T09:18:16Z | 39,612,587 | <p>Perform a <em>numerical evaluation</em> using <a href="http://docs.sympy.org/latest/modules/evalf.html#numerical-evaluation" rel="nofollow">function <code>N</code></a>:</p>
<pre><code>>>> from sympy import N, symbols, cos
>>> x = symbols('x')
>>> f = cos(x)
>>> f.subs(x, 25)
cos(... | 2 | 2016-09-21T09:27:36Z | [
"python",
"numpy",
"trigonometry",
"sympy"
] |
declare a variable as *not* an integer in sage/maxima solve | 39,612,476 | <p>I am trying to solve symbolically a simple equation for x:</p>
<pre><code>solve(x^K + d == R, x)
</code></pre>
<p>I am declaring these variables and assumptions:</p>
<pre><code>var('K, d, R')
assume(K>0)
assume(K, 'real')
assume(R>0)
assume(R<1)
assume(d<R)
assumptions()
︡> [K > 0, K is real,... | 1 | 2016-09-21T09:22:38Z | 39,616,465 | <p>The assumption framework in both Sage and Maxima is fairly weak, though in this case it doesn't matter, since integers are real numbers, right? </p>
<p>However, you might want to try `assume(K,'noninteger') because apparently <a href="http://maxima.sourceforge.net/docs/manual/maxima_11.html#Item_003a-integer" rel=... | 1 | 2016-09-21T12:23:53Z | [
"python",
"sage",
"maxima"
] |
airflow triggle_dag execution_date is the next day, why? | 39,612,488 | <p>Recently I have tested airflow so much that have one problem with <code>execution_date</code> when running <code>airflow trigger_dag <my-dag></code>.</p>
<p>I have learned that <code>execution_date</code> is not what we think at first time from <a href="https://cwiki.apache.org/confluence/display/AIRFLOW/Comm... | 2 | 2016-09-21T09:23:09Z | 39,620,901 | <p>First, I recommend you use constants for <code>start_date</code>, because dynamic ones would act unpredictably based on with your airflow pipeline is evaluated by the scheduler.</p>
<p>More information about <code>start_date</code> here in an FAQ entry that I wrote and sort all this out:
<a href="http://pythonhoste... | 2 | 2016-09-21T15:34:49Z | [
"python",
"airflow"
] |
ValueError: too many values to unpack matplotlib errorbar | 39,612,579 | <p>I am trying to plot a errorbar:</p>
<pre><code>plt.errorbar(np.array(x_axis), np.array(y_axis), yerr=(np.array(y_bot), np.array(y_top)), linestyle='None', marker='^')
</code></pre>
<p>But it throws an error :</p>
<pre><code>plt.errorbar(np.array(x_axis), np.array(y_axis), yerr=(np.array(y_bot), np.array(y_top)), ... | -1 | 2016-09-21T09:27:23Z | 39,612,854 | <p>The following works fine for me:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x_axis = range(4)
y_axis = range(4)
y_bot = range(4)
y_top = range(4)
plt.errorbar(np.array(x_axis), np.array(y_axis), yerr=(np.array(y_bot), np.array(y_top)), linestyle='None', marker='^')
</code></pre>
<p>You way w... | 2 | 2016-09-21T09:39:10Z | [
"python",
"numpy",
"matplotlib"
] |
Python: Socket send returns malformed URL | 39,612,721 | <p>Hello I am trying to access a file via python socket module and I am getting HTTP 400 Bad request error but I am not sure what mistake I have done. </p>
<pre><code>import socket
mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysocket.connect(('www.pythonlearn.com',80))
mysocket.send(b'GET http://www.pyth... | 1 | 2016-09-21T09:33:04Z | 39,613,088 | <p>The error is on the http request, Host and requested file should be separated.</p>
<pre><code>http_request = 'GET /code/intro-short.txt HTTP/1.0\n'
http_request += 'Host:www.pythonlearn.com\n'
http_request += '\n'
mysocket.send(http_request)
</code></pre>
| 0 | 2016-09-21T09:48:58Z | [
"python",
"sockets"
] |
Python - Add a line behind a specific string with a consecutive numeric | 39,612,737 | <p>I do have a little problem i can't solve in Python, iam not really familiar with this codes commands, that's one of the reasons this is kind of difficult for me.</p>
<p>For example, when i have a text file like this:</p>
<pre><code>Indicate somename X1
Random qwerty
Indicate somename X2
random azerty
Indicate some... | 0 | 2016-09-21T09:33:57Z | 39,613,108 | <pre><code>with open('sample') as fp, open('sample_out', 'w') as fo:
for line in fp:
if 'Indicate' in line:
content = line.strip() + " = 500"
else:
content = line.strip()
fo.write(content + "\n")
</code></pre>
| 0 | 2016-09-21T09:49:59Z | [
"python",
"string"
] |
Python - Add a line behind a specific string with a consecutive numeric | 39,612,737 | <p>I do have a little problem i can't solve in Python, iam not really familiar with this codes commands, that's one of the reasons this is kind of difficult for me.</p>
<p>For example, when i have a text file like this:</p>
<pre><code>Indicate somename X1
Random qwerty
Indicate somename X2
random azerty
Indicate some... | 0 | 2016-09-21T09:33:57Z | 39,613,273 | <pre><code>with open('/tmp/content.txt') as f: # where: '/tmp/content.txt' is the path of file
for i, line in enumerate(f.readlines()):
line = line.strip()
if not (i % 2):
line += ' value = 500'
print line.strip()
# Output:
Indicate somename X1 value = 500
Random qwerty
Indicat... | 0 | 2016-09-21T09:56:30Z | [
"python",
"string"
] |
Python - Add a line behind a specific string with a consecutive numeric | 39,612,737 | <p>I do have a little problem i can't solve in Python, iam not really familiar with this codes commands, that's one of the reasons this is kind of difficult for me.</p>
<p>For example, when i have a text file like this:</p>
<pre><code>Indicate somename X1
Random qwerty
Indicate somename X2
random azerty
Indicate some... | 0 | 2016-09-21T09:33:57Z | 39,613,603 | <p>using 're' module</p>
<p>eg.</p>
<pre><code> if re.match(r'Indicate somename [A-Z][0-2]', line):
modified = line.strip() + ' value = XXX'
</code></pre>
<p>if you want require to modify input file in-place,
read entry file in to buffer then write result back. </p>
| 0 | 2016-09-21T10:12:10Z | [
"python",
"string"
] |
Runtime.exec() in java hangs because it is waiting for input from System.in | 39,612,862 | <p>I have the following short python program "test.py"</p>
<pre><code>n = int(raw_input())
print n
</code></pre>
<p>I'm executing the above program from following java program "ProcessRunner.java"</p>
<pre><code>import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] ... | 2 | 2016-09-21T09:39:33Z | 39,613,049 | <p><a href="https://docs.python.org/2/library/functions.html?highlight=raw_input#raw_input" rel="nofollow"><code>raw_input()</code></a>, or <a href="https://docs.python.org/3/library/functions.html?highlight=raw_input#input" rel="nofollow"><code>input()</code></a> in Python 3, will block waiting for new line terminated... | 1 | 2016-09-21T09:47:49Z | [
"java",
"python",
"multithreading",
"process",
"runtime.exec"
] |
Runtime.exec() in java hangs because it is waiting for input from System.in | 39,612,862 | <p>I have the following short python program "test.py"</p>
<pre><code>n = int(raw_input())
print n
</code></pre>
<p>I'm executing the above program from following java program "ProcessRunner.java"</p>
<pre><code>import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] ... | 2 | 2016-09-21T09:39:33Z | 39,613,611 | <p>If I understand you correctly you want your java program to pass any output from your python script to System.out and any input into your java program to your python Script, right?</p>
<p>Have a look at the following program to get an idea how you could do this. </p>
<pre><code>import java.io.IOException;
import j... | 0 | 2016-09-21T10:12:28Z | [
"java",
"python",
"multithreading",
"process",
"runtime.exec"
] |
Collapsable bootstrap multilevel listview populated from database for beginners | 39,613,065 | <p>As a beginning coder, I could use some help understanding what's involved in building a listview populated from a database with rows that can expand and collapse, providing more information, with embedded buttons for controls? I'd like to use mostly bootstrap and python or PHP and replicate this: <a href="http://pre... | -1 | 2016-09-21T09:48:27Z | 39,616,051 | <p>Here is the DEMO that you required </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.collapse').on('shown.bs.collapse', function (e) {
//Get the id of the c... | 0 | 2016-09-21T12:02:35Z | [
"php",
"python",
"database",
"twitter-bootstrap",
"listview"
] |
How to deal with the parameters with script | 39,613,113 | <p>I print the args from: </p>
<pre><code>if __name__ == '__main__':
print('The sys.argv is :\n',sys.argv)
</code></pre>
<p>and find that all the parameters transfer into string and i don't know how to deal with it.</p>
<p>Command <code>python3 MAX_HEAPIFY.py [1,2,3,4,5,6,7,8,9,10] 2</code></p>
<p>output: <code>[... | -1 | 2016-09-21T09:50:07Z | 39,613,414 | <p>You need to understand that python accepts all input on the command line as strings. It is up to you to process the args in your code. </p>
<p>Ideally you would use <code>argparse</code> to make this more robust, but for this example you can run a command like this:</p>
<pre><code>python3 MAX_HEAPIFY.py "1,2,3,4,5... | 0 | 2016-09-21T10:03:17Z | [
"python",
"python-3.x"
] |
Pandas: concatenate dataframes | 39,613,228 | <p>I have 2 dataframe</p>
<pre><code>category count_sec_target
3D-ÑÑÑеÑÑ 0.09375
CеÑÐ¸Ð°Ð»Ñ 201.90625
GPS и ÐÐÐÐÐСС 0.015625
Hi-Tech 187.1484375
ÐбиÑÑÑиенÑам 0.8125
Ðвиакомпании 8.40625
</code></pre>
<p>and </p>
<pre><code>category count_sec_random
3D... | 2 | 2016-09-21T09:54:35Z | 39,613,343 | <pre><code>df3 = pd.concat([d.set_index('category') for d in frames], axis=1).fillna(0)
df3['ratio'] = df3.count_sec_random / df3.count_sec_target
df3
</code></pre>
<p><a href="http://i.stack.imgur.com/Xp8Dg.png" rel="nofollow"><img src="http://i.stack.imgur.com/Xp8Dg.png" alt="enter image description here"></a></p>
... | 5 | 2016-09-21T09:59:50Z | [
"python",
"pandas"
] |
Pandas: concatenate dataframes | 39,613,228 | <p>I have 2 dataframe</p>
<pre><code>category count_sec_target
3D-ÑÑÑеÑÑ 0.09375
CеÑÐ¸Ð°Ð»Ñ 201.90625
GPS и ÐÐÐÐÐСС 0.015625
Hi-Tech 187.1484375
ÐбиÑÑÑиенÑам 0.8125
Ðвиакомпании 8.40625
</code></pre>
<p>and </p>
<pre><code>category count_sec_random
3D... | 2 | 2016-09-21T09:54:35Z | 39,613,460 | <p>Merge should be appropriate here:</p>
<pre><code>df_1.merge(df_2, on='category', how='outer').fillna(0)
</code></pre>
<p><a href="http://i.stack.imgur.com/4pk3L.png" rel="nofollow"><img src="http://i.stack.imgur.com/4pk3L.png" alt="Image"></a></p>
<hr>
<p>To get the division output, simply do:</p>
<pre><code>df... | 4 | 2016-09-21T10:05:23Z | [
"python",
"pandas"
] |
How to get the number of non-shared insertions and gaps in a sequence in Python? | 39,613,421 | <p>I am trying to obtain the number of insertions and gaps contained in a series of sequences with relation to a reference with which they were aligned; therefore, <strong>all sequences are now of the same length.</strong></p>
<p>For instance</p>
<pre><code>>reference
AGCAGGCAAGGCAA--GGAA-CCA
>sequence1
AAAA---... | 2 | 2016-09-21T10:03:51Z | 39,614,370 | <p>This is a job for the <code>zip</code> function. We iterate over the reference and a test sequence in parallel, seeing if either one contains a <code>-</code> at the current position. We use the result of that test to update counts of insertions, deletions and unchanged in a dictionary.</p>
<pre><code>def kind(u, v... | 1 | 2016-09-21T10:45:33Z | [
"python",
"bioinformatics",
"biopython",
"fasta"
] |
How to get the number of non-shared insertions and gaps in a sequence in Python? | 39,613,421 | <p>I am trying to obtain the number of insertions and gaps contained in a series of sequences with relation to a reference with which they were aligned; therefore, <strong>all sequences are now of the same length.</strong></p>
<p>For instance</p>
<pre><code>>reference
AGCAGGCAAGGCAA--GGAA-CCA
>sequence1
AAAA---... | 2 | 2016-09-21T10:03:51Z | 39,627,265 | <p>Using Biopython and numpy:</p>
<pre><code>from Bio import AlignIO
from collections import Counter
import numpy as np
alignment = AlignIO.read("alignment.fasta", "fasta")
events = []
for i in range(alignment.get_alignment_length()):
this_column = alignment[:, i]
# Mark insertions, polymorphism and delet... | 1 | 2016-09-21T22:04:00Z | [
"python",
"bioinformatics",
"biopython",
"fasta"
] |
How to handle SQLAlchemy Connections in ProcessPool? | 39,613,476 | <p>I have a reactor that fetches messages from a RabbitMQ broker and triggers worker methods to process these messages in a process pool, something like this:</p>
<p><a href="http://i.stack.imgur.com/eKbAK.png"><img src="http://i.stack.imgur.com/eKbAK.png" alt="Reactor"></a></p>
<p>This is implemented using python <c... | 20 | 2016-09-21T10:06:08Z | 39,842,259 | <p>@roman: Nice challenge you have there.</p>
<p>I have being in a similar scenario before so here is my <em>2 cents</em>: unless this consumer only <em>"read"</em> and <em>"write"</em> the message, without do any real proccessing of it, you could <em>re-design</em> this consumer as a consumer/producer that will <em>c... | 0 | 2016-10-04T00:01:37Z | [
"python",
"sqlalchemy",
"rabbitmq",
"python-multiprocessing",
"python-asyncio"
] |
How to handle SQLAlchemy Connections in ProcessPool? | 39,613,476 | <p>I have a reactor that fetches messages from a RabbitMQ broker and triggers worker methods to process these messages in a process pool, something like this:</p>
<p><a href="http://i.stack.imgur.com/eKbAK.png"><img src="http://i.stack.imgur.com/eKbAK.png" alt="Reactor"></a></p>
<p>This is implemented using python <c... | 20 | 2016-09-21T10:06:08Z | 39,930,596 | <p>An approach that has served me really well is to use a webserver to handle and scale the process pool. flask-sqlalchemy even in its default state will keep a connection pool and not close each connection on each request response cycle. </p>
<p>The asyncio executor can just call url end points to execute your functi... | 0 | 2016-10-08T09:04:20Z | [
"python",
"sqlalchemy",
"rabbitmq",
"python-multiprocessing",
"python-asyncio"
] |
How to handle SQLAlchemy Connections in ProcessPool? | 39,613,476 | <p>I have a reactor that fetches messages from a RabbitMQ broker and triggers worker methods to process these messages in a process pool, something like this:</p>
<p><a href="http://i.stack.imgur.com/eKbAK.png"><img src="http://i.stack.imgur.com/eKbAK.png" alt="Reactor"></a></p>
<p>This is implemented using python <c... | 20 | 2016-09-21T10:06:08Z | 40,060,154 | <p>Your requirement of <strong>one database connection per process-pool process</strong> can be easily satisfied if some care is taken on how you instantiate the <code>session</code>, assuming you are working with the orm, in the worker processes.</p>
<p>A simple solution would be to have a global <a href="http://docs... | 3 | 2016-10-15T14:20:23Z | [
"python",
"sqlalchemy",
"rabbitmq",
"python-multiprocessing",
"python-asyncio"
] |
Is there a way I can prevent users from entering numbers with input() | 39,613,496 | <p>I would like to prevent the user from entering numbers to save troubles down the line in my program. I know how to use try, except with int(input()) to prevent strings being entered when integers are required but I was wondering if a similar thing was possible with str(input()).</p>
<p>For example, if the user was ... | 0 | 2016-09-21T10:06:55Z | 39,613,634 | <p>Use a <code>try-except</code> with an <code>else</code> block in which you'll raise a <code>ValueError</code> if an Exception <em>didn't</em> occur during conversion to an <code>int</code> (which means the input <em>is</em> an <code>int</code>:</p>
<pre><code>v = input("> ")
try:
_ = int(v)
except:
pass
... | 2 | 2016-09-21T10:13:13Z | [
"python",
"string",
"python-3.x",
"input"
] |
External tools stdout not shown during execution | 39,613,514 | <p>I am calling python scripts from android studio as external tools.</p>
<p>Only after the script has exited, its stderr/stdout is displayed in the integrated Android Studio "Run" tool window. I want to be able to see the output during execution. (How) is that possible?</p>
<p><a href="http://i.stack.imgur.com/Gw1xn... | 0 | 2016-09-21T10:07:38Z | 39,618,508 | <p>Running Python in unbuffered mode (<code>-u</code>) fixxed it
- first Line of my python script: </p>
<pre><code>#! /usr/bin/python3 -u
</code></pre>
<p>Thanks for the solution to Serge Baranov from Jetbrains support:</p>
<blockquote>
<p>Sep 21, 16:23 MSK</p>
<p>Could it be caused by the buffered output? Se... | 0 | 2016-09-21T13:49:58Z | [
"python",
"android-studio",
"intellij-idea"
] |
Installing MySQL-python on windows 7 | 39,613,528 | <p>Hey I tried installing MySQL-Pyhton for abut 5 hours now but keep getting an error. at first it was "Unable to find vcvarsall.bat" and some thing abut me needing to have visual C++ 2010 . so after looking around I found a "solution" for my problem ... only to receive a new error when I pip install MySQL-Pyhton.</p>
... | 0 | 2016-09-21T10:08:01Z | 39,613,663 | <p>you're going to want to add Python to your Path Environment Variable in this way. Go to:</p>
<ol>
<li>My Computer</li>
<li>System Properties</li>
<li>Advanced System Settings</li>
<li>Under the "Advanced" tab click the button that says "Environment Variables"</li>
<li>Then under System Variables you are going to wa... | 0 | 2016-09-21T10:14:24Z | [
"python",
"mysql",
"python-3.x"
] |
N-grams - not in memory | 39,613,555 | <p>I have 3 milion abstracts and I would like to extract 4-grams from them. I want to build a language model so I need to find the frequencies of these 4-grams. </p>
<p>My problem is that I can't extract all these 4-grams in memory. How can I implement a system that it can estimate all frequencies for these 4-grams? <... | 1 | 2016-09-21T10:09:33Z | 39,613,813 | <p>Sounds like you need to store the intermediate frequency counts on disk rather than in memory. Luckily most databases can do this, and python can talk to most databases.</p>
| 0 | 2016-09-21T10:20:25Z | [
"python",
"n-gram",
"language-model"
] |
Programmatically disown/nohup in Python | 39,613,617 | <p>I want to run a little script that pings a server once every X seconds/minutes and if it doesn't get the expected response, send an email to the specified email address to notify me the server is down.
Obviously, I want to run this script on some server with a nohup option, so that it stays alive when I disconnect. ... | 1 | 2016-09-21T10:12:40Z | 39,614,269 | <p>You can give your password as encrypted using openssl.</p>
<p>For example :</p>
<pre><code>echo $(openssl passwd -crypt mypassword)
</code></pre>
<p>Output :</p>
<pre><code>eXzWQlhzBJZ9.
</code></pre>
<p>Similarly You can give it as -</p>
<pre><code>nohup pingServer.py -u <username> -p $(openssl passwd -... | 0 | 2016-09-21T10:40:45Z | [
"python"
] |
Why this python script is giving wrong output,using awk and comapring value in if block? | 39,613,747 | <p>I want to get desktop notification whenever load is more than five,for that I have written this python script but it is giving opposite to expected</p>
<pre><code>#!/usr/bin/python
import commands
a=commands.getoutput("cat /proc/loadavg | awk '{print $1}'")
float (a)
print a
if (a > 5.00):
commands.getoutp... | -1 | 2016-09-21T10:17:49Z | 39,613,843 | <p>You need to assign the typecast float value back to <code>a</code>. A plain print to console can be deceiving since you will not be able to tell if the variable is a float or not. So you can use <code>type</code> to confirm</p>
<pre><code>#!/usr/bin/python
import commands
a = commands.getoutput("cat /proc/loadavg ... | 4 | 2016-09-21T10:22:10Z | [
"python",
"linux",
"shell",
"if-statement"
] |
Why this python script is giving wrong output,using awk and comapring value in if block? | 39,613,747 | <p>I want to get desktop notification whenever load is more than five,for that I have written this python script but it is giving opposite to expected</p>
<pre><code>#!/usr/bin/python
import commands
a=commands.getoutput("cat /proc/loadavg | awk '{print $1}'")
float (a)
print a
if (a > 5.00):
commands.getoutp... | -1 | 2016-09-21T10:17:49Z | 39,652,599 | <p>Getting the first token from a file is easy to do natively in Python. There is no reason to call <code>awk</code> (let alone then <a href="http://www.iki.fi/era/unix/award.html" rel="nofollow"><code>cat</code> and <code>awk</code></a>) and wastefully create a subprocess chain for this simple thing.</p>
<pre><code>... | 1 | 2016-09-23T04:22:37Z | [
"python",
"linux",
"shell",
"if-statement"
] |
Fast random to unique relabeling of numpy 2d regions (without loops) | 39,613,884 | <p>I have a large numpy 2d array (10000,10000) in which regions (clusters of cells with the same number) are randomly labeled. As a result, some separate regions were assigned to the same label. What I would like is to relabel the numpy 2d array so that all separate regions are assigned to a unique label (see example).... | 2 | 2016-09-21T10:24:09Z | 39,614,709 | <p>Let's cheat and just use some high-quality library (<a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>) which offers exactly this.</p>
<p>You may learn from it's implementation or just use it!</p>
<pre><code>import numpy as np
from skimage.measure import label
random_arr = np.array([[1,1,3,3],[1,2... | 3 | 2016-09-21T11:01:20Z | [
"python",
"arrays",
"numpy",
"scipy",
"vectorization"
] |
Antialiased text rendering in matplotlib pgf backend | 39,614,011 | <p>I have a question regarding the text rendering in the matplotlib <code>pgf</code> backend. I am using matplotlib to export .pdf files of my plots. In the section with the rcParameters I define that I want to use sans-serif and I want to use Helvetica as font. Therefore I disabled the option <code>text.usetex</code>.... | 0 | 2016-09-21T10:29:39Z | 39,616,713 | <p>I think I finally found my answer after many attempts. I found it in <a href="http://stackoverflow.com/a/20709149/5528308">this SO post</a>.</p>
<p>I merely added this to the preamble:</p>
<pre><code>r'\usepackage{helvet}', # set the normal font here
r'\usepackage{sansmath}', # load up the sansmath so that mat... | 0 | 2016-09-21T12:34:55Z | [
"python",
"matplotlib",
"fonts",
"pdf-generation",
"pgf"
] |
List available font families in `tkinter` | 39,614,027 | <p>In many <code>tkinter</code> examples available out there, you may see things like:</p>
<pre><code>canvas.create_text(x, y, font=('Helvetica', 12), text='foo')
</code></pre>
<p>However, this may not work when run in your computer (the result would completely ignore the font parameter). Aparently, the <code>font</c... | 0 | 2016-09-21T10:30:00Z | 39,614,028 | <pre><code>from tkinter import Tk, font
root = Tk()
font.families()
</code></pre>
| 1 | 2016-09-21T10:30:00Z | [
"python",
"tkinter"
] |
collect rows and columns based on id matching | 39,614,059 | <p>I use python and the pandas library. I want to collect the rows and columns from a data-frame according to one criteria, collect only those ids with a pattern like 'BIKE-\d\d\d\d' from a specific column 'BikeID'. I tried several versions of the following: </p>
<p>d1 = pandas.dataframe</p>
<pre><code>d2 = d1[d1["Bi... | -1 | 2016-09-21T10:30:48Z | 39,614,204 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>str.extract</code></a> to achieve this with the regex pattern <code>'(^BIKE-[\d]{4})'</code> this will look for strings that start with BIKE- and then 4 digits:</p>
<pre><code>In [167]:
s=... | 0 | 2016-09-21T10:37:57Z | [
"python",
"pandas",
"dataframe"
] |
Duplicates / common elements between two lists | 39,614,083 | <p>I have a stupid question for people who are familiar with lists in Python.
I want to get the common items in two lists. Assuming that I have this list :</p>
<pre><code>dates_list = ['2016-07-08 02:00:02',
'2016-07-08 02:00:17',
'2016-07-08 02:00:03',
'2016-07-08 02:00:20... | 0 | 2016-09-21T10:32:09Z | 39,614,124 | <p>Once the item is found in one of the sublists, the search goes on with the other sublists. </p>
<p>You should consider using a <code>break</code>, to stop the search for the current date item once it is found in one of the sublists:</p>
<pre><code>for item in beginning_time_list:
for one_list in time_by_second... | 1 | 2016-09-21T10:34:28Z | [
"python",
"list",
"python-2.7",
"for-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.