intent
stringlengths
4
183
snippet
stringlengths
2
1k
convert a list to a dictionary in python
b = dict(zip(a[0::2], a[1::2]))
python - sort a list of nested lists
l.sort(key=sum_nested)
how to get the size of a string in python?
print(len('\xd0\xb9\xd1\x86\xd1\x8b'))
how to get the fft of a numpy array to work?
np.fft.fft(xfiltered)
calculating difference between two rows in python / pandas
data.set_index('Date').diff()
efficient computation of the least-squares algorithm in numpy
np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))
how to add an image in tkinter (python 2.7)
root.mainloop()
matrix mirroring in python
np.concatenate((A[::-1, :], A[1:, :]), axis=0)
truth value of numpy array with one falsey element seems to depend on dtype
np.array(['a', 'b']) != 0
add column sum as new column in pyspark dataframe
newdf = df.withColumn('total', sum(df[col] for col in df.columns))
how to find elements by class
soup.find_all('div', class_='stylelistrowone stylelistrowtwo')
how to pad all the numbers in a string
re.sub('\\d+', lambda x: x.group().zfill(padding), s)
removing elements from an array that are in another array
[[1, 1, 2], [1, 1, 3]]
autofmt_xdate deletes x-axis labels of all subplots
plt.setp(plt.xticks()[1], rotation=30, ha='right')
looking for a simple opengl (3.2+) python example that uses glfw
glfw.Terminate()
reorder indexed rows `['z', 'c', 'a']` based on a list in pandas data frame `df`
df.reindex(['Z', 'C', 'A'])
issue sending email with python?
server = smtplib.SMTP('smtp.gmail.com', 587)
return rows of data associated with the maximum value of column 'value' in dataframe `df`
df.loc[df['Value'].idxmax()]
how to invoke a specific python version within a script.py -- windows
print('World')
set index equal to field 'trx_date' in dataframe `df`
df = df.set_index(['TRX_DATE'])
reference to an element in a list
c[:] = b
how to merge two columns together in pandas
pd.melt(df, id_vars='Date')[['Date', 'value']]
create svg / xml document without ns0 namespace using python elementtree
etree.register_namespace('', 'http://www.w3.org/2000/svg')
python - flatten a dict of lists into unique values?
sorted({x for v in content.values() for x in v})
argparse module how to add option without any argument?
parser.add_argument('-s', '--simulate', action='store_true')
un-escaping characters in a string with python
"""\\u003Cp\\u003E""".decode('unicode-escape')
cookies with urllib2 and pywebkitgtk
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
how to unquote a urlencoded unicode string in python?
urllib.parse.unquote('%0a')
tensorflow: how to get a tensor by name?
sess.run('add:0')
how to extract links from a webpage using lxml, xpath and python?
['http://stackoverflow.com/foobar', 'http://stackoverflow.com/baz']
encode value of key `city` in dictionary `data` as `ascii`, ignoring non-ascii characters
data['City'].encode('ascii', 'ignore')
append 2 dimensional arrays to one single array
array([[[1, 5], [2, 6]], [[3, 7], [4, 8]]])
convert list of lists to delimited string
result = '\n'.join('\t'.join(map(str, l)) for l in lists)
pandas: how to run a pivot with a multi-index?
df.groupby(['year', 'month', 'item'])['value'].sum().unstack('item')
python: sort a list of lists by an item in the sublist
sorted(li, key=operator.itemgetter(1), reverse=True)
get key by value in dictionary with same value in python?
print([key for key, value in list(d.items()) if value == 1])
how do you create nested dict in python?
dict(d)
how to replace unicode characters in string with something else python?
str.decode('utf-8')
get count of values associated with key in dict python
sum(1 if d['success'] else 0 for d in s)
access item in a list of lists
50 - list1[0][0] + list1[0][1] - list1[0][2]
python how to get every first element in 2 dimensional list `a`
[i[0] for i in a]
find the element that holds string 'text a' in file `root`
e = root.xpath('.//a[text()="TEXT A"]')
how to get the content of a html page in python
"""""".join(soup.findAll(text=True))
joining two numpy matrices
np.hstack([X, Y])
how to center labels in histogram plot
ax.set_xticklabels(('1', '2', '3', '4'))
interprocess communication in python
socket.send('...nah')
save image created via pil to django model
img.save()
using multipartposthandler to post form-data with python
print(urllib.request.urlopen(request).read())
python regex alternative for join
re.sub('(?<=.)(?=.)', '-', s)
find all list permutations of a string in python
['m', 'o', 'n', 'k', 'e', 'y']
pythonic way to find maximum value and its index in a list?
max_index = my_list.index(max_value)
passing variables to a template on a redirect in python
self.redirect('/sucess')
how do i force django to ignore any caches and reload data?
MyModel.objects.get(id=1).my_field
sorting numbers in string format with python
keys.sort(key=lambda x: map(int, x.split('.')))
can't figure out how to bind the enter key to a function in tkinter
root.mainloop()
make subprocess find git executable on windows
proc = subprocess.Popen(['git', 'status'], stdout=subprocess.PIPE)
how to check if all items in the list are none?
not any(my_list)
how can i get the list of names used in a formatting string?
get_format_vars('hello %(foo)s there %(bar)s')
set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`
rdata.set_index(['race_date', 'track_code', 'race_number'])
check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`
set(['stackoverflow', 'google']).issubset(sites)
python pandas filtering out nan from a data selection of a column of strings
nms.dropna(thresh=2)
correct way of implementing cherrypy's autoreload module
cherrypy.quickstart(Root())
pythonic way to assign the parameter into attribute?
setattr(self, k, v)
getting the second to last element of list `some_list`
some_list[(-2)]
create a list containing elements from list `list` that are predicate to function `f`
[f(x) for x in list]
print a digit `your_number` with exactly 2 digits after decimal
print('{0:.2f}'.format(your_number))
sort list `mylist` alphabetically
mylist.sort(key=lambda x: x.lower())
python byte string encode and decode
"""foo""".decode('latin-1')
python: how to "fork" a session in django
return render(request, 'organisation/wall_post.html', {'form': form})
how to get an arbitrary element from a frozenset?
[random.sample(s, 1)[0] for _ in range(10)]
drop column based on a string condition
df.drop(df.columns[df.columns.str.match('chair')], axis=1)
add leading zeros to strings in pandas dataframe
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
sunflower scatter plot using matplotlib
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
get a list of the keys in each dictionary in a dictionary of dictionaries `foo`
[k for d in list(foo.values()) for k in d]
sort dictionary `mydict` in descending order based on the sum of each value in it
sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]
django circular model reference
team = models.ForeignKey('Team')
match the pattern '[:;][)(](?![)(])' to the string `str`
re.match('[:;][)(](?![)(])', str)
add row `['8/19/2014', 'jun', 'fly', '98765']` to dataframe `df`
df.loc[len(df)] = ['8/19/2014', 'Jun', 'Fly', '98765']
matplotlib: formatting dates on the x-axis in a 3d bar graph
plt.show()
python - how to calculate equal parts of two dictionaries?
d3 = {k: list(set(d1.get(k, [])).intersection(v)) for k, v in list(d2.items())}
round number 1.005 up to 2 decimal places
round(1.005, 2)
pls-da algorithm in python
mypred = myplsda.predict(Xdata)
set the y axis range to `0, 1000` in subplot using pylab
pylab.ylim([0, 1000])
plotting categorical data with pandas and matplotlib
df.colour.value_counts().plot(kind='bar')
using python to extract dictionary keys within a list
names = [item['name'] for item in data]
how to sort pandas data frame using values from several columns?
df.sort(['c1', 'c2'], ascending=[False, True])
how can i get the previous week in python?
start_delta = datetime.timedelta(days=weekday, weeks=1)
generate a random 12-digit number
int(''.join(str(random.randint(0, 9)) for _ in range(12)))
functional statement in python to return the sum of certain lists in a list of lists
sum(len(y) for y in x if len(y) > 1)
set execute bit for a file using python
os.chmod('my_script.sh', 484)
convert hex string `hexstring` to int
int(hexString, 16)
multiple data set plotting with matplotlib.pyplot.plot_date
plt.show()
execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab
system('/path/to/my/venv/bin/python myscript.py')
python: find in list
[i for i, x in enumerate([1, 2, 3, 2]) if x == 2]
python implementation of jenkins hash?
hash, hash2 = hashlittle2(hashstr, 3735928559, 3735928559)
if/else statements accepting strings in both capital and lower-case letters in python
"""3""".lower()
python: create a "with" block on several context managers
do_something()
add variable `var` to key 'f' of first element in json data `data`
data[0]['f'] = var
how to initialize a two-dimensional array in python?
[[Foo() for x in range(10)] for y in range(10)]
decode unicode string `s` into a readable unicode literal
s.decode('unicode_escape')