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 |
|---|---|---|---|---|---|---|---|---|---|
Matlab diff(F,var,n) vs Python numpy diff(a, n=1, axis=-1) | 39,410,096 | <p>I am trying to calculate matlab function in python.</p>
<pre><code>y = diff(x,1,2)
</code></pre>
<p>x is and grayscale image </p>
<p>i tried numpy diff function but i get different answer</p>
<p>please help</p>
| -1 | 2016-09-09T11:01:55Z | 39,411,638 | <p>in the comment to your question, it appears you swapped the arguments to the <code>diff</code> functions. However, the documentation states that both in matlab and in numpy, the order of the arguments is:</p>
<ul>
<li><p>array</p></li>
<li><p>n</p></li>
<li><p>dimension</p></li>
</ul>
| 0 | 2016-09-09T12:28:56Z | [
"python",
"matlab",
"numpy",
"scipy"
] |
Matlab diff(F,var,n) vs Python numpy diff(a, n=1, axis=-1) | 39,410,096 | <p>I am trying to calculate matlab function in python.</p>
<pre><code>y = diff(x,1,2)
</code></pre>
<p>x is and grayscale image </p>
<p>i tried numpy diff function but i get different answer</p>
<p>please help</p>
| -1 | 2016-09-09T11:01:55Z | 39,418,024 | <p>There are two problems here. </p>
<p>First, you swapped the order of arguments in <code>np.diff</code>. MATLAB and Python use the same argument order. Python supports named arguments, so it is often better to use the argument name to avoid this sort of problem.</p>
<p>Second, python indexing starts with 0, whil... | 1 | 2016-09-09T18:50:28Z | [
"python",
"matlab",
"numpy",
"scipy"
] |
JSON parsing encoding causes a unicode encode error | 39,410,173 | <p>I need to parse some simple JOSN in bash which contains non-ascii characters without external dependencies, so I used a python solution <a href="http://stackoverflow.com/a/1955555/296446">from this answer</a></p>
<pre><code>cat $JSON_FILE | python -c "import sys, json; print json.load(sys.stdin)['$KEY']"
</code></... | 1 | 2016-09-09T11:06:57Z | 39,410,214 | <p>You already have <code>unicode</code>, but <strong>encoding</strong> when printing fails.</p>
<p>That's either because you don't have a locale set, have your locale set to ASCII, or you are piping the Python result to something else (but did not include that in your question). In the latter case Python refuses to ... | 3 | 2016-09-09T11:09:43Z | [
"python",
"json",
"bash",
"python-2.x"
] |
readonly_fields returns empty value in django inlined models | 39,410,176 | <p>i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view.</p>
<p>i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to lin... | 0 | 2016-09-09T11:06:59Z | 39,411,018 | <p>I would think you need to reverse the order in the url:</p>
<pre><code>url(r'^download/(?P<pk>\d+)$', self.admin_site.admin_view(self.DLFacture), name="download"),
]
</code></pre>
| 0 | 2016-09-09T11:54:48Z | [
"python",
"django",
"django-admin",
"django-views",
"django-urls"
] |
readonly_fields returns empty value in django inlined models | 39,410,176 | <p>i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view.</p>
<p>i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to lin... | 0 | 2016-09-09T11:06:59Z | 39,411,381 | <p>Firstly, you are using <code>name='download'</code>, but trying to reverse <code>clients_facture_download</code>.</p>
<p>I would try changing the url from</p>
<pre><code>url(r'^(?P<pk>\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"),
</code></pre>
<p>to</p>
<pre><code>url(r'^(... | 0 | 2016-09-09T12:15:28Z | [
"python",
"django",
"django-admin",
"django-views",
"django-urls"
] |
How can l convert tuple to integer to do some calculations? | 39,410,205 | <p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem wi... | 1 | 2016-09-09T11:09:09Z | 39,410,303 | <p>The simplest thing would be:</p>
<pre><code>int(float(y[5][0]))
</code></pre>
<p>Instead. Since your string value has a decimal in it, you will not be able to convert directly to <code>int</code> without converting to <code>float</code> first. Keep in mind, you will lose some precision though:</p>
<pre><code>>... | 1 | 2016-09-09T11:14:03Z | [
"python",
"csv",
"numpy",
"matplotlib"
] |
How can l convert tuple to integer to do some calculations? | 39,410,205 | <p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem wi... | 1 | 2016-09-09T11:09:09Z | 39,410,312 | <p>Thats because you are trying to convert a decimal number into an int</p>
<p>If you want to use the exact value you can use <code>float(tuple(y[5][0]))</code>
Or else if you want to truncate the value you can use <code>int(float(tuple(y[5][0])))</code></p>
| 1 | 2016-09-09T11:14:34Z | [
"python",
"csv",
"numpy",
"matplotlib"
] |
How can l convert tuple to integer to do some calculations? | 39,410,205 | <p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem wi... | 1 | 2016-09-09T11:09:09Z | 39,410,381 | <p>You have got 2 different problems:</p>
<p><strong>1. s+=y[i] #### error (for +=: 'int' and 'list')</strong></p>
<p>Here are the relevant part of the code:</p>
<pre><code>y=[]
for row in reader:
content2= list(row[i] for i in included_col6)
y.append(content2)
s=0
for i in range(1,len(klm)):
s+=... | 1 | 2016-09-09T11:18:24Z | [
"python",
"csv",
"numpy",
"matplotlib"
] |
How can l convert tuple to integer to do some calculations? | 39,410,205 | <p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem wi... | 1 | 2016-09-09T11:09:09Z | 39,410,388 | <p>Since 2.345 is not an integer, you need to determine what to do with the floating part. Do you want to ceil or floor it or round it?</p>
<ul>
<li><p><code>int(round(float("2.345")))</code> gives 2</p></li>
<li><p><code>int(math.ceil(float("2.345")))</code> gives 3</p></li>
<li><p><code>int(math.floor(float("2.345")... | 1 | 2016-09-09T11:18:40Z | [
"python",
"csv",
"numpy",
"matplotlib"
] |
ValueError: invalid literal for int() with base 10: 'abc' | 39,410,215 | <p><strong>models.py</strong></p>
<pre><code>class answers(models.Model):
username = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.ForeignKey(Task)
answer = models.URLField()
ANSWER_CHOICES = (
('F', 'Declined'),
('T', 'Accepted'),
)
accept_answer = models.CharField... | 0 | 2016-09-09T11:09:43Z | 39,410,283 | <p>You need to pass in the <code>task</code> instance, not <code>task.title</code>:</p>
<pre><code>instance = get_object_or_404(answers, title=task)
</code></pre>
<p><code>task.title</code> is a Unicode string, but the <code>answers.title</code> field is a foreign key. You could also pass in the <code>Task.id</code> ... | 2 | 2016-09-09T11:12:50Z | [
"python",
"django",
"django-models",
"django-views"
] |
Horizontal layout of patches in legend (matplotlib) | 39,410,223 | <p>I create legend in my chart this way:</p>
<pre><code>legend_handles.append(matplotlib.patches.Patch(color=color1, label='group1'))
legend_handles.append(matplotlib.patches.Patch(color=color2, label='group2'))
ax.legend(loc='upper center', handles=legend_handles, fontsize='small')
</code></pre>
<p>This results in t... | 0 | 2016-09-09T11:10:25Z | 39,410,716 | <p>There is an argument determining the number of columns <code>ncol=</code>.</p>
<pre><code>ax.legend(loc='upper center', handles=legend_handles, fontsize='small', ncol=2)
</code></pre>
<p>This should do the trick. Got it from <a href="http://stackoverflow.com/questions/14737681/fill-the-right-column-of-a-matplotlib... | 1 | 2016-09-09T11:37:08Z | [
"python",
"matplotlib"
] |
QtQuickControls 2.0 with PyQt5 | 39,410,243 | <p>I setup a virtualenv and installed pyqt5 (PyQt5-5.7-cp35-cp35m-manylinux1_x86_64.whl):</p>
<pre><code>virtualenv -p /usr/bin/python3.5 .
source bin/activate
pip install pyqt5
</code></pre>
<p>I created a basic.qml file:</p>
<pre><code>import QtQuick 2.7
import QtQuick.Controls 2.0
Rectangle {
width: 300
... | 0 | 2016-09-09T11:11:14Z | 39,420,154 | <p>This looks like a bug in PyQt5. The package is missing both <code>libQt5QuickTemplates2.so</code> and <code>libQt5QuickControls2.so</code>.</p>
<p>Hoping that the Qt 5.7 build contained by the PyQt 5.7 package and the official Qt 5.7 build available at qt.io are built in a fully binary compatible way, one possibili... | 1 | 2016-09-09T21:46:13Z | [
"python",
"pyqt",
"pyqt5",
"qtquickcontrols",
"qtquickcontrols2"
] |
Coreference resolution in python nltk using Stanford coreNLP | 39,410,282 | <p>Stanford CoreNLP provides coreference resolution <a href="http://nlp.stanford.edu/software/dcoref.shtml" rel="nofollow">as mentioned here</a>, also <a href="http://stackoverflow.com/questions/30954649/coreference-resolution-using-stanford-corenlp">this thread</a>, <a href="http://stackoverflow.com/questions/30362691... | 1 | 2016-09-09T11:12:47Z | 39,514,695 | <p>Maybe this works for you? <a href="https://github.com/dasmith/stanford-corenlp-python" rel="nofollow">https://github.com/dasmith/stanford-corenlp-python</a>
If not, you can try to combine the two yourself using <a href="http://www.jython.org/" rel="nofollow">http://www.jython.org/</a></p>
| 0 | 2016-09-15T15:16:07Z | [
"python",
"nlp",
"nltk",
"stanford-nlp"
] |
Match URLs by file path and GET parameters (but not their values) | 39,410,308 | <p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p>
<pre><code>links = [
"http://example.com/page.php?param1=111&param2=222",
"http://example.com/page... | 1 | 2016-09-09T11:14:25Z | 39,410,546 | <p>I think <a href="http://www.tutorialspoint.com/python/string_split.htm" rel="nofollow">split</a> is your friend )</p>
<p>First compare <code>links[i].split('?')[0]</code> with <code>url.split('?')[0]</code></p>
<p>Then if true - split your vars with <code>'&'</code>. </p>
<p>I think there exists more optimal ... | 1 | 2016-09-09T11:27:28Z | [
"python",
"regex",
"list",
"url",
"match"
] |
Match URLs by file path and GET parameters (but not their values) | 39,410,308 | <p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p>
<pre><code>links = [
"http://example.com/page.php?param1=111&param2=222",
"http://example.com/page... | 1 | 2016-09-09T11:14:25Z | 39,410,728 | <p>You ideally want to use python's urlparse library.
Parse your url like so:</p>
<pre><code>import urlparse
url = "http://example.com/page2.php?param1=NOT111&param2=NOT222"
parsed_url = urlparse.urlparse(url)
urlparse.parse_qs(parsed_url.query).keys()
</code></pre>
<p>Then you create a datastructure which looks ... | 3 | 2016-09-09T11:37:54Z | [
"python",
"regex",
"list",
"url",
"match"
] |
Match URLs by file path and GET parameters (but not their values) | 39,410,308 | <p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p>
<pre><code>links = [
"http://example.com/page.php?param1=111&param2=222",
"http://example.com/page... | 1 | 2016-09-09T11:14:25Z | 39,410,780 | <p>I think that <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse" rel="nofollow"><code>urllib.parse.urlparse()</code></a> (if you are using Python 3) will help you, or <code>urlparse.urlparse()</code> for Python 2.</p>
<p>This function will break the URL up into its various components... | 1 | 2016-09-09T11:40:46Z | [
"python",
"regex",
"list",
"url",
"match"
] |
Match URLs by file path and GET parameters (but not their values) | 39,410,308 | <p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p>
<pre><code>links = [
"http://example.com/page.php?param1=111&param2=222",
"http://example.com/page... | 1 | 2016-09-09T11:14:25Z | 39,411,107 | <p>Python's standard library comes with a package for parsing urls: <a href="https://docs.python.org/3/library/urllib.parse.html" rel="nofollow"><code>urllib.parse</code></a>. Don't try to write your own regexes for this... <em>especially</em> if you haven't considered all the weird things that are legal parts of a UR... | 2 | 2016-09-09T11:59:33Z | [
"python",
"regex",
"list",
"url",
"match"
] |
Max of pandas dataframe columns multiplied together | 39,410,335 | <p>Given this data:</p>
<pre><code>data = {'C1_IND' : [1,1,0,0,1],
'C1_PRICE' : [55,84,0,0,103],
'P1_IND' : [1,0,0,1,1],
'P1_PRICE' : [72,0,0,33,95]}
df = pd.DataFrame(data)
</code></pre>
<p>How can I create a variable in the same dataframe that is:</p>
<pre><code>max(C1_IND*C1_PRICE,P1_IND*P... | 2 | 2016-09-09T11:16:03Z | 39,410,487 | <p>I think you can select columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a>, then multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.prod.html" rel="nofollow"><code>prod</code></a>. Last... | 3 | 2016-09-09T11:24:13Z | [
"python",
"pandas",
"dataframe",
"max",
"multiple-columns"
] |
How to create a loop that checks if "Remove" exists for multiple "Remove" [Helium] [Selenium] [Python] | 39,410,446 | <p>How to loop the below logic inside a script, till all are deleted then continue to the next text. </p>
<pre><code>if Text("Remove").exists():
click("Remove")
</code></pre>
<p>Explaination:</p>
<p>==============</p>
<p>WEBPAGE 1
CONTENTS:</p>
<p>â
A (REMOVE)
â
B (REMOVE)
â
C (REMOVE)</p>
<p>[ âRemoveâ... | -6 | 2016-09-09T11:22:01Z | 39,411,034 | <p>String have a replace method which you can directly use to replace the word with <code>''</code></p>
<pre><code>page = 'Lorem remove ipsum elit remove id justo eu, finibus remove'
page2 = 'Class aptent taciti sociosqu ad litora remove remove remove'
pageList = [page, page2]
for page in pageList:
while 'remove... | 0 | 2016-09-09T11:55:40Z | [
"python",
"selenium",
"helium"
] |
How to create a loop that checks if "Remove" exists for multiple "Remove" [Helium] [Selenium] [Python] | 39,410,446 | <p>How to loop the below logic inside a script, till all are deleted then continue to the next text. </p>
<pre><code>if Text("Remove").exists():
click("Remove")
</code></pre>
<p>Explaination:</p>
<p>==============</p>
<p>WEBPAGE 1
CONTENTS:</p>
<p>â
A (REMOVE)
â
B (REMOVE)
â
C (REMOVE)</p>
<p>[ âRemoveâ... | -6 | 2016-09-09T11:22:01Z | 39,411,666 | <p>Since Your mind is orbiting around .remove() :</p>
<pre><code>a = 'This is just a Test'
a_list = []
for i in range(0, len(a) - 1):
a_list.append(a[i])
while 't' in a_list: a_list.remove('t') # This Removes all lower case "t"s in a_list
a = ''
# Then you can change it into a string again :
for n in range(... | 0 | 2016-09-09T12:30:43Z | [
"python",
"selenium",
"helium"
] |
How do you define the real/imaginary parts of long symbolic expression without evaluation? | 39,410,579 | <p>I'm new to python and am having trouble with sympy. I define complex equations which are functions of the parameters a, b and use hold=true to save computation time. For example I have defined g in terms of other quantities A,B,C,D,E,F, as,</p>
<pre><code>In [92]: g=sympy.MatAdd(sympy.MatMul(A, B), \
...: s... | 2 | 2016-09-09T11:29:22Z | 39,459,583 | <p><code>hold=True</code> isn't a real SymPy option. You want <code>evaluate=False</code>. Note that <code>MatMul</code> already doesn't evaluate by default. </p>
<p><code>re</code> and <code>im</code> are <a href="https://github.com/sympy/sympy/issues/11600" rel="nofollow">presently</a> only defined to operate on sca... | 1 | 2016-09-12T22:15:06Z | [
"python",
"numpy",
"math",
"plot",
"sympy"
] |
Providing 'default' User when not logged in instead of AnonymousUser | 39,410,656 | <p><strong>Is there a way to globally provide a custom instance of <code>User</code> class instead of <code>AnonymousUser</code>?</strong></p>
<p>It is not possible to assign <code>AnonymousUser</code> instances when <code>User</code> is expected (for example in forms, there is need to check for authentication and so ... | 1 | 2016-09-09T11:34:02Z | 39,411,527 | <p>You could create a custom middleware (called after AuthenticationMiddleware), that checks if the user if logged in or not, and if not, replaces the current user object attached to request, with the the user of your choice.</p>
| 1 | 2016-09-09T12:23:24Z | [
"python",
"django"
] |
Different guiding_lines_colos for different leaf nodes in ETE3 using TreeStyle class or anything else | 39,410,916 | <p>How how can I add different colors for guiding line (connecting leaf node with the text using <a href="http://etetoolkit.org/docs/latest/reference/reference_treeview.html" rel="nofollow">guiding_lines_color in TreeStyle class</a>) in ETE3 python module.</p>
<p>Thanks</p>
| 1 | 2016-09-09T11:48:46Z | 39,414,447 | <p>Use TreeStyle.guiding_lines_color </p>
<p><a href="http://etetoolkit.org/docs/latest/reference/reference_treeview.html#ete3.TreeStyle" rel="nofollow">http://etetoolkit.org/docs/latest/reference/reference_treeview.html#ete3.TreeStyle</a></p>
| 1 | 2016-09-09T14:55:39Z | [
"python",
"etetoolkit",
"ete3"
] |
Render Counter Collections Sort Order | 39,410,954 | <p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p>
<p>I've got this:</p>
<pre><code>users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_comm... | 1 | 2016-09-09T11:50:53Z | 39,411,117 | <p>You extracted the most common, but then put them back into a new dict. Dicts are unordered.</p>
<p>Skip the <code>dict</code> call and just iterate through the result you get from <code>most_common</code>.</p>
| 2 | 2016-09-09T12:00:20Z | [
"python",
"django",
"collections"
] |
Render Counter Collections Sort Order | 39,410,954 | <p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p>
<p>I've got this:</p>
<pre><code>users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_comm... | 1 | 2016-09-09T11:50:53Z | 39,411,920 | <p>It is nice that you got the answer. But I wont prefer to go for Counter as we have annotate in Django.</p>
<p>When you use Counter the code will be</p>
<pre><code>users_cities = Counter(User.objects.all().values_list('city', flat=True)).most_common(5)
</code></pre>
<p>which results in an SQL query of </p>
<pre><... | 1 | 2016-09-09T12:44:50Z | [
"python",
"django",
"collections"
] |
AttributeError: 'module' object has no attribute 'graphviz_layout' with networkx 1.11 | 39,411,102 | <p>I'm trying to draw some DAGs using networkx 1.11 but I'm facing some errors, here's the test:</p>
<pre><code>import networkx as nx
print nx.__version__
G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)
import ... | 4 | 2016-09-09T11:59:23Z | 39,603,436 | <p>The package layout has changed in later versions of networkx. You can import the graphivz_layout function explicitly.</p>
<pre><code>import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout
G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G... | 2 | 2016-09-20T20:46:04Z | [
"python",
"python-2.7",
"networkx"
] |
Make a label / annotation appear, when hovering over an area (rectangle) | 39,411,116 | <p>As you can see the question above, I was wondering, if it is possible to popup a label, when I hover on a rectangle-area. </p>
<p>I found this <a href="http://stackoverflow.com/questions/11537374/matplotlib-basemap-popup-box/11556140#11556140">solution</a> which helped me for popping up a label over a <strong>point... | 1 | 2016-09-09T12:00:19Z | 39,412,339 | <p>Matplotlib by itself isn't going to give you this functionality. Bokeh <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html" rel="nofollow">(link)</a>, another python library, is what you want. <a href="http://bokeh.pydata.org/en/latest/docs/gallery/texas.html" rel="nofollow">Here is an example... | 1 | 2016-09-09T13:08:34Z | [
"python",
"python-2.7",
"matplotlib"
] |
identify a set containing correct values in dictionary of sets | 39,411,357 | <p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p>
<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E",... | 1 | 2016-09-09T12:13:57Z | 39,411,404 | <pre><code>>>> value1 = "A"
>>> value2 = "B"
>>> d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}}
>>> [k for k, v in d.items() if value1 in v and value2 in v]
['set1']
</code></pre>
| 5 | 2016-09-09T12:16:47Z | [
"python",
"python-3.x"
] |
identify a set containing correct values in dictionary of sets | 39,411,357 | <p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p>
<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E",... | 1 | 2016-09-09T12:13:57Z | 39,411,470 | <p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#set.issubset" rel="nofollow"><code>set.issubset</code></a> (which uses the <code><=</code> operator) by combining your needle characters into a set.</p>
<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}}
v... | 3 | 2016-09-09T12:20:39Z | [
"python",
"python-3.x"
] |
identify a set containing correct values in dictionary of sets | 39,411,357 | <p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p>
<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E",... | 1 | 2016-09-09T12:13:57Z | 39,411,501 | <p>You can filter the sets for which the set composed of value1 and value2 is a subset:</p>
<pre><code>def do_values_belong_in_same_set(value1, value2):
sets = [key for key, s in d.items() if {value1, value2} <= s]
if sets:
return True, sets[0]
else:
return False
</code></pre>
| 0 | 2016-09-09T12:22:23Z | [
"python",
"python-3.x"
] |
identify a set containing correct values in dictionary of sets | 39,411,357 | <p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p>
<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E",... | 1 | 2016-09-09T12:13:57Z | 39,411,600 | <p>You could slightly change the logic in your function to achieve this:</p>
<pre><code>def do_values_belong_in_same_set(value1, value2):
r = next((k for k, v in d.items() if all(i in v for i in {value1, value2})), False)
if r:
return True, r
else:
return r
</code></pre>
<p>Calling <code... | 0 | 2016-09-09T12:27:03Z | [
"python",
"python-3.x"
] |
How do i get my support vector regression to work to plot my polynomial graph | 39,411,384 | <p>I have compiled my code for a polynomial graph, but it is not plotting. I am using SVR(support vector regression) from scikit learn and my code is below. It is not showing any error message, and it is just showing my data. I don't know what is going on. Does anyone? It is not even showing anything on the variable co... | 1 | 2016-09-09T12:15:33Z | 39,419,386 | <p>Try the code below. Support Vector Machines expect their input to have zero mean and unit variance. It's not the plot, that's blocking. It's the call to <code>fit</code>.</p>
<pre><code>from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
svr_poly = make_pipeline(StandardScal... | 2 | 2016-09-09T20:39:32Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
How do i get my support vector regression to work to plot my polynomial graph | 39,411,384 | <p>I have compiled my code for a polynomial graph, but it is not plotting. I am using SVR(support vector regression) from scikit learn and my code is below. It is not showing any error message, and it is just showing my data. I don't know what is going on. Does anyone? It is not even showing anything on the variable co... | 1 | 2016-09-09T12:15:33Z | 39,419,716 | <p>Just to build on Matt's answer a little. Nothing about your plotting is in error. When you call to svr_poly.fit with 'unreasonably' large numbers no error is thrown (but I still had to kill my kernel). By tinkering the exponent value in this code I reckoned that you could get up to 1e5 before it breaks, but not more... | 0 | 2016-09-09T21:08:37Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] |
Re-using intermediate results in Dask (mixing delayed and dask.dataframe) | 39,411,407 | <p>Based on the answer I had received on <a href="http://stackoverflow.com/questions/39328398/locking-in-dask-multiprocessing-get-and-adding-metadata-to-hdf">an earlier question</a>, I have written an ETL procedure that looks as follows:
</p>
<pre><code>import pandas as pd
from dask import delayed
from dask import dat... | 2 | 2016-09-09T12:17:19Z | 39,412,000 | <p>There are two ways to approach your problem:</p>
<ol>
<li>Delay everything</li>
<li>Compute in stages</li>
</ol>
<h3>Delay Everything</h3>
<p>The to_hdf call accepts a <code>compute=</code> keyword argument that you can set to False. If False it will hand you back a <code>dask.delayed</code> value that you can c... | 2 | 2016-09-09T12:48:56Z | [
"python",
"dask"
] |
flask file upload not working | 39,411,417 | <p>I have problem with file upload. I getting no errors but i can't to find file. I was looking for solution but without success. Can anyone help to me?
My code:</p>
<pre><code>UPLOAD_FOLDER = '/upload/'
ALLOWED_EXTENSIONS = set(['.xlsx', '.xls'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def ... | 0 | 2016-09-09T12:17:54Z | 39,411,537 | <p>Your <code>allowed_extensions</code> function is splitting on <code>"."</code>, i.e. returning sub-strings split by <code>"."</code>, but then <code>ALLOWED_EXTENSIONS</code> still contains <code>"."</code>s.</p>
<p>Replace your <code>ALLOWED_EXTENSIONS</code> with </p>
<pre><code>ALLOWED_EXTENSIONS = set(['xlsx',... | 0 | 2016-09-09T12:23:52Z | [
"python",
"flask"
] |
Django - Follow a backward ForeignKey and then a ForeignKey (query) | 39,411,477 | <p>I use Django 1.9 and Python 2.7.</p>
<p>My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture".</p>
<pre><code>class Trip(models.Model):
title = models.CharField(max_length=140, blank=True)
class Step(models.Mode... | 0 | 2016-09-09T12:20:58Z | 39,411,536 | <p>Because <code>all()</code> returns a queryset, which is a collection of items; <code>theplace</code> is an attribute on an individual Step, not on the collection.</p>
<p>The way to do this type of query is to start from the class you want to retrieve, and follow the relationships within the query using the double-u... | 0 | 2016-09-09T12:23:51Z | [
"python",
"django",
"django-models",
"foreign-keys",
"django-queryset"
] |
Django - Follow a backward ForeignKey and then a ForeignKey (query) | 39,411,477 | <p>I use Django 1.9 and Python 2.7.</p>
<p>My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture".</p>
<pre><code>class Trip(models.Model):
title = models.CharField(max_length=140, blank=True)
class Step(models.Mode... | 0 | 2016-09-09T12:20:58Z | 39,411,579 | <p>Note that your model does not have an author field.</p>
<pre><code>class Trip(models.Model):
title = models.CharField(max_length=140, blank=True)
</code></pre>
<p>Assuming that it did, you can try something like this</p>
<pre><code>Picture.objects.filter(theplace__step__trip__author=request.user)
</code></pre... | 0 | 2016-09-09T12:25:53Z | [
"python",
"django",
"django-models",
"foreign-keys",
"django-queryset"
] |
Why kafka-python fails to connect to Bluemix message hub service? | 39,411,756 | <p>I'm trying to connect to a Bluemix Message Hub instance on <a href="http://bluemix.net" rel="nofollow">http://bluemix.net</a>. This simple script</p>
<pre><code>#!/usr/bin/env python
from kafka import KafkaProducer
from kafka.errors import KafkaError
kafka_brokers_sasl = [
"kafka01-prod01.messagehub.services... | 1 | 2016-09-09T12:35:23Z | 39,415,438 | <p>Message Hub requires that clients connect using a TLS 1.2 connection. This means specifying a <code>security_protocol</code> parameter to <code>KafkaProducer</code> and also a <code>ssl.SSLContext</code> via the <code>ssl_context</code> parameter - as it appears that the Python Kafka client creates a <code>SSLv23</... | 2 | 2016-09-09T15:54:12Z | [
"python",
"apache-kafka",
"ibm-bluemix",
"message-hub"
] |
i want to scrape data using python script | 39,411,790 | <p>I have written python script to scrape data from <a href="http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" rel="nofollow">http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings</a>
It is a list of 100 players and I successfully scraped this data. The problem is, when i run script in... | 1 | 2016-09-09T12:37:49Z | 39,412,107 | <p>Select the table and look for the divs in that:</p>
<pre><code>maindiv = soup.select("#batsmen-tests div.text-center")
for div in maindiv:
print(div.text)
</code></pre>
<p>Your original output and that above gets all the text from the divs as one line which is not really useful, if you just want the player nam... | 1 | 2016-09-09T12:54:56Z | [
"python",
"html5",
"python-3.x",
"beautifulsoup",
"python-3.4"
] |
i want to scrape data using python script | 39,411,790 | <p>I have written python script to scrape data from <a href="http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" rel="nofollow">http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings</a>
It is a list of 100 players and I successfully scraped this data. The problem is, when i run script in... | 1 | 2016-09-09T12:37:49Z | 39,412,444 | <p>The reason you get output three times is because the website has three categories you have to select it and then accordingly you can use it.</p>
<p>Simplest way of doing it with your code would be to add just one line</p>
<pre><code>import sys,requests,csv,io
from bs4 import BeautifulSoup
url = "http://www.cricbu... | -1 | 2016-09-09T13:15:04Z | [
"python",
"html5",
"python-3.x",
"beautifulsoup",
"python-3.4"
] |
I am not able to run jupyter notebook after installation in ubuntu | 39,411,899 | <p>I installed jupyter on my ubuntu system via the following command :</p>
<pre><code>sudo pip install jupyter
</code></pre>
<p>After executing it I could run <code>jupyter notebook</code> successfully.
But unfortunately while trying to upgrade it for python3, I accidentally deleted all <code>jupyter</code> links fro... | 1 | 2016-09-09T12:43:29Z | 39,411,979 | <p>Don't install python packages with sudo unless you really know what you're doing.</p>
<p>Try this instead:</p>
<pre><code>$ virtualenv myvenv
$ cd myvenv
$ source bin/activate
$ pip install jupyter
$ jupyter notebook
</code></pre>
<p>To run it the next time (in a new shell session i.e), simply do:</p>
<pre><code... | 1 | 2016-09-09T12:47:50Z | [
"python",
"ubuntu",
"jupyter"
] |
How to implement Weighted Binary CrossEntropy on theano? | 39,412,051 | <p><strong>How to implement Weighted Binary CrossEntropy on theano?</strong></p>
<p>My Convolutional neural network only predict 0 ~~ 1 (sigmoid).</p>
<p><strong>I want to penalize my predictions in this way :</strong></p>
<p><a href="http://i.stack.imgur.com/m3rAL.png"><img src="http://i.stack.imgur.com/m3rAL.png" ... | 6 | 2016-09-09T12:51:50Z | 39,536,684 | <p>To address your syntax error:</p>
<p>Change</p>
<pre><code>newshape = (T.shape(tgt)[0])
tgt = T.reshape(tgt, newshape)
</code></pre>
<p>to</p>
<pre><code>newshape = (T.shape(tgt)[0],)
tgt = T.reshape(tgt, newshape)
</code></pre>
<p><code>T.reshape</code> expects a tuple of axes, you didn't provide this, hence t... | 0 | 2016-09-16T17:00:15Z | [
"python",
"theano",
"keras",
"lasagne",
"cross-entropy"
] |
Create Datetime from year and month hidden in multi-index | 39,412,123 | <p>I have a dataframe where year and month are hidden in the <code>multi-index</code>. I want to create a datetime index as additional column (or separate series with same index).</p>
<pre><code> price
mean mom_2
fo... | 2 | 2016-09-09T12:55:46Z | 39,412,380 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, but first need multiple <code>year</code> and <code>month</code> values:</p>
<pre><code>y = df.index.get_level_values('year')
m = df.index.get_level_values('month'... | 2 | 2016-09-09T13:10:52Z | [
"python",
"datetime",
"pandas",
"multi-index",
"datetimeindex"
] |
Is There A Built-in Way to Filter with Given Function in Django? | 39,412,135 | <p>I especially wonder if I can use map, filter and reduce functions with Django model instances. If I cannot, is there a built-in way to pass a function to filter querying in Django?</p>
<p>Let me demonstrate my real problem for better understanding. I use PostgreSQL to use ArrayField and I have similiar model as bel... | 3 | 2016-09-09T12:56:08Z | 39,412,401 | <p>Django's Postgres integration allows you to query in embedded arrays using the <code>__contains</code> operator. So you can do:</p>
<pre><code>Route.objects.filter(stops_forwards__contains=[285])
</code></pre>
<p>See <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#querying-arrayfield" ... | 3 | 2016-09-09T13:12:14Z | [
"python",
"django",
"postgresql",
"filter"
] |
Filter Using Checkboxes w. Jquery | 39,412,344 | <p>I am trying to create checkbox filters that show or hide boxes on my pagebased on their id. I'm very new to jquery, but have been playing around with this for a while and cannot seem to get the boxes to hide / show. Please see my code below. Thanks!</p>
<p>Sport model</p>
<pre><code>class Sport(models.Model):
... | 0 | 2016-09-09T13:09:03Z | 39,412,506 | <p>Here's an example of how .each works in jquery</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleChks() {
$("input[type=checkbox]").each(function(index, ite... | 0 | 2016-09-09T13:18:35Z | [
"javascript",
"jquery",
"python",
"django",
"filter"
] |
Filter Using Checkboxes w. Jquery | 39,412,344 | <p>I am trying to create checkbox filters that show or hide boxes on my pagebased on their id. I'm very new to jquery, but have been playing around with this for a while and cannot seem to get the boxes to hide / show. Please see my code below. Thanks!</p>
<p>Sport model</p>
<pre><code>class Sport(models.Model):
... | 0 | 2016-09-09T13:09:03Z | 39,566,965 | <p>Here's a working one with your example, you've had to put the "id" for the sections, or in other case, change the jquery selector for it's class.</p>
<p>Also you have to set the click action for the input checkbox elements.</p>
<p>Hope this helps.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-... | 0 | 2016-09-19T06:50:04Z | [
"javascript",
"jquery",
"python",
"django",
"filter"
] |
Why am I receiving an error when trying to compare two lists? | 39,412,387 | <p>I am trying to compare two lists on line <code>#12</code> and return matches found. </p>
<p>The lists contain one user selected number (<code>un</code>) and one of which have been randomly generated (<code>rn</code>).</p>
<p>For example, <code>[['1', '5', '3', '7']]</code> and <code>[['9', '6', '3', '2']]</code> w... | 1 | 2016-09-09T13:11:29Z | 39,412,511 | <p>When you cast a list to a string back and forth, the result wouldn't be the original string. It would be a list containing the characters of the representation of the original string. </p>
<pre><code>>>> a = [1, 2, 3]
>>> b = str(a)
>>> c = list(b)
>>> c
['[', '1', ',', ' ', '2',... | 1 | 2016-09-09T13:18:54Z | [
"python",
"list",
"python-3.x",
"string-comparison",
"list-comparison"
] |
Why am I receiving an error when trying to compare two lists? | 39,412,387 | <p>I am trying to compare two lists on line <code>#12</code> and return matches found. </p>
<p>The lists contain one user selected number (<code>un</code>) and one of which have been randomly generated (<code>rn</code>).</p>
<p>For example, <code>[['1', '5', '3', '7']]</code> and <code>[['9', '6', '3', '2']]</code> w... | 1 | 2016-09-09T13:11:29Z | 39,412,932 | <p>Rather than using lists to pass the data around, use function parameters.</p>
<pre><code>import random
import re
def check(random_number, user_number):
print('random_number {}, user_number {}'.format(random_number, user_number))
x = set(random_number).intersection(user_number)
print(x)
def numval():
... | 1 | 2016-09-09T13:40:44Z | [
"python",
"list",
"python-3.x",
"string-comparison",
"list-comparison"
] |
ImportError: No module named views | 39,412,445 | <p>Im writing a web app in flask that displays bus stops pulled from an api. </p>
<p>i have a form on index.html where a user can input a stop number, that number gets picked up in views.py where the function also runs a task through celery to fetch the api data:</p>
<pre><code>from flask import render_template, requ... | 0 | 2016-09-09T13:15:04Z | 39,412,612 | <pre><code>from app.views import stopno
</code></pre>
<p>??</p>
| 0 | 2016-09-09T13:24:04Z | [
"python",
"module",
"celery",
"python-import",
"celery-task"
] |
ImportError: No module named views | 39,412,445 | <p>Im writing a web app in flask that displays bus stops pulled from an api. </p>
<p>i have a form on index.html where a user can input a stop number, that number gets picked up in views.py where the function also runs a task through celery to fetch the api data:</p>
<pre><code>from flask import render_template, requ... | 0 | 2016-09-09T13:15:04Z | 39,415,793 | <p>You are trying to do a relative import but you are not making it <em>explicitly</em> relative, which may or may not work, and which can cause unexpected errors. You should make your import explicitly relative with:</p>
<pre><code>from .views import stopno
</code></pre>
<p>This way you don't have to worry about rep... | 1 | 2016-09-09T16:17:09Z | [
"python",
"module",
"celery",
"python-import",
"celery-task"
] |
python create html table from dict | 39,412,679 | <p>I´m just starting learning python and therefore like to create a html table based on filenames.
Imaging following files</p>
<pre><code>apple.good.2.svg
apple.good.1.svg
banana.1.ugly.svg
banana.bad.2.svg
kiwi.good.svg
</code></pre>
<p>The kind of object is always the first part (before the first dot) the quality... | 2 | 2016-09-09T13:27:34Z | 39,412,965 | <p>You have to iterate all combinations of fruits from your dictionaries and states, and then create one line (instead of one column) for each fruit. Then just iterate all the files matching that fruit and filter those that contain the current state and join those in one cell.</p>
<pre><code>d = {'kiwi': ['kiwi.good.s... | 2 | 2016-09-09T13:42:34Z | [
"python"
] |
How to pass a bytestring to PyGreSQL? | 39,412,754 | <p>I've got a PostgreSQL table with a column of type <code>bytea</code>. Porting that table from SQLite, I ran into an issue - I couldn't figure out how to pass raw binary data to an SQL query. The framework I use is PyGreSQL. I want to stick to the DB-API 2.0 interface to avoid a lot of conversion.<br>
That interface,... | 0 | 2016-09-09T13:31:32Z | 39,555,893 | <p>Not really a solution, but a good-enough workaround. I decided to use <code>psycopg2</code> instead of <code>PyGreSQL</code> as it is more supported and common, so it's easier to find info about any common problems.<br>
There, the solution would be to use <code>%s</code> for every type, which I find much more Python... | 0 | 2016-09-18T09:04:24Z | [
"python",
"postgresql",
"sqlite",
"formatting"
] |
passing file path to youtube-dl in python | 39,412,810 | <p>Im using python <code>subprocess.call()</code> to call <code>[youtube-dl.exe][1]</code> and passing parameters like so</p>
<pre><code>downloadLocation = "-o " + "C:/Users/username/Documents/Youtube/%(title)s.%(ext)s"
subprocess.call(["youtube-dl",
"-f" "bestvideo[ext=mp4, height=1080]+bestaudio[ex... | 1 | 2016-09-09T13:34:05Z | 39,418,146 | <p><strong>Update:</strong> Here's how i got it to work</p>
<pre><code>subprocess.call(["youtube-dl",
"-f" "bestvideo[ext=mp4, height=1080]+bestaudio[ext=m4a]/best[ext=mp4, height=1080]/best",
"-o" "%s" %downloadLocation,
"--ignore-errors",
url])
</co... | 0 | 2016-09-09T18:59:17Z | [
"python",
"python-3.x",
"github",
"subprocess",
"youtube-dl"
] |
pandas.read_html not support decimal comma | 39,412,829 | <p>I was reading an xlm file using <code>pandas.read_html</code> and works <strong>almost perfect</strong>, the problem is that the file has commas as decimal separators instead of dots (the default in <code>read_html</code>). </p>
<p>I could easily replace the commas by dots in one file, but i have almost 200 files w... | 5 | 2016-09-09T13:35:16Z | 39,413,150 | <p>Looking at the source code of <a href="https://github.com/pydata/pandas/blob/master/pandas/io/html.py" rel="nofollow">read_html</a> </p>
<pre><code>def read_html(io, match='.+', flavor=None, header=None, index_col=None,
skiprows=None, attrs=None, parse_dates=False,
tupleize_cols=False, t... | 3 | 2016-09-09T13:51:26Z | [
"python",
"pandas",
"decimal",
"xlm"
] |
pandas.read_html not support decimal comma | 39,412,829 | <p>I was reading an xlm file using <code>pandas.read_html</code> and works <strong>almost perfect</strong>, the problem is that the file has commas as decimal separators instead of dots (the default in <code>read_html</code>). </p>
<p>I could easily replace the commas by dots in one file, but i have almost 200 files w... | 5 | 2016-09-09T13:35:16Z | 39,414,644 | <p>Thanks @zhqiat. I think upgrading <code>pandas</code> to version <code>0.19</code> will solve the problem. unfortunately I couldn't found an easy way to accomplish that. I found a tutorial to upgrade Pandas but for <a href="http://askubuntu.com/questions/70883/how-do-i-install-python-pandas/70885">ubuntu</a> (winXP ... | 2 | 2016-09-09T15:07:25Z | [
"python",
"pandas",
"decimal",
"xlm"
] |
Can I get the total count of a post likes, shares and comments using facebook sdk in Python? | 39,412,861 | <p>I want to get the total number of counts of a facebook post in python. The code below is giving a json object of some persons who likes the post. But not all. I need total counts. Is it possible?</p>
<pre><code>import requests
import facebook
token=''
graph = facebook.GraphAPI(token)
lik = graph.get_connections(id=... | -1 | 2016-09-09T13:36:55Z | 39,413,730 | <p>Use this API call:</p>
<pre><code>/10153608167431961?fields=likes.limit(0).summary(true)
</code></pre>
<p>Result:</p>
<pre><code>{
"likes": {
"data": [
],
"summary": {
"total_count": 13260,
"can_like": true,
"has_liked": false
}
},
"id": "10153608167431961"
}
</code></pre>
... | 0 | 2016-09-09T14:18:26Z | [
"python",
"facebook",
"facebook-graph-api"
] |
Can I get the total count of a post likes, shares and comments using facebook sdk in Python? | 39,412,861 | <p>I want to get the total number of counts of a facebook post in python. The code below is giving a json object of some persons who likes the post. But not all. I need total counts. Is it possible?</p>
<pre><code>import requests
import facebook
token=''
graph = facebook.GraphAPI(token)
lik = graph.get_connections(id=... | -1 | 2016-09-09T13:36:55Z | 39,977,752 | <p>graph.get_connections(id='10153608167431961', connection_name='likes', summary='true')</p>
<p>This should give the total likes for the given post/feed.</p>
| 0 | 2016-10-11T12:55:16Z | [
"python",
"facebook",
"facebook-graph-api"
] |
Handling big numbers in Python 3 for calculating combinations | 39,412,892 | <p>So I have a Python 3 script that calculates combinations in the following way</p>
<pre><code>def permutate(n, k):
if k == 0:
return 1
elif n < n - k + 1:
return n
else:
return n * permutate(n - 1, k - 1)
def choose(n, k):
if k > n / 2:
k = n - k
return int(... | 3 | 2016-09-09T13:38:05Z | 39,412,931 | <p>Problem is: all your divisions use floating point whereas they are clearly targeted as integer.</p>
<p>Python 3 acts differently from Python 2.</p>
<pre><code>3/2 => 1.5
3//2 => 1
</code></pre>
<p>Replace <code>/</code> by <code>//</code> (no need to cast in integer like you did)</p>
<pre><code>return perm... | 3 | 2016-09-09T13:40:37Z | [
"python",
"python-3.x"
] |
Handling big numbers in Python 3 for calculating combinations | 39,412,892 | <p>So I have a Python 3 script that calculates combinations in the following way</p>
<pre><code>def permutate(n, k):
if k == 0:
return 1
elif n < n - k + 1:
return n
else:
return n * permutate(n - 1, k - 1)
def choose(n, k):
if k > n / 2:
k = n - k
return int(... | 3 | 2016-09-09T13:38:05Z | 39,413,332 | <p><strong> Edited for correctness/brevity </strong></p>
<hr/>
<p>I have another approach that would take the load away from division and put it on multiplication. I would suggest taking advantage of the definition of combinations. Since combinations and permutations are counting techniques, losing precision through ... | 0 | 2016-09-09T13:59:07Z | [
"python",
"python-3.x"
] |
Handling big numbers in Python 3 for calculating combinations | 39,412,892 | <p>So I have a Python 3 script that calculates combinations in the following way</p>
<pre><code>def permutate(n, k):
if k == 0:
return 1
elif n < n - k + 1:
return n
else:
return n * permutate(n - 1, k - 1)
def choose(n, k):
if k > n / 2:
k = n - k
return int(... | 3 | 2016-09-09T13:38:05Z | 39,413,857 | <p>Here is another solution, which uses the <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow">fractions</a> module to (by reducing to lowest terms) do the division as it goes along. It also uses the fact that e.g. <code>choose(100,70) = choose(100,30)</code> so as to not do unneeded multiplica... | 2 | 2016-09-09T14:24:41Z | [
"python",
"python-3.x"
] |
Allow only one instance of a model in Django | 39,412,968 | <p>I would like to control some configuration settings for my project using a database model. For example:</p>
<pre><code>class JuicerBaseSettings(models.Model):
max_rpm = model.IntegerField(default=10)
min_rpm = model.IntegerField(default=0)
</code></pre>
<p>There should only be one instance of this model:</... | 2 | 2016-09-09T13:42:42Z | 39,413,083 | <p>You can override <code>save</code> method to control number of instances: </p>
<pre><code>class JuicerBaseSettings(models.Model):
def save(self, *args, **kwargs):
if JuicerBaseSettings.objects.exists() and not self.pk:
# if you'll not check for self.pk
# then error will also raised in... | 2 | 2016-09-09T13:47:45Z | [
"python",
"django"
] |
Allow only one instance of a model in Django | 39,412,968 | <p>I would like to control some configuration settings for my project using a database model. For example:</p>
<pre><code>class JuicerBaseSettings(models.Model):
max_rpm = model.IntegerField(default=10)
min_rpm = model.IntegerField(default=0)
</code></pre>
<p>There should only be one instance of this model:</... | 2 | 2016-09-09T13:42:42Z | 39,413,104 | <p>i am not an expert but i guess you can overwrite the model's save() method so that it will check if there has already been a instance , if so the save() method will just return , otherwise it will call the super().save()</p>
| 2 | 2016-09-09T13:49:19Z | [
"python",
"django"
] |
Allow only one instance of a model in Django | 39,412,968 | <p>I would like to control some configuration settings for my project using a database model. For example:</p>
<pre><code>class JuicerBaseSettings(models.Model):
max_rpm = model.IntegerField(default=10)
min_rpm = model.IntegerField(default=0)
</code></pre>
<p>There should only be one instance of this model:</... | 2 | 2016-09-09T13:42:42Z | 39,413,115 | <p>You could use a pre_save signal </p>
<pre><code>@receiver(pre_save, sender=JuicerBaseSettings)
def check_no_conflicting_juicer(sender, instance, *args, **kwargs):
# If another JuicerBaseSettings object exists a ValidationError will be raised
if JuicerBaseSettings.objects.exclude(pk=instance.pk).exists():
... | 2 | 2016-09-09T13:49:54Z | [
"python",
"django"
] |
find values for which the result of division change in integer in python | 39,412,999 | <p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multi... | 0 | 2016-09-09T13:44:15Z | 39,413,144 | <p>Maybe this would help:</p>
<pre><code>A = 1 # adapt this to your data
B = 894.57 # adapt this to your data
lastInt = -1
for i in range(0,1000):
C = A / B
newInt = int(C)
if newInt!=lastInt:
print "CHANGE: from {} to {}. A is {}".format(lastInt, newInt, A)
lastInt = newInt
A += 10 # ... | 0 | 2016-09-09T13:51:08Z | [
"python",
"bigdata",
"division"
] |
find values for which the result of division change in integer in python | 39,412,999 | <p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multi... | 0 | 2016-09-09T13:44:15Z | 39,413,146 | <p>Assuming you know how to get the data out since you said you tried <code>%</code> and assuming that the data are not strings, wouldn't this work? A simple if statement with a checker that increments? </p>
<pre><code>number_to_check = 1
if c >= number_to_check:
number_to_check += 1
print(a)
</code></pre>
| 0 | 2016-09-09T13:51:16Z | [
"python",
"bigdata",
"division"
] |
find values for which the result of division change in integer in python | 39,412,999 | <p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multi... | 0 | 2016-09-09T13:44:15Z | 39,413,378 | <p>It's probably not an elegant solution, but couldn't you just compare the numbers at the beginning of each entry (assuming your data is consistent)? This would make things very easy. The example below assumes your data is separated by whitespace (as in your post) and is stored in a file called "data."</p>
<hr>
<p>P... | 1 | 2016-09-09T14:01:22Z | [
"python",
"bigdata",
"division"
] |
numpy mask for 2d array with all values in 1d array | 39,413,148 | <p>I want to convert a 2d matrix of dates to boolean matrix based on dates in a 1d matrix. i.e., </p>
<pre><code>[[20030102, 20030102, 20070102],
[20040102, 20040102, 20040102].,
[20050102, 20050102, 20050102]]
</code></pre>
<p>should become</p>
<pre><code>[[True, True, False],
[False, False, False].,
[True, Tr... | 2 | 2016-09-09T13:51:19Z | 39,413,415 | <pre><code>import numpy as np
dateValues = np.array(
[[20030102, 20030102, 20030102],
[20040102, 20040102, 20040102],
[20050102, 20050102, 20050102]])
requestedDates = [20010203, 20030102, 20030501, 20050102, 20060101]
ix = np.in1d(dateValues.ravel(), requestedDates).reshape(dateValues.shape)
print(ix... | 4 | 2016-09-09T14:02:57Z | [
"python",
"numpy"
] |
numpy mask for 2d array with all values in 1d array | 39,413,148 | <p>I want to convert a 2d matrix of dates to boolean matrix based on dates in a 1d matrix. i.e., </p>
<pre><code>[[20030102, 20030102, 20070102],
[20040102, 20040102, 20040102].,
[20050102, 20050102, 20050102]]
</code></pre>
<p>should become</p>
<pre><code>[[True, True, False],
[False, False, False].,
[True, Tr... | 2 | 2016-09-09T13:51:19Z | 39,416,504 | <pre><code>a = np.array([[20030102, 20030102, 20070102],
[20040102, 20040102, 20040102],
[20050102, 20050102, 20050102]])
b = np.array([20010203, 20030102, 20030501, 20050102, 20060101])
>>> a.shape
(3, 3)
>>> b.shape
(5,)
>>>
</code></pre>
<p>For the comparison... | 1 | 2016-09-09T17:03:34Z | [
"python",
"numpy"
] |
In 'IDA PRO', let 'IDAPython' import default module at startup | 39,413,230 | <p>We know 'IDAPython' loads several modules by default at startup, such as idaapi, idautils.... I wrote a module to let python print all numbers as hex format in the command window, which I wish can be imported each time when python loads those default modules. how to achieve that?</p>
| 0 | 2016-09-09T13:54:29Z | 39,688,418 | <p>Create a file <code>%APPDATA%\Hex-Rays\IDA Pro\idapythonrc.py</code> with the following content:</p>
<pre><code>import idaapi
idaapi.require('mymodule')
</code></pre>
<p>With this file in place, you can even keep <code>mymodule.py</code> in the same directory.</p>
<p>P.S. IDA can tell you the path to this directo... | 0 | 2016-09-25T15:10:43Z | [
"python",
"ida"
] |
Sending gzip compressed data through TCP socket in Python | 39,413,290 | <p>I'm creating an HTTP server in Python without any of the HTTP libraries for learning purposes. Right now it can serve static files fine. </p>
<p>The way I serve the file is through this piece of code:</p>
<pre><code>with open(self.filename, 'rb') as f:
src = f.read()
socket.sendall(src)
</code></pre>
<p>Howev... | 0 | 2016-09-09T13:57:06Z | 39,416,270 | <p>The zlib library implements the deflate compression algorithm (RFC 1951). There are two encapsulations for the deflate compression: zlib (RFC 1950) and gzip (RFC 1952). These differ only in the kind of header and trailer they provide around the deflate compressed data.</p>
<p><code>zlib.compress</code> only provide... | 0 | 2016-09-09T16:46:36Z | [
"python",
"sockets",
"http",
"get",
"bzip"
] |
Finding indices from list comprehension in Python 3 | 39,413,359 | <p>I want to find the indices of matches in a list using the best Python syntax. Here is what I have:</p>
<pre><code>v = ['=', 'c', '=', 'c', 'c', 'c', '=', 'c', 'c', '=']
</code></pre>
<p>Now, return the list of integers for the condition of:</p>
<pre><code>'=' in v is True
</code></pre>
<p>So far, I have:</p>
<... | -1 | 2016-09-09T14:00:24Z | 39,413,406 | <p>Use <a href="https://docs.python.org/3.5/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p>
<pre><code>[i for i,x in enumerate(v) if x=='=']
</code></pre>
| 0 | 2016-09-09T14:02:44Z | [
"python",
"if-statement",
"list-comprehension"
] |
Finding indices from list comprehension in Python 3 | 39,413,359 | <p>I want to find the indices of matches in a list using the best Python syntax. Here is what I have:</p>
<pre><code>v = ['=', 'c', '=', 'c', 'c', 'c', '=', 'c', 'c', '=']
</code></pre>
<p>Now, return the list of integers for the condition of:</p>
<pre><code>'=' in v is True
</code></pre>
<p>So far, I have:</p>
<... | -1 | 2016-09-09T14:00:24Z | 39,413,411 | <p>What you need is this:</p>
<pre><code>[i for i, entry in enumerate(v) if entry == '=']
</code></pre>
<p>The difference between this comprehension and yours is that in yours, after finding a match you get it's <code>index</code> which returns the position in the list in which the object is found <strong>for the fir... | 0 | 2016-09-09T14:02:51Z | [
"python",
"if-statement",
"list-comprehension"
] |
Python 2.7 Tkinter: loop through labels to display data on new row | 39,413,405 | <p>I currently trying to create a weather application and I have code that prints out the day, forecast, and maxtemperture for the next 7 days. </p>
<pre><code>weather_req_url = "https://api.forecast.io/forecast/%s/%s,%s?units=uk2" % (weather_api_token, lat,lon)
r = requests.get(weather_req_url)
weather_obj = json.loa... | 0 | 2016-09-09T14:02:42Z | 39,413,905 | <p>As in the comment above, something along these lines should do the trick:</p>
<pre><code>forecasts = []
for i, x in enumerate(weather_obj["daily"]["data"][1:8]):
forecasts.append((t+timedelta(days=i+1)).strftime("\t%a"), x['icon'], ("%.0f" % x['temperatureMax']))
row_num = 0
for forecast in forecasts:
l ... | 2 | 2016-09-09T14:26:50Z | [
"python",
"python-2.7",
"for-loop",
"tkinter"
] |
Function giving wrong output in Python | 39,413,447 | <p>Through this code, i wish to replace all the dots (<code>.</code>) appearing in the string s with the character present at exactly the symmetrically opposite position. For eg: if <code>s=a.bcdcbba</code>, then the <code>.</code> should be replaced by <code>b</code></p>
<p><strong>i.e:</strong></p>
<p>The element a... | 0 | 2016-09-09T14:04:28Z | 39,413,707 | <p>@chepner's way:</p>
<pre><code>def replacedots(s):
return ''.join(x if x !='.' else y for x, y in zip(s, reversed(s)))
</code></pre>
<p>an alternative:</p>
<pre><code>def replacedots(s):
return ''.join(c if c != '.' else s[-i - 1] for i, c in enumerate(s))
</code></pre>
<p>When the char at position <code... | 1 | 2016-09-09T14:17:19Z | [
"python"
] |
How to get a complex number as a user input in python? | 39,413,518 | <p>I'm trying to build a calculator that does basic operations of complex numbers. I'm using code for a calculator I found online and I want to be able to take user input as a complex number. Right now the code uses int(input) to get integers to evaluate, but I want the input to be in the form of a complex number with ... | 1 | 2016-09-09T14:07:32Z | 39,413,632 | <p>Pass your input to the <code>complex</code> type function. This constructor can also be called with a string as argument, and it will attempt to parse it using Python's representation of complex numbers.</p>
<p>Example</p>
<pre><code>my_number = complex(input("Number"))
</code></pre>
<p>Note that Python uses "j" ... | 1 | 2016-09-09T14:13:24Z | [
"python",
"python-2.7",
"input",
"calculator",
"complex-numbers"
] |
python sqlite3 save value out of spinbox into database by pushing button | 39,413,521 | <p>Trying to save a value from a spinbox into my database. This is a part of my code.</p>
<pre><code>numericupdownLL = tk.Spinbox(self, from_=0, to=300)
numericupdownLL.pack()
def saveDate(title):
vLL = int(numericupdownLL.get()) ## convert to int because output of spinbox= str and database=int
c.exec... | 0 | 2016-09-09T14:07:41Z | 39,424,468 | <p>I'll correct the typos in the code in order to be consistent in the explanation</p>
<pre><code>numericupdownLL = tk.Spinbox(self, from_=0, to=300)
numericupdownLL.pack()
# Changed saveDate to saveData that it's actually called in the button
def saveData(title):
# Corrected indentation
vLL = int(numericupdo... | 0 | 2016-09-10T09:06:00Z | [
"python",
"sqlite3"
] |
Using pymodbus to read registers | 39,413,550 | <p>I'm trying to read modbus registers from a PLC using pymodbus. I am following the example posted <a href="http://stackoverflow.com/questions/24872269/reading-registers-with-pymodbus">here</a>. When I attempt <code>print.registers</code> I get the following error: <code>object has no attribute 'registers'</code>
The ... | 0 | 2016-09-09T14:09:17Z | 39,414,431 | <p>From reading <a href="https://github.com/bashwork/pymodbus/blob/master/pymodbus/register_read_message.py" rel="nofollow" title="pymodbus read_holding_registers request object">the pymodbus code</a>, it appears that the <code>read_holding_registers</code> object's <code>execute</code> method will return <em>either</e... | 0 | 2016-09-09T14:54:48Z | [
"python",
"modbus-tcp"
] |
Can I send richly-formatted Slack messages as a Bot and not as a Webhook? | 39,413,582 | <p>I started writing a Slack bot in Python and came to a halt when I couldn't find a way to send richly-formatted messages using the either of the two methods:</p>
<pre><code>sc.rtm_send_message("channel_name", my_message)
sc.api_call("chat.postMessage", channel="channel_name", text=my_message, username="username", i... | 0 | 2016-09-09T14:11:02Z | 39,485,828 | <p>Both API (method chat.postMessage) and incoming webhook offer the same options for formatting your messages including markup and attachments.</p>
<p>Hint: if you want to use markup in your attachments, make sure to add the field "mrkdwn_in" and name the field your want to use it in or it will be ignored by Slack.</... | 2 | 2016-09-14T08:29:19Z | [
"python",
"slack-api",
"slack"
] |
Can I send richly-formatted Slack messages as a Bot and not as a Webhook? | 39,413,582 | <p>I started writing a Slack bot in Python and came to a halt when I couldn't find a way to send richly-formatted messages using the either of the two methods:</p>
<pre><code>sc.rtm_send_message("channel_name", my_message)
sc.api_call("chat.postMessage", channel="channel_name", text=my_message, username="username", i... | 0 | 2016-09-09T14:11:02Z | 39,490,291 | <p>I found out where I was going wrong.</p>
<p>I was passing my message to the wrong argument in the <code>sc.api_call</code> method.</p>
<p>I should've been passing it to <code>sc.api_call(</code><strong><code>attachments=</code></strong><code>...)</code> argument, not the <code>text</code> argument.</p>
| 1 | 2016-09-14T12:19:04Z | [
"python",
"slack-api",
"slack"
] |
Convert strings of bytes to floats in Python | 39,413,600 | <p>I'm using Pandas to handle my data. The first step of my script is to convert a column of strings of bytes to a list of floats. My script is working but its taking too long. Any suggestions on how to speed it up??</p>
<pre><code>def byte_to_hex(byte_str):
array = ["%02X" % ord(chr(x)) for x in byte_str]
ret... | 1 | 2016-09-09T14:12:02Z | 39,414,098 | <p>I think you are looking for the <a href="https://docs.python.org/3.4/library/struct.html" rel="nofollow">Struct</a> package</p>
<pre><code>import struct
struct.pack('f', 3.14)
OUT: b'\xdb\x0'
struct.unpack('f', b'\xdb\x0fI@')
OUT: (3.1415927410125732,)
struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
OUT: '\x00\x00\x80?\x0... | 2 | 2016-09-09T14:37:40Z | [
"python",
"pandas",
"byte"
] |
Taking file input in numpy Matrix | 39,413,702 | <p>I am unable to find a method to take input of a given file in numpy matrix.
I have tried the <code>np.loadtxt()</code> but was unable to get the data.</p>
<p>My file format is something like this:
Number of col = 9 (except the first field all others are in float).</p>
<pre><code>M,0.475,0.37,0.125,0.5095,0.2165,... | 0 | 2016-09-09T14:16:57Z | 39,414,299 | <p>You might want to consider using <code>pandas</code> instead - it's much better suited to homogeneous data, and its <code>read_csv</code> function will take your data file and convert it immediately to something you can work with.</p>
<p>You can give each column a name - if you don't do this, the function will inte... | 1 | 2016-09-09T14:47:24Z | [
"python",
"numpy"
] |
Taking file input in numpy Matrix | 39,413,702 | <p>I am unable to find a method to take input of a given file in numpy matrix.
I have tried the <code>np.loadtxt()</code> but was unable to get the data.</p>
<p>My file format is something like this:
Number of col = 9 (except the first field all others are in float).</p>
<pre><code>M,0.475,0.37,0.125,0.5095,0.2165,... | 0 | 2016-09-09T14:16:57Z | 39,416,578 | <p>With your sample as a list of lines:</p>
<pre><code>In [1]: txt=b"""
...: M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9
...: F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19
...: """
In [2]: txt=txt.splitlines()
</code></pre>
<p><code>genfromtxt</code> can load it with <code>dtype=None</code>:</p>
<pre><co... | 1 | 2016-09-09T17:09:34Z | [
"python",
"numpy"
] |
Iteration through a range of timestamp in Python | 39,413,752 | <p>I have a dataframe df :</p>
<pre><code>TIMESTAMP equipement1 equipement2
2016-05-10 13:20:00 0.000000 0.000000
2016-05-10 14:40:00 0.400000 0.500000
2016-05-10 15:20:00 0.500000 0.500000
</code></pre>
<p>Iam trying to iterate through timestamp by step of 5 minutes .
I try : <code>pd.date_range(start, end, freq='5 ... | 1 | 2016-09-09T14:19:40Z | 39,413,981 | <p>First, make sure your TIMESTAMP column is a datetime instead of a string (e.g. <code>df['TIMESTAMP'] = pd.to_datetime(df.TIMESTAMP)</code>).</p>
<p>Next, use this column as the index of the dataframe. To make this permanent, <code>df.set_index('TIMESTAMP</code>, inplace=True)`.</p>
<p>Now you can <a href="http://... | 3 | 2016-09-09T14:31:14Z | [
"python",
"date",
"pandas"
] |
Can I make an ipywidget floatslider with a list of values? | 39,413,786 | <p>I would like to make an ipywidget floatslider, but passing it a list of values, rather than a range and step. Is there a way to do this, or is making a dropdown widget the only option?</p>
| 0 | 2016-09-09T14:21:15Z | 39,415,297 | <p>Woops! You can use SelectionSlider, e.g.:</p>
<pre><code>import ipywidgets as widgets
def test(val):
print(val)
widgets.interact(test, val=widgets.SelectionSlider(description='value', options=['1', '50', '300', '7000']))
</code></pre>
<p>This widget wasn't available in my ipywidgets 4.0, so I had to upgra... | 0 | 2016-09-09T15:44:29Z | [
"python",
"jupyter",
"ipywidgets"
] |
ImportError: No module named dns.message | 39,413,802 | <p>When I try to run <code>sudo python dns2proxy.py</code> in Ubuntu, I keep getting this error:</p>
<pre><code>Traceback (most recent call last):
File "dns2proxy.py", line 21, in <module>
import dns.message
ImportError: No module named dns.message
</code></pre>
<p>I have the correct repository cloned (<a... | 0 | 2016-09-09T14:22:05Z | 39,413,922 | <p>Try running the command</p>
<pre><code>pip install dnspython
</code></pre>
<p>or, if you are using your system Python (not recommended)</p>
<pre><code>sudo pip install dnspython
</code></pre>
<p>This will install the <code>dns</code> package that is currently missing. If, as you say, you have cloned the reposito... | 1 | 2016-09-09T14:27:28Z | [
"python",
"linux",
"dns"
] |
How to extract columns from multiple rows in Python using nested loops? | 39,413,828 | <p>I have a list with 3 sequences</p>
<pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC']
</code></pre>
<p>I want to extract the columns from the the list and store it in another list using nested loops in python</p>
<p>The final output should be </p>
<pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC']
</code></pre>
<p>I... | 0 | 2016-09-09T14:23:16Z | 39,413,884 | <p>Alternatively, you can <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">"zip" the sequence</a> and <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow">join</a>:</p>
<pre><code>>>> [''.join(item) for item in zip(*seq_list)]
['AAA', 'CTC', 'GTC', 'TT... | 2 | 2016-09-09T14:25:39Z | [
"python",
"python-2.7",
"for-loop",
"extract",
"multiple-columns"
] |
How to extract columns from multiple rows in Python using nested loops? | 39,413,828 | <p>I have a list with 3 sequences</p>
<pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC']
</code></pre>
<p>I want to extract the columns from the the list and store it in another list using nested loops in python</p>
<p>The final output should be </p>
<pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC']
</code></pre>
<p>I... | 0 | 2016-09-09T14:23:16Z | 39,413,972 | <p>By your method I made little modification, for each inner <code>for</code> loop i created a <code>string</code> and then after inner <code>for</code> loop ends i appended it to <code>column</code>:</p>
<pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC']
column = []
for i in range(len(seq_list[0])): #Length of the row
... | 3 | 2016-09-09T14:30:40Z | [
"python",
"python-2.7",
"for-loop",
"extract",
"multiple-columns"
] |
How to extract columns from multiple rows in Python using nested loops? | 39,413,828 | <p>I have a list with 3 sequences</p>
<pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC']
</code></pre>
<p>I want to extract the columns from the the list and store it in another list using nested loops in python</p>
<p>The final output should be </p>
<pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC']
</code></pre>
<p>I... | 0 | 2016-09-09T14:23:16Z | 39,413,986 | <pre><code>new_seq_list = reduce(
lambda new_seq_list,item:
new_seq_list + [''.join([item.pop(0) for item in new_seq_list[0]])]
, range(max([len(item) for item in seq_list])) ,
[[list(item) for item in seq_list]]
)[1:]
</code></pre>
<ol>
<li>transform the original list into a list of list-of-characters rathe... | -2 | 2016-09-09T14:31:37Z | [
"python",
"python-2.7",
"for-loop",
"extract",
"multiple-columns"
] |
Return results from a loop for varying portfolio weights into a dataframe in Pandas | 39,413,872 | <p>I am about to create a portfolio of two assets and would like to vary the weights by a loop, with the weights for the first asset from [-0.5, -0.4, ... 0.4, 0.5]
I manage to calculate the risk return points for each of the 11 portfolios by a loop. Nevertheless, the loop creates a new dataframe for each risk/return c... | 0 | 2016-09-09T14:25:11Z | 39,413,979 | <p>You can use <code>pd.concat</code> to create a single dataframe out of them.</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects</a></p>
| 0 | 2016-09-09T14:31:04Z | [
"python",
"loops",
"dataframe",
"weight",
"portfolio"
] |
How to get nicely formatted documentation in python | 39,413,937 | <p>I'm an R user and I'm just moving to Python for data analysis. </p>
<p>What I'm looking for is a way to pull documentation for any python object (classes, modules, functions...) in a nice-looking, HTML-ish formatted way instead of the output I get when typing <code>help(...)</code>, just like what I would obtain i... | 0 | 2016-09-09T14:28:14Z | 39,414,081 | <p>You might want to check out <a href="http://www.stack.nl/~dimitri/doxygen/" rel="nofollow">DoxyGen</a> - It supports automatic documentation generation for Python with outputs in, among other formats, HTML.</p>
<p>It doesn't provide quite the interface you're looking for, but may still be useful to you.</p>
| 0 | 2016-09-09T14:36:53Z | [
"python",
"formatting",
"documentation"
] |
'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine | 39,413,987 | <p>I have an issue related to Cryptography package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution)</p>
<p>The python code which initiates this error: </p>
<pre><code>print("Salt: %s" % salt)
server_key = pyelliptic.ECC(curve="prime256v1") # --... | 9 | 2016-09-09T14:31:38Z | 39,499,600 | <p>The <a href="https://github.com/pyca/cryptography/issues/2838" rel="nofollow">issue</a> referenced in <a href="http://stackoverflow.com/questions/39413987/entrypoint-object-has-no-attribute-resolve-when-using-google-compute-engine?noredirect=1#comment66303382_39413987">c66303382</a> has this traceback (you never gav... | 3 | 2016-09-14T21:02:56Z | [
"python",
"django",
"cryptography",
"google-compute-engine"
] |
'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine | 39,413,987 | <p>I have an issue related to Cryptography package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution)</p>
<p>The python code which initiates this error: </p>
<pre><code>print("Salt: %s" % salt)
server_key = pyelliptic.ECC(curve="prime256v1") # --... | 9 | 2016-09-09T14:31:38Z | 39,507,792 | <p>Ran Following Commands from the project path /opt/projects/myproject-google/myproject and it resolved the Attribute EntryPoint Error Issue:</p>
<p>(Assuming project virtual env path as: /opt/projects/myproject-google/venv)</p>
<p>Command: (from path: /opt/projects/myproject-google/myproject)</p>
<pre><code>export... | 1 | 2016-09-15T09:39:43Z | [
"python",
"django",
"cryptography",
"google-compute-engine"
] |
Translating Matlab code to Python | 39,413,998 | <p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening?
Also: am I doing it right? I'm a real newbie.</p>
<p>Matlab code:</p>
<pre><code>function Dir = getScriptDir()
fullPath = mfilename('fullpath');
[Dir, ~,~] = fileparts(fullPath)... | 0 | 2016-09-09T14:32:19Z | 39,414,082 | <p>Remember that you need to return variables from a python-function to get their results. </p>
<p>More on how to define your own functions in python: <a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">https://docs.python.org/3/tutorial/controlflow.html#defining-functions</... | 0 | 2016-09-09T14:36:54Z | [
"python",
"matlab",
"function",
"translation"
] |
Translating Matlab code to Python | 39,413,998 | <p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening?
Also: am I doing it right? I'm a real newbie.</p>
<p>Matlab code:</p>
<pre><code>function Dir = getScriptDir()
fullPath = mfilename('fullpath');
[Dir, ~,~] = fileparts(fullPath)... | 0 | 2016-09-09T14:32:19Z | 39,414,121 | <p>Your function definitions were incorrect. I have modified the code you provided. You can also consolidate the <code>getScriptDir()</code> functionality into the <code>getFileList()</code> function.</p>
<pre><code>import os
def getFileList():
dir = os.path.dirname(os.path.realpath(__file__))
list = os.listd... | 0 | 2016-09-09T14:38:34Z | [
"python",
"matlab",
"function",
"translation"
] |
Translating Matlab code to Python | 39,413,998 | <p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening?
Also: am I doing it right? I'm a real newbie.</p>
<p>Matlab code:</p>
<pre><code>function Dir = getScriptDir()
fullPath = mfilename('fullpath');
[Dir, ~,~] = fileparts(fullPath)... | 0 | 2016-09-09T14:32:19Z | 39,414,162 | <p>Your syntax is incorrect. If I'm reading this correctly, you're trying to get the names of the files in the same directory as the script and print the number of files in that list.</p>
<hr>
<p>Here's an example of how you might do this (based on the program you gave):</p>
<pre><code>import os
def getFileList(dir... | 2 | 2016-09-09T14:40:20Z | [
"python",
"matlab",
"function",
"translation"
] |
making pySFML work on linux | 39,414,057 | <p>This might be stupid question, but I am not sure what do to.
Basically I have install sfml-dev (2.3.2) and later python-sfml(2.2) and cython(0.23.4) because by my understanding python-sfml is "not a pure python library. Rather, it is a set of extensions that provide a Pythonic API around a C++ library. As such, ever... | -2 | 2016-09-09T14:35:43Z | 39,420,813 | <p>kk, I managed to fix it.
You need to have these two lines at the beginning of the code when </p>
<pre><code> import sfml as sf
from sfml import sf
#your code in python using the SFML library
</code></pre>
| 0 | 2016-09-09T23:01:19Z | [
"python",
"linux",
"sfml"
] |
Adding an extra hidden layer using Google's TensorFlow | 39,414,060 | <p>I am trying to create a multi-label classifier using TensorFlow. Though I'm having trouble adding and connecting hidden layers.</p>
<p>I was following this tutorial: <a href="http://jrmeyer.github.io/tutorial/2016/02/01/TensorFlow-Tutorial.html" rel="nofollow">http://jrmeyer.github.io/tutorial/2016/02/01/TensorFlow... | 0 | 2016-09-09T14:35:54Z | 39,414,552 | <p>If you want a fully connected network with one hidden layer and an output layer there is how their shapes should look like:</p>
<pre><code># hidden layer
weights_hidden = tf.Variable(tf.random_normal([numFeatures, num_nodes])
bias_hidden = tf.Variable(tf.random_normal([num_nodes])
preactivations_hidden = tf.add(tf.... | 1 | 2016-09-09T15:01:56Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow"
] |
How to convert the following string in python? | 39,414,085 | <p>Input : UserID/ContactNumber </p>
<p>Output: user-id/contact-number</p>
<p>I have tried the following code:</p>
<pre><code>s ="UserID/ContactNumber"
list = [x for x in s]
for char in list:
if char != list[0] and char.isupper():
list[list.index(char)] = '-' + char
fin_list=''.join((list))
pr... | 4 | 2016-09-09T14:36:55Z | 39,414,269 | <p>What about something like that:</p>
<pre><code>s ="UserID/ContactNumber"
so = ''
for counter, char in enumerate(s):
if counter == 0:
so = char
elif char.isupper() and not (s[counter - 1].isupper() or s[counter - 1] == "/"):
so += '-' + char
else:
so += char
print(so.lower())
</co... | 2 | 2016-09-09T14:45:59Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to convert the following string in python? | 39,414,085 | <p>Input : UserID/ContactNumber </p>
<p>Output: user-id/contact-number</p>
<p>I have tried the following code:</p>
<pre><code>s ="UserID/ContactNumber"
list = [x for x in s]
for char in list:
if char != list[0] and char.isupper():
list[list.index(char)] = '-' + char
fin_list=''.join((list))
pr... | 4 | 2016-09-09T14:36:55Z | 39,414,310 | <p>You could use a <a href="https://docs.python.org/3.5/library/re.html">regular expression</a> with a positive lookbehind assertion:</p>
<pre><code>>>> import re
>>> s ="UserID/ContactNumber"
>>> re.sub('(?<=[a-z])([A-Z])', r'-\1', s).lower()
'user-id/contact-number'
</code></pre>
| 7 | 2016-09-09T14:48:18Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to convert the following string in python? | 39,414,085 | <p>Input : UserID/ContactNumber </p>
<p>Output: user-id/contact-number</p>
<p>I have tried the following code:</p>
<pre><code>s ="UserID/ContactNumber"
list = [x for x in s]
for char in list:
if char != list[0] and char.isupper():
list[list.index(char)] = '-' + char
fin_list=''.join((list))
pr... | 4 | 2016-09-09T14:36:55Z | 39,415,778 | <p>I did something like this</p>
<pre><code>s ="UserID/ContactNumber"
new = []
words = s.split("/")
for word in words:
new_word = ""
prev = None
for i in range(0, len(word)):
if prev is not None and word[i].isupper() and word[i-1].islower():
new_word = new_word + "-" + word[i]
... | -1 | 2016-09-09T16:15:59Z | [
"python",
"python-2.7",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.