prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
heck if list `a` is empty | if (not a):
pass |
heck if list `seq` is empty | if (not seq):
pass |
heck if list `li` is empty | if (len(li) == 0):
pass |
eate a list containing the indices of elements greater than 4 in list `a` | [i for i, v in enumerate(a) if v > 4] |
everse list `yourdata` | sorted(yourdata, reverse=True) |
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) |
list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey' | yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True) |
emove decimal points in pandas data frame using round | df.round() |
Get data from matplotlib plo | gca().get_lines()[n].get_xydata() |
get the maximum 2 values per row in array `A` | A[:, -2:] |
Get value for username parameter in GET request in Django | request.GET.get('username', '') |
prettyprint ordered dictionary `o` | pprint(dict(list(o.items()))) |
Confirm urls in Django properly | url('^$', include('sms.urls')), |
Configure url in django properly | url('^', include('sms.urls')), |
get the tuple in list `a_list` that has the largest item in the second index | max_item = max(a_list, key=operator.itemgetter(1)) |
find tuple in list of tuples `a_list` with the largest second eleme | max(a_list, key=operator.itemgetter(1)) |
esample series `s` into 3 months bins and sum each b | s.resample('3M', how='sum') |
extract elements at indices (1, 2, 5) from a list `a` | [a[i] for i in (1, 2, 5)] |
filter lines from a text file 'textfile' which contain a word 'apple' | [line for line in open('textfile') if 'apple' in line] |
vert a date string `s` to a datetime objec | datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ') |
eading tabdelimited csv file `filename` with pandas on mac | pandas.read_csv(filename, sep='\t', lineterminator='\r') |
eplace only first occurence of string `TEST` from a string `longlongTESTstringTEST` | 'longlongTESTstringTEST'.replace('TEST', '?', 1) |
zip file `pdffile` using its basename as directory name | archive.write(pdffile, os.path.basename(pdffile)) |
eate a dictionary of pairs from a list of tuples `myListOfTuples` | dict(x[1:] for x in reversed(myListOfTuples)) |
btract elements of list `List1` from elements of list `List2` | [(x1 - x2) for x1, x2 in zip(List1, List2)] |
heck if string `string` starts with a number | string[0].isdigit() |
Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') | strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) |
print script's directory | print(os.path.dirname(os.path.realpath(__file__))) |
plit string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[AZ]|$)' | re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text) |
Make a scatter plot using unpacked values of list `li` | plt.scatter(*zip(*li)) |
earrange tuple of tuples `t` | tuple(zip(*t)) |
Get average for every three columns in `df` dataframe | df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean() |
vert a list `L` of ascii values to a string | """""".join(chr(i) for i in L) |
he number of pairs in dictionary `d` whose value equal to `chosen_value` | sum(x == chosen_value for x in list(d.values())) |
he number of values in `d` dictionary that are predicate to function `some_condition` | sum(1 for x in list(d.values()) if some_condition(x)) |
vert double 0.00582811585976 to flo | struct.unpack('f', struct.pack('f', 0.00582811585976)) |
vert datetime.date `dt` to utc timestamp | timestamp = (dt - datetime(1970, 1, 1)).total_seconds() |
lumn `m` in panda dataframe `df` | df.sort('m') |
Sort a data `a` in descending order based on the `modified` attribute of elements using lambda functio | a = sorted(a, key=lambda x: x.modified, reverse=True) |
print the truth value of `a` | print(bool(a)) |
ename `last` row index label in dataframe `df` to `a` | df = df.rename(index={last: 'a'}) |
Fit Kmeans function to a onedimensional array `x` by reshaping it to be a multidimensional array of single value | km.fit(x.reshape(-1, 1)) |
Sort a list of strings 'words' such that items starting with 's' come first. | sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x) |
pen the login site 'http://somesite.com/adminpanel/index.php' in the browser | webbrowser.open('http://somesite.com/adminpanel/index.php') |
fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4 | dict((k, v) for k, v in parent_dict.items() if 2 < k < 4) |
fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4 | dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4) |
wo lists `list1` and `list2` together using lambda functio | [list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))] |
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)) |
zip list `a`, `b`, `c` into a list of tuple | [(x + tuple(y)) for x, y in zip(zip(a, b), c)] |
hanging 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) |
gparse associate zero or more arguments with flag 'file' | parser.add_argument('file', nargs='*') |
get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal | z = [(i == j) for i, j in zip(x, y)] |
eate a list which indicates whether each element in `x` and `y` is identical | [(x[i] == y[i]) for i in range(len(x))] |
Python: Extract numbers from a string | [int(s) for s in re.findall('\\b\\d+\\b', "he33llo 42 I'm a 32 string 30")] |
eate an empty data frame `df2` with index from another data frame `df1` | df2 = pd.DataFrame(index=df1.index) |
pack first and second bytes of byte string `pS` into integer | struct.unpack('h', pS[0:2]) |
print list `t` into a tablelike shape | print('\n'.join(' '.join(map(str, row)) for row in t)) |
Sort Pandas Dataframe by Date | df.sort_values(by='Date') |
heck if a checkbox is checked in selenium python webdriver | driver.find_element_by_name('<check_box_name>').is_selected() |
determine if checkbox with id '<check_box_id>' is checked in selenium python webdriver | driver.find_element_by_id('<check_box_id>').is_selected() |
eplace `0` with `2` in the list `[0, 1, 0, 3]` | [(a if a else 2) for a in [0, 1, 0, 3]] |
Produce a string that is suitable as Unicode literal from string 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s' | 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape') |
Parse a unicode string `M\\N{AMPERSAND}M\\N{APOSTROPHE}s` | 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape') |
vert Unicode codepoint to utf8 hex | chr(int('fd9b', 16)).encode('utf-8') |
e upper case letters to print hex value `value` | print('0x%X' % value) |
get a list `cleaned` that contains all nonempty elements in list `your_list` | cleaned = [x for x in your_list if x] |
eate a slice object using string `string_slice` | slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')]) |
Find all the tags `a` and `div` from Beautiful Soup object `soup` | soup.find_all(['a', 'div']) |
get the name of function `func` as a string | print(func.__name__) |
vert dictionary `adict` into string | """""".join('{}{}'.format(key, val) for key, val in sorted(adict.items())) |
vert dictionary `adict` into string | """""".join('{}{}'.format(key, val) for key, val in list(adict.items())) |
py list `old_list` as `new_list` | new_list = old_list[:] |
py list `old_list` as `new_list` | new_list = list(old_list) |
py list `old_list` as `new_list` | new_list = copy.copy(old_list) |
deep copy list `old_list` as `new_list` | new_list = copy.deepcopy(old_list) |
ke a copy of list `old_list` | [i for i in old_list] |
emove frame of legend in plot `plt` | plt.legend(frameon=False) |
Print a emoji from a string `\\ud83d\\ude4f` having surrogate pair | """\\ud83d\\ude4f""".encode('utf-16', 'surrogatepass').decode('utf-16') |
alling a function named 'myfunction' in the module | globals()['myfunction']() |
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()) |
Selenium `driver` click a hyperlink with the pattern a[href^='javascript'] | driver.find_element_by_css_selector("a[href^='javascript']").click() |
e data frame `df` to file `file_name` using pandas, pytho | df.to_pickle(file_name) |
alculate the mean of columns with same name in dataframe `df` | df.groupby(by=df.columns, axis=1).mean() |
list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order | bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True) |
get alpha value `alpha` of a png image `img` | alpha = img.split()[-1] |
w to get the length of words in a sentence? | [len(x) for x in s.split()] |
BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup` | soup.findAll('div', style='width=300px;') |
Execute SQL statement `sql` with values of dictionary `myDict` as parameter | cursor.execute(sql, list(myDict.values())) |
Convert CSV file `Result.csv` to Pandas dataframe using separator ' ' | df.to_csv('Result.csv', index=False, sep=' ') |
pdate the `globals()` dictionary with the contents of the `vars(args)` dictionary | globals().update(vars(args)) |
find all substrings in `mystring` beginning and ending with square bracke | re.findall('\\[(.*?)\\]', mystring) |
Format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places. | print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4)) |
Remove all items from a dictionary `d` where the values are less than `1` | d = dict((k, v) for k, v in d.items() if v > 0) |
Filter dictionary `d` to have items with value greater than 0 | d = {k: v for k, v in list(d.items()) if v > 0} |
vert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe | pd.to_datetime(pd.Series(date_stngs)) |