text
stringlengths 4
1.08k
|
|---|
Django filter JSONField list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_3': [{'key1': 'foo2'}]}])
|
hash unicode string in python,hashlib.sha1(s.encode('utf-8'))
|
Best way to count the number of rows with missing values in a pandas DataFrame,"df.apply(lambda x: sum(x.isnull().values), axis=1)"
|
How to filter a dictionary according to an arbitrary condition function?,"{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}"
|
How to modify a variable inside a lambda function?,"return myFunc(lambda a, b: iadd(a, b))"
|
If any item of list starts with string?,any(item.startswith('qwerty') for item in myList)
|
How can I make an animation with contourf()?,pl.show()
|
When and how to use Python's RLock,self.changeB()
|
How to send file as stream from python to a C library,main()
|
How can I get the IP address of eth0 in Python?,return s.getsockname()[0]
|
How to get one number specific times in an array python,"array([4, 5, 5, 6, 6, 6])"
|
How to replace the first occurrence of a regular expression in Python?,"re.sub('foo', 'bar', s, 1)"
|
How to find the shortest string in a list in Python,"from functools import reduce
|
reduce(lambda x, y: x if len(x) < len(y) else y, l)"
|
SymPy/SciPy: solving a system of ordinary differential equations with different variables,"odeint(dX_dt, [1, 2], np.linspace(0, 1, 5))"
|
How to call a system command with specified time limit in Python?,"os.killpg(self.process.pid, signal.SIGTERM)"
|
3D plot with Matplotlib,ax.set_zlabel('Z')
|
How do I remove all punctuation that follows a string?,"""""""words!?.,;:"""""".rstrip('?:!.,;')"
|
"python, format string","'%s %%s %s' % ('foo', 'bar')"
|
Join last element in list,""""""" & """""".join(['_'.join(inp[:2]), '_'.join(inp[2:])])"
|
Close all open files in ipython,fh.close()
|
Is there a function in Python which generates all the strings of length n over a given alphabet?,"[''.join(i) for i in itertools.product('ab', repeat=4)]"
|
Django: How to filter Users that belong to a specific group,"qs = User.objects.filter(groups__name__in=['foo', 'bar'])"
|
Pythonic way to use range with excluded last number?,"list(range(0, 100, 5))"
|
"How to ""scale"" a numpy array?","np.kron(a, np.ones((n, n)))"
|
Passing newline within string into a python script from the command line,"print(string.replace('\\n', '\n'))"
|
Converting from a string to boolean in Python?,str2bool('no')
|
Converting from a string to boolean in Python?,str2bool('stuff')
|
Converting from a string to boolean in Python?,str2bool('1')
|
Converting from a string to boolean in Python?,str2bool('0')
|
Python: print a generator expression?,[x for x in foo]
|
Secondary axis with twinx(): how to add to legend?,plt.show()
|
Best way to get the nth element of each tuple from a list of tuples in Python,"[x for x, y, z in G]"
|
Django urls with empty values,"url('^api/student/(?P<pk>.*)/(?P<pk2>.*)/$', api.studentList.as_view()),"
|
Writing nicely formatted text in Python,"f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))"
|
get UTC timestamp in python with datetime,dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))
|
How to sort a dataFrame in python pandas by two or more columns?,"df1 = df1.sort(['a', 'b'], ascending=[True, False])"
|
List indexes of duplicate values in a list with Python,"print(list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5]))"
|
delete the first element in subview of a matrix,"b = np.delete(a, i, axis=0)"
|
String arguments in python multiprocessing,"p = multiprocessing.Process(target=write, args=('hello',))"
|
Find element by text with XPath in ElementTree,"print(doc.xpath('//element[text()=""A""]')[0].tag)"
|
Is there a way to use ribbon toolbars in Tkinter?,root.mainloop()
|
How to initialize nested dictionaries in Python,my_tree['a']['b']['c']['d']['e'] = 'whatever'
|
Trying to converting a matrix 1*3 into a list,my_list = [col for row in matrix for col in row]
|
Simple Python Regex Find pattern,"print(re.findall('\\bv\\w+', thesentence))"
|
How to check the existence of a row in SQLite with Python?,"cursor.execute('create table components (rowid int,name varchar(50))')"
|
python BeautifulSoup searching a tag,"print(soup.find_all('a', {'class': 'black'}))"
|
3D plot with Matplotlib,ax.set_xlabel('X')
|
"How can I get the values that are common to two dictionaries, even if the keys are different?",list(set(dict_a.values()) & set(dict_b.values()))
|
How to extract the year from a Python datetime object?,a = datetime.date.today().year
|
finding duplicates in a list of lists,"map(list, list(totals.items()))"
|
convert String to MD5,hashlib.md5('fred'.encode('utf')).hexdigest()
|
Write multiple NumPy arrays into CSV file in separate columns?,"np.savetxt('output.dat', output, delimiter=',')"
|
find row or column containing maximum value in numpy array,"np.argmax(np.max(x, axis=1))"
|
Multiple Element Indexing in multi-dimensional array,"array([0.49482768, 0.53013301, 0.4485054, 0.49516017, 0.47034123])"
|
reading a file in python,"reader = csv.reader(open('filename'), delimiter='\t')"
|
Python + MySQLdb executemany,cursor.close()
|
if/else statements accepting strings in both capital and lower-case letters in python,"""""""3"""""".lower()"
|
How to make lists distinct?,my_list = list(set(my_list))
|
dict keys with spaces in Django templates,{{(test | getkey): 'this works'}}
|
how to make arrow that loops in matplotlib?,plt.show()
|
Print a big integer with punctions with Python3 string formatting mini-language,"""""""{:,}"""""".format(x).replace(',', '.')"
|
"""pythonic"" method to parse a string of comma-separated integers into a list of integers?","mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]"
|
How to properly use python's isinstance() to check if a variable is a number?,"isinstance(var, (int, float, complex))"
|
Convert strings to int or float in python 3?,print('2 + ' + str(integer) + ' = ' + str(rslt))
|
How to make markers on lines smaller in matplotlib?,"plt.errorbar(x, y, yerr=err, fmt='-o', markersize=2, color='k', label='size 2')"
|
How do I modify the last line of a file?,f.close()
|
Django M2M QuerySet filtering on multiple foreign keys,"participants = models.ManyToManyField(User, related_name='conversations')"
|
Changing file permission in python,"subprocess.call(['chmod', '0444', 'path'])"
|
How do I query objects of all children of a node with Django mptt?,Student.objects.filter(studentgroup__level__pk=1)
|
Python: How can I find all files with a particular extension?,glob.glob('?.gif')
|
How to read a config file using python,"self.path = configParser.get('your-config', 'path1')"
|
parsing json fields in python,print(b['indices']['client_ind_2']['index'])
|
How to create a menu and submenus in Python curses?,self.window.keypad(1)
|
How can I simulate input to stdin for pyunit?,"sys.stdin = open('simulatedInput.txt', 'r')"
|
Add custom method to string object,sayhello('JOHN'.lower())
|
From ND to 1D arrays,a.flatten()
|
How do you get a directory listing sorted by creation date in python?,files.sort(key=lambda x: os.path.getmtime(x))
|
How to create list of 3 or 4 columns of Dataframe in Pandas when we have 20 to 50 colums?,df[df.columns[2:5]]
|
Getting Unique Foreign Keys in Django?,Farm.objects.filter(tree__in=TreeQuerySet)
|
Django circular model reference,team = models.ForeignKey('Team')
|
Convert base-2 binary number string to int,"int('11111111', 2)"
|
Changing the color of the offset in scientific notation in matplotlib,"ax1.ticklabel_format(style='sci', scilimits=(0, 0), axis='y')"
|
How can I check a Python unicode string to see that it *actually* is proper Unicode?,""""""""""""".decode('utf8')"
|
Reading in integer from stdin in Python,bin('10')
|
Spawning a thread in python,t.start()
|
Matplotlib contour plot with intersecting contour lines,plt.show()
|
sorting lines of file python,"re.split('\\s+', line)"
|
Get starred messages from GMail using IMAP4 and python,IMAP4.select('[Gmail]/Starred')
|
Find First Non-zero Value in Each Row of Pandas DataFrame,"df.replace(0, np.nan).bfill(1).iloc[:, (0)]"
|
How to create a hyperlink with a Label in Tkinter?,root.mainloop()
|
Retrieving contents from a directory on a network drive (windows),os.listdir('\\networkshares\\folder1\\folder2\\folder3')
|
python cherrypy - how to add header,cherrypy.quickstart(Root())
|
Why Pandas Transform fails if you only have a single column,df.groupby('a')['a'].transform('count')
|
How can I run an external command asynchronously from Python?,p.terminate()
|
python pandas: plot histogram of dates?,df.date = df.date.astype('datetime64')
|
How to access HttpRequest from urls.py in Django,"return super(MyListView, self).dispatch(request, *args, **kwargs)"
|
Index the first and the last n elements of a list,l[:3] + l[-3:]
|
How to find common elements in list of lists?,set([1])
|
How to get the number of <p> tags inside div in scrapy?,"len(response.xpath('//div[@class=""entry-content""]/p'))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.