intent
stringlengths
4
183
snippet
stringlengths
2
1k
sqlalchemy: how to order query results (order_by) on a relationship's field?
session.query(Base).join(Base.owner).order_by(Player.name)
replace fields delimited by braces {} in string "day old bread, 50% sale {0}" with string 'today'
"""Day old bread, 50% sale {0}""".format('today')
how can i import a python module function dynamically?
my_function = getattr(__import__('my_apps.views'), 'my_function')
how to retrieve executed sql code from sqlalchemy
session.commit()
join two lists by interleaving
map(list, zip(charlist, numlist))
encoding an image file with base64
encoded_string = base64.b64encode(image_file.read())
python: download a file over an ftp server
ftp.quit()
how to create a function that outputs a matplotlib figure?
plt.figure().canvas.draw()
python string match
mystring.find('subject')
python max function using 'key' and lambda expression
max(lis, key=lambda x: x[1])
how can i indirectly call a macro in a jinja2 template?
print(template.render())
append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`
jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})
remove square bracket '[]' from pandas dataframe `df` column 'value'
df['value'] = df['value'].str.strip('[]')
changing file extension in python
os.path.splitext('name.fasta')[0] + '.aln'
how can i insert data into a mysql database?
conn.commit()
how do i get the name of a python class as a string?
test.__name__
python list comprehensions: set all elements in an array to 0 or 1
[0, 1, 0, 1, 0, 0, 1, 0]
using python to write text files with dos line endings on linux
f.write('foo\nbar\nbaz\n')
convert currency string `dollars` to decimal `cents_int`
cents_int = int(round(float(dollars.strip('$')) * 100))
stdout encoding in python
print('\xc5\xc4\xd6'.encode('UTF8'))
python 2.7 : how to use beautifulsoup in google app engine?
sys.path.insert(0, 'libs')
confirm urls in django properly
url('^$', include('sms.urls')),
printing tabular data in python
print('%20s' % somevar)
map two lists into a dictionary in python
zip(keys, values)
sort a list 'lst' in descending order.
sorted(lst, reverse=True)
list indexes of duplicate values in a list with python
print(list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5]))
how do i make a django modelform menu item selected by default?
form = MyModelForm(initial={'gender': 'M'})
pandas: how do i select first row in each group by group?
df.drop_duplicates(subset='A')
python - how to call bash commands with pipe?
subprocess.call('tar c my_dir | md5sum', shell=True)
python, how to pass an argument to a function pointer parameter?
f(*args)
using inheritance in python
super(Executive, self).__init__(*args)
how to run scrapy from within a python script
process.start()
how to set the font size of a canvas' text item?
canvas.create_text(x, y, font='Purisa', size=mdfont, text=k)
how to check a string for specific characters?
any(i in '<string>' for i in ('11', '22', '33'))
how to initialise a 2d array in python?
numpy.zeros((3, 3))
how do i find an element that contains specific text in selenium webdriver (python)?
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
variable number of digits `digits` in variable `value` in format string "{0:.{1}%}"
"""{0:.{1}%}""".format(value, digits)
insert spaces before capital letters in string `text`
re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)
break values of one column into two columns
df['last_updated_time'] = d.dt.strftime('%H:%M:%S')
generate a 12-digit random number
'%0.12d' % random.randint(0, 999999999999)
merge two integers in python
z = int(str(x) + str(y))
how to make python format floats with certain amount of significant digits?
print('%.6g' % (i,))
google app engine datastore datetime to date in python?
datetime.strptime('2012-06-25 01:17:40.273000', '%Y-%m-%d %H:%M:%S.%f')
finding index of maximum element from python list
from functools import reduce reduce(lambda a, b: [a, b], [1, 2, 3, 4], 'seed')
creating a color coded time chart using colorbar and colormaps in python
plt.show()
create dictionary from list of variables
dict((k, globals()[k]) for k in ('foo', 'bar'))
get all combination of 3 binary values
bin = [0, 1] [(x, y, z) for x in bin for y in bin for z in bin]
regular expression matching all but a string
res = re.findall('-(?!(?:aa|bb)-)([^-]+)(?=-)', s)
how can i split this comma-delimited string in python?
mystring.split(',')
faster way to remove outliers by group in large pandas dataframe
grouped = df.groupby(level='DATE')
prepend string 'hello' to all items in list 'a'
['hello{0}'.format(i) for i in a]
max value within a list of lists of tuple
map(lambda x: max(x, key=lambda y: y[1]), lists)
how to print variables without spaces between values
print('Value is "' + str(value) + '"')
pyqt qtcpserver: how to return data to multiple clients?
app.exec_()
delete the last column of numpy array `a` and assign resulting array to `b`
b = np.delete(a, -1, 1)
iterating on a file using python
f.seek(0)
add multiple columns to pandas dataframe from function
df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)
matplotlib: -- how to show all digits on ticks?
plt.show()
remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions
re.sub('(?<!\\w)([A-Z])\\.', '\\1', s)
how to specify test timeout for python unittest?
unittest.main()
set values on the diagonal of pandas.dataframe
np.fill_diagonal(df.values, 0)
get the union of values in list of lists `result_list`
return list(set(itertools.chain(*result_list)))
matplotlib: align origin of right axis with specific left axis value
plt.show()
sort python dict by datetime value
sorted(list(a.items()), key=itemgetter(1), reverse=True)
rotating a two-dimensional array in python
original[::-1]
concatenate two dataframes in pandas
pd.concat([df_a, df_b], axis=1)
how to create unittests for python prompt toolkit?
unittest.main()
easy pretty printing of floats in python?
print(['{0:0.2f}'.format(i) for i in a])
how to make a shallow copy of a list in python
newprefix = list(prefix)
how to perform search on a list of tuples
[('jamy', 'Park', 'kick'), ('see', 'it', 'works')]
python : getting the row which has the max value in groups using groupby
df.groupby(['Mt'], sort=False)['count'].max()
match string 'this is my string' with regex '\\b(this|string)\\b' then replace it with regex '<markup>\\1</markup>'
re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')
how to efficiently compare two unordered lists (not sets) in python?
len(a) == len(b) and all(a.count(i) == b.count(i) for i in a)
concurrency control in django model
super(ConcurrentModel, self).save(*args, **kwargs)
pandas plotting with multi-index
summed_group.unstack(level=0).plot(kind='bar', subplots=True)
write dataframe `df` to csv file 'mycsv.csv'
df.write.csv('mycsv.csv')
make an http post request to upload a file using python urllib/urllib2
response = requests.post(url, files=files)
how do i convert datetime to date (in python)?
datetime.datetime.now().date()
how to print a file to paper in python 3 on windows xp/7?
subprocess.call(['notepad', '/p', filename])
in python, is there an easy way to turn numbers with commas into an integer, and then back to numbers with commas?
s = '{0:,}'.format(n)
pass a list of parameters `((1, 2, 3),) to sql queue 'select * from table where column in %s;'
cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))
python3 bytes to hex string
a.decode('ascii')
how to read from a zip file within zip file in python?
return zipfile.ZipFile(path)
strncmp in python
S2[:len(S1)] == S1
python insert numpy array into sqlite3 database
cur.execute('insert into test (arr) values (?)', (x,))
how to calculate quantiles in a pandas multiindex dataframe?
df.groupby(level=[0, 1]).median()
delete the element 6 from list `a`
a.remove(6)
match zero-or-more instances of lower case alphabet characters in a string `f233op `
re.findall('([a-z])*', 'f233op')
matplotlib: formatting dates on the x-axis in a 3d bar graph
ax.set_ylabel('Series')
how to check a string for a special character?
print('Valid' if re.match('^[a-zA-Z0-9_]*$', word) else 'Invalid')
sorting a list of lists of dictionaries in python
key = lambda x: sum(map(itemgetter('play'), x))
how to read integers from a file that are 24bit and little endian using python?
struct.unpack('<I', bytes + '\x00')
how to reverse the elements in a sublist?
[sublist[::-1] for sublist in to_reverse[::-1]]
list comprehension to extract a list of tuples from dictionary
[(movie_dict['title'], movie_dict['year']) for movie_dict in movie_dicts]
print number 1255000 as thousands separators
locale.setlocale(locale.LC_ALL, 'en_US') locale.format('%d', 1255000, grouping=True)
multiply column 'a' and column 'b' by column 'c' in datafram `df`
df[['A', 'B']].multiply(df['C'], axis='index')
how to make a histogram from a list of strings in python?
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
can selenium web driver have access to javascript global variables?
browser.execute_script('return globalVar;')
check if all string elements in list `words` are upper-cased
print(all(word[0].isupper() for word in words))
converting configparser values to python data types
literal_eval("{'key': 10}")