prompt
stringlengths
4
181
completion
stringlengths
2
232
find the magnitude (length) squared of a vector `vf` field
np.einsum('...j,...j->...', vf, vf)
equest http url `url`
r = requests.get(url)
equest http url `url` with parameters `payload`
r = requests.get(url, params=payload)
post request url `url` with parameters `payload`
r = requests.post(url, data=payload)
ke an HTTP post request with data `post_data`
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
django jinja slice list `mylist` by '3:8'
{{(mylist | slice): '3:8'}}
eate dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet'
df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')
get the largest index of the last occurrence of characters '([{' in string `test_string`
max(test_string.rfind(i) for i in '([{')
print 'here is your checkmark: ' plus unicode character u'\u2713'
print('here is your checkmark: ' + '\u2713')
print unicode characters in a string `\u0420\u043e\u0441\u0441\u0438\u044f`
print('\u0420\u043e\u0441\u0441\u0438\u044f')
pads string '5' on the left with 1 zero
print('{0}'.format('5'.zfill(2)))
Remove duplicates elements from list `sequences` and sort it in ascending order
sorted(set(itertools.chain.from_iterable(sequences)))
pandas dataframe `df` column 'a' to l
df['a'].values.tolist()
Get a list of all values in column `a` in pandas data frame `df`
df['a'].tolist()
escaping quotes in string
replace('"', '\\"')
heck if all string elements in list `words` are uppercased
print(all(word[0].isupper() for word in words))
emove items from dictionary `myDict` if the item's value `val` is equal to 42
myDict = {key: val for key, val in list(myDict.items()) if val != 42}
Remove all items from a dictionary `myDict` whose values are `42`
{key: val for key, val in list(myDict.items()) if val != 42}
Determine the byte length of a utf8 encoded string `s`
return len(s.encode('utf-8'))
kill a process with id `process.pid`
os.kill(process.pid, signal.SIGKILL)
get data of columns with Null values in dataframe `df`
df[pd.isnull(df).any(axis=1)]
p everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end
url.split('&')[-1].replace('=', '') + '.html'
Parse a file `sample.xml` using expat parsing in python 3
parser.ParseFile(open('sample.xml', 'rb'))
Exit scrip
sys.exit()
gn value in `group` dynamically to class property `attr`
setattr(self, attr, group)
decode urlencoded string `some_string` to its character equivale
urllib.parse.unquote(urllib.parse.unquote(some_string))
decode a double URL encoded string 'FireShot3%2B%25282%2529.png' to 'FireShot3+(2).png'
urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))
hange flask security register url to `/create_account`
app.config['SECURITY_REGISTER_URL'] = '/create_account'
pen a file `/home/user/test/wsservice/data.pkl` in binary write mode
output = open('/home/user/test/wsservice/data.pkl', 'wb')
emove the last element in list `a`
del a[(-1)]
emove the element in list `a` with index 1
a.pop(1)
emove the last element in list `a`
a.pop()
emove the element in list `a` at index `index`
a.pop(index)
emove the element in list `a` at index `index`
del a[index]
print a celsius symbol on x axis of a plot `ax`
ax.set_xlabel('Temperature (\u2103)')
Print a celsius symbol with matplotlib
ax.set_xlabel('Temperature ($^\\circ$C)')
vert a list of lists `list_of_lists` into a list of strings keeping empty sublists as empty string ''
[''.join(l) for l in list_of_lists]
get a list of all the duplicate items in dataframe `df` using pand
pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)
Delete third row in a numpy array `x`
x = numpy.delete(x, 2, axis=1)
delete first row of array `x`
x = numpy.delete(x, 0, axis=0)
erge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1
pd.concat((df1, df2), axis=1).mean(axis=1)
Get the average values from two numpy arrays `old_set` and `new_set`
np.mean(np.array([old_set, new_set]), axis=0)
Matplotlib change marker size to 500
scatter(x, y, s=500, color='green', marker='h')
Create new list `result` by splitting each item in list `words`
result = [item for word in words for item in word.split(',')]
vert JSON string '20120529T19:30:03.283Z' into a DateTime object using format '%Y%m%dT%H:%M:%S.%fZ'
datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
`True` values associated with key 'one' in dictionary `tadas`
sum(item['one'] for item in list(tadas.values()))
encode a pdf file `pdf_reference.pdf` with `base64` encoding
a = open('pdf_reference.pdf', 'rb').read().encode('base64')
plit string `a` using newline character '\n' as separator
a.rstrip().split('\n')
plit a string `a` with new line character
a.split('\n')[:-1]
eturn http status code 204 from a django view
return HttpResponse(status=204)
heck if 7 is in `a`
(7 in a)
heck if 'a' is in list `a`
('a' in a)
list `results` by keys value 'year'
sorted(results, key=itemgetter('year'))
get current url in selenium webdriver `browser`
print(browser.current_url)
plit string `str` with delimiter '; ' or delimiter ', '
re.split('; |, ', str)
escaping characters in a string with pytho
"""\\u003Cp\\u003E""".decode('unicode-escape')
vert date string `s` in format pattern '%d/%m/%Y' into a timestamp
time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())
vert string '01/12/2011' to an integer timestamp
int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))
get http header of the key 'yourheadername' in flask
request.headers['your-header-name']
elect records of dataframe `df` where the sum of column 'X' for each value in column 'User' is 0
df.groupby('User')['X'].filter(lambda x: x.sum() == 0)
Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0
df.loc[df.groupby('User')['X'].transform(sum) == 0]
Get data from dataframe `df` where column 'X' is equal to 0
df.groupby('User')['X'].transform(sum) == 0
w do I find an element that contains specific text in Selenium Webdriver (Python)?
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
vert pandas group by object to multiindexed dataframe with indices 'Name' and 'Destination'
df.set_index(['Name', 'Destination'])
alesce nonwordcharacters in string `a`
print(re.sub('(\\W)\\1+', '\\1', a))
pen a file $file under Unix
os.system('start "$file"')
Convert a Unicode string `title` to a 'ascii' string
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
Convert a Unicode string `a` to a 'ascii' string
a.encode('ascii', 'ignore')
eate a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg'
files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]
dding a 1d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3d array `np.zeros((6, 9, 20))`
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]
dd array of shape `(6, 9, 20)` to array `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))
w can I launch an instance of an application using Python?
os.system('start excel.exe <path/to/file>')
get the list with the highest sum value in list `x`
print(max(x, key=sum))
m the length of lists in list `x` that are more than 1 item in length
sum(len(y) for y in x if len(y) > 1)
Enclose numbers in quotes in a string `This is number 1 and this is number 22`
re.sub('(\\d+)', '"\\1"', 'This is number 1 and this is number 22')
ltiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`
numpy.dot(numpy.dot(a, m), a)
Django check if an object with criteria `name` equal to 'name' and criteria `title` equal to 'title' exists in model `Entry`
Entry.objects.filter(name='name', title='title').exists()
a nested list by the inverse of element 2, then by element 1
sorted(l, key=lambda x: (-int(x[1]), x[0]))
get domain/host name from request object in Django
request.META['HTTP_HOST']
get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex
re.findall("api\\('(.*?)'", "api('randomkey123xyz987', 'key', 'text')")
voke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to
subprocess.call(['/usr/bin/perl', './uireplace.pl', var])
print list of items `myList`
print('\n'.join(str(p) for p in myList))
pdate the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`
mydic.update({i: o['name']})
plit a `utf8` encoded string `stru` into a list of character
list(stru.decode('utf-8'))
vert utf8 with bom string `s` to utf8 with no bom `u`
u = s.decode('utf-8-sig')
Filter model 'Entry' where 'id' is not equal to 3 in Django
Entry.objects.filter(~Q(id=3))
lookup an attribute in any scope by name 'range'
getattr(__builtins__, 'range')
estart a computer after `900` seconds using subproce
subprocess.call(['shutdown', '/r', '/t', '900'])
hutdown a computer using subproce
subprocess.call(['shutdown', '/s'])
bort a computer shutdown using subproce
subprocess.call(['shutdown', '/a '])
logoff computer having windows operating system using pytho
subprocess.call(['shutdown', '/l '])
hutdown and restart a computer running windows from scrip
subprocess.call(['shutdown', '/r'])
erase the contents of a file `filename`
open('filename', 'w').close()
w to erase the file contents of text file in Python?
open('file.txt', 'w').close()
vert dataframe `df` to list of dictionaries including the index value
df.to_dict('index')
Create list of dictionaries from pandas dataframe `df`
df.to_dict('records')
Group a pandas data frame by monthly frequenct `M` using groupby
df.groupby(pd.TimeGrouper(freq='M'))
divide the members of a list `conversions` by the corresponding members of another list `trials`
[(c / t) for c, t in zip(conversions, trials)]
dict `data` by value
sorted(data, key=data.get)
Sort a dictionary `data` by its value
sorted(data.values())