rewritten_intent
stringlengths
4
183
intent
stringlengths
11
122
snippet
stringlengths
2
232
question_id
int64
1.48k
42.8M
find the magnitude (length) squared of a vector `vf` field
fastest way to find the magnitude (length) squared of a vector field
np.einsum('...j,...j->...', vf, vf)
19,863,964
request http url `url`
Simple URL GET/POST function
r = requests.get(url)
4,476,373
request http url `url` with parameters `payload`
Simple URL GET/POST function
r = requests.get(url, params=payload)
4,476,373
post request url `url` with parameters `payload`
Simple URL GET/POST function
r = requests.post(url, data=payload)
4,476,373
make an HTTP post request with data `post_data`
Simple URL GET/POST
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
4,476,373
django jinja slice list `mylist` by '3:8'
Slicing a list in Django template
{{(mylist | slice): '3:8'}}
23,422,542
create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet'
pandas HDFStore - how to reopen?
df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')
14,591,855
get the largest index of the last occurrence of characters '([{' in string `test_string`
find last occurence of multiple characters in a string in Python
max(test_string.rfind(i) for i in '([{')
31,950,612
print 'here is your checkmark: ' plus unicode character u'\u2713'
How to print Unicode character in Python?
print('here is your checkmark: ' + '\u2713')
10,569,438
print unicode characters in a string `\u0420\u043e\u0441\u0441\u0438\u044f`
How to print Unicode character in Python?
print('\u0420\u043e\u0441\u0441\u0438\u044f')
10,569,438
pads string '5' on the left with 1 zero
in python how do I convert a single digit number into a double digits string?
print('{0}'.format('5'.zfill(2)))
3,505,831
Remove duplicates elements from list `sequences` and sort it in ascending order
Best / most pythonic way to get an ordered list of unique items
sorted(set(itertools.chain.from_iterable(sequences)))
7,458,689
pandas dataframe `df` column 'a' to list
Pandas DataFrame to list
df['a'].values.tolist()
23,748,995
Get a list of all values in column `a` in pandas data frame `df`
Pandas DataFrame to list
df['a'].tolist()
23,748,995
escaping quotes in string
Escaping quotes in string
replace('"', '\\"')
6,275,762
check if all string elements in list `words` are upper-cased
How to check if a character is upper-case in Python?
print(all(word[0].isupper() for word in words))
3,668,964
remove items from dictionary `myDict` if the item's value `val` is equal to 42
What is the best way to remove a dictionary item by value in python?
myDict = {key: val for key, val in list(myDict.items()) if val != 42}
29,218,750
Remove all items from a dictionary `myDict` whose values are `42`
What is the best way to remove a dictionary item by value in python?
{key: val for key, val in list(myDict.items()) if val != 42}
29,218,750
Determine the byte length of a utf-8 encoded string `s`
How can I determine the byte length of a utf-8 encoded string in Python?
return len(s.encode('utf-8'))
6,714,826
kill a process with id `process.pid`
In Python 2.5, how do I kill a subprocess?
os.kill(process.pid, signal.SIGKILL)
1,064,335
get data of columns with Null values in dataframe `df`
Python Pandas How to select rows with one or more nulls from a DataFrame without listing columns explicitly?
df[pd.isnull(df).any(axis=1)]
14,247,586
strip everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end
Strip random characters from url
url.split('&')[-1].replace('=', '') + '.html'
41,133,414
Parse a file `sample.xml` using expat parsing in python 3
Expat parsing in python 3
parser.ParseFile(open('sample.xml', 'rb'))
1,179,305
Exit script
how do I halt execution in a python script?
sys.exit()
3,376,534
assign value in `group` dynamically to class property `attr`
How to dynamically assign values to class properties in Python?
setattr(self, attr, group)
19,153,328
decode url-encoded string `some_string` to its character equivalents
How to decode a 'url-encoded' string in python
urllib.parse.unquote(urllib.parse.unquote(some_string))
28,431,359
decode a double URL encoded string 'FireShot3%2B%25282%2529.png' to 'FireShot3+(2).png'
How to decode a 'url-encoded' string in python
urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))
28,431,359
change flask security register url to `/create_account`
How to use Flask-Security register view?
app.config['SECURITY_REGISTER_URL'] = '/create_account'
14,793,098
open a file `/home/user/test/wsservice/data.pkl` in binary write mode
IO Error while storing data in pickle
output = open('/home/user/test/wsservice/data.pkl', 'wb')
5,285,181
remove the last element in list `a`
remove an element from a list by index
del a[(-1)]
627,435
remove the element in list `a` with index 1
remove an element from a list by index
a.pop(1)
627,435
remove the last element in list `a`
remove an element from a list by index
a.pop()
627,435
remove the element in list `a` at index `index`
remove an element from a list by index
a.pop(index)
627,435
remove the element in list `a` at index `index`
remove an element from a list by index
del a[index]
627,435
print a celsius symbol on x axis of a plot `ax`
How do I print a Celsius symbol with matplotlib?
ax.set_xlabel('Temperature (\u2103)')
8,440,117
Print a celsius symbol with matplotlib
How do I print a Celsius symbol with matplotlib?
ax.set_xlabel('Temperature ($^\\circ$C)')
8,440,117
convert a list of lists `list_of_lists` into a list of strings keeping empty sub-lists as empty string ''
'List of lists' to 'list' without losing empty lists from the original list of lists
[''.join(l) for l in list_of_lists]
18,022,241
get a list of all the duplicate items in dataframe `df` using pandas
How do I get a list of all the duplicate items using pandas in python?
pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)
14,657,241
Delete third row in a numpy array `x`
deleting rows in numpy array
x = numpy.delete(x, 2, axis=1)
3,877,491
delete first row of array `x`
deleting rows in numpy array
x = numpy.delete(x, 0, axis=0)
3,877,491
merge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1
Merge DataFrames in Pandas using the mean
pd.concat((df1, df2), axis=1).mean(axis=1)
19,490,064
Get the average values from two numpy arrays `old_set` and `new_set`
Average values in two Numpy arrays
np.mean(np.array([old_set, new_set]), axis=0)
18,461,623
Matplotlib change marker size to 500
Changing marker's size in matplotlib
scatter(x, y, s=500, color='green', marker='h')
19,948,732
Create new list `result` by splitting each item in list `words`
split items in list
result = [item for word in words for item in word.split(',')]
12,808,420
convert JSON string '2012-05-29T19:30:03.283Z' into a DateTime object using format '%Y-%m-%dT%H:%M:%S.%fZ'
Converting JSON date string to python datetime
datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
10,805,589
count `True` values associated with key 'one' in dictionary `tadas`
python comprehension loop for dictionary
sum(item['one'] for item in list(tadas.values()))
35,561,743
encode a pdf file `pdf_reference.pdf` with `base64` encoding
How to base64 encode a PDF file in Python
a = open('pdf_reference.pdf', 'rb').read().encode('base64')
208,894
split string `a` using new-line character '\n' as separator
split a string in python
a.rstrip().split('\n')
2,094,176
split a string `a` with new line character
split a string in python
a.split('\n')[:-1]
2,094,176
return http status code 204 from a django view
How can I return HTTP status code 204 from a Django view?
return HttpResponse(status=204)
12,476,452
check if 7 is in `a`
check if a value exist in a list
(7 in a)
7,571,635
check if 'a' is in list `a`
check if a value exist in a list
('a' in a)
7,571,635
sort list `results` by keys value 'year'
Sorting JSON data by keys value
sorted(results, key=itemgetter('year'))
13,438,574
get current url in selenium webdriver `browser`
How do I get current URL in Selenium Webdriver 2 Python?
print(browser.current_url)
15,985,339
split string `str` with delimiter '; ' or delimiter ', '
Python: Split string with multiple delimiters
re.split('; |, ', str)
4,998,629
un-escaping characters in a string with python
Unescaping Characters in a String with Python
"""\\u003Cp\\u003E""".decode('unicode-escape')
5,555,063
convert date string `s` in format pattern '%d/%m/%Y' into a timestamp
Convert string date to timestamp in Python
time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())
9,637,838
convert string '01/12/2011' to an integer timestamp
Convert string date to timestamp in Python
int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))
9,637,838
get http header of the key 'your-header-name' in flask
How to get http headers in flask?
request.headers['your-header-name']
29,386,995
select records of dataframe `df` where the sum of column 'X' for each value in column 'User' is 0
How to subset a data frame using Pandas based on a group criteria?
df.groupby('User')['X'].filter(lambda x: x.sum() == 0)
27,868,020
Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0
How to subset a data frame using Pandas based on a group criteria?
df.loc[df.groupby('User')['X'].transform(sum) == 0]
27,868,020
Get data from dataframe `df` where column 'X' is equal to 0
How to subset a data frame using Pandas based on a group criteria?
df.groupby('User')['X'].transform(sum) == 0
27,868,020
null
How do I find an element that contains specific text in Selenium Webdriver (Python)?
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
12,323,403
convert pandas group by object to multi-indexed dataframe with indices 'Name' and 'Destination'
Convert pandas group by object to multi-indexed Dataframe
df.set_index(['Name', 'Destination'])
14,301,913
coalesce non-word-characters in string `a`
How do I coalesce a sequence of identical characters into just one?
print(re.sub('(\\W)\\1+', '\\1', a))
2,813,829
open a file "$file" under Unix
How to open a file with the standard application?
os.system('start "$file"')
1,679,798
Convert a Unicode string `title` to a 'ascii' string
Convert a Unicode string to a string
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
1,207,457
Convert a Unicode string `a` to a 'ascii' string
Convert a Unicode string to a string
a.encode('ascii', 'ignore')
1,207,457
create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg'
Get a filtered list of files in a directory
files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]
2,225,564
adding a 1-d array `[1, 2, 3, 4, 5, 6, 7, 8, 9]` to a 3-d array `np.zeros((6, 9, 20))`
Adding a 1-D Array to a 3-D array in Numpy
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])[(None), :, (None)]
32,283,692
add array of shape `(6, 9, 20)` to array `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
Adding a 1-D Array to a 3-D array in Numpy
np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))
32,283,692
null
How can I launch an instance of an application using Python?
os.system('start excel.exe <path/to/file>')
247,724
get the list with the highest sum value in list `x`
What is the proper way to print a nested list with the highest value in Python
print(max(x, key=sum))
29,760,130
sum the length of lists in list `x` that are more than 1 item in length
Functional statement in Python to return the sum of certain lists in a list of lists
sum(len(y) for y in x if len(y) > 1)
35,707,224
Enclose numbers in quotes in a string `This is number 1 and this is number 22`
Python - Insert numbers in string between quotes
re.sub('(\\d+)', '"\\1"', 'This is number 1 and this is number 22')
42,364,992
multiply the columns of sparse matrix `m` by array `a` then multiply the rows of the resulting matrix by array `a`
Multiplying Rows and Columns of Python Sparse Matrix by elements in an Array
numpy.dot(numpy.dot(a, m), a)
13,163,145
Django check if an object with criteria `name` equal to 'name' and criteria `title` equal to 'title' exists in model `Entry`
How to check if something exists in a postgresql database using django?
Entry.objects.filter(name='name', title='title').exists()
9,561,243
sort a nested list by the inverse of element 2, then by element 1
Sort a nested list by two elements
sorted(l, key=lambda x: (-int(x[1]), x[0]))
34,705,205
get domain/host name from request object in Django
Django - How to simply get domain name?
request.META['HTTP_HOST']
29,945,684
get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex
Python Regex Get String Between Two Substrings
re.findall("api\\('(.*?)'", "api('randomkey123xyz987', 'key', 'text')")
29,703,793
invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it
Call Perl script from Python
subprocess.call(['/usr/bin/perl', './uireplace.pl', var])
4,682,088
print list of items `myList`
Pythonic way to print list items
print('\n'.join(str(p) for p in myList))
15,769,246
update the dictionary `mydic` with dynamic keys `i` and values with key 'name' from dictionary `o`
update dictionary with dynamic keys and values in python
mydic.update({i: o['name']})
13,860,026
split a `utf-8` encoded string `stru` into a list of characters
how to split a unicode string into list
list(stru.decode('utf-8'))
18,711,384
convert utf-8 with bom string `s` to utf-8 with no bom `u`
Convert UTF-8 with BOM to UTF-8 with no BOM in Python
u = s.decode('utf-8-sig')
8,898,294
Filter model 'Entry' where 'id' is not equal to 3 in Django
How do I do a not equal in Django queryset filtering?
Entry.objects.filter(~Q(id=3))
687,295
lookup an attribute in any scope by name 'range'
How can I lookup an attribute in any scope by name?
getattr(__builtins__, 'range')
2,850,966
restart a computer after `900` seconds using subprocess
How to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/r', '/t', '900'])
14,764,126
shutdown a computer using subprocess
How to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/s'])
14,764,126
abort a computer shutdown using subprocess
How to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/a '])
14,764,126
logoff computer having windows operating system using python
How to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/l '])
14,764,126
shutdown and restart a computer running windows from script
How to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/r'])
14,764,126
erase the contents of a file `filename`
How to erase the file contents of text file in Python?
open('filename', 'w').close()
2,769,061
null
How to erase the file contents of text file in Python?
open('file.txt', 'w').close()
2,769,061
convert dataframe `df` to list of dictionaries including the index values
Pandas DataFrame to List of Dictionaries
df.to_dict('index')
29,815,129
Create list of dictionaries from pandas dataframe `df`
Pandas DataFrame to List of Dictionaries
df.to_dict('records')
29,815,129
Group a pandas data frame by monthly frequenct `M` using groupby
pandas dataframe groupby datetime month
df.groupby(pd.TimeGrouper(freq='M'))
24,082,784
divide the members of a list `conversions` by the corresponding members of another list `trials`
How do I divide the members of a list by the corresponding members of another list in Python?
[(c / t) for c, t in zip(conversions, trials)]
3,731,426
sort dict `data` by value
sort dict by value python
sorted(data, key=data.get)
16,772,071
Sort a dictionary `data` by its values
sort dict by value python
sorted(data.values())
16,772,071