neulab/docprompting-conala huggingface dataset:
# divide the values with same keys of two dictionary `d1` and `d2`
{k: (float(d2[k]) / d1[k]) for k in d2}
# divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`
dict((k, float(d2[k]) / d1[k]) for k in d2)
# download "http://randomsite.com/file.gz" from http and save as "file.gz"
testfile = urllib.request.URLopener()
testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')
# download file from http url "http://randomsite.com/file.gz" and save as "file.gz"
urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz')
# filter a Django model `MyModel` to have charfield length of max `255`
MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254'])
# get logical xor of `a` and `b`
((a and (not b)) or ((not a) and b))
# get the date 1 month from today
(date(2010, 12, 31) + relativedelta(months=(+ 1)))
# get the date 2 months from today
(date(2010, 12, 31) + relativedelta(months=(+ 2)))
# call a Python script "test1.py"
subprocess.call('test1.py', shell=True)
# check if object `obj` has attribute 'attr_name'
hasattr(obj, 'attr_name')
# slice list `[1, 2, 3, 4, 5, 6, 7]` into lists of two elements each
list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))
# Slicing a list into a list of sub-lists
[input[i:i + n] for i in range(0, len(input), n)]
# fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\\(|D|P)' in string `s`
re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)
# Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0
df.loc[df.groupby('User')['X'].transform(sum) == 0]
# Get data from dataframe `df` where column 'X' is equal to 0
df.groupby('User')['X'].transform(sum) == 0
# webbrowser open url 'http://example.com'
webbrowser.open('http://example.com')
# get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
# sort dictionary `dictionary` in ascending order by its values
sorted(list(dictionary.items()), key=operator.itemgetter(1))
# iterate over a python dictionary, ordered by values
sorted(list(dictionary.items()), key=lambda x: x[1])
# pandas split strings in column 'stats' by ',' into columns in dataframe `df`
df['stats'].str[1:-1].str.split(',', expand=True).astype(float)
# split string in column 'stats' by ',' into separate columns in dataframe `df`
df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)
# Remove characters "!@#$" from a string `line`
line.translate(None, '!@#$')
# Remove characters "!@#$" from a string `line`
line = re.sub('[!@#$]', '', line)
# Remove characters in '!@#$' from a string `line`
line = line.translate(string.maketrans('', ''), '!@#$')
# subtract 1 hour and 10 minutes from time object `t`
(t - datetime.timedelta(hours=1, minutes=10))
# subtract 5 hours from the time object `dt`
dt -= datetime.timedelta(hours=5)
# generate a 12-digit random number
random.randint(100000000000, 999999999999)
# generate a 12-digit random number
'%0.12d' % random.randint(0, 999999999999)
# Parsing webpage 'http://www.google.com/' using BeautifulSoup
page = urllib.request.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)
# move an x-axis label to the top of a plot `ax` in matplotlib
ax.xaxis.set_label_position('top')
# move x-axis to the top of a plot `ax`
ax.xaxis.tick_top()
# check if array `b` contains all elements of array `a`
numpy.in1d(b, a).all()
# convert decimal 8 to a list of its binary values
list('{0:0b}'.format(8))
# convert decimal integer 8 to a list of its binary values as elements
[int(x) for x in list('{0:0b}'.format(8))]
# print current date and time in a regular format
time.strftime('%Y-%m-%d %H:%M')
# Calling an external command "some_command with args"
os.system('some_command with args')
# Calling an external command "some_command < input_file | another_command > output_file"
os.system('some_command < input_file | another_command > output_file')
# Calling an external command "some_command with args"
stream = os.popen('some_command with args')
# Calling an external command "echo Hello World"
return_code = subprocess.call('echo Hello World', shell=True)
# Find name of current directory
dir_path = os.path.dirname(os.path.realpath(__file__))
# Find the full path of current directory
full_path = os.path.realpath(__file__)
# unpack hexadecimal string `s` to a list of integer values
struct.unpack('11B', s)
# convert column of date objects 'DateObj' in pandas dataframe `df` to strings in new column 'DateStr'
df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
# generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`
print(list(itertools.product([1, 2, 3], [4, 5, 6])))
# generate all permutations of a list `[1, 2, 3]`
itertools.permutations([1, 2, 3])
# Exclude column names when writing dataframe `df` to a csv file `filename.csv`
df.to_csv('filename.csv', header=False)
# create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg'
files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]
# convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns
df.pivot(index='order', columns='sample')
# python pickle/unpickle a list to/from a file 'afile'
pickle.load(open('afile', 'rb'))
# Extract first two substrings in string `phrase` that end in `.`, `?` or `!`
re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)
# how to write a unicode csv in Python 2.7
self.writer.writerow([str(s).encode('utf-8') for s in row])
# calculat the difference between each row and the row previous to it in dataframe `data`
data.set_index('Date').diff()
# get index of elements in array `A` that occur in another array `B`
np.where(np.in1d(A, B))[0]
# query all data from table `Task` where the value of column `time_spent` is bigger than 3 hours
session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
# get current time in pretty format
strftime('%Y-%m-%d %H:%M:%S', gmtime())
# adding a 1-d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3-d array `np.zeros((6, 9, 20))`
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]
# add array of shape `(6, 9, 20)` to array `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))
# extract first and last row of a dataframe `df`
pd.concat([df.head(1), df.tail(1)])
# convert date string '24052010' to date object in format '%d%m%Y'
datetime.datetime.strptime('24052010', '%d%m%Y').date()
# calculate the mean of the nonzero values' indices of dataframe `df`
np.flatnonzero(x).mean()
# Get index of numpy array `a` with another numpy array `b`
a[tuple(b)]
# input a tuple of integers from user
tuple(int(x.strip()) for x in input().split(','))
# rotate x-axis text labels of plot `ax` 45 degrees
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
# sum the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP'
df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())
# transform time series `df` into a pivot table aggregated by column 'Close' using column `df.index.date` as index and values of column `df.index.time` as columns
pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')
# Create array `a` containing integers from stdin
a.fromlist([int(val) for val in stdin.read().split()])
# sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey'
sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)
# sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey'
yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
# Draw node labels `labels` on networkx graph `G ` at position `pos`
networkx.draw_networkx_labels(G, pos, labels)
# get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log'
os.path.commonprefix(['/usr/var', '/usr/var2/log'])
# get relative path of path '/usr/var' regarding path '/usr/var/log/'
print(os.path.relpath('/usr/var/log/', '/usr/var'))
# Evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr
getattr(getattr(myobject, 'id', None), 'number', None)
# outer product of each column of a 2d `X` array to form a 3d array `X`
np.einsum('ij,kj->jik', X, X)
# create a list containing a four elements long tuples of permutations of binary values
itertools.product(list(range(2)), repeat=4)
# match regex pattern '\\$[0-9]+[^\\$]*$' on string '$1 off delicious $5 ham.'
re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')
# generate 6 random numbers between 1 and 50
random.sample(range(1, 50), 6)
# generate six unique random numbers in the range of 1 to 49.
random.sample(range(1, 50), 6)
# set the font 'Purisa' of size 12 for a canvas' text item `k`
canvas.create_text(x, y, font=('Purisa', 12), text=k)
# create a pandas data frame from list of nested dictionaries `my_list`
pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T
# check if string `one` exists in the values of dictionary `d`
'one' in list(d.values())
# Check if value 'one' is among the values of dictionary `d`
'one' in iter(d.values())
# change legend size to 'x-small' in upper-left location
pyplot.legend(loc=2, fontsize='x-small')
# change legend font size with matplotlib.pyplot to 6
plot.legend(loc=2, prop={'size': 6})
# remove all whitespace in a string `sentence`
pattern = re.compile('\\s+')
sentence = re.sub(pattern, '', sentence)
# remove all whitespaces in string `sentence`
sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)
# remove all whitespaces in a string `sentence`
sentence = ''.join(sentence.split())
# create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet'
df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')
# read a text file 'very_Important.txt' into a string variable `str`
str = open('very_Important.txt', 'r').read()
# handle the `urlfetch_errors ` exception for imaplib request to url `url`
urlfetch.fetch(url, deadline=10 * 60)
# remove the fragment identifier `#something` from a url `http://www.address.com/something#something`
urlparse.urldefrag('http://www.address.com/something#something')
# reverse sort items in dictionary `mydict` by value
sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)
# Flask get value of request variable 'firstname'
first_name = request.args.get('firstname')
# Flask get posted form data 'firstname'
first_name = request.form.get('firstname')
# read the contents of the file 'file.txt' into `txt`
txt = open('file.txt').read()
# using python's datetime module, get the year that utc-11 is currently in
(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year
# Filter model 'Entry' where 'id' is not equal to 3 in Django
Entry.objects.filter(~Q(id=3))
# using beautifulsoup to select div blocks within html `soup`
soup.find_all('div', class_='crBlock ')
# convert hex triplet string `rgbstr` to rgb tuple
struct.unpack('BBB', rgbstr.decode('hex'))
# reverse a string `a` by 2 characters at a time
"""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))
# Terminating a Python script with error message "some error message"
sys.exit('some error message')
# hide output of subprocess `['espeak', text]`
subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)
# convert a string `s` containing a decimal to an integer
int(Decimal(s))
# elementwise product of 3d arrays `A` and `B`
np.einsum('ijk,ikl->ijl', A, B)
# run shell command 'rm -r some.file' in the background
subprocess.Popen(['rm', '-r', 'some.file'])
# round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places
df.round({'Alabama_exp': 2, 'Credit_exp': 3})
# retrieve an element from a set `s` without removing it
e = next(iter(s))
# Parse string `datestr` into a datetime object using format pattern '%Y-%m-%d'
dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()
# encode a pdf file `pdf_reference.pdf` with `base64` encoding
a = open('pdf_reference.pdf', 'rb').read().encode('base64')
# change current working directory to directory 'chapter3'
os.chdir('chapter3')
# change current working directory
os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
# upload file with Python Mechanize
br.form.add_file(open(filename), 'text/plain', filename)
# Match regex '[a-zA-Z][\\w-]*\\Z' on string 'A\n'
re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')
# match regex '[a-zA-Z][\\w-]*$' on string '!A_B'
re.match('[a-zA-Z][\\w-]*$', '!A_B')
# Find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`
soup.find_all('div', class_=re.compile('comment-'))
# Open file 'sample.json' in read mode with encoding of 'utf-8-sig'
json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))
# load json file 'sample.json' with utf-8 bom header
json.loads(open('sample.json').read().decode('utf-8-sig'))
# convert string representation `s2` of binary string rep of integer to floating point number
struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]
# convert a binary '-0b1110' to a float number
float(int('-0b1110', 0))
# convert a binary `b8` to a float number
struct.unpack('d', b8)[0]
# in django, check if a user is in a group 'Member'
return user.groups.filter(name='Member').exists()
# check if a user `user` is in a group from list of groups `['group1', 'group2']`
return user.groups.filter(name__in=['group1', 'group2']).exists()
# find rows matching `(0,1)` in a 2 dimensional numpy array `vals`
np.where((vals == (0, 1)).all(axis=1))
# change directory to the directory of a python script
os.chdir(os.path.dirname(__file__))
# export a table dataframe `df` in pyspark to csv 'mycsv.csv'
df.toPandas().to_csv('mycsv.csv')
# Write DataFrame `df` to csv file 'mycsv.csv'
df.write.csv('mycsv.csv')
# zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index
zip(*[(1, 4), (2, 5), (3, 6)])
# split a list of tuples `data` into sub-lists of the same tuple field using itertools
[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]
# pandas dataframe `df` column 'a' to list
df['a'].values.tolist()
# Get a list of all values in column `a` in pandas data frame `df`
df['a'].tolist()
# parse UTF-8 encoded HTML response `response` to BeautifulSoup object
soup = BeautifulSoup(response.read().decode('utf-8'))
# get all the values from a numpy array `a` excluding index 3
a[np.arange(len(a)) != 3]
# get the output of a subprocess command `echo "foo"` in command line
subprocess.check_output('echo "foo"', shell=True)
# extract unique dates from time series 'Date' in dataframe `df`
df['Date'].map(lambda t: t.date()).unique()
# check if file `filename` is descendant of directory '/the/dir/'
os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'
# create a dictionary of pairs from a list of tuples `myListOfTuples`
dict(x[1:] for x in reversed(myListOfTuples))
# sort a list of dictionary values by 'date' in reverse order
list.sort(key=lambda item: item['date'], reverse=True)
# export a pandas data frame `df` to a file `mydf.tsv` and retain the indices
df.to_csv('mydf.tsv', sep='\t')
# Get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values
Counter([1, 2, 2, 2, 3]) - Counter([1, 2])
# compare contents  at filehandles `file1` and `file2` using difflib
difflib.SequenceMatcher(None, file1.read(), file2.read())
# Get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan
min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])
# convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision
str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]
# convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points
str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]
# get element at index 0 of first row and element at index 1 of second row in array `A`
A[[0, 1], [0, 1]]
# subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.
a[np.arange(3), (0, 1, 0)]
# Find all the tags `a` and `div` from Beautiful Soup object `soup`
soup.find_all(['a', 'div'])
# Reverse a string `a_string`
def reversed_string(a_string):
    return a_string[::(-1)]
# set the stdin of the process 'grep f' to be b'one\ntwo\nthree\nfour\nfive\nsix\n'
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]
# set the stdin of the process 'grep f' to be 'one\ntwo\nthree\nfour\nfive\nsix\n'
p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n')
p.communicate()[0]
p.stdin.close()
# normalize a pandas dataframe `df` by row
df.div(df.sum(axis=1), axis=0)
# read a file from redirected stdin and save to variable `result`
result = sys.stdin.read()
# remove elements from an array `A` that are in array `B`
A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]
# drop rows of dataframe `df` whose index is smaller than the value of `start_remove` or bigger than the value of`end_remove`
df.query('index < @start_remove or index > @end_remove')
# Drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`
df.loc[(df.index < start_remove) | (df.index > end_remove)]
# Get all indexes of boolean numpy array where boolean value `mask` is True
numpy.where(mask)
# Convert CSV file `Result.csv` to Pandas dataframe using separator ' '
df.to_csv('Result.csv', index=False, sep=' ')
# convert a list of dictionaries `d` to pandas data frame
pd.DataFrame(d)
# Open gzip-compressed file encoded as utf-8 'file.gz' in text mode
gzip.open('file.gz', 'rt', encoding='utf-8')
# navigate to webpage given by url `http://www.python.org` using Selenium
driver.get('http://www.google.com.br')
# check if "blah" is in string `somestring`
if ('blah' not in somestring):
    pass
# check if string `needle` is in `haystack`
if (needle in haystack):
    pass
# check if string `s` contains "is"
if (s.find('is') == (-1)):
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")
# calling a function named 'myfunction' in the module
globals()['myfunction']()
# convert double 0.00582811585976 to float
struct.unpack('f', struct.pack('f', 0.00582811585976))
# how to uniqify a list of dict in python
[dict(y) for y in set(tuple(x.items()) for x in d)]
# get a list of words `words` of a file 'myfile'
words = open('myfile').read().split()
# create a django query for a list of values `1, 4, 7`
Blog.objects.filter(pk__in=[1, 4, 7])
# case insensitive comparison of strings `string1` and `string2`
if (string1.lower() == string2.lower()):
    print('The strings are the same (case insensitive)')
else:
    print('The strings are not the same (case insensitive)')
# case insensitive string comparison between `string1` and `string2`
if (string1.lower() == string2.lower()):
    pass
# case insensitive string comparison between `string1` and `string2`
(string1.lower() == string2.lower())
# case insensitive string comparison between `first` and `second`
(first.lower() == second.lower())
# case insensitive comparison between strings `first` and `second`
(first.upper() == second.upper())
# Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries
pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)
# get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`
df.groupby(['col5', 'col2']).size().groupby(level=1).max()
# get the attribute `x` from object `your_obj`
getattr(your_obj, x)
# How do I convert datetime to date (in Python)?
datetime.datetime.now().date()
# sort numpy float array `A` column by column
A = np.array(sorted(A, key=tuple))
# convert utf-8 string `s` to lowercase
s.decode('utf-8').lower()
# Update a user's name as `Bob Marley` having id `123` in SQLAlchemy
session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})
# define global variable `something` with value `bob`
globals()['something'] = 'bob'
# Check whether a numpy array `a` contains a given row `[1, 2]`
any(np.equal(a, [1, 2]).all(1))
# convert ndarray with shape 3x3 to array
np.zeros((3, 3)).ravel()
# convert dict `result` to numpy structured array
numpy.array([(key, val) for key, val in result.items()], dtype)
# sort list `mylist` alphabetically
mylist.sort(key=lambda x: x.lower())
# sort list `mylist` in alphabetical order
mylist.sort(key=str.lower)
# load a file `file.py` into the python console
exec(compile(open('file.py').read(), 'file.py', 'exec'))
# check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`
"""test.mp3""".endswith(('.mp3', '.avi'))
# unpack first and second bytes of byte string `pS` into integer
struct.unpack('h', pS[0:2])
# check if all string elements in list `words` are upper-cased
print(all(word[0].isupper() for word in words))
# convert dataframe `df` to integer-type sparse object
df.to_sparse(0)
# check if object `a` has property 'property'
if hasattr(a, 'property'):
    pass
# get the value of attribute 'property' of object `a` with default value 'default value'
getattr(a, 'property', 'default value')
# create a list of all unique characters in string 'aaabcabccd'
"""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))
# get list of all unique characters in a string 'aaabcabccd'
list(set('aaabcabccd'))
# List of all unique characters in a string?
"""""".join(set('aaabcabccd'))
# find the index of sub string 'World' in `x`
x.find('World')
# find the index of sub string 'Aloha' in `x`
x.find('Aloha')
# find the index of sub string 'cc' in string 'sdfasdf'
'sdfasdf'.index('cc')
# find the index of sub string 'df' in string 'sdfasdf'
'sdfasdf'.index('df')
# find the index of sub string 'a' in string `str`
str.find('a')
# find the index of sub string 'g' in string `str`
str.find('g')
# find the index of sub string 's' in string `str` starting from index 11
str.find('s', 11)
# find the index of sub string 's' in string `str` starting from index 15
str.find('s', 15)
# find the index of sub string 's' in string `str` starting from index 16
str.find('s', 16)
# find the index of sub string 's' in string `str` starting from index 11 and ending at index 14
str.find('s', 11, 14)
# reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values
sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)
# Sort dictionary `u` in ascending order based on second elements of its values
sorted(list(u.items()), key=lambda v: v[1])
# reverse sort dictionary `d` based on its values
sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)
# sorting a defaultdict `d` by value
sorted(list(d.items()), key=lambda k_v: k_v[1])
# abort the execution of the script using message 'aa! errors!'
sys.exit('aa! errors!')
# How to get yesterday in python
datetime.datetime.now() - datetime.timedelta(days=1)
# create a pandas dataframe `df` from elements of a dictionary `nvalues`
df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})
# find href value that has string 'follow?page' inside it
print(soup.find('a', href=re.compile('.*follow\\?page.*')))
# Get the average values from two numpy arrays `old_set` and `new_set`
np.mean(np.array([old_set, new_set]), axis=0)
# create a set containing all keys' names from dictionary `LoD`
{k for d in LoD for k in list(d.keys())}
# create a set containing all keys names from list of dictionaries `LoD`
set([i for s in [list(d.keys()) for d in LoD] for i in s])
# extract all keys from a list of dictionaries `LoD`
[i for s in [list(d.keys()) for d in LoD] for i in s]
# create a list containing the digits values from binary string `x` as elements
[int(d) for d in str(bin(x))[2:]]