text
stringlengths
4
1.08k
How to get status of uploading file in Flask,"request.META['REMOTE_ADDR'], request.GET['X-Progress-ID']"
Convert a list of characters into a string,""""""""""""".join(a)"
Plot two histograms at the same time with matplotlib,plt.show()
Pandas conditional creation of a series/dataframe column,"df['color'] = np.where(df['Set'] == 'Z', 'green', 'red')"
Find indices of a value in 2d matrix,"[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]"
Getting Unique Foreign Keys in Django?,"farms = qs.values_list('farm', flat=True).distinct()"
Remove lines from textfile with python,"open('newfile.txt', 'w').writelines(lines[3:-1])"
How do i visualize a connection Matrix with Matplotlib?,plt.show()
Detecting non-ascii characters in unicode string,"print(re.sub('[ -~]', '', '\xa3100 is worth more than \u20ac100'))"
How do I insert a JPEG image into a python Tkinter window?,window.geometry('450x1000+200+0')
Sorting numpy array according to the sum,"np.take(a, idx, axis=1)"
How to create an integer array within a recursion?,return foo(n - 1) + [1]
How to teach beginners reversing a string in Python?,'dammit im mad'[::-1] == 'dammit im mad'
"How can I print a string using .format(), and print literal curly brackets around my replaced string","""""""{{{0}:{1}}}"""""".format('hello', 'bonjour')"
Parsing html data into python list for manipulation,"['13.46', '20.62', '26.69', '30.17', '32.81']"
Django return redirect() with parameters,request.session['temp_data'] = form.cleaned_data
Regex match if not before and after,"re.search('suck', s)"
Automate png formatting with python,img.save('titled_plot.png')
Extract array from list in python,zip(*data)
How to create a ssh tunnel using python and paramiko?,ssh.close()
KDB+ like asof join for timeseries data in pandas?,df1.apply(lambda x: x.asof(df2.index))
Pandas cumulative sum of partial elements with groupby,df['*PtsPerOrder*'] = df.groupby('OrderNum')['PtsPerLot'].transform(sum)
Django equivalent of COUNT with GROUP BY,Player.objects.values('player_type').order_by().annotate(Count('player_type'))
How to merge two Python dictionaries in a single expression?,c = dict(list(a.items()) + list(b.items()))
How can I convert an RGB image into grayscale in Python?,"gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)"
Removing duplicates in each row of a numpy array,numpy.array([v for v in vals if len(numpy.unique(v)) == len(v)])
Sorting associative arrays in Python,"sorted(people, key=lambda dct: dct['name'])"
How to remove a path prefix in Python?,"print(os.path.relpath(full_path, '/book/html'))"
Python requests can't send multiple headers with same key,"headers = {'X-Attribute': 'A', 'X-Attribute': 'B'}"
Combine or join numpy arrays,"[(0, 0), (0, 1), (1, 0), (1, 1)]"
Case Insensitive Python string split() method,"re.split('\\s*[Ff]eat\\.', a)"
Find dictionary keys with duplicate values,"[key for key, values in list(rev_multidict.items()) if len(values) > 1]"
Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', s)"
"How do I get a string format of the current date time, in python?","datetime.datetime.now().strftime('%I:%M%p on %B %d, %Y')"
How to visualize descriptor matching using opencv module in python,cv2.waitKey()
How to size my imshow?,plt.show()
How do I replace a character in a string with another character in Python?,"print(re.sub('[^i]', '!', str))"
How to reverse tuples in Python?,reversed(x)
Checking if a datetime object in mongodb is in UTC format or not from python,v.astimezone(pytz.timezone('US/Eastern'))
Get particular row as series from pandas dataframe,df[df['location'] == 'c'].iloc[0]
Representing a multi-select field for weekdays in a Django model,"Entry.objects.extra(where=['weekdays & %s'], params=[WEEKDAYS.fri])"
Saving numpy array to csv produces TypeError Mismatch,"np.savetxt('test.csv', example, delimiter=',')"
Python regex to get everything until the first dot in a string,find = re.compile('^([^.]*).*')
in python: iterate over each string in a list,"[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]"
How to make pylab.savefig() save image for 'maximized' window instead of default size,"fig.savefig('myfig.png', dpi=600)"
How to choose value from an option list using PyQt4.QtWebKit,"option.setAttribute('selected', 'true')"
GPGPU programming in Python,"sum(clarray1, clarray2, clarray3)"
Problems trying to format currency with Python (Django),"locale.setlocale(locale.LC_ALL, 'en_CA.UTF-8')"
Create List of Single Item Repeated n Times in Python,"[['x'], ['x'], ['x'], ['x']]"
How do I create a variable number of variables?,globals()['a']
Python count items in dict value that is a list,count = sum(len(v) for v in d.values())
Get unique values in List of Lists in python,print(list(set(chain(*array))))
How to animate a scatter plot?,plt.show()
Python Split String,"s.split(':', 1)[1]"
Pandas - intersection of two data frames based on column entries,s1.dropna(inplace=True)
How to print Unicode character in Python?,print('\u2713')
How to execute SELECT * LIKE statement with a placeholder in sqlite?,"cursor.execute('SELECT * FROM posts WHERE tags LIKE ?', ('%{}%'.format(tag),))"
Python Matplotlib Buttons,plt.show()
How to split a string into integers in Python?,"a, b = (int(x) for x in s.split())"
interprocess communication in python,listener.close()
How to get a matplotlib Axes instance to plot to?,plt.show()
Global variable in Python server,sys.exit()
Extract string from between quotations,"re.findall('""([^""]*)""', 'SetVariables ""a"" ""b"" ""c"" ')"
Removing rows in a pandas DataFrame where the row contains a string present in a list?,df[~df.From.str.contains('|'.join(ignorethese))]
scatter plot in matplotlib,"matplotlib.pyplot.scatter(x, y)"
How to execute a python script and write output to txt file?,"subprocess.call(['python', './script.py'], stdout=output)"
How can i substract a single value from a column using pandas and python,df['hb'] - 5
Sorting numpy array on multiple columns in Python,"rows_list.sort(key=operator.itemgetter(0, 1, 2))"
conditional row read of csv in pandas,df[df['B'] > 10]
New column based on conditional selection from the values of 2 other columns in a Pandas DataFrame,"df['A'].where(df['A'] > df['B'], df['B'])"
Format time string in Python 3.3,"""""""{0:%Y-%m-%d %H:%M:%S}"""""".format(datetime.datetime.now())"
How to round to two decimal places in Python 2.7?,"round(1.679, 2)"
How to get a matplotlib Axes instance to plot to?,ax = plt.gca()
How to configure logging to syslog in python?,my_logger.setLevel(logging.DEBUG)
How to find a thread id in Python,logging.basicConfig(format='%(threadName)s:%(message)s')
Find lowest value in a list of dictionaries in python,"min([1, 2, 3, 4, 6, 1, 0])"
Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library,print('\xc4\x89'.decode('utf-8').upper())
Print the concatenation of the digits of two numbers in Python,"print('%d%d' % (2, 1))"
Remove strings containing only white spaces from list,[name for name in starring if name.strip()]
How do I display current time using Python + Django?,now = datetime.datetime.now()
Python: how to sort array of dicts by two fields?,"ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))"
Python-Requests close http connection,"r = requests.post(url=url, data=body, headers={'Connection': 'close'})"
Multiindex from array in Pandas with non unique data,"group_position(df['Z'], df['A'])"
Efficiently find indices of all values in an array,{i: np.where(arr == i)[0] for i in np.unique(arr)}
How can I apply a namedtuple onto a function?,func(*r)
scatterplot with xerr and yerr with matplotlib,plt.show()
Python: How to convert a list of dictionaries' values into int/float from string?,"[dict([a, int(x)] for a, x in b.items()) for b in list]"
Create file path from variables,"os.path.join('/my/root/directory', 'in', 'here')"
TypeError in Django with python 2.7,"MEDIA_ROOT = os.path.join(os.path.dirname(file), 'media').replace('\\\\', '//')"
How do I integrate Ajax with Django applications?,"url('^home/', 'myapp.views.home'),"
How can I show figures separately in matplotlib?,plt.show()
How to set the program title in python,os.system('title Yet Another Title')
How to zoomed a portion of image and insert in the same plot in matplotlib,plt.show()
How to pass initial parameter to django's ModelForm instance?,"super(BackupForm, self).__init__(*args, **kwargs)"
Python: efficient counting number of unique values of a key in a list of dictionaries,print(len(set(p['Nationality'] for p in people)))
drop column based on a string condition,"df.drop([col for col in df.columns if 'chair' in col], axis=1, inplace=True)"
How to assign unique identifier to DataFrame row,df.head(10)
bool value of a list in Python,return len(my_list)
How to use map to lowercase strings in a dictionary?,"map(lambda x: {'content': x['content'].lower()}, messages)"
How to compare type of an object in Python?,isinstance()