prompt
stringlengths
4
181
completion
stringlengths
2
232
get digits in string `my_string`
"""""".join(c for c in my_string if c.isdigit())
plit string `str1` on one or more spaces with a regular expressio
re.split(' +', str1)
python split string based on regular expressio
re.findall('\\S+', str1)
Evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr
getattr(getattr(myobject, 'id', None), 'number', None)
vert generator object to a dictionary
{i: (i * 2) for i in range(10)}
vert generator object to a dictionary
dict((i, i * 2) for i in range(10))
Matplotlib clear the current axes.
plt.cla()
plit string `s` into float values and write sum to `total`
total = sum(float(item) for item in s.split(','))
Convert ascii value 'P' to binary
bin(ord('P'))
print a string after a specific substring ', ' in string `my_string `
print(my_string.split(', ', 1)[1])
get value of key `post code` associated with first index of key `places` of dictionary `data`
print(data['places'][0]['post code'])
emove colon character surrounded by vowels letters in string `word`
word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)
extract data field 'bar' from json objec
json.loads('{"foo": 42, "bar": "baz"}')['bar']
Convert JSON array `array` to Python objec
data = json.loads(array)
Convert JSON array `array` to Python objec
data = json.loads(array)
pars a string 'http://example.org/#comments' to extract hashtags into an array
re.findall('#(\\w+)', 'http://example.org/#comments')
do a boolean check if a string `lestring` contains any of the items in list `lelist`
any(e in lestring for e in lelist)
w to plot two columns of a pandas data frame using points?
df.plot(x='col_name_1', y='col_name_2', style='o')
Parsing HTML string `html` using BeautifulSoup
parsed_html = BeautifulSoup(html) print(parsed_html.body.find('div', attrs={'class': 'container', }).text)
Parsing webpage 'http://www.google.com/' using BeautifulSoup
page = urllib.request.urlopen('http://www.google.com/') soup = BeautifulSoup(page)
hange figure size to 3 by 4 in matplotlib
plt.figure(figsize=(3, 4))
Strip punctuation from string `s`
s.translate(None, string.punctuation)
django urlsafe base64 decode string `uenc` with decryptio
base64.urlsafe_b64decode(uenc.encode('ascii'))
get the number of all keys in the nested dictionary `dict_list`
len(dict_test) + sum(len(v) for v in dict_test.values())
eturn the conversion of decimal `d` to hex without the '0x' prefix
hex(d).split('x')[1]
eate a list containing digits of number 123 as its eleme
list(str(123))
verting integer `num` to l
[int(x) for x in str(num)]
elect a first form with no name in mechanize
br.select_form(nr=0)
Open file 'sample.json' in read mode with encoding of 'utf8sig'
json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))
load json file 'sample.json' with utf8 bom header
json.loads(open('sample.json').read().decode('utf-8-sig'))
etup a smtp mail server to `smtp.gmail.com` with port `587`
server = smtplib.SMTP('smtp.gmail.com', 587)
evers correlating bits of integer `n`
int('{:08b}'.format(n)[::-1], 2)
dd column `d` to index of dataframe `df`
df.set_index(['d'], append=True)
erating over a dictionary `d` using for loop
for (key, value) in d.items(): pass
erating over a dictionary `d` using for loop
for (key, value) in list(d.items()): pass
erating key and items over dictionary `d`
for (letter, number) in list(d.items()): pass
erating key and items over dictionary `d`
for (k, v) in list(d.items()): pass
get keys and items of dictionary `d`
list(d.items())
get keys and items of dictionary `d` as a l
list(d.items())
erating key and items over dictionary `d`
for (k, v) in list(d.items()): pass
erating key and items over dictionary `d`
for (letter, number) in list(d.items()): pass
erating key and items over dictionary `d`
for (letter, number) in list(d.items()): pass
query all data from table `Task` where the value of column `time_spent` is bigger than 3 hour
session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
mpile Visual Studio project `project.sln` from the command line through pytho
os.system('msbuild project.sln /p:Configuration=Debug')
get max key in dictionary `MyCount`
max(list(MyCount.keys()), key=int)
execute command 'source .bashrc; shopt s expand_aliases; nuke x scriptPath' from python scrip
os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')
get a name of function `my_function` as a string
my_function.__name__
w to get a function name as a string in Python?
my_function.__name__
heck if all values in the columns of a numpy matrix `a` are same
np.all(a == a[(0), :], axis=0)
list `a` in ascending order based on the addition of the second and third elements of each tuple in
sorted(a, key=lambda x: (sum(x[1:3]), x[0]))
a list of tuples `a` by the sum of second and third element of each tuple
sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)
g a list of tuples `lst` by the sum of the second elements onwards, and third element of the tuple
sorted(lst, key=lambda x: (sum(x[1:]), x[0]))
he list of tuples `lst` by the sum of every value except the first and by the first value in reverse order
sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)
dd header 'WWWAuthenticate' in a flask app with value 'Basic realm=test'
response.headers['WWW-Authenticate'] = 'Basic realm="test"'
lear session key 'mykey'
del request.session['mykey']
vert date string '24052010' to date object in format '%d%m%Y'
datetime.datetime.strptime('24052010', '%d%m%Y').date()
Replace nonASCII characters in string `text` with a single space
re.sub('[^\\x00-\\x7F]+', ' ', text)
List of lists into numpy array
numpy.array([[1, 2], [3, 4]])
Get a list `myList` from 1 to 10
myList = [i for i in range(10)]
e regex pattern '((.+?)\\2+)' to split string '44442(2)2(2)44'
[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')]
e regular expression '((\\d)(?:[()]*\\2*[()]*)*)' to split string `s`
[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]
emove the space between subplots in matplotlib.pyplo
fig.subplots_adjust(wspace=0, hspace=0)
Reverse list `x`
x[::-1]
Python JSON encoding
json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})
write a list of strings `row` to csv object `csvwriter`
csvwriter.writerow(row)
Jinja2 formate date `item.date` accorto pattern 'Y M d'
{{(item.date | date): 'Y M d'}}
Split a string `text` with comma, question mark or exclamation by nonconsuming regex using lookbehind
re.split('(?<=[\\.\\?!]) ', text)
eate a regular expression object with the pattern '\xe2\x80\x93'
re.compile('\xe2\x80\x93')
declare an array `variable`
variable = []
declare an array with element 'i'
intarray = array('i')
given list `to_reverse`, reverse the all sublists and the list itself
[sublist[::-1] for sublist in to_reverse[::-1]]
Replace all nonalphanumeric characters in a string
re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
escape special characters without splitting data in array of strings `['I ', u'<', '3s U ', u'&', ' you luvz me']`
"""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])
disable logging while running unit tests in python django
logging.disable(logging.CRITICAL)
dding url `url` to mysql row
cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))
vert column of date objects 'DateObj' in pandas dataframe `df` to strings in new column 'DateStr'
df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
plit string `s` by '@' and get the first eleme
s.split('@')[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 the number of NaN values in each column of dataframe `df`
df.isnull().sum()
eset index of dataframe `df`so that existing index values are transferred into `df`as colum
df.reset_index(inplace=True)
generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`
[x['value'] for x in list_of_dicts]
python getting a list of value from list of dic
[d['value'] for d in l]
python getting a list of value from list of dic
[d['value'] for d in l if 'value' in d]
vert numpy array into python list structure
np.array([[1, 2, 3], [4, 5, 6]]).tolist()
verting string '(1,2,3,4)' to a tuple
ast.literal_eval('(1,2,3,4)')
keep a list `dataList` of lists sorted as it is created by second eleme
dataList.sort(key=lambda x: x[1])
emove duplicated items from list of lists `testdata`
list(map(list, set(map(lambda i: tuple(i), testdata))))
queness for list of lists `testdata`
[list(i) for i in set(tuple(i) for i in testdata)]
django, check if a user is in a group 'Member'
return user.groups.filter(name='Member').exists()
heck if a user `user` is in a group from list of groups `['group1', 'group2']`
return user.groups.filter(name__in=['group1', 'group2']).exists()
Change log level dynamically to 'DEBUG' without restarting the applicatio
logging.getLogger().setLevel(logging.DEBUG)
Concat each values in a tuple `(34.2424, 64.2344, 76.3534, 45.2344)` to get a string
"""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))
wap each pair of characters in string `s`
"""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])
ave current figure to file 'graph.png' with resolution of 1000 dp
plt.savefig('graph.png', dpi=1000)
delete items from list `my_list` if the item exist in list `to_dell`
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
find all the elements that consists value '1' in a list of tuples 'a'
[item for item in a if 1 in item]
find all elements in a list of tuples `a` where the first element of each tuple equals 1
[item for item in a if item[0] == 1]
Get the index value in list `p_list` using enumerate in list comprehensio
{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
how to uniqify a list of dict in pytho
[dict(y) for y in set(tuple(x.items()) for x in d)]