text
stringlengths
226
34.5k
SQLAlchemy double-quoting LIKE filter Question: For some reason, SQLAlchemy is double-quoting the LIKE filter value of my queries! The code is this: query = app.db.session.query(model.Attribute)\ .filter(model.Attribute.name == 'photo0')\ .filter(model.Attribute.value.like('%' + file + '%'))\ .all() Pretty simple and straight forward. It should produce something like `value LIKE '%78744154439.htm%'` but SQLAlchemy is adding additional double-quotes. Here's the DB echo from this query: 2014-07-17 14:32:24,472 INFO sqlalchemy.engine.base.Engine SELECT attributes.listing_id AS attributes_listing_id, attributes.id AS attributes_id, attributes.name AS attributes_name, attributes.value AS attributes_value FROM attributes WHERE attributes.name = %s AND attributes.value LIKE %s 2014-07-17 14:32:24,472 INFO sqlalchemy.engine.base.Engine ('photo0', '"%78744154439.htm%"') I've tried to escape the % thinking it was due to string escaping, but still nothing! I'm running Python 2.7.6 with SQLAlchemy 0.9.6 and MySQL-python 1.2.5 as my DBAPI. Answer: You can get around this by using the following syntax: from sqlalchemy.sql import text query = app.db.session.query(model.Attribute)\ .filter(model.Attribute.name == 'photo0')\ .filter(model.Attribute.value.like(text("'%" + file + "%'"))\ .all() HTH
Making a Python program handle mailto links Question: I actually found the answer to this before I asked the question, but I'm posting it (and the answer, in an answer) for the sake of others who might want to know (though if you have more insights, feel free to mention them). EDIT: Someone else gave a better answer (so take note): Question: I made a Python program that is capable of sending email. However, I want to make it capable of being a default email client such that it will capture the email address and subject of HTML email links (mailto links) when the user clicks them. How do I get the email address and subject to my client? Currently, I can set my program as the default mail client, but I don't know what information, or format of information, it's getting from the web browser; so, I'm not sure how to parse it. Answer: Assuming the complete link is passed in as `sys.argv[1]`, you need to do something like this: import urllib.parse parsed = urllib.parse.urlparse(sys.argv[1]) mail_addr = parsed.path fields = urllib.parse.parse_qs(parsed.query) This sets `mail_addr` to the address to send the email to, while `field` will be a dictionary of additional parameters. The fields that you can expect to be present are specified in [RFC 6068](http://tools.ietf.org/html/rfc6068)
Describing gaps in a time series pandas Question: I'm trying to write a function that takes a continuous time series and returns a data structure which describes any missing gaps in the data (e.g. a DF with columns 'start' and 'end'). It seems like a fairly common issue for time series, but despite messing around with groupby, diff, and the like -- and exploring SO -- I haven't been able to come up with much better than the below. It's a priority for me that this use vectorized operations to remain efficient. There has got to be a more obvious solution using vectorized operations -- hasn't there? Thanks for any help, folks. import pandas as pd def get_gaps(series): """ @param series: a continuous time series of data with the index's freq set @return: a series where the index is the start of gaps, and the values are the ends """ missing = series.isnull() different_from_last = missing.diff() # any row not missing while the last was is a gap end gap_ends = series[~missing & different_from_last].index # count the start as different from the last different_from_last[0] = True # any row missing while the last wasn't is a gap start gap_starts = series[missing & different_from_last].index # check and remedy if series ends with missing data if len(gap_starts) > len(gap_ends): gap_ends = gap_ends.append(series.index[-1:] + series.index.freq) return pd.Series(index=gap_starts, data=gap_ends) For the record, Pandas==0.13.1, Numpy==1.8.1, Python 2.7 Answer: This problem can be transformed to find the continuous numbers in a list. find all the indices where the series is null, and if a run of (3,4,5,6) are all null, you only need to extract the start and end (3,6) import numpy as np import pandas as pd from operator import itemgetter from itertools import groupby # create an example data = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17] s = pd.series( data, index=data) s = s.reindex(xrange(18)) print find_gap(s) def find_gap(s): """ just treat it as a list """ nullindex = np.where( s.isnull())[0] ranges = [] for k, g in groupby(enumerate(nullindex), lambda (i,x):i-x): group = map(itemgetter(1), g) ranges.append((group[0], group[-1])) startgap, endgap = zip(* ranges) return pd.series( endgap, index= startgap ) reference : [Identify groups of continuous numbers in a list](http://stackoverflow.com/questions/2154249/identify-groups-of- continuous-numbers-in-a-list)
syncdb fails with django-compositekey Question: I'm planning to use django-compositekey to connect to a legacy db that makes use of compound keys. Just to see that everything is working, I created a new Django project with a simple model like this. from django.db import models from compositekey import db class Book(models.Model): id = db.MultiFieldPK("author", "name") name = models.CharField(max_length=100) author = models.CharField(max_length=100) if I use django_manage.py sql Books everything seems to be fine, I receive BEGIN; CREATE TABLE "Books_book" ( "name" varchar(100) NOT NULL, "author" varchar(100) NOT NULL, UNIQUE ("author", "name"), PRIMARY KEY ("author", "name") ) ; COMMIT; However, when I try to use syncdb I receive the following error Creating tables ... Traceback (most recent call last): File "/home/islas/pycharm-3.4.1/helpers/pycharm/django_manage.py", line 23, in <module> run_module(manage_file, None, '__main__', True) File "/usr/lib/python2.7/runpy.py", line 176, in run_module fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 82, in _run_module_code mod_name, mod_fname, mod_loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/home/islas/PycharmProjects/BooksDemo/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 415, in handle return self.handle_noargs(**options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/syncdb.py", line 112, in handle_noargs emit_post_sync_signal(created_models, verbosity, interactive, db) File "/usr/local/lib/python2.7/dist-packages/django/core/management/sql.py", line 216, in emit_post_sync_signal interactive=interactive, db=db) File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py", line 185, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python2.7/dist- packages/django/contrib/auth/management/__init__.py", line 93, in create_permissions "content_type", "codename" File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 538, in values_list _fields=fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 852, in _clone c._setup_query() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 995, in _setup_query self.query.add_fields(self.field_names, True) File "/usr/local/lib/python2.7/dist-packages/compositekey/db/models/sql/query.py", line 24, in add_fields True) ValueError: need more than 5 values to unpack Process finished with exit code 1 Does anybody have an idea of what might be wrong? I'm new to Django, but as far as I read working with compound primary keys is now possible using django- compositekey. Thanks in advance, Alejandro Answer: Which version of `Django` you are using...? I got the same problem because i was using `Djnago 1.5.8` and the `compositekey` package does not support Djnago 1.5.8 For composite primary keys, you can use [SQLAlchemy](http://www.sqlalchemy.org/) instead of native Django ORM. It can coexist with Django ORM seamlessly.
Timer method inside a class Question: First of all an introduction to my development environment: OS: Windows. SDK: Microsoft Visual Studio 2008. Earlier today I was facing the problem of trying to define a Timer inside a class. My class is interfacing a Python embedded module and a C++ backend, My problem is that I need to receive some time event on the python module. Also it is important to notice that there will be only one instance of this class. The main problem is that when I define a timer using: /* Null, 0, mseconds, CALLBACK_METHOD */ SetTimer(NULL, 0, 100, (TIMERPROC) OnTimer); The method activated on the timer event (OnTimer) needs to be a static method on my Class (and then I cannot access any non-static methods or variables inside that class). Reading some code on codeproject I have found: <http://www.codeproject.com/Articles/4817/How-to-use-SetTimer-with-callback- to-a-non-static> I have a similar implementation but without the lines: void * CSleeperThread::pObject; and CSleeperThread *pSomeClass = (CSleeperThread*)pObject; // cast the void pointer pSomeClass->TimerProc(hwnd, uMsg, idEvent, dwTime); // call non-static function Is this the only way to implement the functionality I'm looking for? Is there an easier way I may have skipped on my information gathering process? Answer: Create a static map of your Class object: static std::map<UINT_PTR, CMyClass*> m_CMyClassMap; //declaration At the time of object creation insert the object in this map: CMyClass myClassObj; CMyClassMap.insert(std::pair<int, CMyClass*>(0, &myClassObj)); Now you can use it in static methods to access its non static members. int a = m_CMyClassMap[0]->m_someNonStaticMember;
Using fields defined in constructor - Python Question: I have a class as below that I'm using to connect to a remote SQL server instance from a linux server python web app. I define and set cursor in the **init** constructor and wish to use it throughout the class. How do I do this? I come form a java background and don't understand the scope and protection levels of Python fields. import pyodbc class SQLSeverConnection(): def __init__(self, DSN, user, password, database): connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database) connection = pyodbc.connect(connectionString) cursor = connection.cursor() def getColumnData(self, columnName, tableName): cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp') data = cursor.fetchall() return data def getColumnTitles(self, tableName): cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position') columns = cursor.fetchall() return columns def getTableNames(self): cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE''') tables = cursor.fetchall() return tables Answer: The answer is simple: Python's "methods" are really plain functions, and local variables are plain local variables. To set / access instance attributes, you **must** use the current instance, which is passed as first argument to the function (and by convention named `self`): class SQLSeverConnection(): def __init__(self, DSN, user, password, database): connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database) self.connection = pyodbc.connect(connectionString) self.cursor = connection.cursor() def getColumnData(self, columnName, tableName): self.cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp') data = self.cursor.fetchall() return data def getColumnTitles(self, tableName): self.cursor.execute('select column_name,* from information_schema.columns where table_name = 'tableName' order by ordinal_position') columns = self.cursor.fetchall() return columns def getTableNames(self): BASE_TABLE ='BASE_TABLE' self.cursor.execute('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'') tables = self.cursor.fetchall() return tables Now using a single shared cursor for all operations is brittle, you'd better instanciate a new cursor for each operation. Also, since a cursor is an iterable, you may want to return the cursor itself and let client code iterate over it, it might save some memory... class SQLSeverConnection(object): def __init__(self, DSN, user, password, database): connectionString = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (DSN, user, password, database) self.connection = pyodbc.connect(connectionString) def getCursor(self): return self.connection.cursor() def getColumnData(self, columnName, tableName): cursor = self.getCursor() cursor.execute('SELECT ' columnName ' FROM ' tableName ' ORDER BY timestamp') return cursor # etc Oh and yes: using `mixCased` is not pythonic, we prefer `all_lower` ;)
Python: calculating checksum of a file for a weird protocol Question: I'm having troubles calculating something like a checksum of a file for a weird protocol that I'm trying to port to python. The checksum is a 4 byte unsigned integer that is the result of adding all the 4-bytes unsigned integers of a file. For example, suppose the following file (note that a real one is about 16MB): ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 ef ee ed ec eb ea e9 e8 e7 e6 With my implementation (see below), the computation is as this: 0xfffefdfc + 0xfbfaf9f8 + 0xf7f6f5f4 + 0xf3f2f1f0 + 0xefeeedec + 0xebeae9e8 + 0xe7e60000 = 0x6aba3b7ac But, it should be `0xaba3b7ac` I've tried to do something like this: import mmap import struct # Prepare file file = open("file.bin", 'rb') map = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) # Calculate checksum checksum = 0 while (map.tell() < map.size()): checksum += struct.unpack('>I', map.read(4))[0] print "checksum: ", checksum # Close file. map.close() file.close() But I see two problems. 1. First of all, the output number is too big. I need a 4 byte number. With the previous code, the output for a typical test file is something like `0x165c0458b224ae` but it should be something like `0xcaac5458` (a 4-byte unsigned integer). 2. My method is slow. The original code (which is written in C) does the calculation much faster. I'm really stuck with this so any help will be really appreciated. Thanks in advance and sorry for my bad english. * * * **Update:** The first problem was solved by Serge Ballesta. The solution is to add the following line before printing the checksum: checksum &= 0xffffffff But the computation is still slow. I would like to have a fast solution but I don't know how to do it. Answer: One way is to use the `array` module and load all the four bytes into memory, sum those, then force back to a 4 byte (as Serge has already mentioned). import os from array import array #with open('data.bin', 'wb') as fout: # fout.write(os.urandom(16800000)) with open('data.bin', 'rb') as fin: arr = array('L') arr.fromfile(fin, 16800000 / 4) arr.byteswap() checksum = sum(arr) & 0xFFFFFFFF Takes less than a second on my laptop... not sure how much faster you want it to go...
Sending hex-data via socket, is interpreted as string Question: I'm new to python, and I'm trying to use a 3rd party library/module. What I'm doing now is: s.send(rtp.header_bytes + rtp.payload) # -> \x80!\x00\x01\x00\x00\x00d\x00\x00\x00\x00Testy to send the header and the payload of a packet via tcp socket. On the receiving side: conn, addr = socket_rtp.accept() data = conn.recv(1024) the data is passed to a constructor `__init__(self, bytes, length)` and then used like this self.version = (bytes[0] & Packet.V_MASK) >> 6 but it seems that it's interpreting the bytes array as string? I'm getting the following exception: .... line 322, in __init__ self.version = (bytes[0] & Packet.V_MASK) >> 6 TypeError: unsupported operand type(s) for &: 'str' and 'int' Thank you for your help. Answer: To convert the string (`bytes`) to int, you can use [`ord`](https://docs.python.org/2/library/functions.html#ord) (assuming your're using Python 2.x): self.version = (bytes[0] & Packet.V_MASK) >> 6 or [`struct.unpack`](https://docs.python.org/2/library/struct.html#struct.unpack): self.version = (struct.unpack('B', bytes[0])[0] & Packet.V_MASK) >> 6 * * * >>> ord('\x80') 128 >>> import struct >>> struct.unpack('B', '\x80')[0] 128
Completely disable scrollbars on GTK webkit webview? Question: I want a simple webview based on webkit, with a fixed size (e.g. 200x200) and without any scrollbars. I use X with no window manager. I tried the following Python code: import gtk import webkit view = webkit.WebView() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_NEVER) sw.add(view) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(sw) win.set_default_size(200, 200) win.show_all() view.open("http://www.blackle.com") gtk.main() The scrollbars still show, although they should not. I also tried to follow a different path and completely remove scrollbars on GTK by using `~/.gtkrc-2.0`: style "custom-scrollbar-style" { GtkScrollbar::slider_width = 0 GtkScrollbar::min-slider-length = 0 GtkScrollbar::activate_slider = 0 GtkScrollbar::trough_border = 0 GtkScrollbar::has-forward-stepper = 0 GtkScrollbar::has-backward-stepper = 0 GtkScrollbar::stepper_size = 0 GtkScrollbar::stepper_spacing = 0 GtkScrollbar::trough-side-details = 0 GtkScrollbar::default_border = { 0, 0, 0, 0 } GtkScrollbar::default_outside_border = { 0, 0, 0, 0 } } widget_class "*Scrollbar" style "custom-scrollbar-style" Even with this, it still shows thin white lines on the two sides of the window where the scrollbars are. Any ideas? Answer: ok here's the thing. You don't want a scrollbar but you construct a Gtk.ScrolledWindow to be the container of WebKit.WebView. If you don't want a scrollbar, just put inside a container that doesn't implement a Gtk.Scrollable, say Gtk.Grid. It will not showing scrollbar at all. Few downsides: 1. your main window will not down size beyond it's content minimum width and height. 2. if your view content change size, and it will (unless you restrict every last detail on how your view will be displayed), the window will follow the current size as well 3. in WebKit.WebView widget, there is no such thing as Gtk.Widget.set_size_request, it will still follow its content. By the way, Gtk.Widget.set_default_size () does not create a fix size for a widget, only set the size when first time it is shown.
Python: Absorbing newlines on keyboard input Question: I have a question specific to multi-line input from the keyboard. It appears that my program is not absorbing newlines. The effect is that, after the input is processed, the program appears to believe that there are a number of carriage returns pending equal to the number of newline characters in the input. I have looked at the sys module (sys.stdin.flush()), the msvsrc module (msvcrt.kbhit() and msvcrt.getch()), raw_input, and tried everything I can think of in search, but I'm coming up dry. Perhaps strip() will work, but I can't seem to figure it out for the general case. The output I am getting is this: Enter a string: def countLetters(): s = input("Enter a string: ") d = histogram(s.upper()) printSortedDict(d, True) ('T', 3) ('E', 3) ('F', 1) ('D', 1) (' ', 1) (':', 1) ('R', 1) ('(', 1) ('N', 1) (')', 1) ('L', 1) ('U', 1) ('C', 1) ('O', 1) ('S', 1) Continue (yes/no): Continue (yes/no): Continue (yes/no): Continue (yes/no): I would like for the output to only have one "Continue (yes/no):" displayed. It appears that the input() routine is eating the last newline (as expected) but not any of the intermediate newlines. These newlines appear to be interpreted as input to the "Continue (yes/no):" statement. I am using Python 3.4.1. I am developing on Win8 but would like the solution to run on at least Linux as well (in case the solution is platform specific). Here is the program. The easiest way to see the problem is just to copy the source code and past it as input to the program. # # letterCountDict - count letters of input. uses a dict() # """letterCountDict - enter a string and the count of each character is returned """ # stolen from p. 122 of "Python for Software Design" by Allen B. Downey def histogram(s): """builds a histogram from the characters of string s""" d = dict() for c in s: if c in d: d[c] += 1 else: d[c] = 1 return d def printSortedDict(d, r=False): """sort and print a doctionary. r == True indicates reserve sort.""" sl = sorted(d.items(), key=lambda x: x[1], reverse=r) for i in range(len(sl)): print(sl[i]) def countLetters(): s = input("Enter a string: ") d = histogram(s.upper()) printSortedDict(d, True) answerList = ["yes", "no"] done = False while not done: countLetters() ans = "" while ans not in answerList: ans = input("\nContinue (yes/no): ").replace(" ", "").lower() if ans == "no": done = True Answer: `input()` doesn't accept multiple lines. Each call to `input()` retrieves exactly one line. So, you have the first call to input: s = input("Enter a string: ") receives this line: def countLetters(): Sure enough, you can see it has three T's, three E's, and so forth. The next call to `input()` is this: ans = input("\nContinue (yes/no): ").replace(" ", "").lower() to which you have typed: s = input("Enter a string: ") Since your response is neither `'yes'` nor `'no'`, your loop asks again. This time you type: d = histogram(s.upper()) which is also neither `'yes'` nor `'no'`. This pattern continues until you get tired of typing nonsense to the question. Finally, you type "no" and the game ends. If you want to read more than one line at a time, try `sys.stdin.read()` or perhaps `sys.stdin.readlines()`. For example: import sys def countLetters(): print("Enter several lines, followed by the EOF signal (^D or ^Z)") s = sys.stdin.read() d = histogram(s.upper()) printSortedDict(d, True)
Retreive the unique keys (second dimension) of a 2 dimensional dictionary in python? Question: I have a a 2d dictionary (named d2_dic). I know how to get the unique keys (It's always unique) of the first dimension by d2_dic.keys(). But how do I get the unique keys of the second dimension? from collections import defaultdict d2_dic = defaultdict(dict) d2_dic['1']['a'] = 'Hi' d2_dic['1']['b'] = 'there' d2_dic['2']['a'] = '.' To get the unique keys in the first dimension, i just need to do a d2_dic.keys() {o/p = 1,2} How do I retreive the unique keys of the second dimension?? I need an o/p of [a,b] Answer: The entity `d2_dic['1']` is itself a dictionary (same with `d2_dic['2']`). So you can use `d2_dic['1'].keys()` to get the keys for that dictionary. If you want a list of all the possible keys in the second dimension then you could do the following. mykeys = [] for k in d2_dic.keys() : mykeys.extend(d2_dic[k].keys()) # this removes duplicates but destroys order mykeys = list(set(mykeys)) print mykeys # ['a', 'b'] Apparently, you can also do this in one line with list comprehension, as per the comment by @vaultah: `mykeys = list({x for d in d2_dic.values() for x in d.keys()})`. You have to be careful with this though, because `d2_dic['2'][mykeys[1]]` will resault in `KeyError: 'b'`. You may want to wrap some of your code in try and except statements. For example: for i in d2_dic.keys() : for j in mykeys : try : d2_dic[i][j] except KeyError : d2_dic[i][j] = None print i, j, d2_dic[i][j] Note that these print statements won't work in python 3
Getting a file from an authenticated site (with python urllib, urllib2) Question: I'm trying to get a queried-excel file from a site. When I enter the direct link, it will lead to a login page and once I've entered my username and password, it will proceed to download the excel file automatically. I am trying to avoid installing additional module that's not part of the standard python (This script will be running on a "standardize machine" and it won't work if the module is not installed) I've tried the following but I see a "page login" information in the excel file itself :-| import urllib url = "myLink_queriedResult/result.xls" urllib.urlretrieve(url,"C:\\test.xls") SO.. then I looked into using urllib2 with password authentication but then I'm stuck. I have the following code: import urllib2 import urllib theurl = 'myLink_queriedResult/result.xls' username = 'myName' password = 'myPassword' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(theurl) pagehandle.read() ##but seems like it still only contain a 'login page' Appreciate any advice in advance. :) Answer: Urllib is generally eschewed these days for [Requests](http://docs.python- requests.org/en/latest/user/quickstart/#response-content). This would do what you want: import requests theurl= 'myLink_queriedResult/result.xls' username = 'myUsername' password = 'myPassword' r=requests.get(theurl, auth=HTTPBasicAuth(myUsername, myPassword)) Here you can find more [information on authentication using request.](http://docs.python-requests.org/en/latest/user/authentication/)
How can I call Vim from Python? Question: I would like a Python script to prompt me for a string, but I would like to use Vim to enter that string (because the string might be long and I want to use Vim's editing capability while entering it). Answer: You can call vim with a file path of your choice: from subprocess import call call(["vim","hello.txt"]) Now you can use this file as your string: file = open("hello.txt", "r") aString = file.read()
Finding ranges of specific character in a string Question: I am working with python-3.x on windows 7. i have a string consists of millions of characters. consider for example ATCGNNNATCGATNNNNNATCGANTCG I want to get the ranges which are N. in here [[4,7],[13,18],[23,24]]. I can not just take positions of Ns and then convert them to ranges because its a huge data and this method will be too slow. It seems such an easy problem but actually no good way comes to my mind. Is there a fast way to do this? Answer: Not sure how this scales to a string of millions of characters, but you could try [regular expressions](https://docs.python.org/3/howto/regex.html): >>> import re >>> data = "ATCGNNNATCGATNNNNNATCGANTCG" >>> spans = (g.span() for g in re.finditer('N+', data)) >>> list(spans) [(4, 7), (13, 18), (23, 24)] _Update:_ Tried this with randomly generated strings of A, C, G, T, and N. For 1,000,000 characters, `list(spans)` takes less than one second, and for 10,000,000 it takes about 10 seconds on my not-at-all-new computer, finding about 1,600,000 groups of Ns.
How to create a shortcut in startmenu using setuptools windows installer Question: I want to create a start menu or Desktop shortcut for my Python windows installer package. I am trying to follow <https://docs.python.org/3.4/distutils/builtdist.html#the-postinstallation- script> Here is my script; import sys from os.path import dirname, join, expanduser pyw_executable = sys.executable.replace('python.exe','pythonw.exe') script_file = join(dirname(pyw_executable), 'Scripts', 'tklsystem-script.py') w_dir = expanduser(join('~','lsf_files')) print(sys.argv) if sys.argv[1] == '-install': print('Creating Shortcut') create_shortcut( target=pyw_executable, description='A program to work with L-System Equations', filename='L-System Tool', arguments=script_file, workdir=wdir ) I also specified this script in scripts setup option, as indicated by aforementioned docs. Here is the command I use to create my installer; python setup.py bdist_wininst --install-script tklsystem-post-install.py After I install my package using created windows installer, I can't find where my shorcut is created, nor I can confirm whether my script run or not? How can I make setuptools generated windows installer to create desktop or start menu shortcuts? Answer: If you want to confirm whether the script is running or not, you can print to a file instead of the console. Looks like text you print to console in the post-install script won't show up. Try this: import sys from os.path import expanduser, join pyw_executable = join(sys.prefix, "pythonw.exe") shortcut_filename = "L-System Toolsss.lnk" working_dir = expanduser(join('~','lsf_files')) script_path = join(sys.prefix, "Scripts", "tklsystem-script.py") if sys.argv[1] == '-install': # Log output to a file (for test) f = open(r"C:\test.txt",'w') print('Creating Shortcut', file=f) # Get paths to the desktop and start menu desktop_path = get_special_folder_path("CSIDL_COMMON_DESKTOPDIRECTORY") startmenu_path = get_special_folder_path("CSIDL_COMMON_STARTMENU") # Create shortcuts. for path in [desktop_path, startmenu_path]: create_shortcut(pyw_executable, "A program to work with L-System Equations", join(path, shortcut_filename), script_path, working_dir)
why i failed to join two dataframes when using python pandas? Question: import pandas as pd from pandas import DataFrame l=[(1,10),(2,5), (3,7)] l2=[(1,5), (2,6), (3,8)] l3=[(2,3), (1,9), (3,9)] d1=DataFrame(l) d2=DataFrame(l2) d3=DataFrame(l3) j1=d1.join(d2, how='left') **failed with error** : Exception: **columns overlap: Int64Index([0, 1], dtype=int64)** **what's wrong? what happened?** In [40]: d1 Out[40]: 0 1 0 1 10 1 2 5 2 3 7 In [41]: d2 Out[41]: 0 1 0 1 5 1 2 6 2 3 8 what i need is to join d1 and d2 using the first colum, the result should be, **which kind of DataFrame operation is needed?** 0 1 2 0 1 10 5 1 2 5 6 2 3 7 8 Answer: That won't work it looks what you want to do is to add just the last column which you could achieve using `concat`: In [15]: # just add the last column j1=pd.concat([d1,d2[[1]]],axis=1) j1 Out[15]: 0 1 1 0 1 10 5 1 2 5 6 2 3 7 8 [3 rows x 3 columns] or you should `merge`: In [19]: j1 = d1.merge(d2, how='left', on=[0]) j1 Out[19]: 0 1_x 1_y 0 1 10 5 1 2 5 6 2 3 7 8 [3 rows x 3 columns] In [20]: # now rename the columns that clashed j1.rename(columns={'1_x':'1', '1_y':'2'}, inplace=True) j1 Out[20]: 0 1 2 0 1 10 5 1 2 5 6 2 3 7 8 [3 rows x 3 columns] If we analyse what went wrong with the join, you have a clash of columns which it cannot resolve unless you specify a suffix: In [42]: j1=d1.join(d2, how='left',lsuffix='', rsuffix='_y') j1 Out[42]: 0 1 0_y 1_y 0 1 10 1 5 1 2 5 2 6 2 3 7 3 8 [3 rows x 4 columns] We can now drop the superfluous column `0_y` and rename the added column: In [43]: j1.drop(labels=['0_y'],axis=1,inplace=True) j1.rename(columns={'1_y':'2'},inplace=True) j1 Out[43]: 0 1 2 0 1 10 5 1 2 5 6 2 3 7 8 [3 rows x 3 columns]
Making requests @python Question: I get many errors while trying to execute code: import requests #import bs4 --not sure if it's necessary from bs4 import BeautifulSoup core = 'http://wwww.lolnexus.com' name = input('\nName: ') region = input('\nRegion NA | EUW | EUNE | BR | TR | RU | LAN | LAS | OCE : ') full = core + '/' + region + '/' + 'search?name=' + name + '&region=' + region print (full) r = requests.get(full) source = r.text soup = BeautifulSoup(source) print (source) input() I have no idea what's wrong. It's the beginning of app that I'm trying to write and errors stop me from scraping the rest of the web page. Errors I get: Name: Fred Region NA | EUW | EUNE | BR | TR | RU | LAN | LAS | OCE : TR http://wwww.lolnexus.com/TR/search?name=Fred&region=TR Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\packages \urllib3\connectionpool.py", line 493, in urlopen body=body, headers=headers) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\packages \urllib3\connectionpool.py", line 291, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Python34\lib\http\client.py", line 1090, in request self._send_request(method, url, body, headers) File "C:\Python34\lib\http\client.py", line 1128, in _send_request self.endheaders(body) File "C:\Python34\lib\http\client.py", line 1086, in endheaders self._send_output(message_body) File "C:\Python34\lib\http\client.py", line 924, in _send_output self.send(msg) File "C:\Python34\lib\http\client.py", line 859, in send self.connect() File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\packages \urllib3\connection.py", line 106, in connect conn = self._new_conn() File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\packages \urllib3\connection.py", line 90, in _new_conn (self.host, self.port), self.timeout, *extra_args) File "C:\Python34\lib\socket.py", line 491, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "C:\Python34\lib\socket.py", line 530, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11004] getaddrinfo failed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\adapters .py", line 344, in send timeout=timeout File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\packages \urllib3\connectionpool.py", line 543, in urlopen raise MaxRetryError(self, url, e) requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='www w.lolnexus.com', port=80): Max retries exceeded with url: /TR/search?name=Fred&r egion=TR (Caused by <class 'socket.gaierror'>: [Errno 11004] getaddrinfo failed) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\x\Desktop\webscraping.py", line 11, in <module> r = requests.get(full) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\api.py", line 55, in get return request('get', url, **kwargs) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\sessions .py", line 461, in request resp = self.send(prep, **send_kwargs) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\sessions .py", line 567, in send r = adapter.send(request, **kwargs) File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\adapters .py", line 392, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='wwww.lolnexus.com' , port=80): Max retries exceeded with url: /TR/search?name=Fred&region=TR (Cause d by <class 'socket.gaierror'>: [Errno 11004] getaddrinfo failed) What's wrong and is it a good idea to use Requests & BeautifulSoup libraries for web scraping? Answer: You are trying to connect to `http://wwww.lolnexus.com/TR/search?name=Fred&region=TR`, with **four** `w` characters in the domain name. That name does not exist. Correct the hostname: core = 'http://www.lolnexus.com'
How to extract image geodata out of flickr xml image data with python? Question: I'm researching the issue of electronic waste and I'm using this code in flickrapi py module to get an xml data on Flickr images tagged with #e-waste. import flickrapi import xml api_key='myAPI key' api_secret ='myAPI secret' flickr = flickrapi.FlickrAPI(api_key,secret=api_secret) r = flickr.photos_search(tags='e-waste', has_geo="1", per_page='100') xml.etree.ElementTree.dump(r) Running the code gives me results: <rsp stat="ok"> <photos page="1" pages="58" perpage="100" total="5785"> <photo farm="3" id="13982876982" isfamily="0" isfriend="0" ispublic="1" owner="100231432@N02" secret="2d33e5efb1" server="2903" title="Sean Gallagher, Pulitzer Photojournalist visits MSA" /> <photo farm="8" id="13962977066" isfamily="0" isfriend="0" ispublic="1" owner="100231432@N02" secret="aeb6bc1454" server="7139" title="Sean Gallagher, Pulitzer Photojournalist visits MSA" /> </photos> </rsp> Now, I want to also **get printed the geo metadata that these images should have**. How can I achieve that? I ultimately want to extract that geodata into a csv that I can then map. Cheers! Answer: Extract the `id` attribute from the `<photo>` element, then pass that to [flickr.photos.getInfo](https://www.flickr.com/services/api/flickr.photos.getInfo.html) and extract data from the `<location>` element. The example on the documentation page doesn't show this, but you can use the [API Explorer](https://www.flickr.com/services/api/explore/flickr.photos.getInfo) to see an example. Here's an example from one of my photos: <location latitude="38.829786" longitude="-77.52202" accuracy="14" context="0" place_id="ioKEzZ1TV7oQ55R_" woeid="2501239"> <locality place_id="ioKEzZ1TV7oQ55R_" woeid="2501239">Sudley Springs</locality> <county place_id="hF2V0rlQUL9MlAlEkA" woeid="12590406">Prince William</county> <region place_id="pPrhG7VTUb6SbYO." woeid="2347605">Virginia</region> <country place_id="nz.gsghTUb4c2WAecA" woeid="23424977">United States</country> </location>
Python returns 5 digit timestamp, what is this? Question: I'm a PHP programmer doing a bit of Python (3.4) just because it's way easier to do it in Python. My script converts a .xlsx file, into many .csv files (one .csv per sheet). Here is the code: wb = xlrd.open_workbook(filepath) for i in range(0, wb.nsheets): sh = wb.sheet_by_index(i) sheet_name = sh.name sheet_name = sheet_name.replace(" ", "_"); fp = open(sheet_name+'.csv', 'at', encoding='utf8') wr = csv.writer(fp, quoting=csv.QUOTE_ALL) for row_num in range(sh.nrows): wr.writerow(sh.row_values(row_num)) fp.close() Full code here: <https://github.com/xtrimsky/xlsx_to_csv> This works well, except that I have a field that is a date, in excel it shows for example: 01/01/2009 But the final csv, contains a number that is 39814. What is this please, what can I do with it ? 01/02/2009 is 39815. Is it a number I can use to find the unix timestamp ? Or is it an issue and I should change my script ? I would feel safer if it would just return the string "01/01/2009". Can someone please help me understand what I am dealing with ? Answer: If 39814 maps to 2009-1-1 and 39815 maps to 2009-1-2, then it looks like the ordinal is counting the number of days since 1899-12-30: In [57]: DT.date(1899,12,30) + DT.timedelta(days=39814) Out[57]: datetime.date(2009, 1, 1) See [Why 1899-12-30!?](http://stackoverflow.com/questions/10559767/how-to- convert-ms-excel-date-from-float-to-date-format-in-ruby) To convert the Excel number to a Unix timestamp, you could use the [`timetuple` method](https://docs.python.org/2/library/datetime.html#datetime.date.timetuple) to convert the `datetime.date` object to a timetuple, and then [time.mktime](https://docs.python.org/2/library/time.html#time.mktime) to convert it to a timestamp (seconds since the Epoch): In [80]: import time In [81]: time.mktime((DT.datetime(1899,12,30) + DT.timedelta(days=39814)).timetuple()) Out[81]: 1230786000.0
Placeholder to set different frequencies of sin wave output to each key press Question: I want to use the placeholder %f to set different frequencies for my sin wave sound output, for each key. However, I get the error message 'SyntaxError: can't assign to literal'. I checked to see if my syntax was incorrect, though I found a similar example - can anyone see what the problem is and why my code won't run? traceback: File "test.py", line 50 (Python, Pygame). import pygame from pygame.locals import * import math import numpy bits = 16 #the number of channels specified here is NOT #the channels talked about here http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_num_channels pygame.mixer.pre_init(44100, -bits, 2) pygame.init() size = (1200, 720) _display_surf = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF) duration = 1.0 # in seconds #this sounds totally different coming out of a laptop versus coming out of headphones sample_rate = 44100 n_samples = int(round(duration*sample_rate)) #setup our numpy array to handle 16 bit ints, which is what we set our mixer to expect with "bits" up above buf = numpy.zeros((n_samples, 2), dtype = numpy.int16) max_sample = 2**(bits - 1) - 1 #default frequency - not used frequency = 440 for s in range(n_samples): t = float(s)/sample_rate # time in seconds #This will keep the sound playing forever, the quit event handling allows the pygame window to close without crashing _running = True while _running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_a: frequency = 261.6 buf[s][0] = int(round(max_sample*math.sin(2*math.pi*frequency*t))) # left buf[s][1] = int(round(max_sample*0.5*math.sin(2*math.pi*frequency*t))) # right sound = pygame.sndarray.make_sound(buf) sound.play() elif event.key == K_s: frequency = 293.7 buf[s][0] = int(round(max_sample*math.sin(2*math.pi*frequency*t))) # left buf[s][1] = int(round(max_sample*0.5*math.sin(2*math.pi*frequency*t))) # right sound = pygame.sndarray.make_sound(buf) sound.play() if event.type == KEYUP: sound.stop() if event.type == pygame.QUIT or event.type == KEYDOWN: if event.key == K_ESCAPE: _running = False break pygame.quit() Answer: String `"%f"` can be variable name. You can't assign `'%f' = 261.6` \- this is your error `"can't assign to literal"`. Name it for example `freq` and use it in place of `"%f"` freq = 261.6 sin(2*math.pi* freq *t) * * * BTW: Placeholder `%f` can be use only in string formating (or string parsing). * * * **EDIT:** import pygame from pygame.locals import * import math import numpy def generate_sound(freq): #setup our numpy array to handle 16 bit ints, which is what we set our mixer to expect with "bits" up above buf = numpy.zeros((n_samples, 2), dtype = numpy.int16) max_sample = 2**(bits - 1) - 1 for s in range(n_samples): t = float(s)/sample_rate # time in seconds buf[s][0] = int(round(max_sample*math.sin(2*math.pi*freq*t))) # left buf[s][1] = int(round(max_sample*0.5*math.sin(2*math.pi*freq*t))) # right return pygame.sndarray.make_sound(buf) bits = 16 #the number of channels specified here is NOT #the channels talked about here http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_num_channels pygame.mixer.pre_init(44100, -bits, 2) pygame.init() size = (1200, 720) screen = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF) duration = 1.0 # in seconds #this sounds totally different coming out of a laptop versus coming out of headphones sample_rate = 44100 n_samples = int(round(duration*sample_rate)) #default frequency - not used sound = None sound_261_6 = generate_sound(261.6) sound_293_7 = generate_sound(293.7) #This will keep the sound playing forever, the quit event handling allows the pygame window to close without crashing _running = True while _running: for event in pygame.event.get(): if event.type == pygame.QUIT: _running = False if event.type == KEYDOWN: if event.key == K_ESCAPE: _running = False elif event.key == K_a: if not sound: sound = sound_261_6 sound.play() elif event.key == K_s: if not sound: sound = sound_261_6 sound.play() if event.type == KEYUP: if sound: sound.stop() sound = None pygame.quit()
Remove integer values from line in a file in python Question: How to remove integer values in lines of a file in python? This is my present output നട തുറന്നപ്പോള്‍ കൃഷ്ണന്‍ പുഞ്ചിരിച്ചു കൊണ്ട് നില്‍ക്കുക ആയിരുന്നു 1. എന്തോ പറയുന്ന പോലെ തോന്നി 2. കള്ള കൃഷ്ണന്‍ 3. അവന് എന്നും ഇങ്ങനേ തന്നെ ആയിരുന്നു 4. I need the output after removing integers as നട തുറന്നപ്പോള്‍ കൃഷ്ണന്‍ പുഞ്ചിരിച്ചു കൊണ്ട് നില്‍ക്കുക ആയിരുന്നു . എന്തോ പറയുന്ന പോലെ തോന്നി . കള്ള കൃഷ്ണന്‍ . അവന് എന്നും ഇങ്ങനേ തന്നെ ആയിരുന്നു . Answer: Use regular expression to replace digit characters, e.g. import re re.sub(r'\d+', '', input_str)
Python: how to reload modules that have been imported with * Question: I know that if I import a module by name `import(moduleName)`, then I can reload it with `reload(moduleName)` But, I am importing a bunch of modules with a Kleene star: from proj import * How can I reload them in this case? Answer: I think there's a way to reload all python modules. The code for Python 2.7 is listed below: Instead of importing the math module with an asterisk, you can import whatever you need. from math import * from sys import * Alfa = modules.keys() modules.clear() for elem in Alfa: str = 'from '+elem+' import *' try: exec(str) except: pass
python BeautifulSoup finding certain things in a table Question: Folks, Ive managed to get beautifulsoup to scrape a page with the following html = response.read() soup = BeautifulSoup(html) links = soup.findAll('a') There are several occurrences of <A href="javascript:Set_Variables('foo1','bar1''')"onmouseover="javascript: return window.status=''"> <A href="javascript:Set_Variables('foo2','bar2''')"onmouseover="javascript: return window.status=''"> How can I iterate through this and get the foo/bar values? Thanks Answer: You can use regular expressions to extract variables from `href` attributes: import re from bs4 import BeautifulSoup data = """ <div> <table> <A href="javascript:Set_Variables('foo1','bar1''')" onmouseover="javascript: return window.status=''"> <A href="javascript:Set_Variables('foo2','bar2''')" onmouseover="javascript: return window.status=''"> </table> </div> """ soup = BeautifulSoup(data) pattern = re.compile(r"javascript:Set_Variables\('(\w+)','(\w+)'") for a in soup('a'): match = pattern.search(a['href']) if match: print match.groups() Prints: ('foo1', 'bar1') ('foo2', 'bar2')
Pyinstaller fails with Python FBX Question: I wrote a simple test script for Python FBX from Autodesk (<http://www.autodesk.com/products/fbx/overview>). It reads an .FBX file and prints out some information on the file's contents. It works fine when running the .py but when using Pyinstaller to turn it into an EXE, it fails with this error: File "<string>", line 2, in <module> File ".....\pyi_importers.py", line 409, in load_module module = imp.load_module(fullname, fp, filename, self._c_ext_tuple) ImportError: No module named fbxsip I have no idea what fbxsip is supposed to be. Answer: It looks as though pyinstaller is not able to resolve the dependencies on the Autodesk SDK. fbxsip.pyd is part of the Autodesk SDK. Most likely you will need to modify your spec to explicitly include fbxsip.pyd and fbx.pyd
Using a COM dll in python? Question: I need to use an COM dll (made in CSharp) in my python project. I tried to follow this example [Using COM Objects in Scripting Languages -- Part 2 (Python)](http://www.codeproject.com/Articles/73880/Using-COM-Objects-in- Scripting-Languages-Part-Py), but I dont have success. **My python code is:** import sys # for TkInter GUI support from Tkinter import * import tkMessageBox import tkColorChooser # for COM support import comtypes.client as cc import comtypes # Load the typelibrary registered with the Windows registry tlb_id = comtypes.GUID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") cc.GetModule((tlb_id, 1, 0)) **When I run the python class, this error occurs:** > Traceback (most recent call last): File "C:\Program Files > (x86)\JetBrains\PyCharm 129.696\helpers\pydev\pydevd.py", line 1481, > in <module> > debugger.run(setup['file'], None, None) File "C:\Program Files (x86)\JetBrains\PyCharm 129.696\helpers\pydev\pydevd.py", line 1124, > in run > pydev_imports.execfile(file, globals, locals) #execute the script File "C:/aa_python/gtk_project/main.py", line 7, in <module> > from com_class_file import ComClass File "C:/aa_python/gtk_project\com_class_file.py", line 15, in <module> > cc.GetModule((tlb_id, 1, 0)) File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\client\_generate.py", > line 101, in GetModule > tlib = comtypes.typeinfo.LoadRegTypeLib(comtypes.GUID(tlib[0]), *tlib[1:]) File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\typeinfo.py", > line 473, in LoadRegTypeLib > _oleaut32.LoadRegTypeLib(byref(GUID(guid)), wMajorVerNum, wMinorVerNum, lcid, byref(tlib)) File "_ctypes/callproc.c", line > 945, in GetResult WindowsError: [Error -2147319779] Library not registered **Error line:** cc.GetModule((tlb_id, 1, 0)) **In my CSharp Project, I have this in my COM dll:** **Interface** [InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY")] public interface ITestCOM { string say_hello(); } **Class** [ClassInterface(ClassInterfaceType.None), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")] public class TestCOM : ITestCOM { public string say_hello() { return "hello world!"; } } This COM project above, is used in others applications and works fine. My problem is only in python. In time: my COM dll is registered in windows registry Any Help? Answer: Here I found a tip that helped me use my COM dll using the TLB file: [Accessing unregistered COM objects from python via a registered TLB](http://stackoverflow.com/a/6001210/1347355) Thanks to Márcio Faustino.
Encoding in Python - non-English characters into a URL Question: I’m trying bit for bit to write a geocoding script. There is a Danish (official and free) web service, where I enter an address in the URL and get a json file with all needed info. I can’t find the right way to translate my Danish characters (æ,ø,å) when they go into an URL. In the example I have included two different urls (containing the address info). One – where the street is ‘Byvej’ works fine, and I get the result I expect printed out in IDLE. (And I can get the lat/long too). The other, where the street is ‘Bispegårdsvej’ gives nothing in IDLE. The returned list is empty. The url works fine in a browser, and I know, I need to add something to the script, I just can’t find anything that works. I'm using ActivePython 2.7.2.5 Thanks, Tommy # -*- coding: cp1252 -*- import urllib2 import json #url='http://geo.oiorest.dk/adresser.json?postnr=4682&vejnavn=Byvej&husnr=31' url='http://geo.oiorest.dk/adresser.json?postnr=4320&vejnavn=Bispegårdsvej&husnr=2' try: data = urllib2.urlopen(url).read() adresser = json.loads(data) for adresse in adresser: print "%s %s, %s %s" % \ (adresse['vejnavn']['navn'], adresse['husnr'], adresse['postnummer']['nr'], adresse['postnummer']['navn']) except urllib2.HTTPError, e: print "HTTP error: %d" % e.code except urllib2.URLError, e: print "Network error: %s" % e.reason.args[1] Answer: You need to encode the social characters with percent encoding, also known as URL encode. After percent encoding, the URL should like like this: http://geo.oiorest.dk/adresser.json?postnr=4320&vejnavn=Bispeg%C3%A5rdsvej&husnr=2 Web services that complies with the IRI to URI mapping defined in RFC 3987 would use utf-8 for encoding after character normalization, but you should need to check the documentation the service to be sure what encoding to use. Python has urllib.quote() in the standard library to do percent encoding from a string and urllib.urlencode() in the standard library to do percent encoding from a dictionary or an iterable of two elements tuples to produce a string for the query parameter.
Issue in return of Image variable from django view (numpy array) to template Question: I am a newbie in python/django/web development. I am facing an issue with returning my image from my `django view` to my `django template`. I have a dummy button on my HTML page which calls a function in my `views.py`. This function returns an image (which is in the form of a numpy array). I want to return the image to my template. Although, I am able to return the image variable without any error, in the template I am not being able to see the image. This is the code in my `views.py` function which returns the image to the `dummy.html` page def ipdtest(request, frameslug): import cv2 frame= VTryON.objects.get(slug=frameslug) image_of_frame=frame.image.url frame_path=("path name"+str(image_of_frame)) d=Frame_Superimposition() img=Frame_Superimposition.frameSuperimpose(d,frame_path) #print type(d) print type(img) #cv2.imshow('img', img) #cv2.waitKey(0) context={'d':d, 'img':img} return render_to_response('dummy.html', context,context_instance=RequestContext(request)) The `img` variable is of the type `numpy array`. I know that the image is properly being processed since I am able to see it doing a `cv2.imshow`. So is this a compatibility issue between numpy form and RGB form? If so, then how do I make the image display properly on to the `dummy.html`? This is how I retrieve it in my dummy.html page. <body class="body"> <div id="pageContainer"> <br> <img src="{{img}}" width=250 height=100/> <br> </div> Please give some suggestions on how to solve this. Thanks in advance :) Answer: What does `print img` statement print...? Anyways try this... `{{ img.url }}`
Using Flask, how can I download a file from a user-given URL? Question: I'm writing (what was supposed to be) a quick application on an OpenShift server running a Python 3.3 cartridge with Flask. Here's what I want: I need a Flask method for getting a file from a URL and saving that file to disk. edit: I should clarify, I have little experience web apps. Despite hours of reading and searching, I can't get the hang of URLs and file transfers. Answer: Using [requests](http://docs.python-requests.org/en/latest/), here's how to download and save the Google logo: import requests r = requests.get('https://www.google.com/images/srpr/logo11w.png') with open('google_logo.png', 'wb') as f: f.write(r.content) You can use this from within a Flask view to download a user provided URL. from flask import request import requests @app.route('/user_download') def user_download(): url = request.args['url'] # user provides url in query string r = requests.get(url) # write to a file in the app's instance folder # come up with a better file name with app.open_instance_resource('downloaded_file', 'wb') as f: f.write(r.content)
Permutating lists too large for RAM in Python Question: I have written a program to read a list of words from a text file (one word per line) and combine them to produce every permutation of 3 words before writing an output file of the permutations, again one per line. import itertools wordList = open("wordlist.txt", "r").readlines() # import words into list wordListOut = open("output.txt", "w") wordList = [item.rstrip() for item in wordList] # strip \n from list items for item in [x for x in itertools.permutations(wordList, 3)]: wordListOut.write("".join("%s %s %s\n" % item)) wordListOut.close() It seems to do the job, but my concern is that with the whole text being stored in RAM in a list and `itertools.permutations()` producing a list of tuples in RAM, without a very large `wordlist.txt` it will quickly run out of memory. It would be better if each permutation was written straight to the output file rather than held in RAM, and depending on size of `wordlist.txt`, it could be better not to load the whole thing to RAM. Also how can I avoid adding `\n` to the last line of the output file? Answer: for item in [x for x in itertools.permutations(wordList, 3)]: This line is not providing any benefit and will only cause problems. [`permutations()`](https://docs.python.org/3.4/library/itertools.html#itertools.permutations) does **not** produce a list, it uses a generator that creates the next permutation as it is requested. By wrapping this call in a list comprehension, **you are** producing that list and ensuring that all permutations exist in memory at one time. This defeats the point of using a generator in the first place. You should change the line to be just: for item in itertools.permutations(wordList, 3):
How to get precipitation/rainfall through weather api? Question: I tired [Open Weather Map](http://openweathermap.org/current) because the docs say it has "rain", but when I call it it doesn't. So I tried [Python Weather API](https://code.google.com/p/python-weather-api/wiki/Examples) but none of those options from weather.com, noaa, or yahoo weather have rainfall or precipitation. So I tried [Wunderground](http://www.wunderground.com/weather/api/d/docs?d=index&MR=1) but that only seems to work for US cities, and on top of that I can't be bothered buying a key. Anyone know where to go from here? On open weather map it says it has rain, but I don't get that in the results: Example of JSON call {"coord":{"lon":139,"lat":35}, "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049}, "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}], "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04}, "wind":{"speed":7.31,"deg":187.002}, "rain":{"3h":0}, # on this line "clouds":{"all":92}, "dt":1369824698, "id":1851632, "name":"Shuzenji", "cod":200} However, when I call it like so from pprint import pprint import requests r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Vancouver') pprint(r.json()) I get something with no rainfall/precipitation. {u'base': u'cmc stations', u'clouds': {u'all': 0}, u'cod': 200, u'coord': {u'lat': 49.25, u'lon': -123.12}, u'dt': 1406042326, u'id': 6173331, u'main': {u'humidity': 77, u'pressure': 862, u'temp': 289.33, u'temp_max': 290.93, u'temp_min': 288.15}, u'name': u'Vancouver', u'sys': {u'country': u'CA', u'message': 0.1867, u'sunrise': 1406032353, u'sunset': 1406088323}, u'weather': [{u'description': u'Sky is Clear', u'icon': u'01d', u'id': 800, u'main': u'Clear'}], u'wind': {u'deg': 104.001, u'speed': 2.75}} Answer: According to the [documentation](http://openweathermap.org/weather-data), `weather`, `rain.3h`, and `snow.3h` are all `optional` parameters, suggesting that they will not always be included in the result. I interpret that to mean that rain and snow won't be reported if there was no rain or snow at the time in question -- such as in your example where it says "Sky is clear" -- but it's also possible that it means they just don't guarantee rain/snow data.
Bottle Python Error 404: Not found: '/' Question: I am very new to using bottle but whenever I try to run my programs I always get the error Error 404: Not Found '/'. The app in my example is not fully functional yet but it should at least display something on the screen. Even with fully functional programs this happens. There are similar problems asked but none of the solutions in those have worked. import bottle from cork import Cork from cork.backends import SQLiteBackend sb = SQLiteBackend('sasdasd.db', initialize=True) aaa = Cork(backend=sb) app = bottle.Bottle() def post_get(name, default=''): return bottle.request.POST.get(name, default).strip() @bottle.route('/login') def login(): return ''' <form action="/login" method="post"> Username: <input name="username" type="text" /> Password: <input name="password" type="password" /> <input value="Login" type="submit" /> </form> ''' @bottle.post('/login') def login(): """Authenticate users""" username = post_get('username') password = post_get('password') aaa.login(username, password, success_redirect='/', fail_redirect='/login') bottle.run() Answer: As @Wooble points out in his comment, you need to register the route "/" if you expect your webapp to respond with anything other than a 404 for that path. Here's some code to illustrate: @bottle.get('/') def home(): return 'Hello!' Now your webserver will respond with an HTTP 200 and a body of "Hello!" when you request /.
In Python, what's the best way to get an unknown int from a string? Question: **SOLUTION:** Ok guys I ended up using the following. It involves regular expressions. This is what I was trying to get at. matches = re.findall(r'My favorite chili was number \d+"', line) # gets 1 match if matches: # if there are matches nums.append(int(re.findall(r'\d+',matches[0])[0])) # append the number This isn't very elegant, but it is extremely robust. It also _always_ works based on the format of the files I'm using. Thank you @The2ndSon for suggesting regular expressions. That's what I had vaguely heard of once and couldn't quite remember. * * * ## Original Question In Python, say I am opening a file. In this file there are certain strings that I want. These strings have the format "My favorite chili was chili number NUM" where `NUM` is replaced by a natural number (a non-negative integer). * * * What is the best way to find lines containing this string, and store `NUM`? I have some code laid out, but it seems like there should be a more elegant solution. Are there built-ins made specifically for this purpose? It seems very similar to other string formatting stuff that Python has built-ins for. * * * I am using Python 2.7 * * * Here is my code so far: nums = [] with open('file.txt', 'r') as txtfile: for line in txtfile: indx = line.find('My favorite chili was number ') if indx != -1: nums.append(int(line[indx+30:indx+31])) * * * **IMPORTANT EDIT** : There can be more than one number on each line, and the numbers I want are NOT always necessarily at the end. The whole chili thing was just an example. Answer: You could use a regular expression to extract digits from a string. >>>import re >>>re.findall(r'\d+', "My favorite chili was chili number 19") ['19']
getting error in canny edge detection Question: i am trying to write a code using opencv python that automatically get canny threshold values instead of doing them manually every time. img= cv2.imread('micro.png',0) output = np.zeros(img.shape, img.dtype) # Otsu's thresholding ret2,highthresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) lowthresh=0.1*highthres edges = cv2.Canny(img,output,lowthresh,highthresh) cv2.imshow('canny',edges) i am getting this error "File "test2.py", line 14, in edges = cv2.Canny(img,output,lowthresh,highthresh) TypeError: only length-1 arrays can be converted to Python scalars" can anyone help me to sort out this error.thankx in advance Answer: It seems like `cv2.threshold` returns the detected edges, and `Canny` applies them to the image. The code below worked for me and gave me some nice detected edges in my image. import cv2 cv2.namedWindow('canny demo') img= cv2.imread('micro.png',0) ret2,detected_edges = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) edges = cv2.Canny(detected_edges,0.1,1.0) dst = cv2.bitwise_and(img,img,mask = edges) cv2.imshow('canny',dst) if cv2.waitKey(0) == 27: cv2.destroyAllWindows()
changing global variable with thread in Python Question: I am trying to write a script updating a global variable every 10 seconds. For simplicity let's just increment `q` once teach time import time, threading q = 0 def f(q): # get asset position every 10 seconds: q += 1 print q # call f() again in 10 seconds threading.Timer(10, f).start() # start calling f now and every 10 sec thereafter f(q) Instead python says: UnboundLocalError: local variable 'q' referenced before assignment What is the correct way to change the variable `q`? * * * this example uses threading, doesn't update any values. [Run certain code every n seconds](http://stackoverflow.com/questions/3393612/run-certain-code- every-n-seconds) Answer: You need to explicitly declare q as a global. `q += 1` confuses the interpreter otherwise. import threading q = 0 def f(): global q q += 1 print q threading.Timer(10, f).start() f()
pick a random line from a very big file, from command line Question: Suppose you have a very big file, and it'd be to expensive to go through all the lines, or to slow. How would you pick a line at random (preferably from command line, or python)? Answer: You can try this from the command line - not sure if totally random, but at least is a beginning. $ lines=$(wc -l file | awk '{ print $1 }'); sed -n "$((RANDOM%lines+1))p" file This works like this: * First, it sets a variable containing the number of lines in the file. lines=$(wc -l file | awk '{ print $1 }') * Later, it prints a random line within that range: sed -n "$((RANDOM%lines+1))p" file * * * As Mark Ransom pointed out, the above solution reads the entire file. I have found a way to choose a random line without (necessarily) having to read the entire file, but just part of it. Using (I think) the same algorithm, here are the links to both Perl and Python solutions: * Perl: [How do I pick a random line from a file?](http://www.perlmonks.org/?node_id=1910) perl -e 'srand;' \ -e 'rand($.) < 1 && ($it = $_) while <>;' \ -e 'print $it' FILE * Python: [Retrieving a Line at Random from a File of Unknown Size](http://my.safaribooksonline.com/book/programming/python/0596001673/files/pythoncook-chp-4-sect-6) import random def randomLine(file_object): "Retrieve a random line from a file, reading through the file once" lineNum = 0 selected_line = '' while 1: aLine = file_object.readline( ) if not aLine: break lineNum = lineNum + 1 # How likely is it that this is the last line of the file? if random.uniform(0,lineNum)<1: selected_line = aLine file_object.close( ) return selected_line
Sphinx autodoc not importing anything? Question: I'm trying to use `sphinx` (in conjunction with `autodoc` and `numpydoc`) to document my module, but after the basic setup, running `make html` produces just the basic html with nothing from the docstrings included. I'm running Python 3.3, the outline of the project structure is as follows: Kineticlib |--docs | |--build | |--source | | |--conf.py |--src | |--kineticmulti | | |--__init__.py | | |--file1.py | | |--file2.py |--setup.py `__init__.py` is empty, and in `conf.py` in the `docs/source` directory I've added `sys.path.insert(0, os.path.abspath('../..'))` Running `make html` in the `docs` directory gives the following output: sphinx-build -b html -d build/doctrees source build/html Running Sphinx v1.2.2 loading pickled environment... done building [html]: targets for 0 source files that are out of date updating environment: 0 added, 0 changed, 0 removed looking for now-outdated files... none found no targets are out of date. Build finished. The HTML pages are in build/html. So, what am I doing wrong? Answer: Did you run sphinx-apidoc in the docs/source directory? This will generate the .rst files used to make the html. From `man sphinx-apidoc`, sphinx-apidoc [options] -o <outputdir> <sourcedir> [pathnames ...] You'll need to include (at a minimum) the `outputdir` (where the .rst files will go, ./ should work) and the `sourcedir` which should point to your package (looks like ../../src/kineticmulti should work)
column wise dictionary creation using python Question: How to make a columnwise dictionary from csv using python? name, lastname, hobby jhon, g, fishing mike, a, boxing tom, v, sking output should be : name = {1 : 'jhon', 2:'mike', 3:'tom'} lastname = {1 : 'g', 2:'a', 3:'v'} hobby = {1 : 'fishing', 2:'boxing', 3:'sking'} Answer: Using [pandas](http://pandas.pydata.org/) you can get both list or dictionary very easily: >>> import pandas as pd >>> from StringIO import StringIO >>> csvfile = StringIO('''name, lastname, hobby ... jhon, g, fishing ... mike, a, boxing ... tom, v, sking''') >>> >>> df = pd.read_csv(csvfile) >>> dict(df['name']) {0: 'jhon', 1: 'mike', 2: 'tom'} >>> list(df['name']) ['jhon', 'mike', 'tom']
Can a dictionary be passed directly to instantiate another object in python Question: I'm experimenting with parse.com as a db for my django app. I've installed parse_rest. I have a list of dictionaries, with each dictionary of the form: all_practices = {'a':value1, 'b':value2 ...} according to the answer provided by Michael Otte, in [Add and save objects to parse.com db from django](http://stackoverflow.com/questions/24900946/add-and- save-objects-to-parse-com-db-from-django) I can save this object by the following: from parse_rest.datatypes import Object class Profile(Object): pass # instantiate with parameters profile = Profile(name='Johnny', age=27) is there a way to directly pass dictionary object as the parameters of the profile object, so as to get: profile = Profile(a='value1', b='value2') Answer: Yes, use the [keyword/dictionary unpacking operator `**`](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument- lists): profile = Profile(**all_practices)
how to insert tabs instead of spaces when creating xml files in python Question: I m using [Creating a simple XML file using python](http://stackoverflow.com/questions/3605680/creating-a-simple-xml-file- using-python) and [inserting newlines in xml file generated via xml.etree.ElementTree in python](http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml- file-generated-via-xml-etree-elementtree-in-python) but my xml subelement has 2 spaces from left, instead of a tab, how do I switch to a tab for a subelement and not 2 spaces? Answer: Set `indent` argument of [`toprettyxml()`](https://docs.python.org/2/library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml) to `\t`: from xml.dom import minidom import xml.etree.cElementTree as ET root = ET.Element("root") doc = ET.SubElement(root, "doc") field1 = ET.SubElement(doc, "field1") field1.set("name", "blah") field1.text = "some value1" field2 = ET.SubElement(doc, "field2") field2.set("name", "asdfasd") field2.text = "some vlaue2" dom = minidom.parseString(ET.tostring(root)) print dom.toprettyxml(indent='\t') prints: <?xml version="1.0" ?> <root> <doc> <field1 name="blah">some value1</field1> <field2 name="asdfasd">some vlaue2</field2> </doc> </root>
Python OpenCV : Rubiks cube solver color extraction Question: **Description:** I am working on solving rubiks cube using Python & OpenCV. For this purpose I am trying to extract all the colors of the cubies(individual cube pieces) and then applying appropriate algorithm(which I've designed, no issues there). **The problem:** Suppose if I've extracted all the colors of the cubies, how I can locate the position of the extracted cubies. Like how I'll know whether it is in top- middle-lower layer or whether its a corner-middle-edge piece. **What I've done:** Here I have just extracted yellow color. **_After color extraction:_** ![enter image description here](http://i.stack.imgur.com/x298k.jpg) **_Original Image_** ![enter image description here](http://i.stack.imgur.com/OYFN2.png) **_The Code_** import numpy as np import cv2 from cv2 import * im = cv2.imread('v123.bmp') im = cv2.bilateralFilter(im,9,75,75) im = cv2.fastNlMeansDenoisingColored(im,None,10,10,7,21) hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) # HSV image COLOR_MIN = np.array([20, 100, 100],np.uint8) # HSV color code lower and upper bounds COLOR_MAX = np.array([30, 255, 255],np.uint8) # color yellow frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) # Thresholding image imgray = frame_threshed ret,thresh = cv2.threshold(frame_threshed,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print type(contours) for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) print x, print y cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Show",im) cv2.imwrite("extracted.jpg", im) cv2.waitKey() cv2.destroyAllWindows() Please give some suggestions on how can I locate the positions of the cubies. Here 4 yellow cubies are spotted: top-right-corner, center, right-edge, bottom-left-corner. How can I identify these positions for eg: by assigning digits to each position (here: 3, 4, 5, 7) Any help/idea is appreciated :) Thanks. P.S.: OpenCV newbie :) Answer: Here's the original code and location of the found yellow squares. ## source import numpy as np import sys; sys.path.append('/usr/lib/pyshared/python2.7') import cv2 from cv2 import * im = cv2.imread('rubik.png') im = cv2.bilateralFilter(im,9,75,75) im = cv2.fastNlMeansDenoisingColored(im,None,10,10,7,21) hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) # HSV image COLOR_MIN = np.array([20, 100, 100],np.uint8) # HSV color code lower and upper bounds COLOR_MAX = np.array([30, 255, 255],np.uint8) # color yellow frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) # Thresholding image imgray = frame_threshed ret,thresh = cv2.threshold(frame_threshed,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # print type(contours) for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) print x,y cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Show",im) cv2.imwrite("extracted.jpg", im) cv2.waitKey() cv2.destroyAllWindows() ## output 185 307 185 189 307 185 431 55
Import Excel to Matlab without numeric data appearing in scientific notation Question: My question is hopefully a simple one for experienced Matlab users. How can I import data in an Excel sheet to Matlab without Matlab automatically converting the numeric data to scientific notation? The data I'm working with are ID numbers, up to 12 digits long, so I need to see (for example) 30094111063 and not 3.0094e+10 or else Matlab confuses similar ID numbers, for example 30094111063 and 30094111742, later in the code as a "match", because they both appear as 3.0094e+10. Things I've tried so far without success: xlsread, uiopen, sscanf. I've also seen answers to very similar questions to mine on StackOverflow, but for Access, R, Python, etc. and not Matlab, so hopefully this is useful to future users. Thanks! Edit: Here's an example of the code I'm working with: A = xlsread('test1974.xlsx'); B = xlsread('test1975.xlsx'); adj = zeros(N,N); for i=1:N; for j=1:N; if A(i,:) == B(:,j) adj(i,j) = 1; else adj(i,j) = 0; end; end; end; The code is creating "false positive" matches between A and B. Answer: add this code to your script: format long Example: >> 33333333333333 ans = 3.3333e+13 >> format long >> 33333333333333 ans = 3.333333333333300e+13
Fast selection of a Timestamp range in hierarchically indexed pandas data in Python Question: Having a DataFrame with tz-aware DatetimeIndex the below is a fast way of selecting multiple rows between two dates for left inclusive, right exclusive intervals: import pandas as pd start_ts = pd.Timestamp('20000101 12:00 UTC') end_ts = pd.Timestamp('20000102 12:00 UTC') ix_df = pd.DataFrame(0, index=[pd.Timestamp('20000101 00:00 UTC'), pd.Timestamp('20000102 00:00 UTC')], columns=['a']) EPSILON_TIME = pd.tseries.offsets.Nano() ix_df[start_ts:end_ts-EPSILON_TIME] The above solution is fairly efficient as we do not create a temporary indexing iterable as I'll do later, nor do we run a lambda expression in Python to create the new data frame. In fact I believe the selection is around O(log(N)) at most. I wonder if this is also possible on a particular axis of a MultiIndex, or I have to create a temporary iterable or run a lambda expressions. E.g.: mux = pd.MultiIndex.from_arrays([[pd.Timestamp('20000102 00:00 UTC'), pd.Timestamp('20000103 00:00 UTC')], [pd.Timestamp('20000101 00:00 UTC'), pd.Timestamp('20000102 00:00 UTC')]]) mux_df = pd.DataFrame(0, index=mux, columns=['a']) Then I can select on the first (zeroth) level of the index on the same way: mux_df[start_ts:end_ts-EPSILON_TIME] which yields: a 2000-01-02 00:00:00+00:00 2000-01-01 00:00:00+00:00 0 but for the second level I have to chose a slow solution: values_itr = mux_df.index.get_level_values(1) mask_ser = (values_itr >= start_ts) & (values_itr < end_ts) mux_df[mask_ser] yielding correctly: a 2000-01-03 00:00:00+00:00 2000-01-02 00:00:00+00:00 0 Any fast workarounds? Thanks! **Edit: Chosen Approach** Ended up with this solution after all, when having realized I also need slicing: def view(data_df): if len(data_df.index) == 0: return data_df values_itr = data_df.index.get_level_values(0) values_itr = values_itr.values from_i = np.searchsorted(values_itr, np.datetime64(start_ts), side='left') to_i = np.searchsorted(values_itr, np.datetime64(end_ts), side='left') return data_df.ix[from_i:to_i] Then do view(data_df).copy(). Note: my values in the first level of the index are in fact sorted. Answer: Well you are actually comparing apples to oranges here. In [59]: N = 1000000 In [60]: pd.set_option('max_rows',10) In [61]: idx = pd.IndexSlice In [62]: df = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([list('abcdefghij'),date_range('20010101',periods=N/10,freq='T',tz='US/Eastern')],names=['one','two'])) In [63]: df Out[63]: value one two a 2001-01-01 00:00:00-05:00 0 2001-01-01 00:01:00-05:00 1 2001-01-01 00:02:00-05:00 2 2001-01-01 00:03:00-05:00 3 2001-01-01 00:04:00-05:00 4 ... ... j 2001-03-11 10:35:00-05:00 999995 2001-03-11 10:36:00-05:00 999996 2001-03-11 10:37:00-05:00 999997 2001-03-11 10:38:00-05:00 999998 2001-03-11 10:39:00-05:00 999999 [1000000 rows x 1 columns] In [64]: df2 = df.reset_index(level='one').sort_index() df In [65]: df2 Out[65]: one value two 2001-01-01 00:00:00-05:00 a 0 2001-01-01 00:00:00-05:00 i 800000 2001-01-01 00:00:00-05:00 h 700000 2001-01-01 00:00:00-05:00 g 600000 2001-01-01 00:00:00-05:00 f 500000 ... .. ... 2001-03-11 10:39:00-05:00 c 299999 2001-03-11 10:39:00-05:00 b 199999 2001-03-11 10:39:00-05:00 a 99999 2001-03-11 10:39:00-05:00 i 899999 2001-03-11 10:39:00-05:00 j 999999 [1000000 rows x 2 columns] When I reset the index (iow create a single-level index), it IS NOT LONGER UNIQUE. This makes a big difference, because it searches diffently. So you cannot really compare indexing on a single-level unique index vs a multi- level. Turns out using the multi-index slicers (introduced in 0.14.0). Makes indexing pretty fast on any level. In [66]: %timeit df.loc[idx[:,'20010201':'20010301'],:] 1 loops, best of 3: 188 ms per loop In [67]: df.loc[idx[:,'20010201':'20010301'],:] Out[67]: value one two a 2001-02-01 00:00:00-05:00 44640 2001-02-01 00:01:00-05:00 44641 2001-02-01 00:02:00-05:00 44642 2001-02-01 00:03:00-05:00 44643 2001-02-01 00:04:00-05:00 44644 ... ... j 2001-03-01 23:55:00-05:00 986395 2001-03-01 23:56:00-05:00 986396 2001-03-01 23:57:00-05:00 986397 2001-03-01 23:58:00-05:00 986398 2001-03-01 23:59:00-05:00 986399 [417600 rows x 1 columns] Compare this with a non-unique single-level In [68]: %timeit df2.loc['20010201':'20010301'] 1 loops, best of 3: 470 ms per loop Here is a UNIQUE single-level In [73]: df3 = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=date_range('20010101',periods=N,freq='T',tz='US/Eastern')) In [74]: df3 Out[74]: value 2001-01-01 00:00:00-05:00 0 2001-01-01 00:01:00-05:00 1 2001-01-01 00:02:00-05:00 2 2001-01-01 00:03:00-05:00 3 2001-01-01 00:04:00-05:00 4 ... ... 2002-11-26 10:35:00-05:00 999995 2002-11-26 10:36:00-05:00 999996 2002-11-26 10:37:00-05:00 999997 2002-11-26 10:38:00-05:00 999998 2002-11-26 10:39:00-05:00 999999 [1000000 rows x 1 columns] In [75]: df3.loc['20010201':'20010301'] Out[75]: value 2001-02-01 00:00:00-05:00 44640 2001-02-01 00:01:00-05:00 44641 2001-02-01 00:02:00-05:00 44642 2001-02-01 00:03:00-05:00 44643 2001-02-01 00:04:00-05:00 44644 ... ... 2001-03-01 23:55:00-05:00 86395 2001-03-01 23:56:00-05:00 86396 2001-03-01 23:57:00-05:00 86397 2001-03-01 23:58:00-05:00 86398 2001-03-01 23:59:00-05:00 86399 [41760 rows x 1 columns] Fastest so far In [76]: %timeit df3.loc['20010201':'20010301'] 1 loops, best of 3: 294 ms per loop Best is a single-level UNIQUE without a timezone In [77]: df3 = DataFrame(np.arange(N).reshape(-1,1),columns=['value'],index=date_range('20010101',periods=N,freq='T')) In [78]: %timeit df3.loc['20010201':'20010301'] 1 loops, best of 3: 240 ms per loop And by far the fastest method (I am doing a slightly different search here to get the same results, as the semantics of the above searches include all dates on the specified dates) In [101]: df4 = df3.reset_index() In [103]: %timeit df4.loc[(df4['index']>='20010201') & (df4['index']<'20010302')] 100 loops, best of 3: 10.6 ms per loop In [104]: df4.loc[(df4['index']>='20010201') & (df4['index']<'20010302')] Out[104]: index value 44640 2001-02-01 00:00:00 44640 44641 2001-02-01 00:01:00 44641 44642 2001-02-01 00:02:00 44642 44643 2001-02-01 00:03:00 44643 44644 2001-02-01 00:04:00 44644 ... ... ... 86395 2001-03-01 23:55:00 86395 86396 2001-03-01 23:56:00 86396 86397 2001-03-01 23:57:00 86397 86398 2001-03-01 23:58:00 86398 86399 2001-03-01 23:59:00 86399 [41760 rows x 2 columns] Ok, so why is the 4th method the fastest. It constructs a boolean indexing array then uses nonzero, so pretty fast. The first three methods use searchsorted (twice) after already determining that the index is unique and monotonic, to figure out the endpoints, so you have multiple things going on. Bottom line, boolean indexing is pretty fast, so use it! (results may different and the first 3 methods may become faster depending on WHAT you are selecting, e.g. a smaller selection range may have different performance characteristics).
decorator inside class not getting values Question: I have a decorator that validates a json response that I obtain using requests. I also wrapped some requests logic into a class which accepts a schema that the decorator needs to validate. I tried to use the decorator on the get function of the class but i get a type error each way I try to do it: TypeError: get() takes exactly 1 argument (0 given) I know that if you use a decorator on a class method you need to set self=None in the decorator. Here is the code: schema = {'pid': int, 'description': str} def validator(schema): def _validator(f): @wraps(f) def wrapped(self=None): print f check = all([isinstance(v, schema[k]) for k,v in f().iteritems() if v]) return f() if check else None return wrapped return _validator class Data(object): ''' Base request wrapper to use for all apis accepts a validator schema to check the type of response values. ''' def __init__(self, base_url, schema=None, debug=False): self.base_url = base_url self.schema = schema def __getattr__(self,key): new_base = self.append_to_url(self.base_url, key) return self.__class__(base_url=new_base) def __getitem__(self,key): return self.__getattr__(key) # def __call__(self, **kwargs): # self.base_url = self.base_url[:-1] # return self.get(self.base_url, **kwargs) def append_to_url(self, base_url, param): return '{}{}/'.format(base_url, param) @validator(schema) def get(self, **kwargs): try: r = requests.get(self.base_url[:-1], **kwargs) r.raise_for_status() return r.json() except requests.exceptions.ConnectionError as e: raise errors.ApiError(e) except requests.exceptions.HTTPError as e: raise errors.ApiError(e) product_details = Data('my_api_url', schema).shoes['10'].get() I think this happens because in my validator I initialize f() which is the get function is expecting self. I tried to pass self to f() in the decorator but that also yields the same error. I even tried to have the get function initialize on the __call__ method but that yields the get function is expecting 1 arg and 2 were given. There must be a more efficient or pythonic way to achieve this. I know there is a library called voluptuous that does tons of validations but I wanted to try something simple as a learning exercise. Answer: It's not the `wrapped` function call that's failing, it's the `get` call. Everywhere you call the `get` you call it like `f()`, i.e. without any arguments. A working example, properly passing `self` argument to the wrapped function: import functools def validator(schema): def _validator(f): @functools.wraps(f) def wrapper(self): # pass self to the wrapped function result = f(self) return 'wrapped {} {}'.format(schema, result) return wrapper return _validator class Data(object): @validator('test') def get(self): return 'data' print(Data().get()) # wrapped test data While you can use `self` or other such specific arguments directly, using `*args` and `**kwargs` instead makes the decorator more flexible, e.g. enables it to be used for non-bound functions too: import functools def validator(schema): def _validator(f): @functools.wraps(f) def wrapped(*args, **kwargs): # pass aribitrary args to the wrapped function # for greater flexibility result = f(*args, **kwargs) return 'wrapped {} {}'.format(schema, result) return wrapped return _validator class Data(object): @validator('test') def get(self): return 'data' @validator('test2') def get(): return 'data2' print(Data().get()) # wrapped test data print(get()) # wrapped test2 data2
Python regular expression to extract optional number at the end of string Question: I'm trying to write a Python regular expression that can parse strings of the type `"<name>(<number>)"`, where `<number>` is optional. For example, if I pass `'sclkout'`, then there is no number at the end, so it should just match `'sclkout'`. If the input is `'line7'`, then is should match `'line'` and `'7'`. The name can also contain numbers inside it, so if I give it `'dx3f'`, then the output should be `'dx3f'`, but for `'dx3b0'` it should match `'dx3b'` and `0`. This is what I first tried: import re def do_match(signal): match = re.match('(\w+)(\d+)?', signal) assert match print "Input = " + signal print "group1 = " + match.group(1) if match.lastindex == 2: print "group2 = " + match.group(2) print "" # should match 'sclkout' do_match("sclkout") # should match 'line' and '7' do_match("line7") # should match 'dx4f' do_match("dx4f") # should match 'dx3b' and '0' do_match("dx3b0") This is of course wrong because of greedy matching in the `(\w+)` group, so I tried setting that to non-greedy: match = re.match('(\w+?)(\d+)?', signal) This however only matches the first letter of the string. Answer: You don't need regex for this: from itertools import takewhile def do_match(s): num = ''.join(takewhile(str.isdigit, reversed(s)))[::-1] return s[:s.rindex(num)], num ... >>> do_match('sclkout') ('sclkout', '') >>> do_match('line7') ('line', '7') >>> do_match('dx4f') ('dx4f', '') >>> do_match('dx3b0') ('dx3b', '0')
Python add numbers in a list Question: Anyone can help me with these? Basically I have list begin created as shown below: >>> item [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')] I want to combine the result of the object only when such as apple and population is met. This is my end result that I want: >>> item [('apple', 16, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')] Any help will be appreciated. My fault if the question wasn't clear: This is some of my code. def add(par): temp_dict = {} for name, count, term in par: if name in temp_dict: temp_dict[name] += count else: temp_dict[name] = count result = [] for name, count, term in par: if name in temp_dict: result.append((name, temp_dict[name], term)) del temp_dict[name] return result How can I make ammendment to the class so that, it returns the desired result? The code above still adds the "apple" together, which is this: > > > item [('apple', 19, 'disease'), ('orange', 6, 'population')] Answer: You may achieve the desired result as follows: In [6]: my_items = [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')] In [7]: import collections In [8]: my_counter = collections.defaultdict(int) In [9]: for i in my_items: # at this point, i is a tuple, let's unpack it (fruit, n, category) = i # use the tuple (fruit, category) as a key. # note that this has to be a tuple, and not a list my_counter[(fruit, category)] += n ...: In [10]: my_counter Out[10]: defaultdict(<class 'int'>, {('orange', 'population'): 6, ('apple', 'population'): 16, ('apple', 'disease'): 3}) (note that this is an [IPython](http://ipython.org/) session I highly recommend it over the vanilla shell for interactive work) In this example, `my_counter` is a modified `dict` object. It differs from the "regular" `dict` by the fact that if the specified key isn't available, a default value will be automatically created (in our case -- integer zero). From your example I understand that you are new to Python. If you need more aggregation power for large data amounts, you may want to take a look at [Pandas](http://pandas.pydata.org/). Good luck. **EDIT** For the sake of completeness, following [keimina](http://stackoverflow.com/users/2931409/keimina)'s [answer in this thread](http://stackoverflow.com/a/24930626/17523), you might consider using `collections.Counter` that has many [features that are useful for counters](http://stackoverflow.com/a/19883180/17523) such as `most_common()` function that was new for me.
Python - read 10min from log file Question: I need some tool to read latest 10 minutes entry in my log file, and if some words are logged then print some text. log file: 23.07.2014 09:22:11 INFO Logging.LogEvent 0 Failed login [email protected] 23.07.2014 09:29:02 INFO Logging.LogEvent 0 login [email protected] 23.07.2014 09:31:55 INFO Logging.LogEvent 0 login [email protected] 23.07.2014 09:44:14 INFO Logging.LogEvent 0 Failed login [email protected] if during last 10min some entry = Failed -print ALARM. All what i did is find 'Failed' match but i have no idea how to check last 10min in my log file ;/ -any idea?? from sys import argv from datetime import datetime, timedelta with open('log_test.log', 'r') as f: for line in f: try: e = line.index("Failed") except: pass else: print(line) Answer: Your format `%d.%m.%Y` is worse than `%Y:%m:%d` which can be used in string comparison. We also do not know if log is big and if it is sorted. If it is not sorted (it is common for multithreaded applications) you will have to analyze each line and convert it into datetime: def get_dt_from_line(s): return datetime.datetime.strptime(s[:20], '%d.%m.%Y %H:%M:%S') Then use it as filter (for small files): MAX_CHECK_TIMEDELTA = datetime.timedelta(minutes=10) LOG_START_ANALYZE_DATETIME = (datetime.datetime.today() - MAX_CHECK_TIMEDELTA) lines = [s for s in TXT.split('\n') if 'Failed' in s and get_dt_from_line(s) >= LOG_START_ANALYZE_DATETIME] print('\n'.join(lines)) For big files you can read file line by line. If your log file is just for one day you can use string comparison instead of datetime comparison: LOG_START_ANALYZE_DATETIME = (datetime.datetime.today() - datetime.timedelta(minutes=10)).strftime('%d.%m.%Y %H:%M:%S') lines = [s for s in TXT.split('\n') if 'Failed' in s and s >= LOG_START_ANALYZE_DATETIME]
How to overcome version incompatibility with Abaqus and Numpy (Python's library)? Question: I want to run an external library of python called `NLopt` within Abaqus through python. The issue is that the NLopt I found is compiled against the latest release of Numpy, **i.e. 1.9** , whereas Abaqus 6.13-2 is compiled against Numpy 1.4. I tried to replace the Numpy folder under the site-packages under the Abaqus installation folder with the respective one of version 1.9 that I created externally through an installation of Numpy 1.9 over Python 2.6 (version that Abaqus uses). Abaqus couldn't even start so I guess that such approach is incorrect. Are there any suggestions on how to overcome such issue? Thanks guys Answer: I have similar problems. As an (annoying) work around I usually write out important data in text files using the regular python. Afterwards, using a bash script, I start a second python (different version) to further analyse the data (matplotlib etc).
Selecting Selected line in listbox python tkinter Question: Hi i have a question to ask regarding Python Tkinter Listbox. when i select the value, what must i add into my code so that the Listbox would return the value? There is no need for multiple selection. Or, can i add in a button to execute a command, while putting the returned value from the listbox into the command? I am using Python 2.7 and lis is the name of my array. Thank you for your kind attention and help! master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "Please select:") for p in lis: listbox.insert(END, p) master.mainloop() Answer: For example you can add button to check selection from Tkinter import * def check_list(): try: s = lb.selection_get() print 'selected:', s except: print 'no selection' master = Tk() lb = Listbox(master) lb.pack() lb.insert(END, "Please select:") for p in range(10): lb.insert(END, p) but = Button(master, text="Check", command=check_list) but.pack() master.mainloop() * * * if you need some argument in `command` then use `lambda` command=lambda:my_function(argument) BTW: look out on argument in `command=` when you use it in `for` loop This puts value `10` in place of `i` in all `my_function(i)` for i in range(10): ... command=lambda:my_function(i) This works as expected for i in range(10): ... command=lambda x=i:my_function(x) * * * **EDIT:** `lb.selection_get()` gives text from listbox (and use `\n` to seperate elements in multiselection) and raise error if there is no selection. `lb.curselection()` gives list of indexes and empty list if there is no selection. def check_list_2(): s = lb.curselection() if not s: print 'no selection' else: for x in s: print 'selected index:', x print 'selected text:', lb.get(x)
passing functions as arguments in other functions python Question: I have these functions, and I'm getting errors, with the do_twice functions, but I'm having problems debugging it #!/usr/bin/python #functins exercise 3.4 def do_twice(f): f() f() def do_four(f): do_twice(f) do_twice(f) def print_twice(str): print str + 'one' print str + 'two' str = 'spam' do_four(print_twice(str)) debugger errors :!python 'workspace/python/functions3.4.py' spamone spamtwo Traceback (most recent call last): File "workspace/python/functions3.4.py", line 18, in <module> do_four(print_twice(str)) File "workspace/python/functions3.4.py", line 9, in do_four do_twice(f) File "workspace/python/functions3.4.py", line 5, in do_twice f() TypeError: 'NoneType' object is not callable shell returned 1 Answer: The problem is that the expression `print_twice(str)` is evaluated by calling `print_twice` with `str` and getting the result that you returned,* and that result is what you're passing as the argument to `do_four`. What you need to pass to `do_four` is a function that, when called, calls `print_twice(str)`. You can build such a function manually: def print_twice_str(): print_twice(str) do_four(print_twice_str) Or you can do the same thing inline: do_four(lambda: print_twice(str)) Or you can use the higher-order function [`partial`](https://docs.python.org/3/library/functools.html#functools.partial) to do it for you: from functools import partial do_four(partial(print_twice, str)) The documentation for `partial` has a pretty nice explanation: > The `partial()` is used for partial function application which “freezes” > some portion of a function’s arguments and/or keywords resulting in a new > object with a simplified signature. For example, `partial()` can be used to > create a callable that behaves like the `int()` function where the _base_ > argument defaults to two: [snip] `basetwo = partial(int, base=2)` * * * * If you're thinking "But I didn't return anything, so where does that `None` come from?": Every function always returns a value in Python. If you don't tell it what to return, it returns `None`.
Python to exe: py2exe issues with pkg_resources Question: I've built an application in Python that I'd like to distribute to my enterprise and installing Python on each machine is unfortunately not an option. I'd like to convert the application to an .exe so that users can run my application with shortcut on their desktop. This is my first attempt at distribution, so please forgive my lack of knowledge on the subject. I'm having issues with py2exe when I attempt to convert my .py script to a .exe. My setup.py script looks like this: from distutils.core import setup import py2exe import numpy import matplotlib setup(console=['inpho.py'], data_files=matplotlib.get_py2exe_datafiles() ) After I run `python setup.py py2exe`, I get the expected `dist` and `build` directories. However, if I run my application, now called `InPho.exe`, a cmd window opens and I immediately get an error: `ImportError: No module named pkg_resources`. My first thought is that my setup.py script is wrong, I just do not know how to properly write one. In my inpho.py script, I use import the following: * pandas * Tkinter * pyodbc * sqlalchemy * sqlite3 * datetime * tkMessageBox * os * shutil Any help is greatly appreciated! Answer: Py2exe might not handle some of the dependencies out of the box. Try this advice from the py2exe tutorial on how to handle import errors in this case: [Dealing With ImportError](http://www.py2exe.org/index.cgi/DealingWithImportError)
Is there a way to gray out (disable) a tkinter Frame? Question: I want to create a GUI in tkinter with two Frames, and have the bottom Frame grayed out until some event happens. **Below is some example code:** from tkinter import * from tkinter import ttk def enable(): frame2.state(statespec='enabled') #Causes error root = Tk() #Creates top frame frame1 = ttk.LabelFrame(root, padding=(10,10,10,10)) frame1.grid(column=0, row=0, padx=10, pady=10) button2 = ttk.Button(frame1, text="This enables bottom frame", command=enable) button2.pack() #Creates bottom frame frame2 = ttk.LabelFrame(root, padding=(10,10,10,10)) frame2.grid(column=0, row=1, padx=10, pady=10) frame2.state(statespec='disabled') #Causes error entry = ttk.Entry(frame2) entry.pack() button2 = ttk.Button(frame2, text="button") button2.pack() root.mainloop() Is this possible without having to individually gray out all of the frame2's widgets? I'm using Tkinter 8.5 and Python 3.3. Answer: Not sure how elegant it is, but I found a solution by adding for child in frame2.winfo_children(): child.configure(state='disable') which loops through and disables each of frame2's children, and by changing `enable()` to essentially reverse this with def enable(childList): for child in childList: child.configure(state='enable') Furthermore, I removed `frame2.state(statespec='disabled')` as this doesn't do what I need and throws an error besides. **Here's the complete code:** from tkinter import * from tkinter import ttk def enable(childList): for child in childList: child.configure(state='enable') root = Tk() #Creates top frame frame1 = ttk.LabelFrame(root, padding=(10,10,10,10)) frame1.grid(column=0, row=0, padx=10, pady=10) button2 = ttk.Button(frame1, text="This enables bottom frame", command=lambda: enable(frame2.winfo_children())) button2.pack() #Creates bottom frame frame2 = ttk.LabelFrame(root, padding=(10,10,10,10)) frame2.grid(column=0, row=1, padx=10, pady=10) entry = ttk.Entry(frame2) entry.pack() button2 = ttk.Button(frame2, text="button") button2.pack() for child in frame2.winfo_children(): child.configure(state='disable') root.mainloop()
Removing \r\n from a Python list after importing with readlines Question: I have saved a list of ticker symbols into a text file as follows: MMM ABT ABBV ANF .... Then I use readlines to put the symbols into a Python list: stocks = open(textfile).readlines() However, when I look at the list in it contains Windows end-of-line delimiter which I do not want: list: ['MMM\r\n', 'ABT\r\n', 'ABBV\r\n', 'ANF\r\n', 'ACE\r\n', 'ACN\r\n', 'ACT\r\n', 'ADBE\r\n', 'ADT\r\n', 'AMD\r\n', 'AES\r\n', ..... Can someone suggest the easiest way to remove these unwanted characters? Answer: That's basically how `readlines` works. You could post-process it: stocks = [x.rstrip() for x in stocks] But I prefer not using `readlines` at all if I don't want EOL character(s), instead doing: stocks = open(textfile).read().splitlines() Or even better: with open(textfile) as f: stocks = f.read().splitlines() (it almost certainly won't make a difference here, but using context managers to explicitly close file objects is a good habit to get into)
TypeError: Can't convert 'int' object to str implicitly *Python* Question: For an assignment i am trying to get the results of a form "age" and to add one to that number using python. The form will have users enter their age and result should be their age next year. Here is what i have thus far: import cgi form = cgi.FieldStorage() name = str(form.getvalue("name")) age = int(form.getvalue("age")) print ("""Content-type: text/html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head> <title>Lab 9</title> </head><body> """) print ("<p>Hello," +name+ ".</p>") print ("Next year you will be" + str(age+1) + "years old") print ("</body></html>") The error i get is Traceback (most recent call last): File "/Users/JLau/Documents/CMPT 165/Lab 9/result.py", line 19, in <module> print ("Next year you will be" + str(age + 1) + "years old") TypeError: Can't convert 'int' object to str implicitly" I somehow need to convert the value of age to and "int" to which a number can be added, not sure how to do this. Answer: That can't be the code you're running. Check the following test. >>> age = 20 >>> print ("Next year you will be" + str(age+1) + "years old") Next year you will be21years old >>> age = '20' >>> print ("Next year you will be" + str(age+1) + "years old") Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> print ("Next year you will be" + str(age+1) + "years old") TypeError: Can't convert 'int' object to str implicitly You'll get this error if `age` is a string. Please add a line with print(type(age)) and look at the result.
AIFF-C file cannot be read with aifc module in python Question: I am trying to read a compressed .aiff file stored on my local directory. I get this; >>>import aifc >>>s = aifc.open('/Users/machinename/Desktop/folder/AudioTrack.aiff','r') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/aifc.py", line 942, in open return Aifc_read(f) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/aifc.py", line 347, in __init__ self.initfp(f) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/aifc.py", line 317, in initfp self._read_comm_chunk(chunk) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/aifc.py", line 497, in _read_comm_chunk raise Error, 'cannot read compressed AIFF-C files' aifc.Error: cannot read compressed AIFF-C files >>> I believe there must be a workaround for this. [Here](https://docs.python.org/2/library/aifc.html) you can see [aifc](https://docs.python.org/2/library/aifc.html) is supports aiff-c files as well. A simple question, yet I could not find a solution on the web. Answer: you might find that [scikits.audiolab](https://pypi.python.org/pypi/scikits.audiolab/) (requires mega-nerd.com/libsndfile/ is installed) does what you need. For example, I recently needed to get the duration of an .aif file (in seconds): import scikits.audiolab aiff_file = scikits.audiolab.Sndfile('best_song_ever.aif') print aiff_file.nframes / float(aiff_file.samplerate) You can do a bunch of other cool stuff too ([Full API docs](http://cournape.github.io/audiolab/fullapi.html)). I hope that helps!
python use each line in for pool probleme Question: i'm programming a script that fetch the http response and searching for 200 responses i need to make url like this : <http://exemple.com/string+number> like : <http://exemple.com/hello123> hello string is in sites.txt and some other strings , and i want to check them all with this 3 case numbers from 100 to 999 and this is the code : ok i will explain the code :) import urllib2 import string #declaring the range of my pool def my_range(start, end, step): while start <= end: yield start start += step # open the file that contains the strings s = open("sites.txt","r+") # effect a value for url url = 'http://exemple.com/' # initialize y to 100 cause i only need string+(100,999) y = 100 # for pool to read the lines line by line for line in s.readlines(): #initialize the y variable so it wont keep increasing by 1 y = 100 # effecting the line value to site so i can use it in the 2nd for pool site = line for x in my_range(100, 999, 1): url+=str(site) #increasing y by 1 to explore all the range (100,900) y =y+1 #url = url+site+y like http://exemple.com/hello123 url+=str(y) #checking wich url i reach it print url #all this to get a 200 response req = urllib2.Request(url) try: resp = urllib2.urlopen(req) except urllib2.URLError, e: if e.code == 404: pass else: pass else: print "200" #initializing the url so it wont going like this http://exemple.com/hello123hello123hello123 url = 'http://exemple.com/' body = resp.read() the problem the script get only the first string in the txt file and the file is by lines like this string1 string2 string3 string4 ... i'm a beginner with python so some explanation or rewrite on the code could be very helpful thanks for any help guys :) Answer: You make multiple requests and get a response from each, but you only `read` from the last one, because that is outside the loop.
Checking using language heuristics Question: so I'm doing some coding with python 2.7 and would like to implement language heuristics to check for certain related keywords within a text file. I'm aware of many language heuristics dictionary are coded in java and therefore would like to ask the expert opinion of the community here if there is anyway to import a java based code into python and is how do i go about doing the following paragraph below? To be clear, I have a text file which contains an article. I aim to use the program to cycle through the article, based on a keyword, to search for any related words to the keyword from the directory (java language heuristics) and to display such related words. PS: I'm new to this so please be forgiving for my ignorance. Answer: > if there is anyway to import a java based code into python The [Jython](http://www.jython.org/) implementation of Python will allow you to import Java based code. Otherwise, you can use cross-language techniques such as [XMLRPC](https://docs.python.org/2.7/library/xmlrpclib.html#module-xmlrpclib), a [REST API](http://www.restapitutorial.com/), a message queue.
python script from youtube video doesn't work Question: I am trying to learn python from this youtube video: <https://www.youtube.com/watch?v=RrPZza_vZ3w> In the video they have given the viewers a script to run: ">>> import urllib" ">>> u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22')" ">>> data = u.read()" ">>> f = open('rt22.xml','wb')" ">>> f.write(data)" ">>> f.close()" which pulls up data from a website and saves it in an xml file. But when I check the xml file I only get this: XML Parsing Error: no element found Answer: I am pretty sure this is all the code needed for the video, It might help as a reference. import urllib import webbrowser import time from xml.etree.ElementTree import parse u = urllib.urlopen("http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22") data = u.read() with open("rt22.xml", "wb") as f: f.write(data) f.close() office_lat = 41.980262 doc = parse("rt22.xml") def distance(lat1, lat2): 'Return approx miles between lat1 and lat2' return 69 * abs(lat1 - lat2) def check_bus_location(): for bus in doc.findall("bus"): if bus.findtext("lat") >= office_lat: latitude = float(bus.findtext("lat")) longitude = float(bus.findtext("lon")) bus_id = (bus.findtext("id")) direction = bus.findtext("d") north_buses = [[bus_id, latitude, longitude]] if direction.startswith("North"): print('%s %s %0.2f miles' % (bus_id, direction, distance(latitude, office_lat))) for bus in north_buses: if distance(float(latitude), office_lat) < 0.5: print(webbrowser.open( 'http://maps.googleapis.com/maps/api/staticmap?size=500x500&sensor=false&markers=|%f,%f' % ( latitude, longitude))) while True: check_bus_location() time.sleep(10)
Sublime text3 and virtualenvs Question: I'm totally new with sublime3, but i couldn't find anything helpful for my problem... I've differents virtualenvs (made with virtualenwrapper) and I'd like to be able to specify which venv to use with each project Since I'm using SublimeREPL plugin to have custom builds, how can i specify which python installation to build my project with? for example, when i work on project A i want to run scripts with venvA's python, and when i work on project B i want to run things with venvB (using a different build script) sorry my terrible english... Answer: Hopefully this is along the lines you are imagining. I attempted to simplify my solution and remove some things you likely do not need. The advantages of this method are: * Single button press to launch a SublimeREPL with correct interpreter _and_ run a file in it if desired. * After setting the interpreter, no changes or extra steps are necessary when switching between projects. * Can be easily extended to automatically pick up project specific environment variables, desired working directories, run tests, open a Django shell, etc. Let me know if you have any questions, or if I totally missed the mark on what you're looking to do. ## Set Project's Python Interpreter 1. Open our project file for editing: Project -> Edit Project 2. Add a new key to the project's settings that points to the desired virtualenv: "settings": { "python_interpreter": "/home/user/.virtualenvs/example/bin/python" } A `"python_interpreter"` project settings key is also used by plugins like [Anaconda](https://sublime.wbond.net/packages/Anaconda). ## Create plugin to grab this setting and launch a SublimeREPL 1. Browse to Sublime Text's `Packages` directory: Preferences -> Browse Packages... 2. Create a new python file for our plugin, something like: `project_venv_repls.py` 3. Copy the following python code into this new file: import sublime_plugin class ProjectVenvReplCommand(sublime_plugin.TextCommand): """ Starts a SublimeREPL, attempting to use project's specified python interpreter. """ def run(self, edit, open_file='$file'): """Called on project_venv_repl command""" cmd_list = [self.get_project_interpreter(), '-i', '-u'] if open_file: cmd_list.append(open_file) self.repl_open(cmd_list=cmd_list) def get_project_interpreter(self): """Return the project's specified python interpreter, if any""" settings = self.view.settings() return settings.get('python_interpreter', '/usr/bin/python') def repl_open(self, cmd_list): """Open a SublimeREPL using provided commands""" self.view.window().run_command( 'repl_open', { 'encoding': 'utf8', 'type': 'subprocess', 'cmd': cmd_list, 'cwd': '$file_path', 'syntax': 'Packages/Python/Python.tmLanguage' } ) ## Set Hotkeys 1. Open user keybind file: Preferences -> Key Bindings - User 2. Add a few keybinds to make use of the plugin. Some examples: // Runs currently open file in repl { "keys": ["f5"], "command": "project_venv_repl" }, // Runs repl without any file { "keys": ["f6"], "command": "project_venv_repl", "args": { "open_file": null } }, // Runs a specific file in repl, change main.py to desired file { "keys": ["f7"], "command": "project_venv_repl", "args": { "open_file": "/home/user/example/main.py" } }
igraph graph.data.frame silently converts factors to character vectors Question: Today I learned that igraph silently loses factors on graph.data.frame, so factors in the vertex data frame are converted to character vectors. Is there a way to retain the factor type e.g. for `V(g)$factor_var` and `df <- get.data.frame(g, what="vertices"); df$factor_var`? In the following code, `gender` is the `factor_var`: actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David", "Esmeralda"), age=c(48,33,45,34,21), gender=factor(c("F","M","F","M","F"))) relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"), to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE), friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3)) g <- graph.data.frame(relations, directed=TRUE, vertices=actors) g_actors <- get.data.frame(g, what="vertices") # Compare type of gender (before and after) is.factor(actors$gender) is.factor(g_actors$gender) In this reproducible example, actors$gender is a factor but g_actors$gender is not. In my opinion, it should be. I found no comment about this issue in the documentation. This is important because exporting vertices via `get.data.frame` for linear regression looses factors (linear regression converts factors to dummy variables, but ignores character vectors). I noticed because my factor variables disappeared in the output. Of course, I can recreate the factors after exporting from igraph, but this is tedious because I have a lot of graphs and the level ordering is all wrong (and I do not believe it should be necessary, unless igraph cannot support this behavior across its C++ and python versions). Ryan Answer: Yes, `graph.data.frame` has newval <- d[, i] if (class(newval) == "factor") { newval <- as.character(newval) } attrs[[names(d)[i]]] <- newval so it converts factors to characters. I am not sure why, but it has been there forever: <https://github.com/igraph/igraph/blame/c5849a89739c0dd058ff0a770aff2443745636fa/interfaces/R/igraph/R/structure.generators.R#L602> As a workaround, you can create a copy of the function, under a different name, and remove these three lines. If you think that this is a bug, then please also open an issue at <https://github.com/igraph/igraph/issues> and I'll add an option not too convert. I think the default will still be to convert, just because it has been there for a long time, and people might rely on it.
Python RaspberryPi GPIO Event Detection in Tkinter Failing Question: I'm having a strange problem detecting GPIO events on the Raspberry Pi using Python with Tkinter. Once the `startGameButton` is clicked, which calls the `start_game` function, a GPIO event is added in the `try` block, and a while loop runs for 30 seconds. During this time, I am expecting the GPIO event, `GPIO.Falling` on pin 23 to occur and each time that the event occurs, the `p2ScoreEvent` function should execute. What actually happens is the event seems to only fire the first time that it occurs, if I keep causing the `GPIO.Falling` event to occur nothing will happen until the while loop completes. Once the loop completes, if the event occured more than once it calls the `p2ScoreEvent` a second time, but that's it. Once I'm out of that while loop in `start_game` the event detection works perfectly. I've also verified that this part: try: GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) while (time.time() - start_time) < game_time print "listening" time.sleep(5) except: print "Something went wrong..." GPIO.cleanup() functions correctly at the command line when it is not part of a function. Here's the full code snippet that's giving me issues: from Tkinter import * import time import RPi.GPIO as GPIO class App: def p2ScoreEvent(self, p1pin): print "ScoreEvent" global p2score p2score = p2score + 1 p2diag.set(p2diagString + repr(p2score)) def start_game(self): global p2score start_time = time.time() game_time = 30 #length of game P1PIN = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(P1PIN, GPIO.IN) GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) try: GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) while (time.time() - start_time) < game_time print "listening" time.sleep(5) except: print "Something went wrong..." GPIO.cleanup() def __init__(self, master): frame = Frame(master) global p2diagString p2diagString = "Player 2 Score: " global p2score p2score = 0 global p2diag p2diag = StringVar() p2diag.set(p2diagString + repr(p2score)) p2Label = Label(root, fg="white", bg="blue", textvariable=p2diag).grid(row=1, column=1) self.startGameButton = Button( root, text="Start Game!", command=self.start_game ) self.startGameButton.grid(row=3, columnspan=2) root = Tk() app = App(root) root.mainloop() I'm thinking this has something to do with the function call to `start_game` but I'm not sure exactly. I don't have much python experience, so I'm having a little trouble understanding what exactly is going on. Why does the GPIO event only occur the first time it happens, and why does it then fire once and only once at the end of the while loop if it actually occurred more than 2 times? Answer: `mainloop()` do all job in program - it runs event function (and other functions) - one after the other - and it looks like multitasking. But if any of function work too long (for example it use `while True` or `time.sleep()` then `mainloop` can execute other functions. So don't use `time sleep()` and long running loop but use `root.after(time, function)` to run some function repeatedly. I can't test it but it could looks like this: def my_loop(self): if (time.time() - self.start_time) < self.game_time: print "listening" root.after(5000, self.my_loop) # run my_loop again after 5000 milliseconds def start_game(self): global p2score # use self. to get access in other function self.start_time = time.time() self.game_time = 30 #length of game P1PIN = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(P1PIN, GPIO.IN) GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) try: GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) self.my_loop() # run my_loop first time except: print "Something went wrong..." GPIO.cleanup() * * * **BTW:** you could use `self.end_time` to make less calculations def my_loop(self): if time.time() < self.end_time: print "listening" root.after(5000, self.my_loop) # run my_loop again after 5000 milliseconds def start_game(self): global p2score # use self. to get access in other function # self.game_time = 30 self.end_time = time.time() + 30 * * * **BTW:** We use `classes` and `self.` to not use `global` All code could look like this: from Tkinter import * import time import RPi.GPIO as GPIO class App(): def __init__(self, master): self.master = master self.frame = Frame(master) self.p2diagString = "Player 2 Score: " self.p2score = 0 self.p2diag = StringVar() self.p2diag.set(self.p2diagString + str(self.p2score)) p2Label = Label(self.frame, fg="white", bg="blue", textvariable=self.p2diag) p2Label.grid(row=1, column=1) self.startGameButton = Button( self.frame, text="Start Game!", command=self.start_game ) self.startGameButton.grid(row=3, columnspan=2) def p2ScoreEvent(self, p1pin): print "ScoreEvent" self.p2score += 1 self.p2diag.set(self.p2diagString + str(self.p2score)) def start_game(self): self.game_time = 30 self.end_time = time.time() + self.game_time P1PIN = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(P1PIN, GPIO.IN) GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) try: GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent) self.my_loop() except: print "Something went wrong..." GPIO.cleanup() def my_loop(self): if time.time() < self.end_time: print "listening" root.after(5000, self.my_loop) # run my_loop again after 5000 milliseconds def run(self): self.master.mainloop() #---------------------------------------------------------------------- App(Tk()).run() I put `__init__` as first function in class - it easer to read it - everybody expect `__init__` at the beginning of class. I use `str()` in place of `repl()` In class I don't use external variables. I have all variables inside.
print statement not appearing in terminal Question: I'm starting to play with scikit-learn after enjoying my AI class last semester. I have no prior experience with python (we used WEKA) so I set up python3 with a virtual env that has all the packages. I've activated the virtual env and try running the below code via `python3 <filename.py>` from sklearn import svm, datasets from numpy import genfromtxt, savetxt import sys def main(): digits = datasets.load_digits() clf = svm.SVC(gamma=0.001, C=100.) clf.fit(digits.data[:-1], digits.target[:-1]) SVC(C=100.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.001, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) print(clf.predict(digits.data[-1])) sys.stdout.flush() which prints nothing to iterm (a mac os x bash terminal). So tried running this code def main(): print("hi", end='\n', file=sys.stdout, flush=True) which also prints nothing. I've looked at the print documentation and asked a friend (who's only used 2.7) without figuring this out Answer: Does your main() function ever get called? Try adding this to the end of your module. if __name__=="__main__": main()
python: encode a url with percentage signs? Question: I am trying to convert the following url http://www.website.com/search/si/1/doctors/Vancouver, BC to http://www.website.com/search/si/1/doctors/Vancouver%2C%20BC I tried urllib.quote('http://www.website.com/search/si/1/doctors/Vancouver, BC', '') and it resulted in replacing everything with a percentage sign. What's the proper way to do this? Answer: Use [`urllib.quote()`](https://docs.python.org/2/library/urllib.html#urllib.quote) for the url `path` leaving everything else as is: from urllib import quote from urlparse import urlparse, urlunparse url = "http://www.website.com/search/si/1/doctors/Vancouver, BC" scheme, netloc, path, params, query, fragment = urlparse(url) path = quote(path) print urlunparse((scheme, netloc, path, params, query, fragment)) prints: http://www.website.com/search/si/1/doctors/Vancouver%2C%20BC See also: * [How can I normalize a URL in python](http://stackoverflow.com/questions/120951/how-can-i-normalize-a-url-in-python)
How would I handle the event of a thread finishing in python? Question: Say I am parsing data from a few different exchanges, I want each extra to run simultaneously so I start each one up in its own process, but inside each process I want to add output string to a list then return that list to the main and output it to a curses UI. Simple version: def exchange1(): #do stuff #add to output list return output_list def exchange2(): #do stuff #add to output list return output_list output_list = startnewprocess(exchange1) output_list = startnewprocess(exchange2) window.getch() #have it so I can input different options to do stuff while those threads above are running how do I make it so that when one of the processes finishes it starts back up again? OR Alternatively, how do I make it so that I can retrive what has been added to output_list within the process from the main function so that I can just have a while True: loop inside the exchange functions, so I can output the data to the screen outside of the processes? Answer: You can use `multiprocessing` to do this: import time import multiprocessing def exchange1(q): while True: time.sleep(2) q.put([1, 2, 3, 4, 5]) def exchange2(q): while True: time.sleep(4) q.put([4, 5, 6, 7, 8]) if __name__ == "__main__": q = multiprocessing.Queue() p1 = multiprocessing.Process(target=exchange1, args=(q,)) p2 = multiprocessing.Process(target=exchange2, args=(q,)) p1.start() p2.start() while True: out = q.get() print("out is {}".format(out)) Output: out is [1, 2, 3, 4, 5] out is [1, 2, 3, 4, 5] out is [4, 5, 6, 7, 8] out is [1, 2, 3, 4, 5] out is [1, 2, 3, 4, 5] out is [4, 5, 6, 7, 8] Note that if you also want to use `getch` to read characters in, you're going to have to listen for data coming back from the queue in a separate thread in the parent process, and use some thread-safe mechanism in the curses library to update the UI: def waiter(q): while True: out = q.get() print("out is {}".format(out)) # Update UI in a thread-safe way if __name__ == "__main__": q = multiprocessing.Queue() p1 = multiprocessing.Process(target=exchange1, args=(q,)) p2 = multiprocessing.Process(target=exchange2, args=(q,)) p1.start() p2.start() t = threading.Thread(target=waiter, args=(q,)) t.daemon = True t.start() while True: char = window.getch() # Other stuff
Python : How to get sum of all values until a specific key is reached in dictionary Question: I am new to python and have a doubt regarding dictionary operations. I am maintaining a dictionary as follows - dict = {counter:distance}. **For example -** dict = {1:1, 2:10, 3:27, 4:10, 5:7, 6:10} For a given key, I wish to find the total distance to reach that key. For given key=5, total distance returned should be `(1+10+27+10) = 48.` I came up with a simple solution as follows - input_key = raw_input() dist = 0 for key,value in dict: if key == input_key break else dist += value return dist I am looking for some in built function or library that I can use to achieve this. My requirement is that I am writing data to an output file. The format is as follows - docid \t termid \t number 100\t2943\t3 I have for loops which run on each docid and termid. Termid can be repeated in the loop in which case I need to modify the line in output file. Hence, if docid 100 and termid 2943 is encoutered again with number as 58, then above line needs to be changed to - 100\t2943\t3\t58 In this way same line in output file can be modified multiple times based on docid and termid. I am looking to reduce time spent in searching the '^docid\ttermid' pattern in output file and then modifying the line. Hence I plan to maintain a dictionary which should maintain offset in output file. This way I can loop over the dictionary and get offset in file, read line and modify the same. Answer: Dictionary is not an ordered mapping. You need to use other sequence data structure, or [`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) if you want mapping. And, iterating over dictionary does not yields key-value pairs, but keys. Here's a solution that use [`itertools.takewhile`](https://docs.python.org/2/library/itertools.html#itertools.takewhile): >>> import itertools >>> from collections import OrderedDict >>> >>> d = OrderedDict([(1,1), (2,10), (3,27), (4,10), (5,7), (6,10)]) >>> print sum(map(d.get, itertools.takewhile(lambda key: key != 5, d))) 48
How to generate RequestToken URL for Google API Question: I'm writing Python 2.7 desktop application which needs to access Google Spreadsheets using OAuth 2.0. I'va found a library for Google Spreadsheets for python [here](https://github.com/burnash/gspread) which uses [this](https://github.com/google/oauth2client) python OAuth2.0 library. The flow for desktop applications described [here](https://developers.google.com/accounts/docs/OAuth2#installed) tells me that I have to generate RequestToken URL first which user can use to get Authorization Code to the application. I already have Client ID and Client Secret generated in Developer's Console. But I can't figure out what class/method I can use to generate RequestToken URL in python. Should I somehow construct it myself or is there an API to do it? Answer: I've figured it out from documentation [here](https://developers.google.com/api-client- library/python/guide/aaa_oauth#step1_get_authorize_url) #!/usr/bin/env python import oauth2client from oauth2client.client import OAuth2WebServerFlow flow = OAuth2WebServerFlow(client_id='your_client_id', client_secret='your_client_secret', scope='https://spreadsheets.google.com/feeds', redirect_uri='urn:ietf:wg:oauth:2.0:oob') auth_uri = flow.step1_get_authorize_url() print auth_uri You'd need your own client_id and client_secret here though.
Why do I have to restart the tcp_server program once it receives the data? Question: I'm using a simple tcp_server in python. Here is the code:- import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() #inputs = [conn, serial_obj] outputs = [] #read_input.read_input(inputs,outputs) while 1: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) conn.close() My question is once it receives the data, the connection is dropped and I have to re-run the tcp_server program to initiate the connection. How do I keep it listening forever. Answer: You need two nested while loops. The outer loop runs forever, once per incoming connection. The inner loop runs according to the data it receives on the current connection. Try this: import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) while True: conn, addr = s.accept() #inputs = [conn, serial_obj] outputs = [] #read_input.read_input(inputs,outputs) while 1: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) conn.close()
Unable to install carbon using pip? Question: I am trying to install carbon on my local machine using pip However, seems like it does not work not sure what is wrong ? Error log attached below ? Can someone help ? Link: <http://graphite.wikidot.com/downloads> pip install carbon Error: Downloading/unpacking carbon Running setup.py (path:c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\carbon\setup.py) egg_info for package carbon package init file 'lib\twisted\plugins\__init__.py' not found (or not a regular file) warning: manifest_maker: MANIFEST.in, line 1: path 'conf/' cannot end with '/' warning: manifest_maker: MANIFEST.in, line 2: path 'distro/' cannot end with '/' warning: no previously-included files found matching 'conf\*.conf' Requirement already satisfied (use --upgrade to upgrade): twisted in c:\python27\lib\site-packages (from carbon) Downloading/unpacking txamqp (from carbon) Downloading txAMQP-0.6.2.tar.gz Running setup.py (path:c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\txamqp\setup.py) egg_info for package txamqp Downloading/unpacking zope.interface>=3.6.0 (from twisted->carbon) Running setup.py (path:c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\zope.interface\setup.py) egg_info for package zope.interface warning: no previously-included files matching '*.dll' found anywhere in distribution warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '*.pyo' found anywhere in distribution warning: no previously-included files matching '*.so' found anywhere in distribution Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python27\lib\site-packages (from zope.interface>=3.6.0->twisted->carbon) Installing collected packages: carbon, txamqp, zope.interface Running setup.py install for carbon Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\carbon\setup.py", line 44, in <module> **setup_kwargs File "C:\Python27\lib\distutils\core.py", line 151, in setup dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 971, in run_command cmd_obj.ensure_finalized() File "C:\Python27\lib\distutils\cmd.py", line 109, in ensure_finalized self.finalize_options() File "C:\Python27\lib\site-packages\setuptools\command\install.py", line 38, in finalize_options orig.install.finalize_options(self) File "C:\Python27\lib\distutils\command\install.py", line 353, in finalize_options 'userbase', 'usersite') File "C:\Python27\lib\distutils\command\install.py", line 504, in convert_paths setattr(self, attr, convert_path(getattr(self, attr))) File "C:\Python27\lib\distutils\util.py", line 124, in convert_path raise ValueError, "path '%s' cannot be absolute" % pathname ValueError: path '/opt/graphite/lib' cannot be absolute Complete output from command C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\ibm_ad~1\\appdata\\local\\temp\\pip_build_MARSHELL\\carbon\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\ibm_ad~1\appdata\local\temp\pip-ptjmmo-record\install-record.txt --single-version-externally-managed --compile: running install Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\carbon\setup.py", line 44, in <module> **setup_kwargs File "C:\Python27\lib\distutils\core.py", line 151, in setup dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 971, in run_command cmd_obj.ensure_finalized() File "C:\Python27\lib\distutils\cmd.py", line 109, in ensure_finalized self.finalize_options() File "C:\Python27\lib\site-packages\setuptools\command\install.py", line 38, in finalize_options orig.install.finalize_options(self) File "C:\Python27\lib\distutils\command\install.py", line 353, in finalize_options 'userbase', 'usersite') File "C:\Python27\lib\distutils\command\install.py", line 504, in convert_paths setattr(self, attr, convert_path(getattr(self, attr))) File "C:\Python27\lib\distutils\util.py", line 124, in convert_path raise ValueError, "path '%s' cannot be absolute" % pathname ValueError: path '/opt/graphite/lib' cannot be absolute ---------------------------------------- Cleaning up... Command C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\ibm_ad~1\\appdata\\local\\temp\\pip_build_MARSHELL\\carbon\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\ibm_ad~1\appdata\local\temp\pip-ptjmmo-record\install-record.txt --single-version-externally-managed --compile failed with error code 1 in c:\users\ibm_ad~1\appdata\local\temp\pip_build_MARSHELL\carbon Storing debug log for failure in C:\Users\IBM_ADMIN\pip\pip.log Answer: From <http://graphite.readthedocs.org/en/latest/install.html>: > Basic Graphite requirements: > > * a UNIX-like Operating System > So Windows is not supported. Try with a virtual machine.
element typemap + stl_vector.i typemap + ??? --> wrapped function taking list of elems Question: Let's say I have an arbitrary non-trivial type `A` that I can write typemaps for. In particular, let's say that I know how to convert `std::strings` into `A` and that I have typemaps from strings in the target language to `A`. I import `stl_vector.i` and `%template(AVector) std::vector<A>;`. What's the quickest/easiest (or even the 'right') course of action in SWIG to having a function wrapper of `void func(const std::vector<A>& vals)` where the expected input on the target language side is a list of strings (e.g. `['a', 'qqq']` in Python)? Unless I'm mistaken it doesn't appear to Just Work™ (specifically, nowhere in generated wrapper code have I seen the typemap code for `A`). If you _need_ a specific target language to answer, let's say it's Python. I'd rather be able to do this in the general case, though... Answer: Assuming we have a header file that looks like: #ifndef TEST_H #define TEST_H #include <iostream> #include <functional> #include <iterator> struct A { A(const std::string& v) : val(v) {} A(const A&) = default; A() = default; std::string val; }; inline std::ostream& operator<<(std::ostream& in, const A& o) { return in << o.val; } inline void run(const std::vector<A>& in) { std::copy(in.begin(), in.end(), std::ostream_iterator<A>(std::cout, "\n")); } #endif We want to wrap it such that `run` can be called with a list of strings, or a `std::vector<A>` interchangeably. Given that language agnosticism is a stated goal the best way to achieve this is by introducing a little more C++, to help with some type conversions and an overload. We can wrap the header file initially with something simple like: %module test %include <std_vector.i> %include <std_string.i> %{ #include "test.h" %} %template(AVec) std::vector<A>; %include "test.h" Which is then sufficient to run the first half of our Python test case: import test test.A("") v1=test.AVec(2,test.A("testing")) print type(v1) test.run(v1) # Here onwards needs some more work though... v2=["hello", "world", "isn't", "this", "fun"] print type(v2) test.run(v2) To start working with the second half of this test case we need to adapt the SWIG interface. I'm going to do this by adding a function, internal to the wrapper and an overload that takes advantage of SWIG's default typemaps for `std::vector<std::string>`. By adding: %{ // Some glue to trivially convert types std::vector<A> convert(const std::vector<std::string>& in) { std::vector<A> ret; std::copy(in.begin(), in.end(), std::back_inserter(ret)); return ret; } %} %inline %{ // An overload. void run(const std::vector<std::string>& in) { run(convert(in)); } %} To the end of the initial SWIG interface we've added an overload that works provided the target language has a suitable understanding of `std::vector`. (Most that I checked seem to). With the version of SWIG that I tested this with running SWIG itself with warnings turned on gave a (spurious) warning about shadowing overloads. This warning seems to be incorrect, because the code generated really did pick the correct overload, based on the argument given. Using overloads added with `%inline` in the interface file is by far the quickest/easiest way to get this up and running. It does of course require the copy/conversion overhead _and_ writing the overloads manually per function. Doing it with a typemap would only require writing a single typemap, but would be very hard to do in a way that is independent of the target language.
How to count similar domains in emails and print every domain only once[python]? Question: I have dataset of 10 hotmail emails, 4 gmails, 3 mail.com. I want to analyze list of emails and print how many of each domain(hotmail,gmail etc) is there and print out. But i do it in a very bruteforce way. I know python has elegant short code(e.g. itertools, islice, xrange) hotmail: 10 gmail: 4 mail.com: 3 but i get this: hotmail 10 hotmail 10 ... hotmail 10 gmail 4 gmail 4 gmail 4 gmail 4 etc def count_domains( emails): for email in emails: current_email = email.split("@", 2)[1] # splits at @, [email protected] => mail.com, #2nd index in the list print(current_email) current_domain_counter = 0 for email2 in emails: if current_email == email2.split("@",2)[1]: current_domain_counter = current_domain_counter + 1 #print(current_email current_domain_counter) print(current_domain_counter) Answer: You could use collections.Counter: email=['[email protected]','[email protected]',"[email protected]","[email protected]","[email protected]",'[email protected]',"[email protected]","[email protected]","[email protected]"] from collections import Counter def count_domains(emails): c = Counter() for email in emails: current_email = email.split("@", 2)[1] # splits at @, [email protected] => mail.com, c.update([current_email]) # wrap in list or will end up counting each letter #2nd index in the list print(c.most_common()) # print most common domains print ("gmail.com count = {}".format(c["gmail.com"])) print ("mail.com count = {}".format(c["mail.com"])) print ("hotmail.com count = {}".format(c["hotmail.com"])) print count_domains(email) [('hotmail.com', 4), ('gmail.com', 3), ('mail.com', 2)] gmail.com count = 3 mail.com count = 2 hotmail.com count = 4
Reading a sqlite3.Binary object with numpy.genfromtxt Question: I have a text file that containes a large string that was originally a binary blob in an SQL column. I would like to read the data using `numpy.genfromtxt` and convert the text to a 1D numpy array and then to a binary blob to be imported later into SQL using the converters parameter: np.genfromtxt(data, delimiter='\t', dtype = [ ("a", 'f8'), ("b", 'U100'), ("c", 'f8') ], converters = {1: lambda x: sqlite3.Binary( np.fromstring(x, dtype='f4', sep=' '))}) And the imput file would be something like this: 1.0\t1.0 2.0 3.0\t1.0 However this gives the error message: File "./import_sql.py", line 25, in <module> converters = {19: lambda x: sqlite3.Binary( File "/usr/lib/python3.4/site-packages/numpy/lib/npyio.py", line 1742, in genfromtxt rows = np.array(data, dtype=[('', _) for _ in dtype_flat]) ValueError: cannot set an array element with a sequence I would like to have genfromtxt return an array where the first and third columns will contain float values and the second column contains sqlite3.Binary blob of data with a 1D numpy array. This does not work so I have read the data into a large string in the output from genfromtxt and then process it before writing the data to the database. Is it possible to include a sqlite3.Binary object into a numpy array? Answer: You just have to switch the type of column `b` from type `'U100'` to `object`, then it should work.
(Python) How to make python program take a random line from a .txt file? Question: Hello i am new to python and i would like your help So i just start learning and the first thing came on my mind is Why not edit a simlpe program ! Well i want to take a line (a username) and put it in an existing code Here a part of the code def getRandomUsername(): username = 'Name_' for x in range(0,9): username = username + getRandomChar() return username I want to pull from my .txt automatically a username and replace it with the hole thing any ideas ? As i told im very new to this type of thing also sorry for my bad engls \-- Thanks Guys Answer: If your text file is not particularly large, you can read the whole thing into memory and select a random one: import random # You can do this once in your program lines = open('filename').read().splitlines() # Whenever you need a new random line, you do this randomline = random.choice(lines)
find and replace with multiple for loops in Python Question: I want to update a text file so that all consecutive capital letters have a space between them. My approach was to use two `for` loops while reading the file line by line. import sys, fileinput ActiveFileR = open('text.txt', 'r') ActiveFileW = open('textW.txt', 'w') CapAlphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] for line in ActiveFileR: for ReChr1 in CapAlphabet: for ReChr2 in CapAlphabet: ActiveFileW.write(line.replace(ReChr1 + ReChr2, ReChr1 + " " + ReChr2)) However, this resulted in 676 (26*26) lines in the output file for each line in the input file. I understand why this happened but do not know how to correct it. I want to keep looping the same line until all spaces have been added before moving on to the next line. Answer: Just modify the line in a local variable, and only write it out once: for line in ActiveFileR: newline = line for ReChr1 in CapAlphabet: for ReChr2 in CapAlphabet: newline = newline.replace(ReChr1 + ReChr2, ReChr1 + " " + ReChr2) ActiveFileW.write(newline)
An error when running an example Question: I am trying to use the `numpy.fft.fft`. When I run the example in the bottom of this page ([numpy.fft.fft](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html#numpy.fft.fft)), there is an error and the figure is weird. How to make it right? I guess the error is related with `backend_macosx.py`? The following are all of the code: >>> import matplotlib.pyplot as plt >>> import numpy as np >>> t = np.arange(256) >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag) [<matplotlib.lines.Line2D object at 0x1046c8c50>, <matplotlib.lines.Line2D object at 0x1046c8ed0>] >>> plt.show() Traceback (most recent call last): File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/figure.py", line 1034, in draw func(*args) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 2086, in draw a.draw(renderer) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 1093, in draw renderer) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/axis.py", line 1042, in _get_tick_bboxes extent = tick.label1.get_window_extent(renderer) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 754, in get_window_extent bbox, info, descent = self._get_layout(self._renderer) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/text.py", line 320, in _get_layout ismath=False) File "/Users/xujc/.Software/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 158, in get_text_width_height_descent width, height, descent = self.gc.get_text_width_height_descent(unicode(s), family, size, weight, style) TypeError: must be string, not int ![figure](http://i.stack.imgur.com/y9cC5.png) ps: $python Python 2.7.7 |Anaconda 2.0.1 (x86_64)| (default, Jun 2 2014, 12:48:16) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://binstar.org `matplotlib` version is `1.3.1`. Answer: Work fine for me, if you click the small ">>>" you will get something like this: import matplotlib.pyplot as plt import numpy as np t = np.arange(256) sp = np.fft.fft(np.sin(t)) freq = np.fft.fftfreq(t.shape[-1]) plt.plot(freq, sp.real, freq, sp.imag) plt.show() python version Python 2.7.6 (default, Jul 9 2014, 20:49:24) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. matplotlib.. matplotlib (1.3.1) So try going back to use the mac distribution of python, since changing this it creates more problems that what it could solve. I install all libraries with pip. :) Result:: ![enter image description here](http://i.stack.imgur.com/BddTU.png)
Calling a Cython Function form C Windowsx64 Question: after a long search without any results, i need some help. I'm trying to call a Cython function form C. I have the following Code: **print.pyx** cdef public int grail(int i, int a): # public function declaration return (i+a) **modul.c** #include <Python.h> #include "print.h" #include <stdio.h> void main(void) { int a; Py_Initialize(); initprint(); a = grail(2,3); printf("%i\n", a); Py_Finalize(); } I try two ways to Compile and Link it, and i always fail by linking it. First with Command Line: cython print.pyx gcc -LD:\Anaconda\libs -ID:\Anaconda\include -o print.exe print.c modul.c -lpython27 -g Second with **setup.py** from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("print", ["print.pyx", "modul.c"])] ) And then on Command Line: python setup.py build_ext --inplace In both cases i got the same error: build\temp.win32-2.7\Release\modul.o:modul.c:(.text+0x2a): undefined reference t o `__imp__grail' Here are some additional information about my system: Python 2.7.7 :: Anaconda 2.0.1 (32-bit) gcc (GCC) 4.7.0 20111219 Cython version 0.20.1 Windows 7 Enterprise x64 I hope someone know how i can solve the Problem, but already thank you very much for your help. Best regards Answer: If I were you, I'd start with CFFI instead of writing this manually: <http://eli.thegreenplace.net/2013/03/09/python-ffi-with-ctypes-and-cffi> I'm not sure how well it works on Windows, though (it worked perfectly on Linux for me). It might work since CFFI project claims this about windows: <http://cffi.readthedocs.org/en/release-0.8/#windows-64>
Python one-liner that answers: Do any of these inputs return True for this function? Question: Goal: Is there a built-in Python function (or one-liner) which will submit arguments to a function, but only until the function returns `True` for the first time? I would like to be able to answer the question > "Do _any_ of these inputs return `True` for this function?" I don't particularly care about the results of the function when using those inputs. The [`any`](https://docs.python.org/2/library/functions.html#any) function returns `True` if any of the `iterable` items passed is `True`. The [`map`](https://docs.python.org/2/library/functions.html#map) function applies arguments to a function and returns the results of all of those function calls. So I'm looking for something in between the two. `any` only applies to `iterable` so is not relevant to functions (unless I want to `map` all arguments to the function); and `map` isn't exactly what I want because it executes the function on all inputs. Answer: [`any`](https://docs.python.org/2/library/functions.html#any) is "lazy", so will `return` as soon as the first element of `iterable` evaluates to `True`. However, in Python 2.x *, `map` builds a list of the results, applying `function` to everything in `iterable` before returning. There is an alternative, though: [`itertools.imap`](https://docs.python.org/2/library/itertools.html#itertools.imap), which returns an iterator instead of a list, restoring lazy evaluation. Once you: from itertools import imap Your one-liner is: any(imap(function, iterable)) * _Note that`map` already returns an iterator [in Python 3.x](https://docs.python.org/3.4/library/functions.html#map), and therefore `itertools.imap` is no longer available._
cats() got an unexpected keyword argument 'pk' Question: I'm a amature django web developer. I have a problam with Django. this error is "cats() got an unexpected keyword argument 'pk'". please see my codes and help me. Request Method: GET Request URL: http://127.0.0.1:8000/1 Django Version: 1.6.5 Exception Type: TypeError Exception Value: cats() got an unexpected keyword argument 'pk' Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response, line 112 Python Executable: /usr/bin/python Python Version: 2.7.6 **models.py** from django.db import models from taggit.managers import TaggableManager class Category(models.Model): title = models.CharField(max_length=40) def __unicode__(self): return self.title class Post (models.Model): title = models.CharField(max_length=150) body = models.TextField() date = models.DateTimeField() tags = TaggableManager () cats = models.ManyToManyField(Category) def __unicode__ (self): return self.title **urls.py** from django.conf.urls import include, url, patterns from django.views.generic import ListView, DetailView from blog.models import Post, Category urlpatterns = patterns('blog.views', url(r'^$',ListView.as_view( queryset = Post.objects.all().order_by("-date")[:2], template_name="index.html")), url(r'^(?P<pk>\d+)$', 'cats', name='cats'), ) **views.py** from blog.models import Post,Category from django.shortcuts import render_to_response from django.template import RequestContext def cats(request): queryset = Post.objects.all().order_by("-date") navitem = Category.objects.all().order_by("title") return render_to_response('post.html',{'queryset':queryset,'navitem':navitem},context_instance=RequestContext(request)) Answer: The problem is in this line in **urls.py** : url(r'^(?P<pk>\d+)$', 'cats', name='cats') You are sending to the view an argument that it doesn't need. You can include the `pk` argument in the view parameters, like this: def cats(request, pk): or this: def cats(request, pk=None): Or, even better, you can use a different pattern in your URL, without [capturing](http://www.regular-expressions.info/named.html) it (because you are not using that `pk` value at all in your view, you don't need to create a variable for it), like this: url(r'^(\d+)$', 'cats', name='cats')
Python Thread class variable is blank Question: I've been trying to fix this issue for the past few hours, and i just can't figure out what i'm doing wrong! I have a single python file: REFRESH_RATE=10.0 MAX_SECONDS=30 class user_manager: users={} def __init__(self,queue,sign_properties): self.properties=sign_properties self.queue=queue self.lock=threading.Lock() t=threading.Thread(target=user_timer,args=(self.lock,)) t.daemon=True t.start() def add_user(self,macaddr,user_properties): self.lock.acquire() user_manager.users[macaddr]=user(user_properties) self.lock.release() def user_exists(self, macaddr): if macaddr in user_manager.users: return True return False def update_rssi_for_user(self, macaddr,rssi): self.lock.acquire() user_manager.users[macaddr].update_rssi(rssi) self.lock.release() def get_users(self): return user_manager.users def user_timer(lock): while True: print 'Test' lock.acquire() print user_manager.users lock.release() format = '%H:%M:%S' for user in user_manager.users: first_seen=user_manager.users[user].get_first_seen() current_time=str(datetime.datetime.now().time()) difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format) print 'difference'+str(difference.seconds) if difference.seconds >30: user.expire() del user_manager.users[user] time.sleep(REFRESH_RATE) The idea is that the user_manager class has a class variable called users, that is populated during runtime - this works perfectly. Then I have a threaded function called user_timer that is started from the user_manager, which manages these users and expires them after X amount of time. This is removed from the context of this post as it's not relevant. Currently, every time user_timer is called the result of `user_manager.users` is an empty dictionary `{}` but from outside of this file other modules can see the class variable as being populated. What exactly am i doing wrong, and why does it work in this fashion? James. EDIT: Calling class' constructor: class api_wrapper(object): def __init__(self,queue,display_queue,macaddr): self.properties={} self.queue=queue self.register_sign(macaddr) self.user_manager=user_manager(self.queue,self.properties) self.nearby_devices={} self.display_queue=display_queue Calling function from the above class: def handle_address(self,address,postcode): if self.user_manager is None: return if self.user_manager.user_exists(address): #print user_manager.users self.user_manager.update_address_for_user(address,postcode) #self.display_queue.put(self.user_manager.get_users()) elif macaddr not in self.nearby_devices: if self.check_address(address) is False: self.nearby_devices[address]=postcode Answer: When I add enough around your code to get it to run, it works for me at least as far as getting an `AttributeError: 'module' object has no attribute 'strptime'` where you have mixed the `datetime` module with the `datetime` class within that module. Not a lot of help I know, but I suspect the problem must lie outside the code you posted. `user_timer` sees the update to `user_manager.users` just fine: import threading import datetime REFRESH_RATE=10.0 MAX_SECONDS=30 class user: def __init__(self, properties): self.properties = properties def get_first_seen(self): return 42 class user_manager: users={} def __init__(self,queue,sign_properties): self.properties=sign_properties self.queue=queue self.lock=threading.Lock() t=threading.Thread(target=user_timer,args=(self.lock,)) t.daemon=True t.start() def add_user(self,macaddr,user_properties): self.lock.acquire() user_manager.users[macaddr]=user(user_properties) self.lock.release() def user_exists(self, macaddr): if macaddr in user_manager.users: return True return False def update_rssi_for_user(self, macaddr,rssi): self.lock.acquire() user_manager.users[macaddr].update_rssi(rssi) self.lock.release() def get_users(self): return user_manager.users def user_timer(lock): while True: print 'Test' lock.acquire() print user_manager.users lock.release() format = '%H:%M:%S' for user in user_manager.users: first_seen=user_manager.users[user].get_first_seen() current_time=str(datetime.datetime.now().time()) difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format) print 'difference'+str(difference.seconds) if difference.seconds >30: user.expire() del user_manager.users[user] time.sleep(REFRESH_RATE) u = user_manager(None, None) u.add_user("1234", "Properties") raw_input() Give me this output: C:\temp>c:\python27\python t.py Test {'1234': <__main__.user instance at 0x02583A80>} Exception in thread Thread-1: Traceback (most recent call last): File "c:\python27\lib\threading.py", line 810, in __bootstrap_inner self.run() File "c:\python27\lib\threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File "t.py", line 55, in user_timer difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format) AttributeError: 'module' object has no attribute 'strptime' Traceback (most recent call last): File "t.py", line 65, in <module> raw_input() KeyboardInterrupt
psycopg2 across python files Question: I am writing a Python application (console based) that makes use of a PostgreSQL database (via psycopg2) and R (via rpy). It is a large procedure- based application and involves several steps and sometimes repeating of steps and do not always involve all steps. I have is the following: main_file.py modules/__init__.py modules/module1.py modules/module2.py functions/__init__.py functions/function1.py functions/function2.py The init files just states import module1, module2 or function1, function2 depending which init file it is. The content of the main_file.py looks something like this: import modules from functions import function1 class myClass(): def my_function(self): scripts = [ # modules.module1.function, modules.module2.function, ] print "Welcome to the program." function1.connect() for i in scripts: i cur.close() print "End of program" if __name__ == '__main__': myClass().my_function() The reason for the loop is to comment out certain steps if I don't need them. The connect() function I'm trying to call is the psycopg2 connection. It looks like this (inside function1.py file): import sys import psycopg2 def connect(): try: con = psycopg2.connect(database=dbname, user=dbuser) cur = con.cursor() db = cur.execute except psycopg2.DatabaseError, e: if con: con.rollback() print e sys.exit In the main_file.py example I'm trying to run module2, which needs to connect to the database, using something like the following: def function: db("SELECT * INTO new_table FROM old_table") con.commit() How do I get Python (2.7) to recognise the global names db, cur and con? Thus connecting once-off to the database and keeping the active connection through all steps in the program? Answer: You should add a function to the module that initialize the DB that will return the created DB objects, and then have every module that wants to use the DB call that function: **function1.py** import sys import psycopg2 con = cur = db = None def connect(): global con, cur, db try: con = psycopg2.connect(database=dbname, user=dbuser) cur = con.cursor() db = cur.execute except psycopg2.DatabaseError, e: if con: con.rollback() print e sys.exit def get_db(): if not (con and cur and db): connect() return (con, cur, db) **function2.py** import function1 con, cur, db = function1.get_db() def function: db("SELECT * INTO new_table FROM old_table") con.commit() There's no way to make certain variables global to every single module in package. You have explicitly import them from whatever module they live in, or return them from a function call.
In python's Bokeh, how can I remove text above the plot? Question: With the following code: import bokeh.plotting as bplt bplt.output_file('output.html', mode="cdn") I get an html file with my graph(s); but it has the text: You have 1 plots Close All Plots Above the graph. Is there a way to produce html output without this text? Answer: As of Bokeh 0.5 there is a much more convenient [embed](http://bokeh.pydata.org/docs/reference.html#module-bokeh.embed) module, which should provide the functionality you desire. In your specific case, I would suggest the following setup: 1. Load BokehJS from CDN at the top of your page (or in the head) `<script src="http://cdn.pydata.org/bokeh-0.5.1.js"></script>` 2. In the Python script generating the plots, run `bokeh.embed.components(bokeh.plotting.curplot(), bokeh.resources.CDN)` for each plot. That will return a tuple with a `<script>` string containing the plot generation code, and a `<div>` string you can place anywhere on your page as a target.
ImportError: cannot import name choice when importing sklearn.mixture Question: I am using scikit learn 0.15.0. When I try to import sklearn.mixture I get ImportError: cannot import name choice Any ideas? =================================================================== In [1]: **from sklearn import mixture** ImportError Traceback (most recent call last) <ipython-input-1-05bc76cab98d> in <module>() ----> 1 from sklearn import mixture /home/f/anaconda/lib/python2.7/site-packages/sklearn/mixture/__init__.py in <module>() 3 """ 4 ----> 5 from .gmm import sample_gaussian, log_multivariate_normal_density 6 from .gmm import GMM, distribute_covar_matrix_to_match_covariance_type 7 from .gmm import _validate_covars /home/f/anaconda/lib/python2.7/site-packages/sklearn/mixture/gmm.py in <module>() 16 from ..utils import check_random_state, deprecated 17 from ..utils.extmath import logsumexp, pinvh ---> 18 from .. import cluster 19 20 from sklearn.externals.six.moves import zip /home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/__init__.py in <module>() 4 """ 5 ----> 6 from .spectral import spectral_clustering, SpectralClustering 7 from .mean_shift_ import mean_shift, MeanShift, estimate_bandwidth, \ 8 get_bin_seeds /home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/spectral.py in <module>() 16 from ..neighbors import kneighbors_graph 17 from ..manifold import spectral_embedding ---> 18 from .k_means_ import k_means 19 20 /home/f/anaconda/lib/python2.7/site-packages/sklearn/cluster/k_means_.py in <module>() 28 from ..utils import as_float_array 29 from ..utils import gen_batches ---> 30 from ..utils.random import choice 31 from ..externals.joblib import Parallel 32 from ..externals.joblib import delayed ImportError: cannot import name choice Answer: I was getting the same error when I tried to `import KMeans` as : `from sklearn.cluster import KMeans` `Error > ImportError: cannot import name choice` I found the answer here: <https://github.com/scikit-learn/scikit- learn/issues/3461> Since I have upgraded to Scikit version 0.15 a few days back, the **older version of** **random.so was present in** `/usr/local/lib/python2.7/dist- packages/sklearn/utils`. I manually deleted it and now I do not get the error anymore. Hope this helps.
Sparse matrix multiplication when results' sparsity is known (in python|scipy|cython) Question: Suppose we want to compute C=A*B for given sparse matrices A,B but are interested in a very small subset of entries of C, represented by a list of index pairs: rows=[i1, i2, i3 ... ] cols=[j1, j2, j3 ... ] Both A and B are quite large (say 50Kx50K), but very sparse (<1% of entries is non-zero). How can we compute this subset of the multiplication? Here's a naive implementation that works really slow: def naive(A, B, rows, cols): N = len(rows) vals = [] for n in xrange(N): v = A.getrow(rows[n]) * B.getcol(cols[n]) vals.append(v[0, 0]) R = sps.coo_matrix((np.array(vals), (np.array(rows), np.array(cols))), shape=(A.shape[0], B.shape[1]), dtype=np.float64) return R even for small matrices this is quite bad: import scipy.sparse as sps import numpy as np D = 1000 A = np.random.randn(D, D) A[np.abs(A) > 0.1] = 0 A = sps.csr_matrix(A) B = np.random.randn(D, D) B[np.abs(B) > 0.1] = 0 B = sps.csr_matrix(B) X = np.random.randn(D, D) X[np.abs(X) > 0.1] = 0 X[X != 0] = 1 X = sps.csr_matrix(X) rows, cols = X.nonzero() naive(A, B, rows, cols) On my machine, naive() finishes after 1 minute, and most of the effort is spent on structuring the rows/cols (in getrow(), getcol()). Of course, converting this (very small) example to dense matrices, the computation takes about 100ms: A0 = np.array(A.todense()) B0 = np.array(B.todense()) X0 = np.array(X.todense()) A0.dot(B0) * X0 Any thoughts on how to **efficiently** compute such matrix multiplication? * Note: This question is almost identical to the following question: [Subset of a matrix multiplication, fast, and sparse](http://stackoverflow.com/questions/18792096/subset-of-a-matrix-multiplication-fast-and-sparse) However, there, A and B are **full** matrices, and, one of the dimensions is very low (say, 10) the proposed solutions seem to benefit from both. Answer: The format of your sparse matrices is important here. You always need a row form A and a column from B. So, store `A` as a `csr` and `B` as `csc` to get rid of the `getrow`/`getcol` overhead. Unfortunately, this is only a small part of the story. The best solution depends a lot on the structure of your sparse matrix (a lot of sparse columns/rows, etc), but you might try one based on dictionaries and sets. For matrix `A` for each row the following are kept: * a set with all non-zero column indices on that row * a dictionary with the non-zero indices as keys and the corresponding non-zero values as values For matrix `B` similar dicts and sets are kept for each column. To calculate element (M, N) in the multiplication result, row M of `A` is multiplied with column N of `B`. The multiplication: * find the set intersection of the non-zero sets * calculate the sum of multiplications of the non-zero elements (i.e. the intersection above) In most cases this should be very fast, as in a sparse matrix the set intersection is usually very small. Some code: class rowarray(): def __init__(self, arr): self.rows = [] for row in arr: nonzeros = np.nonzero(row)[0] nzvalues = { i: row[i] for i in nonzeros } self.rows.append((set(nonzeros), nzvalues)) def __getitem__(self, key): return self.rows[key] def __len__(self): return len(self.rows) class colarray(rowarray): def __init__(self, arr): rowarray.__init__(self, arr.T) def maybe_less_naive(A, B, rows, cols): N = len(rows) vals = [] for n in xrange(N): nz1,v1 = A[rows[n]] nz2,v2 = B[cols[n]] # list of common non-zeros nz = nz1.intersection(nz2) # sum of non-zeros vals.append(sum([ v1[i]*v2[i] for i in nz])) R = sps.coo_matrix((np.array(vals), (np.array(rows), np.array(cols))), shape=(len(A), len(B)), dtype=np.float64) return R D = 1000 Ap = np.random.randn(D, D) Ap[np.abs(Ap) > 0.1] = 0 A = rowarray(Ap) Bp = np.random.randn(D, D) Bp[np.abs(Bp) > 0.1] = 0 B = colarray(Bp) X = np.random.randn(D, D) X[np.abs(X) > 0.1] = 0 X[X != 0] = 1 X = sps.csr_matrix(X) rows, cols = X.nonzero() maybe_less_naive(A, B, rows, cols) This is a bit more efficient, the multiplication takes approximately 2 seconds for the test (80 000 elements). The results seem to be essentially the same. * * * A few comments on the performance. There are two operations performed for each output element: * set intersection * multiplication The complexity of set intersection should be O(min(m,n)) where m and n are the numbers of non-zeros in each operand. This is invariant of the size of the matrix, only the average number of non-zeros per row/column is important. The number of multiplications (and dict lookups) depends on the number of non- zeros found in the intersection above. If both matrices have randomly distributed non-zeros with probability (density) p, and the row/column length is n, then: * set intersection: O(np) * dictionary lookup, multiplication: O(np^2) This shows that with really sparse matrices finding the intersections is the critical point. This can also be verified by profiling; most of the time is spent calculating the intersections. When this is reflected to the real world, we seem to spend around 20 us for a row/column of 80 non-zeros. This is not blindingly fast, and the code can certainly be made faster. Cython may be one solution, but this may be one of the problems where Python is not the best possible solution. A simple linear matching (merge sort -type algorithm) for sorted integers should be at least an order of magnitude faster when written in C. One important thing to note is that the algorithm can be done in parallel for several elements at a time. There is no need to settle for a single thread, as the calculations are independent as far as one thread handles one output point.
Python file wrapper, best design? Question: I need to parse a domain specific configuration file, but before I begin pulling the gold out of it, I want to remove the comments. Once comments are removed, I still want to be able to use things like `getline()`, `seek()` and `tell()` (the offsets in seeking due to large chunks removed is fine because all parsing is encapsulated within a single parsing object) **Inherit from`file` ?:** My first thought was to create an object like `MyFile(file)`, and override `__init__` to create a `self.content` string, then override everything with file access... but it looked far too tricky (I saw many forum posts of people having trouble trying this) **Delegate to`file` object ?:** Create a `MyFile(file)` class that creates a `file` class, and delegate calls from the `MyFile` instance to the internal `file` instance. This makes sense if the calls to `MyFile` expect a return beyond the comment find/replace search parameters... for example: `getline()` would be fine for single-line comments, but for a file where the 1st 3 lines form a single block comment, `getline()` `getline()` isn't going to work without a lot of messy code (not to mention keeping track of `seek()` offsets) **Re-create in temporary file?:** Finally, I felt like I was taking the lazy option in parsing the whole file, then re-saving it as a temporary file... then returning a file-handle to that (demo code below) import re import tempfile FILE_NAME = 'some_file.ldf' # ideal case fh = open(FILE_NAME) # my example def getHandle(self, filename, mode='r'): # ----- Remove comments ----- with open(filename, mode=mode) as fh: content = fh.read() # remove /* ... */ comment blocks content = re.sub(re.compile(r'/\*.*?\*/', re.DOTALL | re.MULTILINE), '', content, re.DOTALL | re.MULTILINE) # remove // ... line comments content = re.sub(r'//.*', '', content) # ----- Write to Temporary File ----- fh = tempfile.TemporaryFile() fh.write(content) fh.seek(0) fh = getHandle(FILE_NAME) **Better Design?:** Does anybody have a better design for this?... or even a completely different angle on this sort of problem. Answer: Honestly it sounds like your DSL parser may be the problem here. Basically if you've designed a DSL, it should include the recognition of comments and just ignore them. Taking the route of writing this as a file filter is an interesting but complex for the sake of complexity - it's just covering up for the fact that your DSL parser is incomplete. Depending on how you've written your parser this may be easy, or not so easy to fix. But, take this pyparsing example of a verilog parser. It simply has the definition of cStyleComment and tells the parser to just ignore them completely. No muss, no fuss. <http://pyparsing.wikispaces.com/file/view/verilogParse.py/241112725/verilogParse.py>
How to run an infinite loop in background and stop it? Question: Here is my problem: Using Tkinter, I want to click a button and launch a python script. This python script is now a module (I don't know if it s the best way to do it) imported to my main script. This script should be running in background. There is a method in it to quit it. How can I call it ? I wanted to pass a flag or something to the module but I don't know how to do that. For now, I call my code like that: in gui.py import sniffer_wideband_v09 from Tkinter import * root = Tk() def handle_click(): global t global stop_flag stop_flag = 0 def callback(): sniffer_wideband_v09.main(sampling_rates, center_frequencies, gains, file_dir, files_names) t = Thread(target=callback) t.start() root.mainloop() I would like to call the quitting() method in sniffer_wideband_v09.py. Or to pass a flag to my module to stop the infinite loop. Afterward, I will need to bind all of this to Tkinter Buttons. I did a bit of research on the question and found : [Is there any way to kill a Thread in Python?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a- thread-in-python) along with [How to run a function in the background of tkinter](http://stackoverflow.com/questions/5048082/how-to-run-a-function-in- the-background-of-tkinter) and [How to run and stop an infinite loop in a python thread](https://stackoverflow.com/questions/15847717/how-to-run-and- stop-an-infinite-loop-in-a-python-thread) The first is promising, but I don't fully understand it, I'm working on it. Note: I run it directly from my shell with ./gui.py and I am under Ubuntu, not windows.(I think it can change some ways of dealing with multi threading). Thanks for the reading, any hint or help will be appreciated. I will post my code if I find a response in the mean time. Edit: To give more info about the script launched in the thread : (it is a GNURadio script) class foo(): def __init__(self): self.parameters() def methods(): self.dostuff() def main(sampling_rates, center_frequencies, gains, file_dir, files_names): tb = foo() while True: #flag could be here to exit the infinite while. tb.start() tb.stop() def quitting(): tb.stop() ## not mandatory piece of code from now on if __name = "__main__": main() quitting() Answer: Since there is no interaction between your Tkinter gui application and the main code you're calling from the `sniffer_wideband_09` module I would recommend you to use multiprocessing: import sniffer_wideband_v09 import multiprocessing from Tkinter import * root = Tk() def handle_click(): global t t = multiprocessing.Process(target=sniffer_wideband_v09.main, args=(sampling_rates, center_frequencies, gains, file_dir, files_names)) t.start() root.mainloop() When you want to stop this process just call `t.terminate()`. Read more on the multiprocessing module documentation.
Easy way to send a message to an XMPP/Jabber conference room? (Shell or Python, Debian wheezy) Question: What is an easy way to send a message to a XMPP/Jabber conference room? Either at the command line (Shell), or by using Python? Ideally, all commands and/or libraries should be available in Debian wheezy (or jessie), without using pip. Answer: I had some problems in getting python-pyxmpp to work, maybe I was just to impatient. Anyway I found another solution, that worked for me, but using sleekxmpp for their website. The solution is not better (nor worse, I hope) than goncalopps, only I got it faster to work on Debian wheezy. $ sudo apt-get install python-sleekxmpp and here's the code: import optparse import sys import time import sleekxmpp class MUCBot(sleekxmpp.ClientXMPP): def __init__(self, jid, password, room, nick, message): sleekxmpp.ClientXMPP.__init__(self, jid, password) self.room = room self.nick = nick self.add_event_handler("session_start", self.start) self.message = message def start(self, event): self.getRoster() self.sendPresence() self.plugin['xep_0045'].joinMUC(self.room, self.nick, wait=True) self.send_message(mto=self.room, mbody=self.message, mtype='groupchat') time.sleep(10) self.disconnect() if __name__ == '__main__': op = optparse.OptionParser(usage='%prog [options] your message text') op.add_option("-j", "--jid", help="JID to use") op.add_option("-n", "--nick", help="MUC nickname") op.add_option("-p", "--password", help="password to use") op.add_option("-r", "--room", help="MUC room to join") opts, args = op.parse_args() if None in [opts.jid, opts.nick, opts.password, opts.room] \ or len(args) < 1: op.print_help() sys.exit(1) xmpp = MUCBot(opts.jid, opts.password, opts.room, opts.nick, " ".join(args)) xmpp.register_plugin('xep_0030') # Service Discovery xmpp.register_plugin('xep_0045') # Multi-User Chat xmpp.register_plugin('xep_0199') # XMPP Ping if xmpp.connect(): xmpp.process(threaded=False) else: print "connect() failed" Not sure, whether the plugin for `xep_0199` is really needed.
How can a file (say image) be stored inside a MongoDB collection, using command line? Question: There is option of GridFS but that requires a driver(some language). Can't we insert a file in a table and display as a field(may b the path of file)? I tried one approach using Gridfs in python. from pymongo import MongoClient import gridfs db = MongoClient().gridfs_example fs = gridfs.GridFS(db) a = fs.put("hello world") After using the last command in pymongo, a error is coming.. Answer: You can keep the path of the file stored on server in collection that is being used. As there is only 16 MB limitation to store in collection for a field. so you can store the filename/path in collection. Please correct me if i am wrong.
Python: comparing two sets and writing results to a third set Question: So this is what I have, I think what I'm looking for is pretty straight- forward. I want to be able to take the items in set c2 that are not in c1 and add those to c3. Sets c1 and c2 populate correctly. Any help is appreciated. Thanks. import csv import sys c1 = set() c2 = set() c3 = set() with open(new, 'r') as newfile: newreader = csv.reader(newfile, delimiter=('|')) for row in newreader: c1.add(row[0]) with open(new, 'r') as oldfile: oldreader = csv.reader(oldfile, delimiter=('|')) for row in oldreader: c2.add(row[0]) for item in c2: if item not in c1: c3.add(item) print(c1) print(c2) print(c3) Answer: try: c3 = c2 - c1 its that easy. Or even: c3 |= c2 - c1 if c3 already has some content. See: <https://docs.python.org/2/library/sets.html>
SUDS Exception Imported Schema Failed Question: I'm getting the error: > Exception: imported schema (<http://www.w3.org/2001/XMLSchema>) at > (<http://www.w3.org/2001/XMLSchema.x> sd), failed when passing a Doctor (constructed with _ImportDoctor_) to the **suds** _Client_ constructor. I'm working on two _Windows_ machines, both of them got the same version of **suds** installed, but only one of them rises the error above. Could someone guide me here to know why this error rises?, so I can figure out what's missing on the machine where it happens?. Thanks in advance!!!. **UPDATE** : I don't really know if this is important, but it's worth noting that my _Windows_ machine that is rising the error is an _Amazon Web Services_ instance. At my local machine everything's working well!. **UPDATE** : Here's some code I ran at the python interpreter of the machine I mentioned. Here you can detail how the error is rising... >>> from suds.client import Client >>> from suds.xsd.doctor import ImportDoctor, Import >>> missing_import = Import("http://www.w3.org/2001/XMLSchema") >>> missing_import.filter.add("http://tempuri.org/") >>> doctor = ImportDoctor(missing_import) >>> client = Client("http://etcfulfill.ebooks.com/Fulfillment.asmx?wsdl") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "suds\client.py", line 112, in __init__ self.wsdl = reader.open(url) File "suds\reader.py", line 152, in open d = self.fn(url, self.options) File "suds\wsdl.py", line 159, in __init__ self.build_schema() File "suds\wsdl.py", line 220, in build_schema self.schema = container.load(self.options) File "suds\xsd\schema.py", line 95, in load child.dereference() File "suds\xsd\schema.py", line 323, in dereference midx, deps = x.dependencies() File "suds\xsd\sxbasic.py", line 422, in dependencies raise TypeNotFound(self.ref) suds.TypeNotFound: Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )' >>> client = Client("http://etcfulfill.ebooks.com/Fulfillment.asmx?wsdl", doctor=doctor) No handlers could be found for logger "suds.xsd.sxbasic" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "suds\client.py", line 112, in __init__ self.wsdl = reader.open(url) File "suds\reader.py", line 152, in open d = self.fn(url, self.options) File "suds\wsdl.py", line 159, in __init__ self.build_schema() File "suds\wsdl.py", line 220, in build_schema self.schema = container.load(self.options) File "suds\xsd\schema.py", line 93, in load child.open_imports(options) File "suds\xsd\schema.py", line 305, in open_imports imported = imp.open(options) File "suds\xsd\sxbasic.py", line 542, in open result = self.download(options) File "suds\xsd\sxbasic.py", line 567, in download raise Exception(msg) Exception: imported schema (http://www.w3.org/2001/XMLSchema) at (http://www.w3.org/2001/XMLSchema.xsd), failed **UPDATE** : I realized that **suds** connections always open in _TCP_ increasing ports, and if it reaches the maximum _TCP_ port (65535) then it starts opening again from the minimum _TCP_ port available, so there's no problem with this. The problem shows up when using **suds** _ImportDoctor_ , because it has to open a previous connection to the location where the import should be retrieved, and for some reason, if the system reaches the maximum _TCP_ port count, then **suds** somehow assumes that there's no _TCP_ port available to open the connection for obtaining the import, and in consecuence it throws the exception: > Exception: imported schema (<http://www.w3.org/2001/XMLSchema>) at > (<http://www.w3.org/2001/XMLSchema.xsd>), failed I repeat, this only happens if **suds** has to open this previous connection for obtaining the import. If _ImportDoctor_ is not used, then **suds** has no problem if the _TCP_ port count reaches its maximum, it just restarts at the minimum port available. Does anyone has any clue on how to resolve this issue???. I'd really appreciate the help!!!. Answer: I've figured out what the problem was. The schema that was missing from the _WSDL_ I was trying to use with **suds** was: > <http://www.w3.org/2001/XMLSchema> And the _XSD_ file for this schema is at: > <http://www.w3.org/2001/XMLSchema.xsd> So when I used **suds** _ImportDoctor_ to add this schema import, sometimes the _w3.org_ domain was denying my access (don't know why really) and that's why this error was rising: > Exception: imported schema (<http://www.w3.org/2001/XMLSchema>) at > (<http://www.w3.org/2001/XMLSchema.xsd>), failed What did I do to solve this problem?. I just downloaded this schema to my machine and used **suds** _ImportDoctor_ to retrieve this import locally. And that was it!!!. Confusing bug!!!. But **SOLVED**.
Python csv.DictReader - how to reverse output? Question: I'm trying to reverse the way a file is read. I am using DictReader because I want the contents in a Dictionary. I'd like to read the first line in the file and use that for the Keys, then parse the file in reverse (bottom to top) kind of like the linux "tac" command. Is there an easy way to do this? Below is my code to read the file into a dictionary and write it to a file... reader = csv.DictReader(open(file_to_parse, 'r'), delimiter=',', quotechar='"') for line in reader: # ... This code works to process the file normally, however.. I need it to read the file from the end. In other words, I'd like it to read the file: fruit, vegetables, cars orange, carrot, ford apple, celery, chevy grape, corn, chrysler and be able to have it return: {' cars': ' chrysler', ' vegetables': ' corn', 'fruit': 'grape'} {' cars': ' chevy', ' vegetables': ' celery', 'fruit': 'apple'} {' cars': ' ford', ' vegetables': ' carrot', 'fruit': 'orange'} instead of: {' cars': ' ford', ' vegetables': ' carrot', 'fruit': 'orange'} {' cars': ' chevy', ' vegetables': ' celery', 'fruit': 'apple'} {' cars': ' chrysler', ' vegetables': ' corn', 'fruit': 'grape'} Answer: You'll have to read the _whole_ CSV file into memory; you can do so by calling `list()` on the reader object: with open(file_to_parse, 'rb') as inf: reader = csv.DictReader(inf, skipinitialspace=True) rows = list(reader) for row in reversed(rows): Note that I used the file as a context manager here to ensure that the file is closed. You also want to open the file in binary mode (leave newline handling to the `csv` module). The rest of the configuration you passed to the `DictReader()` are the defaults, so I omitted them. I set `skipinitialspace` to True, as judging from your sample input and output you do have spaces after your delimiters; the option removes these. The `csv.DictReader()` object takes care of reading that first line as the keys. Demo: >>> import csv >>> sample = '''\ ... fruit, vegetables, cars ... orange, carrot, ford ... apple, celery, chevy ... grape, corn, chrysler ... '''.splitlines() >>> reader = csv.DictReader(sample, skipinitialspace=True) >>> rows = list(reader) >>> for row in reversed(rows): ... print row ... {'cars': 'chrysler', 'vegetables': 'corn', 'fruit': 'grape'} {'cars': 'chevy', 'vegetables': 'celery', 'fruit': 'apple'} {'cars': 'ford', 'vegetables': 'carrot', 'fruit': 'orange'}
Python: Memory-Efficiency of Assigning Variables and Calling Methods Question: This has been bugging me for a while. I'm wondering about the comparative memory-efficiency of assigning variables and calling methods. Consider, for example: > s = "foo" > x = s.lower() Versus > x = "foo".lower() Which one of these is more efficient in terms of memory use? This is obviously a trivial example, but it illustrates what I'm wondering about. There are many instances in which we define some variable `var1 = foo`, and then define a second variable `var2 = var1.method()`. Does this total process require more memory than just defining `var2 = foo.method()`? Answer: The bytecode is larger in the first case, but only by a trivial amount. $ python3 Python 3.3.5 (default, Mar 9 2014, 08:10:50) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> def f(): ... s = "foo" ... x = s.lower() ... return x ... >>> def g(): ... x = "foo".lower() ... return x ... >>> dis.dis(f) 2 0 LOAD_CONST 1 ('foo') 3 STORE_FAST 0 (s) 3 6 LOAD_FAST 0 (s) 9 LOAD_ATTR 0 (lower) 12 CALL_FUNCTION 0 (0 positional, 0 keyword pair) 15 STORE_FAST 1 (x) 4 18 LOAD_FAST 1 (x) 21 RETURN_VALUE >>> dis.dis(g) 2 0 LOAD_CONST 1 ('foo') 3 LOAD_ATTR 0 (lower) 6 CALL_FUNCTION 0 (0 positional, 0 keyword pair) 9 STORE_FAST 0 (x) 3 12 LOAD_FAST 0 (x) 15 RETURN_VALUE >>> (It's sad that CPython _still_ doesn't do even basic CSE or copyprop at byte- compilation time, but that's a whole 'nother question.) The runtime memory requirement is also slightly larger in the first case, because the function has two variable slots instead of one, but the string itself is not copied an extra time. Python consistently uses reference semantics for everything. **EDIT:** as cdonts points out, if the code is more complicated and the variables don't immediately go out of scope, the first version keeps the original string alive on the heap until `s` does go out of scope, which _is_ potentially a significant extra memory cost. I hadn't even thought of that.
how to prevent failure of subprocess stopping the main process in python Question: I wrote a python script to run a command called "gtdownload" on a bunch of files with multiprocessing. The function "download" is where I am having trouble with. #/usr/bin/env python import os, sys, subprocess from multiprocessing import Pool def cghub_dnld_file(file1, file2, file3, np): <open files> <read in lines> p = Pool(int(np)) map_args = [(line.rstrip(),name_lines[i].rstrip(),bar_lines[i].rstrip()) for i, line in enumerate(id_lines)] p.map(download_wrapper,map_args) def download(id, name, bar): <check if file has been downloaded, if not download> <.....> link = "https://cghub.ucsc.edu/cghub/data/analysis/download/" + id dnld_cmd = "gtdownload -c ~/.cghub.key --max-children 4 -vv -d " + link + " > gt.out 2>gt.err" subprocess.call(dnld_cmd,shell=True) def download_wrapper(args): return download(*args) def main(): <read in arguments> <...> cghub_dnld_file(file1,file2,file3,threads) if __name__ == "__main__": main() If this file does not exist in the database, gtdownload would quit which also kills my python job with the following error: Traceback (most recent call last): File "/rsrch1/rists/djiao/bin/cghub_dnld.py", line 102, in <module> main() File "/rsrch1/rists/djiao/bin/cghub_dnld.py", line 98, in main cghub_dnld_file(file1,file2,file3,threads) File "/rsrch1/rists/djiao/bin/cghub_dnld.py", line 22, in cghub_dnld_file p.map(download_wrapper,map_args) File "/rsrch1/rists/apps/x86_64-rhel6/anaconda/lib/python2.7/multiprocessing/pool.py", line 250, in map return self.map_async(func, iterable, chunksize).get() File "/rsrch1/rists/apps/x86_64-rhel6/anaconda/lib/python2.7/multiprocessing/pool.py", line 554, in get raise self._value OSError: [Errno 2] No such file or directory The actual error message from gtdownload : Welcome to gtdownload-3.8.5a. Ready to download Communicating with GT Executive ... Headers received from the client: 'HTTP/1.1 100 Continue HTTP/1.1 404 Not Found Date: Tue, 29 Jul 2014 18:49:57 GMT Server: Apache/2.2.15 (Red Hat and CGHub) Strict-Transport-Security: max-age=31536000 X-Powered-By: PHP/5.3.3 Content-Length: 669 Connection: close Content-Type: text/xml ' Error: You have requested to download a uuid which either does not exist within the system, or has not yet reached the 'live' state. The requested action will not be performed. Please double check the supplied uuid or contact thelpdesk for further assistance. I would like the script to skip the one that does not exist and start gtdownload on the next one. I tried to output the stderr of subprocess.call to a pipe and see if there is the "error" keyword. But it seems it stops at the exact subprocess.call command. Same thing with os.system. I made a MCV case without the multiprocessing and subprocess did not kill the main process at all. Looks like multiprocessing messes things up although I had it run with 1 thread just for testing. #!/usr/bin/env python import subprocess #THis is the id that gtdownload had problem with id = "df1e073f-4485-4d5f-8659-cd8eaac17329" link = "https://cghub.ucsc.edu/cghub/data/analysis/download/" + id dlnd_cmd = "gtdownload -c ~/.cghub.key --max-children 4 -vv -d " + link + " > gt.out 2>gt.err" print dlnd_cmd subprocess.call(dlnd_cmd,shell=True) print "done" Clearly multiprocessing conflicts subprocess.call but it is not clear to me why. Answer: > What is the best way to avoid the failure of subprocess killing the main > process? Handle the exception in some appropriate way and move on, of course. try: subprocess.call(dlnd_cmd) except OSError as e: print 'failed to download: {!r}'.format(e) However, this may not be appropriate here. The kinds of exceptions that `subprocess.call` raises are usually not transient things that you can just log and work around; if it's not working now, it will continue to not work forever until you fix the underlying problem (a bug in your script, or `gtdownload` not being installed right, or whatever). For example, if the code you showed us is your actual code: dlnd_cmd = "gtdownload -c ~/.cghub.key --max-children 4 -vv -d " + link + " > gt.out 2>gt.err" subprocess.call(dlnd_cmd) … then this is guaranteed to raise an `OSError` for the reason explained in dano's answer: `call` (without `shell=True`) will try to take that entire string—spaces, shell-redirection, etc.—as the name of an executable program to find on your `$PATH`. And there is no such program. So it will raise an `OSError(errno.ENOENT)`. (Which is exactly what you're seeing.) Just logging that doesn't do you any good; it's a good thing that your entire process is exiting, so you can debug that problem.
Python re regex matching issue Question: Ok please be gentle - this is my first stackoverflow question and I've struggled with this for a few hours. I'm sure the answer is something obvious, staring me in the face but I give up. I'm trying to grab an element from a webpage (ie determine gender of a name) from a name website. The python code I've written is here: import re import urllib2 response=urllib2.urlopen("http://www.behindthename.com/name/janet") html=response.read() print html patterns = ['Masculine','Feminine'] for pattern in patterns: print "Looking for %s in %s<<<" % (pattern,html) if re.findall(pattern,html): print "Found a match!" exit else: print "No match!" When I dump html I see Feminine there, but the re.findall isn't matching. What in the world am I doing wrong? Answer: [Do not parse an HTML with regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags- except-xhtml-self-contained-tags), use a specialized tool - an HTML parser. Example using [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/): from urllib2 import urlopen from bs4 import BeautifulSoup url = 'http://www.behindthename.com/name/janet' soup = BeautifulSoup(urlopen(url)) print soup.select('div.nameinfo span.info')[0].text # prints "Feminine" * * * Or, you can [find an element by text](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-text- argument): gender = soup.find(text='Feminine') And then, see if it is `None` (not found) or not: `gender is None`.
How to print é as '%C3%A9' in Python 2.7 Question: I want to convert '**é** ' to **%C3%A9** for URI request. My code is like this: import urllib actor = "Bonnie Erbé" I know that I can manually covert it by print urllib.quote(u"Bonnie Erbé".encode("utf-8")). However, I want to use the variable **actor**. When I try print urllib.quote(actor) It prints `'Bonnie%20Erb%E9'` not `'Bonnie%20Erb%C3%A9'`. Thank you. Answer: Make your program look like this: # encoding: utf-8 import urllib actor = u"Bonnie Erbé" print urllib.quote(u"Bonnie Erbé".encode("utf-8")) print urllib.quote(actor.encode('utf-8')) Notice: 1) An `encoding: utf-8` line that says you'll have non-ASCII characters in your text file. 2) Assigning a unicode string, not a plain string, to the `actor` variable. 3) Encoding `actor` just the same as you encoded the literal string.
How to use Python to extract data from the Met Office JSON download Question: I am using Python 3.4. I have started a project to download the UK Met Office Forecast data (in JSON format) and use the information as a weather compensator for my home heating system. I have succeeded in downloading the JSON datafile from the MET Office, and now I want to extract the info I need. I can do this by converting the file to a string and using `.find` and `.int` methods to extract the data, but this seems crude (but effective). As JSON is said to be a well-used data interchange format, there must be a better way to do this. I have found things like `json.load` and `json.loads`, and also `json.JSONDecoder.decode` but I haven't had any success in using these, and I really have little idea of what I am doing! My code is: import urllib.request import json #Comment: THIS IS THE CALL TO GET THE MET OFFICE FILE FROM THE INTERNET #Comment: **** = my personal met office API key, which I had better keep to myself response = urllib.request.urlopen('http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/354037?res=3hourly&key=****') FCData = response.read() FCDataStr = str(FCData) #Comment: END OF THE CALL TO GET MET OFFICE FILE FROM THE INTERNET #Comment: Example of data extraction ChPos = FCDataStr.find('"DV"') #Find "DV" ChPos = FCDataStr.find('"dataDate"', ChPos, ChPos+50) #Find "dataDate" FileDataDate = FCDataStr[ChPos+12:ChPos+22] #Extract the date of the file #Comment: And so on When using `json.loads(FCDataStr)` I get the following error message: > "ValueError: Expecting value: line 1 column 1 (char 0)" By deleting the b' at the start and the ' at the end, this error goes away (see below). Printing the JSON file in string format, using `print(FCDataStr)` gives: b'{"SiteRep":{"Wx":{"Param":[{"name":"F","units":"C","$":"Feels Like Temperature"},{"name":"G","units":"mph","$":"Wind Gust"},{"name":"H","units":"%","$":"Screen Relative Humidity"},{"name":"T","units":"C","$":"Temperature"},{"name":"V","units":"","$":"Visibility"},{"name":"D","units":"compass","$":"Wind Direction"},{"name":"S","units":"mph","$":"Wind Speed"},{"name":"U","units":"","$":"Max UV Index"},{"name":"W","units":"","$":"Weather Type"},{"name":"Pp","units":"%","$":"Precipitation Probability"}]},"DV":{"dataDate":"2014-07-29T20:00:00Z","type":"Forecast","Location":{"i":"354037","lat":"51.7049","lon":"-2.9022","name":"USK","country":"WALES","continent":"EUROPE","elevation":"43.0","Period":[{"type":"Day","value":"2014-07-29Z","Rep":[{"D":"NNW","F":"22","G":"11","H":"51","Pp":"4","S":"9","T":"24","V":"VG","W":"7","U":"7","$":"900"},{"D":"NW","F":"19","G":"16","H":"61","Pp":"8","S":"11","T":"22","V":"EX","W":"8","U":"1","$":"1080"},{"D":"NW","F":"16","G":"20","H":"70","Pp":"1","S":"11","T":"18","V":"VG","W":"2","U":"0","$":"1260"}]},{"type":"Day","value":"2014-07-30Z","Rep":[{"D":"NW","F":"13","G":"16","H":"84","Pp":"0","S":"7","T":"14","V":"VG","W":"0","U":"0","$":"0"},{"D":"WNW","F":"12","G":"13","H":"90","Pp":"0","S":"7","T":"13","V":"VG","W":"0","U":"0","$":"180"},{"D":"WNW","F":"13","G":"11","H":"87","Pp":"0","S":"7","T":"14","V":"GO","W":"1","U":"1","$":"360"},{"D":"SW","F":"18","G":"9","H":"67","Pp":"0","S":"4","T":"19","V":"VG","W":"1","U":"2","$":"540"},{"D":"WNW","F":"21","G":"13","H":"56","Pp":"0","S":"9","T":"22","V":"VG","W":"3","U":"6","$":"720"},{"D":"W","F":"21","G":"20","H":"55","Pp":"0","S":"11","T":"23","V":"VG","W":"3","U":"6","$":"900"},{"D":"W","F":"18","G":"22","H":"57","Pp":"0","S":"11","T":"21","V":"VG","W":"1","U":"2","$":"1080"},{"D":"WSW","F":"16","G":"13","H":"80","Pp":"0","S":"7","T":"16","V":"VG","W":"0","U":"0","$":"1260"}]},{"type":"Day","value":"2014-07-31Z","Rep":[{"D":"SW","F":"14","G":"11","H":"91","Pp":"0","S":"4","T":"15","V":"GO","W":"0","U":"0","$":"0"},{"D":"SW","F":"14","G":"11","H":"92","Pp":"0","S":"4","T":"14","V":"GO","W":"0","U":"0","$":"180"},{"D":"SW","F":"15","G":"11","H":"89","Pp":"3","S":"7","T":"16","V":"GO","W":"3","U":"1","$":"360"},{"D":"WSW","F":"17","G":"20","H":"79","Pp":"28","S":"11","T":"18","V":"GO","W":"3","U":"2","$":"540"},{"D":"WSW","F":"18","G":"22","H":"72","Pp":"34","S":"11","T":"20","V":"GO","W":"10","U":"5","$":"720"},{"D":"WSW","F":"18","G":"22","H":"66","Pp":"13","S":"11","T":"20","V":"VG","W":"7","U":"5","$":"900"},{"D":"WSW","F":"17","G":"22","H":"69","Pp":"36","S":"11","T":"19","V":"VG","W":"10","U":"2","$":"1080"},{"D":"WSW","F":"16","G":"16","H":"84","Pp":"6","S":"9","T":"17","V":"GO","W":"2","U":"0","$":"1260"}]},{"type":"Day","value":"2014-08-01Z","Rep":[{"D":"SW","F":"16","G":"13","H":"91","Pp":"4","S":"7","T":"16","V":"GO","W":"7","U":"0","$":"0"},{"D":"SW","F":"15","G":"11","H":"93","Pp":"5","S":"7","T":"16","V":"GO","W":"7","U":"0","$":"180"},{"D":"SSW","F":"15","G":"11","H":"93","Pp":"7","S":"7","T":"16","V":"GO","W":"7","U":"1","$":"360"},{"D":"SSW","F":"17","G":"18","H":"79","Pp":"14","S":"9","T":"18","V":"GO","W":"7","U":"2","$":"540"},{"D":"SSW","F":"17","G":"22","H":"74","Pp":"43","S":"11","T":"19","V":"GO","W":"10","U":"5","$":"720"},{"D":"SW","F":"16","G":"22","H":"81","Pp":"48","S":"11","T":"18","V":"GO","W":"10","U":"5","$":"900"},{"D":"SW","F":"16","G":"18","H":"80","Pp":"55","S":"9","T":"17","V":"GO","W":"12","U":"1","$":"1080"},{"D":"SSW","F":"15","G":"16","H":"89","Pp":"38","S":"7","T":"16","V":"GO","W":"9","U":"0","$":"1260"}]},{"type":"Day","value":"2014-08-02Z","Rep":[{"D":"S","F":"14","G":"11","H":"94","Pp":"15","S":"7","T":"15","V":"GO","W":"7","U":"0","$":"0"},{"D":"SSE","F":"14","G":"11","H":"94","Pp":"16","S":"7","T":"15","V":"GO","W":"7","U":"0","$":"180"},{"D":"S","F":"14","G":"13","H":"93","Pp":"36","S":"7","T":"15","V":"GO","W":"10","U":"1","$":"360"},{"D":"S","F":"15","G":"20","H":"84","Pp":"62","S":"11","T":"17","V":"GO","W":"14","U":"2","$":"540"},{"D":"SSW","F":"16","G":"22","H":"78","Pp":"63","S":"11","T":"18","V":"GO","W":"14","U":"5","$":"720"},{"D":"WSW","F":"16","G":"27","H":"66","Pp":"59","S":"13","T":"19","V":"VG","W":"14","U":"5","$":"900"},{"D":"WSW","F":"15","G":"25","H":"68","Pp":"39","S":"13","T":"18","V":"VG","W":"10","U":"2","$":"1080"},{"D":"SW","F":"14","G":"16","H":"80","Pp":"28","S":"9","T":"15","V":"VG","W":"0","U":"0","$":"1260"}]}]}}}}' The result of using: DecodedJSON = json.loads(FCDataStr) print(DecodedJSON) gives a very similar result to the original FCDataStr file. How do I proceed to extract the data (such as temperature, wind speed etc for each 3 hourly forecast) from the file? Answer: For other clueless people who may want to use the UK Met Office 3-hourly forecast data feed, below is the solution that I am using: import urllib.request import json ### THIS IS THE CALL TO GET THE MET OFFICE FILE FROM THE INTERNET response = urllib.request.urlopen('http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/**YourLocationID**?res=3hourly&key=**your_api_key**') FCData = response.read() FCDataStr = FCData.decode('utf-8') ### END OF THE CALL TO GET MET OFFICE FILE FROM THE INTERNET #Converts JSON data to a dictionary object FCData_Dic = json.loads(FCDataStr) #The following are examples of extracting data from the dictionary object. #The JSON data is heavily nested. #Each [] goes one level down, usually defined with {} in the JSON data. dataDate = (FCData_Dic['SiteRep']['DV']['dataDate']) print('dataDate =',dataDate) #There are also [] in the JSON data, which are referenced with integers, # starting from [0] #Here, the [0] refers to the first day's block of data defined with []. DateDay0 = (FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['value']) print('DateDay0 =',DateDay0) #The second [0] picks out each of the first day's forecast data, in this case the time, referenced by '$' TimeOfFC = (FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['$']) print('TimeOfFC =',TimeOfFC) #Ditto for the temperature. Temperature = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['T'])) print('Temperature =',Temperature) #Ditto for the weather Type (a code number). WeatherType = int((FCData_Dic['SiteRep']['DV']['Location']['Period'][0]['Rep'][0]['W'])) print('WeatherType =',WeatherType) I hope this helps somebody!
External Module causes os.path.isfile to return incorrect answer Question: I am running Python 2.7 under Windows7 on an iMAC (using BOOTCAMP) and have encountered a strange problem or bug. Here is my problem script boiled down to essentials: import arcpy import arcpy.mapping as mapping import os for fileName in os.listdir("TestDir"): fullPath = os.path.join("TestDir", fileName) #hexpath=':'.join(x.encode('hex') for x in fullPath) #print hexpath if os.path.isfile(fullPath): print fullPath + " is a file" desc = arcpy.Describe(fullPath) if(desc.datatype == "MapDocument"): #mxd = mapping.MapDocument(fullPath) #del mxd print "MAP FILE: " + fileName else: print fullPath + " is not a file" When the line "mxd=" is commented I get the correct output TestDir\A_layer.lyr is a file TestDir\Mapfile1.mxd is a file MAP FILE: Mapfile1.mxd TestDir\Z_file is a file When the line is uncommented I get: TestDir\A_layer.lyr is a file TestDir\Mapfile1.mxd is a file MAP FILE: Mapfile1.mxd TestDir\Z_file is not a file The last line printed differs and is WRONG. (I get the correct behavior again if I uncomment the "del mxd" line). Without getting into details about what the external module does, or simply dismissing the module as buggy, my question is: **What possible bug or type of bug in the mapping.MapDocument method could possibly lead to such a behavior? How can a bug in a user written module affect so profoundly the output of a built-in library?** Unfortunately the source of the arcpy module is not available to me. It is vendor proprietary. The vendor asserts that in their testing the bug cannot be reproduced with very similar test case on the same platform and Python version. Answer: The problem is apparently that the `mapping.MapDocument` constructor changes the current working directory. This means that you're not looking for `TestDir\Z_File` under the original working directory, you're looking for it under a different directory, and there is no such file, and `isfile` returns False for no such file, not just for being a directory or other non-file thing. The best workaround is probably to [`abspath`](https://docs.python.org/2/library/os.path.html#os.path.abspath) all of your paths before ever constructing a `MapDocument`.
Ports with python sockets, are they random? Question: I am trying to learn python sockets, but am becoming very confused by the results of the example code from the website ([found here](http://www.tutorialspoint.com/python/python_networking.htm)). The only modification I have made is replacing `socket.gethostname()` in the server with the local IP of my server, to allow me to run this on two computers. When I connect, attempting to connect on port 12345 as in the example, I get this output: `Got connection from ('10.0.1.10', 37492)` This leads me to believe that it is connecting on port 37492. I would like it to connect on the port I tell it to, so I can port forward. Am I misunderstanding, or is there an extra command to specify it. Edit: I am uploading my code: Client.py #!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.connect(("10.0.1.42", port)) print s.recv(1024) s.close # Close the socket when done Server.py import socket s = socket.socket() # Create a socket object host = "10.0.1.42" # Get local machine name port = 12345 # Reserve a port for your service. s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection. while True: c, addr = s.accept() # Establish connection with client. print 'Got connection from', addr c.send('Thank you for connecting') c.close() # Close the connection Answer: You have reached that point in your networking life where you need to understand protocol multiplexing. Good for you. Think of the TCP/IP stack. An application communicates with a remote application by passing application-layer data to the transport (end-to-end) layer, which passes it to the network layer (internetwork layer) which tries, without guarantees, to have packets reach the IP destination host over a sequence of hops determined by cooperating routers that dynamically update their routing tables by talking to connected routers. Each router conversation goes over a physical transport of some kind (ISDN, Ethernet, PPP - in TCP/IP the task of creating packets and transmitting the appropriate bit stream is regarded as a single "subnetwork" layer, but this is ultimately split into two when differentiation is required between the OSI physical layer (Layer 1) and the data link layer (layer 2) for protocols like DHCP. When TCP and UDP were designed, the designers imagined that each server would listen on a specific port. This typically has the inherent limitation that the port can only handle one version of your service protocol (though protocols like HTTP take care to be backwards-compatible so that old servers/clients can generally interoperate with newer ones). There is often a service called portmapper running on port 111 that allows servers to register the port number they are running on, and clients to query the registered servers by service (program) number and protocol version. This is a part of the Sun-designed RPC protocols, intended to expand the range of listening ports beyond just those that were pre-allocated by standards. Since the preallocated ports were numbered from 1 to 1023, and since those ports typically (on a sensible operating system) require a high level of privilege, RPC also enabled non- privileged server processes as well as allowing a server to be responsive to multiple versions of network application protocols such as NFS. However the server side works, the fact remains that there has to be some way for the network layer to decide which TCP connection (or UDP listener) to deliver a specific packet to. Similarly for the transport layer (I'll just consider TCP here since it's connection-oriented - UDP is similar, but doesn't mind losing packets). Suppose I'm a server and I get two connections from two different client processes on the same machine. The destination (IP address, port number) will be the same if the clients are using the same version of the same protocol, or if the service only listens on a single port. The server's network layer looks at the incoming IP datagram and sees that it's addressed to a specific server port. So it hands it off to that port in the transport layer (the layer above the network layer). The server, being a popular destination, may have several connections from different different client processes on the same machine. This is where the magic of ephemeral ports appears. When the client requests a port to use to connect to a service, the TCP layer _guarantees_ that no other process on that machine (technically, that interface, since different interfaces have unique IP addresses, but that's a detail) will be allocated the same port number while the client process continues to use it. So protocol multiplexing and demultiplexing relies on five pieces of information: (sender IP, sender port, protocol, receiver IP, receiver port) The protocol is a field in the IP header as are the source and destination IP addresses. The sending and receiving port numbers are in the transport layer segment header. When an incoming packet arrives, the guaranteed uniqueness of different ephemeral ports from the same client (endpoint) allows the transport layer to differentiate between different connections to the same server IP address _from_ the same client IP address and port (the worst case for demultiplexing) by their source IP address and port. The (transport) protocol is included to ensure that TCP and UDP traffic don't get mixed up. The TCP/UDP constraints on uniqueness of ephemeral ports guarantee that any server can only receive one connection from a specific combination of `(IP address, port number)` and it's that that allows connections from the same machine to be demultiplexed into separate streams corresponding to the different origins. In Python when you connect a socket to a remote endpoint the `socket.accept()` call returns the (IP address, port number) pair for the remote endpoint. You can use that to discover who is communicating with you, but if you just want to talk back you can simply `write()` the socket.
Implementing a "screen" command for windows machine using python Question: So I am trying to do following: 1. I have _Cygwin_ enabled with _screen_ and _ssh daemon_ in _Windows 7_. 2. I create a new screen using the command `screen -dmS "my_screen"` on my _Windows_ machine. 3. I _ssh_ to the _Windows_ machine from my _Linux_ machine. 4. I attach to it from my unix machine using `screen -d -r my_screen` 5. Now I try to launch a _Windows_ application, for example _notepad.exe_. Now I want to a automate this using _Python._ The objective is to just manually _ssh_ to _Windows_ and then run a _Python_ script which will do the above steps. I have written the following script but it is not working: import shlex import os import time import subprocess cmdString = "screen -d -r default_screen" cmdArgs=shlex.split(cmdString) p=subprocess.Popen(cmdArgs) cmds = "./notepad.exe" cArgs=shlex.split(cmds) pp=subprocess.Popen(cArgs) This is not working. :( Basically to get the screen I will probably need to import pty package or tty. But pty & tty are not supported in _Windows_. I am able to attach to the newly created screen but then attempt to launch the _Windows_ program like _notepad_ for example fails. It hangs and the windows GUI is not launched as it would when down manually. I am still exploring this but I will appreciate it if someone can point me to the right way to do it. Answer: I put the screen command in the bash profile script of cygwin user. This is working now.
Python: convert JSON to XML Question: Are you aware of any good Python `JSON <-> XML` parser that could do the following: Use the following JSON: var json = { "root_element_name" : { "attr1" : "value", "attr2" : "value", "elements": { "element_name1" : "value", "element_name2" : "value" } } } and convert to the following XML & vice versa: <root_element_name attr1="value" attr2="value" > <option name="element_name1" value="value"/> <option name="element_name2" value="value"/> </root_element_name> Any suggestions much appreciated. Answer: Python a allows you to convert from JSON into a native dict (using json or, in versions < 2.6, simplejson) You can do this with the help of a library <https://github.com/quandyfactory/dict2xml> Or you can do this by loading it into `json.loads`.For the more explaiantion of this method please have a look [here](http://stackoverflow.com/questions/1019895/serialize-python-dictionary- to-xml) A sample for converting to xml >>> import xmltools >>> d = {'a':1, 'b':2.2, 'c':'three' } >>> xx = xmltools.WriteToXMLString(d) >>> print xx The result <?xml version="1.0" encoding="UTF-8"?> <top> <a>1</a> <b>2.2</b> <c>three</c> </top>
Recursion depth exceeded Question: I have a problem with my ship generation in the Battleship game! Sometimes when I run the code I get the error: RuntimeError: maximum recursion depth exceeded while calling a Python object Here is the code, I give you all if it can help. The problem is in the "pick" function print "Welcome to Battleships!!!" board = [] import os from random import randint for x in range(10): board.append(["O"] * 10) def print_board(board): for row in board: print " | ".join(row) ships = {"battleship" : [5], "cruiser1" : [4], "cruiser2" : [4], "frigate1" : [3], "frigate2" : [3], "frigate3" : [3], "frigate4" : [3], "minesweeper1" : [2], "minesweeper2" : [2], "minesweeper3" : [2], "minesweeper4" : [2]} numbers1 = [] numbers2 = [] numbers = [] def setup_nums1(): for count1 in range(6): for count2 in range(10): number1 = (count1)*100 number2 = count2 numbers1.append(number1 + number2) def setup_nums2(): for count1 in range(10): for count2 in range(6): number1 = (count1)*100 number2 = count2 numbers2.append(number1 + number2) def setup_nums(): for count1 in range(10): for count2 in range(10): number1 = (count1)*100 number2 = count2 numbers.append(number1 + number2) def pick1(info, ship): random = numbers1[randint (0,len(numbers1) - 1)] if not info[0] + random in numbers: pick1(info, ship) elif not info[0] + random - 1 in numbers: pick1(info, ship) elif not random + 1 in numbers: pick1(info, ship) elif not random + 2 in numbers: pick1(info, ship) elif not random in numbers: pick1(info, ship) else: ships[ship].append(random) y = info[1] print y numbers1.remove(y) if y in numbers2: numbers2.remove(y) numbers.remove(y) for n in range(info[0] - 1): ships[ship].append(y + n + 1) if (y + n + 1) in numbers1: numbers1.remove(y + n + 1) if (y + n + 1) in numbers2: numbers2.remove(y + n + 1) numbers.remove(y + n + 1) def pick2(info, ship): random = numbers2[randint (0,len(numbers2) - 1)] if not info[0]*100 + random in numbers: pick2(info, ship) elif not info[0]*100 + random - 100 in numbers: pick2(info, ship) elif not random + 100 in numbers: pick2(info, ship) elif not random + 200 in numbers: pick2(info, ship) elif not random in numbers: pick2(info, ship) else: ships[ship].append(random) y = info[1] print y if y in numbers1: numbers1.remove(y) if y in numbers2: numbers2.remove(y) numbers.remove(y) for n in range(info[0] - 1): ships[ship].append(y + n*100 + 100) if (y + n*100 + 100) in numbers1: numbers1.remove(y + n*100 + 100) if (y + n*100 + 100) in numbers2: numbers2.remove(y + n*100 + 100) numbers.remove(y + n*100 + 100) def setup_numbers(): setup_nums() setup_nums1() setup_nums2() def setup_ships(): for ship, info in ships.items(): direction = randint(1,2) if direction == 1: pick1(info, ship) elif direction == 2: pick2(info, ship) setup_numbers() setup_ships() print numbers1 print numbers2 print ships Could anyone help me with this? Answer: Change recursion to loop. Here is little bit changed pick1 function: from collections import deque def need_to_process_now(info, ship): random = numbers1[randint (0,len(numbers1) - 1)] if not info[0] + random in numbers: return (random, False) elif not info[0] + random - 1 in numbers: return (random, False) elif not random + 1 in numbers: return (random, False) elif not random + 2 in numbers: return (random, False) elif not random in numbers: return (random, False) return (random, True) def pick1(info, ship): infos = deque() infos.append((info, ship)) while len(infos) > 0: curr = infos.pop() res = need_to_process_now(curr[0], curr[1]) if not res[1]: infos.append(curr) else: ships[ship].append(res[0]) y = curr[0][1] print y numbers1.remove(y) if y in numbers2: numbers2.remove(y) numbers.remove(y) for n in range(info[0] - 1): ships[ship].append(y + n + 1) if (y + n + 1) in numbers1: numbers1.remove(y + n + 1) if (y + n + 1) in numbers2: numbers2.remove(y + n + 1) numbers.remove(y + n + 1) P.S. I think you need to little reformat code, it's not easy read your code.
rounding up time in python error Question: I get the following error when trying to round up time, AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' fajr_jamaat1 printout is 1900-01-01 04:25:00 Please help? from datetime import datetime, timedelta def round_up(tm): upmins = math.ceil(float(tm.minute)/10)*10 diffmins = upmins - tm.minute newtime = tm + datetime.timedelta(minutes=diffmins) newtime = newtime.replace(second=0) return newtime cnx = mysql.connector.connect(host=mysql_remote_host, user=mysql_remote_host_user, password=mysql_remote_host_password, database=mysql_remote_host_database) cursor = cnx.cursor() cursor.execute("select * from paramatta_prayertimes WHERE id =1") results = cursor.fetchall() id, date, fajr_begins, fajr_jamaat, sunrise, zuhr_begins, zuhr_jamaat, asr_begins, asr_jamaat, maghrib_jamaat, isha_begins, isha_jamaat = results[0] cursor.close() print fajr_begins fajr_jamaat1=(timedelta(minutes=20) + datetime.strptime(str(fajr_begins), "%H:%M:%S")) print fajr_jamaat1 round_up(fajr_jamaat1) Answer: Since you imported your functions as from datetime import datetime, timedelta You do not need to call the function as datetime.timedelta You simply call the function by its name timedelta If you prefer to use the former syntax, just import the module itself import datetime Then you can say datetime.datetime datetime.timedelta
Django + wsgi = Forbidden 403 Question: So 403 error is here. My 000-default.conf from /etc/apache2/sites-available/: <VirtualHost talkrecorder.ru:80> ServerName talkrecorder.ru ServerAlias www.talkrecorder.ru ServerAdmin [email protected] DocumentRoot /srv/www/sampleapp/ WSGIScriptAlias / /srv/www/sampleapp/sampleapp/wsgi.py <Directory /srv/www/sampleapp> Order allow,deny Allow from all </Directory> </VirtualHost> My wsgi.py from srv/sampleapp/sampleapp: import os import sys sys.path.append('/srv/www/sampleapp/sampleapp') os.environ['PYTHON_EGG_CACHE'] = '/srv/www/sampleapp/.python-egg' os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() settings.py here: <http://pastebin.sabayon.org/pastie/16969> Answer: In your settings.py, your allowed hosts are empty. You should complete as following : ALLOWED_HOSTS = ['www.talkrecorder.ru', 'talkrecorder.ru'] #Or any other host that you need