text
stringlengths
185
26.5k
<s>[INST] Getting a list of all subdirectories in the current directory Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead. [/INST] Do you mean immediate subdirectories, or every directory ri...
<s>[INST] Python - Pytz - List of Timezones? I would like to know what are all the possible values for the timezone argument in the Python library Pytz. SOLUTION for tz in pytz.all_timezones: print tz Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Ba...
<s>[INST] Python Time Seconds to h:m:s I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? [/INST] or you can do >>> import datetime >>> str(datetime.timedelta(seconds=666)) '0:11:0...
<s>[INST] How to manage local vs production settings in Django? What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should ...
<s>[INST] Relative imports in Python 3 I want to import a function from another file in the same directory. Sometimes it works for me with from .mymodule import myfunction but sometimes I get a SystemError: Parent module '' not loaded, cannot perform relative import Sometimes it works with from mymodule import myfun...
<s>[INST] How can I improve my paw detection? After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws. You see, my proof of concept basically took th...
<s>[INST] which day of week given a date python I want to find out the following: given a date (datetime object), what is the corresponding day of the week. For instance Sunday is the first day, Monday: second day.. and so on And then if the input is something like Today's date. The output is maybe 6 (since its Friday)...
<s>[INST] Filter dict to contain only certain keys? I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? [/INST] Constructing a new dict: dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys } Uses di...
<s>[INST] if else in a list comprehension I have a list l: l = [22, 13, 45, 50, 98, 69, 43, 44, 1] For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5. I tried [x+1 for x in l if x >= 45 else x+5] But it gives me a syntax error. How can I achieve an if – else like this in a list com...
<s>[INST] matplotlib Legend Markers Only Once I often plot a point on a matplotlib plot with: x = 10 y = 100 plot(x, y, "k*", label="Global Optimum") legend() However, this causes the legend to put a star in the legend twice, such that it looks like: * * Global Optimum when I really want it to look like: * Global O...
<s>[INST] Why is Python's "append" not "push"? Does anyone know why Python's list.append function is not called list.push given that there's already a list.pop that removes and returns the last element (that indexed at -1) and list.append semantic is consistent with that use? [/INST] Because "append" existed long befo...
<s>[INST] How to get string objects instead of Unicode ones from JSON in Python? I'm using Python 2 to parse JSON from (ASCII encoded) text files. When loading these files with either json or simplejson, all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data ...
<s>[INST] Python - How do I pass a string into subprocess.Popen (using the stdin argument)? If I do the following: import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] I get: Traceback (most recent c...
<s>[INST] How do I find out my python path using python? How do I find out which directories are listed in my system’s PYTHONPATH variable, from within a Python script (or the interactive shell)? [/INST] You would probably also want this: import sys print(sys.path) Or as a one liner from the terminal: python -c "im...
<s>[INST] Python dictionary from an object's fields Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It sho...
<s>[INST] Determine function name from within that function (without using traceback) In Python, without using the traceback module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name?...
<s>[INST] How can I color Python logging output? Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). Now, Python has the logging module, which lets you specify a lot of options to customize output. So, I'm imagining something s...
<s>[INST] Split string on whitespace in Python I'm looking for the Python equivalent of String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] [/INST] The str.split() method without an argument splits on...
<s>[INST] Get HTML Source of WebElement in Selenium WebDriver using Python I'm using the Python bindings to run Selenium WebDriver. from selenium import webdriver wd = webdriver.Firefox() I know I can grab a webelement like so... elem = wd.find_element_by_css_selector('#my-id') And I know I can get the full page sour...
<s>[INST] Get current time in milliseconds in Python? How can I get the current time in milliseconds in Python? [/INST] For what I needed, here's what I did, based on @samplebias' comment above: import time millis = int(round(time.time() * 1000)) print millis Quick'n'easy. Thanks all, sorry for the brain fart. For r...
<s>[INST] How can I make sense of the `else` statement in Python loops? Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause: for val in iterable: do_something(val) else: clean_up() The body of the else clause is a good place for certain ki...
<s>[INST] Relationship between scipy and numpy scipy appears to provide most (but not all [1]) of numpy's functions in its own namespace. In other words, if there's a function named numpy.foo, there's almost certainly a scipy.foo. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the ...
<s>[INST] How to split a string into array of characters with Python? I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method str.split(//) does not seem to work like Ruby does. Is there a simple way of doing this without looping? [/INST]...
<s>[INST] Dump a NumPy array into a csv file Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format. [/INST] numpy.savetxt saves an array to a text file. import numpy a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpy.savetxt("foo.csv", a, delimit...
<s>[INST] Change one character in a string in Python? What is the easiest way in Python to replace a character in a string like: text = "abcdefg"; text[1] = "Z"; ^ [/INST] Don't modify strings. Work with them as lists; turn them into strings only when needed. >>> s = list("Hello zorld") >>> s ['H', 'e', '...
<s>[INST] Iterating through a range of dates in Python I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension. day_count = (end_date - start_date).days + 1 for single_dat...
<s>[INST] How to set environment variables in Python I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number. If I do os.environ["DEBUSSY"] = 1, it c...
<s>[INST] Python String and Integer concatenation I want to create string using integer appended to it, in a for loop. Like this: for i in range [1,10]: string="string"+i But it returns an error: TypeError: unsupported operand type(s) for +: 'int' and 'str' What's the best way to concatenate the String and Integer...
<s>[INST] How do I update pip itself from inside my virtual environment? I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version. What's the command for that? Do I need to use dis...
<s>[INST] How can I create a directly-executable cross-platform GUI app using Python? Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start o...
<s>[INST] Delete Folder Contents in Python How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see *nix also. [/INST] Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, un...
<s>[INST] Get list from pandas DataFrame column headers I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called. For example, if I'm given a DataFrame like this: >>> my_dataframe y gdp c...
<s>[INST] SSL InsecurePlatform error when using Requests package Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with R...
<s>[INST] Read .mat files in Python Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that scipy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed scipy version 0.7.0, and I can't find the loadmat() method) [/INST] Silly me. Forgot to impo...
<s>[INST] How can I get a list of all classes within current module in Python? I've seen plenty of examples of people extracting all of the classes from a module, usually something like: # foo.py class Foo: pass # test.py import inspect import foo for name, obj in inspect.getmembers(foo): if inspect.isclass(o...
<s>[INST] Python try...except comma vs 'as' in except What is the difference between ',' and 'as' in except statements, eg: try: pass except Exception, exception: pass and: try: pass except Exception as exception: pass Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 ...
<s>[INST] Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best wa...
<s>[INST] What is a "callable" in Python? Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and ...
<s>[INST] Best way to convert string to bytes in Python 3? There appears to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface Which of these methods would be better or more Pythonic? Or is it just a matter of personal preference? b = byt...
<s>[INST] Python unittest - opposite of assertRaises? I want to write a test to establish that an Exception is not raised in a given circumstance. It's straightforward to test if an Exception is raised ... sInvalidPath=AlwaysSuppliesAnInvalidPath() self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath) ... bu...
<s>[INST] Most pythonic way to delete a file which may not exist I want to delete the file filename if it exists. Is it proper to say if os.path.exists(filename): os.remove(filename) Is there a better way? A one-line way? [/INST] A more pythonic way would be: try: os.remove(filename) except OSError: pas...
<s>[INST] How to clear python interpreter console? Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes...
<s>[INST] How do I keep Python print from adding newlines or spaces? In python, if I say print 'h' I get the letter h and a newline. If I say print 'h', I get the letter h and no newline. If I say print 'h', print 'm', I get the letter h, a space, and the letter m. How can I prevent Python from printing the spac...
<s>[INST] Is there a reason Python strings don't have a string length method? I know that python has a len() function that is used to determine the size of a string, but I was wondering why its not a method of the string object. Update Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a st...
<s>[INST] Python - The difference between sys.stdout.write and print Are there situations in which sys.stdout.write() is preferable to print? (Examples: better performance; code that makes more sense) [/INST] print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls th...
<s>[INST] How to change the order of DataFrame columns? I have the following DataFrame (df): import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) I add more column(s) by assignment: df['mean'] = df.mean(1) How can I move the column mean to the front, i.e. set it as first column leaving the...
<s>[INST] How can I compare two lists in python and return matches I want to take two lists and find the values that appear in both. a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) would return [5], for instance. [/INST] Not the most efficient one, but by far the most obvious way to do it is: >>> a = [1,...
<s>[INST] Post JSON using Python Requests I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". Here...
<s>[INST] Select rows from a DataFrame based on values in a column in pandas How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: select * from table where colume_name = some_value. I tried to look at pandas documentation but did not immediately find the answer. [/INST] ...
<s>[INST] Find all occurrences of a substring in Python Python has string.find() and string.rfind() to get the index of a substring in string. I wonder, maybe there is something like string.find_all() which can return all founded indexes (not only first from beginning or first from end)? For example: string = "test tes...
<s>[INST] Checking whether a string starts with XXXX I would like to know how to check whether a string starts with "hello" in Python. In Bash I usually do: if [[ "$string" =~ ^hello ]]; then do something here fi How do I achieve the same in Python? [/INST] aString = "hello world" aString.startswith("hello") </s>
<s>[INST] Remove all occurrences of a value from a Python list In Python remove() will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val)...
<s>[INST] Python and pip, list all versions of a package that's available? Given the name of a Python (2.X) package that can be installed with pip and virtualenv, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a versio...
<s>[INST] Strip HTML from strings in Python from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting its...
<s>[INST] Is there any way to do HTTP PUT in python I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python? [/INST] I've used a variety of python HTTP libs in the past, and I've settled on 'Request...
<s>[INST] Python Dictionary Comprehension Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: l = [] for n in range(1, 11): l.append(n) We can shorten this to a list comprehension: l = [n for n in range(1, 11)]. However, say I ...
<s>[INST] Does Python support short-circuiting? Does Python support short-circuiting in boolean expressions? [/INST] Yep, both and and or operators short-circuit -- see the docs. </s>
<s>[INST] How do you round UP a number in Python? This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: round(2.3) = 2.0 and not 3, what I would like The I tried int(number + .5) but it round the number down again! Example: int(2.3 + .5) = ...
<s>[INST] How can I selectively escape percent (%) in Python strings? I have the following code test = "have it break." selectiveEscape = "Print percent % in sentence and not %s" % test print(selectiveEscape) I would like to get the output: Print percent % in sentence and not have it break. What actually happens: ...
<s>[INST] Passing a dictionary to a function in python as keyword parameters I'd like to call a function in python using a dictionary. Here is some code: d = dict(param='test') def f(param): print param f(d) This prints {'param': 'test'} but I'd like it to just print test. I'd like it to work similarly for more ...
<s>[INST] Text Progress Bar in the Console Is there a good way to do the following? I wrote a simple console app to upload and download files from an FTP server using the ftplib. Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number. But I don't want to erase all th...
<s>[INST] Is it possible to run a Python script as a service in Windows? If possible, how? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these ob...
<s>[INST] What is the difference between an expression and a statement in Python? In Python, what is the difference between expressions and statements? [/INST] Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subsc...
<s>[INST] Django gives Bad Request (400) when DEBUG = False I am new to django-1.6. When I run the django server with DEBUG = True, it's running perfectly. But when I change DEBUG to False in the settings file, then the server stopped and it gives the following error on the command prompt: CommandError: You must set se...
<s>[INST] listing all functions in a python module I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available...
<s>[INST] When is del useful in python? I can't really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it. And when deleting from a dictionary, a del method could be added. Is the...
<s>[INST] Permanently add a directory to PYTHONPATH Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? [/INST] If you're using bash (on a Mac or GNU/Linux distro), add...
<s>[INST] Seeking clarification on apparent contradictions regarding weakly typed languages I think I understand strong typing, but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article name...
<s>[INST] Web scraping with Python I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available? [/INST] Use urllib2 in combination with the brilliant BeautifulSoup library: import urllib2 from BeautifulSoup im...
<s>[INST] How to use Xpath in Python? What is the library? Is there a full implementation? How is the library used? Where is its website? [/INST] libxml2 has a number of advantages: Compliance to the spec Active development and a community participation Speed. This is really a python wrapper around a C implementatio...
<s>[INST] Expanding tuples into arguments Is there a way to expand a Python tuple into a function - as actual parameters? For example, here expand() does the magic: tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo")...
<s>[INST] Is there a short contains function for lists? I see people are using any to gather another list to see if an item exists in a list, but is there a quick way to just do?: if list.contains(myItem): # do something [/INST] You can use this syntax: if myItem in list: # do something Also, inverse operato...
<s>[INST] Finding the average of a list I have to find the average of a list in Python. This is my code so far l = [15, 18, 2, 36, 12, 78, 5, 6, 9] print reduce(lambda x, y: x + y, l) I've got it so it adds together the values in the list, but I don't know how to make it divide into them? [/INST] l = [15, 18, 2, 36, ...
<s>[INST] Split a string by spaces -- preserving quoted substrings -- in Python I have a string which is like this: this is "a test" I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ['this','is','a test'] PS. I know you are going to as...
<s>[INST] How can I convert a datetime object to milliseconds since epoch (unix time) in Python? I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this? [/INST] It appears to me that the simplest way to do this is import datetime epoch = dat...
<s>[INST] How to change the font size on a matplotlib plot How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) But how...
<s>[INST] Check if a given key already exists in a dictionary and increment it Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value? I.e., I want to do this: my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 I.e., I want t...
<s>[INST] Does Python SciPy need BLAS? numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. Whic...
<s>[INST] Return None if Dictionary key is not available I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is...
<s>[INST] How to query as GROUP BY in django? I query a model, Members.objects.all() and it returns say Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop What i want is, to know the best Django way to fire a group_by query to my db, as like, Members.objects.all().group_...
<s>[INST] Pandas: change data type of columns I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example: a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a) What is the best way to convert the columns to the appropriate types...
<s>[INST] How do I get list of methods in a Python class? I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods? Also see: How can I list the methods in a Python 2.5 module? Looping over a Python / IronPytho...
<s>[INST] How to use timeit module I understand the concept of what timeit does but I am not sure how to implement it in my code. How can I compare two functions, say insertion_sort and tim_sort, with timeit? [/INST] If you want to use timeit in an interactive Python session, there are two convenient options: Use the...
<s>[INST] How can I convert a character to a integer in Python, and viceversa? I want to get, given a character, its ASCII value. For example, for the character a, I want to get 97, and vice versa. [/INST] Use chr() and ord(): >>> chr(97) 'a' >>> ord('a') 97 </s>
<s>[INST] What is the easiest way to remove all packages installed by pip? I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production. Is there a quick and easy way to do this with pip? [/INST] I've found this snippet as an alternative solution....
<s>[INST] Python pip install fails: invalid command egg_info I find that recently often when I try to install a Python package using pip, I get the error(s) below. I found a reference online that one has to use "python2 setup.py install" from the download directory, and indeed find that this will then work if I manuall...
<s>[INST] When is "i += x" different from "i = i + x" in Python? I was told that += can have different effects than the standard notation of i = i +. Is there a case in which i += 1 would be different from i = i + 1? [/INST] This depends entirely on the object i. += calls the __iadd__ method (if it exists -- falling...
<s>[INST] How to read csv into record array in numpy? I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use csv.reader() and then apply something lik...
<s>[INST] Why compile Python code? Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? I also notice that some files in my application get compiled into .pyc while others do not, why is this? [/INST] It's compiled to b...
<s>[INST] What are the differences between numpy arrays and matrices? Which one should I use? What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them? Will the style of the ...
<s>[INST] Implement touch using Python? touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google res...
<s>[INST] Turn a string into a valid filename in Python I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python. I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters l...
<s>[INST] How do I set the figure title and axes labels font size in Matplotlib? I am creating a figure in Matplotlib like this: from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title') plt.xlabel('xlabel') plt.ylabel('ylabel') fig.savefig('test.jpg') I want to specify font si...
<s>[INST] Finding what methods an object has Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is calle...
<s>[INST] How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__? I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Shou...
<s>[INST] Is it a good practice to use try-except-else in Python? From time to time in Python, I see the block: try: try_this(whatever) except SomeException as exception: #Handle exception else: return something What is the reason for the try-except-else to exist? I do not like that kind of programming, as it...
<s>[INST] Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad? I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necess...
<s>[INST] Python mysqldb: Library not loaded: libmysqlclient.18.dylib I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports import MySQLdb as mysql Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the fol...
<s>[INST] How to drop rows of Pandas dataframe whose value of certain column is NaN I have a df : >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 60193...
<s>[INST] How do I get user IP address in django? How do I get user's IP in django? I have a view like this: # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request...