prompt
stringlengths
4
181
completion
stringlengths
2
232
Concatenate elements of a list 'x' of multiple integers to a single integer
sum(d * 10 ** i for i, d in enumerate(x[::-1]))
vert a list of integers into a single integer
r = int(''.join(map(str, x)))
vert a DateTime string back to a DateTime object of format '%Y%m%d %H:%M:%S.%f'
datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')
get the average of a list values for each key in dictionary `d`)
[(i, sum(j) / len(j)) for i, j in list(d.items())]
zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each l
zip([1, 2], [3, 4])
prepend string 'hello' to all items in list 'a'
['hello{0}'.format(i) for i in a]
egex for repeating words in a string `s`
re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)
malize a pandas dataframe `df` by row
df.div(df.sum(axis=1), axis=0)
wap values in a tuple/list inside a list `mylist`
map(lambda t: (t[1], t[0]), mylist)
Swap values in a tuple/list in list `mylist`
[(t[1], t[0]) for t in mylist]
Find next sibling element in Python Selenium?
driver.find_element_by_xpath("//p[@id, 'one']/following-sibling::p")
find all occurrences of the pattern '\\[[^\\]]*\\]|\\([^\\)]*\\)|[^]*|\\S+' within `strs`
re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|"[^"]*"|\\S+', strs)
generate the combinations of 3 from a set `{1, 2, 3, 4}`
print(list(itertools.combinations({1, 2, 3, 4}, 3)))
dd multiple columns `hour`, `weekday`, `weeknum` to pandas data frame `df` from lambda function `lambdafunc`
df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)
BeautifulSoup search string 'Elsie' inside tag 'a'
soup.find_all('a', string='Elsie')
Convert a datetime object `my_datetime` into readable format `%B %d, %Y`
my_datetime.strftime('%B %d, %Y')
parse string `s` to int when string contains a number
int(''.join(c for c in s if c.isdigit()))
dd dictionary `{'class': {'section': 5}}` to key 'Test' of dictionary `dic`
dic['Test'].update({'class': {'section': 5}})
ansforming the string `s` into dictionary
dict(map(int, x.split(':')) for x in s.split(','))
w to select element with Selenium Python xpath
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
find rows matching `(0,1)` in a 2 dimensional numpy array `vals`
np.where((vals == (0, 1)).all(axis=1))
w to delete a record in Django models?
SomeModel.objects.filter(id=id).delete()
build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its item
dict([['two', 2], ['one', 1]])
vert list `l` to dictionary having each two adjacent elements as key/value pair
dict(zip(l[::2], l[1::2]))
gn float 9.8 to variable `GRAVITY`
GRAVITY = 9.8
eparate numbers from characters in string 30m1000n20m
re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')
eparate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+|[A-Z])', '20M10000N80M')
eparate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+)([A-Z])', '20M10000N80M')
Get a list of words from a string `Hello world, my name is...James the 2nd!` removing punctuatio
re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')
Convert string '03:55' into datetime.time objec
datetime.datetime.strptime('03:55', '%H:%M').time()
equest url 'https://www.reporo.com/' without verifying SSL certificate
requests.get('https://www.reporo.com/', verify=False)
Extract values not equal to 0 from numpy array `a`
a[a != 0]
p two lists `keys` and `values` into a dictionary
new_dict = {k: v for k, v in zip(keys, values)}
p two lists `keys` and `values` into a dictionary
dict((k, v) for k, v in zip(keys, values))
p two lists `keys` and `values` into a dictionary
dict([(k, v) for k, v in zip(keys, values)])
find the string matches within parenthesis from a string `s` using regex
m = re.search('\\[(\\w+)\\]', s)
Enable the SO_REUSEADDR socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
ppend the sum of each tuple pair in the grouped list `list1` and list `list2` elements to list `list3`
list3 = [(a + b) for a, b in zip(list1, list2)]
verting hex string `s` to its integer representatio
[ord(c) for c in s.decode('hex')]
list `student_tuples` by second element of each tuple in ascending and third element of each tuple in descending
print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))
get list of duplicated elements in range of 3
[y for x in range(3) for y in [x, x]]
ead the contents of the file 'file.txt' into `txt`
txt = open('file.txt').read()
divide each element in list `myList` by integer `myInt`
myList[:] = [(x / myInt) for x in myList]
python: dots in the name of variable in a format string
"""Name: {0[person.name]}""".format({'person.name': 'Joe'})
eplace white spaces in dataframe `df` with '_'
df.replace(' ', '_', regex=True)
vert date `my_date` to datetime
datetime.datetime.combine(my_date, datetime.time.min)
vert tuple `tst` to string `tst2`
tst2 = str(tst)
get modified time of file `file`
time.ctime(os.path.getmtime(file))
get creation time of file `file`
time.ctime(os.path.getctime(file))
get modification time of file `filename`
t = os.path.getmtime(filename)
get modification time of file `path`
os.path.getmtime(path)
get modified time of file `file`
print(('last modified: %s' % time.ctime(os.path.getmtime(file))))
get the creation time of file `file`
print(('created: %s' % time.ctime(os.path.getctime(file))))
get the creation time of file `path_to_file`
return os.path.getctime(path_to_file)
execute os command ''TASKKILL /F /IM firefox.exe''
os.system('TASKKILL /F /IM firefox.exe')
plit string `string` on whitespaces using a generator
return (x.group(0) for x in re.finditer("[A-Za-z']+", string))
Unpack each value in list `x` to its placeholder '%' in string '%.2f'
""", """.join(['%.2f'] * len(x))
h regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353'
print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))
eplace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`
df['name'].str.replace('\\(.*\\)', '')
eate a list `result` containing elements form list `list_a` if first element of list `list_a` is in list `list_b`
result = [x for x in list_a if x[0] in list_b]
generate all possible string permutations of each two elements in list `['hel', 'lo', 'bye']`
print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])
get a list of items form nested list `li` where third element of each item contains string 'ar'
[x for x in li if 'ar' in x[2]]
Sort lists in the list `unsorted_list` by the element at index 3 of each l
unsorted_list.sort(key=lambda x: x[3])
Log message 'test' on the root logger.
logging.info('test')
Return a subplot axes positioned by the grid definition `1,1,1` using matpotlib
fig.add_subplot(1, 1, 1)
Sort dictionary `x` by value in ascending order
sorted(list(x.items()), key=operator.itemgetter(1))
Sort dictionary `dict1` by value in ascending order
sorted(dict1, key=dict1.get)
Sort dictionary `d` by value in descending order
sorted(d, key=d.get, reverse=True)
Sort dictionary `d` by value in ascending order
sorted(list(d.items()), key=(lambda x: x[1]))
elementwise product of 3d arrays `A` and `B`
np.einsum('ijk,ikl->ijl', A, B)
Print a string `card` with string formatting
print('I have: {0.price}'.format(card))
Write a comment `# Data for Class A\n` to a file object `f`
f.write('# Data for Class A\n')
ve the last item in list `a` to the beginning
a = a[-1:] + a[:-1]
Parse DateTime object `datetimevariable` using format '%Y%m%d'
datetimevariable.strftime('%Y-%m-%d')
Normalize line ends in a string 'mixed'
mixed.replace('\r\n', '\n').replace('\r', '\n')
find the real user home directory using pytho
os.path.expanduser('~user')
dex a list `L` with another list `Idx`
T = [L[i] for i in Idx]
get a list of words `words` of a file 'myfile'
words = open('myfile').read().split()
Get a list of lists with summing the values of the second element from each list of lists `data`
[[sum([x[1] for x in i])] for i in data]
mming the second item in a list of lists of l
[sum([x[1] for x in i]) for i in data]
bjects in `Articles` in descending order of counts of `likes`
Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
eturn a DateTime object with the current UTC date
today = datetime.datetime.utcnow().date()
eate a list containing the multiplication of each elements at the same index of list `lista` and list `listb`
[(a * b) for a, b in zip(lista, listb)]
fetch smilies matching regex pattern '(?::|;|=)(?:)?(?:\\)|\\(|D|P)' in string `s`
re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)
h the pattern '[:;][)(](?![)(])' to the string `str`
re.match('[:;][)(](?![)(])', str)
vert a list of objects `list_name` to json string `json_string`
json_string = json.dumps([ob.__dict__ for ob in list_name])
eate a list `listofzeros` of `n` zero
listofzeros = [0] * n
decode the string 'stringnamehere' to UTF8
stringnamehere.decode('utf-8', 'ignore')
Match regex pattern '((?:A|B|C)D)' on string 'BDE'
re.findall('((?:A|B|C)D)', 'BDE')
Create a key `key` if it does not exist in dict `dic` and append element `value` to value.
dic.setdefault(key, []).append(value)
Get the value of the minimum element in the second column of array `a`
a[np.argmin(a[:, (1)])]
extend dictionary `a` with key/value pairs of dictionary `b`
a.update(b)
emoving key values pairs with key 'mykey1' from a list of dictionaries `mylist`
[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]
Removing key values pairs from a list of dictionarie
[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]
eate 3 by 3 matrix of random number
numpy.random.random((3, 3))
ke new column 'C' in panda dataframe by adding values from other columns 'A' and 'B'
df['C'] = df['A'] + df['B']
eate a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york'
[value for key, value in list(programs.items()) if 'new york' in key.lower()]
ppend a path `/path/to/main_folder` in system path
sys.path.append('/path/to/main_folder')
get all digits in a string `s` after a '[' character
re.findall('\\d+(?=[^[]+$)', s)
python pickle/unpickle a list to/from a file 'afile'
pickle.load(open('afile', 'rb'))