prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
emoving control characters from a string `s` | return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C') |
Compare if each value in list `a` is less than respective index value in list `b` | all(i < j for i, j in zip(a, b)) |
python selenium click on button '.button.c_button.s_button' | driver.find_element_by_css_selector('.button.c_button.s_button').click() |
python selenium click on butto | driver.find_element_by_css_selector('.button .c_button .s_button').click() |
kill a process `make.exe` from python script on window | os.system('taskkill /im make.exe') |
SQLAlchemy select records of columns of table `my_table` in addition to current date colum | print(select([my_table, func.current_date()]).execute()) |
emove duplicate characters from string 'ffffffbbbbbbbqqq' | re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq') |
emove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressio | re.sub('(?<!\\w)([A-Z])\\.', '\\1', s) |
Get a list of strings `split_text` with fixed chunk size `n` from a string `the_list` | split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)] |
h string 'this is my string' with regex '\\b(this|string)\\b'
then replace it with regex '<markup>\\1</markup>' | re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string') |
put data of the first 7 columns of Pandas dataframe | pandas.set_option('display.max_columns', 7) |
Display maximum output data of columns in dataframe `pandas` that will fit into the scree | pandas.set_option('display.max_columns', None) |
et the value in column 'B' to NaN if the corresponding value in column 'A' is equal to 0 in pandas dataframe `df` | df.ix[df.A == 0, 'B'] = np.nan |
Selecting Element //li/label/input followed by text polishpottery with Selenium WebDriver `driver` | driver.find_element_by_xpath("//li/label/input[contains(..,'polishpottery')]") |
Sort a list of dictionaries `mylist` by keys weight and factor | mylist.sort(key=operator.itemgetter('weight', 'factor')) |
dering a list of dictionaries `mylist` by elements 'weight' and 'factor' | mylist.sort(key=lambda d: (d['weight'], d['factor'])) |
Convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself | {x[1]: x for x in lol} |
keys of dictionary 'd' based on their value | sorted(d, key=lambda k: d[k][1]) |
d 123 to 100 | int(round(123, -2)) |
eate file 'x' if file 'x' does not ex | fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL) |
get a list of last trailing words from another list of strings`Original_List` | new_list = [x.split()[-1] for x in Original_List] |
Reverse a string 'hello world' | 'hello world'[::(-1)] |
Reverse list `s` | s[::(-1)] |
Reverse string 'foo' | ''.join(reversed('foo')) |
Reverse a string `string` | ''.join(reversed(string)) |
Reverse a string foo | 'foo'[::(-1)] |
Reverse a string `a_string` | a_string[::(-1)] |
Reverse a string `a_string` | def reversed_string(a_string):
return a_string[::(-1)] |
Reverse a string `s` | ''.join(reversed(s)) |
generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`. | """,""".join(str(i) for i in range(100) if i % 4 in (1, 2)) |
vert list `lst` of key, value pairs into a dictionary | dict([(e[0], int(e[1])) for e in lst]) |
g a list of tuples `list_of_tuples` where each tuple is reversed | sorted(list_of_tuples, key=lambda tup: tup[::-1]) |
g a list of tuples `list_of_tuples` by second key | sorted(list_of_tuples, key=lambda tup: tup[1]) |
Concatenating two onedimensional NumPy arrays 'a' and 'b'. | numpy.concatenate([a, b]) |
writing items in list `thelist` to file `thefile` | for item in thelist:
thefile.write(('%s\n' % item)) |
writing items in list `thelist` to file `thefile` | for item in thelist:
pass |
erialize `itemlist` to file `outfile` | pickle.dump(itemlist, outfile) |
writing items in list `itemlist` to file `outfile` | outfile.write('\n'.join(itemlist)) |
Update a user's name as `Bob Marley` having id `123` in SQLAlchemy | session.query(User).filter_by(id=123).update({'name': 'Bob Marley'}) |
end cookies `cookie` in a post request to url 'http://wikipedia.org' with the python requests library | r = requests.post('http://wikipedia.org', cookies=cookie) |
ert directory 'libs' at the 0th index of current directory | sys.path.insert(0, 'libs') |
get current date and time | datetime.datetime.now() |
get current time | datetime.datetime.now().time() |
get current time in pretty form | strftime('%Y-%m-%d %H:%M:%S', gmtime()) |
get current time in string form | str(datetime.now()) |
get current time | datetime.datetime.time(datetime.datetime.now()) |
vert hex '\xff' to integer | ord('\xff') |
dentify duplicated rows in columns 'PplNum' and 'RoomNum' with additional column in dataframe `df` | df.groupby(['PplNum', 'RoomNum']).cumcount() + 1 |
get current utc time | datetime.utcnow() |
ve last item of array `a` to the first positio | a[-1:] + a[:-1] |
Convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexe | df.set_index(['year', 'month', 'item']).unstack(level=-1) |
a pivot with a multiindex `year` and `month` in a pandas data frame | df.pivot_table(values='value', index=['year', 'month'], columns='item') |
print a rational number `3/2` | print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2') |
What is the best way to sort list with custom sorting parameters in Python? | li1.sort(key=lambda x: not x.startswith('b.')) |
erate backwards from 10 to 0 | range(10, 0, -1) |
get value of first child of xml node `name` | name[0].firstChild.nodeValue |
art a new thread for `myfunction` with parameters 'MyStringHere' and 1 | thread.start_new_thread(myfunction, ('MyStringHere', 1)) |
art a new thread for `myfunction` with parameters 'MyStringHere' and 1 | thread.start_new_thread(myfunction, ('MyStringHere', 1)) |
get index of the first biggest element in list `a` | a.index(max(a)) |
eplace periods `.` that are not followed by periods or spaces with a period and a space `. ` | re.sub('\\.(?=[^ .])', '. ', para) |
vert a string `a` of letters embedded in squared brackets into embedded l | [i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)] |
extract dictionary `d` from list `a` where the value associated with the key 'name' of dictionary `d` is equal to 'pluto' | [d for d in a if d['name'] == 'pluto'] |
extract dictionary from list of dictionaries based on a key's value. | [d for d in a if d['name'] == 'pluto'] |
Retrieve list of values from dictionary 'd' | list(d.values()) |
eplace occurrences of two whitespaces or more with one whitespace ' ' in string `s` | re.sub(' +', ' ', s) |
Change the mode of file 'my_script.sh' to permission number 484 | os.chmod('my_script.sh', 484) |
write pandas dataframe `df` to the file 'c:\\data\\t.csv' without row name | df.to_csv('c:\\data\\t.csv', index=False) |
emove all words which contains number from a string `words` using regex | re.sub('\\w*\\d\\w*', '', words).strip() |
l the keyboard and mouse with dogtail in linux | dogtail.rawinput.click(100, 100) |
parse date string '2009/05/13 19:19:30 0400' using format '%Y/%m/%d %H:%M:%S %z' | datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z') |
Get the position of a regex match for word `is` in a string `String` | re.search('\\bis\\b', String).start() |
Get the position of a regex match `is` in a string `String` | re.search('is', String).start() |
put an integer tuple from user | tuple(map(int, input().split(','))) |
put a tuple of integers from user | tuple(int(x.strip()) for x in input().split(',')) |
eplace unicode character '\u2022' in string 'str' with '*' | str.decode('utf-8').replace('\u2022', '*').encode('utf-8') |
eplace unicode characters ''\u2022' in string 'str' with '*' | str.decode('utf-8').replace('\u2022', '*') |
vert ndarray with shape 3x3 to array | np.zeros((3, 3)).ravel() |
get os name | import platform
platform.system() |
get os versio | import platform
platform.release() |
get the name of the OS | print(os.name) |
What is the most pythonic way to exclude elements of a list that start with a specific character? | [x for x in my_list if not x.startswith('#')] |
eplace fields delimited by braces {} in string Day old bread, 50% sale {0} with string 'today' | """Day old bread, 50% sale {0}""".format('today') |
Get a minimum value from a list of tuples `list` with values of type `string` and `float` with | min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1]) |
Find average of a nested list `a` | a = [(sum(x) / len(x)) for x in zip(*a)] |
Log info message 'Log message' with attributes `{'app_name': 'myapp'}` | logging.info('Log message', extra={'app_name': 'myapp'}) |
eplace values of dataframe `df` with True if numeric | df.applymap(lambda x: isinstance(x, (int, float))) |
list `l` based on its elements' dig | sorted(l, key=lambda x: int(re.search('\\d+', x).group(0))) |
lose the window in tkinter | self.root.destroy() |
get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df` | df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1) |
filter dataframe `df` by sublevel index '0630' in pand | df[df.index.map(lambda x: x[1].endswith('0630'))] |
flasksqlalchemy delete row `page` | db.session.delete(page) |
Format a string `u'Andr\xc3\xa9'` that has unicode character | """""".join(chr(ord(c)) for c in 'Andr\xc3\xa9') |
vert a unicode 'Andr\xc3\xa9' to a string | """""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8') |
list all files in directory . | for (dirname, dirnames, filenames) in os.walk('.'):
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
for filename in filenames:
pass |
list all files in directory `path` | os.listdir(path) |
ename file `dir` to `dir` + '!' | os.rename(dir, dir + '!') |
ert a character `` after every two elements in a string `s` | """-""".join(a + b for a, b in zip(s[::2], s[1::2])) |
printing numbers rounding up to third decimal place | print('%.3f' % 3.1415) |
dd variable `var` to key 'f' of first element in JSON data `data` | data[0]['f'] = var |
get the path of module `a_module` | print(a_module.__file__) |