text stringlengths 4 1.08k |
|---|
python remove anything that is not a letter or number,"re.sub('\\W', '', 'text 1, 2, 3...')" |
django: faking a field in the admin interface?,"admin.site.register(Foo, FooAdmin)" |
the truth value of an array with more than one element is ambigous when trying to index an array,"c[np.logical_or(a, b)]" |
moving x-axis to the top of a plot in matplotlib,ax.set_xlabel('X LABEL') |
querying from list of related in sqlalchemy and flask,User.query.join(User.person).filter(Person.id.in_(p.id for p in people)).all() |
is it possible to create a dynamic localized scope in python?,foo() |
"how to make python window run as ""always on top""?",gtk.Window.set_keep_above |
how to designate unreachable python code,"raise ValueError(""Unexpected gender; expected 'm' or 'f', got %s"" % gender)" |
is there a max length to a python conditional (if) statement?,"any(map(eval, my_list))" |
feeding a python array into a perl script,"[1, 2, 3, 4, 5, 6]" |
testing whether a numpy array contains a given row,"any(np.equal(a, [1, 2]).all(1))" |
print a string `card` with string formatting,print('I have: {0.price}'.format(card)) |
get everything after last slash in a url stored in variable 'url',"url.rsplit('/', 1)[-1]" |
python beautifulsoup extract specific urls,"soup.select('a[href^=""http://www.iwashere.com/""]')" |
how do i handle the window close event in tkinter?,root.mainloop() |
get element value with minidom with python,name[0].firstChild.nodeValue |
how to create a list with the characters of a string?,list('5+6') |
joining byte list with python,""""""""""""".join(['line 1\n', 'line 2\n'])" |
regular expression to find any number in a string,"re.findall('[+-]?\\d+', ' 1 sd 2 s 3 sfs 0 -1')" |
how to unfocus (blur) python-gi gtk+3 window on linux,Gtk.main() |
python import a module from a directory(package) one level up,sys.path.append('/path/to/pkg1') |
how can i add nothing to the list in list comprehension?,[(2 * x) for x in some_list if x > 2] |
auto delete data which is older than 10 days in django,posting_date = models.DateTimeField(auto_now_add=True) |
generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`,[x['value'] for x in list_of_dicts] |
how do get the id field in app engine datastore?,entity.key.id() |
color states with python's matplotlib/basemap,plt.show() |
python pandas extract unique dates from time series,df['Date'].map(lambda t: t.date()).unique() |
how to create multidimensional array with numpy.mgrid,"np.mgrid[[slice(row[0], row[1], n * 1j) for row, n in zip(bounds, n_bins)]]" |
return a datetime object with the current utc date,today = datetime.datetime.utcnow().date() |
join items of a list with '+' sign in a string,"print(('+'.join(str(i) for i in n_nx1lst) + ' = ', sum(n_nx1lst)))" |
iterating over a dictionary `d` using for loops,"for (key, value) in list(d.items()): |
pass" |
is there a python equivalent to memcpy,"socket = socket.socket(('127.0.0.1', port))" |
writing a csv file into sql server database using python,cursor.commit() |
how to find the real user home directory using python?,os.path.expanduser('~user') |
check to see if a collection of properties exist inside a dict object in python,all(dict_obj.get(key) is not None for key in properties_to_check_for) |
pipe input to python program and later get input from user,a = input('Prompt: ') |
how to make a figurecanvas fit a panel?,"self.axes = self.figure.add_axes([0, 0, 1, 1])" |
python: matplotlib - probability plot for several data set,plt.show() |
index a list `l` with another list `idx`,T = [L[i] for i in Idx] |
"python mysql update, working but not updating table",dbb.commit() |
convert a string key to int in a dictionary,"coautorshipDictionary = {int(k): int(v) for k, v in json.load(json_data)}" |
pyhon - best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x).mean() |
in python and linux how to get given user's id,pwd.getpwnam('aix').pw_uid |
python accessing values in a list of dictionaries,print('\n'.join(sorted(d['Name'] for d in thisismylist))) |
splitting a string by using two substrings in python,"re.search('Test(.*)print', testStr, re.DOTALL)" |
how to sum the nlargest() integers in groupby,df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum()) |
python append to array in json object,"jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})" |
"convert hex string ""0xa"" to integer","int('0xa', 16)" |
igraph: how to use add_edges when there are attributes?,"graph.add_edge('A', 'B', weight=20)" |
find indices of elements equal to zero from numpy array `x`,numpy.where((x == 0))[0] |
pythonic way to append list of strings to an array,""""""""""""".join(entry_list)" |
"how to change numpy array from (128,128,3) to (3,128,128)?","a.transpose(2, 0, 1)" |
sorting a list of lists by length and by value,"sorted(a, key=lambda x: (len(x), [confrom[card[0]] for card in x]))" |
multi-line logging in python,logging.getLogger().setLevel(logging.DEBUG) |
case insensitive comparison between strings `first` and `second`,(first.upper() == second.upper()) |
get current time in string format,str(datetime.now()) |
remove final characters from string recursively - what's the best way to do this?,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" |
best way to encode tuples with json,"{(1): {(2): [(2, 3), (1, 7)]}}" |
how to access dictionary element in django template?,"choices = {'key1': 'val1', 'key2': 'val2'}" |
print multiple arguments in python,"print('Total score for %s is %s ' % (name, score))" |
how can i find the ip address of a host using mdns?,"sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" |
how do i write to the console in google app engine?,"logging.debug('value of my var is %s', str(var))" |
get canonical path of the filename `path`,os.path.realpath(path) |
retrieving contents from a directory on a network drive (windows),os.listdir('\\\\server\x0colder\\subfolder\\etc') |
is there a pythonic way to do a contingency table in pandas?,print(df1['A'].unstack()) |
how to use variables in sql statement in python?,"cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))" |
slick way to reverse the (binary) digits of a number in python?,"int(bin(n)[:1:-1], 2)" |
pandas dataframe to rdd,spDF.rdd.first() |
custom sorting in pandas dataframe,"s = df['m'].replace({'March': 0, 'April': 1, 'Dec': 3})" |
pandas groupby: how to get a union of strings,df.groupby('A')['C'].apply(lambda x: x.sum()) |
convert a set of tuples `queryresult` to a string `emaillist`,emaillist = '\n'.join(item[0] for item in queryresult) |
"in sympy plotting, how can i get a plot with a fixed aspect ratio?",plt.show() |
how to serve file in webpy?,app.run() |
"print string ""abc"" as hex literal","""""""ABC"""""".encode('hex')" |
scrapy pipeline to mysql - can't find answer,ITEM_PIPELINES = ['myproject.pipelines.somepipeline'] |
what's the best way to aggregate the boolean values of a python dictionary?,all(dict.values()) |
how to find match items from two lists?,set(data1) & set(data2) |
repeating elements in list python,"set(x[0] for x in zip(a, a[1:]) if x[0] == x[1])" |
replace `;` with `:` in a string `line`,"line = line.replace(';', ':')" |
print a list of floating numbers `l` using string formatting,print([('%5.3f' % val) for val in l]) |
list comprehension with an accumulator in range of 10,list(accumulate(list(range(10)))) |
what is the easiest way to detect key presses in python 3 on a linux machine?,main() |
check if object `a` has property 'property',"if hasattr(a, 'property'): |
pass" |
how to move to one folder back in python,os.chdir('..') |
how can i get the executable's current directory in py2exe?,os.path.realpath(os.path.dirname(sys.argv[0])) |
write dictionary of lists to a csv file,writer.writerows(zip(*[d[key] for key in keys])) |
pythonic way to convert a list of integers into a string of comma-separated ranges,"print(','.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in G))" |
using savepoints in python sqlite3,"conn.execute('insert into example values (?, ?);', (5, 205))" |
how can i insert data into a mysql database?,cursor.execute(sql) |
python logging string formatting,logger.setLevel(logging.DEBUG) |
generate all possible strings from a list of token,"print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])" |
"create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`","[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]" |
multiple levels of keys and values in python,creatures['birds']['eagle']['female'] += 1 |
(django) how to get month name?,{{a_date | date('F')}} |
get the union set from list of lists `results_list`,results_union = set().union(*results_list) |
first common element from two lists,[i for i in x if i in y] |
"store data frame `df` to file `file_name` using pandas, python",df.to_pickle(file_name) |
pythonic way to insert every 2 elements in a string,"s[::2], s[1::2]" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.