question_id
int64
502
42.8M
parent_answer_post_id
int64
595
42.8M
prob
float64
0
0.87
snippet
stringlengths
0
12.1k
intent
stringlengths
11
198
id
stringlengths
9
20
19,777,751
19,791,830
0.000697
foo foo.dtypes
pandas increment cell value of dataframe with mixed column types
19777751_19791830_13
2,063,923
2,064,078
0.000697
def statics_wrapper(request, **dict): from django.views import static return static.serve(request, dict['path'], document_root=os.path.join( settings.BASE_DIR, 'apps', dict['app'], 'static'), show_indexes=True)
How should Django Apps bundle static media?
2063923_2064078_9
8,568,233
8,568,655
0.000697
import decimal def display(x): digits = 15
print float to n decimal places including trailing 0's
8568233_8568655_12
36,942,233
36,944,716
0.000697
from pyspark.ml import Pipeline from pyspark.ml.feature import StringIndexer indexers = [StringIndexer(inputCol=column, outputCol=column + '_index').fit (df) for column in list(set(df.columns) - set(['date']))] pipeline = Pipeline(stages=indexers)
Apply StringIndexer to several columns in a PySpark Dataframe
36942233_36944716_18
4,743,035
4,743,069
0.000695
""" >>> least_common_values([1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4], 2) [(1, 2), (2, 4)] """
Python 3.1 - Obtaining the least common element in array
4743035_4743069_7
22,213,298
22,213,400
0.000695
data = robjects.r(""" set.seed(1) x <- runif(5) """)
Creating same random number sequence in Python, NumPy and R
22213298_22213400_13
24,187,248
24,187,292
0.000695
420 420
Python 2to3 tool adds a vowel to my integer
24187248_24187292_1
6,720,121
15,025,409
0.000695
ids_list = list(ids) import json
serializing result of a queryset with json raises error:
6720121_15025409_8
11,096,720
11,096,811
0.000693
import re Variable = ( "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better." )
Replace a string located between
11096720_11096811_7
36,942,233
36,944,716
0.000693
from pyspark.ml import Pipeline from pyspark.ml.feature import StringIndexer indexers = [StringIndexer(inputCol=column, outputCol=column + '_index').fit (df) for column in list(set(df.columns) - set(['date']))]
Apply StringIndexer to several columns in a PySpark Dataframe
36942233_36944716_19
27,301,434
29,272,312
0.000693
END
Read stdin from inlined python in bash
27301434_29272312_5
7,974,902
7,974,981
0.000693
ls
Deploying existing Django app on Heroku
7974902_7974981_0
35,721,503
40,512,757
0.000692
from gensim.models.word2vec import LineSentence np.savetxt('train_data.txt', arr, delimiter=' ', fmt='%s')
Gensim word2vec on predefined dictionary and word-indices data
35721503_40512757_12
22,213,298
22,213,400
0.000692
import rpy2.robjects as robjects data = robjects.r(""" set.seed(1) x <- runif(5) """) print(np.array(data))
Creating same random number sequence in Python, NumPy and R
22213298_22213400_11
34,103,119
40,616,976
0.000691
__requires__ = 'pip==6.1.1' import sys from pkg_resources import load_entry_point
Upgrade pip in Amazon Linux
34103119_40616976_14
31,111,258
31,112,779
0.000691
import itertools def replace(s1, s2, l): lslice = [slice(0, s1.start), s2, slice(s1.stop, s2.start), s1, slice( s2.stop, len(l))]
Swapping two sublists in a list
31111258_31112779_7
14,469,685
14,505,791
0.00069
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell shell = TerminalInteractiveShell(user_ns=namespace)
Google App Engine Local (Development) IPython Shell
14469685_14505791_11
5,697,479
5,705,865
0.00069
ACTIVE_TAG = _ACTIVE_TAG
How can a #defined C value be exposed to Python in a Cython module?
5697479_5705865_19
40,690,598
42,750,563
0.000689
import os
Can Keras with Tensorflow backend be forced to use CPU or GPU at will?
40690598_42750563_5
47,701
550,795
0.000689
gdb > bt
Is there a way to attach a debugger to a multi-threaded Python process?
47701_550795_2
11,615,041
11,615,157
0.000689
nf
How to find match items from two lists?
11615041_11615157_2
10,622,268
10,622,842
0.000688
a = 5 import tst
Accessing variables from IPython interactive namespace in a script
10622268_10622842_10
23,981,601
36,175,424
0.000688
from IPython.core.display import display, HTML output = df.to_html(formatters={'var1': '{:,.2f}'.format, 'var2': '{:,.2f}' .format, 'var3': '{:,.2%}'.format})
Format certain floating dataframe columns into percentage in pandas
23981601_36175424_8
6,018,214
6,019,262
0.000688
ts_column VALUES
How to insert current_timestamp into Postgres via python
6018214_6019262_5
4,846,891
15,375,897
0.000687
for line in tr(tail('-f', 'test.log', _piped=True), '[:upper:]', '[:lower:]', _iter=True): pass
Python piping output between two subprocesses
4846891_15375897_2
14,441,412
33,168,066
0.000687
from configobj import ConfigObj cfg = ConfigObj('/home/.aws/config') access_key_id = cfg['aws_access_key_id']
A configuration file that can be read by python and shell
14441412_33168066_9
16,328,040
17,948,626
0.000687
from amazon.api import AmazonAPI amazon = AmazonAPI(ACCESS_KEY, SECRET, ASSOC) results = amazon.search(Keywords='book name', SearchIndex='Books') for item in results: pass
Searching for books with the Amazon Product Advertising API - Python
16328040_17948626_12
5,760,668
6,584,120
0.000687
t = timeit.Timer( 'c=b.view(np.ndarray)[~b.mask[:,0]]; np.apply_along_axis(test, 1, c)', 'from __main__ import test, b, ma, np') print(round(t.timeit(100), 6))
Python/Numpy - Masked Arrays are Very Slow
5760668_6584120_19
5,283,649
5,284,038
0.000687
from scipy.interpolate import spline xnew = np.linspace(T.min(), T.max(), 300) power_smooth = spline(T, power, xnew) plt.plot(xnew, power_smooth)
Plot smooth line with PyPlot
5283649_5284038_13
21,975,666
22,055,820
0.000687
from platform import node if node() in ['dev1', 'dev2']: from local import * elif node() in ['prod1', 'prod2']: from production import *
Active Django settings file from Celery worker
21975666_22055820_17
7,390,170
7,399,453
0.000687
import croniter import datetime now = datetime.datetime.now() cron = croniter.croniter('45 17 */2 * *', now)
Parsing crontab-style lines
7390170_7399453_19
2,499,746
2,499,903
0.000687
Next
Extracting columns from text file using Perl one-liner: similar to Unix cut
2499746_2499903_6
11,774,925
26,897,450
0.000686
from crontab import CronTab cron = CronTab()
How to run a python file using cron jobs
11774925_26897450_9
34,802,316
34,802,317
0.000686
def _force_https(): if not app.debug: from flask import _request_ctx_stack if _request_ctx_stack is not None: reqctx = _request_ctx_stack.top
Make Flask's url_for use the 'https' scheme in an AWS load balancer without messing with SSLify
34802316_34802317_16
18,776,745
18,776,917
0.000686
MarkupSafe == 0.18
Gunicorn with Flask using wrong Python
18776745_18776917_4
23,703,870
23,704,655
0.000686
from Selenium2Library import Selenium2Library
Pass existing Webdriver object to custom Python library for Robot Framework
23703870_23704655_17
22,947,181
23,085,282
0.000686
import sys def commandline_arg(bytestring): pass
Don't argparse read unicode from commandline?
22947181_23085282_12
20,493,932
20,563,453
0.000685
notAFixedPoint = true pathsToNode.AddMany(newPathsToNode)
Solving a graph issue with Python
20493932_20563453_3
12,556,163
18,394,030
0.000685
import org.openqa.selenium.remote.RemoteWebDriver import org.openqa.selenium.support.events.EventFiringWebDriver
Get browser version using selenium webdriver
12556163_18394030_9
4,843,493
5,082,394
0.000684
pull_sources gen_vim_config
Any pointers on using Ropevim? Is it a usable library?
4843493_5082394_7
10,540,823
10,910,530
0.000684
import os import glob
Buildout-aware Python autocompletion for Sublime Text
10540823_10910530_9
28,678,438
28,678,554
0.000684
who a
How do I inspect one specific object in IPython
28678438_28678554_4
6,091,784
6,091,840
0.000683
from tipfy import RequestHandler, Response from tipfy.ext.auth import AppEngineAuthMixin, user_required
How do I secure REST calls I am making in-app?
6091784_6091840_7
15,382,807
30,091,395
0.000682
bars
How to make ordered dictionary from list of lists?
15382807_30091395_10
35,491,426
35,491,719
0.000682
regions = mlab.contiguous_regions(ser_orig == manual_mode) for i, (start, end) in enumerate(regions): ser_orig[start:end] = new_manual_mode_text.format(i) ser_orig
Finding contiguous, non-unique slices in Pandas series without iterating
35491426_35491719_9
13,567,089
13,567,150
0.000682
from timeit import timeit timeit('factarr*cplxarr.real+(1j)*cplxarr.imag', setup= 'from __main__ import factarr,cplxarr')
Scale the real part of complex numpy array
13567089_13567150_16
28,397,473
28,397,561
0.000682
import time max_execution_time = 10000000 start_time = time.clock()
Stop Sublime Text from executing infinite loop
28397473_28397561_18
9,402,324
9,538,781
0.000681
import datetime now = datetime.datetime.now(created_at) five_minutes_ago = now - datetime.timedelta(minutes=5)
How to minimize datastore writes initiated by the mapreduce library?
9402324_9538781_14
7,249,488
7,254,337
0.000681
import_line = 'from %s import (%%s)' % module_name length = len(import_line) - 3 print(import_line % (',\n' + length * ' ').join([a for a in dir(module) if not re.match('__.*[^_]{2}', a)]))
Tool to help eliminate wildcard imports
7249488_7254337_11
16,294,819
16,298,328
0.000681
Flask, Django >= 1.3,
How to check if my Python has all required packages?
16294819_16298328_12
27,790,415
41,891,285
0.00068
import bs4 def bs_parse(html): pass
Set lxml as default BeautifulSoup parser
27790415_41891285_8
5,207,987
15,373,074
0.00068
nums = [1, 18]
Python: Zip dict with keys
5207987_15373074_11
2,860,563
20,708,090
0.00068
from Chessnut import Game chessgame = Game(fen= 'rnbq1rk1/ppppp1bp/5np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R b KQ - 4 6') print(chessgame) print(chessgame.get_moves())
python: Chess moves validation
2860563_20708090_18
2,764,055
2,765,556
0.000679
one two three four
How to pdb Python code with input?
2764055_2765556_12
30,405,413
30,405,634
0.000679
t = """date Count 6/30/2010 525 7/30/2010 136 8/31/2010 125 9/30/2010 84 10/29/2010 4469"""
python pandas extract year from datetime --- df['year'] = df['date'].year is not working
30405413_30405634_15
3,728,017
3,728,064
0.000679
import numpy a = [2.3, 1.23, 3.4, 0.4]
Sorting while preserving order in python
3728017_3728064_9
15,670,505
15,761,249
0.000678
py - backward - clause py - copy - clause
Comparison of Python modes for Emacs
15670505_15761249_11
28,366,550
28,449,006
0.000677
selectNodeVersion
Custom Deployment to Azure Websites
28366550_28449006_1
3,049,651
3,049,700
0.000677
cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), Py_EQ) return cmp
Specifics of List Membership
3049651_3049700_3
20,774,745
21,539,806
0.000676
this.processor = processor
How to get client's IP in a python thrift server
20774745_21539806_1
29,631,504
29,631,641
0.000676
s1 = """ import numpy as np a=np.random.randint(0,200,100) b1=np.random.randint(0,100,50) np.intersect1d(b1,a) """ s2 = """ import numpy as np a=np.random.randint(0,200,100) b1=np.random.randint(0,100,50) a[np.in1d(a, b1)] """
Return values from array based on indices of common values in two other arrays
29631504_29631641_15
40,079,728
40,082,910
0.000676
import heapq
Get models ordered by an attribute that belongs to its OneToOne model
40079728_40082910_2
26,870,303
26,876,001
0.000676
end end end
Find out largest string value size for keys in Redis database
26870303_26876001_5
8,512,842
8,716,502
0.000676
from memcached_stats import MemcachedStats mem = MemcachedStats()
How do I check the content of a Django cache with Python memcached?
8512842_8716502_17
22,610,896
22,927,489
0.000676
from sortedcontainers import SortedDict sorted_dict = SortedDict(a=1, b=2, c=2, d=1, e=3)
Python select ith element in OrderedDict
22610896_22927489_5
6,408,886
6,409,798
0.000675
print(constant.CLIENT_CONNECTED) print(constant.GET_SERVER_QUEUE) print(constant.GET_SERVER_QUEUE)
Python constants declaration
6408886_6409798_18
42,448,265
42,448,358
0.000675
list_text = """-347 a negative number -100 another negative number -25 and again, a negative number 17 some text 25 foo bar 100 two same texts 100 two same texts (almost) 350 a positive number"""
Alphanumeric sorting in Python and negative numbers
42448265_42448358_9
39,646,760
39,646,997
0.000674
import outside_code import functions for name in getattr(functions, '__all__', (n for n in vars(functions) if not n[0] == '_')): pass
Modules and variable scopes
39646760_39646997_13
7,636,984
36,651,981
0.000674
from asciimatics.screen import Screen def demo(screen): screen.print_at('+' * screen.width, 0, 0) screen.refresh()
Linux Terminal Display and Python
7636984_36651981_15
14,588,098
14,590,233
0.000674
from docopt import docopt from schema import Schema, Use, Or, SchemaError if __name__ == '__main__': pass
docopt + schema validation
14588098_14590233_19
23,650,544
23,651,042
0.000674
from flaskext.uploads import UploadSet, configure_uploads app = Flask(__name__) app.config['UPLOADED_CSVFILES_DEST'] = '/var/uploads' csvfiles = UploadSet('csvfiles', ('csv',))
RuntimeError: cannot access configuration outside request
23650544_23651042_15
22,353,369
22,356,735
0.000674
sh
pandas: extract or split char from number string
22353369_22356735_8
3,333,550
25,235,213
0.000673
directories = [self._root.template_path], imports = ['from utils.view import handle_unicode'],
how to deal with unicode in mako?
3333550_25235213_15
16,994,174
31,764,294
0.000673
from werkzeug.local import LocalProxy from flask import current_app logger = LocalProxy(lambda : current_app.logger) from core import logger @mod.route('/') def index(): pass
In Flask: How to access app Logger within Blueprint
16994174_31764294_17
19,569,701
19,707,600
0.000673
from twisted.web import client d = client.getPage(url=context.client.location(), postdata=str(context. envelope), method='POST', headers=context.client.headers()) d.addCallback(context.succeeded) from pprint import pprint d.addCallback(pprint)
Benefits of twisted-suds - Async way of using python suds soap lib
19569701_19707600_16
14,009,148
14,046,303
0.000673
from PIL.ExifTags import TAGS img = Image.open('test.jpg')
Exif reading library
14009148_14046303_12
8,512,842
8,716,502
0.000672
from memcached_stats import MemcachedStats mem = MemcachedStats() list(mem.keys()) key = list(mem.keys())[0]
How do I check the content of a Django cache with Python memcached?
8512842_8716502_19
7,346,434
10,603,830
0.000672
md5Hash = md5.new somedata = 'foobar'
python subprocess read stdout as it executes
7346434_10603830_8
2,813,227
2,813,384
0.000672
import inspect def pv(name): record = inspect.getouterframes(inspect.currentframe())[1] frame = record[0]
Printing Variable names and contents as debugging tool; looking for emacs/Python shortcut
2813227_2813384_18
6,408,886
6,409,798
0.000672
GET_SERVER_QUEUE = 9998 ERROR = 9999
Python constants declaration
6408886_6409798_17
9,020,860
23,654,859
0.00067
from lockfile.pidlockfile import PIDLockFile from lockfile import AlreadyLocked pidfile = PIDLockFile('/var/run/mydaemon.pid', timeout=-1) try: pidfile.acquire() except AlreadyLocked: pass
python-daemon context fails to start when a stale PID file is present
9020860_23654859_14
24,187,248
24,187,326
0.00067
python 420 python3 420 420
Python 2to3 tool adds a vowel to my integer
24187248_24187326_5
7,912,820
32,020,282
0.000669
stationLat = -40 s
How do I change a value while debugging python with pdb?
7912820_32020282_2
6,290,222
6,293,302
0.000668
import cmath, math z = -1 + 0j
Numpy - square root of -1 leaves a small real part
6290222_6293302_8
15,198,426
15,198,886
0.000667
import re invalid_escape = re.compile('\\\\[0-7]{1,3}') def replace_with_byte(match): pass
Fixing invalid JSON escape
15198426_15198886_18
14,164,350
14,164,704
0.000666
import requests html = requests.get( 'http://www.cnn.com/2013/01/04/justice/ohio-rape-online-video/index.html?hpt=hp_c2' ).text soup = BS(html)
Identifying large bodies of text via BeautifulSoup or other python based extractors
14164350_14164704_15
3,250,749
3,250,975
0.000666
V = list(range(100000)) for x in V: pass
Using Windows Python from Cygwin
3250749_3250975_10
17,803,829
20,720,019
0.000666
req1 == 1.0 req2 == 1.0 req3 == 1.0
How to customize a requirements.txt for multiple environments?
17803829_20720019_6
29,325,838
30,716,284
0.000666
from enum import Enum class Color(Enum): red = 1
Import Error for module that pip reports as installed
29325838_30716284_11
11,021,130
29,618,322
0.000665
python - bcrypt arrow
Parallel Pip install
11021130_29618322_8
13,274,066
13,551,976
0.000665
import fortranformat as ff reader = ff.FortranRecordReader('(6F13.7)')
Read FORTRAN formatted numbers with Python
13274066_13551976_5
19,569,701
19,707,600
0.000664
from twisted.web import client d = client.getPage(url=context.client.location(), postdata=str(context. envelope), method='POST', headers=context.client.headers()) d.addCallback(context.succeeded)
Benefits of twisted-suds - Async way of using python suds soap lib
19569701_19707600_15
6,720,121
15,025,409
0.000664
ids = p.values_list('id', flat=True) ids_list = list(ids) import json
serializing result of a queryset with json raises error:
6720121_15025409_9
1,285,911
1,552,005
0.000664
setup = ( """from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s"%(len(q),len(d)))""" ) Timer('set(q) <= set(d)', 'D=1000000;Q=100;' + setup).timeit(1) Timer('set(q) <= d.keys()', 'D=1000000;Q=100;' + setup).timeit(1)
python: How do I check that multiple keys are in a dict in one go?
1285911_1552005_11
6,071,784
6,072,233
0.000663
text = """show the (name) of the (person) calc the sqrt of (+ (* (2 4) 3))""" import pyparsing for match in pyparsing.nestedExpr('(', ')').searchString(text): pass
Regex: Match brackets both greedy and non greedy
6071784_6072233_10
40,612,091
40,731,065
0.000663
from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('path/to/binary')
Headless script crashes after a few runs
40612091_40731065_9
6,133,154
6,148,721
0.000663
waitQueueMultiple = n
how can I release mongodb connections?
6133154_6148721_5
38,907,219
38,917,817
0.000663
vector < vector < Point >> contours vector < Vec4i > hierarchy
Detection of irregular shapes using houghcircle function opencv python
38907219_38917817_12
291,448
291,733
0.000662
import module if update_version > module.version: download(update_module) import module
Is it possible for a running python program to overwrite itself?
291448_291733_16
10,767,736
10,771,055
0.000662
import Control.Monad import Data.List
How to make ST computation produce lazy result stream (or operate like a co-routine)?
10767736_10771055_4