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
How to define a temporary variable in python?
39,386,837
<p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p> <p>I would like to do something like this:</p> <pre><code>...a, b, and c populated as lists earlier in code... using ix=getindex(): print(a[ix],b[ix],c[ix]) ...now ix is no longer defined... </code></pre> <p>The variable ix would be undefined outside of the one line.</p> <p>Perhaps this pseudo-code is more clear:</p> <pre><code>...a and b are populated lists earlier in code... {ix=getindex(); answer = f(a[ix]) + g(b[ix])} </code></pre> <p>where ix does not exist outside of the bracket.</p>
1
2016-09-08T09:05:47Z
39,387,003
<p>Technically not an answer, but: Don't worry about temporary variables too much, they are only valid within their local scope (most likely function in your case) and garbage collector gets rid of them as soon as that function is finished. One liners in python are mostly used for dict and list comprehensions. </p> <p>If you REALLY want to do it in one line, use <code>lambda</code> which is pretty much keyword for inline function</p>
0
2016-09-08T09:14:28Z
[ "python" ]
How to define a temporary variable in python?
39,386,837
<p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p> <p>I would like to do something like this:</p> <pre><code>...a, b, and c populated as lists earlier in code... using ix=getindex(): print(a[ix],b[ix],c[ix]) ...now ix is no longer defined... </code></pre> <p>The variable ix would be undefined outside of the one line.</p> <p>Perhaps this pseudo-code is more clear:</p> <pre><code>...a and b are populated lists earlier in code... {ix=getindex(); answer = f(a[ix]) + g(b[ix])} </code></pre> <p>where ix does not exist outside of the bracket.</p>
1
2016-09-08T09:05:47Z
39,387,060
<blockquote> <p>Does python have a "temporary" or "very local" variable facility? </p> </blockquote> <p>yes, it's called a block, e.g. a function:</p> <pre><code>def foo(*args): bar = 'some value' # only visible within foo print bar # works foo() &gt; some value print bar # does not work, bar is not in the module's scope &gt; NameError: name 'bar' is not defined </code></pre> <p>Note that any value is temporary in the sense that it is only guaranteed to stay allocated as long as a name is bound to it. You can unbind by calling <code>del</code>:</p> <pre><code>bar = 'foo' print bar # works &gt; foo del bar print bar # fails &gt; NameError: name 'bar' is not defined </code></pre> <p>Note that this does not directly deallocate the string object that is <code>'foo'</code>. That's the job of Python's garbage collector which will clean up after you. In almost all circumstances there is however no need to deal with unbinding or the gc explicitely. Just use variables and enjoy the Python livestyle.</p>
0
2016-09-08T09:17:56Z
[ "python" ]
When will a blocking socket timeout?
39,386,917
<p>In the <a href="https://docs.python.org/2/library/socket.html#socket-objects" rel="nofollow">documentation</a> of the <code>socket</code> module it is written that:</p> <blockquote> <p>Sockets are always created in blocking mode. In blocking mode, operations block until complete or the system returns an error (such as connection timed out).</p> </blockquote> <p>Also, <a href="http://stackoverflow.com/a/25448603/501663">this SO answer</a> says:</p> <blockquote> <p>By default, if no explicit timeout is set for the socket, it will block while doing so and eventually timeout, raising exception <code>socket.error: [Errno 110] Connection timed out</code></p> </blockquote> <p>My question is, in what situation a blocking socket (or is it the OS?) will raise a timeout? Can I have some control over this timeout, or is the only thing I can do is to catch the exception?</p> <p><strong>EDIT</strong> Am I mixing the socket timeout with connection timeout? What is the difference?</p>
1
2016-09-08T09:09:59Z
39,388,193
<p>If you not set, Operating System control the connect timeout. TCP/IP in blocking mode have three different timeout:</p> <ul> <li>Connect.</li> <li>Read.</li> <li>Write.</li> </ul> <p>For connect timeout and how TCP/IP connect work, you should checkout <strong>tcp_syn_retries</strong> sustem configuration value on Linux.</p> <p><strong>EDIT</strong>: connect phrase contain some SYNC "handshake" packets while read/write phrase is "normal" packet. That is the difference.</p>
1
2016-09-08T10:11:53Z
[ "python", "sockets", "connection-timeout" ]
Python, how to get the http header
39,386,933
<p>I was making a script to "automate my life" :) but came across an issue that I'm not able to solve.</p> <p>This python script goes scrapes a page and gets the links of the "products" I need, the problem is that once I've the link to the page of the product to download the pdf of this "product" you have to press a button, and that's the issue because there is no href in the button:</p> <pre><code>&lt;Form name="F1" method="POST" action="onSubmit="if($$('btn_download').disabled)return false;$$('btn_download').value='Invia File...';$$('btn_download').disabled=true;return true;"&gt; </code></pre> <p>Looking at the http header when the button is pressed I saw that to download the file it uses a link like this: </p> <pre><code>https://example.com:443/d/vmlz3ovktv2fvxijixczjdagbdnaeamniexu4zypx3tlesibbhuievcy/product.pdf </code></pre> <p>The value "vmlz3ovktv2fvxijixczjdagbdnaeamniexu4zypx3tlesibbhuievcy" changes every day, any suggestion on how to overcome this issue?</p> <p>Is it possible in python to get the http header and parse to get the value? Or to press a button and then handle the download?</p> <p>Many thanks!</p>
0
2016-09-08T09:10:53Z
39,387,014
<p>It doesn't solve the problem of "getting the header", but I would suggest using <a href="http://www.seleniumhq.org/" rel="nofollow">Selenium</a>. It's a web browser automation tool and you can set your script to click on the button.</p> <p>Here's the Selenium reference for Python: <a href="http://selenium-python.readthedocs.io/" rel="nofollow">link</a></p>
0
2016-09-08T09:15:18Z
[ "python", "http", "download", "header", "automation" ]
Python, how to get the http header
39,386,933
<p>I was making a script to "automate my life" :) but came across an issue that I'm not able to solve.</p> <p>This python script goes scrapes a page and gets the links of the "products" I need, the problem is that once I've the link to the page of the product to download the pdf of this "product" you have to press a button, and that's the issue because there is no href in the button:</p> <pre><code>&lt;Form name="F1" method="POST" action="onSubmit="if($$('btn_download').disabled)return false;$$('btn_download').value='Invia File...';$$('btn_download').disabled=true;return true;"&gt; </code></pre> <p>Looking at the http header when the button is pressed I saw that to download the file it uses a link like this: </p> <pre><code>https://example.com:443/d/vmlz3ovktv2fvxijixczjdagbdnaeamniexu4zypx3tlesibbhuievcy/product.pdf </code></pre> <p>The value "vmlz3ovktv2fvxijixczjdagbdnaeamniexu4zypx3tlesibbhuievcy" changes every day, any suggestion on how to overcome this issue?</p> <p>Is it possible in python to get the http header and parse to get the value? Or to press a button and then handle the download?</p> <p>Many thanks!</p>
0
2016-09-08T09:10:53Z
39,387,441
<p>You can use Beautiful Soup for that. <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">Beautiful Soup</a> is a Python library for pulling data out of HTML and XML files.</p>
0
2016-09-08T09:35:12Z
[ "python", "http", "download", "header", "automation" ]
Read a file in python starting with a particular string
39,386,957
<p>I have a file in the following path:</p> <pre><code>/home/[user]/foo_01-01-2016.txt </code></pre> <p>I need to read it using the wild card (*) character:</p> <pre><code>import pandas as pd df = pd.read_csv("/home/[user]/foo_*.txt") </code></pre> <p>But its giving a file not found error.</p>
3
2016-09-08T09:12:24Z
39,387,055
<p>You can use <a href="https://docs.python.org/3.5/library/glob.html" rel="nofollow"><code>glob</code></a>, but output is list, so select first item by <code>[0]</code>:</p> <pre><code>import pandas as pd import glob path =r'/home/[user]' filename = glob.glob(path + "/foo_*.txt") print (filename[0]) df = pd.read_csv(filename[0]) print (df) </code></pre>
1
2016-09-08T09:17:44Z
[ "python", "file", "pandas", "dataframe", "wildcard" ]
IDE pour Python 2.7 ou Python 3
39,386,962
<p>I started it not long ago on <strong>Python</strong> ^^ I'm looking for an <strong>IDE that could directly install the libraries and Packages</strong> that I need without having to install the packages and get them by myself, because I observed some incompatibilities between packages on Windows and on Linux so <strong>I want to know if there is something magical</strong> <strong>that gets me all available</strong> st DEV C ++ for C and C ++.</p> <p>Thank you ;-)</p> <p>PS: I have Pycharm, but it does not offer this, unless I do not know to use it ^^</p> <p>_______________________________French Version ^^__________________________________</p> <p>Bonjour à tous, Je me suis mis il n'y a pas longtemps sur <strong>Python</strong> ^^ , <strong>Je suis à la recherche d'un IDE</strong> qui pourrait m'installer directement les bibliothèques dont j'ai besoin, sans avoir à installer les packages et d'aller les chercher, car j'ai observé certaines incompatibilités de packages entre Windows et LINUX donc je voudrai savoir s'il existe <strong>quelque chose de magique qui me met tout à disposition</strong> tq DEV C++ pour le le langage C et C++. Merci ;-)</p> <p>PS: j'ai Pycharm chez moi, mais il n'offre pas cela, à moins que je ne sais pas trop m'en servir ^^</p>
-4
2016-09-08T09:12:41Z
39,387,850
<p>Je doute fort que tu trouves une telle chose. </p> <p>Python possède une riche panoplie de modules. Énormément on été implémenter aux préalable certains sont standard d'autre ne le sont pas et sont maintenu par divers groupes ou personnes. </p> <p>Hypothétiquement, installer tout les modules que Python propose occuperait une grande quantité de mémoire, c'est même pas certain que tu ai besoin de tout les modules du coup tu les aura installer pour rien.<br> Le plus simple serait d'installer les outils dont tu auras besoin quand tu en auras besoin. </p> <p>En outre même en C il viendra un moment où il va falloir ajouter des bibliothèques tiers tel que SDL, GTK et autre.<br> À mon avis ce que te fourni DEV C++ se sont le outils que MS pense que tu auras besoin pour développer du C et C++ du point de vu du système Windows.</p> <p>Quant à l'incompatibilité en les packets des deux systèmes pourrais-tu donner plus de précision, peut-être des exemples?<br> Et en quoi pensés tu que avoir tout les packets résoudrait ce problème? </p> <p>Aussi pourquoi ne pas avoir posé ta question sur openclassroomu développez; je demande parce ta question risque d'être fermé XD</p>
0
2016-09-08T09:54:23Z
[ "python", "python-2.7", "python-3.x", "ide", "developer-tools" ]
multiclass classification in xgboost (python)
39,386,966
<p>I can't figure out how to pass number of classes or eval metric to xgb.XGBClassifier with the objective function 'multi:softmax'.</p> <p>I looked at many documentations but the only talk about the sklearn wrapper which accepts n_class/num_class.</p> <p>My current setup looks like</p> <pre><code>kf = cross_validation.KFold(y_data.shape[0], \ n_folds=10, shuffle=True, random_state=30) err = [] # to hold cross val errors # xgb instance xgb_model = xgb.XGBClassifier(n_estimators=_params['n_estimators'], \ max_depth=params['max_depth'], learning_rate=_params['learning_rate'], \ min_child_weight=_params['min_child_weight'], \ subsample=_params['subsample'], \ colsample_bytree=_params['colsample_bytree'], \ objective='multi:softmax', nthread=4) # cv for train_index, test_index in kf: xgb_model.fit(x_data[train_index], y_data[train_index], eval_metric='mlogloss') predictions = xgb_model.predict(x_data[test_index]) actuals = y_data[test_index] err.append(metrics.accuracy_score(actuals, predictions)) </code></pre>
1
2016-09-08T09:12:48Z
39,387,627
<p>You don't need to set <code>num_class</code> in the scikit-learn API for XGBoost classification. It is done automatically when <code>fit</code> is called. Look at <a href="https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/sklearn.py" rel="nofollow">xgboost/sklearn.py</a> at the beginning of the <code>fit</code> method of <code>XGBClassifier</code>:</p> <pre><code> evals_result = {} self.classes_ = np.unique(y) self.n_classes_ = len(self.classes_) xgb_options = self.get_xgb_params() if callable(self.objective): obj = _objective_decorator(self.objective) # Use default value. Is it really not used ? xgb_options["objective"] = "binary:logistic" else: obj = None if self.n_classes_ &gt; 2: # Switch to using a multiclass objective in the underlying XGB instance xgb_options["objective"] = "multi:softprob" xgb_options['num_class'] = self.n_classes_ </code></pre>
1
2016-09-08T09:44:08Z
[ "python", "scikit-learn", "xgboost" ]
Python odeint clearly returning wrong solution
39,387,033
<p>Using python 2.7.8.<br> The differential equation I'm working with is x'=2-3*x. Not that difficult. The correct solution is a decaying exponential with a y-intercept of 2/3. Exercise has three initial conditions. Also have to have a slope field with solution on the same plot. I have the slope field, but the solution provided is wrong. A test case of x'=x worked fine but only when t>0. But the solution odeint provided is wrong. Instead of a decaying exponential I'm given what looks like a trig function. Here is the code. </p> <pre><code>#Solutions function def m_diff_sol(input_domain,input_initial_conditions_set): f_set=[] for n in input_initial_conditions_set: m_sol=odeint(m_fst_diff_eq,n,input_domain) f=[b for [a,b] in m_sol] f_set.append(f) return f_set #Vector field function def m_fst_diff_eq(x,t): m,mdot=x return [mdot,2-3*m] </code></pre> <p><a href="http://i.stack.imgur.com/AAJd6.png" rel="nofollow"><img src="http://i.stack.imgur.com/AAJd6.png" alt="enter image description here"></a></p>
1
2016-09-08T09:16:49Z
39,391,462
<p>You want your ODE function to return 1 output, namely</p> <pre><code>def my_ode_func(x,t): return 2.0 - 3.0*x </code></pre> <p>Then <code>odeint</code> gives the expected exponential decay from the initial condition to <code>x=2/3</code>.</p> <pre><code>import numpy as np from scipy.integrate import odeint t = np.arange(0,10.0,0.01) x0 = 1 out1 = odeint(my_ode_func,x0,t) </code></pre> <p><a href="http://i.stack.imgur.com/i1jlI.png" rel="nofollow"><img src="http://i.stack.imgur.com/i1jlI.png" alt="Numerical solution to linear ODE"></a></p> <p>It looks like you're instead modelling something like the second order ODE <code>x''(t) = 2 - 3*x(t)</code>. This would be written as a system of first order ODEs <code>Y(t) = [x(t),x'(t)]</code>, then</p> <pre><code>Y'(t) = [Y[2](t), 2 - 3*Y[1](t)] </code></pre> <p>The code would look something like this:</p> <pre><code>def my_ode_func2(Y,t): return [Y[1],2.0 - 3.0*Y[0]] Y0 = [1,1] out2 = odeint(my_ode_func2,Y0,t) </code></pre> <p><a href="http://i.stack.imgur.com/Acy9Y.png" rel="nofollow"><img src="http://i.stack.imgur.com/Acy9Y.png" alt="Numerical solution to second order ODE"></a></p>
1
2016-09-08T12:51:27Z
[ "python", "ode" ]
Same python function giving different output
39,387,127
<p>I am making a scraping script in python. I first collect the links of the movie from where I have to scrap the songs list. Here is the <strong>movie.txt</strong> list containing movies link</p> <blockquote> <p><a href="https://www.lyricsbogie.com/category/movies/a-flat-2010" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-flat-2010</a> <a href="https://www.lyricsbogie.com/category/movies/a-night-in-calcutta-1970" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-night-in-calcutta-1970</a> <a href="https://www.lyricsbogie.com/category/movies/a-scandall-2016" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-scandall-2016</a> <a href="https://www.lyricsbogie.com/category/movies/a-strange-love-story-2011" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-strange-love-story-2011</a> <a href="https://www.lyricsbogie.com/category/movies/a-sublime-love-story-barsaat-2005" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-sublime-love-story-barsaat-2005</a> <a href="https://www.lyricsbogie.com/category/movies/a-wednesday-2008" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-wednesday-2008</a> <a href="https://www.lyricsbogie.com/category/movies/aa-ab-laut-chalen-1999" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-ab-laut-chalen-1999</a> <a href="https://www.lyricsbogie.com/category/movies/aa-dekhen-zara-2009" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-dekhen-zara-2009</a> <a href="https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1973" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1973</a> <a href="https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1994" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1994</a> <a href="https://www.lyricsbogie.com/category/movies/aabra-ka-daabra-2004" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabra-ka-daabra-2004</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1943" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1943</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1956" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1956</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1968" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1968</a> <a href="https://www.lyricsbogie.com/category/movies/aabshar-1953" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabshar-1953</a></p> </blockquote> <p>Here is my first python function:</p> <pre><code>import requests from bs4 import BeautifulSoup as bs def get_songs_links_for_movies1(): url='https://www.lyricsbogie.com/category/movies/a-flat-2010' source_code = requests.get(url) plain_text = source_code.text soup = bs(plain_text,"html.parser") for link in soup.find_all('h3',class_='entry-title'): href = link.a.get('href') href = href+"\n" print(href) </code></pre> <p>output of the above function:</p> <pre><code>https://www.lyricsbogie.com/movies/a-flat-2010/pyar-itna-na-kar.html https://www.lyricsbogie.com/movies/a-flat-2010/chal-halke-halke.html https://www.lyricsbogie.com/movies/a-flat-2010/meetha-sa-ishq.html https://www.lyricsbogie.com/movies/a-flat-2010/dil-kashi.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html </code></pre> <p>It successfully fetches the songs url of the specified link. But now when I try to automate the process and passes a file <strong>movie.txt</strong> to read url one by one and get the result but its output does not match with the function above in which I add url by myself one by one. Also this function does not get the songs url. Here is my function that does not work correctly.</p> <pre><code>import requests from bs4 import BeautifulSoup as bs def get_songs_links_for_movies(): file = open("movie.txt","r") for url in file: source_code = requests.get(url) plain_text = source_code.text soup = bs(plain_text,"html.parser") for link in soup.find_all('h3',class_='entry-title'): href = link.a.get('href') href = href+"\n" print(href) </code></pre> <p>output of the above function</p> <pre><code>https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html </code></pre> <p>and so on..........</p> <p>By comparing 1st function output and 2nd function output. You clearly see that there is no song url that function 1 fetches and also function 2 repeating the same output again and again.</p> <p>Can Anyone help me in that why is it happening.</p>
0
2016-09-08T09:21:26Z
39,387,730
<p>To understand what is happening, you can print the representation of the url read from the file in the <code>for</code> loop:</p> <pre><code>for url in file: print(repr(url)) ... </code></pre> <p>Printing this representation (and not just the string) makes it easier to see special characters. In this case, the output gave <code>'https://www.lyricsbogie.com/category/movies/a-flat-2010\n'</code>. As you see, there is a line break in the url, so the fetched url is not correct.</p> <p>Use for instance the <code>rstrip()</code> method to remove the newline character, by replacing <code>url</code> by <code>url.rstrip()</code>.</p>
1
2016-09-08T09:48:18Z
[ "python", "web-scraping", "beautifulsoup" ]
Same python function giving different output
39,387,127
<p>I am making a scraping script in python. I first collect the links of the movie from where I have to scrap the songs list. Here is the <strong>movie.txt</strong> list containing movies link</p> <blockquote> <p><a href="https://www.lyricsbogie.com/category/movies/a-flat-2010" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-flat-2010</a> <a href="https://www.lyricsbogie.com/category/movies/a-night-in-calcutta-1970" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-night-in-calcutta-1970</a> <a href="https://www.lyricsbogie.com/category/movies/a-scandall-2016" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-scandall-2016</a> <a href="https://www.lyricsbogie.com/category/movies/a-strange-love-story-2011" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-strange-love-story-2011</a> <a href="https://www.lyricsbogie.com/category/movies/a-sublime-love-story-barsaat-2005" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-sublime-love-story-barsaat-2005</a> <a href="https://www.lyricsbogie.com/category/movies/a-wednesday-2008" rel="nofollow">https://www.lyricsbogie.com/category/movies/a-wednesday-2008</a> <a href="https://www.lyricsbogie.com/category/movies/aa-ab-laut-chalen-1999" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-ab-laut-chalen-1999</a> <a href="https://www.lyricsbogie.com/category/movies/aa-dekhen-zara-2009" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-dekhen-zara-2009</a> <a href="https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1973" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1973</a> <a href="https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1994" rel="nofollow">https://www.lyricsbogie.com/category/movies/aa-gale-lag-jaa-1994</a> <a href="https://www.lyricsbogie.com/category/movies/aabra-ka-daabra-2004" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabra-ka-daabra-2004</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1943" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1943</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1956" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1956</a> <a href="https://www.lyricsbogie.com/category/movies/aabroo-1968" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabroo-1968</a> <a href="https://www.lyricsbogie.com/category/movies/aabshar-1953" rel="nofollow">https://www.lyricsbogie.com/category/movies/aabshar-1953</a></p> </blockquote> <p>Here is my first python function:</p> <pre><code>import requests from bs4 import BeautifulSoup as bs def get_songs_links_for_movies1(): url='https://www.lyricsbogie.com/category/movies/a-flat-2010' source_code = requests.get(url) plain_text = source_code.text soup = bs(plain_text,"html.parser") for link in soup.find_all('h3',class_='entry-title'): href = link.a.get('href') href = href+"\n" print(href) </code></pre> <p>output of the above function:</p> <pre><code>https://www.lyricsbogie.com/movies/a-flat-2010/pyar-itna-na-kar.html https://www.lyricsbogie.com/movies/a-flat-2010/chal-halke-halke.html https://www.lyricsbogie.com/movies/a-flat-2010/meetha-sa-ishq.html https://www.lyricsbogie.com/movies/a-flat-2010/dil-kashi.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html </code></pre> <p>It successfully fetches the songs url of the specified link. But now when I try to automate the process and passes a file <strong>movie.txt</strong> to read url one by one and get the result but its output does not match with the function above in which I add url by myself one by one. Also this function does not get the songs url. Here is my function that does not work correctly.</p> <pre><code>import requests from bs4 import BeautifulSoup as bs def get_songs_links_for_movies(): file = open("movie.txt","r") for url in file: source_code = requests.get(url) plain_text = source_code.text soup = bs(plain_text,"html.parser") for link in soup.find_all('h3',class_='entry-title'): href = link.a.get('href') href = href+"\n" print(href) </code></pre> <p>output of the above function</p> <pre><code>https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html https://www.lyricsbogie.com/movies/ae-dil-hai-mushkil-2016/ae-dil-hai-mushkil-title.html https://www.lyricsbogie.com/movies/m-s-dhoni-the-untold-story-2016/kaun-tujhe.html https://www.lyricsbogie.com/movies/raaz-reboot-2016/raaz-aankhein-teri.html https://www.lyricsbogie.com/albums/akira-2016/baadal-2.html https://www.lyricsbogie.com/movies/baar-baar-dekho-2016/sau-aasmaan.html https://www.lyricsbogie.com/albums/gajanan-2016/gajanan-title.html https://www.lyricsbogie.com/movies/days-of-tafree-2016/jeeley-yeh-lamhe.html https://www.lyricsbogie.com/tv-shows/coke-studio-pakistan-season-9-2016/ala-baali.html https://www.lyricsbogie.com/albums/piya-2016/piya-title.html https://www.lyricsbogie.com/albums/sach-te-supna-2016/sach-te-supna-title.html </code></pre> <p>and so on..........</p> <p>By comparing 1st function output and 2nd function output. You clearly see that there is no song url that function 1 fetches and also function 2 repeating the same output again and again.</p> <p>Can Anyone help me in that why is it happening.</p>
0
2016-09-08T09:21:26Z
39,387,733
<p>I have a doubt that your file is not read as a single line, to be sure, can you test this code:</p> <pre><code>import requests from bs4 import BeautifulSoup as bs def get_songs_links_for_movies(url): print("##Getting songs from %s" % url) source_code = requests.get(url) plain_text = source_code.text soup = bs(plain_text,"html.parser") for link in soup.find_all('h3',class_='entry-title'): href = link.a.get('href') href = href+"\n" print(href) def get_urls_from_file(filename): with open(filename, 'r') as f: return [url for url in f.readlines()] urls = get_urls_from_file("movie.txt") for url in urls: get_songs_links_for_movies(url) </code></pre>
-1
2016-09-08T09:48:28Z
[ "python", "web-scraping", "beautifulsoup" ]
Replace special character in string
39,387,268
<p>I'm having a issue with a problem where I want to replace a special character in a text-file that I have created with a string that I defined.</p> <pre><code>""" This is a guess the number game. """ import datetime, random from random import randint fileOpen = open('text.txt','r') savedData = fileOpen.read() fileOpen.close() #print (savedData) now = datetime.datetime.now() date = now.strftime("%Y-%m-%d") date = str(date) #print(date) time = now.strftime("%H:%M") time = str(time) #print(time) savedData.replace(";", date) print (savedData) </code></pre> <p>I have tried with something that looks like this. I thought I could just read from the file, save it's content in my own string and then use the <code>replace</code> function to alter the string. But when I try to do the last print, noting has happened with the <code>saveData</code> string. What am I doing wrong?</p> <p>The text-file just looks like this, all is on one line:</p> <pre><code>Today it's the ; and the time is (. I'm feeling ) and : is todays lucky number. The unlucky number of today is # </code></pre>
0
2016-09-08T09:27:52Z
39,387,322
<p><a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace</code></a> doesn't alter the string in place, no string operations do because <em>strings are immutable</em>. It returns a copy of the replaced string which you need to assign to another name:</p> <pre><code>replacedData = savedData.replace(";", date) </code></pre> <p>now your replaced string will be saved to the new name you specified in the assignment.</p>
2
2016-09-08T09:30:04Z
[ "python", "string", "python-3.x" ]
Get path to file within a package?
39,387,328
<p>I have a Python package which is organized like this:</p> <pre><code>package |- subpackage | |- code.py | |- window.ui | ... </code></pre> <p>In <code>code.py</code> I want to access the file <code>window.ui</code> via</p> <pre><code>PyQt4.uic.loadUi('window.ui', self) </code></pre> <p>This works well, if I just run <code>code.py</code> with <code>subpackage</code> as the working directory. But if I import the package from another working directory, this file cannot be found:</p> <pre><code>IOError: [Errno 2] No such file or directory: 'window.ui' </code></pre> <p><strong>My question:</strong> How can I get the path name of the directory the file <code>code.py</code> is placed in, in order to create the absolute path name of <code>window.ui</code>. Or, how can I most efficiently access the file <code>window.ui</code>.</p> <p>I tried <code>os.path.abspath('.')</code> from <a href="http://stackoverflow.com/questions/3758866/python-get-path-to-file-in-sister-directory">here</a>, but it only returns the absolute path of the current working directory.</p>
0
2016-09-08T09:30:23Z
39,387,818
<p>Use absolute path of the file instead of relative path.</p> <pre><code>abspath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "window.ui") PyQt4.uic.loadUi(abspath, self) </code></pre>
2
2016-09-08T09:52:24Z
[ "python", "import", "module" ]
Sum digits of numbers in a list
39,387,399
<p>Trying to write a function that takes a list like:</p> <pre><code>x = [1, 13, 14, 9, 8] </code></pre> <p>for example and sums the digits like:</p> <pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27 </code></pre> <p>What I have attempted thus far:</p> <pre><code>def sum_d(x): if not x: return 0 else: return x[0] + sum_d(x[1:]) </code></pre>
-4
2016-09-08T09:33:44Z
39,387,574
<p>How about this beauty:</p> <pre><code>the_sum = sum(int(char) for n in x for char in str(n)) print(the_sum) # prints -&gt; 27 </code></pre> <p>What is happening here is that i am going through all elements of the list one by one (<code>for n in x</code>), i convert them to strings to be able to iterate through each character by character (<code>for char in str(n)</code>) and finally sum all the generated numbers after converting them back to integers (<code>int(char)</code>)</p> <hr> <p>You can easily convert the above into a function like so:</p> <pre><code>def sum_of_characters(my_list): return sum(int(char) for n in my_list for char in str(n)) </code></pre> <hr> <h2><strong>NOTE</strong></h2> <p>As @Jim noticed, the proposed solution here cannot handle negative numbers in the list. Modifying it so that it doesn't throw an error can be done by checking to make sure <code>char</code> is a digit and not a sign:</p> <pre><code>def sum_of_characters(my_list): return sum(int(char) for n in my_list for char in str(n) if char.isdigit()) </code></pre> <p>Making it work though while at the same time keeping it as a single generator expression is quite a task..</p> <hr> <p>Just for the record, an other variant that just uses a generator expression and can handle negative numbers that are either &lt; 10 or would break up like so: -14 -> -1 <strong>+</strong> 4 is this:</p> <pre><code>def sum_of_characters(my_list): return eval('+'.join(str(char) for n in x for char in str(n))) </code></pre>
6
2016-09-08T09:41:57Z
[ "python", "list", "python-3.x" ]
Sum digits of numbers in a list
39,387,399
<p>Trying to write a function that takes a list like:</p> <pre><code>x = [1, 13, 14, 9, 8] </code></pre> <p>for example and sums the digits like:</p> <pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27 </code></pre> <p>What I have attempted thus far:</p> <pre><code>def sum_d(x): if not x: return 0 else: return x[0] + sum_d(x[1:]) </code></pre>
-4
2016-09-08T09:33:44Z
39,387,576
<pre><code>x = [1,13,14,9,8] number = 0 for element in x: my_string = str(element) for i in range(len(my_string)): number += int(my_string[i]) print(number) </code></pre> <p>This will do it, there might be a way to slice ints that doesn't involve converting them to strings though.</p>
0
2016-09-08T09:41:58Z
[ "python", "list", "python-3.x" ]
Sum digits of numbers in a list
39,387,399
<p>Trying to write a function that takes a list like:</p> <pre><code>x = [1, 13, 14, 9, 8] </code></pre> <p>for example and sums the digits like:</p> <pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27 </code></pre> <p>What I have attempted thus far:</p> <pre><code>def sum_d(x): if not x: return 0 else: return x[0] + sum_d(x[1:]) </code></pre>
-4
2016-09-08T09:33:44Z
39,387,628
<p>A slight modification, and your original code will work :</p> <pre><code>def sum_d(x): x = str(x) if len(x) == 1: return int(x) else: return int(x[0]) + sum_d(int(x[1:])) </code></pre> <p>also possible in single line :</p> <pre><code>sum(int(y) for y in (chain(*[str(x) for x in [1, 13, 14, 9, 8]]))) </code></pre> <p>Explained here :</p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; [str(x) for x in [1, 13, 14, 9, 8]] ['1', '13', '14', '9', '8'] &gt;&gt;&gt; chain(*[str(x) for x in [1, 13, 14, 9, 8]]) &lt;itertools.chain object at 0x7feadcd067d0&gt; &gt;&gt;&gt; list(chain(*[str(x) for x in [1, 13, 14, 9, 8]])) ['1', '1', '3', '1', '4', '9', '8'] &gt;&gt;&gt; sum(int(y) for y in (chain(*[str(x) for x in [1, 13, 14, 9, 8]]))) 27 </code></pre>
1
2016-09-08T09:44:09Z
[ "python", "list", "python-3.x" ]
Sum digits of numbers in a list
39,387,399
<p>Trying to write a function that takes a list like:</p> <pre><code>x = [1, 13, 14, 9, 8] </code></pre> <p>for example and sums the digits like:</p> <pre><code>1 + (1+3) + (1+4) + 9 + 8 = 27 </code></pre> <p>What I have attempted thus far:</p> <pre><code>def sum_d(x): if not x: return 0 else: return x[0] + sum_d(x[1:]) </code></pre>
-4
2016-09-08T09:33:44Z
39,387,676
<pre><code>def sumx(x): for i in range(0,len(x)): if(x[i]&gt;10): sum=0 while(x[i]&gt;0): sum+=x[i]%10 x[i]=x[i]/10 x[i]=sum print(x) &gt;&gt;&gt; sumx(x) [5, 4, 5, 9, 8] </code></pre>
0
2016-09-08T09:46:02Z
[ "python", "list", "python-3.x" ]
ElementTree XML parsing from UTF-8 source file
39,387,403
<p>I have this XML file with utf-8 encoding.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Items&gt; &lt;Item&gt; &lt;Cikkszam&gt;00008&lt;/Cikkszam&gt; &lt;EAN/&gt; &lt;Megjegyzes&gt;BISK&lt;/Megjegyzes&gt; &lt;Leiras1&gt;Bisk Ontario, Dakota szappantartóhoz&lt;/Leiras1&gt; &lt;Leiras2&gt;műanyag betét&lt;/Leiras2&gt; &lt;CikkTipus&gt;07 &lt;/CikkTipus&gt; &lt;ME_&gt;db &lt;/ME_&gt; &lt;Tipus&gt;Választható&lt;/Tipus&gt; &lt;A_ar&gt;338&lt;/A_ar&gt; &lt;B_ar&gt;0&lt;/B_ar&gt; &lt;C_ar&gt;0&lt;/C_ar&gt; &lt;D_ar&gt;0&lt;/D_ar&gt; &lt;E_ar&gt;0&lt;/E_ar&gt; &lt;Tenyl_keszl_&gt;0&lt;/Tenyl_keszl_&gt; &lt;Visszaig_&gt;0&lt;/Visszaig_&gt; &lt;Diszponalt&gt;0&lt;/Diszponalt&gt; &lt;Szabad_keszlet&gt;0&lt;/Szabad_keszlet&gt; &lt;/Item&gt; &lt;/Items&gt; </code></pre> <p>I have this Python code:</p> <pre><code>from xml.etree.ElementTree import ElementTree #import xml.etree.ElementTree items = ElementTree().parse('proba.xml'.encode('utf8')) #items = xml.etree.ElementTree.parse('proba.xml') products = items.findall("Item") for product in products: print product.find("Leiras1").text </code></pre> <p>When I run my script file I got the next error message:</p> <pre class="lang-none prettyprint-override"><code>C:\Python27&gt;python read_xml_orig.py Bisk Ontario, Dakota szappantartóhoz Bisk Álló Wc kefe és papír tartó talpas Bisk sarok szappantartó króm Bisk sarok szappantartó króm Bisk üveg pohár pót Bisk ONTARIO üveg folyékony Bisk ONTARIO üveg polc Bisk ONTARIO dupla Bisk ONTARIO rud Traceback (most recent call last): File "read_xml_orig.py", line 7, in &lt;module&gt; print product.find("Leiras1").text File "C:\Python27\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u0151' in position 21: character maps to &lt;undefined&gt; </code></pre>
0
2016-09-08T09:33:53Z
39,387,675
<p><code>'proba.xml'.encode('utf8')</code> encodes the string <code>'proba.xml'</code> as UTF-8. It does nothing to the file of the same name.</p> <p>When the file really is encoded as UTF-8 then your code will work:</p> <pre><code>from xml.etree.ElementTree import ElementTree doc = ElementTree().parse('proba.xml') products = doc.findall("Item") for product in products: print product.find("Leiras1").text </code></pre> <p>which prints this for me</p> <pre><code>Bisk Ontario, Dakota szappantartóhoz </code></pre> <p><strong>However</strong>, if your file is not really UTF-8 then you might get encoding errors during <code>.parse()</code>.</p> <p>In this case you must figure out what encoding the file is in and correct the XML declaration accordingly. Hint: A likely encoding candidate for Hungarian is <code>Windows-1250</code>.</p>
0
2016-09-08T09:46:02Z
[ "python", "xml", "parsing", "utf-8" ]
group list elements based on another list
39,387,435
<p>I have two list: <code>inp</code> and <code>base</code>. i want to add each item in <code>inp</code> to a list in <code>out</code> based on position in <code>base</code> variable. this code works fine:</p> <pre><code>from pprint import pprint as print num = 3 out = [[] for i in range(num)] inp = [[1,1],[2,1],[3,2],[7,11],[9,99],[0,-1]] base = [0,1,0,2,0,1] for i, num in enumerate(base): out[num].append(inp[i]) print(out,width=40) </code></pre> <p>result:</p> <pre><code>[[[1, 1], [3, 2], [9, 99]], [[2, 1], [0, -1]], [[7, 11]]] </code></pre> <p>i want to do this using <strong><em>numpy</em></strong> module(np.array and np.append or etc.). Can anyone help me?</p>
1
2016-09-08T09:35:00Z
39,387,728
<p>Assuming <code>base</code>and <code>inp</code> as NumPy arrays, we could do something like this -</p> <pre><code># Get sorted indices for base sidx = base.argsort() # Get where the sorted version of base changes groups split_idx = np.flatnonzero(np.diff(base[sidx])&gt;0)+1 # OR np.unique(base[sidx],return_index=True)[1][1:] # Finally sort inp based on the sorted indices and split based on split_idx out = np.split(inp[sidx], split_idx) </code></pre> <hr> <p>To make it work for lists, we need few tweaks, mainly the indexing part, for which we can use <code>np.take</code> to replace the indexing into arrays as listed in the earlier approach. So, the modified version would be -</p> <pre><code>sidx = np.argsort(base) split_idx = np.flatnonzero(np.diff(np.take(base,sidx))&gt;0)+1 out = np.split(np.take(inp,sidx,axis=0), split_idx) </code></pre>
0
2016-09-08T09:48:11Z
[ "python", "arrays", "numpy" ]
Error while running TensorBox ReInspect implementation on TensorFlow
39,387,558
<p>I am trying to train TensorBox ReInspect implementation (<a href="https://github.com/Russell91/TensorBox/" rel="nofollow">https://github.com/Russell91/TensorBox/</a>) on my machine with one GPU (NVidia GeForce GTX 750 Ti). When I run the <code>train.py</code> script:</p> <pre><code>python train.py --hypes hypes/overfeat_rezoom.json --gpu 0 --logdir output </code></pre> <p>I get the following error:</p> <pre><code>Traceback (most recent call last): File "train.py", line 543, in &lt;module&gt; main() File "train.py", line 540, in main train(H, test_images=[]) File "train.py", line 453, in train smooth_op, global_step, learning_rate, encoder_net) = build(H, q) File "train.py", line 346, in build boxes_loss[phase]) = build_forward_backward(H, x, encoder_net, phase, boxes, flags) File "train.py", line 245, in build_forward_backward pred_confidences, pred_confs_deltas, pred_boxes_deltas) = build_forward(H, x, googlenet, phase, reuse) File "train.py", line 167, in build_forward lstm_outputs = build_lstm_inner(H, lstm_input) File "train.py", line 50, in build_lstm_inner state = tf.zeros([batch_size, lstm.state_size]) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 1136, in zeros shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape") File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 628, in convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 163, in constant tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape)) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 354, in make_tensor_proto nparray = np.array(values, dtype=np_dt) ValueError: setting an array element with a sequence. </code></pre> <p>This does not happen if I run the same code on a machine without GPU and just on CPU. </p> <p>What can be the cause of this error? Is there any way to debug it?</p>
1
2016-09-08T09:41:13Z
39,424,451
<p>It appeared that the problem was because of state_is_true flag. Refer this thread for the solution: <a href="https://github.com/Russell91/TensorBox/issues/59#issuecomment-245566316" rel="nofollow">https://github.com/Russell91/TensorBox/issues/59#issuecomment-245566316</a></p>
0
2016-09-10T09:04:55Z
[ "python", "tensorflow" ]
Celery cannot find a worker
39,387,670
<p>I'm using celery with such configuration</p> <pre><code>default_exchange = Exchange('default', type='direct') latest_exchange = Exchange('latest', type='direct') shared_celery_config = { 'BROKER_URL': 'redis://localhost:6379/0', 'CELERY_RESULT_BACKEND': 'redis://localhost:6379/0', 'CELERY_DEFAULT_EXCHANGE': 'default', 'CELERY_DEFAULT_ROUTING_KEY': 'default', 'CELERY_DEFAULT_QUEUE': 'default', 'CELERY_QUEUES': ( Queue('default', default_exchange, routing_key='default'), Queue('latest', latest_exchange, routing_key='latest'), ), } celery = Celery('tasks', config_source=shared_celery_config) </code></pre> <p>But when I'm creating a task none of the worker is consuming it and nothing happens. I start workers with: <code>celery worker -A tasks --loglevel=debug --hostname=worker1</code>. I can see them from <code>ps aux | grep celery</code> output, but when executing some command to get statistics like <code>celery -A tasks status</code> I get following error message <strong><code>Error: No nodes replied within time constraint.</code></strong>. Therefore all tasks are in <em>PENDING</em> status. I believe this is some misconfiguration, but can't figure out what's wrong and how to debug such a thing. Any advise would be very helpful</p>
0
2016-09-08T09:45:58Z
39,390,292
<p>The issue was resolved. I have an web application which uses gevent and in <code>tasks</code> module I have import from another module that has <code>monkey.patch_all()</code>. Somehow it prevents billiard and therefore a worker to start pool and that leads to this consequences. Anyway, <strong>do not use gevent at all</strong>, imho.</p>
0
2016-09-08T11:57:16Z
[ "python", "python-2.7", "celery", "python-2.x", "celeryd" ]
not displaying old value when editing cell in a QTableWidget
39,387,842
<p>I have a basic QTableWidget, created with this python code:</p> <pre><code>from silx.gui import qt app = qt.QApplication([]) qtw = qt.QTableWidget() qtw.show() qtw.setColumnCount(8) qtw.setRowCount(7) app.exec_() </code></pre> <p>The <code>from silx.gui import qt</code> line is just a wrapper that finds out the installed qt wrapper (PyQt4, PyQt5 or PySide) and flattens the qt namespace.</p> <p>The resulting table has a strange behavior when I edit a cell: as expected, the old text is highligted when I double-click the cell, but the unusual behavior is that the old text remains visible and the new text overlaps with the old one while I'm typing it, until I press enter or I click another cell.</p> <p>I would like the old text to disappear as soon as I start typing the new one. I know it's possible, because I have an example of program that features a qTableWidget with the behavior I would like to have. </p> <p>But I cannot find where in that program the cell editing behavior is altered. How can I do this?</p> <p>Example of "spam" and "eggs" overlayed.</p> <p>[<img src="http://i.stack.imgur.com/Fx5tO.png" alt="example of &quot;spam&quot; and &quot;eggs&quot; overlayed[1]"></p> <p>EDIT: the code sample without the wrapper business</p> <pre><code>from PyQt5.Qt import QApplication, QTableWidget, qVersion app =QApplication([]) print(qVersion()) qtw = QTableWidget() qtw.show() qtw.setColumnCount(8) qtw.setRowCount(7) app.exec_() </code></pre> <p>With PyQt4, use this import (also remove the <code>print(qVersion())</code> line):</p> <pre><code>from PyQt4.QtGui import QApplication, QTableWidget </code></pre>
1
2016-09-08T09:53:57Z
39,388,920
<p>You could try connecting the signal emited by QTableWidget <code>cellClicked(int row, int column)</code> with a slot created for clearing the entry. <br><a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html#connecting-disconnecting-and-emitting-signals" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html#connecting-disconnecting-and-emitting-signals</a></p>
0
2016-09-08T10:46:36Z
[ "python", "qt", "pyqt", "qtablewidget" ]
not displaying old value when editing cell in a QTableWidget
39,387,842
<p>I have a basic QTableWidget, created with this python code:</p> <pre><code>from silx.gui import qt app = qt.QApplication([]) qtw = qt.QTableWidget() qtw.show() qtw.setColumnCount(8) qtw.setRowCount(7) app.exec_() </code></pre> <p>The <code>from silx.gui import qt</code> line is just a wrapper that finds out the installed qt wrapper (PyQt4, PyQt5 or PySide) and flattens the qt namespace.</p> <p>The resulting table has a strange behavior when I edit a cell: as expected, the old text is highligted when I double-click the cell, but the unusual behavior is that the old text remains visible and the new text overlaps with the old one while I'm typing it, until I press enter or I click another cell.</p> <p>I would like the old text to disappear as soon as I start typing the new one. I know it's possible, because I have an example of program that features a qTableWidget with the behavior I would like to have. </p> <p>But I cannot find where in that program the cell editing behavior is altered. How can I do this?</p> <p>Example of "spam" and "eggs" overlayed.</p> <p>[<img src="http://i.stack.imgur.com/Fx5tO.png" alt="example of &quot;spam&quot; and &quot;eggs&quot; overlayed[1]"></p> <p>EDIT: the code sample without the wrapper business</p> <pre><code>from PyQt5.Qt import QApplication, QTableWidget, qVersion app =QApplication([]) print(qVersion()) qtw = QTableWidget() qtw.show() qtw.setColumnCount(8) qtw.setRowCount(7) app.exec_() </code></pre> <p>With PyQt4, use this import (also remove the <code>print(qVersion())</code> line):</p> <pre><code>from PyQt4.QtGui import QApplication, QTableWidget </code></pre>
1
2016-09-08T09:53:57Z
39,396,773
<p>Generally, edit behavior is controlled via <code>QItemDelegates</code>. Typically, this is done to provide more advanced editing, or to filter input data or perform some side effects (like update a database) when edits are made. But you can also use it to just clear the editor presented to the user when editing.</p> <pre><code>class MyDelegate(QItemDelegate): def setEditorData(self, editor, index): # Normally, this would set the text of the editor to the current # value of the cell. If you do nothing here, it will be blank. editor.clear() qtw = QTableWidget() delegate = MyDelegate(qtw) qtw.setItemDelegate(delegate) </code></pre>
0
2016-09-08T17:15:04Z
[ "python", "qt", "pyqt", "qtablewidget" ]
CSV Files in Python (Sliding Window)
39,387,857
<p>I am a beginner to Python, I need a help with manipulating csv files in Python. I am trying to do sliding window mechanism for each row in dataset.</p> <p>for an example if the dataset is this</p> <pre><code>timestamp | temperature | windspeed 965068200 9.61883 60.262 965069100 9.47203 60.1664 965070000 9.31125 60.0145 965070900 9.13649 59.8064 </code></pre> <p>and if user specified window size is 3,the result should be something like </p> <pre><code>timestamp | temperature-2 | temperature-1 |temperature-0 | windspeed-2 | windspeed-1 | windspeed-0 965070000 9.61883 9.47203 9.31125 60.262 60.1664 60.0145 965070900 9.47203 9.31125 9.13649 60.1664 60.0145 59.8064 </code></pre> <p>I could do this by using List of ObjectsArray in Java.Reading CSV and generate new CSV which it contains transformed dataset. Here is the code <a href="http://pastebin.com/cQnTBg8d" rel="nofollow">http://pastebin.com/cQnTBg8d</a> #researh</p> <p>I need to do this in Python , please help me to solve this.</p> <p><em>Thank you</em></p>
2
2016-09-08T09:54:43Z
39,388,379
<p><strong>This answer assumes you are using Python 3.x - for Python 2.x some changes are required (some obvious places are commented)</strong></p> <p>For the data format in the question, this could be a starting point in Python:</p> <pre><code>import collections def slide(infile,outfile,window_size): queue=collections.deque(maxlen=window_size) line=infile.readline() headers=[s.strip() for s in line.split("|")] row=[headers[0]] for h in headers[1:] for i in reversed(range(window_size)): row.append("%s-%i"%(h,i)) outfile.write(" | ".join(row)) outfile.write("\n") for line in infile: queue.append(line.split()) if len(queue)==window_size: row=[queue[-1][0]] for j in range(1,len(headers)): for old in queue: row.append(old[j]) outfile.write("\t".join(row)) outfile.write("\n") ws=3 with open("infile.csv","r") as inf: with open("outfile.csv","w") as outf: slide(inf,outf,ws) </code></pre> <p>actually this code is all about using a queue to keep the input rows for the window and not more - everything else is text-to-list-to-text.</p> <p>With actual csv-data (see comment)</p> <pre><code>import csv import collections def slide(infile,outfile,window_size): r=csv.reader(infile) w=csv.writer(outfile) queue=collections.deque(maxlen=window_size) headers=next(r) # r.next() on python 2 l=[headers[0]] for h in headers[1:] for i in reversed(range(window_size)): l.append("%s-%i"%(h,i)) w.writerow(l) hrange=range(1,len(headers)) for row in r: queue.append(row) if len(queue)==window_size: l=[queue[-1][0]] for j in hrange: for old in queue: l.append(old[j]) w.writerow(l) ws=3 with open("infile.csv","r") as inf: # rb and no newline param on python 2 with open("outfile.csv","w") as outf: # wb and no newline param on python 2 slide(inf,outf,ws) </code></pre>
1
2016-09-08T10:19:38Z
[ "java", "python", "csv", "dataset", "pycharm" ]
pandas divide row value by aggregated sum with a condition set by other cell
39,387,954
<p>Hi Hoping to get some help, I have two columns Dataframe <code>df</code> as; </p> <pre><code>Source ID 1 2 2 3 1 2 1 2 1 3 3 1 </code></pre> <p>My intention is to group the Source and divide the ID cell by total based on the grouped Source and attach this to the orginial dataframe so the new column would look like;</p> <pre><code> Source ID ID_new 1 2 2/9 2 3 3/3 1 2 2/9 1 2 2/9 1 3 3/9 3 1 3/1 </code></pre> <p>I've gotten as far as;</p> <pre><code>df.groupby('Source ID')['ID'].sum() </code></pre> <p>to get the total for <code>ID</code> but Im not sure where to go next. </p>
1
2016-09-08T09:59:21Z
39,388,025
<p>try this:</p> <pre><code>In [79]: df.assign(ID_new=df.ID/df.groupby('Source').ID.transform('sum')) Out[79]: Source ID ID_new 0 1 2 0.222222 1 2 3 1.000000 2 1 2 0.222222 3 1 2 0.222222 4 1 3 0.333333 5 3 1 1.000000 </code></pre> <p>if you need it as a new <strong>persistent</strong> column you can do it as @jezrael proposed in the <a href="http://stackoverflow.com/questions/39387954/pandas-divide-row-value-by-aggregated-sum-with-a-condition-set-by-other-cell/39388025?noredirect=1#comment66102743_39388025">comment</a>:</p> <pre><code>In [81]: df['ID_new'] = df.ID/df.groupby('Source').ID.transform('sum') In [82]: df Out[82]: Source ID ID_new 0 1 2 0.222222 1 2 3 1.000000 2 1 2 0.222222 3 1 2 0.222222 4 1 3 0.333333 5 3 1 1.000000 </code></pre>
1
2016-09-08T10:02:50Z
[ "python", "pandas", "dataframe", "group-by" ]
How do I get Django to log why an sql transaction failed?
39,387,983
<p>I am trying to debug a Pootle (pootle is build on django) installation which fails with a django transaction error whenever I try to add a template to an existing language. Using the python debugger I can see that it fails when pootle tries to save a model as well as all the queries that have been made in that session.</p> <p>What I can't see is <em>what specifically causes the save to fail</em>. I figure pootle/django must have added some database database constraint, how do I figure out which one? MySql (the database being used) apparently can't log just failed transactions.</p>
0
2016-09-08T10:01:02Z
39,447,127
<p>Install django debug toolbar, you can easily check all of the queries that have been executed</p>
1
2016-09-12T09:24:35Z
[ "python", "mysql", "django", "pootle" ]
Writing elements to one2many from another model?
39,387,996
<p>How can we pass data's to one2many field where my data's are from another model. I have written like these but error is showing.</p> <p>I am accessing these function through button.</p> <pre><code>@api.multi def action_order(self): rec= self.env['purchase.order'].create({ 'partner_id' : self.vendors.id, 'store_id' : self.store_id.id, 'purchase_order_type' : self.order_type, 'date_order' : self.date_order, 'date_planned' : self.date_order, 'type' : self.type, 'order_line' : (0, 0, [{'brand_id' : self.product_brand_id, 'product_id' : self.purchase_product_id, 'part_number' : self.product_part_number, 'name' : self.desc, 'date_planned' : self.date_order, 'product_qty' : self.quantity_no, 'price_unit' : self.product_price_unit, 'product_uom' : self.product_measure.id, }]) }) </code></pre> <p>My error log is like these</p> <p>Server Error</p> <pre><code>Traceback (most recent call last): File "/opt/ 9/ /openerp/http.py", line 643, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/opt/ 9/ /openerp/http.py", line 680, in dispatch result = self._call_function(**self.params) File "/opt/ 9/ /openerp/http.py", line 316, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/ 9/ /openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/opt/ 9/ /openerp/http.py", line 309, in checked_call result = self.endpoint(*a, **kw) File "/opt/ 9/ /openerp/http.py", line 959, in __call__ return self.method(*args, **kw) File "/opt/ 9/ /openerp/http.py", line 509, in response_wrap response = f(*args, **kw) File "/opt/ 9/ /addons/web/controllers/main.py", line 896, in call_button action = self._call_kw(model, method, args, {}) File "/opt/ 9/ /addons/web/controllers/main.py", line 884, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 381, in old_api result = method(recs, *args, **kwargs) File "/opt/ 9/custom/trunk/floating_purchase_order/models/floating.py", line 57, in action_purchase_order if self.action_order(): File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/custom/trunk/floating_purchase_order/models/floating.py", line 99, in action_order 'product_uom' : self.product_measure.id, File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /addons/purchase/purchase.py", line 180, in create return super(PurchaseOrder, self).create(vals) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /addons/mail/models/mail_thread.py", line 232, in create thread = super(MailThread, self).create(values) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/models.py", line 4151, in create record = self.browse(self._create(old_vals)) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 490, in new_api result = method(self._model, cr, uid, *args, **old_kwargs) File "/opt/ 9/ /openerp/models.py", line 4336, in _create result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or [] File "/opt/ 9/ /openerp/osv/fields.py", line 823, in set if act[0] == 0: TypeError: 'int' object has no attribute '__getitem__' </code></pre>
0
2016-09-08T10:01:47Z
39,389,986
<p>The value for <code>order_line</code> has to be a list of triplets. For creating new entries you need triplets in form <code>(0, 0, value_dictionary)</code></p> <p>So change your code to:</p> <pre class="lang-py prettyprint-override"><code>'order_line' : [(0, 0, { 'brand_id' : self.product_brand_id, 'product_id' : self.purchase_product_id, 'part_number' : self.product_part_number, 'name' : self.desc, 'date_planned' : self.date_order, 'product_qty' : self.quantity_no, 'price_unit' : self.product_price_unit, 'product_uom' : self.product_measure.id, })] </code></pre>
0
2016-09-08T11:41:42Z
[ "python", "openerp" ]
Writing elements to one2many from another model?
39,387,996
<p>How can we pass data's to one2many field where my data's are from another model. I have written like these but error is showing.</p> <p>I am accessing these function through button.</p> <pre><code>@api.multi def action_order(self): rec= self.env['purchase.order'].create({ 'partner_id' : self.vendors.id, 'store_id' : self.store_id.id, 'purchase_order_type' : self.order_type, 'date_order' : self.date_order, 'date_planned' : self.date_order, 'type' : self.type, 'order_line' : (0, 0, [{'brand_id' : self.product_brand_id, 'product_id' : self.purchase_product_id, 'part_number' : self.product_part_number, 'name' : self.desc, 'date_planned' : self.date_order, 'product_qty' : self.quantity_no, 'price_unit' : self.product_price_unit, 'product_uom' : self.product_measure.id, }]) }) </code></pre> <p>My error log is like these</p> <p>Server Error</p> <pre><code>Traceback (most recent call last): File "/opt/ 9/ /openerp/http.py", line 643, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/opt/ 9/ /openerp/http.py", line 680, in dispatch result = self._call_function(**self.params) File "/opt/ 9/ /openerp/http.py", line 316, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/ 9/ /openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/opt/ 9/ /openerp/http.py", line 309, in checked_call result = self.endpoint(*a, **kw) File "/opt/ 9/ /openerp/http.py", line 959, in __call__ return self.method(*args, **kw) File "/opt/ 9/ /openerp/http.py", line 509, in response_wrap response = f(*args, **kw) File "/opt/ 9/ /addons/web/controllers/main.py", line 896, in call_button action = self._call_kw(model, method, args, {}) File "/opt/ 9/ /addons/web/controllers/main.py", line 884, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 381, in old_api result = method(recs, *args, **kwargs) File "/opt/ 9/custom/trunk/floating_purchase_order/models/floating.py", line 57, in action_purchase_order if self.action_order(): File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/custom/trunk/floating_purchase_order/models/floating.py", line 99, in action_order 'product_uom' : self.product_measure.id, File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /addons/purchase/purchase.py", line 180, in create return super(PurchaseOrder, self).create(vals) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /addons/mail/models/mail_thread.py", line 232, in create thread = super(MailThread, self).create(values) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/models.py", line 4151, in create record = self.browse(self._create(old_vals)) File "/opt/ 9/ /openerp/api.py", line 248, in wrapper return new_api(self, *args, **kwargs) File "/opt/ 9/ /openerp/api.py", line 490, in new_api result = method(self._model, cr, uid, *args, **old_kwargs) File "/opt/ 9/ /openerp/models.py", line 4336, in _create result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or [] File "/opt/ 9/ /openerp/osv/fields.py", line 823, in set if act[0] == 0: TypeError: 'int' object has no attribute '__getitem__' </code></pre>
0
2016-09-08T10:01:47Z
39,397,230
<p>It looks like the the item '<strong>self.product_measure.id</strong>' for '<strong>product_uom</strong>' is creating the problem. It seems it is an 'Integer' field and you are trying to access 'id' out of it.</p>
0
2016-09-08T17:46:57Z
[ "python", "openerp" ]
COnvert number to letter
39,388,041
<p>i had install module <strong>num2words</strong> this is my code :</p> <pre><code>from num2words import num2words </code></pre> <p>class HrHolidays(models.Model): _inherit = 'hr.holidays'</p> <pre><code>interim = fields.Many2one( 'hr.employee', string="Interim") partner_id = fields.Many2one('res.partner', string="Customer") remaining_leaves = fields.Integer(compute='_get_remaining_days', string='Leaves') number_text=fields.Char(string='Nombre de jour') @api.multi def _get_remaining_days(self, name, args): res = super(HrHolidays, self)._get_remaining_days(name, args) return res def calculatenumber(self, number_of_days_temp,lang='fr'): number_text = num2words(number_of_days_temp,lang) return {'value': {'number_text': number_text}} </code></pre> <p><strong>.xml</strong></p> <pre><code> &lt;xpath expr="//field[@name='interim']" position="after"&gt; &lt;field name="number_of_days_temp" nolabel="1" on_change="calculatenumber(number_of_days_temp)"/&gt; &lt;/xpath&gt; &lt;field name="number_of_days_temp" position="after"&gt; &lt;field name="number_text"/&gt; &lt;/field&gt; </code></pre> <p>i got this error i dont know how to solve it <a href="http://i.stack.imgur.com/dKpsw.png" rel="nofollow"><img src="http://i.stack.imgur.com/dKpsw.png" alt="enter image description here"></a></p>
0
2016-09-08T10:03:39Z
39,638,043
<p>verify the definition of the function</p> <pre><code>def calculatenumber(self,cr, uid, ids,number_of_days_temp, context=None): number_text = num2words(number_of_days_temp,lang='fr') return {'value': {'number_text': number_text}} </code></pre> <p>or you can use the new api</p> <pre><code>@api.onchange('number_of_days_temp') def calculatenumber(self): self.number_text = num2words(self.number_of_days_temp,lang='fr') </code></pre> <p>then you must remove <code>on_change="calculatenumber(number_of_days_temp)"</code> from your XML view</p>
0
2016-09-22T11:41:29Z
[ "python", "odoo-8" ]
How to change a string into a formatted string?
39,388,072
<p>I want to change a source string: </p> <pre><code>str1 = 'abc-ccd_2013' </code></pre> <p>into the following target string:</p> <pre><code>str2 = 'abc\-ccd\_2013'. </code></pre> <p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p> <p>The following method is not working:</p> <pre><code> &gt;&gt;&gt; str1 'abc-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace('-','\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace(r'-',r'\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; </code></pre>
1
2016-09-08T10:05:32Z
39,388,352
<p>Your code does work and can be combined to a single expression:</p> <pre><code>&gt;&gt;&gt; print("abc-ccd_2013".replace("-","\-").replace("_","\_")) abc\-ccd\_2013 </code></pre> <p>Note the difference of <code>print</code> vs <code>repr</code>:</p> <pre><code>&gt;&gt;&gt; "abc-ccd_2013".replace("-","\-").replace("_","\_") 'abc\\-ccd\\_2013' </code></pre> <p>Is equivalent to:</p> <pre><code>&gt;&gt;&gt; print(repr("abc-ccd_2013".replace("-","\-").replace("_","\_"))) 'abc\\-ccd\\_2013' </code></pre>
2
2016-09-08T10:18:23Z
[ "python", "console" ]
How to change a string into a formatted string?
39,388,072
<p>I want to change a source string: </p> <pre><code>str1 = 'abc-ccd_2013' </code></pre> <p>into the following target string:</p> <pre><code>str2 = 'abc\-ccd\_2013'. </code></pre> <p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p> <p>The following method is not working:</p> <pre><code> &gt;&gt;&gt; str1 'abc-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace('-','\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace(r'-',r'\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; </code></pre>
1
2016-09-08T10:05:32Z
39,388,365
<p>This works. When printing raw string, '\' is replaced with '\\' so it does not interpret it as escape character used for e.g. endline character '\n', tab character '\t' and so on. Try command <code>print str2</code> or <code>print a1</code> and it will be fine.</p> <p>Update: Even stackoverflow replaces '\\' with '\', so instead I have to type '\\\' (to type this I had to use 5 slashes) :D</p>
1
2016-09-08T10:18:55Z
[ "python", "console" ]
How to change a string into a formatted string?
39,388,072
<p>I want to change a source string: </p> <pre><code>str1 = 'abc-ccd_2013' </code></pre> <p>into the following target string:</p> <pre><code>str2 = 'abc\-ccd\_2013'. </code></pre> <p>All <code>'-'</code> should be replaced with <code>'\-'</code> and all <code>'_'</code> should be replaced into <code>'\_'</code>.</p> <p>The following method is not working:</p> <pre><code> &gt;&gt;&gt; str1 'abc-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace("-","\-") &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace('-','\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; a1 = str1.replace(r'-',r'\-') &gt;&gt;&gt; a1 'abc\\-ccd_2013' &gt;&gt;&gt; </code></pre>
1
2016-09-08T10:05:32Z
39,388,788
<p>You could also do the following : </p> <pre><code>str1 = 'abc-ccd_2013' repl = ('-', '\-'), ('_', '\_') print reduce(lambda a1, a2: a1.replace(*a2), repl, str1) </code></pre> <p>You will have to use the print function to get your desired result.</p>
0
2016-09-08T10:39:48Z
[ "python", "console" ]
IntegrityError : (1048, "Column 'user_dob' cannot be null")
39,388,335
<p>I have modified my serializers fields by as follow,</p> <pre><code>class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='user_id') name = serializers.CharField(source='get_name') email = serializers.EmailField(source='user_email') dob = serializers.DateField(source='user_dob') contactNo = serializers.CharField(source='user_mobileno') image = serializers.CharField(source='user_image') bloodGroup = serializers.CharField(source='user_blood_group') location = serializers.CharField(source='user_location_id.location_name') profession = serializers.CharField(source='user_profession') fbId = serializers.CharField(source='user_fb_id') userId = serializers.CharField(source='user_random_id') class Meta: model = UserInfo # fields = ['user_id','get_name'] fields = ["id", "name", "email", "dob", "contactNo", "image", "bloodGroup", "location", "profession", "fbId", "userId"] </code></pre> <p>Now when i make a create request using following code form views.py,</p> <pre><code>def create(self, request, *args, **kwargs): # partial = kwargs.pop('partial', True) serializer = self.get_serializer(data=request.data, partial=True) print("kwargs------------&gt;",serializer) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # headers = self.get_success_headers(serializer.data) response = { "status" : status.HTTP_201_CREATED, "message" : "User Created.", "response" : serializer.data } return Response(response) </code></pre> <p>It's giving me the following error</p> <pre><code>IntegrityError: (1048, "Column 'user_dob' cannot be null") </code></pre> <p>Even after setting <strong>partial=True</strong> its not working.</p> <p><strong>PUT</strong> request is also not working, Its not updating the data</p> <pre><code>def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) # serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) response = { "status" : status.HTTP_200_OK, "message" : "User Detail Updated.", "response" : serializer.data } return Response(response) </code></pre> <p>Can anyone help me wth this?</p> <p>Following are my post params</p> <p><a href="http://i.stack.imgur.com/MKgah.png" rel="nofollow"><img src="http://i.stack.imgur.com/MKgah.png" alt="enter image description here"></a></p>
3
2016-09-08T10:17:36Z
39,396,681
<p>Since you are using a serializer that maps your "user_dob" field with "dob" you should pass parameter according to name provided in serialzers.</p>
2
2016-09-08T17:08:37Z
[ "python", "django", "django-rest-framework" ]
How to prevent all writes to disk from within python
39,388,531
<p>When doing automated tests, I like to make sure my script does not write any data to the disk. I am doing tests on the script as a whole, not unit tests of individual functions.</p> <p><strong>Is there a way to intercept all Disk-IO that a python script performs from within this script?</strong></p> <p>Obviously, I can mock the open function (e.g. with the mock package <a href="http://www.voidspace.org.uk/python/mock/helpers.html?#mock-open" rel="nofollow">http://www.voidspace.org.uk/python/mock/helpers.html?#mock-open</a> ) but the problem is that I need to know in what module the open happens. I have to mock <code>__main__.open</code> as well as <code>__module1.open</code> and <code>module2.open</code> and so on. The problem is that I do not know what modules will write to files.</p>
0
2016-09-08T10:27:12Z
39,388,594
<p>If mocking <code>open</code> is enough, you can stick the mock into the <a href="https://docs.python.org/3/library/builtins.html" rel="nofollow"><code>builtins</code> module</a>; this is the module that is consulted for all built-in functions:</p> <pre><code>with mock.patch('builtins.open', mock_open()): # ... </code></pre> <p>In Python 2, the module was called <a href="https://docs.python.org/2/library/__builtin__.html" rel="nofollow"><code>__builtin__</code></a>.</p> <p>Note that this doesn't necessarily catch all writes; anything that uses <code>os.open()</code> to use OS filehandles directly or uses <code>io.open()</code> or <code>codecs.open()</code> could still end up writing to disk.</p>
1
2016-09-08T10:30:43Z
[ "python" ]
IndexError: list index out of range python
39,388,551
<p>The follwoing code takes a log file and re-writes it in csv format: </p> <pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu") DataFile = open("C:\\Scripts\\MFGData90.csv","a+") for line in file.readlines(): #print line line=line.strip() numbers=line.split() #print numbers #print numbers[0] #alpha = numbers [0] #print alpha StartHour= numbers[0] StartMinute= numbers[1] StartDay=numbers[2] StartMonth=numbers[3] StartYear=numbers[4] EndHour=numbers[5] EndMinute=numbers[6] Meters=numbers[10] #float(Meters) #round(Meters) #int(Meters) #print "before if "+Meters if Meters &gt; "0.1": #print "after if "+Meters print StartDay+"/"+StartMonth+"/"+StartYear+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+","+Meters+"\n" #DataFile.write (StartDay+"/"+StartMonth+"/"+StartYear+","+"90"+","+Meters+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+"\n") DataFile.close() file.close() </code></pre> <p>example log file: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>example output: </p> <pre><code>5/9/2016,12:49,15:14,219.682 6/9/2016,11:12,11:45,83.691 6/9/2016,11:46,11:56,41.125 7/9/2016,12:33,12:54,50.823 </code></pre> <p>but when the log file contains non integer characters like this: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 NAME 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>iget the follwing error:</p> <pre><code>Traceback (most recent call last): File "C:\Scripts\test.py", line 12, in &lt;module&gt; StartMinute= numbers[1] IndexError: list index out of range </code></pre> <p>where did i go wrong? thanks!</p>
0
2016-09-08T10:28:19Z
39,388,649
<p>after <code>numbers=line.split()</code> add a line with this test: <code>if len(numbers) &lt; 11: continue</code></p>
0
2016-09-08T10:33:06Z
[ "python" ]
IndexError: list index out of range python
39,388,551
<p>The follwoing code takes a log file and re-writes it in csv format: </p> <pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu") DataFile = open("C:\\Scripts\\MFGData90.csv","a+") for line in file.readlines(): #print line line=line.strip() numbers=line.split() #print numbers #print numbers[0] #alpha = numbers [0] #print alpha StartHour= numbers[0] StartMinute= numbers[1] StartDay=numbers[2] StartMonth=numbers[3] StartYear=numbers[4] EndHour=numbers[5] EndMinute=numbers[6] Meters=numbers[10] #float(Meters) #round(Meters) #int(Meters) #print "before if "+Meters if Meters &gt; "0.1": #print "after if "+Meters print StartDay+"/"+StartMonth+"/"+StartYear+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+","+Meters+"\n" #DataFile.write (StartDay+"/"+StartMonth+"/"+StartYear+","+"90"+","+Meters+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+"\n") DataFile.close() file.close() </code></pre> <p>example log file: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>example output: </p> <pre><code>5/9/2016,12:49,15:14,219.682 6/9/2016,11:12,11:45,83.691 6/9/2016,11:46,11:56,41.125 7/9/2016,12:33,12:54,50.823 </code></pre> <p>but when the log file contains non integer characters like this: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 NAME 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>iget the follwing error:</p> <pre><code>Traceback (most recent call last): File "C:\Scripts\test.py", line 12, in &lt;module&gt; StartMinute= numbers[1] IndexError: list index out of range </code></pre> <p>where did i go wrong? thanks!</p>
0
2016-09-08T10:28:19Z
39,388,723
<p>So what do you want do to with the line with <code>NAME</code></p> <p>In fact when your script read it, you have :</p> <pre><code>&gt;&gt;&gt; line = "NAME" &gt;&gt;&gt; line = line.strip() &gt;&gt;&gt; numbers = line.split() &gt;&gt;&gt; numbers ['NAME'] </code></pre> <p>And therefore <code>numbers[1]</code> will raise an error as there is only one element in <code>numbers</code></p> <p>You might want to <code>continue</code> with the next line when there is not enough <code>numbers</code> in <code>line</code>:</p> <pre><code>if len(numbers) &lt; 11: continue </code></pre>
0
2016-09-08T10:36:57Z
[ "python" ]
IndexError: list index out of range python
39,388,551
<p>The follwoing code takes a log file and re-writes it in csv format: </p> <pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu") DataFile = open("C:\\Scripts\\MFGData90.csv","a+") for line in file.readlines(): #print line line=line.strip() numbers=line.split() #print numbers #print numbers[0] #alpha = numbers [0] #print alpha StartHour= numbers[0] StartMinute= numbers[1] StartDay=numbers[2] StartMonth=numbers[3] StartYear=numbers[4] EndHour=numbers[5] EndMinute=numbers[6] Meters=numbers[10] #float(Meters) #round(Meters) #int(Meters) #print "before if "+Meters if Meters &gt; "0.1": #print "after if "+Meters print StartDay+"/"+StartMonth+"/"+StartYear+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+","+Meters+"\n" #DataFile.write (StartDay+"/"+StartMonth+"/"+StartYear+","+"90"+","+Meters+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+"\n") DataFile.close() file.close() </code></pre> <p>example log file: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>example output: </p> <pre><code>5/9/2016,12:49,15:14,219.682 6/9/2016,11:12,11:45,83.691 6/9/2016,11:46,11:56,41.125 7/9/2016,12:33,12:54,50.823 </code></pre> <p>but when the log file contains non integer characters like this: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 NAME 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>iget the follwing error:</p> <pre><code>Traceback (most recent call last): File "C:\Scripts\test.py", line 12, in &lt;module&gt; StartMinute= numbers[1] IndexError: list index out of range </code></pre> <p>where did i go wrong? thanks!</p>
0
2016-09-08T10:28:19Z
39,388,791
<pre><code>file = open("tst") DataFile = open("tst_csv.csv","a+") desired_size = 6 for line in file.readlines(): #print line line=line.strip() numbers=line.split() if not len(numbers) &gt;= desired_size: continue #print numbers[0] #alpha = numbers [0] #print alpha StartHour= numbers[0] StartMinute= numbers[1] StartDay=numbers[2] StartMonth=numbers[3] StartYear=numbers[4] EndHour=numbers[5] EndMinute=numbers[6] Meters=numbers[10] #Meters = int(round(float(Meters))) not sure if you wanted to do this &lt;--, int(), round(), float() etc... return copies and do not modify the original print "before if "+Meters if Meters &gt; 0.1: #print "after if "+Meters print StartDay+"/"+StartMonth+"/"+StartYear+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+","+Meters+"\n" #DataFile.write (StartDay+"/"+StartMonth+"/"+StartYear+","+"90"+","+Meters+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+"\n") DataFile.close() file.close() </code></pre>
-1
2016-09-08T10:40:01Z
[ "python" ]
IndexError: list index out of range python
39,388,551
<p>The follwoing code takes a log file and re-writes it in csv format: </p> <pre><code>file = open("C:\\Scripts\\logs\\SteelUsage2.bsu") DataFile = open("C:\\Scripts\\MFGData90.csv","a+") for line in file.readlines(): #print line line=line.strip() numbers=line.split() #print numbers #print numbers[0] #alpha = numbers [0] #print alpha StartHour= numbers[0] StartMinute= numbers[1] StartDay=numbers[2] StartMonth=numbers[3] StartYear=numbers[4] EndHour=numbers[5] EndMinute=numbers[6] Meters=numbers[10] #float(Meters) #round(Meters) #int(Meters) #print "before if "+Meters if Meters &gt; "0.1": #print "after if "+Meters print StartDay+"/"+StartMonth+"/"+StartYear+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+","+Meters+"\n" #DataFile.write (StartDay+"/"+StartMonth+"/"+StartYear+","+"90"+","+Meters+","+StartMinute+":"+StartHour+","+EndMinute+":"+EndHour+"\n") DataFile.close() file.close() </code></pre> <p>example log file: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>example output: </p> <pre><code>5/9/2016,12:49,15:14,219.682 6/9/2016,11:12,11:45,83.691 6/9/2016,11:46,11:56,41.125 7/9/2016,12:33,12:54,50.823 </code></pre> <p>but when the log file contains non integer characters like this: </p> <pre><code> 49 12 5 9 2016 14 15 5 9 2016 219.682 NAME 14 15 5 9 2016 15 15 5 9 2016 0 12 11 6 9 2016 45 11 6 9 2016 83.691 46 11 6 9 2016 56 11 6 9 2016 41.125 6 11 7 9 2016 7 11 7 9 2016 0 7 11 7 9 2016 8 11 7 9 2016 0 32 12 7 9 2016 32 12 7 9 2016 0 33 12 7 9 2016 54 12 7 9 2016 50.823 </code></pre> <p>iget the follwing error:</p> <pre><code>Traceback (most recent call last): File "C:\Scripts\test.py", line 12, in &lt;module&gt; StartMinute= numbers[1] IndexError: list index out of range </code></pre> <p>where did i go wrong? thanks!</p>
0
2016-09-08T10:28:19Z
39,388,915
<p>You take line after line of your log and split is in separate parts. (11 in your case).</p> <p>So if you want to access a part of the line which doesn't exist, you get an error. Try checking every line if it has all parts and access then.</p> <p>I wouldn't suggest using continue, because its considered as bad practice. It's better to explicitly do your stuff only when the number of elements is right.</p> <pre><code>numbers = line.split() if len(numbers) &gt;= 11: // Do your stuff </code></pre>
-1
2016-09-08T10:46:28Z
[ "python" ]
Several static directories for tornado
39,388,641
<p>We are building uServices based on tornado. There are some routes which are common for all uServices, for the time being <code>health</code> and <code>docs</code>. The docs route is built using <code>Swagger</code>. That means, the swagger route, and associated assets, are part of our common library (but not the documentation itself, which is uService related), which is simply a requirement to our uServices.</p> <p>Since swagger needs static assets, and each uService needs its own static assets too, I have a problem: my static assets are coming from two completely different places. I have found a (very inconvenient) hack to solve this:</p> <ol> <li>track static assets in the common repo</li> <li>track static assets in the uService repo</li> <li>when deploying, copy those static assets, from both sources, to a deployment static folder (and hope that there are no clashes)</li> <li>specify the deployment static folder as the <code>static_path</code></li> </ol> <p>Step 3 is quite complex, because it involves pip-installing the common library, finding the assets there (already a hack), and copying them around:</p> <ul> <li>install the common library with pip</li> <li>look for the location of the installed library (<code>site-packages</code>)</li> <li>copy the static assets to the deployment static folder</li> </ul> <p>It would be much easier if, as happens with the <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.get_template_path" rel="nofollow"><code>template_path</code></a>, it would be possible to have a per-application static folder:</p> <pre><code>&gt; Return None to load templates relative to the calling file. </code></pre> <p>I have been searching the web, and it seems <a href="http://stackoverflow.com/a/3935046/647991">this is not possible</a>, but I wanted to double check.</p> <p>An alternative would be to simplify asset extracting from a packaged python module, but not sure what is the preferred method to do this, without having to recur to hacks searching in the <code>virtualenv</code> for the <code>site-packages</code>.</p>
0
2016-09-08T10:32:41Z
39,391,070
<p>It's not possible to do this with the <code>static_path</code> setting, but as long as you don't require the <code>static_url()</code> function, you can create multiple <code>StaticFileHandler</code> entries in your URLSpec list:</p> <pre><code>Application([ ('/static1/(.*)', tornado.web.StaticFileHandler, dict(path='static1')), ('/static2/(.*)', tornado.web.StaticFileHandler, dict(path='static1')), ]) </code></pre> <p>As a substitute for <code>static_url</code>, you can call <code>StaticFileHandler.make_static_url</code> and pass it the arguments that would have been global if you were using <code>static_path</code>.</p>
1
2016-09-08T12:34:41Z
[ "python", "tornado", "assets" ]
Pandas groupwise percentage
39,388,820
<p>How can I calculate a group-wise percentage in pandas?</p> <p>similar to <a href="http://stackoverflow.com/questions/23627782/pandas-groupby-size-and-percentages">Pandas: .groupby().size() and percentages</a> or <a href="http://stackoverflow.com/questions/29299078/pandas-very-simple-percent-of-total-size-from-group-by">Pandas Very Simple Percent of total size from Group by</a> I want to calculate the percentage of a value per group.</p> <p>How can I achieve this?</p> <p>My dataset is structured like</p> <pre><code>ClassLabel, Field </code></pre> <p>Initially, I aggregate on both <code>ClassLbel</code> and <code>Field</code> like</p> <pre><code>grouped = mydf.groupby(['Field', 'ClassLabel']).size().reset_index() grouped = grouped.rename(columns={0: 'customersCountPerGroup'}) </code></pre> <p>Now I would like to know the percentage of customers in each group on a per group basis. The groups total can be obtained like <code>mydf.groupby(['Field']).size()</code> but I neither can merge that as a column nor am I sure this is the right approach - there must be something simpler.</p> <h1>edit</h1> <p>I want to calculate the percentage only based on a single group e.g. 3 0 0.125 1 0.250 the sum of 0 + 1 --> 0.125 + 0.250 = 0,375 and use this value to devide / normalize grouped and not grouped.sum() <a href="http://i.stack.imgur.com/XpiVo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XpiVo.jpg" alt="enter image description here"></a></p>
-1
2016-09-08T10:41:51Z
39,389,016
<p>IIUC you can use:</p> <pre><code>mydf = pd.DataFrame({'Field':[1,1,3,3,3], 'ClassLabel':[4,4,4,4,4], 'A':[7,8,9,5,7]}) print (mydf) A ClassLabel Field 0 7 4 1 1 8 4 1 2 9 4 3 3 5 4 3 4 7 4 3 grouped = mydf.groupby(['Field', 'ClassLabel']).size() print (grouped) Field ClassLabel 1 4 2 3 4 3 dtype: int64 print (100 * grouped / grouped.sum()) Field ClassLabel 1 4 40.0 3 4 60.0 dtype: float64 </code></pre> <hr> <pre><code>grouped = mydf.groupby(['Field', 'ClassLabel']).size().reset_index() grouped = grouped.rename(columns={0: 'customersCountPerGroup'}) print (grouped) Field ClassLabel customersCountPerGroup 0 1 4 2 1 3 4 3 grouped['per'] = 100 * grouped.customersCountPerGroup / grouped.customersCountPerGroup.sum() print (grouped) Field ClassLabel customersCountPerGroup per 0 1 4 2 40.0 1 3 4 3 60.0 </code></pre> <p>EDIT by comment:</p> <pre><code>mydf = pd.DataFrame({'Field':[1,1,3,3,3,4,5,6], 'ClassLabel':[0,0,0,1,1,0,0,6], 'A':[7,8,9,5,7,5,6,4]}) print (mydf) grouped = mydf.groupby(['Field', 'ClassLabel']).size() df = grouped / grouped.sum() df = (grouped / df.groupby(level=0).transform('sum')).reset_index(name='new') print (df) Field ClassLabel new 0 1 0 8.000000 1 3 0 2.666667 2 3 1 5.333333 3 4 0 8.000000 4 5 0 8.000000 5 6 6 8.000000 </code></pre>
3
2016-09-08T10:51:10Z
[ "python", "pandas", "group-by", "percentage" ]
Error in model prediction using hmmlearn
39,388,890
<p>Hi I have a dataframe test, I am trying to predict using a Gaussian HMM with hmmlearn.</p> <p>When I do this:</p> <pre><code>y = model.predict(test) y </code></pre> <p>I get the hmm working fine producing and array of states</p> <p>however if i do this:</p> <pre><code>for i in range(0,len(test)): y = model.predict(test[:i]) </code></pre> <p>all I get is y being set to 1.</p> <p>Can anyone help?</p> <p>UPDATE</p> <p>here is the code that does work iterating through</p> <p>The training set was 0-249:</p> <pre><code>for i in range(251,len(X)): test = X[:i] y = model.predict(test) print(y[len(y)-1]) </code></pre>
0
2016-09-08T10:45:11Z
39,405,552
<p>HMM models sequences of observations. If you feed a single observation into <code>predict</code> (which does <a href="https://en.wikipedia.org/wiki/Viterbi_algorithm" rel="nofollow">Viterbi decoding</a> by default) you essentially reduce the prediction to the <code>argmax</code> over</p> <pre><code>(model.startprob_ * model.predict_proba(test[i:i + 1])).argmax() </code></pre> <p>which can be dominated by <code>startprob_</code>, e.g. if <code>startprob = [10**-8, 1 - 10**-8]</code>. This could explain the all-ones behaviour you're seeing.</p>
1
2016-09-09T06:57:37Z
[ "python", "pandas", "numpy", "hmmlearn" ]
Python: Concatenating scipy sparse matrix
39,388,902
<p>I am trying to Concatenate 2 sparse matrix by the help of hstack function. xtrain_cat is the output of DictVectorizer(encodes categorical values) and xtrain_num is a pandas cvs file.</p> <pre><code> xtrain_num = sparse.csr_matrix(xtrain_num) print type(xtrain_num) print xtrain_cat.shape print xtrain_num.shape x_train_data = hstack(xtrain_cat,xtrain_num) </code></pre> <p>Error :</p> <pre><code>(1000, 2778) &lt;class 'scipy.sparse.csr.csr_matrix'&gt; &lt;class 'scipy.sparse.csr.csr_matrix'&gt; (1000, 2778) (1000, 968) Traceback (most recent call last): File "D:\Projects\Zohair\Bosch\Bosch.py", line 360, in &lt;module&gt; x_train_data = hstack(xtrain_cat,xtrain_num) File "C:\Users\Public\Documents\anaconda2\lib\site-packages\scipy\sparse\construct.py", line 464, in hstack return bmat([blocks], format=format, dtype=dtype) File "C:\Users\Public\Documents\anaconda2\lib\site-packages\scipy\sparse\construct.py", line 547, in bmat raise ValueError('blocks must be 2-D') ValueError: blocks must be 2-D </code></pre> <p>Can someone identify what is the probelm</p>
1
2016-09-08T10:45:47Z
39,389,831
<p>You should try:</p> <pre><code>x_train_data = hstack((xtrain_cat,xtrain_num)) </code></pre> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html" rel="nofollow">It takes a sequence</a>:</p> <blockquote> <p><strong>blocks</strong> sequence of sparse matrices with compatible shapes</p> </blockquote> <hr> <p>When I define <code>a</code> to be a sparse matrix, I can verify your error when I omit it (and correct it when I add it):</p> <pre><code>In [19]: sparse.hstack(a, a) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-19-7c450ab4fda0&gt; in &lt;module&gt;() ----&gt; 1 sparse.hstack(a, a) /usr/local/lib/python2.7/dist-packages/scipy/sparse/construct.pyc in hstack(blocks, format, dtype) 454 455 """ --&gt; 456 return bmat([blocks], format=format, dtype=dtype) 457 458 /usr/local/lib/python2.7/dist-packages/scipy/sparse/construct.pyc in bmat(blocks, format, dtype) 537 538 if blocks.ndim != 2: --&gt; 539 raise ValueError('blocks must be 2-D') 540 541 M,N = blocks.shape ValueError: blocks must be 2-D In [20]: sparse.hstack((a, a)) Out[20]: &lt;3x8 sparse matrix of type '&lt;type 'numpy.float64'&gt;' with 0 stored elements in COOrdinate format&gt; </code></pre>
3
2016-09-08T11:33:06Z
[ "python", "scipy", "sparse-matrix" ]
rpy2 can not import R package with rJava--mac
39,388,994
<p>I want to use rpy2 import R package 'iqspr' which I have aleady installed and test on my Rstudio, this package works fine. </p> <p>Here are the errors I am getting.</p> <pre><code>from rpy2.robjects.packages import importr java=importr('rJava') iqspr=importr('iqspr') </code></pre> <p>errors </p> <pre><code>/Library/Python/2.7/site-packages/rpy2-2.8.3-py2.7-macosx-10.11-intel.egg/rpy2/rinterface/__init__.py:185: RRuntimeWarning: Error : .onLoad failed in loadNamespace() for 'rJava', details: call: dyn.load(file, DLLpath = DLLpath, ...) error: unable to load shared object '/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so': dlopen(/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib Referenced from: /usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so Reason: image not found warnings.warn(x, RRuntimeWarning) /Library/Python/2.7/site-packages/rpy2-2.8.3-py2.7-macosx-10.11-intel.egg/rpy2/rinterface/__init__.py:185: RRuntimeWarning: Error: .onLoad failed in loadNamespace() for 'rJava', details: call: dyn.load(file, DLLpath = DLLpath, ...) error: unable to load shared object '/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so': dlopen(/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib Referenced from: /usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so Reason: image not found warnings.warn(x, RRuntimeWarning) Traceback (most recent call last): File "/Users/yang/Desktop/Chemical compounds design important materials/chemical_compound_design.py", line 4, in &lt;module&gt; java=importr('rJava') File "/Library/Python/2.7/site-packages/rpy2-2.8.3-py2.7-macosx-10.11-intel.egg/rpy2/robjects/packages.py", line 453, in importr env = _get_namespace(rname) rpy2.rinterface.RRuntimeError: Error: .onLoad failed in loadNamespace() for 'rJava', details: call: dyn.load(file, DLLpath = DLLpath, ...) error: unable to load shared object '/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so': dlopen(/usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so, 6): Library not loaded: @rpath/libjvm.dylib Referenced from: /usr/local/lib/R/3.3/site-library/rJava/libs/rJava.so Reason: image not found </code></pre>
0
2016-09-08T10:49:51Z
39,430,503
<p>Issues involving RStudio and rJava were reported in the past (for example <a href="http://stackoverflow.com/questions/30738974/rjava-load-error-in-rstudio-r-after-upgrading-to-osx-yosemite">rJava load error in RStudio/R after &quot;upgrading&quot; to OSX Yosemite</a>), and it is quite possible that the cause is similar.</p> <p>Try doing</p> <pre><code>export LD_LIBRARY_PATH=/usr/local/lib/R/3.3/site-library/rJava/libs/:{LD_LIBRARY_PATH} </code></pre> <p>before starting Python.</p>
0
2016-09-10T20:57:18Z
[ "python", "rpy2", "rjava" ]
Django Rest Framework : Fields are not getting create or update after making custom methods inside models
39,389,134
<pre><code>class UserInfo(models.Model): user_id = models.AutoField(primary_key=True) user_firstname = models.CharField(max_length=20, verbose_name = "First Name") user_lastname = models.CharField(max_length=20, verbose_name = "Last Name") user_email = models.EmailField(max_length=50, verbose_name = "Email Id") user_dob = models.DateField(auto_now = False, auto_now_add=False, verbose_name = "Date of Birth") user_mobileno = models.CharField(max_length=14, verbose_name = "Contact No") user_image = models.ImageField(upload_to = upload_location, null=True, blank=True, width_field = "width_field", height_field = "height_field", verbose_name = "Profile Picture") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) user_password = models.CharField(max_length=20, verbose_name = "Password") user_blood_group = models.CharField(max_length=5, verbose_name = "Blood Group") user_location_id = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name = "Current Location") user_profession = models.CharField(max_length=20, verbose_name = "Profession") user_fb_id = models.CharField(max_length=20, verbose_name = "Facebook Contact", blank=True) user_random_id = models.CharField(max_length=20, verbose_name = "Registration Id") user_created_date = models.DateField(auto_now = True, auto_now_add=False) user_updated_date = models.DateField(auto_now = True, auto_now_add=False) def get_name(self): return "%s %s" % (self.user_firstname, self.user_lastname) def __str__(self): return "%s %s" % (self.user_firstname, self.user_lastname) </code></pre> <p>Not when i made following post request, it's saving user_firstname &amp; lastname and even not updating. And get_name method returning " ".</p> <p>Folowing is my serializer</p> <pre><code>class UserSerializer(serializers.ModelSerializer): name = serializers.CharField(source='get_name') class Meta: model = UserInfo fields = ['user_id','name'] </code></pre> <p>Can anyone help to out this?</p>
3
2016-09-08T10:56:54Z
39,396,877
<p>Pass the parameters for creating object according to name defined in serializer that will work as you have desired make sure you pass values for all the parameters that can not be null. Now incase you want user to pass the parameter name instead of user_firstname &amp; user_lastname you will need to get the value for name while creating &amp; split name to get firstname &amp; lastname &amp; assign it to user_firstname &amp; user_lastname.</p>
2
2016-09-08T17:21:57Z
[ "python", "django", "django-rest-framework" ]
Python post to remote host
39,389,265
<p>Hi I want to write robot to register in toefl test , I send request to remote web site as:</p> <pre><code>from django.http import HttpResponse import requests from bs4 import BeautifulSoup from django.middleware import csrf def index(request): session = requests.Session() page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do') if request.method == 'POST': url = 'https://toefl-registration.ets.org/TOEFLWeb/logon.do' data = { 'password': request.POST.get('password', ''), 'username': request.POST.get('username', ''), 'org.apache.struts.taglib.html.TOKEN': request.POST.get('org.apache.struts.taglib.html.TOKEN', '') } page = session.post(url, data=data) return HttpResponse(request,page.text) </code></pre> <p>My post request is not same as post request made by toefl original web site and instead of login shows error as : We are sorry, our servers are currently busy. Please wait a few minutes and retry your request.</p> <p>what is the problem? someone in other corporation did this without error</p>
1
2016-09-08T11:04:27Z
39,416,200
<p>you should make sure that you enter cookies correctly like:</p> <pre><code>def index(request): response = HttpResponse() if 'JSESSIONID' in request.COOKIES: print('1') else: session = requests.Session() page = session.get('https://toefl-registration.ets.org/TOEFLWeb/extISERLogonPrompt.do') cookie = page.cookies for c in cookie: response.set_cookie(c.name, c.value) iud = '1' if request.method == 'POST': url = 'https://toefl-registration.ets.org/TOEFLWeb/logon.do' iud = '2' page = requests.post(url, data=data, cookies=request.COOKIES) cookie = page.cookies response.write(pageReader(request, page.text, iud)) return response </code></pre>
0
2016-09-09T16:42:11Z
[ "python", "django" ]
Trend curve through data jumps back and forth when it should be smooth
39,389,442
<p>I want to plot a trend curve of my data points. I did that with this code with an exponential model: </p> <pre><code>with open(file,'r') as csvfile: plots = csv.reader(csvfile, delimiter=',') next(plots) x=[] y=[] for row in plots: x.append(float(row[1])) y.append(float(row[3])) plt.plot(x, y, 'ro',label="Original Data") x = np.array(x, dtype=float) #transform your data in a numpy array of floats y = np.array(y, dtype=float) #so the curve_fit can work def func(x, a, b, c): return (a*np.exp(-b*x)+c) popt, pcov = curve_fit(func, x, y) ypredict=func(x, *popt) plt.plot(x, ypredict, '--', label="Fitted Curve") plt.legend(loc='upper left') plt.show() </code></pre> <p>But I obtained this result:</p> <p><img src="http://i.stack.imgur.com/wktjr.png" alt="enter image description here">]</p> <p><strong>Question</strong></p> <p>How can I obtain a smooth trend curve through this data?</p>
1
2016-09-08T11:13:31Z
39,390,711
<p>One way, you can put <code>x.sort()</code> in before plotting:</p> <pre><code>x.sort() ypredict=func(x, *popt) </code></pre> <p>Another way would be to use something like this (better for a plot in my opinion),</p> <pre><code># 1000 evenly spaced points over the range of x values x_plot = np.linspace(x.min(), x.max(), 1000) y_plot=func(x_plot, *popt) </code></pre> <p>Then use <code>x_plot</code> and <code>y_plot</code> for your trend line and it should look fine. The problem is very-likely that your <code>x</code> values are not monotone and so your line plot is connecting points in the order they appear in <code>x</code>. </p>
0
2016-09-08T12:18:23Z
[ "python", "curve", "points", "trend" ]
Javascript generators in Scala.js
39,389,447
<p>Currently I use Transcrypt to generate Javascript code from Python code. In this way I'm able to implement generators in Python like:</p> <pre><code>def color(): colors = ["red", "blue", "yellow"] i = -1 while True: i += 1 if i &gt;= colors.length: i = 0 reset = yield colors[i] if reset: i = -1 gen = color() console.log(next(gen)) # red console.log(gen.js_next(True).value) # red console.log(next(gen)) # blue console.log(next(gen)) # yellow console.log(next(gen)) # red </code></pre> <p>which will be compiled to Javascript like:</p> <pre><code>var color = function* () { var colors = list (['red', 'blue', 'yellow']); var i = -(1); while (true) { i++; if (i &gt;= colors.length) { var i = 0; } var reset = yield colors [i]; if (reset) { var i = -(1); } } }; var gen = color (); console.log (py_next (gen)); console.log (gen.next (true).value); console.log (py_next (gen)); console.log (py_next (gen)); console.log (py_next (gen)); </code></pre> <p>But since I have also Scala knowledge (and an Scala-application which I would like to implement in the browser) I'm looking to Scala.js. But as far as I know this generator construct is not possible in Scala, and the corresponding <code>yield</code> keyword is used in a different way.</p> <p>Is the generator syntax possible in Scala.js, or am I forced to use Python and Transcrypt if I want this?</p>
0
2016-09-08T11:13:51Z
39,390,565
<p>I believe the general concept you are looking for is Continuations. It's a fairly large and complex topic unto itself -- they used to be talked about more, but have largely been supplanted by the easier-to-use async library. But the <a href="https://index.scala-lang.org/scala/scala-continuations" rel="nofollow">scala-continuations library</a> is still around, and discussed various places online -- for example, <a href="https://blog.knoldus.com/2016/05/04/time-travel-in-scala-cps-in-scala-scalas-continuation/" rel="nofollow">this article</a>, or <a href="https://medium.com/@anicolaspp/c-yield-return-and-scala-continuations-d2a6917aa6d4#.1zeftpiue" rel="nofollow">this one</a>.</p>
0
2016-09-08T12:11:24Z
[ "javascript", "python", "scala", "scala.js", "transcrypt" ]
Install SWIGged Python library into dist-packages/myfoo.py, not dist-packages/myfoo/myfoo.py
39,389,556
<p>I have a directory structure like</p> <pre><code> setup.py myfoo/ myfoo.i myfoo.cpp myfoo.hpp </code></pre> <p>with <code>setup.py</code>,</p> <pre><code>from distutils.core import setup, Extension setup( name='myfoo', ext_modules=[ Extension( '_myfoo', [ 'myfoo/myfoo.cpp', 'myfoo/myfoo.i' ], swig_opts=['-c++'], ) ], version='0.0.1', packages=['myfoo'], requires=[] ) </code></pre> <p><code>myfoo.hpp</code></p> <pre><code>#ifndef MYFOO_HPP #define MYFOO_HPP int myfoo(); #endif // MYFOO_HPP </code></pre> <p><code>myfoo.cpp</code></p> <pre><code>#include "myfoo.hpp" #include &lt;iostream&gt; int myfoo() { std::cout &lt;&lt; "hey!" &lt;&lt; std::endl; return 42; } </code></pre> <p>When running <code>python setup.py install</code>, the package builds correctly and installs the files</p> <pre><code>/usr/local/lib/python2.7/dist-packages/ _myfoo.so myfoo/ myfoo.py myfoo.pyc </code></pre> <p>By default, only <code>/usr/local/lib/python2.7/dist-packages/</code> is in the <code>$PYTHONPATH</code>, so <code>import myfoo</code> from anywhere yields an import error. For that to work, either both <code>myfoo.py[c]</code> should be in <code>/usr/local/lib/python2.7/dist-packages/</code> or be renamed to <code>__init__.py</code>. It seems that I didn't call <code>setup.py</code> correctly.</p> <p>Any hints?</p>
0
2016-09-08T11:19:36Z
39,393,365
<p>Removing</p> <pre><code>packages=['myfoo'], </code></pre> <p>and adding</p> <pre><code>py_modules = ['myfoo'], package_dir = {'' : 'myfoo'} </code></pre> <p>to <code>setup.py</code> does the trick.</p>
0
2016-09-08T14:17:50Z
[ "python", "c++", "swig", "distutils" ]
How to work "if np.array([False]):"
39,389,581
<p>The output of the following code is <strong>NOTHING</strong>.</p> <pre><code>if np.array([False]): print("hello") </code></pre> <p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p> <p>The following is a case of a pure array.</p> <pre><code>if [False]: print("hello") </code></pre> <p>The output is <code>hello</code></p> <p>Would you tell me how to code np.array?</p>
1
2016-09-08T11:20:56Z
39,389,687
<p><code>if [False]:</code> will always be <code>True</code> because <code>[Flase]</code> is a list with one item (i.e., non-empty), so the <code>if</code> block will be entered and you will see the output of your <code>print</code> call. </p> <p><code>np.array([False])</code></p> <p>returns a <code>numpy.ndarray</code>, which in this case evaluates to <code>False</code>, so the <code>if</code> block will never be entered and you will not see any output. </p>
1
2016-09-08T11:26:35Z
[ "python", "numpy" ]
How to work "if np.array([False]):"
39,389,581
<p>The output of the following code is <strong>NOTHING</strong>.</p> <pre><code>if np.array([False]): print("hello") </code></pre> <p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p> <p>The following is a case of a pure array.</p> <pre><code>if [False]: print("hello") </code></pre> <p>The output is <code>hello</code></p> <p>Would you tell me how to code np.array?</p>
1
2016-09-08T11:20:56Z
39,389,795
<p>It seems np.array([]) returns False and so do for <code>0</code> and <code>False</code></p> <pre><code>&gt;&gt;&gt; bool(np.array([])) False &gt;&gt;&gt; bool(np.array([0])) False &gt;&gt;&gt; bool(np.array([False])) False </code></pre> <p>Here the list returns true if it has any item..</p> <pre><code>&gt;&gt;&gt; bool([False]) ### the returned boolean value is based on the length of the list. True </code></pre>
2
2016-09-08T11:31:21Z
[ "python", "numpy" ]
How to work "if np.array([False]):"
39,389,581
<p>The output of the following code is <strong>NOTHING</strong>.</p> <pre><code>if np.array([False]): print("hello") </code></pre> <p>Although I tried to search for it, I don't know how it works. Can Python overload <code>if</code>? </p> <p>The following is a case of a pure array.</p> <pre><code>if [False]: print("hello") </code></pre> <p>The output is <code>hello</code></p> <p>Would you tell me how to code np.array?</p>
1
2016-09-08T11:20:56Z
39,390,315
<p>One thing i noticed is <code>if np.array([False])</code> or <code>bool(np.array([False])</code> returns the bool of the only item in the array. And you are not supposed to have more than one item in numpy array if you are doing <code>if</code> or <code>bool</code>. </p> <p>If there are more than one elements, have to use <code>a.any()</code> or <code>a.all()</code></p> <pre><code>&gt;&gt;&gt; if np.array([False, False]): ... print 's' ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() &gt;&gt;&gt; bool(np.array([False, False])) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; bool(np.array([False, 232])) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; bool(np.array([False, 232]).any()) True &gt;&gt;&gt; </code></pre>
2
2016-09-08T11:58:10Z
[ "python", "numpy" ]
Raise MemoryError when I am fitting a sequence to sequnce LSTM using Keras+Theano
39,389,585
<p>I was trying to implement a sequence to sequence language model. During training process, the model takes in a sequence of 50d word vectors generated by GloVe, and output 1-to-V(V is the size of vocabulary) vector meaning the next word which thus can be regarded as the distribution of next word corresponding to the input word vector at current timestep in test process, and I tried with a 112-word vocabulary.</p> <p>Then, I built two models as following:</p> <pre><code>model1 = Sequential() model1.add(LSTM(112, return_sequences=True, input_shape=(31, 50))) model2 = Sequential() model2.add(LSTM(112, return_sequences=True, input_shape=(31, 50))) model2.add(TimeDistributed(Dense(112, activation="linear"))) </code></pre> <p>When I tried to fit them by</p> <pre><code>model.fit(X, Y, batch_size=128, nb_epoch=256, validation_rate=0.1) </code></pre> <p>The first model <code>model1</code> crashed and raised MemoryError, but the second model <code>model2</code> normally finished. X has the shape of <code>(number_of_sentences, max_words_in_one_sentence, 50)</code>, and Y has the shape of <code>(number_of_sentences, max_words_in_one_sentence, 112)</code>. In this example, <code>number_of_sentences=10000, max_words_in_one_sentence=13</code>.</p> <p>I am wondering what happened when I appended a new time-distributed-dense to a LSTM layer, and which one is the model I want to implement my language model.</p>
2
2016-09-08T11:21:00Z
39,440,233
<p>What happened is that your computing device (probably a GPU) ran out of memory. I suspect it is a NVIDIA card (due to lack of alternatives), so check the output of <code>nvidia-smi</code> to see if you run into memory issues.</p> <p>Depending on the backend (Theano or TensorFlow) you may experience different behaviours in memory usage, so switching backends may be a solution in some cases.</p> <p>In case you are using Theano the issue might be the <code>TimeDistributed</code> wrapper. <code>TimeDistributed</code> does this when no batch size is specified:</p> <pre><code>K.reshape(x, (-1,) + input_shape[2:]) </code></pre> <p>so it basically reshapes <code>x</code> from <code>(batchsz,timesteps,units)</code> to <code>(batchsz*timesteps,units)</code>. However, reshape is currently allocating a new array if the reshaped one is not C-contiguous (data is sorted as a n-dimensional C array would be), which I suspect it is not in your case.</p> <p>What you can try is to specify a fixed batch size for your input in which case <code>TimeDistributed</code> will work through the input sequentially using <code>K.rnn</code> without allocation as much memory.</p>
0
2016-09-11T20:15:09Z
[ "python", "keras", "lstm", "language-model" ]
Error when importing numpy (SyntaxError)
39,389,684
<p>I suddenly obtained such error when importing numpy:</p> <p><a href="http://i.stack.imgur.com/G3Z8f.png" rel="nofollow">Print screen with error</a></p> <p>It shows up when I type </p> <pre><code>import numpy as np </code></pre> <p>or just</p> <pre><code>import numpy </code></pre> <p>It also happens in python console as follows:</p> <pre><code> Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Py27_64\lib\site-packages\numpy\__init__.py", line 180, in &lt;module&gt; from . import add_newdocs File "C:\Py27_64\lib\site-packages\numpy\add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "C:\Py27_64\lib\site-packages\numpy\lib\__init__.py", line 22, in &lt;module&gt; from .npyio import * File "C:\Py27_64\lib\site-packages\numpy\lib\npyio.py", line 1162 x % (str(X.dtype), format)) ^ SyntaxError: invalid syntax </code></pre> <p>No numpy functions calling needed to get this error - it happens when importing numpy. I was able to succesfully work with numpy earlier. All other Python functions work well. I tried reinstalling numpy - didn't work. I work on Python 2.7 64bit with PyScripter. I didn't install anything new recently, it happend just like so. </p>
1
2016-09-08T11:26:18Z
39,389,804
<p>Check that you use a Python 2 edition of numpy.</p>
0
2016-09-08T11:31:41Z
[ "python", "numpy", "syntax-error" ]
SQLAlchemy: How to cast string value to date in multiple insert statement?
39,389,719
<p>I have a list of dict objects</p> <pre><code>data = [ {'id': 1, 'dt':'2002-01-02' }, {'id': 2, 'dt':'2014-01-15' }, {'id': 3, 'dt':'2005-10-20' } ] </code></pre> <p>and a table in sqlite created using sqlalchemy as follows</p> <pre><code>engine = create_engine(config.SQLALCHEMY_DATABASE_URI) metadata = MetaData() tbl1 = Table('t1', metadata, Column('the_id', Integer, primary_key=True), Column('the_dt', Date)) metadata.create_all(bind=engine) stmt_insert = tbl1.insert().values(the_id=bindparam('id'), the_dt=bindparam('dt', type_=Date) with engine.connect() as conn: conn.execute(stmt_insert, data) </code></pre> <p>This gives me the following error:</p> <blockquote> <p>sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite Date type only accepts Python date objects as input.</p> </blockquote> <p>What do I assign to the "type_" parameter to make this binding work ?</p>
0
2016-09-08T11:27:54Z
39,389,898
<p>You need to convert your <code>dt</code> strings to date objects, for instance:</p> <pre><code>import datetime for item in data: item['dt'] = datetime.datetime.strptime(item['dt'], "%Y-%m-%d").date() </code></pre> <p>If you don't need the ORM part of SQLAlchemy (no class/table mapping). The easiest way is to tell SQLAlchemy that you use String instead of Date, like this:</p> <pre><code>tbl1 = Table('t1', metadata, Column('the_id', Integer, primary_key=True), Column('the_dt', String)) </code></pre> <p>It will work because your date string use ISO 8601 format ("%Y-%m-%d").</p> <p>But the best practices are:</p> <ol> <li>read records from CSV</li> <li>convert data to Python objects (<code>int</code>, <code>date</code>, etc.)</li> <li>insert data in database.</li> </ol> <p>The conversion can be done in the constructor of the class which is mapped to the table.</p> <p><strong>EDIT</strong> A kind of "solution"</p> <pre><code>from sqlalchemy import Table, Column, Integer, MetaData, Date, String from sqlalchemy import create_engine from sqlalchemy.sql import select engine = create_engine('sqlite:///:memory:', echo=True) metadata = MetaData() </code></pre> <p>I've created a "fake" table with a <code>String</code> type instead of a <code>Date</code>:</p> <pre><code>fake_tbl1 = Table('t1', metadata, Column('id', Integer, primary_key=True), Column('dt', String)) metadata.create_all(bind=engine) </code></pre> <p>And insert the data as-is:</p> <pre><code>data = [ {'id': 1, 'dt': '2002-01-02'}, {'id': 2, 'dt': '2014-01-15'}, {'id': 3, 'dt': '2005-10-20'} ] stmt_insert = fake_tbl1.insert() with engine.connect() as conn: conn.execute(stmt_insert, data) </code></pre> <p>Then I redefine the same table with the required <code>Date</code> field:</p> <pre><code>tbl2 = Table('t1', metadata, Column('id', Integer, primary_key=True), Column('dt', Date), extend_existing=True) </code></pre> <p>Here is a rows selection:</p> <pre><code>stmt_select = select([tbl2]) with engine.connect() as conn: result = conn.execute(stmt_select) for row in result: print(row) </code></pre> <p>You'll get:</p> <pre><code>(1, datetime.date(2002, 1, 2)) (2, datetime.date(2014, 1, 15)) (3, datetime.date(2005, 10, 20)) </code></pre> <p>This works for your simple case, but I won't recommend this for a generic solution.</p>
1
2016-09-08T11:36:24Z
[ "python", "sqlite", "sqlalchemy" ]
How to substitute two numpy subarrays with a single one
39,389,741
<p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p> <pre><code>[1, a, b][1, c, d] -&gt; [1, f_add, f_sub] </code></pre> <p>with </p> <pre><code>f_add(a, b, c, d): return a + b + c + d f_sub(b, d): return b-d </code></pre> <p>Concrete: </p> <pre><code> [1, 0, 50], [1, 3, 1] -&gt; [1, 54, 49] </code></pre> <p>As an addition, the row <code>[1, 0, 50], [1, 3, 1]</code> is part of a bigger array (1st row in example), so it should be substituted in-place</p> <pre><code>([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) ([[1, 54, 49], [2, 0, 50]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) </code></pre> <p>Thanks!</p> <p>EDIT:</p> <p>The functions f_add and f_sub are just examples to illustrate what I want to do and that the change in entries is a result of functions being called. In reality I use slightly more complex functions that carry out a (more) meaningful computation.</p> <p>The second thing is that this substitution should only be carried out on elements where the first entry is the same. So in the first row only <code>[1, 0. 50.]</code> and <code>[1, 3.0, 1.0]</code> merge while in the second it would be <code>[2, 0., 50.]</code> and <code>[2, 30, 1.0)</code>.</p> <p>In this example I first wanted to separate the issue of determining which sub-arrays are intended to merge by comparing the indicies but I guess it should be included to be as general as possible.</p> <p>A more complete example result to the one above would be as following then:</p> <pre><code> ([[1, 0., 50.], [2, 0., 50], [1, 3.0, 1.0]], [[1, 0., 50.], [2, 0., 50.], [2, 3.0, 1.0]]) </code></pre> <p>leading to:</p> <pre><code>([[1, 54., 49.], [2, 0., 50.]], [[1, 0., 50.], [2, 54., 49.]]) </code></pre>
0
2016-09-08T11:29:13Z
39,390,984
<p>You can use a generator expression to get this result (assuming there are three subelements for each element of the array):</p> <pre><code>ar = ([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) ar = tuple([[[x[0][0], sum(x[0][1:]) + sum(x[-1][1:]), x[0][-1]-x[-1][-1]], x[1]] for x in ar]) print ar </code></pre> <blockquote> <p>([[1, 54.0, 49.0], [2, 0, 50]], [[1, 54.0, 49.0], [2, 0, 50]])</p> </blockquote> <hr> <p>EDIT: Perhaps for a more general solution you can define a function <code>f(x)</code> that performs the desired calculation to elements of an array, and map that function to every row of the array. For instance,</p> <pre><code>def f(x): if (x[0][0] == x[1][0]): return [[x[0][0], x[0][1]+x[0][2]+x[1][1]+x[1][2], x[0][2]-x[1][2]], x[2]] elif (x[0][0] == x[2][0]): return [[x[0][0], x[0][1]+x[0][2]+x[2][1]+x[2][2], x[0][2]-x[2][2]], x[1]] elif (x[1][0] == x[2][0]): return [x[0], [x[1][0], x[1][1]+x[1][2]+x[2][1]+x[2][2], x[1][2]-x[2][2]]] else: return x ar = ([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) print tuple(map(f, ar)) </code></pre> <blockquote> <p>([[1, 54.0, 49.0], [2, 0, 50]], [[1, 0, 50], [2, 54.0, 49.0]])</p> </blockquote>
0
2016-09-08T12:30:00Z
[ "python", "arrays", "numpy" ]
How to substitute two numpy subarrays with a single one
39,389,741
<p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p> <pre><code>[1, a, b][1, c, d] -&gt; [1, f_add, f_sub] </code></pre> <p>with </p> <pre><code>f_add(a, b, c, d): return a + b + c + d f_sub(b, d): return b-d </code></pre> <p>Concrete: </p> <pre><code> [1, 0, 50], [1, 3, 1] -&gt; [1, 54, 49] </code></pre> <p>As an addition, the row <code>[1, 0, 50], [1, 3, 1]</code> is part of a bigger array (1st row in example), so it should be substituted in-place</p> <pre><code>([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) ([[1, 54, 49], [2, 0, 50]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) </code></pre> <p>Thanks!</p> <p>EDIT:</p> <p>The functions f_add and f_sub are just examples to illustrate what I want to do and that the change in entries is a result of functions being called. In reality I use slightly more complex functions that carry out a (more) meaningful computation.</p> <p>The second thing is that this substitution should only be carried out on elements where the first entry is the same. So in the first row only <code>[1, 0. 50.]</code> and <code>[1, 3.0, 1.0]</code> merge while in the second it would be <code>[2, 0., 50.]</code> and <code>[2, 30, 1.0)</code>.</p> <p>In this example I first wanted to separate the issue of determining which sub-arrays are intended to merge by comparing the indicies but I guess it should be included to be as general as possible.</p> <p>A more complete example result to the one above would be as following then:</p> <pre><code> ([[1, 0., 50.], [2, 0., 50], [1, 3.0, 1.0]], [[1, 0., 50.], [2, 0., 50.], [2, 3.0, 1.0]]) </code></pre> <p>leading to:</p> <pre><code>([[1, 54., 49.], [2, 0., 50.]], [[1, 0., 50.], [2, 54., 49.]]) </code></pre>
0
2016-09-08T11:29:13Z
39,392,277
<p>It sounds like things could get quite complicated if you have lots of functions working on the array. I would consider breaking each row into a class to manage the function calls a bit more succinctly. For example you could contain all of the relevant functions within the class:</p> <pre class="lang-python prettyprint-override"><code>class Row: def __init__(self, row): self.row = row self.sum1 = None self.sub1 = None self._add(row) self._sub(row) def _add(self, items): self.sum1 = sum([items[0][1], items[0][2], items[-1][1], items[-1][2]]) def _sub(self, items): self.sub1 = items[0][2] - items[-1][2] def update(self): self.row = [[self.row[0][0], self.sum1, self.sub1], self.row[1]] # Data arr = ([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) # Usage for row in arr: r = Row(row) print r.sum1, r.sub1 r.update() print r.row &gt;&gt;&gt; 54.0 49.0 [[1, 54.0, 49.0], [2, 0, 50]] 54.0 49.0 [[1, 54.0, 49.0], [2, 0, 50]] # This row doesnt match your example, but you get the idea </code></pre>
0
2016-09-08T13:28:03Z
[ "python", "arrays", "numpy" ]
How to substitute two numpy subarrays with a single one
39,389,741
<p>is there a simple solution to substitute two numpy subarrays with a single one while the entires are a results of functions being called on the entries of the two former arrays. E.g:</p> <pre><code>[1, a, b][1, c, d] -&gt; [1, f_add, f_sub] </code></pre> <p>with </p> <pre><code>f_add(a, b, c, d): return a + b + c + d f_sub(b, d): return b-d </code></pre> <p>Concrete: </p> <pre><code> [1, 0, 50], [1, 3, 1] -&gt; [1, 54, 49] </code></pre> <p>As an addition, the row <code>[1, 0, 50], [1, 3, 1]</code> is part of a bigger array (1st row in example), so it should be substituted in-place</p> <pre><code>([[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) ([[1, 54, 49], [2, 0, 50]], [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]) </code></pre> <p>Thanks!</p> <p>EDIT:</p> <p>The functions f_add and f_sub are just examples to illustrate what I want to do and that the change in entries is a result of functions being called. In reality I use slightly more complex functions that carry out a (more) meaningful computation.</p> <p>The second thing is that this substitution should only be carried out on elements where the first entry is the same. So in the first row only <code>[1, 0. 50.]</code> and <code>[1, 3.0, 1.0]</code> merge while in the second it would be <code>[2, 0., 50.]</code> and <code>[2, 30, 1.0)</code>.</p> <p>In this example I first wanted to separate the issue of determining which sub-arrays are intended to merge by comparing the indicies but I guess it should be included to be as general as possible.</p> <p>A more complete example result to the one above would be as following then:</p> <pre><code> ([[1, 0., 50.], [2, 0., 50], [1, 3.0, 1.0]], [[1, 0., 50.], [2, 0., 50.], [2, 3.0, 1.0]]) </code></pre> <p>leading to:</p> <pre><code>([[1, 54., 49.], [2, 0., 50.]], [[1, 0., 50.], [2, 54., 49.]]) </code></pre>
0
2016-09-08T11:29:13Z
39,399,573
<p>Here's a function to perform the first (inner most) step, assuming the 2 inputs are lists:</p> <pre><code>def merge(a,b): res = [a[0]] # test b[0] is same? abcd = a[1:]+b[1:] # list join # use np.concatenate here is a,b are arrays res.append(f_add(*abcd)) res.append(f_sum(a[2],b[2])) return res def f_add(a,b,c,d): return a+b+c+d def f_sum(b,d): return b-d In [484]: merge([1,0,50],[1,3,1]) Out[484]: [1, 54, 49] </code></pre> <p>With this mixed use of elements, and general functions there isn't much point to treating these as arrays.</p> <p>Then write a function to handle a 'row', the list of lists where lists with the same <code>x[0]</code> id are to be merged. The easiest way to collect matching pairs (are there only pairs?) is with a <code>defaultdict</code>.</p> <p>So I find the pairs; and the merge them with the above function.</p> <pre><code>def subs(alist): # collect the matching ids from collections import defaultdict dd = defaultdict(list) for i,x in enumerate(alist): dd[x[0]].append(x) # merge pairs for i in dd.keys(): if len(dd[i])==2: dd[i]=merge(dd[i][0],dd[i][1]) elif len(dd[i])==1: dd[i]=dd[i][0] # flatten else: pass # do nothing with triplets etc. return list(dd.values()) In [512]: lll= [[[1, 0, 50], [2, 0, 50], [1, 3.0, 1.0]], ...: [[1, 0, 50], [2, 0, 50], [2, 3.0, 1.0]]] In [513]: [subs(l) for l in lll] Out[513]: [[[1, 54.0, 49.0], [2, 0, 50]], [[1, 0, 50], [2, 54.0, 49.0]]] </code></pre> <p>The <code>lll</code> could be turned into a 3d array:</p> <pre><code>In [523]: arr=np.array(lll) In [524]: arr Out[524]: array([[[ 1., 0., 50.], [ 2., 0., 50.], [ 1., 3., 1.]], [[ 1., 0., 50.], [ 2., 0., 50.], [ 2., 3., 1.]]]) </code></pre> <p>and the ids we want to mix and match are:</p> <pre><code>In [525]: arr[:,:,0] Out[525]: array([[ 1., 2., 1.], [ 1., 2., 2.]]) </code></pre> <p>A pair to be merged is</p> <pre><code>In [526]: arr[0,[0,2],:] Out[526]: array([[ 1., 0., 50.], [ 1., 3., 1.]]) </code></pre> <p>and the 2 mergers:</p> <pre><code>In [527]: merge(*arr[0,[0,2],:].tolist()) Out[527]: [1.0, 54.0, 49.0] In [528]: merge(*arr[1,[1,2],:].tolist()) Out[528]: [2.0, 54.0, 49.0] </code></pre> <p>But identifying these pairs, and performing the mergers and building a new array is no easier with arrays than it was with the lists.</p> <pre><code>In [532]: np.array([subs(l.tolist()) for l in arr]) Out[532]: array([[[ 1., 54., 49.], [ 2., 0., 50.]], [[ 1., 0., 50.], [ 2., 54., 49.]]]) </code></pre>
0
2016-09-08T20:22:45Z
[ "python", "arrays", "numpy" ]
turn a pivot table from pandas into a flat tabular format with a single header row
39,389,766
<p>What's the easiest way to turn my pandas dataframe into a dataframe which has one header row and the two columns</p> <p>from this:</p> <pre><code> date today index 1 2016-07-01 2016-09-08 2 2016-07-01 2016-09-08 3 2016-07-01 2016-09-08 4 2016-07-01 2016-09-08 </code></pre> <p>into this:</p> <pre><code>index date today 1 2016-07-01 2016-09-08 2 2016-07-01 2016-09-08 3 2016-07-01 2016-09-08 4 2016-07-01 2016-09-08 </code></pre>
1
2016-09-08T11:29:56Z
39,389,815
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>print (df.columns) Index(['date', 'today'], dtype='object') print (df.index) Int64Index([1, 2, 3, 4], dtype='int64', name='index') df.reset_index(inplace=True) </code></pre> <p>Or:</p> <pre><code>df = df.reset_index() print (df) index date today 0 1 2016-07-01 2016-09-08 1 2 2016-07-01 2016-09-08 2 3 2016-07-01 2016-09-08 3 4 2016-07-01 2016-09-08 print (df.index) RangeIndex(start=0, stop=4, step=1) </code></pre> <hr> <p>If need remove column <code>index</code>, add parameter <code>drop=True</code>:</p> <pre><code>df.reset_index(inplace=True, drop=True) print (df) date today 0 2016-07-01 2016-09-08 1 2016-07-01 2016-09-08 2 2016-07-01 2016-09-08 3 2016-07-01 2016-09-08 </code></pre> <p>But if need only remove text <code>index</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p> <pre><code>df = df.rename_axis(None) </code></pre> <p>Or:</p> <pre><code>#all versions df.index.name = None print (df) date today 1 2016-07-01 2016-09-08 2 2016-07-01 2016-09-08 3 2016-07-01 2016-09-08 4 2016-07-01 2016-09-08 print (df.index) Int64Index([1, 2, 3, 4], dtype='int64') </code></pre>
0
2016-09-08T11:32:06Z
[ "python", "pandas", "dataframe" ]
How to write conditional code that's compatible with both plain Python values and NumPy arrays?
39,389,819
<p>For writing “piecewise functions” in Python, I'd normally use <code>if</code> (in either the control-flow or ternary-operator form).</p> <pre><code>def spam(x): return x+1 if x&gt;=0 else 1/(1-x) </code></pre> <p>Now, with NumPy, the mantra is to avoid working on single values in favour of vectorisation, for performance. So I reckon something like this would be preferred:<sub><em>As Leon remarks, the following is <strong>wrong</strong></em></sub></p> <pre><code>def eggs(x): y = np.zeros_like(x) positive = x&gt;=0 y[positive] = x+1 y[np.logical_not(positive)] = 1/(1-x) return y </code></pre> <p>(Correct me if I've missed something here, because frankly I find this very ugly.)</p> <p>Now, of course <code>eggs</code> will <em>only</em> work if <code>x</code> is actually a NumPy array, because otherwise <code>x&gt;=0</code> simply yields a single boolean, which can't be used for indexing (at least doesn't do the right thing).</p> <p>Is there a good way to write code that looks more like <code>spam</code> but works idiomatic on Numpy arrays, or should I just use <code>vectorize(spam)</code>?</p>
7
2016-09-08T11:32:16Z
39,390,839
<p>I would use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow">numpy.asarray</a> (which is a no-op if the argument is already an numpy array) if I want to handle both numbers and numpy arrays</p> <pre><code>def eggs(x): x = np.asfarray(x) m = x&gt;=0 x[m] = x[m] + 1 x[~m] = 1 / (1 - x[~m]) return x </code></pre> <p>(here I used <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asfarray.html" rel="nofollow">asfarray</a> to enforce a floating-point type, since your function requires floating-point computations).</p> <p>This is less efficient than your spam function for single inputs, and arguably uglier. However it seems to be the easiest choice.</p> <p>EDIT: If you want to ensure that <code>x</code> is not modified (as pointed out by Leon) you can replace <code>np.asfarray(x)</code> by <code>np.array(x, dtype=np.float64)</code>, the array constructor copies by default.</p>
2
2016-09-08T12:23:30Z
[ "python", "arrays", "numpy", "vectorization" ]
How to write conditional code that's compatible with both plain Python values and NumPy arrays?
39,389,819
<p>For writing “piecewise functions” in Python, I'd normally use <code>if</code> (in either the control-flow or ternary-operator form).</p> <pre><code>def spam(x): return x+1 if x&gt;=0 else 1/(1-x) </code></pre> <p>Now, with NumPy, the mantra is to avoid working on single values in favour of vectorisation, for performance. So I reckon something like this would be preferred:<sub><em>As Leon remarks, the following is <strong>wrong</strong></em></sub></p> <pre><code>def eggs(x): y = np.zeros_like(x) positive = x&gt;=0 y[positive] = x+1 y[np.logical_not(positive)] = 1/(1-x) return y </code></pre> <p>(Correct me if I've missed something here, because frankly I find this very ugly.)</p> <p>Now, of course <code>eggs</code> will <em>only</em> work if <code>x</code> is actually a NumPy array, because otherwise <code>x&gt;=0</code> simply yields a single boolean, which can't be used for indexing (at least doesn't do the right thing).</p> <p>Is there a good way to write code that looks more like <code>spam</code> but works idiomatic on Numpy arrays, or should I just use <code>vectorize(spam)</code>?</p>
7
2016-09-08T11:32:16Z
39,391,848
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>. You'll get an array as the output even for plain number input, though.</p> <pre><code>def eggs(x): y = np.asarray(x) return np.where(y&gt;=0, y+1, 1/(1-y)) </code></pre> <p>This works for both arrays and plain numbers:</p> <pre><code>&gt;&gt;&gt; eggs(5) array(6.0) &gt;&gt;&gt; eggs(-3) array(0.25) &gt;&gt;&gt; eggs(np.arange(-3, 3)) /home/praveen/.virtualenvs/numpy3-mkl/bin/ipython3:2: RuntimeWarning: divide by zero encountered in true_divide array([ 0.25 , 0.33333333, 0.5 , 1. , 2. , 3. ]) &gt;&gt;&gt; eggs(1) /home/praveen/.virtualenvs/numpy3-mkl/bin/ipython3:3: RuntimeWarning: divide by zero encountered in long_scalars # -*- coding: utf-8 -*- array(2.0) </code></pre> <p>As ayhan remarks, this raises a warning, since <code>1/(1-x)</code> gets evaluated for the whole range. But a warning is just that: a warning. If you know what you're doing, you can ignore the warning. In this case, you're only choosing <code>1/(1-x)</code> from indices where it can never be <code>inf</code>, so you're safe.</p>
4
2016-09-08T13:08:48Z
[ "python", "arrays", "numpy", "vectorization" ]
How to cope u prefix utf-8 string( need to decode but fail by `u` )?
39,389,971
<p>I am using python build a web base file manager with python 3 compatibility.</p> <p>Every file header is:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import </code></pre> <p>Then I found something wrong due to Unicode.</p> <p>My system is Chinese, I have a folder named <code>E:\filemanager\data\c - 副本</code>.</p> <p>I use <code>ajax GET</code> send (<code>E:\filemanager\data\c - 副本</code>) to the flask app(filemanager). I also confusing when I meet the <code>Windows Error[3]</code> which indicate path not exists. Then I use pycharm to debug my code, and see the string has already became <code>u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code> when <code>os.listdir(path)</code>.</p> <p>This string is horrible. Let me show the problem:</p> <pre><code>&gt;&gt;&gt; p1 = ur'E:\filemanager\data\c - 副本' &gt;&gt;&gt; p1 u'E:\\filemanager\\data\\c - \u526f\u672c' &gt;&gt;&gt; p1.encode('utf-8') 'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' # here you can see this result just like p2 without `u` prefix &gt;&gt;&gt; p2 = u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' &gt;&gt;&gt; p2.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\kasim\Envs\fmgr\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-29: ordinal not in range(128) </code></pre> <p>There is a <code>u</code> prefix in <code>p2</code>! Which make me can not list the directory(because the name is wrong).</p> <p>I know only remove that <code>u</code> prefix can make decode successful. But How to remove it ?</p> <hr> <p><strong>UPDATE</strong>:</p> <p>What I want is convert</p> <p><code>u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code> to </p> <p>either <code>u'E:\\filemanager\\data\\c - \u526f\u672c'</code> or <code>'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code></p> <p><code>\xe5\x89\xaf\xe6\x9c\xac</code> can not be decode due to the <code>u</code> prefix, , that is the key problem!</p> <hr> <p><strong>UPDATE2:</strong></p> <p>my ajax code:</p> <pre><code>function ajax2(options) { var querystring = options.params ? urllib.format({ query: options.params }) : '' if (options.loading) swalShowLoading(); reqwest({ url: options.url + querystring, contentType: 'application/json', method: options.method || 'GET', data: JSON.stringify(options.data) }) } // getFileList // because this is a `GET` method, so no data be JSON.stringify here // sorry for wrong explanation before. ajax2({ url: ApiUrl.list, params: { path: encodeURI(path) }, success:success, error:error }) </code></pre>
0
2016-09-08T11:40:53Z
39,390,378
<p><code>unicode</code> strings can be <em>encoded</em> to byte <code>str</code>.<br> <code>str</code> can be <em>decoded</em> to <code>unicode</code> strings.</p> <p>When you have a <code>u''</code> string literal, <em>or</em> when you <code>import unicode_literals</code>, all your string literals will be <code>unicode</code> strings. You can only <em>encode</em> those, not <code>decode</code>. The error you get stems from an implicit conversion when you try to <code>decode</code> an already decoded <code>unicode</code> string.</p> <pre><code>&gt;&gt;&gt; p1.encode('utf-8') 'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' </code></pre> <p>The <code>\x35…</code> represent the raw bytes (<code>str</code>) of your string.</p> <pre><code>u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' </code></pre> <p>This is a <code>unicode</code> literal which literally expresses the text "\xe5…".<br> When you have a raw byte representation, you need to make sure Python treats it as a <code>str</code>, not as <code>unicode</code>:</p> <pre><code>&gt;&gt;&gt; p2 = b'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' &gt;&gt;&gt; p2.decode('utf-8') u'E:\\filemanager\\data\\c - \u526f\u672c' </code></pre> <p>The <code>b</code> prefix marks the literal as <code>str</code>, which can be decoded into a <code>unicode</code>.</p> <p><code>u''</code>, <code>''</code> with <code>unicode_literals</code> and <code>\u526f</code> are <code>unicode</code> → <code>encode</code> to <code>str</code><br> <code>b''</code> and <code>\xe5</code> are <code>str</code> → <code>decode</code> to <code>unicode</code></p>
0
2016-09-08T12:03:00Z
[ "python", "python-2.7", "unicode" ]
How to cope u prefix utf-8 string( need to decode but fail by `u` )?
39,389,971
<p>I am using python build a web base file manager with python 3 compatibility.</p> <p>Every file header is:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import </code></pre> <p>Then I found something wrong due to Unicode.</p> <p>My system is Chinese, I have a folder named <code>E:\filemanager\data\c - 副本</code>.</p> <p>I use <code>ajax GET</code> send (<code>E:\filemanager\data\c - 副本</code>) to the flask app(filemanager). I also confusing when I meet the <code>Windows Error[3]</code> which indicate path not exists. Then I use pycharm to debug my code, and see the string has already became <code>u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code> when <code>os.listdir(path)</code>.</p> <p>This string is horrible. Let me show the problem:</p> <pre><code>&gt;&gt;&gt; p1 = ur'E:\filemanager\data\c - 副本' &gt;&gt;&gt; p1 u'E:\\filemanager\\data\\c - \u526f\u672c' &gt;&gt;&gt; p1.encode('utf-8') 'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' # here you can see this result just like p2 without `u` prefix &gt;&gt;&gt; p2 = u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' &gt;&gt;&gt; p2.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\kasim\Envs\fmgr\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-29: ordinal not in range(128) </code></pre> <p>There is a <code>u</code> prefix in <code>p2</code>! Which make me can not list the directory(because the name is wrong).</p> <p>I know only remove that <code>u</code> prefix can make decode successful. But How to remove it ?</p> <hr> <p><strong>UPDATE</strong>:</p> <p>What I want is convert</p> <p><code>u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code> to </p> <p>either <code>u'E:\\filemanager\\data\\c - \u526f\u672c'</code> or <code>'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac'</code></p> <p><code>\xe5\x89\xaf\xe6\x9c\xac</code> can not be decode due to the <code>u</code> prefix, , that is the key problem!</p> <hr> <p><strong>UPDATE2:</strong></p> <p>my ajax code:</p> <pre><code>function ajax2(options) { var querystring = options.params ? urllib.format({ query: options.params }) : '' if (options.loading) swalShowLoading(); reqwest({ url: options.url + querystring, contentType: 'application/json', method: options.method || 'GET', data: JSON.stringify(options.data) }) } // getFileList // because this is a `GET` method, so no data be JSON.stringify here // sorry for wrong explanation before. ajax2({ url: ApiUrl.list, params: { path: encodeURI(path) }, success:success, error:error }) </code></pre>
0
2016-09-08T11:40:53Z
39,402,273
<blockquote> <p>What I want is convert</p> <p>u'E:\filemanager\data\c - \xe5\x89\xaf\xe6\x9c\xac' to</p> <p>either u'E:\filemanager\data\c - \u526f\u672c' or 'E:\filemanager\data\c - \xe5\x89\xaf\xe6\x9c\xac'</p> <p>\xe5\x89\xaf\xe6\x9c\xac can not be decode due to the u prefix, , that is the key problem!</p> </blockquote> <p>You can't decode Unicode strings. The key problem is that a UTF-8-encoded byte string was decoded incorrectly in the first place.</p> <p>Here's how to reverse it, but what you should really solve is why it was wrong to begin with.</p> <p><code>latin1</code> is a codec that converts the first 256 Unicode codepoints directly to bytes:</p> <pre><code>&gt;&gt;&gt; s = u'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' &gt;&gt;&gt; s.encode('latin1') 'E:\\filemanager\\data\\c - \xe5\x89\xaf\xe6\x9c\xac' </code></pre> <p>So that "gets rid of the u". You now have a byte string that can be decoded with UTF-8:</p> <pre><code>&gt;&gt;&gt; s.encode('latin1').decode('utf8') u'E:\\filemanager\\data\\c - \u526f\u672c' &gt;&gt;&gt; print s.encode('latin1').decode('utf8') E:\filemanager\data\c - 副本 </code></pre>
1
2016-09-09T00:55:34Z
[ "python", "python-2.7", "unicode" ]
Create DataFrame from Loop with Bloomberg function
39,390,060
<p>I have a list of company ticker's:</p> <pre><code>df = {'Ticker': ['AVON LN EQUITY', 'GFS LN EQUITY'], 'Value': [1., 2.]} df = pd.DataFrame(df) </code></pre> <p>I am using the BLPAPI wrapper, <a href="https://github.com/alex314159/blpapiwrapper" rel="nofollow">https://github.com/alex314159/blpapiwrapper</a></p> <p>Using this i would like to get a DataFrame, of all the prices over on a monthly basis. For this i am using the BLP class and BDH function. Settings below (the longer version is in the link):</p> <pre><code>def bdh(self, strSecurity='SPX Index', strData='PX_LAST', startdate=datetime.date(2013, 1, 1), enddate=datetime.date(2016, 9, 6), adjustmentSplit=False, periodicity='MONTHLY', strOverrideField='', strOverrideValue=''): </code></pre> <p>for simplicity i created a mini function:</p> <pre><code>def bloom_func(x, func): bloomberg = BLP() return bloomberg.bdh(x, func, strOverrideField='BEST_FPERIOD_OVERRIDE', strOverrideValue='1GY' ) bloomberg.closeSession() </code></pre> <p>Using these i can get a DataFrame for one equity. </p> <pre><code>Price = bloom_func('VOD LN EQUITY', 'PX_LAST') print (c) </code></pre> <p>which works. </p> <p>However, when i try to run this in a across the 2 companies using:</p> <pre><code>df1 = pd.concat([df.apply(lambda x: bloom_func(x)) for p in df['Ticker']]) </code></pre> <p>i get ValueError: Shape of passed values is (2, 0), indices imply (2, 2). </p>
0
2016-09-08T11:45:00Z
39,391,598
<p>Was simpler than I thought</p> <pre><code>for d in df['Ticker']: x[d] = bloom_func(d) </code></pre>
0
2016-09-08T12:57:22Z
[ "python", "pandas", "bloomberg" ]
Can't pass a list as class attribute
39,390,157
<p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_list = (args) self.index = -1 def __iter__(self): return self def __next__(self): if self.index == len(self.ingredient_list): raise StopIteration for ingredient in self.ingredient_list: if ingredient in Vegan.NONE_VEGAN_INGREDIENT: self.index += 1 return ('{} is a vegan ingredient'.format(ingredient[self.index])) else: self.index += 1 return ('{} is NOT a vegan ingredient'.format(ingredient[self.index])) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break </code></pre> <p>as you can see, I'm passing *args, which should be a list, but whenever I try to run this, it iterates through the first word, and checks the letters of the word 'tomato'. I want my iterator to go through the ingredients, and if something is not in the NONE_VEGAN_INGREDIENT list, then print as it is in the code. How can I pass in a list?</p>
1
2016-09-08T11:50:28Z
39,390,508
<p>Here's a possible solution to your problem:</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_list = (args) def __iter__(self): self.index = 0 return self def __next__(self): if self.index &gt;= len(self.ingredient_list): raise StopIteration ingredient = self.ingredient_list[self.index] self.index += 1 if ingredient in Vegan.NONE_VEGAN_INGREDIENT: return ('{} is a vegan ingredient'.format(ingredient)) else: return ('{} is NOT a vegan ingredient'.format(ingredient)) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break </code></pre> <p>In any case, I think this problem could be solved in 1 or 2 lines instead of using <code>__iter__</code> and <code>__next__</code> methods like this</p>
0
2016-09-08T12:08:37Z
[ "python", "oop" ]
Can't pass a list as class attribute
39,390,157
<p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_list = (args) self.index = -1 def __iter__(self): return self def __next__(self): if self.index == len(self.ingredient_list): raise StopIteration for ingredient in self.ingredient_list: if ingredient in Vegan.NONE_VEGAN_INGREDIENT: self.index += 1 return ('{} is a vegan ingredient'.format(ingredient[self.index])) else: self.index += 1 return ('{} is NOT a vegan ingredient'.format(ingredient[self.index])) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break </code></pre> <p>as you can see, I'm passing *args, which should be a list, but whenever I try to run this, it iterates through the first word, and checks the letters of the word 'tomato'. I want my iterator to go through the ingredients, and if something is not in the NONE_VEGAN_INGREDIENT list, then print as it is in the code. How can I pass in a list?</p>
1
2016-09-08T11:50:28Z
39,390,515
<p>Your issue is because you are indexing the ingredient not the tuple, <code>ingredient[self.index]</code> should be <code>self.ingredient_list[self.index]</code>. </p> <p>You could simplify your code to behave like yours but work by making <em>args</em> <em>iterable</em> so you can pass the strings as you were without needing to put them in a list etc..:</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_iter = iter(args) def __iter__(self): return self def __next__(self): ingredient = next(self.ingredient_iter) if ingredient in Vegan.NONE_VEGAN_INGREDIENT: return '{} is a vegan ingredient'.format(ingredient) return '{} is NOT a vegan ingredient'.format(ingredient) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') for ele in iterable: print(ele) </code></pre> <p>Output:</p> <pre><code>In [2]: iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') In [3]: for ele in iterable: ...: print(ele) ...: tomato is NOT a vegan ingredient banana is NOT a vegan ingredient asd is NOT a vegan ingredient egg is a vegan ingredient tomato is NOT a vegan ingredient </code></pre> <p>You raise a Stopiteration in your own code but calling <code>next(iterable)</code> will do the same so, the point of making an object iterable is you can iterate directly over it so no need for a try/except. Also <em>I'm passing args, which should be a list</em> is incorrect, args is a tuple.</p> <p>Also if you have a lot of ingredients to check making <code>NONE_VEGAN_INGREDIENT</code> a set would be more efficient:</p> <pre><code>NONE_VEGAN_INGREDIENT = {'egg', 'milk', 'honey', 'butter'} </code></pre>
3
2016-09-08T12:08:53Z
[ "python", "oop" ]
Can't pass a list as class attribute
39,390,157
<p>I have created an iterator. I'm trying to iterate through recipe ingredients, to check if a vegan person can it it, or not.</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_list = (args) self.index = -1 def __iter__(self): return self def __next__(self): if self.index == len(self.ingredient_list): raise StopIteration for ingredient in self.ingredient_list: if ingredient in Vegan.NONE_VEGAN_INGREDIENT: self.index += 1 return ('{} is a vegan ingredient'.format(ingredient[self.index])) else: self.index += 1 return ('{} is NOT a vegan ingredient'.format(ingredient[self.index])) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break </code></pre> <p>as you can see, I'm passing *args, which should be a list, but whenever I try to run this, it iterates through the first word, and checks the letters of the word 'tomato'. I want my iterator to go through the ingredients, and if something is not in the NONE_VEGAN_INGREDIENT list, then print as it is in the code. How can I pass in a list?</p>
1
2016-09-08T11:50:28Z
39,390,832
<p>I think the problem with your class is that you're looping through the elements in your <code>__next__()</code> method. Here is a solution using your code:</p> <pre><code>class Vegan: NONE_VEGAN_INGREDIENT = ['egg', 'milk', 'honey', 'butter'] def __init__(self, *args): self.ingredient_list = args self.index = -1 def __iter__(self): return self def __next__(self): if self.index == len(self.ingredient_list) - 1: # index is incremented raise StopIteration self.index += 1 if self.ingredient_list[self.index] in Vegan.NONE_VEGAN_INGREDIENT: return ('{} is a vegan ingredient'.format(self.ingredient_list[self.index])) else: return ('{} is NOT a vegan ingredient'.format(self.ingredient_list[self.index])) iterable = Vegan('tomato', 'banana', 'asd', 'egg', 'tomato') iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break </code></pre> <p>All I did was change the check for index out of bounds to <code>len() - 1</code> and removed the for loop. This works, producing the output I assume you were going for: </p> <pre><code>tomato is NOT a vegan ingredient banana is NOT a vegan ingredient asd is NOT a vegan ingredient egg is a vegan ingredient tomato is NOT a vegan ingredient </code></pre> <p>edit: fixed issue with if statement</p>
0
2016-09-08T12:23:13Z
[ "python", "oop" ]
pandas.factorize on an entire data frame
39,390,160
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>pandas.factorize</code></a> encodes input values as an enumerated type or categorical variable. </p> <p>But how can I easily and efficiently convert many columns of a data frame? What about the reverse mapping step?</p> <p>Example: This data frame contains columns with string values such as "type 2" which I would like to convert to numerical values - and possibly translate them back later.</p> <p><a href="http://i.stack.imgur.com/MLATh.png" rel="nofollow"><img src="http://i.stack.imgur.com/MLATh.png" alt="enter image description here"></a></p>
1
2016-09-08T11:50:52Z
39,390,208
<p>You can use <code>apply</code> if you need to <code>factorize</code> each column separately:</p> <pre><code>df = pd.DataFrame({'A':['type1','type2','type2'], 'B':['type1','type2','type3'], 'C':['type1','type3','type3']}) print (df) A B C 0 type1 type1 type1 1 type2 type2 type3 2 type2 type3 type3 print (df.apply(lambda x: pd.factorize(x)[0])) A B C 0 0 0 0 1 1 1 1 2 1 2 1 </code></pre> <p>If you need for the same string value the same numeric one:</p> <pre><code>print (df.stack().rank(method='dense').unstack()) A B C 0 1.0 1.0 1.0 1 2.0 2.0 3.0 2 2.0 3.0 3.0 </code></pre> <hr> <p>If you need to apply the function only for some columns, use a subset:</p> <pre><code>df[['B','C']] = df[['B','C']].stack().rank(method='dense').unstack() print (df) A B C 0 type1 1.0 1.0 1 type2 2.0 3.0 2 type2 3.0 3.0 </code></pre> <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.factorize.html" rel="nofollow"><code>factorize</code></a>:</p> <pre><code>stacked = df[['B','C']].stack() df[['B','C']] = pd.Series(stacked.factorize()[0], index=stacked.index).unstack() print (df) A B C 0 type1 0 0 1 type2 1 2 2 type2 2 2 </code></pre> <p>Translate them back is possible via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> by <code>dict</code>, where you need to remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>:</p> <pre><code>vals = df.stack().drop_duplicates().values b = [x for x in df.stack().drop_duplicates().rank(method='dense')] d1 = dict(zip(b, vals)) print (d1) {1.0: 'type1', 2.0: 'type2', 3.0: 'type3'} df1 = df.stack().rank(method='dense').unstack() print (df1) A B C 0 1.0 1.0 1.0 1 2.0 2.0 3.0 2 2.0 3.0 3.0 print (df1.stack().map(d1).unstack()) A B C 0 type1 type1 type1 1 type2 type2 type3 2 type2 type3 type3 </code></pre>
2
2016-09-08T11:53:16Z
[ "python", "pandas", "dataframe", "machine-learning" ]
kivy: KeyError: (3385,) in widget.py
39,390,227
<p>When trying to exectue following code (edited version from the <a href="https://github.com/kivy/kivy-designer" rel="nofollow">kivy-designer</a>, stands under the MIT license):</p> <pre><code>def __init__(self, **kwargs): self._buttons = {} super(PlaygroundSizeView, self).__init__(**kwargs) for title, values in self.default_sizes: grid = StackLayout(orientation="lr-tb", size_hint=(1, None)) def sort_sizes(item): return item[1][1] * item[1][0] values = sorted(values, key=sort_sizes, reverse=True) for name, size in values: btn = ToggleButton(text='', markup=True, size_hint=(0.25, 0.25)) btntext = ('%s\n[color=777777][size=%d]%dx%d[/size][/color]' % (name, btn.font_size * 0.8, size[0], size[1])) btn.text = btntext btn.bind(on_press=partial(self.set_size, size)) grid.add_widget(btn) self._buttons[name] = btn item = AccordionItem(title=title) _sv = ScrollView(do_scroll_x=False) _sv.add_widget(grid) item.add_widget(_sv) self.accordion.add_widget(item) self.accordion.select(self.accordion.children[-1]) self.update_buttons() </code></pre> <p>I get following Error 7 times in a row with different numbers before the program stops:</p> <blockquote> <p>Exception ignored in: functools.partial(, 3385)<br> Traceback (most recent call last):<br> File "E:\Programme(x86)\Python\Kivy Virtual Environment\lib\site-packages\kivy\uix\widget.py", line 239, in _widget_destructor KeyError: (3385,)</p> </blockquote> <p>It only appeared after I edited the code and added <code>ScrollView</code> at #1. I think it might be that python is trying to garbage collect <code>ScrollView</code> but is somehow unable to.</p> <p>Linue 239 of widget.py is the <code>del</code> line of following function:</p> <pre><code>def _widget_destructor(uid, r): # Internal method called when a widget is deleted from memory. the only # thing we remember about it is its uid. Clear all the associated callbacks # created in kv language. del _widget_destructors[uid] Builder.unbind_widget(uid) </code></pre> <p>Thanks a lot in advance!</p>
0
2016-09-08T11:54:38Z
39,390,409
<p>That line #1 has a typo in add_widget. Are you sure that add_widget returns the parent widget? I suggest you make a ScrollView first, then add the grid, then add the item to accordion.</p>
0
2016-09-08T12:04:15Z
[ "python", "kivy", "destructor", "keyerror" ]
removing dict entries by key using startswith
39,390,368
<p>I have a dict containing several entries beginning with '_'. I want to get rid of all this entries using:</p> <pre><code>for key in item: if key.startswith('_') del item[key] </code></pre> <p>But i get a syntax error on <em>if key.startswith('_')</em></p> <p>Is this method not allowed on key for dicts?</p>
0
2016-09-08T12:02:17Z
39,390,432
<p>Your if statement is syntactically wrong. You need a : at the end of it like this</p> <pre><code>for key in item: if key.startswith('_'): del item[key] </code></pre>
0
2016-09-08T12:05:24Z
[ "python" ]
removing dict entries by key using startswith
39,390,368
<p>I have a dict containing several entries beginning with '_'. I want to get rid of all this entries using:</p> <pre><code>for key in item: if key.startswith('_') del item[key] </code></pre> <p>But i get a syntax error on <em>if key.startswith('_')</em></p> <p>Is this method not allowed on key for dicts?</p>
0
2016-09-08T12:02:17Z
39,390,491
<p>You miss the <code>:</code> at the end of the if.</p> <pre><code>for key in item: if key.startswith('_'): # &lt;---------- del item[key] </code></pre>
1
2016-09-08T12:07:46Z
[ "python" ]
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)
39,390,418
<p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%&gt;python myscript.py foo bar</code>. </p> <p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p> <p><code>%dir%&gt;python myscript.py main(foo, bar)</code>.</p> <p>I know that I can use the <code>argparse</code> module, but I'm not sure how to do it. </p> <pre><code>import sys def main(foo,bar,**kwargs): print 'Called myscript with:' print 'foo = %s' % foo print 'bar = %s' % bar if kwargs: for k in kwargs.keys(): print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k] if __name__=="__main__": exec(''.join(sys.argv[1:])) </code></pre>
0
2016-09-08T12:04:48Z
39,390,779
<p>First, you won't be passing an arbitrary Python expression as an argument. It's brittle and unsafe.</p> <p>To set up the argument parser, you define the arguments you want, then parse them to produce a <code>Namespace</code> object that contains the information specified by the command line call.</p> <pre><code>import argparse p = argparse.ArgumentParser() p.add_argument('foo') p.add_argument('bar') p.add_argument('--add-feature-a', dest='a', action='store_true', default=False) </code></pre> <p>In your <code>__main__</code> block, you'll parse the arguments, then pass a dictionary produced from the <code>Namespace</code> to <code>main</code>.</p> <pre><code>if __name__ == '__main__': args = p.parse_args() main(**vars(args)) </code></pre> <p>Then you'll call your script with a line like</p> <pre><code># foo = "3", bar = "6", a = True python myscript.py 3 6 --add-feature-a </code></pre> <p>or</p> <pre><code># foo = "moo", bar="7.7", a = False python myscript.py moo 7.7 </code></pre> <p>There's a lot more you can do with <code>argparse</code>, but this is a simple example for getting the value it produces into <code>main</code>.</p>
0
2016-09-08T12:20:44Z
[ "python", "python-2.7", "command-line", "argparse", "kwargs" ]
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)
39,390,418
<p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%&gt;python myscript.py foo bar</code>. </p> <p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p> <p><code>%dir%&gt;python myscript.py main(foo, bar)</code>.</p> <p>I know that I can use the <code>argparse</code> module, but I'm not sure how to do it. </p> <pre><code>import sys def main(foo,bar,**kwargs): print 'Called myscript with:' print 'foo = %s' % foo print 'bar = %s' % bar if kwargs: for k in kwargs.keys(): print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k] if __name__=="__main__": exec(''.join(sys.argv[1:])) </code></pre>
0
2016-09-08T12:04:48Z
39,391,133
<p>If you want to pass in keyword arguments as you would in the main function, <code>key=value</code>, you can do it like so:</p> <pre><code>import sys def main(foo, bar, *args): print "Called my script with" print "foo = %s" % foo print "bar = %s" % bar for arg in args: k = arg.split("=")[0] v = arg.split("=")[1] print "Keyword argument: %s = %s" % (k, v) if __name__ == "__main__": if len(sys.argv) &lt; 3: raise SyntaxError("Insufficient arguments.") if len(sys.argv) != 3: # If there are keyword arguments main(sys.argv[1], sys.argv[2], *sys.argv[3:]) else: # If there are no keyword arguments main(sys.argv[1], sys.argv[2]) </code></pre> <p>Some examples:</p> <pre><code>$&gt; python my_file.py a b x=4 Called my script with foo = a bar = b Keyword argument: x = 4 $&gt; python my_file.py foo bar key=value Called my script with foo = foo bar = bar Keyword argument: key = value </code></pre> <p>However, this assumes that the key and value do not have any whitespace between them, <code>key = value</code> will not work.</p> <p>If you are looking for <code>--argument</code> kinds of keyword arguments, you <strong>should</strong> use <code>argparse</code>.</p>
0
2016-09-08T12:36:58Z
[ "python", "python-2.7", "command-line", "argparse", "kwargs" ]
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)
39,390,418
<p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%&gt;python myscript.py foo bar</code>. </p> <p>I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using </p> <p><code>%dir%&gt;python myscript.py main(foo, bar)</code>.</p> <p>I know that I can use the <code>argparse</code> module, but I'm not sure how to do it. </p> <pre><code>import sys def main(foo,bar,**kwargs): print 'Called myscript with:' print 'foo = %s' % foo print 'bar = %s' % bar if kwargs: for k in kwargs.keys(): print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k] if __name__=="__main__": exec(''.join(sys.argv[1:])) </code></pre>
0
2016-09-08T12:04:48Z
39,391,238
<p>@Moon beat me to it with a similar solution, but I'd suggest doing the parsing beforehand and passing in actual <code>kwargs</code>:</p> <pre><code>import sys def main(foo, bar, **kwargs): print('Called myscript with:') print('foo = {}'.format(foo)) print('bar = {}'.format(bar)) for k, v in kwargs.items(): print('keyword argument: {} = {}'.format(k, v)) if __name__=='__main__': main(sys.argv[1], # foo sys.argv[2], # bar **dict(arg.split('=') for arg in sys.argv[3:])) # kwargs # Example use: # $ python myscript.py foo bar hello=world 'with spaces'='a value' # Called myscript with: # foo = foo # bar = bar # keyword argument: hello = world # keyword argument: with spaces = a value </code></pre>
0
2016-09-08T12:41:12Z
[ "python", "python-2.7", "command-line", "argparse", "kwargs" ]
How to get the line number of a match with scrapy
39,390,585
<p>Using the following example:</p> <pre><code>$ scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html </code></pre> <p>where <em>selectors-sample1-html</em> is:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;base href='http://example.com/' /&gt; &lt;title&gt;Example website&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='images'&gt; &lt;a href='image1.html'&gt;Name: My image 1 &lt;br /&gt;&lt;img src='image1_thumb.jpg' /&gt;&lt;/a&gt; &lt;a href='image2.html'&gt;Name: My image 2 &lt;br /&gt;&lt;img src='image2_thumb.jpg' /&gt;&lt;/a&gt; &lt;a href='image3.html'&gt;Name: My image 3 &lt;br /&gt;&lt;img src='image3_thumb.jpg' /&gt;&lt;/a&gt; &lt;a href='image4.html'&gt;Name: My image 4 &lt;br /&gt;&lt;img src='image4_thumb.jpg' /&gt;&lt;/a&gt; &lt;a href='image5.html'&gt;Name: My image 5 &lt;br /&gt;&lt;img src='image5_thumb.jpg' /&gt;&lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is it possible to get the line number of a match using Scrapy 1.1.2? For instance, something like:</p> <pre><code>$ response.selector.xpath('//title/text()').some_magic_to_get_line_number $ # should output 4 </code></pre> <p>Thank you!</p>
0
2016-09-08T12:12:39Z
39,395,927
<p>I don't know of a way to get source line for text nodes, but for element nodes, you can hack into the underlying lxml object of the selector (with <code>.root</code>), and access <code>.sourceline</code> attribute:</p> <pre><code>$ scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html 2016-09-08 18:13:12 [scrapy] INFO: Scrapy 1.1.2 started (bot: scrapybot) 2016-09-08 18:13:12 [scrapy] INFO: Spider opened 2016-09-08 18:13:13 [scrapy] DEBUG: Crawled (200) &lt;GET http://doc.scrapy.org/en/latest/_static/selectors-sample1.html&gt; (referer: None) &gt;&gt;&gt; response.selector.xpath('//title/text()') [&lt;Selector xpath='//title/text()' data=u'Example website'&gt;] &gt;&gt;&gt; s = response.selector.xpath('//title/text()')[0] &gt;&gt;&gt; type(s) &lt;class 'scrapy.selector.unified.Selector'&gt; &gt;&gt;&gt; type(s.root) &lt;type 'str'&gt; &gt;&gt;&gt; s = response.selector.xpath('//title')[0] &gt;&gt;&gt; s.root &lt;Element title at 0x7fa95d3f1908&gt; &gt;&gt;&gt; type(s.root) &lt;type 'lxml.etree._Element'&gt; &gt;&gt;&gt; dir(s.root) ['__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '_init', 'addnext', 'addprevious', 'append', 'attrib', 'base', 'clear', 'cssselect', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'getnext', 'getparent', 'getprevious', 'getroottree', 'index', 'insert', 'items', 'iter', 'iterancestors', 'iterchildren', 'iterdescendants', 'iterfind', 'itersiblings', 'itertext', 'keys', 'makeelement', 'nsmap', 'prefix', 'remove', 'replace', 'set', 'sourceline', 'tag', 'tail', 'text', 'values', 'xpath'] &gt;&gt;&gt; s.root.sourceline 4 &gt;&gt;&gt; </code></pre>
0
2016-09-08T16:20:11Z
[ "python", "scrapy" ]
Are there any workarounds for pandas casting INT to Float when NaN is present?
39,390,610
<p>Trying to get my column to be formatted as INT as the 1.0 2.0 3.0 is causing issues with how I am using the data. The first thing I tried was <code>df['Severity'] = pd.to_numeric(df['Severity'], errors='coerce')</code>. While this looked like it worked initially, it reverted back to appearing as float when I wrote to csv. Next I tried using <code>df['Severity'] = df['Severity'].astype(int)</code> followed by another failed attempt using <code>df['Severity'] = df['Severity'].astype(int, errors='coerce')</code> because it seemed a logical solution to me.</p> <p>I did some digging into pandas' docs and found this regarding how pandas handles NAs:</p> <pre><code>Typeclass Promotion dtype for storing NAs floating no change object no change integer cast to float64 boolean cast to object </code></pre> <p>What I find strange though, is that when I run df.info(), I get <code>Severity 452646 non-null object</code></p> <p>Sample Data:</p> <pre><code>Age,Severity 1,1 2,2 3,3 4,NaN 5,4 6,4 7,5 8,7 9,6 10,5 </code></pre> <p>Any help would be greatly appreciated :)</p>
2
2016-09-08T12:13:49Z
39,391,360
<p>It's up to you how to handle missing values there is no correct way as it's up to you. You can either drop them using <code>dropna</code> or replace/fill them using <code>replace/fillna</code>, note that there is no way to represent <code>NaN</code> using integers: <a href="https://en.wikipedia.org/wiki/NaN#Integer_NaN" rel="nofollow">https://en.wikipedia.org/wiki/NaN#Integer_NaN</a>.</p> <p>The reason you get <code>object</code> as the <code>dtype</code> is because you now have a mixture of integers and floats. Depending on the operation then the entire Series maybe upcast to <code>float</code> but in your case you have mixed dtypes.</p>
1
2016-09-08T12:46:53Z
[ "python", "pandas", "int" ]
Mapping a dataframe based on the columns from other dataframe
39,390,612
<p>I have two data frames one looks like this,</p> <pre><code>df1.head() #CHR Start End Name chr1 141474 173862 SAP chr1 745489 753092 ARB chr1 762988 794826 SAS chr1 1634175 1669127 ETH chr1 2281853 2284259 BRB </code></pre> <p>And second datafarme looks as follows,</p> <pre><code>df2.head() #chr start end chr1 141477 173860 chr1 745500 753000 chr16 56228385 56229180 chr11 101785507 101786117 chr7 101961796 101962267 </code></pre> <p>I am looking to map the first 3 columns from two data frame and create a new data frame, df3. ie if #chr from both df1 and df2 are equal then look for <code>df2.start &gt;= df1.start</code> and <code>df2.end &lt;= df1.end</code>, if so print it out as the following, </p> <pre><code> df3.head() #chr start end Name chr1 141477 173860 SAP chr1 745500 753000 ARB </code></pre> <p>So far I tried to make it a function as following,</p> <pre><code>def start_smaller_than_end(df1,df2): if df1.CHR == df2.CHR: df2.start &gt;= df1.Start df2.End &lt;= df2.End return df3 </code></pre> <p>and when I run it I have the following error,</p> <blockquote> <p>df3(df1, df2) name 'df3' is not defined</p> </blockquote> <p>Any suggestions and help are greatly appreciated. </p>
1
2016-09-08T12:13:55Z
39,391,207
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>df = pd.merge(df1, df2, how='outer', left_on='#CHR', right_on='#chr') df = df[(df.start &gt;= df.Start) &amp; (df.end &lt;= df.End)] df = df[['#chr','start','end','Name']] print (df) #chr start end Name 0 chr1 141477 173860 SAP 3 chr1 745500 753000 ARB </code></pre> <p>EDIT by comment:</p> <p>Function <code>start_smaller_than_end</code>:</p> <pre><code>def start_smaller_than_end(df1,df2): df = pd.merge(df1, df2, how='outer', left_on='#CHR', right_on='#chr') df = df[(df.start &gt;= df.Start) &amp; (df.end &lt;= df.End)] df = df[['#chr','start','end','Name']] return df df3 = start_smaller_than_end(df1,df2) print (df3) </code></pre>
1
2016-09-08T12:40:00Z
[ "python", "pandas", "numpy", "indexing", "merge" ]
Melding several columns by unique value
39,390,616
<p>I have a dataset with a lot of columns. The data is structured like this:</p> <pre><code>id Artist 1 Artist 2 Artist 3 1 Red hot 2 Wiz Red hot 3 Red hot Wiz Bronson 4 Bronson Bruce Red hot 5 Wiz Bronson 6 Red Hot </code></pre> <p>And I need it to be like this:</p> <pre><code>id Artist 1 Red hot 2 Wiz 2 Red hot 3 Red hot 3 Wiz 3 Bronson 4 Red hot 4 Bronson 4 bruce 5 Wiz 5 Bronson 6 Red hot </code></pre> <p>Is there an easy way to do this in pandas? I've tried using melt from this response, but it's not what im aiming it: <a href="http://stackoverflow.com/questions/28654047/pandas-convert-some-columns-into-rows">pandas convert some columns into rows</a></p> <p>thx in advance!</p>
0
2016-09-08T12:14:19Z
39,390,849
<p>I think you can use:</p> <pre><code>#if column `id` is not index, first set it to index df.set_index('id', inplace=True) #create multiindex from columns df.columns = df.columns.str.split(expand=True) print (df) Artist 1 2 3 id 1 Red hot NaN NaN 2 Wiz Red hot NaN 3 Red hot Wiz Bronson 4 Bronson Bruce Red hot 5 Wiz Bronson NaN 6 Red Hot NaN NaN #reshape it print (df.stack().reset_index(drop=True, level=1).reset_index()) id Artist 0 1 Red hot 1 2 Wiz 2 2 Red hot 3 3 Red hot 4 3 Wiz 5 3 Bronson 6 4 Bronson 7 4 Bruce 8 4 Red hot 9 5 Wiz 10 5 Bronson 11 6 Red Hot </code></pre>
0
2016-09-08T12:23:49Z
[ "python", "excel", "pandas" ]
Where should I locate my Python file if I want to use virtualenv?
39,390,639
<p>I have a virtual environment and I do not know where should I save my Python file ? it only works when I run it in <code>/home/jojo/Enviroment/venv1</code> can I save it in other place ? Especially when I want to use PyCharm thank you </p>
0
2016-09-08T12:15:40Z
39,391,137
<p>virtualenv and your code base <strong>can</strong> very well be in different locations. I prefer things this way. Here are sample commands that I use. </p> <p><strong>Step 1</strong>: Activate the virtualenv.</p> <pre><code>[mayank@demo /dev]$ source /usr/local/pyenv3.4/bin/activate (pyenv3.4)[mayank@demo dev]$ </code></pre> <p>Notice the prefix "(pyenv3.4)" that indicates that virtualenv is now activated.</p> <p><strong>Step 2</strong>: Ensure that python executable in virtualenv is indeed pointed by "python"</p> <pre><code>(pyenv3.4)[mayank@demo dev]$ which python /usr/local/pyenv3.4/bin/python </code></pre> <p>Notice that python is indeed pointing to the one in virtualenv directory.</p> <p><strong>Step 3</strong>: Create a file elsewhere and execute it</p> <pre><code>echo "import sys; print(sys.executable)" &gt; /tmp/print_python_exe.py python /tmp/print_python_exe.py </code></pre> <p>Edit: As suggested by Paul, one might choose to keep the virtualenv directory inside the app directory. This style of structuring projects is also suggested here: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/#basic-usage" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/#basic-usage</a></p>
1
2016-09-08T12:37:02Z
[ "python", "pycharm", "virtualenv" ]
Getting contents of an lxml.objectify comment
39,390,653
<p>I have an XML file that I'm reading using python's <code>lxml.objectify</code> library.</p> <p>I'm not finding a way of getting the contents of an XML comment:</p> <pre><code>&lt;data&gt; &lt;!--Contents 1--&gt; &lt;some_empty_tag/&gt; &lt;!--Contents 2--&gt; &lt;/data&gt; </code></pre> <p>I'm able to retrieve the comment (is there a better way? <code>xml.comment[1]</code> does not seem to work):</p> <pre><code>xml = objectify.parse(the_xml_file).getroot() for c in xml.iterchildren(tag=etree.Comment): print c.???? # how do i print the contets of the comment? # print c.text # does not work # print str(c) # also does not work </code></pre> <p>What is the correct way?</p>
0
2016-09-08T12:16:08Z
39,391,003
<p>You just need to convert the child back to string to extract the comments, like this:</p> <pre><code>In [1]: from lxml import etree, objectify In [2]: tree = objectify.fromstring("""&lt;data&gt; ...: &lt;!--Contents 1--&gt; ...: &lt;some_empty_tag/&gt; ...: &lt;!--Contents 2--&gt; ...: &lt;/data&gt;""") In [3]: for node in tree.iterchildren(etree.Comment): ...: print(etree.tostring(node)) ...: b'&lt;!--Contents 1--&gt;' b'&lt;!--Contents 2--&gt;' </code></pre> <p>Of course you may want to strip the unwanted wrapping.</p>
0
2016-09-08T12:31:10Z
[ "python", "lxml.objectify" ]
Reading math function issue
39,390,899
<p>Here is my code</p> <pre><code>import math try: valor = float(input("Give a real number ")) print("Your value given is: ", value) except ValueError: print("You gave a value not interpretable as a real onel!!") </code></pre> <p>And when my input is <code>sqrt(2)</code>, I got this error, anyone knows why?</p> <pre><code>%run "c:\users\aar15\appdata\local\temp\tmpvzauzz.py" Give a real number sqrt(2) --------------------------------------------------------------------------- NameError Traceback (most recent call last) c:\users\aar15\appdata\local\temp\tmpvzauzz.py in &lt;module&gt;() 1 import math 2 try: ----&gt; 3 valor = float(input("Give a real number ")) 4 print("Your value given is: ", value) 5 except ValueError: C:\Users\aar15\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.1.3253.win-x86_64\lib\site-packages\IPython\kernel\zmq\ipkernel.pyc in &lt;lambda&gt;(prompt) C:\Users\aar15\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.1.3253.win-x86_64\lib\site-packages\IPython\kernel\zmq\ipkernel.pyc in &lt;module&gt;() NameError: name 'sqrt' is not defined </code></pre>
0
2016-09-08T12:25:46Z
39,391,510
<p>As you can see from the <a href="https://docs.python.org/2/library/functions.html#input" rel="nofollow">doc</a>, <code>input</code> is equivalent to <code>eval(raw_input(prompt))</code>, but you can still make it work:</p> <pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; input() math.sqrt(2) 1.4142135623730951 &gt;&gt;&gt; from math import * &gt;&gt;&gt; input() sqrt(2) 1.4142135623730951 </code></pre>
0
2016-09-08T12:53:18Z
[ "python", "math", "input", "nameerror" ]
Getting GET in django view
39,390,919
<p>I have this URL pattern to get to my view: </p> <pre><code>url(r'^api/cabinet/(?P&lt;cabinetid&gt;[0-9]+)/bin/$', views.api_cabinetbin), </code></pre> <p>and pointing my browser to <code>http://domain/api/cabinet/10/bin/</code> gives me the info on cabinet 10.</p> <p>I would like to put some extra info to the URL, like this: <code>http://domain/api/cabinet/10/bin/?format=test</code>. However, this gives me a 404 (<code>{"detail":Not found."}</code> is the message I see in my browser).</p> <p>The view is like this:</p> <pre><code>@api_view(['GET', 'POST']) @authentication_classes((SessionAuthentication,BasicAuthentication,TokenAuthentication)) @permission_classes((IsAuthenticated,)) def api_cabinetbin(request, cabinetid): ... </code></pre>
1
2016-09-08T12:27:06Z
39,391,614
<p>Turns out, <code>format</code> has some magical properties in Django REST framework.</p> <p>Using another variable did work.</p>
2
2016-09-08T12:57:59Z
[ "python", "django", "django-rest-framework" ]
Convert Model.Objects.all() to JSON in python using django
39,390,927
<p>I have a list of objects of the same model type. I want to iterate over this list and create a JSON to send back. I tried some things like 2-dim arrays, google,... but can't find something like this? Though I think it can't be difficult. </p> <p>my code now is:</p> <pre><code>def get_cashflows(request): response_data = {} cashflow_set = Cashflow.objects.all(); i = 0; for e in cashflow_set.iterator(): c = Cashflow(value=e.value, date=str(e.date)); response_data[i] = c; return HttpResponse( json.dumps(response_data), content_type="application/json" ) </code></pre> <p>here it is not possible to give model in json.dumps. But how i give more then 1 object to it?</p> <p>error : </p> <pre><code>TypeError: coercing to Unicode: need string or buffer, float found [08/Sep/2016 14:14:00] "GET /getcashflow/ HTTP/1.1" 500 85775 </code></pre>
0
2016-09-08T12:27:23Z
39,391,091
<p>As @Ivan mentions the DRF does this out of the box if you want an API layer, but if you just want a basic view to return some json without the overhead of configuring a new package then it should be a fairly simple operation with django's serializers:</p> <pre><code>from django.core import serializers def get_cashflows(request): response_data = {} cashflow_set = Cashflow.objects.all(); i = 0; for e in cashflow_set.iterator(): c = Cashflow(value=e.value, date=str(e.date)); response_data[i] = c; return HttpResponse( serializers.serialize("json", response_data), content_type="application/json" ) </code></pre> <p>The docs have a good break down of how to achieve this even if the default json serializer doesn't quite do what you need</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-formats-json" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-formats-json</a></p> <p>Also to note: </p> <p>you could use the queryset directly <code>serializers.serialize("json", Cashflow.objects.all())</code></p> <p>and you're also not incrementing <code>i</code> in your loop...</p>
0
2016-09-08T12:35:14Z
[ "python", "json", "django" ]
Finding craters [descending/ ascending ints] in a python list of ints
39,391,007
<p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first int in the crater. If the last number is equal or smaller than the first - it should be in the output at the end of the crater. If the last number is greater than the first number in the crater - it should not be appended to the end of the output list.</p> <p>For example, for the list: 1,2,3,4,5,6,5,4,3,4,5,6,7,8,9 A "crater" would be: 6,5,4,3,4,5,6</p> <p>My code:</p> <pre><code>def find_crater(my_list): cur_crater = [] for i in range(len(my_list)-1): #check if the numbers are decreasing if (my_list[i] - my_list[i+1] &gt; 0): cur_crater.append(my_list[i]) #if increasing - check if we're in a crater #and if current number is smaller than begining of crater elif len(cur_crater) &gt; 1 and my_list[i] &lt;= cur_crater[0]: cur_crater.append(my_list[i]) #print crater and empty list elif len(cur_crater) &gt; 1 and my_list[i+1] &gt; cur_crater[0]: print(cur_crater) cur_crater = [] #continue if we're out of a crater else: continue #catching the last crater in the list if len(cur_crater) &gt; 1: #include last int if my_list[i] - my_list[-1] &lt; 0 and my_list[-1] &lt;= cur_crater[0]: cur_crater.append(my_list[-1]) print(cur_crater) return </code></pre> <p>I have called the function on 2 lists. The 1st output is as expected:</p> <pre><code>ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>Ok list output [edit: not so ok - it ommited the first '4' so turns out it's not so OK after all]: </p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>However, the second list combines 2 lists of craters into 1 list in the output:</p> <pre><code>problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>problematic Output:</p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25] </code></pre> <p>I was expecting: </p> <pre><code>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>I tried to take care of this by writing: my_list[i+1] > cur_crater[0] and thus checking the size of next int in the list - but that does not seem to fix it [I left it in the code even though it does not do the trick in hopes of someone explaining why is that wrong/ not working?].</p> <p>In conclusion, my code can't handle it when there is a crater right after a crater with only one int in between. </p> <p>If the input is: </p> <p>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 10, 9, 8, 6, 9, 10]</p> <p>Then the output is one long list, but I'd like to split it after list item 12 and before list item 21, but the output is one long list. </p> <p>I would love to get info about any library or method that can give me more ideas regarding a better and more efficient solution. </p>
2
2016-09-08T12:31:17Z
39,392,144
<p>Here is what I came with:</p> <pre><code>def find_crater(my_list): previous = None current_crater = [] crater_list = [] for elem in my_list: #For the first element if not previous: previous = elem continue if len(current_crater) == 0: if elem &gt; previous: previous = elem else: current_crater.append(previous) previous = elem else: if elem &gt; current_crater[0]: current_crater.append(previous) crater_list.append(current_crater) current_crater = [] previous = elem else: current_crater.append(previous) previous = elem if len(current_crater) != 0: if elem &gt; current_crater[0]: current_crater.append(previous) crater_list.append(current_crater) else: current_crater.append(previous) crater_list.append(current_crater) return crater_list </code></pre> <p>That gave me the exact output you want:</p> <pre><code>In [5]: ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, ...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, ...: 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] In [6]: find_crater(ok_list) Out[6]: [[12, 4, 7, 4, 2, 4, 5, 6, 5, 12], [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17], [28, 19, 17, 19, 21, 19, 12, 23, 25, 27]] In [7]: problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, ...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, ...: 17, 27, 19, 25, 19, 12, 23, 25, 27] In [8]: find_crater(problematic) Out[8]: [[12, 4, 7, 4, 2, 4, 5, 6, 5, 12], [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17], [27, 19, 25, 19, 12, 23, 25, 27]] </code></pre>
0
2016-09-08T13:22:11Z
[ "python", "list", "int" ]
Finding craters [descending/ ascending ints] in a python list of ints
39,391,007
<p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first int in the crater. If the last number is equal or smaller than the first - it should be in the output at the end of the crater. If the last number is greater than the first number in the crater - it should not be appended to the end of the output list.</p> <p>For example, for the list: 1,2,3,4,5,6,5,4,3,4,5,6,7,8,9 A "crater" would be: 6,5,4,3,4,5,6</p> <p>My code:</p> <pre><code>def find_crater(my_list): cur_crater = [] for i in range(len(my_list)-1): #check if the numbers are decreasing if (my_list[i] - my_list[i+1] &gt; 0): cur_crater.append(my_list[i]) #if increasing - check if we're in a crater #and if current number is smaller than begining of crater elif len(cur_crater) &gt; 1 and my_list[i] &lt;= cur_crater[0]: cur_crater.append(my_list[i]) #print crater and empty list elif len(cur_crater) &gt; 1 and my_list[i+1] &gt; cur_crater[0]: print(cur_crater) cur_crater = [] #continue if we're out of a crater else: continue #catching the last crater in the list if len(cur_crater) &gt; 1: #include last int if my_list[i] - my_list[-1] &lt; 0 and my_list[-1] &lt;= cur_crater[0]: cur_crater.append(my_list[-1]) print(cur_crater) return </code></pre> <p>I have called the function on 2 lists. The 1st output is as expected:</p> <pre><code>ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>Ok list output [edit: not so ok - it ommited the first '4' so turns out it's not so OK after all]: </p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>However, the second list combines 2 lists of craters into 1 list in the output:</p> <pre><code>problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>problematic Output:</p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25] </code></pre> <p>I was expecting: </p> <pre><code>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>I tried to take care of this by writing: my_list[i+1] > cur_crater[0] and thus checking the size of next int in the list - but that does not seem to fix it [I left it in the code even though it does not do the trick in hopes of someone explaining why is that wrong/ not working?].</p> <p>In conclusion, my code can't handle it when there is a crater right after a crater with only one int in between. </p> <p>If the input is: </p> <p>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 10, 9, 8, 6, 9, 10]</p> <p>Then the output is one long list, but I'd like to split it after list item 12 and before list item 21, but the output is one long list. </p> <p>I would love to get info about any library or method that can give me more ideas regarding a better and more efficient solution. </p>
2
2016-09-08T12:31:17Z
39,392,602
<p>Try this:</p> <p>We just slice the list finding <code>start_index:end_index</code> making three cases</p> <ul> <li>When element is equal</li> <li>When element is greater </li> <li>Boundary case when last element even if smaller may need to be sliced</li> </ul> <hr> <pre><code>def find_crater(l): result = [] start_index = 0 for i in range( start_index +1,len(l)): start = l[start_index] if i==len(l)-1 and l[i]!=start: result = l[start_index:i+1] print result elif l[i]==start: end_index = i+1 result = l[start_index:end_index] start_index = end_index +1 if len(result)&gt;1: print result elif l[i]&gt;start: end_index = i result = l[start_index:end_index] start_index = end_index if len(result)&gt;1: print result </code></pre> <p><strong>Input:</strong></p> <pre><code>ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p><strong>Output:</strong></p> <pre><code>find_crater(ok_list) find_crater(problematic) [12, 4, 7, 4, 2, 4, 5, 6, 5, 12] [25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [28, 19, 17, 19, 21, 19, 12, 23, 25, 27] [12, 4, 7, 4, 2, 4, 5, 6, 5, 12] [25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [27, 19, 25, 19, 12, 23, 25, 27] </code></pre>
0
2016-09-08T13:43:43Z
[ "python", "list", "int" ]
Finding craters [descending/ ascending ints] in a python list of ints
39,391,007
<p>I have a list of ints in python, and I would like the output to be a list of different "craters" in the sequence. I define a crater as a sequence of numbers that begins with descending ints that gradually grow bigger, until they reach a number that is equal to the first int of the crater or greater than the first int in the crater. If the last number is equal or smaller than the first - it should be in the output at the end of the crater. If the last number is greater than the first number in the crater - it should not be appended to the end of the output list.</p> <p>For example, for the list: 1,2,3,4,5,6,5,4,3,4,5,6,7,8,9 A "crater" would be: 6,5,4,3,4,5,6</p> <p>My code:</p> <pre><code>def find_crater(my_list): cur_crater = [] for i in range(len(my_list)-1): #check if the numbers are decreasing if (my_list[i] - my_list[i+1] &gt; 0): cur_crater.append(my_list[i]) #if increasing - check if we're in a crater #and if current number is smaller than begining of crater elif len(cur_crater) &gt; 1 and my_list[i] &lt;= cur_crater[0]: cur_crater.append(my_list[i]) #print crater and empty list elif len(cur_crater) &gt; 1 and my_list[i+1] &gt; cur_crater[0]: print(cur_crater) cur_crater = [] #continue if we're out of a crater else: continue #catching the last crater in the list if len(cur_crater) &gt; 1: #include last int if my_list[i] - my_list[-1] &lt; 0 and my_list[-1] &lt;= cur_crater[0]: cur_crater.append(my_list[-1]) print(cur_crater) return </code></pre> <p>I have called the function on 2 lists. The 1st output is as expected:</p> <pre><code>ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>Ok list output [edit: not so ok - it ommited the first '4' so turns out it's not so OK after all]: </p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [28, 19, 17, 19, 21, 19, 12, 23, 25, 27] </code></pre> <p>However, the second list combines 2 lists of craters into 1 list in the output:</p> <pre><code>problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>problematic Output:</p> <pre><code>[12, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17, 27, 19, 25, 19, 12, 23, 25] </code></pre> <p>I was expecting: </p> <pre><code>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12] [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17] [27, 19, 25, 19, 12, 23, 25, 27] </code></pre> <p>I tried to take care of this by writing: my_list[i+1] > cur_crater[0] and thus checking the size of next int in the list - but that does not seem to fix it [I left it in the code even though it does not do the trick in hopes of someone explaining why is that wrong/ not working?].</p> <p>In conclusion, my code can't handle it when there is a crater right after a crater with only one int in between. </p> <p>If the input is: </p> <p>[12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 10, 9, 8, 6, 9, 10]</p> <p>Then the output is one long list, but I'd like to split it after list item 12 and before list item 21, but the output is one long list. </p> <p>I would love to get info about any library or method that can give me more ideas regarding a better and more efficient solution. </p>
2
2016-09-08T12:31:17Z
39,392,656
<p>Presuming your expected output is wrong which it seems to be, all you want to do is go until you find an element >= to the start of the chain and catch chains that only contain a single element:</p> <pre><code>def craters(lst): it = iter(lst) # get start of first chain first = next(it) tmp = [first] # iterate over the remaining for ele in it: # &gt;= ends chain if ele &gt;= first: # if equal, add it and call # next(it) to set the next first element. if ele == first: tmp.append(ele) yield tmp first = next(it) tmp = [first] # else yield the group if it has &gt; 1 element. # if it has 1 element it is not a descending start sequecne else: if len(tmp) &gt; 1: yield tmp tmp = [ele] first = ele else: tmp.append(ele) if len(tmp) &gt; 1: # catch single element last yield tmp </code></pre> <p>Output:</p> <pre><code>In [5]: ok_list = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, ...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, ...: 17, 27, 28, 19, 17, 19, 21, 19, 12, 23, 25, 27] In [6]: problematic = [12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 23, ...: 24, 26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, ...: 17, 27, 19, 25, 19, 12, 23, 25, 27] In [7]: ex_ok = [[12, 4, 7, 4, 2, 4, 5, 6, 5, 12], ...: [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17], ...: [28, 19, 17, 19, 21, 19, 12, 23, 25, 27]] In [8]: ex_p = [[12,4, 7, 4, 2, 4, 5, 6, 5, 12], ...: [26, 25, 22, 10, 9, 8, 6, 9, 10, 11, 13, 12, 14, 17], ...: [27, 19, 25, 19, 12, 23, 25, 27]] In [9]: print(list(craters(problematic)) == ex_p) True In [10]: print(list(craters(ok_list)) == ex_ok) True In [11]: print(list(craters([12, 4, 7, 4, 2, 4, 5, 6, 5, 12, 21, 10, 9, 8, 6, 9, 10]))) [[12, 4, 7, 4, 2, 4, 5, 6, 5, 12], [21, 10, 9, 8, 6, 9, 10]] In [12]: list(craters([1, 2, 3, 4, 5, 6, 5, 4, 3, 4, 5, 6, 7, 8, 9])) Out[13]: [[6, 5, 4, 3, 4, 5, 6]] </code></pre> <p>That does not involve any slicing/indexing you can lazily return each group.</p> <p>To simplify your algorithm, the steps are:</p> <ul> <li><p>Start with the first element, then check if the next element is >=, if it is and it is equal add it to the group, if it is > set that to be the new <em>start</em> of the group.</p></li> <li><p>If the new first is not greater than the next element the length of that group will be one as it does not satisfy <em>sequence of numbers that begins with descending</em>. So we keep consuming and setting the next element to be the <em>first</em> element of the sequence until we find one the is > the next element, that is what the call to <code>next(it)</code> is doing then we just need to wash and repeat.</p></li> </ul>
0
2016-09-08T13:46:08Z
[ "python", "list", "int" ]
Exception handling in Django of queryset
39,391,068
<p>I'm trying to catch an exception if a user does not exist and redirect if that's the case. </p> <p>When I run this I get an error saying:</p> <blockquote> <p>'NoneType' object is not iterable</p> </blockquote> <pre><code>try: return {'sub_user': User.objects.get(username=username)} except User.DoesNotExist: redirect('home') </code></pre> <p>How can I catch this error? I tried with:</p> <pre><code>try: return {'sub_user': User.objects.get(username=username)} except User is None: redirect('home') </code></pre> <p>But that gave me another error:</p> <blockquote> <p>catching classes that do not inherit from BaseException is not allowed</p> </blockquote>
-1
2016-09-08T12:34:38Z
39,391,185
<p>The problem is not in how you catch the exception.</p> <p>You need to return the result of the call to <code>redirect</code>.</p>
2
2016-09-08T12:39:09Z
[ "python", "django", "python-3.x" ]
Extracting hand writing text out in shape with OpenCV
39,391,080
<p>I am very new to OpenCV Python and I really need some help here.</p> <p>So what I am trying to do here is to extract out these words in the image below.</p> <p><a href="http://i.stack.imgur.com/XsSOP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XsSOP.jpg" alt="hand drawn image"></a></p> <p>The words and shapes are all hand drawn, so they are not perfect. I have did some coding below. </p> <p>First of all, I grayscale the image</p> <pre><code>img_final = cv2.imread(file_name) img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) </code></pre> <p>Then I use THRESH_INV to show the content</p> <pre><code>ret, new_img = cv2.threshold(image_final, 100 , 255, cv2.THRESH_BINARY_INV) </code></pre> <p>After which, I dilate the content</p> <pre><code>kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3 , 3)) dilated = cv2.dilate(new_img,kernel,iterations = 3) </code></pre> <p>I dilate the image is because I can identify text as one cluster</p> <p>After that, I apply boundingRect around the contour and draw around the rectangle</p> <pre><code>contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours index = 0 for contour in contours: # get rectangle bounding contour [x,y,w,h] = cv2.boundingRect(contour) #Don't plot small false positives that aren't text if w &lt; 10 or h &lt; 10: continue # draw rectangle around contour on original image cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2) </code></pre> <p>This is what I got after that.</p> <p><a href="http://i.stack.imgur.com/vxKYi.png" rel="nofollow"><img src="http://i.stack.imgur.com/vxKYi.png" alt="result image"></a></p> <p>I am only able to detect one of the text. I have tried many other methods but this is the closet results I have got and it does not fulfill the requirement.</p> <p>The reason for me to identify the text is so that I can get the X and Y coordinate of each of the text in this image by putting a bounding Rectangle "boundingRect()".</p> <p>Please help me out. Thank you so much</p>
0
2016-09-08T12:35:00Z
39,394,512
<p>You can use the fact that the connected component of the letters are much smaller than the large strokes of the rest of the diagram.</p> <p>I used opencv3 connected components in the code but you can do the same things using findContours.</p> <p>The code:</p> <pre><code>import cv2 import numpy as np # Params maxArea = 150 minArea = 10 # Read image I = cv2.imread('i.jpg') # Convert to gray Igray = cv2.cvtColor(I,cv2.COLOR_RGB2GRAY) # Threshold ret, Ithresh = cv2.threshold(Igray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # Keep only small components but not to small comp = cv2.connectedComponentsWithStats(Ithresh) labels = comp[1] labelStats = comp[2] labelAreas = labelStats[:,4] for compLabel in range(1,comp[0],1): if labelAreas[compLabel] &gt; maxArea or labelAreas[compLabel] &lt; minArea: labels[labels==compLabel] = 0 labels[labels&gt;0] = 1 # Do dilation se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(25,25)) IdilateText = cv2.morphologyEx(labels.astype(np.uint8),cv2.MORPH_DILATE,se) # Find connected component again comp = cv2.connectedComponentsWithStats(IdilateText) # Draw a rectangle around the text labels = comp[1] labelStats = comp[2] #labelAreas = labelStats[:,4] for compLabel in range(1,comp[0],1): cv2.rectangle(I,(labelStats[compLabel,0],labelStats[compLabel,1]),(labelStats[compLabel,0]+labelStats[compLabel,2],labelStats[compLabel,1]+labelStats[compLabel,3]),(0,0,255),2) </code></pre> <p><a href="http://i.stack.imgur.com/k0UdG.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/k0UdG.jpg" alt="enter image description here"></a></p>
2
2016-09-08T15:09:46Z
[ "python", "opencv" ]
How to use opencv functions in C++ file and bind it with Python?
39,391,136
<p>I want to pass an image from python script to c++ code for opencv computations. To bind the two I have followed <a href="https://github.com/Algomorph/pyboostcvconverter" rel="nofollow">this</a>. The binding is working fine But when I use any opencv in-built functions it gives me error. </p> <p>Traceback (most recent call last): File "/home/prashant/Desktop/example.py", line 1, in import pbcvt # your module, also the name of your compiled dynamic library file w/o the extension ImportError: /usr/local/lib/python2.7/dist-packages/pbcvt.so: undefined symbol: _ZN2cv8cvtColorERKNS_11_InputArrayERKNS_12_OutputArrayEii</p> <p>I am using opencv 3.1 and python 2.7.Any help/guidance is much appreciated.`</p> <p>Code for reference. Python file.</p> <pre><code>import pbcvt import numpy as np import cv2 a = cv2.imread("/home/prashant/Documents/opencv-practice/screenshot.png") c = pbcvt.dot(a) cv2.imshow("gray image",c) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>C++ code:</p> <pre><code>#include &lt;pyboostcvconverter/pyboostcvconverter.hpp&gt; #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; namespace pbcvt { using namespace std; using namespace boost::python; cv::Mat dot(PyObject *image) { cv::Mat matImage, greyMat; matImage = pbcvt::fromNDArrayToMat(image); cv::cvtColor(matImage, greyMat, CV_BGR2GRAY); return greyMat; } cv::Mat dot2(cv::Mat leftMat, cv::Mat rightMat) { auto c1 = leftMat.cols, r2 = rightMat.rows; if (c1 != r2) { PyErr_SetString(PyExc_TypeError, "Incompatible sizes for matrix multiplication."); throw_error_already_set(); } cv::Mat result = leftMat * rightMat; return result; } #if (PY_VERSION_HEX &gt;= 0x03000000) static void *init_ar() { #else static void init_ar(){ #endif Py_Initialize(); import_array(); return NUMPY_IMPORT_ARRAY_RETVAL; } BOOST_PYTHON_MODULE (pbcvt) { //using namespace XM; init_ar(); //initialize converters to_python_converter&lt;cv::Mat, pbcvt::matToNDArrayBoostConverter&gt;(); pbcvt::matFromNDArrayBoostConverter(); //expose module-level functions def("dot", dot); def("dot2", dot2); } } //end namespace pbcvt </code></pre>
0
2016-09-08T12:37:02Z
39,407,557
<p>It could be that you have to edit the CMakeLists.txt in line 27 <code>find_package(OpenCV COMPONENTS core REQUIRED)</code> and add more components like <code>find_package(OpenCV COMPONENTS core imgproc highgui REQUIRED)</code></p>
0
2016-09-09T08:51:53Z
[ "python", "c++", "opencv", "binding" ]
python XML find and replace
39,391,157
<p>After fighting a day with python / etree without considerable success:</p> <p>I have a xml file (items.xml)</p> <pre><code>&lt;symbols&gt; &lt;symbol&gt; &lt;layer class="SvgMarker"&gt; &lt;prop k="size" v="6.89"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;symbol&gt; &lt;layer class="SvgMarker"&gt; &lt;prop k="size" v="3.56"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;symbol&gt; &lt;layer class="line"&gt; &lt;prop k="size" v="1"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;/symbols&gt; </code></pre> <p><strong>Questions</strong></p> <ol> <li>read this file </li> <li>find all prop elements which have a parent element namend "layer" with class "SvgMarker" </li> <li>multiply the value of v with 1.5 </li> <li>write the content back</li> </ol> <p>I do not stick on etree if there is something easier.</p>
0
2016-09-08T12:38:02Z
39,391,909
<p>You need to take care of hierarchy in xml tags and their type conversion to perform multiplication. I tested below code with your xml, it works fine.</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse('homemade.xml') #Step 1 root = tree.getroot() for symbol in tree.findall('symbol'): for layer in symbol.findall('layer'): class_ = layer.get('class') if(class_=="SvgMarker"): #Step 2 for prop in layer.findall('prop'): new_v = prop.get('v') new_v = float(new_v)*1.5 #Step 3 prop.set('v',str(new_v)) outFile = open('homemade.xml', 'w') tree.write(outFile) #Step 4 </code></pre> <p>Hope this helps.</p>
0
2016-09-08T13:12:05Z
[ "python", "xml" ]
python XML find and replace
39,391,157
<p>After fighting a day with python / etree without considerable success:</p> <p>I have a xml file (items.xml)</p> <pre><code>&lt;symbols&gt; &lt;symbol&gt; &lt;layer class="SvgMarker"&gt; &lt;prop k="size" v="6.89"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;symbol&gt; &lt;layer class="SvgMarker"&gt; &lt;prop k="size" v="3.56"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;symbol&gt; &lt;layer class="line"&gt; &lt;prop k="size" v="1"/&gt; &lt;/layer&gt; &lt;/symbol&gt; &lt;/symbols&gt; </code></pre> <p><strong>Questions</strong></p> <ol> <li>read this file </li> <li>find all prop elements which have a parent element namend "layer" with class "SvgMarker" </li> <li>multiply the value of v with 1.5 </li> <li>write the content back</li> </ol> <p>I do not stick on etree if there is something easier.</p>
0
2016-09-08T12:38:02Z
39,392,330
<p>This would help you</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse('test.xml') # Path to input file root = tree.getroot() for prop in root.iter('.//*[@class="SvgMarker"]/prop'): prop.set('v', str(float(prop.get('v')) * 1.5)) tree.write('out.xml', encoding="UTF-8") </code></pre> <p>Ref: <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#example" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html#example</a></p>
0
2016-09-08T13:30:25Z
[ "python", "xml" ]
using x.reshape on a 1D array in sklearn
39,391,275
<p>I tried to use sklearn to use a simple decision tree classifier, and it complained that using a 1D array is now depricated and must use X.reshape(1,-1). So I did but it has turned my labels list to a list of lists with only one element so number of labels and samples do not match now. Another words my list of labels=[0,0,1,1] turns into [[0 0 1 1]]. Thanks</p> <p>This is the simple code that I used:</p> <pre><code>from sklearn import tree import numpy as np features =[[140,1],[130,1],[150,0],[170,0]] labels=[0,0,1,1] labels = np.array(labels).reshape(1,-1) clf = tree.DecisionTreeClassifier() clf = clf.fit(features,labels) print clf.predict([150,0]) </code></pre>
0
2016-09-08T12:42:40Z
39,392,612
<p>You are reshaping the wrong thing. Reshape the data your are predicting on, not your labels.</p> <pre><code>&gt;&gt;&gt; clf.predict(np.array([150,0]).reshape(1,-1)) array([1]) </code></pre> <p>Your labels have to align with your training data (features) ,so the length of both arrays should be the same. If labels is reshaped, you are right, it is a list of lists with a length of 1 and not equal to the length of your features.</p> <p>You have to reshape your test data because prediction needs an array that looks like your training data. i.e. each index needs to be a training example with the same number of features as in training. You'll see that the following two commands return a list of lists and just a list respectively.</p> <pre><code>&gt;&gt;&gt; np.array([150,0]).reshape(1,-1) array([[150, 0]]) &gt;&gt;&gt; np.array([150,0]) array([150, 0]) </code></pre>
1
2016-09-08T13:44:28Z
[ "python", "scikit-learn" ]
How to change number of iterations in maxent classifier for POS Tagging in NLTK?
39,391,280
<p>I am trying to perform POS tagging using <code>ClassifierBasedPOSTagger</code> with <code>classifier_builder=MaxentClassifier.train</code>. Here is the piece of code:</p> <pre><code>from nltk.tag.sequential import ClassifierBasedPOSTagger from nltk.classify import MaxentClassifier from nltk.corpus import brown brown_tagged_sents = brown.tagged_sents(categories='news') size = int(len(brown_tagged_sents) * 0.9) train_sents = brown_tagged_sents[:size] test_sents = brown_tagged_sents[size:] me_tagger = ClassifierBasedPOSTagger(train=train_sents, classifier_builder=MaxentClassifier.train) print(me_tagger.evaluate(test_sents)) </code></pre> <p>But after an hour of running the code, I see that it is still initialising the <code>ClassifierBasedPOSTagger(train=train_sents, classifier_builder=MaxentClassifier.train)</code>. In the output, I can see the following piece of code running:</p> <pre><code> ==&gt; Training (100 iterations) Iteration Log Likelihood Accuracy --------------------------------------- 1 -5.35659 0.007 2 -0.85922 0.953 3 -0.56125 0.986 </code></pre> <p>I think the iterations are going to be 100 before the classifier is ready to tag parts of speech to any input. That would take whole day I suppose. Why is it taking so much time? And will decreasing the iterations make this code a bit practical(meaning reduce the time and still be useful enough), and if yes, then how to decrease those iterations?</p> <p><strong>EDIT</strong></p> <p>After 1.5 hours, I get the following output:</p> <pre><code> ==&gt; Training (100 iterations) Iteration Log Likelihood Accuracy --------------------------------------- 1 -5.35659 0.007 2 -0.85922 0.953 3 -0.56125 0.986 E:\Analytics Practice\Social Media Analytics\analyticsPlatform\lib\site-packages\nltk\classify\maxent.py:1310: RuntimeWarning: overflow encountered in power exp_nf_delta = 2 ** nf_delta E:\Analytics Practice\Social Media Analytics\analyticsPlatform\lib\site-packages\nltk\classify\maxent.py:1312: RuntimeWarning: invalid value encountered in multiply sum1 = numpy.sum(exp_nf_delta * A, axis=0) E:\Analytics Practice\Social Media Analytics\analyticsPlatform\lib\site-packages\nltk\classify\maxent.py:1313: RuntimeWarning: invalid value encountered in multiply sum2 = numpy.sum(nf_exp_nf_delta * A, axis=0) Final nan 0.991 0.892155885577594 </code></pre> <p>Was the algorithm supposed to get to <code>100 iterations</code> as specified in the first line of the output and because of the error it didn't? And is there any possible way of reducing the time it took for training?</p>
0
2016-09-08T12:42:45Z
39,392,005
<p>You can set parameter value of <code>max_iter</code> to desired number.</p> <p><strong>Code:</strong></p> <pre><code>from nltk.tag.sequential import ClassifierBasedPOSTagger from nltk.classify import MaxentClassifier from nltk.corpus import brown brown_tagged_sents = brown.tagged_sents(categories='news') # Change size based on your requirement size = int(len(brown_tagged_sents) * 0.05) print("size:",size) train_sents = brown_tagged_sents[:size] test_sents = brown_tagged_sents[size:] #me_tagger = ClassifierBasedPOSTagger(train=train_sents, classifier_builder=MaxentClassifier.train) me_tagger = ClassifierBasedPOSTagger(train=train_sents, classifier_builder=lambda train_feats: MaxentClassifier.train(train_feats, max_iter=15)) print(me_tagger.evaluate(test_sents)) </code></pre> <p><strong>Output:</strong></p> <pre><code>('size:', 231) ==&gt; Training (15 iterations) Iteration Log Likelihood Accuracy --------------------------------------- 1 -4.67283 0.013 2 -0.89282 0.964 3 -0.56137 0.998 4 -0.40573 0.999 5 -0.31761 0.999 6 -0.26107 0.999 7 -0.22175 0.999 8 -0.19284 0.999 9 -0.17067 0.999 10 -0.15315 0.999 11 -0.13894 0.999 12 -0.12719 0.999 13 -0.11730 0.999 14 -0.10887 0.999 Final -0.10159 0.999 0.787489765499 </code></pre> <p><strong>For Edit</strong>:</p> <p>Those messages are RuntimeWarnings and not errors.</p> <p>As after 4th iteration it found <code>Log Likelihood = nan</code>, so it stopped processing further. So, it became final iteration. </p>
1
2016-09-08T13:15:48Z
[ "python", "nlp", "classification", "nltk" ]
Detect automatic item selection in a Listbox using Tkinter
39,391,439
<p>I mean, for Buttons you can write something like this: </p> <pre><code>def addItem(): pass addbtn = Button(mainFrame, text = "Add Item", command = addItem) </code></pre> <p>How can I do the same thing for a Listbox? Like this one for example:</p> <pre><code>def on_selection(): pass list = Listbox(mainFrame, selectmode = SINGLE, command = on_selection) # This doesn't work. </code></pre> <p>The point is that the binding <code>mainFrame.bind("&lt;&lt;ListboxSelect&gt;&gt;", on_selection)</code> <strong>doesn't works when I select an item automatically with <code>list.selection_set(selection)</code></strong>.</p> <p>In other words <strong>automatically trigger the on_selection() function when list.selection_set(...) is called</strong> without overwriting the Listbox class or selection_set function. The goal is to write one line instead of </p> <pre><code>list.selection_set(selct) on_selection() </code></pre> <p>every time.</p> <p>Is there a way to do this?</p>
-1
2016-09-08T12:50:27Z
39,403,827
<pre><code>import tkinter as tk root = tk.Tk() def on_selection(event): print(dir(event)) def some_nonevent(): print(str(2 + 2)) listbox = tk.Listbox(root, selectmode=tk.SINGLE, activestyle='none') for name in ['john', 'tim', 'sam', 'jill', 'sandra']: listbox.insert(tk.END, name) listbox.bind('&lt;&lt;ListboxSelect&gt;&gt;', on_selection) listbox.selection_set(3) listbox.grid() with open('myfile.py') as f: contents = f.read() if '\nlistbox.selection_set(2)\n' in contents: listbox.event_generate('&lt;&lt;ListboxSelect&gt;&gt;') some_nonevent() else: print('do nothing') root.mainloop() </code></pre>
0
2016-09-09T04:22:05Z
[ "python", "events", "tkinter", "listbox" ]
defining max and min yaxis values after using ax.set_yscale('log') in matplotlib python
39,391,589
<p>I generated the following chart:</p> <p><a href="http://i.stack.imgur.com/R8wui.png" rel="nofollow"><img src="http://i.stack.imgur.com/R8wui.png" alt="Regular Chart"></a></p> <p>Then wanted to adjust the vertical axis of the first subplot to show in logscale, so did <code>ax.set_yscale('log')</code>.</p> <p>This produces the following chart: <a href="http://i.stack.imgur.com/vuF3C.png" rel="nofollow"><img src="http://i.stack.imgur.com/vuF3C.png" alt="yaxis in logscale"></a></p> <p>The question is how do I set max and min levels to show in this new logarithmic yscale? </p>
1
2016-09-08T12:57:05Z
39,391,963
<p>The same as you do on any other scale, use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_ylim" rel="nofollow"><code>ax.set_ylim()</code></a></p> <p>If you want to set it to the range 8,20 as you have above, then pass those two limits to <code>set_ylim</code>:</p> <pre><code>ax.set_ylim(8, 20) </code></pre>
1
2016-09-08T13:14:16Z
[ "python", "matplotlib" ]
Gaps in border around text
39,391,592
<p>I would like to add a border around some texts in a matplotlib plot, which I can do using <code>patheffects.withStroke</code>. However, for some letters and number there is a small gap to the top right of the symbol.</p> <p>Is there a way to not have this gap?</p> <p>Minimal working example:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patheffects as patheffects fig, ax = plt.subplots() ax.text( 0.1, 0.5, "test: S6", color='white', fontsize=90, path_effects=[patheffects.withStroke(linewidth=13, foreground='black')]) fig.savefig("text_stroke.png") </code></pre> <p>This gives the image, which shows the gap in S and 6 symbols. <a href="http://i.stack.imgur.com/Ffjhl.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ffjhl.png" alt="enter image description here"></a></p> <p>I'm using matplotlib 1.5.1.</p>
2
2016-09-08T12:57:14Z
39,393,019
<p>The documentation does not mention it (or I did not found it) but, searching in the code, we can see that the <code>patheffects.withStroke</code> method accepts a lot of keyword arguments.</p> <p>You can have the list of those keyword arguments by executing this in interactive session:</p> <pre><code>&gt;&gt;&gt; from matplotlib.backend_bases import GraphicsContextBase as gcb &gt;&gt;&gt; print([attr[4:] for attr in dir(gcb) if attr.startswith("set_")]) ['alpha', 'antialiased', 'capstyle', 'clip_path', 'clip_rectangle', 'dashes', 'foreground', 'gid', 'graylevel', 'hatch', 'joinstyle', 'linestyle', 'linewidth', 'sketch_params', 'snap', 'url'] </code></pre> <p>The argument you are looking for is <code>capstyle</code> which accepts 3 possible values:</p> <ul> <li>"butt"</li> <li>"round"</li> <li>"projecting"</li> </ul> <p>In you case, the "round" value seems to fix the problem. Consider the code below...</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patheffects as patheffects fig, ax = plt.subplots() ax.text( 0.1, 0.5, "test: S6", color='white', fontsize=90, path_effects=[patheffects.withStroke(linewidth=13, foreground='black', capstyle="round")]) fig.savefig("text_stroke.png") </code></pre> <p>... it produces this:</p> <p><a href="http://i.stack.imgur.com/LmZT9.png" rel="nofollow"><img src="http://i.stack.imgur.com/LmZT9.png" alt="enter image description here"></a></p> <hr> <p>The accepted keywords arguments are actually all the <code>set_*</code> (minus the "set_" prefixe) methods of the <a href="http://matplotlib.org/api/backend_bases_api.html?highlight=graphicscontextbase#matplotlib.backend_bases.GraphicsContextBase" rel="nofollow">GraphicsContextBase</a> class. You can find details on the accepted values into the class documentation.</p>
2
2016-09-08T14:02:25Z
[ "python", "matplotlib" ]
ValueError: import data via chunks into pandas.csv_reader()
39,391,597
<p>I have a large <code>gzip</code> file which I would like to import into a pandas dataframe. Unfortunately, the file has an uneven number of columns. The data has roughly this format: </p> <pre><code>.... Col_20: 25 Col_21: 23432 Col22: 639142 .... Col_20: 25 Col_22: 25134 Col23: 243344 .... Col_21: 75 Col_23: 79876 Col25: 634534 Col22: 5 Col24: 73453 .... Col_20: 25 Col_21: 32425 Col23: 989423 .... Col_20: 25 Col_21: 23424 Col22: 342421 Col23: 7 Col24: 13424 Col 25: 67 .... Col_20: 95 Col_21: 32121 Col25: 111231 </code></pre> <p>As a test, I tried this: </p> <pre><code>import pandas as pd filename = `path/to/filename.gz` for chunk in pd.read_csv(filename, sep='\t', chunksize=10**5, engine='python'): print(chunk) </code></pre> <p>Here is the error I get in return: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/nfs/sw/python/python-3.5.1/lib/python3.5/site-packages/pandas/io/parsers.py", line 795, in __next__ return self.get_chunk() File "/nfs/sw/python/python-3.5.1/lib/python3.5/site-packages/pandas/io/parsers.py", line 836, in get_chunk return self.read(nrows=size) File "/nfs/sw/python/python-3.5.1/lib/python3.5/site-packages/pandas/io/parsers.py", line 815, in read ret = self._engine.read(nrows) File "/nfs/sw/python/python-3.5.1/lib/python3.5/site-packages/pandas/io/parsers.py", line 1761, in read alldata = self._rows_to_cols(content) File "/nfs/sw/python/python-3.5.1/lib/python3.5/site-packages/pandas/io/parsers.py", line 2166, in _rows_to_cols raise ValueError(msg) ValueError: Expected 18 fields in line 28, saw 22 </code></pre> <p>How can you allocate a certain number of columns for pandas.read_csv()?</p>
1
2016-09-08T12:57:21Z
39,391,888
<p>You could also try this:</p> <pre><code>for chunk in pd.read_csv(filename, sep='\t', chunksize=10**5, engine='python', error_bad_lines=False): print(chunk) </code></pre> <p><code>error_bad_lines</code> would skip bad lines thought. I will see if a better alternative can be found</p> <p>EDIT: In order to maintain the lines that were skipped by <code>error_bad_lines</code> we can go through the error and add it back to the dataframe</p> <pre><code>line = [] expected = [] saw = [] cont = True while cont == True: try: data = pd.read_csv('file1.csv',skiprows=line) cont = False except Exception as e: errortype = e.message.split('.')[0].strip() if errortype == 'Error tokenizing data': cerror = e.message.split(':')[1].strip().replace(',','') nums = [n for n in cerror.split(' ') if str.isdigit(n)] expected.append(int(nums[0])) saw.append(int(nums[2])) line.append(int(nums[1])-1) else: cerror = 'Unknown' print 'Unknown Error - 222' </code></pre>
1
2016-09-08T13:11:00Z
[ "python", "pandas", "chunking" ]
Django 'instancemethod' object has no attribute '__getitem__'
39,391,611
<p>Html</p> <pre><code> &lt;ul class="dropdown-menu" role="menu"&gt; &lt;li&gt;java &lt;input type="checkbox" name="categories[]" value="Java"&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;c &lt;input type="checkbox" name="categories[]" value="C"&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;network &lt;input type="checkbox" name="categories[]" value="Network"&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Python</p> <pre><code>list_categories = request.POST.getlist['categories'] </code></pre> <p>This code cause error</p> <blockquote> <p>'instancemethod' object has no attribute <code>'__getitem__'</code>.</p> </blockquote> <p>And I already tried </p> <pre><code>list.categories = request.POST['categories'] </code></pre>
2
2016-09-08T12:57:53Z
39,391,709
<p>Change </p> <pre><code>list_categories = request.POST.getlist['categories'] </code></pre> <p>for</p> <pre><code>list_categories = request.POST.getlist('categories') </code></pre> <p><code>getlist</code> is a method, so the syntax requires parenthesis.</p>
2
2016-09-08T13:02:40Z
[ "python", "django" ]
doc2vec How to cluster DocvecsArray
39,391,753
<p>I've patched the following code from examples I've found over the web:</p> <pre><code># gensim modules from gensim import utils from gensim.models.doc2vec import LabeledSentence from gensim.models import Doc2Vec from sklearn.cluster import KMeans # random from random import shuffle # classifier class LabeledLineSentence(object): def __init__(self, sources): self.sources = sources flipped = {} # make sure that keys are unique for key, value in sources.items(): if value not in flipped: flipped[value] = [key] else: raise Exception('Non-unique prefix encountered') def __iter__(self): for source, prefix in self.sources.items(): with utils.smart_open(source) as fin: for item_no, line in enumerate(fin): yield LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]) def to_array(self): self.sentences = [] for source, prefix in self.sources.items(): with utils.smart_open(source) as fin: for item_no, line in enumerate(fin): self.sentences.append(LabeledSentence(utils.to_unicode(line).split(), [prefix + '_%s' % item_no])) return self.sentences def sentences_perm(self): shuffle(self.sentences) return self.sentences sources = {'test.txt' : 'DOCS'} sentences = LabeledLineSentence(sources) model = Doc2Vec(min_count=1, window=10, size=100, sample=1e-4, negative=5, workers=8) model.build_vocab(sentences.to_array()) for epoch in range(10): model.train(sentences.sentences_perm()) print(model.docvecs) </code></pre> <p>my test.txt file contains a paragraph per line.</p> <p>The code runs fine and generates DocvecsArray for each line of text</p> <p>my goal is to have an output like so:</p> <p>cluster 1: [DOC_5,DOC_100,...DOC_N]<br> cluster 2: [DOC_0,DOC_1,...DOC_N]</p> <p>I have found the <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python">following Answer</a>, but the output is:</p> <p>cluster 1: [word,word...word]<br> cluster 2: [word,word...word]</p> <p>How can I alter the code and get document clusters?</p>
1
2016-09-08T13:04:24Z
39,392,564
<p>So it looks like you're almost there.</p> <p>You are outputting a set of vectors. For the sklearn package, you have to put those into a numpy array - using the numpy.toarray() function would probably be best. <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html" rel="nofollow">The documentation</a> for KMeans is really stellar and even across the whole library it's good.</p> <p>A note for you is that I have had much better luck with <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html#example-cluster-plot-dbscan-py" rel="nofollow">DBSCAN</a> than KMeans, which are both contained in the same sklearn library. DBSCAN doesn't require you to specify how many clusters you want to have on the output.</p> <p>There are well-commented code examples in both links.</p>
0
2016-09-08T13:41:40Z
[ "python", "machine-learning", "k-means", "word2vec", "doc2vec" ]
jinja2: including script, replacing {{variable}} and json encoding the result
39,391,789
<p>I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains <code>{{&lt;variables&gt;}}</code> that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using <code>json.dumps()</code>.</p> <p><code>str = '{ "nestedScript" : {% include "scripts/sc.ps1" | json %} }'</code></p> <p>The <code>escape</code> function isn't enough, since the finished product contains characters that are valid HTML, but not JSON.</p> <p>I'm thinking something along the lines of:</p> <p><code>str = '{ "nestedScript" : {{ include("scripts/sc.ps1") | json}} %} }'</code></p> <p>using some a custom filter or something, but I can't seem to write the include function such that it also does variable replacement in the script. This is my script so far that I am including as a global:</p> <h1>Complete example</h1> <p>Folder structure:</p> <pre><code> . └── templates ├── test.json └── scripts     └── script.ps1 </code></pre> <p>template-file:</p> <pre><code>test.json = '{ "nestedScript" : {{ include("scripts/script.ps1") | json}} }' </code></pre> <p>Script:</p> <pre><code>loader = jinja2.FileSystemLoader("templates") env = jinja2.Environment(loader=self.loader) template = env.get_template("test.json") template.render({ 'service_name': 'worker', 'context_name': 'googlesellerratings', }) </code></pre> <p>result:</p> <pre><code>{ "nestedScript" : "echo {{service_name}}" } </code></pre>
0
2016-09-08T13:06:01Z
39,412,150
<p>Solved this in a way that feels a little hackish, so I'd love some feedback. When instantiating my class, I defined a global function called <code>include_script</code>:</p> <pre><code>loader = jinja2.FileSystemLoader(templates_folder) env = inja2.Environment(loader=self.loader) env.globals['include_script'] = render_script_func(env) </code></pre> <p>the <code>render_script_func</code> returns a function that retrieves the context from the environment and uses it to render the file I referenced:</p> <pre><code>def render_script_func(env): def render_script(name): ctx = env.globals['context'] tmpl = env.get_template(name) raw = tmpl.render(ctx) return json.dumps(raw) return render_script </code></pre> <p>Now, before rendering, all one has to do, is add the context for the rendering to the global <code>context</code> object:</p> <pre><code>template = env.get_template(template_name) template.environment.globals["context"] = ctx renderedData = template.render(ctx) </code></pre> <p>And when a template uses <code>{{ include_script("path/to/script") }}</code> the script is both rendered and then json encoded.</p> <p>Still feels a bit wrong, but so be it.</p>
0
2016-09-09T12:57:01Z
[ "python", "json", "jinja2" ]
jinja2: including script, replacing {{variable}} and json encoding the result
39,391,789
<p>I'm attempting to build a json document using Jinja2 and the document has a nested script. The script contains <code>{{&lt;variables&gt;}}</code> that I need to replace along with non-json characters. Therefore, the script needs to be json-escaped afterwards using <code>json.dumps()</code>.</p> <p><code>str = '{ "nestedScript" : {% include "scripts/sc.ps1" | json %} }'</code></p> <p>The <code>escape</code> function isn't enough, since the finished product contains characters that are valid HTML, but not JSON.</p> <p>I'm thinking something along the lines of:</p> <p><code>str = '{ "nestedScript" : {{ include("scripts/sc.ps1") | json}} %} }'</code></p> <p>using some a custom filter or something, but I can't seem to write the include function such that it also does variable replacement in the script. This is my script so far that I am including as a global:</p> <h1>Complete example</h1> <p>Folder structure:</p> <pre><code> . └── templates ├── test.json └── scripts     └── script.ps1 </code></pre> <p>template-file:</p> <pre><code>test.json = '{ "nestedScript" : {{ include("scripts/script.ps1") | json}} }' </code></pre> <p>Script:</p> <pre><code>loader = jinja2.FileSystemLoader("templates") env = jinja2.Environment(loader=self.loader) template = env.get_template("test.json") template.render({ 'service_name': 'worker', 'context_name': 'googlesellerratings', }) </code></pre> <p>result:</p> <pre><code>{ "nestedScript" : "echo {{service_name}}" } </code></pre>
0
2016-09-08T13:06:01Z
39,418,644
<p>Given the (incomplete) example it seems you are searching the <code>filter</code> tag.</p> <p>First the script in a form that's actually runnable and defines a <code>json</code> filter in terms of <code>json.dumps()</code>:</p> <pre><code>import json import jinja2 loader = jinja2.FileSystemLoader('templates') env = jinja2.Environment(loader=loader) env.filters['json'] = json.dumps template = env.get_template('test.json') print( template.render({ 'service_name': 'worker', 'context_name': 'googlesellerratings', }) ) </code></pre> <p>The missing PowerShell script with characters that cause trouble if used as is in JSON (<code>"</code>):</p> <pre><code>echo "{{service_name}}" </code></pre> <p>Now the solution for the <code>test.json</code> template:</p> <pre><code>{ "nestedScript" : {% filter json %}{% include "scripts/script.ps1" %}{% endfilter %} } </code></pre> <p>And finally the printed result:</p> <pre><code>{ "nestedScript" : "echo \"worker\"" } </code></pre>
0
2016-09-09T19:37:04Z
[ "python", "json", "jinja2" ]