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 |
|---|---|---|---|---|---|---|---|---|---|
Creating functions from following code in python | 38,821,414 | <p>I'm trying to create functions from the following code but am having trouble. I've posted the code i want to make functions out of up top and my failed attempt at the bottom. Thanks for your help </p>
<pre><code>inputFile = open(inputPath)
name = ""
for line in inputFile:
lineSegment = line.split(", ")
if name != l... | 0 | 2016-08-08T04:41:40Z | 38,821,482 | <p><code>open()</code> returns a file object, and is most commonly used with two arguments: <code>open(filename, mode)</code>.</p>
| -3 | 2016-08-08T04:49:55Z | [
"python",
"arcpy"
] |
How to make a drop down menu and connect the choice to a CBGV | 38,821,480 | <p>I am new to Django and am struggling to understand how to make a user accessible connection between two models.</p>
<p>models.py:</p>
<pre><code>class StudyGroup(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
ex_1_trial = models.IntegerField(blank=True, null=True, defaul... | 0 | 2016-08-08T04:49:46Z | 38,852,548 | <p>The best way I see it can be done is via the <code>forms.py</code>, indeeed. Especially, that you will be altering the data in your database. You would want to use <code>POST</code> method together with <code>CSRF</code>, because of that.</p>
<p>So you first of all you need to create <code>forms.py</code> with a
<... | 0 | 2016-08-09T13:45:23Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Write one element by row in a csv file with scrapy | 38,821,485 | <p>I'm scraping this page:</p>
<p><a href="http://www.mymcpl.org/cfapps/botb/movie.cfm" rel="nofollow">http://www.mymcpl.org/cfapps/botb/movie.cfm</a></p>
<p>Extracting four items:
book, author, movie,movie_year</p>
<p>I want to save this in a CSV file where each row contain records of one movie.</p>
<p>This is the... | 0 | 2016-08-08T04:50:18Z | 38,822,724 | <p>Scrapy already has in-built csv exporter. All you have to do is yield items and scrapy will output those items to csv file.</p>
<pre><code>def parse(self, response):
xpaths = {'book':'//*[@id="main"]/tr[{}]/td[2]/text()[1]',
'author':'//*[@id="main"]/tr[{}]/td[2]/a/text()',
'movie':'... | 1 | 2016-08-08T06:42:10Z | [
"python",
"csv",
"web-scraping",
"scrapy",
"yield"
] |
Pycharm manage.py autocomplete error | 38,821,565 | <p>In every django project manage.py commands work but no autocomplete</p>
<p>Failed to get real commands on module "projects_name" python died with code 1
File opt/Pycharm/helpers/.../jb_manage_tasks_provider.py
File opt/pycharm/helpers.../parser.py
File my virtual env folder/lib/python3.5/site packages/django/core/m... | 3 | 2016-08-08T04:58:59Z | 38,821,846 | <p>i've been using django 1.10 and pycharm not supporting it yet.
Downgraded to 1.9.8 and now autocompletion works without errors</p>
| 3 | 2016-08-08T05:27:41Z | [
"python",
"django"
] |
Pycharm manage.py autocomplete error | 38,821,565 | <p>In every django project manage.py commands work but no autocomplete</p>
<p>Failed to get real commands on module "projects_name" python died with code 1
File opt/Pycharm/helpers/.../jb_manage_tasks_provider.py
File opt/pycharm/helpers.../parser.py
File my virtual env folder/lib/python3.5/site packages/django/core/m... | 3 | 2016-08-08T04:58:59Z | 38,841,790 | <p>You can use helper from community edition which support django 1.10+
Replace file
JetBrains\PyCharm 2016.2\helpers\pycharm\django_manage_commands_provider_parser\parser.py</p>
<p>with <a href="https://github.com/JetBrains/intellij-community/blob/master/python/helpers/pycharm/django_manage_commands_provider/_parser... | 1 | 2016-08-09T03:58:43Z | [
"python",
"django"
] |
One line to check if string or list, then convert to list in Python | 38,821,586 | <p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>... | 1 | 2016-08-08T05:00:33Z | 38,821,619 | <p>You can use a ternary operator:</p>
<pre><code>a = [a] if isinstance(a, str) else a
</code></pre>
| 1 | 2016-08-08T05:03:57Z | [
"python"
] |
One line to check if string or list, then convert to list in Python | 38,821,586 | <p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>... | 1 | 2016-08-08T05:00:33Z | 38,821,625 | <pre><code>[a] if isinstance(a, str) else a
</code></pre>
| 0 | 2016-08-08T05:05:03Z | [
"python"
] |
One line to check if string or list, then convert to list in Python | 38,821,586 | <p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>... | 1 | 2016-08-08T05:00:33Z | 38,821,657 | <p>I prefer the other option rather than <code>isinstance</code>:</p>
<pre><code>b = [a] if type(a) is str else a
print(b)
</code></pre>
<p>And it's possible to do the other way around:</p>
<pre><code>b = a if type(a) is list else [a]
</code></pre>
<p>And even make it a little ore robust:</p>
<pre><code>b = a if t... | 0 | 2016-08-08T05:08:44Z | [
"python"
] |
How does .apply in Graphlab work? | 38,821,591 | <p>I have been programming in Java and am trying to learn Python and Graphlab now.</p>
<p>I looked at the Graphlab documentation here but it is insufficient for me to understand how .apply works. There does not seem to be much on Google either.</p>
<p>There are two examples of usage I am trying to figure out:</p>
<o... | 0 | 2016-08-08T05:01:15Z | 40,030,242 | <p>Here is a quick demo on use of apply. Its creating a new column in the sframe from an existing sframe column. The new column is squared.</p>
<pre><code>train_data['bedrooms_squared'] = train_data['bedrooms'].apply(lambda x: x**2)
</code></pre>
| 0 | 2016-10-13T20:20:12Z | [
"python",
"graphlab"
] |
Automate outlook web app by using selenium , python | 38,821,726 | <p>I am trying to send email automatically from my office outlook web app. I have successfully automated the login process of outlook. But after login, there is no inspect element on new tab for sending mail. So how can i click on this new tab with selenium. Do i need to use some other framework for that.</p>
<p>Flow ... | 0 | 2016-08-08T05:16:52Z | 38,823,472 | <p>Using <code>Selenium</code> for email generation is not the best idea. I advise you to look toward <a href="https://win32com.goermezer.de/content/view/227/291/" rel="nofollow"><code>win32com.client</code></a> or <a href="https://docs.python.org/2/library/smtplib.html" rel="nofollow"><code>smtplib</code></a></p>
<p>... | 0 | 2016-08-08T07:27:58Z | [
"python",
"selenium",
"automation"
] |
Automate outlook web app by using selenium , python | 38,821,726 | <p>I am trying to send email automatically from my office outlook web app. I have successfully automated the login process of outlook. But after login, there is no inspect element on new tab for sending mail. So how can i click on this new tab with selenium. Do i need to use some other framework for that.</p>
<p>Flow ... | 0 | 2016-08-08T05:16:52Z | 39,256,136 | <p>I used Firebug Plugin of Firefox to inspect and now I am able to see elements.
Thanks everybody for providing the answer.</p>
| 0 | 2016-08-31T17:57:17Z | [
"python",
"selenium",
"automation"
] |
python: "while (len(list1)>0) or (len(list2)>0)" doesn't work | 38,821,756 | <p>Im taking the Google Python Course and I am solving the below problem:</p>
<blockquote>
<p>Given two lists sorted in increasing order, create and return a merged >list of all the elements in sorted order. You may modify the passed in >lists. Ideally, the solution should work in "linear" time, making a single >pas... | 0 | 2016-08-08T05:19:14Z | 38,821,789 | <blockquote>
<p>My issue is even though I check if both lists are empty...</p>
</blockquote>
<p>No, you are checking if <strong>either one of them is not empty</strong>.</p>
<hr>
<p>Change this:</p>
<pre><code>while (len(list1)>0) or (len(list2)>0)
</code></pre>
<p>To this:</p>
<pre><code>while (len(list1... | 1 | 2016-08-08T05:21:50Z | [
"python"
] |
manytomany relation does not exist. It's in a different schema | 38,821,937 | <p>I use AbstractBaseUser together with CustomPermissionsMixin.
CustomPermissionsMixin is kind of the same with django PermissionsMixin the difference is I changed related_name and related_query_name for user_permissions and groups so it won't clashing with django PermissionsMixin related_name</p>
<pre><code>@python_... | 5 | 2016-08-08T05:37:38Z | 38,932,776 | <p>I found the problem was about django tenant schemas and not django. <s>The migrate_schema --shared actually migrates the whole makemigration files regardless of the app being shared or tenant.</s> Both apps (shared and tenant) are registered in <code>django_content_type</code> table which also registered in <code>au... | 3 | 2016-08-13T12:33:21Z | [
"python",
"django",
"postgresql",
"django-models",
"django-rest-framework"
] |
Processing/Transposing Pandas Dataframe | 38,821,985 | <p>I got the following pandas dataframe: </p>
<pre><code>Id Category
1 type 2
1 type 3
1 type 2
2 type 1
2 type 2
</code></pre>
<p>I need to process and transpose the above data frame to:</p>
<pre><code>Id Category_type_1 Category_type_2 Category_type_3
1 0 2 ... | 3 | 2016-08-08T05:42:55Z | 38,822,028 | <pre><code>pd.crosstab(df['Id'], df['Category'])
Out:
Category type 1 type 2 type 3
Id
1 0 2 1
2 1 1 0
</code></pre>
| 3 | 2016-08-08T05:47:14Z | [
"python",
"pandas",
"dataframe",
"pivot-table",
"crosstab"
] |
Processing/Transposing Pandas Dataframe | 38,821,985 | <p>I got the following pandas dataframe: </p>
<pre><code>Id Category
1 type 2
1 type 3
1 type 2
2 type 1
2 type 2
</code></pre>
<p>I need to process and transpose the above data frame to:</p>
<pre><code>Id Category_type_1 Category_type_2 Category_type_3
1 0 2 ... | 3 | 2016-08-08T05:42:55Z | 38,822,035 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>print (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0))
Category type 1 type 2 type 3
Id
1 0... | 2 | 2016-08-08T05:48:02Z | [
"python",
"pandas",
"dataframe",
"pivot-table",
"crosstab"
] |
Processing/Transposing Pandas Dataframe | 38,821,985 | <p>I got the following pandas dataframe: </p>
<pre><code>Id Category
1 type 2
1 type 3
1 type 2
2 type 1
2 type 2
</code></pre>
<p>I need to process and transpose the above data frame to:</p>
<pre><code>Id Category_type_1 Category_type_2 Category_type_3
1 0 2 ... | 3 | 2016-08-08T05:42:55Z | 38,823,489 | <p>I'd <code>groupby</code> and use <code>size</code></p>
<pre><code>df.groupby(df.columns.tolist()).size().unstack().fillna(0)
</code></pre>
<p><a href="http://i.stack.imgur.com/mzcAD.png" rel="nofollow"><img src="http://i.stack.imgur.com/mzcAD.png" alt="enter image description here"></a></p>
| 4 | 2016-08-08T07:29:01Z | [
"python",
"pandas",
"dataframe",
"pivot-table",
"crosstab"
] |
Cannot install python package tables | 38,822,105 | <pre><code>[root@e06e8f90e201 optimus]# pip install tables
Collecting tables
Downloading tables-3.2.3.1.tar.gz (7.1MB)
100% |################################| 7.1MB 120kB/s
Complete output from command python setup.py egg_info:
/usr/bin/ld: cannot find -lhdf5
collect2: error: ld returned 1 exit statu... | 0 | 2016-08-08T05:55:23Z | 38,822,223 | <p>From the blurp on <code>tables</code> on PyPI: </p>
<blockquote>
<p>PyTables is built on top of the HDF5 library ...</p>
</blockquote>
<p>Therefore you have to have the libhdf5.[so/a] library installed, which is also
mentioned in the <a href="http://www.pytables.org/usersguide/installation.html" rel="nofollow">p... | 1 | 2016-08-08T06:05:35Z | [
"python",
"pip",
"hdf5"
] |
PSQL - How to filter out if a column value equals a specific string | 38,822,255 | <p>I created a database with column called option where the value is a varchar of either 'Call', 'Put', or None. When I set up the database I made the default value None if there was no Call or Put.</p>
<p>I'm trying to filter out the rows that contain 'Call' or 'Put' for option. However, when I write the query</p>
<... | 1 | 2016-08-08T06:08:23Z | 38,822,481 | <p>There is logic error in statement. You should write this instead:</p>
<pre><code>SELECT * FROM holdings h WHERE h.option != 'Call' OR h.option != 'Put';
</code></pre>
<p>or this:</p>
<pre><code>SELECT * FROM holdings h WHERE h.option NOT IN ( 'Call' , 'Put');
</code></pre>
<p>Thanks.</p>
| 0 | 2016-08-08T06:25:19Z | [
"python",
"postgresql"
] |
PSQL - How to filter out if a column value equals a specific string | 38,822,255 | <p>I created a database with column called option where the value is a varchar of either 'Call', 'Put', or None. When I set up the database I made the default value None if there was no Call or Put.</p>
<p>I'm trying to filter out the rows that contain 'Call' or 'Put' for option. However, when I write the query</p>
<... | 1 | 2016-08-08T06:08:23Z | 38,823,045 | <p>Looks like Syntax error here:</p>
<p><code>curr.execute('SELECT option FROM holdings h WHERE option NOT LIKE '%Call%';')</code></p>
<p>String 1 is <code>'SELECT option FROM holdings h WHERE option NOT LIKE '</code>, breaks with <code>'</code> (before <code>%Call%</code>), then some variable named Call (which Your... | 3 | 2016-08-08T07:02:42Z | [
"python",
"postgresql"
] |
Getting a sane default date axis in matplotlib | 38,822,294 | <p>I am often working interactively in an ipython shell or ipython notebook.
Say, I had a <code>pandas.DataFrame</code> with a <code>DatetimeIndex</code>, like this:</p>
<pre><code>idx = pd.date_range("12:00", periods=400000, freq="S")
df = pd.DataFrame({"temp":np.random.normal(size=len(idx))}, index=idx)
</code></pre... | 2 | 2016-08-08T06:10:56Z | 38,822,426 | <p>You can use <a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.DateFormatter" rel="nofollow"><code>DateFormatter</code></a>:</p>
<pre><code>import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize=(8,5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M:%S'))
#rotates the ti... | 2 | 2016-08-08T06:21:10Z | [
"python",
"datetime",
"pandas",
"matplotlib"
] |
Why does Python return an escaping backslash in a string? | 38,822,301 | <pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
</code></pre>
<p>gives as output:</p>
<pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
</code></pre>
<p>Why is the escape character showing up in the output? </p>
<p>When I type the string below, this doesn't happen.</p>
<pr... | 0 | 2016-08-08T06:11:22Z | 38,822,332 | <p>because in first one the whole string is in one-quote so another one-quotes should be escaped. Whereas in second one the whole string is in double quote.</p>
<pre><code>>>> '\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
^ ... | 2 | 2016-08-08T06:13:49Z | [
"python",
"string",
"syntax",
"escaping"
] |
Why does Python return an escaping backslash in a string? | 38,822,301 | <pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
</code></pre>
<p>gives as output:</p>
<pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
</code></pre>
<p>Why is the escape character showing up in the output? </p>
<p>When I type the string below, this doesn't happen.</p>
<pr... | 0 | 2016-08-08T06:11:22Z | 38,822,339 | <p>The escape character is needed because that is the string that, if typed out exactly, would reproduce the string. The string contains both single and double quotes, so whichever type encloses the string will need to be escaped within the string.</p>
| 0 | 2016-08-08T06:14:19Z | [
"python",
"string",
"syntax",
"escaping"
] |
Why does Python return an escaping backslash in a string? | 38,822,301 | <pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
</code></pre>
<p>gives as output:</p>
<pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
</code></pre>
<p>Why is the escape character showing up in the output? </p>
<p>When I type the string below, this doesn't happen.</p>
<pr... | 0 | 2016-08-08T06:11:22Z | 38,822,877 | <p>You get to choose either single quotes or double quotes to enclose a string. Any occurrences of your enclosing quote character must be escaped with a '\'.</p>
<pre><code>>>> b = 'Hello\'s'
>>> a = "Hello's"
>>> b = 'Hello\'s'
>>> c = 'Hello"s'
>>> d = "Hello\"s"
>>... | 0 | 2016-08-08T06:51:38Z | [
"python",
"string",
"syntax",
"escaping"
] |
Interaction with Python cmd module | 38,822,323 | <p>I have a program that uses <code>cmd</code> module and looks like this:</p>
<pre><code>import cmd
class Prog(cmd.Cmd):
prompt = '>>'
def do_reverse(self, line):
print line[::-1]
def do_exit(self, line):
return True
if __name__ == '__main__':
Prog().cmdloop()
</code></pre>... | 0 | 2016-08-08T06:13:00Z | 38,884,680 | <p>Finally found an answer. By default interpreter works in buffered mode sending data to stdout in chunks, in order to avoid that it should be running in unbuffered mode with <code>-u</code> command line argument:</p>
<pre><code>p = Popen(['python', '-u', 'prog.py'], stdin=PIPE, stdout=PIPE)
</code></pre>
| 0 | 2016-08-10T22:37:53Z | [
"python",
"windows",
"cmd",
"stdout",
"stdin"
] |
user uploaded image is not displaying | 38,822,342 | <p>Image uploaded by user is not displaying though i have not done wrong in template. Also i have defined MEDIA_URL and MEDIA_ROOT. What might be the reason for not getting image displayed?</p>
<p><strong>Code</strong> </p>
<pre><code> image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
</code>... | 0 | 2016-08-08T06:14:23Z | 38,830,873 | <p>It is working now after fresh restart of the server. So the above code and process of serving media files is correct.</p>
| 0 | 2016-08-08T13:45:38Z | [
"python",
"django",
"django-templates",
"django-1.10"
] |
slicing multiple arrays where their indices are not the same | 38,822,385 | <p>I have four time series signals that turns on at different times and later turns off at different times as well.
time = [(0,23),(5,15),(9,20),(12,25)]</p>
<p>For example, channel0 turned on at time 0 and off at 23sec. channel two turned on at time =5sec and turned off at 15.</p>
<p>I want to segment each array ac... | 0 | 2016-08-08T06:17:14Z | 38,822,627 | <p>First don't use upper case for variable name so <code>signals</code> and not <code>Signals</code>.</p>
<pre><code>all_signals = [[s[slice(max(0,lg-lt),max(0,ug-lt+1))] for (lg,ug) in grid] for (lt,ut),s in zip(time, signals)]
for i,s in enumerate(all_signals):
print "\nsignal",i
for g in s:
print g... | 1 | 2016-08-08T06:34:24Z | [
"python",
"numpy"
] |
conv2d_transpose is dependent on batch_size when making predictions | 38,822,411 | <p>I have a neural network currently implemented in tensorflow, but I am having a problem making predictions after training, because I have a conv2d_transpose operations, and the shapes of these ops are dependent on the batch size. I have a layer that requires output_shape as an argument:</p>
<pre><code>def deconvLaye... | 0 | 2016-08-08T06:19:38Z | 38,838,883 | <p>So I came across a solution based on the issues forum of tensorflow at <a href="https://github.com/tensorflow/tensorflow/issues/833" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/833</a>.</p>
<p>In my code</p>
<pre><code> conv4 = layers.deconvLayer(conv3['layer_output'],
... | 0 | 2016-08-08T21:35:56Z | [
"python",
"tensorflow",
"deep-learning"
] |
convert pandas dataframe to list of tuples and drop all pandas datatypes | 38,822,486 | <p>I need to convert a dataframe into a format that can be inserted into a sql table. </p>
<pre><code>data_tuples = [tuple(row) for row in df.values]
</code></pre>
<p>How do I remove all the non python datatypes from a pandas dataframe (including np ints and nans and NaTs)?</p>
| 1 | 2016-08-08T06:25:48Z | 38,822,831 | <p>if you want to do it efficiently, use corresponding pandas method - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">to_sql()</a>:</p>
<pre><code>from sqlalchemy import create_engine
# conn = create_engine('postgresql://user:password@host:port/dbname')
con... | 3 | 2016-08-08T06:49:12Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Python insert value to foreign key attribute (MYSQL) | 38,822,540 | <p>i created two table in MySQL database </p>
<p>Staff table:</p>
<pre><code>+----+-----------+-------------
| ID | NAME |
+----+-----------+-------------
| No data available in table |
+----+-----------+-------------
</code></pre>
<p>Qualification table:</p>
<pre><code>+----+----------... | 0 | 2016-08-08T06:29:38Z | 38,822,622 | <p>Why are you executing the <code>SELECT</code> statement. You already have the ID available. Pass it as such:</p>
<pre><code>con = pymysql.connect(host='localhost',port=3306,user='root',password='admin',db='mydb')
cursor = con.cursor()
cursor.execute(
"INSERT INTO Staff (ID,Name) VALUES (%d,%s)",
(1001,"MR T... | 0 | 2016-08-08T06:34:12Z | [
"python",
"mysql",
"database"
] |
Python insert value to foreign key attribute (MYSQL) | 38,822,540 | <p>i created two table in MySQL database </p>
<p>Staff table:</p>
<pre><code>+----+-----------+-------------
| ID | NAME |
+----+-----------+-------------
| No data available in table |
+----+-----------+-------------
</code></pre>
<p>Qualification table:</p>
<pre><code>+----+----------... | 0 | 2016-08-08T06:29:38Z | 38,822,682 | <p>2 ways :</p>
<p>You can try</p>
<pre><code>cursor.execute("INSERT INTO Staff (ID,Name)VALUES (%d,%s)",(1001,"MR Tan"))
cursor.execute("INSERT INTO Qualification VALUES (%d,%s,%s)",(2001,"Professor","select ID from Staff where ID=1001"))
</code></pre>
<p>or </p>
<pre><code>cursor.execute("INSERT INTO Staff (ID,Na... | 0 | 2016-08-08T06:38:42Z | [
"python",
"mysql",
"database"
] |
How to iterate through a list of tuple within tuple in python? | 38,822,546 | <p>Let's say I have a list like so: <code>[(1, (1,2)), (2, (23, -10)), (3, (4, 5))...]</code></p>
<p>I want to get (1,2), (23, -10), etc</p>
<p>edit: Thanks for help. I didn't know about list comprehension as I'm not too familiar with python</p>
| -5 | 2016-08-08T06:29:49Z | 38,822,644 | <p>Yes, you can iterate over all tuples and then take the second element:</p>
<pre><code>list = [(1, (1,2)), (2, (23, -10)), (3, (4, 5))]
for elem in list:
print(elem[1])
</code></pre>
<p>In each iteration elem value its <code>(1,(1,2)) -> (2,(23,-10))</code> -> ....
Then you take the second item of the tuple ... | -2 | 2016-08-08T06:35:38Z | [
"python"
] |
How to iterate through a list of tuple within tuple in python? | 38,822,546 | <p>Let's say I have a list like so: <code>[(1, (1,2)), (2, (23, -10)), (3, (4, 5))...]</code></p>
<p>I want to get (1,2), (23, -10), etc</p>
<p>edit: Thanks for help. I didn't know about list comprehension as I'm not too familiar with python</p>
| -5 | 2016-08-08T06:29:49Z | 38,822,734 | <p>Try Something like this:-</p>
<p>Here is List and get other list of tuples:-</p>
<pre><code>a = [(1, (1,2)), (2, (23, -10)), (3, (4, 5))...]
b = map(lambda item: item[1], a)
print b
</code></pre>
| -1 | 2016-08-08T06:42:47Z | [
"python"
] |
How can I use 2 submit buttons in a single form in HTML & Django? | 38,822,641 | <p>In this, only second button is working. If I delete the second button, then the first button is worked.I want to work both buttons.How can I work them?</p>
<p>HTML template
IInd_std.html</p>
<pre><code> <form method="get" action="#">
<table style="width:100%">
<tr>
<th>Slno&l... | 0 | 2016-08-08T06:35:21Z | 38,822,753 | <p>Try changing it to:</p>
<pre><code>request.GET['add20']:
</code></pre>
<p>and</p>
<pre><code>request.GET['add21']:
</code></pre>
<p>Also, you are re-initializing <code>my_dictionary</code> in your if statements.</p>
<p>Change it to:</p>
<pre><code>my_dictionary["u"] = u
</code></pre>
<p>and</p>
<pre><code>my... | 0 | 2016-08-08T06:44:38Z | [
"python",
"html",
"django"
] |
Django could not import settings after import a model in a python script | 38,822,725 | <p>After import one of my models in a python script, when I run the localhost server, I get this <strong>erro</strong>r, I have been reading, but all my tries were a fail:</p>
<pre><code>ubuntu@INN0095_VM2:~/env_Compass4D/Compass4D$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line... | 0 | 2016-08-08T06:42:13Z | 38,823,161 | <p>I confirm the problem was that I had manage.py, settings.py and wsgi.py in the same folder, then you can not write appName.settings in the path import conf, thanks guys.</p>
| 0 | 2016-08-08T07:08:55Z | [
"python",
"django",
"django-wsgi"
] |
Python re.search anomaly | 38,822,730 | <p>I have a routine that searches through a directory of files and extracts a customer number from the filename:</p>
<pre><code>import os
import re
suffix= '.csv'
# For each file in input folder, extract customer number
input_list = os.listdir(path_in)
for input_file in input_list:
fileInput = os.path.join(... | 0 | 2016-08-08T06:42:16Z | 38,840,479 | <p>@BrenBarn spotted the cause of the problem. The regex failed because there was a subdirectory in the directory who's name didn't match. I've solved it by introducing <code>try....except</code> </p>
<pre><code>import os
import re
suffix= '.png'
# For each file in input folder, extract customer number
input_list ... | 0 | 2016-08-09T00:56:12Z | [
"python",
"search",
"substring"
] |
Convert bytes to long in python | 38,822,736 | <p>Here is my C++ code:</p>
<pre><code> int r; // result of log_2(v) goes here
union { unsigned int u[2]; double d; } t; // temp
t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000;
t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = v;
t.d -= 4503599627370496.0;
r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] >> 2... | -1 | 2016-08-08T06:42:58Z | 38,879,187 | <p>It helps to have a complete example (lots of undefined values here), but this is closer to the intent. Note the use of <code>Union</code> and <code>c_int * 2</code>:</p>
<pre><code>class s(Union):
_fields_ = [("u", c_int * 2),
("d", c_double)]
t = s()
t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0... | 0 | 2016-08-10T16:43:55Z | [
"python",
"c",
"struct",
"ctypes",
"little-endian"
] |
SQLAlchemy raises QueuePool limit of size 10 overflow 10 reached, connection timed out after some time | 38,822,829 | <p>While using Flask-SQLAlchemy I get the error 'QueuePool limit of size 10 overflow 10 reached, connection timed out' consistently, after some time. I tried to increase connection pool size, but it only deferred the problem. </p>
<pre><code>def create_app(config_name):
app = Flask(__name__)
app.config.from_ob... | 1 | 2016-08-08T06:49:07Z | 38,955,433 | <p></p>
<p>I figured out the problem. The issue was sometimes database connection was going to lost state, which is causing pool size to be Exhausted after some interval.<br>
To fix the issue I made the MySQL server configuration change for query timeout and made it 1 second.<br>
After 1 second if the query didn't res... | 1 | 2016-08-15T12:50:08Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
Why does next() always display the same value? | 38,822,840 | <p>I was practicing the <code>yield</code> statement. I have written the following function in Python 2.7:</p>
<pre><code>>>> def mygen():
... i = 0
... j = 3
... for k in range(i, j):
... yield k
...
>>> mygen().next()
0
>>> mygen().next()
0
>>> mygen().next()
0... | 3 | 2016-08-08T06:49:37Z | 38,822,868 | <p>You are <em>recreating</em> the generator each time, so it starts from the beginning each time.</p>
<p>Create the generator <strong>once</strong>:</p>
<pre><code>gen = mygen()
gen.next()
gen.next()
gen.next()
</code></pre>
<p>Generator functions produce a new iterator every time you call them; that way you can pr... | 10 | 2016-08-08T06:51:13Z | [
"python",
"python-2.7",
"generator",
"yield"
] |
Why does next() always display the same value? | 38,822,840 | <p>I was practicing the <code>yield</code> statement. I have written the following function in Python 2.7:</p>
<pre><code>>>> def mygen():
... i = 0
... j = 3
... for k in range(i, j):
... yield k
...
>>> mygen().next()
0
>>> mygen().next()
0
>>> mygen().next()
0... | 3 | 2016-08-08T06:49:37Z | 38,823,621 | <p>A function definition containing a yield statement returns a generator. You have to apply the next function to that generator in stead of the function itself. To clarify, your function definition is equivalent to:</p>
<pre><code> def mygen():
i, j = 0, 3
return (k for k in range(i, j))
</code></... | 0 | 2016-08-08T07:36:34Z | [
"python",
"python-2.7",
"generator",
"yield"
] |
Sorting and Grouping Nested Lists Consists of Class Objects | 38,822,843 | <p>I have hundreds of text files that i need to parse according to the username and the date. I tried to put useful data in the text files in lists like that:</p>
<pre><code> [
['1234245@gmail.com', '34209809' '1434546354', '2016-07-18 00:20:58'],
['abcd@gmail.com', '234534345', '09402380',, '2016-07-1... | -1 | 2016-08-08T06:49:46Z | 38,822,892 | <p>You can probably just use the simple Python built-in sort.</p>
<pre><code>sorted_list = sorted(data, key=lambda user_info: (user_info[0], user_info[3]))
</code></pre>
<p>The lambda key tells Python how to sort the list (ascending). For each entry in <code>data</code>, <code>user_info</code> will be the list of 4 a... | 2 | 2016-08-08T06:52:38Z | [
"python",
"list",
"sorting",
"object",
"grouping"
] |
How to return my cursor automatically after an indentation in Python? | 38,822,876 | <p>any code editor knows where to indent in python since python uses <code>:</code> as its indent flag, but after completing a code block, we will want our cursor to go back in the last place it was, like this:
</p>
<pre><code>def test_func():
print("Here we have an auto indent")
# but how to
# return, withou... | 0 | 2016-08-08T06:51:32Z | 38,823,314 | <p>No, it is not possible for an IDE to know when your block is ending in all cases.</p>
<p>The are a few <em>exceptions</em> where it is reasonable to <em>guess</em> that you wanted to end the current indentation level. E.g. using <code>pass</code> to leave a block 'empty' where the Python grammar requires you to use... | 2 | 2016-08-08T07:17:43Z | [
"python",
"vim",
"syntax",
"editor",
"indentation"
] |
Return null inside the class | 38,823,086 | <p>I'm wondering why my code below return null, however print command return proper value, could anyone explain my that? </p>
<pre><code>class Newclass:
def __init__(self,portal):
config = configparser.ConfigParser()
config.read("config.ini")
self.connection_source=config.get(portal,'So... | 0 | 2016-08-08T07:05:03Z | 38,823,148 | <p>You are calling the function but doing nothing with its return value.</p>
<p>Try to actually fetch and print it:</p>
<pre><code>emp1 = Newclass('portalname')
value = emp1.getPortalSources()
print(value)
</code></pre>
<p>You may also want to catch that <code>configparser.NoOptionError</code> that waits to ha... | 2 | 2016-08-08T07:08:25Z | [
"python"
] |
Return null inside the class | 38,823,086 | <p>I'm wondering why my code below return null, however print command return proper value, could anyone explain my that? </p>
<pre><code>class Newclass:
def __init__(self,portal):
config = configparser.ConfigParser()
config.read("config.ini")
self.connection_source=config.get(portal,'So... | 0 | 2016-08-08T07:05:03Z | 38,823,786 | <pre><code>import configparser, os
class ConfigIni(dict, configparser.ConfigParser):
def __init__(self, file):
configparser.ConfigParser.__init__(self)
self.iniFile=file
if os.path.isfile(self.iniFile):
self.read(self.iniFile)
for section in self.sections():
... | 1 | 2016-08-08T07:47:16Z | [
"python"
] |
Python: Best way to frame a loop with 2 alternating tasks | 38,823,146 | <p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p>
<p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</cod... | 2 | 2016-08-08T07:08:18Z | 38,823,252 | <p>Check out enumeration:</p>
<pre><code>for n, item in enumerate(my_list):
if n % 2 == 0:
# do things for even-indexed items
else:
# do things for odd-indexed items
</code></pre>
| 1 | 2016-08-08T07:14:13Z | [
"python"
] |
Python: Best way to frame a loop with 2 alternating tasks | 38,823,146 | <p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p>
<p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</cod... | 2 | 2016-08-08T07:08:18Z | 38,823,256 | <p>You could use <a href="https://docs.python.org/3.4/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> and <a href="https://docs.python.org/3.4/reference/expressions.html#binary-arithmetic-operations" rel="nofollow">modulo</a> to alternate:</p>
<pre><code>li = ['a', 'b', 'c']
for idx, ch in ... | 2 | 2016-08-08T07:14:17Z | [
"python"
] |
Python: Best way to frame a loop with 2 alternating tasks | 38,823,146 | <p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p>
<p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</cod... | 2 | 2016-08-08T07:08:18Z | 38,823,257 | <p>You can handle using map and a apply function, each function must be in the same position as the value it needs to operate with.
functional approach</p>
<p>Example:</p>
<pre><code>>>> import operator
import functools
import itertools
def apply(f, e):
return f(e)
elems = range(10)
functs = itertools.cy... | 1 | 2016-08-08T07:14:20Z | [
"python"
] |
Python: Best way to frame a loop with 2 alternating tasks | 38,823,146 | <p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p>
<p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</cod... | 2 | 2016-08-08T07:08:18Z | 38,823,956 | <p>python comprehensions can be useful for things like this in a very simple way where in another language you have to write functions and control statements in python you can just do: </p>
<pre><code>new_list = [f2(list_item) for i, list_item in zip(range(len(old_list)), old_list) if i%2==0 else f1(list_item)]
</cod... | 1 | 2016-08-08T07:57:22Z | [
"python"
] |
spotipy auth workflow results in error=state_mismatch in browser | 38,823,180 | <p>I am attempting to run through the Spotify authentication workflow via <code>spotipy</code> and it's <code>prompt_for_user_token</code> utility. I am following the directions <a href="https://developer.spotify.com/web-api/tutorial/" rel="nofollow">here</a>, the official Spotify web API tutorial, verbatim from what I... | 0 | 2016-08-08T07:09:52Z | 38,840,369 | <p>I found a great and basic example of spotify oauth workflow via spotipy which doesn't depend on node or util.prompt_for_user_token <a href="http://stackoverflow.com/a/34973812/2403318">here</a> contributed by perelin.</p>
<p>In addition the spoti<strong>py</strong> documentation does not indicate which of several u... | 0 | 2016-08-09T00:34:08Z | [
"python",
"authentication",
"oauth-2.0",
"spotify",
"spotipy"
] |
How to remove part of the string after specific word in Python | 38,823,270 | <p>I get API-responses as a string which can be in two different formats:</p>
<p>1) <code>This is a message. <br><br>This message was created by Jimmy.</code> </p>
<p>2) </p>
<pre><code>This is a message.
Text can be in the new row.
This message was created by Jimmy.
</code></pre>
<p>I want to remove ... | -3 | 2016-08-08T07:15:19Z | 38,823,715 | <p>Please check this.
Added code to handle multiline strings.</p>
<pre><code>import re
data1 = "This is a message. <br><br>This message was created by Jimmy."
data2 = """
This is a message.
This message was created by Jimmy.
"""
print "First case..."
print data1
output1 = re.findall('(.*?)This message was... | 1 | 2016-08-08T07:42:14Z | [
"python"
] |
Copy nested dictionary to another dictionary with all the levels. | 38,823,327 | <p>For some third party APIs, there is a huge data that needs to be sent in the API parameters. And input data comes to our application in the CSV format. </p>
<p>I receive all the rows of the CSV containing around 120 columns, in a plane dict format by CSV DictReader. </p>
<pre><code>file_data_obj = csv.DictReader(o... | 0 | 2016-08-08T07:18:29Z | 38,823,542 | <p>You could use recursion:</p>
<pre><code>def update_nested_params(self, template, source):
result = {}
for key, value in template.items():
if key in source:
result[key] = source[key]
elif not isinstance(value, dict):
# assume the template value is a default
... | 1 | 2016-08-08T07:31:45Z | [
"python",
"csv",
"dictionary"
] |
How do I vectorize a conditional timedelta operation? | 38,823,331 | <p>I wanted to avoid the for loops in Python pandas, but I didn't make it due to lack of exposure. I wanted to derive a new column based on an existing column by adding some amount of information to it.</p>
<p>My Scenario:</p>
<pre><code>for each in data['days']:
if each<100000:
clsdate.append(datetime... | 0 | 2016-08-08T07:18:56Z | 38,823,361 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>Series.apply</code></a>: </p>
<pre><code>data['clsdate'] = data['days'].apply(lambda x: datetime.now() + relativedelta(days=x))
</code></pre>
| 0 | 2016-08-08T07:20:58Z | [
"python",
"loops",
"pandas"
] |
How do I vectorize a conditional timedelta operation? | 38,823,331 | <p>I wanted to avoid the for loops in Python pandas, but I didn't make it due to lack of exposure. I wanted to derive a new column based on an existing column by adding some amount of information to it.</p>
<p>My Scenario:</p>
<pre><code>for each in data['days']:
if each<100000:
clsdate.append(datetime... | 0 | 2016-08-08T07:18:56Z | 38,823,468 | <p>You can use pandas' datetime functions:</p>
<pre><code>df = pd.DataFrame()
df['days'] = [1, 3, 2, 4]
pd.to_datetime('now') + pd.to_timedelta(df['days'], unit='days')
Out:
0 2016-08-09 07:25:22
1 2016-08-11 07:25:22
2 2016-08-10 07:25:22
3 2016-08-12 07:25:22
Name: days, dtype: datetime64[ns]
</code></pre>
| 3 | 2016-08-08T07:27:35Z | [
"python",
"loops",
"pandas"
] |
Using py2exe packing python program with ply got strange error? | 38,823,400 | <p>I downloaded the <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>, and ran a simple test in <code>ply3.8/test/calclex.py</code></p>
<pre><code># -----------------------------------------------------------------------------
# calclex.py
# -------------------------------------------------------------------... | 0 | 2016-08-08T07:23:59Z | 38,836,056 | <p>Ply insists that its grammars be defined in real files, not virtualized filesystems. So it won't work with py2exe or pyinstaller or other such programmers which attempt to pack python source files into single archives. (See also <a href="http://stackoverflow.com/q/35589881">Pyinstaller and Ply IOError: source code n... | 0 | 2016-08-08T18:25:31Z | [
"python",
"py2exe",
"ply"
] |
Scrape 'deep' audio features using Spotipy python library | 38,823,403 | <p>For the past few days, I've been using the excellent <a href="http://spotipy.readthedocs.io/en/latest/" rel="nofollow">Spotipy</a> python library for the Spotify Web API. Having navigated my way to accessing the basic information, however (track/artist/album names, urls, uris, etc), I'm now trying to find some deepe... | 0 | 2016-08-08T07:24:13Z | 38,824,511 | <p>That link is not an enterprising service, it is part of the examples for the Echo nest parts of the Spotify Web API.</p>
<p><a href="https://developer.spotify.com/web-api/code-examples/#echo-nest-example-apps" rel="nofollow">https://developer.spotify.com/web-api/code-examples/#echo-nest-example-apps</a>
<a href="ht... | 0 | 2016-08-08T08:30:27Z | [
"python",
"api",
"spotify",
"bpm",
"spotipy"
] |
Django-DRF See all posts from friends | 38,823,485 | <p>I just started toying around with the Django Rest Framework, so I'm still not entirely sure what exactly is going on. But I have a user model, a friend model, and a post model, I also have my serializers and views in order. But, I can't figure out how to return all the posts from my user's friends. Any help would be... | 0 | 2016-08-08T07:28:55Z | 38,825,596 | <p>This may get you started,</p>
<p>So what you need to do first is get all the friends, you can do that by using</p>
<pre><code>friends = <user_objects>.Friendship_set.all()
</code></pre>
<p>Read more about is <a href="https://docs.djangoproject.com/ja/1.9/topics/db/queries/#related-objects" rel="nofollow">he... | 1 | 2016-08-08T09:28:13Z | [
"python",
"django",
"django-rest-framework"
] |
How to read data in specific column of XLSX file using python script | 38,823,609 | <p>I want to read the data given in 2nd and 3rd column from XLSX file.</p>
<pre><code>import xlrd
workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb")
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
cols = (sheet.row_values(row,1)) and (sheet.row_values(row,2))
print(cols)
</code></pre>
... | 1 | 2016-08-08T07:35:55Z | 38,824,150 | <p>This example read all the content of the excel sheet and puts it in a matrix (list of lists), then you can use the columns you need:</p>
<pre><code>import xlrd
workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb")
sheet = workbook.sheet_by_index(0)
rows = []
for i in range(sheet.nrows):
columns = []
for... | 0 | 2016-08-08T08:08:43Z | [
"python",
"python-2.7"
] |
How to read data in specific column of XLSX file using python script | 38,823,609 | <p>I want to read the data given in 2nd and 3rd column from XLSX file.</p>
<pre><code>import xlrd
workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb")
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
cols = (sheet.row_values(row,1)) and (sheet.row_values(row,2))
print(cols)
</code></pre>
... | 1 | 2016-08-08T07:35:55Z | 38,824,277 | <p>Try this</p>
<pre><code>import xlrd
workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb")
sheets = workbook.sheet_names()
required_data = []
for sheet_name in sheets:
sh = workbook.sheet_by_name(sheet_name)
for rownum in range(sh.nrows):
row_valaues = sh.row_values(rownum)
required_data.... | 0 | 2016-08-08T08:17:30Z | [
"python",
"python-2.7"
] |
youtube-dl package - Python, SyntaxError: invalid syntax | 38,823,965 | <p>I installed youtube-dl using pip <code>sudo pip install youtube-dl</code>and the install was successful.
When I run import youtube-dl from a python script, it says invalid syntax.</p>
<pre><code>python youtube_downloader.py
File "youtube_downloader.py", line 1
import youtube-dl
^
SyntaxError: invalid... | -1 | 2016-08-08T07:57:47Z | 38,824,002 | <p>You can't have the <code>-</code> sign in <code>import</code> statements, as the interpreter thinks you are trying to subtract.</p>
<p>Use an underscore instead:</p>
<pre><code>>> import youtube_dl
>>
</code></pre>
<p>This is also described in the <a href="https://github.com/rg3/youtube-dl/blob/master... | 1 | 2016-08-08T07:59:54Z | [
"python",
"python-2.7",
"pip",
"homebrew",
"youtube-dl"
] |
Getting variable from other class | 38,823,985 | <p>as totally beginner I need to ask you for some help.
I defined class Config which take from config.ini file some information and put them into variable.
Now I define class : Connection, which base of result from class Config. I was trying to do it many ways, but finally give up. Could anyone take a look ? </p>
<pr... | 0 | 2016-08-08T07:59:01Z | 38,824,033 | <p>You simply pass the config object into the <code>__init__</code> function</p>
<pre><code>class Config:
def __init__(self,system):
self.config = configparser.ConfigParser()
self.config.read("config.ini")
self.connection_source=self.config.get(system,'Source')
self.getConnection... | 1 | 2016-08-08T08:01:53Z | [
"python"
] |
regular expressions, the meaning of curly braces | 38,824,038 | <p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p>
<p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p>
<p>The code fragm... | 0 | 2016-08-08T08:02:15Z | 38,824,311 | <p>The provided regex is using square brackets incorrectly. Brackets denote a set of characters, and so a <code>{3}</code> after those characters indicates any combination of three of those characters will match. You can see the documentation <a href="https://docs.python.org/2/library/re.html#regular-expression-syntax"... | 2 | 2016-08-08T08:18:58Z | [
"python",
"regex"
] |
regular expressions, the meaning of curly braces | 38,824,038 | <p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p>
<p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p>
<p>The code fragm... | 0 | 2016-08-08T08:02:15Z | 38,824,320 | <p>What you have there is a bogus regular expression. It doesn't do quite what whoever wrote it meant it to do.</p>
<p>To demonstrate this, I fed it an invalid input:</p>
<pre><code>$ python2
...
>>> s = ("mov .* ptr \[(?P<dst>([(rax)|(rbx)|(rcx)|(rdx)|"
... "(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(... | 0 | 2016-08-08T08:19:41Z | [
"python",
"regex"
] |
regular expressions, the meaning of curly braces | 38,824,038 | <p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p>
<p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p>
<p>The code fragm... | 0 | 2016-08-08T08:02:15Z | 38,824,446 | <p>The others have answered it correctly, I just show you a way to visualize/test your regex patterns.</p>
<p><img src="https://www.debuggex.com/i/WOX4TAA8eqlEp69E.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/WOX4TAA8eqlEp69E" rel="nofollow">Debuggex Demo</a></p>
| 0 | 2016-08-08T08:27:08Z | [
"python",
"regex"
] |
Regular expression for class with whitestaces using Beautifulsoup | 38,824,121 | <p>I found that method BeautifulSoup.find() splits class attribute by whitespaces.
In that case I couldn't use regular expression as show in code below.
Could you somebody help me to get right way find all 'tree children' elements:</p>
<pre><code>import re
from bs4 import BeautifulSoup
r_html = "<div class='root'... | 1 | 2016-08-08T08:06:58Z | 38,825,064 | <p>There are a few different ways depending on the structure of the html, they are css classes so you could just use <code>class_=..</code> or a css selector using <em>.select</em>:</p>
<pre><code>In [3]: bs_tab.find_all('div', class_="tree")
Out[3]:
[<div class="tree children1">text children 1 </div>,
&... | 2 | 2016-08-08T09:00:22Z | [
"python",
"beautifulsoup"
] |
Print the consecutive 3 line at the pattern match | 38,824,144 | <p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p>
<p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting ..
I tried awk with getline but somehow i am missing to fit it ..</p>
<p>awk '/vm/... | 0 | 2016-08-08T08:08:24Z | 38,824,271 | <p>You were almost there: Just accumulate in a variable and print in the end:</p>
<pre><code>awk 'BEGIN{s="";} /vm/ {s = s $0 " "} END {print s}' log.txt
</code></pre>
<p>You can also use your exact construction and convert the newlines:</p>
<pre><code>awk '/vm/ {printf $0 " ";getline; print $0}' log.txt | tr "\n" "... | 2 | 2016-08-08T08:17:00Z | [
"python",
"awk",
"sed"
] |
Print the consecutive 3 line at the pattern match | 38,824,144 | <p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p>
<p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting ..
I tried awk with getline but somehow i am missing to fit it ..</p>
<p>awk '/vm/... | 0 | 2016-08-08T08:08:24Z | 38,825,607 | <pre><code>$ awk '/vm/ {printf "%s%s", $0, (++i%3?OFS:ORS)}' log.txt
[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0
[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0... | 1 | 2016-08-08T09:28:38Z | [
"python",
"awk",
"sed"
] |
Print the consecutive 3 line at the pattern match | 38,824,144 | <p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p>
<p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting ..
I tried awk with getline but somehow i am missing to fit it ..</p>
<p>awk '/vm/... | 0 | 2016-08-08T08:08:24Z | 38,830,029 | <p>Another answer using <code>sed</code> only</p>
<pre><code>/vm/{
H
x
s/\n/ /g
s/ \[kfg-ap.\] out: / /
x
blab
}
x
p
:lab
</code></pre>
<p>invoke like this (save above file as <code>filter.sed</code>):</p>
<pre><code>sed -n -f filter.sed text.txt
</code></pre>
<p>If <code>vm</code> is matched, then stores in the h... | 0 | 2016-08-08T13:06:57Z | [
"python",
"awk",
"sed"
] |
howto instantiate certain class from string in python project packed by pyinstaller? | 38,824,177 | <p>i am using getattr, but i cant make it working with pyinstaller</p>
<p>short summary:</p>
<ul>
<li>Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32</li>
<li>i have project, packed by pyinstaller to single file</li>
<li>i have external text file with scrip... | 0 | 2016-08-08T08:10:51Z | 38,931,490 | <p>"You are right. Simply using --hidden-import=Subs won't work. You have to use it with the -p DIR option and point to the folder that includes your modules. If that fails, you can also try to bundle the files as additional data. â Aug 8 at 14:31
"
i am marking this as answer, as i could successfuly instan.class by... | 0 | 2016-08-13T09:52:28Z | [
"python",
"pyinstaller"
] |
Considering Highest Peak Curve From Two Sets of Data Points | 38,824,201 | <p>I have two columns which would correspond to x and y-axis in which I will be eventually graphing that sets of data points to a curve like graph. <br></p>
<p>The problem is that based on the nature of the datapoints, when graphing it, I end up having two peaks however, I want to pick only the highest peak when graph... | 0 | 2016-08-08T08:12:55Z | 38,825,426 | <p>You can use <code>scipy</code> argrelextrema to get all the peaks, work out the maximum and then build up a mask array for the peak you want to plot. This will give you full control based on your data, using things like mincutoff to work out what determines a separate peak,</p>
<pre><code>import numpy as np
from sc... | 1 | 2016-08-08T09:19:52Z | [
"python",
"matplotlib",
"graphing"
] |
Iterate over nested keys in Python dict and break on first occurence | 38,824,205 | <p>I have a JSON dict like the following :</p>
<pre><code> "{
"a":1,
"b":{
"b1":False,
"b2":{"b21": 2, "b22":8}
},
"c": {
... | 0 | 2016-08-08T08:13:03Z | 38,824,326 | <p>You need to return from the <em>recursive</em> calls too, and use that to inform wether or not you are going to continue looping; your code ignores what the recursive <code>isb1True(value)</code> call returns.</p>
<p>You can use the <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code... | 4 | 2016-08-08T08:20:01Z | [
"python",
"dictionary",
"nested",
"key"
] |
django custom filters not working | 38,824,339 | <p>Here is my folders organization :</p>
<p><a href="http://i.stack.imgur.com/gmohP.png" rel="nofollow"><img src="http://i.stack.imgur.com/gmohP.png" alt="enter image description here"></a></p>
<p>core_extras.py content :</p>
<pre><code>from django.contrib.auth.models import Group
from django.conf import settings
f... | 0 | 2016-08-08T08:20:36Z | 38,824,538 | <p>I'm stupid.</p>
<p>I loaded <code>{% load i18n staticfiles core_extras %}</code> in a base html file which I extend then on child html files. The <code>get_develop_state</code> was working because I import it as a variable <code>DEVELOP</code> which is available on the child html files but not the filter <code>in_g... | 1 | 2016-08-08T08:31:53Z | [
"python",
"django"
] |
import css using 'static' template in Django | 38,824,544 | <p>I have been importing JS files into my template using:</p>
<pre><code> <script src="{% static 'inventory/js/panel.js' %}" type="text/javascript"></script>
</code></pre>
<p>while importin CSS using</p>
<pre><code> <link href="{{ STATIC_URL }}common/css/form.css" rel="stylesheet" type="text/css">... | 0 | 2016-08-08T08:32:18Z | 38,824,582 | <p>It's almost the same as your js:</p>
<pre><code>{% load staticfiles %}
<link href="{% static "css/base.css" %}" rel="stylesheet"/>
</code></pre>
| 1 | 2016-08-08T08:34:46Z | [
"javascript",
"python",
"html",
"css",
"django"
] |
BeautifulSoup, TypeError:'NoneType' object is not callable. from book: Web Scraping With Python | 38,824,579 | <p>This train from a book, Python Web Scraping With Python by Ryan Mitchell,in Chinese version p23.and I find any others are similar.who can tell me how fix it? thank you in advance.
I has posted picture. code as follow:</p>
<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = ... | 0 | 2016-08-08T08:34:35Z | 38,825,308 | <p>It is actually the <code>*findALL*</code> it should be lowercase <em>l's</em> i.e <code>findAll</code> or better to use <code>*find_all*</code> as <em>findAll</em> is deprecated.:</p>
<pre><code> images = bsObj.find_all("img",{"src":re.compile("\.\./img/gifts/img.*\.jpg")})
</code></pre>
<p>Which will give you:</p... | 1 | 2016-08-08T09:13:39Z | [
"python",
"beautifulsoup",
"nonetype"
] |
Automate the boring stuff with Python: Comma Code | 38,824,634 | <p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p>
<blockquote>
<p>takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted ... | 0 | 2016-08-08T08:37:42Z | 38,824,699 | <p>Use <code>str.join()</code> to join a sequence of strings with a delimiter. If you do so for all words <em>except</em> for the last, you can insert <code>' and '</code> there instead:</p>
<pre><code>def list_thing(words):
if len(words) == 1:
return words[0]
return '{}, and {}'.format(', '.join(words... | 3 | 2016-08-08T08:41:47Z | [
"python"
] |
Automate the boring stuff with Python: Comma Code | 38,824,634 | <p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p>
<blockquote>
<p>takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted ... | 0 | 2016-08-08T08:37:42Z | 38,824,761 | <p>Others have given great one-liner solutions, but a good way to improve your actual implementation - and fix the fact that it does not work when elements are repeated - is to use <code>enumerate</code> in the for loop to keep track of the index, rather than using <code>index</code> which always finds the <em>first</e... | 1 | 2016-08-08T08:44:32Z | [
"python"
] |
Automate the boring stuff with Python: Comma Code | 38,824,634 | <p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p>
<blockquote>
<p>takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted ... | 0 | 2016-08-08T08:37:42Z | 38,825,157 | <p>I tried this, hope this is what you are looking for :- </p>
<pre><code>spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
#creating a string then splitting it as list with two items, second being last word
new_string=', '.join(list).rsplit(',', 1)
#Using the same method used above to recre... | 2 | 2016-08-08T09:06:02Z | [
"python"
] |
Automate the boring stuff with Python: Comma Code | 38,824,634 | <p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p>
<blockquote>
<p>takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted ... | 0 | 2016-08-08T08:37:42Z | 38,826,787 | <p>Here's a solution that handles the <a href="https://en.wikipedia.org/wiki/Serial_comma" rel="nofollow">Oxford comma</a> properly. It also copes with an empty list, in which case it returns an empty string.</p>
<pre><code>def list_thing(seq):
return (' and '.join(seq) if len(seq) <= 2
else '{}, and {}... | 3 | 2016-08-08T10:25:14Z | [
"python"
] |
Get the content HTML of an API | 38,824,786 | <p>I'm tring to get the content of an API result in python.<br/>
This is an HTML template with an image inside.</p>
<p>I tried lot of method to get the content but it don't work everytime.</p>
<p><strong>The fuction</strong> :</p>
<pre><code>def screenshotlayer(self, access_key, secret_keyword, domain, args):
do... | 0 | 2016-08-08T08:45:36Z | 38,824,910 | <p>The api does not returns html, but a raw image file (default to png).</p>
<p>You need to see if the <code>status_code</code> was 200, and if so, simply save the result into a file.</p>
<pre><code>import requests
res = requests.get(
'http://api.screenshotlayer.com/api/capture',
params={
'access_key... | 3 | 2016-08-08T08:52:43Z | [
"python",
"scrapy",
"urllib"
] |
Python: How to catch inner exception of exception chain? | 38,824,798 | <p>Consider the simple example:</p>
<pre><code>def f():
try:
raise TypeError
except TypeError:
raise ValueError
f()
</code></pre>
<p>I want to catch <code>TypeError</code> object when <code>ValueError</code> is thrown after <code>f()</code> execution. Is it possible to do it?</p>
<p>If I exe... | 0 | 2016-08-08T08:46:12Z | 38,824,962 | <p>Python 3 has a beautiful syntactic enhancement on exceptions handling. Instead of plainly raising ValueError, you should raise it from a caught exception, i.e.:</p>
<pre><code>try:
raise TypeError('Something awful has happened')
except TypeError as e:
raise ValueError('There was a bad value') from e
</code>... | 6 | 2016-08-08T08:55:49Z | [
"python",
"python-3.x",
"exception-handling"
] |
Instead of printing, returning the value of whole the string instead | 38,825,039 | <p>Currently working on an assignment where I want to print stars as triangles, the code is currently looking like this (very basic, I know):</p>
<pre><code>def triangelbasupp(n,m):
for a in range(0,m):
print((n*" "),(m*"*"))
m=m-2
n=n+1
if m<=0:
break
</code></pre>
... | 1 | 2016-08-08T08:59:32Z | 38,825,141 | <p>Instead of printing, initialize an empty string and use the <a class='doc-link' href="http://stackoverflow.com/documentation/python/1019/string-formatting/14479/string-concatenation#t=201608080908078797832">string concatenation</a> operator to build the string:</p>
<pre><code>def triangelbasupp(n,m):
s = ""
... | 2 | 2016-08-08T09:04:21Z | [
"python"
] |
Instead of printing, returning the value of whole the string instead | 38,825,039 | <p>Currently working on an assignment where I want to print stars as triangles, the code is currently looking like this (very basic, I know):</p>
<pre><code>def triangelbasupp(n,m):
for a in range(0,m):
print((n*" "),(m*"*"))
m=m-2
n=n+1
if m<=0:
break
</code></pre>
... | 1 | 2016-08-08T08:59:32Z | 38,825,159 | <p>Collect the lines in a list, then <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> them with <code>\n</code> and return.</p>
<pre><code>def triangelbasupp(n,m):
lines = []
for a in range(0,m):
lines.append(n*" " + m*"*")
...
return "... | 2 | 2016-08-08T09:06:05Z | [
"python"
] |
how to write random numbers to file in python | 38,825,082 | <p>I would like to store 100 randomly drawn numbers in a file.
How can I write random numbers to a list, using a file?
How can I read a file?
How can I separate draw numbers</p>
<pre><code>import random
draw = []
while True:
numbers_lotto = random.randint(1,50)
draw.append(numbers_lotto)
if len(draw)... | -3 | 2016-08-08T09:01:15Z | 38,825,219 | <pre><code>import random
file_name = 'random_numbers.txt'
with open ('file_name', 'w') as a_file:
for i in range (100):
a_file.write ('{}\n'.format (random.random ()))
with open ('file_name', 'r') as a_file:
a_list = [float (word) for word in a_file.read () .split ()]
print (a_list)
</code></pre>
<... | 1 | 2016-08-08T09:09:29Z | [
"python",
"list",
"file"
] |
Python pandas remove rows where multiple conditions are not met | 38,825,087 | <p>Lets say I have a dataframe like this:</p>
<pre><code> id num
0 1 1
1 2 2
2 3 1
3 4 2
4 1 1
5 2 2
6 3 1
7 4 2
</code></pre>
<p>The above can be generated with this for testing purposes:</p>
<pre><code>test = pd.DataFrame({'id': np.array([1,2,3,4] * 2,dtype='int32'),
... | 1 | 2016-08-08T09:01:28Z | 38,825,127 | <p>If you change the boolean condition to be equality and invert the combined boolean conditions by enclosing both in additional parentheses then you get the desired behaviour:</p>
<pre><code>In [14]:
test = test[~((test['id'] == 1) & (test['num'] == 1))]
test
Out[14]:
id num
1 2 2
2 3 1
3 4 ... | 3 | 2016-08-08T09:03:56Z | [
"python",
"pandas",
"dataframe"
] |
Counting login attempts in Flask | 38,825,111 | <p>I'm a total newbie to web development, and here is what I've tried:</p>
<pre><code>@app.route('/login', methods=['GET', 'POST'])
def login():
attempt = 0
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for OpenID="%s", remember_me=%s' %
(form.openid.data, st... | 0 | 2016-08-08T09:03:02Z | 38,825,189 | <p>The web is stateless. Every time you press a submit button, your browser calls the URL associated with that form; that URL is routed to your <code>login()</code> handler function, which runs from the start. The function itself has no memory of previous calls (and nor would you want it to, otherwise all users of your... | 4 | 2016-08-08T09:08:06Z | [
"python",
"flask",
"flask-wtforms"
] |
Optimal Directed Dijkstra search in Python | 38,825,253 | <p>I've played around writing my own heap and trying out the directed Dijkstra's algorithm using a heap to store the distances. </p>
<p>I've cross-checked the answers with Bellman-Ford (and also on paper) so I'm confident it runs correctly, however it seems to be too slow for my liking. I've also made my own Graph cla... | 1 | 2016-08-08T09:11:06Z | 38,840,803 | <blockquote>
<p>Is this a reasonable time to expect with python?</p>
</blockquote>
<p>Unable to answer this without knowing your system specifications. Try comparing against a pre-built data structure e.g. <a href="https://docs.python.org/2/library/heapq.html" rel="nofollow">https://docs.python.org/2/library/heapq.h... | 0 | 2016-08-09T01:44:12Z | [
"python",
"algorithm",
"performance",
"dijkstra",
"conventions"
] |
Django model update on fetch | 38,825,430 | <p>My model has a field that should change if it's within a date range.</p>
<p>It would look like this:</p>
<pre><code>class Election(models.Model)
start_date = models.DateTimeField(verbose_name = 'Start Date')
end_date = models.DateTimeField(verbose_name = 'End date')
active = models.BooleanField(default... | 1 | 2016-08-08T09:20:24Z | 38,826,669 | <p>You can write a custom manager for the model. While you can set the active attribute for the instances in the query itself, it doesn't seem correct from a design point of view(A get method shouldn't mutate the data it is querying). It makes sense to have an active attribute as you may want to invalidate a certain in... | 0 | 2016-08-08T10:19:00Z | [
"python",
"django"
] |
Django model update on fetch | 38,825,430 | <p>My model has a field that should change if it's within a date range.</p>
<p>It would look like this:</p>
<pre><code>class Election(models.Model)
start_date = models.DateTimeField(verbose_name = 'Start Date')
end_date = models.DateTimeField(verbose_name = 'End date')
active = models.BooleanField(default... | 1 | 2016-08-08T09:20:24Z | 38,834,349 | <p>The best method would be not to have the <code>active</code> field at all in your model. The main reason is that when a value can be generated from a simple calculation, it should not be stored in the database. The second reason is that BooleanField cannot be effectively indexed and queries involving this field will... | 1 | 2016-08-08T16:33:54Z | [
"python",
"django"
] |
Odd character popping up when writing to a file | 38,825,492 | <p>New to python. I'm testing out files and I'm trying to get a number (taken as raw input) to be written to a file. Then I want a function I've made to take that number as it's input parameter and perform an equation with it.</p>
<p>For some reason though, when writing to the file a strange character pops up. When I ... | 0 | 2016-08-08T09:23:19Z | 38,826,048 | <p>You need to reset the file pointer back to the beginning.
You can check the current position of the file pointer with the tell() function.</p>
<pre><code>with open('in_test.txt','w+') as inFile_test:
inFile_test.write(Input)
print inFile_test.tell()
inFile_test.seek(0) # re-position the file pointer to ... | 0 | 2016-08-08T09:49:46Z | [
"python",
"python-2.7",
"file",
"character",
"file-writing"
] |
Run python script in VB.net on button click | 38,825,514 | <p>I want to run a Python script in cmd when a button is clicked in VB.Net.
Do you need to call the Python script in a batch file? Or can you do it directly in VB?</p>
<p>I tried this</p>
<pre><code>Dim ps As New ProcessStartInfo("cmd.exe")
ps.Arguments = "C:\yourbatfile.bat"
Process.Start(ps)
</code></pre>
... | 3 | 2016-08-08T09:24:28Z | 38,826,342 | <pre><code>Dim psi = New ProcessStartInfo("c:\python27\python.exe", "myPythonScript.py")
Dim proc = Process.Start(psi)
proc.WaitForExit()
If proc.ExitCode <> 0 then throw new Exception(" Script Failed")
</code></pre>
| 2 | 2016-08-08T10:03:38Z | [
"python",
"vb.net",
"cmd"
] |
Jupyter keyboard shortcut for running a specific cell | 38,825,528 | <p>In my workflow with Jupyter notebook, I have a cell like:</p>
<pre><code>%run myscript.py
</code></pre>
<p>Which loads the latest version of a script with functions I'm using. I am constantly updating this script and using its function in my notebook. Therefore, I find myself constantly going back to the first cel... | 2 | 2016-08-08T09:24:51Z | 38,828,414 | <p>You can click "Ctrl + Enter" to run only the chosen cell no matter it is "edit mode" or "command mode".</p>
<p>If you want to know more available commands, just input <code>Esc</code> to change you current mode to "command mode" and input "h" to show the Keyboard shortcuts modal.</p>
| 2 | 2016-08-08T11:46:41Z | [
"python",
"keyboard-shortcuts",
"jupyter",
"jupyter-notebook"
] |
how can i call mutiple files(bash files) from subprocess.call in python | 38,825,530 | <p>#i am trying to run all the bash scripts in plugin folder </p>
<pre><code>import sys,os,subprocess
folder_path=os.listdir(os.path.join(os.path.dirname(__file__),'plugins'))
sys.path.append(os.path.join(os.path.dirname(__file__),'plugins'))
for file in folder_path:
if file == '~':
con... | 0 | 2016-08-08T09:24:53Z | 38,825,600 | <p>You'll need to actually insert the <code>file</code> variable into the subprocess call string:</p>
<pre><code>subprocess.call(['./plugins/%s what' % file],shell=True,executable='/bin/bash')
</code></pre>
| 1 | 2016-08-08T09:28:18Z | [
"python",
"bash",
"subprocess"
] |
time in strings format: python | 38,825,562 | <p>I am using a function to bring my date consistent in a column, it goes like this</p>
<pre><code>from dateutil.parser import parse
def dateconv1(x):
c = parse(x)
return c
</code></pre>
<p>so if i will use it as, it works fine </p>
<pre><code>In[15]:dateconv1("1 / 22 / 2016 15:03")
Out[15]:datetime.datetime(... | 0 | 2016-08-08T09:26:30Z | 38,825,656 | <p>What you have is not a valid syntax for defining a Python variable. You should wrap with <code>''</code> or <code>""</code> to make it a string:</p>
<pre><code>a = "1 / 22 / 2016 15:03"
dateconv1(a)
</code></pre>
| 0 | 2016-08-08T09:31:38Z | [
"python",
"string",
"datetime",
"pandas",
"dataframe"
] |
time in strings format: python | 38,825,562 | <p>I am using a function to bring my date consistent in a column, it goes like this</p>
<pre><code>from dateutil.parser import parse
def dateconv1(x):
c = parse(x)
return c
</code></pre>
<p>so if i will use it as, it works fine </p>
<pre><code>In[15]:dateconv1("1 / 22 / 2016 15:03")
Out[15]:datetime.datetime(... | 0 | 2016-08-08T09:26:30Z | 38,826,094 | <p>assuming that <a href="http://stackoverflow.com/questions/38825562/time-in-strings-format-python/38826094#comment65017630_38825656">you are talking about pandas dataset</a>, you can use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> met... | 1 | 2016-08-08T09:52:26Z | [
"python",
"string",
"datetime",
"pandas",
"dataframe"
] |
can't put text to .txt file using python | 38,825,660 | <p>This is flow what i want in my program:<br>
- Read latest data in text file<br>
- add up latest data with specific data what i want<br>
- write the sum into text file in starts at the beginning of the file<br><br></p>
<p>I've got what I want to make but there is an error. What should I do?<br>
Here's my python code... | -1 | 2016-08-08T09:31:43Z | 38,825,813 | <p>Your code needs a fix at <code>f.write</code>, which takes a string as parameter and not an integer:</p>
<pre><code>f.write(str(data) + '\n')
# |<- cast integer to string
# |<- add new line character
</code></pre>
| 0 | 2016-08-08T09:39:17Z | [
"python",
"text-files",
"python-2.x"
] |
Convert measurement from String to Int or Float | 38,825,669 | <p>I have the string</p>
<pre><code>var = '7 msecs'
#var = int(var)
#var = float(var)
</code></pre>
<p>And I want to convert that to an integer (7), or float (7.0).
This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p>
<p>How can I do this in Python?... | -2 | 2016-08-08T09:32:14Z | 38,825,820 | <p>If <code>var = '7 msecs'</code></p>
<p>By <strong>filter</strong>:</p>
<pre><code>int(filter(str.isdigit, var))
</code></pre>
<p>By <strong>Regex</strong>:</p>
<pre><code>import re
p = re.compile(ur'\d')
re.search(p, var)
</code></pre>
<p>Or By <strong>join</strong>:</p>
<pre><code>s = ''.join(x fo... | -1 | 2016-08-08T09:39:32Z | [
"python",
"string",
"int",
"measurement"
] |
Convert measurement from String to Int or Float | 38,825,669 | <p>I have the string</p>
<pre><code>var = '7 msecs'
#var = int(var)
#var = float(var)
</code></pre>
<p>And I want to convert that to an integer (7), or float (7.0).
This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p>
<p>How can I do this in Python?... | -2 | 2016-08-08T09:32:14Z | 38,825,885 | <p>This is already answered here: <a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a></p>
<p>You could use a regular expression to extract all numbers from a string:</p>
<pre><code>>>> import re
>>> s = "7 msecs"
>>... | -1 | 2016-08-08T09:42:04Z | [
"python",
"string",
"int",
"measurement"
] |
Convert measurement from String to Int or Float | 38,825,669 | <p>I have the string</p>
<pre><code>var = '7 msecs'
#var = int(var)
#var = float(var)
</code></pre>
<p>And I want to convert that to an integer (7), or float (7.0).
This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p>
<p>How can I do this in Python?... | -2 | 2016-08-08T09:32:14Z | 38,825,987 | <p>If you want to avoid importing regex, you can try using <a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="nofollow"><code>isdigit()</code></a>. But for what it's worth, I'd prefer <code>int(var.split()[0])</code> to this:</p>
<pre><code>var = '7 msecs'
numeric_end = 0
for i in xrange(len(va... | -1 | 2016-08-08T09:46:49Z | [
"python",
"string",
"int",
"measurement"
] |
Convert measurement from String to Int or Float | 38,825,669 | <p>I have the string</p>
<pre><code>var = '7 msecs'
#var = int(var)
#var = float(var)
</code></pre>
<p>And I want to convert that to an integer (7), or float (7.0).
This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p>
<p>How can I do this in Python?... | -2 | 2016-08-08T09:32:14Z | 38,826,667 | <p>If you have white space, use <code>split</code>:</p>
<pre><code>>>> s = "123 msecs2"
>>> int(s.split()[0])
123
</code></pre>
<p>If you want to take the numbers from the start of a string only without white space (or using regex), try this:</p>
<pre><code>>>> s = "123msecs2"
>>>... | 1 | 2016-08-08T10:18:58Z | [
"python",
"string",
"int",
"measurement"
] |
best match algorithm in python | 38,825,712 | <p>What should be optimal implementation for best match in python.</p>
<p>I have a txt file which has some country codes mapping e.g.</p>
<h1>CODES NAME</h1>
<p>123 ABC</p>
<p>1234 DEF</p>
<p>1235 GHI</p>
<p>124 JKL</p>
<p>1241 MNO</p>
<p>This txt file is big(13500 records) I'm just putting some... | -3 | 2016-08-08T09:35:11Z | 38,834,124 | <p>Dictionaries are the easiest way to implement this. See below solution:</p>
<ol>
<li>Convert</li>
</ol>
<p>123 ABC</p>
<p>1234 DEF</p>
<p>1235 GHI</p>
<p>124 JKL</p>
<p>1241 MNO</p>
<p>to {1241: 'MNO', 1234: 'DEF', 123: 'ABC', 124: 'JKL', 1235: 'GHI'}</p>
<ol start="2">
<li>Read CDR file with country codes a... | -1 | 2016-08-08T16:20:48Z | [
"python",
"algorithm",
"search"
] |
Checking time for executing if statement | 38,825,824 | <p>I'm practising Python and I want to write a program that checks current time and see if it matches 2:12 pm and says: <code>its lunch time</code> So first I figured out using <code>import time</code> module, but I don't know how?</p>
<p>My problem is I don't know how to use time module for that. Or I'm using right s... | -3 | 2016-08-08T09:39:43Z | 38,825,941 | <p>I suggest the datetime module, which is more practicale in this case (as polku suggested). You will then directly access only hour and minute to check if it is lunch time.</p>
<p>Further information can be found here:
<a href="http://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-... | 1 | 2016-08-08T09:45:11Z | [
"python"
] |
Checking time for executing if statement | 38,825,824 | <p>I'm practising Python and I want to write a program that checks current time and see if it matches 2:12 pm and says: <code>its lunch time</code> So first I figured out using <code>import time</code> module, but I don't know how?</p>
<p>My problem is I don't know how to use time module for that. Or I'm using right s... | -3 | 2016-08-08T09:39:43Z | 38,826,164 | <pre><code>import datetime as da
lunch = "02:12 PM"
now = da.datetime.now().strftime("%I:%M %p")
if now == lunch:
print("lunch time")
else:
print("not lunch time")
</code></pre>
| -2 | 2016-08-08T09:56:04Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.