intent
stringlengths
4
183
snippet
stringlengths
2
1k
more elegant way to implement regexp-like quantifiers
['x', ' ', 'y', 'y', ' ', 'z']
convert a string 'mystr' to numpy array of integer values
print(np.array(list(mystr), dtype=int))
how to convert this particular json string into a python dictionary?
json.loads('[{"name":"sam"}]')
creating a screenshot of a gtk.window
gtk.main()
how to delete a record in django models?
SomeModel.objects.filter(id=id).delete()
python- trying to multiply items in list
[i for i in a if i.isdigit()]
how to make mxn piechart plots with one legend and removed y-axis titles in matplotlib
plt.show()
revers correlating bits of integer `n`
int('{:08b}'.format(n)[::-1], 2)
swap letters in a string in python
return strg[n:] + strg[:n]
finding in elements in a tuple and filtering them
[x for x in l if x[0].startswith('img')]
python - how to clear spaces from a text
re.sub(' (?=(?:[^"]*"[^"]*")*[^"]*$)', '', s)
pandas: elementwise multiplication of two dataframes
pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)
concatenate elements of a tuple in a list in python
new_data = (' '.join(w) for w in sixgrams)
iterating key and items over dictionary `d`
for (k, v) in list(d.items()): pass
what is the best way to sort list with custom sorting parameters in python?
li1.sort(key=lambda x: not x.startswith('b.'))
can i use an alias to execute a program from a python script
os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')
regular expression in python sentence extractor
re.split('\\.\\s', re.sub('\\.\\s*$', '', text))
how to build and fill pandas dataframe from for loop?
pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))
how can i convert a python datetime object to utc?
datetime.utcnow() + timedelta(minutes=5)
numpy select fixed amount of values among duplicate values in array
array([1, 2, 2, 3, 3])
how to pass a dictionary as value to a function in python
{'physics': 1}, {'volume': 1, 'chemistry': 1}, {'chemistry': 1}
how to decrypt unsalted openssl compatible blowfish cbc/pkcs5padding password in python?
cipher.decrypt(ciphertext).replace('\x08', '')
convert string to boolean from defined set of strings
s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
get the path of module `a_module`
print(a_module.__file__)
how do i draw a grid onto a plot in python?
plt.rc('grid', linestyle='-', color='black')
how to make a timer program in python
time.sleep(1)
find first item with alphabetical precedence in list with numbers
min(x for x in lst if isinstance(x, str))
convert tab-delimited txt file into a csv file using python
open('demo.txt', 'rb').read()
call a function `otherfunc` inside a bash script `test.sh` using subprocess
subprocess.call('test.sh otherfunc')
avoiding regex in pandas str.replace
df['a'] = df['a'].str.replace('in.', ' in. ')
python - subprocess - how to call a piped command in windows?
subprocess.call(['ECHO', 'Ni'])
arrows in matplotlib using mplot3d
plt.show()
encode string "\\xc3\\x85a" to bytes
"""\\xc3\\x85a""".encode('utf-8')
merge values of same key, in list of dicts
[{'id1': k, 'price': temp[k]} for k in temp]
plotting animated quivers in python
plt.show()
how to transform a pair of values into a sorted unique array?
sorted(set().union(*input_list))
precision in python
print('{0:.2f}'.format(your_number))
reverse mapping of dictionary with python
revdict = dict((v, k) for k, v in list(ref.items()))
get number of workers from process pool in python multiprocessing module
multiprocessing.cpu_count()
pandas, filter rows which column contain another column
df[df['B'].str.contains('|'.join(df['A']))]
sqlalchemy and flask, how to query many-to-many relationship
x = Dish.query.filter(Dish.restaurants.any(name=name)).all()
swap values in a tuple/list inside a list in python?
map(lambda t: (t[1], t[0]), mylist)
blank lines in file after sorting content of a text file in python
lines.sort()
google app engine python download file
self.response.headers['Content-Disposition'] = 'attachment; filename=fname.csv'
python - get yesterday's date as a string in yyyy-mm-dd format
(datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
delete row based on nulls in certain columns (pandas)
df.dropna(subset=['city', 'latitude', 'longitude'], how='all')
plot image color histogram using matplotlib
plt.show()
sorting associative arrays in python
sorted(people, key=operator.itemgetter('name'))
search for regex pattern 'test(.*)print' in string `teststr` including new line character '\n'
re.search('Test(.*)print', testStr, re.DOTALL)
validate a filename in python
return os.path.join(directory, filename)
python numpy: how to count the number of true elements in a bool array
sum([True, True, True, False, False])
get top `3` items from a dictionary `mydict` with largest sum of values
heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))
how to filter a dictionary according to an arbitrary condition function?
dict((k, v) for k, v in list(points.items()) if all(x < 5 for x in v))
how do i pull a recurring key from a json?
print(item['name'])
writing utf-8 string to mysql with python
cursor.execute('INSERT INTO mytable SET name = %s', (name,))
how to download file from ftp?
ftp.retrbinary('RETR README', open('README', 'wb').write)
a list as a key for pyspark's reducebykey
rdd.map(lambda k_v: (frozenset(k_v[0]), k_v[1])).groupByKey().collect()
how to send email attachments with python
smtp.sendmail(send_from, send_to, msg.as_string())
index confusion in numpy arrays
A[np.ix_([0, 2], [0, 1], [1, 2])]
in python, how to convert a hex ascii string to raw internal binary string?
"""""".join('{0:04b}'.format(int(c, 16)) for c in hex_string)
split string `s` into strings of repeating elements
print([a for a, b in re.findall('((\\w)\\2*)', s)])
set legend symbol opacity with matplotlib?
plt.legend()
how to open a file with the standard application?
os.system('start "$file"')
how can i count the occurrences of an item in a list of dictionaries?
sum(1 for d in my_list if d.get('id') == 20)
splitting a list inside a pandas dataframe
pd.melt(split, id_vars=['a', 'b'], value_name='TimeStamp')
increment numpy array with repeated indices
array([0, 0, 2, 1, 0, 1])
python re.findall print all patterns
re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')
pandas - dataframe expansion with outer join
df.columns = ['user', 'tweet']
control the keyboard and mouse with dogtail in linux
dogtail.rawinput.click(100, 100)
convert a binary `b8` to a float number
struct.unpack('d', b8)[0]
select everything but a list of columns from pandas dataframe
df[df.columns - ['T1_V6']]
removing nan values from an array
x = x[numpy.logical_not(numpy.isnan(x))]
parse utf-8 encoded html response `response` to beautifulsoup object
soup = BeautifulSoup(response.read().decode('utf-8'))
separating a string
['abcd', 'a,bcd', 'a,b,cd', 'a,b,c,d', 'a,bc,d', 'ab,cd', 'ab,c,d', 'abc,d']
generate a 12-digit random number
random.randint(100000000000, 999999999999)
python finding index of maximum in list
a.index(max(a))
replacing '\u200b' with '*' in a string using regular expressions
'used\u200b'.replace('\u200b', '*')
regex for matching string python
size = re.findall('\\d+(?:,\\d{3})*(?:\\.\\d+)?', my_string)
how to use the pass statement in python
print("I'm meth_b")
python beautifulsoup searching a tag
print(soup.find_all('a', {'class': 'black'}))
python - convert datetime to varchar/string
datetimevariable.strftime('%Y-%m-%d')
is there a cake equivalent for python?
main()
how to convert list of intable strings to int
[[try_int(x) for x in lst] for lst in list_of_lists]
list all the contents of the directory 'path'.
os.listdir('path')
how can i handle an alert with ghostdriver via python?
driver.execute_script('return lastAlert')
python replace backslashes to slashes
print('pictures\\12761_1.jpg'.replace('\\', '/'))
get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`
pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)
group vertices in clusters using networkx
nx.draw_spring(G)
python: get the first character of a the first string in a list?
mylist = ['base', 'sample', 'test']
pyqt window focus
self.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint)
close pyplot figure using the keyboard on mac os x
plt.show()
python convert decimal to hex
hex(dec).split('x')[1]
delete all digits in string `s` that are not directly attached to a word character
re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)
plotting ellipsoid with matplotlib
plt.show()
python regex to split on certain patterns with skip patterns
regx = re.compile('\\s+and\\s+|\\s*,\\s*')
how can i clear the python pdb screen?
os.system('clear')
write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%y%m%d`
df.to_csv(filename, date_format='%Y%m%d')
how to round a number to significant figures in python
round(1234, -3)
is it possible to get widget settings in tkinter?
print(w.cget('text'))
how to set default value to all keys of a dict object in python?
d['foo']