text
stringlengths
4
1.08k
disable logging while running unit tests in python django,logging.disable(logging.CRITICAL)
convert csv file `result.csv` to pandas dataframe using separator ' ',"df.to_csv('Result.csv', index=False, sep=' ')"
python: how to generate a 12-digit random number?,"'%0.12d' % random.randint(0, 999999999999)"
finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)]), 0]"
how to resample a df with datetime index to exactly n equally sized periods?,"df.resample('216000S', how='sum')"
plot a bar graph from the column 'color' in the dataframe 'df',df.colour.value_counts().plot(kind='bar')
transforming the string `s` into dictionary,"dict(map(int, x.split(':')) for x in s.split(','))"
representing version number as regular expression,"""""""\\d+(\\.\\d+)*$"""""""
how to animate a scatter plot?,plt.show()
convert a string of bytes into an int (python),"struct.unpack('<L', 'y\xcc\xa6\xbb')[0]"
convert year/month/day to day of year in python,day_of_year = datetime.now().timetuple().tm_yday
count the number of occurrence of values based on another column,df.Country.value_counts().reset_index(name='Sum of Accidents')
custom python list sorting,alist.sort(key=lambda x: x.foo)
how do i tell matplotlib that i am done with a plot?,plt.clf()
proxies with python 'requests' module,"r = requests.get(url, headers=headers, proxies=proxyDict)"
tweaking axis labels and names orientation for 3d plots in matplotlib,plt.show()
how can i vectorize this triple-loop over 2d arrays in numpy?,"np.einsum('im,jm,km->ijk', x, y, z)"
django rest framework - how to test viewset?,"self.assertEqual(response.status_code, 200)"
how to repeat pandas data frame?,pd.concat([x] * 5)
how can i kill a thread in python,thread.exit()
"find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x`","re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)"
is there a way to access the context from everywhere in django?,return {'ip_address': request.META['REMOTE_ADDR']}
sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (-sum(x[1:]), x[0]))"
create new string with unique characters from `s` seperated by ' ',print(' '.join(OrderedDict.fromkeys(s)))
matplotlib 3d scatter plot with colorbar,fig.colorbar(p)
index 2d numpy array by a 2d array of indices without loops,"array([[0, 0], [1, 1], [2, 2]])"
get the number of nan values in each column of dataframe `df`,df.isnull().sum()
multiplying rows and columns of python sparse matrix by elements in an array,"numpy.dot(numpy.dot(a, m), a)"
plotting different colors in matplotlib,plt.show()
sort list of strings in list `the_list` by integer suffix,"sorted(the_list, key=lambda k: int(k.split('_')[1]))"
matching blank lines with regular expressions,"re.split('(?m)^\\s*$\\s*', text)"
sorting alphanumerical dictionary keys in python,"keys.sort(key=lambda k: (k[0], int(k[1:])))"
python: defining a union of regular expressions,"[': error:', 'cc1plus:']"
how to sort a scipy array with order attribute when it does not have the field names?,"x = np.array([(1, 0), (0, 1)])"
how do i fit a sine curve to my data with pylab and numpy?,plt.show()
python: check if an numpy array contains any element of another array,"np.any(np.in1d(a1, a2))"
list of ints into a list of tuples python,"my_new_list = zip(my_list[0::2], my_list[1::2])"
how to get object from pk inside django template?,"return render_to_response('myapp/mytemplate.html', {'a': a})"
string formatting in python,"print('[%i, %i, %i]' % (1, 2, 3))"
python dict comprehension with two ranges,"{i: j for i, j in zip(list(range(1, 5)), list(range(7, 11)))}"
how to get rid of punctuation using nltk tokenizer?,"['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']"
convert csv file to list of dictionaries,"[{'col3': 3, 'col2': 2, 'col1': 1}, {'col3': 6, 'col2': 5, 'col1': 4}]"
add a vertical slider with matplotlib,ax.set_xticks([])
python mysqldb typeerror: not all arguments converted during string formatting,"cur.execute(""SELECT * FROM records WHERE email LIKE '%s'"", [search])"
how do i exclude an inherited field in a form in django?,"super(UsuarioForm, self).__init__(*args, **kwargs)"
sort dictionary `x` by value in ascending order,"sorted(list(x.items()), key=operator.itemgetter(1))"
convert integer to binary,"your_list = map(int, your_string)"
subtract values in one list from corresponding values in another list - python,"C = [(a - b) for a, b in zip(A, B)]"
starting two methods at the same time in python,threading.Thread(target=play1).start()
how can i convert a unicode string into string literals in python 2.7?,print(s.encode('unicode_escape'))
how to find match items from two lists?,set(data1).intersection(data2)
binarize a float64 pandas dataframe in python,"pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)"
python logging - disable logging from imported modules,logger = logging.getLogger(__name__)
remove newline from file in python,"str2 = str.replace('\n', '')"
from multiindexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`,"data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]"
how to use pandas dataframes and numpy arrays in rpy2?,"r.plot([1, 2, 3], [1, 2, 3], xlab='X', ylab='Y')"
how to make two markers share the same label in the legend using matplotlib?,plt.show()
why i can't convert a list of str to a list of floats?,"['0', '182', '283', '388', '470', '579', '757', '']"
sort dictionary `d` by value in descending order,"sorted(d, key=d.get, reverse=True)"
how to convert nonetype to int or string?,int(0 if value is None else value)
pandas dataframe groupby two columns and get counts,"df.groupby(['col5', 'col2']).size()"
remove backslashes from string `result`,"result.replace('\\', '')"
convert unicode text from list `elems` with index 0 to normal text 'utf-8',elems[0].getText().encode('utf-8')
how to close a tkinter window by pressing a button?,root.destroy()
convert bytes to a python string,"""""""abcde"""""".decode('utf-8')"
python beautifulsoup extract specific urls,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))"
how to sort with lambda in python,"sorted(iterable, cmp=None, key=None, reverse=False)"
read a text file 'very_important.txt' into a string variable `str`,"str = open('very_Important.txt', 'r').read()"
filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'l',"list(dict((x['id'], x) for x in L).values())"
get current datetime in iso format,datetime.datetime.now().isoformat()
how should i best store fixed point decimal values in python for cryptocurrency?,decimal.Decimal('1.10')
scientific notation colorbar in matplotlib,plt.show()
what alterations do i need to make for my flask python application to use a mysql database?,db.session.commit()
"django-social-auth : connected successfully, how to query for users now?",user.social_auth.filter(provider='...')
sorting a 2d list alphabetically?,lst.sort()
how do i print bold text in python?,print('\x1b[0m')
merging multiple dataframes on column,merged.reset_index()
python: how can i find all files with a particular extension?,results += [each for each in os.listdir(folder) if each.endswith('.c')]
matplotlib - extracting data from contour lines,plt.show()
clamping floating number `my_value` to be between `min_value` and `max_value`,"max(min(my_value, max_value), min_value)"
automatically setting y-axis limits for bar graph using matplotlib,plt.show()
how to unzip a list of tuples into individual lists?,zip(*l)
remove italics in latex subscript in matplotlib,plt.xlabel('Primary T$_{\\rm eff}$')
pandas dataframe select columns in multiindex,"df.xs('A', level='Col', axis=1)"
"how to set a variable to be ""today's"" date in python/pandas",dt.datetime.today().strftime('%m/%d/%Y')
add second axis to polar plot,"plt.setp(ax.get_yticklabels(), color='darkblue')"
how to convert datetime to string in python in django,{{(item.date | date): 'Y M d'}}
filter a dictionary `d` to remove keys with value none and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v is None)"
how to group dataframe by a period of time?,"df.groupby([df.index.map(lambda t: t.minute), 'Source'])"
check if all values of a dictionary `your_dict` are zero `0`,all(value == 0 for value in list(your_dict.values()))
convert backward slash to forward slash in python,"var.replace('\\', '/')"
import file from parent directory?,sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
storing a collection of integers in a list,"[3, 4, 1, 2]"
best way to strip punctuation from a string in python,"myString.translate(None, string.punctuation)"
where's the error in this for loop to generate a list of ordered non-repeated combinations?,"[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]"
how can i list the contents of a directory in python?,"print(os.path.join(path, filename))"
converting a pandas groupby object to dataframe,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()"
reshaping array into a square array python,"x.reshape(2, 2, 5).transpose(1, 0, 2)"
python's webbrowser launches ie instead of default on windows 7,webbrowser.open('file://' + os.path.realpath(filename))
"strip all non-ascii characters from a unicode string, `\xa3\u20ac\xa3\u20ac`","print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))"