neulab/docprompting-conala huggingface dataset:
# group dataframe `df` by columns 'Month' and 'Fruit'
df.groupby(['Month', 'Fruit']).sum().unstack(level=0)
# request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd'
requests.get('https://www.mysite.com/', auth=('username', 'pwd'))
# list folders in zip file 'file' that ends with '/'
[x for x in file.namelist() if x.endswith('/')]
# remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`
str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')
# convert dictionary `dict` into a string formatted object
'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'
# load a json data `json_string` into variable `json_data`
json_data = json.loads(json_string)
# Rename file from `src` to `dst`
os.rename(src, dst)
# pygobject center window `window`
window.set_position(Gtk.WindowPosition.CENTER)
# Retrieve parameter 'var_name' from a GET request.
self.request.get('var_name')
# convert keys in dictionary `thedict` into case insensitive
theset = set(k.lower() for k in thedict)
# merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date'
df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue'])
# permanently set the current directory to the 'C:/Users/Name/Desktop'
os.chdir('C:/Users/Name/Desktop')
# get a request parameter `a` in jinja2
{{request.args.get('a')}}
# get the  size of file 'C:\\Python27\\Lib\\genericpath.py'
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
# urlencode a querystring 'string_of_characters_like_these:$#@=?%^Q^$' in python 2
urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
# generate random Decimal
decimal.Decimal(random.randrange(10000)) / 100
# How to get only the last part of a path in Python?
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
# get index of key 'c' in dictionary `x`
list(x.keys()).index('c')
# create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york'
[value for key, value in list(programs.items()) if 'new york' in key.lower()]
# Replace special characters in utf-8 encoded string `s` using the %xx escape
urllib.parse.quote(s.encode('utf-8'))
# Get sum of values of columns  'Y1961', 'Y1962', 'Y1963' after group by on columns "Country" and "Item_code" in dataframe `df`.
df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()
# get the number of values in list `j` that is greater than 5
sum(((i > 5) for i in j))
# get the number of values in list `j` that is greater than 5
len([1 for i in j if (i > 5)])
# get the number of values in list `j` that is greater than `i`
j = np.array(j)
sum((j > i))
# check if a numpy array `a1` contains any element of another array `a2`
np.any(np.in1d(a1, a2))
# clamping floating number `my_value` to be between `min_value` and `max_value`
max(min(my_value, max_value), min_value)
# get all combination of n binary values
lst = list(itertools.product([0, 1], repeat=n))
# get all combination of n binary values
lst = map(list, itertools.product([0, 1], repeat=n))
# 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]
# get all combination of 3 binary values
lst = list(itertools.product([0, 1], repeat=3))
# add one day and three hours to the present time from datetime.now()
datetime.datetime.now() + datetime.timedelta(days=1, hours=3)
# unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float
struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))
# add a colorbar to plot `plt` using image `im` on axes `ax`
plt.colorbar(im, ax=ax)
# remove first and last lines of string `s`
s[s.find('\n') + 1:s.rfind('\n')]
# From multiIndexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`
data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]
# select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns
data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]
# filter `Users` by field `userprofile` with level greater than or equal to `0`
User.objects.filter(userprofile__level__gte=0)
# make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character
[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]
# How to group similar items in a list?
[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]
# django get the value of key 'title' from POST request `request` if exists, else return empty string ''
request.POST.get('title', '')
# List comprehension with an accumulator in range of 10
list(accumulate(list(range(10))))
# Create a default empty json object if no json is available in request parameter `mydata`
json.loads(request.POST.get('mydata', '{}'))
# get the largest index of the last occurrence of characters '([{' in string `test_string`
max(test_string.rfind(i) for i in '([{')
# get all characters in string 'foobar' up to the fourth index
"""foobar"""[:4]
# count unique index values in column 'A' in pandas dataframe `ex`
ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
# List of lists into numpy array
numpy.array([[1, 2], [3, 4]])
# Create a tuple `t` containing first element of each tuple in tuple `s`
t = tuple(x[0] for x in s)
# BeautifulSoup get value associated with attribute 'content' where attribute 'name' is equal to 'City' in tag 'meta' in HTML parsed string `soup`
soup.find('meta', {'name': 'City'})['content']
# pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index
df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)
# changing permission of file `path` to `stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH`
os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
# write dataframe `df` to csv file `filename` with dates formatted as yearmonthday  `%Y%m%d`
df.to_csv(filename, date_format='%Y%m%d')
# replace NaN values in array `a` with zeros
b = np.where(np.isnan(a), 0, a)
# get a numpy array that contains the element wise minimum of three 3x1 arrays
np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)
# obtain the current day of the week in a 3 letter format from a datetime object
datetime.datetime.now().strftime('%a')
# dictionary `d` to string, custom format
"""<br/>""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])
# select rows of dataframe `df` whose value for column `A` is `foo`
print(df.loc[df['A'] == 'foo'])
# select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame
df.loc[df['column_name'] != some_value]
# select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`
df.loc[~df['column_name'].isin(some_values)]
# select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`
df.loc[df['column_name'] == some_value]
# Select rows whose value of the "B" column is "one" or "three" in the DataFrame `df`
print(df.loc[df['B'].isin(['one', 'three'])])
# Enable the SO_REUSEADDR socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# import all classes from module `some.package`
globals().update(importlib.import_module('some.package').__dict__)
# Find indices of elements equal to zero from numpy array `x`
numpy.where((x == 0))[0]
# create a json response `response_data`
return HttpResponse(json.dumps(response_data), content_type='application/json')
# Convert a string `s` containing hex bytes to a hex string
s.decode('hex')
# convert a string `s` containing hex bytes to a hex string
binascii.a2b_hex(s)
# zip list `a`, `b`, `c` into a list of tuples
[(x + tuple(y)) for x, y in zip(zip(a, b), c)]
# convert dictionary `adict` into string
"""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))
# convert dictionary `adict` into string
"""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))
# convert matlab engine array `x` to a numpy ndarray
np.array(x._data).reshape(x.size[::-1]).T
# Convert list of booleans `walls` into a hex string
hex(int(''.join([str(int(b)) for b in walls]), 2))
# convert the sum of list `walls` into a hex presentation
hex(sum(b << i for i, b in enumerate(reversed(walls))))
# set the current working directory to 'c:\\Users\\uname\\desktop\\python'
os.chdir('c:\\Users\\uname\\desktop\\python')
# Check the status code of url "http://www.stackoverflow.com"
urllib.request.urlopen('http://www.stackoverflow.com').getcode()
# Check the status code of url "www.python.org"
conn = httplib.HTTPConnection('www.python.org')
conn.request('HEAD', '/')
r1 = conn.getresponse()
print(r1.status, r1.reason)
# Check the status code of url `url`
r = requests.head(url)
return (r.status_code == 200)
# Checking if website "http://www.stackoverflow.com" is up
print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())
# rename column 'gdp' in dataframe `data` to 'log(gdp)'
data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)
# best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object
{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}
# extract subset of key-value pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`
dict((k, bigdict[k]) for k in ('l', 'm', 'n'))
# Get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`
{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}
# Extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3
{k: bigdict[k] for k in ('l', 'm', 'n')}
# Search for string 'blabla' in txt file 'example.txt'
if ('blabla' in open('example.txt').read()):
    pass
# Search for string 'blabla' in txt file 'example.txt'
f = open('example.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if (s.find('blabla') != (-1)):
    pass
# Search for string `blabla` in txt file 'example.txt'
datafile = file('example.txt')
found = False
for line in datafile:
    if (blabla in line):
        return True
return False
# request http url `url` with parameters `payload`
r = requests.get(url, params=payload)
# post request url `url` with parameters `payload`
r = requests.post(url, data=payload)
# make an HTTP post request with data `post_data`
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
# convert binary string '01010101111' to integer
int('01010101111', 2)
# convert binary string '0b0010101010' to integer
int('0b0010101010', 2)
# convert binary string '11111111' to integer
int('11111111', 2)
# get proportion of rows in dataframe `trace_df` whose values for column `ratio` are greater than 0
(trace_df['ratio'] > 0).mean()
# get all possible combination of items from 2-dimensional list `a`
list(itertools.product(*a))
# iterate over a dictionary `d` in sorted order
it = iter(sorted(d.items()))
# iterate over a dictionary `d` in sorted order
for (key, value) in sorted(d.items()):
    pass
# iterate over a dictionary `dict` in sorted order
return iter(sorted(dict.items()))
# iterate over a dictionary `foo` in sorted order
for (k, v) in sorted(foo.items()):
    pass
# iterate over a dictionary `foo` sorted by the key
for k in sorted(foo.keys()):
    pass
# lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\1'
re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()
# convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow
print(type(tf.Session().run(tf.constant([1, 2, 3]))))
# Initialize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`
s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])
# get set intersection between dictionaries `d1` and `d2`
dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())
# construct pandas dataframe from a list of tuples
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
# converting dictionary `d` into a dataframe `pd` with keys as data for column 'Date' and the corresponding values as data for column 'DateValue'
pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])
# generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
# Convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes
df.set_index(['year', 'month', 'item']).unstack(level=-1)
# run a pivot with a multi-index `year` and `month` in a pandas data frame
df.pivot_table(values='value', index=['year', 'month'], columns='item')
# How to get output of exe in python script?
output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]
# get all sub-elements of an element `a` in an elementtree
[elem.tag for elem in a.iter()]
# get all sub-elements of an element tree `a` excluding the root element
[elem.tag for elem in a.iter() if elem is not a]
# get the next value greatest to `2` from a list of numbers `num_list`
min([x for x in num_list if x > 2])
# delete the element `c` from list `a`
if (c in a):
    a.remove(c)
# delete the element `c` from list `a`
try:
    a.remove(c)
except ValueError:
    pass
# call a function `otherfunc` inside a bash script `test.sh` using subprocess
subprocess.call('test.sh otherfunc')
# Can a python script execute a function inside a bash script?
subprocess.Popen(['bash', '-c', '. foo.sh; go'])
# write pandas dataframe `df` to the file 'c:\\data\\t.csv' without row names
df.to_csv('c:\\data\\t.csv', index=False)
# match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353'
print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))
# filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`
Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])
# filter objects month wise in django model `Sample` for year `2011`
Sample.objects.filter(date__year='2011', date__month='01')
# Open image 'picture.jpg'
img = Image.open('picture.jpg')
img.show()
# Open image "picture.jpg"
img = Image.open('picture.jpg')
Img.show
# write the content of file `xxx.mp4` to file `f`
f.write(open('xxx.mp4', 'rb').read())
# Sort the values of the dataframe `df` and align the columns accordingly based on the obtained indices after np.argsort.
pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))
# remove duplicate rows from dataframe `df1` and calculate their frequency
df1.groupby(['key', 'year']).size().reset_index()
# Get average for every three columns in `df` dataframe
df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()
# django redirect to view 'Home.views.index'
redirect('Home.views.index')
# get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight'
sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)
# get the path of the python module `amodule`
path = os.path.abspath(amodule.__file__)
# sum the values in each row of every two adjacent columns in dataframe `df`
df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')
# display current time
now = datetime.datetime.now().strftime('%H:%M:%S')
# decode a hex string '4a4b4c' to UTF-8.
bytes.fromhex('4a4b4c').decode('utf-8')
# capture final output of a chain of system commands `ps -ef | grep something | wc -l`
subprocess.check_output('ps -ef | grep something | wc -l', shell=True)
# find intersection data between series `s1` and series `s2`
pd.Series(list(set(s1).intersection(set(s2))))
# Format a datetime string `when` to extract date only
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
# get the first object from a queryset in django model `Entry`
Entry.objects.filter()[:1].get()
# download a file "http://www.example.com/songs/mp3.mp3" over HTTP and save to "mp3.mp3"
urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
# download a file `url` over HTTP and save to `file_name`
u = urllib.request.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders('Content-Length')[0])
print(('Downloading: %s Bytes: %s' % (file_name, file_size)))
file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if (not buffer):
        break
    file_size_dl += len(buffer)
    f.write(buffer)
    status = ('%10d  [%3.2f%%]' % (file_size_dl, ((file_size_dl * 100.0) / file_size)))
    status = (status + (chr(8) * (len(status) + 1)))
    print(status, end=' ')
f.close()
# download a file 'http://www.example.com/' over HTTP
response = urllib.request.urlopen('http://www.example.com/')
html = response.read()
# download a file `url` over HTTP and save to "10MB"
response = requests.get(url, stream=True)
with open('10MB', 'wb') as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)
# Multiply a matrix `P` with a 3d tensor `T` in scipy
scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)
# convert hex string '470FC614' to a float number
struct.unpack('!f', '470FC614'.decode('hex'))[0]
# reverse the list that contains 1 to 10
list(reversed(list(range(10))))
# get the date 7 days before the current date
(datetime.datetime.now() - datetime.timedelta(days=7)).date()
# encode binary string 'your string' to base64 code
base64.b64encode(bytes('your string', 'utf-8'))
# identify duplicate values in list `mylist`
[k for k, v in list(Counter(mylist).items()) if v > 1]
# write the data of dataframe `df` into text file `np.txt`
np.savetxt('c:\\data\\np.txt', df.values, fmt='%d')
# write content of DataFrame `df` into text file 'c:\\data\\pandas.txt'
df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')
# Split a string `x` by last occurrence of character `-`
print(x.rpartition('-')[0])
# get the last part of a string before the character '-'
print(x.rsplit('-', 1)[0])
# create a random list of integers
[int(1000 * random.random()) for i in range(10000)]
# Using %f with strftime() in Python to get microseconds
datetime.datetime.now().strftime('%H:%M:%S.%f')
# print a 2 dimensional list `tab` as a table with delimiters
print('\n'.join('\t'.join(str(col) for col in row) for row in tab))
# count non zero values in each column in pandas data frame
df.astype(bool).sum(axis=1)
# lower a string `text` and remove non-alphanumeric characters aside from space
re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip()
# remove all non-alphanumeric characters except space from a string `text` and lower it
re.sub('(?!\\s)[\\W_]', '', text).lower().strip()
# access a tag called "name" in beautifulsoup `soup`
print(soup.find('name').string)
# Get the characters count in a file `filepath`
os.stat(filepath).st_size
# count the occurrences of item "a" in list `l`
l.count('a')
# count the occurrences of items in list `l`
[[x, l.count(x)] for x in set(l)]
# count the occurrences of items in list `l`
dict(((x, l.count(x)) for x in set(l)))
# count the occurrences of item "b" in list `l`
l.count('b')
# copy file `srcfile` to directory `dstdir`
shutil.copy(srcfile, dstdir)
# combine values from column 'b' and column 'a' of dataframe `df`  into column 'c' of datafram `df`
df['c'] = np.where(df['a'].isnull, df['b'], df['a'])
# Convert tuple `level1` to list
level1 = map(list, level1)
# send the output of pprint object `dataobject` to file `logFile`
pprint.pprint(dataobject, logFile)
# get index of rows in column 'BoolCol'
df.loc[df['BoolCol']]
# Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True
df.iloc[np.flatnonzero(df['BoolCol'])]
# get list of indexes of rows where column 'BoolCol' values match True
df[df['BoolCol'] == True].index.tolist()
# get index of rows in dataframe `df` which column 'BoolCol' matches value True
df[df['BoolCol']].index.tolist()
# remove a div with a id `main-content` using beautifulsoup
soup.find('div', id='main-content').decompose()
# join each element in array `a` with element at the same index in array `b` as a tuple
np.array([zip(x, y) for x, y in zip(a, b)])
# zip two 2-d arrays `a` and `b`
np.array(zip(a.ravel(), b.ravel()), dtype='i4,i4').reshape(a.shape)
# Find last occurrence of character '}' in string "abcd}def}"
'abcd}def}'.rfind('}')
# shuffle columns of an numpy array 'r'
np.random.shuffle(np.transpose(r))
# determine number of files on a drive with python
os.statvfs('/').f_files - os.statvfs('/').f_ffree
# how to get a single result from a SQLite query in python?
cursor.fetchone()[0]
# prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile'
open('outfile', 'w').write('#test firstline\n' + open('infile').read())
# return `True` if string `foobarrrr` contains regex `ba[rzd]`
bool(re.search('ba[rzd]', 'foobarrrr'))
# Removing duplicates in list `source_list`
list(set(source_list))
# Removing duplicates in list `abracadabra`
list(OrderedDict.fromkeys('abracadabra'))
# Convert array `a` into a list
numpy.array(a).reshape(-1).tolist()
# Convert the first row of numpy matrix `a` to a list
numpy.array(a)[0].tolist()
# In `soup`, get the content of the sibling of the `td`  tag with text content `Address:`
print(soup.find(text='Address:').findNext('td').contents[0])
# encode string 'data to be encoded'
encoded = base64.b64encode('data to be encoded')
# encode a string `data to be encoded` to `ascii` encoding
encoded = 'data to be encoded'.encode('ascii')
# Get attribute `my_str` of object `my_object`
getattr(my_object, my_str)
# replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros
np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)
# calculate mean across dimension in a 2d array `a`
np.mean(a, axis=1)
# selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1
a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]
# convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`
pd.DataFrame({'email': sf.index, 'list': sf.values})
# resized image `image` to width, height of `(x, y)` with filter of `ANTIALIAS`
image = image.resize((x, y), Image.ANTIALIAS)
# find 10 largest differences between each respective elements of list `l1` and list `l2`
heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))
# BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'
soup.find_all('span', {'class': 'starGryB sp'})
# Sort lis `list5` in ascending order based on the degrees value of its elements
sorted(list5, lambda x: (degree(x), x))
# How do I perform secondary sorting in python?
sorted(list5, key=lambda vertex: (degree(vertex), vertex))
# get attribute 'attr' from object `obj`
getattr(obj, 'attr')
# encode `Decimal('3.9')` to a JSON string
json.dumps(Decimal('3.9'))
# filter dataframe `df` by values in column `A` that appear more than once
df.groupby('A').filter(lambda x: len(x) > 1)
# add color bar with image `mappable` to plot `plt`
plt.colorbar(mappable=mappable, cax=ax3)
# count most frequent 100 words in column 'text' of dataframe `df`
Counter(' '.join(df['text']).split()).most_common(100)
# get a value of datetime.today() in the UTC time zone
datetime.now(pytz.utc)
# Django response with JSON `data`
return HttpResponse(data, mimetype='application/json')
# Open a background process 'background-process' with arguments 'arguments'
subprocess.Popen(['background-process', 'arguments'])
# finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
# unpack a series of tuples in pandas into a DataFrame with column names 'out-1' and 'out-2'
pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)
# rotate the xtick labels of matplotlib plot `ax` by `45` degrees to make long labels readable
ax.set_xticklabels(labels, rotation=45)
# get number of keys in dictionary `yourdict`
len(list(yourdict.keys()))
# count the number of keys in dictionary `yourdictfile`
len(set(open(yourdictfile).read().split()))