title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Pyspark RDD .filter() with wildcard | 39,256,520 | <p>I have an Pyspark RDD with a text column that I want to use as a a filter, so I have the following code:</p>
<pre><code>table2 = table1.filter(lambda x: x[12] == "*TEXT*")
</code></pre>
<p>To problem is... As you see I'm using the <code>*</code> to try to tell him to interpret that as a wildcard, but no success.
Anyone has a help no that ?</p>
| 0 | 2016-08-31T18:23:31Z | 39,256,540 | <pre><code>table2 = table1.filter(lambda x: "TEXT" in x[12])
</code></pre>
| 0 | 2016-08-31T18:24:58Z | [
"python",
"apache-spark",
"rdd"
] |
formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib | 39,256,529 | <h1>TL;DR</h1>
<p>How can you...</p>
<ul>
<li><p>Force the <code>LogFormatter</code> to use scientific notation for every label? Now it uses it for values smaller than <code>0</code> or larger than <code>1000</code>. It does not seem to expose any <code>set_powerlimit</code> method that I can find, either. Is there any way get it right or should you use a different formatter? which one?</p></li>
<li><p>Get the scientific notations with the exponents as superscripts like in the first plot attached, instead of things like <code>-1e+02</code>? The <code>plt.xscale('symlog')</code> call also gets it right for an x axis, so it doesn't look like a limitation of the scale itself...</p></li>
</ul>
<p>Of course, if there were a simpler way to get nicely formatted xticks and labels on a colormap with symlog scaling, that'd be great too. But honestly, looking at the colorbars that the <a href="http://matplotlib.org/1.5.1/users/colormapnorms.html" rel="nofollow">documentation</a> itself exhibits, I don't have much hope... :-/</p>
<hr>
<h1>Starting from the beginning...</h1>
<p>Matplotlib offers a few normalizations that can be used with <code>colorbar</code>. This is nicely explained in the <a href="http://matplotlib.org/1.5.1/users/colormapnorms.html" rel="nofollow">documentation</a>.</p>
<p>Among them, the logarithmic one (<code>mpl.colors.LogNorm</code>) works specially well, as it</p>
<ol>
<li>places the xticks evenly distributed.</li>
<li>formats the ticklabels with a <em>nice looking</em> scientific notation**.</li>
</ol>
<p>by itself. A minimal example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors, ticker
data = np.arange(4).reshape(-1,1)+np.arange(4).reshape(1,-1)
data = 10**(data/2.)
plt.figure(figsize=(4,3))
plt.imshow(data, interpolation="None", cmap="gray", norm=colors.LogNorm())
plt.colorbar()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/fx5nN.png" rel="nofollow"><img src="http://i.stack.imgur.com/fx5nN.png" alt="imshow with LogNorm normalization"></a></p>
<p>On the other hand, the symmetric logarithmic one (<code>matplotlib.colors.SymLogNorm</code>) does neither.
<a href="http://stackoverflow.com/a/23118662">This SO answer</a> defines a wrapper function for imshow that goes a long way towards the desired results, but it does not quite get there yet.</p>
<p>A minimal example with an adaptation of that function:</p>
<pre><code>def imshow_symlog(arr, vmin=None, vmax=None, logthresh=5, logstep=1,
linscale=1, **kwargs):
# Adapted from http://stackoverflow.com/a/23118662
vmin = arr.min() if vmin is None else vmin
vmax = arr.max() if vmax is None else vmax
img=plt.imshow(arr,
vmin=float(vmin), vmax=float(vmax),
norm=colors.SymLogNorm(10**-logthresh, linscale=linscale),
**kwargs)
maxlog=int(np.ceil(np.log10(vmax)))
minlog=int(np.ceil(np.log10(-vmin)))
#generate logarithmic ticks
tick_locations=([-(10**x) for x in xrange(-logthresh, minlog+1, logstep)][::-1]
+[0.0]
+[(10**x) for x in xrange(-logthresh,maxlog+1, logstep)] )
cb=plt.colorbar(ticks=tick_locations, format=ticker.LogFormatter())
return img,cb
data2 = data - data[::-1,::-1]
plt.figure(figsize=(4,3))
img, cb = imshow_symlog(data2, interpolation="None", cmap="gray", logthresh=0)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/iMJoV.png" rel="nofollow"><img src="http://i.stack.imgur.com/iMJoV.png" alt="imshow with SymLogNorm normalization"></a></p>
| 2 | 2016-08-31T18:24:06Z | 39,256,959 | <p>Change the formatter in the function to <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.LogFormatterMathtext" rel="nofollow"><code>LogFormatterMathtext</code></a>: </p>
<pre><code>cb=plt.colorbar(ticks=tick_locations, format=ticker.LogFormatterMathtext())
</code></pre>
<p>The formatters obviously lack nice (if any) documentation, but this one seems to do what you want:</p>
<p><a href="http://i.stack.imgur.com/mq8xF.png" rel="nofollow"><img src="http://i.stack.imgur.com/mq8xF.png" alt="enter image description here"></a></p>
| 1 | 2016-08-31T18:50:03Z | [
"python",
"matplotlib"
] |
os.environ doesn't show all environmental variables in Jupyter notebook | 39,256,559 | <p>I am finding that the following code prints out my expected environmental variable when I execute the script in a shell:</p>
<pre><code>import os
print(os.environ['STUFF'])
</code></pre>
<p>However, when I run this same code in Jupyter Notebook, I get a key error. I have tried restarting the Jupyter server. What else should I do?</p>
| 0 | 2016-08-31T18:26:38Z | 39,256,671 | <p>You can query all the dictionary keys to confirm the one you have is not there.</p>
<pre><code>import os
print(os.environ.keys())
</code></pre>
<p>Or better you can test for the presence of the specific key.</p>
<pre><code>print(os.environ.has_key('STUFF'))
</code></pre>
| 0 | 2016-08-31T18:33:08Z | [
"python",
"environment-variables"
] |
Add confirmation step to custom Django management/manage.py command | 39,256,578 | <p>I created the following custom management command following <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">this tutorial</a>.</p>
<pre><code>from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from topspots.models import Notification
class Command(BaseCommand):
help = 'Sends message to all users'
def add_arguments(self, parser):
parser.add_argument('message', nargs='?')
def handle(self, *args, **options):
message = options['message']
users = User.objects.all()
for user in users:
Notification.objects.create(message=message, recipient=user)
self.stdout.write(
self.style.SUCCESS(
'Message:\n\n%s\n\nsent to %d users' % (message, len(users))
)
)
</code></pre>
<p>It works exactly as I want it to, but I would like to add a confirmation step so that before the <code>for user in users:</code> loop you are asked if you really want to send message X to N users, and the command is aborted if you choose "no". </p>
<p>I assume this can be easily done because it happens with some of the built-in management commands, but it doesn't seem to cover this in the tutorial and even after some searching and looking at the source for the built-in management commands, I have not been able to figure it out on my own.</p>
| 0 | 2016-08-31T18:27:43Z | 39,257,511 | <p>You can use Python's <code>raw_input</code>/<code>input</code> function. Here's an example method from Django's <a href="https://github.com/django/django/blob/59afe61a970dd60df388e7cda9041ef3c0e770cb/django/db/migrations/questioner.py#L87" rel="nofollow">source code</a>:</p>
<pre><code>from django.utils.six.moves import input
def boolean_input(question, default=None):
result = input("%s " % question)
if not result and default is not None:
return default
while len(result) < 1 or result[0].lower() not in "yn":
result = input("Please answer yes or no: ")
return result[0].lower() == "y"
</code></pre>
<p>Be sure to use the import from <code>django.utils.six.moves</code> if your code should be compatible with Python 2 and 3, or use <code>raw_input()</code> if you're on Python 2. <code>input()</code> on Python 2 will evaluate the input rather than converting it to a string. </p>
| 1 | 2016-08-31T19:24:30Z | [
"python",
"django",
"django-manage.py",
"django-management-command"
] |
Python: Dedup a dictionary | 39,256,611 | <p>Good afternoon,</p>
<p>I reading in a pcap and am basically trying to get a dedup'd list of BSSID's & ESSID's. I am still getting duplicates with this code and cannot for the life of me figure out what I am doing wrong:</p>
<pre><code>if not (t[0] in ssid_pairs and ssid_pairs[t[0]] == t[1]):
ssid_pairs[t[0]] = t[1]
of.write(t[0] + ',' + t[1] + ((',' + f + '\n') if verbose else '\n'))
</code></pre>
<p>ssid_pairs is a dictionary, t[0] is the bssid & t[1] is the essid. An example of the dictionary is:</p>
<pre><code>{'FF:FF:FF:FF:FF:FF':'MyWIFI',...}
</code></pre>
<p>I am still seeing multiple instances of the same key->value pair being written to the file. I put some debugging print statements in and sometimes it will recognize a duplicate, sometimes it will not. This is from a parse pcap with scapy.</p>
<p>Thanks for any help.</p>
<p>*** EDIT: Thanks everyone, I am not really solving my problem the right way with a dictionary. Time to think this through a bit clearer...</p>
| 0 | 2016-08-31T18:29:52Z | 39,256,829 | <p>Dictionaries <em>can't</em> have duplicates:</p>
<pre><code>some_data = [('foo', 'bar'),
('bang', 'quux'),
('foo', 'bar'),
('zappo', 'whoo'),
]
mydict = {}
for data in some_data:
mydict[data[0]] = data[1]
import pprint; print(mydict)
</code></pre>
<p>The only way you're going to re-write the same data is if you aren't opening your file in <code>'w'</code> mode. But</p>
<pre><code>with open('outfile.txt', 'w') as of:
for key in mydict:
of.write('{},{}{}'.format(key, mydict[key], (',' + f + '\n') if verbose else '\n'))
</code></pre>
<p>Will never write the same line twice.</p>
| 1 | 2016-08-31T18:42:16Z | [
"python",
"scapy"
] |
Python: Dedup a dictionary | 39,256,611 | <p>Good afternoon,</p>
<p>I reading in a pcap and am basically trying to get a dedup'd list of BSSID's & ESSID's. I am still getting duplicates with this code and cannot for the life of me figure out what I am doing wrong:</p>
<pre><code>if not (t[0] in ssid_pairs and ssid_pairs[t[0]] == t[1]):
ssid_pairs[t[0]] = t[1]
of.write(t[0] + ',' + t[1] + ((',' + f + '\n') if verbose else '\n'))
</code></pre>
<p>ssid_pairs is a dictionary, t[0] is the bssid & t[1] is the essid. An example of the dictionary is:</p>
<pre><code>{'FF:FF:FF:FF:FF:FF':'MyWIFI',...}
</code></pre>
<p>I am still seeing multiple instances of the same key->value pair being written to the file. I put some debugging print statements in and sometimes it will recognize a duplicate, sometimes it will not. This is from a parse pcap with scapy.</p>
<p>Thanks for any help.</p>
<p>*** EDIT: Thanks everyone, I am not really solving my problem the right way with a dictionary. Time to think this through a bit clearer...</p>
| 0 | 2016-08-31T18:29:52Z | 39,256,844 | <p>Let's say you get:</p>
<pre><code>t[0] = 'foo'
t[1] = 'bar'
</code></pre>
<p>Then we hit your code above:</p>
<pre><code>if not (t[0] in ssid_pairs and ssid_pairs[t[0]] == t[1]):
ssid_pairs[t[0]] = t[1]
of.write(t[0] + ',' + t[1] + ((',' + f + '\n') if verbose else '\n'))
</code></pre>
<p>The condition passes (because <code>t[0]</code> is not in <code>ssid_pairs</code>), so we set:</p>
<pre><code>ssid_pairs[t[0]] = t[1]
</code></pre>
<p>Which gives us:</p>
<pre><code>ssid_pairs = {
'foo': 'bar',
}
</code></pre>
<p>In our next iteration of the loop, we read:</p>
<pre><code>t[0] = 'foo'
t[1] = 'gizmo'
</code></pre>
<p>Your condition passes (because <code>ssid_pairs[t[0]] != t[1]</code>), so we set:</p>
<pre><code>ssid_pairs[t[0]] = t[1]
</code></pre>
<p>Which gives us:</p>
<pre><code>ssid_pairs = {
'foo': 'gizmo',
}
</code></pre>
<p>Then we read the same data we encountered in our first iteration:</p>
<pre><code>t[0] = 'foo'
t[1] = 'bar'
</code></pre>
<p>But because we just <code>ssid_pairs['foo'] = 'gizmo'</code>, your condition will pass again, and you will once again write out the same data.</p>
<p>If you are trying to get a list of unique <em>pairs</em>, then maybe create a set of <code>(essid,bssid)</code> tuples:</p>
<pre><code>seen_pairs = set()
...
if not ((t[0],t(1)) in seen_pairs):
seen_pairs.add((t[0], t[1]))
of.write(t[0] + ',' + t[1] + ((',' + f + '\n') if verbose else '\n'))
</code></pre>
| 1 | 2016-08-31T18:43:20Z | [
"python",
"scapy"
] |
Load a .csv file into a numpy array as a column vector | 39,256,672 | <p>I've got a .csv file that I'm trying to load into a numpy array as a column vector. When using </p>
<pre><code>temp = np.genfromtxt(location, delimiter=',')
</code></pre>
<p>the data is a <code>numpy array</code> where the entries are represented as follows:</p>
<pre><code>[ 0. ... 0. 1. 0. ... 0.], [ 0. ... 1. 0. 0. ... 0.]
</code></pre>
<p>whereas, I would like something like this: </p>
<pre><code>[array([[0],
[0],
[0],
...
[0],
[1],
[0],
...
[0],
[0]]), array([[0],
[0],
[0],
...
[0],
[1],
[0],
...)]
</code></pre>
<p>I'm able to accomplish this using</p>
<pre><code>my_data = []
for i in range(len(temp)):
foo = np.array([temp[i]]).T
my_data.append(foo)
</code></pre>
<p>But am wondering if there is a more efficient way of achieving the required result.</p>
| 0 | 2016-08-31T18:33:13Z | 39,257,012 | <p>Add a new axis to <code>temp</code>, and cast sublists to <em>np arrays</em>:</p>
<pre><code>temp = np.genfromtxt(location, delimiter=',')
my_data = map(np.array, temp[:, :, np.newaxis])
</code></pre>
<hr>
<p>For Python 3, call <code>list</code> on the above result or use a list comprehension:</p>
<pre><code>my_data = [np.array(arr) for arr in temp[:, :, np.newaxis]]
</code></pre>
| 1 | 2016-08-31T18:54:28Z | [
"python",
"arrays",
"csv",
"numpy"
] |
python apply function to df pandas - atribute error | 39,256,717 | <p>I have a data frame "b" with numbers stored as text like '12.5%'.
One column is:</p>
<pre><code>1 NaN
2 NaN
3 1.2%
4 0.6%
5 NaN
6 1.4%
7 0.1%
8 NaN
9 5.1%
10 2.5%
11 89.1%
12 NaN
Name: Idaho, dtype: object
</code></pre>
<p>I've wrote a function to apply to each column:</p>
<pre><code>def sinPorc(tbl):
return float(tbl.replace('%', ''))
</code></pre>
<p>but when I try to apply it I get:</p>
<pre><code>b.Idaho.apply(sinPorc)
</code></pre>
<blockquote>
<p>AttributeError: 'float' object has no attribute 'replace'</p>
</blockquote>
<p>I 've also created an example table, and apply the function but in this case worked:</p>
<pre><code>ejemplo=pd.DataFrame({'A':['1.3%', 'NaN'],
'B':['1.3%', '0.7%']})
ejemplo.A.apply(sinPorc)
</code></pre>
<p>and I got the expected result:</p>
<pre><code> 1.3
NaN
Name: A, dtype: float64
</code></pre>
<p>I don't know why I cannot apply the function to the original table. What might be the problem and what should I do to solve it?</p>
<p>Thanks.</p>
| 0 | 2016-08-31T18:35:46Z | 39,256,993 | <p>Your original method didn't work because NaN was not a string, but the float value <code>np.NaN</code> </p>
<p>Try this... </p>
<pre><code>np.NaN.replace('%', '')
</code></pre>
<p>and you will get the same error.</p>
<pre><code>AttributeError: 'float' object has no attribute 'replace'
</code></pre>
<p>You could change <code>sinPorc</code> to</p>
<pre><code>def sinPorc(tbl):
if tbl is np.NaN:
return tbl
else:
return float(tbl.replace('%', ''))
</code></pre>
<p>Which will preserver your <code>NaN</code> values which are useful for other Pandas functionality, or you could force the value to a string like Nickil mentioned in the comments.</p>
<pre><code>float(str(tbl).replace('%', ''))
</code></pre>
| 2 | 2016-08-31T18:53:03Z | [
"python",
"function",
"pandas",
"attributes",
"apply"
] |
lxml XPath - extracting text from multi p nodes | 39,256,973 | <h2>Please have a look at <a href="http://stackoverflow.com/questions/39242154/lxml-xpath-position-does-not-work">lxml XPath position() does not work</a> first.</h2>
<p>Since XPath does not support to extract text from multi nodes, I decided to write for loop to get 30 stuffs.</p>
<pre><code>for i in range(1,31):
content = "string(//div[@id='article']/p[" + (print(i)) + "]/.)"
print(content)
</code></pre>
<p>I imagined it would return like,</p>
<pre><code>"string(//div[@id='article']/p[1]/.)"
"string(//div[@id='article']/p[2]/.)"
"string(//div[@id='article']/p[3]/.)"
....
"string(//div[@id='article']/p[30]/.)"
</code></pre>
<p>However, obviously it does not work as I expected.. I got error message as following.</p>
<pre><code>TypeError: Can't convert 'NoneType' object to str implicitly
</code></pre>
<p>What should I do? Any other elegant approach to solve this problem?</p>
| 0 | 2016-08-31T18:51:21Z | 39,257,015 | <p>In Python3, <code>print</code> is a <em>function</em> which prints to the screen <em>and returns</em> <code>None</code>. (In Python2, <code>print</code> is a <em>statement</em> and the code would have raised an error since you can't put a statement in the middle of an expression.) Instead, to build a string use the <code>format</code> method:</p>
<pre><code>content = "string(//div[@id='article']/p[{}]/.)".format(i)
</code></pre>
<hr>
<p>And by the way, you should be able to use <code>position()</code> just fine with lxml. For instance,</p>
<pre><code>import lxml.html as LH
content = '''\
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
<book>
<title lang="eng">Things Fall Apart</title>
<price>19.99</price>
</book>
<book>
<title lang="eng">Blood Meridian</title>
<price>9.99</price>
</book>
</bookstore>'''
root = LH.fromstring(content)
# Compare with http://stackoverflow.com/a/39242701/190597
print(root.xpath('//book[position()>=1 and position()<=last()]/title/text()'))
# ['Harry Potter', 'Learning XML', 'Things Fall Apart', 'Blood Meridian']
# But note that it is equivalent to
print(root.xpath('//book/title/text()'))
# ['Harry Potter', 'Learning XML', 'Things Fall Apart', 'Blood Meridian']
print(root.xpath('//book[position()<3]'))
</code></pre>
<p>prints</p>
<pre><code>['Harry Potter', 'Learning XML']
</code></pre>
<p>which shows that you can select the first <code>N</code> <code>books</code> without having to loop.</p>
<hr>
<p><a href="http://stackoverflow.com/questions/39242154/lxml-xpath-position-does-not-work#comment65822655_39242701">As Tomalak mentions</a>, the XPath <code>string</code> function only returns the string representation of the first node. For example,</p>
<pre><code>print(root.xpath('string(//book[position()<3]/title/text())'))
</code></pre>
<p>only prints</p>
<pre><code>Harry Potter
</code></pre>
<p>If you want a list of strings, then don't use <code>string</code>.</p>
<p>If, as <a href="http://stackoverflow.com/questions/39256973/lxml-xpath-extracting-text-from-multi-p-nodes/39257015?noredirect=1#comment65851036_39257015">Daniel Haley points out</a>, the desired text is in a mixture of nested nodes and child elements, e.g. <code><title lang="eng">Harry <b>Potter</b></title></code>, then you can extract the desired text using the <code>text_content</code> method:</p>
<pre><code>[title.text_content() for title in root.xpath('//book[position()<3]/title')]
</code></pre>
| 1 | 2016-08-31T18:54:33Z | [
"python",
"python-3.x",
"xpath",
"lxml"
] |
lxml XPath - extracting text from multi p nodes | 39,256,973 | <h2>Please have a look at <a href="http://stackoverflow.com/questions/39242154/lxml-xpath-position-does-not-work">lxml XPath position() does not work</a> first.</h2>
<p>Since XPath does not support to extract text from multi nodes, I decided to write for loop to get 30 stuffs.</p>
<pre><code>for i in range(1,31):
content = "string(//div[@id='article']/p[" + (print(i)) + "]/.)"
print(content)
</code></pre>
<p>I imagined it would return like,</p>
<pre><code>"string(//div[@id='article']/p[1]/.)"
"string(//div[@id='article']/p[2]/.)"
"string(//div[@id='article']/p[3]/.)"
....
"string(//div[@id='article']/p[30]/.)"
</code></pre>
<p>However, obviously it does not work as I expected.. I got error message as following.</p>
<pre><code>TypeError: Can't convert 'NoneType' object to str implicitly
</code></pre>
<p>What should I do? Any other elegant approach to solve this problem?</p>
| 0 | 2016-08-31T18:51:21Z | 39,257,018 | <p>The trailing <code>/.</code> in your xpath is invalid. </p>
<p>Try: </p>
<pre><code>content = "string(//div[@id='article']/p[" + (print(i)) + "])"
</code></pre>
<p>Full example:</p>
<pre class="lang-py prettyprint-override"><code>import lxml.html
html = """<tag1>
<tag2>
<div id="article">
<p> stuff1 </p>
<p> stuff2 </p>
<p> stuff30 <b>more stuff</b></p>
</div>
</tag2>
</tag1>"""
root = lxml.html.fromstring(html)
for i in range(1,4):
content = root.xpath("string(//div[@id='article']/p[" + str(i) + "])")
print(content)
#stuff1
#stuff2
#stuff30 more stuff
</code></pre>
| 1 | 2016-08-31T18:54:44Z | [
"python",
"python-3.x",
"xpath",
"lxml"
] |
Call a Python function in a file with command-line argument | 39,256,977 | <p>I'm trying to pass arguments from Node.js to Python with <code>child_process</code> spawn. I also want to invoke the specific Python function with one of the argument that I specified in the Node.js array.</p>
<p><code>test.js</code></p>
<pre><code>'use strict';
const path = require('path');
const spawn = require('child_process').spawn;
const exec = (file, fnCall, argv1, argv2) => {
const py = spawn('python', [path.join(__dirname, file), fnCall, argv1, argv2]);
py.stdout.on('data', (chunk) => {
const textChunk = chunk.toString('utf8'); // buffer to string
const array = textChunk.split(', ');
console.log(array);
});
};
exec('lib/test.py', 'test', 'argument1', 'argument2'.length - 2); // => [ 'argument1', '7' ]
exec('lib/test.py', 'test', 'arg3', 'arg4'.length - 2); // => [ 'arg3', '2' ]
</code></pre>
<p>The second argument here is <code>test</code>, which should call the <code>test()</code> Python function.</p>
<p><code>lib/test.py</code>:</p>
<pre><code>import sys
def test():
first_arg = sys.argv[2]
second_arg = sys.argv[3]
data = first_arg + ", " + second_arg
print(data, end="")
sys.stdout.flush()
</code></pre>
<p>If I try to run this Python file without any Node.js from the command line, the execution looks like this:</p>
<p><code>$ python lib/test.py test arg3 2</code></p>
<p>Where <code>test</code>, <code>arg3</code>, and <code>2</code> are just command-line arguments, but <code>test</code> should call the <code>test()</code> function, which will use the <code>arg3</code>, <code>2</code> arguments for <code>print()</code>.</p>
| 1 | 2016-08-31T18:51:36Z | 39,257,140 | <p>I'd recommend using <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse</a> to parse the command line arguments. Then you can use <a href="https://docs.python.org/3.5/library/functions.html#eval" rel="nofollow">eval</a> to get the actual function from the input.</p>
<pre><code>import argparse
def main():
# Parse arguments from command line
parser = argparse.ArgumentParser()
# Set up required arguments this script
parser.add_argument('function', type=str, help='function to call')
parser.add_argument('first_arg', type=str, help='first argument')
parser.add_argument('second_arg', type=str, help='second argument')
# Parse the given arguments
args = parser.parse_args()
# Get the function based on the command line argument and
# call it with the other two command line arguments as
# function arguments
eval(args.function)(args.first_arg, args.second_arg)
def test(first_arg, second_arg):
print(first_arg)
print(second_arg)
if __name__ == '__main__':
main()
</code></pre>
| 2 | 2016-08-31T19:01:46Z | [
"python",
"arguments",
"command-line-arguments",
"sys"
] |
how to use for loop to iterating url index to collect the data | 39,256,983 | <p>I am a newbie in python. I want to write a for loop to iterate the index in order to pull the data. </p>
<p>Here is my code:</p>
<pre><code>url90=[]
for i in range(-90,0):
url90.append('http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&**index=i**&filter={}&filterOverride=0&su=1')
</code></pre>
<p>I want index=i which from range(-90,0), however the python consider my i as a string instead of a integer. </p>
<p>my result give me 90 identical url :</p>
<pre><code>'http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&index=i&filter={}&filterOverride=0&su=1'
</code></pre>
<p>Is there anyone can help me to solve the problem?</p>
<p>Thank you!</p>
| 2 | 2016-08-31T18:52:11Z | 39,257,156 | <p>If you think that <code>i</code> variable will automatically be used in the string used to populate the list, you are wrong. It does not work that way. Use <code>.format</code>:</p>
<pre><code>url90=[]
for i in range(-90,0):
url90.append('http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&index={0}&filter={{}}&filterOverride=0&su=1'.format(i))
print("\n".join(url90))
</code></pre>
<p>See <a href="http://ideone.com/0isAAv" rel="nofollow">Python demo</a></p>
<p>Note that literal <code>{</code> and <code>}</code> in the format string must be doubled (see <code>index={0}</code>). The <code>{0}</code> is a placeholder for the <code>i</code> variable (see <code>filter={{}}</code>) that is the first and only argument to the method.</p>
| 1 | 2016-08-31T19:02:21Z | [
"python",
"string",
"for-loop"
] |
sort a list by prefered order | 39,257,017 | <p>is it possible to sort through a list and do something depending on your preferred order or pre determined choice?</p>
<p>so i have a list of files containing definitions, if i re.search the string and return a match, i would like to only print the string + highest definition</p>
<p>i started to explore the below idea but i cannot seem to get it to print only the highest -currently it prints all 3</p>
<pre><code>#!/usr/bin/python3
import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4','movie_c_SD.mp4']
for each in some_files:
for defs in definitions:
match = re.search(defs, each, re.M | re.I)
if match:
if match.group() == '1080p':
print('1080p', each)
break
else:
if match.group() == '720p':
print('720p', each)
break
else:
if match.group() == 'SD':
print('SD', each)
break
</code></pre>
<p>any help would be awesome</p>
| 2 | 2016-08-31T18:54:38Z | 39,257,112 | <p>If you want only a single result (the highest) and considering that your list is ordered highest to lowest, you can simply return after the first result was found:</p>
<pre><code>import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4', 'movie_c_SD.mp4']
def find():
for each in some_files:
for defs in definitions:
match = re.search(defs, each, re.M | re.I)
if match:
return match.group(0)
print(find())
</code></pre>
| 1 | 2016-08-31T19:00:30Z | [
"python",
"python-2.7",
"python-3.x"
] |
sort a list by prefered order | 39,257,017 | <p>is it possible to sort through a list and do something depending on your preferred order or pre determined choice?</p>
<p>so i have a list of files containing definitions, if i re.search the string and return a match, i would like to only print the string + highest definition</p>
<p>i started to explore the below idea but i cannot seem to get it to print only the highest -currently it prints all 3</p>
<pre><code>#!/usr/bin/python3
import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4','movie_c_SD.mp4']
for each in some_files:
for defs in definitions:
match = re.search(defs, each, re.M | re.I)
if match:
if match.group() == '1080p':
print('1080p', each)
break
else:
if match.group() == '720p':
print('720p', each)
break
else:
if match.group() == 'SD':
print('SD', each)
break
</code></pre>
<p>any help would be awesome</p>
| 2 | 2016-08-31T18:54:38Z | 39,257,183 | <p>If I understand what you're trying to do, this should work:</p>
<pre><code>def best(some_files):
for definition in ('1080p', '720p', 'SD'):
match = next((file for file in some_files if definition in file), None)
if match is not None:
return match
print(best(['movie_a_1080p.mp4', 'movie_b_720p.mp4', 'movie_c_SD.mp4'])) # movie_a_1080p.mp4
print(best(['movie_b_720p.mp4', 'movie_c_SD.mp4', 'movie_a_1080p.mp4'])) # movie_a_1080p.mp4
print(best(['movie_b_720p.mp4', 'movie_c_SD.mp4'])) # movie_b_720p.mp4
print(best(['movie_d.mp4', 'movie_c_SD.mp4'])) # movie_c_SD.mp4
print(best(['movie_d.mp4'])) # None
</code></pre>
<p>The main issue with your approach is that the <code>break</code> only breaks out of the nearest loop. @alfasin's answer fixes this by <code>return</code>ing from a function instead.</p>
<p>My answer could also just be used without a function if you want, since it only has one loop to break out of:</p>
<pre><code>for definition in ('1080p', '720p', 'SD'):
match = next((file for file in some_files if definition in file), None)
if match is not None:
print('Found the best one: {}'.format(match))
break
</code></pre>
| 1 | 2016-08-31T19:03:37Z | [
"python",
"python-2.7",
"python-3.x"
] |
sort a list by prefered order | 39,257,017 | <p>is it possible to sort through a list and do something depending on your preferred order or pre determined choice?</p>
<p>so i have a list of files containing definitions, if i re.search the string and return a match, i would like to only print the string + highest definition</p>
<p>i started to explore the below idea but i cannot seem to get it to print only the highest -currently it prints all 3</p>
<pre><code>#!/usr/bin/python3
import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4','movie_c_SD.mp4']
for each in some_files:
for defs in definitions:
match = re.search(defs, each, re.M | re.I)
if match:
if match.group() == '1080p':
print('1080p', each)
break
else:
if match.group() == '720p':
print('720p', each)
break
else:
if match.group() == 'SD':
print('SD', each)
break
</code></pre>
<p>any help would be awesome</p>
| 2 | 2016-08-31T18:54:38Z | 39,257,613 | <p>Since your <code>definitions</code> is in order, you can just traverse the lists, and return the file when a match is found. </p>
<pre><code>def best_quality(l):
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
for definition in definitions:
for file in some_files:
if definition in file: return file
some_files = ['movie_c_SD.mp4', 'movie_a_1080p.mp4', 'movie_b_720p.mp4']
print best_quality(some_files)
>>> movie_a_1080p.mp4
</code></pre>
| 3 | 2016-08-31T19:30:44Z | [
"python",
"python-2.7",
"python-3.x"
] |
Theano crashing using cuDNN in linux | 39,257,060 | <p>I am a non-root user on a cluster computer running Scientific Linux release 6.6 (Carbon). </p>
<p>I am experiencing some theano crashes when running code on a GPU with CUDA 7.5 and cuDNN 5. I am using Python 2.7, Theano 0.9, Keras 1.0.7 and Lasange 0.1.</p>
<p>The following crash occurs ONLY when I run the program on a GPU node with cuDNN enabled. The code completes without issue on a CPU and a GPU with cuDNN disabled. </p>
<pre><code>Traceback (most recent call last):
File "runner.py", line 306, in <module>
main()
File "runner.py", line 241, in main
queries_exp = __import__(args.exp_model).queries_exp
File "/mnt/nfs2/inf/tjb32/workspace/CNN_EL/nlp-entity-convnet/exp_multi_conv_cosim.py", line 923, in <module>
queries_exp = EntityVectorLinkExp()
File "/mnt/nfs2/inf/tjb32/workspace/CNN_EL/nlp-entity-convnet/exp_multi_conv_cosim.py", line 51, in __init__
self._setup()
File "/mnt/nfs2/inf/tjb32/workspace/CNN_EL/nlp-entity-convnet/exp_multi_conv_cosim.py", line 543, in _setup
on_unused_input='ignore',
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/compile/function.py", line 326, in function
output_keys=output_keys)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/compile/pfunc.py", line 484, in pfunc
output_keys=output_keys)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/compile/function_module.py", line 1788, in orig_function
output_keys=output_keys).create(
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/compile/function_module.py", line 1467, in __init__
optimizer_profile = optimizer(fgraph)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 102, in __call__
return self.optimize(fgraph)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 90, in optimize
ret = self.apply(fgraph, *args, **kwargs)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 235, in apply
sub_prof = optimizer.optimize(fgraph)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 90, in optimize
ret = self.apply(fgraph, *args, **kwargs)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 235, in apply
sub_prof = optimizer.optimize(fgraph)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 90, in optimize
ret = self.apply(fgraph, *args, **kwargs)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 2262, in apply
lopt_change = self.process_node(fgraph, node, lopt)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 1825, in process_node
lopt, node)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 1719, in warn_inplace
return NavigatorOptimizer.warn(exc, nav, repl_pairs, local_opt, node)
File "/home/t/tj/tjb32/.local/lib/python2.7/site-packages/theano/gof/opt.py", line 1705, in warn
raise exc
AssertionError
</code></pre>
<p>My .theanorc looks like this:</p>
<pre><code>[global]
floatX = float32
device = gpu
[lib]
cnmem = 1
[nvcc]
fastmath = True
</code></pre>
<p>And my profile has the following:</p>
<pre><code>export LD_LIBRARY_PATH=/home/t/tj/tjb32/cuda/lib64:$LD_LIBRARY_PATH
export CPATH=/home/t/tj/tjb32/cuda/include:$CPATH
export LIBRARY_PATH=/home/t/tj/tjb32/cuda/lib64:$LD_LIBRARY_PATH
export PATH=/home/t/tj/tjb32/cuda/bin:$PATH
</code></pre>
<p>When I query theano, the following is returned, which suggests to me that theano is interacting with CUDA and cuDNN.</p>
<pre><code>Using gpu device 0: Tesla K20m (CNMeM is enabled with initial size: 95.0% of memory, cuDNN 5005)
</code></pre>
<p>I'm fairly sure that I have installed CUDA and cuDNN correctly, if anyone could suggest any additional configuration steps that I may have missed that is causing cuDNN to crash the program, that would be greatly appreciated. </p>
| 0 | 2016-08-31T18:57:23Z | 39,265,420 | <p>Not sure if this can be the issues but:
export LIBRARY_PATH=/home/t/tj/tjb32/cuda/lib64:$<strong>LD_</strong>LIBRARY_PATH
should be?
export LIBRARY_PATH=/home/t/tj/tjb32/cuda/lib64:$LIBRARY_PATH</p>
| 0 | 2016-09-01T07:34:43Z | [
"python",
"linux",
"theano",
"theano-cuda",
"cudnn"
] |
flask: get session time remaining via AJAX | 39,257,102 | <p>I am using Flask, with the flask-session plugin for server-side sessions stored in a Redis backend. I have flask set up to use persistent sessions, with a session timeout. How can I make an AJAX request to get the time remaining on the session without resetting the timeout?</p>
<p>The idea is for the client to check with the server before displaying a timeout warning (or logging out the user) in case the user is active in a different tab/window of the same browser.</p>
<p>EDIT: after some digging, I found the config directive <code>SESSION_REFRESH_EACH_REQUEST</code>, which it <em>appears</em> I should be able to use to accomplish what I want: set that to False, and then the session should only be refreshed if something actually changes in the session, so I should be able to make a request to get the timeout without the session timeout changing. It was added in 0.11, and I'm running 0.11.1, so it <em>should</em> be available.</p>
<p>Unfortunately, in practice this doesn't appear to work - at least when checking the <code>ttl</code> of the redis key to get the time remain. I checked, and <code>session.modified</code> is False, so it's not just that I am doing something in the request that modifies the session (unless it just doesn't set that flag)</p>
| 1 | 2016-08-31T19:00:08Z | 39,259,673 | <p>The following works, though it is rather hacky:</p>
<p>In the application <code>__init__.py</code>, or wherever you call <code>Session(app)</code> or <code>init_app(app)</code>:</p>
<pre><code>#set up the session
Session(app)
# Save a reference to the original save_session function so we can call it
original_save_session = app.session_interface.save_session
#----------------------------------------------------------------------
def discretionary_save_session(self, *args, **kwargs):
"""A wrapper for the save_session function of the app session interface to
allow the option of not saving the session when calling specific functions,
for example if the client needs to get information about the session
(say, expiration time) without changing the session."""
# bypass: list of functions on which we do NOT want to update the session when called
# This could be put in the config or the like
#
# Improvement idea: "mark" functions on which we want to bypass saving in
# some way, then check for that mark here, rather than having a hard-coded list.
bypass = ['check_timeout']
#convert function names to URL's
bypass = [flask.url_for(x) for x in bypass]
if not flask.request.path in bypass:
# if the current request path isn't in our bypass list, go ahead and
# save the session normally
return original_save_session(self, *args, **kwargs)
# Override the save_session function to ours
app.session_interface.save_session = discretionary_save_session
</code></pre>
<p>Then, in the <code>check_timeout</code> function (which is in the bypass list, above), we can do something like the following to get the remaining time on the session:</p>
<pre><code>@app.route('/auth/check_timeout')
def check_timeout():
""""""
session_id = flask.session.sid
# Or however you want to get a redis instance
redis = app.config.get('REDIS_MASTER')
# If used
session_prefix = app.config.get('SESSION_KEY_PREFIX')
#combine prefix and session id to get the session key stored in redis
redis_key = "{}{}".format(session_prefix, session_id)
# The redis ttl is the time remaining before the session expires
time_remain = redis.ttl(redis_key)
return str(time_remain)
</code></pre>
<p>I'm sure the above can be improved upon, however the result is as desired: when calling <code>/auth/check_timeout</code>, the time remaining on the session is returned without modifying the session in any way.</p>
| 0 | 2016-08-31T22:01:22Z | [
"python",
"ajax",
"session",
"flask"
] |
WxPython, How to fill ListBox with class attributes | 39,257,126 | <p>I am building a wxpython project, I have a list of elements that are a class instances. Each of this elements has an attribute <code>title</code>. In a ListBox I want to display only the titles, and when the title selected, after we GetSelection from listbox, the instance should be returned and not just the title. Is this achievable ?</p>
<p><strong>Note:</strong> Searching for the string is out of question because names(titles) may be recurring.</p>
<p>Thank you.</p>
| 0 | 2016-08-31T19:01:07Z | 39,257,327 | <ul>
<li>Put your instances in a list</li>
<li>Use <code>GetSelection</code> to retrieve the index of the item you selected from the listbox</li>
<li>Get the corresponding instance from that index in the list</li>
</ul>
| 1 | 2016-08-31T19:12:41Z | [
"python",
"listbox",
"wxpython"
] |
How to fix <Response [400]> while make a POST in Python? | 39,257,168 | <p>I kept getting <code><Response [400]></code> in my terminal while running the script.</p>
<p>I have tried </p>
<pre><code>import requests
import json
url = 'http://172.19.242.32:1234/vse/account'
data = '{
"account_id": 1008,
"email_address": "bhills_4984@mailinator.com",
"password": "qqq",
"account_type": "customer",
"name_prefix": "",
"first_name": "Beverly",
"middle_names": "",
"last_name": "Hills",
"name_suffix": "",
"non_person_name": false,
"DBA": "",
"display_name": "BeverlyHills",
"address1": "4984 Beverly Dr",
"address2": "4984 Beverly Dr",
"address3": "",
"city": "Beverly Hills",
"state": "CA",
"postal_code": "90210",
"nation_code": "90210",
"phone1": "3105554984",
"phone2": "",
"phone3": "",
"time_zone_offset_from_utc": -5,
"customer_type": "2",
"longitude": -118.4104684,
"latitude": 34.1030032,
"altitude": 0
}'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)
print r
</code></pre>
<hr>
<p>What did I do wrong ?</p>
| 0 | 2016-08-31T19:02:54Z | 39,257,227 | <p>Change </p>
<pre><code>r = requests.post(url, data=json.dumps(data), headers=headers)
</code></pre>
<p>to</p>
<pre><code>r = requests.post(url, data=data, headers=headers)
</code></pre>
<p>because data is not a dict that must be transformed to json but is already json.</p>
| 4 | 2016-08-31T19:05:57Z | [
"python",
"request",
"http-status-code-400"
] |
Python interpreter PATH oddity. Can't use django | 39,257,191 | <p>I have three Python environments across two different interpreters. The first is the basic Python27 in my c:. The second is an Anaconda interpreter with its own environment and another environment in it's \envs\ directory. I have directed my PYTHONPATH variable to point to the Anaconda interpreter not in the \envs\ folder.
<a href="http://i.stack.imgur.com/VFmP0.png" rel="nofollow"><img src="http://i.stack.imgur.com/VFmP0.png" alt="enter image description here"></a></p>
<p>I also have my PATH variable set to the scripts directory from that environment <a href="http://i.stack.imgur.com/8eIIv.png" rel="nofollow"><img src="http://i.stack.imgur.com/8eIIv.png" alt="enter image description here"></a></p>
<p>However, when I run Django, I get a message about a discrepancy in versions. I think this results from the fact that Django is using the interpreter in my C:\ directory, Python27. When I echo my PATH environment variable in cmd, this is what I see:</p>
<pre><code>C:\Program Files (x86)\ActiveState Komodo Edit 10\;C:\Program Files (x86)\ActiveState Komodo IDE 10\;
C:\Program Files\MATLAB\R2014a\bin\win64;
C:\ProgramData\Oracle\Java\javapath;
c:\Program Files (x86)\Intel\iCLS Client\;
c:\Program Files\Intel\iCLS Client\;
C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;
C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;
C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;
**C:\Python27**;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C:\Program Files (x86)\Skype\Phone\;
C:\Program Files\MATLAB\R2016a\runtime\win64;
C:\Program Files\MATLAB\R2016a\bin;
C:\WINDOWS\system32;
C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\Users\jackf_000\sw\FFMPEG\bin;
C:**\Users\jackf_000\sw\Anaconda2\Scripts\**;
</code></pre>
<p>C:\cygwin64\bin;C:\Users\jackf_000\AppData\Local\Microsoft\WindowsApps;</p>
<p>When I run python in cmd and import os to see the executable, I get the following output:</p>
<pre><code>C:\Users\jackf_000>python
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'C:\\Python27\\python.exe'
</code></pre>
<p>Why is the Python interpreter from C:\ in the PATH variable before the Anaconda one if I do not have it specified anywhere in PATH in the control panel window? And how can I specify that I want Django to look in the Anaconda environment for what it needs, or use pip to install to Django to C:\Python27? Currently, pip installs all packages to the Anaconda environment.</p>
| 0 | 2016-08-31T19:04:02Z | 39,257,356 | <p>Because python 2.7 path is set in the system environment variable PATH. You are editing your user variables (which are bizarrely configured because they contain duplicate stuff only found in system path like <code>C:\windows\system32</code> for instance)</p>
<p>if you type <code>where python</code> you'll probably get:</p>
<pre><code>C:\Python27\python.exe
</code></pre>
<p>(EDIT: you actually get that value, since you answered to my comment)</p>
<p>if you type <code>where pip</code> you'll probably get:</p>
<pre><code>C:\users\jackf_000\sw\anaconda2\scripts\pip.exe
</code></pre>
<p>which explains that pip installs package in the anaconda2 package</p>
<p>To get anaconda python in your path you would need to add <code>C:\users\jackf_000\sw\anaconda2</code> not the scripts subdir that contain pip.</p>
<p>then, if you typed <code>where python</code> you'll probably get:</p>
<pre><code>C:\Python27\python.exe
C:\users\jackf_000\sw\anaconda2\python.exe
</code></pre>
<p>But that wouldn't be enough because..</p>
<p>The system path comes first. PATH is one special env variable that you dont override with your user profile, only append dirs to. And it's perfectly normal to have one user PATH variable and one system PATH variable.</p>
<p>On the other hand, let's say the system variable <code>PYTHONPATH</code> does not please you, you could choose to replace it by setting a completely different one in your user variables. That would replace the paths, not append to them, unless you add <code>;%PYTHONPATH%</code> somewhere (<code>PYTHONPATH</code> is a path variable, but unknown by windows, it's nothing special). And PYTHONPATH does not influence which executable will be loaded, so forget it for now.</p>
<p>2 solutions:</p>
<ol>
<li>modify system path (admin needed) to add anaconda is before python 2.7 (not recommended)</li>
<li><p>run your applications which require anaconda with a .bat file starting by the following:</p>
<p><code>set PATH=C:\users\jackf_000\sw\anaconda2;%PATH%
rem now run the command which needs anaconda python first</code></p></li>
</ol>
| 1 | 2016-08-31T19:14:16Z | [
"python",
"django",
"environment-variables",
"windows-10"
] |
How can i insert a scrollbar in my Tk window? | 39,257,319 | <p>I wrote this for my school project, but I can't figure out how to add a scroll bar.</p>
<pre><code>from Tkinter import* #import Tk
main_s= Tk() #forming a Tk window
fundo = PhotoImage(file="d.gif")
class Welcome:
def __init__(self):
def proceed():
main_s.update() #config of the Tk window
main_s.config(bg="yellow")
Label(main_s,text="Choose your curve",fg="red",font=("arial",20)).pack()
var=IntVar() #variable for values of radios
r1=Radiobutton(main_s,text="Circle",variable=var,value=1,command=curves) '''creating radiobuttons which come below the canvas for which the scroll bar is needed'''
r2=Radiobutton(main_s,text="Parabola",variable=var,value=2,command=curves)
r3=Radiobutton(main_s,text="Ellipse",variable=var,value=3,command=curves)
r4=Radiobutton(main_s,text="Line",variable=var,value=4,command=curves)
r5=Radiobutton(main_s,text="Hyperbola",variable=var,value=5,command=curves)
r1.pack()
r2.pack()
r3.pack()
r4.pack() #packing of radiom buttons
r5.pack()
# execution starts here, working with a Canvas object.
# the indentation level is same for __init__ of class
self.scr = Canvas(main_s, width=1000, height=600) #creating a canvas
self.scr.pack()
self.scr.create_image(0, 0, image=fundo, anchor='nw') #placing image inside the canvas
main_s.config(bg="orange")
main_s.title("*********")
btn=Button(main_s,text="*********",fg="orange",command=proceed)
btn.pack()
def curves():
class Curves:
def __init__(self):
main_s.update() #adding more content to follow
i=Label(main_s,text="**********")
i.pack()
self.rotation=Entry(main_s)
self.rotation.pack()
i1=Label(main_s,text="*************")
i1.pack()
self.xshift=Entry(main_s) #action of radio buttons
self.xshift.pack()
i2=Label(main_s,text="**************")
i2.pack()
self.yshift=Entry(main_s)
self.yshift.pack()
t=Curves()
# execution of radio buttons command
#execution -calling the above instances
Welcome()
main_s.mainloop()
</code></pre>
| -1 | 2016-08-31T19:12:02Z | 39,318,073 | <p>Here is your standard vetical scrollbar. Nice project by the way, at our school the most complicated thing we do is text based programs XD</p>
<p>I see you're new to stack overflow, what you wanna do is press that nice big green tick next to my answer :)</p>
<pre><code>from Tkinter import* #import Tk
main_s= Tk() #forming a Tk window
fundo = PhotoImage(file="d.gif")
class Welcome:
def __init__(self):
def proceed():
main_s.update() #config of the Tk window
main_s.config(bg="yellow")
Label(main_s,text="Choose your curve",fg="red",font=("arial",20)).pack()
var=IntVar() #variable for values of radios
r1=Radiobutton(main_s,text="Circle",variable=var,value=1,command=curves) #'''creating radiobuttons which come below the canvas for which the scroll bar is needed'''
r2=Radiobutton(main_s,text="Parabola",variable=var,value=2,command=curves)
r3=Radiobutton(main_s,text="Ellipse",variable=var,value=3,command=curves)
r4=Radiobutton(main_s,text="Line",variable=var,value=4,command=curves)
r5=Radiobutton(main_s,text="Hyperbola",variable=var,value=5,command=curves)
r1.pack()
r2.pack()
r3.pack()
r4.pack() #packing of radiom buttons
r5.pack()
# execution starts here, working with a Canvas object.
# the indentation level is same for __init__ of class
self.frame = Frame(main_s)
self.scr = Canvas(self.frame, width=1000, height=200, scrollregion = (0, 0, 0, 500)) #creating a canvas
self.bar = Scrollbar(self.frame, orient = "vertical")
self.scr.grid(row = 0, column = 1)
self.bar.grid(row = 0, column = 0, sticky = "ns")
self.scr.config(yscrollcommand = self.bar.set)
self.bar.config(command = self.scr.yview)
self.frame.pack()
self.scr.create_image(0, 0, image=fundo, anchor='nw') #placing image inside the canvas
main_s.config(bg="orange")
main_s.title("*********")
btn=Button(main_s,text="*********",fg="orange",command=proceed)
btn.pack()
def curves():
class Curves:
def __init__(self):
main_s.update() #adding more content to follow
i=Label(main_s,text="**********")
i.pack()
self.rotation=Entry(main_s)
self.rotation.pack()
i1=Label(main_s,text="*************")
i1.pack()
self.xshift=Entry(main_s) #action of radio buttons
self.xshift.pack()
i2=Label(main_s,text="**************")
i2.pack()
self.yshift=Entry(main_s)
self.yshift.pack()
t=Curves()
# execution of radio buttons command
#execution -calling the above instances
Welcome()
main_s.mainloop()
</code></pre>
| 0 | 2016-09-04T14:39:43Z | [
"python",
"tkinter",
"tk"
] |
Django custom command - Not Implemented Error | 39,257,379 | <p>I'm trying to set up a cronjob on my Ubuntu server to run a django <code>.py</code> file - but I'm having trouble running the script first.</p>
<p>I'm using the command <code>python3 /opt/mydir/manage.py updatefm</code> </p>
<p>which produces the error:</p>
<pre><code>File "/opt/mydir/manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 324, in handle
raise NotImplementedError()
NotImplementedError
</code></pre>
<p>Can anybody enlighten my on what I'm doing incorrect? Here is my script and structure:</p>
<pre><code>/mydir
/mydir
__init__.py
/management
__init__.py
/commands
updatefm.py
</code></pre>
<p><strong>updatefm.py</strong></p>
<pre><code>class Command(BaseCommand):
args = ''
help = 'Help Test'
def update_auto(self, *args, **options):
hi = 'test'
</code></pre>
<p>My app name is listed in <code>settings.py</code> as it should be. </p>
| 0 | 2016-08-31T19:15:58Z | 39,257,651 | <p>Check <code>__init__.py</code> inside <code>commands</code> folder. Then you have to use <code>handle</code> method</p>
<pre><code>class Command(BaseCommand):
args = ''
help = 'Help Test'
def handle(self, *args, **options):
hi = 'test
</code></pre>
<p>For more info <a href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/#django.core.management.BaseCommand.handle" rel="nofollow">https://docs.djangoproject.com/en/dev/howto/custom-management-commands/#django.core.management.BaseCommand.handle</a></p>
| 1 | 2016-08-31T19:33:52Z | [
"python",
"django",
"python-3.x"
] |
Django custom command - Not Implemented Error | 39,257,379 | <p>I'm trying to set up a cronjob on my Ubuntu server to run a django <code>.py</code> file - but I'm having trouble running the script first.</p>
<p>I'm using the command <code>python3 /opt/mydir/manage.py updatefm</code> </p>
<p>which produces the error:</p>
<pre><code>File "/opt/mydir/manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 324, in handle
raise NotImplementedError()
NotImplementedError
</code></pre>
<p>Can anybody enlighten my on what I'm doing incorrect? Here is my script and structure:</p>
<pre><code>/mydir
/mydir
__init__.py
/management
__init__.py
/commands
updatefm.py
</code></pre>
<p><strong>updatefm.py</strong></p>
<pre><code>class Command(BaseCommand):
args = ''
help = 'Help Test'
def update_auto(self, *args, **options):
hi = 'test'
</code></pre>
<p>My app name is listed in <code>settings.py</code> as it should be. </p>
| 0 | 2016-08-31T19:15:58Z | 39,257,714 | <p>Classes inheriting from <code>BaseCommand</code> must implement the method <code>handle</code>. </p>
<p>In your case, you should change </p>
<p><code>def update_auto(self, *args, **options):</code></p>
<p>to </p>
<p><code>def handle(self, *args, **options):</code></p>
| 1 | 2016-08-31T19:38:51Z | [
"python",
"django",
"python-3.x"
] |
Combining Pandas Dataframe with indexed value as column name | 39,257,459 | <p>Given the following two pandas DataFrames:</p>
<pre><code>main_table = pd.DataFrame([[1, 'A'],
[2, 'B'],
[3,'C']],
columns=['id', 'label'])
extras_table = pd.DataFrame([[1, 'e1', 'e1_Val'],
[1, 'e2', 'e2_Val'],
[2, 'e2', 'e2_Val2'],
[3, 'e1', 'e1_val3']],
columns=['main_id', 'col_label', 'value'])
</code></pre>
<p>I want to use the 'main_id' column of extras_table, and 'col_label' to create additional columns on main_table. i.e.:</p>
<pre><code>result:
id label e1 e2
0 1 A e1_Val e2_Val
1 2 B None e2_Val2
2 3 C e1_val3 None
</code></pre>
<p>Note that some of the rows may not have all of the new columns. Is this possible in Pandas, without iterating over extras table, and adding the new columns/values?</p>
| 1 | 2016-08-31T19:20:27Z | 39,257,573 | <pre><code>xdf = extras_table.set_index(['main_id', 'col_label']) \
.unstack().value.reset_index('main_id')
main_table.merge(xdf, left_on='id', right_on='main_id').drop('main_id', axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/uPy0S.png" rel="nofollow"><img src="http://i.stack.imgur.com/uPy0S.png" alt="enter image description here"></a></p>
| 3 | 2016-08-31T19:28:28Z | [
"python",
"pandas",
"dataframe"
] |
Import Selenium IDE script as unittest.TestCase and Modify Dynamically | 39,257,481 | <p>I am writing a program in python that will generate more robust data and reports from Selenium tests. I want to be able to export a test case from Selenium IDE from Firefox, and without modifying that specific exported python file, inject it into my script and allow my script to make modifications such as changing the webdriver (part of the implementation is for a Nagios server, which will use PhantomJS as the driver) and pulling request information and screenshots for reporting (Btw, I know I can change the driver in the IDE template, but it's just an example).</p>
<p>Lets say I have a file exported from the IDE <i>path/to/mytests/search.py</i>:</p>
<pre><code>import...
class Search(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.base_url = 'http://www.example.com'
def test_search(self):
driver = self.driver
driver.get(self.base_url)
elem = self.driver.find_element_by_name('q')
elem.send_keys('nagios')
elem.send_keys(Keys.RETURN)
assert 'No results found.' not in self.driver.page_source
driver.get(self.base_url + '/status')
assert 'OK' in self.driver.page_source
def tearDown(self):
self.driver.quit()
</code></pre>
<p>I want my script to be able to do this:</p>
<pre><code>python -m my_wrapper mytests.search --url 'http://www.google.com'
</code></pre>
<p>Which will somehow import <i>search.py</i>, create a new testcase from it, and allow me to override the setUp/tearDown methods (changing the driver to PhantomJS, modifying the base URL from the sys.argv), and allow for catching errors and writing information related to where a failed test might have stopped (since there are two different URL calls, a screenshot of that page will be exported for wherever the driver is currently at).</p>
<p>I'm thinking something like <i>my_wrapper.__main__</i>:</p>
<pre><code># get 'mytests.search' from argparse
dirname, module = os.path.split('mytests.search'.replace('.', '/'))
suite = unittest.TestLoader().discover(dirname, pattern='%s.py' % module)
# Modify testcases here <-- THIS IS THE HARD PART
#
# Is there a way to inject the tests into another testCase class?
#
# class BaseClass(unittest.TestCase):
# def setUp(self):
# self.driver = webdriver.PhantomJS()
# ...
#
# def runTest(self): pass
#
# def tearDown(self): ...
#
# then...
new_suite = unittest.TestSuite()
for sub_suite in master_suite: #<-- iterating over the above suite here
for tests in sub_suite._tests: #<-- why do you have to do this twice?
for test_name in tests._tests:
# This doesn't work but show's my thought process
mytest = BaseClass(methodName=test_name)
setattr(mytest, test_func, getattr(tests, test_name))
new_suite.addTest(mytest)
try:
result = unittest.TextTestRunner(verbosity=2).run(new_suite)
except (SOME_SELENIUM_ERROR):
# get the screenshot, save to file <-- don't know how to do this either
</code></pre>
<p>Anyway, any help into this would be appreciated. I would really like to keep this code as simple as possible using as much of what's available as I can.</p>
<p>Note: Other than selenium and PhantomJS, I'm also wary of using other dependencies like non-standard libraries, etc, for a number of policy reasons.
...</p>
| 3 | 2016-08-31T19:21:59Z | 39,437,390 | <p>Hi my friend i have been searchin something like this for few days. I found this question in stackoverflow</p>
<p><a href="http://stackoverflow.com/questions/11380413/python-unittest-passing-arguments">Python unittest passing arguments</a></p>
<p>so you code should be like this:</p>
<pre><code>import sys
import unittest
class Search(unittest.TestCase):
URL = ""
def setUp(self):
self.driver = webdriver.Firefox()
self.base_url = 'http://www.example.com'
def test_search(self):
driver = self.driver
driver.get(self.base_url)
elem = self.driver.find_element_by_name('q')
elem.send_keys('nagios')
elem.send_keys(Keys.RETURN)
assert 'No results found.' not in self.driver.page_source
driver.get(self.base_url + '/status')
assert 'OK' in self.driver.page_source
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
Search.URL=sys.argv.pop()
unittest.main()
</code></pre>
<p>I hope this is what you was looking for.</p>
<p>to execute you should do:</p>
<pre><code>python mySearchTest.py "http://example.com"
</code></pre>
| 1 | 2016-09-11T14:59:13Z | [
"python",
"unit-testing",
"selenium",
"phantomjs"
] |
Access JSON Key in Python | 39,257,547 | <p>I'm trying to print out all the <code>cpe_mac</code> fields of my JSON data.</p>
<h1>I have</h1>
<pre><code># Last updated : BH | 8/31/2016
import requests
import json
ssc_ip = raw_input("What is your SSC Host (Ex. http://172.19.242.32:1234/ ) ? : ")
if not ssc_ip:
ssc_ip = 'http://172.19.242.32:1234/'
cpe_num = raw_input("How many CPE(s) you want to delete ? : ")
print '\n'
url = ssc_ip+'vse/vcpes'
json_data = requests.get(url).json()
# print json_data
for x in json_data:
print json_data.cpe_mac
</code></pre>
<hr>
<p>I kept getting </p>
<p><code>AttributeError: 'dict' object has no attribute 'cpe_mac'</code></p>
<hr>
<h1>Trying</h1>
<p><code>print json_data['cpe_mac']</code></p>
<p>I got </p>
<p><code>KeyError: 'cpe_mac'</code></p>
| -2 | 2016-08-31T19:26:39Z | 39,257,610 | <p>That's not how to access a dictionary item. The dictionaries of interest are contained in a list (accessible via key <code>data</code>) inside the parent dictionary <code>json_data</code>. </p>
<p>You should do:</p>
<pre><code>for x in json_data['data']:
print x['cpe_mac']
</code></pre>
| 1 | 2016-08-31T19:30:36Z | [
"python"
] |
Access JSON Key in Python | 39,257,547 | <p>I'm trying to print out all the <code>cpe_mac</code> fields of my JSON data.</p>
<h1>I have</h1>
<pre><code># Last updated : BH | 8/31/2016
import requests
import json
ssc_ip = raw_input("What is your SSC Host (Ex. http://172.19.242.32:1234/ ) ? : ")
if not ssc_ip:
ssc_ip = 'http://172.19.242.32:1234/'
cpe_num = raw_input("How many CPE(s) you want to delete ? : ")
print '\n'
url = ssc_ip+'vse/vcpes'
json_data = requests.get(url).json()
# print json_data
for x in json_data:
print json_data.cpe_mac
</code></pre>
<hr>
<p>I kept getting </p>
<p><code>AttributeError: 'dict' object has no attribute 'cpe_mac'</code></p>
<hr>
<h1>Trying</h1>
<p><code>print json_data['cpe_mac']</code></p>
<p>I got </p>
<p><code>KeyError: 'cpe_mac'</code></p>
| -2 | 2016-08-31T19:26:39Z | 39,257,636 | <p>You have a nested dictionary, it should be:</p>
<pre><code>for x in json_data['data']:
print x['cpe_mac']
</code></pre>
| 3 | 2016-08-31T19:32:51Z | [
"python"
] |
Add a clip_analysis to a buffer_analysis | 39,257,575 | <p>I'm trying to add a clip_analysis to the buffer_analysis I just completed. </p>
<p>The script that I'm using is:</p>
<pre><code>for i in range(len(cities)):
arcpy.Buffer_analysis(sites[i]+'.shp', sites[i]+'_Buffer3000.shp','3000')
print 'site buffered to',i,'buffer 3000'
arcpy.Clip_analysis(openSpace,[i]+'.shp', [i]+'_OpenSpace.shp')
print 'open space clipped to',i,'city limits'
</code></pre>
<p>When I leave the script like this, I keep getting the following error:</p>
<pre><code>TypeError: can only concatenate list (not "str") to list
</code></pre>
<p>or a error that says unsupported operand type(s) for +: 'int' and 'str'</p>
| 0 | 2016-08-31T19:28:36Z | 39,258,041 | <p>In the line:</p>
<pre><code>arcpy.Clip_analysis(openSpace,[i]+'.shp', [i]+'_OpenSpace.shp')
</code></pre>
<p>you're trying to append together the list <code>[i]</code> to the string <code>.shp</code></p>
<p>...did you mean to write:</p>
<pre><code>arcpy.Clip_analysis(openSpace,sites[i]+'.shp', [i]+'_OpenSpace.shp')
</code></pre>
| 0 | 2016-08-31T19:59:08Z | [
"python"
] |
How to iterate through this nested json array with python | 39,257,576 | <p>So I made an API call to JIRA to get the list of all the issues. It returns something like this: </p>
<pre><code>{
issues: [
{
fields: {
description:
summary:
creator:
reporter:
priority:
}
}
]
</code></pre>
<p>and I'm trying to get to what's inside <code>fields</code>.
Here's what I have: </p>
<p><code>response = requests.get(url + '/search?jql=resolution%20=%20Unresolved%20order%20by%20priority%20DESC,updated%20DESC', auth=auth).json()</code></p>
<p>and then : </p>
<p><code>response['issues']</code> works. But I can't find a way to access <code>fields</code> and then the elements inside it. I thought about iterating through but not sure if there's a simpler solution. </p>
<p>My understanding is that response[issues] is a list and I know how to access each element of it <code>response[issues][0]</code> but how to access the object nested inside the list? (still researching on it -- might find an answer) </p>
| 0 | 2016-08-31T19:28:36Z | 39,257,639 | <p>if you look at your json it's an array to a hash or list to dict. To get fields you'd just call the first array element and the key.</p>
<p><code>response[issues][0][fields]</code></p>
| 1 | 2016-08-31T19:33:01Z | [
"python",
"json",
"api",
"jira",
"jira-rest-api"
] |
Pyspark: Prevent removal of terminal ansi-escape characters in logging while using pyspark | 39,257,608 | <p>I have put together a custom formatter for a logger and I am using pyspark, but it looks like all of my color is removed on the command-line. I can confirm that the escape sequences are present within the record of each emitted value, but it appears that they're stripped when sent to the terminal. </p>
<p>Why?</p>
<pre class="lang-py prettyprint-override"><code>import datetime
import logging
import colorama
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import Terminal256Formatter
# Required for colored output
colorama.init()
class CustomFormatter(logging.Formatter):
'''Modifies the level prefix of the log with the following level
information:
!!! - critical
! - error
? - warn
- info
- - debug
'''
default_prefix = '???' # used with non-generic levels
color_mapping = {
logging.CRITICAL: colorama.Fore.RED + colorama.Style.BRIGHT,
logging.ERROR: colorama.Fore.RED + colorama.Style.BRIGHT,
logging.WARNING: colorama.Fore.YELLOW + colorama.Style.BRIGHT,
logging.DEBUG: colorama.Style.DIM,
}
prefix_mapping = {
logging.CRITICAL: '!!!',
logging.ERROR: ' ! ',
logging.WARNING: ' ? ',
logging.INFO: ' ',
logging.DEBUG: ' · ',
}
def format(self, record):
# Capture relevant record data
level = self.prefix_mapping.get(record.levelno) or self.default_prefix
msecs = datetime.datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S")
msg = record.msg.rstrip('\n')
# Setup colors
color = self.color_mapping.get(record.levelno) or ''
dim = colorama.Style.DIM
reset = colorama.Fore.RESET + colorama.Style.RESET_ALL
name = record.name
func = record.funcName
# Setup output
lexer = JsonLexer()
formatter = Terminal256Formatter()
try:
msg = '\n'.join(
highlight(m, lexer, formatter).rstrip('\n')
for m in msg.split('\n')
)
except:
pass
data = {k: v for k, v in locals().items()}
d = '{color}{level}{reset} {dim}{msecs} [{name}]{reset} {msg}'.format(**data)
record.msg = d
# Dump
return super(CustomFormatter, self).format(record)
</code></pre>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>import logging
from CustomFormatter import CustomFormatter
def get_logger(name, level=None):
level = logging.DEBUG if not isinstance(level, int) else level
handler = logging.StreamHandler(sys.stdout)
handler.level = level or logging.INFO
formatter = CustomFormatter()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.addHandler(handler)
return logger
logger = get_logger('tester')
logger.error('Error here')
</code></pre>
| -1 | 2016-08-31T19:30:27Z | 39,358,454 | <p>I spent some time digging into this, and I found that the terminal escape sequences are different when loading under pyspark. The way I fixed it is by using pygments to run over the terminal output I created (see function: <code>fix_for_spark</code>).</p>
<pre><code># -*- coding: utf-8 -*-
import datetime
import json
import logging
import os
import colorama
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import Terminal256Formatter
# Required for colored output
colorama.init()
class CustomFormatter(logging.Formatter):
'''Modifies the level prefix of the log with the following level
information:
!!! - critical
! - error
? - warn
- info
- - debug
'''
default_prefix = '???' # used with non-generic levels
PYGMENTS_LEXER = JsonLexer()
PYGMENTS_FORMATTER = Terminal256Formatter()
color_mapping = {
logging.CRITICAL: colorama.Fore.RED + colorama.Style.BRIGHT,
logging.ERROR: colorama.Fore.RED + colorama.Style.BRIGHT,
logging.WARNING: colorama.Fore.YELLOW + colorama.Style.BRIGHT,
logging.DEBUG: colorama.Style.DIM,
}
prefix_mapping = {
logging.CRITICAL: '!!!',
logging.ERROR: ' ! ',
logging.WARNING: ' ? ',
logging.INFO: ' ï¸ ',
logging.DEBUG: ' · ',
}
def fix_for_spark(self, string):
if os.environ.get('SPARK_ENV_LOADED'):
# Setup output
new_string = []
for s in string.split('\n'):
s = highlight(string, self.PYGMENTS_LEXER, self.PYGMENTS_FORMATTER)
new_string.append(s.rstrip('\n'))
string = '\n'.join(new_string)
return string
def format(self, record):
# Capture relevant record data
data = dict(
level=self.prefix_mapping.get(record.levelno) or self.default_prefix,
msecs=datetime.datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S"),
# Setup colors
color=self.color_mapping.get(record.levelno) or '',
dim=colorama.Style.DIM,
reset=colorama.Fore.RESET + colorama.Style.RESET_ALL,
name=record.name,
func=record.funcName,
)
# Format msg
prefix = '{color}{level}{reset} {dim}{msecs}{reset} {color}[{name}]{reset}'
prefix = prefix.format(**data)
prefix = self.fix_for_spark(prefix)
msg = record.msg
if not isinstance(msg, str):
try:
msg = json.dumps(msg, indent=4, sort_keys=True)
except:
msg = str(msg)
dmsg = []
for m in msg.split('\n'):
m = highlight(m, self.PYGMENTS_LEXER, self.PYGMENTS_FORMATTER).rstrip('\n')
m = self.fix_for_spark(m)
dmsg.append(m)
dmsg = '\n'.join(dmsg)
data.update(locals().items())
template = prefix + ' {msg}'
record.msg = '\n'.join(template.format(msg=m) for m in dmsg.split('\n'))
# Dump
return super(CustomFormatter, self).format(record)
</code></pre>
| 0 | 2016-09-06T21:58:09Z | [
"python",
"logging",
"pyspark",
"ansi-escape"
] |
From string library, template function doesnt work with int value? | 39,257,631 | <p>I am trying to use Template from string. I have a directory with 100 csv files with data pertaining to each year.</p>
<p>For ex.:</p>
<pre><code>yob1881.txt
yob1882.txt
yob1883.txt
yob1884.txt
yob1885.txt
</code></pre>
<p>Now i want to use template so that i can loop over all files. So i am using a range function like:</p>
<pre><code>for year in range(1880,2011):
template = Template(/name/year$year)
template.substitute(year)
</code></pre>
<p>This is returning an error:</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-4-85f21050945a> in <module>()
2 filepath = tp('/pythonDataProjects/Loan Granting/names/yob$year.txt')
3 year = '1880'
----> 4 print(filepath.substitute(year))
/Users/omkar/anaconda/lib/python3.5/string.py in substitute(*args, **kws)
127 raise ValueError('Unrecognized named group in pattern',
128 self.pattern)
--> 129 return self.pattern.sub(convert, self.template)
130
131 def safe_substitute(*args, **kws):
/Users/omkar/anaconda/lib/python3.5/string.py in convert(mo)
117 named = mo.group('named') or mo.group('braced')
118 if named is not None:
--> 119 val = mapping[named]
120 # We use this idiom instead of str() because the latter will
121 # fail if val is a Unicode containing non-ASCII characters.
</code></pre>
<p>TypeError: string indices must be integers</p>
<p>I know what the error is. However, i am not getting how to resolve it.</p>
<p>Any help? </p>
| -2 | 2016-08-31T19:32:23Z | 39,257,841 | <p>You should pass the parameter as a named argument:</p>
<pre><code>for year in range(1880, 2011):
template = Template('/name/year$year')
t = template.substitute(year=year)
</code></pre>
| 0 | 2016-08-31T19:47:45Z | [
"python",
"string",
"python-3.x",
"templates"
] |
From string library, template function doesnt work with int value? | 39,257,631 | <p>I am trying to use Template from string. I have a directory with 100 csv files with data pertaining to each year.</p>
<p>For ex.:</p>
<pre><code>yob1881.txt
yob1882.txt
yob1883.txt
yob1884.txt
yob1885.txt
</code></pre>
<p>Now i want to use template so that i can loop over all files. So i am using a range function like:</p>
<pre><code>for year in range(1880,2011):
template = Template(/name/year$year)
template.substitute(year)
</code></pre>
<p>This is returning an error:</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-4-85f21050945a> in <module>()
2 filepath = tp('/pythonDataProjects/Loan Granting/names/yob$year.txt')
3 year = '1880'
----> 4 print(filepath.substitute(year))
/Users/omkar/anaconda/lib/python3.5/string.py in substitute(*args, **kws)
127 raise ValueError('Unrecognized named group in pattern',
128 self.pattern)
--> 129 return self.pattern.sub(convert, self.template)
130
131 def safe_substitute(*args, **kws):
/Users/omkar/anaconda/lib/python3.5/string.py in convert(mo)
117 named = mo.group('named') or mo.group('braced')
118 if named is not None:
--> 119 val = mapping[named]
120 # We use this idiom instead of str() because the latter will
121 # fail if val is a Unicode containing non-ASCII characters.
</code></pre>
<p>TypeError: string indices must be integers</p>
<p>I know what the error is. However, i am not getting how to resolve it.</p>
<p>Any help? </p>
| -2 | 2016-08-31T19:32:23Z | 39,257,853 | <p>Your issue is that you're not assigning the substitution when calling <code>template.substitute(year)</code>. You need to format this like:</p>
<pre><code>template.substitute(year=year)
</code></pre>
<p>Also, <code>substitute()</code> returns a new string, so you should either reassign this template or assign it to a new variable.</p>
<pre><code>for year in range(1880,2011):
template = Template("/name/year$year")
template = template.substitute(year=year)
# Or
new_temp = template.substitute(year=year)
</code></pre>
<p><strong>Suggestion</strong></p>
<p>Is there a reason why you're not using the <code>format()</code> method? You can get the same results by doing</p>
<pre><code>for year in range(1880,2011):
template = "/name/yob{}.txt".format(year)
</code></pre>
| 0 | 2016-08-31T19:48:14Z | [
"python",
"string",
"python-3.x",
"templates"
] |
Python: rolling an array multiple times and saving each iteration as an image | 39,257,652 | <p>I have multiple images that I am taking in with a for loop. I want to obtain 5 pseudo-layers for each image by rolling the initial by one pixel in both x and y and saving the rolled image each time. </p>
<p>I'm practicing with one image making sure I can get five layers out of it but no joy.</p>
<p>My code is below but it is only saving the first image; output is pl_0.tif</p>
<pre><code>list_frames = glob.glob('*.gif')
for index, fname in enumerate(list_frames):
im = Image.open(fname)
shift=1
imary0 = np.array(im) # initial image (first layer)
imary1x = np.roll(imary0, shift, axis=0) # shift image by one pixel to create second layer
imary1xy = np.roll(imary1x, shift, axis=1)
imary2x = np.roll(imary1xy, shift, axis=0) # shift previous image again to create third layer
imary2xy = np.roll(imary2x, shift, axis=1)
imary3x = np.roll(imary2xy, shift, axis=0) # shift previous image again to create fourth layer
imary3xy = np.roll(imary3x, shift, axis=1)
imary4x = np.roll(imary3xy, shift, axis=0) # shift previous image again to create fifth layer
imary4xy = np.roll(imary4x, shift, axis=1)
im0 = Image.fromarray(imary0)
im0.save('pl_{}.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}.tif'.format(index))
im.close()
</code></pre>
<p>Any suggestions? (And please feel free to ridicule me if this is an easy fix)</p>
| 0 | 2016-08-31T19:34:10Z | 39,257,689 | <p>You save all 5 images in the same output file, which means that you get only one image, <code>im4</code></p>
<pre><code>im0.save('pl_{}.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}.tif'.format(index))
</code></pre>
<p>(note that index is not modified until next loop)</p>
<p>quickfix:</p>
<pre><code>im0.save('pl_{}0.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}1.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}2.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}3.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}4.tif'.format(index))
</code></pre>
| 1 | 2016-08-31T19:37:01Z | [
"python",
"numpy",
"pillow"
] |
Python: rolling an array multiple times and saving each iteration as an image | 39,257,652 | <p>I have multiple images that I am taking in with a for loop. I want to obtain 5 pseudo-layers for each image by rolling the initial by one pixel in both x and y and saving the rolled image each time. </p>
<p>I'm practicing with one image making sure I can get five layers out of it but no joy.</p>
<p>My code is below but it is only saving the first image; output is pl_0.tif</p>
<pre><code>list_frames = glob.glob('*.gif')
for index, fname in enumerate(list_frames):
im = Image.open(fname)
shift=1
imary0 = np.array(im) # initial image (first layer)
imary1x = np.roll(imary0, shift, axis=0) # shift image by one pixel to create second layer
imary1xy = np.roll(imary1x, shift, axis=1)
imary2x = np.roll(imary1xy, shift, axis=0) # shift previous image again to create third layer
imary2xy = np.roll(imary2x, shift, axis=1)
imary3x = np.roll(imary2xy, shift, axis=0) # shift previous image again to create fourth layer
imary3xy = np.roll(imary3x, shift, axis=1)
imary4x = np.roll(imary3xy, shift, axis=0) # shift previous image again to create fifth layer
imary4xy = np.roll(imary4x, shift, axis=1)
im0 = Image.fromarray(imary0)
im0.save('pl_{}.tif'.format(index))
im1 = Image.fromarray(imary1xy)
im1.save('pl_{}.tif'.format(index))
im2 = Image.fromarray(imary2xy)
im2.save('pl_{}.tif'.format(index))
im3 = Image.fromarray(imary3xy)
im3.save('pl_{}.tif'.format(index))
im4 = Image.fromarray(imary4xy)
im4.save('pl_{}.tif'.format(index))
im.close()
</code></pre>
<p>Any suggestions? (And please feel free to ridicule me if this is an easy fix)</p>
| 0 | 2016-08-31T19:34:10Z | 39,257,994 | <p>Untested, but I think this should do what you're aiming for:</p>
<p>Addition of a <code>number_of_shifts</code> variable, and then using that to iterate. Then the calls to np.roll are nested, which I think should work</p>
<pre><code>list_frames = glob.glob('*.gif')
for index1, fname in enumerate(list_frames):
im = Image.open(fname)
shift=1
number_of_shifts = 4
image_list = []
imary0 = np.array(im) # initial image (first layer)
for _ in range(number_of_shifts):
if not image_list:
image_list.append(imary0)
else:
image_list.append(np.roll(np.roll(image_list[-1], shift, axis=0), shift, axis=1))
for index2, img in enumerate(image_list):
img.save("pl_{}_{}.tif".format(fname, index2))
im.close()
</code></pre>
| 1 | 2016-08-31T19:56:54Z | [
"python",
"numpy",
"pillow"
] |
How to display x axis label for each matplotlib subplot | 39,257,712 | <p>I want to add an x axis label below each subplot. I use this code to create the charts:</p>
<pre><code>fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
</code></pre>
<p>This is how it looks. Only the first one shows</p>
<p><a href="http://i.stack.imgur.com/uEB0g.png" rel="nofollow"><img src="http://i.stack.imgur.com/uEB0g.png" alt="enter image description here"></a></p>
<p>How can I show a different x axis label under each <code>subplot</code>?</p>
| 0 | 2016-08-31T19:38:33Z | 39,257,779 | <p>You can add a title above each plot using:</p>
<pre><code>ax.set_title('your title')
</code></pre>
| 0 | 2016-08-31T19:44:18Z | [
"python",
"matplotlib",
"histogram"
] |
How to display x axis label for each matplotlib subplot | 39,257,712 | <p>I want to add an x axis label below each subplot. I use this code to create the charts:</p>
<pre><code>fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
</code></pre>
<p>This is how it looks. Only the first one shows</p>
<p><a href="http://i.stack.imgur.com/uEB0g.png" rel="nofollow"><img src="http://i.stack.imgur.com/uEB0g.png" alt="enter image description here"></a></p>
<p>How can I show a different x axis label under each <code>subplot</code>?</p>
| 0 | 2016-08-31T19:38:33Z | 39,257,797 | <p>That's easy, just use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_title" rel="nofollow">matplotlib.axes.Axes.set_title</a>, here's a little example out of your code:</p>
<pre><code>from matplotlib import pyplot as plt
import pandas as pd
df1 = pd.DataFrame({
"Age":[1,2,3,4]
})
df2 = pd.DataFrame({
"Age":[10,20,30,40]
})
df3 = pd.DataFrame({
"Age":[100,200,300,400]
})
fig = plt.figure(figsize=(16, 8))
ax1 = fig.add_subplot(1, 3, 1)
ax1.set_title("Title for df1")
ax1.set_xlim([min(df1["Age"]), max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1, 3, 2)
ax2.set_xlim([min(df2["Age"]), max(df2["Age"])])
ax2.set_title("Title for df2")
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1, 3, 3)
ax3.set_xlim([min(df3["Age"]), max(df3["Age"])])
ax3.set_title("Title for df3")
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
</code></pre>
| 0 | 2016-08-31T19:45:03Z | [
"python",
"matplotlib",
"histogram"
] |
How to display x axis label for each matplotlib subplot | 39,257,712 | <p>I want to add an x axis label below each subplot. I use this code to create the charts:</p>
<pre><code>fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
</code></pre>
<p>This is how it looks. Only the first one shows</p>
<p><a href="http://i.stack.imgur.com/uEB0g.png" rel="nofollow"><img src="http://i.stack.imgur.com/uEB0g.png" alt="enter image description here"></a></p>
<p>How can I show a different x axis label under each <code>subplot</code>?</p>
| 0 | 2016-08-31T19:38:33Z | 39,257,803 | <p>You are using <code>ax.set_xlabel</code> wrong, which is a <strong>function</strong> (first call is correct, the others are not):</p>
<pre><code>fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq") # CORRECT USAGE
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq" # ERROR set_xlabel is a function
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq" # ERROR set_xlabel is a function
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
</code></pre>
| 2 | 2016-08-31T19:45:19Z | [
"python",
"matplotlib",
"histogram"
] |
How to calculate the number of matched groups of rows in pandas dataframe? | 39,257,713 | <p>Having been banging my head against the wall for 2 days now for this one. Got some ideas, tried to implement, but the speed was terribly slow, so wonder whether someone can point out a better way of doing this. Here's what I want:</p>
<p>I have a dataframe like this:</p>
<p><code>pd.DataFrame({'var1':[1, 1, 4, 4, 4, 7, 8], 'var2': [2, 2, 5, 5, 5, 8, 8], 'var3':[3, 3, 6, 6, 6, 9, 8], 'label':['a', 'a', 'b', 'b', 'c', 'd', 'd']})</code></p>
<pre><code> label var1 var2 var3
0 a 1 2 3
1 a 1 2 3
2 b 4 5 6
3 b 4 5 6
4 c 4 5 6
5 d 7 8 9
6 d 8 8 8
</code></pre>
<p>So, what I want is to calculate the percentage of matched labels given duplicated vars. For example, row 0, row 1 are duplicates based on var1, var2, and var3, the same happens with row 2, row 3 and row 4, while row 5 and 6 are not duplicates due to the difference in values of var3. Out of the two duplicate groups, if we check the labels, we see that group 1 (rows 0, 1) labels also match ('a', 'a'), while group 2 (rows 2, 3, 4) are not matched ('b', 'b', 'c'). Therefore, the percentage is 1/2 = 50%.</p>
<p>Currently, this is what I am doing:</p>
<ol>
<li>Sort the data frame using var1, var2, var3</li>
<li>Loop thru the rows and record index of rows that are not duplicate of the next row</li>
<li>Use previous index to slice dataframe to keep only rows that have duplicate(s). Each set of duplicated rows is a group. Count the total number of groups.</li>
<li>In the new dataframe, check each group's label column, if all labels match in a group, count it as a matched group.</li>
<li>Use number of matched groups to divide total number of groups. </li>
</ol>
<p>Any help is appreciated!</p>
| 1 | 2016-08-31T19:38:41Z | 39,258,109 | <pre><code>gb = df.groupby(['var1', 'var2', 'var3', 'label'])
size = gb.size()
size
var1 var2 var3 label
1 2 3 a 2
4 5 6 b 2
c 1
7 8 9 d 1
8 8 8 d 1
dtype: int64
</code></pre>
<hr>
<pre><code>lvls = list(range(size.index.nlevels))
size2 = size.groupby(level=lvls[:-1]).size()
size2
var1 var2 var3
1 2 3 1
4 5 6 2
7 8 9 1
8 8 8 1
dtype: int64
</code></pre>
<hr>
<pre><code>(size2 == 1).sum() / float(size2.shape[0])
0.75
</code></pre>
| 0 | 2016-08-31T20:04:11Z | [
"python",
"pandas"
] |
How to calculate the number of matched groups of rows in pandas dataframe? | 39,257,713 | <p>Having been banging my head against the wall for 2 days now for this one. Got some ideas, tried to implement, but the speed was terribly slow, so wonder whether someone can point out a better way of doing this. Here's what I want:</p>
<p>I have a dataframe like this:</p>
<p><code>pd.DataFrame({'var1':[1, 1, 4, 4, 4, 7, 8], 'var2': [2, 2, 5, 5, 5, 8, 8], 'var3':[3, 3, 6, 6, 6, 9, 8], 'label':['a', 'a', 'b', 'b', 'c', 'd', 'd']})</code></p>
<pre><code> label var1 var2 var3
0 a 1 2 3
1 a 1 2 3
2 b 4 5 6
3 b 4 5 6
4 c 4 5 6
5 d 7 8 9
6 d 8 8 8
</code></pre>
<p>So, what I want is to calculate the percentage of matched labels given duplicated vars. For example, row 0, row 1 are duplicates based on var1, var2, and var3, the same happens with row 2, row 3 and row 4, while row 5 and 6 are not duplicates due to the difference in values of var3. Out of the two duplicate groups, if we check the labels, we see that group 1 (rows 0, 1) labels also match ('a', 'a'), while group 2 (rows 2, 3, 4) are not matched ('b', 'b', 'c'). Therefore, the percentage is 1/2 = 50%.</p>
<p>Currently, this is what I am doing:</p>
<ol>
<li>Sort the data frame using var1, var2, var3</li>
<li>Loop thru the rows and record index of rows that are not duplicate of the next row</li>
<li>Use previous index to slice dataframe to keep only rows that have duplicate(s). Each set of duplicated rows is a group. Count the total number of groups.</li>
<li>In the new dataframe, check each group's label column, if all labels match in a group, count it as a matched group.</li>
<li>Use number of matched groups to divide total number of groups. </li>
</ol>
<p>Any help is appreciated!</p>
| 1 | 2016-08-31T19:38:41Z | 39,258,406 | <p>Using a <code>groupby</code> approach:</p>
<pre><code>def matched_group(grp):
if len(grp) == 1:
return np.nan
return grp.nunique() == 1
is_matched = df.groupby(['var1', 'var2', 'var3'])['label'].apply(matched_group).dropna()
match_pcnt = is_matched.sum()/len(is_matched)
</code></pre>
<p>The <code>matched_group</code> function returns a Boolean indicating if all of the labels within a group of variables are unique, or <code>np.nan</code> if the group of variables has only one element, meaning the group is not duplicated. Then, after dropping null values, just count the matches and divide by the total number of duplicate groups.</p>
<p>The code above gives a value of <code>0.5</code> for <code>match_pcnt</code>.</p>
| 1 | 2016-08-31T20:24:20Z | [
"python",
"pandas"
] |
"IndexError: too many indices" using HDF5 file with 8760 - every hour for the year | 39,257,734 | <p><strong>Background:</strong> I am trying to pull out the daily max windspeed from an 8760 hdf5 dataset using a kdtree to lat/lons from a point file and then pull it all into a csv. Things go smoothly, until I try to make an empty array to store the max values. I am having a hard time wrapping my head around the logic needed here. </p>
<p>I have browsed other questions and from other answers think I may have a one-dimensional array and I'm trying to slice it with two dimensions. But not sure. Any help would be appreciated.</p>
<pre><code># Store X / Y coordinates
x_vector = []
y_vector = []
# Open dummy HDF5 file
hf = h5py.File(dir + 'h5/wspd_2014.h5', 'r')
# Break out attributes of the data
ws = hf['wspd'][...]
meta = hf['meta'][...]
# Get coordinates of HDF5 file
coords = np.vstack([meta['latitude'], meta['longitude']]).T
# Open the vector data
with fiona.open(dir + 'shapefiles/soil_winderode4.shp', 'r') as vector:
# create array to store xy coordinates
coords_arr = []
# get the coordinates from the shapefile
for feature in vector:
coords = feature['geometry']['coordinates']
coords_arr.append(coords)
# Run a loop using the coordinates and split the x and y
for x, y in coords_arr:
x_vector.append(x)
y_vector.append(y)
# Run the kdtree to match nearest values
tree = cKDTree(np.vstack([x_vector, y_vector]).T)
kdtree_indices = tree.query(coords)[1]
# ------ Match WSPD, lat/lon & Save to CSV -------
ws_sites = ws[:, kdtree_indices]
indices = range(0, 8760, 24)
indices.append(8759)
</code></pre>
<p><strong>Issue:</strong> This is where things get wonky, I make an empty numpy array using days (365) and the shape of windspeed (194940) in the <code>for</code>loop and then my intent is to get the max value for every day (ind).</p>
<pre><code>out = np.empty(shape=(365, ws.shape[1]))
for ind in range(len(indices)-1):
out[ind, :] = ws_sites[indices[ind]: indices[ind + 1], :].max(axis=0)
</code></pre>
<p><strong>As per request here is the traceback:</strong></p>
<pre><code>Traceback (most recent call last):
194940
File "meera_extract.py", line 56, in <module>
out[ind, :] = ws_sites[indices[ind]: indices[ind + 1], :].max(axis=0)
IndexError: too many indices for array
</code></pre>
| 0 | 2016-08-31T19:40:29Z | 39,261,584 | <p>First, there was some indentation missing below the <code>with ... a vector:</code>. I added my guess on that. But I'm guessing all of that <code>hdf5</code> stuff is unimportant - at least for your problem.</p>
<p>The problem is all at the end - if I read your question right:</p>
<pre><code>ws_sites = ws[:, kdtree_indices]
indices = range(0, 8760, 24)
indices.append(8759)
#....
out = np.empty(shape=(365, ws.shape[1]))
for ind in range(len(indices)-1):
out[ind, :] = ws_sites[indices[ind]: indices[ind + 1], :].max(axis=0)
</code></pre>
<p>From this I deduce that <code>indices</code> is a list with values in the range 0 8760, 366 values in all. <code>out</code> is 2d, so indexing it with <code>ind</code> should be fine.</p>
<p>But what about <code>ws_sites</code>? What is its shape? Any time you have indexing errors, check the shapes. Often they aren't what you might guess. You are indexing it as though it were 2d, eg.</p>
<pre><code>ws_sites[24:48, :]
</code></pre>
<p>It looks like <code>ws</code> is 2d. But if <code>kdtree_indices</code> is a single number, <code>ws_sites = ws[:, kdtree_indices]</code> will be 1d, producing the <code>too many indices</code>. </p>
<p>The error has to do with the number of dimensions, not their size. Trying to index with too high a number will produce a different error.</p>
| 0 | 2016-09-01T01:57:25Z | [
"python",
"arrays",
"numpy"
] |
Regular Expression with letter | 39,257,759 | <p>I need to match things that format something along the lines of
657432-76, 54678-01, 54364<strong>A</strong>-12</p>
<p>I got <code>(r'^\d{6}-\d{2}$')</code>
and <code>(r'^\d{5}-\d{2}$')</code>
but how do you get the letter?</p>
<p>thanks!!</p>
| 2 | 2016-08-31T19:42:23Z | 39,257,812 | <p>If you want a single regex to match the 3rd pattern you can use a regex like this:</p>
<pre><code>(?i)(r'^\d{5}[a-z]-\d{2}$')
</code></pre>
<p><strong><a href="https://regex101.com/r/uA0bK2/1" rel="nofollow">Working demo</a></strong></p>
<p>However, if you want to have a single regex for all of them, you might find useful:</p>
<pre><code>(?i)(r'^\d{5-6}[a-z]?-\d{2}$')
</code></pre>
<p>Keep in mind that this will allow: <code>657432A-76</code> but if you just want 5 digits only with the letter, then you could use:</p>
<pre><code>(?i)(r'^\d{5}(?:\d?|[a-z])-\d{2}$')
</code></pre>
| 0 | 2016-08-31T19:46:01Z | [
"python",
"regex",
"format",
"expression"
] |
Regular Expression with letter | 39,257,759 | <p>I need to match things that format something along the lines of
657432-76, 54678-01, 54364<strong>A</strong>-12</p>
<p>I got <code>(r'^\d{6}-\d{2}$')</code>
and <code>(r'^\d{5}-\d{2}$')</code>
but how do you get the letter?</p>
<p>thanks!!</p>
| 2 | 2016-08-31T19:42:23Z | 39,257,814 | <p>For the letter use <code>[a-zA-Z]</code>, and if it's only upper case then <code>[A-Z]</code> is sufficient.</p>
| 0 | 2016-08-31T19:46:09Z | [
"python",
"regex",
"format",
"expression"
] |
Regular Expression with letter | 39,257,759 | <p>I need to match things that format something along the lines of
657432-76, 54678-01, 54364<strong>A</strong>-12</p>
<p>I got <code>(r'^\d{6}-\d{2}$')</code>
and <code>(r'^\d{5}-\d{2}$')</code>
but how do you get the letter?</p>
<p>thanks!!</p>
| 2 | 2016-08-31T19:42:23Z | 39,257,845 | <p>it seems the pattern generically is 6 characters with possible letter or number at last char max then <code>-</code> then 2 numbers? so then you'd use this pattern</p>
<p><code>pattern = r'^d{5}.+-\d{2}$'</code></p>
| 0 | 2016-08-31T19:47:51Z | [
"python",
"regex",
"format",
"expression"
] |
Regular Expression with letter | 39,257,759 | <p>I need to match things that format something along the lines of
657432-76, 54678-01, 54364<strong>A</strong>-12</p>
<p>I got <code>(r'^\d{6}-\d{2}$')</code>
and <code>(r'^\d{5}-\d{2}$')</code>
but how do you get the letter?</p>
<p>thanks!!</p>
| 2 | 2016-08-31T19:42:23Z | 39,257,899 | <p>How about this expression:</p>
<pre><code>>>> re.search(r'^\d+[A-Z]?-\d+$','657432A-76')
<_sre.SRE_Match object; span=(0, 10), match='657432A-76'>
>>>
>>> re.search(r'^\d+[A-Z]?-\d+$','657432-76')
<_sre.SRE_Match object; span=(0, 9), match='657432-76'>
>>>
>>> re.search(r'^\d+[A-Z]?-\d+$','65743-76')
<_sre.SRE_Match object; span=(0, 8), match='65743-76'>
>>>
</code></pre>
<p>Or if the format is as : <br /></p>
<p><code>[At most six digits][Possibility of a letter][-][At most two digits]</code> <br /> </p>
<p>Then:</p>
<pre><code>>>> re.search(r'^\d{,6}[A-Z]?-\d{,2}$','65743A-76')
<_sre.SRE_Match object; span=(0, 9), match='65743A-76'>
>>>
>>> re.search(r'^\d{,6}[A-Z]?-\d{,2}$','657436-76')
<_sre.SRE_Match object; span=(0, 9), match='657436-76'>
</code></pre>
| 0 | 2016-08-31T19:50:34Z | [
"python",
"regex",
"format",
"expression"
] |
Regular Expression with letter | 39,257,759 | <p>I need to match things that format something along the lines of
657432-76, 54678-01, 54364<strong>A</strong>-12</p>
<p>I got <code>(r'^\d{6}-\d{2}$')</code>
and <code>(r'^\d{5}-\d{2}$')</code>
but how do you get the letter?</p>
<p>thanks!!</p>
| 2 | 2016-08-31T19:42:23Z | 39,257,925 | <p>Here's a possible candidate matching all your samples:</p>
<pre><code>import re
samples = [
"657432-76",
"54678-01",
"54364A-12"
]
for s in samples:
print re.match(r'^(\d+[A-Z]?)-(\d+)$', s).groups()
</code></pre>
| 0 | 2016-08-31T19:52:48Z | [
"python",
"regex",
"format",
"expression"
] |
Performant Spectral Graph Partitioning in Python? | 39,257,776 | <p>I'm working on partitioning a sparse graph I have, and while I'm happy with the results I've seen, it's currently far too slow. The graph has around 200,000 nodes and scipy.sparse.linalg.eigsh takes on the order of hours. I've tried using shift-invert mode and various initializations, as well as a linear spectral shift, but it still takes many hours to run on my i7-4770k. Are there any tricks for initialization or alternate algorithms that are faster for sparse graphs of certain structure?</p>
<p>Part of my hope for this improvement on performance is that nVidia has benchmarks for some of their GPU approaches for similar graphs running in the order of seconds:
<a href="https://devblogs.nvidia.com/parallelforall/fast-spectral-graph-partitioning-gpus/" rel="nofollow">https://devblogs.nvidia.com/parallelforall/fast-spectral-graph-partitioning-gpus/</a></p>
<p>Of course that's on a GPU and not on a CPU like I have now, but that seems like a massive gap for something that's not especially parallelizable (matrix-vector products). Maybe that's all it is, though - I'm trying to avoid adding a GPU dependency for the moment, but I can if that's what it takes.</p>
| 3 | 2016-08-31T19:43:57Z | 39,297,709 | <p>I found scipy.sparse.linalg.lobpcg to give much better results relatively quickly, so if anyone else is trying this in the future I suggest starting there. I also used a <a href="https://en.wikipedia.org/wiki/Preconditioner#Jacobi_.28or_diagonal.29_preconditioner" rel="nofollow">Jacobi diagonal preconditioner</a> based on my matrix, which I would recommend, though I didn't try it without.</p>
| 0 | 2016-09-02T17:17:26Z | [
"python",
"algorithm",
"performance",
"linear-algebra",
"linear"
] |
I've tried to change my font size and it still has no affect. How do I actually change the font size? | 39,257,827 | <p>I'm trying to change the font size of my buttons in Tkinter so it's not so small. Does anyone have any idea on what I can do that might have the result that I'm looking for? Why is there so much text required for me to ask a question when I can ask it plainly and simply with less text?! </p>
<pre><code>from Tkinter import *
from tkFont import *
class App:
def __init__(self):
guiWindow = Tkinter.Tk()
guiWindow.wm_title("FooBar")
# Creates a custom font
customFont = Font(size=18)
# code to add widgets will go here
buttonFrame = Frame()
# colors the "ChangeLicense" button
color = '#005DA6'
# tells licenseChange what to do
def openLicenseChange():
print('Change License')
#button properties
licenseChange = Button(guiWindow,
command=openLicenseChange,
bd=20, bg=color, font=customFont,
text="Change License")
buttonFrame.pack(side="top", fill="x")
guiWindow.mainloop()
app=App()
</code></pre>
| 0 | 2016-08-31T19:46:47Z | 39,257,870 | <p>I'm not familiar with <code>Font</code>, but you can denote it also using a string:</p>
<pre><code>customFont = '{arial} 18'
</code></pre>
<p>For default font uer</p>
<pre><code>customFont = '{} 18'
</code></pre>
| 0 | 2016-08-31T19:49:22Z | [
"python",
"tkinter"
] |
I've tried to change my font size and it still has no affect. How do I actually change the font size? | 39,257,827 | <p>I'm trying to change the font size of my buttons in Tkinter so it's not so small. Does anyone have any idea on what I can do that might have the result that I'm looking for? Why is there so much text required for me to ask a question when I can ask it plainly and simply with less text?! </p>
<pre><code>from Tkinter import *
from tkFont import *
class App:
def __init__(self):
guiWindow = Tkinter.Tk()
guiWindow.wm_title("FooBar")
# Creates a custom font
customFont = Font(size=18)
# code to add widgets will go here
buttonFrame = Frame()
# colors the "ChangeLicense" button
color = '#005DA6'
# tells licenseChange what to do
def openLicenseChange():
print('Change License')
#button properties
licenseChange = Button(guiWindow,
command=openLicenseChange,
bd=20, bg=color, font=customFont,
text="Change License")
buttonFrame.pack(side="top", fill="x")
guiWindow.mainloop()
app=App()
</code></pre>
| 0 | 2016-08-31T19:46:47Z | 39,257,983 | <p>When you create a <code>tk.button</code> object, use the font option, and specify the font style as a string like so:
<code>"Arial 10 Bold"</code></p>
<p>I used your code as an example and made the font Arial, size 18, bolded.</p>
<pre><code>from Tkinter import *
from tkFont import *
class App:
def __init__(self):
guiWindow = Tkinter.Tk()
guiWindow.wm_title("FooBar")
# Creates a custom font
customFont = "Arial 18 Bold"
# code to add widgets will go here
buttonFrame = Frame()
# colors the "ChangeLicense" button
color = '#005DA6'
# tells licenseChange what to do
def openLicenseChange():
print('Change License')
#button properties
licenseChange = Button(guiWindow,
command=openLicenseChange,
bd=20, bg=color, font=customFont,
text="Change License")
buttonFrame.pack(side="top", fill="x")
licenseChange.pack()
guiWindow.mainloop()
app=App()
</code></pre>
<p>If that doesnt work, instead of <code>"Arial 18 Bold"</code>, try quoting each word in the string like so <code>"'Arial' '18' 'Bold'"</code> in your <code>customFont</code> variable.</p>
| 0 | 2016-08-31T19:56:24Z | [
"python",
"tkinter"
] |
I've tried to change my font size and it still has no affect. How do I actually change the font size? | 39,257,827 | <p>I'm trying to change the font size of my buttons in Tkinter so it's not so small. Does anyone have any idea on what I can do that might have the result that I'm looking for? Why is there so much text required for me to ask a question when I can ask it plainly and simply with less text?! </p>
<pre><code>from Tkinter import *
from tkFont import *
class App:
def __init__(self):
guiWindow = Tkinter.Tk()
guiWindow.wm_title("FooBar")
# Creates a custom font
customFont = Font(size=18)
# code to add widgets will go here
buttonFrame = Frame()
# colors the "ChangeLicense" button
color = '#005DA6'
# tells licenseChange what to do
def openLicenseChange():
print('Change License')
#button properties
licenseChange = Button(guiWindow,
command=openLicenseChange,
bd=20, bg=color, font=customFont,
text="Change License")
buttonFrame.pack(side="top", fill="x")
guiWindow.mainloop()
app=App()
</code></pre>
| 0 | 2016-08-31T19:46:47Z | 39,258,050 | <p>You can create a new font and then just applying it to your widgets using <code>my_widget['font']=my_font</code>, example out of your code:</p>
<pre><code>from Tkinter import *
from tkFont import *
class App:
def __init__(self):
guiWindow = Tkinter.Tk()
guiWindow.wm_title("FooBar")
# Creates a custom font
customFont = Font(size=18)
# code to add widgets will go here
buttonFrame = Frame()
# colors the "ChangeLicense" button
color = '#005DA6'
# tells licenseChange what to do
def openLicenseChange():
print('Change License')
# button properties
helv36 = Font(family='Helvetica', size=36, weight='bold')
licenseChange = Button(guiWindow,
command=openLicenseChange,
bd=20, bg=color, font=customFont,
text="Change License")
licenseChange['font'] = helv36
buttonFrame.pack(side="top", fill="x")
guiWindow.mainloop()
app = App()
</code></pre>
<p>You can read more about tkFont.Font <a href="http://www.tutorialspoint.com/python/tk_fonts.htm" rel="nofollow">here</a></p>
| 0 | 2016-08-31T19:59:32Z | [
"python",
"tkinter"
] |
CPU cores, treads and optimal number of workers - python threading | 39,257,857 | <p>I am beginning to appreciate the usefulness of the threading library on python and I was wondering what was the optimal number of threads to keep open in order to maximise the efficiency of the script I am running. </p>
<p>Please do keep in mind that my one and only priority is speed, I don't need to multitask /do other stuff (think a computing dedicated server)</p>
<p>To be specific, if I run on a 4 cores / 4 threads CPU, will the optimal number of threads be 4? 8? 16? Then again, if I had more than a thread per core (4 core 8 t), would the answer change? Also, does cpu clock influence any of this?</p>
<p>I understand there are a variety of implications on the matter but, as much as my research on the subject went, I still feel to be very much in the dark. (I gathered it's not so simple as n threads = n processes)</p>
| 0 | 2016-08-31T19:48:29Z | 39,257,984 | <p>The question is very complex, because on the same CPU there can be an arbitrary number of others threads running, from processes that are not under your control.</p>
<p>Instead, you can estimate when a certain piece of code worth to be executed by a separate thread, based on the time needed to create a new thread.</p>
| 1 | 2016-08-31T19:56:27Z | [
"python",
"multithreading",
"cpu"
] |
python: if (substring X in string Y) only true for last characters? | 39,257,884 | <p>This code only returns true when the substring is at the end. How do I fix it to consider any substring? Data looks like this:</p>
<p>prediction: </p>
<ol>
<li><p>dog</p></li>
<li><p>cat</p></li>
</ol>
<p>actual: </p>
<ol>
<li><p>red,dog</p></li>
<li><p>cat,blue</p></li>
</ol>
<p>returns true then returns false</p>
<pre><code>with open("test_class.txt") as g:
prediction = g.readlines()
with open("y_smallTest.txt") as g:
actual = g.readlines()
for n in range(len(prediction)):
if prediction[n] in actual[n]:
correct += 1
else:
incorrect +=1
</code></pre>
<p>Edit: .rstrips works! The expected output is true, true</p>
| 0 | 2016-08-31T19:50:01Z | 39,257,949 | <p><code>readlines</code> gives you each line include the newline at the end of the line. So you're doing comparisons like <code>"cat\n" in "cat,blue\n"</code>. Since there isn't a newline in the right place, the check fails.</p>
<p>Try this to strip the newlines off the end of each line:</p>
<pre><code>with open("test_class.txt") as g:
prediction = [line.rstrip() for line in g]
with open("y_smallTest.txt") as g:
actual = [line.rstrip() for line in g]
for n in range(len(prediction)):
if prediction[n] in actual[n]:
correct += 1
else:
incorrect +=1
</code></pre>
<p><strong>EDIT</strong></p>
<p>Perhaps a better rewrite is to use zip and just iterate through the files:</p>
<pre><code>with open("test_class.txt") as predictions, open("y_smallTest.txt") as actuals:
for prediction, actual in zip(predictions, actual):
if prediction.rstrip() in actual:
correct += 1
else:
incorrect += 1
</code></pre>
| 1 | 2016-08-31T19:54:00Z | [
"python",
"python-3.x"
] |
python: if (substring X in string Y) only true for last characters? | 39,257,884 | <p>This code only returns true when the substring is at the end. How do I fix it to consider any substring? Data looks like this:</p>
<p>prediction: </p>
<ol>
<li><p>dog</p></li>
<li><p>cat</p></li>
</ol>
<p>actual: </p>
<ol>
<li><p>red,dog</p></li>
<li><p>cat,blue</p></li>
</ol>
<p>returns true then returns false</p>
<pre><code>with open("test_class.txt") as g:
prediction = g.readlines()
with open("y_smallTest.txt") as g:
actual = g.readlines()
for n in range(len(prediction)):
if prediction[n] in actual[n]:
correct += 1
else:
incorrect +=1
</code></pre>
<p>Edit: .rstrips works! The expected output is true, true</p>
| 0 | 2016-08-31T19:50:01Z | 39,257,996 | <p><code>'cat' in 'cat,blue'</code> returns True</p>
<p>Please make small change to your script</p>
<pre><code>if prediction[n].strip() in actual[n]
</code></pre>
| 0 | 2016-08-31T19:56:59Z | [
"python",
"python-3.x"
] |
python: if (substring X in string Y) only true for last characters? | 39,257,884 | <p>This code only returns true when the substring is at the end. How do I fix it to consider any substring? Data looks like this:</p>
<p>prediction: </p>
<ol>
<li><p>dog</p></li>
<li><p>cat</p></li>
</ol>
<p>actual: </p>
<ol>
<li><p>red,dog</p></li>
<li><p>cat,blue</p></li>
</ol>
<p>returns true then returns false</p>
<pre><code>with open("test_class.txt") as g:
prediction = g.readlines()
with open("y_smallTest.txt") as g:
actual = g.readlines()
for n in range(len(prediction)):
if prediction[n] in actual[n]:
correct += 1
else:
incorrect +=1
</code></pre>
<p>Edit: .rstrips works! The expected output is true, true</p>
| 0 | 2016-08-31T19:50:01Z | 39,258,002 | <p>The items in the list returned by <code>readlines</code> will include the <code>\n</code> at the end of each line, so you are <em>actually</em> testing <code>'dog\n' in 'red,dog\n'</code>, which is fine, and <code>'cat\n' in 'cat,blue\n'</code>, which is not.</p>
<p>To fix it, you can use <code>strip()</code> to remove the line terminators (and any other enclosing whitespace).</p>
| 0 | 2016-08-31T19:57:18Z | [
"python",
"python-3.x"
] |
python: if (substring X in string Y) only true for last characters? | 39,257,884 | <p>This code only returns true when the substring is at the end. How do I fix it to consider any substring? Data looks like this:</p>
<p>prediction: </p>
<ol>
<li><p>dog</p></li>
<li><p>cat</p></li>
</ol>
<p>actual: </p>
<ol>
<li><p>red,dog</p></li>
<li><p>cat,blue</p></li>
</ol>
<p>returns true then returns false</p>
<pre><code>with open("test_class.txt") as g:
prediction = g.readlines()
with open("y_smallTest.txt") as g:
actual = g.readlines()
for n in range(len(prediction)):
if prediction[n] in actual[n]:
correct += 1
else:
incorrect +=1
</code></pre>
<p>Edit: .rstrips works! The expected output is true, true</p>
| 0 | 2016-08-31T19:50:01Z | 39,258,064 | <p>You just need to <em>rstrip</em> the <em>newline</em> from each line of the first file so you don't compare <code>dog\n</code> with <code>red,dog\n</code>, the newline on the string you are testing is irrelevant. You can also use <em>zip</em> and read the files line by line withput the need for <em>readlines</em> and indexing:</p>
<pre><code>with open("test_class.txt") as f1, open("y_smallTest.txt") as f2:
correct = incorrect = 0
for a, b in zip(f1, f2):
if a.rstrip() in b:
correct += 1
else:
incorrect += 1
</code></pre>
<p>If you want exact matches then you will need to <em>rstrip</em> and <em>split</em> on the comma:</p>
<pre><code>with open("test_class.txt") as f1, open("y_smallTest.txt") as f2:
correct = incorrect = 0
for a, b in zip(f1, f2):
if a.rstrip() in b.rstrip().split(","):
correct += 1
else:
incorrect += 1
</code></pre>
<p>The difference on splitting would mean <em>dog</em> would not match <em>dogs,cats</em>.</p>
| 0 | 2016-08-31T20:01:12Z | [
"python",
"python-3.x"
] |
Case insensitive dictionary search with enchant | 39,257,988 | <p>Is there a way to do a case-insensitive search in enchant?</p>
<p>I am trying to achieve the following:</p>
<pre><code>import enchant
d = enchant.DictWithPWL("en_US","mywords.txt")
d.check("Alexandria")
True
d.check("alexandria")
False
</code></pre>
<p>Both cases should return True</p>
| 0 | 2016-08-30T05:29:24Z | 39,257,989 | <p>As per you example, it should return <code>True</code>.</p>
<pre><code>import enchant
d = enchant.DictWithPWL("en_US","/home/user/yourscript.py")
a=d.check("import")
print(a)
a=d.check("Import")
print(a)
</code></pre>
<p>Output:</p>
<pre><code>True
True
</code></pre>
<p>You can try following link, you may get some other alternatives to achieve this <a href="http://pythonhosted.org/pyenchant/tutorial.html" rel="nofollow">http://pythonhosted.org/pyenchant/tutorial.html</a></p>
| 0 | 2016-08-30T06:07:22Z | [
"python"
] |
Python Remove List of Strings from List of Strings | 39,257,990 | <p>I'm trying to remove several strings from a list of URLs. I have more than 300k URLs, and I'm trying to find which are variations of the original. Here's a toy example that I've been working with.</p>
<pre><code>URLs = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']
locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']
</code></pre>
<p>What I'd like to end up with is a list of the pages without the language or locations:</p>
<pre><code>desired_output = ['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']
</code></pre>
<p>I've tried list comprehension and nested for loops, nothing has worked yet. Can anyone help?</p>
<pre><code># doesn't remove anything
for item in URLs:
for string in locs:
re.sub(string, '', item)
# doesn't remove anything
for item in URLs:
for string in locs:
item.strip(string)
# only removes the last string in locs
clean = []
for item in URLs:
for string in locs:
new = item.replace(string, '')
clean.append(new)
</code></pre>
| 0 | 2016-08-31T19:56:46Z | 39,258,130 | <p>You have to assign the result of <code>replace</code> to <code>item</code> again:</p>
<pre><code>clean = []
for item in URLs:
for loc in locs:
item = item.replace(loc, '')
clean.append(item)
</code></pre>
<p>or in short:</p>
<pre><code>clean = [
reduce(lambda item,loc: item.replace(loc,''), [item]+locs)
for item in URLs
]
</code></pre>
| 4 | 2016-08-31T20:05:22Z | [
"python",
"list"
] |
Python Remove List of Strings from List of Strings | 39,257,990 | <p>I'm trying to remove several strings from a list of URLs. I have more than 300k URLs, and I'm trying to find which are variations of the original. Here's a toy example that I've been working with.</p>
<pre><code>URLs = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']
locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']
</code></pre>
<p>What I'd like to end up with is a list of the pages without the language or locations:</p>
<pre><code>desired_output = ['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']
</code></pre>
<p>I've tried list comprehension and nested for loops, nothing has worked yet. Can anyone help?</p>
<pre><code># doesn't remove anything
for item in URLs:
for string in locs:
re.sub(string, '', item)
# doesn't remove anything
for item in URLs:
for string in locs:
item.strip(string)
# only removes the last string in locs
clean = []
for item in URLs:
for string in locs:
new = item.replace(string, '')
clean.append(new)
</code></pre>
| 0 | 2016-08-31T19:56:46Z | 39,258,191 | <p>The biggest problem you have is that you don't save the return value. </p>
<pre><code>urls = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']
locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']
stripped = list(urls) ## create a new copy, not necessary
for loc in locs:
stripped = [url.replace(loc, '') for url in stripped]
</code></pre>
<p>After this, <code>stripped</code> is equal to</p>
<pre><code>['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']
</code></pre>
<p><strong>EDIT</strong></p>
<p>Alternatively, without creating a new list, you can do</p>
<pre><code>for loc in locs:
urls = [url.replace(loc, '') for url in urls]
</code></pre>
<p>After this, <code>urls</code> is equal to</p>
<pre><code>['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']
</code></pre>
| 3 | 2016-08-31T20:08:43Z | [
"python",
"list"
] |
Python Remove List of Strings from List of Strings | 39,257,990 | <p>I'm trying to remove several strings from a list of URLs. I have more than 300k URLs, and I'm trying to find which are variations of the original. Here's a toy example that I've been working with.</p>
<pre><code>URLs = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']
locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']
</code></pre>
<p>What I'd like to end up with is a list of the pages without the language or locations:</p>
<pre><code>desired_output = ['example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html',
'example.com/page.html']
</code></pre>
<p>I've tried list comprehension and nested for loops, nothing has worked yet. Can anyone help?</p>
<pre><code># doesn't remove anything
for item in URLs:
for string in locs:
re.sub(string, '', item)
# doesn't remove anything
for item in URLs:
for string in locs:
item.strip(string)
# only removes the last string in locs
clean = []
for item in URLs:
for string in locs:
new = item.replace(string, '')
clean.append(new)
</code></pre>
| 0 | 2016-08-31T19:56:46Z | 39,258,215 | <p>You could first abstract the removing part into a function and then use a list comprehension:</p>
<pre><code>def remove(target, strings):
for s in strings:
target = target.replace(s,'')
return target
URLs = ['example.com/page.html',
'www.example.com/in/page.html',
'example.com/ca/fr/page.html',
'm.example.com/de/page.html',
'example.com/fr/page.html']
locs = ['/in', '/ca', '/de', '/fr', 'm.', 'www.']
</code></pre>
<p>Used like:</p>
<pre><code>URLs = [remove(url,locs) for url in URLs]
for url in URLs: print(url)
</code></pre>
<p>output:</p>
<pre><code>example.com/page.html
example.com/page.html
example.com/page.html
example.com/page.html
example.com/page.html
</code></pre>
| 2 | 2016-08-31T20:10:26Z | [
"python",
"list"
] |
The most efficient way to iterate over a list of elements. Python 2.7 | 39,258,038 | <p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p>
<pre><code>for article in list_articles:
</code></pre>
<p>Each article in the list_articles are an object in the format of:</p>
<pre><code><newspaper.article.Article object at 0x1103e1250>
</code></pre>
<p>I checked that some recommended using xrange or range, however that did not work in my case, giving a type error:</p>
<pre><code>TypeError: 'int' object is not iterable
</code></pre>
<p>It would be awesome if anyone can point me to the right direction or give me some idea that can efficietly increase iterating over this list.</p>
| -2 | 2016-08-31T19:59:06Z | 39,258,199 | <p>Here's a little benchmark to make the question a little bit more interesting:</p>
<pre><code>import timeit
import random
N = 1000000
class Foo:
def __init__(self):
self.n = random.randint(0, 1000)
bar = [Foo() for r in xrange(N)]
def f1(lst):
return [v for v in lst]
def f2(lst):
return [v for index, v in enumerate(lst)]
def f3(lst):
return [lst[i] for i in range(len(lst))]
K = 100
print timeit.timeit('f1(bar)', setup='from __main__ import f1, bar', number=K)
print timeit.timeit('f2(bar)', setup='from __main__ import f2, bar', number=K)
print timeit.timeit('f3(bar)', setup='from __main__ import f3, bar', number=K)
</code></pre>
<p>In my machine gives:</p>
<pre><code>5.1150355947
6.89524135475
7.90469366922
[Finished in 22.1s]
</code></pre>
<p>Conclusion: Iterating using the idiom <code>for v in huge_list</code> is a really good choice, so you should profile to check where the bottleneck is, which is probably in the inner loop (items processing)</p>
| -1 | 2016-08-31T20:09:09Z | [
"python",
"list",
"python-2.7",
"loops",
"cpython"
] |
The most efficient way to iterate over a list of elements. Python 2.7 | 39,258,038 | <p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p>
<pre><code>for article in list_articles:
</code></pre>
<p>Each article in the list_articles are an object in the format of:</p>
<pre><code><newspaper.article.Article object at 0x1103e1250>
</code></pre>
<p>I checked that some recommended using xrange or range, however that did not work in my case, giving a type error:</p>
<pre><code>TypeError: 'int' object is not iterable
</code></pre>
<p>It would be awesome if anyone can point me to the right direction or give me some idea that can efficietly increase iterating over this list.</p>
| -2 | 2016-08-31T19:59:06Z | 39,258,211 | <p>The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...</p>
<p>The there is the list comprehension or <code>map</code> when possible. If you need to construct one list from another by manipulating each element, then this is it.</p>
<p>The thirst best way is the <code>for item in items</code> loop.</p>
<p><strong>ADDED</strong></p>
<p>One of the things that makes you a Python programmer, a better programmer, takes you to the next level of programming is the second thing I mentioned - list comprehension and map. Many times you iterate a list only to construct something that could be easily done with list comprehension. For example:</p>
<pre><code>new_items = []
for item in items:
if item > 3:
print(item * 10)
new_items.append(item * 10)
</code></pre>
<p>You could do this much better (shorter and faster and more robust) like this:</p>
<pre><code>new_items = [item * 10 for item in items if item > 3]
print(items)
</code></pre>
<p>Now, the printing is a bit different from the first example, but more often than not, it doesn't matter, and even better, and also can be transformed with one line of code to what you need.</p>
| 1 | 2016-08-31T20:10:11Z | [
"python",
"list",
"python-2.7",
"loops",
"cpython"
] |
Python - BeautifulSoup scrape non-standard web table | 39,258,047 | <p>I am attempting to scrape data from several webpages in order to create a CSV of the data. The data is just nutritional information of products. I have generated code to access the website, but I can't quite get the code to iterate out properly. The problem is, the website uses DIV tags for the product name, and inside of the DIV either or , it varies between the pages. When I attempt to iterate it out, the product names all show at once, in a list with tags, and then I get the contents of the column I requested, without tags. I am trying to figure out what I am doing wrong. </p>
<p>Source code example:</p>
<pre><code><div><strong>Product 1 Name</strong></div>
<table>
<tbody>
<tr>
<td>Serving Size</td>
<td>8 (fl. Oz.)</td>
</tr>
<tr>
<td>Calories</td>
<td>122 Calories</td>
</tr>
<tr>
<td>Fat</td>
<td>0 (g)</td>
</tr>
<tr>
<td>Sodium</td>
<td>0.2 (mg)</td>
</tr>
<tr>
<td>Carbs</td>
<td>8.8 (mg)</td>
</tr>
<tr>
<td>Dietary Fiber</td>
<td>0 (g)</td>
</tr>
<tr>
<td>Sugar</td>
<td>8.8 (g)<br />
&nbsp;</td>
</tr>
</tbody>
</table>
&nbsp;
<div><strong>Product 2 Name</strong></div>
<table>
<tbody>
<tr>
<td>Serving Size</td>
<td>8 (fl. Oz.)</td>
</tr>
<tr>
<td>Calories</td>
<td>134 Calories</td>
</tr>
<tr>
<td>Fat</td>
<td>0 (g)</td>
</tr>
<tr>
<td>Sodium</td>
<td>0.0 (mg)</td>
</tr>
<tr>
<td>Carbs</td>
<td>8.4 (mg)</td>
</tr>
<tr>
<td>Dietary Fiber</td>
<td>0 (g)</td>
</tr>
<tr>
<td>Sugar</td>
<td>8.4 (g)<br />
&nbsp;</td>
</tr>
</tbody>
</table>
&nbsp;
</code></pre>
<p>Ideally, I would like to be able to output to a CSV that has "Product Name" and Column 1 data in the header row, since it is the same for all of the tables. Then the data rows would be like:
<code>"Product 1 Name, 8, 112, 0, 0.2, 8.8, 0, 8.8"</code></p>
<p>I know there is some manipulation that needs to be done to the data to get it to that point (to remove the size information).</p>
<p>Here is what I have so far that is starting to drive me crazy:</p>
<pre><code>import requests, bs4, urllib2, csv
from bs4 import BeautifulSoup
from collections import defaultdict
#Loop on URLs to get Nutritional Information from each one.
with open('NutritionalURLs.txt') as f:
for line in f:
r = requests.get('website' + line)
soup=BeautifulSoup(r.text.encode('ascii','ignore'),"html.parser")
#TESTING
with open('output.txt', 'w') as o:
product_list = soup.find_all('b')
product_list = soup.find_all('strong')
print(product_list)
table_list = soup.find_all('table')
for tables in table_list:
trs = tables.find_all('tr')
for tr in trs:
tds = tr.find_all('td')[1:]
if tds:
facts = tds[0].find(text=True)
print(facts)
# o.write("Serving Size: %s, Calories: %s, Fat: %s, Sodium: %s, Carbs: %s, Dietary Fiber: %s, Sugar: %s\n" % \
# (facts[0].text, facts[1].text, facts[2].text, facts[3].text, facts[4].text, facts[5].text, facts[6].text))
</code></pre>
<p>This gives me an output like this:</p>
<pre><code>[<strong>Product 1 Name</strong>, <strong>Product 2 Name</strong>]
8 (fl. Oz.)
101 Calories
0 (g)
0.0 (mg)
0 (mg)
0 (g)
0 (g)
8 (fl. Oz.)
101 Calories
0 (g)
0.0 (mg)
0 (mg)
0 (g)
0 (g)
[]
</code></pre>
| 2 | 2016-08-31T19:59:23Z | 39,258,264 | <p>Find the tables, then extract the text from the previous strong and take the second <em>td</em> from each <em>tr</em> splitting the text once to remove the <code>(g)</code> etc..:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for table in soup.find_all("table"):
name = [table.find_previous("strong").text]
amounts = [td.text.split(None, 1)[0] for td in table.select("tr td + td")])
print(name + amounts)
</code></pre>
<p>Which would give you:</p>
<pre><code>['Product 1 Name', '8', '122', '0', '0.2', '8.8', '0', '8.8']
['Product 2 Name', '8', '134', '0', '0.0', '8.4', '0', '8.4']
</code></pre>
<p><em>select("tr td + td")</em> uses a css selector to get the second <em>td</em> from each <em>tr/row</em>,</p>
<p>Or using <em>find_all</em> and slicing would look like:</p>
<pre><code>for table in soup.find_all("table"):
name = [table.find_previous("strong").text]
amounts = [td.find_all("td")[1].text.split(None, 1)[0] for td in table.find_all("tr")]
print(name + amounts)
</code></pre>
<p>Since it is not always a strong but sometimes a bold tag you want, just look for the strong first and fall back to the bold:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
html = requests.get("http://beamsuntory.desk.com/customer/en/portal/articles/1676001-nutrition-information-cruzan").content
soup = BeautifulSoup(html, "html.parser")
for table in soup.select("div.article-content table"):
name = table.find_previous("strong") or table.find_previous("b")
amounts = [td.text.split(None, 1)[0] for td in table.select("tr td + td")]
print([name.text] + amounts)
</code></pre>
<p>If <em>table.find_previous("strong")</em> finds nothing it will be None so the or will be executed and name will be set to <em>table.find_previous("b")</em>.</p>
<p>Now it will work for both:</p>
<pre><code>In [12]: html = requests.get("http://beamsuntory.desk.com/customer/en/portal/articles/1676001-nutrition-information-cruzan").content
In [13]: soup = BeautifulSoup(html, "html.parser")
In [14]: for table in soup.select("div.article-content table"):
....: name = table.find_previous("strong") or table.find_previous("b")
....: amounts = [td.text.split(None, 1)[0] for td in table.select("tr td + td")]
....: print([name.text] + amounts)
....:
[u'Cruzan Banana Flavored Rum 42 proof', u'1.5', u'79', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Banana Flavored Rum 55 proof', u'1.5', u'95', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Black Cherry Flavored Rum 42 proof', u'1.5', u'80', u'0', u'0.0', u'6.9', u'0', u'6.9']
[u'Cruzan Citrus Flavored Rum 42 proof', u'1.5', u'99', u'0', u'0.0', u'2.8', u'0', u'2.6']
[u'Cruzan Coconut Flavored Rum 42 proof', u'1.5', u'78', u'0', u'0.1', u'6.9', u'0', u'6.5']
[u'Cruzan Coconut Flavored Rum 55 proof', u'1.5', u'95', u'0', u'0.1', u'6.1', u'0', u'0']
[u'Cruzan Guaza Flavored Rum 42 proof', u'1.5', u'78', u'0', u'0.1', u'6.5', u'0', u'6.5']
[u'Cruzan Key Lime Flavored Rum 42 proof', u'1.5', u'81', u'0', u'0.0', u'8.1', u'0', u'6']
[u'Cruzan Mango Flavored Rum 42 proof', u'1.5', u'85', u'0', u'0.0', u'8.5', u'0', u'8.5']
[u'Cruzan Mango Flavored Rum 55 proof', u'1.5', u'101', u'0', u'0.0', u'8.5', u'0', u'8.5']
[u'Cruzan Orange Flavored Rum 42 proof', u'1.5', u'76.77', u'0', u'0', u'6.4', u'0', u'6.4']
[u'Cruzan Passion Fruit Flavored Rum 42 proof', u'1.5', u'77', u'0', u'0.0', u'6.3', u'0', u'6.3']
[u'Cruzan Pineapple Flavored Rum 42 proof', u'1.5', u'78', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Pineapple Flavored Rum 55 proof', u'1.5', u'94', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Raspberry Flavored Rum 42 proof', u'1.5', u'92', u'0', u'0.0', u'10.1', u'0', u'10.1']
[u'Cruzan Raspberry Flavored Rum 55 proof', u'1.5', u'108', u'0', u'0.0', u'10.1', u'0', u'10.1']
[u'Cruzan Strawberry Flavored Rum 42 proof', u'1.5', u'76', u'0', u'0.0', u'6.1', u'0', u'6']
[u'Cruzan Vanilla Flavored Rum 42 proof', u'1.5', u'78', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Vanilla Flavored Rum 55 proof', u'1.5', u'94', u'0', u'0.0', u'6.5', u'0', u'6.5']
[u'Cruzan Estate Dark Rum 80 proof', u'1.5', u'101', u'0', u'0.0', u'0', u'0', u'0']
[u'Cruzan Estate Light Rum 80 proof', u'1.5', u'101', u'0', u'0.0', u'0', u'0', u'0']
[u'Cruzan Estate Single Barrel Rum 80 proof', u'1.5', u'99', u'0', u'0.0', u'0.9', u'0', u'0.9']
</code></pre>
<p>And the bold:</p>
<pre><code>In [20]: html = requests.get("http://beamsuntory.desk.com/customer/en/portal/articles/1790163-midori-nutrition-information").content
In [21]: soup = BeautifulSoup(html, "html.parser")
In [22]: for table in soup.select("div.article-content table"):
....: name = table.find_previous("strong") or table.find_previous("b")
....: amounts = [td.text.split(None, 1)[0] for td in table.select("tr td + td")]
....: print([name.text] + amounts)
....:
[u'Midori', u'1.0', u'62.1', u'0', u'0.3', u'7.5', u'0', u'7.0']
</code></pre>
| 1 | 2016-08-31T20:13:52Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Initial and final check when running pytest test suite | 39,258,076 | <p>I have productive code which creates config files in my <code>$HOME</code> folder and to run my tests in an isolated environment I patch <code>$HOME</code> in <code>conftest.py</code>. Still I'm not sure if this works in general and maybe unthoughtful written test functions might break out.</p>
<p>To ensure the validity of my test suite I'd like to run a preliminary check of the respective files in <code>$HOME</code> and I'd like to run a final check after running the test suite.</p>
<p>How can I achieve this with the "official" means of <code>pytest</code> ? I have a dirty hack which works but messes up reporting.</p>
<p>My test suite is correct now and this question is out of curiosity because I'd like to learn more about <code>pytest</code>.</p>
<hr>
<p>Addition: Same question, but different use case: I'd like to check if a 3rd-party plugin fullfills a version requierement. If this is not the case I'd like to show a message and stop py.test. </p>
| 8 | 2016-08-31T20:02:15Z | 39,515,114 | <p>Have you considered writing a session-scoped pytest fixture? Something like:</p>
<pre><code>@pytest.fixture(scope="session")
def global_check(request):
assert initial_condition
def final_check(request):
assert final_condition
request.addfinalizer(final_check)
return request
</code></pre>
<p>If all of your other fixtures inherit from <code>global_check</code>, then <code>initial_condition</code> will be asserted at the beginning of all of your test runs and <code>final_condition</code> will be asserted at the end of your test runs.</p>
| 0 | 2016-09-15T15:36:47Z | [
"python",
"py.test"
] |
Datetime does not work in my index series | 39,258,290 | <p>I have a hf5 filled with some data. </p>
<p>when I open it in python I have this output</p>
<pre><code>hf['SB'].head()
0_1 price cng
2015-07-15 07:30:00.087 12.61 4
2015-07-15 07:30:00.087 12.61 1
2015-07-15 07:30:00.087 12.61 1
2015-07-15 07:30:00.087 12.61 2
2015-07-15 07:30:00.087 12.61 19
</code></pre>
<p>This file ranges from 2015 to 2016.</p>
<pre><code>hf['SB'].index
DatetimeIndex(['2015-07-15 07:30:00.087000', '2015-07-15 07:30:00.087000',
'2015-07-15 07:30:00.087000', '2015-07-15 07:30:00.087000',
'2015-07-15 07:30:00.087000', '2015-07-15 07:30:00.087000',
'2015-07-15 07:30:00.087000', '2015-07-15 07:30:00.087000',
'2015-07-15 07:30:00.087000', '2015-07-15 07:30:00.087000',
...
'2016-07-14 16:59:57.670000', '2016-07-14 16:59:58.047000',
'2016-07-14 16:59:59.170000', '2016-07-14 16:59:59.170000',
'2016-07-14 16:59:59.170000', '2016-07-14 16:59:59.170000',
'2016-07-14 16:59:59.170000', '2016-07-14 16:59:59.170000',
'2016-07-14 16:59:59.170000', '2016-07-14 16:59:59.957000'],
dtype='datetime64[ns]', name=u'0_1', length=3961015, freq=None)
</code></pre>
<p>Well... My problem is:</p>
<p>when I want a slice, for example, august 20 2015:</p>
<pre><code>hf['SB'][datetime(2015,8,20)]
</code></pre>
<p>I got this error: <code>KeyError: datetime.datetime(2015, 8, 20, 0, 0)</code></p>
<p>But if I use:</p>
<pre><code>hf['SB']['2015-08-20']
</code></pre>
<p>its works!!!</p>
<p>There is something wrong in my index file or I'm using <code>datetime</code> function wrong?</p>
| 0 | 2016-08-31T20:16:06Z | 39,258,610 | <p>I believe, that you are truing to get value for a key which is not present in index at all. <code>hf['SB']['2015-08-20']</code> will give you all records for that particular date.
See example below:</p>
<pre><code>>>> rng = pd.date_range('1/1/2016', periods=10, freq='S')
>>> ts = pd.Series(np.random.randn(len(rng)), index=rng)
>>> ts = ts[1:]
>>> ts
2016-01-01 00:00:01 0.133551
2016-01-01 00:00:02 1.067772
2016-01-01 00:00:03 0.591676
2016-01-01 00:00:04 -2.445586
2016-01-01 00:00:05 0.700155
2016-01-01 00:00:06 -0.127861
2016-01-01 00:00:07 1.116494
2016-01-01 00:00:08 -0.427959
2016-01-01 00:00:09 2.115352
Freq: S, dtype: float64
>>> ts[datetime.date(2016,1,1)]
....
KeyError: datetime.date(2016, 1, 1)
>>> ts['2016-01-01']
2016-01-01 00:00:01 0.133551
2016-01-01 00:00:02 1.067772
2016-01-01 00:00:03 0.591676
2016-01-01 00:00:04 -2.445586
2016-01-01 00:00:05 0.700155
2016-01-01 00:00:06 -0.127861
2016-01-01 00:00:07 1.116494
2016-01-01 00:00:08 -0.427959
2016-01-01 00:00:09 2.115352
Freq: S, dtype: float64
</code></pre>
<p>so with <code>hf['SB']['2015-08-20']</code> you are getting all records for '2015-08-20', but none for <code>datetime.datetime(2015,8,20,0,0)</code></p>
<p>if you want a slice using datetime, try following:</p>
<pre><code>>>> ts[datetime.datetime(2016,1,1,0,0,1):datetime.datetime(2016,1,1,0,0,3)]
2016-01-01 00:00:01 0.133551
2016-01-01 00:00:02 1.067772
2016-01-01 00:00:03 0.591676
Freq: S, dtype: float64
</code></pre>
| 1 | 2016-08-31T20:39:26Z | [
"python",
"datetime",
"pandas"
] |
Sorting all the sub Dictionary using values of one of the sub dictionary | 39,258,329 | <p>I have data structure like the below and would like to sort the
all the sub dictionaries to be sorted based on the values of the 'order' column.</p>
<p>Input:</p>
<pre><code>to_sort = [
('Fruits',
{
'size': {1:[4, 2, 7,9]},
'name': {1:['Orange', 'Apple', 'Kiwi', 'Mango']},
'color': {1:['Orange', 'Red', 'Brown','Green']},
'order': {1:[2, 1, 4,3]}
}
)
]
</code></pre>
<p>output:</p>
<pre><code>[
('Fruits',
{
'size': {1:[2, 4, 9, 7]},
'name': {1:['Apple', 'Orange', 'Mango', 'Kiwi']},
'color':{1:['Red', 'Orange', 'Green', 'Brown']},
'order':{1:[1, 2, 3, 4]}
}
)
]
</code></pre>
<p>I tried using the lambda</p>
<pre><code>sort = to_sort[1]
print(sorted(sort.items(), key=lambda i: i['order'].values()))
</code></pre>
<p>i am getting "tuple indices must be integers or slices, not str" error</p>
| 4 | 2016-08-31T20:18:18Z | 39,258,731 | <p>Assuming you are okay with modifying your data structure as mentioned in the comments, this will work for you. This is adapted from this other question: <a href="http://stackoverflow.com/q/6618515/3901060">Sorting list based on values from another list?</a></p>
<pre><code>to_sort = [('Fruits', {
'size': [4, 2, 7,9],
'name': ['Orange', 'Apple', 'Kiwi', 'Mango'],
'color': ['Orange', 'Red', 'Brown','Green'],
'order': [2, 1, 4,3]
})
]
postsort = []
for category, catdata in to_sort:
sorteddata = {}
for name, namedata in catdata.iteritems():
sorteddata[name] = [x for (y,x) in sorted(zip(catdata['order'], namedata))]
postsort.append((category, sorteddata))
print postsort
</code></pre>
<p>Which results in:</p>
<pre><code>[(
'Fruits',
{
'color': ['Red', 'Orange', 'Green', 'Brown'],
'size': [2, 4, 9, 7],
'order': [1, 2, 3, 4],
'name': ['Apple', 'Orange', 'Mango', 'Kiwi']
}
)]
</code></pre>
<p>This could be modified to work with your existing data structure, but I would recommend making the change if that is possible.</p>
| 1 | 2016-08-31T20:47:21Z | [
"python",
"python-3.x"
] |
Sorting all the sub Dictionary using values of one of the sub dictionary | 39,258,329 | <p>I have data structure like the below and would like to sort the
all the sub dictionaries to be sorted based on the values of the 'order' column.</p>
<p>Input:</p>
<pre><code>to_sort = [
('Fruits',
{
'size': {1:[4, 2, 7,9]},
'name': {1:['Orange', 'Apple', 'Kiwi', 'Mango']},
'color': {1:['Orange', 'Red', 'Brown','Green']},
'order': {1:[2, 1, 4,3]}
}
)
]
</code></pre>
<p>output:</p>
<pre><code>[
('Fruits',
{
'size': {1:[2, 4, 9, 7]},
'name': {1:['Apple', 'Orange', 'Mango', 'Kiwi']},
'color':{1:['Red', 'Orange', 'Green', 'Brown']},
'order':{1:[1, 2, 3, 4]}
}
)
]
</code></pre>
<p>I tried using the lambda</p>
<pre><code>sort = to_sort[1]
print(sorted(sort.items(), key=lambda i: i['order'].values()))
</code></pre>
<p>i am getting "tuple indices must be integers or slices, not str" error</p>
| 4 | 2016-08-31T20:18:18Z | 39,258,851 | <h2> How to deal with what you've got</h2>
<p>Your existing data structure is a bit crazy, but here is how I would handle it (<strong>edit</strong> suppose the key for the color list was <code>123</code>):</p>
<pre><code>>>> to_sort = [
... ('Fruits',
... {
... 'size': {1:[4, 2, 7,9]},
... 'name': {1:['Orange', 'Apple', 'Kiwi', 'Mango']},
... 'color': {123:['Orange', 'Red', 'Brown','Green']},
... 'order': {1:[2, 1, 4,3]}
... }
... )
... ]
>>> d = to_sort[0][1]
>>> keys = list(d.keys())
>>> idx = keys.index('order')
>>> ordered_kv = zip(keys, zip(*sorted(zip(*(d[k][n] for k in keys for n in d[k])), key = lambda t:t[idx])))
>>> sorted_dict = {k:{n:list(v) for n in d[k]} for k,v in ordered_kv}
>>> from pprint import pprint
>>> pprint(sorted_dict)
{'color': {123: ['Red', 'Orange', 'Green', 'Brown']},
'name': {1: ['Apple', 'Orange', 'Mango', 'Kiwi']},
'order': {1: [1, 2, 3, 4]},
'size': {1: [2, 4, 9, 7]}}
</code></pre>
<p>Let's break this down: First, I made a canonical list of keys and find the index of <code>'order'</code>:</p>
<pre><code>>>> keys = list(to_sort[0][1].keys())
>>> idx = keys.index('order')
</code></pre>
<p>The next step is to <code>zip</code> the internal lists together into tuples where each of the items share the same relative position:</p>
<pre><code>>>> list(zip(*(d[k][n] for k in keys for n in d[k])))
[(4, 2, 'Orange', 'Orange'), (2, 1, 'Red', 'Apple'), (7, 4, 'Brown', 'Kiwi'), (9, 3, 'Green', 'Mango')]
</code></pre>
<p>This can be sorted now according the the <code>idx</code> position and then "unzipped" (which really just means applying the <a href="http://stackoverflow.com/questions/5917522/unzipping-and-the-operator">zip-splat</a> combination again:</p>
<pre><code>>>> list(zip(*sorted(zip(*(d[k][n] for k in keys for n in d[k])), key=lambda t:t[idx])))
[(2, 4, 9, 7), (1, 2, 3, 4), ('Red', 'Orange', 'Green', 'Brown'), ('Apple', 'Orange', 'Mango', 'Kiwi')]
</code></pre>
<p>And finally, you rebuild your crazy dictionary with a dictionary comprehension, making sure to zip up your ordered values with the original keys:</p>
<pre><code>>>> ordered_kv = zip(keys, zip(*sorted(zip(*(d[k][n] for k in keys for n in d[k])), key = lambda t:t[idx])))
>>> sorted_dict = {k:{n:list(v) for n in d[k]} for k,v in ordered_kv}
>>> from pprint import pprint
>>> pprint(sorted_dict)
{'color': {123: ['Red', 'Orange', 'Green', 'Brown']},
'name': {1: ['Apple', 'Orange', 'Mango', 'Kiwi']},
'order': {1: [1, 2, 3, 4]},
'size': {1: [2, 4, 9, 7]}}
</code></pre>
<h2> However...</h2>
<p>You should really consider using the <code>pandas</code> library for manipulating data like this. Observe:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({k: pd.Series(v[1]) for k,v in to_sort[0][1].items()})
>>> df
color name order size
0 Orange Orange 2 4
1 Red Apple 1 2
2 Brown Kiwi 4 7
3 Green Mango 3 9
</code></pre>
<p>Notice I still had to finagle your original data structure into a <code>pandas</code> DataFrame, but if you start whatever you are doing with a <code>DataFrame</code> to begin with, it will all be much easier. Now you can do cool things like: </p>
<pre><code>>>> df.sort_values('order')
color name order size
1 Red Apple 1 2
0 Orange Orange 2 4
3 Green Mango 3 9
2 Brown Kiwi 4 7
</code></pre>
| 1 | 2016-08-31T20:55:27Z | [
"python",
"python-3.x"
] |
How to check Ubuntu program coredump in either bash or python? | 39,258,362 | <p>I have a binary foo, and i will give a file input to foo which may potentially trigger coredump in Ubuntu. I write a loop to do so and I change the file content in every iteration. But I would like to terminate the loop whenever a coredump appears. Here is the bash code:</p>
<pre><code>while true
do
change_file file_s > file_new
./foo file_new
# need to check coredump to terminate the loop
done
</code></pre>
<p>I can change the script to python if it is easier to do that in python.</p>
| 1 | 2016-08-31T20:20:42Z | 39,258,460 | <p>If the return code is greater than 127, then the program exited due to a signal. Core dumps only happen as the result of this sort of exit.</p>
<pre><code>./foo file_new
if (($? > 127)); then
echo foo crashed
break
fi
</code></pre>
| 1 | 2016-08-31T20:28:12Z | [
"python",
"bash",
"ubuntu",
"coredump"
] |
How to identify the values of indexes around a specific array coordinate? | 39,258,576 | <p>If I had a 2-D array, representing a world, that looked something like: </p>
<pre><code>. . . . . . . . . . . . . . .
. P . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . . t . . . . . . . .
. . . . . . . t . . . . . . .
. . . . . . . t t . . . . . .
. . . . . m . . . . . . . . .
. . . . . . m m . . . . . . .
. . . . . . . . m m . . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . . m . . .
. . . . . . . . . . . . . . .
</code></pre>
<p><code>m</code> stands for <code>mountains</code>, <code>t</code> for <code>trees</code> and <code>P</code> for <code>Player</code>.</p>
<p>Now, let's say we have a <code>Player</code> class that tracks the <code>userpos</code> or user position in an array, which is currently <code>(1, 1)</code>:</p>
<pre><code>class Player(object):
def __init__(self, x, y, array):
self.x = x
self.y = y
self.userpos = array[x][y]
</code></pre>
<p>If I were to write a method inside of the <code>Player</code> class that deals with basic movement controls to edit the location of the <code>P</code> value inside of the array, how could I go about tracking the 8 tiles around the <code>P</code> value? For example, we can see all of the tiles around the current <code>player</code> <code>userpos</code> is all <code>.</code>'s. </p>
<p>I want to restrict the player from moving onto <code>m</code> tiles, being that they are mountains. It is easy to identify the current tile with the <code>userpos</code> variable, since the <code>P</code> value is only added to a string version of the map, and not the actual array. However, the issue comes from trying to move the player to a previous position. I want to be able to return the player to the nearest <code>empty</code> or <code>.</code> tile, but do not know how to decide what index inside of the array that the player should be moved to. </p>
<p>Is there an easier way of doing this, or would tracking the tiles around the player be the easiest way?</p>
| 0 | 2016-08-31T20:36:23Z | 39,258,755 | <p>Since you got the x and y and the original array, you should be able to iterate through this points with code like:</p>
<pre><code>tiles_to_move = []
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if i != x or j != y:
if array[i][j] != 'm': # depends on how you manage your array
tiles_to_move.append([i, j])
</code></pre>
<p>and use the tiles stored in <code>tiles_to_move</code> to determine your next optional move.</p>
| 0 | 2016-08-31T20:49:24Z | [
"python",
"arrays",
"python-2.7",
"multidimensional-array"
] |
How to identify the values of indexes around a specific array coordinate? | 39,258,576 | <p>If I had a 2-D array, representing a world, that looked something like: </p>
<pre><code>. . . . . . . . . . . . . . .
. P . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . . t . . . . . . . .
. . . . . . . t . . . . . . .
. . . . . . . t t . . . . . .
. . . . . m . . . . . . . . .
. . . . . . m m . . . . . . .
. . . . . . . . m m . . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . . m . . .
. . . . . . . . . . . . . . .
</code></pre>
<p><code>m</code> stands for <code>mountains</code>, <code>t</code> for <code>trees</code> and <code>P</code> for <code>Player</code>.</p>
<p>Now, let's say we have a <code>Player</code> class that tracks the <code>userpos</code> or user position in an array, which is currently <code>(1, 1)</code>:</p>
<pre><code>class Player(object):
def __init__(self, x, y, array):
self.x = x
self.y = y
self.userpos = array[x][y]
</code></pre>
<p>If I were to write a method inside of the <code>Player</code> class that deals with basic movement controls to edit the location of the <code>P</code> value inside of the array, how could I go about tracking the 8 tiles around the <code>P</code> value? For example, we can see all of the tiles around the current <code>player</code> <code>userpos</code> is all <code>.</code>'s. </p>
<p>I want to restrict the player from moving onto <code>m</code> tiles, being that they are mountains. It is easy to identify the current tile with the <code>userpos</code> variable, since the <code>P</code> value is only added to a string version of the map, and not the actual array. However, the issue comes from trying to move the player to a previous position. I want to be able to return the player to the nearest <code>empty</code> or <code>.</code> tile, but do not know how to decide what index inside of the array that the player should be moved to. </p>
<p>Is there an easier way of doing this, or would tracking the tiles around the player be the easiest way?</p>
| 0 | 2016-08-31T20:36:23Z | 39,258,927 | <p>I think a better solution would be to have a method which tries to move the player in the desired direction and have that method be outside the player class since the player class shouldn't know about the map (code not tested):</p>
<pre><code>def try_to_move_player(direction,map,player):
desired_x = player.x
desired_y = player.y
if direction == "Left":
desired_x -= 1
elif direction == "Right":
desired_x += 1
#etc
#Prevent player from moving off map left or right
if desired_x < 0 or desired_x > len(map): #<-- map length might not be right
return False
#do the same for going above or below
#Prevent the player from moving into mountains
if map[desired_x][desired_y] == "m":
print "Tried to walk into a mountain"
return False
#After all incorrect moving is taken care of
player.x = desired_x
player.y = desired_y
return True
class Player(object):
def __init__(self, x, y, array):
self.x = x
self.y = y
self.userpos = array[x][y]
#Try to move the player left
moved_successfully = try_to_move_player("Left",map,player)
if moved_successfully:
print "The player was moved successfully w/ an updated position"
else:
print "The player was not moved correctly"
</code></pre>
| 0 | 2016-08-31T21:00:39Z | [
"python",
"arrays",
"python-2.7",
"multidimensional-array"
] |
How to identify the values of indexes around a specific array coordinate? | 39,258,576 | <p>If I had a 2-D array, representing a world, that looked something like: </p>
<pre><code>. . . . . . . . . . . . . . .
. P . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . . t . . . . . . . .
. . . . . . . t . . . . . . .
. . . . . . . t t . . . . . .
. . . . . m . . . . . . . . .
. . . . . . m m . . . . . . .
. . . . . . . . m m . . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . . m . . .
. . . . . . . . . . . . . . .
</code></pre>
<p><code>m</code> stands for <code>mountains</code>, <code>t</code> for <code>trees</code> and <code>P</code> for <code>Player</code>.</p>
<p>Now, let's say we have a <code>Player</code> class that tracks the <code>userpos</code> or user position in an array, which is currently <code>(1, 1)</code>:</p>
<pre><code>class Player(object):
def __init__(self, x, y, array):
self.x = x
self.y = y
self.userpos = array[x][y]
</code></pre>
<p>If I were to write a method inside of the <code>Player</code> class that deals with basic movement controls to edit the location of the <code>P</code> value inside of the array, how could I go about tracking the 8 tiles around the <code>P</code> value? For example, we can see all of the tiles around the current <code>player</code> <code>userpos</code> is all <code>.</code>'s. </p>
<p>I want to restrict the player from moving onto <code>m</code> tiles, being that they are mountains. It is easy to identify the current tile with the <code>userpos</code> variable, since the <code>P</code> value is only added to a string version of the map, and not the actual array. However, the issue comes from trying to move the player to a previous position. I want to be able to return the player to the nearest <code>empty</code> or <code>.</code> tile, but do not know how to decide what index inside of the array that the player should be moved to. </p>
<p>Is there an easier way of doing this, or would tracking the tiles around the player be the easiest way?</p>
| 0 | 2016-08-31T20:36:23Z | 39,259,197 | <p>You can add a method to your <code>Player</code> class which will move a given number of steps vertically and/or horizontally. It could achieve this by calculating what the new coordinates of the <code>Player</code> object would be and checking the matrix at that index to make sure it's not a mountain (I'm also assuming you don't want your <code>Player</code> object to walk into trees).</p>
<pre><code>class Player(object):
def __init__(self, x, y, array):
self.x = x
self.y = y
self.userpos = array[x][y]
# Make a list of the different items that can block the player
self.obstacles = ['m', 't']
def move(self xOffset, yOffset, array):
newX = self.x + xOffset
newY = self.y + yOffset
# The following two conditionals make sure that the position
# that the player is trying to move to is within the actual
# bounds of the array
if 0 <= newX < len(array):
if 0 <= newY < len(array[newX]):
# Check if the position that the player is trying to
# move to is not filled by an obstacle
if array[newX][newY] not in self.obstacles:
self.x = newX
self.y = newY
</code></pre>
| 0 | 2016-08-31T21:21:00Z | [
"python",
"arrays",
"python-2.7",
"multidimensional-array"
] |
iPyWidget with date slider? | 39,258,580 | <p>I am wondering if there's an easy way to build an iPyWidget with a datetime slider. Right now it is easy to slide over integer or floating point ranges (e.g. numbers 1-10, decimals 0.01, 0.02, ...). </p>
<p>I imagine you could convert dates to floats or integers, build some sort of slider using these, and then convert back to dates for the display labels on the slider. However, this seems clunky. Does anyone have a smoother solution? </p>
| 0 | 2016-08-31T20:36:41Z | 39,268,222 | <p>I had the same issue recently. I had to write my own class to do a daterange picker. Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import ipywidgets as widgets
from IPython.display import display
class DateRangePicker(object):
def __init__(self,start,end,freq='D',fmt='%Y-%m-%d'):
"""
Parameters
----------
start : string or datetime-like
Left bound of the period
end : string or datetime-like
Left bound of the period
freq : string or pandas.DateOffset, default='D'
Frequency strings can have multiples, e.g. '5H'
fmt : string, defauly = '%Y-%m-%d'
Format to use to display the selected period
"""
self.date_range=pd.date_range(start=start,end=end,freq=freq)
options = [(item.strftime(fmt),item) for item in self.date_range]
self.slider_start = widgets.SelectionSlider(
description='start',
options=options,
continuous_update=False
)
self.slider_end = widgets.SelectionSlider(
description='end',
options=options,
continuous_update=False,
value=options[-1][1]
)
self.slider_start.on_trait_change(self.slider_start_changed, 'value')
self.slider_end.on_trait_change(self.slider_end_changed, 'value')
self.widget = widgets.Box(children=[self.slider_start,self.slider_end])
def slider_start_changed(self,key,value):
self.slider_end.value=max(self.slider_start.value,self.slider_end.value)
self._observe(start=self.slider_start.value,end=self.slider_end.value)
def slider_end_changed(self,key,value):
self.slider_start.value=min(self.slider_start.value,self.slider_end.value)
self._observe(start=self.slider_start.value,end=self.slider_end.value)
def display(self):
display(self.slider_start,self.slider_end)
def _observe(self,**kwargs):
if hasattr(self,'observe'):
self.observe(**kwargs)
def fct(start,end):
print start,end
</code></pre>
<p>Using it is relatively straightforward:</p>
<pre class="lang-py prettyprint-override"><code>w=DateRangePicker(start='2016-08-02',end="2016-09-02",freq='D',fmt='%Y-%m-%d')
w.observe=fct
w.display()
</code></pre>
<p>Enjoy ;-)</p>
| 1 | 2016-09-01T09:49:22Z | [
"python",
"jupyter",
"ipywidgets"
] |
running two process simultaneously | 39,258,616 | <p>I'm trying to run 2 processes simultaneously, but only the first one runs </p>
<pre><code>def add():
while True:
print (1)
time.sleep(3)
def sud():
while True:
print(0)
time.sleep(3)
p1 = multiprocessing.Process(target=add)
p1.run()
p = multiprocessing.Process(target=sud)
p.run()
</code></pre>
| -1 | 2016-08-31T20:39:53Z | 39,258,674 | <p>The method you're looking for is <code>start</code>, not <code>run</code>. <code>start</code> starts the process and calls <code>run</code> to perform the work in the new process; if you call <code>run</code>, you run the work in the calling process instead of a new process.</p>
| 2 | 2016-08-31T20:43:31Z | [
"python",
"multiprocessing"
] |
running two process simultaneously | 39,258,616 | <p>I'm trying to run 2 processes simultaneously, but only the first one runs </p>
<pre><code>def add():
while True:
print (1)
time.sleep(3)
def sud():
while True:
print(0)
time.sleep(3)
p1 = multiprocessing.Process(target=add)
p1.run()
p = multiprocessing.Process(target=sud)
p.run()
</code></pre>
| -1 | 2016-08-31T20:39:53Z | 39,260,326 | <p>Below will work for sure but try to run this as a module.Don't try in console or Jupiter notebook as notebook will never satisfy the condition "if <strong>name</strong> == '<strong>main</strong>'".
Save the entire code in a file say process.py and run it from command prompt.
Edit -
It's working fine. Just now I tried - <a href="http://i.stack.imgur.com/fOQl0.png" rel="nofollow"><img src="http://i.stack.imgur.com/fOQl0.png" alt="enter image description here"></a></p>
<pre><code>import multiprocessing
import time
def add():
while True:
print (1)
time.sleep(3)
def sud():
while True:
print(0)
time.sleep(3)
if __name__ == '__main__':
p1 = multiprocessing.Process(name='p1', target=add)
p = multiprocessing.Process(name='p', target=sud)
p1.start()
p.start()
</code></pre>
| -1 | 2016-08-31T23:03:19Z | [
"python",
"multiprocessing"
] |
Finding global matches inside a pattern | 39,258,669 | <p>If I have a pattern like this: (<a href="https://regex101.com/r/cR0aG8/12" rel="nofollow">https://regex101.com/r/cR0aG8/12</a>)</p>
<pre><code>Product:.*?(.*?),.*?ReqID:
</code></pre>
<p>I assume(d) that</p>
<pre><code>Product.*?(.*?),.*?ReqID:
</code></pre>
<p>would find <code>Toys</code>, <code>Books</code>, <code>Clothes</code> individually with G(lobal) on since to my (somewhat newbie) eye it is looking for ANY match that has <code>Product:</code> and any string ending in a comma before it and any string ending in <code>ReqID:</code> after it.</p>
<p>But as you can see by the regeg101 global-on gets the exact same result as global-off; the very first ,. Is there a way to structure this so the regex says just that (any string preceded by <code>Product:</code> and a <code>,</code> and followed by a <code>ReqID</code>? </p>
<p>Essentially I need to gather all values before or after a <code>,</code> that are bordered by the start/end pattern.</p>
| -1 | 2016-08-31T20:43:21Z | 39,258,784 | <p>You need to create separate groups:</p>
<pre><code>Product: (.*?), (.*?), (.*?), (.*?) ReqID:
</code></pre>
<p>To match these words. You don't even need <code>?</code> for this pattern.</p>
<p>This is a sed for multiple patterns:</p>
<pre><code>$ cat t1
Product: Toys, Books, Clothes, Radios ReqID:
Product: Toys, Books, Clothes, Radios ReqID:z
izProduct: Toys, Books, Clothes, Radios ReqID:
$ sed -e '/^Product:.*ReqID:$/ s/\(\w\+\)\(,\| \)/REPLACE\2/g' < t1
Product: REPLACE, REPLACE, REPLACE, REPLACE ReqID:
Product: Toys, Books, Clothes, Radios ReqID:z
izProduct: Toys, Books, Clothes, Radios ReqID:
</code></pre>
<p>It looks for line starting with <code>Product:</code> and ending with <code>ReqID:</code>. For each line it matches <code>\(\w\+\)\(,\| \)</code></p>
| 0 | 2016-08-31T20:51:45Z | [
"python",
"regex"
] |
Finding global matches inside a pattern | 39,258,669 | <p>If I have a pattern like this: (<a href="https://regex101.com/r/cR0aG8/12" rel="nofollow">https://regex101.com/r/cR0aG8/12</a>)</p>
<pre><code>Product:.*?(.*?),.*?ReqID:
</code></pre>
<p>I assume(d) that</p>
<pre><code>Product.*?(.*?),.*?ReqID:
</code></pre>
<p>would find <code>Toys</code>, <code>Books</code>, <code>Clothes</code> individually with G(lobal) on since to my (somewhat newbie) eye it is looking for ANY match that has <code>Product:</code> and any string ending in a comma before it and any string ending in <code>ReqID:</code> after it.</p>
<p>But as you can see by the regeg101 global-on gets the exact same result as global-off; the very first ,. Is there a way to structure this so the regex says just that (any string preceded by <code>Product:</code> and a <code>,</code> and followed by a <code>ReqID</code>? </p>
<p>Essentially I need to gather all values before or after a <code>,</code> that are bordered by the start/end pattern.</p>
| -1 | 2016-08-31T20:43:21Z | 39,258,802 | <p>If you are using PCRE engine (like your demo is made on it) or any of .NET, Java, Ruby or Perl regex flavors then use start match from end of previous one token <code>\G</code>:</p>
<pre><code>(?:Product:|(?!\A)\G)(\s+\w+),
</code></pre>
<p><a href="https://regex101.com/r/hG6gP8/3" rel="nofollow">Live demo</a></p>
<h2>Update</h2>
<p>Based on new requirements:</p>
<pre><code>(?:Product:|(?!\A)\G)\s*(\w+)(?:,| \w+:)
</code></pre>
<p><a href="https://regex101.com/r/hG6gP8/4" rel="nofollow">Live demo</a></p>
| 0 | 2016-08-31T20:52:38Z | [
"python",
"regex"
] |
Modification of Future Value | 39,258,769 | <p>For this you have to add the annual contribution to the beginning of the year (the principal total) before computing interest for that year.</p>
<p>I am stuck and need help. This is what I have so far:</p>
<pre><code>def main():
print("Future Value Program - Version 2")
print()
principal = eval(input("Enter Initial Principal:"))
contribution = eval(input("Enter Annual Contribution:"))
apr = eval(input("Enter Annual Percentage Rate (decimal):"))
yrs = eval(input("Enter Number of Years:"))
for k in range (1, yrs):
principal= principal * (1 + apr)
print()
print( yrs,) ": Amount $", int(principal * 100 + 0.5)/100)
main()
</code></pre>
<p>It is supposed to look like this:</p>
<pre><code>Future Value Program - Version 2
Enter Initial Principal: 1000.00
Enter Annual Contribution: 100.00
Enter Annual Percentage Rate (decimal): 0.034
Enter Number of Years: 5
Year 1: Amount $ 1137.4
Year 2: Amount $ 1279.47
Year 3: Amount $ 1426.37
Year 4: Amount $ 1578.27
Year 5: Amount $ 1735.33
The value in 5 years is $ 1735.33
</code></pre>
| 0 | 2016-08-31T20:50:43Z | 39,259,382 | <p>Here's a working example that produces the expected output:</p>
<pre><code>def main():
print("Future Value Program - Version 2")
print()
principal = float(input("Enter Initial Principal: "))
contribution = float(input("Enter Annual Contribution: "))
apr = float(input("Enter Annual Percentage Rate (decimal): "))
yrs = int(input("Enter Number of Years: "))
print()
for yr in range(1, yrs + 1):
principal += contribution
principal = int(((principal * (1 + apr)) * 100) + 0.5) / 100
print("Year {0}: Amount $ {1}".format(yr, principal))
print()
print("The value in {0} years is $ {1}".format(yrs, principal))
if __name__ == '__main__':
main()
</code></pre>
<p>There were a few problems with the example in the question:</p>
<ol>
<li>A syntax error in the print statement on line 12. Calling <code>print</code> with parens means all the arguments should be enclosed inside the parens. Python interpreted the errant paren as the end of arguments passed to <code>print</code>.</li>
<li>As noted by others, you shouldn't call <code>eval</code> on the inputs. Call <code>float</code> for floating point numbers, <code>int</code> for integers.</li>
<li>The <code>range</code> operator had an off by one error.</li>
<li>As noted by others, <code>print</code> is called outside of the loop, so intermediate states of the principal aren't output.</li>
<li>As far as basic maths, it seems as though adding the contribution was left out.</li>
<li>As per the expected output, the final <code>print</code> was missing.</li>
</ol>
| 0 | 2016-08-31T21:35:18Z | [
"python",
"python-3.x"
] |
Python pull values from nested dictionary for args in function call | 39,258,783 | <p>So I'm writing a bit of Python code to read in JSON data containing object types and parameters. I essentially need to run through this data and call one of a few functions that, using those parameters, creates a new, unique object each time to be used later. The JSON data looks like this:</p>
<pre><code> {
"objects" : {
"1" : {
"type" : "sphere",
"radius" : "100",
"centerx" : "30",
"centery" : "40",
"centerz" : "50"
},
"2" : {
"type" : "box",
"lengthx" : "30",
"lengthy" : "40",
"lengthz" : "50",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
},
"3" : {
"type" : "cone",
"length" : "30",
"radius1" : "40",
"radius2" : "50",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
},
"4" : {
"type" : "cylinder",
"length" : "30",
"radius" : "40",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
}
}
}
</code></pre>
<p>Here's my updated code as it stands now:</p>
<pre><code>display, start_display, add_menu, add_function_to_menu = init_display()
with open('C:\Users\willi_000\Documents\Code\document (9).json') as data_file:
data = json.load(data_file)
funcs = {
'sphere': BRepPrimAPI_MakeSphere,
'box': BRepPrimAPI_MakeBox,
'cone': BRepPrimAPI_MakeCone,
'cylinder': BRepPrimAPI_MakeCylinder
}
shapes = []
for index, kwargs in data['objects'].iteritems():
mypoint = gp_Pnt(float(kwargs.pop('centerx')), float(kwargs.pop('centery')), float(kwargs.pop('centerz')))
function = funcs[kwargs.pop('type')]
#print mypoint
#print function
myshape = function(mypoint,float(**kwargs)).Shape()
start_display()
</code></pre>
<p>And night now I'm getting the following error</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/willi_000/Documents/Code/dumbbox.py", line 32, in <module>
myshape = function(mypoint,**kwargs).Shape()
TypeError: keywords must be strings"
</code></pre>
<p>For reference, here are two examples of what the make functions are expecting</p>
<pre><code>BRepPrimAPI_MakeSphere::BRepPrimAPI_MakeSphere ( const gp_Pnt & Center,
const Standard_Real R )
BRepPrimAPI_MakeBox::BRepPrimAPI_MakeBox ( const gp_Pnt & P,
const Standard_Real dx,
const Standard_Real dy,
const Standard_Real dz )
</code></pre>
| 1 | 2016-08-31T20:51:43Z | 39,258,987 | <p>This will add all of the <code>Shapes</code> to a list. </p>
<pre><code>data ={
"objects" : {
"1" : {
"type" : "sphere",
"radius" : "100",
"centerx" : "30",
"centery" : "40",
"centerz" : "50"
},
"2" : {
"type" : "box",
"lengthx" : "30",
"lengthy" : "40",
"lengthz" : "50",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
},
"3" : {
"type" : "cone",
"length" : "30",
"radius1" : "40",
"radius2" : "50",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
},
"4" : {
"type" : "cylinder",
"length" : "30",
"radius" : "40",
"centerx" : "60",
"centery" : "70",
"centerz" : "80"
}
}
}
funcs = {
'sphere': BRepPrimAPI_MakeSphere,
'box': BRepPrimAPI_MakeBox,
'cone': BRepPrimAPI_MakeCone,
'cylinder': BRepPrimAPI_MakeCylinder
}
shapes = []
for index, kwargs in data['objects'].iteritems():
function = funcs[kwargs.pop('type')]
shapes.append(function(**kwargs).Shape())
</code></pre>
<p>I had to fake the functions and the <code>.Shape()</code> part, but it works for me.</p>
<hr>
<h2>Update</h2>
<p>As per the comment (by @williamwatts), I think this is what you want. Replace the <code>for</code> loop with this:</p>
<pre><code>for index, kwargs in data['objects'].iteritems():
function = funcs[kwargs.pop('type')]
kwargs = {k:float(v) for k, v in kwargs.iteritems()}
mypoint = gp_Pnt(kwargs.pop('centerx'), kwargs.pop('centery'), kwargs.pop('centerz'))
myshape = function(mypoint, **kwargs).Shape()
shapes.append(myshape)
display.DisplayShape(myshape, update=True)
</code></pre>
<p>This assumes that all shapes will have <code>centerx</code>, <code>centery</code> and <code>centerz</code> attributes.</p>
<hr>
<h2>Update 2</h2>
<p>Since the functions are defined using *args, you cannot use keyword arguments. You will have to use this instead:</p>
<pre><code>funcs = {
'sphere': {
'function': BRepPrimAPI_MakeSphere,
'argnames': ['radius']
},
'box': {
'function': BRepPrimAPI_MakeBox,
'argnames': ['lengthx', 'lengthy', 'lengthz']
},
'cone': {
'function': BRepPrimAPI_MakeCone,
'argnames': ['length', 'radius1', 'radius2']
},
'cylinder': {
'function': BRepPrimAPI_MakeCylinder,
'argnames': ['length', 'radius']
}
}
shapes = []
for index, kwargs in data['objects'].iteritems():
print kwargs
shapeinfo = funcs[kwargs.pop('type')]
kwargs = {k:float(v) for k, v in kwargs.iteritems()}
mypoint = gp_Pnt(kwargs.pop('centerx'), kwargs.pop('centery'), kwargs.pop('centerz'))
args = [kwargs[name] for name in shapeinfo['argnames']]
myshape = shapeinfo['function'](mypoint, *args).Shape()
shapes.append(myshape)
display.DisplayShape(myshape, update=True)
</code></pre>
<p>This makes sure that the args are sent in the correct order.</p>
| 2 | 2016-08-31T21:04:36Z | [
"python",
"json",
"dictionary"
] |
Using Python to Post json contact list to Qualtrics API, error with Content-Type | 39,258,853 | <p>I'm trying to import contacts into a contact list in Qualtrics. I am using python to do this. </p>
<pre><code>Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
headers = {'X-API-TOKEN': Token, 'Content-Type':'application/json',}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports', headers=headers, data=data)
r.text
</code></pre>
<p>This code gives me the following error: '{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Invalid Content-Type. expected=multipart/form-data found=application/json","errorCode":"RP_0.1"},"requestId":null}}'</p>
<p>I changed the content type to multipart/form-data that it says it is expecting and received the response "413", which qualtrics explains means "The request body was too large. This can also happen in cases where a multipart/form-data request is malformed."</p>
<p>I have tested my json and verified that it is valid. Also, I don't know why the request body would be too large because it's only 13 contacts that I'm trying to import. Any ideas?</p>
| 2 | 2016-08-31T20:55:36Z | 39,259,011 | <p>You need to use <code>files = ..</code> for a <a href="http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">multipart</a> request:</p>
<pre><code>Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
headers = {'X-API-TOKEN': Token}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports',files={"file":data}, headers=headers)
r.text
</code></pre>
<p>Once you do requests will take care of the rest:</p>
<pre><code>In [36]: url = 'http://httpbin.org/post'
In [37]: headers = {'X-API-TOKEN': "123456789"}
In [38]: files = {'file': open('a.csv', 'rb')}
In [39]: r = requests.post(url, files=files, headers=headers)
In [40]: print r.text
{
"args": {},
"data": "",
"files": {
"file": "a,b,c\n1,2,3"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "152",
"Content-Type": "multipart/form-data; boundary=3830dbe5fa6141f69d3d85dee4ba6e78",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0",
"X-Api-Token": "123456789"
},
"json": null,
"origin": "51.171.98.185",
"url": "http://httpbin.org/post"
}
In [41]: print(r.request.body)
--3830dbe5fa6141f69d3d85dee4ba6e78
Content-Disposition: form-data; name="file"; filename="a.csv"
a,b,c
1,2,3
--3830dbe5fa6141f69d3d85dee4ba6e78--
</code></pre>
<p>looking at the <a href="https://api.qualtrics.com/docs/create-contacts-import" rel="nofollow">docs</a>, you actually want something closer to:</p>
<pre><code>Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
files = {'file': ('contact', data ,'application/json', {'X-API-TOKEN': Token})}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports',files=files)
</code></pre>
| 1 | 2016-08-31T21:06:34Z | [
"python",
"json",
"content-type",
"qualtrics"
] |
Using Python to Post json contact list to Qualtrics API, error with Content-Type | 39,258,853 | <p>I'm trying to import contacts into a contact list in Qualtrics. I am using python to do this. </p>
<pre><code>Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
data = open('contacts.json', 'rb')
headers = {'X-API-TOKEN': Token, 'Content-Type':'application/json',}
r = requests.post('https://az1.qualtrics.com/API/v3/mailinglists/' + ContactsID +'/contactimports', headers=headers, data=data)
r.text
</code></pre>
<p>This code gives me the following error: '{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Invalid Content-Type. expected=multipart/form-data found=application/json","errorCode":"RP_0.1"},"requestId":null}}'</p>
<p>I changed the content type to multipart/form-data that it says it is expecting and received the response "413", which qualtrics explains means "The request body was too large. This can also happen in cases where a multipart/form-data request is malformed."</p>
<p>I have tested my json and verified that it is valid. Also, I don't know why the request body would be too large because it's only 13 contacts that I'm trying to import. Any ideas?</p>
| 2 | 2016-08-31T20:55:36Z | 39,296,146 | <p>With the help of Qualtrics Support, I was eventually able to get the following code to work:</p>
<pre><code>Token = 'MyToken' #when running the code I put in my actual token and id
ContactsID = 'MyContactsID'
url = "https://az1.qualtrics.com/API/v3/mailinglists/" + ContactsID + "/contactimports/"
headers = {
'content-type': "multipart/form-data; boundary=---BOUNDRY",
'x-api-token': "Token"
}
files = {'contacts': ('contacts', open('contacts.json', 'rb'), 'application/json')}
request = requests.post(url, headers=headers, files=files)
print(request.text)
</code></pre>
<p>Please note that if you want to use this code, you will need to change "az1" in the URL to your own Qualtrics datacenter ID.</p>
| 1 | 2016-09-02T15:38:16Z | [
"python",
"json",
"content-type",
"qualtrics"
] |
Jenkins Master/Slave Windows | 39,258,953 | <p>Just want a clarification of the following. I am currently in the process of transferring a Bamboo plan into a Jenkins one and everything was working fine up until the point I ran a Python script on my CentOS Virtual Machine. The reason being that Python wants to import a library called <strong>winreg</strong> which is not available on RedHat distributions. </p>
<p>In order to fix this, I wanted to have my Master be a CentOS machine and my slave be a Windows 10 machine. Is that how it works? Will the plan be built on the Windows 10 machine while the output is handled by the CentOS machine?</p>
<p>Thanks</p>
| 0 | 2016-08-31T21:02:32Z | 39,284,421 | <p>Yes, it will. This is usual Jenkins using - see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Distributed+builds" rel="nofollow">documentation</a>.</p>
| 0 | 2016-09-02T04:38:45Z | [
"python",
"jenkins",
"centos"
] |
Open file with Adobe Captivate from command line | 39,258,993 | <p>I am attempting to open an XML file with Adobe Captivate in my script using <code>os.system()</code>. Here is my code:</p>
<p><code>os.system("open /Applications/Adobe\ Captivate\ 9/Adobe\ Captivate.app/ \"flashcards_template_changed.xml\"")</code></p>
<p>It works fine the issue is with the opening screen on Adobe Captivate. When the program is run one of those 'New Document' windows pops up and asks you whether you want to start a new document, what kind of document, etc. Similar to Microsoft Word.</p>
<p>I was wondering if anyone had any experience bypassing this menu so the file would open. When I open Adobe Captivate and open my XML file it opens perfectly so I know it is in the right format.</p>
<p>Any help would be great! Thanks! </p>
| 2 | 2016-08-31T21:05:23Z | 39,259,124 | <p>If Adobe Captivate is registered as the default application for handling XML files, then you can leave out the application name altogether:</p>
<pre><code>os.system("open flashcards_template_changed.xml")
</code></pre>
<p>Otherwise, specify the application with the <code>-a</code> flag:</p>
<pre><code>os.system("open -a captivate flashcards_template_changed.xml")
</code></pre>
<p>I don't know for certain that "captivate" is a recognized name for Adobe Captivate; I'm just guessing, and I don't have access to a suitable Mac to find out. If that doesn't work, you could probably use something very similar to what you had in your post:</p>
<pre><code>os.system("open -a '/Applications/Adobe Captivate 9/Adobe Captivate.app' flashcards_template_changed.xml")
</code></pre>
| 0 | 2016-08-31T21:15:08Z | [
"python",
"xml",
"operating-system",
"adobe"
] |
fmin_ncg not returning an optimized result | 39,259,026 | <p>I am trying to use fmin_ncg for minimizing my cost function. But, the results that I get back are not minimized. I get the same result I would get without advanced optimization. I know for a fact that it can further be minimized. </p>
<p>PS. I am trying to code assignment 2 of the <a href="https://www.coursera.org/learn/machine-learning" rel="nofollow">Coursera's ML course</a>. </p>
<p>My cost fn:</p>
<pre><code>def costFn(theta, X, y, m, lam):
h = sigmoid(X.dot(theta))
theta0 = theta
J = 1 / m * np.sum((-(y * np.log(h))) - ((1-y) * np.log(1-h))) + (lam/(2*m) * theta0.T.dot(theta0))
return J.flatten()
</code></pre>
<p>X would look something like this:</p>
<pre><code>[[ 1.00000000e+00 5.12670000e-02 6.99560000e-01 ..., 6.29470940e-04
8.58939846e-03 1.17205992e-01]
[ 1.00000000e+00 -9.27420000e-02 6.84940000e-01 ..., 1.89305413e-03
-1.39810280e-02 1.03255971e-01]
[ 1.00000000e+00 -2.13710000e-01 6.92250000e-01 ..., 1.04882142e-02
-3.39734512e-02 1.10046893e-01]
...,
[ 1.00000000e+00 -4.84450000e-01 9.99270000e-01 ..., 2.34007252e-01
-4.82684337e-01 9.95627986e-01]
....
</code></pre>
<p>Y is a bunch of 0s and 1s</p>
<pre><code>[[1]
[1]
[1]
[1]
...
[0]
[0]]
X.shape = (118, 28)
y.shape = (118, 1)
</code></pre>
<p>My grad function:</p>
<pre><code>def grad(theta, X, y, m, lam):
h = sigmoid(X.dot(theta))
theta0 = initial_theta
gg = 1.0 / m * ((X.T.dot(h-y)) + (lam * theta0))
return gg.flatten()
</code></pre>
<p>Using just my costFn and grad, I get the following:</p>
<pre><code>Cost at initial theta (zeros): 0.69314718056
</code></pre>
<p>With fmin_ncg:</p>
<pre><code>xopt = fmin_ncg(costFn, fprime=grad, x0=initial_theta, args=(X, y, m, lam), maxiter=400, disp=True, full_output=True )
</code></pre>
<p>I get:</p>
<pre><code>Optimization terminated successfully.
Current function value: 0.693147
Iterations: 1
Function evaluations: 2
Gradient evaluations: 4
Hessian evaluations: 0
</code></pre>
<p>Using octave, my J after advanced optimization should be:</p>
<pre><code> 0.52900
</code></pre>
<p>What am I doing wrong?</p>
<hr>
<p>EDIT:
I got my optimization to work:</p>
<pre><code>y1 = y.flatten()
Result = op.minimize(fun = costFn,
x0 = initial_theta,
args = (X, y1, m, lam),
method = 'CG',
options={'disp': True})
</code></pre>
<p>I get the costFn to be 0.52900, which is what I expected.</p>
<p>But the values of 'theta' are a bit off that the accuracy is only 42%. It's supposed to be 83%.</p>
<p>The values of theta I got:</p>
<pre><code>[ 1.14227089 0.60130664 1.16707559 -1.87187892 -0.91534354 -1.26956697
0.12663015 -0.36875537 -0.34522652 -0.17363325 -1.42401493 -0.04872243
-0.60650726 -0.269242 -1.1631064 -0.24319088 -0.20711764 -0.04333854
-0.28026111 -0.28693582 -0.46918892 -1.03640373 0.02909611 -0.29266766
0.01725324 -0.32899144 -0.13795701 -0.93215664]
</code></pre>
<p>The actual values:</p>
<pre><code>[1.273005 0.624876 1.177376 -2.020142 -0.912616 -1.429907 0.125668 -0.368551
-0.360033 -0.171068 -1.460894 -0.052499 -0.618889 -0.273745 -1.192301
-0.240993 -0.207934 -0.047224 -0.278327 -0.296602 -0.453957 -1.045511
0.026463 -0.294330 0.014381 -0.328703 -0.143796 -0.924883]
</code></pre>
| 0 | 2016-08-31T21:07:48Z | 39,260,249 | <p>First of all your gradient is invalid</p>
<pre><code>def grad(theta, X, y, m, lam):
h = sigmoid(X.dot(initial_theta))
theta0 = initial_theta
gg = 1 / m * ((X.T.dot(h-y)) + (lam * theta0))
return gg.flatten()
</code></pre>
<p>this function <strong>never uses theta</strong>, you put <code>initial_theta</code> instead, which is incorrect.</p>
<p>Similar error in the cost</p>
<pre><code>def costFn(theta, X, y, m, lam):
h = sigmoid(X.dot(initial_theta))
theta0 = theta
J = 1 / m * np.sum((-(y * np.log(h))) - ((1-y) * np.log(1-h))) + (lam/(2*m) * theta0.T.dot(theta0))
return J.flatten()
</code></pre>
<p>you have some odd mix of <code>theta</code> and <code>initial_theta</code>, which also does not make sense, there should be only <code>theta</code> inside. As a side note - there should be no need for flattening, your cost function should be <strong>a scalar</strong>, thus if you have to flatten - something is wrong in your computations.</p>
<p>Also worth checking - what is your <code>m</code>? If it is an integer, and you are using python 2.X, then <code>1 / m</code> equals <strong>zero</strong>, since it is <strong>integer division</strong>. You should do <code>1.0 / m</code> instead. (in both functions)</p>
| 1 | 2016-08-31T22:53:20Z | [
"python",
"machine-learning",
"octave",
"jupyter",
"logistic-regression"
] |
Django model with a list | 39,259,046 | <p>How to implement a list in a Django model?</p>
<p>Lets say I have a <code>UserProfile</code> model, and each user can have a list of mortgages (undefined quantity) defined by <code>MortgageModel</code>.</p>
<pre><code>class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# list of morgtages?
</code></pre>
<p>my only idea is to make a old school list, where every mortgage can point to another one or null, like this:</p>
<pre><code>class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
next_mortgage = MortgageModel(null=True, default=null)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mortgages = MortgageModel(null=True, default=null)
</code></pre>
<p>is there any other possibility?</p>
| 0 | 2016-08-31T21:09:21Z | 39,259,118 | <p>You'll have to assign a <code>ForeignKey</code> to <code>User</code> , so that each <code>Mortgate</code> 'belongs' to a user.
That is how a <strong><em>One-To-Many relationship</em></strong> is done. Then, if you want to get the list of Mortgages a user have, you'd filter them out like <code>MortgageModel.objects.filter(related_user=user)</code></p>
<p>So, you'd have something like</p>
<h3>Model</h3>
<pre><code> class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
related_user = models.ForeignKey(UserProfile)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
</code></pre>
<h3>View</h3>
<pre><code>list_of_mortages = MortgageModel.objects.filter(related_user=user)
</code></pre>
| 3 | 2016-08-31T21:14:55Z | [
"python",
"django"
] |
Group by column and get mean of the the group pandas | 39,259,089 | <p>I have a dataframe like below </p>
<pre><code>Mode Time
Air 2
Sea 4
Air 5
Sea 6
</code></pre>
<p>So I want to have the output as </p>
<pre><code>Mode Time
Air 3.5
Sea 5
</code></pre>
<p>The output should contain two columns Mode and the Time.</p>
<p>With my Code I dont see the columns coming. Below is my code:</p>
<pre><code>mean_remaining_shipment_time_mode=training_data.groupby('mode')['Time'].mean()
</code></pre>
<p>The output of this is:</p>
<pre><code>Series: mode
Air 3.813711
Ocean 14.670060
Parcel 3.036790
Truck 3.097268
Name: remainingShiptime, dtype: float64
</code></pre>
| 0 | 2016-08-31T21:12:50Z | 39,259,324 | <p>Don't select the column:</p>
<pre><code>>>> df1.groupby('Mode').mean()
Time
Mode
Air 3.5
Sea 5.0
>>>
</code></pre>
<h2>Edit in response to comment</h2>
<pre><code>>>> df1.groupby('Mode').mean().reset_index()
Mode Time
0 Air 3.5
1 Sea 5.0
>>>
</code></pre>
| 2 | 2016-08-31T21:31:31Z | [
"python",
"pandas",
"dataframe"
] |
Python: moving file to a newly created directory | 39,259,136 | <p>I've got my script creating a bunch of files (size varies depending on inputs) and I want to be certain files in certain folders based on the filenames.</p>
<p>So far I've got the following but although directories are being created no files are being moved, I'm not sure if the logic in the final for loop makes any sense.</p>
<p>In the below code I'm trying to move all .png files ending in _01 into the sub_frame_0 folder.</p>
<p>Additionally is their someway to increment both the file endings _01 to _02 etc., and the destn folder ie. from sub_frame_0 to sub_frame_1 to sub_frame_2 and so on.</p>
<pre><code>for index, i in enumerate(range(num_sub_frames+10)):
path = os.makedirs('./sub_frame_{}'.format(index))
# Slice layers into sub-frames and add to appropriate directory
list_of_files = glob.glob('*.tif')
for fname in list_of_files:
image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames
list_of_sub_frames = glob.glob('*.png')
for i in list_of_sub_frames:
if i == '*_01.png':
shutil.move(os.path.join(os.getcwd(), '*_01.png'), './sub_frame_0/')
</code></pre>
| 1 | 2016-08-31T21:16:09Z | 39,259,245 | <p>A simple fix would be to check if '*_01.png' is in the file name <code>i</code> and change the <code>shutil.move</code> to include <code>i</code>, the filename. (It's also worth mentioning that <code>i</code>is not a good name for a filepath</p>
<pre><code>list_of_sub_frames = glob.glob('*.png')
for i in list_of_sub_frames:
if '*_01.png' in i:
shutil.move(os.path.join(os.getcwd(), i), './sub_frame_0/')
</code></pre>
<blockquote>
<p>Additionally is [there some way] to increment both the file endings _01 to _02 etc., and the destn folder ie. from sub_frame_0 to sub_frame_1 to sub_frame_2 and so on.</p>
</blockquote>
<p>You could create file names doing something as simple as this:</p>
<pre><code>for i in range(10):
#simple string parsing
file_name = 'sub_frame_'+str(i)
folder_name = 'folder_sub_frame_'+str(i)
</code></pre>
| 1 | 2016-08-31T21:25:35Z | [
"python",
"filesystems",
"shutil"
] |
Python: moving file to a newly created directory | 39,259,136 | <p>I've got my script creating a bunch of files (size varies depending on inputs) and I want to be certain files in certain folders based on the filenames.</p>
<p>So far I've got the following but although directories are being created no files are being moved, I'm not sure if the logic in the final for loop makes any sense.</p>
<p>In the below code I'm trying to move all .png files ending in _01 into the sub_frame_0 folder.</p>
<p>Additionally is their someway to increment both the file endings _01 to _02 etc., and the destn folder ie. from sub_frame_0 to sub_frame_1 to sub_frame_2 and so on.</p>
<pre><code>for index, i in enumerate(range(num_sub_frames+10)):
path = os.makedirs('./sub_frame_{}'.format(index))
# Slice layers into sub-frames and add to appropriate directory
list_of_files = glob.glob('*.tif')
for fname in list_of_files:
image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames
list_of_sub_frames = glob.glob('*.png')
for i in list_of_sub_frames:
if i == '*_01.png':
shutil.move(os.path.join(os.getcwd(), '*_01.png'), './sub_frame_0/')
</code></pre>
| 1 | 2016-08-31T21:16:09Z | 39,259,472 | <p>As you said, the logic of the final loop does not make sense.</p>
<pre><code>if i == '*_01.ng'
</code></pre>
<p>It would evaluate something like <code>'image_01.png' == '*_01.png'</code> and be always false.</p>
<p>Regexp should be the way to go, but for this simple case you just can slice the number from the file name.</p>
<pre><code>for i in list_of_sub_frames:
frame = int(i[-6:-4]) - 1
shutil.move(os.path.join(os.getcwd(), i), './sub_frame_{}/'.format(frame))
</code></pre>
<p>If <code>i = 'image_01.png'</code> then <code>i[-6:-4]</code> would take '01', convert it to integer and then just subtract 1 to follow your schema.</p>
| 2 | 2016-08-31T21:42:46Z | [
"python",
"filesystems",
"shutil"
] |
Python: moving file to a newly created directory | 39,259,136 | <p>I've got my script creating a bunch of files (size varies depending on inputs) and I want to be certain files in certain folders based on the filenames.</p>
<p>So far I've got the following but although directories are being created no files are being moved, I'm not sure if the logic in the final for loop makes any sense.</p>
<p>In the below code I'm trying to move all .png files ending in _01 into the sub_frame_0 folder.</p>
<p>Additionally is their someway to increment both the file endings _01 to _02 etc., and the destn folder ie. from sub_frame_0 to sub_frame_1 to sub_frame_2 and so on.</p>
<pre><code>for index, i in enumerate(range(num_sub_frames+10)):
path = os.makedirs('./sub_frame_{}'.format(index))
# Slice layers into sub-frames and add to appropriate directory
list_of_files = glob.glob('*.tif')
for fname in list_of_files:
image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames
list_of_sub_frames = glob.glob('*.png')
for i in list_of_sub_frames:
if i == '*_01.png':
shutil.move(os.path.join(os.getcwd(), '*_01.png'), './sub_frame_0/')
</code></pre>
| 1 | 2016-08-31T21:16:09Z | 39,259,512 | <p>Here is a complete example using regular expressions. This also implements the incrementing of file names/destination folders</p>
<pre><code>import os
import glob
import shutil
import re
num_sub_frames = 3
# No need to enumerate range list without start or step
for index in range(num_sub_frames+10):
path = os.makedirs('./sub_frame_{0:02}'.format(index))
# Slice layers into sub-frames and add to appropriate directory
list_of_files = glob.glob('*.tif')
for fname in list_of_files:
image_slicer.slice(fname, num_sub_frames) # Slices the .tif frames into .png sub-frames
list_of_sub_frames = glob.glob('*.png')
for name in list_of_sub_frames:
m = re.search('(?P<fname>.+?)_(?P<num>\d+).png', name)
if m:
num = int(m.group('num'))+1
newname = '{0}_{1:02}.png'.format(m.group('fname'), num)
newpath = os.path.join('./sub_frame_{0:02}/'.format(num), newname)
print m.group() + ' -> ' + newpath
shutil.move(os.path.join(os.getcwd(), m.group()), newpath)
</code></pre>
| 1 | 2016-08-31T21:46:38Z | [
"python",
"filesystems",
"shutil"
] |
How to draw a circular heatmap within a rectangle in Python | 39,259,225 | <p>Say I have an image and I have a bounding box on a part of the image. How can I draw a circular heatmap within this rectangle?</p>
| 0 | 2016-08-31T21:23:51Z | 39,259,969 | <p>You need to create a new <code>Axes</code> in the desired position, and use a polar <code>pcolor</code> plot to construct a "heatmap":</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig,ax1 = plt.subplots()
# plot dummy image
ax1.imshow(np.random.rand(200,200),cmap='viridis')
# create new Axes, position is in figure relative coordinates!
relpos = [0.6, 0.6, 0.2, 0.2]
ax2 = fig.add_axes(relpos, polar=True)
ax2.axis('off')
phi = np.linspace(0,2*np.pi,50)
r = np.linspace(0,1,50)
gradient = np.tile(np.linspace(0,1,r.size)[:,None],phi.size)
ax2.pcolor(gradient,cmap='hot_r')
</code></pre>
<p>The result:</p>
<p><a href="http://i.stack.imgur.com/EIv0E.png" rel="nofollow"><img src="http://i.stack.imgur.com/EIv0E.png" alt="result"></a></p>
<p>The color gradient samples linearly from the colormap, in the above example named <code>hot_r</code>. You can play around with both the colormap and with the transition of the <code>gradient</code> variable, the result will always be radially dependent.</p>
<p>The only thing you need to take care of is to transform your rectangle (given in units which only you can tell) to relative figure units (where (0,0) is the bottom left corner of the figure, and (1,1) is the top left). The axis positioning works in the way which is usual for box-shaped objects: <code>[left,bottom,width,height]</code>.</p>
| 1 | 2016-08-31T22:27:39Z | [
"python",
"matplotlib",
"heatmap"
] |
Is there an option to edit the padding inside of a Tkinter EntryBox? | 39,259,264 | <p>Is there an option to edit the padding inside of a Tkinter EntryBox? So that the text that the user inputs starts e.g. 10px from the left border.</p>
| 3 | 2016-08-31T21:26:40Z | 39,509,532 | <p>Technically, yes if you are using <code>.grid()</code>. </p>
<p>Using:</p>
<pre><code>grid(ipadx=HORIZONTAL-PADDING, ipady=VERTICAL-PADDING)
</code></pre>
<p>Is what the documentation says, however it doesn't seem to dictate how the text bbehaves. I can only get it to work for <code>ipady</code>. <code>ipadx</code> seems to just add extra padding to extend the width of the Entry widget without the text moving right.</p>
<pre><code>import tkinter as tk
root = tk.Tk()
entry = Entry(root)
entry.grid(row=0,column=0,ipadx=10)
root.mainloop()
</code></pre>
<p>Reference:
<a href="http://effbot.org/tkinterbook/grid.htm" rel="nofollow">http://effbot.org/tkinterbook/grid.htm</a></p>
| 0 | 2016-09-15T11:06:21Z | [
"python",
"tkinter"
] |
Unicode python Error | 39,259,290 | <p>i'm trying to print : Pokémon GO Viá»t Nam</p>
<pre><code>print u"Pokémon GO Viá»t Nam"
</code></pre>
<p>and i'm getting :</p>
<pre><code>print u"PokÃmon GO Vi?t Nam"
SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xe9 in position 0: unexpected end of data
</code></pre>
<p>i've tried : </p>
<pre><code>.encode("utf-8")
.decode("utf-8")
.decode('latin-1').encode("utf-8")
unicode(str.decode("iso-8859-4"))
</code></pre>
<p>My python version is 2.7.9 , Notepad++ UTF-8 encoding .
with no luck , how can i print it ? and i'm encountering this kind of issues all the time , what's the proper way to debug and get the right encoding ? </p>
| 1 | 2016-08-31T21:28:17Z | 39,259,334 | <pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
print "Pokémon GO Viá»t Nam"
</code></pre>
<p>You can find <a href="https://www.python.org/dev/peps/pep-0263/" rel="nofollow">here</a> more info</p>
<p>For PyCharm settings, go to the menu: PyCharm --> Preference then use the search to look up "encoding", you should reach the following screen:</p>
<p><a href="http://i.stack.imgur.com/ftj8L.png" rel="nofollow"><img src="http://i.stack.imgur.com/ftj8L.png" alt="enter image description here"></a></p>
| 4 | 2016-08-31T21:32:09Z | [
"python",
"unicode"
] |
Unicode python Error | 39,259,290 | <p>i'm trying to print : Pokémon GO Viá»t Nam</p>
<pre><code>print u"Pokémon GO Viá»t Nam"
</code></pre>
<p>and i'm getting :</p>
<pre><code>print u"PokÃmon GO Vi?t Nam"
SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xe9 in position 0: unexpected end of data
</code></pre>
<p>i've tried : </p>
<pre><code>.encode("utf-8")
.decode("utf-8")
.decode('latin-1').encode("utf-8")
unicode(str.decode("iso-8859-4"))
</code></pre>
<p>My python version is 2.7.9 , Notepad++ UTF-8 encoding .
with no luck , how can i print it ? and i'm encountering this kind of issues all the time , what's the proper way to debug and get the right encoding ? </p>
| 1 | 2016-08-31T21:28:17Z | 39,259,349 | <p>Specify the encoding</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
</code></pre>
<p>in the top of the program</p>
| 1 | 2016-08-31T21:33:07Z | [
"python",
"unicode"
] |
Unicode python Error | 39,259,290 | <p>i'm trying to print : Pokémon GO Viá»t Nam</p>
<pre><code>print u"Pokémon GO Viá»t Nam"
</code></pre>
<p>and i'm getting :</p>
<pre><code>print u"PokÃmon GO Vi?t Nam"
SyntaxError: (unicode error) 'utf8' codec can't decode byte 0xe9 in position 0: unexpected end of data
</code></pre>
<p>i've tried : </p>
<pre><code>.encode("utf-8")
.decode("utf-8")
.decode('latin-1').encode("utf-8")
unicode(str.decode("iso-8859-4"))
</code></pre>
<p>My python version is 2.7.9 , Notepad++ UTF-8 encoding .
with no luck , how can i print it ? and i'm encountering this kind of issues all the time , what's the proper way to debug and get the right encoding ? </p>
| 1 | 2016-08-31T21:28:17Z | 39,261,872 | <p>As an alternative you can encode the unicode string:</p>
<pre><code>print u"Pokémon GO Viá»t Nam".encode('utf-8')
</code></pre>
<p>The advantage is that the bytes in the resulting string are independent of the encoding of the source file: <code>u"á»".encode('utf-8')</code> is always the same 3 bytes <code>"\xe1\xbb\x87"</code>.</p>
<p>It is also consistent with what you'd do if you have an unicode string in a variable.</p>
<pre><code># get text from somewhere...
text = u"Pokémon GO Viá»t Nam"
# assuming your terminal expects UTF-8 -- this won't work on Windows.
print text.encode('utf-8')
</code></pre>
| 0 | 2016-09-01T02:37:58Z | [
"python",
"unicode"
] |
Python search for single filename recursively in directory tree. Return false if not found | 39,259,318 | <p>Using Python, I would like to search a directory tree recursively for a specific file name.</p>
<p>**If found, print nothing.</p>
<p>**If not found print a message stating it was not found.</p>
<p>===== here is what I have so far, no errors, but no message when file not found either=====</p>
<pre><code>import os
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
def find_file(file_name,rootDir):
for dirpath, dirnames, filenames in os.walk(rootDir):
if file_name in filenames:
print 'found'
</code></pre>
| 0 | 2016-08-31T21:31:01Z | 39,259,384 | <p>Return early when you find the file; that way, after your <code>os.walk()</code> loop has completed you know the file was never found:</p>
<pre><code>import os
def find_file(name, root):
for _, _, filenames in os.walk(root):
if name in filenames:
return # found the file, exit early
print 'Not found'
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
find_file(file_name, rootDir)
</code></pre>
<p>I used <code>_</code> for both the dirpath and directories values returned by <code>os.walk()</code> for each iteration; the loop otherwise ignores these and <code>_</code> signals this to the reader.</p>
| 1 | 2016-08-31T21:35:27Z | [
"python",
"recursion",
"filenames",
"os.walk"
] |
Python search for single filename recursively in directory tree. Return false if not found | 39,259,318 | <p>Using Python, I would like to search a directory tree recursively for a specific file name.</p>
<p>**If found, print nothing.</p>
<p>**If not found print a message stating it was not found.</p>
<p>===== here is what I have so far, no errors, but no message when file not found either=====</p>
<pre><code>import os
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
def find_file(file_name,rootDir):
for dirpath, dirnames, filenames in os.walk(rootDir):
if file_name in filenames:
print 'found'
</code></pre>
| 0 | 2016-08-31T21:31:01Z | 39,259,432 | <pre><code>if not any(file_name in filenames
for dirpath, dirnames, filenames in os.walk(rootDir)):
print file_name, 'not found'
</code></pre>
| 0 | 2016-08-31T21:39:22Z | [
"python",
"recursion",
"filenames",
"os.walk"
] |
Python search for single filename recursively in directory tree. Return false if not found | 39,259,318 | <p>Using Python, I would like to search a directory tree recursively for a specific file name.</p>
<p>**If found, print nothing.</p>
<p>**If not found print a message stating it was not found.</p>
<p>===== here is what I have so far, no errors, but no message when file not found either=====</p>
<pre><code>import os
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
def find_file(file_name,rootDir):
for dirpath, dirnames, filenames in os.walk(rootDir):
if file_name in filenames:
print 'found'
</code></pre>
| 0 | 2016-08-31T21:31:01Z | 39,259,505 | <p>If you are using Python3.5+ you can use <code>**</code> with the <code>recursive</code> flag:</p>
<pre><code>import glob
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
found_files = glob.glob("{}**\\{}".format(rootDir, file_name), recursive=True)
if not found_files:
# do whatever you need
pass
else:
print('found')
</code></pre>
| 0 | 2016-08-31T21:46:07Z | [
"python",
"recursion",
"filenames",
"os.walk"
] |
PyQt5: Progamically adding QWidget to layout, doesn't show Qwidget when a spacer is added | 39,259,367 | <p><strong>Edit</strong>: I have tried a few more things. If I move the spacer to a layout below the spacer I am adding to it doesn't exibit the same exact behavior. Its still not optimal, and isn't going to work because my end goal is to have a scrollArea with a spacer inside that i add my widgets to, but this would not look right. I think the problem is the widgets are getting to a size zero I just do not know why or how to fix it.</p>
<p>I have two ui files made in QtDesigner. The first file is my main window at the start of the program I load the second ui file and place it into a vertical spacer in the middle of the first one. Additional copies are placed each time a button is clicked.</p>
<p>This all works great until I add a vertical spacer to push the items to the top. I have tired adding it from Designer and in the code. Both have the same result.</p>
<p>I have looked on google quite a bit and tried a lot of suggestions.</p>
<p>I tried setting the second ui files parent as a Qwidget I added on the first that contained the vertical layout.</p>
<p>I tried setting the minimum sizes and sizing polices to various things.</p>
<p>Below is my current code, any ideas or suggestions would be appreciated!</p>
<pre><code>#!python3
import sys
from PyQt5 import QtWidgets, QtCore, uic
class TimesheetWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TimesheetWidget, self).__init__(parent)
self.parent = parent
self.tableRows = dict()
def setup(self):
self.labelSaved.hide()
self.addTableRow()
def addTableRow(self):
thisRow = len(self.tableRows)
self.tableRows[thisRow] = uic.loadUi("gui/tableRow.ui")
self.tableRows[thisRow].addButton.clicked.connect(self.addTableRow)
self.spacer.addWidget(self.tableRows[thisRow])
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
timesheet = TimesheetWidget()
Mytimesheet = uic.loadUi("gui/timesheet.ui", baseinstance=timesheet)
Mytimesheet.setup()
Mytimesheet.show()
sys.exit(app.exec_())
</code></pre>
<p>here is a link to the ui files (they are to long to post):
<a href="https://gist.github.com/dossjh/95d14b15c63cee6bb0b5d2db631b755d" rel="nofollow">gist link for ui files</a></p>
| 0 | 2016-08-31T21:34:26Z | 39,283,290 | <p>I finally fixed this by trying random things over and over until something worked.</p>
<p>It turned out that on my second ui file I did not have a top level layout. (I am not sure if that's what its called.)</p>
<p>To fix this I right clicked on the top level widget and choose layout and selected horizontal layout, although I think any would have worked.</p>
<p>Here is a picture that shows the top level widget with the cancel symbol on it. Once I added the layout that went away and everything worked!</p>
<p><a href="http://i.stack.imgur.com/0UOYk.png" rel="nofollow"><img src="http://i.stack.imgur.com/0UOYk.png" alt="enter image description here"></a></p>
| 0 | 2016-09-02T02:04:10Z | [
"python",
"pyqt5"
] |
np.array returning numpy.ndarray with "..." | 39,259,371 | <p>I created a script to generate a list:</p>
<pre><code>import random
nota1 = range (5, 11)
nota2 = range (5, 11)
nota3 = range (5, 11)
nota4 = range (0, 2)
dados = []
for i in range(1000):
dados_dado = []
n1 = random.choice(nota1)
n2 = random.choice(nota2)
n3 = random.choice(nota3)
n4 = random.choice(nota4)
n1 = float (n1)
n2 = float (n2)
n3 = float (n3)
n4 = float (n4)
dados_dado.append (n1)
dados_dado.append (n2)
dados_dado.append (n3)
dados_dado.append (n4)
dados.append (dados_dado)
</code></pre>
<p>When i print <code>type (dados)</code> python return: <code><type 'list'></code>, a huge list that looks like this:</p>
<pre><code>[[5.0, 8.0, 10.0, 1.0], [8.0, 9.0, 9.0, 1.0], [7.0, 5.0, 6.0, 1.0], [5.0, 8.0, 7.0, 0.0], [9.0, 7.0, 10.0, 0.0], [6.0, 7.0, 9.0, 1.0], [6.0, 9.0, 8.0, 1.0]]
</code></pre>
<p>I need to transform it to <code><type 'numpy.ndarray'></code> so i made :</p>
<pre><code>data = np.array(dados)
</code></pre>
<p>What i expected to return was something like this:</p>
<pre><code> [[ 6.8 3.2 5.9 2.3]
[ 6.7 3.3 5.7 2.5]
[ 6.7 3. 5.2 2.3]
[ 6.3 2.5 5. 1.9]
[ 6.5 3. 5.2 2. ]
[ 6.2 3.4 5.4 2.3]
[ 5.9 3. 5.1 1.8]]
</code></pre>
<p>But, what i get instead is:</p>
<pre><code> [[ 7. 10. 6. 1.]
[ 8. 6. 6. 1.]
[ 6. 9. 5. 0.]
...,
[ 9. 7. 10. 0.]
[ 6. 7. 9. 1.]
[ 6. 9. 8. 1.]]
</code></pre>
<p>What am i doing wrong?</p>
| 0 | 2016-08-31T21:34:38Z | 39,259,407 | <p>Your array is fine. NumPy just suppresses display of the whole array for large arrays by default.</p>
<p>(If you actually <em>were</em> expecting your array to be short enough not to trigger this behavior, or if you were actually expecting it to have non-integer entries, you'll have to explain why you expected that.)</p>
| 0 | 2016-08-31T21:37:16Z | [
"python",
"arrays",
"numpy"
] |
np.array returning numpy.ndarray with "..." | 39,259,371 | <p>I created a script to generate a list:</p>
<pre><code>import random
nota1 = range (5, 11)
nota2 = range (5, 11)
nota3 = range (5, 11)
nota4 = range (0, 2)
dados = []
for i in range(1000):
dados_dado = []
n1 = random.choice(nota1)
n2 = random.choice(nota2)
n3 = random.choice(nota3)
n4 = random.choice(nota4)
n1 = float (n1)
n2 = float (n2)
n3 = float (n3)
n4 = float (n4)
dados_dado.append (n1)
dados_dado.append (n2)
dados_dado.append (n3)
dados_dado.append (n4)
dados.append (dados_dado)
</code></pre>
<p>When i print <code>type (dados)</code> python return: <code><type 'list'></code>, a huge list that looks like this:</p>
<pre><code>[[5.0, 8.0, 10.0, 1.0], [8.0, 9.0, 9.0, 1.0], [7.0, 5.0, 6.0, 1.0], [5.0, 8.0, 7.0, 0.0], [9.0, 7.0, 10.0, 0.0], [6.0, 7.0, 9.0, 1.0], [6.0, 9.0, 8.0, 1.0]]
</code></pre>
<p>I need to transform it to <code><type 'numpy.ndarray'></code> so i made :</p>
<pre><code>data = np.array(dados)
</code></pre>
<p>What i expected to return was something like this:</p>
<pre><code> [[ 6.8 3.2 5.9 2.3]
[ 6.7 3.3 5.7 2.5]
[ 6.7 3. 5.2 2.3]
[ 6.3 2.5 5. 1.9]
[ 6.5 3. 5.2 2. ]
[ 6.2 3.4 5.4 2.3]
[ 5.9 3. 5.1 1.8]]
</code></pre>
<p>But, what i get instead is:</p>
<pre><code> [[ 7. 10. 6. 1.]
[ 8. 6. 6. 1.]
[ 6. 9. 5. 0.]
...,
[ 9. 7. 10. 0.]
[ 6. 7. 9. 1.]
[ 6. 9. 8. 1.]]
</code></pre>
<p>What am i doing wrong?</p>
| 0 | 2016-08-31T21:34:38Z | 39,259,428 | <pre><code>numpy.set_printoptions(precision=20)
</code></pre>
<p>Will give you more displayabilty, set precision as you desire.</p>
| 0 | 2016-08-31T21:38:57Z | [
"python",
"arrays",
"numpy"
] |
np.array returning numpy.ndarray with "..." | 39,259,371 | <p>I created a script to generate a list:</p>
<pre><code>import random
nota1 = range (5, 11)
nota2 = range (5, 11)
nota3 = range (5, 11)
nota4 = range (0, 2)
dados = []
for i in range(1000):
dados_dado = []
n1 = random.choice(nota1)
n2 = random.choice(nota2)
n3 = random.choice(nota3)
n4 = random.choice(nota4)
n1 = float (n1)
n2 = float (n2)
n3 = float (n3)
n4 = float (n4)
dados_dado.append (n1)
dados_dado.append (n2)
dados_dado.append (n3)
dados_dado.append (n4)
dados.append (dados_dado)
</code></pre>
<p>When i print <code>type (dados)</code> python return: <code><type 'list'></code>, a huge list that looks like this:</p>
<pre><code>[[5.0, 8.0, 10.0, 1.0], [8.0, 9.0, 9.0, 1.0], [7.0, 5.0, 6.0, 1.0], [5.0, 8.0, 7.0, 0.0], [9.0, 7.0, 10.0, 0.0], [6.0, 7.0, 9.0, 1.0], [6.0, 9.0, 8.0, 1.0]]
</code></pre>
<p>I need to transform it to <code><type 'numpy.ndarray'></code> so i made :</p>
<pre><code>data = np.array(dados)
</code></pre>
<p>What i expected to return was something like this:</p>
<pre><code> [[ 6.8 3.2 5.9 2.3]
[ 6.7 3.3 5.7 2.5]
[ 6.7 3. 5.2 2.3]
[ 6.3 2.5 5. 1.9]
[ 6.5 3. 5.2 2. ]
[ 6.2 3.4 5.4 2.3]
[ 5.9 3. 5.1 1.8]]
</code></pre>
<p>But, what i get instead is:</p>
<pre><code> [[ 7. 10. 6. 1.]
[ 8. 6. 6. 1.]
[ 6. 9. 5. 0.]
...,
[ 9. 7. 10. 0.]
[ 6. 7. 9. 1.]
[ 6. 9. 8. 1.]]
</code></pre>
<p>What am i doing wrong?</p>
| 0 | 2016-08-31T21:34:38Z | 39,259,861 | <p>With your sample:</p>
<pre><code>In [574]: dados=[[5.0, 8.0, 10.0, 1.0], [8.0, 9.0, 9.0, 1.0], [7.0, 5.0, 6.0, 1.
...: 0], [5.0, 8.0, 7.0, 0.0], [9.0, 7.0, 10.0, 0.0], [6.0, 7.0, 9.0, 1.0],
...: [6.0, 9.0, 8.0, 1.0]]
In [575]: print(dados)
[[5.0, 8.0, 10.0, 1.0], [8.0, 9.0, 9.0, 1.0], [7.0, 5.0, 6.0, 1.0], [5.0, 8.0, 7.0, 0.0], [9.0, 7.0, 10.0, 0.0], [6.0, 7.0, 9.0, 1.0], [6.0, 9.0, 8.0, 1.0]]
</code></pre>
<p>convert it to an array, an see the whole thing. Your input didn't have decimals to numpy display omits those.</p>
<pre><code>In [576]: print(np.array(dados))
[[ 5. 8. 10. 1.]
[ 8. 9. 9. 1.]
[ 7. 5. 6. 1.]
[ 5. 8. 7. 0.]
[ 9. 7. 10. 0.]
[ 6. 7. 9. 1.]
[ 6. 9. 8. 1.]]
</code></pre>
<p>Replicate the list many times, and print display has this <code>...</code>, rather than show 10,000 lines. That's nice isn't it?</p>
<pre><code>In [577]: print(np.array(dados*1000))
[[ 5. 8. 10. 1.]
[ 8. 9. 9. 1.]
[ 7. 5. 6. 1.]
...,
[ 9. 7. 10. 0.]
[ 6. 7. 9. 1.]
[ 6. 9. 8. 1.]]
</code></pre>
<p>The full array is still there</p>
<pre><code>In [578]: np.array(dados*1000).shape
Out[578]: (7000, 4)
</code></pre>
<p>The default is for numpy to add the ellipsis when the total number of entries is 1000. Do you really need to see all those lines?</p>
<p>That print standard can be changed, but I question whether you need to do that.</p>
| 1 | 2016-08-31T22:18:57Z | [
"python",
"arrays",
"numpy"
] |
How do I create a new dict of dicts from a dict with nested dicts in Python | 39,259,383 | <p>I am starting with a dict received from an api </p>
<pre><code>start_dict = {
"a": 795,
"b": 1337,
"c": [
{
"d1": 2,
"d2": [
{
"e1": 4
}
]
}
]
}
</code></pre>
<p>I need to create a separate dict from that dict. That has each of the keys and value separated by their key and value into there own dict. While keeping the nested dicts intact.</p>
<pre><code>values =
{
"fields": [
{
"element_name": "a",
"value": 795
},
{
"element_name": "b",
"value": 1337
},
{
"element_name": "c",
"value": [
{
"element_name": "d1",
"value": 2
},
{
"element_name": "d2",
"value" : [
{
"element_name": "e1",
"value": 4
}
]
]
}
]
}
</code></pre>
<p>The actual dict is quite a bit larger but there are no more then one two deep nested dicts in the original but many single nested dicts. This is the only way the api will accept new data so I am kinda stuck until I figure it out. Any help is greatly appreciated as I am quite new to Python (3 Weeks) lol so if this is something simple please don't be to harsh.</p>
| 0 | 2016-08-31T21:35:19Z | 39,259,446 | <p>You can build the output with a recursive function:</p>
<pre><code>def transform(ob):
if isinstance(ob, list):
return [transform(v) for v in ob]
elif not isinstance(ob, dict):
return ob
return [{'element_name': k, 'value': transform(v)}
for k, v in ob.items()]
values = {'fields': transform(start_dict)}
</code></pre>
<p>so each <code>key, value</code> pair is transformed to a <code>{'element_name': key, 'value': value}</code> dictionary in a list, where any value that is itself a list or dictionary is transformed by a recursive call.</p>
<p>Demo:</p>
<pre><code>>>> from pprint import pprint
>>> def transform(ob):
... if isinstance(ob, list):
... return [transform(v) for v in ob]
... elif not isinstance(ob, dict):
... return ob
... return [{'element_name': k, 'value': transform(v)}
... for k, v in ob.items()]
...
>>> start_dict = {
... "a": 795,
... "b": 1337,
... "c": [
... {
... "d1": 2,
... "d2": [
... {
... "e1": 4
... }
... ]
... }
... ]
... }
>>> pprint({'fields': transform(start_dict)})
{'fields': [{'element_name': 'a', 'value': 795},
{'element_name': 'c',
'value': [[{'element_name': 'd1', 'value': 2},
{'element_name': 'd2',
'value': [[{'element_name': 'e1', 'value': 4}]]}]]},
{'element_name': 'b', 'value': 1337}]}
</code></pre>
| 5 | 2016-08-31T21:40:52Z | [
"python",
"python-2.7",
"dictionary"
] |
What is the best way to store a list of functions? | 39,259,411 | <p>I need to store a large numbers of functions rules in Python (around 100000 ), to be used after....</p>
<pre><code>def rule1(x,y) :...
def rule2(x,y): ...
</code></pre>
<p>What is the best way to store, manage those function rules instance into Python structure ? </p>
<p>What about using Numpy dtype=np.object array ?
(list are bad when they become too large...)</p>
<p>Main goal is to access in the fastest and minimum memory footprint when storing in memory.</p>
<p>Thanks</p>
| 0 | 2016-08-31T21:37:52Z | 39,259,467 | <p>Functions are first class objects in Python - you can store them just like you'd store any other variable or value:</p>
<pre><code>def a():
pass
def b():
pass
funcs = [a,b]
funcs[0]() # calls `a()`.
</code></pre>
| 2 | 2016-08-31T21:42:05Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.