prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
lear terminal screen on window | os.system('cls') |
lear the terminal screen in Linux | os.system('clear') |
execute external commands/script `your_own_script` with csh instead of bash | os.system('tcsh your_own_script') |
execute command 'echo $0' in Z shell | os.system("zsh -c 'echo $0'") |
pdate a list `l1` dictionaries with a key `count` and value from list `l2` | [dict(d, count=n) for d, n in zip(l1, l2)] |
eate a list with the sum of respective elements of the tuples of list `l` | [sum(x) for x in zip(*l)] |
m each value in a list `l` of tuple | map(sum, zip(*l)) |
he number of nonnan elements in a numpy ndarray matrix `data` | np.count_nonzero(~np.isnan(data)) |
Convert each list in list `main_list` into a tuple | map(list, zip(*main_list)) |
django get the value of key 'title' from POST request `request` if exists, else return empty string '' | request.POST.get('title', '') |
heck if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')` | """test.mp3""".endswith(('.mp3', '.avi')) |
plit a string 's' by space while ignoring spaces within square braces and quotes. | re.findall('\\[[^\\]]*\\]|"[^"]*"|\\S+', s) |
get biggest 3 values from each column of the pandas dataframe `data` | data.apply(lambda x: sorted(x, 3)) |
permanently set the current directory to the 'C:/Users/Name/Desktop' | os.chdir('C:/Users/Name/Desktop') |
get all characters between two `$` characters in string `string` | re.findall('\\$([^$]*)\\$', string) |
getting the string between 2 '$' characters in '$sin (x)$ is an function of x' | re.findall('\\$(.*?)\\$', '$sin (x)$ is an function of x') |
Format a date object `str_data` into iso fomr | datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat() |
get element at index 0 of first row and element at index 1 of second row in array `A` | A[[0, 1], [0, 1]] |
bset 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)] |
Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1` | [k for k, v in dictA.items() if v.count('duck') > 1] |
Create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy) | [[2, 3, 4], [2, 3, 4], [2, 3, 4]] |
get an element at index `[1,1]`in a numpy array `arr` | print(arr[1, 1]) |
Set colorbar range from `0` to `15` for pyplot object `quadmesh` in matplotlib | quadmesh.set_clim(vmin=0, vmax=15) |
ead csv file 'my_file.csv' into numpy array | my_data = genfromtxt('my_file.csv', delimiter=',') |
ead csv file 'myfile.csv' into array | df = pd.read_csv('myfile.csv', sep=',', header=None) |
ead csv file 'myfile.csv' into array | np.genfromtxt('myfile.csv', delimiter=',') |
ead csv file 'myfile.csv' into array | np.genfromtxt('myfile.csv', delimiter=',', dtype=None) |
ead the first line of a string `my_string` | my_string.splitlines()[0] |
w do I read the first line of a string? | my_string.split('\n', 1)[0] |
generate a list from a pandas dataframe `df` with the column name and column value | df.values.tolist() |
Replace repeated instances of a character '*' with a single instance in a string 'text' | re.sub('\\*\\*+', '*', text) |
eplace repeated instances of * with a single instance of * | re.sub('\\*+', '*', text) |
ltiply values of dictionary `dict` with their respective values in dictionary `dict2` | dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2) |
Get a random string of length `length` | return ''.join(random.choice(string.lowercase) for i in range(length)) |
Get total number of values in a nested dictionary `food_colors` | sum(len(x) for x in list(food_colors.values())) |
all elements in a nested dictionary `food_colors` | sum(len(v) for v in food_colors.values()) |
pply logical operator 'AND' to all elements in list `a_list` | all(a_list) |
emoving vowel characters 'aeiouAEIOU' from string `text` | """""".join(c for c in text if c not in 'aeiouAEIOU') |
Divide elements in list `a` from elements at the same index in list `b` | [(x / y) for x, y in zip(a, b)] |
h regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123' | re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123') |
pply function `log2` to the grouped values by 'type' in dataframe `df` | df.groupby('type').apply(lambda x: np.mean(np.log2(x['v']))) |
get geys of dictionary `my_dict` that contain any values from list `lst` | [key for key, value in list(my_dict.items()) if set(value).intersection(lst)] |
get list of keys in dictionary `my_dict` whose values contain values from list `lst` | [key for item in lst for key, value in list(my_dict.items()) if item in value] |
Sum elements of tuple `b` to their respective elements of each tuple in list `a` | c = [[(i + j) for i, j in zip(e, b)] for e in a] |
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')) |
filter dataframe `grouped` where the length of each group `x` is bigger than 1 | grouped.filter(lambda x: len(x) > 1) |
dictionary of lists `myDict` by the third item in each l | sorted(list(myDict.items()), key=lambda e: e[1][2]) |
Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once | """hello {name}, how are you {name}, welcome {name}""".format(name='john') |
eorder indexed rows `['Z', 'C', 'A']` based on a list in pandas data frame `df` | df.reindex(['Z', 'C', 'A']) |
heck if any values in a list `input_list` is a l | any(isinstance(el, list) for el in input_list) |
get the size of list `items` | len(items) |
get the size of a list `[1,2,3]` | len([1, 2, 3]) |
get the size of object `items` | items.__len__() |
function to get the size of objec | len() |
get the size of list `s` | len(s) |
each row in a pandas dataframe `df` in descending order | df.sort(axis=1, ascending=False) |
Fastest way to sort each row in a pandas dataframe | df.sort(df.columns, axis=1, ascending=False) |
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() |
heck if string 'x' is in list `['x', 'd', 'a', 's', 'd', 's']` | 'x' in ['x', 'd', 'a', 's', 'd', 's'] |
Delete an item with key key from `mydict` | mydict.pop('key', None) |
Delete an item with key `key` from `mydict` | del mydict[key] |
Delete an item with key `key` from `mydict` | try:
del mydict[key]
except KeyError:
pass
try:
del mydict[key]
except KeyError:
pass |
pecify multiple positional arguments with argparse | parser.add_argument('input', nargs='+') |
Plot using the color code `#112233` in matplotlib pyplo | pyplot.plot(x, y, color='#112233') |
p html from string | re.sub('<[^<]+?>', '', text) |
lign values in array `b` to the order of corresponding values in array `a` | a[np.in1d(a, b)] |
plit string jvm.args= Dappdynamics.com=true, Dsomeotherparam=false, on the first occurrence of delimiter '=' | """jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,""".split('=', 1) |
print numbers in list `list` with precision of 3 decimal place | print('[%s]' % ', '.join('%.3f' % val for val in list)) |
format print output of list of floats `l` to print only up to 3 decimal po | print('[' + ', '.join('%5.3f' % v for v in l) + ']') |
print a list of floating numbers `l` using string formatting | print([('%5.3f' % val) for val in l]) |
Change the current directory one level up | os.chdir('..') |
print a unicode string `text` | print(text.encode('windows-1252')) |
vert string representation `s2` of binary string rep of integer to floating point number | struct.unpack('d', struct.pack('Q', int(s2, 0)))[0] |
vert a binary '0b1110' to a float number | float(int('-0b1110', 0)) |
vert a binary `b8` to a float number | struct.unpack('d', b8)[0] |
plot a bar graph from the column 'color' in the DataFrame 'df' | df.colour.value_counts().plot(kind='bar') |
plot categorical data in series `df` with kind `bar` using pandas and matplotlib | df.groupby('colour').size().plot(kind='bar') |
p and split each line `line` on white space | line.strip().split(' ') |
pply functions `mean` and `std` to each column in dataframe `df` | df.groupby(lambda idx: 0).agg(['mean', 'std']) |
dictionary `tag_weight` in reverse order by values cast to integer | sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True) |
find the largest integer less than `x` | int(math.ceil(x)) - 1 |
heck if the string `myString` is empty | if (not myString):
pass |
heck if string `some_string` is empty | if (not some_string):
pass |
heck if string `my_string` is empty | if (not my_string):
pass |
heck if string `my_string` is empty | if some_string:
pass |
erate over a dictionary `d` in sorted order | it = iter(sorted(d.items())) |
erate over a dictionary `d` in sorted order | for (key, value) in sorted(d.items()):
pass |
erate over a dictionary `dict` in sorted order | return sorted(dict.items()) |
erate over a dictionary `dict` in sorted order | return iter(sorted(dict.items())) |
erate over a dictionary `foo` in sorted order | for (k, v) in sorted(foo.items()):
pass |
erate over a dictionary `foo` sorted by the key | for k in sorted(foo.keys()):
pass |
gn the index of the last occurence of `x` in list `s` to the variable `last` | last = len(s) - s[::-1].index(x) - 1 |
atenating values in `list1` to a string | str1 = ''.join(list1) |
atenating values in list `L` to a string, separate by space | ' '.join((str(x) for x in L)) |
atenating values in `list1` to a string | str1 = ''.join((str(e) for e in list1)) |
atenating values in list `L` to a string | makeitastring = ''.join(map(str, L)) |
emove None value from list `L` | [x for x in L if x is not None] |
elect a random element from array `[1, 2, 3]` | random.choice([1, 2, 3]) |
eating a 5x6 matrix filled with `None` and save it as `x` | x = [[None for _ in range(5)] for _ in range(6)] |