text
stringlengths
4
1.08k
coalesce non-word-characters in string `a`,"print(re.sub('(\\W)\\1+', '\\1', a))"
"open 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')"
create 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)]"
"adding a 1-d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3-d array `np.zeros((6, 9, 20))`","np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]"
"add 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))"
get the list with the highest sum value in list `x`,"print(max(x, key=sum))"
sum 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')"
multiply 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()"
"sort 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')"")"
invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])"
print list of items `myList`,print('\n'.join(str(p) for p in myList))
update the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`,mydic.update({i: o['name']})
split a `utf-8` encoded string `stru` into a list of characters,list(stru.decode('utf-8'))
convert utf-8 with bom string `s` to utf-8 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')"
restart a computer after `900` seconds using subprocess,"subprocess.call(['shutdown', '/r', '/t', '900'])"
shutdown a computer using subprocess,"subprocess.call(['shutdown', '/s'])"
abort a computer shutdown using subprocess,"subprocess.call(['shutdown', '/a '])"
logoff computer having windows operating system using python,"subprocess.call(['shutdown', '/l '])"
shutdown and restart a computer running windows from script,"subprocess.call(['shutdown', '/r'])"
erase the contents of a file `filename`,"open('filename', 'w').close()"
convert dataframe `df` to list of dictionaries including the index values,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)]"
sort dict `data` by value,"sorted(data, key=data.get)"
Sort a dictionary `data` by its values,sorted(data.values())
Get a list of pairs of key-value sorted by values in dictionary `data`,"sorted(list(data.items()), key=lambda x: x[1])"
display current time,now = datetime.datetime.now().strftime('%H:%M:%S')
find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`,"""""""foo bar bar bar"""""".replace('bar', 'XXX', 1).find('bar')"
check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`,"set(['stackoverflow', 'google']).issubset(sites)"
replace string ' and ' in string `stuff` with character '/',"stuff.replace(' and ', '/')"
"Save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`","np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])"
current time,t = datetime.datetime.now()
subtract 1 hour and 10 minutes from time object `t`,"(t - datetime.timedelta(hours=1, minutes=10))"
add 1 hour and 2 minutes to time object `t`,"dt = datetime.datetime.combine(datetime.date.today(), t)"
subtract 5 hours from the time object `dt`,dt -= datetime.timedelta(hours=5)
encode string `data` using hex 'hex' encoding,print(data.encode('hex'))
Return the decimal value for each hex character in data `data`,print(' '.join([str(ord(a)) for a in data]))
Get all the items from a list of tuple 'l' where second item in tuple is '1'.,[x for x in l if x[1] == 1]
Create array `a` containing integers from stdin,a.fromlist([int(val) for val in stdin.read().split()])
place '\' infront of each non-letter char in string `line`,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))"
Get all `a` tags where the text starts with value `some text` using regex,"doc.xpath(""//a[starts-with(text(),'some text')]"")"
convert a list of lists `a` into list of tuples of appropriate elements form nested lists,zip(*a)
convert a list of strings `lst` to list of integers,"[map(int, sublist) for sublist in lst]"
convert strings in list-of-lists `lst` to ints,[[int(x) for x in sublist] for sublist in lst]
get index of elements in array `A` that occur in another array `B`,"np.where(np.in1d(A, B))[0]"
create a list where each element is a dictionary with keys 'key1' and 'key2' and values corresponding to each value in the lists referenced by keys 'key1' and 'key2' in dictionary `d`,"[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]"
Get Last Day of the first month in 2002,"calendar.monthrange(2002, 1)"
Get Last Day of the second month in 2002,"calendar.monthrange(2008, 2)"
Get Last Day of the second month in 2100,"calendar.monthrange(2100, 2)"
Get Last Day of the month `month` in year `year`,"calendar.monthrange(year, month)[1]"
Get Last Day of the second month in year 2012,"monthrange(2012, 2)"
Get Last Day of the first month in year 2000,"(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))"
"Calling an external command ""ls -l""",from subprocess import call
"Calling an external command ""some_command with args""",os.system('some_command with args')
"Calling an external command ""some_command < input_file | another_command > output_file""",os.system('some_command < input_file | another_command > output_file')
"Calling an external command ""some_command with args""",stream = os.popen('some_command with args')
"Calling an external command ""echo Hello World""","print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())"
"Calling an external command ""echo Hello World""",print(os.popen('echo Hello World').read())
"Calling an external command ""echo Hello World""","return_code = subprocess.call('echo Hello World', shell=True)"
"Calling an external command ""ls -l""","call(['ls', '-l'])"
decode url `url` with utf8 and print it,print(urllib.parse.unquote(url).decode('utf8'))
decode a urllib escaped url string `url` with `utf8`,url = urllib.parse.unquote(url).decode('utf8')
delete letters from string '12454v',""""""""""""".join(filter(str.isdigit, '12454v'))"
Update row values for a column `Season` using vectorized string operation in pandas,df['Season'].str.split('-').str[0].astype(int)
sort a list of tuples `my_list` by second parameter in the tuple,my_list.sort(key=lambda x: x[1])
find indexes of all occurrences of a substring `tt` in a string `ttt`,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]"
find all occurrences of a substring in a string,"[m.start() for m in re.finditer('test', 'test test test test')]"
split string `s` based on white spaces,"re.findall('\\s+|\\S+', s)"
"set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`","rdata.set_index(['race_date', 'track_code', 'race_number'])"
recursively go through all subdirectories and files in `rootdir`,"for (root, subFolders, files) in os.walk(rootdir):
pass"
sort a list of dictionary values by 'date' in reverse order,"list.sort(key=lambda item: item['date'], reverse=True)"
display first 5 characters of string 'aaabbbccc',"""""""{:.5}"""""".format('aaabbbccc')"
unpack hexadecimal string `s` to a list of integer values,"struct.unpack('11B', s)"
"finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it","[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']"
"generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`","print(list(itertools.product([1, 2, 3], [4, 5, 6])))"
"generate all permutations of a list `[1, 2, 3]`","itertools.permutations([1, 2, 3])"
substitute occurrences of unicode regex pattern u'\\p{P}+' with empty string '' in string `text`,"return re.sub('\\p{P}+', '', text)"
manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened',raise ValueError('A very specific bad thing happened')
"throw an exception ""I know Python!""",raise Exception('I know Python!')
"Manually throw an exception ""I know python!""",raise Exception('I know python!')
"throw a ValueError with message 'represents a hidden bug, do not catch this'","raise ValueError('represents a hidden bug, do not catch this')"
throw an Exception with message 'This is the exception you expect to handle',raise Exception('This is the exception you expect to handle')
"throw a value error with message 'A very specific bad thing happened', 'foo', 'bar', 'baz'",raise ValueError('A very specific bad thing happened')
throw a runtime error with message 'specific message',raise RuntimeError('specific message')
"throw an assertion error with message ""Unexpected value of 'distance'!"", distance","raise AssertionError(""Unexpected value of 'distance'!"", distance)"
"if Selenium textarea element `foo` is not empty, clear the field",driver.find_element_by_id('foo').clear()
clear text from textarea 'foo' with selenium,driver.find_element_by_id('foo').clear()
convert a number 2130706433 to ip string,"socket.inet_ntoa(struct.pack('!L', 2130706433))"
"Rearrange the columns 'a','b','x','y' of pandas DataFrame `df` in mentioned sequence 'x' ,'y','a' ,'b'","df = df[['x', 'y', 'a', 'b']]"
call base class's __init__ method from the child class `ChildClass`,"super(ChildClass, self).__init__(*args, **kwargs)"