text
stringlengths
4
1.08k
comparing lists of dictionaries,"all(d1[k] == d2[k] for k in ('testclass', 'testname'))"
how to get the label of a choice in a django forms choicefield?,{{OBJNAME.get_FIELDNAME_display}}
python matplotlib legend shows first entry of a list only,ax.legend()
how do i dissolve a pattern in a numpy array?,"array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])"
sqlalchemy count the number of rows in table `congress`,rows = session.query(Congress).count()
django: how to use settings in templates?,{{settings.MY_SETTING_NAME}}
python - convert dictionary into list with length based on values,"list(itertools.chain(*[([k] * v) for k, v in list(d.items())]))"
how can i exit fullscreen mode in pygame?,pygame.display.set_mode(size)
check if any of the items in `search` appear in `string`,any(x in string for x in search)
how can i recreate this graphic with python//matplotlib?,plt.show()
how to do multiple arguments to map function where one remains the same in python?,"[add(x, 2) for x in [1, 2, 3]]"
sorting a defaultdict by value in python,"sorted(list(u.items()), key=lambda v: v[1])"
chunking stanford named entity recognizer (ner) outputs from nltk format,"[('Remaking', 'O'), ('The', 'O'), ('Republican Party', 'ORGANIZATION')]"
how to scale images to screen size in pygame,"screen = pygame.display.set_mode((1600, 900))"
pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?,"dict(zip(l[::2], l[1::2]))"
encode string `s` to utf-8 code,s.encode('utf8')
python how do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (c[x], x), reverse=True)"
"zip lists `[1, 2], [3, 4], [5, 6]` in a list","zip(*[[1, 2], [3, 4], [5, 6]])"
python: using vars() to assign a string to a variable,locals()[4]
is there a cleaner way to iterate through all binary 4-tuples?,"itertools.product(list(range(2)), repeat=4)"
how do i read the number of files in a folder using python?,len(os.walk(path).next()[2])
parsing html page using beautifulsoup,print(''.join(x.stripped_strings))
find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')"
python base64 string decoding,base64.b64decode('AME=').decode('UTF-16BE')
split a multidimensional numpy array using a condition,"good_data = np.array([x for x in data[(0), :] if x == 1.0])"
how to print next year from current year in python,"print(date(today.year + 1, today.month, today.day))"
how can i set the y axis in radians in a python plot?,"ax.plot(x, y, 'b.')"
what's the life-time of a thread-local value in python?,time.sleep(1)
how can i remove all instances of an element from a list in python?,"a[:] = [x for x in a if x != [1, 1]]"
sorting one list to match another in python,"sorted(objects, key=lambda x: idmap[x['id']])"
"how do i iterate over a python dictionary, ordered by values?","sorted(iter(d.items()), key=lambda x: x[1])"
python checking a string's first and last character,"print('hi' if str1.startswith('""') and str1.endswith('""') else 'fails')"
how do i mock users with gae and nosetest?,testself.testbed.setup_env(user_is_admin='1')
getting the row index for a 2d numpy array when multiple column values are known,"np.where(np.any(a == 2, axis=0) & np.any(a == 5, axis=0))"
choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: x[1] + random.random())"
"pandas split strings in column 'stats' by ',' into columns in dataframe `df`","df['stats'].str[1:-1].str.split(',', expand=True).astype(float)"
matplotlib: add circle to plot,plt.show()
matplotlib.animation: how to remove white margin,"fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)"
python. convert escaped utf string to utf-string,print('your string'.decode('string_escape'))
django: how to disable ordering in model,People.objects.all().order_by()
how to click through gtk.window?,win.show_all()
python: use of counter in a dictionary of lists,Counter(v for sublist in list(d.values()) for v in sublist)
comparing lists of dictionaries,"return [d for d in list1 if (d['classname'], d['testname']) not in check]"
save current figure to file 'graph.png' with resolution of 1000 dpi,"plt.savefig('graph.png', dpi=1000)"
"checking if website ""http://www.stackoverflow.com"" is up",print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())
python - set list range to a specific value,my_list[bounds[0]:bounds[1] + 1] = ['foo'] * (bounds[1] + 1 - bounds[0])
split a string 's' by space while ignoring spaces within square braces and quotes.,"re.findall('\\[[^\\]]*\\]|""[^""]*""|\\S+', s)"
pandas: how to make apply on dataframe faster?,"df['C'] = numpy.where(df['B'] > 5, df['A'], 0.1 * df['A'] * df['B'])"
sorting a list with objects of a class as its items,your_list.sort(key=operator.attrgetter('anniversary_score'))
get a repeated pandas data frame object `x` by `5` times,pd.concat([x] * 5)
how to pass arguments as tuple to odeint?,"odeint(func, y0, t, args=(123, 456))"
how do i plot multiple x or y axes in matplotlib?,plt.show()
regex in python - using groups,a = re.compile('p(?:resent)')
splitting the sentences in python,"return re.findall('\\w+', text)"
"in django, how do i select 100 random records from the database?",Content.objects.all().order_by('?')[:100]
check for a cookie with python flask,cookie = flask.request.cookies.get('my_cookie')
plotting a polynomial in python,plt.show()
how to clear the entry widget after a button is pressed in tkinter?,root.mainloop()
how to add title to subplots in matplotlib?,ax.set_title('Title for first plot')
set data in column 'value' of dataframe `df` equal to first element of each list,df['value'] = df['value'].str[0]
"import module in another directory from a ""parallel"" sub-directory",sys.path.append('/path/to/main_folder')
merge lists `a` and `a` into a list of tuples,"list(zip(a, b))"
how to convert a set to a list in python?,"set([1, 2])"
plotting a polynomial in python,plt.show()
how to delete everything after a certain character in a string?,s = s[:s.index('.zip') + 4]
postgresql ilike query with sqlalchemy,Post.query.filter(Post.title.ilike('%some_phrase%'))
looping over a multiindex in pandas,df.index.get_level_values(0).unique()
matplotlib - how to plot a high resolution graph?,plt.savefig('filename.png')
how to return the regex that matches some text?,r = re.compile('(?P<int>^\\d+$)|(?P<word>^\\w+$)')
multiply values of dictionary `dict` with their respective values in dictionary `dict2`,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)"
index of element in numpy array,"i, = np.where(a == value)"
assigning a function to a variable,silly_var()
find all the tags `a` and `div` from beautiful soup object `soup`,"soup.find_all(['a', 'div'])"
what would be the python code to add time to a specific timestamp?,datetime.datetime.now() + datetime.timedelta(seconds=10)
matplotlib - how to plot a high resolution graph?,"plt.savefig('filename.png', dpi=300)"
how do i authenticate a urllib2 script in order to access https web services from a django site?,"req.add_header('Referer', login_url)"
how can i avoid storing a command in ipython history?,hismgr = get_ipython().history_manager
how do i parse xml in python?,e = xml.etree.ElementTree.parse('thefile.xml').getroot()
how to find the last occurrence of an item in a python list,len(li) - 1 - li[::-1].index('a')
get the creation time of file `path_to_file`,return os.path.getctime(path_to_file)
how to find the list in a list of lists whose sum of elements is the greatest?,"max(x, key=sum)"
customize beautifulsoup's prettify by tag,print(soup.prettify())
python dict comprehension with two ranges,"dict(zip(list(range(1, 5)), list(range(7, 11))))"
find the index of sub string 'df' in string 'sdfasdf','sdfasdf'.index('df')
convert list to a list of tuples python,"zip(it, it, it)"
"python, locating and clicking a specific button with selenium",next = driver.find_element_by_css_selector('li.next>a')
an elegant way to get hashtags out of a string in python?,[i[1:] for i in line.split() if i.startswith('#')]
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3d plot?,plt.show()
modifying a subset of rows in a pandas dataframe,"df.ix[df.A == 0, 'B'] = np.nan"
python how to sort this list?,lst.sort(reverse=True)
selecting a column on a multi-index pandas dataframe,df
how to join links in python to get a cycle?,"list(cycle([[0, 3], [1, 0], [3, 1]], 0))"
python regex findall,"re.findall('\\[P\\]\\s?(.+?)\\s?\\[\\/P\\]', line)"
changing image hue with python pil,img = Image.open('tweeter.png').convert('RGBA')
print the complete string of a pandas dataframe,"df.iloc[2, 0]"
reading hex to double-precision float python,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))"
"in django, where is the best place to put short snippets of html-formatted data?",{{value | linebreaks}}
"plotting a list of (x, y) coordinates in python matplotlib",plt.scatter(*zip(*li))
how to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]"
subtract time from datetime.time object,current_time = (datetime.now() - timedelta(seconds=10)).time()