prompt
stringlengths
4
181
completion
stringlengths
2
232
Split string with comma (,) and remove whitespace from a string 'my_string'
[item.strip() for item in my_string.split(',')]
Get all object attributes of object `obj`
print((obj.__dict__))
Get all object attributes of an objec
dir()
Get all object attributes of an objec
dir()
pygobject center window `window`
window.set_position(Gtk.WindowPosition.CENTER)
hange the size of the sci notation to '30' above the y axis in matplotlib `plt`
plt.rc('font', **{'size': '30'})
heck if datafram `df` has any NaN vlaue
df.isnull().values.any()
pack the arguments out of list `params` to function `some_func`
some_func(*params)
decode encodeuricomponent in GAE
urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')
get proportion of rows in dataframe `trace_df` whose values for column `ratio` are greater than 0
(trace_df['ratio'] > 0).mean()
vert a set of tuples `queryresult` to a string `emaillist`
emaillist = '\n'.join(item[0] for item in queryresult)
vert a set of tuples `queryresult` to a list of string
[item[0] for item in queryresult]
vert a list of tuples `queryresult` to a string from the first indexes.
emaillist = '\n'.join([item[0] for item in queryresult])
get the widget which has currently the focus in tkinter instance `window2`
print(('focus object class:', window2.focus_get().__class__))
alize a list `a` with `10000` items and each item's value `0`
a = [0] * 10000
Keep only unique words in list of words `words` and join into string
print(' '.join(sorted(set(words), key=words.index)))
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)
lowercase keys and values in dictionary `{'My Key': 'My Value'}`
{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}
lowercase all keys and values in dictionary `{'My Key': 'My Value'}`
dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())
Convert each key,value pair in a dictionary `{'My Key': 'My Value'}` to lowercase
dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())
g the lists in list of lists `data`
[sorted(item) for item in data]
SQLite get a list of column names from cursor object `cursor`
names = list(map(lambda x: x[0], cursor.description))
get the absolute path of a running python scrip
os.path.abspath(__file__)
2d array `matrix` by row with index 1
sorted(matrix, key=itemgetter(1))
Get all indexes of a letter `e` from a string `word`
[index for index, letter in enumerate(word) if letter == 'e']
decode utf8 code `x` into a raw unicode literal
print(str(x).decode('raw_unicode_escape'))
plit string 'abcdefg' into a list of character
re.findall('\\w', 'abcdefg')
heck whether a file `fname` ex
os.path.isfile(fname)
heck whether file /path/to/file ex
my_file = Path('/path/to/file') if my_file.is_file(): pass
heck whether file `file_path` ex
os.path.exists(file_path)
heck whether a file /etc/password.txt ex
print(os.path.isfile('/etc/password.txt'))
heck whether a file /etc ex
print(os.path.isfile('/etc'))
heck whether a path /does/not/exist ex
print(os.path.exists('/does/not/exist'))
heck whether a file /does/not/exist ex
print(os.path.isfile('/does/not/exist'))
heck whether a path /etc ex
print(os.path.exists('/etc'))
heck whether a path /etc/password.txt ex
print(os.path.exists('/etc/password.txt'))
plit string a;bcd,ef g on delimiters ';' and ','
"""a;bcd,ef g""".replace(';', ' ').replace(',', ' ').split()
get a list each value `i` in the implicit tuple `range(3)`
list(i for i in range(3))
dd field names as headers in csv constructor `writer`
writer.writeheader()
flatten a tuple `l`
[(a, b, c) for a, (b, c) in l]
vert 3652458 to string represent a 32bit hex number
"""0x{0:08X}""".format(3652458)
vert a python dictionary `d` to a list of tuple
[(v, k) for k, v in list(d.items())]
vert dictionary of pairs `d` to a list of tuple
[(v, k) for k, v in d.items()]
vert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple eleme
[(v, k) for k, v in a.items()]
vert a python dictionary 'a' to a list of tuple
[(k, v) for k, v in a.items()]
vert a list of hex byte strings `['BB', 'A7', 'F6', '9E']` to a list of hex integer
[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]
vert the elements of list `L` from hex byte strings to hex integer
[int(x, 16) for x in L]
gn values to two variables, `var1` and `var2` from user input response to `'Enter two numbers here: ` split on whitespace
var1, var2 = input('Enter two numbers here: ').split()
Filter a json from a keyvalue pair as `{'fixed_key_1': 'foo2'}` in Django
Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
eate a list containing a four elements long tuples of permutations of binary value
itertools.product(list(range(2)), repeat=4)
get yesterday's date as a string in `YYYYMMDD` format using timedel
(datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
Get the dot product of matrix `[1,0,0,1,0,0]` and matrix `[[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]`
np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])
vert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%Y'
df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')
mporting file `file` from folder '/path/to/application/app/folder'
sys.path.insert(0, '/path/to/application/app/folder') import file
do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`
x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')
Create a default empty json object if no json is available in request parameter `mydata`
json.loads(request.POST.get('mydata', '{}'))
get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))
lice 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 subl
[input[i:i + n] for i in range(0, len(input), n)]
Sort list `keys` based on its elements' dotseperated number
keys.sort(key=lambda x: map(int, x.split('.')))
Sort a list of integers `keys` where each value is in string form
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
vert a 3d array `img` of dimensions 4x2x3 to a 2d array of dimensions 3x8
img.transpose(2, 0, 1).reshape(3, -1)
eplacing 'ABC' and 'AB' values in column 'BrandName' of dataframe `df` with 'A'
df['BrandName'].replace(['ABC', 'AB'], 'A')
eplace values `['ABC', 'AB']` in a column 'BrandName' of pandas dataframe `df` with another value 'A'
df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')
Subtract the mean of each row in dataframe `df` from the corresponding row's eleme
df.sub(df.mean(axis=1), axis=0)
emove all nonalphabet chars from string `s`
"""""".join([i for i in s if i.isalpha()])
plit a string `s` into integer
l = (int(x) for x in s.split())
plit a string `42 0` by white spaces.
"""42 0""".split()
w to split a string into integers in Python?
map(int, '42 0'.split())
get indexes of all true boolean values from a list `bool_list`
[i for i, elem in enumerate(bool_list, 1) if elem]
group dataframe `data` entries by year value of the date in column 'date'
data.groupby(data['date'].map(lambda x: x.year))
Get the indices in array `b` of each element appearing in array `a`
np.in1d(b, a).nonzero()[0]
display current time in readable form
time.strftime('%l:%M%p %z on %b %d, %Y')
ate xaxis text labels of plot `ax` 45 degree
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
ppend array of strings `['x', 'x', 'x']` into one string
"""""".join(['x', 'x', 'x'])
etrieve all items in an numpy array 'x' except the item of the index 1
x[(np.arange(x.shape[0]) != 1), :, :]
pull a value with key 'name' from a json object `item`
print(item['name'])
ead a file from redirected stdin and save to variable `result`
result = sys.stdin.read()
Get all the texts without tags from beautiful soup object `soup`
"""""".join(soup.findAll(text=True))
extract all rows from dataframe `data` where the value of column 'Value' is True
data[data['Value'] == True]
emoving duplicate characters from a string variable foo
"""""".join(set(foo))
bjects in model `Profile` based on Theirs `reputation` attribute
sorted(Profile.objects.all(), key=lambda p: p.reputation)
flatten a dataframe df to a l
df.values.flatten()
list `users` using values associated with key 'id' according to elements in list `order`
users.sort(key=lambda x: order.index(x['id']))
a python list of dictionaries `users` by a given list `order` of ids 'id' with the desired order
users.sort(key=lambda x: order.index(x['id']))
equest URI '<MY_URI>' and pass authorization token 'TOK:<MY_TOKEN>' to the header
r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})
escape a backslashescaped string in `Hello,\\nworld!`
print('"Hello,\\nworld!"'.decode('string_escape'))
h regex pattern 'a*?bc*?' on string 'aabcc' with DOTALL enabled
re.findall('a*?bc*?', 'aabcc', re.DOTALL)
get second array column length of array `a`
a.shape[1]
e operations like max/min within a row to a dataframe 'd' in pand
d.apply(lambda row: min([row['A'], row['B']]) - row['C'], axis=1)
mber of occurrences of a substring 'ab' in a string abcdabcva
"""abcdabcva""".count('ab')
get a list of values with key 'key' from a list of dictionaries `l`
[d['key'] for d in l if 'key' in d]
get a list of values for key 'key' from a list of dictionaries `l`
[d['key'] for d in l]
get a list of values for key key from a list of dictionaries in `l`
[d['key'] for d in l]
der a list of lists `l1` by the first value
l1.sort(key=lambda x: int(x[0]))
der a list of lists `[[1, 'mike'], [1, 'bob']]` by the first value of individual l
sorted([[1, 'mike'], [1, 'bob']])
eplace a string `Abc` in case sensitive way using maketr
"""Abc""".translate(maketrans('abcABC', 'defDEF'))
dictionary `d` to string, custom form
"""<br/>""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])
how to write a unicode csv in Python 2.7
self.writer.writerow([str(s).encode('utf-8') for s in row])