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 |
---|---|---|---|---|---|---|---|---|---|
pip install jupyter: "Unable to locate finder for 'pip._vendor.distlib'"
| 39,552,710 |
<p>I'm trying to install <code>jupyter</code> to use the IPython Notebook under Windows. However, if I run <code>pip install jupyter</code> I'm getting</p>
<pre><code> Using cached pyzmq-15.4.0.zip
Requirement already satisfied (use --upgrade to upgrade): wcwidth in c:\users\stefan\appdata\local\programs\python\python36\lib\site-packages (from prompt-toolkit<2.0.0,>=1.0.0->jupyter-console->jupyter)
Installing collected packages: nbformat, nbconvert, pyzmq, jupyter-client, tornado, ipykernel, notebook, widgetsnbextension, ipywidgets, qtconsole, jupyter-console, jupyter
Exception:
Traceback (most recent call last):
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\basecommand.py", line 215, in main
status = self.run(options, args)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files
maker.make_multiple(['%s = %s' % kv for kv in console.items()])
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple
filenames.extend(self.make(specification, options))
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make
self._make_script(entry, filenames, options=options)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script
self._write_script(scriptnames, shebang, script, filenames, ext)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script
launcher = self._get_launcher('t')
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher
result = finder(distlib_package).find(name).bytes
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder
raise DistlibException('Unable to locate finder for %r' % package)
pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib'
</code></pre>
<p>Any idea what the problem here is?</p>
| 0 |
2016-09-17T23:34:45Z
| 39,908,861 |
<p>Try uninstalling pip and installing get-pip.py. It appears to be a bug in the 3.6 version for Windows. <a href="https://github.com/pypa/pip/issues/3964" rel="nofollow">https://github.com/pypa/pip/issues/3964</a></p>
| 1 |
2016-10-07T03:22:56Z
|
[
"python",
"pip",
"jupyter"
] |
pip install jupyter: "Unable to locate finder for 'pip._vendor.distlib'"
| 39,552,710 |
<p>I'm trying to install <code>jupyter</code> to use the IPython Notebook under Windows. However, if I run <code>pip install jupyter</code> I'm getting</p>
<pre><code> Using cached pyzmq-15.4.0.zip
Requirement already satisfied (use --upgrade to upgrade): wcwidth in c:\users\stefan\appdata\local\programs\python\python36\lib\site-packages (from prompt-toolkit<2.0.0,>=1.0.0->jupyter-console->jupyter)
Installing collected packages: nbformat, nbconvert, pyzmq, jupyter-client, tornado, ipykernel, notebook, widgetsnbextension, ipywidgets, qtconsole, jupyter-console, jupyter
Exception:
Traceback (most recent call last):
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\basecommand.py", line 215, in main
status = self.run(options, args)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files
maker.make_multiple(['%s = %s' % kv for kv in console.items()])
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple
filenames.extend(self.make(specification, options))
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make
self._make_script(entry, filenames, options=options)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script
self._write_script(scriptnames, shebang, script, filenames, ext)
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script
launcher = self._get_launcher('t')
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher
result = finder(distlib_package).find(name).bytes
File "C:\Users\Stefan\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder
raise DistlibException('Unable to locate finder for %r' % package)
pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib'
</code></pre>
<p>Any idea what the problem here is?</p>
| 0 |
2016-09-17T23:34:45Z
| 40,142,402 |
<p>uninstall current pip by typing:</p>
<pre><code>python -m pip uninstall pip setuptools
</code></pre>
<p>download get-pip.py from <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a> and run it:</p>
<pre><code>python get-pip.py
</code></pre>
| 1 |
2016-10-19T22:15:41Z
|
[
"python",
"pip",
"jupyter"
] |
How to take input as operation
| 39,552,718 |
<p>I'm trying to make a calculator but little bit different.
I'm thinking if a get input as operation like:</p>
<pre><code>first_number = input('Type first number: ')
first_operation = input('Type your operation (+, -, *, /): ')
second_number = input('Type second number: ')
first_answer = input('Do you wanna stop here y/n: ')
if first_answer = "y":
print(int(first_number), str(first_operation), int(second_number))
</code></pre>
<p>At the moment, the program needs to make a problem with user's input. For example, if user types <code>3</code> for first number, <code>+</code> for first operation, <code>2</code> for second number. I can only write those inputs like <code>3 + 2</code>, but I want to solve after print answer.</p>
| -1 |
2016-09-17T23:36:04Z
| 39,552,865 |
<p>Grab the operations from the <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>operator</code></a> module and create a dictionary of the available operators:</p>
<pre><code>>>> from operator import add, sub, mul, truediv
>>> ops = {'+': add, '-': sub, '*': mul, '/': truediv}
</code></pre>
<p>After doing this you can use <code>first_operation</code> as the <code>key</code> on <code>ops</code>, get the corresponding function for the operation and supply <code>first_number</code> and <code>second_number</code> as its arguments:</p>
<pre><code>>>> first_number = int(input('Type first number: '))
>>> second_number = int(input('Type second number: '))
>>> first_operation = input('Type your operation (+, -, *, /): ')
</code></pre>
<p>Let's say we enter <code>5</code> and <code>10</code> and <code>+</code>, then:</p>
<pre><code>>>> print(ops[first_operation](first_number, second_number))
15
</code></pre>
<p>Note, the numbers are wrapped in <code>int</code> before supplying them to the operator since they behave differently when of type <code>str</code>.</p>
<p>As a simple alternative, you could use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>literal_eval</code></a> from the <a href="https://docs.python.org/3/library/ast.html#module-ast" rel="nofollow"><code>ast</code></a> module, supplying it an expression as input:</p>
<pre><code>>>> from ast import literal_eval
>>> first_number = input('Type first number: ')
>>> second_number = input('Type second number: ')
>>> first_operation = input('Type your operation (+, -, *, /): ')
</code></pre>
<p>Here you don't need to change anything to <code>int</code>, you just join all arguments and make a string of the overall expression and feed it to <code>literal_eval</code> for it to do its thing.</p>
<pre><code>>>> literal_eval(" ".join([first_number, first_operation, second_number]))
</code></pre>
<p>In essence your call will look like:</p>
<pre><code>>>> literal_eval('5 + 10')
</code></pre>
<p>With a result of 15, again.</p>
| 0 |
2016-09-18T00:02:15Z
|
[
"python",
"python-3.x"
] |
How to edit many objects at the same time in django?
| 39,552,720 |
<p>Well, usually, when I like edit one object I using instance and get_object_or_404, something like this:</p>
<pre><code>question = get_object_or_404(Question, id = id)
form = FormQuestion(request.POST, instance=question)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('/Something/')
else:
form = FormQuestion(instance = question)
return render(request, {'form':form}, 'Ask/question.html')
</code></pre>
<p>Using this code I can edit one object, the problem is: I need to list all questions and the fields will be editable, but I can't find a way to do this.</p>
<p>Someone has a method or a code who resolve my problem?</p>
| 0 |
2016-09-17T23:36:41Z
| 39,712,293 |
<p>First place, is much better you develop in CBV(Class Based Views), where you will do the view more easily.</p>
<p>I had a problem around your problem, follow how do it:
<a href="http://stackoverflow.com/questions/39534543/django-inlineformset-factory-how-to-edit">Django - inlineformset-factory (How to Edit)</a>
And you need formset-factory and/or inlineformset-factory.
And here: <a href="http://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_formsets.htm" rel="nofollow">http://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_formsets.htm</a>.</p>
<p><a href="https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-more-than-one-formset-in-a-view" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-more-than-one-formset-in-a-view</a></p>
<p>I hope I've helped</p>
| 0 |
2016-09-26T20:59:51Z
|
[
"python",
"django",
"edit"
] |
How to use python to interpret a url
| 39,552,767 |
<p>I'm writing code that is attempting to extract the text from the <a href="https://libraryofbabel.info" rel="nofollow">Library of Babel</a>.</p>
<p>They basically use a system of Hexes, Walls, Shelfs, Volumes and Pages to split up their library of randomly generated text files. Here is an example (<a href="https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1" rel="nofollow">https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1</a>)
Here we have Hex: 2, Wall: 1, Shelf: 2, Volume: 22, Page: 1.</p>
<p>I would ideally like to randomly generate a page across all these variables to extract text from, however I am not getting the output I would imagine. </p>
<p>Here is my code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
from urlparse import urlparse
import random
hex = str(random.randint(0, 6))
wall = str(random.randint(1, 4))
shelf = str(random.randint(1, 5))
vol = str(random.randint(1, 32))
page = str(random.randint(1, 410))
print("Fetching: " + " Hex: " + hex + ", Wall: " + wall + ", Shelf: " + shelf + ", Vol: " + vol + ", Page: " + page)
babel_url = str("https://libraryofbabel.info/browse.cgi?" + hex + "-w" + wall + "-s" + shelf + "-v" + vol + ":" + page)
r = requests.get(babel_url)
soup = BeautifulSoup(r.text)
print(soup.get_text())
</code></pre>
<p>My output would be identical to that if I changed the url to be <a href="https://libraryofbabel.info/browse.cgi" rel="nofollow">https://libraryofbabel.info/browse.cgi</a>. print(babel_url) shows me that the way I wrote the url is fine but something isn't interpreting what I have written in the way I want.</p>
<p>I've found that just pasting <a href="https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1" rel="nofollow">https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1</a> into chrome drops me at <a href="https://libraryofbabel.info/book.cgi" rel="nofollow">https://libraryofbabel.info/book.cgi</a>. But if I navigate to <a href="https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1" rel="nofollow">https://libraryofbabel.info/book.cgi?2-w1-s2-v22:1</a> (or any other page) I can move between pages at will.</p>
<p>The only thing I get in the output worth mentioning is:</p>
<blockquote>
<p>It appears your browser has javascript disabled. Follow this link to browse without javascript.</p>
</blockquote>
| 0 |
2016-09-17T23:44:55Z
| 39,552,868 |
<p>Put on you glasses :<br>
You are requesting <code>browse.cgi</code> instead of <code>book.cgi</code><br><br>
<a href="https://libraryofbabel.info/browse.cgi?2-w2-s1-v10:72" rel="nofollow">https://libraryofbabel.info/browse.cgi?2-w2-s1-v10:72</a><br>
instead of<br>
<a href="https://libraryofbabel.info/book.cgi?2-w2-s1-v10:72" rel="nofollow">https://libraryofbabel.info/book.cgi?2-w2-s1-v10:72</a></p>
| 3 |
2016-09-18T00:04:17Z
|
[
"python",
"beautifulsoup"
] |
Apply Numpy function over entire Dataframe
| 39,552,773 |
<p>I am applying this function over a dataframe <code>df1</code> such as the following:</p>
<pre><code> AA AB AC AD
2005-01-02 23:55:00 "EQUITY" "EQUITY" "EQUITY" "EQUITY"
2005-01-03 00:00:00 32.32 19.5299 32.32 31.0455
2005-01-04 00:00:00 31.9075 19.4487 31.9075 30.3755
2005-01-05 00:00:00 31.6151 19.5799 31.6151 29.971
2005-01-06 00:00:00 31.1426 19.7174 31.1426 29.9647
def func(x):
for index, price in x.iteritems():
x[index] = price / np.sum(x,axis=1)
return x[index]
df3=func(df1.ix[1:])
</code></pre>
<p>However, I only get a single column returned as opposed to 3</p>
<pre><code> 2005-01-03 0.955843
2005-01-04 0.955233
2005-01-05 0.955098
2005-01-06 0.955773
2005-01-07 0.955877
2005-01-10 0.95606
2005-01-11 0.95578
2005-01-12 0.955621
</code></pre>
<p>I am guessing I am missing something in the formula to make it apply to the entire dataframe. Also how could I return the first index that has strings in its row?</p>
| 0 |
2016-09-17T23:45:46Z
| 39,552,922 |
<p>You need to do it the following way :</p>
<pre><code>def func(row):
return row/np.sum(row)
df2 = pd.concat([df[:1], df[1:].apply(func, axis=1)], axis=0)
</code></pre>
<p>It has 2 steps :</p>
<ol>
<li><code>df[:1]</code> extracts the first row, which contains strings, while <code>df[1:]</code> represents the rest of the DataFrame. You concatenate them later on, which answers the second part of your question.</li>
<li>For operating over rows you should use <code>apply()</code> method.</li>
</ol>
| 2 |
2016-09-18T00:14:38Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
Override settings from another Django app
| 39,552,784 |
<p>How can I in my project settings.py override a setting from an apps settings.py?</p>
<p>I tried importing it like this:</p>
<pre><code>import app.settings
EXTENSIONS = {
'Folder': [''],
'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff', '.svg'],
}
</code></pre>
<p><strong>But I get an error:</strong></p>
<blockquote>
<p>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting
must not be empty.</p>
</blockquote>
<p>How can I override settings from another app?</p>
| 1 |
2016-09-17T23:47:14Z
| 39,553,591 |
<p>I think what you're looking for is:</p>
<pre><code>from app.settings import *
</code></pre>
<p>The goal is to import the settings into the module namespace.</p>
| -1 |
2016-09-18T02:52:56Z
|
[
"python",
"django"
] |
Override settings from another Django app
| 39,552,784 |
<p>How can I in my project settings.py override a setting from an apps settings.py?</p>
<p>I tried importing it like this:</p>
<pre><code>import app.settings
EXTENSIONS = {
'Folder': [''],
'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff', '.svg'],
}
</code></pre>
<p><strong>But I get an error:</strong></p>
<blockquote>
<p>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting
must not be empty.</p>
</blockquote>
<p>How can I override settings from another app?</p>
| 1 |
2016-09-17T23:47:14Z
| 39,560,722 |
<p>Your SECRET_KEY is empty or missing in settings.py file.</p>
<p>Add random generated SECRET_KEY to settings file.</p>
<p>For example:</p>
<pre><code># SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=6x$7smkllimrwa@j+d7(tr%i=3cax!bz+0vyje%$!gj+*dvd4'
</code></pre>
| 0 |
2016-09-18T17:38:55Z
|
[
"python",
"django"
] |
SQLAlchemy load_only on parent model
| 39,552,809 |
<p>When eager loading a child relationship, how can I only load few columns of the parent model:</p>
<p>This works if I only need <code>title</code> column of the <code>chapters</code> model:</p>
<pre><code>session.query(Book)\
.options(joinedload('chapters').load_only('title'))
</code></pre>
<p>But this throws an error:</p>
<pre><code>session.query(Book.author)\
.options(joinedload('chapters').load_only('title'))
</code></pre>
<blockquote>
<p>Query has only expression-based entities - can't find property named
'chapters'.</p>
</blockquote>
<p>In other words I want this SQL in ORM syntax:</p>
<pre><code>SELECT
books.author,
chapters.title,
FROM
books JOIN chapters ON book.id = chapters.book_id
</code></pre>
| 1 |
2016-09-17T23:52:30Z
| 39,553,869 |
<p>The error message says you're only selecting <code>Book.author</code>, instead of instances of <code>Book</code>. Where is <code>chapters</code> going to go if all it's returning is a list of strings (for <code>author</code>).</p>
<p>You can either do:</p>
<pre><code>session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters)
</code></pre>
<p>or</p>
<pre><code>session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))
</code></pre>
| 2 |
2016-09-18T03:45:41Z
|
[
"python",
"sql",
"orm",
"sqlalchemy"
] |
How to read a python tuple using PyYAML?
| 39,553,008 |
<p>I have the following YAML file named <code>input.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>cities:
1: [0,0]
2: [4,0]
3: [0,4]
4: [4,4]
5: [2,2]
6: [6,2]
highways:
- [1,2]
- [1,3]
- [1,5]
- [2,4]
- [3,4]
- [5,4]
start: 1
end: 4
</code></pre>
<p>I'm loading it using PyYAML and printing the result as follows:</p>
<pre class="lang-py prettyprint-override"><code>import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
print(data)
</code></pre>
<p>The result is the following data structure:</p>
<pre class="lang-py prettyprint-override"><code>{ 'cities': { 1: [0, 0]
, 2: [4, 0]
, 3: [0, 4]
, 4: [4, 4]
, 5: [2, 2]
, 6: [6, 2]
}
, 'highways': [ [1, 2]
, [1, 3]
, [1, 5]
, [2, 4]
, [3, 4]
, [5, 4]
]
, 'start': 1
, 'end': 4
}
</code></pre>
<p>As you can see, each city and highway is represented as a list. However, I want them to be represented as a tuple. Hence, I manually convert them into tuples using comprehensions:</p>
<pre class="lang-py prettyprint-override"><code>import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
data["cities"] = {k: tuple(v) for k, v in data["cities"].items()}
data["highways"] = [tuple(v) for v in data["highways"]]
print(data)
</code></pre>
<p>However, this seems like a hack. Is there some way to instruct PyYAML to directly read them as tuples instead of lists?</p>
| 1 |
2016-09-18T00:32:36Z
| 39,553,138 |
<p>I wouldn't call what you've done hacky for what you are trying to do. Your alternative approach from my understanding is to make use of python-specific tags in your YAML file so it is represented appropriately when loading the yaml file. However, this requires you modifying your yaml file which, if huge, is probably going to be pretty irritating and not ideal.</p>
<p>Look at the <a href="http://pyyaml.org/wiki/PythonTagScheme" rel="nofollow">PyYaml doc</a> that further illustrates this. Ultimately you want to place a <code>!!python/tuple</code> in front of your structure that you want to represented as such. To take your sample data, it would like: </p>
<p>YAML FILE:</p>
<pre><code>cities:
1: !!python/tuple [0,0]
2: !!python/tuple [4,0]
3: !!python/tuple [0,4]
4: !!python/tuple [4,4]
5: !!python/tuple [2,2]
6: !!python/tuple [6,2]
highways:
- !!python/tuple [1,2]
- !!python/tuple [1,3]
- !!python/tuple [1,5]
- !!python/tuple [2,4]
- !!python/tuple [3,4]
- !!python/tuple [5,4]
start: 1
end: 4
</code></pre>
<p>Sample code: </p>
<pre><code>import yaml
with open('y.yaml') as f:
d = yaml.load(f.read())
print(d)
</code></pre>
<p>Which will output: </p>
<pre><code>{'cities': {1: (0, 0), 2: (4, 0), 3: (0, 4), 4: (4, 4), 5: (2, 2), 6: (6, 2)}, 'start': 1, 'end': 4, 'highways': [(1, 2), (1, 3), (1, 5), (2, 4), (3, 4), (5, 4)]}
</code></pre>
| 2 |
2016-09-18T01:05:26Z
|
[
"python",
"yaml",
"pyyaml"
] |
How to read a python tuple using PyYAML?
| 39,553,008 |
<p>I have the following YAML file named <code>input.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>cities:
1: [0,0]
2: [4,0]
3: [0,4]
4: [4,4]
5: [2,2]
6: [6,2]
highways:
- [1,2]
- [1,3]
- [1,5]
- [2,4]
- [3,4]
- [5,4]
start: 1
end: 4
</code></pre>
<p>I'm loading it using PyYAML and printing the result as follows:</p>
<pre class="lang-py prettyprint-override"><code>import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
print(data)
</code></pre>
<p>The result is the following data structure:</p>
<pre class="lang-py prettyprint-override"><code>{ 'cities': { 1: [0, 0]
, 2: [4, 0]
, 3: [0, 4]
, 4: [4, 4]
, 5: [2, 2]
, 6: [6, 2]
}
, 'highways': [ [1, 2]
, [1, 3]
, [1, 5]
, [2, 4]
, [3, 4]
, [5, 4]
]
, 'start': 1
, 'end': 4
}
</code></pre>
<p>As you can see, each city and highway is represented as a list. However, I want them to be represented as a tuple. Hence, I manually convert them into tuples using comprehensions:</p>
<pre class="lang-py prettyprint-override"><code>import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
data["cities"] = {k: tuple(v) for k, v in data["cities"].items()}
data["highways"] = [tuple(v) for v in data["highways"]]
print(data)
</code></pre>
<p>However, this seems like a hack. Is there some way to instruct PyYAML to directly read them as tuples instead of lists?</p>
| 1 |
2016-09-18T00:32:36Z
| 39,554,610 |
<p>Depending on where your YAML input comes from your "hack" is a good solution, especially if you would use <code>yaml.safe_load()</code> instead of the unsafe <code>yaml.load()</code>. If only the "leaf" sequences in your YAML file need to be tuples you can do ¹:</p>
<pre><code>import pprint
import ruamel.yaml
from ruamel.yaml.constructor import SafeConstructor
def construct_yaml_tuple(self, node):
seq = self.construct_sequence(node)
# only make "leaf sequences" into tuples, you can add dict
# and other types as necessary
if seq and isinstance(seq[0], (list, tuple)):
return seq
return tuple(seq)
SafeConstructor.add_constructor(
u'tag:yaml.org,2002:seq',
construct_yaml_tuple)
with open('input.yaml') as fp:
data = ruamel.yaml.safe_load(fp)
pprint.pprint(data, width=24)
</code></pre>
<p>which prints:</p>
<pre><code>{'cities': {1: (0, 0),
2: (4, 0),
3: (0, 4),
4: (4, 4),
5: (2, 2),
6: (6, 2)},
'end': 4,
'highways': [(1, 2),
(1, 3),
(1, 5),
(2, 4),
(3, 4),
(5, 4)],
'start': 1}
</code></pre>
<p>if you then need to process more material where sequence need to be "normal" lists again, use:</p>
<pre><code>SafeConstructor.add_constructor(
u'tag:yaml.org,2002:seq',
SafeConstructor.construct_yaml_seq)
</code></pre>
<hr>
<p>¹ <sub>This was done using <a href="https://pypi.python.org/pypi/ruamel.yaml" rel="nofollow">ruamel.yaml</a> a YAML 1.2 parser, of which I am the author. You should be able to do same with the older PyYAML if you only ever need to support YAML 1.1 and/or cannot upgrade for some reason</sub></p>
| 1 |
2016-09-18T05:57:44Z
|
[
"python",
"yaml",
"pyyaml"
] |
giving index to QLineEdit
| 39,553,013 |
<p>i want to give index for QLineEdit's.</p>
<p>i have this code.</p>
<pre><code> from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
# main button
self.addButton = QtGui.QPushButton('button to add other widgets')
self.addButton.clicked.connect(self.addWidget)
self.savebutton = QtGui.QPushButton('Save')
# scroll area widget contents - layout
self.scrollLayout = QtGui.QFormLayout()
# scroll area widget contents
self.scrollWidget = QtGui.QWidget()
self.scrollWidget.setLayout(self.scrollLayout)
# scroll area
self.scrollArea = QtGui.QScrollArea()
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.scrollWidget)
# main layout
self.mainLayout = QtGui.QVBoxLayout()
# add all main to the main vLayout
self.mainLayout.addWidget(self.addButton)
self.mainLayout.addWidget(self.scrollArea)
self.mainLayout.addWidget(self.savebutton)
# central widget
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.mainLayout)
# set central widget
self.setCentralWidget(self.centralWidget)
def addWidget(self):
self.scrollLayout.addRow(Test())
class Test(QtGui.QWidget):
def __init__( self, parent=None):
super(Test, self).__init__(parent)
self.kod = QtGui.QLineEdit()
layout = QtGui.QHBoxLayout()
layout.addWidget(self.kod)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()
</code></pre>
<p>when i clicked save button, savebutton sends just last QLineEdit widget.
<a href="http://i.stack.imgur.com/mrwos.png" rel="nofollow">image is here</a></p>
<p>like in this photo, i want self.kod[0].text()="aaaa" self.kod<a href="http://i.stack.imgur.com/mrwos.png" rel="nofollow">1</a>="bbbb" self.kod[2]="cccc" and it just will go like this. kod[x] this x number will increase automatically, while i click add widgetbutton. or it can be like this: kod1,kod2,kod3, kodx. it doesnt matter, i want to just differ from eacht other and take text from them.</p>
| 0 |
2016-09-18T00:34:00Z
| 39,556,238 |
<p>You can set a list in Main class, like this ['aaa', 'bbb', 'ccc'],
and set a var = 0.</p>
<pre><code>class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
#
self.lineText = ['aaa', 'bbb', 'ccc']
self.var = 0
...
def addWidget(self):
self.scrollLayout.addRow(Test(self, self.var))
self.var += 1
</code></pre>
<p>Then give Test class a arg, </p>
<pre><code>class Test(QtGui.QWidget):
def __init__( self, parent=None, count):
super(Test, self).__init__(parent)
#
self.parent = parent
self.kod = QtGui.QLineEdit()
#
self.kod.setText(self.parent.lineText[count])
</code></pre>
<h2>---</h2>
<hr>
<pre><code>class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
self.kod = []
...
def addWidget(self):
temp = Test()
self.kod.append(temp)
self.scrollLayout.addRow(temp)
</code></pre>
<p>and print(self.kod)</p>
<pre><code>[<__main__.Test object at 0x00000000032EEC18>, <__main__.Test object at 0x00000000032EEDC8>, <__main__.Test object at 0x00000000032EEF78>]
</code></pre>
| 0 |
2016-09-18T09:42:29Z
|
[
"python",
"qt",
"pyqt",
"pyqt4"
] |
why two points can't show in the figure (matplotlib)?
| 39,553,030 |
<p>Figure1 show data points<a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow">1</a></p>
<p><a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow">1</a>:<a href="http://i.stack.imgur.com/j7b9r.png" rel="nofollow"><img src="http://i.stack.imgur.com/j7b9r.png" alt="enter image description here"></a></p>
<p>I drawed the figure by matplotlib in python, but the data points cannot be fully displayed. There are two points not displayed the lower-right corner of the figure.The two coordinates are (-0.6731984257692413, 6.0), (-0.7105983383119769, 7.0).I don't know why.Anyone could help?</p>
<pre><code>import matplotlib.pyplot as plt
theta = [0.8975979010256552, 2.6927937030769655, 0, -0.6731984257692413, 0.0, -1.7951958020513104, -0.8975979010256552, -1.7951958020513104, -2.6927937030769655, -0.5235987755982988, -0.59839860068377, -0.8975979010256552, -1.1967972013675403, 1.7951958020513104, -0.5609986881410344, -0.59839860068377, -0.6357985132265057, -0.7105983383119769]
r = [1.0, 0.5, 0, 6.0, 1.0, 1.5, 1.0, 1.0, 1.0, 4.5, 4.0, 4.0, 4.0, 0.5, 4.5, 4.5, 4.5, 7.0]
colors = [1.13290242331, 0.81108163706000003, 0, 0.94180655750400011, 0.90356396220000001, 0.946707749135, 1.09650064153, 1.2068422679700002, 1.1150923324999999, 2.4619798379700004, 0.83030335877799999, 0.87957520389799992, 0.872155341769, 0.92537488526299994, 2.70431872671, 1.10024483211, 0.89817718522000012, 1.1547139643100002]
plt.subplot(111,polar=True)
cc=plt.scatter(theta,r,c=colors,cmap=plt.cm.hsv)
cc.set_alpha(0.75)
plt.grid(color='y', alpha=0.8, linestyle='dashed', linewidth=1)
plt.colorbar()
plt.thetagrids([30])
plt.show()
</code></pre>
| 2 |
2016-09-18T00:38:40Z
| 39,554,821 |
<p>With the help of Andras Deak, I use <code>plt.ylim([0, max(r)+1])</code>to solve this problem.Thanks.</p>
| 0 |
2016-09-18T06:28:45Z
|
[
"python",
"matplotlib"
] |
I can load multiple stock tickers from yahoo finance, but I am having trouble adding new columns before it is saved to a csv
| 39,553,271 |
<p>The code below starts by uploading data from yahoo finance in pnls. It does this successufly. Then I have code where I want to add columns to the loaded data in pnls. This part is unsuccessful. Finally I want to save pnls to a csv file which it does successfully if the column changes are not in the code.</p>
<p>The question that I need answered is how do I successfully make multiple column changes before I save pnls to csv??</p>
<pre><code>from pandas_datareader import data as dreader
import pandas as pd
from datetime import datetime
import numpy as np
# Symbols is a list of all the ticker symbols that I am downloading from yahoo finance
symbols = ['tvix','pall','pplt','sivr','jju','nib','jo','jjc','bal','jjg','ld','cdw','gaz','jjn','pgm',
'sgg','jjt','grn','oil','gld','corn','soyb','weat','uhn','uga','bunl','jgbl','bndx','aunz',
'cemb','emhy','vwob','ald','udn','fxa','fxb']
#This gets the data from yahoo finance
pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols}
# These are the new columns that I want to add
pnls['PofChg'] = ((pnls.Close - pnls.Open) / (pnls.Open)) * 100
pnls['U_D_F'] = np.where(pnls.PofChg > 0 , 'Up', np.where(pnls.PofChg == 0, 'Flat', 'Down'));pnls
pnls['Up_Down'] = pnls.Close.diff()
pnls['Close%pd'] = pnls.Close.pct_change()*100
# This saves the current ticker to a csv file
for df_name in pnls:
pnls.get(df_name).to_csv("{}_data.csv".format(df_name), index=True, header=True)
</code></pre>
<p>This is the error that I get when I run the code</p>
<pre><code>Traceback (most recent call last):
File "YahooFinanceDataGetter.py", line 14, in <module>
pnls['PofChg'] = ((pnls.Close - pnls.Open) / (pnls.Open)) * 100
AttributeError: 'dict' object has no attribute 'Close'
Press any key to continue . . .
</code></pre>
| 1 |
2016-09-18T01:34:11Z
| 39,561,996 |
<p>The line</p>
<pre><code>pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols}
</code></pre>
<p>builds a python <code>dict</code> (using <a href="http://stackoverflow.com/questions/14507591/python-dictionary-comprehension">dictionary comprehension</a>). To check this, you can run the following:</p>
<pre><code>assert type(pnls) == dict
</code></pre>
<p>This is what the error message is telling you: <code>AttributeError: 'dict' object has no attribute 'Close'</code>.</p>
<p>The DataFrames are actually the values of the dictionary. To apply transformations to them, you can iterate over the <code>values()</code> of the dictionary:</p>
<pre><code>for df in pnls.values():
df = ((df.Close - df.Open) / (df.Open)) * 100
...
</code></pre>
| 1 |
2016-09-18T19:50:28Z
|
[
"python",
"csv",
"pandas",
"dataframe"
] |
Representing time sequence input/output in tensorflow
| 39,553,292 |
<p>I've been working through the TensorFlow documentation (still learning), and I can't figure out how to represent input/output sequence data. My inputs are a sequences of 20 8-entry vectors, making a 8x20xN matrix, where N is the number of instances. I'd like to eventually pass these through an LSTM for sequence to sequence learning. I know I need a 3D vector, but I'm unsure which dimensions are which. </p>
<p>RTFMs with pointers to the correct documentation greatly appreciated. I feel like this is obvious and I'm just missing it. </p>
| 0 |
2016-09-18T01:39:54Z
| 39,556,093 |
<p>As described in the excellent blog post by <a href="http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/" rel="nofollow">WildML</a>, the proper way is to save your example in a TFRecord using the formate <code>tf.SequenceExample()</code>. Using TFRecords for this provides the following advantages: </p>
<ul>
<li>You can split your data in to many files and load them each on a different GPU.</li>
<li>You can use Tensorflow utilities for loading the data (for example using <code>Queues</code> to load you data on demand.</li>
<li>Your model code will be separate from your dataset processing (this is a good habit to have).</li>
<li>You can bring new data to your model just by putting it into this format.</li>
</ul>
<p>TFRecords uses <code>protobuf</code> or protocol buffers as a way to format your data. The documentation of which can be found <a href="https://developers.google.com/protocol-buffers/" rel="nofollow">here</a>. The basic idea is you have a format for your data (in this case in the format of tf.SequenceExample) save it to a TFRecord and load it using the same data definition. Code for this pattern can be found at <a href="https://github.com/dennybritz/tf-rnn/blob/master/sequence_example.ipynb" rel="nofollow">this</a> ipython notebook.</p>
<p>As my answer is mostly summarizing the WildML blog post on this topic, I suggest you check that out, again found <a href="http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/" rel="nofollow">here</a>.</p>
| 1 |
2016-09-18T09:27:28Z
|
[
"python",
"tensorflow"
] |
sorting list of a sentence and number
| 39,553,334 |
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p>
<p>Let's say I have a list like this:
['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p>
<p>Is there a way to sort by the number after each sentence? </p>
<p>I am trying to learn this stuff on my own, so I tried stuff like:</p>
<pre><code>def sortMyList(string):
return len(string)-1
sortedList = sorted(MyList, key=sortMyList())
</code></pre>
<p>But of course it doesn't work becaue sortMyList expects one parameter.</p>
| 0 |
2016-09-18T01:52:13Z
| 39,553,358 |
<p>This worked for me:</p>
<pre><code>sorted(myList, key=lambda x: x[-1])
</code></pre>
<p>If you need to go into double digits:</p>
<pre><code>sorted(myList, key=lambda x: int(x.split(',')[1]))
</code></pre>
| 0 |
2016-09-18T01:58:36Z
|
[
"python",
"python-3.x"
] |
sorting list of a sentence and number
| 39,553,334 |
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p>
<p>Let's say I have a list like this:
['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p>
<p>Is there a way to sort by the number after each sentence? </p>
<p>I am trying to learn this stuff on my own, so I tried stuff like:</p>
<pre><code>def sortMyList(string):
return len(string)-1
sortedList = sorted(MyList, key=sortMyList())
</code></pre>
<p>But of course it doesn't work becaue sortMyList expects one parameter.</p>
| 0 |
2016-09-18T01:52:13Z
| 39,553,370 |
<p>You can do this</p>
<pre><code>>>> sorted(l, key=lambda x : int(x.split(',')[-1]))
['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']
>>>
</code></pre>
<p>This would also work if you happen to have numbers in your string that have more than one digit</p>
<pre><code>>>> l = ['Today is a good day,12', 'yesterday was a strange day,21', 'feeling hopeful,23']
>>> sorted(l, key=lambda x : int(x.split(',')[1]))
['Today is a good day,12', 'yesterday was a strange day,21', 'feeling hopeful,23'] # still works
>>> sorted(l, key=lambda x : x[-1])
['yesterday was a strange day,21', 'Today is a good day,12', 'feeling hopeful,23'] # doesn't work in this scenario
</code></pre>
| 2 |
2016-09-18T02:01:07Z
|
[
"python",
"python-3.x"
] |
sorting list of a sentence and number
| 39,553,334 |
<p>I have checked several of the answers on how to sort lists in python, but I can't figure this one out.</p>
<p>Let's say I have a list like this:
['Today is a good day,1', 'yesterday was a strange day,2', 'feeling hopeful,3']</p>
<p>Is there a way to sort by the number after each sentence? </p>
<p>I am trying to learn this stuff on my own, so I tried stuff like:</p>
<pre><code>def sortMyList(string):
return len(string)-1
sortedList = sorted(MyList, key=sortMyList())
</code></pre>
<p>But of course it doesn't work becaue sortMyList expects one parameter.</p>
| 0 |
2016-09-18T01:52:13Z
| 39,553,511 |
<p>Since no one has commented on your coding attempts so far:</p>
<pre><code>def sortMyList(string):
return len(string)-1
sortedList = sorted(MyList, key=sortMyList())
</code></pre>
<p>You are on your way, but there are a few issues. First, the <code>key</code> argument expects a function. That function should be <code>sortMyList</code>. <code>sortMyList()</code> would be the <em>result</em> of <em>calling</em> a function - and besides, your function has a parameter (as it should), so calling it with no arguments wouldn't work. Just refer to the function itself.</p>
<pre><code>sortedList = sorted(MyList, key=sortMyList)
</code></pre>
<p>Next, you need to tell <code>sorted</code> what is actually being compared when you compare two strings. <code>len(string)-1</code> gets the length of the string and subtracts one. This would have the effect of sorting the strings by their length, which isn't what you're looking for. You want the <em>character</em> in the string <em>at that index</em>, so <code>sorted</code> will look at all those characters to form a basis for comparison.</p>
<pre><code>def sortMyList(string):
return string[len(string)-1]
</code></pre>
<p>Next, you can use a negative index instead of calculating the length of the string, to directly get the last character:</p>
<pre><code>def sortMyList(string):
return string[-1]
</code></pre>
<p>Next, we'd like to handle multi-digit numbers. It looks like there's a comma right before the number, so we'll split on that, starting from the right (in case the sentence itself has a comma). We only need the first split, so we'll specify a <code>maxsplit</code> of <code>1</code>:</p>
<pre><code>def sortMyList(string):
return string.rsplit(',', maxsplit=1)[1]
</code></pre>
<p>This will run into a problem: these "numbers" are actually still strings, so when you compare them, it will do so alphabetically, putting "10" before "2" and so on. To fix this, turn the number into an integer before returning it:</p>
<pre><code>def sortMyList(string):
return int(string.rsplit(',', maxsplit=1)[1])
</code></pre>
<p>Putting it all together:</p>
<pre><code>def sortMyList(string):
return int(string.rsplit(',', maxsplit=1)[1])
sortedList = sorted(MyList, key=sortMyList)
</code></pre>
| 3 |
2016-09-18T02:34:48Z
|
[
"python",
"python-3.x"
] |
How to update drawing area in GTK
| 39,553,371 |
<p>I'm trying to make a clock using GTK in python 2. The version I have at this point is just a basic one, it will be much more complicated, however I need to make it refresh first. In the end it will be a screensaver, hopefully.</p>
<p>I have tried to understand how queue_draw() works, but I can't figure it out. I'm new to GTK and not experienced in using classes (although I'm trying). These two are causing my problem I guess.
Can someone help me with this part please :D
I know there are posts about this issue, still I couldn't figure out how to make this working :(
Thank you</p>
<p>I'm using Ubuntu 14.04, python 2.</p>
<p>Here's the code I have at the moment:</p>
<pre><code>#!/usr/bin/env python
import time
import gtk
import math
class Base:
def destroy(self, widget, data=None):
gtk.main_quit()
def close(self, widget):
self.window.destroy()
def rotate(self, center, point, angle):
#http://stackoverflow.com/questions/12161277/how-to-rotate-a-vertex-around-a-certain-point
px = point[0]
py = point[1]
rx = center[0] + (px - center[0]) * math.cos(math.radians(angle)) - (py - center[1]) * math.sin(math.radians(angle))
ry = center[1] + (px - center[0]) * math.sin(math.radians(angle)) + (py - center[1]) * math.cos(math.radians(angle))
return(rx, ry)
# This function will be called whenever the drawing area is exposed:
def expose_handler(self, widget, event) :
w, h = widget.window.get_size()
center = [int(w / 2), int(h / 2)]
xgc = widget.window.new_gc()
#%H for a 24 hour system as %I is for a 12 hour system
TIME = time.strftime("%Y-%m-%d %I:%M:%S") #add this to get GMT time# , time.gmtime())
H, M, S = TIME.split(" ")[1].split(":")
H, M, S = int(H), int(M), int(S)
Dial_radius = (h / 2 - ((h / 2) / 10)) / 3
H_size, M_size, S_size = (Dial_radius / 2), Dial_radius, Dial_radius
H_angle = H * (360 / 12) + (float(M) / 60) * (360 / 12)
M_angle = M * (360 / 60) + (float(S) / 60) * (360 / 60)
S_angle = S * (360 / 60)
H_zero = [center[0], center[1] - H_size]
M_zero = [center[0], center[1] - M_size]
S_zero = [center[0], center[1] - S_size]
Hx, Hy = self.rotate(center, H_zero, H_angle)
Mx, My = self.rotate(center, M_zero, M_angle)
Sx, Sy = self.rotate(center, S_zero, S_angle)
#Hour
xgc.set_rgb_fg_color(gtk.gdk.color_parse("red"))
widget.window.draw_line(xgc, center[0], center[1], int(Hx), int(Hy))
#Minute
xgc.set_rgb_fg_color(gtk.gdk.color_parse("green"))
widget.window.draw_line(xgc, center[0], center[1], int(Mx), int(My))
#Second
xgc.set_rgb_fg_color(gtk.gdk.color_parse("blue"))
widget.window.draw_line(xgc, center[0], center[1], int(Sx), int(Sy))
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_position(gtk.WIN_POS_CENTER)
#self.window.fullscreen()
self.window.set_size_request(600, 400)
self.vbox = gtk.VBox()
self.window.add(self.vbox)
# Create an area to draw in:
self.drawing_area = gtk.DrawingArea()
self.vbox.pack_start(self.drawing_area)
self.drawing_area.show()
self.drawing_area.connect("expose-event", self.expose_handler)
self.drawing_area.show()
self.window.show_all()
self.window.connect("destroy", self.destroy)
def main(self):
gtk.main()
if __name__ == "__main__":
base = Base()
base.main()
</code></pre>
<p>I've updated the code with acw1668's code, now it's working, thanks again, and it look like this:</p>
<pre><code>#!/usr/bin/env python
import time
import gtk
import math
import glib
class Base:
def destroy(self, widget, data=None):
gtk.main_quit()
def close(self, widget):
self.window.destroy()
def refresh_clock(self):
self.drawing_area.queue_draw()
return True
def rotate(self, center, point, angle):
#http://stackoverflow.com/questions/12161277/how-to-rotate-a-vertex-around-a-certain-point
px = point[0]
py = point[1]
rx = center[0] + (px - center[0]) * math.cos(math.radians(angle)) - (py - center[1]) * math.sin(math.radians(angle))
ry = center[1] + (px - center[0]) * math.sin(math.radians(angle)) + (py - center[1]) * math.cos(math.radians(angle))
return(rx, ry)
# This function will be called whenever the drawing area is exposed:
def expose_handler(self, widget, event) :
w, h = widget.window.get_size()
center = [int(w / 2), int(h / 2)]
xgc = widget.window.new_gc()
#%H for a 24 hour system as %I is for a 12 hour system
TIME = time.strftime("%Y-%m-%d %I:%M:%S") #add this to get GMT time# , time.gmtime())
H, M, S = TIME.split(" ")[1].split(":")
H, M, S = int(H), int(M), int(S)
Dial_radius = (h / 2 - ((h / 2) / 10)) / 3
H_size, M_size, S_size = (Dial_radius / 2), Dial_radius, Dial_radius
H_angle = H * (360 / 12) + (float(M) / 60) * (360 / 12)
M_angle = M * (360 / 60) + (float(S) / 60) * (360 / 60)
S_angle = S * (360 / 60)
H_zero = [center[0], center[1] - H_size]
M_zero = [center[0], center[1] - M_size]
S_zero = [center[0], center[1] - S_size]
Hx, Hy = self.rotate(center, H_zero, H_angle)
Mx, My = self.rotate(center, M_zero, M_angle)
Sx, Sy = self.rotate(center, S_zero, S_angle)
#Hour
xgc.set_rgb_fg_color(gtk.gdk.color_parse("red"))
widget.window.draw_line(xgc, center[0], center[1], int(Hx), int(Hy))
#Minute
xgc.set_rgb_fg_color(gtk.gdk.color_parse("green"))
widget.window.draw_line(xgc, center[0], center[1], int(Mx), int(My))
#Second
xgc.set_rgb_fg_color(gtk.gdk.color_parse("blue"))
widget.window.draw_line(xgc, center[0], center[1], int(Sx), int(Sy))
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_position(gtk.WIN_POS_CENTER)
#self.window.fullscreen()
self.window.set_size_request(600, 400)
self.vbox = gtk.VBox()
self.window.add(self.vbox)
# Create an area to draw in:
self.drawing_area = gtk.DrawingArea()
self.vbox.pack_start(self.drawing_area)
self.drawing_area.show()
self.drawing_area.connect("expose-event", self.expose_handler)
self.drawing_area.show()
self.window.show_all()
self.window.connect("destroy", self.destroy)
def main(self):
glib.timeout_add_seconds(1, self.refresh_clock)
gtk.main()
if __name__ == "__main__":
base = Base()
base.main()
</code></pre>
| 2 |
2016-09-18T02:01:15Z
| 39,554,199 |
<p>You can use <code>glib.timeout_add_seconds(...)</code> to setup a timer to call <code>queue_draw()</code> every second:</p>
<pre><code>import glib
</code></pre>
<p>Add a function to refresh the clock:</p>
<pre><code>def refresh_clock(self):
self.drawing_area.queue_draw()
return True
</code></pre>
<p>Update <code>main()</code>:</p>
<pre><code>def main(self):
glib.timeout_add_seconds(1, self.refresh_clock)
gtk.main()
</code></pre>
| 3 |
2016-09-18T04:44:38Z
|
[
"python",
"python-2.7",
"gtk"
] |
text to columns with comma delimiter using python
| 39,553,392 |
<p>how to divide a column in to two columns in an excel using a delimiter ', 'and name the header's using python</p>
<p>here is my code</p>
<pre><code>import openpyxl
w=openpyxl.load_workbook('DDdata.xlsx')
active=w.active
a=active.columns[1]
for cellobj in a:
s=cellobj.value
fila=s.split(',')
print(fila)
</code></pre>
<p><a href="https://drive.google.com/file/d/0Bw8qvPLsyp8dWG5Lc0dBbHpwMEU/view?usp=sharing" rel="nofollow">Input file link</a></p>
<p><a href="http://i.stack.imgur.com/VueSu.jpg" rel="nofollow">outputfile</a></p>
| 0 |
2016-09-18T02:06:10Z
| 39,561,076 |
<p>This looks to be a duplicate of <a href="http://stackoverflow.com/questions/14745022/pandas-dataframe-how-do-i-split-a-column-into-two">this post</a>, but here's a solution for you to consider:</p>
<pre><code>import pandas as pd
df = pd.read_excel('input.xlsx')
df['First Name'], df['Last Name'] = df['Applicant Name'].str.split(',', 1).str
del df['Applicant Name']
df.to_excel('output.xlsx')
</code></pre>
<p>Output (in python):</p>
<pre><code>First Name Last Name
0 - Mohammed Abdul Naser Aziz
1 - Gottipati Harshavardhan
2 - Sandeep Kaur
3 . Rounak
4 abbas Syed
5 Abbas Mohd Manzar
6 Abbasi Fatema
7 Abdelkader BEKHTIE
8 abdollahzadehkan mina
</code></pre>
| 0 |
2016-09-18T18:17:50Z
|
[
"python",
"python-3.x",
"pandas",
"openpyxl"
] |
Python to exe win32crypt CryptProtectData error
| 39,553,474 |
<p>I wrote code which is using win32crypt. When I'm running in Python IDLE there is no problem. I get all data that I need.
But when i'm converted to .exe and executed it I didn't get any result. I get this error</p>
<blockquote>
<p>Traceback (most recent call last): File "chromeHack.py", line 22, in
pywintypes.error: (998, 'CryptProtectData',
'\xcd\xe5\xe2\xe5\xf0\xed\xe0\xff \xef\xee\xef\xfb\xf2\xea\xe0
\xe4\xee\xf1\xf2\xf3\xef\xe0 \xea \xe0\xe4\xf0\xe5\xf1\xf3
\xef\xe0\xec\xff\xf2\xe8.')</p>
</blockquote>
<p>Line 22 is </p>
<pre><code>password = win32crypt.CryptUnprotectData(raw[2])[1]
fileOut.write(password + '\n')
</code></pre>
<p>.exe can't use windows password to decrypt data. I tried to run as administrator but same result.</p>
| -1 |
2016-09-18T02:26:41Z
| 39,934,506 |
<p>You have to run in system command(windows?cmd:shell) to test the code before changing the code to exe.</p>
<p>The result told you that you have a wrong returned value after using the win32crypt.CryptUnprotectData.</p>
<p>the correct usage:
<a href="http://timgolden.me.uk/pywin32-docs/win32crypt__CryptUnprotectData_meth.html" rel="nofollow">win32crypt.CryptUnprotectData</a></p>
| 0 |
2016-10-08T16:08:21Z
|
[
"python",
"winapi"
] |
Dynamically update label text in kivy program (Python)
| 39,553,559 |
<p>New to the kivy library and having some trouble dynamically updating a property. The label here is just a place-holder. Ultimately I want the displayed image to change sequentially based on which quadrant the user clicks/touches.</p>
<p>The program runs fine with no errors, hover the label (label2) does not update (label1 does update). When I click on the four quadrants the quadrant number is displayed to the console as I would expect. I'm also printing out the self.incr whenever the user clicks on Q1 and this also displays and increases which means the incr attribute is increasing as it should.</p>
<p>So, I can't figure out why it doesn't update for the label.</p>
<p>main.py</p>
<pre><code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
class TouchInput(Widget):
def __init__(self,**kwargs):
self.incr = 5
super(TouchInput,self).__init__(**kwargs)
def on_touch_up(self, touch):
if touch.x < self.width / 2:
lateral = 'left'
elif touch.x > self.width / 2:
lateral = 'right'
else:
lateral = None
if touch.y < self.height / 2:
vertical = 'bottom'
elif touch.y > self.height / 2:
vertical = 'top'
else:
vertical = None
if vertical and lateral:
if lateral == 'left' and vertical == 'top':
quadrant = 1
print 'Q1'
self.incr += 1
print self.incr
elif lateral == 'right' and vertical == 'top':
quadrant = 2
print 'Q2'
elif lateral == 'left' and vertical == 'bottom':
quadrant = 3
print 'Q3'
elif lateral == 'right' and vertical == 'bottom':
quadrant = 4
print 'Q4'
class PPVT(App):
def build(self):
t = TouchInput()
print t.incr
return t
if __name__ == "__main__":
PPVT().run()
</code></pre>
<p>main.kv</p>
<pre><code><TouchInput>:
Image:
source: 'img1.jpg'
size: root.width, root.height
Label:
id: label1
text: str(root.width)
pos: root.width / 2, root.height / 2
Label:
id: label2
text: str(root.incr)
</code></pre>
| 0 |
2016-09-18T02:46:29Z
| 39,555,298 |
<p>Use a numeric property, so kivy can track its changes.</p>
<pre><code>from kivy.properties import NumericProperty
...
class TouchInput(Widget):
incr = NumericProperty(5)
...
</code></pre>
| 1 |
2016-09-18T07:47:26Z
|
[
"python",
"dynamic",
"kivy"
] |
Python - object has no attribute Error
| 39,553,578 |
<p><strong>I re-wrote the entire class from scratch in a separate file and everything magically worked, conditionals and all. So, I simply imported that class and a couple functions from the new file into the master file. I still have no idea what went wrong the first time around.</strong></p>
<p><strong>Note the issues below were <em>technically</em> solved. You can see a typo towards the bottom of the code. That, however, uncovered an issue where all of my conditionals (if, try, etc.) stopped functioning, which is why I re-wrote the class in a separate module</strong></p>
<p><strong>I <em>would</em> delete this post since it got everyone nowhere, but that's not how things work on Stack Overflow, apparently.</strong></p>
<p>Alright, I've been learning Python 3.4 and decided to do some homework on the side as practice. I started making a script that does a very basic simulation of 2 people fighting, and would expand upon it with any new stuff I learn (such as adding a GUI).</p>
<p>The script started out fine, but the more changes I made the more errors started showing up. Now it's to the point where I can't access any fields of the "fighter" class without it throwing errors such as:</p>
<pre><code>'duelist' object has no attribute '_duelist__health'
</code></pre>
<p>Besides "<em>'duelist' object has no attribute '_duelist__XXX'</em>", I've had 0 other errors besides typos.
Google unfortunately couldn't help with this one, so that's why I'm making my first StackOverflow post.</p>
<p>Here's the class down to the first error-happy field, "health":</p>
<pre><code>class duelist:
def __init__(self):
self.name = "Duelist" #must not be ""
self.health = 5 #must be >0
self.damage = [1, 3] #random attack range. Must be >=0 0 and the first must not be higher.
self.skill = 10 #% chance to pass a skill check. Representative of parrying/dodging. Must be >=0
self.shield = True #can block?
self.shieldE = 80 #max block %. Must be >0
self.agility = 0.5 #rate of attack in seconds. Must be >=0.05
self.precision = 10 #critical hit chance. Must be >=0
self.critical = 2.0 #critical multiplier. Must be >= 1.1
#name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if value != "":
self.__name = value
else:
print("Invalid Name.\n")
#name
#health
@property
def health(self):
return self.__health
@health.setter
def health(self, value):
try:
value = value(int)
if value>=1:
self.__health = value
else:
print("Health must be above 0.\n")
except:
print("Invalid Health.\n")
#health
</code></pre>
<p>Also, for those suggesting to change the field names to not include an ' __ ' (or to include an ' __ ' everywhere), that causes an infinite loop.
Typing exactly this:</p>
<pre><code>class duelist:
def __init__(self):
self.health = 5
@property
def health(self):
return self.__health
@health.setter
def health(self, value):
self.__health = value
D = duelist()
print(D.health)
D.health = 15
print(D.health)
</code></pre>
<p>Correctly returns </p>
<pre><code>5
15
</code></pre>
| -1 |
2016-09-18T02:50:39Z
| 39,553,785 |
<p>Your code does:</p>
<ol>
<li>Set the value of <code>.name =</code> inside <code>__init__()</code></li>
<li>That goes through the setter, and sets <code>.__name =</code></li>
<li>When you read it by <code>.name</code> that reads through the getter, and reads <code>.__name</code></li>
</ol>
<p>And your description of the problem "<em>I can't access any fields of the "fighter" class</em>", I suspect is wrong, because accessing <em>some</em> of them work.</p>
<p>Health doesn't, though, and on line 45 you have this:</p>
<pre><code>value = value(int)
</code></pre>
<p>instead of</p>
<pre><code>value = int(value)
</code></pre>
<p>So that causes the getter to throw an exception and <code>print("Invalid Health.\n")</code> and <code>__health</code> is never set.</p>
<p>With <code>self.shield = True</code>, the setter is trying to do:</p>
<pre><code>if value.lower() == 'y':
</code></pre>
<p>and you can't call <code>lower()</code> on a boolean, so it crashes out before it ever gets to try to <code>type(value) == bool</code>, and <code>__shield</code> is never set.</p>
| 2 |
2016-09-18T03:30:27Z
|
[
"python",
"object",
"attributes",
"field"
] |
Python - object has no attribute Error
| 39,553,578 |
<p><strong>I re-wrote the entire class from scratch in a separate file and everything magically worked, conditionals and all. So, I simply imported that class and a couple functions from the new file into the master file. I still have no idea what went wrong the first time around.</strong></p>
<p><strong>Note the issues below were <em>technically</em> solved. You can see a typo towards the bottom of the code. That, however, uncovered an issue where all of my conditionals (if, try, etc.) stopped functioning, which is why I re-wrote the class in a separate module</strong></p>
<p><strong>I <em>would</em> delete this post since it got everyone nowhere, but that's not how things work on Stack Overflow, apparently.</strong></p>
<p>Alright, I've been learning Python 3.4 and decided to do some homework on the side as practice. I started making a script that does a very basic simulation of 2 people fighting, and would expand upon it with any new stuff I learn (such as adding a GUI).</p>
<p>The script started out fine, but the more changes I made the more errors started showing up. Now it's to the point where I can't access any fields of the "fighter" class without it throwing errors such as:</p>
<pre><code>'duelist' object has no attribute '_duelist__health'
</code></pre>
<p>Besides "<em>'duelist' object has no attribute '_duelist__XXX'</em>", I've had 0 other errors besides typos.
Google unfortunately couldn't help with this one, so that's why I'm making my first StackOverflow post.</p>
<p>Here's the class down to the first error-happy field, "health":</p>
<pre><code>class duelist:
def __init__(self):
self.name = "Duelist" #must not be ""
self.health = 5 #must be >0
self.damage = [1, 3] #random attack range. Must be >=0 0 and the first must not be higher.
self.skill = 10 #% chance to pass a skill check. Representative of parrying/dodging. Must be >=0
self.shield = True #can block?
self.shieldE = 80 #max block %. Must be >0
self.agility = 0.5 #rate of attack in seconds. Must be >=0.05
self.precision = 10 #critical hit chance. Must be >=0
self.critical = 2.0 #critical multiplier. Must be >= 1.1
#name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if value != "":
self.__name = value
else:
print("Invalid Name.\n")
#name
#health
@property
def health(self):
return self.__health
@health.setter
def health(self, value):
try:
value = value(int)
if value>=1:
self.__health = value
else:
print("Health must be above 0.\n")
except:
print("Invalid Health.\n")
#health
</code></pre>
<p>Also, for those suggesting to change the field names to not include an ' __ ' (or to include an ' __ ' everywhere), that causes an infinite loop.
Typing exactly this:</p>
<pre><code>class duelist:
def __init__(self):
self.health = 5
@property
def health(self):
return self.__health
@health.setter
def health(self, value):
self.__health = value
D = duelist()
print(D.health)
D.health = 15
print(D.health)
</code></pre>
<p>Correctly returns </p>
<pre><code>5
15
</code></pre>
| -1 |
2016-09-18T02:50:39Z
| 39,553,854 |
<p>The exception <em>can</em> be caused if your class does not define an attribute <code>__health</code> in its <code>__init__()</code> method. Trying to read its value will trigger the problem. The attribute will be created by calling the setter method (indirectly through attribute assignment), and after that the attribute becomes available. </p>
<p>Here is a simplified version of your class:</p>
<pre><code>class Duelist:
def __init__(self):
# self.health = 5
pass
@property
def health(self):
return self.__health
@health.setter
def health(self, value):
self.__health = value
>>> d = Duelist()
>>> d.health
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "p.py", line 9, in health
return self.__health
AttributeError: 'Duelist' object has no attribute '_Duelist__health'
>>> d.health = 123
>>> d.health
123
</code></pre>
<p>So one way to fix it is to initialise the attributes using the <em>same</em> name:</p>
<pre><code>class Duelist:
def __init__(self):
# self.health = 5 # this will also work
self.__health = 5
>>> d.health
5
>>> d.health = 123
>>> d.health
123
</code></pre>
<p>So, given that the exception will be raised if you do not initialise the property (<code>self.health</code>) or the underlying attribute (<code>self.__health</code>), have you posted the actual code that causes the problem in your question?</p>
| 0 |
2016-09-18T03:42:46Z
|
[
"python",
"object",
"attributes",
"field"
] |
How can I avoid JSON percent-encoding and \u-escaping?
| 39,553,703 |
<p>When I parse the file</p>
<pre><code><html>
<head><meta charset="UTF-8"></head>
<body><a href="Düsseldorf.html">Düsseldorf</a></body>
</html>
</code></pre>
<p>using</p>
<pre><code>item = SimpleItem()
item['name'] = response.xpath('//a/text()')[0].extract()
item["url"] = response.xpath('//a/@href')[0].extract()
return item
</code></pre>
<p>I end up with either <code>\u</code> escapes</p>
<pre><code>[{
"name": "D\u00fcsseldorf",
"url": "D\u00fcsseldorf.html"
}]
</code></pre>
<p>or with percent-encoded strings</p>
<pre><code>D%C3%BCsseldorf
</code></pre>
<p>The <a href="http://doc.scrapy.org/en/latest/topics/exporters.html" rel="nofollow">item exporter</a> described <a href="https://groups.google.com/forum/#!topic/scrapy-users/rJcfSFVZ3O4" rel="nofollow">here</a></p>
<pre><code># -*- coding: utf-8 -*-
import json
from scrapy.contrib.exporter import BaseItemExporter
class UnicodeJsonLinesItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
self._configure(kwargs)
self.file = file
self.encoder = json.JSONEncoder(ensure_ascii=False, **kwargs)
def export_item(self, item):
itemdict = dict(self._get_serialized_fields(item))
self.file.write(self.encoder.encode(itemdict) + '\n')
</code></pre>
<p>along with the appropriate feed exporter setting</p>
<pre><code>FEED_EXPORTERS = {
'json': 'myproj.exporter.UnicodeJsonLinesItemExporter',
}
</code></pre>
<p>do not help.</p>
<p>How do I get a utf-8-encoded JSON output?</p>
<p>I'm reiterating/expanding an <a href="http://stackoverflow.com/q/24884011/704972">unanswered question</a>.</p>
<p><strong>Update</strong>:</p>
<p>Orthogonal to Scrapy, note that without setting</p>
<pre><code>export PYTHONIOENCODING="utf_8"
</code></pre>
<p>running</p>
<pre><code>> echo { \"name\": \"Düsseldorf\", \"url\": \"Düsseldorf.html\" } > dorf.json
> python -c'import fileinput, json;print json.dumps(json.loads("".join(fileinput.input())),sort_keys=True, indent=4, ensure_ascii=False)' dorf.json > dorf_pp.json
</code></pre>
<p>will fail with</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 16: ordinal not in range(128)
</code></pre>
<p><strong>Update</strong></p>
<p>As posted my question was unanswerable. The UnicodeJsonLinesItemExporter works, but another part of the pipeline was the culprit: As a post-process to pretty-print the JSON output, I was was using <code>python -m json.tool in.json > out.json</code>.</p>
| 0 |
2016-09-18T03:15:09Z
| 39,554,214 |
<pre><code>>>> a = [{
"name": "D\u00fcsseldorf",
"url": "D\u00fcsseldorf.html"
}]
>>> a
[{'url': 'Düsseldorf.html', 'name': 'Düsseldorf'}]
>>> json.dumps(a, ensure_ascii=False)
'[{"url": "Düsseldorf.html", "name": "Düsseldorf"}]'
</code></pre>
| 2 |
2016-09-18T04:46:24Z
|
[
"python",
"json",
"unicode",
"scrapy"
] |
How can I avoid JSON percent-encoding and \u-escaping?
| 39,553,703 |
<p>When I parse the file</p>
<pre><code><html>
<head><meta charset="UTF-8"></head>
<body><a href="Düsseldorf.html">Düsseldorf</a></body>
</html>
</code></pre>
<p>using</p>
<pre><code>item = SimpleItem()
item['name'] = response.xpath('//a/text()')[0].extract()
item["url"] = response.xpath('//a/@href')[0].extract()
return item
</code></pre>
<p>I end up with either <code>\u</code> escapes</p>
<pre><code>[{
"name": "D\u00fcsseldorf",
"url": "D\u00fcsseldorf.html"
}]
</code></pre>
<p>or with percent-encoded strings</p>
<pre><code>D%C3%BCsseldorf
</code></pre>
<p>The <a href="http://doc.scrapy.org/en/latest/topics/exporters.html" rel="nofollow">item exporter</a> described <a href="https://groups.google.com/forum/#!topic/scrapy-users/rJcfSFVZ3O4" rel="nofollow">here</a></p>
<pre><code># -*- coding: utf-8 -*-
import json
from scrapy.contrib.exporter import BaseItemExporter
class UnicodeJsonLinesItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
self._configure(kwargs)
self.file = file
self.encoder = json.JSONEncoder(ensure_ascii=False, **kwargs)
def export_item(self, item):
itemdict = dict(self._get_serialized_fields(item))
self.file.write(self.encoder.encode(itemdict) + '\n')
</code></pre>
<p>along with the appropriate feed exporter setting</p>
<pre><code>FEED_EXPORTERS = {
'json': 'myproj.exporter.UnicodeJsonLinesItemExporter',
}
</code></pre>
<p>do not help.</p>
<p>How do I get a utf-8-encoded JSON output?</p>
<p>I'm reiterating/expanding an <a href="http://stackoverflow.com/q/24884011/704972">unanswered question</a>.</p>
<p><strong>Update</strong>:</p>
<p>Orthogonal to Scrapy, note that without setting</p>
<pre><code>export PYTHONIOENCODING="utf_8"
</code></pre>
<p>running</p>
<pre><code>> echo { \"name\": \"Düsseldorf\", \"url\": \"Düsseldorf.html\" } > dorf.json
> python -c'import fileinput, json;print json.dumps(json.loads("".join(fileinput.input())),sort_keys=True, indent=4, ensure_ascii=False)' dorf.json > dorf_pp.json
</code></pre>
<p>will fail with</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 16: ordinal not in range(128)
</code></pre>
<p><strong>Update</strong></p>
<p>As posted my question was unanswerable. The UnicodeJsonLinesItemExporter works, but another part of the pipeline was the culprit: As a post-process to pretty-print the JSON output, I was was using <code>python -m json.tool in.json > out.json</code>.</p>
| 0 |
2016-09-18T03:15:09Z
| 39,570,495 |
<p>this seems to work for me</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
import urllib
class SimpleItem(scrapy.Item):
name = scrapy.Field()
url = scrapy.Field()
class CitiesSpider(scrapy.Spider):
name = "cities"
allowed_domains = ["sitercity.info"]
start_urls = (
'http://en.sistercity.info/countries/de.html',
)
def parse(self, response):
for a in response.css('a'):
item = SimpleItem()
item['name'] = a.css('::text').extract_first()
item['url'] = urllib.unquote(
a.css('::attr(href)').extract_first().encode('ascii')
).decode('utf8')
yield item
</code></pre>
<p>using the feed exporter cited in your question, it worked also using another storage</p>
<pre><code># -*- coding: utf-8 -*-
import json
import io
import os
from scrapy.contrib.exporter import BaseItemExporter
from w3lib.url import file_uri_to_path
class CustomFileFeedStorage(object):
def __init__(self, uri):
self.path = file_uri_to_path(uri)
def open(self, spider):
dirname = os.path.dirname(self.path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
return io.open(self.path, mode='ab')
def store(self, file):
file.close()
class UnicodeJsonLinesItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
self._configure(kwargs)
self.file = file
self.encoder = json.JSONEncoder(ensure_ascii=False, **kwargs)
def export_item(self, item):
itemdict = dict(self._get_serialized_fields(item))
self.file.write(self.encoder.encode(itemdict) + '\n')
</code></pre>
<p>(removing the comments if necessary)</p>
<pre><code>FEED_EXPORTERS = {
'json': 'myproj.exporter.UnicodeJsonLinesItemExporter'
}
#FEED_STORAGES = {
# '': 'myproj.exporter.CustomFileFeedStorage'
#}
FEED_FORMAT = 'json'
FEED_URI = "out.json"
</code></pre>
| 1 |
2016-09-19T10:07:10Z
|
[
"python",
"json",
"unicode",
"scrapy"
] |
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
| 39,553,706 |
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p>
<p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the face. The default fipy condition is the former (value = 0), but the explicit method (faceGrad.constrain) is the latter. The issue can be understood by adding the following code to the end of the fipy <a href="http://www.ctcms.nist.gov/fipy/examples/diffusion/generated/examples.diffusion.mesh20x20.html" rel="nofollow">diffusion.mesh20x20</a> example and noting different face gradient results. </p>
<pre><code>facesNeumann = mesh.exteriorFaces & ~facesTopLeft & ~facesBottomRight
print 'grad(phi) with default Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
phi.faceGrad.constrain(0.,facesNeumann)
DiffusionTerm().solve(var=phi)
print 'and with explicit Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
</code></pre>
| 1 |
2016-09-18T03:15:23Z
| 39,575,670 |
<p>Please see the discussion on <a href="http://www.ctcms.nist.gov/fipy/documentation/USAGE.html#applying-fixed-flux-boundary-conditions" rel="nofollow">fixed flux boundary conditions</a>. Basically, you add a source containing the the divergence of the desired boundary flux to FiPy's default no-flux condition.</p>
| 2 |
2016-09-19T14:29:30Z
|
[
"python",
"mesh",
"pde",
"fipy"
] |
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
| 39,553,706 |
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p>
<p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the face. The default fipy condition is the former (value = 0), but the explicit method (faceGrad.constrain) is the latter. The issue can be understood by adding the following code to the end of the fipy <a href="http://www.ctcms.nist.gov/fipy/examples/diffusion/generated/examples.diffusion.mesh20x20.html" rel="nofollow">diffusion.mesh20x20</a> example and noting different face gradient results. </p>
<pre><code>facesNeumann = mesh.exteriorFaces & ~facesTopLeft & ~facesBottomRight
print 'grad(phi) with default Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
phi.faceGrad.constrain(0.,facesNeumann)
DiffusionTerm().solve(var=phi)
print 'and with explicit Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
</code></pre>
| 1 |
2016-09-18T03:15:23Z
| 39,578,205 |
<p>In terms of just specifying the flux normal to a boundary for a variable independent of solving an equation, there does not appear to be any way to do that. The syntax might be <code>phi.faceGrad[0].constrain(...)</code> for example, but that currently doesn't work in FiPy. It might also be difficult to implement for arbitrary oriented faces.</p>
<p>However, for practical purposes, the component tangential to a boundary is not used when solving an equation in FiPy, only the normal component has any influence on the solution. For example, take the following code,</p>
<pre><code>import fipy as fp
mesh = fp.Grid2D(nx=2, ny=1)
var = fp.CellVariable(mesh=mesh)
var.constrain(1, mesh.facesLeft)
var.constrain(0, mesh.facesRight)
#var.faceGrad.constrain(0, mesh.facesTop)
fp.DiffusionTerm().solve(var)
print 'face gradient on top plane:',var.faceGrad[0, mesh.facesTop.value]
print 'variable value:',var
</code></pre>
<p>This gives an output of</p>
<pre><code>face gradient on top plane: [-0.5 -0.5]
variable value: [ 0.75 0.25]
</code></pre>
<p>The answer is correct, but the top face gradient is -0.5. However, when the line <code>#var.faceGrad.constrain(0, mesh.facesTop)</code> is uncommented, the result is</p>
<pre><code>face gradient on top plane: [ 0. 0.]
variable value: [ 0.75 0.25]
</code></pre>
<p>The tangential face gradient is now 0, but the answer is the same. The point is that setting the face gradient tangentially (via <code>.constrain</code>) has no influence on the solution.</p>
| 2 |
2016-09-19T16:49:12Z
|
[
"python",
"mesh",
"pde",
"fipy"
] |
How do you specifiy a Neumann (fixed flux normal to face) boundary condition in Fipy?
| 39,553,706 |
<p>How do I explicitly set the flux normal to a boundary face in a fipy mesh to be a specific value, without constraining components of flux within the face?</p>
<p>A Neumann boundary condition can be specified as: (1) fixed component of flux normal to a boundary face, or (2) as a complete specification of flux at the face. The default fipy condition is the former (value = 0), but the explicit method (faceGrad.constrain) is the latter. The issue can be understood by adding the following code to the end of the fipy <a href="http://www.ctcms.nist.gov/fipy/examples/diffusion/generated/examples.diffusion.mesh20x20.html" rel="nofollow">diffusion.mesh20x20</a> example and noting different face gradient results. </p>
<pre><code>facesNeumann = mesh.exteriorFaces & ~facesTopLeft & ~facesBottomRight
print 'grad(phi) with default Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
phi.faceGrad.constrain(0.,facesNeumann)
DiffusionTerm().solve(var=phi)
print 'and with explicit Neumann BC...'
print phi.faceGrad.value.T[facesNeumann.value]
</code></pre>
| 1 |
2016-09-18T03:15:23Z
| 39,713,838 |
<p>The discussion on fixed flux boundary conditions does answer my question, but I had not understood the documentation, which is very brief. Below is a worked example that illustrates how to apply this in a simple 2D case, similar to the mesh20x20 example.</p>
<pre><code>import matplotlib.pyplot as plt
from fipy import *
nx = 20
ny = nx
dx = 1.
dy = dx
L = dx * nx
msh = Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)
xFace, yFace = msh.faceCenters
xCell,yCell = msh.cellCenters
phi = CellVariable(name = "solution variable",
mesh = msh,
value = 0.)
D = FaceVariable(name='diffusion coefficient',mesh=msh,value=1.)
# Dirichlet condition on top face
valueTop = FaceVariable(name='valueTop',mesh=msh,value=xFace*0.1-1)
phi.constrain(valueTop, msh.facesTop)
# Fixed flux (Neumann) on base
D.constrain(0., msh.facesBottom)
fluxBottom = -0.05
eq = DiffusionTerm(coeff=D) + (msh.facesBottom * fluxBottom).divergence
eq.solve(var=phi)
# confirm only y component of gradient is zero
print phi.faceGrad.value.T[msh.facesBottom.value]
plt.scatter(phi.value, yCell)
plt.show()
viewer = Viewer(vars=phi, datamin=-1., datamax=1.)
viewer.plot()
</code></pre>
| 0 |
2016-09-26T23:24:40Z
|
[
"python",
"mesh",
"pde",
"fipy"
] |
how to simplify a try, if except code in python for repetitive input?
| 39,553,737 |
<p>I used multiple if elif, also there are repetitive try, if, except command to eliminate negative, non-integer, non-number input, can I have a command that eliminate those ones altogether? Thanks! The code is as the following:</p>
<pre><code>print("Welcome to Supermarket")
print("1. Potatoes($0.75 per potato)")
print("2. Tomatoes ($1.25 per tomato)")
print("3. Apples ($0.50 per apple)")
print("4. Mangoes ($1.75 per mango)")
print("5. checkout")
total = 0
i = 0
while i <= 0:
try:
choice = int(input("please enter 1, 2, 3, 4 or 5: "))
if choice not in (1, 2, 3, 4, 5):
raise ValueError()
except ValueError:
print("invalid input, you need to enter 1, 2, 3, 4 or5")
choice = -1
else:
if choice == 1:
try:
amount = int(input("how many potatoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 0.75 * amount + total
cop = 0.75 * amount
print("the cost of potatoes is $", format(cop, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 2:
try:
amount = int(input("how many tomatoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 1.25 * amount + total
cot = 1.25 * amount
print("the cost of tomatoes is $", format(cot, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 3:
try:
amount = int(input("how many apples do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 0.5 * amount + total
coa = 0.5 * amount
print("the cost of apples is $", format(coa, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 4:
try:
amount = int(input("how many mangoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 1.75 * amount + total
com = 1.75 * amount
print("the cost of mangoes is $", format(com, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 5:
print("your total is $", format(total, ".2f"))
choice = choice + 1
i = choice - 5
k = 0
while k < 1:
try:
insert = float(
input("enter you payment to the nearest cent(ex. 17.50 means you have entered 17 dollars and 50 cents): "))
if (insert - total) < 0:
raise ValueError()
except ValueError:
print(
"you must enter a number in the form like '17.50' and you have to enter an amount more than the total cost!")
k = k - 1
else:
change = insert - total
five_do = int(change / 5)
one_do = int(change % 5)
quart = int((change - five_do * 5 - one_do) / 0.25)
dime = int((change - five_do * 5 - one_do - quart * 0.25) / 0.1)
nickel = int((change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1) / 0.05)
penny = (change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1 - nickel * 0.05) * 100
print("total change is: $ ", format(change, ".2f"))
print("give customer: ", five_do, "$5 note,", one_do, "$1 note,",
quart, "quartz,", dime, "dimes,", nickel, "nickels,", format(penny, ".0f"), "pennies")
</code></pre>
| 1 |
2016-09-18T03:20:22Z
| 39,553,803 |
<p>Extract the common validation code into it's own function:</p>
<pre><code>def validate_input(input_message):
"""Validate that input is a positive integer"""
amount = int(input(input_message))
if amount < 0:
raise ValueError("positive number required")
return amount
</code></pre>
<p>Then call the function as needed:</p>
<pre><code>if choice == 1:
try:
amount = validate_input("how many potatoes do you want? ")
except ValueError:
# do something with invalid input here
else:
# do something with valid input here
</code></pre>
<p>When you have this sort of repetition in your code it pays to see if there's a way to refactor it out into a function.</p>
| 0 |
2016-09-18T03:32:54Z
|
[
"python",
"python-3.x"
] |
how to simplify a try, if except code in python for repetitive input?
| 39,553,737 |
<p>I used multiple if elif, also there are repetitive try, if, except command to eliminate negative, non-integer, non-number input, can I have a command that eliminate those ones altogether? Thanks! The code is as the following:</p>
<pre><code>print("Welcome to Supermarket")
print("1. Potatoes($0.75 per potato)")
print("2. Tomatoes ($1.25 per tomato)")
print("3. Apples ($0.50 per apple)")
print("4. Mangoes ($1.75 per mango)")
print("5. checkout")
total = 0
i = 0
while i <= 0:
try:
choice = int(input("please enter 1, 2, 3, 4 or 5: "))
if choice not in (1, 2, 3, 4, 5):
raise ValueError()
except ValueError:
print("invalid input, you need to enter 1, 2, 3, 4 or5")
choice = -1
else:
if choice == 1:
try:
amount = int(input("how many potatoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 0.75 * amount + total
cop = 0.75 * amount
print("the cost of potatoes is $", format(cop, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 2:
try:
amount = int(input("how many tomatoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 1.25 * amount + total
cot = 1.25 * amount
print("the cost of tomatoes is $", format(cot, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 3:
try:
amount = int(input("how many apples do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 0.5 * amount + total
coa = 0.5 * amount
print("the cost of apples is $", format(coa, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 4:
try:
amount = int(input("how many mangoes do you want? "))
if amount < 0:
raise ValueError()
except ValueError:
print("invalid input")
else:
total = 1.75 * amount + total
com = 1.75 * amount
print("the cost of mangoes is $", format(com, ".2f"))
print("the total now is $", format(total, ".2f"))
elif choice == 5:
print("your total is $", format(total, ".2f"))
choice = choice + 1
i = choice - 5
k = 0
while k < 1:
try:
insert = float(
input("enter you payment to the nearest cent(ex. 17.50 means you have entered 17 dollars and 50 cents): "))
if (insert - total) < 0:
raise ValueError()
except ValueError:
print(
"you must enter a number in the form like '17.50' and you have to enter an amount more than the total cost!")
k = k - 1
else:
change = insert - total
five_do = int(change / 5)
one_do = int(change % 5)
quart = int((change - five_do * 5 - one_do) / 0.25)
dime = int((change - five_do * 5 - one_do - quart * 0.25) / 0.1)
nickel = int((change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1) / 0.05)
penny = (change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1 - nickel * 0.05) * 100
print("total change is: $ ", format(change, ".2f"))
print("give customer: ", five_do, "$5 note,", one_do, "$1 note,",
quart, "quartz,", dime, "dimes,", nickel, "nickels,", format(penny, ".0f"), "pennies")
</code></pre>
| 1 |
2016-09-18T03:20:22Z
| 39,553,845 |
<p>I would suggest to do a function that validates that the input is an integer and greater than zero.
Something like :</p>
<pre><code>def validateInt(value):
value = int(value) #try to cast the value as an integer
if value < 0:
raise ValueError
</code></pre>
<p>In your code you can now use it as follows:</p>
<pre><code>choice = input("Choose an option : ")
try:
validateInt(choice)
except:
Print("Invalid Input.")
</code></pre>
| 0 |
2016-09-18T03:41:19Z
|
[
"python",
"python-3.x"
] |
How to access property cross class and cross file in Python?
| 39,553,792 |
<p>Now I need a property which in another class to do something in one class.</p>
<p>just like:</p>
<pre><code>a.py
class A:
def __init__(self, io_loop): # the same io_loop instance
self.access = None
self.w_id = None
self.io_loop = io_loop
@gen.coroutine
def setup(self):
# `async_client` has the `get`, 'post', 'put', 'delete' methods
self.access = yield async_client()
@gen.coroutine
def do_something(self):
self.w_id = self.access.get('w_id')
...
def run(self):
self.io_loop.run_sync(self.setup)
self.io_loop.spawn_callback(self.do_something)
self.io_loop.start()
if __name__ == '__main__':
a = A()
a.run()
</code></pre>
<p>-</p>
<pre><code>b.py
class B:
def __init__(self, io_loop):
self.w_id = None
self.io_loop = io_loop # the same io_loop instance
# How can i get the w_id from `class A`
def run(self):
...
if __name__ == '__main__':
b = B()
b.run()
</code></pre>
<p><strong>Notice</strong>:</p>
<p>when zone_id of <code>class B</code> is not None, <code>class B</code> can do next. that's means, if <code>class A</code> zone_id is None, <code>class B</code> will waiting for it.</p>
<p>And the <code>class A</code> and <code>class B</code> only could initialize one instance.</p>
<p><strong>the <code>class A</code> and <code>class B</code> in differents files.</strong></p>
| 1 |
2016-09-18T03:31:01Z
| 39,554,355 |
<p>You can't access that variable until you create an instance that initializes. Otherwise, <code>w_id</code> doesn't exist in <code>A</code>.</p>
<p>If you want to give <code>w_id</code> an arbitrary value for access from other classes, put it as a class variable, means you write directly <code>w_id = 'some value'</code> inside class <code>A</code> with the same indentation as the <code>def</code>s:</p>
<pre><code>class A:
w_id = something
def __init__(self):
...
class B:
def __init__(self):
self.w_id = A.w_id
</code></pre>
<p>Otherwise, you need an instance of <code>A</code>, like that:</p>
<pre><code>class B:
def __init__(self):
a = A()
a.do_something()
self.w_id = a.w_id
</code></pre>
<p>The only other option is to create the same functions inside <code>B</code>:</p>
<pre><code>class B:
...
@gen.coroutine
def setup(self):
# `async_client` has the `get`, 'post', 'put', 'delete' methods
self.access = yield async_client()
@gen.coroutine
def do_something(self):
self.w_id = self.access.get('w_id')
...
</code></pre>
<p>As you mentioned that io_loop is the same instance in all of the classes, it might occur that you need to create a copy of it if your functions uses it. You can't change a variable and expect it to stay unchanged. </p>
| 0 |
2016-09-18T05:15:00Z
|
[
"python",
"tornado"
] |
Vim double-indents python files
| 39,553,825 |
<p>I get the following behavior. Given this <code>settings.py</code> snippet, hitting 'o' from line 33</p>
<pre><code>31# Application definition
32
33 INSTALLED_APPS = [
34 'rest_framework',
</code></pre>
<p>I get this</p>
<pre><code>31# Application definition
32
33 INSTALLED_APPS = [
34 |<-cursor is here, two indents, 8 spaces
35 'rest_framework',
</code></pre>
<p>What I really want would be one indent, or a total of 4 spaces, in line with the rest of the list. What gives? I'm using the following .vimrc which I mostly cribbed from <a href="https://realpython.com/blog/python/vim-and-python-a-match-made-in-heaven/" rel="nofollow">here</a>.</p>
<pre><code>set nocompatible " required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" Themes
Plugin 'altercation/vim-colors-solarized'
Plugin 'jnurmine/Zenburn'
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
if has('gui_running')
set background=dark
colorscheme solarized
else
colorscheme zenburn
endif
au BufNewFile,BufRead *.py set tabstop=4 shiftwidth=4 textwidth=79 expandtab autoindent fileformat=unix
set encoding=utf-8
set nu
let python_highlight_all=1
syntax on
set backspace=indent,eol,start
</code></pre>
| 2 |
2016-09-18T03:37:28Z
| 39,554,322 |
<p>This happens because of default vim indentation plugin for Python. It inserts 2 <code>shiftwidth</code> on the first line below <code>[</code>.</p>
<p>You can see code which causes this behaviour here: <a href="https://github.com/vim/vim/blob/0b9e4d1224522791c0dbbd45742cbd688be823f3/runtime/indent/python.vim#L74" rel="nofollow">https://github.com/vim/vim/blob/0b9e4d1224522791c0dbbd45742cbd688be823f3/runtime/indent/python.vim#L74</a></p>
<p>I would recommend you to install <a href="https://github.com/hynek/vim-python-pep8-indent" rel="nofollow"><code>vim-python-pep8-indent</code></a> plugin which does indentation inside parenthesis exactly as you need.</p>
| 3 |
2016-09-18T05:07:04Z
|
[
"python",
"vim"
] |
inserting values into numpy array
| 39,553,837 |
<p>I am new to python and numpy, coming from a java background.</p>
<p>I want to insert int values into a an array.
However my current way of doing it is not resulting in the proper values.
I create an array 'a' of size 5, and would like to insert int values into 'a'. </p>
<pre><code>data = ocr['data']
test_data = ocr['testdata']
a = np.empty(5, dtype=np.int)
for t in range(0,5):
np.append(a,np.dot(np.subtract(test_data[t], data[0]), np.subtract(test_data[t], data[d])))
</code></pre>
| 1 |
2016-09-18T03:39:59Z
| 39,553,939 |
<p>When you initialize a numpy array by <code>np.empty()</code>, it allocates enough space for you, but the values inside these supposedly empty cells will be random rubbish. E.g.</p>
<pre><code>>>> a = np.empty(5,dtype = int)
>>> a
array([-2305843009213693952, -2305843009213693952, 4336320554,
0, 0])
>>> k = np.empty(5,dtype = int)
>>> k
array([-2305843009213693952, -2305843009213693952, 4336320556,
4294967297, 140215654037360])
</code></pre>
<p>Hence, you have two choices: initilize an empty array with length 0 then append. NOTE: as @hpaulj pointed out, you need to set some array to be equal to the array returned by <code>np.append()</code> i.e.</p>
<pre><code>>>> a = np.array([],dtype = int)
>>> a = np.append(a,2)
>>> a = np.append(a,1)
>>> a = np.append(a,3)
>>> a = np.append(a,5)
>>> a
array([2, 1, 3, 5])
</code></pre>
<p>Or you can initialize by <code>np.empty()</code> but then you have to use up all the cells that you initialized first before appending. i.e.</p>
<pre><code>>>> a = np.empty(3,dtype = np.int)
>>> a[0] = 2
>>> a[1] = 1
>>> a[2] = 5
>>> a = np.append(a,3)
>>> a
array([2, 1, 5, 3])
</code></pre>
| 3 |
2016-09-18T03:57:14Z
|
[
"python",
"arrays",
"numpy"
] |
Use apply() with Pandas Series
| 39,553,866 |
<p>I have the code below:</p>
<pre><code>import pandas as pd
frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),index=['Utah','Ohio','Texas','Oregon'])
frame
b d e
Utah 0.479210 0.161892 -1.315375
Ohio -0.572543 0.080203 -0.446178
Texas 0.052954 0.043417 0.365056
Oregon 1.462631 0.244453 2.207720
f = lambda x: x.max()-x.min()
frame.apply(f)
</code></pre>
<p>This results to:</p>
<pre><code>b 2.035174
d 0.201035
e 3.523095
dtype: float64
</code></pre>
<p>Im trying to learn how to apply the lambda to the specific column only so I wanted to apply the lambda to the 'd' column only. So this is what I did</p>
<pre><code>frame['d'].apply(f)
</code></pre>
<p>It results to an error though:
AttributeError: 'float' object has no attribute 'max'</p>
<pre><code>type(frame['d'])
pandas.core.series.Series
frame['d'].dtype
dtype('float64')
</code></pre>
<p>I try to debug it. It seems that frame['d'] which is of type Series and each of the values in this series is a float and a float doesn't have a min/max attribute.</p>
<p>I thought I'm just missing something simple here, but my limited knowledge of Python and Pandas is giving me a hard time. How do I get to apply the lambda to column 'd' only?</p>
| 2 |
2016-09-18T03:45:21Z
| 39,553,927 |
<p>The problem is <code>.apply</code> on a Series works <em>elementwise</em>, in a <code>DataFrame</code> it works <em>by series</em> or <em>by row</em>. If you really want to use <code>.apply</code> this way, you can subset like this:</p>
<pre><code>In [9]: frame.loc[:,['d']]
Out[9]:
d
Utah 2.259488
Ohio 0.458926
Texas -0.072635
Oregon 0.470217
In [10]: type(frame.loc[:,['d']])
Out[10]: pandas.core.frame.DataFrame
</code></pre>
<p>Which returns a <code>DataFrame</code>. So then you can simply do:</p>
<pre><code>In [11]: frame.loc[:,['d']].apply(lambda x: x.max()-x.min())
Out[11]:
d 2.332124
dtype: float64
</code></pre>
<p>Note, for brevity you can simply use <code>frame[['d']]</code>, however, this makes more sense:</p>
<pre><code>In [12]: frame.d.max() - frame.d.min()
Out[12]: 2.3321235565383334
</code></pre>
<p><strong>ETA:</strong> In fact, even for the whole <code>DataFrame</code> you really don't need apply in this case, and it will certainly be slower than the following:</p>
<pre><code>In [19]: frame.max() - frame.min()
Out[19]:
b 3.337040
d 2.332124
e 2.224037
dtype: float64
</code></pre>
| 1 |
2016-09-18T03:54:58Z
|
[
"python",
"pandas",
"lambda"
] |
syntax error near unexpected token while use subprocess
| 39,553,923 |
<p>This design makes me cry,code below,please help</p>
<pre><code>def runbatch(CMD,HOST):
print CMD
print HOST
for host in HOST:
env.host_string=host
print CMD
print env.host_string
print "Execute command : \"%s\" at Host : %s" %(CMD,host)
print "-------------------------------------------------"
p=subprocess.Popen("run('ls')",shell=True,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output = p.communicate()
print output
</code></pre>
<p>error shows</p>
<p><em>(None, "/bin/sh: -c: line 0: syntax error near unexpected token <code>'ls''\n/bin/sh: -c: line 0:</code>run('ls')'\n")</em></p>
| 0 |
2016-09-18T03:54:30Z
| 39,558,590 |
<p><code>subprocess.Popen()</code> runs a bash command on your <strong>local machine</strong>. What <code>fabric</code> has to offer is a way to enter a command on <em>local machine</em> which got sent to and run on a <em>remote machine</em>. To this end, you need a <code>fabfile.py</code> (for now, you need to name it precisely <code>fabfile.py</code>) where you store the fabric <code>fabric.api.run()</code> command, which actually is a Python command and not a bash command. The argument of <code>fabric.api.run()</code> is a bash command that runs on the <em>remote machine</em>. E.g. of a <code>fabfile.py</code></p>
<pre><code>from fabric.api import run
from fabric.api import env
def runcommand():
run(env.my_command)
</code></pre>
<p>Using this example, you could activate this remote call by using command line <code>fab --set my_command=some_bash_command -H remote_host_ip runcommand</code>. This string is the string you should pass to <code>subprocess.Popen()</code> in your script. E.g. let's call your script <code>stackoverflow.py</code> that takes in a command line argument the bash function to be executed on the <em>remote machine</em></p>
<pre><code>import subprocess
import sys
p=subprocess.Popen("fab --set my_command="+sys.argv[1]+" -H localhost runcommand",shell=True,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output = p.communicate()
print output
</code></pre>
<p>Sample run:</p>
<pre><code>Chip chip@ 12:10:58@ ~: python stackoverflow.py ls
[localhost] Executing task 'runcommand'
[localhost] run: ls
[localhost] out: AllArms.py fines
[localhost] out: Applications github
[localhost] out: Box Sync grades_assgn1
[localhost] out: DFExperiment heuristic.py
[localhost] out: Desktop honour-project-in-thompson-sampling
[localhost] out: Documents jags_bin
[localhost] out: Downloads latemath
[localhost] out: Dropbox launchall.sh
[localhost] out: FIT3080 launcher
[localhost] out: GaussianExperiments launchucb.sh
[localhost] out: GoogleDrive minuteSep5
[localhost] out: HierarchicalStan.py minutes22aug
[localhost] out: IMG_6169.JPG model1.pkl
[localhost] out: Library mydata
[localhost] out: Monarch notes15Aug2016
[localhost] out: Movies notesSep12
[localhost] out: Music old-honour
[localhost] out: PTSTuneBeta oracle.R
[localhost] out: Pictures paper
[localhost] out: Public parallelExperiments
[localhost] out: Samsung people_to_mark_first
[localhost] out: WindowFrame.class rezaPhone
[localhost] out: WindowFrame.java spike.py
[localhost] out: a.out stackoverflow.class
[localhost] out: aaai.tar.gz stackoverflow.cpp
[localhost] out: all_experiments stackoverflow.java
[localhost] out: api4.csv stackoverflow.py
[localhost] out: atlas test
[localhost] out: boostlib test.py
[localhost] out: codes_and_data.tar.gz test.txt
[localhost] out: eclipse test1.html
[localhost] out: emo test2.html
[localhost] out: experimentlist testlib.py
[localhost] out: fabfile.py testlib.pyc
[localhost] out: fabfile.pyc uselib.py
[localhost] out: file1 uselib.pyc
[localhost] out: file2
[localhost] out:
Done.
Disconnecting from localhost... done.
(None, "[localhost] Login password for 'hiennguyen': \n")
</code></pre>
<p><strong>IMPORTANT NOTE</strong>: When calling <code>fab</code> this way, you might have to:</p>
<ol>
<li><p>Enable <code>ssh</code> access to your <em>remote machine</em>. In this case, the <em>remote machine</em> is just <code>localhost</code></p></li>
<li><p>Sometimes, the <em>remote host</em> requires you to enter password and you <strong>will not</strong> be prompted to enter password (this is the case on my machine). If you wait for awhile and see nothing, you might want to enter the password then hit ENTER. </p></li>
</ol>
| 0 |
2016-09-18T14:15:36Z
|
[
"python",
"subprocess",
"fabric"
] |
Python module returning True
| 39,554,009 |
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p>
<pre><code>cur_user = "null"
users = {
"Splavacado100": "20310"
}
def login():
good_login = 0
user_name = raw_input("Enter your username: ")
for user in users:
if user == user_name:
good_login = 1
if good_login == 1:
user_password = raw_input("Enter your password: ")
if users[user_name] == user_password:
return True
else:
return False
else:
return "None"
def OS():
log_att = False
log_att = login()
if log_att:
print "True"
else:
print "False"
OS()
</code></pre>
<p>How can I make it return false in those cases?</p>
<p>I am using Python 2.7.10.</p>
| 0 |
2016-09-18T04:10:52Z
| 39,554,045 |
<p>There is something wrong with your second method. I took it out and the first part works. I then took out the last else in the first method and seems to work. Try <a href="https://repl.it/DcBH" rel="nofollow">this</a></p>
<pre><code>cur_user = "null"
users = {
"Splavacado100": "20310"
}
def login():
good_login = 0
user_name = raw_input("Enter your username: ")
for user in users:
if user == user_name:
good_login = 1
if good_login == 1:
user_password = raw_input("Enter your password: ")
if users[user_name] == user_password:
return True
else:
return False
def OS():
log_att = False
log_att = login()
if log_att:
print "True"
else:
print "False"
OS()
</code></pre>
| 0 |
2016-09-18T04:18:35Z
|
[
"python",
"python-2.7"
] |
Python module returning True
| 39,554,009 |
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p>
<pre><code>cur_user = "null"
users = {
"Splavacado100": "20310"
}
def login():
good_login = 0
user_name = raw_input("Enter your username: ")
for user in users:
if user == user_name:
good_login = 1
if good_login == 1:
user_password = raw_input("Enter your password: ")
if users[user_name] == user_password:
return True
else:
return False
else:
return "None"
def OS():
log_att = False
log_att = login()
if log_att:
print "True"
else:
print "False"
OS()
</code></pre>
<p>How can I make it return false in those cases?</p>
<p>I am using Python 2.7.10.</p>
| 0 |
2016-09-18T04:10:52Z
| 39,554,051 |
<p>Instead of returning "None", return None (as "None" is always true as it is a non-zero value).</p>
| 3 |
2016-09-18T04:19:13Z
|
[
"python",
"python-2.7"
] |
Python module returning True
| 39,554,009 |
<p>I'm writing Python for a kind of computer, and the login module always returns true, even if it's not in the <code>users</code> dictionary:</p>
<pre><code>cur_user = "null"
users = {
"Splavacado100": "20310"
}
def login():
good_login = 0
user_name = raw_input("Enter your username: ")
for user in users:
if user == user_name:
good_login = 1
if good_login == 1:
user_password = raw_input("Enter your password: ")
if users[user_name] == user_password:
return True
else:
return False
else:
return "None"
def OS():
log_att = False
log_att = login()
if log_att:
print "True"
else:
print "False"
OS()
</code></pre>
<p>How can I make it return false in those cases?</p>
<p>I am using Python 2.7.10.</p>
| 0 |
2016-09-18T04:10:52Z
| 39,554,094 |
<p>I think your login function should look more like;</p>
<pre><code>def login():
raw_user = raw_input("Enter your username: ")
password = users.get(raw_user)
if not password:
return False
raw_password = raw_input("Enter your password: ")
if password == raw_password:
return True
return False
</code></pre>
<p>Then your second function can be simplified:</p>
<pre><code>def OS():
if login():
print "True"
else:
print "False"
</code></pre>
| 0 |
2016-09-18T04:27:02Z
|
[
"python",
"python-2.7"
] |
Django: Trouble with named URLs instead of ids
| 39,554,208 |
<p>So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like</p>
<pre><code>localhost:8000/subjects/Biology/unit-one/
</code></pre>
<p>Here is my code</p>
<p>views.py</p>
<pre><code>class IndexView(generic.ListView):
template_name = 'card/index.html'
context_object_name = 'subjects'
def get_queryset(self):
return Subject.objects.all()
class SubjectView(DetailView):
model = Subject
slug_field = "subject"
template_name = 'card/subject.html'
class DeckView(DetailView):
model = Deck
template_name = 'card/deck.html'
def get_object(self, subjects, deck):
subject_obj = Subject.objects.filter(subject_name=subjects).first()
obj = Deck.objects.filter(subject=subject_obj, deck_name=deck).first()
return obj
def get(self, request, subjects, deck):
self.object = self.get_object(subjects, deck)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
</code></pre>
<p>models.py</p>
<pre><code>class Subject(models.Model):
subject_name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.subject_name
def get_absolute_url(self):
return reverse('card:index')
class Deck(models.Model):
deck_name = models.CharField(max_length=100)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
def __str__(self):
return self.deck_name
class Card(models.Model):
term = models.CharField(max_length=100)
definition = models.TextField()
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
def __str__(self):
return self.term
</code></pre>
<p>urls.py</p>
<pre><code>url(r'^subjects/(?P<subject>[\w ]+)/$', views.SubjectView.as_view(), name='subject'),
url(r'^subjects/(?P<subject>[\w ]+)/(?P<deck>[\w ]+)/$', views.DeckView.as_view(), name='deck'),
</code></pre>
<p>index.html</p>
<pre><code><li><a href="{% url 'card:subject' subject.subject_name %}">
</code></pre>
<p>subject.html</p>
<pre><code><ul>
{% for deck in subject.deck_set.all %}
<li><a href="{% url 'card:deck' deck.deck_name %}">{{deck.deck_name}}</a></li>
{% endfor %}
</ul>
</code></pre>
<p>However, I am getting this error.</p>
<pre><code>Generic detail view SubjectView must be called with either an object pk or a slug.
</code></pre>
<p>The index page is showing properly, but when I click on a subject, I get that error. How do I fix this?</p>
| 1 |
2016-09-18T04:45:49Z
| 39,554,276 |
<p>Have you tried setting <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.slug_url_kwarg" rel="nofollow"><code>SubjectView.slug_url_kwarg</code></a>?</p>
| 0 |
2016-09-18T04:59:11Z
|
[
"python",
"django"
] |
Django: Trouble with named URLs instead of ids
| 39,554,208 |
<p>So I'm making a study app that involves flash cards. A user can make subjects and put decks containing cards in them. So for example, in the Biology subject, there would be a Deck called "unit one" and in that deck would be full of cards. The URL for a deck would ideally look like</p>
<pre><code>localhost:8000/subjects/Biology/unit-one/
</code></pre>
<p>Here is my code</p>
<p>views.py</p>
<pre><code>class IndexView(generic.ListView):
template_name = 'card/index.html'
context_object_name = 'subjects'
def get_queryset(self):
return Subject.objects.all()
class SubjectView(DetailView):
model = Subject
slug_field = "subject"
template_name = 'card/subject.html'
class DeckView(DetailView):
model = Deck
template_name = 'card/deck.html'
def get_object(self, subjects, deck):
subject_obj = Subject.objects.filter(subject_name=subjects).first()
obj = Deck.objects.filter(subject=subject_obj, deck_name=deck).first()
return obj
def get(self, request, subjects, deck):
self.object = self.get_object(subjects, deck)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
</code></pre>
<p>models.py</p>
<pre><code>class Subject(models.Model):
subject_name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.subject_name
def get_absolute_url(self):
return reverse('card:index')
class Deck(models.Model):
deck_name = models.CharField(max_length=100)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
def __str__(self):
return self.deck_name
class Card(models.Model):
term = models.CharField(max_length=100)
definition = models.TextField()
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
def __str__(self):
return self.term
</code></pre>
<p>urls.py</p>
<pre><code>url(r'^subjects/(?P<subject>[\w ]+)/$', views.SubjectView.as_view(), name='subject'),
url(r'^subjects/(?P<subject>[\w ]+)/(?P<deck>[\w ]+)/$', views.DeckView.as_view(), name='deck'),
</code></pre>
<p>index.html</p>
<pre><code><li><a href="{% url 'card:subject' subject.subject_name %}">
</code></pre>
<p>subject.html</p>
<pre><code><ul>
{% for deck in subject.deck_set.all %}
<li><a href="{% url 'card:deck' deck.deck_name %}">{{deck.deck_name}}</a></li>
{% endfor %}
</ul>
</code></pre>
<p>However, I am getting this error.</p>
<pre><code>Generic detail view SubjectView must be called with either an object pk or a slug.
</code></pre>
<p>The index page is showing properly, but when I click on a subject, I get that error. How do I fix this?</p>
| 1 |
2016-09-18T04:45:49Z
| 39,554,784 |
<p>Just an assumption. Try by change <code>Char</code> to <code>Slug</code></p>
<pre><code>class Subject(models.Model):
subject_name = models.SlugField(max_length=100)
description = models.TextField()
</code></pre>
<p>Also </p>
<pre><code>slug_field = "subject_name"
</code></pre>
| 1 |
2016-09-18T06:24:11Z
|
[
"python",
"django"
] |
Python3 change string to byte
| 39,554,250 |
<p>I'm using Python3.5 and I want to change <code>\xe1BA\x06\xbe\x084</code> into <code>b'\xe1BA\x06\xbe\x084'</code></p>
<p>But using <code>'\xe1BA\x06\xbe\x084'.encode('ascii')</code> or <code>'\xe1BA\x06\xbe\x084'.encode('utf-8')</code>doesn't work.</p>
<p>In <code>.encode('utf-8')</code>, it will become<br>
<code>b'\xc3\xa1BA\x06\xc2\xbe\x084'</code> differs from<br>
<code>b'\xe1BA\x06\xbe\x084'</code></p>
<p>How to deal with this?</p>
| 2 |
2016-09-18T04:53:56Z
| 39,554,398 |
<p>Use the <code>latin1</code> codec.</p>
<pre><code>>>> '\xe1BA\x06\xbe\x084'.encode('latin1')
b'\xe1BA\x06\xbe\x084'
</code></pre>
<p>The reason why this works (and is the way it is) because originally those bytes sequences were defined to be those characters by the <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="nofollow">ISO-8859-1 standard</a>, and thus encoding them down back using that encoding well, gets you back those exact bytes.</p>
<p>While the other answer is useful (the loop through all available codecs to get all possible output is great), do keep in mind that while other specific codecs will work for some specific strings, it may or may not end up mapping to the identical base "byte" sequence.</p>
<pre><code>>>> '\xfe'.encode('iso8859_9')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/encodings/iso8859_9.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 0: character maps to <undefined>
>>> '\xfe'.encode('latin1')
b'\xfe'
>>>
</code></pre>
<p>Of course, the <code>raw_unicode_escape</code> can be useful if your intent is to encode everything to a form of base byte encoding that also allow anything > <code>\xff</code> to be represented through the <code>\\uXXXX</code> form:</p>
<pre><code>>>> 'ã'.encode('latin1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode character '\u3042' in position 0: ordinal not in range(256)
>>> 'ã'.encode('raw_unicode_escape')
b'\\u3042'
>>>
</code></pre>
<p>Naturally, pick the strategy that makes the most sense for your intent.</p>
| 4 |
2016-09-18T05:23:59Z
|
[
"python",
"unicode",
"utf-8"
] |
Python3 change string to byte
| 39,554,250 |
<p>I'm using Python3.5 and I want to change <code>\xe1BA\x06\xbe\x084</code> into <code>b'\xe1BA\x06\xbe\x084'</code></p>
<p>But using <code>'\xe1BA\x06\xbe\x084'.encode('ascii')</code> or <code>'\xe1BA\x06\xbe\x084'.encode('utf-8')</code>doesn't work.</p>
<p>In <code>.encode('utf-8')</code>, it will become<br>
<code>b'\xc3\xa1BA\x06\xc2\xbe\x084'</code> differs from<br>
<code>b'\xe1BA\x06\xbe\x084'</code></p>
<p>How to deal with this?</p>
| 2 |
2016-09-18T04:53:56Z
| 39,554,513 |
<p>You can try all kind of encodings to see if it match what you want.</p>
<pre><code>s = '\xe1BA\x06\xbe\x084'
code_list = ["ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500",
"cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858",
"cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874",
"cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251",
"cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "euc_jp",
"euc_jis_2004", "euc_jisx0213", "euc_kr", "gb2312", "gbk", "gb18030", "hz", "iso2022_jp",
"iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3", "iso2022_jp_ext",
"iso2022_kr", "latin_1", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6",
"iso8859_7", "iso8859_8", "iso8859_9", "iso8859_10", "iso8859_13", "iso8859_14",
"iso8859_15", "iso8859_16", "johab", "koi8_r", "koi8_u", "mac_cyrillic", "mac_greek",
"mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "ptcp154", "shift_jis",
"shift_jis_2004", "shift_jisx0213", "utf_32", "utf_32_be", "utf_32_le", "utf_16",
"utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", "idna", "mbcs", "palmos",
"punycode", "raw_unicode_escape", "rot_13", "undefined", "unicode_escape",
"base64_codec", "bz2_codec", "hex_codec", "quopri_codec",
"string_escape"]
for i in code_list:
try:
if s.encode(i) == b'\xe1BA\x06\xbe\x084':
print('**{:>20}** ==> {}'.format(i, s.encode(i)))
except Exception as e:
pass
</code></pre>
<p>RESULT:</p>
<pre><code>** cp1252** ==> b'\xe1BA\x06\xbe\x084'
** cp1254** ==> b'\xe1BA\x06\xbe\x084'
** cp1258** ==> b'\xe1BA\x06\xbe\x084'
** latin_1** ==> b'\xe1BA\x06\xbe\x084'
** iso8859_9** ==> b'\xe1BA\x06\xbe\x084'
** palmos** ==> b'\xe1BA\x06\xbe\x084'
** raw_unicode_escape** ==> b'\xe1BA\x06\xbe\x084'
</code></pre>
| 1 |
2016-09-18T05:42:14Z
|
[
"python",
"unicode",
"utf-8"
] |
python 2.7 string reverse
| 39,554,258 |
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p>
<p>For string reverse I mean, for example, given s = "hello", return "olleh". </p>
<pre><code>def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ''
temp = []
result=''
for i in range(len(s)-1,-1,-1):
result += s[i]
return result
</code></pre>
<p>regards,
Lin</p>
| 0 |
2016-09-18T04:55:20Z
| 39,554,273 |
<p>Try recursion</p>
<pre><code>def reverse(str):
if str == "":
return str
else:
return reverse(str[1:]) + str[0]
</code></pre>
| 3 |
2016-09-18T04:58:10Z
|
[
"python",
"python-2.7"
] |
python 2.7 string reverse
| 39,554,258 |
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p>
<p>For string reverse I mean, for example, given s = "hello", return "olleh". </p>
<pre><code>def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ''
temp = []
result=''
for i in range(len(s)-1,-1,-1):
result += s[i]
return result
</code></pre>
<p>regards,
Lin</p>
| 0 |
2016-09-18T04:55:20Z
| 39,554,275 |
<p>Try this:</p>
<pre><code>def reverseString(self, s):
return s[::-1]
</code></pre>
| 6 |
2016-09-18T04:59:09Z
|
[
"python",
"python-2.7"
] |
python 2.7 string reverse
| 39,554,258 |
<p>If I need to implement string reverse by myself in Python 2.7 other than using system library, wondering if any more efficient solutions? I tried my code runs slow for a very long string (e.g. a few thousand characters). Thanks.</p>
<p>For string reverse I mean, for example, given s = "hello", return "olleh". </p>
<pre><code>def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return ''
temp = []
result=''
for i in range(len(s)-1,-1,-1):
result += s[i]
return result
</code></pre>
<p>regards,
Lin</p>
| 0 |
2016-09-18T04:55:20Z
| 39,554,304 |
<h2>EDIT: Actually, I was mistaken</h2>
<p>I did a rough-and-dirty test comparing the two functions and the complexity looks to be the same: linear</p>
<p><a href="http://i.stack.imgur.com/sZttR.png" rel="nofollow"><img src="http://i.stack.imgur.com/sZttR.png" alt="enter image description here"></a></p>
<p>It seems that since Python 2.4, for CPython, there has been an optimisation avoiding the quadratic behavior. See the following answer to a similar question:</p>
<p><a href="http://stackoverflow.com/a/37133870/5014455">http://stackoverflow.com/a/37133870/5014455</a></p>
<p><strong>What I said below is outdated for Python 2.7.</strong></p>
<p>This is going to be O(n^2) because strings are immutable in Python so:</p>
<pre><code>result += s[i]
</code></pre>
<p>Will touch ever element in the resulting string <em>every iteration in the loop</em>. It will be faster to build up a mutable container (e.g. a list) of individual characters and then "".join them at the end.</p>
<pre><code>def reverseString(s):
"""
:type s: str
:rtype: str
"""
if not s:
return ''
result = []
for i in xrange(len(s)-1,-1,-1):
result.append(s[i])
return "".join(result)
</code></pre>
| 2 |
2016-09-18T05:02:55Z
|
[
"python",
"python-2.7"
] |
why it is saying at i have declare kernel
| 39,554,292 |
<pre><code> import numpy as np
from numpy.fft import fft2, ifft2
import cv2
from PIL import Image
def wiener_filter(img,kernel,K = 10):
kernel=([3,1],[2,1])
dummy = np.copy(img)
kernel = np.pad(kernel, [(0, dummy.shape[0] - kernel.shape[0]), (0, dummy.shape[1] - kernel.shape[1])], 'constant')
# Fourier Transform
dummy = fft2(dummy)
kernel = fft2(kernel)
kernel = np.conj(kernel) / (np.abs(kernel) ** 2 + K)
dummy = dummy * kernel
dummy = np.abs(ifft2(dummy))
return np.uint8(dummy)
img = cv2.imread("C:\\Users\\anup\\Desktop\\New folder\\leo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#gray1 = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
kernel=([3,1],[2,1])
fm = wiener_filter(img,kernel)
cv2.imshow("Image", img)
key = cv2.waitKey(0)
</code></pre>
<p>I am trying to implement the Wiener Filter to perform deconvolution on blurred image. My implementation is like this</p>
<p>While implementing this i got error</p>
<pre><code>Traceback (most recent call last):
File "C:\Python27\deblur.py", line 21, in <module>
fm = wiener_filter(img,kernel)
File "C:\Python27\deblur.py", line 8, in wiener_filter
kernel = np.pad(kernel, [(0, dummy.shape[0] - kernel.shape[0]), (0, dummy.shape[1] - kernel.shape[1])], 'constant')
AttributeError: 'tuple' object has no attribute 'shape'
</code></pre>
| 1 |
2016-09-18T05:01:05Z
| 39,554,311 |
<p>There : </p>
<pre><code>def wiener_filter(img,kernel,K = 10):
kernel=([3,1],[2,1])
</code></pre>
<p>You define a function that takes <code>kernel</code> as a parameter and you overwrite it directly.</p>
<p>Then you try to use <code>kernel.shape</code> which obviously doesn't exist in <code>([3,1],[2,1])</code></p>
<p>Apparently, <code>shape</code> is a method used for <code>numpy</code> <code>ndarray</code> objects.
So maybe this works for you : </p>
<pre><code>def wiener_filter(img,kernel,K = 10):
kernel=np.array([[3,1],[2,1]])
</code></pre>
<p>Or as mentionned by @Eric :</p>
<pre><code>def wiener_filter(img,kernel,K = 10):
kernel=np.array(kernel)
</code></pre>
| 2 |
2016-09-18T05:04:13Z
|
[
"python",
"numpy"
] |
Laser Detection Sensor
| 39,554,399 |
<p><br />
I have been trying to work on a project that requires me to know when a laser is being hit into a sensor. Unfortunately, I am not able to find such a product that gives an output current when it is hit by a laser to be used with a Raspberry Pi/Arduino. I heard of Laser Break Beam Sensors, but I do not want to purchase the wrong thing.</p>
<p>Would anyone know of a sensor of sorts? And possibly a controllable laser to go with?</p>
<p>Thanks.</p>
| -1 |
2016-09-18T05:24:01Z
| 39,554,494 |
<p>Look into a standard LED. They can produce a current when hit with a laser. Or a small solar panel might work better. You can then interpret this using a python script and GPIO from the Raspberry Pi. The laser can also be wired from a GPIO and controlled from software.</p>
| 2 |
2016-09-18T05:39:35Z
|
[
"python",
"arduino",
"raspberry-pi",
"raspberry-pi2",
"electronics"
] |
How can I find the position in a list where an item differs from the previous item?
| 39,554,417 |
<pre><code>l1 = [1,2,2,2]
</code></pre>
<p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
| 0 |
2016-09-18T05:26:53Z
| 39,554,492 |
<p>Try this: </p>
<pre><code>l1.index(min(set(l1), key=l1.count))
</code></pre>
<p>EDIT:</p>
<p>The lambda expression <code>min(set(l1), key=l1.count)</code> tells us what is the element that occurs the fewest number of times in the list. Then we use <code>l1.index</code> to figure out the position of that element in the list.</p>
| 2 |
2016-09-18T05:39:11Z
|
[
"python"
] |
How can I find the position in a list where an item differs from the previous item?
| 39,554,417 |
<pre><code>l1 = [1,2,2,2]
</code></pre>
<p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
| 0 |
2016-09-18T05:26:53Z
| 39,554,525 |
<p>Try this:</p>
<pre><code>l1 = [1,2,2,2]
for pos, i in enumerate(l1):
if l1.count(i)==1:
print pos
</code></pre>
| 0 |
2016-09-18T05:44:32Z
|
[
"python"
] |
How can I find the position in a list where an item differs from the previous item?
| 39,554,417 |
<pre><code>l1 = [1,2,2,2]
</code></pre>
<p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
| 0 |
2016-09-18T05:26:53Z
| 39,554,548 |
<pre><code>import numpy as np
UniqueList, indices = np.unique(l1, return_inverse=True)
print(UniqueList) #Unique elements in List l1
</code></pre>
<p>array([1, 2])</p>
<pre><code>print(indices) #indices of element in l1 mapped to UniqueList
</code></pre>
<p>array([0, 1, 1, 1])</p>
| 1 |
2016-09-18T05:48:08Z
|
[
"python"
] |
How can I find the position in a list where an item differs from the previous item?
| 39,554,417 |
<pre><code>l1 = [1,2,2,2]
</code></pre>
<p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
| 0 |
2016-09-18T05:26:53Z
| 39,554,710 |
<p>Assuming you need to show indexes of <strong><em>all</em></strong> occurrences where items change:</p>
<pre><code>l = [1 ,2, 2, 3, 3, 1, 1]
changes = [i for i, n in list(enumerate(l))[1:] if l[i] != l[i-1]]
print(changes)
> [1, 3, 5]
</code></pre>
<p>This simply compares each item from the list with the previous one, lists where elements differ.</p>
| 0 |
2016-09-18T06:12:26Z
|
[
"python"
] |
How can I find the position in a list where an item differs from the previous item?
| 39,554,417 |
<pre><code>l1 = [1,2,2,2]
</code></pre>
<p>In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?</p>
| 0 |
2016-09-18T05:26:53Z
| 39,555,376 |
<p>Using a modification of <code>itertools</code> recipe <code>unique_everseen</code> for a solution that keeps track of new entries in a list.</p>
<pre><code>from itertools import ifilterfalse
def unique_everseen(iterable, key=None, per_index=False):
"List unique elements, preserving order. Remember all elements ever seen.
Use per_index=True to return indices instead of elements."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
# unique_everseen('ABBCcAD', str.lower, True) --> 0 1 3 6
seen = set()
seen_add = seen.add
if key is None:
for index, element in enumerate(ifilterfalse(seen.__contains__, iterable)):
seen_add(element)
yield element if not per_index else index
else:
for index, element in enumerate(iterable):
k = key(element)
if k not in seen:
seen_add(k)
yield element if not per_index else index
</code></pre>
<p>To try it out on your example:</p>
<pre><code>list(unique_everseen(l1, per_index=True)) # returns [0, 1]
</code></pre>
| 0 |
2016-09-18T07:56:05Z
|
[
"python"
] |
Odoo v9 - Set a dynamic domain when EDITING a form (not creating)
| 39,554,587 |
<p>Lets say you are setting a field called "Animal Type", and there is a field dependent upon this called "Favorite toy". If the "Animal Type" is a dog, I'd want to set the domain of "Favorite toy" to something like ('isdogtoy','=',True). If its a cat, then maybe we set it to False or some other condition.</p>
<p>Normally to set dynamic domains, you'd use onchange, and then set the domain for the field.</p>
<p>However, there are cases where nothing changes. For instance, if you edit an existing record, onchange isn't necessarily called. If I never change the "Animal Type", then my domain on "Favorite Toy" is never set through my onchange method. </p>
<p>I'm not sure how we do this dynamically in Odoo. It seems like there obviously should be a way, but I can't find anything on this. </p>
| 1 |
2016-09-18T05:54:21Z
| 39,587,047 |
<p>This is the best that I could come up with, using a computed field. Here is an example solution from my code</p>
<p>In my XML,</p>
<pre><code> <field name="uom_id" position="replace">
<!-- The category_id.name is really only used to filter when islocaluom=True. The result is that if a uom_class is used, only uom's from that class can be selected. Otherwise, the default uom's are present -->
<field name="uom_id" groups="product.group_uom" domain="['&amp;',('islocaluom','=',calcislocaluom),'|',('islocaluom','=',False),('category_id','=',calccatidname)]" options="{'no_create' : True},{'no_create_edit' : True}" />
</field>
</code></pre>
<p>Now I just created some computed fields using store=True, and then set them in the compute functions.</p>
<pre><code>class ProductTemplate(models.Model):
_inherit = 'product.template'
#This field will let us choose if we are using per product uom on the product
uom_class = fields.Many2one('productuom.class', 'Per Product UOM Conversion Class', ondelete='restrict',required=False, help="Unit of Measure class for Per Product UOM")
#These computed fields are for calculating the domain on a form edit
calcislocaluom = fields.Boolean('Find if its a localuom',compute='_computelocaluom', store=True, default=False)
calccatidname = fields.Char('Find the name of the category id', compute='_computecatidname', store=True,default=True)
#[...] other code removed
@api.one
@api.depends('uom_class')
def _computelocaluom(self):
if (self.uom_class):
self.calcislocaluom = True
return True
else:
self.calcislocaluom = False
return False
@api.one
@api.depends('uom_class')
def _computecatidname(self):
if (self.uom_class):
self.calccatidname = self.uom_class.name
return self.uom_class.name
else:
#Due to the conditions we later impose within the view, we need to specify a category name that will always be there
self.calccatidname = "Unsorted/Imported Units"
return True
</code></pre>
<p>I'm going to hold off on marking this as a correct answer, because its hard enough to create statically defined domains that actually do what I want them to, and act dynamically depending on the data.... but having to make these complicated statements in reverse polish notation is just torture.</p>
| 0 |
2016-09-20T06:22:48Z
|
[
"python",
"openerp",
"views"
] |
If statement with input check with incorrect outputs
| 39,554,637 |
<p>Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses <code>webbrowser</code>. It may be a dirty script and I would love input like "you should do <em>this</em>", "<em>this</em> can be simplified". The thing i cant figure out is using <code>if</code> statement to handle incorrect input, prompt, then recheck the if statement. I tried searching but nothing assisted in this.</p>
<pre><code>import webbrowser
a = input ('Do you want to search?(y or n)')
if a == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
else:
x = input('Where do you want to go?: ')
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = x
webbrowser.open(url)
</code></pre>
<p>The question is: How do i ether do a recurring that will handle incorrect answers. If they use something other then the listed yes, it will print <code>please use ('y' or 'yes' or 'Y' or 'Yes' or 'YES')</code>, then prompt again and allow for input. I know i will have to change it to a nested if statement to allow the same with no to move to next. Also as is, when i use the code and enter <code>'y'</code> it will open with my default (firefox), but if i enter anything else, it only opens in IE without the google search but "searching" like <code>http://fun/</code> instead of <code>https://www.google.com//search?q=fun</code> as it should.<br>
What did leave out? Also if you could post information on in-depth the meaning behind the code to help further learning. Thank you all!</p>
| 1 |
2016-09-18T06:02:19Z
| 39,554,715 |
<p>There's a different way to check if the value is one of the given values. You should make your if condition be like this:</p>
<pre><code>if a in ('y', 'yes', 'Y', 'Yes', 'YES'):
</code></pre>
<p>It is fast and understandable. </p>
<p>Here's a reason why your condition does not work.<br>
Let's say we entered <code>'no'</code>. Let's see what happens in your if statement:<br>
1. First, the <code>('y' or 'yes' or 'Y' or 'Yes' or 'YES')</code> is evaluated. Since a non-empty string in Python converts to <code>True</code>, this part evaluates <strong>entirely</strong> to <code>True</code><br>
2. Then, the comparison takes place. It looks like this:</p>
<pre><code>if a == True:
</code></pre>
<p>With <code>a</code> being a string <code>'no'</code>. That's obviously not what you want. Use the method a described above and everything will be fine</p>
<p>To constantly re-ask until a correct input is received, try an endless loop with a <code>break</code> statement:</p>
<pre><code>while True:
a = input()
if a in ...:
# process input
break
else:
print("please use 'y' or 'yes' or 'Y' or 'Yes' or 'YES'")
</code></pre>
| 1 |
2016-09-18T06:13:35Z
|
[
"python",
"if-statement",
"python-3.4"
] |
If statement with input check with incorrect outputs
| 39,554,637 |
<p>Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses <code>webbrowser</code>. It may be a dirty script and I would love input like "you should do <em>this</em>", "<em>this</em> can be simplified". The thing i cant figure out is using <code>if</code> statement to handle incorrect input, prompt, then recheck the if statement. I tried searching but nothing assisted in this.</p>
<pre><code>import webbrowser
a = input ('Do you want to search?(y or n)')
if a == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
else:
x = input('Where do you want to go?: ')
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = x
webbrowser.open(url)
</code></pre>
<p>The question is: How do i ether do a recurring that will handle incorrect answers. If they use something other then the listed yes, it will print <code>please use ('y' or 'yes' or 'Y' or 'Yes' or 'YES')</code>, then prompt again and allow for input. I know i will have to change it to a nested if statement to allow the same with no to move to next. Also as is, when i use the code and enter <code>'y'</code> it will open with my default (firefox), but if i enter anything else, it only opens in IE without the google search but "searching" like <code>http://fun/</code> instead of <code>https://www.google.com//search?q=fun</code> as it should.<br>
What did leave out? Also if you could post information on in-depth the meaning behind the code to help further learning. Thank you all!</p>
| 1 |
2016-09-18T06:02:19Z
| 39,554,860 |
<p>The following code should work:</p>
<pre><code>import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a[0].lower()
if a in "y":
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a not in "n":
print "Please only enter 'y' or 'n'."
</code></pre>
<p>The <strong><em>while</em></strong> loop tells python to loop as long as the answer is not "n".</p>
<p>The <strong><em>a = a[0]</em></strong> tells python to only use the first letter of the response. This is to make the comparison easier later on.</p>
<p>The <strong><em>.lower()</em></strong> code tells python to convert the result to lowercase. Again, this is to make the comparison easier later on.</p>
<p>Now our answer will always be lowercase, and the first letter entered. So y ,yes, Yes, YES and n, no, No, NO will be converted to y or n. Of course, any other text will be treated the same way (lowercase and first character), but we only care about y and n.</p>
<p>The rest should be pretty straightforward. Since we have limited the possibilities of what the answer can be, we can do a simple comparison.</p>
<p>Below are modifications to check for only yes and no:</p>
<pre><code>import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a.lower()
if a in ("y", "yes"):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a in "no"
a = "n"
elif a not in ("n", "no"):
print "Please only enter 'y' or 'n'."
</code></pre>
| 1 |
2016-09-18T06:35:53Z
|
[
"python",
"if-statement",
"python-3.4"
] |
np arrays being immutable - "assignment destination is read-only"
| 39,554,660 |
<p>FD** - I am a Python newb as well as a stack overflow newb as you can tell. I have edited the question based on comments.</p>
<p>My goal is to read a set of PNG files, create Image(s) with Image.open('filename') and convert them to simple 2D arrays with only 1s and 0s. The PNG is of the format RGBA with mostly only 255 and 0 as values. Quite often in the images, the edges are grey scale values, which I would like to avoid in the 2D array. </p>
<p>I created the 2D array from image using np.asarray(Image) getting only the 'Red' channel. In each of the 2d image array, I would like to set the cell value = 1 if the current value is non zero.</p>
<p>So, I loop into the 2d array and I check the cell value and try to set it to 1.</p>
<p>It gives me an error indicating that the array is read-only. I read through several stack overflow threads discussing that np arrays are immutable and it is a still bit unclear. I use PIL and numpy</p>
<p>Thanks @user2314737. I will attempt to set that flag.
@Eric, thanks for your comments as well. </p>
<pre><code>from PIL import Image
import numpy as np
</code></pre>
<p>The relevant code:</p>
<pre><code>prArray = [np.asarray(img)[:, :, 0] for img in problem_images]
for img in prArray:
for x in range(184):
for y in range(184):
if img[x][y] != 0:
img[x][y] = 1
</code></pre>
<p>The error "assignment destination is read-only" is in the last line.</p>
<p>Thank you everyone for help. </p>
| 2 |
2016-09-18T06:05:54Z
| 39,554,807 |
<p>Check if the array is writable with</p>
<pre><code>>>> img.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : True
UPDATEIFCOPY : False
</code></pre>
<p>If <code>WRITEABLE</code>is false, change it with</p>
<pre><code>img.setflags(write=1)
</code></pre>
| 2 |
2016-09-18T06:26:50Z
|
[
"python",
"arrays",
"numpy"
] |
geeksforgeeks practice: how to take inputs?
| 39,554,767 |
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p>
<p>I use Python. The default code does not have anything. How should I take my inputs and return my outputs? </p>
| -2 |
2016-09-18T06:22:22Z
| 39,554,816 |
<p>Cool! I hope you've had fun so far!</p>
<p>Python makes these operations quite easy. Both of the functions you'll want to start with are builtins, so you don't even need to <code>import</code> anything!</p>
<p>For inputs, this is probably best handled with <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow"><code>input()</code></a>.</p>
<p>The <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow"><code>print()</code></a> function prints output.</p>
| 3 |
2016-09-18T06:28:25Z
|
[
"python"
] |
geeksforgeeks practice: how to take inputs?
| 39,554,767 |
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p>
<p>I use Python. The default code does not have anything. How should I take my inputs and return my outputs? </p>
| -2 |
2016-09-18T06:22:22Z
| 39,554,854 |
<p>To take user input, use the <code>input()</code> function. For displaying output to user, use the <code>print()</code> function</p>
<pre><code>originalString = input('Enter The String : ')
# Perform manipulations here
print('Modified String is : ', modifiedString)
</code></pre>
| 3 |
2016-09-18T06:34:46Z
|
[
"python"
] |
geeksforgeeks practice: how to take inputs?
| 39,554,767 |
<p>I am trying to code in geeksforgeeks practice in this link: <a href="http://www.practice.geeksforgeeks.org/problem-page.php?pid=282" rel="nofollow">http://www.practice.geeksforgeeks.org/problem-page.php?pid=282</a></p>
<p>I use Python. The default code does not have anything. How should I take my inputs and return my outputs? </p>
| -2 |
2016-09-18T06:22:22Z
| 39,555,423 |
<p>hope it work for you :</p>
<pre><code>T = int(raw_input())
if T < 0 or T > 10 :
print '0<=T<=10 !'
exit(0)
for x in xrange(T):
print '.'.join(str(raw_input()).split('.')[::-1])
</code></pre>
| 0 |
2016-09-18T08:02:57Z
|
[
"python"
] |
Bind acl file generate from CSV ip list using bash
| 39,554,782 |
<p>I would like to generate geoiplist.acl file from a csv file. acl file format:</p>
<pre><code>acl "A1" {
31.14.133.39/32;
37.221.172.0/23;
acl "A2" {
5.145.149.142/32;
57.72.6.0/24;
......
</code></pre>
<p>the csv file: <a href="http://download.db-ip.com/free/dbip-country-2016-09.csv.gz" rel="nofollow">http://download.db-ip.com/free/dbip-country-2016-09.csv.gz</a></p>
<p>Here are sample lines from CSV file with IP_Start, IP_End and Country columns.</p>
<pre><code>"0.0.0.0","0.255.255.255","US"
"1.0.0.0","1.0.0.255","AU"
"1.0.1.0","1.0.3.255","CN"
"1.0.4.0","1.0.7.255","AU"
"1.0.8.0","1.0.15.255","CN"
"1.0.16.0","1.0.31.255","JP"
"1.0.32.0","1.0.63.255","CN"
"1.0.64.0","1.0.127.255","JP"
"1.0.128.0","1.0.255.255","TH"
"1.1.0.0","1.1.0.255","CN"
</code></pre>
<p>I got some references from here: <a href="http://geoip.site/" rel="nofollow">http://geoip.site/</a> but their acl don't have complete list.</p>
<p>Anyone can help me to do this in bash code please. Thanks in advance.</p>
| -1 |
2016-09-18T06:24:04Z
| 39,563,512 |
<p>The issue here is that DB-IP provide the begin and end value of each range in human readable IP address format. Why they have done this, I'm not sure, because the more universal (easier to process) format is to simply present these values in integer form.</p>
<p>In any case, I have modified the Python script on <a href="http://geoip.site/" rel="nofollow">http://geoip.site/</a> to handle this and included the DB-IP database URL within the script; the ACL file generated from their CSV file is now also available to download from <a href="http://geoip.site/download/DB-IP/GeoIP.acl" rel="nofollow">http://geoip.site/download/DB-IP/GeoIP.acl</a></p>
<p>Note I have already identified some issues with this database:</p>
<ol>
<li>The entry <code>"::","2001:1ff:ffff:ffff:ffff:ffff:ffff:ffff","US"</code> exists in it. This is obviously complete rubbish and also broke the Python script (I've improved the error detection code to handle this) and is also one of the reasons for point 4 below.</li>
<li><code>"224.0.0.0","255.255.255.255","CH"</code> is an interesting entry. I'm not entirely sure how they have deemed the entire multicast block of the IPv4 address space to be delegated to Switzerland, or why it exists in their database at all.</li>
<li>The statistical analysis (available on <a href="http://geoip.site/" rel="nofollow">http://geoip.site/</a>) suggests that their DB/CSV file spans 100% of the IPv4 address space outside <code>224.0.0.0/3</code> (multicast). That's 3,758,096,384 addresses. But we already know that several address blocks should not exist in here, the obvious ones being <code>10.0.0.0/8</code>, <code>172.16.0.0/12</code> and <code>192.168.0.0/16</code> (and indeed others; further investigation reveals the entry <code>"192.168.0.0","192.169.31.255","US"</code> exists, which covers <code>192.168.0.0/16</code> and beyond). So this result looks questionable.</li>
<li>The statistical analysis also reports that their DB/CSV spans 100% of the IPv6 address space. This is primarily because they have mapped <code>3000::/4</code> (and various other smaller address blocks) to the <code>US</code>, which is wrong (see <a href="http://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml" rel="nofollow">http://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml</a> where <code>3000::/4</code> is listed as <code>RESERVED</code>). This mapping originates from the entry <code>"2c10::","ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff","US"</code>. The other 2 databases on <a href="http://geoip.site/" rel="nofollow">http://geoip.site/</a> are nowhere close to this magnitude of coverage across the IPv6 address space (both are currently less than 0.1%), so this result also looks questionable.</li>
</ol>
<p>Given all of the above, I would question the accuracy of their database and contact them about it. But feel free to download the <a href="http://geoip.site/download/DB-IP/GeoIP.acl" rel="nofollow">http://geoip.site/download/DB-IP/GeoIP.acl</a> file if you wish to use it.</p>
<p>Finally, I would not have even attempted this in BASH. The conversions required to produce this file from their CSV file are only available in more advanced languages like Python; BASH just wouldn't cut this (well, not my BASH).</p>
<p>I hope this has helped resolved your query/problem.</p>
| 0 |
2016-09-18T23:14:08Z
|
[
"python",
"bash",
"csv",
"bind9"
] |
Aggregate function to data frame in pandas
| 39,554,806 |
<p>I want to create a dataframe from an aggregate function. I thought that it would create by default a dataframe as this solution states, but it creates a series and I don't know why (<a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">Converting a Pandas GroupBy object to DataFrame</a>).</p>
<p>The dataframe is from Kaggle's San Francisco Salaries. My code:</p>
<pre><code>df=pd.read_csv('Salaries.csv')
in: type(df)
out: pandas.core.frame.DataFrame
in: df.head()
out: EmployeeName JobTitle TotalPay TotalPayBenefits Year Status 2BasePay 2OvertimePay 2OtherPay 2Benefits 2Year
0 NATHANIEL FORD GENERAL MANAGER-METROPOLITAN TRANSIT AUTHORITY 567595.43 567595.43 2011 NaN 167411.18 0.00 400184.25 NaN 2011-01-01
1 GARY JIMENEZ CAPTAIN III (POLICE DEPARTMENT) 538909.28 538909.28 2011 NaN 155966.02 245131.88 137811.38 NaN 2011-01-01
2 ALBERT PARDINI CAPTAIN III (POLICE DEPARTMENT) 335279.91 335279.91 2011 NaN 212739.13 106088.18 16452.60 NaN 2011-01-01
3 CHRISTOPHER CHONG WIRE ROPE CABLE MAINTENANCE MECHANIC 332343.61 332343.61 2011 NaN 77916.00 56120.71 198306.90 NaN 2011-01-01
4 PATRICK GARDNER DEPUTY CHIEF OF DEPARTMENT,(FIRE DEPARTMENT) 326373.19 326373.19 2011 NaN 134401.60 9737.00 182234.59 NaN 2011-01-01
in: df2=df.groupby(['JobTitle'])['TotalPay'].mean()
type(df2)
out: pandas.core.series.Series
</code></pre>
<p>I want df2 to be a dataframe with the columns 'JobTitle' and 'TotalPlay'</p>
| 0 |
2016-09-18T06:26:34Z
| 39,554,857 |
<p>Breaking down your code:</p>
<pre><code>df2 = df.groupby(['JobTitle'])['TotalPay'].mean()
</code></pre>
<p>The <code>groupby</code> is fine. It's the <code>['TotalPay']</code> that is the misstep. That is telling the <code>groupby</code> to only execute the the <code>mean</code> function on the <code>pd.Series</code> <code>df['TotalPay']</code> for each group defined in <code>['JobTitle']</code>. Instead, you want to refer to this column with <code>[['TotalPay']]</code>. Notice the double brackets. Those double brackets say <code>pd.DataFrame</code>.</p>
<hr>
<h3>Recap</h3>
<pre><code>df2 = df2=df.groupby(['JobTitle'])[['TotalPay']].mean()
</code></pre>
| 1 |
2016-09-18T06:35:31Z
|
[
"python",
"pandas",
"dataframe",
"aggregate-functions",
"series"
] |
Retrieving specific data from a .json file more efficiently?
| 39,554,826 |
<p>I have the following <code>.json</code> file, which have some lists like values in some elements:</p>
<pre><code>{
"paciente": [
{
"id": 1234,
"nombre": "Pablo",
"sesion": [
{
"id": 12345,
"juego": [
{
"nombre": "bonzo",
"nivel": [
{
"id": 1234,
"nombre": "caida libre"
}
],
"___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",
"iteraciones": [
{
"victoria": true,
"tiempo": 120
},
{
"victoria": false,
"tiempo": 232
}
]
}
],
"segmento": [
{
"id": 12345,
"nombre": "Hombro",
"movimiento": [
{
"id": 12,
"nombre": "flexion",
"metricas": [
{
"min": 12,
"max": 34,
"media": 23,
"moda": 20
}
]
}
]
}
]
}
]
},
{
"id": 156,
"nombre": "Bernardo",
"sesion": [
{
"id": 456,
"juego": [
{
"nombre": "Rita",
"nivel": [
{
"id": 1,
"nombre": "NAVEGANDO"
}
],
"___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",
"iteraciones": [
{
"victoria": true,
"tiempo": 120
},
{
"victoria": false,
"tiempo": 232
}
]
}
],
"segmento": [
{
"id": 12345,
"nombre": "Escapula",
"movimiento": [
{
"id": 12,
"nombre": "Protracción",
"metricas": [
{
"min": 12,
"max": 34,
"media": 23,
"moda": 20
}
]
}
]
}
]
}
]
}
]
}
</code></pre>
<p>From my script, I want to go through it's different nested elements for get specific information</p>
<pre><code>import json
with open('myfile.json') as data_file:
data = json.loads(data_file.read())
patient_id = data["paciente"][0]["id"]
patient_name = data["paciente"][0]["nombre"]
id_session = data["paciente"][0]["sesion"][0]["id"]
game_session = data["paciente"][0]["sesion"][0]["juego"][0]["nombre"]
level_game = data["paciente"][0]["sesion"][0]["juego"][0]["nivel"][0]["nombre"]
iterations = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"]
iterations_victory = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["victoria"]
iterations_time = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["tiempo"]
iterations_victory1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["victoria"]
iterations_time1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["tiempo"]
segment = data["paciente"][0]["sesion"][0]["segmento"][0]["nombre"]
movement = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["nombre"]
#metrics = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"]
metric_min = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["min"]
metric_max = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["max"]
metric_average = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["media"]
metric_moda = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["moda"]
print(
'Patient ID:', patient_id,'\n',
'Patient Name:', patient_name, '\n',
'Session:','\n',
' Id Session:',id_session,'\n',
' Game:', game_session, '\n',
' Level:', level_game, '\n',
' Iterations:', len(iterations),'\n',
' Victory:', iterations_victory, '\n',
' Time:', iterations_time, '\n',
' Victory:', iterations_victory1, '\n',
' Time:', iterations_time1, '\n',
' Affected Segment:', segment, '\n',
' Movement:', movement, '\n',
' Metrics:','\n',
' Minimum:', metric_min, '\n'
' Maximum:', metric_max, '\n'
' Average:', metric_average, '\n'
' Moda/Trend:', metric_moda, '\n'
)
</code></pre>
<p>This is my output:</p>
<pre class="lang-none prettyprint-override"><code>Patient ID: 1234
Patient Name: Pablo
Session:
Id Session: 12345
Game: bonzo
Level: caida libre
Iterations: 2
Victory: True
Time: 120
Victory: False
Time: 232
Affected Segment: Hombro
Movement: flexion
Metrics:
Minimum: 12
Maximum: 34
Average: 23
Moda/Trend: 20
[Finished in 0.0s]
</code></pre>
<p>Is it possible to optimize this code?
How to can I make this code more readable or short?</p>
<p>I would like especially when I will have query for more of one element (just in case of that exist) in the lists/arrays like as segment, movement, iterations, games, etc</p>
<p>Any orientation is welcome.</p>
| 0 |
2016-09-18T06:29:12Z
| 39,555,610 |
<p>Depending on what else your program is doing, it may or may not matter if you speed the code up. You should use the <code>profile</code> or <code>cProfile</code> module to find out where your script is spending its time and work on those.</p>
<p>Regardless, you could save some processing time by removing all the redundant indexing operations by using temporary variable to hold the result. You can think of this simple as the removal of common prefixes. It's relatively easy if you've got a good code editor.</p>
<p>Although it may not be shorter or more readable code, it likely will execute faster (although there is some overhead involved).</p>
<p>Here's what I'm describing:</p>
<pre><code>import json
with open('myfile.json') as data_file:
data = json.loads(data_file.read())
patient0_data = data["paciente"][0]
patient_id = patient0_data["id"]
patient_name = patient0_data["nombre"]
patient0_data_sesion0 = patient0_data["sesion"][0]
id_session = patient0_data_sesion0["id"]
patient0_data_sesion0_juego0 = patient0_data_sesion0["juego"][0]
game_session = patient0_data_sesion0_juego0["nombre"]
level_game = patient0_data_sesion0_juego0["nivel"][0]["nombre"]
iterations = patient0_data_sesion0_juego0["iteraciones"]
patient0_data_sesion0_juego0_iteraciones = patient0_data_sesion0_juego0["iteraciones"]
iterations_victory = patient0_data_sesion0_juego0_iteraciones[0]["victoria"]
iterations_time = patient0_data_sesion0_juego0_iteraciones[0]["tiempo"]
iterations_victory1 = patient0_data_sesion0_juego0_iteraciones[1]["victoria"]
iterations_time1 = patient0_data_sesion0_juego0_iteraciones[1]["tiempo"]
patient0_data_sesion0_segmento0 = patient0_data_sesion0["segmento"][0]
segment = patient0_data_sesion0_segmento0["nombre"]
patient0_data_sesion0_segmento0_movimiento0 = (
patient0_data_sesion0_segmento0["movimiento"][0])
movement = patient0_data_sesion0_segmento0_movimiento0["nombre"]
#metrics = patient0_data_sesion0_segmento0_movimiento0["metricas"]
patient0_data_sesion0_segmento0_movimiento0_metricas0 = (
patient0_data_sesion0_segmento0["movimiento"][0]["metricas"][0])
metric_min = patient0_data_sesion0_segmento0_movimiento0_metricas0["min"]
metric_max = patient0_data_sesion0_segmento0_movimiento0_metricas0["max"]
metric_average = patient0_data_sesion0_segmento0_movimiento0_metricas0["media"]
metric_moda = patient0_data_sesion0_segmento0_movimiento0_metricas0["moda"]
print(
'Patient ID:', patient_id,'\n',
'Patient Name:', patient_name, '\n',
'Session:','\n',
' Id Session:',id_session,'\n',
' Game:', game_session, '\n',
' Level:', level_game, '\n',
' Iterations:', len(iterations),'\n',
' Victory:', iterations_victory, '\n',
' Time:', iterations_time, '\n',
' Victory:', iterations_victory1, '\n',
' Time:', iterations_time1, '\n',
' Affected Segment:', segment, '\n',
' Movement:', movement, '\n',
' Metrics:','\n',
' Minimum:', metric_min, '\n'
' Maximum:', metric_max, '\n'
' Average:', metric_average, '\n'
' Moda/Trend:', metric_moda, '\n'
)
</code></pre>
| 1 |
2016-09-18T08:27:40Z
|
[
"python",
"arrays",
"json"
] |
Retrieving specific data from a .json file more efficiently?
| 39,554,826 |
<p>I have the following <code>.json</code> file, which have some lists like values in some elements:</p>
<pre><code>{
"paciente": [
{
"id": 1234,
"nombre": "Pablo",
"sesion": [
{
"id": 12345,
"juego": [
{
"nombre": "bonzo",
"nivel": [
{
"id": 1234,
"nombre": "caida libre"
}
],
"___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",
"iteraciones": [
{
"victoria": true,
"tiempo": 120
},
{
"victoria": false,
"tiempo": 232
}
]
}
],
"segmento": [
{
"id": 12345,
"nombre": "Hombro",
"movimiento": [
{
"id": 12,
"nombre": "flexion",
"metricas": [
{
"min": 12,
"max": 34,
"media": 23,
"moda": 20
}
]
}
]
}
]
}
]
},
{
"id": 156,
"nombre": "Bernardo",
"sesion": [
{
"id": 456,
"juego": [
{
"nombre": "Rita",
"nivel": [
{
"id": 1,
"nombre": "NAVEGANDO"
}
],
"___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",
"iteraciones": [
{
"victoria": true,
"tiempo": 120
},
{
"victoria": false,
"tiempo": 232
}
]
}
],
"segmento": [
{
"id": 12345,
"nombre": "Escapula",
"movimiento": [
{
"id": 12,
"nombre": "Protracción",
"metricas": [
{
"min": 12,
"max": 34,
"media": 23,
"moda": 20
}
]
}
]
}
]
}
]
}
]
}
</code></pre>
<p>From my script, I want to go through it's different nested elements for get specific information</p>
<pre><code>import json
with open('myfile.json') as data_file:
data = json.loads(data_file.read())
patient_id = data["paciente"][0]["id"]
patient_name = data["paciente"][0]["nombre"]
id_session = data["paciente"][0]["sesion"][0]["id"]
game_session = data["paciente"][0]["sesion"][0]["juego"][0]["nombre"]
level_game = data["paciente"][0]["sesion"][0]["juego"][0]["nivel"][0]["nombre"]
iterations = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"]
iterations_victory = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["victoria"]
iterations_time = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["tiempo"]
iterations_victory1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["victoria"]
iterations_time1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["tiempo"]
segment = data["paciente"][0]["sesion"][0]["segmento"][0]["nombre"]
movement = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["nombre"]
#metrics = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"]
metric_min = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["min"]
metric_max = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["max"]
metric_average = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["media"]
metric_moda = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["moda"]
print(
'Patient ID:', patient_id,'\n',
'Patient Name:', patient_name, '\n',
'Session:','\n',
' Id Session:',id_session,'\n',
' Game:', game_session, '\n',
' Level:', level_game, '\n',
' Iterations:', len(iterations),'\n',
' Victory:', iterations_victory, '\n',
' Time:', iterations_time, '\n',
' Victory:', iterations_victory1, '\n',
' Time:', iterations_time1, '\n',
' Affected Segment:', segment, '\n',
' Movement:', movement, '\n',
' Metrics:','\n',
' Minimum:', metric_min, '\n'
' Maximum:', metric_max, '\n'
' Average:', metric_average, '\n'
' Moda/Trend:', metric_moda, '\n'
)
</code></pre>
<p>This is my output:</p>
<pre class="lang-none prettyprint-override"><code>Patient ID: 1234
Patient Name: Pablo
Session:
Id Session: 12345
Game: bonzo
Level: caida libre
Iterations: 2
Victory: True
Time: 120
Victory: False
Time: 232
Affected Segment: Hombro
Movement: flexion
Metrics:
Minimum: 12
Maximum: 34
Average: 23
Moda/Trend: 20
[Finished in 0.0s]
</code></pre>
<p>Is it possible to optimize this code?
How to can I make this code more readable or short?</p>
<p>I would like especially when I will have query for more of one element (just in case of that exist) in the lists/arrays like as segment, movement, iterations, games, etc</p>
<p>Any orientation is welcome.</p>
| 0 |
2016-09-18T06:29:12Z
| 39,556,022 |
<p>Note that you are omitting the second patient record in your data (Bernardo), and that you assume there are always exactly two iterations. This might not always be true.</p>
<p>When you look for speed, your code is close to the best you can get, but for the above reasons, you would probably do good to add some tests and loops to make sure you cover all data, and not more.</p>
<p>Here is a function you could use to print the data in your format, based on a template you pass it. The template lists all labels you want to use for the keys you want to print the values for. In order to avoid ambiguity, the template needs both the key and the parent key of the elements of interest.</p>
<p>As the function needs to visit the keys in order, <code>OrderedDict</code> is used instead of <code>dict</code>:</p>
<pre><code>import json
from collections import OrderedDict
data = json.loads(data, object_pairs_hook=OrderedDict)
def pretty(template, item, parentName='', name='', indent=0):
label = template.get(parentName + '/' + name)
if label:
label = ' ' * indent + label + ': '
if isinstance(item, list):
label += str(len(item))
elif not isinstance(item, OrderedDict):
label += str(item)
print(label)
if isinstance(item, list):
for value in item:
pretty(template, value, parentName + '[]', name, indent)
elif isinstance(item, OrderedDict):
for key, value in item.items():
pretty(template, value, name, key, indent+1)
template = {
"paciente/id": "Patient ID",
"paciente/nombre": "Patient Name",
"paciente/sesion": "Sessions",
"sesion/id": "Id Session",
"juego/nombre": "Game",
"nivel/nombre": "Level",
"juego/iteraciones": "Iterations",
"iteraciones/victoria": "Victory",
"iteraciones/tiempo": "Time",
"segmento/nombre": "Affected Segment",
"movimiento/nombre": "Movement",
"movimiento/metricas": "Metrics",
"metricas/min": "Minimum",
"metricas/max": "Maximum",
"metricas/media": "Average",
"metricas/moda": "Moda/Trend"
}
pretty(template, data)
</code></pre>
<p>The output is:</p>
<pre class="lang-none prettyprint-override"><code> Patient ID: 1234
Patient Name: Pablo
Sessions: 1
Id Session: 12345
Game: bonzo
Level: caida libre
Iterations: 2
Victory: True
Time: 120
Victory: False
Time: 232
Affected Segment: Hombro
Movement: flexion
Metrics: 1
Minimum: 12
Maximum: 34
Average: 23
Moda/Trend: 20
Patient ID: 156
Patient Name: Bernardo
Sessions: 1
Id Session: 456
Game: Rita
Level: NAVEGANDO
Iterations: 2
Victory: True
Time: 120
Victory: False
Time: 232
Affected Segment: Escapula
Movement: Protracción
Metrics: 1
Minimum: 12
Maximum: 34
Average: 23
Moda/Trend: 20
</code></pre>
| 1 |
2016-09-18T09:19:14Z
|
[
"python",
"arrays",
"json"
] |
Django: Use post() in UpdateView to populate form's fields with instance's existing field values
| 39,554,829 |
<p>I have trouble getting the current instance's fields on my UpdateView. How do I get the specific instance based on its id?</p>
<p><strong>views.py</strong></p>
<pre><code>class ShowUpdate(UpdateView):
model = Show
fields = ['description', 'season', 'episode']
def post(self, request, **kwargs):
request.POST = request.POST.copy()
request.POST['description'] = "how to get instance description?" # problem here
request.POST['season'] = 2
return super(ShowUpdate, self).post(request, **kwargs)
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Show(models.Model):
owner = models.ForeignKey(User, null=True, default=True, related_name='o')
title = models.CharField(max_length=100)
description = models.TextField(default='N/A', blank=True, max_length=250)
season = models.IntegerField(default=0)
episode = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('show:index')
def __str__(self):
return self.title
</code></pre>
| 0 |
2016-09-18T06:29:47Z
| 40,088,457 |
<p>Look to the <a href="http://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/UpdateView/" rel="nofollow">UpdateView</a> docs</p>
<p>This View has method <code>get_object(self, queryset=None)</code></p>
<p>In you case just need to call it in <code>POST</code> method something like this:</p>
<pre><code>class ShowUpdate(UpdateView):
model = Show
fields = ['description', 'season', 'episode']
def post(self, request, **kwargs):
self.object = self.get_object()
request.POST = request.POST.copy()
request.POST['description'] = self.object.description
request.POST['season'] = 2
return super(ShowUpdate, self).post(request, **kwargs)
</code></pre>
| 0 |
2016-10-17T14:00:54Z
|
[
"python",
"django"
] |
CSjark: NameError name 'Platform' is not defined
| 39,554,877 |
<p>I'm usually not working with Python (but have ability to read the code).
I'm trying to use <a href="http://csjark.readthedocs.io/" rel="nofollow">csjark</a>.
All the dependencies were installed correctly.
When executing <code>csjark.py</code> I'm receiving following error: </p>
<pre><code>NameError name 'Platform' is not defined
</code></pre>
<p>The import is done with <code>from platform import Platform</code></p>
<p>All the *.py files are located in the same folder.
I don't have any issue similar statements for other imports.</p>
<p>Importing with <code>import platform</code> is working, but latter I can't use any parameter from the class.</p>
<p>Please suggest ways to resolve the issue with the <a href="https://raw.githubusercontent.com/eventh/kpro9/master/CSjark/csjark/platform.py" rel="nofollow"><code>platform.py</code></a> file.</p>
| -1 |
2016-09-18T06:38:41Z
| 39,554,927 |
<p>Maybe your program is importing the wrong platform.py, for example this one:
<a href="https://docs.python.org/2/library/platform.html" rel="nofollow">https://docs.python.org/2/library/platform.html</a>
which doesn't seem to have a Platform class. Try renaming the platform.py to something else and importing from that to see if this is the issue.</p>
| 1 |
2016-09-18T06:46:42Z
|
[
"python",
"csjark"
] |
Want to choose multiple random numbers from a given list of numbers in python
| 39,554,926 |
<p>In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory answers.for example:</p>
<pre><code>import random
a=['1','2','3','4','5','6','7','8']
b=['4','3','9','2','7','1','6','5']
c=random.sample(a,4)
d=random.sample(b,4)
print "c=",c
print "d=",d
</code></pre>
<p>The code gives me the following result:</p>
<pre><code>c=['4','2','3','8']
d=['1','9','5','4']
</code></pre>
<p>But I want the answer as:</p>
<pre><code>c=['4','5','6','7']
d=['9','2','7','1']
</code></pre>
<p>or</p>
<pre><code>c=['5','6','7','8']
d=['7','1','6','5']
</code></pre>
| -3 |
2016-09-18T06:46:30Z
| 39,554,959 |
<h3>Answer for original version of question:</h3>
<p>To get two samples randomly, use <a href="https://docs.python.org/3/library/random.html" rel="nofollow"><code>random.sample</code></a>. First, lets define a list:</p>
<pre><code>>>> lst = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
</code></pre>
<p>Now, lets get two samples randomly:</p>
<pre><code>>>> random.sample(lst, 2)
[13, 16]
>>> random.sample(lst, 2)
[10, 12]
</code></pre>
<p>Sampling is done without replacement.</p>
| 0 |
2016-09-18T06:50:58Z
|
[
"python",
"python-2.7",
"random"
] |
Want to choose multiple random numbers from a given list of numbers in python
| 39,554,926 |
<p>In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory answers.for example:</p>
<pre><code>import random
a=['1','2','3','4','5','6','7','8']
b=['4','3','9','2','7','1','6','5']
c=random.sample(a,4)
d=random.sample(b,4)
print "c=",c
print "d=",d
</code></pre>
<p>The code gives me the following result:</p>
<pre><code>c=['4','2','3','8']
d=['1','9','5','4']
</code></pre>
<p>But I want the answer as:</p>
<pre><code>c=['4','5','6','7']
d=['9','2','7','1']
</code></pre>
<p>or</p>
<pre><code>c=['5','6','7','8']
d=['7','1','6','5']
</code></pre>
| -3 |
2016-09-18T06:46:30Z
| 40,028,712 |
<p>Looks like you want four <em>consecutive</em> values starting at a random offset, not four values from anywhere in the sequence. So don't use <code>sample</code>, just select a random start point (early enough to ensure the slice doesn't run off the end of the <code>list</code> and end up shorter than desired), then slice four elements off starting there:</p>
<pre><code>import random
...
selectcnt = 4
cstart = random.randint(0, len(a) - selectcnt)
c = a[cstart:cstart + selectcnt]
dstart = random.randint(0, len(b) - selectcnt)
d = b[dstart:dstart + selectcnt]
</code></pre>
<p>You could factor it out to make it a little nicer (allowing you to one-line individual selections):</p>
<pre><code>import random
def get_random_slice(seq, slicelen):
'''Get slicelen items from seq beginning at a random offset'''
start = random.randint(0, len(seq) - slicelen)
return seq[start:start + slicelen]
c = get_random_slice(a, 4)
d = get_random_slice(b, 4)
</code></pre>
| 0 |
2016-10-13T18:48:01Z
|
[
"python",
"python-2.7",
"random"
] |
Python - BeautifulSoup: find td width
| 39,554,944 |
<p>I have many tables and each has table data tag something like this:</p>
<pre><code><td width="563" valign="top" bgcolor="#FFFF99" class="text">
...
<td width="12" bgcolor="#FFFF99" class="lettnav">
<td bgcolor="#FFFF99" class="lettnav">
</code></pre>
<p>The goal is to locate which <code><td></code> with the highest value. To do that, first I want to get the value of the width using beautifulsoap (if no with just print empty string).</p>
<p>Here is my code snippet that so far did not work:</p>
<pre><code>soup = BeautifulSoup(page, 'html.parser')
cells = soup.findAll("td",{"width": re.compile('\d')})
for aCell in cells:
width=aCell.find("width")
print(width)
</code></pre>
<p>Any help?</p>
| 2 |
2016-09-18T06:49:02Z
| 39,555,125 |
<p>In BeautifulSoup attributes are accessed in dict notation (see <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes</a> for more information).</p>
<p>Using <code>width=aCell["width"]</code> your code works:</p>
<pre><code>for aCell in cells:
width=aCell["width"]
print(width)
</code></pre>
<p>If you're just interested in the max value you could also omit the <code>for</code> loop and use a list comprehension instead:</p>
<pre><code>maxwidth = max(int(x["width"]) for x in cells)
</code></pre>
| 0 |
2016-09-18T07:19:27Z
|
[
"python",
"html",
"beautifulsoup"
] |
Python - BeautifulSoup: find td width
| 39,554,944 |
<p>I have many tables and each has table data tag something like this:</p>
<pre><code><td width="563" valign="top" bgcolor="#FFFF99" class="text">
...
<td width="12" bgcolor="#FFFF99" class="lettnav">
<td bgcolor="#FFFF99" class="lettnav">
</code></pre>
<p>The goal is to locate which <code><td></code> with the highest value. To do that, first I want to get the value of the width using beautifulsoap (if no with just print empty string).</p>
<p>Here is my code snippet that so far did not work:</p>
<pre><code>soup = BeautifulSoup(page, 'html.parser')
cells = soup.findAll("td",{"width": re.compile('\d')})
for aCell in cells:
width=aCell.find("width")
print(width)
</code></pre>
<p>Any help?</p>
| 2 |
2016-09-18T06:49:02Z
| 39,556,845 |
<p>To find the <em>td</em> with the largest width you can use <em>max</em> on the list of <em>td's</em> returned from the <em>find_all</em> call, setting the key to <code>key=lambda t: int(t["width"])</code>:</p>
<pre><code>soup = BeautifulSoup(page, 'html.parser')
cells = soup.find_all("td", width=True)
mx_td = max(cells, key=lambda t: int(t["width"]))
</code></pre>
<p><code>t["width"]</code> accesses the <em>attribute</em> value, we need to call <em>int</em> on the result or the value would be compared <a href="https://en.wikipedia.org/wiki/Lexicographical_order" rel="nofollow">lexicographically</a> i.e <code>2 > 100</code> would be True.</p>
| 1 |
2016-09-18T10:51:31Z
|
[
"python",
"html",
"beautifulsoup"
] |
How to reuse a custom @contextlib.contextmanager?
| 39,554,981 |
<p>I'm trying to create a wrapper to make context objects optional. When the condition is true, the thing should behave like the wrapped context object, otherwise it should behave like a no-op context object. This example works for using the wrapped object once, but fails it it is reused.</p>
<p>Example:</p>
<pre><code>import contextlib
from threading import Lock
@contextlib.contextmanager
def conditional_context(context, condition):
if condition and context:
with context:
yield
else:
yield
use_locking = False
lock = conditional_context(Lock(), use_locking)
with lock:
print('Foo')
with lock:
print('Bar')
</code></pre>
<p>Output:</p>
<pre><code>Foo
Traceback (most recent call last):
File "example.py", line 16, in <module>
with lock:
File "/usr/lib/python3.5/contextlib.py", line 61, in __enter__
raise RuntimeError("generator didn't yield") from None
RuntimeError: generator didn't yield
</code></pre>
| 1 |
2016-09-18T06:55:11Z
| 39,555,073 |
<p>You can't do that with <code>contextlib.contextmanager</code>. As mentioned in passing in <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow">the docs</a>, context managers created by contextmanager are one-shot.</p>
<p>You will have to write your own class with <code>__enter__</code> and <code>__exit__</code> methods if you want the same object to be reusable in multiple <code>with</code> statements:</p>
<pre><code>from threading import Lock
class ConditionalContext:
def __init__(self, context, condition):
self._context = context
self._condition = condition
def __enter__(self, *args, **kwargs):
if self._condition:
self._context.__enter__(*args, **kwargs)
def __exit__(self, *args, **kwargs):
if self._condition:
self._context.__exit__(*args, **kwargs)
use_locking = False
lock = ConditionalContext(Lock(), use_locking)
with lock:
print('Foo')
with lock:
print('Bar')
</code></pre>
| 4 |
2016-09-18T07:10:36Z
|
[
"python",
"python-3.x",
"contextmanager"
] |
Pymongo: How to insert an array of multiple fields in a document?
| 39,555,057 |
<p>I am working on <code>MongoDB</code> in <code>python</code> <code>[pymongo]</code>. I want to insert an array of multiple fields in a document. For example: In the below structure of a collection, I want to insert array of <code>Places Visited</code> in all documents. I do not know what it is called in the world of <code>Mongo</code>.So that I may insert it. <strong>How to insert an array in a document?</strong> Can some one help? </p>
<pre><code>collectionName
{
"_id" : "4564345343",
"name": "Bunty",
"Basic Intro": "A.B.C.D.",
"Places Visited": [
"1" : "Palace of Dob",
"2" : "Palace of Victoria",
"3" : "Sahara Desert"
]
}
{
"_id" : "45657865745",
"name": "Humty",
"Basic Intro": "B.C.D.",
"Places Visited": [
"1" : "Palace of Pakistan",
"2" : "Palace of U.S.A."
"3" : "White House"
]
}
</code></pre>
| -1 |
2016-09-18T07:08:22Z
| 39,555,281 |
<p>This should give you the idea how to do it </p>
<pre><code>import pymongo
client = pymongo.MongoClient('yourHost', 30000) # adjust to your needs
db = client.so
coll = db.yourcollection
# show initial data
for doc in coll.find():
print(doc)
# update data
places_visited = [
"Palace of Dob",
"Palace of Victoria",
"Sahara Desert"
]
coll.update({}, { "$set": { "Places Visited": places_visited } }, multi=True)
# show updated data
for doc in coll.find():
print(doc)
</code></pre>
<p>which for your sample data should give output similar to this </p>
<pre class="lang-none prettyprint-override"><code>daxaholic$ python3 main.py
{'name': 'Bunty', 'Basic Intro': 'A.B.C.D.', '_id': '4564345343'}
{'name': 'Humty', 'Basic Intro': 'B.C.D.', '_id': '45657865745'}
{'name': 'Bunty', 'Places Visited': ['Palace of Dob', 'Palace of Victoria', 'Sahara Desert'], 'Basic Intro': 'A.B.C.D.', '_id': '4564345343'}
{'name': 'Humty', 'Places Visited': ['Palace of Dob', 'Palace of Victoria', 'Sahara Desert'], 'Basic Intro': 'B.C.D.', '_id': '45657865745'}
</code></pre>
<p>For further information see the <a href="https://docs.mongodb.com/manual/reference/method/db.collection.update/#db.collection.update" rel="nofollow">docs</a> about <code>update</code></p>
| 1 |
2016-09-18T07:45:18Z
|
[
"python",
"mongodb",
"pymongo"
] |
Can I safely do inference from another thread when using tf.train.Optimizer(use_locking=True)?
| 39,555,060 |
<p>I have several threads that run operation on the same TensorFlow graph. The operations are either inference or optimization of a neural network. I can use the <code>use_locking</code> parameter for the optimizer to prevent concurrent updates of the variables.</p>
<p>However, does this safe me from reading partially updated versions of the weights when doing inference at the same time? If not, how can I ensure this and is a Python lock around all <code>sess.run()</code> a good alternative?</p>
| 0 |
2016-09-18T07:09:02Z
| 39,577,466 |
<p>Do your inference calls need to be on an up-to-date version of the graph? If you don't mind some delay, you could make a copy of the graph by calling sess.graph.as_graph_def on the training thread, and then create a new session on the inference thread using that graph_def periodically.</p>
| 0 |
2016-09-19T16:05:22Z
|
[
"python",
"multithreading",
"thread-safety",
"locking",
"tensorflow"
] |
Python deduplicate records - dedupe
| 39,555,127 |
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p>
<pre><code>data_d = {}
for row in data:
clean_row = [(k, preProcess(v)) for (k, v) in row.items()]
row_id = int(row['id'])
data_d[row_id] = dict(clean_row)
</code></pre>
<p>the dictionary consumes quite a lot of memory compared to e.g. a dictionary created by pandas out of a pd.Datafrmae, or even a normal pd.Dataframe.</p>
<p>If this format is required, how can I convert a pd.Dataframe efficiently to such a dictionary?</p>
<h1>edit</h1>
<p>Example what pandas generates</p>
<pre><code>{'column1': {0: 1389225600000000000,
1: 1388707200000000000,
2: 1388707200000000000,
3: 1389657600000000000,....
</code></pre>
<p>Example what dedupe expects</p>
<pre><code>{'1': {column1: 1389225600000000000, column2: "ddd"},
'2': {column1: 1111, column2: "ddd} ...}
</code></pre>
| 0 |
2016-09-18T07:19:44Z
| 39,555,215 |
<p>It appears that <code>df.to_dict(orient='index')</code> will produce the representation you are looking for:</p>
<p>import pandas</p>
<pre><code>data = [[1, 2, 3], [4, 5, 6]]
columns = ['a', 'b', 'c']
df = pandas.DataFrame(data, columns=columns)
df.to_dict(orient='index')
</code></pre>
<p>results in </p>
<pre><code>{0: {'a': 1, 'b': 2, 'c': 3}, 1: {'a': 4, 'b': 5, 'c': 6}}
</code></pre>
| 2 |
2016-09-18T07:35:38Z
|
[
"python",
"pandas",
"dictionary",
"duplicates",
"dedupeplugin"
] |
Python deduplicate records - dedupe
| 39,555,127 |
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p>
<pre><code>data_d = {}
for row in data:
clean_row = [(k, preProcess(v)) for (k, v) in row.items()]
row_id = int(row['id'])
data_d[row_id] = dict(clean_row)
</code></pre>
<p>the dictionary consumes quite a lot of memory compared to e.g. a dictionary created by pandas out of a pd.Datafrmae, or even a normal pd.Dataframe.</p>
<p>If this format is required, how can I convert a pd.Dataframe efficiently to such a dictionary?</p>
<h1>edit</h1>
<p>Example what pandas generates</p>
<pre><code>{'column1': {0: 1389225600000000000,
1: 1388707200000000000,
2: 1388707200000000000,
3: 1389657600000000000,....
</code></pre>
<p>Example what dedupe expects</p>
<pre><code>{'1': {column1: 1389225600000000000, column2: "ddd"},
'2': {column1: 1111, column2: "ddd} ...}
</code></pre>
| 0 |
2016-09-18T07:19:44Z
| 39,555,259 |
<p>You can try something like this:</p>
<pre><code>df = pd.DataFrame({'A': [1,2,3,4,5], 'B': [6,7,8,9,10]})
A B
0 1 6
1 2 7
2 3 8
3 4 9
4 5 10
print(df.T.to_dict())
{0: {'A': 1, 'B': 6}, 1: {'A': 2, 'B': 7}, 2: {'A': 3, 'B': 8}, 3: {'A': 4, 'B': 9}, 4: {'A': 5, 'B': 10}}
</code></pre>
<p><em>This is the same output as in @chthonicdaemon answer so his answer is probably better. I am using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow">pandas.DataFrame.T</a> to transpose index and columns.</em></p>
| 0 |
2016-09-18T07:42:09Z
|
[
"python",
"pandas",
"dictionary",
"duplicates",
"dedupeplugin"
] |
Python deduplicate records - dedupe
| 39,555,127 |
<p>I want to use <a href="https://github.com/datamade/dedupe" rel="nofollow">https://github.com/datamade/dedupe</a> to deduplicate some records in python. Looking at their examples </p>
<pre><code>data_d = {}
for row in data:
clean_row = [(k, preProcess(v)) for (k, v) in row.items()]
row_id = int(row['id'])
data_d[row_id] = dict(clean_row)
</code></pre>
<p>the dictionary consumes quite a lot of memory compared to e.g. a dictionary created by pandas out of a pd.Datafrmae, or even a normal pd.Dataframe.</p>
<p>If this format is required, how can I convert a pd.Dataframe efficiently to such a dictionary?</p>
<h1>edit</h1>
<p>Example what pandas generates</p>
<pre><code>{'column1': {0: 1389225600000000000,
1: 1388707200000000000,
2: 1388707200000000000,
3: 1389657600000000000,....
</code></pre>
<p>Example what dedupe expects</p>
<pre><code>{'1': {column1: 1389225600000000000, column2: "ddd"},
'2': {column1: 1111, column2: "ddd} ...}
</code></pre>
| 0 |
2016-09-18T07:19:44Z
| 39,558,156 |
<p>A python dictionary is not required, you just need an object that allows indexing by column name. i.e. <code>row['col_name']</code></p>
<p>So, assuming <code>data</code> is a pandas dataframe should just be able to do something like:</p>
<pre><code>data_d = {}
for row_id, row in data.iterrows():
data_d[row_id] = row
</code></pre>
<p>That said, the memory overhead of python dicts is not going to be where you have memory bottlenecks in dedupe.</p>
| 0 |
2016-09-18T13:30:07Z
|
[
"python",
"pandas",
"dictionary",
"duplicates",
"dedupeplugin"
] |
In django how can I make the result of the background program as a record and then insert it to mysql
| 39,555,160 |
<p>In django, I want to make the result of the program in server as a record and then insert it to the mysql, how can I do this?</p>
| 0 |
2016-09-18T07:26:26Z
| 39,559,057 |
<p>If your program is part of django, you can just follow <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#creating-objects" rel="nofollow">Creating objects</a>, if not, you can do something in your program settings:</p>
<pre><code>import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'your_django_project.settings'
django.setup()
</code></pre>
<p>Then you can use django orm as above </p>
| 0 |
2016-09-18T15:00:16Z
|
[
"python",
"django"
] |
AttributeError: instance has no attribute
| 39,555,189 |
<p>This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing. </p>
<p>I'm receiving <strong>AttributeError: WebHandler instance has no attribute 'search_str'</strong> </p>
<p>It seems to be this one particular method, any time I call any of the class variables set in <strong>___init___</strong> from this method I receive this error. I've extracted it to a test file as a simple function rather than a class method and it works fine, and I've tried re-indenting everything a few times to make sure it wasn't that, so I'm at a loss on this.</p>
<p>I'm using Python 2.7 and TextWrangler if either of these are helpful (TextWrangler hasn't given me any problems in 3 years like this, but figured anything should be included)</p>
<pre><code>import requests
import re
class WebHandler():
def ___init___(self):
self.urllist = []
self.search_str = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.I|re.M)
def set_urls(self, test, data):
for line in test[11:]:
if (("even" in line) or ("odd" in line)):
match = re.search(self.search_str, line)
self.urllist.append(match.group(0))
</code></pre>
<p>Another thing I tried, if I copy the attributes from <strong>___init___</strong> and simply make them local to <strong>set_urls()</strong> and call them without <strong>self</strong> that way it works properly and doesn't throw any errors, which is confusing me even more.</p>
<p>No idea what I'm missing. Thanks!</p>
| 1 |
2016-09-18T07:31:11Z
| 39,555,209 |
<p>This that you have:</p>
<pre><code>def ___init___(self):
</code></pre>
<p>Is not the same as this that gets called when an object is instantiated:</p>
<pre><code>def __init__(self):
</code></pre>
<p>The difference is that you have <em>three</em> underscores on either side of <code>init</code>, while two are required.</p>
| 2 |
2016-09-18T07:34:30Z
|
[
"python",
"python-2.7",
"oop",
"attributeerror"
] |
AttributeError: instance has no attribute
| 39,555,189 |
<p>This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing. </p>
<p>I'm receiving <strong>AttributeError: WebHandler instance has no attribute 'search_str'</strong> </p>
<p>It seems to be this one particular method, any time I call any of the class variables set in <strong>___init___</strong> from this method I receive this error. I've extracted it to a test file as a simple function rather than a class method and it works fine, and I've tried re-indenting everything a few times to make sure it wasn't that, so I'm at a loss on this.</p>
<p>I'm using Python 2.7 and TextWrangler if either of these are helpful (TextWrangler hasn't given me any problems in 3 years like this, but figured anything should be included)</p>
<pre><code>import requests
import re
class WebHandler():
def ___init___(self):
self.urllist = []
self.search_str = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.I|re.M)
def set_urls(self, test, data):
for line in test[11:]:
if (("even" in line) or ("odd" in line)):
match = re.search(self.search_str, line)
self.urllist.append(match.group(0))
</code></pre>
<p>Another thing I tried, if I copy the attributes from <strong>___init___</strong> and simply make them local to <strong>set_urls()</strong> and call them without <strong>self</strong> that way it works properly and doesn't throw any errors, which is confusing me even more.</p>
<p>No idea what I'm missing. Thanks!</p>
| 1 |
2016-09-18T07:31:11Z
| 39,555,211 |
<p>Your init function has three underscores:</p>
<pre><code>def ___init___(self):
</code></pre>
<p>It <a href="https://docs.python.org/2/reference/datamodel.html#basic-customization" rel="nofollow">should have only two</a>:</p>
<pre><code>def __init__(self):
</code></pre>
<p>As it is written now, it is not being called when you create a new object.</p>
| 2 |
2016-09-18T07:34:42Z
|
[
"python",
"python-2.7",
"oop",
"attributeerror"
] |
How to add space between two widgets placed in grid in tkinter ~ python?
| 39,555,194 |
<p>a. Have placed a widget in the row 0 in the grid as shown below.</p>
<pre><code>self.a_button = Button(root, text="A Button")
self.a_button.grid(row=0, column=1)
</code></pre>
<p>b. And tried placing another widget in row 2 inside the grid.</p>
<pre><code>self.b_button = Button(root, text="B Button")
self.b_button.grid(row=2, column=1)
</code></pre>
<p>But when I run the program, I don't see any space between the widgets, rather its stacked once after the other. </p>
<p>So, how do I program to allow space between two widgets placed in different rows? Share your comments !!</p>
| -2 |
2016-09-18T07:31:54Z
| 39,555,320 |
<p>When you pack the widget you can use</p>
<pre><code>self.a_button = Button(root, text="A Button")
self.a_button.grid(row=0, column=1, padx=10, pady=10)
</code></pre>
<p>Using padx and pady you can add padding to the outer side of the button and alternatively if you want to increase the size of the button you can add inner padding using ipadx and ipady.</p>
<p>If you want more on the Grid function you can view all the options and uses here:
<a href="http://effbot.org/tkinterbook/grid.htm" rel="nofollow">http://effbot.org/tkinterbook/grid.htm</a></p>
| 1 |
2016-09-18T07:48:43Z
|
[
"python",
"python-2.7",
"tkinter"
] |
MySQL Error in Python
| 39,555,227 |
<blockquote>
<p>I need to insert a record into the table MemberDetails but I end up with the error stating " _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'I' at line 1") "</p>
</blockquote>
<pre><code>sql5="INSERT INTO MemberDetails VALUES"+"("+"'2016-2020','"+PhoneNum+"','VEC','"+Address+"','"+StuID+"','"+DOB+"','1000','"+Name+"','"+Pass+"','"+dept+"','"+year+"','"+sec+"')"
cursor.execute(sql5)
</code></pre>
| -3 |
2016-09-18T07:37:59Z
| 39,555,414 |
<p>You need to add spacing as well as the columns in the table each variable will be inserted into, your query should be like this:</p>
<pre><code>"INSERT INTO MemberDetails (datetime, phone, code, address, stuid, birthdate, num, name, pass, dept, year, sec) VALUES (" + "'2016-2020','" + PhoneNum + "','VEC','" + Address + "','" + StuID + "','" +DOB +"','1000','" + Name + "','" + Pass + "','" + dept + "','" + year + "','" +sec + "')"
</code></pre>
<p>Just replace the variables in the first set of brackets with the column name you want each variable to be put into.</p>
| -1 |
2016-09-18T08:00:40Z
|
[
"python",
"mysql"
] |
Calling a C++ CUDA device function from a Python kernel
| 39,555,235 |
<p>I'm working on a project that involves creating CUDA kernels in Python. Numba works quite well (what these guys have accomplished is quite incredible), and so does PyCUDA.</p>
<p>My problem is that I want to call a C device function from my Python generated kernel. I couldn't find a way to accomplish this. Numba can call CFFI modules but only in CPU code. In PyCUDA I can add my C device functions to the SourceModule, but I couldn't figure out how to include functions that already exist in another library.</p>
<p>Is there a way to accomplish this?</p>
| 1 |
2016-09-18T07:38:37Z
| 39,557,406 |
<p>As far as I am aware, this isn't possible in either language. Neither exposes the necessary toolchain controls for separate compilation or APIs to do runtime linking of device code.</p>
| 2 |
2016-09-18T11:57:14Z
|
[
"python",
"cuda",
"cython",
"numba",
"pycuda"
] |
What are the advantages and disadvantages of creating class and instance in this way in Python?
| 39,555,299 |
<pre><code>class CIFAR10Record(object):
pass
result = CIFAR10Record()
result.height = 32
result.width = 32
result.depth = 3
</code></pre>
<p>This snippet of code creates a class and its instance.</p>
<p>What are the advantages and disadvantages of this pattern?</p>
| 2 |
2016-09-18T07:47:28Z
| 39,555,354 |
<p>This code uses a class in order to "bunch together" a number of related fields.</p>
<p>The pros are that it's very flexible. The class is defined without any members. Any function can decide which fields to add. Different invocations can create objects of this class, and populate them in different ways (so, simultaneously, you could have objects of the same class with different members).</p>
<p>This flexibility is also a con. This lacks structure: it's harder to look at the code and decide which members the class will have. It's also less straightforward to get such an object, and iterate over the members. Finally, the class is an extreme case of no <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)" rel="nofollow">encapsulation</a>.</p>
<hr>
<p>Altogether, I think there are better alternatives:</p>
<p>If this flexibility is really needed (which is a question in itself), you might want to consider using a <code>dict</code> instead.</p>
<pre><code>result = {}
result['height'] = 32
result['width'] = 32
result['depth'] = 3
</code></pre>
<p>It's much clearer here (IMHO) that result is just a grouping of fields, and it's easier to iterate over the fields using <a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow"><code>dict</code>'s methods</a>.</p>
<p>If this flexibility is not needed, and it's just a way to minimize the amount of code, you should consider using <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow"><code>collections.namedtuple</code></a>.</p>
<pre><code>import collections
CIFAR10Record = collections.namedtuple('CIFAR10Record', ['height', 'width', 'depth'])
</code></pre>
| 4 |
2016-09-18T07:53:34Z
|
[
"python",
"class"
] |
Force vertical display with pprint
| 39,555,387 |
<p>I'm using <code>pprint</code> to display the <code>diff</code> between two dictionaries. Sometimes the values in the dictionary are long strings, which I want to see as single lines, so I set the <code>width</code> to some large value. Unfortunately, sometimes these dictionary are shallow (i.e., while in the general case they can embed lists and dictionaries, some are just dictionaries with short string values) in which case <code>pprint</code> "pretty-prints" them on a single line:</p>
<pre><code>>>> pprint.pprint({'a': 'a', 'b': 'b'})
{'a': 'a', 'b': 'b'}
</code></pre>
<p>Is there a means to force <code>pprint</code> to always display lists and dictionaries vertically? Again <code>width</code> is not an option as because of it strings are split inside lines (i.e., breaking on <code>\n</code> is good, but not elsewhere).</p>
<pre><code>>>> pprint.pprint({'a': 'a ' * 50}, width=20)
{'a': 'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a a a a a '
'a a '}
</code></pre>
<p>If <code>pprint</code> is not suitable, is there some standard library that would save me from writing a dedicated routine?</p>
| 2 |
2016-09-18T07:57:10Z
| 39,556,354 |
<h2>Option: Use <code>json</code></h2>
<p>I found converting the dictionary to JSON more predictable than <code>pprint</code>. In
addition, there you have an option to sort the keys, which should help your
comparison</p>
<pre><code> >>> import json
>>> d1 = {'a': 'a', 'b': 'b', 'c':'c'}
>>> print(json.dumps(d1, sort_keys=True, indent=''))
{
"a": "a",
"b": "b",
"c": "c"
}
>>> d2 = {'a': 'a ' * 50, 'b':'b', 'c': 'c ' * 50}
>>> print(json.dumps(d2, sort_keys=True, indent=''))
{
"a": "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a ",
"b": "b",
"c": "c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c "
}
</code></pre>
| 1 |
2016-09-18T09:56:06Z
|
[
"python",
"dictionary",
"pretty-print"
] |
TKinter - How to stop a loop with a stop button?
| 39,555,463 |
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p>
<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time, winsound, msvcrt
running = True
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
sec = 0
while running:
if sec % 1 == 0:
winsound.Beep(Freq, Dur)
time.sleep(1)
sec += 1
def stop():
running = False
startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 1 |
2016-09-18T08:08:55Z
| 39,556,017 |
<p>There are several things wrong with your code. First of all you shouldn't use <code>time.sleep()</code> in a Tkinter program because it interferes with the <code>mainloop()</code>. Instead one typically uses the universal widget method <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow"><code>.after()</code></a> to schedule a function to run after a specified delay.</p>
<p>Secondly you're not using global variables correctly. When you assign a value to a named variable in a function, it will create a local variable unless that name has been previous declared <code>global</code>. So for instance, your <code>stop()</code> function is creating a local variable named <code>running</code> and setting its value to 0, <em>not</em> changing the value of the global variable with the same name.</p>
<p>The previous rule doesn't apply to just referencing (reading) the current value of a variable. That is why it was OK to not have declared <code>Freq</code> and <code>Dur</code> globals in <code>start()</code>.</p>
<p>Another problem is with the <code>sec % 1 == 0</code> in your <code>start()</code> function. Any value <code>% 1</code> is <code>0</code>. To check odd/evenness use <code>sec % 2</code>.</p>
<p>Here's a working version which has also been reformatted to follow <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8 - Style Guide for Python Code</a> more closely.</p>
<pre><code>import Tkinter
import tkMessageBox
import time
import winsound
FREQ = 2500
DUR = 150
after_id = None
secs = 0
def beeper():
global after_id
global secs
secs += 1
if secs % 2 == 0: # every other second
winsound.Beep(FREQ, DUR)
after_id = top.after(1000, beeper) # check again in 1 second
def start():
global secs
secs = 0
beeper() # start repeated checking
def stop():
global after_id
if after_id:
top.after_cancel(after_id)
after_id = None
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100')
startButton = Tkinter.Button(top, height=2, width=20, text="Start",
command=start)
stopButton = Tkinter.Button(top, height=2, width=20, text="Stop",
command=stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 2 |
2016-09-18T09:18:31Z
|
[
"python",
"tkinter"
] |
TKinter - How to stop a loop with a stop button?
| 39,555,463 |
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p>
<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time, winsound, msvcrt
running = True
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
sec = 0
while running:
if sec % 1 == 0:
winsound.Beep(Freq, Dur)
time.sleep(1)
sec += 1
def stop():
running = False
startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 1 |
2016-09-18T08:08:55Z
| 39,556,024 |
<p>The problem is that the while loop in <code>start()</code> blocks the GUI handler <code>mainloop()</code>. Try using <code>Tk.after()</code> in <code>start()</code>:</p>
<pre><code>def start(force=True):
global running
if force:
running = True
if running:
winsound.Beep(Freq, Dur)
top.after(1000, start, False)
</code></pre>
<p>And change <code>stop()</code>:</p>
<pre><code>def stop():
global running
running = False
</code></pre>
| 0 |
2016-09-18T09:19:43Z
|
[
"python",
"tkinter"
] |
TKinter - How to stop a loop with a stop button?
| 39,555,463 |
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p>
<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time, winsound, msvcrt
running = True
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
sec = 0
while running:
if sec % 1 == 0:
winsound.Beep(Freq, Dur)
time.sleep(1)
sec += 1
def stop():
running = False
startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 1 |
2016-09-18T08:08:55Z
| 39,556,099 |
<p>You code have <code>top.mainloop()</code> which has a <code>while</code> loop running inside it and on top of that you also have a while loop inside <code>def start():</code>. So it is like loop inside loop. </p>
<p>You can create a function that does what you want for the body of the loop. It should do exactly one iteration of the loop. Once it is done, it needs to arrange for itself to be called again some time in the future using <code>after</code>. How far in the future defines how fast your loop runs. </p>
<p>And you can then use <code>after_cancel</code> to cancel the event. Below code worked for me</p>
<pre><code>import Tkinter, tkMessageBox, time, winsound, msvcrt
Freq = 2500
Dur = 150
top = tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
global job1
if running == True:
winsound.Beep(Freq, Dur)
job1 = top.after(1000, start) # reschedule event in 1 seconds
def stop():
global job1
top.after_cancel(job1)
startButton = tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
#top.after(1000, start)
top.mainloop()
</code></pre>
| 3 |
2016-09-18T09:27:49Z
|
[
"python",
"tkinter"
] |
TKinter - How to stop a loop with a stop button?
| 39,555,463 |
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p>
<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time, winsound, msvcrt
running = True
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
sec = 0
while running:
if sec % 1 == 0:
winsound.Beep(Freq, Dur)
time.sleep(1)
sec += 1
def stop():
running = False
startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 1 |
2016-09-18T08:08:55Z
| 39,556,213 |
<p>Beaten to the punch again but here goes nothing. As above use the <code>after</code> function to prevent the <code>mainloop</code> blocking.<br>
See:
<a href="http://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method#25753719">tkinter: how to use after method</a></p>
<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
print ("Beep")
top.after(1000, start)
def stop():
print ("Stop")
top.quit()
startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
</code></pre>
| 0 |
2016-09-18T09:40:09Z
|
[
"python",
"tkinter"
] |
re.findall() returning the wrong values when using optionals
| 39,555,527 |
<p>I'm following along in a tutorial and I seem to be stuck on what seems to be an easy thing to do:</p>
<pre><code>numRegex = re.compile(r'\d+(\s+\w+)?')
spam = numRegex.findall("my address is 999 Street Ave City CA 95014 x")
print(len(spam))
print(spam)
</code></pre>
<p>this returns <code>[' Street', ' x']</code> which is obviously wrong as it should be <code>['999 Street', '95014 x']</code>.</p>
| 0 |
2016-09-18T08:16:03Z
| 39,555,543 |
<p>You are capturing the group wrongly. Try:</p>
<pre><code>numRegex = re.compile(r'(\d+(?:\s+\w+)?)')
</code></pre>
<p>Or, </p>
<pre><code>numRegex = re.compile(r'\d+(?:\s+\w+)?')
</code></pre>
<p><code>\d+(\s+\w+)?</code> seeks for the whole pattern, but only matches <code>(\s+\w+)</code> part because, this is the capturing group.</p>
<p>You need to match the whole pattern. So, you should add a parenthesis over the whole pattern to match the whole pattern as captured group.</p>
<p>Now, You have one nested capturing group <code>(\s+\w+)?</code>. You need to make it a non capturing group. So, Add a <code>?:</code> inside the parenthesis to get the effect. </p>
| 0 |
2016-09-18T08:18:04Z
|
[
"python",
"regex"
] |
Plot quadratic function / model with matplotlib
| 39,555,569 |
<p>I'm playing around with python and want to plot a quadratic linear regression with matplotlib. The problem is, that my plot ends up being a lot of connected lines/dots instead of just the one function:</p>
<p><a href="http://i.stack.imgur.com/EljBs.png" rel="nofollow">Plot</a></p>
<p><a href="http://i.stack.imgur.com/wQxfD.png" rel="nofollow">Zoomed plot</a></p>
<p>Normally I would think of this being a problem with row vs. column vectors. But nothing seems to change when I transpose. </p>
<p>Here's my code:</p>
<pre><code>from sklearn import datasets, linear_model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Load diabetes dataset JSON
dsDiabetes = datasets.load_diabetes()
# Create feature- and outcome vectors
lin_train = np.array(dsDiabetes.data[:, np.newaxis, 2])
quad_train = np.concatenate((lin_train, lin_train**2), axis=1)
outcome = np.array(dsDiabetes.target)
# Create regression objects
lin_model = linear_model.LinearRegression()
quad_model = linear_model.LinearRegression()
# lin_train model
lin_model.fit(lin_train, outcome)
quad_model.fit(quad_train, outcome)
# Plot
plt.style.use('fivethirtyeight')
plt.scatter(lin_train, outcome, color='black')
# plt.plot(lin_train, quad_model.predict(quad_train))
# plt.plot(lin_train, lin_model.predict(lin_train), color='blue', linewidth=1)
plt.plot(lin_train, quad_model.predict(quad_train), color='red', linewidth=1)
plt.show()
</code></pre>
<p>What am I missing?</p>
| 0 |
2016-09-18T08:22:18Z
| 39,555,778 |
<p>From what I can see, the x values on your plots are not sorted in ascending order. The plot does what it should and connects the dots, but they are in such an order that the line jumps "back" and "forward" on the x-axis. Now - you can't see that on the linear plot as everything is on a single line, but starts to become visible on the quadratic. If you sort the points used for the line based on ascending x-value that should do it.</p>
| 0 |
2016-09-18T08:48:51Z
|
[
"python",
"matplotlib"
] |
Plot quadratic function / model with matplotlib
| 39,555,569 |
<p>I'm playing around with python and want to plot a quadratic linear regression with matplotlib. The problem is, that my plot ends up being a lot of connected lines/dots instead of just the one function:</p>
<p><a href="http://i.stack.imgur.com/EljBs.png" rel="nofollow">Plot</a></p>
<p><a href="http://i.stack.imgur.com/wQxfD.png" rel="nofollow">Zoomed plot</a></p>
<p>Normally I would think of this being a problem with row vs. column vectors. But nothing seems to change when I transpose. </p>
<p>Here's my code:</p>
<pre><code>from sklearn import datasets, linear_model
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Load diabetes dataset JSON
dsDiabetes = datasets.load_diabetes()
# Create feature- and outcome vectors
lin_train = np.array(dsDiabetes.data[:, np.newaxis, 2])
quad_train = np.concatenate((lin_train, lin_train**2), axis=1)
outcome = np.array(dsDiabetes.target)
# Create regression objects
lin_model = linear_model.LinearRegression()
quad_model = linear_model.LinearRegression()
# lin_train model
lin_model.fit(lin_train, outcome)
quad_model.fit(quad_train, outcome)
# Plot
plt.style.use('fivethirtyeight')
plt.scatter(lin_train, outcome, color='black')
# plt.plot(lin_train, quad_model.predict(quad_train))
# plt.plot(lin_train, lin_model.predict(lin_train), color='blue', linewidth=1)
plt.plot(lin_train, quad_model.predict(quad_train), color='red', linewidth=1)
plt.show()
</code></pre>
<p>What am I missing?</p>
| 0 |
2016-09-18T08:22:18Z
| 39,555,794 |
<p>You need to sort your values. You can take any approach. Personally, I would just use <code>pandas</code> but there are more lightweight solutions for sure.</p>
<pre><code>>>> df = pd.DataFrame({'x':lin_train.reshape((lin_train.shape[0],)), 'y':quad_model.predict(quad_train)})
>>> df.sort_values(by='x', inplace=True)
>>> plt.style.use('fivethirtyeight')
>>> plt.scatter(lin_train, outcome, color='black')
<matplotlib.collections.PathCollection object at 0x7f6bf2906590>
>>> # plt.plot(lin_train, quad_model.predict(quad_train))
... # plt.plot(lin_train, lin_model.predict(lin_train), color='blue', linewidth=1)
... plt.plot(df.x, df.y, color='red', linewidth=1)
[<matplotlib.lines.Line2D object at 0x7f6bf29069d0>]
</code></pre>
<p><a href="http://i.stack.imgur.com/guMDo.png" rel="nofollow"><img src="http://i.stack.imgur.com/guMDo.png" alt="enter image description here"></a></p>
| 0 |
2016-09-18T08:51:28Z
|
[
"python",
"matplotlib"
] |
How to keep one single column as a dataframe
| 39,555,592 |
<p>I have dataframe with 20 columns and one index.</p>
<p>Its shape is something like (100, 20).</p>
<p>I want to slice the 3rd column from this dataframe, but want to keep the result as a dataframe of (100,1). </p>
<ol>
<li>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</li>
<li>If I do a <code>v =df[df['col3']!=0]</code> and then <code>v.drop(label=[list of 19 columns], axis = 1)</code> --- I get what I want [that is a df(100,1)] but I have to </li>
</ol>
<p>(a) write an unnecessary != condition ( which I want to avoid) and </p>
<p>(b) I have to write a long list of 19 column names.</p>
<p>There should be a better and cleaner way of doing what I wan to achieve.</p>
| 2 |
2016-09-18T08:25:42Z
| 39,555,643 |
<blockquote>
<p>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</p>
</blockquote>
<p>If you use <code>df[cols]</code>, where <code>cols</code> is a list, you'll get a DataFrame (not a Series). This includes the case where it is a list consisting of a single item. So, you can use <code>df[['col3']]</code>.</p>
<p>For example:</p>
<pre><code>In [33]: df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
</code></pre>
<p>This gives a Series:</p>
<pre><code>In [35]: df['a']
Out[35]:
0 1
1 2
Name: a, dtype: int64
</code></pre>
<p>This gives a DataFrame:</p>
<pre><code>In [36]: df[['a']]
Out[36]:
a
0 1
1 2
</code></pre>
<p>Finally, note that you can always transform a Series to a DataFrame with <code>reset_index</code>. So here, you can also use:</p>
<pre><code>In [44]: df['a'].reset_index()
Out[44]:
index a
0 0 1
1 1 2
</code></pre>
| 3 |
2016-09-18T08:32:00Z
|
[
"python",
"pandas",
"sklearn-pandas"
] |
How to keep one single column as a dataframe
| 39,555,592 |
<p>I have dataframe with 20 columns and one index.</p>
<p>Its shape is something like (100, 20).</p>
<p>I want to slice the 3rd column from this dataframe, but want to keep the result as a dataframe of (100,1). </p>
<ol>
<li>If I do a <code>v = df['col3']</code>, I get a Series (which I do not want)</li>
<li>If I do a <code>v =df[df['col3']!=0]</code> and then <code>v.drop(label=[list of 19 columns], axis = 1)</code> --- I get what I want [that is a df(100,1)] but I have to </li>
</ol>
<p>(a) write an unnecessary != condition ( which I want to avoid) and </p>
<p>(b) I have to write a long list of 19 column names.</p>
<p>There should be a better and cleaner way of doing what I wan to achieve.</p>
| 2 |
2016-09-18T08:25:42Z
| 39,555,884 |
<p>Another handy trick is <code>to_frame()</code></p>
<pre><code>df['col3'].to_frame()
</code></pre>
| 2 |
2016-09-18T09:03:01Z
|
[
"python",
"pandas",
"sklearn-pandas"
] |
setting up nginx with django
| 39,555,611 |
<p>I have created a django project called "yo" in my /home/ubuntu/test directory.</p>
<p>These are my nginx files:</p>
<p>nginx/sites-available/yo</p>
<pre><code> server {
listen 80;
server_name 52.89.220.11;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ubuntu/test/yo/static;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/home/ubuntu/test/yo/yo.sock;
}
}
</code></pre>
<p>nginx/sites-enabled/yo_nginx.conf:</p>
<pre><code># mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///home/Ubuntu/test/yo/yo.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 52.89.220.11; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
# location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
# }
#location /static {
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/ubuntu/test/yo/uwsgi_params; # the uwsgi_params file you installed
}
}
</code></pre>
<p>/home/ubuntu/test/yo/uwsgi_params:</p>
<pre><code>uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REQUEST_SCHEME $scheme;
uwsgi_param HTTPS $https if_not_empty;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;
</code></pre>
<p>There are my files along with their url. When i go to the domain_name on port 80, i get 502 bad gateway instead of django success page. Please help.</p>
| 1 |
2016-09-18T08:27:42Z
| 39,557,230 |
<ul>
<li>you have unmatched parens in your <code>nginx/sites-enabled/yo_nginx.conf</code></li>
<li><code>nginx/sites-available/yo</code> is not read by nginx - only files ending in <code>.conf</code> and located in <code>nginx/sites-enabled/</code> are read in default nginx configuration.</li>
<li>since your command line <code>uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=664</code> tells uwsgi to listen on unix socket, your <code>upstream django</code> block should be modified accordingly.</li>
</ul>
<p>That should get rid of the 502 error.</p>
<pre><code>upstream django {
server unix:///home/ubuntu/test/yo/mysite.sock; # for a file socket, check if the path is correct
# server 127.0.0.1:8001; # for a web port socket
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 52.89.220.11; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
# location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
# }
# location /static {
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
# }
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/ubuntu/test/yo/uwsgi_params; # the uwsgi_params file you installed
}
}
</code></pre>
| 1 |
2016-09-18T11:36:42Z
|
[
"python",
"django",
"nginx"
] |
setting up nginx with django
| 39,555,611 |
<p>I have created a django project called "yo" in my /home/ubuntu/test directory.</p>
<p>These are my nginx files:</p>
<p>nginx/sites-available/yo</p>
<pre><code> server {
listen 80;
server_name 52.89.220.11;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ubuntu/test/yo/static;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/home/ubuntu/test/yo/yo.sock;
}
}
</code></pre>
<p>nginx/sites-enabled/yo_nginx.conf:</p>
<pre><code># mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///home/Ubuntu/test/yo/yo.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 52.89.220.11; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
# location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
# }
#location /static {
# alias /path/to/your/mysite/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/ubuntu/test/yo/uwsgi_params; # the uwsgi_params file you installed
}
}
</code></pre>
<p>/home/ubuntu/test/yo/uwsgi_params:</p>
<pre><code>uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REQUEST_SCHEME $scheme;
uwsgi_param HTTPS $https if_not_empty;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;
</code></pre>
<p>There are my files along with their url. When i go to the domain_name on port 80, i get 502 bad gateway instead of django success page. Please help.</p>
| 1 |
2016-09-18T08:27:42Z
| 39,558,941 |
<p>First install required applications.
sudo apt-get install nginx uwsgi uwsgi-plugin-python python-virtualenv
Versions of packages that will be used:</p>
<pre><code>Nginx
Uwsgi
Virtualenv
Django
Virtualenv.
</code></pre>
<p>I store my project in ~/projects. Now I'm creating python virtual environment for my project and I'm installing Django.</p>
<pre><code>cd ~/projects/
virtualenv example.com
cd example.com
source bin/activate
pip install django
django-admin.py startproject project
</code></pre>
<p>Nginx configuration.
IMHO, by default, nginx is configured for basic tasks. I won't change this configuration in this entry. Configuration files are stored in </p>
<pre><code>/etc/nginx/sites-available. Go to this directory and create a new file.
cd /etc/nginx/sites-available
</code></pre>
<p>vim example.com
It's example configuration.</p>
<pre><code>server {
listen 80;
server_name eample.com,www.example.com;
access_log /var/log/nginx/eample.com_access.log;
error_log /var/log/nginx/example.com_error.log;
location / {
uwsgi_pass unix:///tmp/example.com.sock;
include uwsgi_params;
}
location /media/ {
alias /home/eshlox/projects/example.com/project/project/media/;
}
location /static/ {
alias /home/eshlox/projects/example.com/project/project/static/;
}
}
</code></pre>
<p>We must create symlink to enable this.</p>
<pre><code>cd /etc/nginx/sites-enabled
ln -s ../sites-available/example.com .
</code></pre>
<p>Uwsgi.
Like with Nginx.. configuration files are stored in /etc/uwsgi/apps-available. Go to this directory and create a new file.</p>
<pre><code>cd /etc/uwsgi/apps-available
vim example.com.ini
</code></pre>
<p>Edit example.com.ini
[uwsgi]</p>
<pre><code>vhost = true
plugins = python
socket = /tmp/example.com.sock
master = true
enable-threads = true
processes = 2
wsgi-file = /home/eshlox/projects/example.com/project/project/wsgi.py
virtualenv = /home/eshlox/projects/example.com
chdir = /home/eshlox/projects/example.com/project
touch-reload = /home/eshlox/projects/example.com/project/reload
</code></pre>
<p>Enable this.</p>
<pre><code>cd /etc/uwsgi/apps-enabled/
ln -s ../apps-available/example.com.ini .
That's all. Now, run this services.
sudo service nginx start
sudo service uwsgi start
</code></pre>
| 1 |
2016-09-18T14:48:42Z
|
[
"python",
"django",
"nginx"
] |
How to translate Python console program (including while true loop) to PyQt?
| 39,555,653 |
<p>I have a Python console program that I want to transfer to a GUI.
I thought of using PyQt 5, but I'm open to alternatives.</p>
<p>The simplified console code looks like this:</p>
<pre><code>while True:
data = obtain_data_from_device(source)
print(datatotext(data))
</code></pre>
<p>Now from what I understand, GUI code works different.
But how do I continuously update a text box in PyQt using the obtain_data_from_device function which might take any time from 0.5 to 30 seconds?</p>
<p>A while loop can't do it, as it screws up the GUI, a timer doesn't work, as the duration is variable.</p>
<p>I'd appreciate any hints.</p>
| 0 |
2016-09-18T08:33:52Z
| 39,556,908 |
<p>You could try something like this:</p>
<pre><code>import sys
import random
import time
import string
from PyQt5 import QtWidgets, QtCore
def obtain_data_from_device(source):
time.sleep(0.001)
data = ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(len(source)))
return data
class Main(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.init_ui()
def init_ui(self):
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.time)
self.timer.start(0)
self.lcd = QtWidgets.QLineEdit(self)
self.lcd.setText(
obtain_data_from_device("whatever data you're capturing"))
self.setCentralWidget(self.lcd)
self.setGeometry(300, 300, 250, 100)
self.setWindowTitle("Displaying capture data from device")
def time(self):
self.lcd.setText(
obtain_data_from_device("whatever data you're capturing"))
def main():
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
</code></pre>
<p>You will just need to replace the existing obtain_data_from_device by yours.</p>
| 0 |
2016-09-18T10:59:27Z
|
[
"python",
"qt",
"pyqt"
] |
How to translate Python console program (including while true loop) to PyQt?
| 39,555,653 |
<p>I have a Python console program that I want to transfer to a GUI.
I thought of using PyQt 5, but I'm open to alternatives.</p>
<p>The simplified console code looks like this:</p>
<pre><code>while True:
data = obtain_data_from_device(source)
print(datatotext(data))
</code></pre>
<p>Now from what I understand, GUI code works different.
But how do I continuously update a text box in PyQt using the obtain_data_from_device function which might take any time from 0.5 to 30 seconds?</p>
<p>A while loop can't do it, as it screws up the GUI, a timer doesn't work, as the duration is variable.</p>
<p>I'd appreciate any hints.</p>
| 0 |
2016-09-18T08:33:52Z
| 39,558,057 |
<p>One option, since you already have a working program that writes to STDOUT, is to let the GUI program run the console program as a child process using <code>QProcess</code>.</p>
<p>The child will run asynchronously under control of the GUI program and the GUI program will receive the child's output via signals, i.e. non-blocking</p>
| 1 |
2016-09-18T13:18:16Z
|
[
"python",
"qt",
"pyqt"
] |
How to define a weighted loss function in TensorFlow?
| 39,555,745 |
<p>I have a training dataset of train_data and train_labels which is train_data_node and train_labels_node in the graph of tensorflow.
As you know, I can use the loss function of tensorflow as bellows:</p>
<pre><code>logits = model(train_data_node)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits,train_labels_node))
</code></pre>
<p>However, this loss function processes all the training data equally.
But in our situation, we want to process the data discriminately.
For example, we have a csv file corresponding to the training data to indicate the train data is original or augmented.
Then we want to define a custom loss function which makes the loss of original data play more important role and the loss of augmented data play less important role, such as:</p>
<pre><code>loss_no_aug = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(noAugLogits, noAugLabels))
loss_aug = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(augLogits, augLabels))
loss = loss_no_aug * PENALTY_COEFFICIENT + loss_aug
</code></pre>
<p>I have defined a loss function as bellow, but it didn't work:</p>
<pre><code>def calLoss(logits, labels, augs):
noAugLogits = []
noAugLabels = []
augLogits = []
augLabels = []
tf.get_collection()
for i in range(augs.shape[0]):
if augs[i] == 1:
noAugLogits.append(logits[i])
noAugLabels.append(labels[i])
else:
augLogits.append(logits[i])
augLabels.append(labels[i])
noAugLogits = tf.convert_to_tensor(noAugLogits)
noAugLabels = tf.convert_to_tensor(noAugLabels)
augLogits = tf.convert_to_tensor(augLogits)
augLabels = tf.convert_to_tensor(augLabels)
return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
noAugLogits, noAugLabels)) * PENALTY_COEFFICIENT + \
tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(augLogits, augLabels))
</code></pre>
<p>I think we should write the loss function using tensor operations, however, I am not familiar with them. So could anyone give me some advice on how to define the loss function.</p>
<p>Thank you for your kind answers or suggestions.</p>
| 1 |
2016-09-18T08:45:29Z
| 39,564,270 |
<p>I have finally solved the problem by myself using the function tf.boolen_mask() of tensorflow. The defined custom weighted loss function is as bellows:</p>
<pre><code>def calLoss(logits, labels, augs):
augSum = tf.reduce_sum(augs)
pred = tf.less(augSum, BATCH_SIZE)
def noaug(logits, labels, augs):
augs = tf.cast(augs, tf.bool)
noaugs = tf.logical_not(augs)
noAugLogits = tf.boolean_mask(logits, noaugs)
noAugLabels = tf.boolean_mask(labels, noaugs)
augLogits = tf.boolean_mask(logits, augs)
augLabels = tf.boolean_mask(labels, augs)
noaugLoss = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(noAugLogits, noAugLabels))
augLoss = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(augLogits, augLabels))
return noaugLoss * PENALTY_COEFFICIENT + augLoss
def aug(logits, labels):
return tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels))
return tf.cond(pred, lambda: noaug(logits, labels, augs), lambda: aug(logits, labels))
</code></pre>
<p>As you can see, I use a numpy array variable, augs, using 1 and 0 in corresponding positions to indicate whether a sample in a batch of samples is augmented or non-augmented. Then I convert the variable to a bool tensor and use it as the bool mask of tf.boolen_mask() to fetch the augmented and non-augmented samples and calculate the loss respectively.</p>
| 0 |
2016-09-19T01:43:59Z
|
[
"python",
"tensorflow"
] |
Flask context missing in 404 errorhandler
| 39,555,768 |
<p>I have the following structure for my flask application. When an invalid url comes in a 404 error is called, but my 404.html requires data from the context_processor but in the abort 404 the blueprint is None so context_processor is never called and 404.html is missing data.</p>
<p>How can I approach this differently?</p>
<h3><strong>init</strong>.py</h3>
<pre><code>def create_app(settings_overide=None):
app = factory.create_app(__name__, __path__, settings_overide)
if not app.debug:
app.errorhandler(404)(page_not_found)
return app
def page_not_found(e):
return render_template('404.html'), 404
</code></pre>
<h3>processors.py</h3>
<pre><code>@blueprint.context_processor
def load_global_data():
return get_data()
</code></pre>
| 0 |
2016-09-18T08:47:40Z
| 39,555,787 |
<p>When a route is not found, no blueprint is set yet (because setting a blueprint requires a route to be determined first). As such a 404 error handler can't count on a blueprint to have been determined.</p>
<p>You'd have to execute the <code>get_data()</code> call manually. Test if a specific global has been set, then execute the <code>get_data()</code> function if not before rendering your 404 template.</p>
| 1 |
2016-09-18T08:50:25Z
|
[
"python",
"flask"
] |
Jinja2 include & extends not working as expected
| 39,555,769 |
<p>I used <code>include</code> and <code>extends</code> in the <code>base.html</code> file and expect them to be included in order. But the <code>extends</code> template is appended to the end of the file.</p>
<p>I expect my template to give me the output of:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Test String from block !</p>
<footer>text from footer.</footer>
</body>
</html>
</code></pre>
<p>but the current result are:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<footer>text from footer.</footer>
</body>
</html>
<p>Test String from block !</p>
</code></pre>
<p>In <code>base.html</code>, first I include <code>header.html</code>, then <code>content.html</code> and then <code>footer.html</code> but the rendered order is <code>header.html</code>, <code>footer.html</code>, <code>content.html</code>.</p>
<p><code>index.html</code></p>
<pre><code>{% extends "base.html" %}
{% block content %}
<p>Test String from block !</p>
{% endblock %}
</code></pre>
<p><code>base.html</code></p>
<pre><code>{% include "header.html" %}
<body>
{% extends "content.html" %}
{% include "footer.html" %}
</code></pre>
<p><code>header.html</code></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
</code></pre>
<p><code>content.html</code></p>
<pre><code>{% block content %}
{% endblock %}
</code></pre>
<p><code>footer.html</code></p>
<pre><code><footer>text from footer.</footer>
</body>
</html>
</code></pre>
| 2 |
2016-09-18T08:47:49Z
| 39,555,899 |
<p>I think that you want to use <code>include</code> instead of <code>extends</code> in </p>
<pre><code>{% extends "content.html" %}
</code></pre>
| 0 |
2016-09-18T09:05:49Z
|
[
"python",
"flask",
"jinja2"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.