rewritten_intent
stringlengths
4
183
intent
stringlengths
11
122
snippet
stringlengths
2
232
question_id
int64
1.48k
42.8M
Get a list of pairs of key-value sorted by values in dictionary `data`
sort dict by value python
sorted(list(data.items()), key=lambda x: x[1])
16,772,071
null
sort dict by value python
sorted(list(data.items()), key=lambda x: x[1])
16,772,071
display current time
How do I display current time using Python + Django?
now = datetime.datetime.now().strftime('%H:%M:%S')
5,110,352
find the index of the second occurrence of the substring `bar` in string `foo bar bar bar`
Find the nth occurrence of substring in a string
"""foo bar bar bar""".replace('bar', 'XXX', 1).find('bar')
1,883,980
check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`
How do you check the presence of many keys in a Python dictinary?
set(['stackoverflow', 'google']).issubset(sites)
2,813,806
replace string ' and ' in string `stuff` with character '/'
Replace part of a string in Python?
stuff.replace(' and ', '/')
10,037,742
Save array at index 0, index 1 and index 8 of array `np` to tmp file `tmp`
How to use `numpy.savez` in a loop for save more than one array?
np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])
22,712,292
substract 1 hour and 10 minutes from current time
time offset
t = datetime.datetime.now() (t - datetime.timedelta(hours=1, minutes=10))
14,043,934
subtract 1 hour and 10 minutes from time object `t`
time offset
(t - datetime.timedelta(hours=1, minutes=10))
14,043,934
add 1 hour and 2 minutes to time object `t`
time offset
dt = datetime.datetime.combine(datetime.date.today(), t)
14,043,934
subtract 5 hours from the time object `dt`
time offset
dt -= datetime.timedelta(hours=5)
14,043,934
encode string `data` using hex 'hex' encoding
Manipulating binary data in Python
print(data.encode('hex'))
3,059,301
Return the decimal value for each hex character in data `data`
Manipulating binary data in Python
print(' '.join([str(ord(a)) for a in data]))
3,059,301
Get all the items from a list of tuple 'l' where second item in tuple is '1'.
python - iterating over a subset of a list of tuples
[x for x in l if x[1] == 1]
18,131,367
Create array `a` containing integers from stdin
How to read stdin to a 2d python array of integers?
a.fromlist([int(val) for val in stdin.read().split()])
8,192,379
place '\' infront of each non-letter char in string `line`
Is there a way to refer to the entire matched expression in re.sub without the use of a group?
print(re.sub('[_%^$]', '\\\\\\g<0>', line))
26,155,985
Get all `a` tags where the text starts with value `some text` using regex
How to use regular expression in lxml xpath?
doc.xpath("//a[starts-with(text(),'some text')]")
2,755,950
convert a list of lists `a` into list of tuples of appropriate elements form nested lists
Compare elements of a list of lists and return a list
zip(*a)
35,017,035
convert a list of strings `lst` to list of integers
Convert list of strings to int
[map(int, sublist) for sublist in lst]
34,696,853
convert strings in list-of-lists `lst` to ints
Convert list of strings to int
[[int(x) for x in sublist] for sublist in lst]
34,696,853
get index of elements in array `A` that occur in another array `B`
Numpy: find index of elements in one array that occur in another array
np.where(np.in1d(A, B))[0]
28,901,311
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`
Split dictionary of lists into list of dictionaries
[{'key1': a, 'key2': b} for a, b in zip(d['key1'], d['key2'])]
1,780,174
null
Split dictionary of lists into list of dictionaries
map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))
1,780,174
Get Last Day of the first month in 2002
Get Last Day of the Month
calendar.monthrange(2002, 1)
42,950
Get Last Day of the second month in 2002
Get Last Day of the Month
calendar.monthrange(2008, 2)
42,950
Get Last Day of the second month in 2100
Get Last Day of the Month
calendar.monthrange(2100, 2)
42,950
Get Last Day of the month `month` in year `year`
Get Last Day of the Month
calendar.monthrange(year, month)[1]
42,950
Get Last Day of the second month in year 2012
Get Last Day of the Month
monthrange(2012, 2)
42,950
Get Last Day of the first month in year 2000
Get Last Day of the Month
(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))
42,950
Calling an external command "ls -l"
Calling an external command
from subprocess import call
89,228
Calling an external command "some_command with args"
Calling an external command
os.system('some_command with args')
89,228
Calling an external command "some_command < input_file | another_command > output_file"
Calling an external command
os.system('some_command < input_file | another_command > output_file')
89,228
Calling an external command "some_command with args"
Calling an external command
stream = os.popen('some_command with args')
89,228
Calling an external command "echo Hello World"
Calling an external command
print(subprocess.Popen('echo Hello World', shell=True, stdout=subprocess.PIPE).stdout.read())
89,228
Calling an external command "echo Hello World"
Calling an external command
print(os.popen('echo Hello World').read())
89,228
Calling an external command "echo Hello World"
Calling an external command
return_code = subprocess.call('echo Hello World', shell=True)
89,228
Calling an external command "ls"
Calling an external command
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print(line, end=' ') retval = p.wait()
89,228
Calling an external command "ls -l"
Calling an external command
call(['ls', '-l'])
89,228
decode url `url` with utf8 and print it
Url decode UTF-8 in Python
print(urllib.parse.unquote(url).decode('utf8'))
16,566,069
decode a urllib escaped url string `url` with `utf8`
Url decode UTF-8 in Python
url = urllib.parse.unquote(url).decode('utf8')
16,566,069
delete letters from string '12454v'
Delete letters from string
"""""".join(filter(str.isdigit, '12454v'))
14,750,675
Update row values for a column `Season` using vectorized string operation in pandas
applying regex to a pandas dataframe
df['Season'].str.split('-').str[0].astype(int)
25,292,838
sort a list of tuples `my_list` by second parameter in the tuple
Sort tuples based on second parameter
my_list.sort(key=lambda x: x[1])
8,459,231
find indexes of all occurrences of a substring `tt` in a string `ttt`
Find all occurrences of a substring in Python
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
4,664,850
find all occurrences of a substring in a string
Find all occurrences of a substring in Python
[m.start() for m in re.finditer('test', 'test test test test')]
4,664,850
split string `s` based on white spaces
re.split with spaces in python
re.findall('\\s+|\\S+', s)
35,005,907
set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`
Working with set_index in Pandas DataFrame
rdata.set_index(['race_date', 'track_code', 'race_number'])
18,071,222
recursively go through all subdirectories and files in `rootdir`
recursively go through all subdirectories and read files
for (root, subFolders, files) in os.walk(rootdir): pass
13,571,134
sort a list of dictionary values by 'date' in reverse order
sorting a list of dictionary values by date in python
list.sort(key=lambda item: item['date'], reverse=True)
652,291
display first 5 characters of string 'aaabbbccc'
How to truncate a string using str.format in Python?
"""{:.5}""".format('aaabbbccc')
24,076,297
unpack hexadecimal string `s` to a list of integer values
How do I convert a string of hexadecimal values to a list of integers?
struct.unpack('11B', s)
14,961,562
finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it
Finding the index of an item given a list containing it in Python
[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']
176,918
generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`
How to generate all permutations of a list in Python
print(list(itertools.product([1, 2, 3], [4, 5, 6])))
104,420
generate all permutations of a list `[1, 2, 3]`
How to generate all permutations of a list in Python
itertools.permutations([1, 2, 3])
104,420
substitute occurrences of unicode regex pattern u'\\p{P}+' with empty string '' in string `text`
Remove punctuation from Unicode formatted strings
return re.sub('\\p{P}+', '', text)
11,066,400
manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened'
manually throw/raise an exception
raise ValueError('A very specific bad thing happened')
2,052,390
throw an exception "I know Python!"
Manually raising (throwing) an exception
raise Exception('I know Python!')
2,052,390
Manually throw an exception "I know python!"
Manually raising (throwing) an exception
raise Exception('I know python!')
2,052,390
throw a ValueError with message 'represents a hidden bug, do not catch this'
Manually raising (throwing) an exception
raise ValueError('represents a hidden bug, do not catch this')
2,052,390
throw an Exception with message 'This is the exception you expect to handle'
Manually raising (throwing) an exception
raise Exception('This is the exception you expect to handle')
2,052,390
throw a value error with message 'A very specific bad thing happened', 'foo', 'bar', 'baz'
Manually raising (throwing) an exception
raise ValueError('A very specific bad thing happened')
2,052,390
throw a runtime error with message 'specific message'
Manually raising (throwing) an exception
raise RuntimeError('specific message')
2,052,390
throw an assertion error with message "Unexpected value of 'distance'!", distance
Manually raising (throwing) an exception
raise AssertionError("Unexpected value of 'distance'!", distance)
2,052,390
if Selenium textarea element `foo` is not empty, clear the field
Clear text from textarea with selenium
driver.find_element_by_id('foo').clear()
7,732,125
clear text from textarea 'foo' with selenium
Clear text from textarea with selenium
driver.find_element_by_id('foo').clear()
7,732,125
convert a number 2130706433 to ip string
Convert an IP string to a number and vice versa
socket.inet_ntoa(struct.pack('!L', 2130706433))
9,590,965
Rearrange the columns 'a','b','x','y' of pandas DataFrame `df` in mentioned sequence 'x' ,'y','a' ,'b'
How to rearrange Pandas column sequence?
df = df[['x', 'y', 'a', 'b']]
12,329,853
call base class's __init__ method from the child class `ChildClass`
How to call Base Class's __init__ method from the child class?
super(ChildClass, self).__init__(*args, **kwargs)
19,205,916
sum of all values in a python dict `d`
Sum of all values in a Python dict
sum(d.values())
4,880,960
null
Sum of all values in a Python dict
sum(d.values())
4,880,960
convert python dictionary `your_data` to json array
Convert Python dictionary to JSON array
json.dumps(your_data, ensure_ascii=False)
14,661,051
assign an array of floats in range from 0 to 100 to a variable `values`
numpy array assignment using slicing
values = np.array([i for i in range(100)], dtype=np.float64)
23,638,638
sort a list of dictionaries `list_of_dct` by values in an order `order`
Sort a list of dictionary provided an order
sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))
35,078,261
change the case of the first letter in string `s`
how to change the case of first letter of a string?
return s[0].upper() + s[1:]
4,223,923
join list of numbers `[1,2,3,4] ` to string of numbers.
how to change [1,2,3,4] to '1234' using python
"""""".join([1, 2, 3, 4])
2,597,932
delete every non `utf-8` characters from a string `line`
Delete every non utf-8 symbols froms string
line = line.decode('utf-8', 'ignore').encode('utf-8')
26,541,968
execute a command `command ` in the terminal from a python script
How to execute a command in the terminal from a Python script?
os.system(command)
33,065,588
MySQL execute query 'SELECT * FROM foo WHERE bar = %s AND baz = %s' with parameters `param1` and `param2`
Python MySQL Parameterized Queries
c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))
775,296
Parse string `datestr` into a datetime object using format pattern '%Y-%m-%d'
Convert a string to datetime object in python
dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()
5,868,374