text
stringlengths
4
1.08k
python argparse with dependencies,"parser.add_argument('host', nargs=1, help='ip address to lookup')"
How to send email attachments with Python,"smtp.sendmail(send_from, send_to, msg.as_string())"
How to get return value from coroutine in python,print(list(sk.d.items()))
How to set a cell to NaN in a pandas dataframe,"pd.to_numeric(df['y'], errors='coerce')"
How to save Xlsxwriter file in certain path?,workbook = xlsxwriter.Workbook('demo.xlsx')
How to update/modify a XML file in python?,et.write('file_new.xml')
Extract row with maximum value in a group pandas dataframe,df.iloc[df.groupby(['Mt']).apply(lambda x: x['count'].idxmax())]
How to get the current model instance from inlineadmin in Django,"return super(MyModelAdmin, self).get_form(request, obj, **kwargs)"
Setting different color for each series in scatter plot on matplotlib,"plt.scatter(x, y, color=c)"
matplotlib problems plotting logged data and setting its x/y bounds,plt.show()
flask : how to architect the project with multiple apps?,settings.py
convert a string of bytes into an int (python),"int.from_bytes('y\xcc\xa6\xbb', byteorder='big')"
How do I turn a dataframe into a series of lists?,"print(pd.Series(df.values.tolist(), index=df.index))"
Simple way of creating a 2D array with random numbers (Python),[[random.random() for x in range(N)] for y in range(N)]
Comparing lists of dictionaries,"return [d for d in list1 if (d['classname'], d['testname']) not in check]"
Convert DataFrame column type from string to datetime,pd.to_datetime(pd.Series(['05/23/2005']))
How to get the difference of two querysets in Django,set(alllists).difference(set(subscriptionlists))
How to de-import a Python module?,"delete_module('psyco', ['Psycho', 'KillerError'])"
variable length of %s with the % operator in python,"print('<%.*s>' % (len(text) - 2, text))"
Find Synonyms for multi-word phrases,print(wn.synset('main_course.n.01').lemma_names)
How to unset csrf in modelviewset of django-rest-framework?,"return super(MyModelViewSet, self).dispatch(*args, **kwargs)"
Reading a CSV into pandas where one column is a json string,"df = pandas.read_csv(f1, converters={'stats': CustomParser}, header=0)"
generating a CSV file online on Google App Engine,"writer.writerow(['Date', 'Time', 'User'])"
Can a value in a Python Dictionary have two values?,"afc = {'Baltimore Ravens': (10, 3), 'Pb Steelers': (3, 4)}"
Accepting a dictionary as an argument with argparse and python,"dict(""{'key1': 'value1'}"")"
masking part of a contourf plot in matplotlib,plt.show()
Standard way to open a folder window in linux?,"os.system('xdg-open ""%s""' % foldername)"
python library to beep motherboard speaker,"call(['echo', '\x07'])"
Find dictionary keys with duplicate values,"[values for key, values in list(rev_multidict.items()) if len(values) > 1]"
How can I get the previous week in Python?,"start_delta = datetime.timedelta(days=weekday, weeks=1)"
How do I autosize text in matplotlib python?,plt.tight_layout()
Append two multiindexed pandas dataframes,"pd.concat([df_current, df_future]).sort_index()"
How to convert signed to unsigned integer in python,bin(_)
numpy: efficiently reading a large array,"a = a.reshape((m, n)).T"
How to create a list or tuple of empty lists in Python?,result = [list(someListOfElements) for _ in range(x)]
Python: How to remove all duplicate items from a list,x = list(set(x))
passing variable from javascript to server (django),document.getElementById('geolocation').submit()
Boxplot with variable length data in matplotlib,plt.show()
Creating a program that prints true if three words are entered in dictionary order,print(all(lst[i].lower() < lst[i + 1].lower() for i in range(len(lst) - 1)))
get count of values associated with key in dict python,len([x for x in s if x['success']])
Choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: (x[1], random.random()))"
Converting integer to binary in python,bin(6)[2:].zfill(8)
How do I format a string using a dictionary in python-3.x?,"""""""foo is {foo}, bar is {bar} and baz is {baz}"""""".format(**d)"
python convert list to dictionary,"dict(zip(it, it))"
Pandas: remove reverse duplicates from dataframe,"data.apply(lambda r: sorted(r), axis=1).drop_duplicates()"
"decoupled frontend and backend with Django, webpack, reactjs, react-router","STATICFILES_DIRS = os.path.join(BASE_DIR, 'app'),"
Removing letters from a list of both numbers and letters,sum(int(c) for c in strs if c.isdigit())
How to print utf-8 to console with Python 3.4 (Windows 8)?,print(text.encode('utf-8'))
Numpy 2D array: change all values to the right of NaNs,"arr[np.maximum.accumulate(np.isnan(arr), axis=1)] = np.nan"
Adding a string in front of a string for each item in a list in python,n = [(i if i.startswith('h') else 'http' + i) for i in n]
Writing a Python list into a single CSV column,writer.writerow([val])
How to put parameterized sql query into variable and then execute in Python?,"cursor.execute(sql_and_params[0], sql_and_params[1:])"
Python string formatting,"'%3d\t%s' % (42, 'the answer to ...')"
"Python, pandas: how to sort dataframe by index",df.sort_index(inplace=True)
Summing rows from a MultiIndex pandas df based on index label,print(df.head())
How to get the name of an open file?,print(os.path.basename(sys.argv[0]))
How to draw line inside a scatter plot,"plt.savefig('scatter_line.png', dpi=80)"
How to upload image file from django admin panel ?,"urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)"
(Django) how to get month name?,{{a_date | date('F')}}
Regular expression matching all but a string,"res = re.findall('-(?!(?:aa|bb)-)(\\w+)(?=-)', s)"
Looping over a list of objects within a Django template,entries_list = Recipes.objects.order_by('-id')[0:10]
How to set my xlabel at the end of xaxis,plt.show()
Plot single data with two Y axes (two units) in matplotlib,ax2.set_ylabel('Sv')
Most Pythonic way to print *at most* some number of decimal places,"format(f, '.2f').rstrip('0').rstrip('.')"
How can I memoize a class instantiation in Python?,self.somevalue = somevalue
Matplotlib: Vertical lines in scatter plot,plt.show()
Regex: How to match sequence of key-value pairs at end of string,"pairs = dict([match.split(':', 1) for match in matches])"
Python cleaning dates for conversion to year only in Pandas,"df['datestart'] = pd.to_datetime(df['datestart'], coerce=True)"
How do I determine the size of an object in Python?,sys.getsizeof('this also')
Custom constructors for models in Google App Engine (python),"rufus = Dog(name='Rufus', breeds=['spaniel', 'terrier', 'labrador'])"
How can I use a nested name as the __getitem__ index of the previous iterable in list comprehensions?,[x for i in range(len(l)) for x in l[i]]
How to use a file in a hadoop streaming job using python?,"f = open('user_ids', 'r')"
Removing Set Identifier when Printing sets in Python,"print(', '.join(words))"
Python List of np arrays to array,np.vstack(dat_list)
Choosing a maximum randomly in the case of a tie?,"max(l, key=lambda x: x[1] + random.random())"
pandas: create single size & sum columns after group by multiple columns,"df.xs('size', axis=1, level=1)"
How can I turn 000000000001 into 1?,"int('08', 10)"
How to check if a datetime object is localized with pytz?,self.date = d.replace(tzinfo=pytz.utc)
How do I move the last item in a list to the front in python?,"a.insert(0, a.pop())"
Python: sort an array of dictionaries with custom comparator?,"key = lambda d: d.get('rank', float('inf'))"
Convert a 1D array to a 2D array in numpy,"new = np.reshape(a, (-1, ncols))"
what is numpy way of arranging numpy 2D array based on 2D numpy array of index?,"x[np.arange(x.shape[0])[..., (None)], y]"
Python: Finding the last index of min element?,"min(list(range(len(values))), key=lambda i: (values[i], -i))"
What is a 'good practice' way to write a Python GTK+ application?,gtk.main()
Replace the single quote (') character from a string,""""""""""""".join([c for c in string if c != ""'""])"
Convert string to binary in python,print(' '.join(['{0:b}'.format(x) for x in a_bytes]))
How do I plot hatched bars using pandas?,"df.plot(ax=ax, kind='bar', legend=False)"
Converting a list to a string,file2.write(' '.join(buffer))
Is there a Python equivalent of Ruby's 'any?' function?,any(pred(x) for x in lst)
Converting datetime.date to UTC timestamp in Python,timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
How to dynamically change base class of instances at runtime?,"setattr(Person, '__mro__', (Person, Friendly, object))"
How to find out if the elements in one list are in another?,print([x for x in A if all(y in x for y in B)])
Open a text file using notepad as a help file in python?,os.startfile('file.txt')
Matplotlib scatter plot with legend,plt.show()
Python: How to generate a 12-digit random number?,'%012d' % random.randrange(10 ** 12)
Multiple lines of x tick labels in matplotlib,ax.set_xticklabels(xlbls)
Python - Bulk Select then Insert from one DB to another,"cursor.execute('ATTACH ""/path/to/main.sqlite"" AS master')"
How can I programmatically authenticate a user in Django?,return HttpResponseRedirect('/splash/')
Python converting lists into 2D numpy array,"np.transpose([list1, list2, list3])"
Writing hex data into a file,fout.write(binascii.unhexlify(''.join(line.split())))