Search Results

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

Page 114/548 | < Previous Page | 110 111 112 113 114 115 116 117 118 119 120 121  | Next Page >

  • Apply function to one element of a list in Python

    - by user189637
    I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python. For example, for the following input: inp = ("hello", "my", "friend") I would like to be able to get the following output: out = ("hello", "MY", "friend") I came up with two solutions which I'm not satisfied with. One uses a higher-order function. def apply_at(arr, func, i): return arr[0:i] + [func(arr[i])] + arr[i+1:] apply_at(inp, lambda x: x.upper(), 1) One uses list comprehensions (this one assumes the length of the tuple is known). [(a,b.upper(),c) for a,b,c in [inp]][0] Is there a better way? Thanks!

    Read the article

  • Find the min max and average of one column of data in python

    - by user1440194
    I have a set of data that looks like this 201206040210 -3461.00000000 -8134.00000000 -4514.00000000 -4394.00000000 0 201206040211 -3580.00000000 -7967.00000000 -4614.00000000 -7876.00000000 0 201206040212 -3031.00000000 -9989.00000000 -9989.00000000 -3419.00000000 0 201206040213 -1199.00000000 -6961.00000000 -3798.00000000 -5822.00000000 0 201206040214 -2940.00000000 -5524.00000000 -5492.00000000 -3394.00000000 0 I want to take the second to last column and find the min, max, and average. Im a little confused on how to use split when the columns are delimited by a space and -. i Figure once i do that i can use min() and max function. I have written a shell script to do the same here #!/bin/ksh awk '{print substr($5,2);}' data' > /data1 sort -n data1 > data2 tail -1 data2 head -1 data2 awk '{sum+=$1} END {print "average = ",sum/NR}' data2 Im just not sure how to do this in python. Thanks

    Read the article

  • How do I splice a python string programmatically?

    - by Robin Welch
    Very simple question, hopefully. So, in Python you can split up strings using indices as follows: >>> a="abcdefg" >>> print a[2:4] cd but how do you do this if the indices are based on variables? E.g. >>> j=2 >>> h=4 >>> print a[j,h] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: string indices must be integers

    Read the article

  • Counts of events grouped by date in python?

    - by Sologoub
    This is no doubt another noobish question, but I'll ask it anyways: I have a data set of events with exact datetime in UTC. I'd like to create a line chart showing total number of events by day (date) in the specified date range. Right now I can retrieve the total data set for the needed date range, but then I need to go through it and count up for each date. The app is running on google app engine and is using python. What is the best way to create a new data set showing date and corresponding counts (including if there were no events on that date) that I can then use to pass this info to a django template? Data set for this example looks like this: class Event(db.Model): event_name = db.StringProperty() doe = db.DateTimeProperty() dlu = db.DateTimeProperty() user = db.UserProperty() Ideally, I want something with date and count for that date. Thanks and please let me know if something else is needed to answer this question!

    Read the article

  • Python | How to create dynamic and expandable dictionaries

    - by MMRUser
    I want to create a Python dictionary which holds values in a multidimensional accept and it should be able to expand, this is the structure that the values should be stored :- userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','country':'USA'}]} Lets say I want to add another user def user_list(): users = [] for i in xrange(5, 0, -1): lonlatuser.append(('username','%s %s' % firstn, lastn)) lonlatuser.append(('age',age)) lonlatuser.append(('country',country)) return dict(user) This will only returns a dictionary with a single value in it (since the key names are same values will overwritten).So how do I append a set of values to this dictionary. Note: assume age, firstn, lastn and country are dynamically generated. Thanks.

    Read the article

  • How to create a glib.Source from Python?

    - by Matt Joiner
    I want to integrate some asyncore.dispatcher instances into GLib's default main context. I figure I can create a custom GSource that's able to detect event readiness on the various sockets in asyncore.socket_map. From C I believe this is done by creating the necessary GSourceFuncs which could involve cheap and non-blocking calls to select, and then handling them using asyncore.read, .write and friends. How do I actually create a GSource from Python? The class glib.Source is undocumented, and attempts to use the class interactively have been in vain. Is there some other method that allows me to handled socket events in the asyncore module without resorting to timeouts (or anything that endangers potential throughput and CPU usage)?

    Read the article

  • In python writing from XML to CSV, encoding error

    - by user574435
    Hi, I am trying to convert an XML file to CSV, but the encoding of the XML ("ISO-8859-1") apparently contains characters that are not in the ascii codec which Python uses to write rows. I get the error: Traceback (most recent call last): File "convert_folder_to_csv_PLAYER.py", line 139, in <module> xml2csv_PLAYER(filename) File "convert_folder_to_csv_PLAYER.py", line 121, in xml2csv_PLAYER fout.writerow(row) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128) I have tried opening the file as follows: dom1 = parse(input_filename.encode( "utf-8" ) ) and I have tried replacing the \xe1 character in each row before it is written. Any suggestions?

    Read the article

  • Python how to handle # in a dictionary

    - by Jack
    I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below. { "artist": "similar": { "artist": { "name": "Blah", "image": {"#text":"URLHERE","size": "small"} "image": {"#text":"URLHERE","size": "medium"} "image": {"#text":"URLHERE","size": "large"} } } } Any ideas how I can access the image urls of various different sizes. My attempts at accessing the #text variable don't seem to work because python doesn't appear to like #'s in the names. And any ideas how I can easily get the url for the depending on the size? Thanks, Jack

    Read the article

  • Read random lines from huge CSV file in Python

    - by jbssm
    I have this quite big CSV file (15 Gb) and I need to read about 1 million random lines from it. As far as I can see - and implement - the CSV utility in Python only allows to iterate sequentially in the file. It's very memory consuming to read the all file into memory to use some random choosing and it's very time consuming to go trough all the file and discard some values and choose others, so, is there anyway to choose some random line from the CSV file and read only that line? I tried without success: import csv with open('linear_e_LAN2A_F_0_435keV.csv') as file: reader = csv.reader(file) print reader[someRandomInteger] A sample of the CSV file: 331.093,329.735 251.188,249.994 374.468,373.782 295.643,295.159 83.9058,0 380.709,116.221 352.238,351.891 183.809,182.615 257.277,201.302 61.4598,40.7106

    Read the article

  • What are "named tuples" in Python?

    - by Denilson Sá
    Reading the changes in Python 3.1, I found something... unexpected: The sys.version_info tuple is now a named tuple: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I never expected they could be indexed both ways. Thus, my questions are: What are named tuples? How to use them? Why/when should I use named tuples instead of normal tuples? Why/when should I use normal tuples instead of named tuples? Is there any kind of "named list" (a mutable version of the named tuple)?

    Read the article

  • Python Parse CSV Correctly

    - by cornerstone
    I am very new to Python. I want to parse a csv file such that it will recognize quoted values - For example 1997,Ford,E350,"Super, luxurious truck" should be split as ('1997', 'Ford', 'E350', 'Super, luxurious truck') and NOT ('1997', 'Ford', 'E350', '"Super', ' luxurious truck"') the above is what I get if I use something like str.split(). How do I do this? Also would it be best to store these values in an array or some other data structure? because after I get these values from the csv I want to be able to easily choose, lets say any two of the columns and store it as another array or some other data structure. Thanks in advance.

    Read the article

  • Python win32api not moving mouse cursor in VirtualBox

    - by wes
    I'm trying to use this Python code: import math for i in xrange(500): x = 500 + math.sin(math.pi * i / 100) * 500 y = 500 + math.cos(i) * 100 x, y = int(x), int(y) win32api.SetCursorPos((x, y)) time.sleep(.01) taken from here to move the mouse cursor in an XP VirtualBox. The mouse icon will flicker to the appropriate graphic (when it hits the edge of a window it turns into the <- resize image, for instance), but it doesn't actually move the visible cursor. I can move the mouse around while the code is running. Same result using the ctypes example in the above link. It works fine in the Win7 host. I have Guest Additions installed, if that matters.

    Read the article

  • Python programming. Accessing Windows rigth click menu options

    - by Zack
    I'm hoping to automate a few tasks at work. One of them being combining and converting power point files to PDFs. I'm a bit of a newbie (I just finished Magus Heitland's Beginning Python), so I'm not entirely sure what I'm specifically asking. On windows, one can select multiple files, right click, and select combine as adobe PDF. I've figured out the 'grouping' of the files I want to convert (I traverse the dir and nest the files inside of a list based on their names), but I'm unsure how to pursue the next step (the rightclick/combine command). Googling has led me to things like win32api, pywinauto, and ctypes. But as I read over what they do my newbieness prevents me from knowing which is the tool I need. Could any one suggest a few good resources or tips?

    Read the article

  • Proper way to reload a python module from the console

    - by ensnare
    I'm debugging from the python console and would like to reload a module every time I make a change so I don't have to exit the console and re-enter it. I'm doing: >>> from project.model.user import * >>> reload(user) but I receive: >>>NameError: name 'user' is not defined What is the proper way to reload the entire user class? Is there a better way to do this, perhaps auto-updating while debugging? Thanks.

    Read the article

  • Need help understanding some Python code

    - by Yarin
    I'm new to Python, and stumped by this piece of code from the Boto project: class SubdomainCallingFormat(_CallingFormat): @assert_case_insensitive def get_bucket_server(self, server, bucket): return '%s.%s' % (bucket, server) def assert_case_insensitive(f): def wrapper(*args, **kwargs): if len(args) == 3 and not (args[2].islower() or args[2].isalnum()): raise BotoClientError("Bucket names cannot contain upper-case " \ "characters when using either the sub-domain or virtual " \ "hosting calling format.") return f(*args, **kwargs) return wrapper Trying to understand what's going on here. What is the '@' symbol in @assert_case_sensitive ? What do the args *args, **kwargs mean? What does 'f' represent? Thanks!

    Read the article

  • Rearrange a python list into n lists, by column

    - by Ben R
    Trying to solve this at this hour has gotten my mind into a tail-spin: I want to rearrange a list l into a list of n lists, where n is the number of columns. e.g., l = [1,2,3,4,5,6,7,8] n = 5 ==> [[1,6][2,7][3,8][4][5]] another example: l = [1,2,3,4,5,6,7,8,9,10] n = 4 ==> [[1,5,9],[2,6,10],[3,7][4,8] Can someone please help me out with an algorithm? Feel free to use any python awesomeness that's available; I'm sure theres some cool mechanism that's a good fit for this, i just can't think of it.

    Read the article

  • Python having problems writing/reading and testing in a correct format

    - by Ionut
    I’m trying to make a program that will do the following: check if auth_file exists if yes - read file and try to login using data from that file - if data is wrong - request new data if no - request some data and then create the file and fill it with requested data So far: import json import getpass import os import requests filename = ".auth_data" auth_file = os.path.realpath(filename) url = 'http://example.com/api' headers = {'content-type': 'application/json'} def load_auth_file(): try: f = open(auth_file, "r") auth_data = f.read() r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return auth_data else: print "Incorrect login..." req_auth() except IOError: f = file(auth_file, "w") f.write(req_auth()) f.close() def req_auth(): user = str(raw_input('Username: ')) password = getpass.getpass('Password: ') auth_data = (user, password) r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return user, password elif r.reason == "FORBIDDEN": print "Incorrect login information..." req_auth() return False I have the following problems(understanding and applying the correct way): I can't find a correct way of storing the returned data from req_auth() to auth_file in a format that can be read and used in load_auth file PS: Of course I'm a beginner in Python and I'm sure I have missed some key elements here :(

    Read the article

  • Dealing with Windows line-endings in Python

    - by Adam Nelson
    I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requiring opening the file ... which seems crazy) Using Universal newline support is not standard on my Mac Snow Leopard - so isn't an option. I'm open to anything that requires Python 2.6+ but it needs to work on Snow Leopard and Ubuntu 9.10 with minimal external requirements. I don't mind a small performance penalty but I am looking for the standard best way to deal with this.

    Read the article

  • Using Nose & NoseXUnit on a Python package

    - by Wraith
    This is a previous post detailing a CI setup for Python. The asker and answerer detail the use of Nose and NoseXUnit with Hudson for their builds. However, NoseXUnit throws an error when run on any source folder where init.py is present: File "build/bdist.linux-x86_64/egg/nosexunit/tools.py", line 59, in packages nosexunit.excepts.ToolError: following folder can not contain __init__.py file: /home/dev/source/web2py/applications I can't think of a source folder of mine that is not a package also. Is there a step I am missing when dealing with NoseXUnit?

    Read the article

  • Python CSV file processing

    - by kingwarchief
    I just got introduced to python, the first language I get to learn, and I have this question below: I have an excel based CSV file with two columns (or rows, Pythonically) that I am working on. What I need to do is to perform some operations so that I can compare the two data entries in each 'row'. To be more precise, one column has constant numbers all the way down, whereas the other column varies. So I need to count the number of times the varying column data entry values crosses the constant value on the other column. For example: Varying Column; Constant Column 24 25 26 25 crosses 27 25 26 25 25.5 25 23 25 crossed 26 25 crossed So in this case the number of times there is a cross

    Read the article

  • Summary count for Python logging

    - by Craig McQueen
    At the end of my Python program, I'd like to be able to get a summary of the number of items logged through the standard logging module. I'd specifically like to be able to get a count for each specified name (and possibly its children). E.g. if I have: input_logger = getLogger('input') input_logger.debug("got input1") input_logger.debug("got input2") input_logger.debug("got input3") network_input_logger = getLogger('input.network') network_input_logger.debug("got network input1") network_input_logger.debug("got network input2") getLogger('output') output_logger.debug("sent output1") Then at the end I'd like to get a summary such as: input: 5 input.network: 2 output: 1 Perhaps by calling a getcount() method for a logger or a handler. What would be a good way to achieve this? I imagine it would involve a sub-class of one of the logging classes, but I'm not sure which one would be best.

    Read the article

  • Python universal feedparser xml

    - by timg
    I am trying to read an xml feed with the python feedparser, but cannot seem to navigate the elements. Here is what I am trying: import feedparser d = feedparser.parse('http://www.website.com/feed') text= d.status.test and here is the xml: <?xml version="1.0" encoding="UTF-8"?> <statuses type="array"> <status> <created>Tue Dec 21 14:16:12 +0000 2010</created> <id>123</id> <text>Hello</text> </status> </statuses>

    Read the article

  • may be python error!!!

    - by bahar
    Hi I'm not familiar with python, I just want to check something so I tried to run a .py code in linux so I wrote : ./waf wifi-olsr-flowmon --plot which is a .py program after that whatever I want to run just see these error: /home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscript: error: Traceback (most recent call last): File "/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/.waf-1.5.16-e6d03192b5ddfa5ef2c8d65308e48e42/wafadmin/Utils.py", line 197, in load_module exec(compile(code,file_path,'exec'),module.__dict__) File "/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscript", line 32, in <module> import cflags # override the build profiles from waf ImportError: No module named cflags I dont know what does it mean or why it happened, would you please tell me what is the problem . Bests

    Read the article

  • Problems inserting file data into sqlite database using python

    - by tylerc230
    I'm trying to open an image file in python and add that data to an sqlite table. I created the table using: "CREATE TABLE "images" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "description" VARCHAR, "image" BLOB );" I am trying to add the image to the db using: imageFile = open(imageName, 'rb') b = sqlite3.Binary(imageFile.read()) targetCursor.execute("INSERT INTO images (image) values(?)", (b,)) targetCursor.execute("SELECT id from images") for id in targetCursor: imageid= id[0] targetCursor.execute("INSERT INTO %s (questionID,imageID) values(?,?)" % table, (questionId, imageid)) When I print the value of 'b' it looks like binary data but when I call: 'select image from images where id = 1' I get '????' printed to the console. Anyone know what I'm doing wrong?

    Read the article

  • Using Python simplejson for transmitting JSON to another server results in unicode encoding problems

    - by Mark
    Hi there, I'm encoding a string with Python's simplejson library with special characters: hello testing spécißl characters plusses: +++++ special chars :œ?´®†¥¨ˆøp“ß?ƒ©??°¬O˜çv?˜µ== However, when I encode it and transmit it to the other machine (using POST), it turns out like this: {'message': ['{"body": "hello testing sp\\u00e9ci\\u00dfl characters\\n\\nplusses: \\n\\nspecial chars :\\u0153\\u2211\\u00b4\\u00ae\\u2020\\u00a5\\u00a8\\u02c6\\u00f8\\u03c0\\u201c\\u00df\\u2202\\u0192\\u00a9\\u02d9\\u2206\\u02da\\u00ac\\u03a9\\u2248\\u00e7\\u221a\\u222b\\u02dc\\u00b5\\u2264\\u2265"}']} The + signs are completely stripped and the rest are in this unicode(?) format. My code for this is: data = {'body': data_string} data_encoded = json.dumps(data) Any ideas? Thanks! Edit: I've tried using json.dumps(data, ensure_ascii=False) but it results in a UnicodeError ordinal not in range error.

    Read the article

< Previous Page | 110 111 112 113 114 115 116 117 118 119 120 121  | Next Page >