Search Results

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

Page 110/548 | < Previous Page | 106 107 108 109 110 111 112 113 114 115 116 117  | Next Page >

  • Python: avoiding fraction simplification

    - by Anthony Labarre
    Hi all, I'm working on a music app' in Python and would like to use the fractions module to handle time signatures amongst other things. My problem is that fractions get simplified, i.e.: >>> from fractions import Fraction >>> x = Fraction(4, 4) >>> x Fraction(1, 1) However, it is important from a musical point of view that 4/4 stays 4/4 even though it equals 1. Is there any built-in way to avoid that behaviour? Thanks!

    Read the article

  • Python regular expressions assigning to named groups

    - by None
    When you use variables (is that the correct word?) in python regular expressions like this: "blah (?P\w+)" ("value" would be the variable), how could you make the variable's value be the text after "blah " to the end of the line or to a certain character not paying any attention to the actual content of the variable. For example, this is pseudo-code for what I want: >>> import re >>> p = re.compile("say (?P<value>continue_until_text_after_assignment_is_recognized) endsay") >>> m = p.match("say Hello hi yo endsay") >>> m.group('value') 'Hello hi yo' Note: The title is probably not understandable. That is because I didn't know how to say it. Sorry if I caused any confusion.

    Read the article

  • A Python IDE with Debugging and iPython Integration?

    - by skibum1981
    Does anyone know of a python IDE that has iPython as the interpreter? Using the standard interpreter just drives me nuts, as I've just grown to love using iPython and all the features it provides. To be honest, I'd rather code with a simple text editor + ipython than an IDE, but I love being able to set breakpoints with a click of a mouse, etc., so I'd like to combine both. Sorry if there's something out there and this is common knowledge. Any information/tips you can provide is GREATLY appreciated. Thanks!

    Read the article

  • Python: Trying to get index of an intersection

    - by user1620716
    I have the following line of code: for i in [i for i,x in enumerate(catdate) if x == set(NNSRCfile['datetimenew']).intersection(catdate)]: print i I am trying to find the index of the intersection for the two components above. Both are lengthy lists that have several commonalities. The intersection part works perfectly; however, the for loop seems to output nothing. (ie: there is nothing that is printed). Python outputs no error, and when I run the code in IPython, I notice that i is equivalent to to the very last element in the list "catdate", instead of listing the indices of "catdate" that are equivalent to the intersection values. Any help is greatly appreciated!

    Read the article

  • Binary search of unaccesible data field in ldap from python

    - by EricR
    I'm interested in reproducing a particular python script. I have a friend who was accessing an ldap database, without authentication. There was a particular field of interest, we'll call it nin (an integer) for reference, and this field wasn't accessible without proper authentication. However, my friend managed to access this field through some sort of binary search (rather than just looping through integers) on the data; he would check the first digit, check if it was greater or less than the starting value, he would augment that until it returned a true value indicating existence, adding digits and continuing checking until he found the exact value of the integer nin. Any ideas on how he went about this? I've access to a similarly set up database.

    Read the article

  • Problem with Classes in Python..

    - by Gui
    Ok guys, I'm really new at python (and programming itself) so sorry for my ignorance, but I really needed to ask this. So im doing a wxPython project where I added several tabs for a notebook (each tab of the notebook = a class) and there is one tab where I added a checkbox (in a tab, lets call it for example Tab1), and what I want is that when someone checks it, a button that exists in other tab (class called for example tab2) gets hidden where previously it was being shown. Well I see that it isn't hard to accomplish this, but my problem is the classes (tab1 and tab2, in this example). I've been trying to figure it out by searching but I guess im not searching hard enough because I just can't get it right. If they were in the same class I wouldn't have a problem, but as they are in different classes, im having a huge struggle with this. Hope someone can help me, and sorry for my ignorance once again.

    Read the article

  • Automatic logout in python web app

    - by Ali
    I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session id, with allows the user to interact with other parts of the sight. When the user clicks logout, the script erases the session id from the database and deletes the cookie. The cookie expires after 5 hours. My concern is that if the user doesnt log out, and the cookie expires, the script will force him to login, but if he has copied the session id from before, it can still be validated. How do i automatically delete the session id from the mysql database after 5 hours?

    Read the article

  • Problem about python import with error

    - by xiao
    Hello, I have write a small python module with one class and two functions. The skeleton of the module is as following: #file name: test_module.py class TestClass: @classmethod def method1(cls, param1): #to do something pass def __init__(self, param1): #to do something ... def fun1(*params): #to do something ... def fun2(*params): #to do something ... Another py file is a small script which imports function and class from the module, as following: import sys from test_module import TestClass, fun1, fun2 def main(sys_argv): li = range(5) inst1 = TestClass(li) fun1(inst1) fun2(inst1) return if __name__ == "__main__": main(sys.argv) But when I execute the script, it is broken with following message: ./script.py: line 4: syntax error near unexpected token `(' ./script.py: line 4: `def main(sys_argv):' I am not sure what the problem is. Is it a problem with import? But when I try to import the module in ipython, everything is just ok.

    Read the article

  • Python os module path functions

    - by broiyan
    From the documentation: os.path.realpath(path) Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system). When I invoke this with an extant file's name, I get the path to it: /home/myhome/myproject. When I invoke this with a 'nonsense.xxx' string argument, I still get a path to /home/myhome/myproject/nonsense.xxx. This is a little inconsistent because it looks like nonsense.xxx is taken to be a directory not a file (though it is neither: it does not exist). When I invoke this with a null string file name, I still get a path to /home/myhome/myproject. How can I account for this behaviour when the documentation says so little about realpath()? (I am using Python 2.5.) Edit: Somebody suggested a way to test if files exist. My concern is not to test if files exist. My concern is to account for behaviour.

    Read the article

  • syntax error in python:

    - by pecker
    Hello, I'm learning python. It gives syntax error in this script. I'm unable to figure out. import exceptions class FOUND(Exception): pass x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89] while True: test = int(raw_input('Enter integer to be checked in list:')) try: count = -1 for y in x: count += 1 if y == test: raise FOUND except ValueError,e: print "Not a valid integer (%d)"%(e) except FOUND: print "Found (%d) at (%d)"%(test,count) else: print "Not found ,Appending (%d) to list at location (%d)"%(test,count+1) x.append(test) finally: print "The List:" print x print " " Invalid syntax & it highlights comma in this line: 'except ValueError,e:'

    Read the article

  • Python code that needs some overview

    - by fabio
    Hi guys, im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it. Today I created this code that should random trought 01 to 60 (but is running from 01 to 69) import random dez = ['0', '1', '2', '3', '4', '5', '6'] uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] sort = [] while len(sort) <= 5: random.shuffle(dez) random.shuffle(uni) w = random.choice(dez) z = random.choice(uni) chosen = str(w) + str(z) if chosen != "00" and chosen not in sort: sort.append(chosen) print chosen I'm also in doubt how to make the code stop at "60".

    Read the article

  • sampling integers uniformly efficiently in python using numpy/scipy

    - by user248237
    I have a problem where depending on the result of a random coin flip, I have to sample a random starting position from a string. If the sampling of this random position is uniform over the string, I thought of two approaches to do it: one using multinomial from numpy.random, the other using the simple randint function of Python standard lib. I tested this as follows: from numpy import * from numpy.random import multinomial from random import randint import time def use_multinomial(length, num_points): probs = ones(length)/float(length) for n in range(num_points): result = multinomial(1, probs) def use_rand(length, num_points): for n in range(num_points): rand(1, length) def main(): length = 1700 num_points = 50000 t1 = time.time() use_multinomial(length, num_points) t2 = time.time() print "Multinomial took: %s seconds" %(t2 - t1) t1 = time.time() use_rand(length, num_points) t2 = time.time() print "Rand took: %s seconds" %(t2 - t1) if __name__ == '__main__': main() The output is: Multinomial took: 6.58072400093 seconds Rand took: 2.35189199448 seconds it seems like randint is faster, but it still seems very slow to me. Is there a vectorized way to get this to be much faster, using numpy or scipy? thanks.

    Read the article

  • Python: Dynamic attribute name generation without exec() or eval()

    - by PyNewbie27
    Hi, I'm trying to dynamically create buttons at runtime with PyQT4.7 However, this being my first python program I'm not sure how to get the functionality I want. I would like to be able to substitute a text string for an attribute name: i.e. for each in xrange(4): myname = "tab1_button%s" % each #tab1_button0, tab1_button1, tab1_button2 #self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button #here's where I get stuck. this code isn't valid, but it shows what i want to do self.ui.gridLayout.addWidget(self.ui.%s) % myname #I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement? I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)

    Read the article

  • Reading a triangle of numbers into a 2d array of ints in Python

    - by Gabriel Silk
    I want to read a triangle of integer values from a file into a 2D array of ints using Python. The numbers would look like this: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 ... The code I have so far is as follows: f = open('problem18.input', 'r') arr = [] for i in range(0, 15): arr.append([]) str = f.readline() a = str.split(' ') for tok in a: arr[i].append(int(tok[:2])) print arr I have a feeling this could be done in a tighter, more Pythonesque way. How would you do it?

    Read the article

  • Python - question regarding the concurrent use of `multiprocess`.

    - by orokusaki
    I want to use Python's multiprocessing to do concurrent processing without using locks (locks to me are the opposite of multiprocessing) because I want to build up multiple reports from different resources at the exact same time during a web request (normally takes about 3 seconds but with multiprocessing I can do it in .5 seconds). My problem is that, if I expose such a feature to the web and get 10 users pulling the same report at the same time, I suddenly have 60 interpreters open at the same time (which would crash the system). Is this just the common sense result of using multiprocessing, or is there a trick to get around this potential nightmare? Thanks

    Read the article

  • Load JSON in Python as header chracterset

    - by mridang
    Hi everyone, I've always found character-sets and encodings complicated to understand and here I'm faced with another problem. My apologies for any inaccuracies. I'll do my best. I'm requesting data from a server which returns JSON. In the HTTP headers it also returns the character.set like so: Content-Type: text/html; charset=UTF-8 I'm using the JSON library in python to load the JSON using the json.loads method. When I pass it the returned JSON, it gives me a dictionary in Unicode. I've Googled around and I know that JSON should return Unicode as JavaScript strings are Unicode objects. How can I load the JSON as UTF-8. I would like to use the same encoding as specified in the response header. I've read this post but it didn't help. Thank you.

    Read the article

  • Simulating C-style for loops in python

    - by YGA
    (even the title of this is going to cause flames, I realize) Python made the deliberate design choice to have the for loop use explicit iterables, with the benefit of considerably simplified code in most cases. However, sometimes it is quite a pain to construct an iterable if your test case and update function are complicated, and so I find myself writing the following while loops: val = START_VAL while <awkward/complicated test case>: # do stuff ... val = <awkward/complicated update> The problem with this is that the update is at the bottom of the while block, meaning that if I want to have a continue embedded somewhere in it I have to: use duplicate code for the complicated/awkard update, AND run the risk of forgetting it and having my code infinite loop I could go the route of hand-rolling a complicated iterator: def complicated_iterator(val): while <awkward/complicated test case>: yeild val val = <awkward/complicated update> for val in complicated_iterator(start_val): if <random check>: continue # no issues here # do stuff This strikes me as waaaaay too verbose and complicated. Do folks in stack overflow have a simpler suggestion?

    Read the article

  • Python `.pth` files and using relative paths

    - by kRON
    I have a lot of development versions of packages installed with virtualenv under the default /src directory in the environment. Normally, I decided to do the development of my project under the /src directory afterwards. To add my directory to the Python path, I decided to eschew from using any absolute paths, since I'm going to have to move the project around with my friends. It's a Django application, so I was happy with putting environment.pth under the root that contained the path to my project and a wsgi in the same directory would call the sites module to parse environment.pth. All good. I was also looking to move the .pth file into site-packages, but I'm having trouble with relative paths that move up the directory tree. For: /env /lib /site-pacakges /src /myproject So, the .pth entry in site-packages to myproject should look like ../../src/myproject, but this doesn't seem to be working for me on Windows.

    Read the article

  • Instantiating a python class in C#

    - by Jekke
    I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class? The class looks (partially) like this: class PokerCard: "A card for playing poker, immutable and unique." def __init__(self, cardName): The test stub I wrote in C# is: using System; namespace pokerapp { class Program { static void Main(string[] args) { var card = new PokerCard(); // I also tried new PokerCard("Ah") Console.WriteLine(card.ToString()); Console.ReadLine(); } } } What do I have to do in order to instantiate this class in C#?

    Read the article

  • How to use OpenCV in Python?

    - by Roman
    I have just installed OpenCV on my Windows 7 machine. As a result I get a new directory: C:\OpenCV2.2\Python2.7\Lib\site-packages In this directory I have two files: cv.lib and cv.pyd. Then I try to use the opencv from Python. I do the following: import sys sys.path.append('C:\OpenCV2.2\Python2.7\Lib\site-packages') import cv As a result I get the following error message: File "<stdin>", line 1, in <module> ImportError: DLL load failed: The specified module could not be found. What am I doing wrong? ADDED As it was recommended here, I have copied content of C:\OpenCV2.0\Python2.6\Lib\site-packages to the C:\Python26\Lib\site-packages. It did not help.

    Read the article

  • Parsing files with python

    - by iHeartDucks
    My input file is going to be something like this key "value" key "value" ... the above lines repeat What I do is read the file contents, populate an object with the data and return it. There are only a set number of keys that can be present in the file. Since I am a beginner in python, I feel that my code to read the file is not that good My code is something like this ObjInstance = CustomClass() fields = ['key1', 'key2', 'key3'] for field in fields: for line in f: if line.find(field) >= 0: if pgn_field == 'key1': objInstance.DataOne = get_value_using_re(line) elif pgn_field == 'key2': objInstance.DataTwo = get_value_using_re(line) return objInstance; The function "get_value_using_re" is very simple, it looks for a string in between the double quotes and returns it. I fear that I will have multiple if elif statements and I don't know if this is the right way or not. Am I doing the right thing here?

    Read the article

  • Python command line UI

    - by hdx
    Hey guys/gals I'm writing a python script that fixes some duplicate issues on my database. I would like to display some progress status to the users, currently I just print it like this: print "Merged " + str(idx) + " out of " + str(totalCount); The problem is that it prints that in a new line for every record and that does not look so good :) I'd like to either always print the string above on the same line on the screen or use some smart widget that displays it in some sort of progress bar. I intent to run this on the command line, any suggestions will be much appreciated.

    Read the article

  • python - sys.argv and flag identification

    - by tekknolagi
    when I accept arguments how do I check if two show up at the same time without having a compound conditional i.e. #!/usr/bin/python import random, string import mymodule import sys z = ' '.join(sys.argv[2:]) q = ''.join(sys.argv[3:]) a = ''.join(sys.argv[2:]) s = ' '.join(sys.argv[1:]) flags = sys.argv[1:5] commands = [["-r", "reverse string passed next with no quotes needed."], ["-j", "joins arguments passed into string. no quotes needed."], ["--palindrome", "tests whether arguments passed are palindrome or not. collective."],["--rand","passes random string of 10 digits/letters"]] try: if "-r" in flags: if "-j" in flags: print mymodule.reverse(q) if not "-j" in flags: print mymodule.reverse(z) if "-j" in flags: if not "-r" in flags: print a if "--palindrome" in flags: mymodule.ispalindrome(z) if (not "-r" or not "-j" or not "--palindrome") in flags: mymodule.say(s) if "--rand" in flags: print(''.join([random.choice(string.ascii_letters+"123456789") for f in range(10)])) if not sys.argv[1]: print mymodule.no_arg_error if "--help" in flags: print commands except: print mymodule.no_arg_error i just want to be able to say if "-r" and "-j" in flags in no particular order: do whatever

    Read the article

  • List of IP addresses/hostnames from local network in Python

    - by joshhunt
    How can I get a list of the IP addresses or host names from a local network easily in Python? It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow. Edit: By local I mean all active addresses within a local network, such as 192.168.xxx.xxx. So, if the IP address of my computer (within the local network) is 192.168.1.1, and I have three other connected computers, I would want it to return the IP addresses 192.168.1.2, 192.168.1.3, 192.168.1.4, and possibly their hostnames.

    Read the article

  • float change from python 3.0.1 to 3.1.2

    - by Jeremy
    Im trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1 here is my code import urllib.request price = (99.99) while price 4.74: page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html") text = page.read().decode("utf8") where = text.find('>$') start_of_price = where + 2 end_of_price = start_of_price + 6 price = float(text[start_of_price:end_of_price]) print ("Buy!") - here is my error Traceback (most recent call last): File "/Users/odin/Desktop/Coffe.py", line 14, in price = float(text[start_of_price:end_of_price]) ValueError: invalid literal for float(): 4.59 what is wrong? please help!!

    Read the article

< Previous Page | 106 107 108 109 110 111 112 113 114 115 116 117  | Next Page >