input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Decorator class decorating a class method I have got a decorator that I have implemented as a class: ````class Cached(object): def __init__(self func): self cache = None self func = func def __call__(self *args **kwargs): if self cache is None or (time time() - self cache[0] >= 1000): res = self f(*args **kwargs) self cache = (time time() res) else: res = self cache[1] return res ```` I want to use this decorator to decorate a method of a class e g : ````class Foo(object): def __init__(self x): self x = x @cached def bar(self y): return self x y ```` As it stands ````f = Foo(10) f bar(11) ```` throws `TypeError: foo() takes exactly 2 arguments (1 given)` `f bar(f 11)` works but is the code smell equivalent of summer in New York City during a sanitation worker strike What am I missing? ETA: Originally I was trying to implement Cached as a function: ````def cached(cache): def w1(func): def w2(*args **kwargs): # same return w2 return w1 ```` but I kept getting weird scoping errors about `cache` being used before it is defined which switching to a decorator class fixed | You need to add this to your decorator class: ````def __get__(self obj objtype): """support instance methods""" from functools import partial return partial(self __call__ obj) ```` |
Iteratively count elements in list and store count in dictionary I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network For each node my code returns me a list `b` containing integer values giving me the path length for every possible connection I want to count the number of occurences of given path lengths so I can create a histogram ````local_path_length_hist = {} for ver in vertices: dist = gt shortest_distance(g source=g vertex(ver)) a = dist a #Delete some erroneous entries b = a[a!=2147483647] for dist in b: if dist in local_path_length_hist: local_path_length_hist[dist]+=1 else: local_path_length_hist[dist]=1 ```` This presumably is very crude coding as far as the dictionary update is concerned Is there a better way of doing this? What is the most efficient way of creating this histogram? | The check that element exists in `dict` is not really necessary You can just use `collections defaultdict` Its initialization accepts callable object (like function) that will be called if you want to access (or assign something to) element that does not exist to generate the value (i e function that generates default value) For your case it can be just `int` I e ````import collections local_path_length_hist = collections defaultdict(int) # you could say collections defaultdict(lambda : 0) instead for ver in vertices: dist = gt shortest_distance(g source=g vertex(ver)) a = dist a #Delete some erroneous entries b = a[a!=2147483647] for dist in b: local_path_length_hist[dist] = 1 ```` You could turn the last two lines in one like that but there is really no point |
Matching a string to a regular expression I would like to check if a string matches part of a family of strings described by a regular expression The desired behavior would be something like: ````>>> re findall("hi" "h[ia]t") ["hi"] >>> re findall("at" "h[ia]t") ["at"] >>> re findall("hat" "h[ia]t") ["hat"] >>> re findall("cat" "h[ia]t") [] ```` but the second argument to re findall() is interpreted literally Of course in the simple example above I could explicitly check against both "hit" and "hat" but for more complicated expressions that seems unwieldy | Regular expressions are not generators You can match a string versus a regex but you cannot construct all strings that match a given regular expression You probably need she will-like brace expansion but I do not think something like that is provided in the stdlib (`fnmatch` is close but offers only matching) |
How many doctors visited Chopin? | 3 |
manipulating and searching within large files in python I apologize if this question has been answered already but I cannot seem to find a page that describes this process What I am trying to do is to take a large file (The new york times corpus) change it to a list of words using the split function and then search through that long list for certain words I have been able to get python to print the file with this code ````words=open('nyt txt') for line in words: print (line) ```` but I would like to be able to use words split() on this function afterward So far I have been developing the program using a small corpus that I just type in like this ````words= ('A B C D E F G A B C D E F G A B C D E F G A B C D E F G') ```` but rather than copying and pasting the nyt into the parentheses (this does not work the file is too large) I would rather have it source the file into the variable name Once again I am sorry if this has been asked and answered before as is likely | Take a look at `nltk` It is a huge project and it has tools for working with corpora The project is written in Python and available at <a href="http://www nltk org/" rel="nofollow">http://www nltk org/</a> |
How to handle TCP connection events in order to call methods within other class? I am creating a robot which is going to be driven by the commands received over TCP connection Therefore I will have a robot class with methods (e g sense() drive() ) and the class for TCP connection To establish TCP connection I looked at examples from twisted On the client side I have written a client py script for connection handling: ````from twisted internet import reactor protocol import random from eventhook import EventHook import common #from Common socketdataobjects import response # a client protocol class EchoClient(protocol Protocol): """Once connected send a message then print the result """ def connectionMade(self): self transport write("hello world!") #the server should be notified that the connection to the robot has been established #along with robot state (position) #eventConnectionEstablishedHook fire() def dataReceived(self data): print "Server said:" data self transport write("Hello %s" % str(random randint(1 10))) ''' serverMessage = common deserializeJson(data) command = serverMessage command arguments = serverMessage arguments #here we get for example command = "DRIVE" #arguments = {motor1Speed: 50 motor2Speed: 40} instead of above response used for testing purposes the commands should be extracted from the data and according to the command the method in Robot instance should be called When the command execution finishes the self transport write() method should be called to notify the server that the command execution finished ''' def connectionLost(self reason): print "connection lost" class EchoFactory(protocol ClientFactory): protocol = EchoClient def clientConnectionFailed(self connector reason): print "Connection failed - goodbye!" reactor stop() def clientConnectionLost(self connector reason): print "Connection lost - goodbye!" reactor stop() # this connects the protocol to a server runing on port 8000 def initializeEventHandlers(connectionEstablishedHook): global connection connection established = 0 global eventConnectionEstablishedHook eventConnectionEstablishedHook = connectionEstablishedHook def main(): f = EchoFactory() reactor connectTCP("localhost" 8000 f) reactor run() # this only runs if the module was *not* imported if __name__ == '__main__': main() ```` Beside this script I have a robot class: ````Class Robot(object(): def __init(self)__: self position = (0 0) def drive(self speedMotor1 speedMotor2 driveTime) updateMotor1State(speedMotor1) updateMotor2State(speedMotor2) time sleep(driveTime) #when the execution finished the finish status should be sent to client in order to inform the server return "Finished" def sense(self) #logic to get the data from the environment ```` What I would like to do is to receive the data(commands) from TCP connection and then call the according method in Robot instance Some procedures might take longer (e g driving) so I tried to use events but have not figured out the appropriate way to communicate between TCP client and robot using events: ````if __name__ == '__main__': robotController = Robot() eventController = Controller() connectionEstablishedHook = EventHook() client initializeEventHandlers(connectionEstablishedHook) eventController connection = connectionEstablishedHook client main() ```` I tried to create ClientMainProgram script where I wanted to create an instance of a robot an instance of TCP client and implement the communication between them using events Previously I have managed to implement event handling using <a href="http://www voidspace org uk/python/weblog/arch_d7_2007_02_03 shtml#e616" rel="nofollow">Michael Foord's events pattern</a> on a simpler example I would be very thankful if anyone could provide the solution to this question or any similar example which might be helpful to solve this problem | Events are easily represented using regular Python function calls For example if your protocol looks like this: ````from twisted internet protocol import Protocol class RobotController(Protocol): def __init__(self robot): self robot = robot def dataReceived(self data): for byte in data: self commandReceived(byte) def commandReceived(self command): if command == "\x00": # drive: self robot drive() elif command == "\x01": # sense: self robot sense() ```` (The specifics of the protocol used in this example are somewhat incidental I picked this protocol because it is very simple and has almost no parsing logic For your real application I suggest you use `twisted protocols amp` ) Then all you need to do is make sure the `robot` attribute is properly initialized You can do this easily using the somewhat newer endpoint APIs that can often replace use of factories: ````from sys import argv from twisted internet endpoints import clientFromString connectProtocol from twisted internet task import react def main(reactor description): robot = endpoint = clientFromString(reactor description) connecting = connectProtocol(endpoint RobotController(robot)) def connected(controller): connecting addCallback(connected) return connecting react(main argv[1:]) ```` |
Special use of args / kwargs I need to do something like this: ````def func1(a *args b="BBB" **kwargs): print "a=%s b=%s args=%s kwargs=%s" % (a b args kwargs) ```` So that calling like this: ````func1("AAAA" h="HHH" j="JJJ") ```` Produces the output: ````a=AAAA b=BBB args=() kwargs={'h': 'HHH' 'j': 'JJJ'} ```` But it is not possible to put a default named argument after `*args` (`SyntaxError: invalid syntax`) - Why is this not allowed? - Is there any readable way to implement this? The only way I know is `b=kwargs pop("b" "BBB")` but this is not very readable I would prefer to have this in the function call definition where it belongs: it is a parameter which will <them>always</them> have a value either a default value or a user-given value <h1>EDIT</h1> I could put `b` in front of `args`: ````def func1(a b="BBB" *args **kwargs): print "a=%s b=%s args=%s kwargs=%s" % (a b args kwargs) ```` But that would mean that this call: ````func1("AAAA" "CCC" h="HHH" j="JJJ") ```` Assigns `"CCC"` to `b` which I do not want I want `b` to be a named arg not a possitional arg | That is perfectly valid in Python 3 (<a href="http://liveworkspace org/code/gHHOt%244" rel="nofollow">demonstration</a>); <a href="http://www python org/dev/peps/pep-3102/" rel="nofollow">PEP 3102</a> introduced <strong>keyword-only arguments</strong> In Python 2 x you will have to continue using `kwargs pop` or an appropriate decorator: - <a href="http://code activestate com/recipes/577940-emulate-keyword-only-arguments-in-python-2/" rel="nofollow">http://code activestate com/recipes/577940-emulate-keyword-only-arguments-in-python-2/</a> - <a href="https://pypi python org/pypi/kwonly" rel="nofollow">https://pypi python org/pypi/kwonly</a> |
How many 3 star Michelin restaurants were in France in 2015? | 29 |
How to keep a number below n I have a python program that outputs a list of coordinates that correspond to points in a survey To keep this simple I am trying to make any coordinate above n (36) display something like: `1 8+36` which is 37 8 however `1x1 8` (same number) could also work or any similar permutation the coordinates are in lists (one for x and one for y) I currently use an if statement but that obviously only works for numbers less than 72 | As long as your values remain below 1296 (36*36) you can divide your number by 36 and represent it as this number into 36 ````input_1 = 105 output_1 = (105 * 1 0) / 36 # 2 197 print '36*' output_1 # 36*2 197 ```` |
How to enforce ealry-binding with cx_freeze and win32com? I made some python scripts to control an external CATIA application I now have to package those scripts into executable files but i cannot manage to do it <h2>Question :</h2> <them>How to enforce win32com to use early binding for specific modules once scripts are built ?</them> <hr> <h2>Details :</h2> My scripts controls a CATIA application using <strong>win32com client</strong> module I handle CATIA with late binding except the module <them>CATIA V5 SpaceAnalysisInterfaces Object Library</them> that contains functions with reference input/output arguments For this one i use early binding sadly the simple use of <strong>MakePy</strong> was not enought i had to modify generated sources from the <strong>win32com gen_py</strong> package to obtain a correct behavior from the input/output arguments Now it works fine when i execute python scripts But if i build them using either <strong>py2exe</strong> or <strong>cx_freeze</strong> the executable uses only late-binding so i get bad results Here is the way that i hook CATIA application and use its API : <pre class="lang-py prettyprint-override">`import win32com client buff = [0 0 0] catApp = win32com client GetActiveObject("CATIA Application") # Late bind needed doc = catApp Documents Open(path) part = doc Part # This property fails if using early binding spa = doc GetWorkbench(you"SPAWorkbench") I = spa Inertias Add(part) # Early bind needed cogCoords = I GetCOGPosition(buff) # The damn input/ouput argument function ```` And here is my build script using <strong>cx_freeze</strong> : <pre class="lang-py prettyprint-override">`from cx_Freeze import setup Executable options = { "includes": [] "excludes": [] "packages": ["win32com gen_py"] } target = Executable( script = "test py" base = "Console" compress = True icon = None ) setup( name = "Test" version = "1 0" description = "Early Binding Test Built" author = "C LECLERC" options = {"build_exe": options} executables = [target] ) ```` This build script generate a bunch of files including the content of my actual <strong>win32com gen_py</strong> module so it should works But when i execute the file it uses only late binding I could not check if the files are correctly added when i use <strong>py2exe</strong> but the behavior is exactly the same : <strong>late bind !</strong> <hr> I took a look at <a href="http://stackoverflow com/questions/19662605/python-win32com-and-cx-freeze-error">this post</a> but my problem is different Modules are correctly copied and scripts does not raise exceptions The input/output functions just does not works correctly Any help would be appreciated | I answer my own question to share the solution i found and flag the problem as resolved <h2>Solution :</h2> Just copy the <them>'dicts dat'</them> file from the <strong>win32com gen_py</strong> package to the equivalent folder of the <them>'library zip'</them> archive generated by cx_freeze |
Sqlalchemy raw query and parameters I am trying to perform raw sql query using sqlalchemy and wondering what is a 'proper' way to do it My query looks as follows (for now): ````db my_session execute( """UPDATE client SET musicVol = {} messageVol = {}""" format( music_volume message_volume)) ```` What I do not like is string formatting and lack of any parameter handling (hello to quotation marks in music_volume :-D) I tried to follow this answer: <a href="http://stackoverflow com/questions/17972020/how-to-execute-raw-sql-in-sqlalchemy-flask-app#answer-18808942">How to execute raw SQL in SQLAlchemy-flask app</a> And after applying what I read my snippet looks as follows: ````db my_session execute( "UPDATE client SET musicVol = :mv messageVol = :ml" mv=music_volume ml=message_volume) ```` However I am getting error that mv and ml is not recognized parameter If I change my snippet into this it works: ````db my_session execute( "UPDATE client SET musicVol = :mv messageVol = :ml" {mv: music_volume ml: message_volume}) ```` Lastly my_session is initiated like that in a file called db py: ````engi = sqlalchemy create_engine( 'mysql://{user}:{passwd}@{host}/{db}' format( host=settings HOST user=settings USER passwd=settings PASS db=settings DB_NAME) execution_options={ 'autocommit': True }) my_session = sqlalchemy orm scoped_session(sqlalchemy orm sessionmaker(bind=engi) scopefunc=os getpid) sqlalchemy orm scoped_session configure(my_session autocommit=True) ```` What I would like to know is why answer linked above and this part of documentation: <a href="http://docs sqlalchemy org/en/rel_0_9/core/tutorial html#using-text" rel="nofollow">http://docs sqlalchemy org/en/rel_0_9/core/tutorial html#using-text</a> Are showing slightly different solution to what actually is working for me Also if my approach is one to go | Both `mv` and `ml` will not be recognized since you have not defined them as variables The second argument of `execute` statement is a dictionary and all the elements of your plain query `"UPDATE client SET musicVol = :mv messageVol = :ml"` escaped with a colon are being searched for in this dictionary's keys The `execute` method did not found a key `'mv'` nor `'ml'` in this dictionary therefore an error is raised This is the correct version: `db my_session execute( "UPDATE client SET musicVol = :mv messageVol = :ml" {'mv': music_volume 'ml': message_volume} )` |
Django: Access given field's choices tuple I would like to get the named values of a choices field for a choice that is not currently selected Is this possible? For instance: models py ````FILE_STATUS_CHOICES = ( ('P' 'Pending') ('A' 'Approved') ('R' 'Rejected') ) class File(models Model): status = models CharField(max_length=1 default='P' choices=FILE_STATUS_CHOICES) ```` views py ````f = File() f status = 'P' f save() old_value = f status print f get_status_display() > Pending f status = 'A' f save() new_value = f status print f get_status_display() > Approved ```` How can I get the old display value from the 'P' to 'Pending?' I may be able to do so by creating a form in the view and accessing its dictionary of values/labels Is this the best/only approach? | This is pretty much ok to import your choice mapping `FILE_STATUS_CHOICES` from models and use it to get `Pending` by `P`: ````from my_app models import FILE_STATUS_CHOICES print dict(FILE_STATUS_CHOICES) get('P') ```` `get_FIELD_display()` method on your model is doing essentially the same thing: ````def _get_FIELD_display(self field): value = getattr(self field attname) return force_text(dict(field flatchoices) get(value value) strings_only=True) ```` And since there is a `flatchoices` field on the model field you can use it with the help of `_meta` and `get_field_by_name()` method: ````choices = f _meta get_field_by_name('name')[0] flatchoices print dict(choices) get('P') ```` where `f` is your model instance Also see: - <a href="http://stackoverflow com/questions/15984130/django-get-display-name-choices">Django get display name choices</a> |
Worker always offline in Celery flower I have `Celery` and <a href="https://github com/mher/flower#celery-flower" rel="nofollow">Flower</a> running on my server and the tasks run just fine and are correctly registered and updated for me to monitor within the Flower UI however the worker status is allways `Offline` no matter if I restart the workers or Flower itself and my log file (as given by the `--log_file_prefix` option) is empty so no errors nothing The only thing I can see is that the chrome dev tools show a Websocket Handshake error as shown below: <img src="http://i stack imgur com/hoVB1 png" alt="flower error in chrome dev tools"> and a message `CAUTION: Provitional headers are shown ` <img src="http://i stack imgur com/sAbkk png" alt="enter image description here"> I read that I need to make my server to respond with the `Upgrade: websocket` and `Connection: upgrade` headers for the Websocket handshake to be successful I am using apache then I tried so by specifying the following in `/etc/apache2/sites-enabled/mysite conf`: ````Header set Upgrade "websocket" Header set Connection "upgrade" ```` but it did not work Does anyone have a clue on this error? Let me know if you need any more info Thanks!! | Gerard check the kombu version I solved a similar problem upgrading kombu to version 3 0 21 (rel 2014-07-07) pip install kombu==3 0 21 I am not sure it solves your problem but give it a try |
Python calling a module I Am trying to call module but some reason its giving me error The data py contains a list of items and in the main py I Am trying to iterate and print over the items but I get the below error Error ````Import error: No module named Basics ```` Both data py & main py are located in c:/python27/basics/ data py ````bob={'name':'bobs mith' 'age':42 'salary':5000 'job':'software'} sue={'name':'sue more' 'age':30 'salary':3000 'job':'hardware'} people=[bob sue] ```` main py ````from Basics import data if __name__ == '__main__': for key in people: print(key '=>\n ' people[key]) ```` If I just give import data then I get the below error Name error:name 'people' is not defined <strong>Update:</strong> New code: ````from Basics import data if __name__ == '__main__': for key in data people: print(key '=>\n ' data people[key]) ```` TypeError:list indices must be integers not dict | You will need `__init__ py` in your Basics directory And you will need to have that directory in your `PYTHON_PATH` or `sys path` To use people you need to do either of these ````from Basics data import people ```` Or ````from Basics import data print data people ```` |
Close server socket on quit/crash I am learning how to use sockets in python and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port This obviously stops the program from listening on that port when it starts back up again so I have to keep changing it I am guessing I need to do socket close() somewhere but where? | Terminating a program makes all its sockets automatically close However the TCP ports are still kept in use after that The <a href="http://www faqs org/faqs/unix-faq/socket/" rel="nofollow">UNIX socket FAQ</a> has a really long explanation in section 2 7 For testing purposes it may be best to ask for an arbitrary port (or ask for successive ones like 8000 8001 8002 ) and output that port in the console |
Broken Pandas Installation I am having problems importing pandas but do not know what enough about the error message to fix it How can I get my pandas installation working again? I am using Anacondas And run it in the py33 environment rather than the default 2 x environment I have tried pip install --upgrade pandas But it has not helped ````In [17]: import pandas as pd DLL load failed: The specified module could not be found --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-17-af55e7023913> in <module>() ---> 1 import pandas as pd C:\Anaconda\envs\py33\lib\site-packages\pandas\__init__ py in <module>() 4 5 try: ---> 6 from import hashtable tslib lib 7 except Exception: # pragma: no cover 8 import sys ImportError: DLL load failed: The specified module could not be found In [18]: ```` | I found the fix: ````sudo easy_install -YOU pandas ```` it was here: <a href="http://stackoverflow com/questions/17759128/python-pandas-stuck-at-version-0-7-0">Python pandas stuck at version 0 7 0</a> |
What is the coloring of the northeast subspecies of cheetah? | null |
Scale Resolution in Pyglet I am using the pyglet (OpenGL) library and I want to be able to change the virtual resolution without changing the size of the window For example a 2x2 box would be drawn as 4x4 pixels on the screen I know I can find everything that is being draw and scale it individually but this would probably be costly I could not find a solution for this online (if it even exists) so any help would be greatly appreciated Clarification: I am thinking along the lines of the resolution settings in most games The window stays in full screen at the same size but the scale changes | <blockquote> Clarification: I am thinking along the lines of the resolution settings in most games The window stays in full screen at the same size but the scale changes </blockquote> No the window <them>does</them> change the size because the screen resolution is changed and the window follows However what you intend to do it perfectly possible: First render your image to a FBO of the desired smaller size then render the contents of that FBO covering the full window In the case a 3D engine uses some form of post processing (like for depth of field color grading compositing effects) this comes virtually for free |
Spark using PySpark read images Hi there I have a lot of images (lower millions) that I need to do classification on I am using Spark and managed to read in all the images in the format of `(filename1 content1) (filename2 content2) ` into a big RDD ````images = sc wholeTextFiles("hdfs:///user/myuser/images/image/00*") ```` However I got really confused what to do with the unicode representation of the image Here is an example of one image/file: ````(you'hdfs://NameService/user/myuser/images/image/00product jpg' you'\ufffd\ufffd\ufffd\ufffd\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\ufffd\ufffd\x01\x1eExif\x00\x00II*\x00\x08\x00\x00\x00\x08\x00\x12\x01\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x1a\x01\x05\x00\x01\x00\x00\x00n\x00\x00\x00\x1b\x01\x05\x00\x01\x00\x00\x00v\x00\x00\x00(\x01\x03\x00\x01\x00\x00\x00\x02\x00\x00\x001\x01\x02\x00\x0b\x00\x00\x00~\x00\x00\x002\x01\x02\x00\x14\x00\x00\x00\ufffd\x00\x00\x00\x13\x02\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00i\ufffd\x04\x00\x01\x00\x00\x00\ufffd\x00\x00\x00\x00\x00\x00\x00`\x00\x00\x00\x01\x00\x00\x00`\x00\x00\x00\x01\x00\x00\x00GIMP 2 8 2\x00\x002013:07:29 10:41:35\x00\x07\x00\x00\ufffd\x07\x00\x04\x00\x00\x000220\ufffd\ufffd\x02\x00\x04\x00\x00\x00407\x00\x00\ufffd\x07\x00\x04\x00\x00\x000100\x01\ufffd\x03\x00\x01\x00\x00\x00\ufffd\ufffd\x00\x00\x02\ufffd\x04\x00\x01\x00\x00\x00\x04\x04\x00\x00\x03\ufffd\x04\x00\x01\x00\x00\x00X\x01\x00\x00\x05\ufffd\x04\x00\x01\x00\x00\x00\ufffd\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01\x00\x02\x00\x04\x00\x00\x00R98\x00\x02\x00\x07\x00\x04\x00\x00\x000100\x00\x00\x00\x00\ufffd\ufffd\x04_http://ns adobe com/xap/1 0/\x00<?xpacket begin=\'\ufeff\' id=\'W5M0MpCehiHzreSzNTczkc9d\'?>\n<x:xmpmeta xmlns:x=\'adobe:ns:meta/\'>\n<rdf:RDF xmlns:rdf=\'http://www w3 org/1999/02/22-rdf-syntax-ns#\'>\n\n <rdf:Description xmlns:exif=\'http://ns adobe com/exif/1 0/\'>\n <exif:Orientation>Top-left</exif:Orientation>\n <exif:XResolution>96</exif:XResolution>\n <exif:YResolution>96</exif:YResolution>\n <exif:ResolutionUnit>Inch</exif:ResolutionUnit>\n <exif:Software>ACD Systems Digital Imaging</exif:Software>\n <exif:DateTime>2013:07:29 10:37:00</exif:DateTime>\n <exif:YCbCrPositioning>Centered</exif:YCbCrPositioning>\n <exif:ExifVersion>Exif Version 2 2</exif:ExifVersion>\n <exif:SubsecTime>407</exif:SubsecTime>\n <exif:FlashPixVersion>FlashPix Version 1 0</exif:FlashPixVersion>\n <exif:ColorSpace>Uncalibrated</exif:ColorSpace>\n ```` Looking closer there are actually some characters look like the metadata like ```` <x:xmpmeta xmlns:x=\'adobe:ns:meta/\'>\n<rdf:RDF xmlns:rdf=\'http://www w3 org/1999/02/22-rdf-syntax-ns#\'>\n\n <rdf:Description xmlns:exif=\'http://ns adobe com/exif/1 0/\'>\n <exif:Orientation>Top-left</exif:Orientation>\n <exif:XResolution>96</exif:XResolution>\n <exif:YResolution>96</exif:YResolution>\n ```` My previous experience was using the package scipy and related functions like 'imread' and the input is usually a filename Now I really got lost what does those unicode mean and what I can do to transform it into a format that I am familiar with Can anyone share with me how can I read in those unicode into a scipy image (ndarray)? | Your data looks like the raw bytes from a real image file (JPG?) The problem with your data is that it should be bytes not unicode You have to figure out how to convert from unicode to bytes There is a whole can of worms full of encoding traps you have to deal with but you may be lucky using `img encode('iso-8859-1')` I do not know and I will not deal with that in my answer The raw data for a PNG image looks like this: ````rawdata = '\x89PNG\r\n\x1a\n\x00\x00 \x00\x00IEND\xaeB`\x82' ```` Once you have it in bytes you can create a PIL image from the raw data and read it as a nparray: ````>>> from StringIO import StringIO >>> from PIL import Image >>> import numpy as np >>> np asarray(Image open(StringIO(rawdata))) array([[[255 255 255 0] [255 255 255 0] [255 255 255 0] [255 255 255 0] [255 255 255 0] [255 255 255 0]]] dtype=uint8) ```` All you need to make it work on Spark is `SparkContext binaryFiles`: ````>>> images = sc binaryFiles("path/to/images/") >>> image_to_array = lambda rawdata: np asarray(Image open(StringIO(rawdata))) >>> images values() map(image_to_array) ```` |
Stopping unnecessary posts to PHP file <img src="http://i stack imgur com/4WbSK png" alt="enter image description here"> Above you can see Google's account registration page telling me that a username is already taken Firstly this is how I assume it is informing me: - Upon the text input losing focus an AJAX call is made to a file somewhere within Google's web server - The server (running Python I believe?) processes the username and performs a check against a database via a query - Once the database has performed the query the result is returned to the server - Then it is returned to the browser where it is made pretty and informs me of the result in a way that is useful to the user <strong>My question</strong> is to do with where the processing occurs Wherever the processing is happening it is purely serving a purpose for this page I as any person should not be able to find this file where Google perform this check and post data to it and see a response I want to find out what is stopping me how are Google preventing me from making a check manually against this Python file that is making the check? Or are they at all? Currently I am using PHP to do the exact same thing as Google are doing here The PHP file that is being invoked via AJAX is in the same directory as the registration it is called "check php" If you were to post a username to that file on my web server you would see the response and this is what I need to stop (or should I just not be stopping it?) How can this be done? Thanks | If I understand you correctly you are trying to determine whether or not a request is via ajax and if not block the request You have several options for this (will have missed some out): - Attach a 'session_id' to the form and validate it on the 'check php' page If it is valid then proceed - Look for the AJAX request header (example below) <strong><them>This is not necessarily reliable as headers can be manipulated</them></strong> - Manipulate the header yourself using jQuery `ajax` and then test for it on 'check php' Example of option 2: ````if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){ // I am AJAX! } ```` You have other options as well but this should be a good start |
Sorting a txt file by name in python I have a huge blast output file in tabular format I want to sort my data according to protein names to see which seq-s align to that particular protein Let us say I have ````con19 sp|Q24K02|IDE_BOVIN 3 con19 sp|P35559|IDE_RAT 2 con15 sp|Q24K02|IDE_BOVIN 8 con15 sp|P14735|IDE_HUMAN 30 con16 sp|Q24K02|IDE_BOVIN 45 con16 sp|P35559|IDE_RAT 23 ```` I want to get an output both are OK ````sp|Q24K02|IDE_BOVIN con19 3 sp|Q24K02|IDE_BOVIN con19 3 con15 8 sp|Q24K02|IDE_BOVIN con15 8 con16 45 sp|Q24K02|IDE_BOVIN con16 45 sp|P35559|IDE_RAT con19 2 sp|P35559|IDE_RAT con19 2 con16 23 sp|P35559|IDE_RAT con16 23 sp|P14735|IDE_HUMAN con15 30 sp|P14735|IDE_HUMAN con15 30 f1 = open('file txt' 'r') lines=f1 readlines() for line in lines: a=sorted(lines) r=open('file txt' 'w') r writelines(a) f1 close ```` | You need to sort on the middle element just sorting the lines themselves will do an alphabetical sort i e on the first element Try this instead: ````with open('infile txt') as f_in open('outfile txt' 'w') as f_out: f_out write('' join(sorted(f_in key=lambda x: x split()[1:2]))) ```` |
In CST, what triggers a destructive immune response? | "nonself" entities (e.g., pathogens, an allograft) |
How does ply lex extract the regular expression from each token definition function? I was really surprised by the fact that the token function definitions for ply lex just contain the regex's floating there without actually being returned as a return value or anything Here is an example: ```` def t_INITIAL_TOKENNAME(token): r"[h]+" return token ```` I wanted to understand how this actually works so I started looking at lex py Here is some of the source code of ply lex taken from lex py of ply3 4: ````# Build the master regular expressions for state in stateinfo: regex_list = [] # Add rules defined by functions first for fname f in linfo funcsym[state]: line = func_code(f) co_firstlineno file = func_code(f) co_filename regex_list append("(?P<%s>%s)" % (fname f __doc__)) if debug: debuglog info("lex: Adding rule %s > '%s' (state '%s')" fname f __doc__ state) # Now add all of the simple rules for name r in linfo strsym[state]: regex_list append("(?P<%s>%s)" % (name r)) if debug: debuglog info("lex: Adding rule %s > '%s' (state '%s')" name are state) regexs[state] = regex_list ```` What exactly is going on in the following line? It seems like the crucial line where lex is extracting the regex from each token definition but I do not know what it is doing ```` regex_list append("(?P<%s>%s)" % (fname f __doc__)) ```` I kind of see the fprintf formatting going on here but I do not see how the "(?P<%s>%s)" contains the regex of interest when the %s's are replaced with fname and f <strong>doc</strong> | When you define a function (or class or module) in Python if the first thing is a string it becomes the `__doc__` attribute of the thing: ````>>> def f(a b): """Adds a and b """ return a+b >>> f __doc__ 'Adds a and b ' ```` ply lex uses this feature of Python You define the regex pattern (which is really just a string) as the first thing in the body of the function and it is accessible as the `__doc__` attribute of the function |
Bluemix Python Flask app passing list parameter to template using list append() I am passing a list of strings from my flask app to the html template which works perfectly fine until I attempt to append the list I have tested my usage of the append method using a client-side python script and it is working I am perplexed as to why my appending of the list causes an internal server error Here is the section of my template which uses the parameters ````<ul> {% for file in files %} <li>{{ file }}</li> {% endfor %} </ul> ```` And here is the route in my flask app ````@app route('/') def main(): FILES = [ 'test1' 'test2' ] # Iterate through each file in the cloud storage container for container in conn get_account()[1]: for data in conn get_container(container['name'])[1]: print 'object: {0}t size: {1}t date: {2}' format(data['name'] data['bytes'] data['last_modified']) FILES append('test3') return render_template('index html' files = FILES) ```` The line FILES append('test3') is causing the problem but I am not sure why When I comment this line out the list is passed to the template as you would expect Here is the full traceback ````Traceback (most recent call last): File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1836 in __call__ return self wsgi_app(environ start_response) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1820 in wsgi_app response = self make_response(self handle_exception(e)) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1403 in handle_exception reraise(exc_type exc_value tb) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1817 in wsgi_app response = self full_dispatch_request() File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1477 in full_dispatch_request rv = self handle_user_exception(e) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1381 in handle_user_exception reraise(exc_type exc_value tb) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1475 in full_dispatch_request rv = self dispatch_request() File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/flask/app py" line 1461 in dispatch_request return self view_functions[rule endpoint](**req view_args) File "/home/vcap/app/server py" line 93 in main for container in conn get_account()[1]: File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 1615 in get_account full_listing=full_listing) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 1553 in _retry self url self token = self get_auth() File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 1507 in get_auth timeout=self timeout) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 617 in get_auth auth_version=auth_version) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 517 in get_auth_keystone ksclient exceptions = _import_keystone_client(auth_version) File "/home/vcap/app/ heroku/python/lib/python2 7/site-packages/swiftclient/client py" line 502 in _import_keystone_client variables to be set or overridden with -A -YOU or -K ''') ClientException: Auth versions 2 0 and 3 require python-keystoneclient install it or use Auth version 1 0 which requires ST_AUTH ST_USER and ST_KEY environment variables to be set or overridden with -A -YOU or -K ```` Seems like the append was not causing an error but exposing one I will update once this is sorted | As indicated at the bottom of the traceback I was missing the python-keystoneclient in both my application requirements and import statements I fixed this by adding ````python-keystoneclient ```` to my requirements txt (which is the requirements file for the python-heroku-buildpack) which then allowed me to add the import to my Flask app ````import keystoneclient v3 as keystoneclient ```` |
Pick the same value of many dictionary in python Recently I was given a problem from an interviewer who gave me a json file which looks like: ```` {"id:"110235" "symbol":"ccl" "qty":"900" "available":"35500" "time":"2016-05-05T08:00:00 169646Z"} {"id:"110235" "symbol":"ccl" "qty":"550" "available":"16000" "time":"2016-05-05T08:01:05 167356Z"} {"id:"110235" "symbol":"ssi" "qty":"1550" "available":"24000" "time":"2016-05-05T08:01:07 173386Z"} {"id:"110235" "symbol":"tcl" "qty":"270" "available":"21340" "time":"2016-05-05T08:01:15 089586Z"} {"id:"110235" "symbol":"ccl" "qty":"690" "available":"57840" "time":"2016-05-05T08:01:24 236786Z"} {"id:"110235" "symbol":"tcl" "qty":"740" "available":"38540" "time":"2016-05-05T08:01:28 145786Z"} ```` He wants me to sum the values of all `available` that have the same `symbol` I thought about making a set of `symbol`s and loop through the json file and sum the values of `available` but it is slow What is the most efficient way to do this? | Its not clear what the expected output format is but if it can be a dictionary the following would be O(n) time ````def sum_symbols(data): symbols = {} for row in data: symbol = symbols["symbol"] available = int(row["available"]) if symbol in symbols: symbols[symbol] = available else: symbols[symbol] = available return symbols sum_symbols(data) ```` |
Object of custom type as dictionary key What must I do to use my objects of a custom type as keys in a Python dictionary (where I do not want the "object id" to act as the key) e g ````class MyThing: def __init__(self name location length): self name = name self location = location self length = length ```` I would want to use MyThing's as keys that are considered the same if name and location are the same From C#/Java I am used to having to override and provide an equals and hashcode method and promise not to mutate anything the hashcode depends on What must I do in Python to accomplish this ? Should I even ? (In a simple case like here perhaps it would be better to just place a (name location) tuple as key - but consider I would want the key to be an object) | You override `__hash__` if you want special hash-semantics and `__cmp__` or `__eq__` in order to make your class usable as a key Objects who compare equal need to have the same hash value Python expects `__hash__` to return an integer returning `Banana()` is not recommended :) User defined classes have `__hash__` by default that calls `id(self)` as you noted There is some extra tips from the <a href="http://docs python org/reference/datamodel html#object __hash__">documentation</a> : <blockquote> Classes which inherit a `__hash__()` method from a parent class but change the meaning of `__cmp__()` or `__eq__()` such that the hash value returned is no longer appropriate (e g by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting `__hash__ = None` in the class definition Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value but they will also be correctly identified as unhashable when checking `isinstance(obj collections Hashable)` (unlike classes which define their own `__hash__()` to explicitly raise TypeError) </blockquote> |
How to find the size of a partially known name file in a partially known name folder in a known drive The Python code below let us me read the file size ````import os b = os path getsize("known_drive_name/folder_name_partial_known/file_name_partial_unknown_file_ext_known") print b ```` But given the following conditions: - I know the drive name; - There is only one file inside the folder; - I know the file extension; - I do not know the file name (or I know only certain letters); - I do not know the folder name (or I know only certain letters); Can you help me build the code to find the size of the file? | As stated by tmoreau you can use the glob module <a href="https://docs python org/3/library/pathlib html#pathlib Path glob" rel="nofollow">https://docs python org/3/library/pathlib html#pathlib Path glob</a> If you only want to match one file you can try : ````import glob import os extension = " gif" drive = "/mnt/ssd0/" dir_glob = "**/[0-9]/*" paths = glob glob(drive dir_glob extension) if paths: # if the list is not empty print os path getsize(paths[0]) ```` of course you will have to adapt the glob_pattern according to what you know of the directory names |
PYTHON How to detect when a proccess has been ended Given a proccess name(PID is unkown) how can i detect when a proccess has been ended(Also how can i find out the PID given a proccess name)? Also I am doing this for windows explorer so how would I track the proccess name as it changes as the user moves thorugh directories I am using Python 2 7 and windows if that helps Thank you | As Padraic Cunningham wrote here: <a href="http://stackoverflow com/questions/26688936/python-how-to-get-pid-by-process-name">Python: How to get PID by process name?</a> In order to get pid from process-name: ````from subprocess import check_output def get_pid(name): return int(check_output(["pidof" "-s" name])) ```` As Mat wrote here: <a href="http://stackoverflow com/a/6767792/5088142">http://stackoverflow com/a/6767792/5088142</a> In order to get status of a process using its pid your can use psutil <a href="https://github com/giampaolo/psutil" rel="nofollow">https://github com/giampaolo/psutil</a> ````import psutil print psutil Process(pid) status ```` Edit: You can combine those two parts into the following code: ````from subprocess import check_output import psutil def get_pid(name): return int(check_output(["pidof" "-s" name])) def get_status(name) pid = get_pid(name) print psutil Process(pid) status ```` |
Is there a way to control a webcam focus in pygame? I have 2 web cams and I want to take pictures with them This code do the work ````import pygame import pygame camera from datetime import datetime import Image import threading import time class Camera (threading Thread): def __init__(self camera): self camera = pygame camera Camera(camera (2304 1536)) self stop = False threading Thread __init__(self) def run(self): self camera start() srf = self camera get_image() img = pygame image tostring(srf 'RGB') img = Image fromstring('RGB' srf get_size() img) img save('%s png'%datetime now() 'PNG') s = datetime now() pygame init() pygame camera init() cam1 = Camera("/dev/video0") cam2 = Camera("/dev/video1") cam1 start() cam2 start() cam1 join() cam2 join() print datetime now() - s ```` But I need to set the focus I find this command lines: ````apt-get install uvcdynctrl uvcdynctrl --device=/dev/video1 --clist uvcdynctrl --device=/dev/video1 --get='Focus Auto' uvcdynctrl --device=/dev/video1 --set='Focus Auto' 0 uvcdynctrl --device=/dev/video1 --set='Focus (absolute)' 20 ```` I know this dirty trick: ````import os os system('command to set the focus') ```` But My camera is a logitech and this do not work I am on ubuntu 12 04 python 2 7 and I get this output from the command line ````uvcdynctrl --device=/dev/video1 --set='Focus Auto' 0 [libwebcam] Unsupported V4L2_CID_EXPOSURE_AUTO control with a non-contiguous range of choice IDs found [libwebcam] Invalid or unsupported V4L2 control encountered: ctrl_id = 0x009A0901 name = 'Exposure Auto' [libwebcam] Unsupported V4L2_CID_EXPOSURE_AUTO control with a non-contiguous range of choice IDs found [libwebcam] Invalid or unsupported V4L2 control encountered: ctrl_id = 0x009A0901 name = 'Exposure Auto' ```` Edit: The camera is a Logitech HD Pro Webcam C920 and runing the next command: ````uvcdynctrl --device=/dev/video1 --clist ```` I get this output: ````[libwebcam] Unsupported V4L2_CID_EXPOSURE_AUTO control with a non-contiguous range of choice IDs found [libwebcam] Invalid or unsupported V4L2 control encountered: ctrl_id = 0x009A0901 name = 'Exposure Auto' [libwebcam] Unsupported V4L2_CID_EXPOSURE_AUTO control with a non-contiguous range of choice IDs found [libwebcam] Invalid or unsupported V4L2 control encountered: ctrl_id = 0x009A0901 name = 'Exposure Auto' Listing available controls for device /dev/video1: Brightness Contrast Saturation White Balance Temperature Auto Gain Power Line Frequency White Balance Temperature Sharpness Backlight Compensation Exposure (Absolute) Exposure Auto Priority Pan (Absolute) Tilt (Absolute) Focus (absolute) Focus Auto Zoom Absolute ```` | execute this ````sudo apt-get install v4l-utils ```` and in python ````os system('v4l2-ctl -d 0 -c focus_auto=0') os system('v4l2-ctl -d 0 -c focus_absolute=250') ```` |
Imported classes are prefixed in Client Library In Python I am creating backend for my Android app My code is too big so I broke it to 2 files with functions and one with shared classes (shared_classes py) which inherit from messages Message When I generate client library all classes get prefixed with name of the python file I stored them in (they look like: SharedClassesExampleName java) <strong>Is it possible to force endpointscfg py to stop generating library with prefixed python classes?</strong> | customize the API method name with ````@endpoints method(name='subject action') ```` and API class with ````name = "appname" ```` your API will be accessible at ````gapi client appname subject action() ```` check details at <a href="https://developers google com/appengine/docs/python/endpoints/getstarted/backend/write_api" rel="nofollow">https://developers google com/appengine/docs/python/endpoints/getstarted/backend/write_api</a> |
I cannot get ? instead of %s to work on an insert with python mysqldb I cannot get ? instead of %s to work on an insert with python mysqldb I try ````cur execute("""INSERT INTO project (project) VALUES (?) """ ('ham')) ```` but I get ````query = query % db literal(args) TypeError: not all arguments converted during string formatting ```` works fine if I simply substitute ? with %s What am I doing wrong? | You cannot The `mysqldb` adapter only supports the `format` and `pyformat` parameter styles The <a href="http://www python org/dev/peps/pep-0249/" rel="nofollow">Python DB API 2 0 specification</a> supports <a href="http://www python org/dev/peps/pep-0249/#paramstyle" rel="nofollow">5 different `paramstyle` parameter styles</a> but it is up to the exact database adapter implementation what they support The <a href="http://mysql-python sourceforge net/MySQLdb html#functions-and-attributes" rel="nofollow">`mysqldb` project documentation</a> tells you what styles are supported by that adapter and `qmark` is not one of them If you are trying to write SQL suitable for multiple database adapters you will most likely have to deal with more issues than just the parameter style Consider using <a href="http://www sqlalchemy org/" rel="nofollow">SQLAlchemy</a> instead which can generate SQL for you that is more database agnostic (up to a point) |
RE pandas resample Been trying to take an average of a month worth of data but I wanted to check that: ````df=df resample('M') mean() ```` Does give the monthly mean and NOT the mean of the last calander day of month Also I have seen `W-Mon` which would give an average of the monday at a frequency of a week What would be the equivalent to compare the monthly average of October over multiple years I thought it would be this- but it does not seem to recognise the command ````df=df resample("M-OCT") mean() ```` | try this: ````df assign(y=df index year m=df index month) query('m==10') groupby(['y' 'm']) mean() ```` PS if you need a neat and tested answer please post sample data set and desired output in your question |
How do I properly reference Python classes? I am working on writing my first Python class Being the java programmer that I am I have something like this: ````#class1 py class class1: def __init__(self): #Do stuff here ```` And in my current script: ````import class1 object = class1() ```` I am getting a `Name Error: name 'class1' is not defined` I have also tried this with no luck: ````import class1 object = class1 class1() ```` The error I get here is `AttributeError: 'module' object has no attribute 'class1'` What am I doing wrong? | Python import is by module and then by the contents of the module so for your class1 py it becomes: ````from class1 import class1 ```` <a href="http://docs python org/2/tutorial/modules html" rel="nofollow">Python module docs</a> |
Multiple dimension matrix multiplication in Python I have a matrix `M` `M shape` = `(4 4)` and `M[1 1] shape`=`(600 300)` Each `M[i j]` is calculated by passing a `meshgrid` For Example ````x=300 t=np linspace(0 np pi num=x) p=np linspace(0 2*np pi num=2*x) [T P]=np meshgrid(t p) M[1 1]=np sin(T)*np cos(P) ```` Each element of M is a different combination of `sin` and `cos` Next I have `x` such that `x shape`=`(4 600 300)` x is calculated as follows: ````for j in xrange(n): x[0]+=np sin(T)*np sin(time[j]) x[1]+=np sin(T)*np sin(time[j]) x[2]+=np sin(P)*np cos(time[j]) x[3]+=np sin(P)*np cos(time[j]) ```` where `time[j]` is some number I want to know how to compute transpose(x) M X So this should come to be a quantity of shape(600 300) I have computed `a = np tensordot(M x axes=[1 0])` which yields `a shape`=`(4 600 300)` Firstly is this correct? Secondly I how to take the transpose and compute transpose(x) M x? | Forget about how you calculate things like `M` and `x` and focus on the multiplication: <blockquote> I want to know how to compute transpose(x) M X So this should come to be a quantity of shape(600 300) I have computed a = np tensordot(Mat x axes=[1 0]) which yields a shape=(4 600 300) </blockquote> What is the total shape of `M`? `wwii`s guess makes most sense `(4 4 600 300)` You say `x` is `(4 600 300)` What is `transpose(x)`? Transpose is defined for 2 axes but ambiguous with 3 What is `X`? what is `Mat`? The only thing that works in your `np tensordot(Mat x [1 0])` is `(4 4)` But let me make an educated guess you want `X T * M * X` but with the added `(600 300)` dimension ```` np einsum('inm ijnm jnm>nm' X M X) ```` That is you want a dot produce of `X` with the 1st dim of `M` and another dot product of `X` with the 2nd dim of `M` without altering the last 2 dimensions |
Small Tables in Python? Let us say I do not have more than one or two dozen objects with different properties such as the following: UID Name Value Color Type Location I want to be able to call up all objects with Location = "Boston" or Type = "Primary" Classic database query type stuff Most table solutions (pytables *sql) are really overkill for such a small set of data Should I simply iterate over all the objects and create a separate dictionary for each data column (adding values to dictionaries as I add new objects)? This would create dicts like this: {'Boston' : [234 654 234] 'Chicago' : [324 765 342] } - where those 3 digit entries represent things like UID's As you can see querying this would be a bit of a pain Any thoughts of an alternative? | For small relational problems I love using Python's builtin <a href="http://docs python org/library/sets html">sets</a> For the example of location = 'Boston' OR type = 'Primary' if you had this data: ````users = { 1: dict(Name="Mr Foo" Location="Boston" Type="Secondary") 2: dict(Name="Mr Bar" Location="New York" Type="Primary") 3: dict(Name="Mr Quux" Location="Chicago" Type="Secondary") # } ```` You can do the `WHERE OR ` query like this: ````set1 = set(you for you in users if users[you]['Location'] == 'Boston') set2 = set(you for you in users if users[you]['Type'] == 'Primary') result = set1 union(set2) ```` Or with just one expression: ````result = set(you for you in users if users[you]['Location'] == 'Boston' or users[you]['Type'] == 'Primary') ```` You can also use the functions in <a href="http://docs python org/library/itertools html">itertools</a> to create fairly efficient queries of the data For example if you want to do something similar to a `GROUP BY city`: ````cities = ('Boston' 'New York' 'Chicago') cities_users = dict(map(lambda city: (city ifilter(lambda you: users[you]['Location'] == city users)) cities)) ```` You could also build indexes manually (build a `dict` mapping Location to User ID) to speed things up If this becomes too slow or unwieldy then I would probably switch to <a href="http://docs python org/library/sqlite3 html">sqlite</a> which is now included in the Python (2 5) standard library |
Range for nargs in argparse I have a script which merges multiple video and audio files Now I have a parameter which allows four values: ````# -A FILENAME LANGUAGE POSITION SPEED $ script py [ more parameters ] -A audio mp3 eng -1 1 [ more parameters ] ```` Now I want the third and fourth to be optional Currently I have two ideas but maybe there is a better solution: - Set `nargs` to `+` and throw an error if 1 or more than 4 parameters are supplied Maybe the `type` parameter can catch this Problem would be that it is not visible in the help that 2 to 4 values are required - Have 4 different parameters for all combinations This would allow to have the position optional Problem is that I then need four parameter names The parameter also might appear multiple times (`action` is `append`) | I would suggest having `-A` take a single comma-separated string (or use the delimiter of your choice) and supply a custom metavar for the help message ````def av_file_type(str): data = tuple(str split(" ")) n = len(data) if n < 2: raise ArgumentError("Too few arguments") elif n == 2: return data (default_position default_speed) elif n == 3: return data (default_speed ) elif n == 4: return data else: return ArgumentError("Too many arguments") p add_argument("-A" action='append' type=av_file_type metavar='filename language[ position[ speed]]') ```` With `nargs='+'` it would be extremely non-trivial to format the help string the way you like |
Determine arguments where two numpy arrays intersect in Python I have two arrays say: ````a b = np array([13 14 15 32 33 ]) np array([15 16 17 33 34 47 ]) ```` I need to find the indices of all the elements in a that are not present in b In the above example the result would be: ````[0 1 3] ```` Because a[0] a[1] and a[3] are 13 14 and 32 which are not present in b Notice that I do not care to know the actual values of 13 14 and 32 (I could have used set(a) difference(set(b)) in that case) I am genuinely interested in the indices only If possible the answer should be "vectorized" i e not using a for loop | You could use <a href="http://docs scipy org/doc/numpy/reference/routines set html" rel="nofollow">np in1d</a>: ````>>> np arange(a shape[0])[~np in1d(a b)] tolist() [0 1 3] ```` |