text
stringlengths 4
1.08k
|
|---|
how python http request and response works,"urllib.parse.urlencode({'data': {'wifi': {'ssid': 'guest', 'rssi': '80'}}})"
|
expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))"
|
how to use logging inside gevent?,"logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(msg)s')"
|
efficient array operations in python,transmission_array.extend(zero_array)
|
sort list `list_` based on first element of each tuple and by the length of the second element of each tuple,"list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])"
|
how do i abort the execution of a python script?,sys.exit()
|
get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions,"list(itertools.product(list(range(-x, y)), repeat=dim))"
|
exit while loop in python,sys.exit()
|
how to compare elements in a list of lists and compare keys in a list of lists in python?,len(set(a))
|
efficient way to create strings from a list,"['_'.join(k + v for k, v in zip(d, v)) for v in product(*list(d.values()))]"
|
how can i use named arguments in a decorator?,"return func(*args, **kwargs)"
|
generate pdf file `output_filename` from markdown file `input_filename`,"with open(input_filename, 'r') as f:
|
html_text = markdown(f.read(), output_format='html4')
|
pdfkit.from_string(html_text, output_filename)"
|
sort list `files` based on variable `file_number`,files.sort(key=file_number)
|
django: lookup by length of text field,"ModelWithTextField.objects.filter(text_field__iregex='^.{7,}$')"
|
get all combination of n binary values,"lst = list(itertools.product([0, 1], repeat=n))"
|
"defaultdict of defaultdict, nested",defaultdict(lambda : defaultdict(dict))
|
how can i plot hysteresis in matplotlib?,"ax = fig.add_subplot(111, projection='3d')"
|
sort dict by value python,sorted(data.values())
|
"how to set ticks on fixed position , matplotlib",plt.show()
|
"remove all articles, connector words, etc., from a string in python","re.sub('\\s+(a|an|and|the)(\\s+)', '\x02', text)"
|
python: find the sum of all the multiples of 3 or 5 below 1000,sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
|
how to get all the values from a numpy array excluding a certain index?,a[np.arange(len(a)) != 3]
|
sort a dictionary `d` by length of its values and print as string,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))"
|
how to remove the left part of a string?,"rightmost = re.compile('^Path=').sub('', fullPath)"
|
how to set environment variables in python,os.environ['DEBUSSY'] = '1'
|
python pandas: drop rows of a timeserie based on time range,df.loc[(df.index < start_remove) | (df.index > end_remove)]
|
most pythonic way to extend a potentially incomplete list,"map(lambda a, b: a or b, choicesTxt, [('Choice %i' % n) for n in range(1, 10)])"
|
show the final y-axis value of each line with matplotlib,plt.show()
|
"find all digits in string '6,7)' and put them to a list","re.findall('\\d|\\d,\\d\\)', '6,7)')"
|
counting unique index values in pandas groupby,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique())
|
sum of outer product of corresponding lists in two arrays - numpy,"np.einsum('ik,il->i', x, e)"
|
customize x-axis in matplotlib,plt.show()
|
finding largest value in a dictionary,"max(x, key=lambda i: x[i])"
|
merging a list with a list of lists,[a[x].append(b[x]) for x in range(3)]
|
how to filter (or replace) unicode characters that would take more than 3 bytes in utf-8?,"pattern = re.compile('[^\\u0000-\\uFFFF]', re.UNICODE)"
|
remove character `char` from a string `a`,"a = a.replace(char, '')"
|
using slicers on a multi-index,"df.loc[(slice(None), '2014-05'), :]"
|
permutations with unique values,"[(2, 1, 1), (1, 2, 1), (1, 1, 2)]"
|
python parse comma-separated number into int,"int('1,000,000'.replace(',', ''))"
|
how to check if value is nan in unittest?,assertTrue(math.isnan(nan_value))
|
how to use grep in ipython?,"grep('text', 'path/to/files/*')"
|
python sum of ascii values of all characters in a string,"print(sum(map(ord, my_string)))"
|
how to have a directory dialog in pyqt,"file = str(QFileDialog.getExistingDirectory(self, 'Select Directory'))"
|
"get the output of a subprocess command `echo ""foo""` in command line","subprocess.check_output('echo ""foo""', shell=True)"
|
find the eigenvalues of a subset of dataframe in python,"np.linalg.eigvals(df.replace('n/a', 0).astype(float))"
|
how to check if given variable exist in jinja2 template?,"""""""{{ x.foo }}"""""""
|
how can i generalize my pandas data grouping to more than 3 dimensions?,"pd.concat([df2, df2], axis=1, keys=['tier1', 'tier2'])"
|
most efficient way to access binary files on adls from worker node in pyspark?,"[4957, 4957, 1945]"
|
sum values in list of dictionaries `example_list` with key 'gold',sum(item['gold'] for item in example_list)
|
i want to plot perpendicular vectors in python,plt.show()
|
how to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in list(points.items()) if v[0] < 5 and v[1] < 5}"
|
run a script to populate a django db,sys.path.append('/path/to/your/djangoproject/')
|
two values from one input in python?,"var1, var2 = input('Enter two numbers here: ').split()"
|
how to convert list of intable strings to int,"[try_int(x) for x in ['sam', '1', 'dad', '21']]"
|
how do i get user ip address in django?,get_client_ip(request)
|
how to update mysql with python where fields and entries are from a dictionary?,"cur.execute(sql, list(d.values()))"
|
convert a string to integer with decimal in python,int(Decimal(s))
|
python random sequence with seed,"['list', 'elements', 'go', 'here']"
|
how to remove the space between subplots in matplotlib.pyplot?,ax.set_yticklabels([])
|
how to fix unicode issue when using a web service with python suds,thestring = thestring.decode('utf8')
|
how to find contiguous substrings from a string in python,"['a', 'b', 'c', 'cc', 'd', 'dd', 'ddd', 'c', 'cc', 'e']"
|
remove column from multi index dataframe,df.columns = pd.MultiIndex.from_tuples(df.columns.to_series())
|
output data of the first 7 columns of pandas dataframe,"pandas.set_option('display.max_columns', 7)"
|
ranking of numpy array with possible duplicates,"np.cumsum(np.concatenate(([0], np.bincount(v))))[v]"
|
how to read lines from a file into a multidimensional array (or an array of lists) in python,"arr = [line.split(',') for line in open('./urls-eu.csv')]"
|
find all digits between a character in python,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))"
|
find all keys from a dictionary `d` whose values are `desired_value`,"[k for k, v in d.items() if v == desired_value]"
|
sort python dict by datetime value,"sorted(dct, key=dct.get)"
|
get the size of object `items`,items.__len__()
|
how to send cookies in a post request with the python requests library?,"r = requests.post('http://wikipedia.org', cookies=cookie)"
|
get logical xor of `a` and `b`,(bool(a) != bool(b))
|
splitting the sentences in python,"re.findall('\\w+', ""Don't read O'Rourke's books!"")"
|
django - multiple apps on one webpage?,"url('home/$', app.views.home, name='home')"
|
how to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22})
|
matching id's in beautifulsoup,"print(soupHandler.findAll('div', id=lambda x: x and x.startswith('post-')))"
|
write to csv from dataframe python pandas,"a.to_csv('test.csv', cols=['sum'])"
|
get second array column length of array `a`,a.shape[1]
|
how can i add an element at the top of an ordereddict in python?,"OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])"
|
convert json string '2012-05-29t19:30:03.283z' into a datetime object using format '%y-%m-%dt%h:%m:%s.%fz',"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')"
|
remove empty string from list,mylist[:] = [i for i in mylist if i != '']
|
how do i exit program in try except,sys.exit(1)
|
how to make pylab.savefig() save image for 'maximized' window instead of default size,"fig.savefig('myfig.png', dpi=600)"
|
"in python, how to change text after it's printed?",sys.stdout.flush()
|
how to remove all of the data in a table using django,Reporter.objects.all().delete()
|
add keys in dictionary in sorted order,sorted_dict = collections.OrderedDict(sorted(d.items()))
|
python pandas add column in dataframe from list,"df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6, 5]})"
|
get all sub-elements of an element tree `a` excluding the root element,[elem.tag for elem in a.iter() if elem is not a]
|
how can i build a recursive function in python?,sys.setrecursionlimit()
|
how do i add space between two variables after a print in python,print(str(count) + ' ' + str(conv))
|
intraday candlestick charts using matplotlib,plt.show()
|
how to count the number of occurences of `none` in a list?,print(len([x for x in lst if x is not None]))
|
place '\' infront of each non-letter char in string `line`,"print(re.sub('[_%^$]', '\\\\\\g<0>', line))"
|
how to handle unicode (non-ascii) characters in python?,yourstring = receivedbytes.decode('utf-8')
|
represent datetime object '10/05/2012' with format '%d/%m/%y' into format '%y-%m-%d',"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')"
|
how to set number of ticks in plt.colorbar?,plt.show()
|
converting string to tuple,"[tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]"
|
displaying a list of items vertically in a table instead of horizonally,[l[i::5] for i in range(5)]
|
using django auth user model as a foreignkey and reverse relations,Post.objects.filter(user=request.user).order_by('-timestamp')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.