# Datasets: neulab /conala

question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
41,067,960
How to convert a list of multiple integers into a single integer?
Concatenate elements of a list 'x' of multiple integers to a single integer
sum(d * 10 ** i for i, d in enumerate(x[::-1]))
41,067,960
How to convert a list of multiple integers into a single integer?
convert a list of integers into a single integer
r = int(''.join(map(str, x)))
4,170,655
how to convert a datetime string back to datetime object?
convert 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')
29,565,452
Averaging the values in a dictionary based on the key
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())]
13,704,860
zip lists in python
zip two lists [1, 2] and [3, 4] into a list of two tuples containing elements at the same index in each list
zip([1, 2], [3, 4])
13,331,419
Prepend the same string to all items in a list
prepend string 'hello' to all items in list 'a'
['hello{0}'.format(i) for i in a]
25,474,338
regex for repeating words in a string in Python
regex for repeating words in a string s
re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)
18,594,469
Normalizing a pandas DataFrame by row
normalize a pandas dataframe df by row
df.div(df.sum(axis=1), axis=0)
13,384,841
swap values in a tuple/list inside a list in python?
swap values in a tuple/list inside a list mylist
map(lambda t: (t[1], t[0]), mylist)
13,384,841
swap values in a tuple/list inside a list in python?
Swap values in a tuple/list in list mylist
[(t[1], t[0]) for t in mylist]
23,887,592
Find next sibling element in Python Selenium?
null
driver.find_element_by_xpath("//p[@id, 'one']/following-sibling::p")
17,352,321
Python splitting string by parentheses
find all occurrences of the pattern '\$[^\$]*\\]|\$$[^\$$]*\\)|"[^"]*"|\\S+' within strs
re.findall('\$[^\$]*\\]|\$$[^\$$]*\\)|"[^"]*"|\\S+', strs)
10,115,967
What's the most memory efficient way to generate the combinations of a set in python?
generate the combinations of 3 from a set {1, 2, 3, 4}
print(list(itertools.combinations({1, 2, 3, 4}, 3)))
30,026,815
Add Multiple Columns to Pandas Dataframe from Function
add multiple columns hour, weekday, weeknum to pandas data frame df from lambda function lambdafunc
df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)
31,958,637
BeautifulSoup - search by text inside a tag
BeautifulSoup search string 'Elsie' inside tag 'a'
soup.find_all('a', string='Elsie')
2,158,347
How do I turn a python datetime into a string, with readable format date?
Convert a datetime object my_datetime into readable format %B %d, %Y
my_datetime.strftime('%B %d, %Y')
17,888,152
Parse string to int when string contains a number + extra characters
parse string s to int when string contains a number
int(''.join(c for c in s if c.isdigit()))
37,855,490
adding new key inside a new key and assigning value in python dictionary
add dictionary {'class': {'section': 5}} to key 'Test' of dictionary dic
dic['Test'].update({'class': {'section': 5}})
4,127,344
Transforming the string representation of a dictionary into a real dictionary
transforming the string s into dictionary
dict(map(int, x.split(':')) for x in s.split(','))
19,035,186
How to select element with Selenium Python xpath
null
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
25,823,608
Find matching rows in 2 dimensional numpy array
find rows matching (0,1) in a 2 dimensional numpy array vals
np.where((vals == (0, 1)).all(axis=1))
3,805,958
How to delete a record in Django models?
null
SomeModel.objects.filter(id=id).delete()
6,900,955
python convert list to dictionary
build a dictionary containing the conversion of each list in list [['two', 2], ['one', 1]] to a key/value pair as its items
dict([['two', 2], ['one', 1]])
6,900,955
python convert list to dictionary
convert list l to dictionary having each two adjacent elements as key/value pair
dict(zip(l[::2], l[1::2]))
18,224,991
how to set global const variables in python
assign float 9.8 to variable GRAVITY
GRAVITY = 9.8
15,103,484
How to use regular expression to separate numbers and characters in strings like "30M1000N20M"
separate numbers from characters in string "30m1000n20m"
re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')
15,103,484
How to use regular expression to separate numbers and characters in strings like "30M1000N20M"
separate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+|[A-Z])', '20M10000N80M')
15,103,484
How to use regular expression to separate numbers and characters in strings like "30M1000N20M"
separate numbers and characters in string '20M10000N80M'
re.findall('([0-9]+)([A-Z])', '20M10000N80M')
7,633,274
Extracting words from a string, removing punctuation and returning a list with separated words in Python
Get a list of words from a string Hello world, my name is...James the 2nd! removing punctuation
re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')
14,295,673
Convert string into datetime.time object
Convert string '03:55' into datetime.time object
datetime.datetime.strptime('03:55', '%H:%M').time()
28,667,684
Python Requests getting SSLerror
request url 'https://www.reporo.com/' without verifying SSL certificates
requests.get('https://www.reporo.com/', verify=False)
5,927,180
removing data from a numpy.array
Extract values not equal to 0 from numpy array a
a[a != 0]
209,840
Map two lists into a dictionary in Python
map two lists keys and values into a dictionary
new_dict = {k: v for k, v in zip(keys, values)}
209,840
Map two lists into a dictionary in Python
map two lists keys and values into a dictionary
dict((k, v) for k, v in zip(keys, values))
209,840
Map two lists into a dictionary in Python
map two lists keys and values into a dictionary
dict([(k, v) for k, v in zip(keys, values)])
8,569,201
Get the string within brackets in Python
find the string matches within parenthesis from a string s using regex
m = re.search('\$(\\w+)\$', s)
12,362,542
Python server "Only one usage of each socket address is normally permitted"
Enable the SO_REUSEADDR socket option in socket object s to fix the error only one usage of each socket address is normally permitted
11,703,064
How do i add two lists' elements into one list?
append 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)]
7,595,148
Python - Converting Hex to INT/CHAR
converting hex string s to its integer representations
[ord(c) for c in s.decode('hex')]
16,537,636
How to sort in decreasing value first then increasing in second value
sort 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])))
3,925,465
Repeating elements in list comprehension
get list of duplicated elements in range of 3
[y for x in range(3) for y in [x, x]]
3,278,850
Doc, rtf and txt reader in python
read the contents of the file 'file.txt' into txt
8,244,915
How do you divide each element in a list by an int?
divide each element in list myList by integer myInt
myList[:] = [(x / myInt) for x in myList]
7,934,620
python: dots in the name of variable in a format string
null
"""Name: {0[person.name]}""".format({'person.name': 'Joe'})
42,462,530
How to replace the white space in a string in a pandas dataframe?
replace white spaces in dataframe df with '_'
df.replace(' ', '_', regex=True)
15,661,013
Python: most efficient way to convert date to datetime
convert date my_date to datetime
datetime.datetime.combine(my_date, datetime.time.min)
3,886,669
Tuple to string
convert tuple tst to string tst2
tst2 = str(tst)
237,079
get file creation & modification date/times in
get modified time of file file
time.ctime(os.path.getmtime(file))
237,079
get file creation & modification date/times in
get creation time of file file
time.ctime(os.path.getctime(file))
237,079
get file creation & modification date/times in
get modification time of file filename
t = os.path.getmtime(filename)
237,079
get file creation & modification date/times in
get modification time of file path
os.path.getmtime(path)
237,079
get file creation & modification date/times in
get modified time of file file
237,079
get file creation & modification date/times in
get the creation time of file file
print(('created: %s' % time.ctime(os.path.getctime(file))))
237,079
get file creation & modification date/times in
get the creation time of file path_to_file
return os.path.getctime(path_to_file)
5,625,524
How to Close a program using python?
execute os command ''TASKKILL /F /IM firefox.exe''
3,862,010
Is there a generator version of string.split() in Python?
split string string on whitespaces using a generator
return (x.group(0) for x in re.finditer("[A-Za-z']+", string))
7,568,627
Using Python String Formatting with Lists
Unpack each value in list x to its placeholder '%' in string '%.2f'
""", """.join(['%.2f'] * len(x))
9,891,814
How to use regex with optional characters in python?
match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353'
print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))
20,894,525
How to remove parentheses and all data within using Pandas/Python?
replace parentheses and all data within it with empty string '' in column 'name' of dataframe df
df['name'].str.replace('\$$.*\$$', '')
18,448,469
Python: filter list of list with another list
create 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]
4,059,550
Generate all possible strings from a list of token
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)])
6,889,785
python how to search an item in a nested list
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]]
17,555,218
Python - How to sort a list of lists by the fourth element in each list?
Sort lists in the list unsorted_list by the element at index 3 of each list
unsorted_list.sort(key=lambda x: x[3])
18,292,500
Python logging typeerror
Log message 'test' on the root logger.
logging.info('test')
1,358,977
How to make several plots on a single page using matplotlib?
Return a subplot axes positioned by the grid definition 1,1,1 using matpotlib
613,183
Sort a Python dictionary by value
Sort dictionary x by value in ascending order
sorted(list(x.items()), key=operator.itemgetter(1))
613,183
Sort a Python dictionary by value
Sort dictionary dict1 by value in ascending order
sorted(dict1, key=dict1.get)
613,183
Sort a Python dictionary by value
Sort dictionary d by value in descending order
sorted(d, key=d.get, reverse=True)
613,183
Sort a Python dictionary by value
Sort dictionary d by value in ascending order
sorted(list(d.items()), key=(lambda x: x[1]))
31,957,364
Numpy elementwise product of 3d array
elementwise product of 3d arrays A and B
np.einsum('ijk,ikl->ijl', A, B)
14,041,791
print variable and a string in python
Print a string card with string formatting
print('I have: {0.price}'.format(card))
30,994,370
How can I add a comment to a YAML file in Python
Write a comment # Data for Class A\n to a file object f
f.write('# Data for Class A\n')
6,490,560
How do I move the last item in a list to the front in python?
move the last item in list a to the beginning
a = a[-1:] + a[:-1]
40,173,569
python - convert datetime to varchar/string
Parse DateTime object datetimevariable using format '%Y-%m-%d'
datetimevariable.strftime('%Y-%m-%d')
1,749,466
What's the most pythonic way of normalizing lineends in a string?
Normalize line ends in a string 'mixed'
mixed.replace('\r\n', '\n').replace('\r', '\n')
2,668,909
How to find the real user home directory using python?
find the real user home directory using python
os.path.expanduser('~user')
1,012,185
In Python, how do I index a list with another list?
index a list L with another list Idx
T = [L[i] for i in Idx]
7,745,260
Iterate through words of a file in Python
get a list of words words of a file 'myfile'
37,619,348
Summing 2nd list items in a list of lists of lists
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]
37,619,348
Summing 2nd list items in a list of lists of lists
summing the second item in a list of lists of lists
[sum([x[1] for x in i]) for i in data]
35,097,130
Django order by highest number of likes
sort objects in Articles in descending order of counts of likes
Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
27,587,127
How to convert datetime.date.today() to UTC time?
return a DateTime object with the current UTC date
today = datetime.datetime.utcnow().date()
10,271,484
How to perform element-wise multiplication of two lists in Python?
create 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)]
14,571,103
Capturing emoticons using regular expression in python
fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\$$|D|P)' in string s re.findall('(?::|;|=)(?:-)?(?:\$$|\\(|D|P)', s)
14,571,103
Capturing emoticons using regular expression in python
match the pattern '[:;][)(](?![)(])' to the string str
re.match('[:;][)(](?![)(])', str)
26,033,239
List of objects to JSON with Python
convert a list of objects list_name to json string json_string
json_string = json.dumps([ob.__dict__ for ob in list_name])
8,528,178
List of zeros in python
create a list listofzeros of n zeros
listofzeros = [0] * n
4,182,603
python: how to convert a string to utf-8
decode the string 'stringnamehere' to UTF-8
stringnamehere.decode('utf-8', 'ignore')
11,985,628
Python regex - Ignore parenthesis as indexing?
Match regex pattern '((?:A|B|C)D)' on string 'BDE'
re.findall('((?:A|B|C)D)', 'BDE')
12,905,999
Python dict how to create key or append an element to key?
Create a key key if it does not exist in dict dic and append element value to value.
dic.setdefault(key, []).append(value)
14,956,683
Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row
Get the value of the minimum element in the second column of array a
a[np.argmin(a[:, (1)])]
577,234
Python "extend" for a dictionary
extend dictionary a with key/value pairs of dictionary b
a.update(b)
13,254,241
Removing key values pairs from a list of dictionaries
removing 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]
13,254,241
Removing key values pairs from a list of dictionaries
null
[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]
15,451,958
Simple way to create matrix of random numbers
create 3 by 3 matrix of random numbers
numpy.random.random((3, 3))
34,023,918
Make new column in Panda dataframe by adding values from other columns
make new column 'C' in panda dataframe by adding values from other columns 'A' and 'B'
df['C'] = df['A'] + df['B']
10,484,261
Find dictionary items whose key matches a substring
create 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()]
9,153,527
Import module in another directory from a "parallel" sub-directory
append a path /path/to/main_folder in system path
sys.path.append('/path/to/main_folder')
34,338,341
Regex for getting all digits in a string after a character
get all digits in a string s after a '[' character
re.findall('\\d+(?=[^[]+\$)', s)
18,229,082
Python pickle/unpickle a list to/from a file
python pickle/unpickle a list to/from a file 'afile'