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 |
|---|---|---|---|---|---|---|---|---|---|
Give multiple terminal commands in a single file and run all the commands at once? | 39,207,545 | <p>I'm a beginner into Raspberry pi and i have a basic doubt.</p>
<p>I'm basically trying to make my raspberry pi into a beacon and advertise data from it to a Android app. </p>
<p>I wonder if I can give multiple terminal commands in a single file and run all the commands simply by compiling and running the file?</p>... | 1 | 2016-08-29T13:30:17Z | 39,209,244 | <p>If you truly want to use python for this you could use the subprocess module.</p>
<pre><code>import subprocess
with open ('/home/pi/bluetoothcommands.txt') as btcommands:
for line in btcommands:
subprocess.run (line)
</code></pre>
<p>If you wanted this in a loop:</p>
<pre><code>import subprocess
with ... | 1 | 2016-08-29T14:54:39Z | [
"python",
"linux",
"raspberry-pi",
"bluetooth-lowenergy",
"ibeacon"
] |
save input() into the variable(python) | 39,207,593 | <p>Here is my code:</p>
<pre><code>def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
break
else:
print('Error, enter the right ... | -3 | 2016-08-29T13:32:57Z | 39,207,653 | <p>Do not return within your while-loop you break (you have one indent to much).</p>
<pre><code>def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
b... | 2 | 2016-08-29T13:35:43Z | [
"python",
"user-input"
] |
save input() into the variable(python) | 39,207,593 | <p>Here is my code:</p>
<pre><code>def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
break
else:
print('Error, enter the right ... | -3 | 2016-08-29T13:32:57Z | 39,207,656 | <p>Did you mean something like</p>
<pre><code>res = chose_range()
</code></pre>
| 0 | 2016-08-29T13:35:51Z | [
"python",
"user-input"
] |
save input() into the variable(python) | 39,207,593 | <p>Here is my code:</p>
<pre><code>def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
break
else:
print('Error, enter the right ... | -3 | 2016-08-29T13:32:57Z | 39,207,660 | <p>If you mean "save the result of calling <code>chose_range()</code> into a variable (you didn't say which), then:</p>
<pre><code>theVariable = chose_range()
</code></pre>
<p>However, note that your function does not always return a value to be saved; if it hits a <code>break</code> statement, it exits the loop with... | 0 | 2016-08-29T13:36:02Z | [
"python",
"user-input"
] |
Import Winreg in a Python Script | 39,207,650 | <p>I am currently working on a Jenkins freestyle job and one of the build steps is to run a Python script. I have been working on this job for a couple of days now and this is one of the last build steps needed to finish it off. I have reached a point where I get an error letting me know that the <strong>import winreg<... | 0 | 2016-08-29T13:35:39Z | 39,208,547 | <p>It makes sense, the <a href="https://docs.python.org/2/library/_winreg.html#module-_winreg" rel="nofollow">_winreg docs</a> says:</p>
<blockquote>
<p>These functions expose the Windows registry API to Python.</p>
</blockquote>
<p>You could try to make it run on a windows virtual machine in your centos host or ju... | 0 | 2016-08-29T14:19:27Z | [
"python",
"winreg"
] |
setup.py console_scripts entry point does not resolve import | 39,207,670 | <p>I have following setup.py:</p>
<pre><code>from setuptools import setup
from distutils.core import setup
setup(
name="foobar",
version="0.1.0",
author="Batman",
author_email="batman@gmail.com",
packages = ["foobar"],
include_package_data=True,
install_requires=[
"asyncio",
],
... | 1 | 2016-08-29T13:36:36Z | 39,258,478 | <p>In Python 3, <code>import</code>s are absolute by default, and so <code>from wont_be_imported_one import ...</code> inside of <code>foobar</code> will be interpreted as a reference to some module named <code>wont_be_imported_one</code> outside of <code>foobar</code>. You need to use a relative import instead:</p>
... | 2 | 2016-08-31T20:29:29Z | [
"python",
"setuptools"
] |
Finding and comparing the minimum timedelta of 2 datetime lists python | 39,207,851 | <p>I have 2 lists containing <strong>datetime.timedelta</strong> values.
Need help finding the minimum of both lists and comparing them to find out which is greater.</p>
<p>Note: I am fairly new to Python</p>
<p>This is the first list, extracting datetime values from dicts v,w:</p>
<pre><code>for y in range(len(v)):... | 1 | 2016-08-29T13:45:06Z | 39,209,265 | <p>you can use max and min to find out </p>
<pre><code>w = [datetime.timedelta(10), datetime.timedelta(9), datetime.timedelta(0)]
v = [datetime.timedelta(11), datetime.timedelta(12), datetime.timedelta(13)]
max(min(v),min(w))
datetime.timedelta(11)
</code></pre>
| 0 | 2016-08-29T14:55:41Z | [
"python",
"python-2.7",
"datetime",
"timedelta"
] |
Logs not getting created in Django Project | 39,207,854 | <p>My Django project is not creating logs, this is the Logging info in my setting.py:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/home/bithu/bservice/bservice/lo... | 0 | 2016-08-29T13:45:08Z | 39,230,819 | <p>Maybe you can try:</p>
<pre><code># rest of config
'loggers': {
'your_app_name': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},}
</code></pre>
| 0 | 2016-08-30T14:53:48Z | [
"python",
"django",
"python-2.7",
"logging"
] |
Stacking a pair of columns by looking at the first column | 39,207,866 | <p>I struggle with making the move from Excel to Python since I'm so used to having everything be visible. Below, I'm trying to convert the table up top to the table below. Wanted to use pandas dataframes but if there's a different solution that's better then I'd love to hear it.</p>
<p>Also, as an added bonus, if s... | 1 | 2016-08-29T13:45:31Z | 39,208,059 | <p>I think <a href="https://github.com/pydata/pandas/blob/master/pandas/core/reshape.py#L805" rel="nofollow"><code>lreshape</code></a> would be ideal for this situation.</p>
<pre><code>pd.lreshape(df, {'Code': ['Code', 'Code2', 'Code3'], 'ID': ['ID', 'ID2', 'ID3']}) \
.sort_values('State', ascending=False)
... | 4 | 2016-08-29T13:55:17Z | [
"python",
"pandas",
"dataframe",
"reshape"
] |
Efficient way to make numpy object arrays intern strings | 39,207,890 | <p>Consider numpy arrays of the <code>object</code> dtype. I can shove anything I want in there.</p>
<p>A common use case for me is to put strings in them. However, for very large arrays, this <em>may</em> use up a lot of memory, depending on how the array is constructed. For example, if you assign a long string (e.g.... | 2 | 2016-08-29T13:46:44Z | 39,208,145 | <p>Here's one way to do it, using a dictionary whose values are equal to its keys:</p>
<pre><code>seen = {}
for idx, string in enumerate(file):
arr[idx] = seen.setdefault(string, string)
</code></pre>
| 2 | 2016-08-29T13:59:30Z | [
"python",
"numpy"
] |
If statement in python Pandas | 39,207,921 | <p>I've a dataframe called family in pandas that I've created following an sql code. I've done all of it except this line. The sql code is the following </p>
<pre><code>SELECT IF(name Is Null, family.last_name, family.first_name) as family.NAME
from family
</code></pre>
<p>I've tried the following </p>
<pre><code>fa... | 1 | 2016-08-29T13:48:18Z | 39,208,190 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">numpy.where(condition[, x, y])</a> function expects <code>bool</code> values as a <code>condition</code> argument:</p>
<blockquote>
<p><strong>condition :</strong> array_like, bool</p>
<p>When True, yield x, otherwi... | 2 | 2016-08-29T14:01:09Z | [
"python",
"sql",
"pandas"
] |
If statement in python Pandas | 39,207,921 | <p>I've a dataframe called family in pandas that I've created following an sql code. I've done all of it except this line. The sql code is the following </p>
<pre><code>SELECT IF(name Is Null, family.last_name, family.first_name) as family.NAME
from family
</code></pre>
<p>I've tried the following </p>
<pre><code>fa... | 1 | 2016-08-29T13:48:18Z | 39,208,192 | <p>As MAXU said </p>
<pre><code>family['NAME'] = np.where(family.name.isnull(),family.last_name, family.first_name)
</code></pre>
<p>was the correct code</p>
| 0 | 2016-08-29T14:01:18Z | [
"python",
"sql",
"pandas"
] |
Python UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 | 39,207,994 | <p>I'm reading a config file in python getting sections and creating new config files for each section.</p>
<p>However.. I'm getting a decode error because one of the strings contains <code>Español=spain</code></p>
<pre><code>self.output_file.write( what.replace( " = ", "=", 1 ) )
UnicodeDecodeError: 'ascii' codec c... | 0 | 2016-08-29T13:51:38Z | 39,209,175 | <p>If you use <code>python2</code> with <code>from __future__ import unicode_literals</code> then every string literal you write is an unicode literal, as if you would prefix every literal with <code>u"..."</code>, unless you explicityl write <code>b"..."</code>.</p>
<p>This explains why you get an Unicode<i>Decode</i... | 0 | 2016-08-29T14:51:59Z | [
"python",
"parsing",
"configparser",
"python-config"
] |
Pulling omniture data using API (fully processed) using Python giving error max_queue_checks reached | 39,208,036 | <p>I was trying to pull data from API (fully processed),
Attaching the code snippet I used for the same:</p>
<pre><code>from sitecat_py.pandas_api import SiteCatPandas
report_description = {
"reportSuiteID": "**********",
"dateFrom": "2016-08-22",
"dateTo": "2016-08-28",
"dateGranularity": "day",
"metrics": [{"id": ... | 0 | 2016-08-29T13:54:06Z | 39,247,392 | <p>I posted the same question to this forum above, this answer was helpful</p>
<p><a href="https://marketing.adobe.com/developer/forum/reporting/pulling-omniture-data-using-api-fully-processed-using-python-error-max-queue-checks-reached?page=1#comment_5281" rel="nofollow">https://marketing.adobe.com/developer/forum/re... | 0 | 2016-08-31T10:41:01Z | [
"python",
"adobe",
"adobe-analytics"
] |
django.db.utils.IntegrityError: (1048, "Column 'create_timestamp' cannot be null") | 39,208,218 | <p>This is the full output after execute script this error is present when run script on python I use django 1.10 python 2.7</p>
<pre><code>File "/usr/bin/snort-sig-parser.py", line 213, in <module>
main()
File "/usr/bin/snort-sig-parser.py", line 205, in main
sig_parse(sig_line, 0,options.branch,optio... | 1 | 2016-08-29T14:02:31Z | 39,209,571 | <p>Add <code>auto_now=True</code> in your <code>create_timestamp</code> field if you want to add Time Stamp automatically, else if you want to add anything other than current time stamp, you can add<code>blank=True</code> and add any custom time stamp if you like before saving. </p>
<pre><code>create_timestamp = Date... | 0 | 2016-08-29T15:11:11Z | [
"python",
"django"
] |
Sort django queryset using a Python list | 39,208,266 | <p>I have a</p>
<pre><code>Model Car(self.Models)
# a bunch of features here
</code></pre>
<p>then in my views.py, I get all the cars and compute a score for them:</p>
<pre><code>allCars = Car.object.all() # so you get [A, B, C, D]
scoreList = someComputation(allCars) # returns [3,1,2,4]
</code></pre>
<p>then in my... | 0 | 2016-08-29T14:05:04Z | 39,208,427 | <p>First off, to answer your question, you can't use ORM/sql to sort something that's derived from the records with complex logic, unless it's just pure math, which database can do to some extent. </p>
<p>Your next option is to use python built in sorting. However, you can't sort items by a function that "take all in"... | 2 | 2016-08-29T14:13:47Z | [
"python",
"sql",
"django"
] |
Pandas: how to create a year-week variable? | 39,208,305 | <p>I have a dataframe with datetimes</p>
<pre><code>dates = pd.date_range('9/25/2010', periods=10, freq='D')
df = pd.DataFrame({'col':dates})
df['col']=pd.to_datetime(df['col'])
df['dow'] = df.col.dt.dayofweek
df['week'] = df.col.dt.to_period('W')
df['week_alt']=df.col.dt.year.astype(str) + '-w' + df.col.dt.week.asty... | 1 | 2016-08-29T14:07:12Z | 39,208,375 | <p><strong>UPDATE:</strong> you can choose between these three UNIX modifiers: <code>%U</code>,<code>%V</code>,<code>%W</code>:</p>
<blockquote>
<p><strong>%U</strong> week number of year, with Sunday as first day of week (00..53).</p>
<p><strong>%V</strong> ISO week number, with Monday as first day of we... | 2 | 2016-08-29T14:11:29Z | [
"python",
"pandas",
"dataframe"
] |
dictionary python with a csv file | 39,208,352 | <p>I'm new at all this coding but have lots of motivation even when things don't work.</p>
<p>I'm trying to work on a dictionary with a CSV file. I get to open and edit a new file but I think I'm missing something when trying to read from the csv file.
I'm getting errors in rows 39-41 i'm probably doing something wron... | -2 | 2016-08-29T14:10:18Z | 39,208,438 | <p>Does the file have any contents? Looks like you're trying to loop over an empty iterator of lines. Try something like...</p>
<pre><code>for row in csv_file:
print(row)
else:
print('no phone numbers')
</code></pre>
<p>And see what you get.</p>
| 1 | 2016-08-29T14:14:15Z | [
"python",
"csv",
"dictionary"
] |
dictionary python with a csv file | 39,208,352 | <p>I'm new at all this coding but have lots of motivation even when things don't work.</p>
<p>I'm trying to work on a dictionary with a CSV file. I get to open and edit a new file but I think I'm missing something when trying to read from the csv file.
I'm getting errors in rows 39-41 i'm probably doing something wron... | -2 | 2016-08-29T14:10:18Z | 39,209,417 | <p>Please check the below code.
There were some other errors also which I tried to fix.Did couple of changes for the same.</p>
<p>For reading csv, I didn't use csv reader module.</p>
<p>If you want to use that, please replace the code in search() function.</p>
<pre><code>import csv
import os
import os.path
phonebo... | 0 | 2016-08-29T15:03:13Z | [
"python",
"csv",
"dictionary"
] |
Is a dictionary the right data structure for this? | 39,208,453 | <p>I would like to use a data structure that would allow me to store my data like this:</p>
<pre><code>data[1][a]
data[1][b]
data[1][c]
data[1][d]
data[2][a]
data[2][b]
</code></pre>
<p>...
With the labels a, b, c, d known from the beginning, while i iter over the 1, 2, ... from a list.</p>
<p>I thought about using... | 1 | 2016-08-29T14:14:49Z | 39,208,822 | <p>I suggest a list of dictionaries. And I suggest that you replace your suggested iteration:</p>
<pre><code>for i in mylist:
dict[i][a]=something
</code></pre>
<p>With this:</p>
<pre><code>for elem in list_of_dicts:
elem[a] = something
</code></pre>
<p>If for some reason, you really need the list index, yo... | 0 | 2016-08-29T14:34:32Z | [
"python",
"dictionary",
"data-structures",
"label"
] |
Is a dictionary the right data structure for this? | 39,208,453 | <p>I would like to use a data structure that would allow me to store my data like this:</p>
<pre><code>data[1][a]
data[1][b]
data[1][c]
data[1][d]
data[2][a]
data[2][b]
</code></pre>
<p>...
With the labels a, b, c, d known from the beginning, while i iter over the 1, 2, ... from a list.</p>
<p>I thought about using... | 1 | 2016-08-29T14:14:49Z | 39,209,800 | <p>If you want to have data[1][a] using dict. You could have a dict of dicts and initialize like so.</p>
<pre><code>dict={}
mylist=(1, 2, 3)
labels = ('a','b','c','d')
something = 'foo'
for i in mylist:
for l in labels:
if(i in dict):
dict[i].update({l:something})
else:
di... | 1 | 2016-08-29T15:23:56Z | [
"python",
"dictionary",
"data-structures",
"label"
] |
removing words from a list after splitting the words :Python | 39,208,488 | <p>I have a list </p>
<pre><code>List = ['iamcool', 'Noyouarenot']
stopwords=['iamcool']
</code></pre>
<p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p>
<pre><code>query1=List.split()
resultwords = [word for word in query1 if word not in stopwords]
resu... | 0 | 2016-08-29T14:17:04Z | 39,208,542 | <p>A list comprehension with a condition checking for membership in <code>stopwords</code>.</p>
<pre><code>print [item for item in List if item not in stopwords]
</code></pre>
<p>or <code>filter</code></p>
<pre><code>print filter(lambda item: item not in stopwords, List)
</code></pre>
<p>or <code>set</code> operati... | 4 | 2016-08-29T14:19:18Z | [
"python",
"list"
] |
removing words from a list after splitting the words :Python | 39,208,488 | <p>I have a list </p>
<pre><code>List = ['iamcool', 'Noyouarenot']
stopwords=['iamcool']
</code></pre>
<p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p>
<pre><code>query1=List.split()
resultwords = [word for word in query1 if word not in stopwords]
resu... | 0 | 2016-08-29T14:17:04Z | 39,208,576 | <p>It should be <code>result=[i for i in Mylist if i not in stopword]</code></p>
<p>I think you should read the document like <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">this</a>.It will help you learn Python.</p>
<p>By the way,I know something about NLP.<br>
I think the input shou... | 0 | 2016-08-29T14:21:32Z | [
"python",
"list"
] |
removing words from a list after splitting the words :Python | 39,208,488 | <p>I have a list </p>
<pre><code>List = ['iamcool', 'Noyouarenot']
stopwords=['iamcool']
</code></pre>
<p>What I want to do is to remove stowprds from my list. I am trying to acheive this with following script </p>
<pre><code>query1=List.split()
resultwords = [word for word in query1 if word not in stopwords]
resu... | 0 | 2016-08-29T14:17:04Z | 39,208,633 | <p>Here's the snippet fixing your error:</p>
<pre><code>lst = ['iamcool', 'Noyouarenot']
stopwords = ['iamcool']
resultwords = [word for word in lst if word not in stopwords]
result = ' '.join(resultwords)
print result
</code></pre>
<p>Another possible solution assuming your input list and stopwords list don't care ... | 1 | 2016-08-29T14:24:50Z | [
"python",
"list"
] |
Why my code is not encrypting the password if i inherit django user? | 39,208,585 | <p>Im learning about django, and i need create a customized user, called Person. I use inherit from contrib.auth.models User, but in my django administrator the form for add a new Teacher dont show the field confirm password and the password is not encrypted in the table user</p>
<pre><code>from django.db import mode... | 1 | 2016-08-29T14:21:57Z | 39,211,961 | <p>In order to encrypt a password, you need to set it through User's <code>set_password</code> method. for example, </p>
<pre><code>user = User(
email=email, is_staff=False, is_active=True,
is_superuser=False,
last_login=now, date_joined=now, **extra_fields)
user.set_password(passw... | 0 | 2016-08-29T17:33:48Z | [
"python",
"django",
"django-models",
"django-views"
] |
Basic Bar Chart with plotly | 39,208,680 | <p>I try to do a bar charts, with this code </p>
<pre><code>import plotly.plotly as py
import plotly.graph_objs as go
data = [go.Bar(
x=['giraffes', 'orangutans', 'monkeys'],
y=[20, 14, 23]
)]
py.iplot(data, filename='basic-bar')
</code></pre>
<p>But I got this error : </p>
<blockquote>... | 0 | 2016-08-29T14:27:13Z | 39,208,868 | <p>You need to pay attention to the traceback in the error. In this case, it's even more helpful than usual. The solution is given to you here:</p>
<pre><code>PlotlyLocalCredentialsError:
Couldn't find a 'username', 'api-key' pair for you on your local machine. To sign in temporarily (until you stop running Python), ... | 1 | 2016-08-29T14:37:06Z | [
"python",
"plot",
"plotly"
] |
Python list of dictionaries: Get last item of each day | 39,208,735 | <p>I have a list of dictionaries, ordered by the key <code>date</code>:</p>
<pre><code>d = [{'date': datetime.strptime('2016-01-01 07:00', "%Y-%m-%d %H:%M"), 'val': 1},
{'date': datetime.strptime('2016-01-01 23:00', "%Y-%m-%d %H:%M"), 'val': 3},
{'date': datetime.strptime('2016-01-02 07:00', "%Y-%m-%d %H:%M"), 'val': ... | 1 | 2016-08-29T14:30:19Z | 39,208,951 | <p>Assuming that the data is already sorted by <code>'date'</code> (it seems to be in your case), you can use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to group by the <code>date()</code>, and then get the last item from each group.<... | 3 | 2016-08-29T14:41:09Z | [
"python"
] |
Solution for storing digital asset management metadata and dependencies in Python | 39,208,751 | <p>I'm planning to write some sort of digital management system to help users to deal with files in VCS (SVN, Perforce...) easily. The main premise is, that all files custom metadata and dependencies are stored alongside real files in VCS and not on separate database server.
But when querying the metadata it would be ... | -2 | 2016-08-29T14:31:10Z | 39,209,674 | <p><a href="https://pypi.python.org/pypi/ZODB" rel="nofollow">ZODB</a> satisfies most of your criteria:</p>
<ul>
<li>support for arbitrary python constructs</li>
<li>usable mostly like having everything in memory as normal objects</li>
<li>if opened in read-only mode multiple processes can read at the same time (i thi... | 0 | 2016-08-29T15:16:31Z | [
"python",
"database",
"search",
"nosql"
] |
I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000 | 39,208,771 | <pre><code> math.pi = 3.14
while math.pi > 10000
print math.pi
</code></pre>
<p>I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000</p>
| -4 | 2016-08-29T14:32:23Z | 39,209,003 | <p>Do you want something like this? I tried to provide an example with as similar format to what you provided. </p>
<pre><code>import math
exponent = 0
num = math.pi
while num ** exponent < 10000:
print num ** exponent
exponent += 1
</code></pre>
<p>If we take a look at the code that you posted, you're n... | 0 | 2016-08-29T14:43:53Z | [
"python"
] |
I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000 | 39,208,771 | <pre><code> math.pi = 3.14
while math.pi > 10000
print math.pi
</code></pre>
<p>I'm trying to write a loop that raises the mathematical constant of pi to its powers until the result is greater than 10000</p>
| -4 | 2016-08-29T14:32:23Z | 39,209,046 | <p>It looks like you forgot to actually assign pi to a variable and increase it's value</p>
<pre><code>p = math.pi
while p < 10000:
p *= math.pi
</code></pre>
<p>or using a bit of math you can get the same result:</p>
<pre><code>p = math.pi ** (math.ceil(math.log(10000) / math.log(math.pi)))
</code></pre>
| 0 | 2016-08-29T14:45:41Z | [
"python"
] |
How to set an GTK Entry as an default active element in Python GTK2 | 39,208,829 | <p>How can I set a GTK entry as default activated element / widget on start so I can insert my text without click into the entry widget first?</p>
<p>For example, when I start this script I want to insert into entry2 by default:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import gtk
window = gtk.Window... | 1 | 2016-08-29T14:35:04Z | 39,209,140 | <p>Just found:</p>
<p><strong>5.10. How do I focus a widget? How do I focus it before its toplevel window is shown?</strong></p>
<p><a href="http://faq.pygtk.org/index.py?file=faq05.010.htp&req=show" rel="nofollow">http://faq.pygtk.org/index.py?file=faq05.010.htp&req=show</a></p>
<pre><code>entry2.grab_focus... | 2 | 2016-08-29T14:50:35Z | [
"python",
"gtk2"
] |
Python - Select latest file with a specific start string and extension | 39,208,881 | <p>Newbie: I have the following code that fetches the latest Excel file from the downloads folder, based on the Modification time:</p>
<pre><code>import os
import glob
latest_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/*.xlsx'), key=os.path.getmtime)
</code></pre>
<p>Now, all excel files have either <strong>'Lo... | 0 | 2016-08-29T14:37:37Z | 39,208,982 | <pre><code>latest_local_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/Local*.xlsx'),
key=os.path.getmtime)
latest_gloabl_Excel = max(glob.iglob('C:\Users\Aditya\Downloads/Global*.xlsx'),
key=os.path.getmtime)
</code></pre>
| 2 | 2016-08-29T14:42:57Z | [
"python",
"excel"
] |
Python, pandas, cumulative sum in new column on matching groups | 39,208,948 | <p>If I have these columns in a dataframe:</p>
<pre><code>a b
1 5
1 7
2 3
1,2 3
2 5
</code></pre>
<p>How do I create column <code>c</code> where column <code>b</code> is summed using groupings of column <code>a</code> (string), keeping the existing dataframe. Some rows can belong to more th... | 2 | 2016-08-29T14:41:02Z | 39,209,284 | <p>You can first need split column <code>a</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> it to original <code>DataFrame</code>:</p>
<pre><code>print (df.a.str.split(',', expand=True)
.stack()
.res... | 2 | 2016-08-29T14:56:38Z | [
"python",
"pandas",
"dataframe",
"group-by",
"sum"
] |
Data Migrations on Django getting previous Model versions | 39,208,967 | <p>Im working on a data migrations which needs to change a Foreign key to a different model and alter all the existing instances foreign keys to the new Model pk. I think this can be achieved with data migrations on Django. My question is:</p>
<p>¿How can I access previous versions of my models in order to perform th... | 1 | 2016-08-29T14:42:09Z | 39,211,896 | <p>Use the versioned app registry to get the model, rather than an import statement.</p>
<pre><code>def my_migration(apps, schema_editor):
MyModel = apps.get_model("my_app", "MyModel")
</code></pre>
<p>The first argument passed to your migration worker function is an app registry that has the historical versions ... | 1 | 2016-08-29T17:29:19Z | [
"python",
"django"
] |
Python lxml objectify: Strange behaviour when changing an elements value | 39,209,062 | <p>I´m new to stack overflow, so "hi" to everbody and I hope someone can help me with my question...</p>
<p>Recently I start to play around a bit with lxml.objectify and stumble over the following behavior, which I found to be strange.
If I just create a little xml string like this:</p>
<pre><code>from lxml import o... | 1 | 2016-08-29T14:46:25Z | 39,211,468 | <p>It is actually not that strange of behavior once we dig into it a bit. Using <code>root.element.subelement....</code> is not performing as you might assume it is. We can use <code>etree</code> to print out the state of the xml tree and check the structure.</p>
<pre><code>from lxml import objectify, etree
objroot... | 1 | 2016-08-29T17:02:31Z | [
"python",
"python-3.x",
"attributeerror",
"lxml.objectify"
] |
Running a package as a script: executing __main__.py without importing __init__.py | 39,209,065 | <p>My package directory is as follow:</p>
<pre><code>foo/
__init__.py
__main__.py
setup.py
</code></pre>
<p>If that matters, I installed it using setuptools.</p>
<p>Now, if I have a Python code with the line <code>import foo</code>, then <code>__init__.py</code> is executed and <code>__main__.py</code> is no... | 0 | 2016-08-29T14:46:31Z | 39,209,109 | <p>You can't. <code>__init__</code> is the <em>core</em> of the package and will <strong>always</strong> be imported for anything from the package.</p>
<p>You'll have to move the code from <code>__main__.py</code> to live outside the package, or move the code you don't want executed from <code>__init__.py</code> to an... | 0 | 2016-08-29T14:48:43Z | [
"python",
"package"
] |
How to know more about built-in modules | 39,209,131 | <p><strong>OVERVIEW</strong></p>
<p>Once you've imported a package you can query the source path using the <code>__path__</code> attribute and from there most of the time you can read the Python source code directly. The problem comes when the module in question is similar to winreg. If I do</p>
<pre><code>import win... | 1 | 2016-08-29T14:49:56Z | 39,209,264 | <p>For Python's modules written in C, you can always check CPython's source code over at GitHub: <a href="https://github.com/python/cpython" rel="nofollow">https://github.com/python/cpython</a></p>
<p>Usually you can find them in the <code>Modules</code> folder but the <code>winreg</code> one is special, here it is: <... | 2 | 2016-08-29T14:55:33Z | [
"python",
"built-in"
] |
Python order of conditions | 39,209,145 | <p>When I enter this code, the program never throws an error, even if I enter a non-number:</p>
<pre><code>user_input = input("Enter a number.")
if user_input.isdigit() and 0 <= float(user_input) <= 10:
print("A number between 0 and 10.")
else:
print("Not a number between 0 and 10.")
</code></pre>
<p>Bu... | 0 | 2016-08-29T14:50:38Z | 39,209,229 | <p>Of course it matters.</p>
<pre><code>if 0 <= float(user_input) <= 10 and user_input.isdigit():
</code></pre>
<p>First tries to evaluate <code>float(user_input)</code>. If <code>user_input</code> is a non-number string it would raise a <code>ValueError</code>.</p>
<p><br/></p>
<pre><code>if user_input.isdig... | 2 | 2016-08-29T14:53:56Z | [
"python",
"condition"
] |
Python order of conditions | 39,209,145 | <p>When I enter this code, the program never throws an error, even if I enter a non-number:</p>
<pre><code>user_input = input("Enter a number.")
if user_input.isdigit() and 0 <= float(user_input) <= 10:
print("A number between 0 and 10.")
else:
print("Not a number between 0 and 10.")
</code></pre>
<p>Bu... | 0 | 2016-08-29T14:50:38Z | 39,209,230 | <p>In the first case, the <code>isdigit()</code> method is false, so the next condition is not checked. In the second case, the <code>float()</code> is attempted and raises and exception:</p>
<pre><code>... float('bob')
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: c... | 0 | 2016-08-29T14:54:04Z | [
"python",
"condition"
] |
How to change multiple Pandas DF columns to categorical without a loop | 39,209,240 | <p>I have a DataFrame where I want to change several columns from type 'object' to 'category'.</p>
<p>I can change several columns at the same time for float, </p>
<pre><code>dftest[['col3', 'col4', 'col5', 'col6']] = \
dftest[['col3', 'col4', 'col5', 'col6']].astype(float)
</code></pre>
<p>For 'category' I can ... | 3 | 2016-08-29T14:54:32Z | 39,209,586 | <p>you can do it this way:</p>
<pre><code>In [99]: pd.concat([dftest[['col1', 'col2']].apply(lambda x: x.astype('category')), dftest.ix[:, 'col3':].astype('float')], axis=1)
Out[99]:
col1 col2 col3 col4 col5 col6
0 a xx 0.30 2.28 0.84 0.31
1 a xx -0.13 2.04 2.62 0.49
2 ab xx -0.34 -0.32 -1.8... | 1 | 2016-08-29T15:11:55Z | [
"python",
"pandas",
"numpy",
"dataframe",
"categorization"
] |
How to change multiple Pandas DF columns to categorical without a loop | 39,209,240 | <p>I have a DataFrame where I want to change several columns from type 'object' to 'category'.</p>
<p>I can change several columns at the same time for float, </p>
<pre><code>dftest[['col3', 'col4', 'col5', 'col6']] = \
dftest[['col3', 'col4', 'col5', 'col6']].astype(float)
</code></pre>
<p>For 'category' I can ... | 3 | 2016-08-29T14:54:32Z | 39,232,578 | <p>It's not immediately clear what the result of <code>dftest[['col1','col2']].astype('category')</code> should be, i.e. whether the resulting columns should share the same categories or not.</p>
<p>Looping over columns make each column have a separate set of categories. (I believe this is a desired result in your exa... | 1 | 2016-08-30T16:21:44Z | [
"python",
"pandas",
"numpy",
"dataframe",
"categorization"
] |
Error in parsing json in python | 39,209,261 | <p>Trying to parse this json in python</p>
<pre><code>'''[{"accountName":"London\"Paris\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]'''
</code></pre>
<p>gives this error</p>
<pre><code>Traceback (most recent call last):
File "unicode_test.py", line 5, in <modu... | 0 | 2016-08-29T14:55:27Z | 39,209,392 | <p>The issue you are facing is called <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">character escaping</a>. The parser is indeed working as intended; this is a common topic across most programming languages.</p>
<p>In your particular example, you are trying to use d... | 0 | 2016-08-29T15:01:47Z | [
"python",
"json"
] |
Error in parsing json in python | 39,209,261 | <p>Trying to parse this json in python</p>
<pre><code>'''[{"accountName":"London\"Paris\"Geneva","accountId":"1664800781","isActive":true,"timeZone":"Asia/Jerusalem","currency":"ILS"}]'''
</code></pre>
<p>gives this error</p>
<pre><code>Traceback (most recent call last):
File "unicode_test.py", line 5, in <modu... | 0 | 2016-08-29T14:55:27Z | 39,210,716 | <p>Preceding quotes with a <code>\</code> in a string literal is called escaping it, and tells the parser that you actually mean the string contains a quote, not to end the string there. Python has two other options for that: Use a different type of quote to wrap the string, or put <code>r</code> before the string whic... | 0 | 2016-08-29T16:14:57Z | [
"python",
"json"
] |
Joining hundreds of columns and column indexes into a string | 39,209,287 | <p>I've got what I hope is a unique/interesting problem for my first question on Stack Overflow!</p>
<p>I have data on skills assessments, currently in a very large pandas dataframe. Each row represents a student, and each column contains their scores for a particular skills assessment. There are about 200 skill asses... | 2 | 2016-08-29T14:56:42Z | 39,210,508 | <p>Using <code>to_json</code> then fixing it</p>
<pre><code>def to_str(x):
return x.dropna().to_json(double_precision=0) \
.replace('"', '').replace(',', ' ').strip("{}")
df.T.apply(to_str)
</code></pre>
<p>Or using list comprehension and <code>join</code></p>
<pre><code>def to_str(x):
return " ... | 1 | 2016-08-29T16:02:18Z | [
"python",
"pandas",
"dataframe"
] |
Joining hundreds of columns and column indexes into a string | 39,209,287 | <p>I've got what I hope is a unique/interesting problem for my first question on Stack Overflow!</p>
<p>I have data on skills assessments, currently in a very large pandas dataframe. Each row represents a student, and each column contains their scores for a particular skills assessment. There are about 200 skill asses... | 2 | 2016-08-29T14:56:42Z | 39,210,931 | <p>Try this: </p>
<pre><code>ld = df.set_index('id').fillna("").to_dict(orient='records')
ll = [' '.join([ k +":"+ str(v) for k,v in x.iteritems() if v != "" ]) for x in ld ]
ll
['skill2:50.0 skill1:10.0 skill4:3.0',
'skill3:2.0 skill2:10.0 skill4:70.0',
'skill3:45.0 skill1:23.0 skill5:5.0']
</code></pre>
| 0 | 2016-08-29T16:29:18Z | [
"python",
"pandas",
"dataframe"
] |
Using different font (Gentium) for Matplotlib plots | 39,209,465 | <p>I'm trying to use Gentium Plus as the main font in matplotlib, especially for the numbers.
The following works in order to use Palatino for everything, which is fine for the math font.</p>
<pre><code>import matplotlib.pyplot as plt
font = {'family': 'serif', 'serif': ['Palatino'], 'size': 10}
plt.rc('font', **font)... | 1 | 2016-08-29T15:05:29Z | 39,209,740 | <p>You can check the available fonts in matplotlib by the following..</p>
<pre><code>import matplotlib.font_manager
list = matplotlib.font_manager.get_fontconfig_fonts()
names = [matplotlib.font_manager.FontProperties(fname=fname).get_name() for fname in list]
print names
</code></pre>
<p>To check for more options yo... | 1 | 2016-08-29T15:20:01Z | [
"python",
"matplotlib",
"fonts"
] |
Using different font (Gentium) for Matplotlib plots | 39,209,465 | <p>I'm trying to use Gentium Plus as the main font in matplotlib, especially for the numbers.
The following works in order to use Palatino for everything, which is fine for the math font.</p>
<pre><code>import matplotlib.pyplot as plt
font = {'family': 'serif', 'serif': ['Palatino'], 'size': 10}
plt.rc('font', **font)... | 1 | 2016-08-29T15:05:29Z | 39,223,009 | <p>Thanks to Denduluri I found the name for Gentium</p>
<pre><code>import matplotlib
import matplotlib.pyplot as plt
font = {'family': 'serif', 'serif': ['Gentium Basic'], 'size': 10}
plt.rc('font', **font)
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Gentium Basic'
matplotl... | 0 | 2016-08-30T08:58:49Z | [
"python",
"matplotlib",
"fonts"
] |
Using an '&' in a string in python | 39,209,626 | <p>What is the purpose of the '&' in the string in this line?</p>
<pre><code>exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
</code></pre>
<p>Likewise here:</p>
<pre><code>fileMenu = menubar.addMenu('&File')
</code></pre>
| 0 | 2016-08-29T15:13:32Z | 39,209,764 | <p>The <code>&</code> character has a special purpose if you use it in the text of a <code>QAction</code> object: If the QAction object is used in a tool button, the character directly after the <code>&</code> symbol can be used as a keyboard shortcut for that button (in combination with the alt-key).</p>
<p>S... | 2 | 2016-08-29T15:21:27Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
Assertion error when comparing two float tensors | 39,209,633 | <p>I'm using tensorflow-10.0 with gpu support, and I want to compare if 2 equations return the the same thing (which they actually should). I simplified the second equation up to the point where both equations are equal, but the assert returns that they are not.</p>
<p>In the following code snippet b,c,d are float32 t... | 0 | 2016-08-29T15:13:52Z | 39,209,918 | <p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/index.html" rel="nofollow"><code>tf.reduce_sum()</code></a> operator—in common with most of TensorFlow's <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/math_ops.html#reduction" rel="nofollow">reduction operators</a>—is im... | 2 | 2016-08-29T15:28:58Z | [
"python",
"tensorflow"
] |
Concatenating filter requests with a loop in django | 39,209,634 | <p>I have a list of strings that I need to determine if they are present in my model names. Currently I am using a series of if and elif statements to determine how many strings are in my list of strings then execute a filter request to my database like this (this works but is extremely inefficient as I am constantly r... | 0 | 2016-08-29T15:13:58Z | 39,209,807 | <p>You probably want to use the <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow">distinct</a> filter.</p>
| 1 | 2016-08-29T15:24:07Z | [
"python",
"django"
] |
python google app engine stripe integration | 39,209,770 | <p>I am working on a project in which i want to integrate stripe for payments. I am following their documentation to integrate it in python <a href="https://stripe.com/docs/charges" rel="nofollow">Stripe Documentation</a>. In documentation they downloaded the stripe library to use it. The code to download it was:</p>
... | 1 | 2016-08-29T15:21:53Z | 39,210,327 | <p>When you pip installed stripe, it installed it in your local system. But GAE does not have that package, so you cannot simply import it in production. You need to download the package, and add it inside your app. For example, in a "libs" directory. Then, it will upload with the rest of your app when you deploy, ... | 0 | 2016-08-29T15:51:36Z | [
"python",
"google-app-engine",
"stripe-payments"
] |
python google app engine stripe integration | 39,209,770 | <p>I am working on a project in which i want to integrate stripe for payments. I am following their documentation to integrate it in python <a href="https://stripe.com/docs/charges" rel="nofollow">Stripe Documentation</a>. In documentation they downloaded the stripe library to use it. The code to download it was:</p>
... | 1 | 2016-08-29T15:21:53Z | 39,210,899 | <p>The proper way to install a 3rd party library into your GAE application is described in <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27?hl=en#installing_a_library" rel="nofollow">Installing a library</a>:</p>
<blockquote>
<p>The easiest way to manage this is with a ./lib di... | 3 | 2016-08-29T16:27:05Z | [
"python",
"google-app-engine",
"stripe-payments"
] |
PyCharm wrong notification: no module named cx_Oracle | 39,209,776 | <p>I've installed cx_Oracle 5.2.1 for Python 2.7.10, and it works (running Win). My problem is though; PyCharm notifies me that the module name does not exists, which is not a problem in runtime. But because of this PyCharm is unable to assist me on the modules different function etc.</p>
<p>Can anyone clarify please?... | 0 | 2016-08-29T15:22:22Z | 39,210,017 | <p>Go to <code>File > Invalidate Caches > Invalidate</code> and Restart or Invalidate and check. </p>
<p>If you want to check the library inside pyCharm go to <code>File > Settings > Project > Project Interpreter</code>. Select the interpreter and check the library is listed.</p>
<p>If you want to chec... | 0 | 2016-08-29T15:34:17Z | [
"python",
"pycharm",
"cx-oracle"
] |
Clustering text documents and obtaining duplicate top terms | 39,209,820 | <p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p>
<p>I used the same code in the post above but added a test document... | 0 | 2016-08-29T15:24:39Z | 39,210,359 | <p>Not necessarily. The code you are using creates vector space of the bag of words (excluding stop words) of your corpus (I am ignoring the tf-idf weighting.). Looking at your documents, your vector space is of size 5, with the a word array like (ignoring the order):</p>
<pre><code>word_vec_space = [yesterday, ran,... | 1 | 2016-08-29T15:53:13Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
Clustering text documents and obtaining duplicate top terms | 39,209,820 | <p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p>
<p>I used the same code in the post above but added a test document... | 0 | 2016-08-29T15:24:39Z | 39,212,759 | <p>TF*IDF tells you the representativeness of a word (in this case the column) for a specific document (and in this case the row). By representative I mean: a word occurs frequently in one document but not frequently in other documents. The higher the TF*IDF value, the more this word represents a specific document. </p... | 1 | 2016-08-29T18:26:23Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
Clustering text documents and obtaining duplicate top terms | 39,209,820 | <p>I found the code in <a href="http://stackoverflow.com/questions/27889873/clustering-text-documents-using-scikit-learn-kmeans-in-python?rq=1">this post</a> to be very helpful. (I would add a comment to that post but I need 50 reputation points.)</p>
<p>I used the same code in the post above but added a test document... | 0 | 2016-08-29T15:24:39Z | 39,280,446 | <p>Why would clusters have distinct top terms?</p>
<p>Consider the clustering worked (very often it doesn't - beware), would you consider these clusters to be bad or good:</p>
<ul>
<li>banana fruit</li>
<li>apple fruit</li>
<li>apple computer</li>
<li>windows computer</li>
<li>window blinds</li>
</ul>
<p>If I would ... | 1 | 2016-09-01T20:34:25Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
Decode Base64 string to byte array | 39,209,872 | <p>I would create a python script that decode a Base64 string to an array of byte (or array of Hex values).</p>
<p>The embedded side of my project is a micro controller that creates a base64 string starting from raw byte. The string contains some no-printable characters (for this reason I choose base64 encoding).</p>
... | -1 | 2016-08-29T15:26:56Z | 39,210,134 | <p>You can use <a href="https://docs.python.org/2/library/functions.html#bytearray" rel="nofollow">bytearray</a> for exactly this. Possibly the <a href="https://docs.python.org/2/library/binascii.html" rel="nofollow">binascii</a> module and <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">struct</... | 1 | 2016-08-29T15:40:45Z | [
"python",
"string",
"embedded",
"base64",
"decode"
] |
collect some specific classes in python module | 39,209,891 | <p>I have a packages contains classes <code>C1, C2, CInvalid3, C4</code>, which are defined in different sub modules.</p>
<pre><code>my_package/
__init__.py
sub_package1/
__init__.py
sub_module1.py # contains C1, C2
sub_package2/
__init__.py
sub_module2.py # contains CInvali... | 1 | 2016-08-29T15:27:27Z | 39,213,082 | <p>To get what you're looking for, what you can do is to <em>mark</em> valid classes with a class attribute:</p>
<pre><code>class C1(object):
_valid = True
</code></pre>
<p>And then dynamically import all modules in your package, storing valid classes separately in your <code>all_valid_classes</code> dictionary dur... | 1 | 2016-08-29T18:44:44Z | [
"python",
"python-2.7",
"python-3.x",
"oop",
"python-3.4"
] |
Text got cut off when strange chars inside when trying to save into TEXT field | 39,209,898 | <p>Having a text like that in a file. I want to insert that text in my database (UTF8 encoding by the way).</p>
<pre><code>OK: "Spanning op P4V2 (TP2)" : 4.00 V DC <= 4.20 V DC
OK: "Spanning op P1V8_EHSX_BGS2 (TP1030)" : 1.81 V DC >= 1.71 V DC
OK: "Spanning op P1V8_EHSX_BGS2 (TP1030)" : 1.81 V DC <... | 0 | 2016-08-29T15:27:48Z | 39,210,042 | <p><code>0x00</code> (<code>^@</code>) is a string terminator. It is the only character you can not save in a 0x00-terminated field (which TEXT is).</p>
<p>Replace the chars and you will be just fine.</p>
| 1 | 2016-08-29T15:35:49Z | [
"python",
"postgresql",
"unicode",
"utf-8",
"psycopg2"
] |
NLTK can't find the Stanford POS tagger model file | 39,210,008 | <p>I am trying to use StanfordPOSTagger from the NLTK. I downloaded Stanford POS full tagger. I have set </p>
<pre><code>CLASSPATH=/home/waheeb/Stanford_Tools/stanford-postagger-full-2015-12-09 /stanford-postagger.jar
STANFORD_MODELS=home/waheeb/Stanford_Tools/stanford-postagger-full-2015-12-09/models
</code></pre>
... | 0 | 2016-08-29T15:33:41Z | 39,210,557 | <p>You forgot to use <code>export</code> in the command line before calling your python script. I.e. </p>
<pre><code>alvas@ubi:~$ export STANFORDTOOLSDIR=$HOME
alvas@ubi:~$ export CLASSPATH=$STANFORDTOOLSDIR/stanford-postagger-full-2015-12-09/stanford-postagger.jar
alvas@ubi:~$ export STANFORD_MODELS=$STANFORDTOOLSDIR... | 0 | 2016-08-29T16:05:03Z | [
"python",
"nlp",
"nltk",
"stanford-nlp",
"pos-tagger"
] |
Pandas: set a default datetime for None values | 39,210,033 | <p>I have a Pandas dataframe with columns that contain dates as strings (in SQL-like format). However, many cells contain <code>None</code> values. I'm trying to convert these columns to Pandas dates using <code>to_datetime</code> and set a "default" value for cells that contain the <code>None</code> value. Example cod... | 1 | 2016-08-29T15:34:51Z | 39,210,098 | <p>use <code>fillna</code></p>
<pre><code>df[date_cols] = df[date_cols].fillna(pd.to_datetime('2015-01-01'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/EPTWy.png" rel="nofollow"><img src="http://i.stack.imgur.com/EPTWy.png" alt="enter image description here"></a></p>
| 2 | 2016-08-29T15:38:18Z | [
"python",
"datetime",
"pandas"
] |
How can I write each element of a list to each line of a text file? | 39,210,073 | <p>Using python, I've got the following list:</p>
<pre><code>data = ['element0', 'element1', 'element2', 'element3']
</code></pre>
<p>And I want to write each element, into a new line of "myfile.txt", so I've been trying this:</p>
<pre><code>for x in data:
open("myfile.txt", "w").write(x + "\n")
</code></pre>
<... | 0 | 2016-08-29T15:37:02Z | 39,210,102 | <p>Just open the file object <strong>once</strong>:</p>
<pre><code>with open("myfile.txt", "w") as fobj:
for x in data:
fobj.write(x + "\n")
</code></pre>
<p>I'm using the file as a <em>context manager</em> by passing it to the <code>with</code> statement; this ensures that the file is closed again after ... | 4 | 2016-08-29T15:38:27Z | [
"python",
"list",
"file"
] |
Change the width of the Basic Bar Chart | 39,210,160 | <p>I create a Bar Chart with matplotlib with : </p>
<pre><code>import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('ETA_PRG_P2REF_RM', 'ETA_PRG_VDES_RM', 'ETA_PRG_P3REF_RM', 'Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
pe... | 1 | 2016-08-29T15:42:21Z | 39,210,442 | <p>You can add tick labels with a rotation:</p>
<pre><code>pyplot.xticks(y_pos, objects, rotation=70)
</code></pre>
<p>In addition to an angle in degrees, you can specify a string:</p>
<pre><code>pyplot.xticks(y_pos, objects, rotation='vertical')
</code></pre>
<p>You may also want to specify a horizontal alignment,... | 1 | 2016-08-29T15:57:51Z | [
"python",
"matplotlib",
"bar-chart"
] |
Trouble with Kivy ScreenManager | 39,210,179 | <p>Lately I have some problems with Kivy's Screenmanager. I can't use the <code>switch_to</code> method of the manager when accessing it from a <code>Screen</code> class. In a <code>Screen</code> class: <code>self.manager.switch_to</code> gives the error: <code>AttributeError: 'NoneType' object has no attribute 'switch... | 0 | 2016-08-29T15:43:41Z | 39,225,001 | <p>try declaring your screen manager as a global variable below screen1</p>
<pre><code>import kivy
kivy.require("1.9.1")
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen
screen1 = True
screen_manager = ScreenManager()
</code></pre>
<p>then in your bu... | 0 | 2016-08-30T10:27:43Z | [
"python",
"kivy"
] |
Python classes: method has same name as property | 39,210,250 | <p>I'm constructing a class Heating. Every instance of this class has the property 'temperature'. It's mandatory that Heating also supports the method temperature() that prints the property 'temperature' as an integer.</p>
<p>When I call the method temperature() I get the error 'int' object is not callable because sel... | -2 | 2016-08-29T15:47:42Z | 39,210,317 | <p>You can't have both a method and an attribute with the same name. Methods are attributes too, albeit ones that you can call.</p>
<p>Just rename the attribute to something else. You could use <code>_temperature</code>:</p>
<pre><code>def __init__(self, name, temperature = 10, minimum = 0, maximum = 100):
self.n... | 2 | 2016-08-29T15:51:04Z | [
"python",
"class"
] |
Select text from either a DIV or an underlying container, if it exists | 39,210,350 | <p>I'm having a div table where each row has two cells/columns.
The second cell/column sometimes has a clear text (<code><div class="something">Text</div></code>) while sometimes it's hidden within an "a" tag inside: <code><div class="something"><a href="url">Text</a></div></code>.</... | 0 | 2016-08-29T15:52:53Z | 39,212,148 | <p>If I understand you correctly then you should probably just iterate through program nodes and create item for every cycle. Also there's xpath shortcut <code>//text()</code> which captures all text under the node and it's childrem</p>
<p>Try something like:</p>
<pre><code>programs = response.xpath("//div[contains(@... | 0 | 2016-08-29T17:45:57Z | [
"python",
"scrapy"
] |
Function within while loop not running more than once | 39,210,360 | <p>I am writing a small game as a way to try and learn python. At the bottom of my code, there is a while loop which asks for user input. If that user input is yes, it is supposed to update a variable, encounter_prob. If encounter_prob is above 20, it is supposed to call the function. I can get this behavior to happen,... | 0 | 2016-08-29T15:53:16Z | 39,210,650 | <p>It's actually calling the function <code>encounter</code> twice but the first time ends up killing the monster by decreasing its <code>hp</code> to 0 or below, while the second time the function exits without entering the <code>while</code> loop because the <code>monster['hp'] > 0</code> comparison evaluates to <... | 2 | 2016-08-29T16:10:37Z | [
"python",
"python-2.7"
] |
Function within while loop not running more than once | 39,210,360 | <p>I am writing a small game as a way to try and learn python. At the bottom of my code, there is a while loop which asks for user input. If that user input is yes, it is supposed to update a variable, encounter_prob. If encounter_prob is above 20, it is supposed to call the function. I can get this behavior to happen,... | 0 | 2016-08-29T15:53:16Z | 39,211,378 | <p>Your code with a couple of print commands to show you how they can let you see what is going on, when you haven't finished all of your coding.<br>
Oh! and I evened things up a bit, can't have you with an unfair advantage :)</p>
<pre><code>import random
def def_monster_attack():
monster_attack = random.randrang... | 0 | 2016-08-29T16:57:51Z | [
"python",
"python-2.7"
] |
Defining Python function with input | 39,210,459 | <p>I have Postgres table called Records with several appIds. I am writing a function to pull out the data for one <code>AppId</code> (ABC0123) and want to store this result in dataframe <code>df</code>.
I have created a variable AppId1 to store my AppId(ABC0123) and passed it to the query.
The script got executed, but... | 1 | 2016-08-29T15:59:08Z | 39,210,549 | <ul>
<li>Change % AppId1 to % AppId only.</li>
<li>return df</li>
</ul>
<p></p>
<pre><code>def fun(AppId):
AppId1=pd.read_sql_query(""" select 'AppId' from 'Records' where 'AppId'='%s'""" %AppId,con=engine )
query = """ SELECT 'AppId' from 'Records' where AppId='%s' """ %AppId
df=pd.read_sql_query(query,c... | 0 | 2016-08-29T16:04:21Z | [
"python",
"postgresql",
"function"
] |
Flurry Login Requests.Session() Python 3 | 39,210,484 | <p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
loginurl = "https:... | 5 | 2016-08-29T16:00:18Z | 39,217,281 | <p>They now have a new design and a <a href="https://login.flurry.com/home" rel="nofollow">new login page</a> to which they redirect you too - that's why you see 302 and 303 status codes. The login process and logic behind it, the URLs, links to CSV files - everything is now different and you have to "reimplement"/"rem... | 1 | 2016-08-30T00:50:36Z | [
"python",
"python-3.x",
"session",
"beautifulsoup",
"flurry"
] |
Flurry Login Requests.Session() Python 3 | 39,210,484 | <p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
loginurl = "https:... | 5 | 2016-08-29T16:00:18Z | 39,301,685 | <p>You can offer up a dummy session id and it will log you in with a new one. <a href="https://www.getpostman.com/docs/" rel="nofollow">Postman</a> interceptor helped with the redirects.</p>
<pre><code>import requests
import json
def login(email, password, session, session_id=None):
""" Authenticate with flurry.c... | 1 | 2016-09-02T23:02:33Z | [
"python",
"python-3.x",
"session",
"beautifulsoup",
"flurry"
] |
Flurry Login Requests.Session() Python 3 | 39,210,484 | <p>So I had this question answered before <a href="http://stackoverflow.com/questions/38670599/flurry-scraping-using-python3-requests-session">here</a>. However, something on the Flurry website has changed and the answer no longer works.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
loginurl = "https:... | 5 | 2016-08-29T16:00:18Z | 39,337,666 | <p>you can use uuid lib to generate an uuid for the session id, in order to use the old interface you'll need to perform a request to <a href="https://dev.flurry.com/home.do?isFirstPostLogin=true" rel="nofollow">https://dev.flurry.com/home.do?isFirstPostLogin=true</a>, now you can get the csv. (url_get variable)</p>
<... | 0 | 2016-09-05T21:02:46Z | [
"python",
"python-3.x",
"session",
"beautifulsoup",
"flurry"
] |
Call a __init__ function from another function | 39,210,531 | <p>I need some help form all of you, so i have something like this</p>
<pre><code>class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
...
...
...
def _login_btn_clickked(self):
...
...
result = messagebox.askyesno("Wrong usernam... | 1 | 2016-08-29T16:03:22Z | 39,210,631 | <blockquote>
<p>But when i execute the program the process fail. </p>
</blockquote>
<p>Actually it should. <code>__init__</code> method is normally called once an instance is created. You need to redesign this to either recreate an instance (first call <code>pack_forget</code> on that frame and then make new one and... | 0 | 2016-08-29T16:09:51Z | [
"python",
"recursion"
] |
Call a __init__ function from another function | 39,210,531 | <p>I need some help form all of you, so i have something like this</p>
<pre><code>class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
...
...
...
def _login_btn_clickked(self):
...
...
result = messagebox.askyesno("Wrong usernam... | 1 | 2016-08-29T16:03:22Z | 39,210,634 | <p>Are you using tkinter.Frame?</p>
<p>I should think that it wouldn't like being reconstructed through the use of
super().<strong>init</strong>()
While already being packed into a root window (I'm adsuming that is the setup you have).</p>
| 0 | 2016-08-29T16:09:56Z | [
"python",
"recursion"
] |
PyQt Qwizardpage : Cut up url after Question mark letter, and add groupbox to each found | 39,210,556 | <p>This is a double question</p>
<p>Questions</p>
<p><s>1) split url after question marks</s></p>
<p>2) when split up, count how many questions marks , and add a groupbox to each found </p>
<p>I making a Qwizardpage which have two pages.</p>
<p>PyQt4 Qwizardpage app info.</p>
<p>On page one i have a textboxEdit w... | 0 | 2016-08-29T16:05:01Z | 39,211,151 | <p>You can use some string splitting in your case:</p>
<pre><code>url ="http://example.com/over/example?sender=senderexample&password=passwxample&recipients=recipientsexample&sId=idexample&content=contentexample"
for key_value in url.split("?")[1].split("&"):
tsplit = key_value.split("=")
... | 0 | 2016-08-29T16:42:38Z | [
"python",
"split",
"pyqt4",
"groupbox"
] |
How can I get values from dictionary for particular key using python | 39,210,569 | <p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa... | 2 | 2016-08-29T16:05:37Z | 39,210,723 | <p>The working version of the code should be:</p>
<pre><code>my_dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa']}
iin = input('Enter your ID :')
# Enter your ID :"bb"
try:
my_id = my_dict['id'].index(iin)
print my_dict['... | 0 | 2016-08-29T16:15:20Z | [
"python",
"for-loop",
"dictionary",
"input",
"output"
] |
How can I get values from dictionary for particular key using python | 39,210,569 | <p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa... | 2 | 2016-08-29T16:05:37Z | 39,210,735 | <p>There's no need to loop over all the items in the dictionary; it would be silly to look for an id in the <code>Firstname</code> and <code>Lastname</code> fields. (And this could produce incorrect results if the entered id happens to be a substring of someone's name.)</p>
<p>What you want is to check if the given i... | 3 | 2016-08-29T16:15:53Z | [
"python",
"for-loop",
"dictionary",
"input",
"output"
] |
How can I get values from dictionary for particular key using python | 39,210,569 | <p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa... | 2 | 2016-08-29T16:05:37Z | 39,210,764 | <p>Building on <a href="http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python">previous posts</a></p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', ... | -1 | 2016-08-29T16:17:56Z | [
"python",
"for-loop",
"dictionary",
"input",
"output"
] |
How can I get values from dictionary for particular key using python | 39,210,569 | <p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa... | 2 | 2016-08-29T16:05:37Z | 39,210,781 | <p>Please check the below code with comments inline.</p>
<pre><code>iin = input('Enter your ID :')
d = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa']}
#Get list of IDs
id_list = d['id']
#Check input in list
if iin in id_list:
#Get ind... | 3 | 2016-08-29T16:19:15Z | [
"python",
"for-loop",
"dictionary",
"input",
"output"
] |
How can I get values from dictionary for particular key using python | 39,210,569 | <p>In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa... | 2 | 2016-08-29T16:05:37Z | 39,210,891 | <p>Using .items() will allow for a loop on a dictionary.</p>
<pre><code>iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa']}
for k, v in dict.items():
if k == 'id':
loc = v.index(iin)
print(... | -1 | 2016-08-29T16:26:26Z | [
"python",
"for-loop",
"dictionary",
"input",
"output"
] |
Python PDF module and Visual Studio | 39,210,636 | <p>I'm teaching myself Python thanks to a book and nice people i find every day in SO. Thanks all of you.</p>
<p>The question is that i been using VS, because i find it easy, but idk how/where to write commands like "python pythonprogram.py" and make use of the optparse module as i do on a Linux console.</p>
<p>The p... | 0 | 2016-08-29T16:09:58Z | 39,216,108 | <p>To make sure where your relative path starts, you might want to use <code>os.chdir</code></p>
<pre><code>from os import chdir
chdir("path/to/my/python/file")
</code></pre>
<p>then, you'll be able to import files in the same directory even if you're running the script from another folder.</p>
<p>Hope that helps</p... | 0 | 2016-08-29T22:25:43Z | [
"python",
"visual-studio",
"python-3.x",
"pdf"
] |
Change name of the "Authentication and Authorization" menu in Django/python | 39,210,668 | <p>I'm learning python/Django and setting up my first project. All is going well but I've been searching like crazy on something very simple.</p>
<p>There is a default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I need to extend something, I've searched ... | 0 | 2016-08-29T16:11:29Z | 39,212,494 | <p>This can't be done at least cleanly via templates..</p>
<p>You can put the auth app verbose name "authentication and authorization" in your own .po file (& follow Django docs on translation)
This way Django will normally use your name. </p>
| 0 | 2016-08-29T18:08:11Z | [
"python",
"django",
"admin"
] |
Change name of the "Authentication and Authorization" menu in Django/python | 39,210,668 | <p>I'm learning python/Django and setting up my first project. All is going well but I've been searching like crazy on something very simple.</p>
<p>There is a default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I need to extend something, I've searched ... | 0 | 2016-08-29T16:11:29Z | 39,213,750 | <p>Create a custom <code>AppConfig</code> pointing to original <code>django.auth</code> module and override <code>verbose_name</code>. Then use your custom <code>AppConfig</code> in <code>INSTALLED_APPS</code> instead of original <code>auth</code> app.</p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/applica... | 0 | 2016-08-29T19:28:40Z | [
"python",
"django",
"admin"
] |
plot data points on map | 39,210,706 | <p>While trying to plot gps coordinates on a map from a CSV file named test_gps.csv and i am getting the error:</p>
<pre><code>ValueError: Some errors were detected !
Line #1 (got 2 columns instead of 2)
Line #2 (got 2 columns instead of 2)
...
</code></pre>
<p>My code is:</p>
<pre><code>import numpy as ... | 1 | 2016-08-29T16:14:02Z | 39,211,375 | <p>It is because the index in usecols starts from 0 not 1. And the code was expecting another column to read the data and throwing the error.</p>
<p>This change in the code is able to read the values.</p>
<pre><code>airports = np.genfromtxt("test_gps.csv",
delimiter=';',
dty... | 1 | 2016-08-29T16:57:41Z | [
"python",
"matplotlib-basemap"
] |
Selenium Python - Finding div containing two specific elements | 39,210,743 | <p>I'm building a python script using selenium, and have ran into a quite confusing problem.</p>
<p>The website lists products using a name, which is not unique, and a color, which is not unique either. The color and name elements have the same parent.</p>
<p>My script gets user input on which product he wants the sc... | 0 | 2016-08-29T16:16:30Z | 39,211,028 | <p>Create a main loop that selects each <code>div class="inner-article"</code> element.</p>
<p>In the loop, look for elements that have an <code>h1</code> child element and an <code>a class=product-name</code> grandchild element with text of "Silk Shirt", and a <code>p</code> child element and a <code>a class=product-... | 1 | 2016-08-29T16:35:09Z | [
"python",
"css",
"selenium",
"selection"
] |
Selenium Python - Finding div containing two specific elements | 39,210,743 | <p>I'm building a python script using selenium, and have ran into a quite confusing problem.</p>
<p>The website lists products using a name, which is not unique, and a color, which is not unique either. The color and name elements have the same parent.</p>
<p>My script gets user input on which product he wants the sc... | 0 | 2016-08-29T16:16:30Z | 39,254,483 | <p>Perhaps try searching using xpath. The xpath below will return the div element that contains the product and color you desire.</p>
<pre><code>driver.find_element_by_xpath('//div[@class="inner-article"][.//a[@class="product-name"][.="Silk Shirt"]][.//a[@class="product-color"][.="Black"]]')
</code></pre>
<p>To make ... | 0 | 2016-08-31T16:16:57Z | [
"python",
"css",
"selenium",
"selection"
] |
Randomly distribute files into train/test given a ratio | 39,210,765 | <p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually.
I started doing this in bash, but quickly realized that would not work that well. </p>
<p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was... | 0 | 2016-08-29T16:17:58Z | 39,210,813 | <p><code>scikit-learn</code> comes to the rescue =)</p>
<pre><code>>>> import numpy as np
>>> from sklearn.cross_validation import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
&g... | 2 | 2016-08-29T16:21:30Z | [
"python",
"bash",
"text-files",
"file-handling",
"train-test-split"
] |
Randomly distribute files into train/test given a ratio | 39,210,765 | <p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually.
I started doing this in bash, but quickly realized that would not work that well. </p>
<p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was... | 0 | 2016-08-29T16:17:58Z | 39,211,194 | <p>Here's first dry-cut solution, pure Python:</p>
<pre><code>import sys, random, os
def splitdirs(files, dir1, dir2, ratio):
shuffled = files[:]
random.shuffle(shuffled)
num = round(len(shuffled) * ratio)
to_dir1, to_dir2 = shuffled[:num], shuffled[num:]
for d in dir1, dir2:
if not os.pat... | 1 | 2016-08-29T16:45:12Z | [
"python",
"bash",
"text-files",
"file-handling",
"train-test-split"
] |
Randomly distribute files into train/test given a ratio | 39,210,765 | <p>I am at the moment trying make a setup script, capable of setting up a workspace up for me, such that I don't need to do it manually.
I started doing this in bash, but quickly realized that would not work that well. </p>
<p>My next idea was to do it using python, but can't seem to do it a proper way.. My idea was... | 0 | 2016-08-29T16:17:58Z | 39,254,279 | <p>Here's a simple example that uses bash's <code>$RANDOM</code> to move things to one of two target directories.</p>
<pre><code>$ touch {1..10}
$ mkdir red blue
$ a=(*/)
$ RANDOM=$$
$ for f in [0-9]*; do mv -v "$f" "${a[$((RANDOM/(32768/${#a[@]})))]}"; done
1 -> red/1
10 -> red/10
2 -> blue/2
3 -> red/3
4... | 1 | 2016-08-31T16:04:27Z | [
"python",
"bash",
"text-files",
"file-handling",
"train-test-split"
] |
Python figure crashing and is unresponsive | 39,210,995 | <p>I'm trying to make a script where it'll go to each point and save a figure of the plot if the point is good or not. But the figure is just unresponsive/blank. Any ideas?</p>
<pre><code>import matplotlib.pyplot as plt
A = range(-3, 3, 1)
for moving in range(len(A)):
parsedFile = 'TEST/data_%d' % (moving)
... | 1 | 2016-08-29T16:33:14Z | 39,214,930 | <p>In non-interactive mode <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow">plt.show()</a> will block until the figure is closed. The <code>block</code> argument is experimental according to the documentation, and it seems to me that it won't work in your case. Well, at least it... | 0 | 2016-08-29T20:47:42Z | [
"python",
"debugging",
"figure"
] |
Operation of Python's LRU cache | 39,211,095 | <p>I've got the following code:</p>
<pre><code>def sharpe(self):
return (self.weighted_returns()/self.weighted_returns().std())*np.sqrt(252)
</code></pre>
<p>Where <code>self.weighted_returns()</code> has a <code>@lru_cache(maxsize=None)</code> decorator.</p>
<p>Will <code>self.weighted_returns()</code> be calcu... | 0 | 2016-08-29T16:38:43Z | 39,211,532 | <p>You could use <code>functools.lru_cache</code> for this. But if you're only caching the calculations for <code>self</code> and the function does not use an argument, it is an overkill. </p>
<p>Rather, I'd steal the lazy <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/api/decorator.html#pyramid.dec... | 0 | 2016-08-29T17:06:50Z | [
"python",
"python-3.x"
] |
Prime code not working | 39,211,186 | <p>I am trying to learn some code, and found python. I'm only a beginner but intrested in a programming language.</p>
<p>I have some trouble writing my first program. I am trying to make a program that ask the user for a number, then checks if the number is a prime number, if it is, it will add it to the prime number ... | 0 | 2016-08-29T16:44:37Z | 39,211,354 | <pre><code>prime.extend(get)
</code></pre>
<p><code>extend</code> is used to add a list to a list. If you only want to add a single value, use <code>append</code>.</p>
<pre><code>prime.append(get)
</code></pre>
| 2 | 2016-08-29T16:56:20Z | [
"python",
"primes"
] |
Prime code not working | 39,211,186 | <p>I am trying to learn some code, and found python. I'm only a beginner but intrested in a programming language.</p>
<p>I have some trouble writing my first program. I am trying to make a program that ask the user for a number, then checks if the number is a prime number, if it is, it will add it to the prime number ... | 0 | 2016-08-29T16:44:37Z | 39,211,505 | <p>Given the way you set it up, you would get that 26 is a prime. Since it is only divisible by 13, and 13 is not yet in the table, it will fall through the while. You need to find all primes less than the number that you ask for to populate your table, or set the program find the first n primes.</p>
<p>I notice that ... | 1 | 2016-08-29T17:05:15Z | [
"python",
"primes"
] |
A pythonic way to use Lxml to find all elements of a certain type | 39,211,236 | <p>I'm not very good with Lxml but thought a few of you might know how one can quickly get through the following task. See below... Specifically, I need to parse the XML to get the value of the name attribute in all of the category elements. For example:</p>
<pre><code><categories>
<category name="Test"&... | -1 | 2016-08-29T16:48:38Z | 39,211,335 | <pre><code>names = root_el.xpath('//category/@name')
</code></pre>
| 1 | 2016-08-29T16:54:53Z | [
"python",
"xml",
"lxml"
] |
Failure to load image with AsyncImage in kivy | 39,211,301 | <p>i have a code that loads an image online with the AsyncImage module in kivy. i wrote the code in python3 which runs well on the pc but doesnt work on a packaged apk. i think this is because i packaged it using python2.7 buildozer. thanks <a href="http://i.stack.imgur.com/I5f0V.png" rel="nofollow">an image showing th... | 2 | 2016-08-29T16:52:51Z | 39,221,882 | <p>It seems that your APK is missing ssl support (the URL is redirecting you to an https site...)</p>
<p>try adding:</p>
<pre><code> requirements = kivy,OTHER_STUFF_YOU_NEED,openssl
</code></pre>
<p>to your buildozer spec.</p>
| 1 | 2016-08-30T07:57:18Z | [
"python",
"kivy"
] |
multiprocessing - calling function with different input files | 39,211,309 | <p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p>
<p>I have an empty list for adding matched results to:</p>
<pre><code>match = []
</code></pre>
<p>I have a list <code>restrictions</... | 1 | 2016-08-29T16:53:15Z | 39,211,384 | <p>Multiprocessing creates multiple processes. The context of your "match" variable will now be in that child process, not the parent Python process that kicked the processing off.</p>
<p>Try writing the list results out to a file in your function to see what I mean.</p>
| 1 | 2016-08-29T16:58:20Z | [
"python",
"multiprocessing"
] |
multiprocessing - calling function with different input files | 39,211,309 | <p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p>
<p>I have an empty list for adding matched results to:</p>
<pre><code>match = []
</code></pre>
<p>I have a list <code>restrictions</... | 1 | 2016-08-29T16:53:15Z | 39,211,579 | <p>To expand cthrall's answer, you need to return something from your function in order to pass the info back to your main thread, e.g.</p>
<pre><code>def link_match(file):
[put all the code here]
return match
[main thread]
all_matches = pool.map(link_match,list_files)
</code></pre>
<p>the list <code>match</... | 1 | 2016-08-29T17:09:33Z | [
"python",
"multiprocessing"
] |
multiprocessing - calling function with different input files | 39,211,309 | <p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p>
<p>I have an empty list for adding matched results to:</p>
<pre><code>match = []
</code></pre>
<p>I have a list <code>restrictions</... | 1 | 2016-08-29T16:53:15Z | 39,211,781 | <p><code>multiprocessing</code> runs a new instance of Python for each process in the pool - the context is empty (if you use <code>spawn</code> as a start method) or copied (if you use <code>fork</code>), plus copies of any arguments you pass in (either way), and from there they're all separate. If you want to pass da... | 1 | 2016-08-29T17:22:33Z | [
"python",
"multiprocessing"
] |
multiprocessing - calling function with different input files | 39,211,309 | <p>I have a function which reads in a file, compares a record in that file to a record in another file and depending on a rule, appends a record from the file to one of two lists. </p>
<p>I have an empty list for adding matched results to:</p>
<pre><code>match = []
</code></pre>
<p>I have a list <code>restrictions</... | 1 | 2016-08-29T16:53:15Z | 39,211,994 | <p>When multiprocessing, each subprocess gets its own copy of any global variables in the main module defined before the <code>if __name__ == '__main__':</code> statement. This means that the <code>link_match()</code> function in each one of the processes will be accessing a <em>different</em> <code>match</code> list i... | 1 | 2016-08-29T17:35:38Z | [
"python",
"multiprocessing"
] |
Custom initializer for get_variable | 39,211,332 | <p>How can one specify a custom initializer as the third argument for <code>tf.get_variable()</code>? Specifically, I have a variable <code>y</code> which I want to initialize using another (already initialized) variable <code>x</code>. </p>
<p>This is easy to do using <code>tf.Variable()</code>, just say, <code>y = t... | 2 | 2016-08-29T16:54:32Z | 39,211,524 | <p>You can use <code>x.initialized_value()</code> as well. For example:</p>
<pre><code>import tensorflow as tf
x = tf.Variable(1.0)
y = tf.get_variable('y', initializer=x.initialized_value())
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(sess.run(y)) #Â prints 1.0
</code></pre>
| 1 | 2016-08-29T17:06:27Z | [
"python",
"tensorflow"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.