Search Results

Search found 4955 results on 199 pages for 'range'.

Page 124/199 | < Previous Page | 120 121 122 123 124 125 126 127 128 129 130 131  | Next Page >

  • Python string manipulation

    - by paradox
    I'm trying to split a string into a int list for further processing. But somehow I can't remove certain whitespaces in between elements of the list. The string x is supposed to have a length of 1000 instead of 1019. I tried reading the documentation for python and saw the function strip() for stripping whitespaces from strings. However, it only works for trailing and leading whitespaces. How should I go about removing these whitespaces and also how do I convert a str list to a int list? My code is as follows : import array x = """73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450""" y=[] for i in range(0,len(x)): #String is now in a string list if x[i]!='': y.append(x[i]) print(y[i]) print(len(x))

    Read the article

  • Image 8-connectivity without excessive branching?

    - by shoosh
    I'm writing a low level image processing algorithm which needs to do alot of 8-connectivity checks for pixels. For every pixel I often need to check the pixels above it, below it and on its sides and diagonals. On the edges of the image there are special cases where there are only 5 or 3 neighbors instead of 8 neighbors for a pixels. The naive way to do it is for every access to check if the coordinates are in the right range and if not, return some default value. I'm looking for a way to avoid all these checks since they introduce a large overhead to the algorithm. Are there any tricks to avoid it altogether?

    Read the article

  • Lost in UTF-8 hell. (Django and Python)

    - by user140314
    I am working through the Django RSS reader project here. The RSS feed will read something like "OKLAHOMA CITY (AP) — James Harden let". The RSS feed's encoding reads encoding="UTF-8" so I believe I am passing utf-8 to markdown in the code snippet below. The em dash is where it chokes. I get the Django error of "'ascii' codec can't encode character u'\u2014' in position 109: ordinal not in range(128)" which is an UnicodeEncodeError. In the variables being passed I see "OKLAHOMA CITY (AP) \u2014 James Harden". The code line that is not working is: content = content.encode(parsed_feed.encoding, "xmlcharrefreplace") I am using markdown 2.0, django 1.1, and python 2.4. What is the magic sequence of encoding and decoding that I need to do to make this work? Thanks.

    Read the article

  • Capture Backspace , is this a OK solution?

    - by f0rz
    Hello, I having a hard time to capture the backspace button in a UITextView. I am trying to capture it in the method - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text I thought it was ok to do like this. if([text isEqualToString:@"\b") { // code ... } But for some reason, when backspace is pressed 'text' is empty. I know I can compare lenght of the UITextView but it isnt what I want to achieve. So I found a solution to this. If I look at '[text lenght]' every key on the defaultkeyboard returns 0 . Every key excepts the backspace wich is 0. In that way i know when backspace is pressed. I do this check. if([text lenght] == 0) { // BACKSPACE PRESSED   } What is your opinion about this? -or can I do it in a better way? Regards. - Martin

    Read the article

  • How can I process command line arguments in Python?

    - by photographer
    What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that: if 'debug' in argv[1:]: print 'Will be running in debug mode.' How to find out if 009 or 575 was passed? All those are expected calls: python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf At this point I don't care about calls like that: python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 ...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.

    Read the article

  • C# int to byte[]

    - by Petoj
    If I need to convert an int to byte[] I could use Bitconvert.GetBytes(). But if I should follow this: An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows: Taken from RFC1014 3.2. What method should I use then if there is no method to do this? How would it look like if you write your own? I don't understand the text 100% so I can't implement it on my own.

    Read the article

  • Text encoding problem between NSImage, NSData, and NSXMLDocument

    - by andyvn22
    I'm attempting to take an NSImage and convert it to a string which I can write in an XML document. My current attempt looks something like this: [xmlDocument setCharacterEncoding: @"US-ASCII"]; NSData* data = [image TIFFRepresentation]; NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; //Put string inside of NSXMLElement, write out NSXMLDocument. Reading back in looks something like this: NSXMLDocument* newXMLDocument = [[NSXMLDocument alloc] initWithData:data options:0 error:outError]; //Here's where it fails. I get: //Error Domain=NSXMLParserErrorDomain Code=9 UserInfo=0x100195310 "Line 7: Char 0x0 out of allowed range" I assume I'm missing something basic. What's up with this encoding issue?

    Read the article

  • Timeline graph - how to handle "time gaps"?

    - by ebae
    I've been working with Google chart API and annotated timeline. Drawing graphs is fine. I have no problem. However, I need to draw a timeline graph for share prices. And as you may know, share prices are meaningful only between certain times (e.g. from 10AM to 4PM, when the market opens and closes). How do I change the Google timeline graph so that on X-Axis, the range is from 10AM-4PM? Right now, it just draws a long constant line between 4PM till 10AM next day before prices start to move again. Man, I hope that makes sens. (Google finance chart seems to do it). Thank you SO much for whoever can answer. You are a CHAMPION!

    Read the article

  • Discrete and Continuous Classifier on Sparse Data

    - by Chris S
    I'm trying to classify an example, which contains discrete and continuous features. Also, the example represents sparse data, so even though the system may have been trained on 100 features, the example may only have 12. What would be the best classifier algorithm to use to accomplish this? I've been looking at Bayes, Maxent, Decision Tree, and KNN, but I'm not sure any fit the bill exactly. The biggest sticking point I've found is that most implementations don't support sparse data sets and both discrete and continuous features. Can anyone recommend an algorithm and implementation (preferably in Python) that fits these criteria? Libraries I've looked at so far include: Orange (Mostly academic. Implementations not terribly efficient or practical.) NLTK (Also academic, although has a good Maxent implementation, but doesn't handle continuous features.) Weka (Still researching this. Seems to support a broad range of algorithms, but has poor documentation, so it's unclear what each implementation supports.)

    Read the article

  • pythonic way to associate list elements with their indices

    - by Dragan Chupacabrovic
    Hello Everybody, I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more elegant. I've come across the following, but it does the opposite of what I need: >>> d = dict(enumerate(t)) >>> d {0: 5, 1: 6, 2: 7} Please share your solutions, Thank you

    Read the article

  • exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore th

    - by gatoatigrado
    Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very much! python -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('?????')" returns Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/codecs.py", line 686, in write return self.writer.write(data) File "/usr/lib/python2.6/codecs.py", line 351, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

    Read the article

  • problem plotting on logscale in matplotlib in python

    - by user248237
    I am trying to plot the following numbers on a log scale as a scatter plot in matplotlib. Both the quantities on the x and y axes have very different scales, and one of the variables has a huge dynamic range (nearly 0 to 12 million roughly) while the other is between nearly 0 and 2. I think it might be good to plot both on a log scale. I tried the following, for a subset of the values of the two variables: fig = plt.figure(figsize(8, 8)) ax = fig.add_subplot(1, 1, 1) ax.set_yscale('log') ax.set_xscale('log') plt.scatter([1.341, 0.1034, 0.6076, 1.4278, 0.0374], [0.37, 0.12, 0.22, 0.4, 0.08]) The x-axes appear log scaled but the points do not appear -- only two points appear. Any idea how to fix this? Also, how can I make this log scale appear on a square axes, so that the correlation between the two variables can be interpreted from the scatter plot? thanks.

    Read the article

  • Select from mysql by day with different timezones (php)

    - by Adam
    I'm storing leads in a database, and each lead has a datetime field with a PST timezone based date & time. I want my user to be able to display all leads from a certain date (e.g. today, yseterday), and choose the timezone. E.g. if I want to see all leads that were generated yesterday in EST timezone, I need to first convert (or read) all the datetime values to EST, and then only select those who are in the right range (yesterday). What would be the best way to do that?

    Read the article

  • Python thread pool similar to the multiprocessing Pool?

    - by Martin
    Is there a Pool class for worker threads, similar to the multiprocessing module's Pool class? I like for example the easy way to parallelize a map function def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Pool(4) xs = p.map(long_running_func, range(100)) however I would like to do it without the overhead of creating new processes. I know about the GIL. However, in my usecase, the function will be an IO-bound C function for which the python wrapper will release the GIL before the actual function call. Do I have to write my own threading pool?

    Read the article

  • twitter api is throwing exception "# is not a valid value for Int32" while getting freinds

    - by vakas
    i am using the api twitterizer.framework while getting the friends of a user the api starts throwing this error. "# is not a valid value for Int32. --- System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex at System.ParseNumbers.StringToInt(String s, Int32 radix, Int32 flags, Int32* currPos) at System.Convert.ToInt32(String value, Int32 fromBase) at System.ComponentModel.Int32Converter.FromString(String value, Int32 radix) at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) --- End of inner exception stack trace --- at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.ComponentModel.TypeConverter.ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, String text) at System.Drawing.ColorConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.ComponentModel.TypeConverter.ConvertFromString(String text) at System.Drawing.ColorTranslator.FromHtml(String htmlColor) at Twitterizer.Framework.TwitterRequest.ParseUserNode(XmlNode element) in C:\Projects\twitterizer\Twiterizer.Framework\TwitterRequest.cs:line 514 at Twitterizer.Framework.TwitterRequest.ParseUsers(XmlElement element) in C:\Projects\twitterizer\Twiterizer.Framework\TwitterRequest.cs:line 483 at Twitterizer.Framework.TwitterRequest.ParseResponseData(TwitterRequestData data) in C:\Projects\twitterizer\Twiterizer.Framework\TwitterRequest.cs:line 305" how to handle this?

    Read the article

  • Do you know a good and efficient FFT?

    - by yan bellavance
    Hi, I am trying to find a very fast and efficient Fourier transform (FFT). Does anyone know of any good ones. I need to run it on the iPhone so it must not be intensive. Instead, maybe you know of one that is wavelet like, i need frequency resolution but only a narrow band (vocal audio range up to 10khz max...even 10Khz might be too high). Im thinking also of truncating this FFT to keep the frequency resolution while eliminating the unwanted frequency band. This is for an iphone ...I have taken a look at the FFT in Aurio touch but it seems this is an int FFT but my app uses floats.....would it give a big performance increase to try and adapt program to an int FFT or not(which i really dont feel like doing...plus aurio touch uses a radix 2 FFT which is not that great).

    Read the article

  • Java playback of 24 bit audio is incorrect

    - by Paul Hampson
    I am using the javax sound API to implement a simple console playback program based on http://www.jsresources.org/examples/AudioPlayer.html. Having tested it using a 24 bit ramp file (each sample is the last sample plus 1 over the full 24 bit range) it is evident that something odd is happening during playback. The recorded output is not the contents of the file (I have a digital loopback to verify this). It seems to be misinterpreting the samples in some way that causes the left channel to look like it is having some gain applied to it and the right channel looks like it is being attenuated. I have looked into whether the PAN and BALANCE controls need setting but these aren't available and I have checked the windows xp sound system settings. Any other form of playback of this ramp file is fine. If I do the same test with a 16bit file it performs correctly with no corruption of the stream. So does anyone have any idea why the Java Sound API is modifying my audio stream?

    Read the article

  • How to use unicode inside an xpath string? (UnicodeEncodeError)

    - by Gj
    I'm using xpath in Selenium RC via the Python api. I need to click an a element who's text is "Submit »" Here's the error that I'm getting: In [18]: sel.click(u"xpath=//a[text()='Submit \xbb')]") ERROR: An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line statement', (1121, 0)) --------------------------------------------------------------------------- Exception Traceback (most recent call last) /Users/me/<ipython console> in <module>() /Users/me/selenium.pyc in click(self, locator) 282 'locator' is an element locator 283 """ --> 284 self.do_command("click", [locator,]) 285 286 /Users/me/selenium.pyc in do_command(self, verb, args) 213 #print "Selenium Result: " + repr(data) + "\n\n" 214 if (not data.startswith('OK')): --> 215 raise Exception, data 216 return data 217 <type 'str'>: (<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u"ERROR: Invalid xpath [2]: //a[text()='Submit \xbb')]", 45, 46, 'ordinal not in range(128)'))

    Read the article

  • Python: Retrieve Image from MSSQL

    - by KoRkOnY
    Dear All, I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('<ServerIP>','<UserID>','<Password>') mssql.select_db('<Database>') x=1 while x==1: query="select TOP 1 * from table;" if mssql.query(query): rows=mssql.fetch_array() rowNumbers = rows[0][1] #print "Number of rows fetched: " + str(rowNumbers) for row in rows: for i in range(rowNumbers): FILE=open('/home/images/' + str(row[2][i][1]) + '-' + str(row[2][i][2]).strip() + ' (' + str(row[2][i][0]) + ').jpg','wb') FILE.write(row[2][i][4]) FILE.close() print 'Successfully downloaded image: ' + str(row[2][i][0]) + '\t' + str(row[2][i][2]).strip() + '\t' + str(row[2][i][1]) else: print mssql.errmsg() print mssql.stdmsg() mssql.close()

    Read the article

  • Entity framework error: The conversion of a datetime2 data type to a datetime data

    - by EdenMachine
    I know there are a ton of posts about this issue but none of them seem to solve my problem. Here's the scenario: I have a CreateDate DateTime column in my MS SQL Server database User table that is non-nullable and is automatically set using GetDate() method in "Default Value or Binding" setting. I am able to create a User just fine with the standard EF Insert but when I try to update the user, I get this error: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. What is the trick to not having the EF worry about the CreateDate column for updates? I have the StoreGenerationPattern = Identity but that isn't helping. Here are the EF properties for my Entity Property: http://screencast.com/t/8ndQRn9N And here is my Update method: http://screencast.com/t/UXIzhkhR

    Read the article

  • PyQt4 Move QTableWidget row with widgets

    - by Guard
    I have the following method in my PyQt4 app. r2 is the number of row to move, and r1 is the position where it should be moved. To clarify: the table is filled with cellWidgets, not widgetItems. def move_row(self, r1, r2): tt = self.tableWidget tt.insertRow(r1) for c in range(tt.columnCount()): tt.setCellWidget(r1, c, tt.cellWidget(r2 + 1, c)) tt.removeRow(r2 + 1) # <--- ??? If I comment out the last line, it behaves as expected: the new row is inserted at position r1, it is filled with widgets from r2 (now it's r2+1), and the r2+1 row is empty. If I even hide this row, it behaves well, though it is not what I want (I have the rows numbered, and I don't want this hidden row to occupy the number). But if I remove the row, the widgets initially owned by it disappear. Looks like their ownership is taken on first placement, and is not changed after the move. Any ideas?

    Read the article

  • How to catch FTP errors? e.g., socket.error: [Errno 10060]

    - by Johnson
    I'm using the ftplib module to upload files: files = [ a.txt , b.txt , c.txt ] s = ftplib.FTP(ftp_server , ftp_user , ftp_pw) # Connect to FTP for i in range(len(files)): f = open(files[i], 'rb') stor = 'stor ' + files[i] s.storbinary(stor, f) f.close() # close file s.quit() # close ftp How do I catch the following error? socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond And what other errors are common when using the FTP module that I should also catch? Thanks for any help or pointers.

    Read the article

  • NSNumber >= 13 won't retain. Everything else will.

    - by jkap
    The code I'm currently working on requires adding an NSNumber object to an array. All of the NSNumbers with value 0-12 are added fine, but 13 onward causes a EXC_BAD_ACCESS. I turned on NSZombieEnabled and am now getting *** -[CFNumber retain]: message sent to deallocated instance 0x3c78420. Here's the call stack: #0 0x01eac3a7 in ___forwarding___ #1 0x01e886c2 in __forwarding_prep_0___ #2 0x01e3f988 in CFRetain #3 0x01e4b586 in _CFArrayReplaceValues #4 0x0002a2f9 in -[NSCFArray insertObject:atIndex:] #5 0x0002a274 in -[NSCFArray addObject:] #6 0x00010a3b in -[Faves addObject:] at Faves.m:24 #7 0x000062ff in -[ShowController processFave] at ShowController.m:458 #8 0x002af405 in -[UIApplication sendAction:to:from:forEvent:] #9 0x00312b4e in -[UIControl sendAction:to:forEvent:] #10 0x00314d6f in -[UIControl(Internal) _sendActionsForEvents:withEvent:] #11 0x00313abb in -[UIControl touchesEnded:withEvent:] #12 0x002c8ddf in -[UIWindow _sendTouchesForEvent:] #13 0x002b27c8 in -[UIApplication sendEvent:] #14 0x002b9061 in _UIApplicationHandleEvent #15 0x02566d59 in PurpleEventCallback #16 0x01e83b80 in CFRunLoopRunSpecific #17 0x01e82c48 in CFRunLoopRunInMode #18 0x02565615 in GSEventRunModal #19 0x025656da in GSEventRun #20 0x002b9faf in UIApplicationMain #21 0x00002498 in main at main.m:14 If it wasn't isolated to NSNumbers of a certain range, I'd assume I screwed something up with my memory management, but I've just got no idea. Any ideas? Thanks, Josh

    Read the article

  • Getting the Value of a UITextField as keystrokes are entered?

    - by Nocturne
    Let's say I have the following code: IBOutlet UITextField* nameTextField; IBOutlet UILabel* greetingLabel; I'd like the greetingLabel to read "Hello [nameTextField]" as soon as the user presses any key. What I need basically is the iPhone equivalent of the Cocoa delegate method -controlTextDidChange: The -textField:shouldChangeCharactersInRange: delegate method is called each time a keystroke occurs: - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string The string argument returns the character that is pressed. The actual textField's value (nameTextField.text) remains blank however. What am I missing here? (I'd like nameTextField to reflect the exact string that the user has entered so far)

    Read the article

  • software/languages for online structured data collection from (human) clients

    - by Ben
    I need to develop a web interface to collect and validate a range of data from many of my organization's clients. This isn't a single form, but a collection of forms with interdependencies (i.e., field X on form Y is needed if field A was equal to C on form B), and variable length lists (please provide the details for all Xs in your possession). I had a look at the marketing on Microsoft InfoPath and Adobe LiveCycle, but I get the impression that they're principally electronic forms solutions rather than data collection tools. (e.g., If a user has entered their address once, they should never have to see it on a form again). Any suggestions of good tools, applications or domain-specific languages?

    Read the article

< Previous Page | 120 121 122 123 124 125 126 127 128 129 130 131  | Next Page >