text
stringlengths 4
1.08k
|
|---|
how can i get the name of an object in python?,"dict([(t.__name__, t) for t in fun_list])"
|
create a function with four parameters,"print(f(1, 2, 3))"
|
reading a csv file using python,f.close()
|
how can i restrict the scope of a multiprocessing process?,"multiprocessing.Process(target=foo, args=(x,)).start()"
|
how to union two subqueries in sqlalchemy and postgresql,session.query(q).limit(10)
|
csv parsing in python,writer.writerow([])
|
counting positive elements in a list with python list comprehensions,sum(x > 0 for x in frequencies)
|
how to use variables in sql statement in python?,"cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))"
|
how to make urllib2 requests through tor in python?,print(opener.open('http://www.google.com').read())
|
how to replace the some characters from the end of a string?,"s[::-1].replace('2', 'x', 1)[::-1]"
|
python: how to generate a 12-digit random number?,"return '{0:0{x}d}'.format(random.randint(0, 10 ** x - 1), x=x)"
|
element-wise minimum of multiple vectors in numpy,np.asarray(V).min(0)
|
how to query multiindex index columns values in pandas,"x.loc[(x.B >= 111.0) & (x.B <= 500.0)].set_index(['A', 'B'])"
|
python splitting string by parentheses,"re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)"
|
complex sorting of a list,"sorted(['1:14', '8:01', '12:46', '6:25'], key=daytime)"
|
"how to make a python script which can logoff, shutdown, and restart a computer?","subprocess.call(['shutdown', '/r', '/t', '900'])"
|
python print string to text file,text_file.write('Purchase Amount: {0}'.format(TotalAmount))
|
binning a numpy array,"print(data.reshape(-1, 2).mean(axis=1))"
|
sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])"
|
matplotlib bar graph x axis won't plot string values,plt.show()
|
how can i detect dos line breaks in a file?,"print(open('myfile.txt', 'U').read())"
|
clear the textbox `text` in tkinter,"tex.delete('1.0', END)"
|
"shuffle an array with python, randomize array item order with python",random.shuffle(array)
|
move an x-axis label to the top of a plot `ax` in matplotlib,ax.xaxis.set_label_position('top')
|
get a list of items from the list `some_list` that contain string 'abc',matching = [s for s in some_list if 'abc' in s]
|
how to deal with unstable data received from rfid reader?,cache.get('data')
|
loop for each item in a list,list(itertools.product(*list(mydict.values())))
|
reading data blocks from a file in python,line = f.readline()
|
numpy: get random set of rows from 2d array,"A[np.random.choice(A.shape[0], num_rows_2_sample)]"
|
hexagonal self-organizing map in python,"(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1), (i - 1, j - 1), (i + 1, j - 1)"
|
how to handle unicode (non-ascii) characters in python?,outbytes = yourstring.encode('utf-8')
|
insert a list `k` at the front of list `a`,"a.insert(0, k)"
|
"in django, how do i clear a sessionkey?",del request.session['mykey']
|
filter dataframe `df` by sub-level index '0630' in pandas,df[df.index.map(lambda x: x[1].endswith('0630'))]
|
python converting datetime to be used in os.utime,settime = time.mktime(ftime.timetuple())
|
how do i split an ndarray based on array of indexes?,"print(np.split(a, b, axis=0))"
|
how do i order fields of my row objects in spark (python),"rdd.toDF(['foo', 'bar'])"
|
regular expression substitution in python,"line = re.sub('\\(+as .*?\\) ', '', line)"
|
how do i make a django modelform menu item selected by default?,form = MyModelForm(instance=someinst)
|
how do i send data to a running python thread?,time.sleep(0.1)
|
argsort for a multidimensional ndarray,"a[np.arange(np.shape(a)[0])[:, (np.newaxis)], np.argsort(a)]"
|
how to get pdf filename with python requests?,r.headers['content-disposition']
|
how to sort a dataframe in python pandas by two or more columns?,"df1 = df1.sort(['a', 'b'], ascending=[True, False])"
|
convert a list `my_list` into string with values separated by spaces,""""""" """""".join(my_list)"
|
changing the referrer url in python requests,"requests.get(url, headers={'referer': my_referer})"
|
how to get all youtube comments with python's gdata module?,"""""""https://gdata.youtube.com/feeds/api/videos/{video_id}/comments?start-index={sta rt_index}&max-results={max_results}"""""""
|
how to query multiindex index columns values in pandas,result_df.index.get_level_values('A')
|
django - include app urls,__init__.py
|
how to check if an object is created with `with` statement?,x.do_something()
|
create a list by appending components from list `a` and reversed list `b` interchangeably,"[value for pair in zip(a, b[::-1]) for value in pair]"
|
split array at value in numpy,"B = np.split(A, np.where(A[:, (0)] == 0.0)[0][1:])"
|
how do you specify the foreign key column value in sqlalchemy?,"users = relationship('User', backref='account')"
|
pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * series)
|
how to reduce queries in django model has_relation method?,Person.objects.exclude(pets=None)
|
how to change font properties of a matplotlib colorbar label?,"plt.colorbar().set_label(label='a label', size=15, weight='bold')"
|
"remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`","str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')"
|
set the default encoding to 'utf-8',sys.setdefaultencoding('utf8')
|
looking for a more pythonic way to access the database,cursor.execute('delete from ...')
|
adding calculated column(s) to a dataframe in pandas,d['A'][:-1] < d['C'][1:]
|
making a python program wait until twisted deferred returns a value,reactor.run()
|
delete every non utf-8 symbols froms string,"line = line.decode('utf-8', 'ignore').encode('utf-8')"
|
divide two lists in python,"map(truediv, a, b)"
|
django: save image from url inside another model,"self.image.save('test.jpg', ContentFile(content), save=False)"
|
ordering django queryset by an @property,"sorted(Thing.objects.all(), key=lambda t: t.name)"
|
converting a string to list in python,"[int(x) for x in '0,1,2'.split(',')]"
|
numpy einsum to get axes permutation,"np.einsum('kij->ijk', M)"
|
url encoding in python,urllib.parse.quote('%')
|
how do i wrap a string in a file in python?,f = io.StringIO('foo')
|
python regexp groups: how do i get all groups?,"re.findall('[a-z]+', s)"
|
get a list of lists with summing the values of the second element from each list of lists `data`,[[sum([x[1] for x in i])] for i in data]
|
pandas: replace string with another string,df['prod_type'] = 'responsive'
|
python: sum string lengths,length = sum(len(s) for s in strings)
|
collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).upper()"
|
how do i print out the full url with tweepy?,print(url['expanded_url'])
|
list of unicode strings,"['aaa', 'bbb', 'ccc']"
|
how do you calculate correlation between all columns in a dataframe and all columns in another dataframe?,df1.apply(lambda s: df2.corrwith(s))
|
what is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 5))
|
explicit line joining in python,""""""", """""".join(('abc', 'def', 'ghi'))"
|
remove all characters from string `stri` upto character 'i',"re.sub('.*I', 'I', stri)"
|
most pythonic way to split an array by repeating elements,"nSplit(['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g'], 'X', 2)"
|
how to replace (or strip) an extension from a filename in python?,print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
|
how to run webpage code with phantomjs via ghostdriver (selenium),driver.get('http://stackoverflow.com')
|
merge two arrays into a matrix in python and sort,"A2, B2 = zip(*sorted(zip(A, B), key=lambda x: x[1]))"
|
"printing a list of lists, without brackets","print(item[0], ', '.join(map(str, item[1:])))"
|
formatting a list of text into columns,return '\n'.join(lines)
|
how do i release memory used by a pandas dataframe?,df.dtypes
|
convert hex string `s` to integer,"int(s, 16)"
|
create an array containing the conversion of string '100110' into separate elements,"np.array(map(int, '100110'))"
|
replace a string in list of lists,"[['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]"
|
plot single data with two y axes (two units) in matplotlib,ax2.set_ylabel('Sv')
|
how do i sort a python list of dictionaries given a list of ids with the desired order?,users.sort(key=lambda x: order.index(x['id']))
|
convert pandas dataframe to sparse numpy matrix directly,scipy.sparse.csr_matrix(df.values)
|
python: how to get pid by process name?,get_pid('chrome')
|
how do i return a string from a regex match in python,"imtag = re.match('<img.*?>', line).group(0)"
|
reading 3 bytes as an integer,"print(struct.unpack('>I', '\x00' + s)[0])"
|
python - simple reading lines from a pipe,sys.stdout.flush()
|
python requests encoding post data,urllib.parse.unquote_plus('Andr%C3%A9+T%C3%A9chin%C3%A9').decode('utf-8')
|
execute file 'filename.py',"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))"
|
grouping pandas dataframe by n days starting in the begining of the day,df['date'] = df['time'].apply(lambda x: x.date())
|
extract first and last row of a dataframe `df`,"pd.concat([df.head(1), df.tail(1)])"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.