Search Results

Search found 13693 results on 548 pages for 'python metaprogramming'.

Page 140/548 | < Previous Page | 136 137 138 139 140 141 142 143 144 145 146 147  | Next Page >

  • Python Django Global Variables

    - by Joe J
    Hi all, I'm looking for simple but recommended way in Django to store a variable in memory only. When Apache restarts or the Django development server restarts, the variable is reset back to 0. More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for performance reasons, I don't want to store these counts in the database. I don't care if the counts disappear after a server restart. But as long as the server is up, I want these counts to be consistent between the Django shell and the web interface, and I want to be able to return how many times the action has taken place on each model instance. I don't want the variables to be associated with a user or session because I might want to return these counts without being logged in (and I want the counts to be consistent no matter what user is logged in). Am I describing a global variable? If so, how do I use one in Django? I've noticed the files like the urls.py, settings.py and models.py seems to be parsed only once per server startup (by contrast to the views.py which seems to be parsed eache time a request is made). Does this mean I should declare my variables in one of those files? Or should I store it in a model attribute somehow (as long as it sticks around for as long as the server is running)? This is probably an easy question, but I'm just not sure how it's done in Django. Any comments or advice is much appreciated. Thanks, Joe

    Read the article

  • Remove certain filetypes in Python

    - by Gareth
    Hello. I am running a script that walks a directory structure and generates new files in each folder in the directory. I want to delete some of the files right after creation. This is my idea, but it is quite wrong I imagine: directory = os.path.dirname(obj) m = MeshExporterApplication(directory) os.remove(os.path.join(directory,"*.mesh.xml")) How to you put wildcards in a path? I guess not like /home/me/*.txt, but that is what I am trying. Thanks, Gareth

    Read the article

  • Regex in Python

    - by newToProgramming
    SO, I am trying create a simple regex that matches the following string: ..."chrX:33267175-33267784 610bp TGATGTTTGGCGAGGAACTC GCAGAGTTTGAAGAGCTCGG\nTGATGTTTGGCGAGGAACTCtactattgttacacttaggaaaataatcta\natccaaaggctttgcatctgtacagaagagcgagtagatactgaaagaga\ntttgcagatccactgttttttaggcaggaagaatgctcgttaaatgcaaa\ncgctgctctggctcatgtgtttgctccgaggtataggttttgttcgactg\nacgtatcagatagtcagagtggttaccacaccgacgttgtagcagctgca\ntaataaatgactgaaagaatcatgttaggcatgcccacctaacctaactt\ngaatcatgcgaaaggggagctgttggaattcaaatagactttctggttcc\ncagcagtcggcagtaatagaatgctttcaggaagatgacagaatcaggag\naaagatgctgttttgcactatcttgatttgttacagcagccaacttattg\ngcatgatggagtgacaggaaaaacagctggcatggaaggtaggattatta\naagctattacatcattacaaatacaattagaagctggccatgacaaagca\ntatgtttgaacaagcagctgttggtagctggggtttgttgCCGAGCTCTT\nCAAACTCTGC\n"... I have created the following regex: <PRE>[.|[\n]]*</PRE>' yet it won't match the string above. Does anyone have a solution to this conundrum and perhaps a reasoning as toward why this doesn't work.

    Read the article

  • Operations on Python hashes

    - by cdecker
    I've got a rather strange problem. For a Distributed Hash Table I need to be able to do some simple math operations on MD5 hashes. These include a sum (numeric sum represented by the hash) and a modulo operation. Now I'm wondering what the best way to implement these operations is. I'm using hashlib to calculate the hashes, but since the hashes I get are then string, how do I calculate with them?

    Read the article

  • Python: Can subclasses overload inherited methods?

    - by Rosarch
    I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler: class BaseHandler(webapp.RequestHandler): def get(self, CSIN=None): self.body(CSIN) Does this mean that the body() method of every descendant class needs to have the same argument? This is cumbersome. Only one descendant actually uses that argument. And what about when I add new args? Do I need to go through and change every class? class Detail(BaseHandler): def body(self, CSIN): class MainPage(BaseHandler): def body(self, CSIN=None): #@UnusedVariable class Cart(BaseHandler): def body(self, CSIN): #@UnusedVariable

    Read the article

  • Python, datetime "time gap" percentage

    - by Hellnar
    Hello Assume I have these datatime variables: start_time, end_time, current_time I would like to know how much time left as percentage by checking current_time and the time delta between start_time and the end_time Like if the interval is a 24 hours, and between now and end_time, there are 6 hours left, %25 should be left. How can this be done ?

    Read the article

  • How to log python exception ?

    - by Maxim Veksler
    Hi, Coming from java, being familiar with logback I used to do try { ... catch (Exception e) { log("Error at X", e); } I would like the same functionality of being able to log the exception and the stacktrace into a file. How would you recommend me implementing this? Currently using boto logging infrastructre, boto.log.info(...) I've looked at some options and found out I can access the actual exception details using this code: import sys try: 1/0 except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) I would like to somehow get the string print_exception() throws to stdout so that I can log it. Thank you, Maxim.

    Read the article

  • Joining the previous and next sentence using python

    - by JudoWill
    I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just keep the sentence and its only neighbor. An example is best: ex_paragraph = ['The quick brown fox jumps over the fence.', 'Where there is another red fox.', 'They run off together.', 'They live hapily ever after.'] t1 = lambda x: x.startswith('Where') t2 = lambda x: x'startswith('The ') The result for t1 should be: ['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.'] The result for t2 should be: ['The quick brown fox jumps over the fence. Where there is another red fox.'] My solution is: def YieldContext(sent_list, cont_fun): def JoinSent(sent_list, ind): if ind == 0: return sent_list[ind]+sent_list[ind+1] elif ind == len(sent_list)-1: return sent_list[ind-1]+sent_list[ind] else: return ' '.join(sent_list[ind-1:ind+1]) for sent, sentnum in izip(sent_list, count(0)): if cont_fun(sent): yield JoinSent(sent_list, sent_num) Does anyone know a "cleaner" or more pythonic way to do something like this. The if-elif-else seems a little forced. Thanks, Will PS. I'm obviously doing this with a more complicated "context-function" but this is just for a simple example.

    Read the article

  • Sorting objects in Python

    - by Curious2learn
    I want to sort objects using by one of their attributes. As of now, I am doing it in the following way USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True) This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort? I tried, keyFunc=operator.attrgetter('utility[chosenCar]') USpeople.sort(key=keyFunc,reverse=True) However, I get an error saying that there is no attribute 'utility[chosenCar]'. The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form: utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500} I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this? Thanks in advance.

    Read the article

  • Can someone here explain constructors and destructors in python - simple explanation required - new

    - by rgolwalkar
    i will try to see if it makes sense :- class Person: '''Represnts a person ''' population = 0 def __init__(self,name): //some statements and population += 1 def __del__(self): //some statements and population -= 1 def sayHi(self): '''grettings from person''' print 'Hi My name is %s' % self.name def howMany(self): '''Prints the current population''' if Person.population == 1: print 'i am the only one here' else: print 'There are still %d guyz left ' % Person.population rohan = Person('Rohan') rohan.sayHi() rohan.howMany() sanju = Person('Sanjivi') sanju.howMany() del rohan # am i doing this correctly --- ? i need to get an explanation for this del - destructor O/P:- Initializing person data ****************************************** Initializing Rohan ****************************************** Population now is: 1 Hi My name is Rohan i am the only one here Initializing person data ****************************************** Initializing Sanjivi ****************************************** Population now is: 2 In case Person dies: ****************************************** Sanjivi Bye Bye world there are still 1 people left i am the only one here In case Person dies: ****************************************** Rohan Bye Bye world i am the last person on earth Population now is: 0 If required i can paste the whole lesson as well --- learning from :- http://www.ibiblio.org/swaroopch/byteofpython/read/

    Read the article

  • Python port forwarding/multiplexing server

    - by Ib33X
    I would like to make server that listen on UDP port 162 (SNMP trap) and then forwards this traffic to multiple clients. Also important is that the source port & address stays same (address spoofing). I guess that best tool for this would be Twisted or Scapy or mybe vanilla sockets, only I can't find anything in the documentation for Twisted about source address spoofing/forging. What would you recommend me to do? Edit:added bounty

    Read the article

  • Python: OSX Library for fast full screen jpg/png display

    - by Parand
    Frustrated by lack of a simple ACDSee equivalent for OS X, I'm looking to hack one up for myself. I'm looking for a gui library that accommodates: Full screen image display High quality image fit-to-screen (for display) Low memory usage Fast display Reasonable learning curve (the simpler the better) Looks like there are several choices, so which is the best? Here are some I've run across: PyOpenGL PyGame PyQT wxpython I don't have any particular experience with any of these, nor any strong desire to become an expert - I'm looking for the simplest solution. What do you recommend? [Update] For those not familiar with ACDSee, here's what it does that I care about: Simple list/thubmnail display of images in a directory Sort by name/size/type Ability to view images full screen Single-key delete while viewing full screen Move to next/previous image while viewing full screen Ability to select a group of images for: move to / copy to directory delete resize ACDSee has a bunch of niceties as well, such as remembering directories you've moved images to in the past, remembering your resize settings, displaying the total size of the images you've selected, etc. I've tried most of the options I could find (including Xee) and none of them quite get there. Please keep in mind that this is a programming/library question, not a criticism of any of the existing tools.

    Read the article

  • Defining the context of a word - Python

    - by RadiantHex
    Hi folks, I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Technology Web Design I need to try and match words with the appropriate context/contexts if possible. Maybe discovering word relationships in some way. Any ideas? Help would be much appreciated!

    Read the article

  • Get last n lines of a file with Python, similar to tail

    - by Armin Ronacher
    I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom. So I need a tail() method that can read n lines from the bottom and supports an offset. What I came up with looks like this: def tail(f, n, offset=0): """Reads a n lines from f with an offset of offset lines.""" avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 Is this a reasonable approach? What is the recommended way to tail log files with offsets?

    Read the article

  • Python: Decent config file format

    - by miracle2k
    I'd like to use a configuration file format which supports key value pairs and nestable, repeatable structures, and which is as light on syntax as possible. I'm imagining something along the lines of: cachedir = /var/cache mail_to = [email protected] job { name = my-media frequency = 1 day source { from = /home/michael/Images source { } source { } } job { } I'd be happy with something using significant-whitespace as well. JSON requires too many explicit syntax rules (quoting, commas, etc.). YAML is actually pretty good, but would require the jobs to be defined as a YAML list, which I find slightly awkward to use.

    Read the article

  • Django/Python best practice template_dict

    - by fredrik
    Hi, After just been coding for about 6-9 months. I probably changed my coding style a number of times after reading some code or read best practices. But one thing I haven't yet come a cross is a good why to populate the template_dict. As of now I pass the template_dict across a number of methods (that changes/modifies it) and returns is. The result is that every methods takes template_dict as first argument and the returns it and this in my eyes doesn't seems to be the best solution. An idea is to have a method that handles all the changes. But I'm curios if there's a best practice for this? Or is it "do what you feel like"-type of thing? The 2 things I think is pretty ugly is to send as an argument and return it in all methods. And the just the var name is written xxx number of times in the code :) ..fredrik

    Read the article

  • Python Mechanize select a form with no name

    - by mvid
    I am attempting to have mechanize select a form from a page, but the form in question has no "name" attribute in the html. What should I do? when I try to use br.select_form(name = "") i get errors that no form is declared with that name, and the function requires a name input. There is only one form on the page, is there some other way I can select that form?

    Read the article

  • How to define and use Python generators appropriately

    - by Morlock
    I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner. a = ["Hello", "world", "!"] b = (x for x in a) c = next(b, None) while c != None: print c, c = next(b, None) Is there anything wrong or improvable with the while approach here? Is there a way to avoid having to assign 'c' before the loop? Thanks!

    Read the article

  • Possible to use Python with Intel's Atom Developer SDK (C/C++)?

    - by Jordan Magnuson
    So I've made a game in Python and PyGame. Now I'm interested in submitting the game to Intel's March Developer Challenge. However, the developer challenge requires use of Intel's Atom Developer SDK (http://appdeveloper.intel.com/en-us/sdk), which only has API's for C and C++. I'm new to Python and PyGame, and have no experience in C or C++. My question is, would it be possible to somehow implement Intel's Atom SDK through/with/from a Python application (as the first link above suggests)? I've read up a little bit on embedding/extending Python into/with C, but I'm not entirely sure what to embed or where. I mean, I know I can do things like this in C: #include <Python.h> int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } But what do I do about all my dependencies on Python and Pygame, for people that don't have those installed on their machines? Normally Py2Exe takes care of compacting the required dependencies (I've managed to package my game into an exe/zip), but how do I take care of that stuff in the context of embedding within C? Can I somehow work with py2exe on this, or do I need to do something entirely different for embedding within C? It seems like it would be a lot easier to go the route of extending Python with the C validation code, rather than trying to embed my whole game within C, but I think that's not an option, "because the library provided is currently only available as a Visual Studio 2008 '.lib'", meaning the application has to be compiled with Visual Studio...? Any help, thoughts, or ideas are much appreciated! You can find the complete SDK Developer's Guide on the intel site above, but here is their "Hello World" using the C Language API: #include <stdio.h> #include “adpcore.h” int main( int argc, char* argv[] ) { ADP_RET_CODE ret_code; const ADP_APPLICATIONID myApplicationID = {{ 0x12345678,0x11112222,0x33331234,0x567890ab}}; if ((ret_code = ADP_Initialize()) != ADP_SUCCESS ){ printf( “ERROR: exiting” ); exit( -1 ); } if (( ret_code = ADP_IsAuthorized( myApplicationId )) == ADP_AUTHORIZED ) printf( “Hello World” ); else printf( “Not authorized to run” ); exit 0; } 35 Page SDK Developer Guide: http:// appdeveloper.intel.com/sites/files/pages/SDK%20Developer%20Guide.pdf

    Read the article

  • Copy whole SQL Server database into JSON from Python

    - by Oli
    I facing an atypical conversion problem. About a decade ago I coded up a large site in ASP. Over the years this turned into ASP.NET but kept the same database. I've just re-done the site in Django and I've copied all the core data but before I cancel my account with the host, I need to make sure I've got a long-term backup of the data so if it turns out I'm missing something, I can copy it from a local copy. To complicate matters, I no longer have Windows. I moved to Ubuntu on all my machines some time back. I could ask the host to send me a backup but having no access to a machine with MSSQL, I wouldn't be able to use that if I needed to. So I'm looking for something that does: db = {} for table in database: db[table.name] = [row for row in table] And then I could serialize db off somewhere for later consumption... But how do I do the table iteration? Is there an easier way to do all of this? Can MSSQL do a cross-platform SQLDump (inc data)? For previous MSSQL I've used pymssql but I don't know how to iterate the tables and copy rows (ideally with column headers so I can tell what the data is). I'm not looking for much code but I need a poke in the right direction.

    Read the article

  • Converting python objects for rpy2

    - by bgbg
    The following code is supposed to created a heatmap in rpy2 import numpy as np from rpy2.robjects import r data = np.random.random((10,10)) r.heatmap(data) However, it results in the following error Traceback (most recent call last): File "z.py", line 8, in <module> labRow=rowNames, labCol=colNames) File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 418, in __call__ new_args = [conversion.py2ri(a) for a in args] File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 93, in default_py2ri raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o)))) ValueError: Nothing can be done for the type <type 'numpy.ndarray'> at the moment. From the documentation I learn that r.heatmap expects "a numeric matrix". How do I convert np.array to the required data type?

    Read the article

  • Python key word arguments

    - by pythonic metaphor
    I have several layers of function calls, passing around a common dictionary of key word arguments: def func1(**qwargs): func2(**qwargs) func3(**qwargs) I would like to supply some default arguments in some of the subsequent function calls, something like this: def func1(**qwargs): func2(arg = qwargs.get("arg", default), **qwargs) func3(**qwargs) The problem with this approach is that if arg is inside qwargs, a TypeError is raised with "got multiple values for keyword argument". I don't want to set qwargs["arg"] to default, because then func3 gets this argument without warrant. I could make a copy.copy of the qwargs and set "arg" in the copy, but qwargs could have large data structures in it and I don't want to copy them (maybe copy.copy wouldn't, only copy.deepcopy?). What's the pythonic thing to do here?

    Read the article

  • assign operator to variable in python?

    - by abhilashm86
    Usual method of applying mathematics to variables is a * b Is it able to calculate and manipulate two operands like this? a = input('enter a value') b = input('enter a value') op = raw_input('enter a operand') then how do i connect op and two variables a and b?? i know i can compare op to +, -, %, $ and then assign and compute.... but can i do something like a op b , how to tell compiler that op is an operator?? any tweaks possible?

    Read the article

< Previous Page | 136 137 138 139 140 141 142 143 144 145 146 147  | Next Page >