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