prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
load a file `file.py` into the python console | exec(compile(open('file.py').read(), 'file.py', 'exec')) |
SQLAlchemy count the number of rows in table `Congress` | rows = session.query(Congress).count() |
Execute Shell Script from python with variable | subprocess.call(['test.sh', str(domid)]) |
ead excel file `file_name` using pand | dfs = pd.read_excel(file_name, sheetname=None) |
pack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a flo | struct.unpack('d', binascii.unhexlify('4081637ef7d0424a')) |
Get index of numpy array `a` with another numpy array `b` | a[tuple(b)] |
find all possible sequences of elements in a list `[2, 3, 4]` | map(list, permutations([2, 3, 4])) |
a list `unsorted_list` based on another sorted list `presorted_list` | sorted(unsorted_list, key=presorted_list.index) |
w to get yesterday in pytho | datetime.datetime.now() - datetime.timedelta(days=1) |
eate a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list` | d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list) |
find the index of sub string 'World' in `x` | x.find('World') |
find the index of sub string 'Aloha' in `x` | x.find('Aloha') |
find the index of sub string 'cc' in string 'sdfasdf' | 'sdfasdf'.index('cc') |
find the index of sub string 'df' in string 'sdfasdf' | 'sdfasdf'.index('df') |
find the index of sub string 'a' in string `str` | str.find('a') |
find the index of sub string 'g' in string `str` | str.find('g') |
find the index of sub string 's' in string `str` starting from index 11 | str.find('s', 11) |
find the index of sub string 's' in string `str` starting from index 15 | str.find('s', 15) |
find the index of sub string 's' in string `str` starting from index 16 | str.find('s', 16) |
find the index of sub string 's' in string `str` starting from index 11 and ending at index 14 | str.find('s', 11, 14) |
list of date strings 'd' | sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y')) |
Get all the sentences from a string `text` using regex | re.split('\\.\\s', text) |
Regular expression in Python sentence extractor | re.split('\\.\\s', re.sub('\\.\\s*$', '', text)) |
get all characters in string 'foobar' up to the fourth index | """foobar"""[:4] |
a string by delimiter '&' | s.rfind('&') |
a string using delimiter '&' | s[:s.rfind('&')] |
find a tag `option` whose `value` attribute is `state` in selenium | driver.find_element_by_xpath("//option[@value='" + state + "']").click() |
ppend line appended text to file test.txt | with open('test.txt', 'a') as myfile:
myfile.write('appended text') |
ppend line cool beans... to file foo | with open('foo', 'a') as f:
f.write('cool beans...') |
ppend to file 'test1' content 'koko' | with open('test1', 'ab') as f:
pass |
ppend to file 'test' content 'koko' | open('test', 'a+b').write('koko') |
plit string 'x+13.5*10x4e1' into toke | print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i]) |
Find all Chinese characters in string `ipath` | re.findall('[\u4e00-\u9fff]+', ipath) |
plit string `s` by letter 's' | s.split('s') |
hell command 'rm r some.file' in the background | subprocess.Popen(['rm', '-r', 'some.file']) |
vert a list of dictionaries `listofdict into a dictionary of dictionarie | dict((d['name'], d) for d in listofdict) |
print current date and time in a regular form | datetime.datetime.now().strftime('%Y-%m-%d %H:%M') |
print current date and time in a regular form | time.strftime('%Y-%m-%d %H:%M') |
find consecutive consonants in a word `CONCENTRATION` using regex | re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE) |
get a list of indices of non zero elements in a list `a` | [i for i, e in enumerate(a) if e != 0] |
get multiple integer values from a string 'string1' | map(int, re.findall('\\d+', string1)) |
get the path of Python executable under window | os.path.dirname(sys.executable) |
ve an xaxis label to the top of a plot `ax` in matplotlib | ax.xaxis.set_label_position('top') |
ve xaxis to the top of a plot `ax` | ax.xaxis.tick_top() |
Move xaxis of the pyplot object `ax` to the top of a plot in matplotlib | ax.xaxis.set_ticks_position('top') |
parse string '2015/01/01 12:12am' to DateTime object using format '%Y/%m/%d %I:%M%p' | datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p') |
Open image 'picture.jpg' | img = Image.open('picture.jpg')
img.show() |
Open image picture.jpg | img = Image.open('picture.jpg')
Img.show |
erminate the script using status value 0 | sys.exit(0) |
bort the execution of the script using message 'aa! errors!' | sys.exit('aa! errors!') |
bort the execution of a python scrip | sys.exit() |
find maximum with lookahead = 4 in a list `arr` | [max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)] |
et the current working directory to 'c:\\Users\\uname\\desktop\\python' | os.chdir('c:\\Users\\uname\\desktop\\python') |
et the current working directory to path `path` | os.chdir(path) |
get a list `no_integers` of all the items in list `mylist` that are not of type `int` | no_integers = [x for x in mylist if not isinstance(x, int)] |
h contents of an element to 'Example' in xpath (lxml) | tree.xpath(".//a[text()='Example']")[0].tag |
atenate key/value pairs in dictionary `a` with string ', ' into a single string | """, """.join([(str(k) + ' ' + str(v)) for k, v in list(a.items())]) |
Strip all nonASCII characters from a unicode string, `\xa3\u20ac\xa3\u20ac` | print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac'))) |
Get all nonascii characters in a unicode string `\xa3100 is worth more than \u20ac100` | print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100')) |
build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}` | ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}") |
Print string `t` with proper unicode representatio | print(t.decode('unicode_escape')) |
Normalize string `str` from 'cp1252' code to 'utf8' code | print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8')) |
erge lists `list_a` and `list_b` into a list of tuple | zip(list_a, list_b) |
erge lists `a` and `a` into a list of tuple | list(zip(a, b)) |
vert pandas DataFrame `df` to a dictionary using `id` field as the key | df.set_index('id').to_dict() |
vert pandas dataframe `df` with fields 'id', 'value' to dictionary | df.set_index('id')['value'].to_dict() |
Can I sort text by its numeric value in Python? | sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.'))) |
emove parentheses and text within it in string `filename` | re.sub('\\([^)]*\\)', '', filename) |
Check if string 'a b' only contains letters and space | """a b""".replace(' ', '').isalpha() |
m each element `x` in list `first` with element `y` at the same index in list `second`. | [(x + y) for x, y in zip(first, second)] |
a python dictionary `a_dict` by element `1` of the value | sorted(list(a_dict.items()), key=lambda item: item[1][1]) |
w to exclude a character from a regex group? | re.compile('[^a-zA-Z0-9-]+') |
get index of the biggest 2 values of a list `a` | sorted(list(range(len(a))), key=lambda i: a[i])[-2:] |
get indexes of the largest `2` values from a list `a` using itemgetter | zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:] |
get the indexes of the largest `2` values from a list of integers `a` | sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2] |
get index of key 'c' in dictionary `x` | list(x.keys()).index('c') |
Print +1 using format '{0:+d}' | print('{0:+d}'.format(score)) |
emove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]` | [k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])] |
plit string 0,1,2 based on delimiter ',' | """0,1,2""".split(',') |
vert the string '0,1,2' to a list of integer | [int(x) for x in '0,1,2'.split(',')] |
vert list of keyvalue tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary | dict([('A', 1), ('B', 2), ('C', 3)]) |
ave numpy array `x` into text file 'test.txt' | np.savetxt('test.txt', x) |
e the output of command 'ls' in variable `direct_output` | direct_output = subprocess.check_output('ls', shell=True) |
get all column name of dataframe `df` except for column 'T1_V6' | df[df.columns - ['T1_V6']] |
get count of values in numpy array `a` that are between values `25` and `100` | ((25 < a) & (a < 100)).sum() |
Get day name from a datetime objec | date.today().strftime('%A') |
Python regular expression match whole word | re.search('\\bis\\b', your_string) |
Jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime` | {{car.date_of_manufacture | datetime}} |
Get the date object `date_of_manufacture` of object `car` in string format '%Y%m%d' | {{car.date_of_manufacture.strftime('%Y-%m-%d')}} |
ke a flat list from list of lists `sublist` | [item for sublist in l for item in sublist] |
ke a flat list from list of lists `list2d` | list(itertools.chain(*list2d)) |
ke a flat list from list of lists `list2d` | list(itertools.chain.from_iterable(list2d)) |
vert ascii value 'a' to | ord('a') |
eplace white spaces in string ' a\n b\n c\nd e' with empty string '' | re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e') |
emove white spaces from all the lines using a regular expression in string 'a\n b\n c' | re.sub('(?m)^\\s+', '', 'a\n b\n c') |
destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c` | a, b, c = [1, 2, 3] |
plit list `mylist` into a list of lists whose elements have the same first five character | [list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])] |
emove all instances of parenthesesis containing text beginning with `as ` from string `line` | line = re.sub('\\(+as .*?\\) ', '', line) |
kip the newline while printing `line` | print(line.rstrip('\n')) |
get index values of pandas dataframe `df` as l | df.index.values.tolist() |