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
Beautifulsoup can't extract data in this website
38,694,480
<pre><code>import requests from bs4 import BeautifulSoup import lxml import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] f =open('ala2009link.csv','r') s=open('2009alanews.csv','w') for row in csv.reader(f): url=row[0] print url res = requests.get(url) print res.content so...
0
2016-08-01T08:45:01Z
38,698,345
<p>The reason that no results are returned is because this website requires that you have a User-Agent header in your request.</p> <p>To fix this add a headers parameter with a <code>User-Agent</code> to the <code>requests.get()</code> like so.</p> <pre><code>url = 'http://www.rolltide.com/news/2009/6/23/Bert_Bank_Pa...
0
2016-08-01T12:00:50Z
[ "python", "request", "beautifulsoup" ]
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python
38,694,486
<p>I am getting below error while trying to do this </p> <pre><code>from datetime import datetime time1 = '2016-08-01 13:39:00+05:30' x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z') print(x) </code></pre> <p>Error is ...</p> <pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%...
2
2016-08-01T08:45:09Z
38,694,701
<p>this works in python 3.4, conforms to the datetime documentation</p> <pre><code>from datetime import datetime time1 = '2016-08-01 13:39:00+0530' x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S%z') print(x) </code></pre> <p>gives</p> <pre><code>2016-08-01 13:39:00+05:30 </code></pre>
0
2016-08-01T08:56:39Z
[ "python", "datetime" ]
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python
38,694,486
<p>I am getting below error while trying to do this </p> <pre><code>from datetime import datetime time1 = '2016-08-01 13:39:00+05:30' x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z') print(x) </code></pre> <p>Error is ...</p> <pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%...
2
2016-08-01T08:45:09Z
38,698,484
<p>If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the <a href="https://dateutil.readthedocs.io/en/latest/" rel="nofollow"><code>dateutil</code></a> library for <a class='doc-link' href="http://stackoverflow.com/documentation/python/484/date-and-time/1592/parsing-a-string-into-a-timez...
1
2016-08-01T12:08:26Z
[ "python", "datetime" ]
How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python
38,694,486
<p>I am getting below error while trying to do this </p> <pre><code>from datetime import datetime time1 = '2016-08-01 13:39:00+05:30' x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z') print(x) </code></pre> <p>Error is ...</p> <pre><code>ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%...
2
2016-08-01T08:45:09Z
39,757,674
<p>Consider using <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow">dateparser</a>:</p> <pre><code>&gt;&gt;&gt; dateparser.parse('2016-08-01 13:39:00+05:30') datetime.datetime(2016, 8, 1, 13, 39) &gt;&gt;&gt; dateparser.parse('2016-08-01 13:39:00+05:30', settings={'TO_TIMEZONE': 'UTC'}) datetime.datetim...
0
2016-09-28T21:06:59Z
[ "python", "datetime" ]
Slicing a graph
38,694,540
<p>I have created a graph in python but I now need to take a section of the graph and expand this by using a small range of the original data, but I don't know how to find the row number of the results that form the range or how I can create a graph using just these results form the file. This is the code I have for th...
-1
2016-08-01T08:48:12Z
38,694,846
<p>If I understand you correctly, you could do it this way:</p> <pre><code>my_slice = slice(np.argwhere(x&gt;5.5e3)[0], np.argwhere(x&gt;6e3)[0]) x = data[my_slice,0] y = data[my_slice,1] </code></pre> <p><code>np.argwhere(x&gt;5.5e3)[0]</code> is the index of the first occurrence of <code>x&gt;5.5e3</code> and like ...
0
2016-08-01T09:05:11Z
[ "python", "indexing", "graph", "slice" ]
Slicing a graph
38,694,540
<p>I have created a graph in python but I now need to take a section of the graph and expand this by using a small range of the original data, but I don't know how to find the row number of the results that form the range or how I can create a graph using just these results form the file. This is the code I have for th...
-1
2016-08-01T08:48:12Z
38,695,763
<p>solved by using</p> <pre><code>plt.axis([5500, 6000, 0, 8e-15]) </code></pre> <p>thanks for help.</p>
0
2016-08-01T09:48:38Z
[ "python", "indexing", "graph", "slice" ]
fill in a column only if its not none or empty
38,694,675
<p>I am trying to fill in the missing values of county column based on its add_suburb value. I tried the following two codes which doesn't work</p> <pre><code>for index, row in fileco.iterrows(): df.loc[df['add_suburb'].str.contains(str(row['place'])) &amp; ( df['county'].str=='') , 'county'] = str('County '+r...
0
2016-08-01T08:55:17Z
38,697,879
<p>I don't exactly understand what you're trying to do in the loop (what are you looping over?), but I think it should work if you enclose your conditions in brackets like this:</p> <pre><code>df.loc[(condition1) &amp; (condition2)] = "replacement" </code></pre>
0
2016-08-01T11:38:07Z
[ "python", "dataframe" ]
Why os.fdopen doesn't work on fd 2?
38,694,837
<p>Take stderr for example:</p> <pre><code>import os fh = os.fdopen(2, "w") fh.write("hello\n") </code></pre> <p>It doesn't output anything, what's wrong with the codes?</p>
0
2016-08-01T09:04:45Z
38,694,861
<p>You just need to flush it out.</p> <pre><code>fh.flush() </code></pre>
1
2016-08-01T09:06:06Z
[ "python" ]
Django Send mail only when one perticular field is changed
38,694,948
<p>I am using : <a href="https://github.com/ui/rq-scheduler" rel="nofollow">RQ scheduler</a></p> <p>There is a Job model in my project:</p> <pre><code>class Job(models.Model): # Other fields status = models.CharField( max_length=2, choices=choices.JOB_STATE_CHOICES, default=choices.PENDING_APPROVAL) ...
1
2016-08-01T09:10:31Z
38,695,098
<p>You shoud use <a href="https://github.com/romgar/django-dirtyfields" rel="nofollow">django-dirtyfields</a> and send email immediately or add this job_id to RQ. Full docs <a href="http://django-dirtyfields.readthedocs.io/en/develop/" rel="nofollow">here</a></p> <p>Or update <code>updated_at</code> field only when <c...
1
2016-08-01T09:17:19Z
[ "python", "django", "redis" ]
Why is there no delay between same-line printing?
38,695,003
<pre><code>print 'foo', time.sleep(1) print 'bar' </code></pre> <p>This seems to run <code>time.sleep(1)</code> first, then prints <code>"foo bar"</code> all at once.</p> <p>However, printing both <code>foo</code> and <code>bar</code> on its own lines produces the expected delay between the print statements:</p> <pr...
2
2016-08-01T09:12:55Z
38,695,092
<p><code>print</code> by default prints to sys.stdout and it is line-buffered. you could flush the buffer each time after a print statement</p> <pre><code>import time import sys print 'foo' sys.stdout.flush() time.sleep(1) print 'bar </code></pre> <p>reference: <a href="https://docs.python.org/3/library/sys.html" re...
6
2016-08-01T09:17:04Z
[ "python", "printing", "output", "delay" ]
Python pause thread, do manually and reset time
38,695,060
<p>I need to call function every x seconds but with option to call it manually and in this case reset time. I have sth like this:</p> <pre><code>import time import threading def printer(): print("do it in thread") def do_sth(event): while not event.is_set(): printer() time.sleep(10) event = ...
0
2016-08-01T09:15:41Z
38,699,054
<p>It may be that <em>buffered outputs</em> are the culprits and thus - you're are getting your expected behaviour.</p> <p>I changed your code to the following, and it seems to do something (if that's what you wanted, is up to you):</p> <pre><code>import time import threading def printer(): print("do it in threa...
0
2016-08-01T12:34:26Z
[ "python", "multithreading" ]
Pandas combining keys when grouping by multiple column
38,695,103
<p>I have 3 levels of grouping based on 3 keys: key1, key2, key3 I want to get the sum of a column (c1) for the following combination:</p> <pre><code>key1, sum(c1) key1, key2, sum(c1) key1, key2, key3, sum(c1) </code></pre> <p>I am getting the sums in 3 different dfs. (sum_k1, sum_k1k2, sum_k1k2k3) I want to combine ...
1
2016-08-01T09:17:26Z
38,698,654
<p>I don't know if this is the most efficient way to go about it, but this is what I came up with</p> <pre><code>import pandas as pd import random # Prepare the sample dataset table = [] for i in range(100000): row = {'key1': random.choice('ABC'), 'key2': random.choice('KLM'), 'key3': rando...
1
2016-08-01T12:17:00Z
[ "python", "json", "pandas", "numpy" ]
Pandas combining keys when grouping by multiple column
38,695,103
<p>I have 3 levels of grouping based on 3 keys: key1, key2, key3 I want to get the sum of a column (c1) for the following combination:</p> <pre><code>key1, sum(c1) key1, key2, sum(c1) key1, key2, key3, sum(c1) </code></pre> <p>I am getting the sums in 3 different dfs. (sum_k1, sum_k1k2, sum_k1k2k3) I want to combine ...
1
2016-08-01T09:17:26Z
38,760,884
<p>I used multilevel index for this and xs for this one. Get the lowest level aggregates.</p> <pre><code>lvl3_grp = df.groupby(['key1', 'key2', 'key3'])['col1', 'col2'].sum() lvl3_grp = lvl3_grp.reset_index() lvl3_grp.set_index(['key1', 'key2', 'key3'], inplace=True) res = {} for k1 in lvl3_grp.index.levels[0]: sums...
0
2016-08-04T07:20:54Z
[ "python", "json", "pandas", "numpy" ]
Search for word in text file in Python
38,695,194
<p>I have this text file:</p> <pre><code>MemTotal,5,2016-07-30 12:02:33,781 model name,3,2016-07-30 13:37:59,074 model,3,2016-07-30 15:39:59,075 </code></pre> <p>I need to find the line with the model.</p> <p>My code:</p> <pre><code>term = "model" file = open('file.txt') for line in file: line.strip().split('/n...
-1
2016-08-01T09:22:04Z
38,695,340
<p>Just replace the line:</p> <pre><code>if term in line: </code></pre> <p>with line :</p> <pre><code>if line.startswith('model,'): </code></pre>
2
2016-08-01T09:28:24Z
[ "python", "python-2.7" ]
Search for word in text file in Python
38,695,194
<p>I have this text file:</p> <pre><code>MemTotal,5,2016-07-30 12:02:33,781 model name,3,2016-07-30 13:37:59,074 model,3,2016-07-30 15:39:59,075 </code></pre> <p>I need to find the line with the model.</p> <p>My code:</p> <pre><code>term = "model" file = open('file.txt') for line in file: line.strip().split('/n...
-1
2016-08-01T09:22:04Z
38,695,388
<p>It depends on what your file contains. Your example is quite light, but I see a few immediate solutions that don't change your code too much :</p> <ol> <li><p>Replace <code>term = 'model'</code> by <code>term = 'model,'</code> and this will only show the line you want.</p></li> <li><p>Use some additional criteria, ...
1
2016-08-01T09:30:48Z
[ "python", "python-2.7" ]
Search for word in text file in Python
38,695,194
<p>I have this text file:</p> <pre><code>MemTotal,5,2016-07-30 12:02:33,781 model name,3,2016-07-30 13:37:59,074 model,3,2016-07-30 15:39:59,075 </code></pre> <p>I need to find the line with the model.</p> <p>My code:</p> <pre><code>term = "model" file = open('file.txt') for line in file: line.strip().split('/n...
-1
2016-08-01T09:22:04Z
38,695,424
<p>You can split the line by <code>,</code> and check for the first field:</p> <pre><code>term = "model" file = open('file.txt') for line in file: line = line.strip().split(',') # &lt;--- if term == line[0]: # &lt;--- You can also stay with "if term in line:" if you doesn't care which field the "...
1
2016-08-01T09:32:34Z
[ "python", "python-2.7" ]
Adding a new column for substruction : Length of values does not match length of index
38,695,196
<p>I have a dataframe which contains: <code>TIMESTAMP</code>, <code>P_ACT_KW</code> and <code>P_SOUSCR</code>.</p> <pre><code>df2 = pd.read_csv('C:/Users/Demonstrator/Downloads/power.csv',delimiter=';') </code></pre> <p>First, I dropped missing observations: </p> <pre><code>df_no_missing = df2.dropna() </code></pre>...
1
2016-08-01T09:22:06Z
38,695,371
<p>You can add parameter <code>inplace=True</code> to <code>df2</code> for inplace removing <code>NaN</code> and correct parentheses:</p> <pre><code>import pandas as pd import numpy as np df2 = pd.DataFrame({'P_SOUSCR':[10,2,1,np.nan], 'P_ACT_KW':[4,5,6,4]}) df2.dropna(inplace=True) print (df2) ...
0
2016-08-01T09:30:02Z
[ "python", "pandas" ]
My form's is_valid method returns false
38,695,315
<p>I have a form as below :</p> <pre><code>class CookDuty(forms.Form ): # cook = None def __init__(self, *args, **kwargs): cook = kwargs.pop('cook') super(CookDuty, self).__init__(*args, **kwargs) self.fields['duty'].choices = foods_for_cook(cook) duty = forms.ChoiceField(widget=for...
1
2016-08-01T09:27:26Z
38,695,428
<p>When it is a post request, you need to pass the POST data to the form.</p> <pre><code>if request.method == 'POST': c = Cook.objects.all()[0] form = CookDuty(cook=c, data=request.POST) </code></pre> <p>Without the post data, the form is unbound, so will always be invalid.</p> <p>See the docs on <a href="ht...
1
2016-08-01T09:32:41Z
[ "python", "django", "django-forms", "django-views" ]
Invoking a pyramid framework application from inside another application
38,695,372
<p>I have a Python application running in a framework that drives a network protocol to control remote devices. Now I want to add a browser-based monitoring and control and I am looking at the Pyramid framework to build it.</p> <p>Normally you start a Pyramid application using <strong>pserve</strong> from a command l...
1
2016-08-01T09:30:04Z
38,709,093
<p>A WSGI app is basically a function which receives some input and returns a response, you don't really need <code>pserve</code> to serve a WSGI app, it's more like a wrapper which assembles an application from an .ini file.</p> <p>Have a look at <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/...
1
2016-08-01T22:30:34Z
[ "python", "python-3.x", "pyramid", "wsgi" ]
Read a line from a file in python
38,695,508
<p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p> <pre><code>no-syslog = yes # (or no to disable) logfile = /tmp/logfile </code></pre> <p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <co...
0
2016-08-01T09:36:50Z
38,695,656
<p>You can just split the line to get the value you want:</p> <pre><code>line.split(' = ')[1] </code></pre> <p>However, you might want to look at the documentation for <a href="https://docs.python.org/3/library/configparser.html" rel="nofollow">configparser module</a>.</p>
2
2016-08-01T09:43:36Z
[ "python", "file-io" ]
Read a line from a file in python
38,695,508
<p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p> <pre><code>no-syslog = yes # (or no to disable) logfile = /tmp/logfile </code></pre> <p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <co...
0
2016-08-01T09:36:50Z
38,695,684
<p>Change the code to:</p> <pre><code>with open('/etc/mcelog/mcelog.conf', 'r+') as fp: for line in fp: if re.search("no-syslog =", line) and re.search("= no", line): memoryErrors = readLogFile("/var/log/messages") mcelogPathFound = true break elif re.search("no-...
1
2016-08-01T09:44:29Z
[ "python", "file-io" ]
Read a line from a file in python
38,695,508
<p>I have one file named <code>mcelog.conf</code> and I am reading this file in my code. Contents of the file are </p> <pre><code>no-syslog = yes # (or no to disable) logfile = /tmp/logfile </code></pre> <p>Program will read the <code>mcelog.conf</code> file and will check for the <code>no-syslog</code> tag, if <co...
0
2016-08-01T09:36:50Z
38,704,654
<p>I liked the suggestion of the <code>configparser</code> module, so here is an example of that (Python 3)</p> <p>For the given input, it will output <code>reading /var/log/messages</code></p> <pre><code>import configparser, itertools config = configparser.ConfigParser() filename = "/tmp/mcelog.conf" def readLogFil...
0
2016-08-01T17:21:45Z
[ "python", "file-io" ]
Lists in Python
38,695,557
<p>I noticed that you can multiply list by scalar but the behavior is weird If I multiply: </p> <pre><code>[2,3,4] * 3 </code></pre> <p>I get:<br> <code>[2,3,4,2,3,4,2,3,4</code>]<br> I understand the results but what it's good for? Is there any other weird operations like that?</p>
1
2016-08-01T09:38:33Z
38,695,585
<p>The main purpose of this operand is for initialisation. For example, if you want to initialize a list with 20 equal numbers you can do it using a for loop:</p> <pre><code>arr=[] for i in range(20): arr.append(3) </code></pre> <p>An alternative way will be using this operator:</p> <pre><code>arr = [3] * 20 </c...
3
2016-08-01T09:40:30Z
[ "python" ]
Lists in Python
38,695,557
<p>I noticed that you can multiply list by scalar but the behavior is weird If I multiply: </p> <pre><code>[2,3,4] * 3 </code></pre> <p>I get:<br> <code>[2,3,4,2,3,4,2,3,4</code>]<br> I understand the results but what it's good for? Is there any other weird operations like that?</p>
1
2016-08-01T09:38:33Z
38,695,647
<p>The operation has a use of creating arrays initialized with some value.</p> <p>For example <code>[5]*1000</code> means "create an array of length 1000 initialized with 5".</p> <p>If you want to multiply each element by 3, use</p> <pre><code>map(lambda x: 3*x, arr) </code></pre>
0
2016-08-01T09:43:11Z
[ "python" ]
jupyter notebook not working in Mac
38,695,693
<p>I can have already gone through the following questions: </p> <p><a href="http://stackoverflow.com/questions/35029029/jupyter-notebook-command-does-not-work-on-mac">Jupyter notebook command does not work on Mac</a></p> <p><a href="http://stackoverflow.com/questions/35313876/after-installing-with-pip-jupyter-comman...
0
2016-08-01T09:44:51Z
38,695,949
<p>you can check a couple of issues:</p> <p>• Verify you have Python correctly installed. I recommend installing with <a href="http://brew.sh" rel="nofollow">Homebrew</a> for the right dependencies to be installed too:</p> <pre><code>brew install python </code></pre> <p>• You can also install Python and Jupyter ...
1
2016-08-01T09:57:30Z
[ "python", "osx", "jupyter", "jupyter-notebook" ]
RethinkDB Join and Order using Python
38,695,756
<p>I would like to join and order the field in RethinkDB. My tables and sample data is:</p> <p>Category Table</p> <pre><code>{ "id": "2be434e0-0f34-4705-ba7f-560437a8e65c" , "name": "IT" } { "id": "76db46b7-2b1b-4c6e-99dd-83852d921ec0" , "name": "Electronic" } { "id": "61774bf5-b197-4676-be95-873d6f701243" , "na...
0
2016-08-01T09:48:12Z
38,720,752
<pre><code> r.table('Category').merge(lambda row:{'count':r.table('Item').filter({'category_id':row['id']}).count()}).order_by(r.desc('count')).run() </code></pre> <p>I got the solution. Thanks all.</p>
0
2016-08-02T12:43:42Z
[ "python", "rethinkdb-python" ]
Can't find efficient way to replicate original code after refactoring of pandas .resample()
38,695,811
<p>I am passing a dictionary of pandas DataFrames (or a pandas panel) into the function below in order convert from daily to monthly data. Each DataFrame represents a field (eg Open, High, Low or Close) in datetime v stock code space. The function works fine but I am getting deprecation warnings. I can't find an eff...
1
2016-08-01T09:51:15Z
38,696,609
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.tseries.resample.Resampler.aggregate.html" rel="nofollow"><code>Resampler.aggregate</code></a> and pass a dict of the Column names as keys with it's respective intended operation as the values.</p> <pre><code>dict_ohlcv = {'Op...
0
2016-08-01T10:32:47Z
[ "python", "pandas", "resampling", "deprecation-warning" ]
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
38,695,947
<p>I have dataframe and I need to make an assessment of the quality before using nearest neighbor method. I use <code>sklearn.cross_validation.KFold</code>, but I don't know, how can I give a dataframe to this function. </p> <pre><code>quality = KFold(df, n_folds=5, shuffle=True, random_state=42) </code></pre> <p>But...
-6
2016-08-01T09:57:22Z
38,696,065
<p>Does <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.KFold.html" rel="nofollow">documentation</a> say you can pass a dataframe as the first argument? No. It accepts number. Read the docs carefully. </p>
-1
2016-08-01T10:02:17Z
[ "python", "pandas", "scikit-learn" ]
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
38,695,947
<p>I have dataframe and I need to make an assessment of the quality before using nearest neighbor method. I use <code>sklearn.cross_validation.KFold</code>, but I don't know, how can I give a dataframe to this function. </p> <pre><code>quality = KFold(df, n_folds=5, shuffle=True, random_state=42) </code></pre> <p>But...
-6
2016-08-01T09:57:22Z
38,696,348
<p>You're supposed to pass the number of rows you want to perform the split on:</p> <pre><code>quality = KFold(len(df), n_folds=5, shuffle=True, random_state=42) </code></pre> <p>this will use the number of rows of the df and return you an array of indices to perform the splits on, you can then use this to slice the ...
3
2016-08-01T10:18:23Z
[ "python", "pandas", "scikit-learn" ]
Optimising the generation of a large number of random numbers using python 3
38,696,070
<p>I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too slow for <code>N &gt; 10^6</code>, especially when I am averaging over N trials <co...
2
2016-08-01T10:02:31Z
38,696,572
<p>By the Central Limit Theorem, your random variable will closely follow a normal law.</p> <p>The sum of the eight uniform variables has a bell-shaped distribution over the range [0, π]. If I am right, the distribution can be represented as a B-spline of order 8. Taking the sine gives a value in range [0, 1]. You ca...
1
2016-08-01T10:30:17Z
[ "python", "python-3.x", "optimization", "random", "numbers" ]
Optimising the generation of a large number of random numbers using python 3
38,696,070
<p>I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too slow for <code>N &gt; 10^6</code>, especially when I am averaging over N trials <co...
2
2016-08-01T10:02:31Z
38,696,624
<p>Given your requirement of obtaining the result with this method, <code>np.sin(np.random.uniform(0,np.pi/8,size=(8,10**6,25)).sum(axis=0)).mean(axis=0)</code> gets you your 25 trials pretty quickly... This is fully vectorised (and concise which is always a bonus!) so I doubt you could do any better...</p> <p>Explana...
6
2016-08-01T10:33:29Z
[ "python", "python-3.x", "optimization", "random", "numbers" ]
Python: How to check the number of occurrences and top (n) values in a dataframe?
38,696,101
<p>I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.</p> <pre><code> Date Location 0 09/17/1908 Virginia 1 07/12/1912 New Jersey 2 08/06/1913 Canada 3 09/09/1913 ...
-1
2016-08-01T10:04:55Z
38,696,167
<pre><code>countCollection = df['collection'].value_counts() </code></pre> <p><code>.value_counts()</code> will give you a count for the items from the collection named <code>collection</code> in a dataFrame.</p> <p>Also, as you mentioned you're new to Python, to get the final value:</p> <pre><code>countCollection["...
1
2016-08-01T10:08:40Z
[ "python", "python-3.x", "pandas" ]
Python: How to check the number of occurrences and top (n) values in a dataframe?
38,696,101
<p>I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.</p> <pre><code> Date Location 0 09/17/1908 Virginia 1 07/12/1912 New Jersey 2 08/06/1913 Canada 3 09/09/1913 ...
-1
2016-08-01T10:04:55Z
38,697,308
<p>You may use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> together with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow">size</a>:</p> <pre><code>counts = df.groupby('Locati...
0
2016-08-01T11:09:07Z
[ "python", "python-3.x", "pandas" ]
python source file analysis and transformation using Rascal
38,696,394
<p>I would like to scan all project files in a python project, identify all instantiations of objects that are subclass of a certain type and then: 1. Add the "yield" keyword to the object instantiation 2. identify all call stack for that object creation, and add a decorator to all functions in that call stack.</p> <p...
1
2016-08-01T10:21:07Z
38,777,882
<p>When you have a representation of your Python source code as tree (parse tree or abstract syntax tree) you can convert this to a Rascal data type and use Rascal for further processing. This can be achieved by using and connecting an existing Python parser to generate the Rascal representation of your Python program...
1
2016-08-04T21:43:05Z
[ "python", "callstack", "rascal" ]
Creating a Django demo-user who can't save to the database
38,696,423
<p>I'm creating a Django web application on which users can create an account for free. I have also set-up a demo user which is already configured and has data attached to its account. Purpose of this demo account is to give a new user a quick overview of what the application can do.</p> <p>Now I would like to have th...
1
2016-08-01T10:22:31Z
38,702,863
<blockquote> <p>Off course there are multiple ways of doing this that I know of. But they all require me to edit multiple pages or views:</p> </blockquote> <p>Well, you won't have to repeat the logic for every template or view if you utilize certain <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel...
1
2016-08-01T15:38:11Z
[ "python", "django" ]
Why does this for loop not work
38,696,469
<p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p> <p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. ...
-2
2016-08-01T10:24:52Z
38,696,692
<p>It looks like your <code>draw</code> function is called in an infinite loop, probably here: <code>frame.set_draw_handler(draw)</code> so you should lookup that frame function.</p> <p>Also no need for <code>deck1</code> just do: <code>deck = range(8) * 2</code></p>
1
2016-08-01T10:36:35Z
[ "python", "python-2.7" ]
Why does this for loop not work
38,696,469
<p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p> <p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. ...
-2
2016-08-01T10:24:52Z
38,697,297
<p>The <code>draw()</code> function in simplegui is called about 60 per second and the code in the <code>for</code> loop inside your version doubles the global <code>C_W</code> 16 times each time the function is called. This means its value quickly becomes astronomical and the text is drawn way off the screen to the ri...
1
2016-08-01T11:08:29Z
[ "python", "python-2.7" ]
Why does this for loop not work
38,696,469
<p>I want to write a for loop that iterates over a list. The list is a deck of "cards". There are 16 cards, numbered 0 - 7. Each number appears in the list twice.</p> <p>When I comment the for loop out, the program correctly displays 1 card on the left side of the canvas. But when I use the loop, nothing's displayed. ...
-2
2016-08-01T10:24:52Z
38,697,498
<p>Try this loop:</p> <pre><code>for card,count in enumerate(deck): canvas.draw_text(str(card), (C_W * count+1 / 3, C_H - 25), 60, "White") </code></pre> <p>It prevents the global value from changing, and gives you the intended effect.</p>
0
2016-08-01T11:18:31Z
[ "python", "python-2.7" ]
Python Serial communition with device
38,696,483
<p><a href="http://i.stack.imgur.com/GnHLc.jpg" rel="nofollow">enter image description here</a></p> <p>I am making serial port communication device from a genious guy's work instructables.com.</p> <p>It will measure the distance of the hamster's running in a day or month.</p> <p>Using 4, 6 pin of the serial port ca...
1
2016-08-01T10:25:45Z
38,700,384
<p>Well, <code>ser = serial.Serial("/dev/ttyS1")</code> is for a linux machine, on windows you'll need something like <code>ser = serial.Serial("COM1")</code> (you can check what COM do you need in the device manager).</p> <p>As a side note, </p> <pre><code>def waitForPinOff(): while ser.getDSR() == 1: 1 # D...
0
2016-08-01T13:39:23Z
[ "python", "serial-port", "port", "distance", "period" ]
make a 2D matrix of strings to match mesh coordinates
38,696,546
<p>I have a structured mesh. The mesh has coordinates (X,Y), but each mesh cell also has an alphanumerical code assigned. The mesh X and Y coordinates are generated as 2D arrays with meshgrid. </p> <p>The series with the alphanumerical codes looks like this</p> <pre><code>Index Code 0 aa1 1 aa2 2 ...
1
2016-08-01T10:28:50Z
38,696,734
<p>Well, if you know the length of each row you can use just a list. You can make the 2D array in "your head" and convert the coordinates into their position in an array.</p> <p><strong>Example</strong>:</p> <p>You have got a row_length x column_length grid, therefore you have a list with a row_length*column_length e...
0
2016-08-01T10:38:43Z
[ "python", "arrays", "pandas", "numpy" ]
make a 2D matrix of strings to match mesh coordinates
38,696,546
<p>I have a structured mesh. The mesh has coordinates (X,Y), but each mesh cell also has an alphanumerical code assigned. The mesh X and Y coordinates are generated as 2D arrays with meshgrid. </p> <p>The series with the alphanumerical codes looks like this</p> <pre><code>Index Code 0 aa1 1 aa2 2 ...
1
2016-08-01T10:28:50Z
38,697,546
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html" rel="nofollow"><code>numpy.array_split</code></a> or even <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow"><code>numpy.split</code></a> to split the arrays into multiple sub-a...
1
2016-08-01T11:20:45Z
[ "python", "arrays", "pandas", "numpy" ]
Writing to particular address in memory in python
38,696,575
<p>I know python is a high level language and manages the memory allocation etc. on its own user/developer doesn't need to worry much unlike other languages like c, c++ etc.</p> <p>but is there a way through will we can write some value in a particular memory address in python</p> <p>i know about id() which if hex ty...
1
2016-08-01T10:30:34Z
38,696,887
<p>Python itself does not include any facilities to allow the programmer direct access to memory. This means that sadly (or happily, depending on your outlook) the answer to your question is "no".</p>
1
2016-08-01T10:47:46Z
[ "python", "python-2.7" ]
Writing to particular address in memory in python
38,696,575
<p>I know python is a high level language and manages the memory allocation etc. on its own user/developer doesn't need to worry much unlike other languages like c, c++ etc.</p> <p>but is there a way through will we can write some value in a particular memory address in python</p> <p>i know about id() which if hex ty...
1
2016-08-01T10:30:34Z
38,706,483
<p>To begin with, as noted in the comments, it's quite a question why you would want to do such a thing at all. You should consider carefully whether there is any alternative.</p> <p>Having said that, it is quite easy to do so via extensions. Python itself is built so that it is easy to <a href="https://docs.python.or...
2
2016-08-01T19:16:56Z
[ "python", "python-2.7" ]
Regular expression to match the word but not the word inside other strings
38,696,658
<p>I have a rich text like </p> <pre><code>Sample text for testing:&lt;a href="http://www.baidu.com" title="leoshi"&gt;leoshi&lt;/a&gt;leoshi for details balala... Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple! </code></pre> <p>What I want to match is the word <code>leoshi</code>, but not ins...
-1
2016-08-01T10:35:04Z
38,696,810
<p>I used a positive lookbehind to start the match <strong>AFTER</strong> the closing tag <code>&lt;/a&gt;</code>. And then matched <code>leoshi</code> with a parentheses when it is used as a separate word.</p> <p>Regex: <code>(?&lt;=&lt;\/a&gt;).*?\b(leoshi)</code></p> <p><a href="https://regex101.com/r/rM4eQ9/6" re...
0
2016-08-01T10:43:27Z
[ "javascript", "python", "regex" ]
Regular expression to match the word but not the word inside other strings
38,696,658
<p>I have a rich text like </p> <pre><code>Sample text for testing:&lt;a href="http://www.baidu.com" title="leoshi"&gt;leoshi&lt;/a&gt;leoshi for details balala... Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple! </code></pre> <p>What I want to match is the word <code>leoshi</code>, but not ins...
-1
2016-08-01T10:35:04Z
38,696,876
<p>The best approach (using regex) would be to first remove all of the tags, then detect the word in the remaining string. For example:</p> <pre><code>var str_without_links = str.replace(/&lt;a\b.*?&lt;\/a&gt;/, '') str_without_links.match(/leoshi/) </code></pre> <p>If you need to preserve the string length (for cor...
-1
2016-08-01T10:47:16Z
[ "javascript", "python", "regex" ]
Regular expression to match the word but not the word inside other strings
38,696,658
<p>I have a rich text like </p> <pre><code>Sample text for testing:&lt;a href="http://www.baidu.com" title="leoshi"&gt;leoshi&lt;/a&gt;leoshi for details balala... Welcome to RegExr v2.1 by gskinner.com, proudly hosted by Media Temple! </code></pre> <p>What I want to match is the word <code>leoshi</code>, but not ins...
-1
2016-08-01T10:35:04Z
38,697,800
<p>A trick aimed to handle such "find a word but not a specific context" cases is described here: <a href="http://www.rexegg.com/regex-best-trick.html" rel="nofollow">http://www.rexegg.com/regex-best-trick.html</a>.</p> <p>In essence it is: match your word in the undesired context or (using alternation) just this word...
0
2016-08-01T11:33:32Z
[ "javascript", "python", "regex" ]
Maya command not return reference list from *.ma
38,696,668
<p>In Maya I execute command to get the list for references included in the file:</p> <pre><code>cmds.file(fileName, q=True, reference=True) </code></pre> <p>It returns a list of the first level for references. And there is already a problem. If the file has an extension *.mb - then everything comes back. But if the ...
0
2016-08-01T10:35:25Z
38,880,238
<p>use <a href="http://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/CommandsPython/referenceQuery.html" rel="nofollow">referenceQuery</a> instead if you just want information about what is referenced from the file</p>
0
2016-08-10T17:46:43Z
[ "python", "reference", "maya", "mel" ]
Maya command not return reference list from *.ma
38,696,668
<p>In Maya I execute command to get the list for references included in the file:</p> <pre><code>cmds.file(fileName, q=True, reference=True) </code></pre> <p>It returns a list of the first level for references. And there is already a problem. If the file has an extension *.mb - then everything comes back. But if the ...
0
2016-08-01T10:35:25Z
39,084,039
<p>which maya version is the .ma file in compare to the main session where the "cmds.file(fileName, q=True, reference=True)" command will call </p>
0
2016-08-22T16:03:14Z
[ "python", "reference", "maya", "mel" ]
How to set variable of a class from another function?
38,696,669
<p>I want to replace 'YouTube' with 'Gmail' from fat function. This class and function are in two separate files.</p> <pre><code>class Data(): url = 'YouTube' from . import Data def fat(): r = 'Gmail' Data.url = r return "something" </code></pre> <p>how can i do this?</p>
0
2016-08-01T10:35:26Z
38,698,775
<p>Actually It's showing 'Youtube' because you are not calling fat() function i guess here is the code please go for it</p> <p>file class_var contains</p> <pre><code>class Data(): url = 'YouTube' </code></pre> <p>file func_var contains</p> <pre><code>from class_var import Data def fat(): r = 'Gmail' Dat...
0
2016-08-01T12:22:33Z
[ "python" ]
Python pandas display dataframe as a table with tabs and not spaces
38,696,799
<p>How can I print or display a <code>pandas.DataFrame</code> object like a "real" table? I mean using <strong>only one tab</strong> between columns and <strong>not more spaces</strong>. In IPython Jupyter Notebook I can use the following code to get a "real" table style:</p> <pre><code>from IPython.core.display impor...
0
2016-08-01T10:42:48Z
38,696,850
<p>Unfortunately the Jupyter Notebook is a specialized environment, which knows how to tell objects to render themselves as HTML inside the Jupyter (web) interface. I don't believe Spyder has this capability.</p>
1
2016-08-01T10:46:06Z
[ "python", "pandas", "printing" ]
HTTP Requests (Python + VBA)
38,696,804
<p>can anyone guide me in the right direction when it comes to http requests with python? What I'm after is a Excel-VBA add-in which will track which workbooks the user opens and when etc. While that's already done, I would now like to get the information to a database.</p> <p>For that purpose I can imagine running a ...
0
2016-08-01T10:43:11Z
38,697,144
<p>Nice project! You can use <a href="https://flask-restful.readthedocs.io/en/latest/" rel="nofollow">Flask</a> for the Python part to build a small REST Api and for the VBA part you can use <a href="https://github.com/VBA-tools/VBA-Web" rel="nofollow">VBA-WEB</a> to consume that API. </p> <p>Both Flask than VBA-WEB a...
1
2016-08-01T11:01:05Z
[ "python", "vba", "server" ]
plot multiple columns on one axis python
38,696,813
<p>I'm new to data analysis and am looking to plot a table that has multiple date columns as one of the axis. I have tried this:</p> <pre><code>years = [data['1996'],data['1997'],data['1998'],data['1999'],data['2000']] data.plot(x=years,y=data['City']) </code></pre> <p>and </p> <pre><code>[data.plot(data[:,x],data2[...
0
2016-08-01T10:43:31Z
38,697,101
<p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from column <code>City</code>, then transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><code>T<...
0
2016-08-01T10:58:40Z
[ "python", "pandas", "matplotlib" ]
How to replace/bypass a property in Python?
38,696,819
<p>I would like to have a class with an attribute <code>attr</code> that, when accessed for the first time, runs a function and returns a value, and then <em>becomes</em> this value (its type changes, etc.).</p> <p>A similar behavior can be obtained with:</p> <pre><code>class MyClass(object): @property def at...
1
2016-08-01T10:44:03Z
38,697,657
<p>This looks a bit like premature optimization : you want to skip a method call by making a descriptor change itself. </p> <p>It's perfectly possible, but it would have to be justified.</p> <p>To modify the descriptor from your property, you'd have to be editing your class, which is probably not what you want.</p> ...
2
2016-08-01T11:27:00Z
[ "python", "properties", "attributes" ]
Regex - Why won't this regex work in Python?
38,696,855
<p>I have this expression</p> <pre><code>:([^"]*) \(([^"]*)\) </code></pre> <p>and this text</p> <pre><code>:chkpf_uid ("{4astr-hn389-918ks}") :"#cert" ("false") </code></pre> <p>Im trying to match it so that on the first sentence ill get these groups:</p> <ol> <li>chkpf_uid</li> <li>{4astr-hn389-918ks}</li> </ol...
1
2016-08-01T10:46:18Z
38,697,436
<p><em>Sidenote: your input may require a specific parser to handle, especially if it may have escape sequences.</em></p> <p>Answering the question itself, remember that a regex is processed from left to right <em>sequentially</em>, and the string is processed the same here. A match is returned if the pattern matches ...
1
2016-08-01T11:15:13Z
[ "python", "regex" ]
Python Flask failing on combined GET and POST request
38,697,035
<p>I'm writing a function in Python Flask to deal with the oauth2 call backs of multiple api's.</p> <p>The function as it stands is:</p> <pre><code>@app.route('/external_api/&lt;api&gt;/oauth2callback', methods=['POST', 'GET']) def gdrive_oauth2callback(api): toReturn = external_api.APIs[api]['lib'].oauth2callbac...
1
2016-08-01T10:55:32Z
38,699,342
<p>I think that flask must not be failing, if you take a look to this example, it works perfectly, <a href="http://flask.pocoo.org/snippets/62/" rel="nofollow">http://flask.pocoo.org/snippets/62/</a>.</p> <p>I tried: </p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/&lt;name&gt;",methods=['...
0
2016-08-01T12:48:23Z
[ "python", "flask" ]
how to convert Python 2 unicode() function into correct Python 3.x syntax
38,697,037
<p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p> <p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and f...
-10
2016-08-01T10:55:35Z
38,750,151
<p>You can test whether there is such a function as <code>unicode()</code> in the version of Python that you're running. If not, you can create a <code>unicode()</code> alias for the <code>str()</code> function, which does in Python 3 what <code>unicode()</code> did in Python 2, as all strings are unicode in Python 3.<...
1
2016-08-03T17:28:37Z
[ "python", "python-3.x", "python-unicode" ]
how to convert Python 2 unicode() function into correct Python 3.x syntax
38,697,037
<p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p> <p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and f...
-10
2016-08-01T10:55:35Z
38,751,157
<p>As has already been pointed out in the comments, there is already <a href="https://docs.python.org/3/howto/pyporting.html">advice on porting from 2 to 3</a>.</p> <p>Having recently had to port some of my own code from 2 to 3 and maintain compatibility for each for now, I wholeheartedly recommend using <a href="http...
10
2016-08-03T18:30:41Z
[ "python", "python-3.x", "python-unicode" ]
how to convert Python 2 unicode() function into correct Python 3.x syntax
38,697,037
<p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p> <p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and f...
-10
2016-08-01T10:55:35Z
38,782,128
<p>First, as a strategy, I would take a small part of your program and try to port it. The number of <code>unicode</code> calls you are describing suggest to me that your application cares about string representations more than most and each use-case is often different.</p> <p>The important consideration is that <em>...
4
2016-08-05T06:01:12Z
[ "python", "python-3.x", "python-unicode" ]
how to convert Python 2 unicode() function into correct Python 3.x syntax
38,697,037
<p>I enabled the compatibility check in my Python IDE and now I realize that the inherited Python 2.7 code has a lot of calls to <code>unicode()</code> which are not allowed in Python 3.x.</p> <p>I looked at the <a href="https://docs.python.org/2/library/functions.html#unicode" rel="nofollow">docs</a> of Python2 and f...
-10
2016-08-01T10:55:35Z
38,860,645
<p>Short answer: Replace all <code>unicode</code> calls with <code>str</code> calls.</p> <p>Long answer: In Python 3, Unicode was replaced with strings because of its abundance. The following solution should work if you are only using Python 3:</p> <pre><code>unicode = str # the rest of your goes goes here </code></p...
0
2016-08-09T21:20:51Z
[ "python", "python-3.x", "python-unicode" ]
How to pass parmeters to functions inside tf.cond in Tensorflow?
38,697,045
<p>I have following simple placeholders:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[1]) y = tf.placeholder(tf.float32, shape=[1]) z = tf.placeholder(tf.float32, shape=[1]) </code></pre> <p>There are two functions <code>f1</code> and <code>f2</code> defined as:</p> <pre><code>def fn1(a, b): return tf.m...
1
2016-08-01T10:56:02Z
38,700,367
<p>The easiest would be to define your functions in the call:</p> <pre><code>result = tf.cond(pred, lambda: tf.mul(a, b), lambda: tf.add(a, b)) </code></pre>
0
2016-08-01T13:38:26Z
[ "python", "if-statement", "tensorflow" ]
How to pass parmeters to functions inside tf.cond in Tensorflow?
38,697,045
<p>I have following simple placeholders:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[1]) y = tf.placeholder(tf.float32, shape=[1]) z = tf.placeholder(tf.float32, shape=[1]) </code></pre> <p>There are two functions <code>f1</code> and <code>f2</code> defined as:</p> <pre><code>def fn1(a, b): return tf.m...
1
2016-08-01T10:56:02Z
39,573,566
<p>You can pass parameters to the functions using <strong>lambda</strong> and the code is as bellows.</p> <pre><code>x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) z = tf.placeholder(tf.float32) def fn1(a, b): return tf.mul(a, b) def fn2(a, b): return tf.add(a, b) pred = tf.placeholder(tf.bool) r...
0
2016-09-19T12:46:21Z
[ "python", "if-statement", "tensorflow" ]
In Python, how to do groupby, sort the elements within the group and then write the output to a file
38,697,064
<p>My python data frame contents looks like this:</p> <pre><code>ID [enter image description here][1] ROLE DOB E548621 MANAGER 1980-12-31 E548622 Dy MANAGER 1983-06-01 E548623 MANAGER 1978-01-05 E548624 SSE 1988-12-31 E548625 MANAGER 1983-05-11 E548626 Dy MAN...
-2
2016-08-01T10:56:55Z
38,698,088
<p>I think Below query will do fine if not do correct me</p> <pre><code>query_obj = db.session.query(Table_name).group_by(Table_name.ROLE).order_by(desc(Table_name.DOB)) </code></pre> <p>Then run a for loop in query_obj to retrieve values as one row</p>
0
2016-08-01T11:48:33Z
[ "python", "file", "sorting", "group-by" ]
Transform string column to vector column Spark DataFrames
38,697,066
<p>I have a Spark dataframe that looks as follows:</p> <pre><code>+-----------+-------------------+ | ID | features | +-----------+-------------------+ | 18156431|(5,[0,1,4],[1,1,1])| | 20260831|(5,[0,4,5],[2,1,1])| | 91859831|(5,[0,1],[1,3]) | | 206186631|(5,[3,4,5],[1,5]) | | 223134831...
1
2016-08-01T10:56:56Z
38,699,366
<p>Not particularly efficient (it would be a good idea to use a format that preserves types) due to UDF overhead but you can do something like this:</p> <pre><code>from pyspark.mllib.linalg import Vectors, VectorUDT from pyspark.sql.functions import udf df = sc.parallelize([ (18156431, "(5,[0,1,4],[1,1,1])") ]).t...
1
2016-08-01T12:49:27Z
[ "python", "pyspark", "spark-dataframe" ]
type object 'UploadSerializers' has no attribute 'HyperlinkedModelSerializer'
38,697,068
<p>trying to do the Django Rest Framework foreign key serialization ,,however I got this error,</p> <blockquote> <p>models.py</p> </blockquote> <pre><code>class ProductsTbl(models.Model): model_number = models.CharField( max_length=255, blank=True, unique=True, error_messages={ ...
0
2016-08-01T10:56:57Z
38,698,511
<p>You've inherited your <code>UploadSerializer</code> class from serializers.ModelSerializer, not from <code>serializers.HyperLinkedModelSerializer</code> </p> <pre><code>class UploadSerializers(serializers.ModelSerializer): class Meta: model = Upload fields = ('image',) </code></pre> <p>So when ...
1
2016-08-01T12:09:38Z
[ "python", "django", "django-rest-framework" ]
Compiling Python 2.7.12 with non-system Openssl on Centos 5
38,697,181
<p>I'm currently trying to get Python 2.7.12 to compile with Openssl 1.0.2h on a Centos 5 host.</p> <p>The reason for this is that I need Paramiko 2 to run on this host but that doesn't support the system provided OpenSSL version which is 0.9.8e-fips-rhel5 01 Jul 2008.</p> <p>I've found some great hints and tips on h...
0
2016-08-01T11:03:07Z
38,700,814
<p>I think I tried to copy too cute solutions and mix and match - tidied up and simplified a bit and got it to work in the end.</p> <p>This is what I did this time:</p> <p><em>Download and install OpenSSL</em> </p> <pre><code>cd /tmp curl http://www.openssl.org/source/openssl-1.0.2h.tar.gz | tar zxvf - cd openssl-...
0
2016-08-01T13:58:39Z
[ "python", "linux", "compilation", "openssl", "centos5" ]
How to get a number from a string with regex
38,697,212
<p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p> <pre><code>Showing Results (1 – 15 of 96,831) </code></pre> <p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way wher...
-2
2016-08-01T11:04:25Z
38,697,329
<p>This is clear case where you should avoid regex as it just needs simple <code>strip</code> and <code>split</code>, like so:</p> <pre><code>&gt;&gt;&gt; s = 'Showing Results (1 – 15 of 96,831)' &gt;&gt;&gt; num = s.split()[-1] '96,831)' &gt;&gt;&gt; num.strip(')') '96,831' </code></pre> <p>Or, using <code>str.rst...
2
2016-08-01T11:09:55Z
[ "python", "regex" ]
How to get a number from a string with regex
38,697,212
<p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p> <pre><code>Showing Results (1 – 15 of 96,831) </code></pre> <p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way wher...
-2
2016-08-01T11:04:25Z
38,697,453
<p>One compact way of doing it without regex:</p> <pre><code>str = "Showing Results (1 – 15 of 96,831)" print str.split(" ")[-1].strip(")") </code></pre>
2
2016-08-01T11:16:08Z
[ "python", "regex" ]
How to get a number from a string with regex
38,697,212
<p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p> <pre><code>Showing Results (1 – 15 of 96,831) </code></pre> <p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way wher...
-2
2016-08-01T11:04:25Z
38,697,457
<p><strong>NOTE:</strong> I assume regex is necessary.</p> <pre><code>import re print (re.findall(re.compile(u'of ([0-9,]+)'), u"Showing Results (1 – 15 of 96,831)")[0].replace(",", "")) </code></pre>
2
2016-08-01T11:16:16Z
[ "python", "regex" ]
How to get a number from a string with regex
38,697,212
<p>I have a string which have following pattern. String will always remain same. Just numbers will be different</p> <pre><code>Showing Results (1 – 15 of 96,831) </code></pre> <p>I want to extract <code>96,831</code> from that string. I want to do this with regex. What can be regex for that? I have tried a way wher...
-2
2016-08-01T11:04:25Z
38,697,674
<p>Assuming all of your test strings share the same format you can simply do:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = "\d+,\d+" &gt;&gt;&gt; pattern = re.compile(regex) &gt;&gt;&gt; str = "Showing Results (1 – 15 of 96,831") &gt;&gt;&gt; pattern.findall(str) ['96,831'] </code></pre>
2
2016-08-01T11:27:53Z
[ "python", "regex" ]
Can`t render django form in the template
38,697,257
<p>after reading the <a href="https://docs.djangoproject.com/ja/1.9/topics/forms/" rel="nofollow">doc on django form</a>, I tried to build my own form but the form just won`t render in the template. I also went through similar questions on stackoverflow but no solutions can solve my problem.<br> I have this simple form...
1
2016-08-01T11:06:20Z
38,698,857
<p>I have rendered my form using a loop in my template:</p> <pre><code>{% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} ...
0
2016-08-01T12:25:56Z
[ "python", "django", "django-forms", "django-templates" ]
Can`t render django form in the template
38,697,257
<p>after reading the <a href="https://docs.djangoproject.com/ja/1.9/topics/forms/" rel="nofollow">doc on django form</a>, I tried to build my own form but the form just won`t render in the template. I also went through similar questions on stackoverflow but no solutions can solve my problem.<br> I have this simple form...
1
2016-08-01T11:06:20Z
38,711,412
<p>I finally found out what went wrong... And it`s something silly. I actually rendered the <code>user.html</code> in another function so anything I did in method <code>user</code> is not working. After instantiating a <code>form</code> instance in the <em>right</em> view method, the <code>TweetForm</code> is rendered ...
0
2016-08-02T03:42:10Z
[ "python", "django", "django-forms", "django-templates" ]
Windows path with spaces in python
38,697,330
<p>I have a problem with passing windows path to a function in python. Now, if I hard code the path everything actually works. So, my code is:</p> <pre><code>from pymatbridge import Matlab lab = Matlab(executable=r'"c:\Program Files \MATLAB\bin\matlab.exe"') lab.start() </code></pre> <p>This works fine as I am using ...
0
2016-08-01T11:10:00Z
38,697,937
<pre><code>def testpath(path): print path testpath(path='c:\\Program Files \\MATLAB\\bin\\matlab.exe') </code></pre> <p>output is:</p> <pre><code>c:\Program Files \MATLAB\bin\matlab.exe </code></pre> <p>If you are facing issues with space between <code>Program Files</code> use <code>Progra~1</code> instead</p>
0
2016-08-01T11:40:42Z
[ "python" ]
Pandas - Explanation on apply function being slow
38,697,404
<p>Apply function seems to work very slow with a large dataframe (about 1~3 million rows).</p> <p>I have checked related questions here, like <a href="http://stackoverflow.com/questions/31363908/speeding-up-pandas-apply-function">Speed up Pandas apply function</a>, and <a href="http://stackoverflow.com/questions/38267...
3
2016-08-01T11:13:34Z
38,708,239
<p>Concerning your first question, I can't say exactly why this instance is slow. But generally, <code>apply</code> does not take advantage of vectorization. Also, <code>apply</code> returns a new Series or DataFrame object, so with a very large DataFrame, you have considerable IO overhead (I cannot guarantee this is t...
0
2016-08-01T21:15:01Z
[ "python", "pandas" ]
How to return generated file download with Django REST Framework?
38,697,529
<p>I need to return generated file download as a Django REST Framework response. I tried the following:</p> <pre><code>def retrieve(self, request, *args, **kwargs): template = webodt.ODFTemplate('test.odt') queryset = Pupils.objects.get(id=kwargs['pk']) serializer = StudentSerializer(queryset) context ...
3
2016-08-01T11:19:55Z
38,697,955
<p>This may work for you:</p> <pre><code>file_path = file_url FilePointer = open(file_path,"r") response = HttpResponse(FilePointer,content_type='application/msword') response['Content-Disposition'] = 'attachment; filename=NameOfFile' return response. </code></pre> <p>For FrontEnd code refer <a href="http://stackove...
1
2016-08-01T11:41:44Z
[ "python", "django", "ms-word", "django-rest-framework", "downloading" ]
How to return generated file download with Django REST Framework?
38,697,529
<p>I need to return generated file download as a Django REST Framework response. I tried the following:</p> <pre><code>def retrieve(self, request, *args, **kwargs): template = webodt.ODFTemplate('test.odt') queryset = Pupils.objects.get(id=kwargs['pk']) serializer = StudentSerializer(queryset) context ...
3
2016-08-01T11:19:55Z
38,703,639
<p>I solved my problem by saving file in media folder and sending of the link of it to front-end.</p> <pre><code>@permission_classes((permissions.IsAdminUser,)) class StudentDocxViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): def retrieve(self, request, *args, **kwargs): template = webodt.ODFT...
1
2016-08-01T16:22:07Z
[ "python", "django", "ms-word", "django-rest-framework", "downloading" ]
Pad numpy array with fixed array as constant
38,697,641
<p>I have the following code :</p> <pre><code>x = np.array([[1]]) print x print np.lib.pad(x,(1,1),mode='constant',constant_values=[4,8]) </code></pre> <p>output : </p> <pre><code>[[1]] [[4 4 8] [4 1 8] [4 8 8]] </code></pre> <p>the problem is : in the constant values I want to put the new padding for example : </p...
3
2016-08-01T11:25:52Z
38,700,370
<p>This is a reverse engineering of <a href="http://stackoverflow.com/questions/726756/print-two-dimensional-array-in-spiral-order">Print two-dimensional array in spiral order</a>:</p> <pre><code>inner_array = np.array([3, 6, 7, 2]) outer_array = np.array([0, 23, 3, 5, 6, 8, 99, 73, 18, 42, 67, 88, 91, 12]) total_arr...
1
2016-08-01T13:38:34Z
[ "python", "arrays", "numpy" ]
Pad numpy array with fixed array as constant
38,697,641
<p>I have the following code :</p> <pre><code>x = np.array([[1]]) print x print np.lib.pad(x,(1,1),mode='constant',constant_values=[4,8]) </code></pre> <p>output : </p> <pre><code>[[1]] [[4 4 8] [4 1 8] [4 8 8]] </code></pre> <p>the problem is : in the constant values I want to put the new padding for example : </p...
3
2016-08-01T11:25:52Z
38,703,653
<p>The answer is way different since it's pretty customized to my problem ( Field Of View).</p> <pre><code>def updatevalues(self,array,elementsCount): counter =0 R1 =Agent.GetCenterCoords(array.shape)[0] C1 = array.shape[1]-1 coords = {'R1':R1,'R2':R1,'C1':C1,'C2':C1,'Phase':1} array[coords['R1'],...
0
2016-08-01T16:23:09Z
[ "python", "arrays", "numpy" ]
Issue loading objects from model in Django
38,697,722
<p>I am currently writing a web application in Django for an interview.</p> <p>On the home page I am looking to have 3 lists of various data.</p> <p>This is the error I receive when loading the home page: </p> <pre><code>invalid literal for int() with base 10: 'Critical' </code></pre> <p>This is the models.py:</p> ...
1
2016-08-01T11:29:27Z
38,697,765
<p>Since you appear to be trying to filter on the status_level on the Status model</p> <pre><code>critical_list=Event.objects.filter(event_status__status_level='Critical') </code></pre>
4
2016-08-01T11:31:33Z
[ "python", "django" ]
Run sqoop in python script
38,697,820
<p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p> <pre><code>#!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) </code></pre> <p>I got an ...
0
2016-08-01T11:34:42Z
38,698,044
<p>You need to skip " on --query param</p> <pre> sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000" </pre>
2
2016-08-01T11:46:25Z
[ "python", "sqoop" ]
Run sqoop in python script
38,697,820
<p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p> <pre><code>#!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) </code></pre> <p>I got an ...
0
2016-08-01T11:34:42Z
38,698,081
<p>The build in <code>exec</code> statement that you're using is for interpreting python code inside a python program.</p> <p>What you want is to execute an external (shell) command. For that you could use <code>call</code> from the <strong>subprocess module</strong></p> <pre><code>import subprocess subprocess.call([...
1
2016-08-01T11:48:16Z
[ "python", "sqoop" ]
Run sqoop in python script
38,697,820
<p>I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: </p> <pre><code>#!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) </code></pre> <p>I got an ...
0
2016-08-01T11:34:42Z
38,698,887
<p>You can use: Invalid syntax error noted that you haven't backslashed \"queryname\"</p> <pre><code>#!/usr/bin/env python import os sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" " os.system(sqoopcom) </code></pre>
0
2016-08-01T12:27:09Z
[ "python", "sqoop" ]
Do we have some inbuild function in python 2.7.9 which gets input both in integer & string using same function
38,697,843
<p>I am using python 2.7.9 and also i am new to stack overflow.</p> <p><code>input()</code> is used for getting integer as input from user.<br> <code>raw_input()</code> is used for getting string as input from user.</p> <p>I am looking for some common function in python 2.7.9 which will allow user to input either int...
0
2016-08-01T11:36:32Z
38,698,191
<p>You can use raw_input() and try to convert it to an int.</p> <pre><code>rawinput=raw_input("Enter a String :") try: value=int(rawinput) except ValueError: value=rawinput print "Type is ", type(value) print "Value is ", value </code></pre>
0
2016-08-01T11:53:05Z
[ "python", "input" ]
Python scikit learn multi-class multi-label performance metrics?
38,697,982
<p>I ran Random Forest classifier for my multi-class multi-label output variable. I got below output.</p> <pre><code>My y_test values Degree Nature 762721 1 7 548912 0 6 727126 1 12 14880 1 12 189505 1 12 657486 1 ...
2
2016-08-01T11:42:51Z
38,699,687
<p>To calculate the unsupported hamming loss for multiclass / multilabel, you could: </p> <pre><code>import numpy as np y_true = np.array([[1, 1], [2, 3]]) y_pred = np.array([[0, 1], [1, 2]]) np.sum(np.not_equal(y_true, y_pred))/float(y_true.size) 0.75 </code></pre> <p>You can also get the <code>confusion_matrix</co...
2
2016-08-01T13:04:09Z
[ "python", "machine-learning", "scikit-learn", "precision", "multilabel-classification" ]
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python?
38,698,000
<pre><code>In [301]: string_to_write Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D' In [302]: len(string_to_write) Out[302]: 72 In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D" In [304]: print thestring S8CC3FF000000121 In [305]: le...
1
2016-08-01T11:44:11Z
38,698,330
<p>Just use the built-in encode lib for example:</p> <pre><code>&gt;&gt;&gt; "hello".encode("hex") '68656c6c6f' &gt;&gt;&gt; "68656c6c6f".decode("hex") 'hello' &gt;&gt;&gt; </code></pre>
0
2016-08-01T11:59:47Z
[ "python", "python-2.7", "serial-port", "ascii" ]
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python?
38,698,000
<pre><code>In [301]: string_to_write Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D' In [302]: len(string_to_write) Out[302]: 72 In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D" In [304]: print thestring S8CC3FF000000121 In [305]: le...
1
2016-08-01T11:44:11Z
38,698,441
<p>You need to chop <code>string_to_write</code> into strings of length 4, convert those strings to integer, then convert each of those integers to characters. Here's an efficient way to do that in Python 2 (a different approach is needed in Python 3). Note that this code assumes that all of your hex codes contain exac...
0
2016-08-01T12:06:15Z
[ "python", "python-2.7", "serial-port", "ascii" ]
How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python?
38,698,000
<pre><code>In [301]: string_to_write Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D' In [302]: len(string_to_write) Out[302]: 72 In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D" In [304]: print thestring S8CC3FF000000121 In [305]: le...
1
2016-08-01T11:44:11Z
38,699,052
<p>may be you can use this as an example:</p> <pre><code>string_to_write = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D' temp = [i for i in string_to_write.split('0x') if i] print map(lambda x: int('0x'+x, 16), temp) </code></pre> <p>op:</p> <pre><code>[1, 83, 56, 67, 67, 51, 70, 70, 48,...
0
2016-08-01T12:34:24Z
[ "python", "python-2.7", "serial-port", "ascii" ]
How to use variable in different classes in Python?
38,698,025
<p>Here is my code:</p> <pre><code>class ProjectApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.filepaths = [] class StartPage(tk.Frame): def __init__(self, parent, controller, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **k...
1
2016-08-01T11:45:11Z
38,698,111
<p>You need to create an instance of the ProjectApp</p> <pre><code>myProjectApp = ProjectApp() </code></pre> <p>Then you will be able to call the attribute <code>filepaths</code></p> <pre><code>print(myProjectApp.filepaths) </code></pre>
2
2016-08-01T11:49:21Z
[ "python", "class" ]
How to use variable in different classes in Python?
38,698,025
<p>Here is my code:</p> <pre><code>class ProjectApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.filepaths = [] class StartPage(tk.Frame): def __init__(self, parent, controller, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **k...
1
2016-08-01T11:45:11Z
38,698,167
<p>filepaths is an instance attribute. I.e. filepath only exists after ProjectApp has been instantiated via the constructor call (= <strong>init</strong> ).</p> <p>When instantiating StartPage, you should do it like that:</p> <pre><code>app = ProjectApp() # her you create the ProjectApp instance with filepaths start_...
1
2016-08-01T11:51:42Z
[ "python", "class" ]
How to use variable in different classes in Python?
38,698,025
<p>Here is my code:</p> <pre><code>class ProjectApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.filepaths = [] class StartPage(tk.Frame): def __init__(self, parent, controller, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **k...
1
2016-08-01T11:45:11Z
38,699,447
<p>This will depend of what you want. There is two kind of attribute for object: The class attribute and the instance attribute.</p> <h3>Class attribute</h3> <p>The class attribute is the same object for each instance of the class.</p> <pre><code>class MyClass: class_attribute = [] </code></pre> <p>Here <code>M...
2
2016-08-01T12:53:10Z
[ "python", "class" ]
Creating custom source for reading from cloud datastore using latest python apache_beam cloud datafow sdk
38,698,233
<p>Recently cloud dataflow python sdk was made available and I decided to use it. Unfortunately the support to read from cloud datastore is yet to come so I have to fall back on writing custom source so that I can utilize the benefits of dynamic splitting, progress estimation etc as promised. I did study the documentat...
0
2016-08-01T11:54:52Z
38,705,127
<p>In the code you provided, the access to Datastore happens before the pipeline is even constructed:</p> <pre><code>query = client.query(kind='User').fetch() </code></pre> <p>This executes the whole query and reads all entities before the Beam SDK gets involved at all.</p> <p>More precisely, <code>fetch()</code> re...
0
2016-08-01T17:50:20Z
[ "python", "google-cloud-dataflow", "apache-beam" ]
Plot normal distribution in 3D
38,698,277
<p>I am trying to plot the comun distribution of two normal distributed variables. </p> <p>The code below plots one normal distributed variable. What would the code be for plotting two normal distributed variables?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab import...
1
2016-08-01T11:57:12Z
38,705,297
<p>It sounds like what you're looking for is a <a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="nofollow">Multivariate Normal Distribution</a>. This is implemented in scipy as <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html" rel="nofo...
1
2016-08-01T18:00:35Z
[ "python", "matplotlib", "mplot3d" ]
Python - Mac - renamed file is created at the same level with the folder that was containing it
38,698,298
<p>I am trying to rename a file in a specific path, but it moves the file at the same level with the folder that was containing it before being renamed.</p> <pre><code>import os path_to_file = "/Users/Me/file.txt" #NOTE that in my code, file name will be randomly generated path_before_file, file_name = os.path.split(...
0
2016-08-01T11:58:27Z
38,698,603
<pre><code>renamed_file_path = os.path.join(path_to_file, renamed_file) #"/Users/Me/file_renamed.txt" </code></pre> <p>Above line has a bug. Above line should be as below</p> <pre><code>renamed_file_path = os.path.join(path_before_file, renamed_file) #"/Users/Me/file_renamed.txt" </code></pre>
0
2016-08-01T12:14:23Z
[ "python" ]
Python - Mac - renamed file is created at the same level with the folder that was containing it
38,698,298
<p>I am trying to rename a file in a specific path, but it moves the file at the same level with the folder that was containing it before being renamed.</p> <pre><code>import os path_to_file = "/Users/Me/file.txt" #NOTE that in my code, file name will be randomly generated path_before_file, file_name = os.path.split(...
0
2016-08-01T11:58:27Z
38,701,145
<p>I figured out what was the problem. path_before_file was something like "Users/Me"(without slash at the end). If I do:</p> <pre><code>renamed_file_path = os.path.join(path_before_file + '/' + renamed_file) </code></pre> <p>or</p> <pre><code>renamed_file_path = path_before_file + '/' + renamed_file </code></pre> ...
0
2016-08-01T14:15:26Z
[ "python" ]
Executable called via subprocess.check_output prints on console but result is not returned
38,698,383
<p>On a Windows machine, I'm trying to call an external executable from Python and gather its outputs for further processing. Because a local path variable has to be set before calling the executable, I created a batch script that </p> <ul> <li>first calls another script to set %PATH% and </li> <li>then calls the exec...
2
2016-08-01T12:02:47Z
38,749,458
<p>If a program writes directly to the console (e.g. by opening the <code>CONOUT$</code> device) instead of to the process standard handles, the only option is to read the console screen buffer directly. To make this simpler, start with a new, empty screen buffer. Create, size, initialize, and activate a new screen buf...
1
2016-08-03T16:50:41Z
[ "python", "windows", "batch-file", "subprocess" ]
Create a 'standard property' for class attributes in Python
38,698,535
<p>I have a class, that is used to translate binary stream to human readable. I want to translate it both ways, because I send and receive binary messages. Attributes of this class are made mostly the same way - take the bytes from startbyte to stopbyte and decode them - so I made a decision to use a property to do tha...
1
2016-08-01T12:10:34Z
38,698,612
<p>Have your function produce both the getter and setter, and return the <code>property</code> object for those two functions:</p> <pre><code>def standard_property(startbyte, stopbyte): def getter(self): return decode(self.data[startbyte:stopbyte]) def setter(self, value): self.data[startbyte:s...
3
2016-08-01T12:14:51Z
[ "python", "properties" ]
module' object has no attribute 'SelectDateWidget'
38,698,591
<p>I'm trying to create a custom form/view in Calendarium and i keep getting an error </p> <pre><code>AttributeError: 'module' object has no attribute 'SelectDateWidget' </code></pre> <p>CreateEvent within my forms.py</p> <pre><code>class CreateEvent(forms.ModelForm): class Meta: model = Event fi...
2
2016-08-01T12:13:50Z
38,698,786
<p>You are missing <code>widgets</code>:</p> <pre><code>class CreateEvent(forms.ModelForm): class Meta: model = Event fields = ['title', 'start', 'end', 'description', 'category', 'created_by', 'rule', 'end_recurring_period'] widgets = { 'start': forms.widgets.SelectDateWidget()...
2
2016-08-01T12:22:57Z
[ "python", "django", "django-forms", "django-views" ]
module' object has no attribute 'SelectDateWidget'
38,698,591
<p>I'm trying to create a custom form/view in Calendarium and i keep getting an error </p> <pre><code>AttributeError: 'module' object has no attribute 'SelectDateWidget' </code></pre> <p>CreateEvent within my forms.py</p> <pre><code>class CreateEvent(forms.ModelForm): class Meta: model = Event fi...
2
2016-08-01T12:13:50Z
38,698,939
<p>According to <a href="https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#selectdatewidget" rel="nofollow">the docs</a>, you can only import the <code>SelectDateWidget</code> widget from <code>django.forms</code> in Django 1.9+.</p> <p>In earlier versions, you need to import it from <code>django.forms.extras.w...
1
2016-08-01T12:29:36Z
[ "python", "django", "django-forms", "django-views" ]
What is the Python equivalent of StringEntity in Java?
38,698,621
<p>I have the following class in Java:</p> <pre><code>class JsonEntity extends StringEntity { private final String string; public JsonEntity(String string, Charset charset) { super(string, ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), charset)); this.string = string } </code><...
1
2016-08-01T12:15:13Z
38,698,940
<p>I don' know if I exactly get your need, however if you need to save as JSON with a particular charset in python you can do something like this:</p> <pre><code>import json json_string = json.dumps("your string even with wierd symbols", ensure_ascii=False).encode('utf8') </code></pre> <p>NB: you can change utf8 wit...
0
2016-08-01T12:29:36Z
[ "java", "python", "json", "python-2.7" ]
Changes in environment variables are not reflected in python
38,698,914
<p>trying to install spark, I've some problems when I try to set the system enviroment variables. I modify the PATH using:</p> <p>“Advanced system settings” → “Environment Variables”</p> <p>but when I call these variables from python, using the code:</p> <pre><code>import os path = os.environ.get('PATH', N...
1
2016-08-01T12:28:18Z
38,699,164
<p>Any program invoked from the command prompt will be given the environment variables that was at the time the command prompt was invoked.</p> <p>Therefore, when you modify or add an environment variable you should restart the command prompt (cmd.exe) and then invoke python to see the changes.</p>
1
2016-08-01T12:39:46Z
[ "python", "windows", "environment-variables", "windows-10" ]
Python selenium webdriver. Find elements with specified class name
38,698,948
<p>I am using Selenium to parse a page containing markup that looks a bit like this:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Example&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;span class="Fw(500) D(ib) Fz(42px)"&gt;1&lt;/span&gt; &lt;span class="Fw(500)...
0
2016-08-01T12:29:55Z
38,699,017
<p>Try as below :-</p> <pre><code>elem = wd.find_elements_by_css_selector("span.foobar") </code></pre> <p>If there is space between class <code>foo</code> and <code>bar</code> then try as below :-</p> <pre><code>elem = wd.find_elements_by_css_selector("span.foo.bar") </code></pre> <p><strong>Edited</strong> : If yo...
1
2016-08-01T12:32:46Z
[ "python", "selenium" ]