prompt
stringlengths
4
181
completion
stringlengths
2
232
Clicking a link using selenium using pytho
driver.find_element_by_xpath('xpath').click()
que index values in column 'A' in pandas dataframe `ex`
ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionarie
pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)
find out the number of nonmatched elements at the same index of list `a` and list `b`
sum(1 for i, j in zip(a, b) if i != j)
ke all keys lowercase in dictionary `d`
d = {(a.lower(), b): v for (a, b), v in list(d.items())}
list `list_` based on first element of each tuple and by the length of the second element of each tuple
list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])
m whitespace in string `s`
s.strip()
m whitespace (including tabs) in `s` on the left side
s = s.lstrip()
m whitespace (including tabs) in `s` on the right side
s = s.rstrip()
m characters ' \t\n\r' in `s`
s = s.strip(' \t\n\r')
m whitespaces (including tabs) in string `s`
print(re.sub('[\\s+]', '', s))
Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']
Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])
Change background color in Tkinter
root.configure(background='black')
vert dict `result` to numpy structured array
numpy.array([(key, val) for key, val in result.items()], dtype)
Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'
pd.concat([df_1, df_2.sort_values('y')])
eplace the last occurence of an expression '</div>' with '</bad>' in a string `s`
re.sub('(.*)</div>', '\\1</bad>', s)
get the maximum of 'salary' and 'bonus' values in a dictionary
print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))
Filter Django objects by `author` with ids `1` and `2`
Book.objects.filter(author__id=1).filter(author__id=2)
plit string 'fooxyzbar' based on caseinsensitive matching using string 'XYZ'
re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')
get list of sums of neighboring integers in string `example`
[sum(map(int, s)) for s in example.split()]
Get all the keys from dictionary `y` whose value is `1`
[i for i in y if y[i] == 1]
verting byte string `c` in unicode string
c.decode('unicode_escape')
pivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`
pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')
dd key item3 and value 3 to dictionary `default_data `
default_data['item3'] = 3
dd key item3 and value 3 to dictionary `default_data `
default_data.update({'item3': 3, })
dd key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`
default_data.update({'item4': 4, 'item5': 5, })
Get the first and last 3 elements of list `l`
l[:3] + l[-3:]
eset index to default in dataframe `df`
df = df.reset_index(drop=True)
For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.
[a[x].append(b[x]) for x in range(3)]
get canonical path of the filename `path`
os.path.realpath(path)
heck if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`
set(L[0].f.items()).issubset(set(a3.f.items()))
find all the indexes in a Numpy 2D array where the value is 1
zip(*np.where(a == 1))
w to find the index of a value in 2d array in Python?
np.where(a == 1)
Collapse hierarchical column index to level 0 in dataframe `df`
df.columns = df.columns.get_level_values(0)
eate a matrix from a list `[1, 2, 3]`
x = scipy.matrix([1, 2, 3]).transpose()
dd character '@' after word 'get' in string `text`
text = re.sub('(\\bget\\b)', '\\1@', text)
get a numpy array that contains the element wise minimum of three 3x1 array
np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)
dd a column 'new_col' to dataframe `df` for index in range
df['new_col'] = list(range(1, len(df) + 1))
et environment variable 'DEBUSSY' equal to 1
os.environ['DEBUSSY'] = '1'
Get a environment variable `DEBUSSY`
print(os.environ['DEBUSSY'])
et environment variable 'DEBUSSY' to '1'
os.environ['DEBUSSY'] = '1'
pdate dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`
b.update(d)
get all the values in column `b` from pandas data frame `df`
df['b']
ke a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)
ebar = plt.errorbar(x, y, yerr=err, ecolor='y')
find all files with extension '.c' in directory `folder`
results += [each for each in os.listdir(folder) if each.endswith('.c')]
dd unicode string '1' to UTF8 decoded string '\xc2\xa3'
print('\xc2\xa3'.decode('utf8') + '1')
lowercase the string obtained by replacing the occurrences of regex pattern '(?<=[az])([AZ])' in string `s` with eplacement '\\1'
re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()
Setting stacksize in a python scrip
os.system('ulimit -s unlimited; some_executable')
format a string `num` using string formatting
"""{0:.3g}""".format(num)
ppend the first element of array `a` to array `a`
numpy.append(a, a[0])
eturn the column for value 38.15 in dataframe `df`
df.ix[:, (df.loc[0] == 38.15)].columns
erge 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'])
load a json data `json_string` into variable `json_data`
json_data = json.loads(json_string)
vert radians 1 to degree
math.cos(math.radians(1))
he number of integers in list `a`
sum(isinstance(x, int) for x in a)
eplacing '\u200b' with '*' in a string using regular expressio
'used\u200b'.replace('\u200b', '*')
function 'SudsMove' simultaneously
threading.Thread(target=SudsMove).start()
m of squares values in a list `l`
sum(i * i for i in l)
alculate the sum of the squares of each value in list `l`
sum(map(lambda x: x * x, l))
Create a dictionary `d` from list `iterable`
d = dict(((key, value) for (key, value) in iterable))
Create a dictionary `d` from list `iterable`
d = {key: value for (key, value) in iterable}
Create a dictionary `d` from list of key value pairs `iterable`
d = {k: v for (k, v) in iterable}
d off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal place
df.round({'Alabama_exp': 2, 'Credit_exp': 3})
Make function `WRITEFUNCTION` output nothing in curl `p`
p.setopt(pycurl.WRITEFUNCTION, lambda x: None)
eturn a random word from a word list 'words'
print(random.choice(words))
Find a max value of the key `count` in a nested dictionary `d`
max(d, key=lambda x: d[x]['count'])
get list of string elements in string `data` delimited by commas, putting `0` in place of empty string
[(int(x) if x else 0) for x in data.split(',')]
plit string `s` into a list of strings based on ',' then replace empty strings with zero
""",""".join(x or '0' for x in s.split(','))
egular expression match nothing
re.compile('$^')
egular expression syntax for not to match anything
re.compile('.\\A|.\\A*|.\\A+')
eate a regular expression object with a pattern that will match nothing
re.compile('a^')
drop all columns in dataframe `df` that holds a maximum value bigger than 0
df.columns[df.max() > 0]
heck if date `yourdatetime` is equal to today's date
yourdatetime.date() == datetime.today().date()
print bold text 'Hello'
print('\x1b[1m' + 'Hello')
emove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv'
re.sub('.{20}(.mkv)', '\\1', 'unique12345678901234567890.mkv')
Define a list with string values `['a', 'c', 'b', 'obj']`
['a', 'c', 'b', 'obj']
bstitute multiple whitespace with single whitespace in string `mystring`
""" """.join(mystring.split())
print a floating point number 2.345e67 without any truncatio
print('{:.100f}'.format(2.345e-67))
Check if key 'key1' in `dict`
('key1' in dict)
Check if key 'a' in `d`
('a' in d)
Check if key 'c' in `d`
('c' in d)
Check if a given key 'key1' exists in dictionary `dict`
if ('key1' in dict): pass
Check if a given key `key` exists in dictionary `d`
if (key in d): pass
eate a django query for a list of values `1, 4, 7`
Blog.objects.filter(pk__in=[1, 4, 7])
ead a binary file 'test/test.pdf'
f = open('test/test.pdf', 'rb')
ert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46
format(12345678.46, ',').replace(',', ' ').replace('.', ',')
Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
alculate ratio of sparsity in a numpy array `a`
np.isnan(a).sum() / np.prod(a.shape)
everse sort items in default dictionary `cityPopulation` by the third item in each key's list of value
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 value
sorted(list(u.items()), key=lambda v: v[1])
everse sort dictionary `d` based on its value
sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)
g a defaultdict `d` by value
sorted(list(d.items()), key=lambda k_v: k_v[1])
pen a file 'bundledresource.jpg' in the same directory as a python scrip
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
pen the file 'words.txt' in 'rU' mode
f = open('words.txt', 'rU')
divide the values with same keys of two dictionary `d1` and `d2`
{k: (float(d2[k]) / d1[k]) for k in d2}
divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`
{k: (d2[k] / d1[k]) for k in list(d1.keys()) & 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)
write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%Y%m%d`
df.to_csv(filename, date_format='%Y%m%d')
emove a key 'key' from a dictionary `my_dict`
my_dict.pop('key', None)
eplace NaN values in array `a` with zero
b = np.where(np.isnan(a), 0, a)