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 |
|---|---|---|---|---|---|---|---|---|---|
PySpark: Calculate grouped-by AUC | 37,582,385 | <ul>
<li>Spark version: 1.6.0</li>
</ul>
<p>I tried computing AUC (area under ROC) grouped by the field <code>id</code>. Given the following data:</p>
<pre><code># Within each key-value pair
# key is "id"
# value is a list of (score, label)
data = sc.parallelize(
[('id1', [(0.5, 1.0), (0.6, 0.0), (0.7, 1.0),... | 3 | 2016-06-02T03:56:31Z | 37,587,466 | <p>Instead of using <code>BinaryClassificationMetrics</code> you can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html" rel="nofollow">sklearn.metrics.auc</a> and map each RDD element value and you'll get your AUC value per key:</p>
<pre><code>from sklearn.metrics import auc
data ... | 3 | 2016-06-02T09:13:18Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-mllib"
] |
Change Boolean Output | 37,582,465 | <p>I'm trying to change the output of Boolean values.</p>
<p>For example if I've got something like:</p>
<pre><code>3 == 3
</code></pre>
<p>I don't want it to return <code>True</code>, but to return something that I specify like <code>Correct</code></p>
<p>How can I do this?</p>
<p><strong>Update</strong></p>
<p>... | -1 | 2016-06-02T04:04:37Z | 37,582,481 | <pre><code>def equivalence(a,b):
if(a==b):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>Then you can call this function.</p>
<pre><code>equivalence(5,5) #This will print "Correct"
equivalence(5,6) #This will print "Incorrect"
</code></pre>
<p>If you actually want to change what <... | 4 | 2016-06-02T04:06:31Z | [
"python",
"boolean"
] |
Change Boolean Output | 37,582,465 | <p>I'm trying to change the output of Boolean values.</p>
<p>For example if I've got something like:</p>
<pre><code>3 == 3
</code></pre>
<p>I don't want it to return <code>True</code>, but to return something that I specify like <code>Correct</code></p>
<p>How can I do this?</p>
<p><strong>Update</strong></p>
<p>... | -1 | 2016-06-02T04:04:37Z | 37,582,595 | <pre><code>x = float(input("enter a Number between 1 - 5: "))
Correct = False
while (not Correct):
if x == 3:
Correct = True
print("Correct")
else:
print("sorry guess again!")
x = float(input("enter a Number between 1 - 5: "))
</code></pre>
| -1 | 2016-06-02T04:18:31Z | [
"python",
"boolean"
] |
Change Boolean Output | 37,582,465 | <p>I'm trying to change the output of Boolean values.</p>
<p>For example if I've got something like:</p>
<pre><code>3 == 3
</code></pre>
<p>I don't want it to return <code>True</code>, but to return something that I specify like <code>Correct</code></p>
<p>How can I do this?</p>
<p><strong>Update</strong></p>
<p>... | -1 | 2016-06-02T04:04:37Z | 37,582,603 | <p>The <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow">shorties way</a> to do it is:</p>
<pre><code>"Correct" if 3 == 3 else "Incorrect"
</code></pre>
<p>There is no good way to change behaivour of <code>print(True)</code> output.</p>
| 2 | 2016-06-02T04:19:26Z | [
"python",
"boolean"
] |
Python: How would one represent this particular for loop using list comprehension? | 37,582,496 | <p>As the title states, I would like to know how to use "list comprehension" to shorten this for loop. The loop is functional; however, the details of the assignment given to me states that I should have at least one list comprehension and this was the only for loop in my code. By the way, I am fairly new to python.</p... | 0 | 2016-06-02T04:07:58Z | 37,582,638 | <p>I assume what you want is to take elements from <code>a</code> and place them in <code>c</code> if those elements are present in <code>b</code>. Also you want to make sure that only one such element exits in <code>c</code>, meaning <code>c</code> is a set. </p>
<p>You can do that as</p>
<pre><code>>>> a =... | 1 | 2016-06-02T04:23:58Z | [
"python",
"for-loop",
"list-comprehension"
] |
Dividing a text file into two different parts | 37,582,513 | <p>I have written a simple script to collect a list of titles from the JSON file and generated a text file containing the list.</p>
<p>The result is as follows:</p>
<pre><code>Animal geography
Autobiogeography
Chorography
Economic geography
Footloose industry
Geomorphometry
Health geography
Human geography
Military g... | 0 | 2016-06-02T04:09:39Z | 37,582,696 | <p>You can try this :</p>
<pre><code>with open('file.txt', 'r') as f:
data = []
category = []
lines = f.readlines()
for line in lines:
if line.startswith('Category'):
category.append(line)
else:
data.append(line)
cat_file = open('category.txt', 'w')
d... | 0 | 2016-06-02T04:30:26Z | [
"python",
"json",
"python-2.7"
] |
Dividing a text file into two different parts | 37,582,513 | <p>I have written a simple script to collect a list of titles from the JSON file and generated a text file containing the list.</p>
<p>The result is as follows:</p>
<pre><code>Animal geography
Autobiogeography
Chorography
Economic geography
Footloose industry
Geomorphometry
Health geography
Human geography
Military g... | 0 | 2016-06-02T04:09:39Z | 37,582,732 | <p>To test if a line in a file begins with "Category:", you can simply do this:</p>
<pre><code>with open("file.txt", "r") as f:
for line in f.read().splitlines():
if line[0:8] == "Category":
<here your code that writes "Category:" lines in a new file>
else:
<here y... | 1 | 2016-06-02T04:35:12Z | [
"python",
"json",
"python-2.7"
] |
Dividing a text file into two different parts | 37,582,513 | <p>I have written a simple script to collect a list of titles from the JSON file and generated a text file containing the list.</p>
<p>The result is as follows:</p>
<pre><code>Animal geography
Autobiogeography
Chorography
Economic geography
Footloose industry
Geomorphometry
Health geography
Human geography
Military g... | 0 | 2016-06-02T04:09:39Z | 37,582,760 | <p>Thanks leekaiinthesky for telling me to use 'in'</p>
<pre><code>f1 = open('List.text', 'r')
f2 = open('WordWithCat.text', 'w')
f3 = open('WordwithoutCat.text', 'w')
query = 'Category:'
lines = f1.read().splitlines()
for line in lines:
if query in line:
f2.write(line+'\n')
else:
f3.writ... | 0 | 2016-06-02T04:37:49Z | [
"python",
"json",
"python-2.7"
] |
List of Dictionary Manipulation in python | 37,582,548 | <p>I have a list of the folowing form: </p>
<pre><code>oldlist = [{'x': 1, 'y':2},{'x':2, 'y':2},{'x':1, 'y':3},{'x':1, 'y':2},{'x':3, 'y':4}]
</code></pre>
<p>to be converted into </p>
<pre><code>final = [{'x':1,'y':[2,3,2],'count':3},{'x':2,'y':[2],'count':1},{'x':3,'y':[4],'count':1}]
</code></pre>
<p>I ha... | 0 | 2016-06-02T04:12:46Z | 37,582,605 | <p>You can collect the dicts to <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> where key is <code>x</code> from original dicts and value is list of related <code>y</code> values. Then use list comprehension to generate the final result:</... | 4 | 2016-06-02T04:19:32Z | [
"python"
] |
List of Dictionary Manipulation in python | 37,582,548 | <p>I have a list of the folowing form: </p>
<pre><code>oldlist = [{'x': 1, 'y':2},{'x':2, 'y':2},{'x':1, 'y':3},{'x':1, 'y':2},{'x':3, 'y':4}]
</code></pre>
<p>to be converted into </p>
<pre><code>final = [{'x':1,'y':[2,3,2],'count':3},{'x':2,'y':[2],'count':1},{'x':3,'y':[4],'count':1}]
</code></pre>
<p>I ha... | 0 | 2016-06-02T04:12:46Z | 37,582,823 | <p>Ok, I used a little trick here to do the job, it's not the most pythonic way but it still gets the answer you want.
The problem was indexing? So a changed s to t, where t is a list and changed the end of the code because you have to put the keys on your dictionaries as strings, so x become 'x' and so on.</p>
<p>See... | 0 | 2016-06-02T04:43:44Z | [
"python"
] |
Remove the outline of an oval in Tkinter? | 37,582,572 | <p>By default, the circle I draw on a canvas has a black outline. I'm trying not to use a color, but somehow make the outline disappear.</p>
<pre><code>import tkinter
class Draw:
def __init__(self):
self._root_window = tkinter.Tk()
self._canvas = tkinter.Canvas(master = self._root_window,
... | 2 | 2016-06-02T04:16:22Z | 37,583,410 | <p>Add <code>outline=""</code> parameter to <code>create_oval</code> method.</p>
<p>Then you can create oval link that:</p>
<pre><code>self._canvas.create_oval(100,100,250,250, fill = 'white', outline="")
</code></pre>
| 3 | 2016-06-02T05:32:54Z | [
"python",
"tkinter"
] |
Remove the outline of an oval in Tkinter? | 37,582,572 | <p>By default, the circle I draw on a canvas has a black outline. I'm trying not to use a color, but somehow make the outline disappear.</p>
<pre><code>import tkinter
class Draw:
def __init__(self):
self._root_window = tkinter.Tk()
self._canvas = tkinter.Canvas(master = self._root_window,
... | 2 | 2016-06-02T04:16:22Z | 37,585,963 | <p>Apart from using <code>outline =""</code> or <code>outline = "white"</code>, you can specify the width of outline to be <code>0</code> because by default it is set to <code>1</code>. </p>
<p>Add <strong><code>width = 0</code></strong> as an option when you create the oval:</p>
<pre><code> self._canvas.create_ov... | 3 | 2016-06-02T08:01:07Z | [
"python",
"tkinter"
] |
Custom sort by property | 37,582,581 | <p>I have a method in Python for sorting, which takes a parameter <code>alarm.__dict__['severity']</code>. How can I access the severity parameter another way?</p>
<p>My sort function is:</p>
<pre><code>sorted(alarm_list, key=lambda alarm: alarm.__dict__['severity'])
</code></pre>
<p>Is there any other way in which ... | 1 | 2016-06-02T04:17:10Z | 37,582,607 | <p>You can use <a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow"><code>getattr()</code></a> instead of <code>__dict__</code>:</p>
<pre><code>sorted(alarm_list, key=lambda alarm: getattr(alarm, 'severity'))
</code></pre>
<p>However, it seems like this would work just as well:</p>
<pre>... | 1 | 2016-06-02T04:19:54Z | [
"python",
"dictionary"
] |
Code improvement, Python the hard way ex48 | 37,582,655 | <p>I completed the exercise after much confusion and made this code which complies with his tests.</p>
<pre><code>WORD_TYPES = {
'verb' : ['go', 'kill', 'eat'],
'direction' : ['north', 'south', 'east', 'west'],
'noun' : ['bear', 'princess'],
'stop' : ['the','in','of']
}
def scan(sentance):
listy = []... | 0 | 2016-06-02T04:26:19Z | 37,582,894 | <p>I will assume you are referring to the exercise in <a href="http://learnpythonthehardway.org/book/ex48.html" rel="nofollow">http://learnpythonthehardway.org/book/ex48.html</a></p>
<p>The author says to use <code>try</code> and <code>except</code> to "cheat" at interpreting numbers because, generally, the common way... | 0 | 2016-06-02T04:50:06Z | [
"python",
"python-2.7",
"try-except"
] |
Getting UnparsedFlagAccessError when trying to import glog in python | 37,582,672 | <p>I am trying to use glog in my python code and when I am trying to import, it throws the following error:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/glog.py:171: RuntimeWarning:
Trying to access flag verbosity before flags were parsed. This will raise
an exception in the future.
setLevel(FLAGS.verbosit... | 0 | 2016-06-02T04:28:03Z | 38,883,716 | <p>I have the same issue. After checking the code, it seems some kind of bug of glog.</p>
<p>When <code>import glog</code> is intercepted, it assumes <code>gflags.GFLAGS</code> has been initiated, and tries to read <code>gflags.GFLAGS.verbosity</code>, which actually is not guaranteed to be initialized in most cases.<... | 1 | 2016-08-10T21:16:35Z | [
"python",
"python-2.7",
"python-3.x",
"glog",
"gflags"
] |
Printing certain strings different colour with termcolor.colored? | 37,582,695 | <p>I would like to print certain strings in different colours in Python. I need to modify the code:</p>
<pre><code>board_p1 = []
board_pc = []
board_size=6
for x in range(board_size):
board_p1.append(["[W]"] * board_size)
board_pc.append(["[W]"] * board_size)
def print_board(board):
if board == board_p1... | 0 | 2016-06-02T04:30:07Z | 37,583,547 | <p>Although the following would parse correctly due to the added parentheses:</p>
<pre><code>print " ".join(colored(element,"cyan") if element != "[S]" else (colored(element,"green") if element != "[X]" else (colored(element,"red") if element != "[H]" else colored(element,"magenta"))) for element in row)
</code></pre>... | 1 | 2016-06-02T05:42:49Z | [
"python",
"colors"
] |
Find unique permutation of a list binary values without generating all possibilities | 37,582,782 | <p>Forgive my ignorance. I have a brain fart at the moment and unable to come up with a solution. Let's say I have a list of <code>[1, 1, 0, 0]</code>. I want to calculate all the four digits binary numbers that have exactly two 1s and two zeros, like:</p>
<pre><code>['0110', '0011', '0101', '1100', '1010', '1001']
</... | 2 | 2016-06-02T04:40:05Z | 37,583,203 | <p>Use <code>itertools.combinations()</code> to find all possible <em>positions</em> for your ones, then construct the numbers using those positions:</p>
<pre><code>def binary(length=4, ones=2):
result = []
for positions in combinations(range(length), ones):
result.append("".join("1" if _ in positions ... | 4 | 2016-06-02T05:17:15Z | [
"python",
"permutation"
] |
Find unique permutation of a list binary values without generating all possibilities | 37,582,782 | <p>Forgive my ignorance. I have a brain fart at the moment and unable to come up with a solution. Let's say I have a list of <code>[1, 1, 0, 0]</code>. I want to calculate all the four digits binary numbers that have exactly two 1s and two zeros, like:</p>
<pre><code>['0110', '0011', '0101', '1100', '1010', '1001']
</... | 2 | 2016-06-02T04:40:05Z | 37,584,849 | <p>This post is bit late. <br>
@Tim Pietzcker 's answer is excellent, but one inner loop inside append is very hard for me to digest;</p>
<p>so i write same in simple way and its around 4-7 times faster. </p>
<pre><code>def binary(length=4, ones=2):
result = []
rr = ['0'] * length ## initialize empty list wi... | 2 | 2016-06-02T07:04:39Z | [
"python",
"permutation"
] |
pandas - rank elements of dataframe | 37,582,904 | <pre><code>data = pandas.DataFrame(numpy.random.randn(4,3))
print data
Out[4]:
0 1 2
0 -1.122880 -2.662009 1.180418
1 -0.335768 0.162640 0.105928
2 -1.282813 0.049638 1.532208
3 -0.422884 -1.110049 0.031648
</code></pre>
<p>Working with a huge dataset and am trying to efficientl... | 0 | 2016-06-02T04:51:03Z | 37,583,149 | <p>Here is what you can do :</p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.randn(4,3))
>>> df
0 1 2
0 1.644294 1.476467 -0.137539
1 -0.44... | 1 | 2016-06-02T05:12:46Z | [
"python",
"numpy",
"pandas",
"dataframe",
"rank"
] |
pandas - rank elements of dataframe | 37,582,904 | <pre><code>data = pandas.DataFrame(numpy.random.randn(4,3))
print data
Out[4]:
0 1 2
0 -1.122880 -2.662009 1.180418
1 -0.335768 0.162640 0.105928
2 -1.282813 0.049638 1.532208
3 -0.422884 -1.110049 0.031648
</code></pre>
<p>Working with a huge dataset and am trying to efficientl... | 0 | 2016-06-02T04:51:03Z | 37,583,330 | <p><code>stack</code> your dataframe, then <code>sort_values</code> with <code>ascending=False</code>, then take <code>index.tolist()</code></p>
<pre><code>data.stack().sort_values(ascending=False).index.tolist()
</code></pre>
| 1 | 2016-06-02T05:26:03Z | [
"python",
"numpy",
"pandas",
"dataframe",
"rank"
] |
Use Python to invert and translate images | 37,583,041 | <p>I have written the following code to loop through all the images in a folder, create its negative and save it under a new similar name. </p>
<p>How can I do the same thing to translate them by 5 pixels to the right? </p>
<p>Code:</p>
<pre><code>from PIL import Image
import PIL.ImageOps
import glob
files = glob.... | -1 | 2016-06-02T05:02:49Z | 37,585,724 | <p>You could take the following approach. This creates a new image 5 pixels bigger and pastes your original image into the new image offset by 5 pixels:</p>
<pre><code>from PIL import Image
import PIL.ImageOps
import glob
shift = 5
files = glob.glob('path/*.JPG') # Use *.* if you're sure all are images
for f in file... | 1 | 2016-06-02T07:49:40Z | [
"python",
"image-processing"
] |
How to specify custom marker with py.test command line with sub-set of attributes? | 37,583,078 | <p>I'd like to define a custom marker (my_marker containing a bunch of attributes. While triggering the tests, how do I select/specify a set of tests with a specific attribute?</p>
<p>For e.g., consider the following:</p>
<pre><code>import pytest
@pytest.mark.my_marker(foo='bar')
def test_001():
passÂ
def test... | 0 | 2016-06-02T05:06:31Z | 37,608,052 | <p>I was able to get reasonably close with this:</p>
<h2>conftest.py</h2>
<pre><code>import ast
import pytest
def pytest_collection_modifyitems(session, config, items):
mymarkerFilter = config.option.markexpr
if not mymarkerFilter:
return
mymarkerFilter = ast.literal_eval(mymarkerFilter).get('my_... | 0 | 2016-06-03T07:07:26Z | [
"python",
"py.test"
] |
List of Dictionary Manipulation in python - TypeError: unhashable type: 'dict' | 37,583,117 | <p>I have a list of the folowing form: </p>
<pre><code>oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]
</code></pre>
<p>to be converted into </p>
<pre><code>final = [{'x':{'a':1,'b':2},'y':[2,3,2],'count':3},{'x... | 0 | 2016-06-02T05:10:11Z | 37,583,247 | <p>The set function can only handle <code>hashable</code> objects, like a string, number, tuple e.t.c</p>
<p>Data types like List, dict are unhashable types, and hence the set function cannot handle them.</p>
<p>For some more clarity:</p>
<p><a href="http://stackoverflow.com/questions/14535730/what-do-you-mean-by-ha... | 3 | 2016-06-02T05:20:37Z | [
"python"
] |
List of Dictionary Manipulation in python - TypeError: unhashable type: 'dict' | 37,583,117 | <p>I have a list of the folowing form: </p>
<pre><code>oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]
</code></pre>
<p>to be converted into </p>
<pre><code>final = [{'x':{'a':1,'b':2},'y':[2,3,2],'count':3},{'x... | 0 | 2016-06-02T05:10:11Z | 37,583,755 | <p>Set function of python does not allow dictionaries and you can not force it, try another method instead. (Take a closer look of the comment on the <strong>5th</strong> and <strong>6th</strong> line)</p>
<p>Try this code:</p>
<pre><code>oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'... | 1 | 2016-06-02T05:57:43Z | [
"python"
] |
List of Dictionary Manipulation in python - TypeError: unhashable type: 'dict' | 37,583,117 | <p>I have a list of the folowing form: </p>
<pre><code>oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]
</code></pre>
<p>to be converted into </p>
<pre><code>final = [{'x':{'a':1,'b':2},'y':[2,3,2],'count':3},{'x... | 0 | 2016-06-02T05:10:11Z | 37,587,934 | <p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> where keys are <a href="https://docs.python.org/2/library/stdtypes.html#frozenset" rel="nofollow"><code>frozenset</code></a> objects created from value of <code>x</code> in the... | 1 | 2016-06-02T09:32:44Z | [
"python"
] |
Django 1.9 with Python 3.4 with MySQL support (Fedora) | 37,583,257 | <p>The question is so simple:</p>
<p>How can I used MySQL database with Django 1.9 + Python 3.4 in Fedora? I'm actually using a <code>virtualenv</code> if that adds more info. </p>
<p>I tried installing <code>mysqlclient</code> but that didn't work. And I really don't know how to go about the <code>MySQL connector Py... | 0 | 2016-06-02T05:21:14Z | 37,583,522 | <p>For python2</p>
<p>Try this steps:</p>
<pre><code>yum install mysql mysql-server
chkconfig --levels 235 mysqld on
/etc/init.d/mysqld start
# Create your username and password in MySQL
# Create your db in MySQL
yum install MySQL-python
</code></pre>
<p>For python2 or python3:</p>
<pre><code>pip install mysqlclien... | 1 | 2016-06-02T05:40:43Z | [
"python",
"mysql",
"django",
"python-3.x"
] |
Django 1.9 with Python 3.4 with MySQL support (Fedora) | 37,583,257 | <p>The question is so simple:</p>
<p>How can I used MySQL database with Django 1.9 + Python 3.4 in Fedora? I'm actually using a <code>virtualenv</code> if that adds more info. </p>
<p>I tried installing <code>mysqlclient</code> but that didn't work. And I really don't know how to go about the <code>MySQL connector Py... | 0 | 2016-06-02T05:21:14Z | 37,597,790 | <p>The documentation for <a href="https://github.com/PyMySQL/mysqlclient-python" rel="nofollow">mysqlclient</a> says: </p>
<p><strong>Prerequisites:</strong>
You may need to install the Python and MySQL development headers and libraries like so:</p>
<pre><code>sudo dnf install python-devel mysql-devel # Red Hat / Ce... | 0 | 2016-06-02T16:52:43Z | [
"python",
"mysql",
"django",
"python-3.x"
] |
scikit-learn cross validation custom splits for time series data | 37,583,263 | <p>I'd like to use scikit-learn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html" rel="nofollow">GridSearchCV</a> to determine some hyper parameters for a random forest model. My data is time dependent and looks something like</p>
<pre><code>import pandas as pd
train ... | 0 | 2016-06-02T05:21:39Z | 37,591,377 | <p>You just have to pass an iterable with the splits to GridSearchCV. This split should have the following format:</p>
<pre><code>[
(split1_train_idxs, split1_test_idxs),
(split2_train_idxs, split2_test_idxs),
(split3_train_idxs, split3_test_idxs),
...
]
</code></pre>
<p>To get the idxs you can do something like ... | 2 | 2016-06-02T12:04:20Z | [
"python",
"machine-learning",
"scikit-learn"
] |
How to pass the content of list one element at a time to a method? | 37,583,272 | <p>I have a libnmap scanner script which basically works by collecting all the EIP from AWS and scanning them one by one, the function which collects all EIP looks like :</p>
<pre><code>def gather_public_ip():
ACCESS_KEY = config.get('aws','access_key')
SECRET_KEY = config.get('aws','secret_key')
regions =... | 0 | 2016-06-02T05:22:20Z | 37,587,504 | <p>The way you pass in the arguments looks good. However, you don't have any code that actually uses the result.</p>
<p>Try changing <code>Scanner.run</code> like this:</p>
<pre><code>class Scanner(object):
...
def run(self, targets="" ,options="-Pn"):
#start a new nmap scan on localhost with some spe... | 1 | 2016-06-02T09:14:27Z | [
"python",
"list",
"nmap"
] |
YML ERROR IndentationError: expected an indented block in ansible | 37,583,285 | <p>I am getting the indentationError: expected an indented block when i try to run the ansiple playbook.I have validate in <a href="https://yaml-online-parser.appspot.com/" rel="nofollow">https://yaml-online-parser.appspot.com/</a>.</p>
<p>The similar yml is working for other servers</p>
<h2>Working</h2>
<pre><code>... | 0 | 2016-06-02T05:22:59Z | 37,587,576 | <p><strong>Hint</strong> (maybe reporting artefact): The non working has a space (in the question at least) before the initial <code>---</code></p>
<p>A (unified) diff with the leading space in non-working version removed):</p>
<pre><code>$ diff -u so_ansible_{not,''}working.yml
--- so_ansible_notworking.yml 2016-... | 0 | 2016-06-02T09:17:35Z | [
"python",
"ansible",
"ansible-playbook"
] |
SyntaxException in python method. Unsure why | 37,583,302 | <p>Can anyone explain why I get the following syntax error when running the <code>setup.py install</code>:</p>
<p><strong>Exception</strong></p>
<pre><code>SyntaxError: ('invalid syntax', ('build/bdist.linux-x86_64/egg/cardstream/payment.py', 46, 15, ' for key, value in parse_qs(query).items()\n'))
</code>... | 0 | 2016-06-02T05:24:24Z | 37,584,449 | <p>It doesn't like you splitting your dictionary comprehension on separate lines.</p>
<p>Just put it on a single line:</p>
<pre><code>return {
key: value if len(value) > 1 else value[0] for key, value in parse_qs(query).items()
}
</code></pre>
<p>or if you absolutely have to split use line continuation charac... | 0 | 2016-06-02T06:39:43Z | [
"python"
] |
SyntaxException in python method. Unsure why | 37,583,302 | <p>Can anyone explain why I get the following syntax error when running the <code>setup.py install</code>:</p>
<p><strong>Exception</strong></p>
<pre><code>SyntaxError: ('invalid syntax', ('build/bdist.linux-x86_64/egg/cardstream/payment.py', 46, 15, ' for key, value in parse_qs(query).items()\n'))
</code>... | 0 | 2016-06-02T05:24:24Z | 37,584,603 | <p>Just convert the dict comprehension to the equivalent <code>dict()</code> constructor call:</p>
<pre><code>return dict((
(key, value if len(value) > 1 else value[0])
for key, value in parse_qs(query).items()
))
</code></pre>
| 1 | 2016-06-02T06:48:43Z | [
"python"
] |
How to check whether ManytoMany has values before saving Model? | 37,583,355 | <p>Let's say I have two classes/models: <code>Hand</code> and <code>Finger</code>. Imagine that the fingerprint is a TextField and a Hand has an unknown number of Fingers, in the <code>models.py</code>:</p>
<pre><code>from django.db import models
class Hand(models.Model):
smoothness = models.IntegerField(default=... | 1 | 2016-06-02T05:27:58Z | 37,583,840 | <p><a href="https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/" rel="nofollow">This</a> is django documentation about working with ManyToMany fields. And <a href="https://docs.djangoproject.com/en/1.10/ref/signals/#django.db.models.signals.m2m_changed" rel="nofollow">this</a> documentation for m2m_c... | 1 | 2016-06-02T06:03:07Z | [
"python",
"django",
"orm",
"many-to-many"
] |
How to check whether ManytoMany has values before saving Model? | 37,583,355 | <p>Let's say I have two classes/models: <code>Hand</code> and <code>Finger</code>. Imagine that the fingerprint is a TextField and a Hand has an unknown number of Fingers, in the <code>models.py</code>:</p>
<pre><code>from django.db import models
class Hand(models.Model):
smoothness = models.IntegerField(default=... | 1 | 2016-06-02T05:27:58Z | 37,584,325 | <p>I'm not sure if you can do it <code>before</code> your object get saved. And I don't think this is the right way. I believe what you need to do is to listen for a <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#m2m-changed" rel="nofollow"><code>m2m_changed</code></a> signal and update your hand.</p>
<pr... | 1 | 2016-06-02T06:33:08Z | [
"python",
"django",
"orm",
"many-to-many"
] |
How to check whether ManytoMany has values before saving Model? | 37,583,355 | <p>Let's say I have two classes/models: <code>Hand</code> and <code>Finger</code>. Imagine that the fingerprint is a TextField and a Hand has an unknown number of Fingers, in the <code>models.py</code>:</p>
<pre><code>from django.db import models
class Hand(models.Model):
smoothness = models.IntegerField(default=... | 1 | 2016-06-02T05:27:58Z | 37,590,629 | <p>You may use <code>hand.fingers.count()</code> in order to know the number of fingers of your object.</p>
| 0 | 2016-06-02T11:32:36Z | [
"python",
"django",
"orm",
"many-to-many"
] |
How Can I Write Scripy To See Url Website? | 37,583,460 | <p>In Title I Said My Opinion I Wanna See URL After This (?)
For example: this site WWW.name.com has many name after this(?) like these php?id=
php?cat=
php?page=
Search in URL and show all things after question mark
By python3 please </p>
| -2 | 2016-06-02T05:37:13Z | 37,583,656 | <p>Here try this code:</p>
<pre><code>from urlparse import urlparse
rurl = urlparse('http://name.com/data.php?id=5')
query = rurl.query
print query
</code></pre>
<p>The code above will print the query string which is "id=5"<br></p>
| 0 | 2016-06-02T05:51:26Z | [
"python"
] |
TypeError: 'NoneType' | 37,583,561 | <p>Alright so I came across this ridiculous error in my code and none of the other stackoverflow errors seem to help. I'm in need of help with figuring out what's wrong with this code especially in the <code>def makePoem()</code> section.</p>
<pre><code>import random
noun = ["fossil" , "horse" , "aardvark" , "chef" ,... | -5 | 2016-06-02T05:44:12Z | 37,583,615 | <p>You're not returning <code>selection</code>, you're printing it instead. Replace <code>print(selection)</code> with <code>return selection</code>.</p>
| 1 | 2016-06-02T05:48:37Z | [
"python",
"python-3.x"
] |
Why does my POST requests on flask-restless==1.0.0b1 result in ERROR:400 MissingData | 37,583,609 | <p>I have the following code:</p>
<pre><code>import requests
data = {u"username":u"cryarchy", u"password":u"Pass1234", u"email":u"email@domain.com"}
url = "http://localhost:5000/api/account"
headers = {"Content-Type":"application/vnd.api+json", "Accept":"application/vnd.api+json"}
import json
r = requests.post(url, da... | 0 | 2016-06-02T05:47:45Z | 37,584,482 | <p>Noticed my mistake after a revisit to <a href="https://flask-restless.readthedocs.io/en/1.0.0b1/creating.html" rel="nofollow">https://flask-restless.readthedocs.io/en/1.0.0b1/creating.html</a>. The post request data format is what I'd got wrong. It should be:</p>
<pre><code>data = {'data': {'attributes': {u'usernam... | 0 | 2016-06-02T06:41:34Z | [
"python",
"flask-restless"
] |
How to correctly setup a path relative to running script also in tests? | 37,583,625 | <p>In order to set some paths to access subdirectories of my app (like <code>locale/</code>), I use this in a <code>settings.py</code>:</p>
<pre><code>__process_name = os.path.basename(sys.argv[0])
__abspath = os.path.abspath(sys.argv[0])
__l1 = len(__process_name)
__l2 = len(__abspath)
rootdir = __abspath[:__l2-__l1]... | 3 | 2016-06-02T05:49:12Z | 37,584,848 | <p>So the usual thing to do is <code>os.path.dirname(os.path.abspath(__file__))</code>.</p>
<p><code>__file__</code> is the path to the current module, <code>os.path.abspath</code> makes sure it's absolute, and <code>os.path.dirname</code> gives you the directory part of it.</p>
<p>If you have a module as part of a p... | 5 | 2016-06-02T07:04:32Z | [
"python",
"python-3.x",
"testing",
"relative-path",
"py.test"
] |
Getting system check errors | 37,583,630 | <p>I am trying to set a local development environment for a very complex web application. There is no proper documentation for setting up the environment, so it's been two days I am resolving errors by myself. After resolving all the errors, I am getting system check errors mentioned below and I don't understand what t... | 0 | 2016-06-02T05:49:27Z | 37,583,951 | <p>The class <code>credits.admin.creditshistoryAdmin</code> has an attribute <code>readonly_fields</code>.</p>
<p>It's a list of fields that are shown as read-only in the admin (see docs on <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields" rel="nofollow"... | 2 | 2016-06-02T06:11:07Z | [
"python",
"django",
"django-models",
"django-1.7"
] |
How to save changes to a python object? | 37,583,675 | <p>I have a Python dictionary of objects from a class that I have created in one file. It is of the form <code>{string : object}</code>, with several key, value pairs.</p>
<p>My goal is to do something in a method in a separate file that changes an attribute of certain objects in the dictionary and to save those chang... | 0 | 2016-06-02T05:52:46Z | 37,584,638 | <p>From the <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle documentation</a>:</p>
<blockquote>
<p>Note that none of the classâs code or data is pickled</p>
</blockquote>
<p>See <a href="https://docs.python.org/3/library/pickle.html#pickling-class-instances" rel="nofollow">pickling c... | 0 | 2016-06-02T06:51:12Z | [
"python",
"object",
"dictionary",
"pickle",
"savechanges"
] |
Struggling with Python Regex for a very specific array | 37,583,880 | <p>I'm trying to make a regex method (if you can find an easier method, please tell)</p>
<p>For example: I need the lines that are marked with "!" at the end</p>
<pre><code>[ExpertSingle]
{
192 = N 0 0
384 = N 0 0
576 = N 0 0
768 = N 0 0
960 = N 0 0
}
</code></pre>
<p><strong>Edit</strong>: replaced with actual data... | -3 | 2016-06-02T06:05:30Z | 37,583,938 | <p>You could just find the lines that with one or more numbers</p>
<pre><code>import re
inputStr = """[ExpertSingle]
{
192 = N 0 0
270 = N 1 0
270 = N 2 0
360 = N 0 0
}"""
goodLines = re.findall(r"\d+.+", inputStr)
print(goodLines)
</code></pre>
<p>This outputs: <code>['192 = N 0 0', '270 = N 1 0', '270 = N 2 0', '3... | 1 | 2016-06-02T06:10:25Z | [
"python",
"regex",
"python-2.7"
] |
How to find a particular key in list of dictionary objects in python | 37,583,888 | <p>i have query.oderby which is a list of dict objects.</p>
<pre><code>[{'name': 'asc'}, {'user_id': 'desc'}]
</code></pre>
<p>I check if the list has user_id with the following</p>
<pre><code>for query in query.orderby:
if query.keys().__contains__('user_id'):
if query['user_id'] == 'desc':
... | 0 | 2016-06-02T06:06:04Z | 37,583,964 | <p>You can do this :</p>
<pre><code>>>> ar = [{'name': 'asc'}, {'user_id': 'desc'}]
>>> any('user_id' in elt for elt in ar)
True
</code></pre>
<p>You can find more informations regarding <code>any()</code> <a href="https://docs.python.org/3.5/library/functions.html#any" rel="nofollow">here</a>.</p>
... | 2 | 2016-06-02T06:12:09Z | [
"python",
"list",
"dictionary"
] |
How to find a particular key in list of dictionary objects in python | 37,583,888 | <p>i have query.oderby which is a list of dict objects.</p>
<pre><code>[{'name': 'asc'}, {'user_id': 'desc'}]
</code></pre>
<p>I check if the list has user_id with the following</p>
<pre><code>for query in query.orderby:
if query.keys().__contains__('user_id'):
if query['user_id'] == 'desc':
... | 0 | 2016-06-02T06:06:04Z | 37,584,331 | <p>without for loop..</p>
<pre><code>any(map((lambda x: True if 'user_id' in x.keys() else False ), ar ))
</code></pre>
| 0 | 2016-06-02T06:33:28Z | [
"python",
"list",
"dictionary"
] |
How to find a particular key in list of dictionary objects in python | 37,583,888 | <p>i have query.oderby which is a list of dict objects.</p>
<pre><code>[{'name': 'asc'}, {'user_id': 'desc'}]
</code></pre>
<p>I check if the list has user_id with the following</p>
<pre><code>for query in query.orderby:
if query.keys().__contains__('user_id'):
if query['user_id'] == 'desc':
... | 0 | 2016-06-02T06:06:04Z | 37,584,345 | <p>You may use something like this if u want ur code to look simple.</p>
<pre><code>l = [{'name': 'asc'}, {'user_id': 'desc'}]
for query in l:
if (query.has_key('user_id')):
print "Key Found"
</code></pre>
| 0 | 2016-06-02T06:34:46Z | [
"python",
"list",
"dictionary"
] |
$project does not return the specified fields | 37,584,053 | <p>My document structure</p>
<p><a href="http://i.stack.imgur.com/CTUtX.png" rel="nofollow"><img src="http://i.stack.imgur.com/CTUtX.png" alt="enter image description here"></a></p>
<p>Here is what i am running ....</p>
<pre><code>query = self._database.suiteruns.aggregate([
{
"$project": {
"... | 1 | 2016-06-02T06:17:01Z | 37,584,619 | <p>You can try following way:-</p>
<pre><code>self._database.suiteruns.aggregate(
[
{$match : {"user": user_id}},
{ $group : {
"_id" : "$name",
"result": { $push: "$$ROOT" },
"count":
{
"$sum": "$name"
}
}
}
]... | 0 | 2016-06-02T06:49:45Z | [
"python",
"mongodb",
"mongodb-query",
"aggregate"
] |
Convert a standard python key value dictionary list to pyspark data frame | 37,584,077 | <p>Consider i have a list of python dictionary key value pairs , where key correspond to column name of a table, so for below list how to convert it into a pyspark dataframe with two cols arg1 arg2?</p>
<pre><code> [{"arg1": "", "arg2": ""},{"arg1": "", "arg2": ""},{"arg1": "", "arg2": ""}]
</code></pre>
<p>How can i... | 0 | 2016-06-02T06:17:50Z | 37,584,531 | <p>Old way:</p>
<pre><code>sc.parallelize([{"arg1": "", "arg2": ""},{"arg1": "", "arg2": ""},{"arg1": "", "arg2": ""}]).toDF()
</code></pre>
<p>New way:</p>
<pre><code>from pyspark.sql import Row
from collections import OrderedDict
def convert_to_row(d: dict) -> Row:
return Row(**OrderedDict(sorted(d.items()... | 5 | 2016-06-02T06:44:36Z | [
"python",
"dictionary",
"apache-spark",
"pyspark"
] |
Opencv: ValueError | 37,584,260 | <p>I have detected contours and stored them in cnts and i am accessing them one by one, c_list is the list of contours which are of interest to me.
I want to check if the contour i am accessing now is already been accessed before or not by using this code:</p>
<pre><code>if not (np.all(cnts[c] in c_list)):
while... | 0 | 2016-06-02T06:30:00Z | 37,678,747 | <p>Your issue is not really related to OpenCV, it comes from numpy.</p>
<p>Consider the following examples:</p>
<pre><code>>>> import numpy as np
>>> [1,3] in [[1,3],[4,5]]
True
>>> np.array([1,3]) in [[1,3],[4,5]]
Traceback (most recent call last):
File "<stdin>", line 1, in <m... | 2 | 2016-06-07T11:57:52Z | [
"python",
"python-2.7",
"opencv",
"numpy",
"opencv-contour"
] |
need help in python list | 37,584,368 | <p>I am implementing a linked list in python. However my insert operation is giving the error below. Can any one help in fixing this ? My list will have head as the first node. Subsequent nodes will be appended in insert operation. </p>
<p>output:</p>
<pre><code>10
Traceback (most recent call last):
File "z.py", li... | 0 | 2016-06-02T06:35:59Z | 37,584,412 | <p>On the line:</p>
<pre><code>current = current.get_nextnode
</code></pre>
<p>You're missing parenthesis meaning "call that function", here your're just binding the function to the <code>current</code> variable, leading obviously to the next <code>'function' object has no attribute 'get_data'</code>.</p>
| 0 | 2016-06-02T06:38:14Z | [
"python",
"data-structures",
"hyperlink",
"linked-list"
] |
Sending argument in reverse_lazy django - Python | 37,584,406 | <p>I am using reverse_lazy as following</p>
<pre><code>def index:
if firstTimeLogin == 0:
response = HttpResponseRedirect(reverse_lazy('abc', args={'cid': 0}))
else:
response = HttpResponseRedirect(reverse_lazy('abc', args={'cid': 1}))
</code></pre>
<p>abc view</p>
<pre><code>def abc(reques... | 0 | 2016-06-02T06:37:58Z | 37,584,488 | <p>You have two urls that have the same name, and take in the same parameters (same regex).</p>
<p>You can't combine these two to have the view take in both, thats not how django works.</p>
<p>You either have to</p>
<ul>
<li>Make a url that takes in two parameters</li>
<li>Make separate views</li>
</ul>
<p>But eith... | 2 | 2016-06-02T06:41:49Z | [
"python",
"django",
"django-views"
] |
Sending argument in reverse_lazy django - Python | 37,584,406 | <p>I am using reverse_lazy as following</p>
<pre><code>def index:
if firstTimeLogin == 0:
response = HttpResponseRedirect(reverse_lazy('abc', args={'cid': 0}))
else:
response = HttpResponseRedirect(reverse_lazy('abc', args={'cid': 1}))
</code></pre>
<p>abc view</p>
<pre><code>def abc(reques... | 0 | 2016-06-02T06:37:58Z | 37,584,820 | <p>Replace <code>args</code> with <code>kwargs</code> in parameters of <code>reverse_lazy</code> function:</p>
<pre><code>response = HttpResponseRedirect(reverse_lazy('abcfirst', kwargs={'cid': 1}))
</code></pre>
| 0 | 2016-06-02T07:02:53Z | [
"python",
"django",
"django-views"
] |
Regular expression substitution in Python | 37,584,492 | <p>I have a string</p>
<p><code>line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"</code></p>
<p>From this I want to remove all instances of <code>"(as...)"</code> using some regular expression. I want the output to look like</p>
<p><code>line = "haha avsrv arv afneoifew"</code></p>
<p>I tried:</p>
<pre><co... | 4 | 2016-06-02T06:42:09Z | 37,584,662 | <p>To get <a href="https://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy" rel="nofollow">non-greedy behaviour</a>, you have to use <code>*?</code> instead of <code>*</code>, ie <code>re.sub(r'\(+as .*?\) ','',line)</code>. To get the desired string, you also have to add a space, ie <code>re.sub(r'\(+as .*... | 3 | 2016-06-02T06:52:44Z | [
"python",
"regex",
"python-3.x"
] |
Regular expression substitution in Python | 37,584,492 | <p>I have a string</p>
<p><code>line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"</code></p>
<p>From this I want to remove all instances of <code>"(as...)"</code> using some regular expression. I want the output to look like</p>
<p><code>line = "haha avsrv arv afneoifew"</code></p>
<p>I tried:</p>
<pre><co... | 4 | 2016-06-02T06:42:09Z | 37,584,663 | <p>try:</p>
<pre><code>re.sub(r'\(as[^\)]*\)', '', line)
</code></pre>
| 1 | 2016-06-02T06:52:45Z | [
"python",
"regex",
"python-3.x"
] |
Regular expression substitution in Python | 37,584,492 | <p>I have a string</p>
<p><code>line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"</code></p>
<p>From this I want to remove all instances of <code>"(as...)"</code> using some regular expression. I want the output to look like</p>
<p><code>line = "haha avsrv arv afneoifew"</code></p>
<p>I tried:</p>
<pre><co... | 4 | 2016-06-02T06:42:09Z | 37,584,665 | <p>The problem is that your regexp matches this whole group : <code>(as jfeoiwf) avsrv arv (as qwefo)</code>, hence your result.</p>
<p>You can use :</p>
<pre><code>>>> import re
>>> line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"
>>> line = re.sub(r'\(+as [a-zA-Z]*\)','',line)
&g... | 2 | 2016-06-02T06:52:52Z | [
"python",
"regex",
"python-3.x"
] |
Regular expression substitution in Python | 37,584,492 | <p>I have a string</p>
<p><code>line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"</code></p>
<p>From this I want to remove all instances of <code>"(as...)"</code> using some regular expression. I want the output to look like</p>
<p><code>line = "haha avsrv arv afneoifew"</code></p>
<p>I tried:</p>
<pre><co... | 4 | 2016-06-02T06:42:09Z | 37,584,709 | <p>You were very close. You need to use lazy quantifier '?' after .*. In default it will try to capture biggest group it possibly can. With lazy quantifier it'll actually try to match smallest possible groups.</p>
<pre><code>line = re.sub(r'\(+as .*?\) ','',line)
</code></pre>
| 2 | 2016-06-02T06:55:23Z | [
"python",
"regex",
"python-3.x"
] |
Regular expression substitution in Python | 37,584,492 | <p>I have a string</p>
<p><code>line = "haha (as jfeoiwf) avsrv arv (as qwefo) afneoifew"</code></p>
<p>From this I want to remove all instances of <code>"(as...)"</code> using some regular expression. I want the output to look like</p>
<p><code>line = "haha avsrv arv afneoifew"</code></p>
<p>I tried:</p>
<pre><co... | 4 | 2016-06-02T06:42:09Z | 37,584,745 | <p>Try:</p>
<pre><code>re.sub(u".\(as \w+\).", ' ',line)
</code></pre>
| 2 | 2016-06-02T06:57:37Z | [
"python",
"regex",
"python-3.x"
] |
Dict merge in a dict comprehension | 37,584,544 | <p>In python 3.5, we can merge dicts by using double-splat unpacking</p>
<pre><code>>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
</code></pre>
<p>Cool. It doesn't seem to generalise to dynamic use cases, though:</p>
<pre><code>>&... | 4 | 2016-06-02T06:45:19Z | 37,584,733 | <p>To me, the obvious way is:</p>
<pre><code>d_out = {}
for d in ds:
d_out.update(d)
</code></pre>
<p>This is quick and probably quite performant. I don't know that I can speak for the python developers, but I don't know that your expected version is more easy to read. For example, your comprehension looks more... | 3 | 2016-06-02T06:57:05Z | [
"python",
"dictionary",
"syntax-error",
"python-3.5",
"dict-comprehension"
] |
Dict merge in a dict comprehension | 37,584,544 | <p>In python 3.5, we can merge dicts by using double-splat unpacking</p>
<pre><code>>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
</code></pre>
<p>Cool. It doesn't seem to generalise to dynamic use cases, though:</p>
<pre><code>>&... | 4 | 2016-06-02T06:45:19Z | 37,585,628 | <p>It's not exactly an answer to your question but I'd consider using <a href="https://docs.python.org/3.5/library/collections.html#collections.ChainMap" rel="nofollow"><code>ChainMap</code></a> to be an idiomatic and elegant way to do what you propose (merging dictionaries in-line):</p>
<pre><code>>>> d1 = {... | 4 | 2016-06-02T07:44:49Z | [
"python",
"dictionary",
"syntax-error",
"python-3.5",
"dict-comprehension"
] |
How to create a record in a model while creating a record in another model in odoo | 37,584,589 | <p>In my custom application i want to create automatically a record in my custom model while i create a sale order.</p>
<pre><code> class custom_sale_order(models.Model):
_inherit='sale.order'
time1 = fields.Date('TIme1')
time2 = fields.Date('TIme2')
class demo(models.Model):
... | 0 | 2016-06-02T06:48:01Z | 37,590,838 | <p>You need to override the <code>create</code> method of the <code>sale.order</code> class and inside this method you can create a record in the demo model and access to <code>values</code> of the current model. </p>
<p>For example:</p>
<pre><code>class custom_sale_order(models.Model):
_inherit='sale.order'
... | 1 | 2016-06-02T11:41:02Z | [
"python",
"odoo-8"
] |
get contents of a cell Python | 37,584,622 | <p>I am trying to get the contents of a cell from a csv file with a Python code.
What is wrong with my code? Can you please help me?</p>
<pre><code>import csv
file = csv.reader(open('C:\Users\bbb222\PycharmProjects\scivalCSVs\g.csv'))
InstName = file.cell(0, 1)
print(InstName)
</code></pre>
| -1 | 2016-06-02T06:50:07Z | 37,584,792 | <p><code>cell</code> is not a proper attribute for a <code>csv.reader</code> object. If you want to access data by indexes, you can do the following :</p>
<pre><code>>>> import csv
>>> file = csv.reader(open('C:\Users\bbb222\PycharmProjects\scivalCSVs\g.csv'))
>>> ar = list(data)
>>>... | 0 | 2016-06-02T07:01:06Z | [
"python",
"csv",
"cell"
] |
SSL connection to Redshift using Psycopg2 | 37,584,629 | <p>I am trying to connect to a AWS Redshift server via SSL. I am using psycopg2 library in python to establish the connection and used <code>sslmode='require'</code> as a parameter in the connect line. Unfortunately i got this error:</p>
<pre><code>sslmode value "require" invalid when SSL support is not compiled in
</... | 1 | 2016-06-02T06:50:36Z | 37,611,435 | <p>Is your cluster enabled for SSL connections? Your URL itself will have the SSL info. and you can use the same in your code.</p>
| 0 | 2016-06-03T10:04:14Z | [
"python",
"ssl",
"ssl-certificate",
"amazon-redshift",
"psycopg2"
] |
SSL connection to Redshift using Psycopg2 | 37,584,629 | <p>I am trying to connect to a AWS Redshift server via SSL. I am using psycopg2 library in python to establish the connection and used <code>sslmode='require'</code> as a parameter in the connect line. Unfortunately i got this error:</p>
<pre><code>sslmode value "require" invalid when SSL support is not compiled in
</... | 1 | 2016-06-02T06:50:36Z | 39,082,080 | <p>This worked for me: <a href="http://stackoverflow.com/a/36489939/101266">http://stackoverflow.com/a/36489939/101266</a></p>
<blockquote>
<p>had this same error, which turned out to be because I was using the Anaconda version of psycopg2. To fix it, I had adapt VictorF's solution from here and run:</p>
</blockquot... | 0 | 2016-08-22T14:25:43Z | [
"python",
"ssl",
"ssl-certificate",
"amazon-redshift",
"psycopg2"
] |
Mechanize Selecting a Form and entering Text | 37,584,728 | <p>I am trying to automatically input text on a webpage and parse the resulting page in Python. After some research here I found this piece of code which should help me with that:</p>
<pre><code>from mechanize import Browser
br = Browser()
br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]
br.op... | 0 | 2016-06-02T06:56:47Z | 37,585,736 | <p><strong>Selenium with PhantomJS webdriver</strong> can help you do that, enter the text in the selected text box using <strong>findelement with help of xpath</strong> and click the Get button.
It seems like the text that we enter, the websites gives out suggestions and only for those words that are relevant/exist in... | 0 | 2016-06-02T07:50:14Z | [
"python",
"mechanize"
] |
dict pop does not free the memory | 37,584,921 | <p>Looks like garbage collector does not collect the values <code>pop</code>'d from the <code>dict()</code> in python 2.7 (did not try on python 3). Here is the example:</p>
<pre><code>a = dict()
# fill the memory (dict)
for i in xrange(0, 9999999):
a[i] = i
# Memory usage is about 600 MB
# try to free the memor... | 2 | 2016-06-02T07:08:03Z | 37,585,457 | <p>There is no memory leak issue, since the memory is freed, when the dictionary isn't used any more. Dictionaries use internal tables to store the entries. These tables are not freed when using <code>pop</code>, because every key is mapped to a hash modulo size of the internal table. So the last existing key could lie... | 4 | 2016-06-02T07:35:05Z | [
"python",
"dictionary",
"memory",
"memory-management",
"memory-leaks"
] |
Python Robot Invalid Return From Keyword usage | 37,584,942 | <p>I am trying to execute following code in Robot and getting below error.
I am having hard time figuring out whats wrong</p>
<pre><code>${job_id}= Run Keyword And Return If "${cur_build}" != "<my_Build>" perform software upgrade ${wd} <device_name> <my_build>
</code></pre>
<p>Belo... | 0 | 2016-06-02T07:09:03Z | 37,719,129 | <p>Please let me know if below code serves your purpose</p>
<pre><code>*** Variables ***
@{list1} @{EMPTY}
@{list2} This is list list1
*** Test Cases ***
Conditional Test Case1
${flag}= Set Variable If @{list1}!=@{EMPTY} ${true} ${false}
${rc}= Run Keyword If ${fla... | 0 | 2016-06-09T07:11:38Z | [
"python",
"robotframework"
] |
pandas groupby object index turns into FUBAR | 37,585,000 | <p>I have a pandas where my groupby operation turns the index into mush. I need the dates as my index, sorted within each ticker-group</p>
<p>To illustrate. Setup pandas like so:</p>
<pre><code>import pandas as pd
from StringIO import StringIO
text = """Date Ticker Open High Low Adj_Close ... | -3 | 2016-06-02T07:12:00Z | 37,587,192 | <p>The groupby function automatically sets the column you've grouped on as index. To avoid that pass the option: <code>as_index = False</code> in your groupby:</p>
<pre><code>df_test = df.groupby('Ticker', as_index = False).head(7).reset_index().set_index('Date')
</code></pre>
| 0 | 2016-06-02T09:00:52Z | [
"python",
"pandas",
"indexing",
"group-by"
] |
pandas groupby object index turns into FUBAR | 37,585,000 | <p>I have a pandas where my groupby operation turns the index into mush. I need the dates as my index, sorted within each ticker-group</p>
<p>To illustrate. Setup pandas like so:</p>
<pre><code>import pandas as pd
from StringIO import StringIO
text = """Date Ticker Open High Low Adj_Close ... | -3 | 2016-06-02T07:12:00Z | 37,590,580 | <p>The <code>diff</code> method of <code>GroupBy</code> objects keeps the dates as index:</p>
<pre><code># sort if needed (use 'mergesort' algorithm to preserve date order)
df = df.sort().sort_values('Ticker', kind='mergesort')
df['Difference'] = df.groupby('Ticker')['Adj_Close'].diff()
</code></pre>
<p>Note: if the... | 0 | 2016-06-02T11:30:14Z | [
"python",
"pandas",
"indexing",
"group-by"
] |
pandas groupby object index turns into FUBAR | 37,585,000 | <p>I have a pandas where my groupby operation turns the index into mush. I need the dates as my index, sorted within each ticker-group</p>
<p>To illustrate. Setup pandas like so:</p>
<pre><code>import pandas as pd
from StringIO import StringIO
text = """Date Ticker Open High Low Adj_Close ... | -3 | 2016-06-02T07:12:00Z | 37,704,635 | <p>OK finally I found a solution. This line was my secret sauce</p>
<pre><code>df = df.reset_index(level=0, drop=True)
</code></pre>
<p>This question helped me get the index back to how I wanted it. <a href="http://stackoverflow.com/questions/20703599/how-to-get-rows-in-pandas-data-frame-with-maximal-values-in-a-colu... | 1 | 2016-06-08T13:57:43Z | [
"python",
"pandas",
"indexing",
"group-by"
] |
I need to get tuples of x,y coordinates from a file and add it to a list | 37,585,038 | <p>So my txt file looks like this:</p>
<pre><code>68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12
</code></pre>
<p>I need to read these files and then put it into a list of x and y coordinates tuples.</p>
<p>My output should be </p>
<pre><code>[(68, 125), (113, 69), (65, 86), (108, 149), (152, 5... | 0 | 2016-06-02T07:13:56Z | 37,585,156 | <p>Here are 3 and 2 line answers:</p>
<pre><code>with open("my_txt_file") as f:
lines = f.readlines()
result = [tuple(int(s) for s in line.strip().split(",")) for line in lines]
</code></pre>
<p>better, as Ilja Everilä pointed out, "open file as iterator":</p>
<pre><code>with open("my_txt_file") as f:
result = ... | 2 | 2016-06-02T07:19:44Z | [
"python",
"list",
"file",
"python-3.x",
"tuples"
] |
I need to get tuples of x,y coordinates from a file and add it to a list | 37,585,038 | <p>So my txt file looks like this:</p>
<pre><code>68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12
</code></pre>
<p>I need to read these files and then put it into a list of x and y coordinates tuples.</p>
<p>My output should be </p>
<pre><code>[(68, 125), (113, 69), (65, 86), (108, 149), (152, 5... | 0 | 2016-06-02T07:13:56Z | 37,585,332 | <p>Read all the content on the basis of new line from file.
Strip the newlines from each string.
Then convert each string into tuple by splitting on comma.
Below is the code witha text file input having content as you have asked and result as you expected.</p>
<pre><code>import sys
def test(filename):
f = open(fil... | 2 | 2016-06-02T07:29:02Z | [
"python",
"list",
"file",
"python-3.x",
"tuples"
] |
I need to get tuples of x,y coordinates from a file and add it to a list | 37,585,038 | <p>So my txt file looks like this:</p>
<pre><code>68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12
</code></pre>
<p>I need to read these files and then put it into a list of x and y coordinates tuples.</p>
<p>My output should be </p>
<pre><code>[(68, 125), (113, 69), (65, 86), (108, 149), (152, 5... | 0 | 2016-06-02T07:13:56Z | 37,585,504 | <p>As your file contains comma separated integer values, you could use the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow"><code>csv</code></a> module to handle it:</p>
<pre><code>import csv
with open(filename, newline='') as f:
reader = csv.reader(f)
numbers = [tuple(map(int, row)) for ro... | 1 | 2016-06-02T07:37:10Z | [
"python",
"list",
"file",
"python-3.x",
"tuples"
] |
Multiple Python Scripts on single multi-core machine | 37,585,045 | <p>I have a python script that has a high runtime (4 days when tested a single script on single virtual-core machine) which works on some list of files based on its input arguments that we provide.</p>
<p>The list of arguments that I wanted to test is very long and running each of them sequentially is not feasible due... | 0 | 2016-06-02T07:14:02Z | 37,585,183 | <p>I would suggest first trying to describe and understand more about your program and its performance:</p>
<p>You can start with Python line profiler, it is used to see how fast and how often each line of code is running in your script.</p>
<pre><code>pip install line_profiler
</code></pre>
<p>Once you time it, you... | 0 | 2016-06-02T07:21:09Z | [
"python",
"multicore"
] |
Unable to view files in a browser with python http server | 37,585,147 | <p>I am creating a python httpserver for a folder on remote machine using command : </p>
<pre><code>python -m SimpleHTTPServer 9999
</code></pre>
<p>But I am unable to view a file in the browser using this. As soon as click on the link the file gets downloaded. Is there a way to create a server so that i can view the... | 1 | 2016-06-02T07:19:06Z | 37,585,373 | <p>Serving files like <code>foo.sh</code> should work fine using the <code>SimpleHTTPServer</code>. Using <code>curl</code> as the client, I get a HTTP response like this:</p>
<pre><code>$ curl -v http://localhost:9999/so.sh
* Hostname was NOT found in DNS cache
* Trying 127.0.0.1...
* Connected to localhost (127.0... | 0 | 2016-06-02T07:31:05Z | [
"python",
"browser",
"httpserver"
] |
Unable to view files in a browser with python http server | 37,585,147 | <p>I am creating a python httpserver for a folder on remote machine using command : </p>
<pre><code>python -m SimpleHTTPServer 9999
</code></pre>
<p>But I am unable to view a file in the browser using this. As soon as click on the link the file gets downloaded. Is there a way to create a server so that i can view the... | 1 | 2016-06-02T07:19:06Z | 37,587,216 | <p>To make the browser open files inline instead of downloading them, you have to senue the files with the appropriate http <code>Content</code> headers.</p>
<p>This can be done by subclassing the default <code>SimpleHTTPRequestHandler</code> with a custom one. </p>
<p>This is how it can be done using python 3. You h... | 0 | 2016-06-02T09:01:31Z | [
"python",
"browser",
"httpserver"
] |
openpyxl generates broken workbook | 37,585,163 | <p>I am using openpyxl (2.3.5).
When I create a new workbook and open it with Microsoft Excel, it pops up an error saying: </p>
<blockquote>
<p>"We found a problem with some content in 'pourquoi.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes"</p>
</blo... | 0 | 2016-06-02T07:20:07Z | 37,597,568 | <p>Unfortunately, these error messages are often not very helpful. Which version of Excel are you using? It's worth noting that <em>Excel 2007</em> is no longer supported.</p>
<p>Bugs should be reported using the <a href="https://bitbucket.org/openpyxl/openpyxl/issues" rel="nofollow">bug tracker</a></p>
<p>For more i... | 0 | 2016-06-02T16:40:36Z | [
"python",
"excel",
"xlsx",
"openpyxl"
] |
Spark set more node worker instances in nodes with larger memory | 37,585,176 | <p>In my Spark (1.6.1) cluster some nodes have more physical memory than others. However in <code>executor.memory</code> I have to put a fix value that applies equally to each node and hence to each node's worker. </p>
<p>Some nodes have twice as much memory but cannot use it all. A work around to utilize <em>all</em>... | 0 | 2016-06-02T07:20:37Z | 37,586,719 | <p>I think you're trying to do something which is not feasible or at least it's not the way you should think. When you create a Spark application, you create executors, which are your workers and are basically JVMs. They are independent from the number and the size of your worker nodes. E.g. if you ask 3 executors with... | 1 | 2016-06-02T08:39:03Z | [
"python",
"scala",
"apache-spark"
] |
How to slice a 3d ndarray with a index vector | 37,585,241 | <p>Considering a 3d numpy array:</p>
<pre><code>ax1, ax2, ax3 = 3, 3, 2
arr = np.asarray(range(ax1*ax2*ax3)).reshape([ax1, ax2, ax3])
arr: [[[0, 1], [2, 3], [4, 5]],
[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]]
</code></pre>
<p>and a index vector <code>idx = [0, 1, 2]</code>.</p>
<p>I want... | 1 | 2016-06-02T07:24:10Z | 37,595,646 | <p>Here's a vectorized approach assuming <code>arr</code> and <code>idx</code> as NumPy arrays -</p>
<pre><code>np.split(arr[np.arange(arr.shape[0]) <= idx[:,None]],(idx+1).cumsum())[:-1]
</code></pre>
<p>Sample run to verify results -</p>
<pre><code>In [5]: arr
Out[5]:
array([[[ 0, 1],
[ 2, 3],
... | 1 | 2016-06-02T15:08:30Z | [
"python",
"numpy",
"multidimensional-array"
] |
How to slice a 3d ndarray with a index vector | 37,585,241 | <p>Considering a 3d numpy array:</p>
<pre><code>ax1, ax2, ax3 = 3, 3, 2
arr = np.asarray(range(ax1*ax2*ax3)).reshape([ax1, ax2, ax3])
arr: [[[0, 1], [2, 3], [4, 5]],
[[6, 7], [8, 9], [10, 11]],
[[12, 13], [14, 15], [16, 17]]]
</code></pre>
<p>and a index vector <code>idx = [0, 1, 2]</code>.</p>
<p>I want... | 1 | 2016-06-02T07:24:10Z | 37,595,704 | <p>Your problem is that the resulting values are <em>not</em> rectangular: you cannot represent that properly as an array.</p>
<p>If you're fine with having the <em>values</em> only in a different format, you can get what you need through a <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-... | 2 | 2016-06-02T15:10:49Z | [
"python",
"numpy",
"multidimensional-array"
] |
Error retrieving data from hive using python | 37,585,293 | <p>I use python to connect hive & retrieve the data into pandas, but its giving an error:</p>
<pre><code>pyhive.exc.OperationalError: TExecuteStatementResp
</code></pre>
<p>my code:</p>
<pre><code># -*- coding: utf-8 -*-
from pyhive import hive
from impala.util import as_pandas
from string import Template
confi... | 0 | 2016-06-02T07:27:09Z | 37,611,153 | <p>update hql data</p>
<pre><code>hql = """
SELECT
keywords,
count(keywords)
FROM
table
WHERE
eventname = 'xxx' AND
cdate >= '$start_date' AND
cdate <= '$end_date'
GROUP BY
keywords
LIMIT 100
"""
</code></pre>
<p>add limit run success</p>
<p>Can provide train of thought?</p>
<p>Tha... | 0 | 2016-06-03T09:50:35Z | [
"python",
"hadoop",
"pandas",
"hive"
] |
Plotting 3D Polygons in Python 3 | 37,585,340 | <p>In my quest to somehow get 3D polygons to actually plot, I came across the following script (EDIT: modified slightly): <a href="http://stackoverflow.com/questions/4622057/plotting-3d-polygons-in-python-matplotlib">Plotting 3D Polygons in python-matplotlib</a></p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
f... | 1 | 2016-06-02T07:29:23Z | 37,585,763 | <p>You have to use <strong>Poly3DCollection</strong> instead of PolyCollection:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x,y,z... | 1 | 2016-06-02T07:52:13Z | [
"python",
"matplotlib",
"plot"
] |
Plotting 3D Polygons in Python 3 | 37,585,340 | <p>In my quest to somehow get 3D polygons to actually plot, I came across the following script (EDIT: modified slightly): <a href="http://stackoverflow.com/questions/4622057/plotting-3d-polygons-in-python-matplotlib">Plotting 3D Polygons in python-matplotlib</a></p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
f... | 1 | 2016-06-02T07:29:23Z | 37,832,779 | <p>I've had a similar problem with the zipping. I support the thesis it is a python 2.x vs 3.x thing.</p>
<p>However, I've found somewhere that apparently works:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.fi... | 2 | 2016-06-15T10:27:09Z | [
"python",
"matplotlib",
"plot"
] |
how to get the SUM from any Start date and any End date. (file.txt) Python | 37,585,548 | <p>Hello I have been stuck on this for weeks. if i have a list saved in file.dat file or text file which contains the following information below: </p>
<pre><code>1-3-2014,job4,51081.5,10
10-10-2014,job3,1010.1,35
4-2-2015,job2,61824.7,35
2-4-2016,Job1,222.1,12
</code></pre>
<p>(separated by commas because they be un... | -1 | 2016-06-02T07:40:08Z | 37,586,502 | <p>Hi you can use following code,</p>
<pre><code>from datetime import datetime
def calculate(file_name, s_date, e_date):
dollar = 0
_format = '%d-%m-%Y'
start_date = datetime.strptime(s_date, _format)
end_date = datetime.strptime(e_date, _format)
with open(file_name) as f:
lines = f.readli... | 1 | 2016-06-02T08:28:45Z | [
"python"
] |
How to import Scipy and Numpy in Python? | 37,585,601 | <p>I am very new to Python and want to add Numpy and Scipy module. I think my question is very simple for you. I am using Python 3.06a.1 version. I think I already installed something called Anaconda that contains those library. When I type import scipy I get the following message:</p>
<pre><code>import scipy
Tracebac... | 0 | 2016-06-02T07:43:14Z | 37,585,755 | <p>You shouldn't have problem with scipy and numpy if you installed Anaconda. What I'm advising you may sound stupid, but I'm sure it has a good chance to solve your problem.</p>
<p>Relaunch Anaconda, reboot your computer, reinstall Anaconda.</p>
<p>Edit : also watch out to use "scipy" and not "spicy" as I just witne... | 1 | 2016-06-02T07:51:34Z | [
"python",
"numpy",
"scipy"
] |
How to import Scipy and Numpy in Python? | 37,585,601 | <p>I am very new to Python and want to add Numpy and Scipy module. I think my question is very simple for you. I am using Python 3.06a.1 version. I think I already installed something called Anaconda that contains those library. When I type import scipy I get the following message:</p>
<pre><code>import scipy
Tracebac... | 0 | 2016-06-02T07:43:14Z | 37,586,325 | <p>if you are using anaconda, try installing scipy using anaconda:</p>
<pre><code>conda install scipy
</code></pre>
| 0 | 2016-06-02T08:19:29Z | [
"python",
"numpy",
"scipy"
] |
Reuse an exisiting numpy array or create a new one? | 37,585,698 | <p>In iterative algorithms, it is common to use large numpy arrays many times. I want to fill value into a big existing numpy array, but I found create a new array is even faster. </p>
<pre><code>>>>import numpy as np
>>>a=np.arange(10000)
>>>b=a.copy()
>>>%timeit b=a+a # Every ti... | 1 | 2016-06-02T07:48:41Z | 37,591,415 | <ul>
<li><code>np.copyto(b,a);b+=a</code> is faster, but not the fastest way.</li>
<li><code>np.add(a,a,b)</code> is the best choice for now, 100000 loops, best of 3: 8.66 µs per loop. </li>
</ul>
<p>Maybe <code>b[:]=a+a</code> will genarate some temporary calculation spaces? I don't konw. But use "+=, -=, *=, add" t... | 2 | 2016-06-02T12:06:05Z | [
"python",
"performance",
"numpy"
] |
Python & Matplotlib: How to pass dict to functions? | 37,585,863 | <p>I'm making a custom plot configure function <code>plt_configure</code>, so I can combine label, legend and other plot options with one command.</p>
<p>For legend, I want to do something like:</p>
<pre><code>plt_configure(legend={loc: 'best'})
# => plt.legend(loc='best')
plt_configure(legend=True)
# => plt.le... | 1 | 2016-06-02T07:57:00Z | 37,586,081 | <p>Use <code>None</code> instead in your keyword argument since legend would otherwise be a <code>dict</code> object (not a boolean instance) and then check if the legend is a dictionary instance:</p>
<pre><code>def plt_configure(xlabel='', ylabel='', legend=None):
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if ... | 2 | 2016-06-02T08:06:42Z | [
"python",
"matplotlib"
] |
Python & Matplotlib: How to pass dict to functions? | 37,585,863 | <p>I'm making a custom plot configure function <code>plt_configure</code>, so I can combine label, legend and other plot options with one command.</p>
<p>For legend, I want to do something like:</p>
<pre><code>plt_configure(legend={loc: 'best'})
# => plt.legend(loc='best')
plt_configure(legend=True)
# => plt.le... | 1 | 2016-06-02T07:57:00Z | 37,586,208 | <p>An empty dictionary will evaluate to <code>False</code>, a not empty one will evaluate to <code>True</code>. Therefore you can use <code>if legend</code> no matter if <code>legend</code> is a dict or a boolean.</p>
<p>Then you can test if <code>legend</code> is a dict, and pass it to <code>plt.legend</code></p>
<p... | 4 | 2016-06-02T08:13:14Z | [
"python",
"matplotlib"
] |
Python & Matplotlib: How to pass dict to functions? | 37,585,863 | <p>I'm making a custom plot configure function <code>plt_configure</code>, so I can combine label, legend and other plot options with one command.</p>
<p>For legend, I want to do something like:</p>
<pre><code>plt_configure(legend={loc: 'best'})
# => plt.legend(loc='best')
plt_configure(legend=True)
# => plt.le... | 1 | 2016-06-02T07:57:00Z | 37,586,278 | <p>Moses Koledoye's answer is fine, however if you want to pass additional options to legend, you'd want to pass them to your function, as well:</p>
<pre><code>def plt_configure(xlabel, ylabel, legend, *args, **kwargs):
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if legend:
plt.legend(*args, **kwargs)
</... | 2 | 2016-06-02T08:17:09Z | [
"python",
"matplotlib"
] |
Python & Matplotlib: How to pass dict to functions? | 37,585,863 | <p>I'm making a custom plot configure function <code>plt_configure</code>, so I can combine label, legend and other plot options with one command.</p>
<p>For legend, I want to do something like:</p>
<pre><code>plt_configure(legend={loc: 'best'})
# => plt.legend(loc='best')
plt_configure(legend=True)
# => plt.le... | 1 | 2016-06-02T07:57:00Z | 37,586,764 | <p>I join to early answers, but I think, checking for None have to be in function and you <code>legend</code> dict have to use as <code>kwargs</code>:</p>
<pre><code>def plt_configure(xlabel='', ylabel='', legend=None):
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if not(legend is None): plt.legend(**legend)
...... | 1 | 2016-06-02T08:40:53Z | [
"python",
"matplotlib"
] |
TypeError: 'Section' object is not callable | 37,585,903 | <p>I'm trying to testing python program. I don't have enough knowledge about python module. When I run the program I got such as error <strong>server=myconf.getoption('server') TypeError: 'Section' object is not callable</strong> and this is piece of program I'm trying to run</p>
<pre><code>import sys
from zabbix_api ... | -2 | 2016-06-02T07:58:41Z | 37,586,712 | <p>A sample of - "how to use simpleconfigparser" </p>
<p>from <a href="https://pypi.python.org/pypi/SimpleConfigParser/" rel="nofollow">https://pypi.python.org/pypi/SimpleConfigParser/</a></p>
<p>if your ini file includes the following:</p>
<pre><code>[app]
debug = yes
</code></pre>
<p>You can use it using:</p>
<p... | 0 | 2016-06-02T08:38:52Z | [
"python"
] |
Apache Spark 2.0 Model Persistence | 37,585,950 | <p>According to this post: <a href="https://databricks.com/blog/2016/05/31/apache-spark-2-0-preview-machine-learning-model-persistence.html" rel="nofollow">https://databricks.com/blog/2016/05/31/apache-spark-2-0-preview-machine-learning-model-persistence.html</a>
Spark 2.0 includes a language independent model serializ... | 0 | 2016-06-02T08:00:35Z | 37,586,551 | <p>It depends on the model. They are saying that it is language independent (and not Spark independent), but there are some things to consider:</p>
<ol>
<li>If the model is rather large (like ALS, for instance), you will have many issues using a non distributed program to load it.</li>
<li>You should implement by your... | 1 | 2016-06-02T08:31:01Z | [
"python",
"apache-spark"
] |
How to prevent writing into txt file the same words using open(text.txt,a)? | 37,586,001 | <p>I have a question regarding appending to text file. I have written a script and what this script does is that it will read the URL in JSON format and extract the list of titles and write into the file "WordsInCategory.text".</p>
<p>As this code will be used in a loop thus I used f1 = open('WordsInCategory.text', '... | 1 | 2016-06-02T08:03:02Z | 37,586,112 | <p>You can track the titles you added.</p>
<pre><code>titles = []
</code></pre>
<p>and then add each title to the list when writing</p>
<pre><code>if title not in titles:
# write to file
titles += title
</code></pre>
| 1 | 2016-06-02T08:08:25Z | [
"python",
"python-2.7"
] |
How to prevent writing into txt file the same words using open(text.txt,a)? | 37,586,001 | <p>I have a question regarding appending to text file. I have written a script and what this script does is that it will read the URL in JSON format and extract the list of titles and write into the file "WordsInCategory.text".</p>
<p>As this code will be used in a loop thus I used f1 = open('WordsInCategory.text', '... | 1 | 2016-06-02T08:03:02Z | 37,586,230 | <p>I would suggest saving every title in an array, before writing to a file (and hence writing only once to the given file). You can modify your code this way :</p>
<pre><code>import urllib2
import json
data = []
f1 = open('WordsInCategory.text', 'w')
url1 ='https://en.wikipedia.org/w/api.php?\
action=query&for... | 3 | 2016-06-02T08:14:25Z | [
"python",
"python-2.7"
] |
Is it possible to request other api in a Tastypie resource? | 37,586,002 | <p>I'm using Django 1.9.6 + Tastypie to implement RESTFUL api, there is an api that need to fetch data from api whitch is on another server, I don't know how to do it.</p>
<p>All the example I'd found is like this:</p>
<pre><code>from tastypie.resources import ModelResource
from services.models import Product
from ta... | 1 | 2016-06-02T08:03:02Z | 37,664,469 | <p>Maybe what you are looking for are <a href="http://django-tastypie.readthedocs.io/en/latest/cookbook.html#nested-resources" rel="nofollow">nested Resources</a> or just the related resource fields, for instance:</p>
<pre><code>from tastypie.resources import ModelResource
from tastypie import fields
from services.mod... | 0 | 2016-06-06T18:30:40Z | [
"python",
"django",
"rest",
"tastypie"
] |
Is it possible to request other api in a Tastypie resource? | 37,586,002 | <p>I'm using Django 1.9.6 + Tastypie to implement RESTFUL api, there is an api that need to fetch data from api whitch is on another server, I don't know how to do it.</p>
<p>All the example I'd found is like this:</p>
<pre><code>from tastypie.resources import ModelResource
from services.models import Product
from ta... | 1 | 2016-06-02T08:03:02Z | 37,729,305 | <p>Your question is not stupid it's quite common thing to deal with.</p>
<p>But first of all some theory about it:</p>
<p>You say you have existing RESTful API representing probably separate and independent service. Each API server which provides one kind of service should be as much independent as possible. The fron... | 0 | 2016-06-09T14:49:57Z | [
"python",
"django",
"rest",
"tastypie"
] |
Can I copy folder into dmg file using some python (or Java) API? | 37,586,023 | <p>I need to update a <code>.dmg</code> (a.k.a. Apple disk image) file by adding a folder to it (it's an OSGI application and I want to add a few more bundles) but I would prefer a platform independent solution. My main code is written in Python but I am also comfortable with Java. Is it possible to to edit a <code>.dm... | 1 | 2016-06-02T08:04:02Z | 37,597,012 | <p>Creating .dmg images elsewhere than on a Mac is not as easy task at least not an easy task to do using free software. And with non-free, it is mostly for-Mac software. I have been there and decided this was a waste of time.</p>
<p>If you are on a mac, using <code>hdiutil</code> is the way to manipulate .dmg</p>
<p... | 0 | 2016-06-02T16:10:50Z | [
"java",
"python",
"dmg"
] |
Find lost cards (faster solution) | 37,586,034 | <p>We're given N (3 <= N <= 50000) cards with unique numbers from 1 to N.
We lost some 3 cards and our goal is to find them.</p>
<p><em>Input</em>: first line contains number of cards N.
Second line contains 3 numbers: sum of all left cards we have, sum of their squares and sum of their cubes.</p>
<p><em>Output... | 1 | 2016-06-02T08:04:43Z | 37,586,207 | <p>Surely there exists a faster approach!</p>
<p>For N=50,000 your brute-force function would have to make up to </p>
<pre><code>N * N * N = 125,000,000,000,000
</code></pre>
<p>iterations, so this is not an option.</p>
<p>Additionally, you should check for <code>num1 == num2</code> etc. to avoid duplicated numb... | 0 | 2016-06-02T08:13:11Z | [
"python",
"algorithm",
"optimization"
] |
Find lost cards (faster solution) | 37,586,034 | <p>We're given N (3 <= N <= 50000) cards with unique numbers from 1 to N.
We lost some 3 cards and our goal is to find them.</p>
<p><em>Input</em>: first line contains number of cards N.
Second line contains 3 numbers: sum of all left cards we have, sum of their squares and sum of their cubes.</p>
<p><em>Output... | 1 | 2016-06-02T08:04:43Z | 37,586,426 | <p>You can sort the list, and find the pairs such that <code>a[i+1] =/= a[i]+1</code>. For every such pair numbers <code>[a[i]+1;a[i+1])</code> are missing. This would give you O(n log n) running time.</p>
| 0 | 2016-06-02T08:25:02Z | [
"python",
"algorithm",
"optimization"
] |
Find lost cards (faster solution) | 37,586,034 | <p>We're given N (3 <= N <= 50000) cards with unique numbers from 1 to N.
We lost some 3 cards and our goal is to find them.</p>
<p><em>Input</em>: first line contains number of cards N.
Second line contains 3 numbers: sum of all left cards we have, sum of their squares and sum of their cubes.</p>
<p><em>Output... | 1 | 2016-06-02T08:04:43Z | 37,586,629 | <p>This can be simplified by mathematical approach. You are given 3 equations and have 3 unknowns. </p>
<pre><code>sum(1+2+..+N) - x1 - x2 - x3 = a
sum(1^2+2^2+..+N^2) - x1^2 - x2^2 - x3^3 = b
sum(1^3+2^3+..+N^3) - x1^3 - x2^3 - x3^3 = c
</code></pre>
<p>Obviously <code>sum(1..N)</code> is <code>1/2 *N(N+1)</cod... | 1 | 2016-06-02T08:35:00Z | [
"python",
"algorithm",
"optimization"
] |
Find lost cards (faster solution) | 37,586,034 | <p>We're given N (3 <= N <= 50000) cards with unique numbers from 1 to N.
We lost some 3 cards and our goal is to find them.</p>
<p><em>Input</em>: first line contains number of cards N.
Second line contains 3 numbers: sum of all left cards we have, sum of their squares and sum of their cubes.</p>
<p><em>Output... | 1 | 2016-06-02T08:04:43Z | 37,586,668 | <p>I can give you an idea, </p>
<p>let <code>sum1 = 1+2+3...n</code></p>
<p>let <code>sum2 = 1^2+2^2+3^2...n</code></p>
<p>and <code>p, q, r</code> is three numbers given by input consecutively.</p>
<p>We need to search <code>a, b, c</code>. Iterate <code>for c = 1 to N.</code></p>
<p>For each iteration, </p>
<p>... | 0 | 2016-06-02T08:37:05Z | [
"python",
"algorithm",
"optimization"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.