Search Results

Search found 3176 results on 128 pages for 'parsing'.

Page 64/128 | < Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >

  • Approaches to create a nested tree structure of NSDictionaries?

    - by d11wtq
    I'm parsing some input which produces a tree structure containing NSDictionary instances on the branches and NSString instance at the nodes. After parsing, the whole structure should be immutable. I feel like I'm jumping through hoops to create the structure and then make sure it's immutable when it's returned from my method. We can probably all relate to the input I'm parsing, since it's a query string from a URL. In a string like this: a=foo&b=bar&a=zip We expect a structure like this: NSDictionary { "a" => NSDictionary { 0 => "foo", 1 => "zip" }, "b" => "bar" } I'm keeping it just two-dimensional in this example for brevity, though in the real-world we sometimes see var[key1][key2]=value&var[key1][key3]=value2 type structures. The code hasn't evolved that far just yet. Currently I do this: - (NSDictionary *)parseQuery:(NSString *)queryString { NSMutableDictionary *params = [NSMutableDictionary dictionary]; NSArray *pairs = [queryString componentsSeparatedByString:@"&"]; for (NSString *pair in pairs) { NSRange eqRange = [pair rangeOfString:@"="]; NSString *key; id value; // If the parameter is a key without a specified value if (eqRange.location == NSNotFound) { key = [pair stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; value = @""; } else { // Else determine both key and value key = [[pair substringToIndex:eqRange.location] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; if ([pair length] > eqRange.location + 1) { value = [[pair substringFromIndex:eqRange.location + 1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; } else { value = @""; } } // Parameter already exists, it must be a dictionary if (nil != [params objectForKey:key]) { id existingValue = [params objectForKey:key]; if (![existingValue isKindOfClass:[NSDictionary class]]) { value = [NSDictionary dictionaryWithObjectsAndKeys:existingValue, [NSNumber numberWithInt:0], value, [NSNumber numberWithInt:1], nil]; } else { // FIXME: There must be a more elegant way to build a nested dictionary where the end result is immutable? NSMutableDictionary *newValue = [NSMutableDictionary dictionaryWithDictionary:existingValue]; [newValue setObject:value forKey:[NSNumber numberWithInt:[newValue count]]]; value = [NSDictionary dictionaryWithDictionary:newValue]; } } [params setObject:value forKey:key]; } return [NSDictionary dictionaryWithDictionary:params]; } If you look at the bit where I've added FIXME it feels awfully clumsy, pulling out the existing dictionary, creating an immutable version of it, adding the new value, then creating an immutable dictionary from that to set back in place. Expensive and unnecessary? I'm not sure if there are any Cocoa-specific design patterns I can follow here?

    Read the article

  • What is the difference between LR, SLR, and LALR parsers?

    - by equilibrium
    What is the actual difference between LR, SLR, and LALR parsers? I know that SLR and LALR are types of LR parsers, but what is the actual difference as far as their parsing tables are concerned? And how to show whether a grammar is LR, SLR, or LALR? For an LL grammar we just have to show that any cell of the parsing table should not contain multiple production rules. Any similar rules for LALR, SLR, and LR? For example, how can we show that the grammar S --> Aa | bAc | dc | bda A --> d is LALR(1) but not SLR(1)?

    Read the article

  • GWT's JSONParser producing incorrect values for numbers.

    - by WesleyJohnson
    I'm work with GWT and parsing a JSON result from an ASP.NET webservice method that returns a DataTable. I can parse the result into a JSONvalue/JSONObject just fine. The issue I'm having is that one my columns in a DECIMAL(20, 0) and the values that are getting parsed into JSON aren't exact. To demonstrate w/o the need for a WS call, in GWT I threw this together: String jsonString = "{value:4768428229311981600}"; JSONObject jsonObject = JSONParser.parse( jsonString ).isObject(); Window.alert( jsonObject.toString() ); This in turn alerts: {"value":4768428229311982000} I'm under the understanding that GWT's JSONParser is just using eval() to do the parsing, so is this some sort of number/precision issue with JavaScript that I've never been aware of. I'll admit I don't work with numbers that much in JavaScript and I might be able to work around this by changing the .NET WebService to return this column as string, but I'd really rather not do that. Thanks for any help.

    Read the article

  • XPATH - Select all child nodes with a specific attribute

    - by David
    Hi, what would be the xpath for the following: Find all child nodes with a specific attibute value but starting from a node with a specific attribute value. This is kind of related to a question I posted earlier about parsing and rdf xml file - I thought I had solved it but not quite yet. For example I am trying to parse and grab all of the rdf:about attribute values. I have this working fine. I need to add the following condition though - parsing needs to start after a specific rdf:about value is found. I am working in php and and using DomDocument and am using the following xpath query: $xpath-query('//@rdf:about') - it is finding all rdf:about attributes fine. I need to extend this to only find thos attributes that come after the node who rdf:about attribute is equal to something. Hope this makes sense.

    Read the article

  • Threading extra state through a parser in Scala

    - by Travis Brown
    I'll give you the tl;dr up front I'm trying to use the state monad transformer in Scalaz 7 to thread extra state through a parser, and I'm having trouble doing anything useful without writing a lot of t m a -> t m b versions of m a -> m b methods. An example parsing problem Suppose I have a string containing nested parentheses with digits inside them: val input = "((617)((0)(32)))" I also have a stream of fresh variable names (characters, in this case): val names = Stream('a' to 'z': _*) I want to pull a name off the top of the stream and assign it to each parenthetical expression as I parse it, and then map that name to a string representing the contents of the parentheses, with the nested parenthetical expressions (if any) replaced by their names. To make this more concrete, here's what I'd want the output to look like for the example input above: val target = Map( 'a' -> "617", 'b' -> "0", 'c' -> "32", 'd' -> "bc", 'e' -> "ad" ) There may be either a string of digits or arbitrarily many sub-expressions at a given level, but these two kinds of content won't be mixed in a single parenthetical expression. To keep things simple, we'll assume that the stream of names will never contain either duplicates or digits, and that it will always contain enough names for our input. Using parser combinators with a bit of mutable state The example above is a slightly simplified version of the parsing problem in this Stack Overflow question. I answered that question with a solution that looked roughly like this: import scala.util.parsing.combinator._ class ParenParser(names: Iterator[Char]) extends RegexParsers { def paren: Parser[List[(Char, String)]] = "(" ~> contents <~ ")" ^^ { case (s, m) => (names.next -> s) :: m } def contents: Parser[(String, List[(Char, String)])] = "\\d+".r ^^ (_ -> Nil) | rep1(paren) ^^ ( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String) = parseAll(paren, s).map(_.toMap) } It's not too bad, but I'd prefer to avoid the mutable state. What I want Haskell's Parsec library makes adding user state to a parser trivially easy: import Control.Applicative ((*>), (<$>), (<*)) import Data.Map (fromList) import Text.Parsec paren = do (s, m) <- char '(' *> contents <* char ')' h : t <- getState putState t return $ (h, s) : m where contents = flip (,) [] <$> many1 digit <|> (\ps -> (map (fst . head) ps, concat ps)) <$> many1 paren main = print $ runParser (fromList <$> paren) ['a'..'z'] "example" "((617)((0)(32)))" This is a fairly straightforward translation of my Scala parser above, but without mutable state. What I've tried I'm trying to get as close to the Parsec solution as I can using Scalaz's state monad transformer, so instead of Parser[A] I'm working with StateT[Parser, Stream[Char], A]. I have a "solution" that allows me to write the following: import scala.util.parsing.combinator._ import scalaz._, Scalaz._ object ParenParser extends ExtraStateParsers[Stream[Char]] with RegexParsers { protected implicit def monadInstance = parserMonad(this) def paren: ESP[List[(Char, String)]] = (lift("(" ) ~> contents <~ lift(")")).flatMap { case (s, m) => get.flatMap( names => put(names.tail).map(_ => (names.head -> s) :: m) ) } def contents: ESP[(String, List[(Char, String)])] = lift("\\d+".r ^^ (_ -> Nil)) | rep1(paren).map( ps => ps.map(_.head._1).mkString -> ps.flatten ) def parse(s: String, names: Stream[Char]) = parseAll(paren.eval(names), s).map(_.toMap) } This works, and it's not that much less concise than either the mutable state version or the Parsec version. But my ExtraStateParsers is ugly as sin—I don't want to try your patience more than I already have, so I won't include it here (although here's a link, if you really want it). I've had to write new versions of every Parser and Parsers method I use above for my ExtraStateParsers and ESP types (rep1, ~>, <~, and |, in case you're counting). If I had needed to use other combinators, I'd have had to write new state transformer-level versions of them as well. Is there a cleaner way to do this? I'd love to see an example of a Scalaz 7's state monad transformer being used to thread state through a parser, but Scala 6 or Haskell examples would also be useful.

    Read the article

  • Background job with status in rails

    - by pepernik
    Hey. I would like to upload a file and then parse it. Because parsing can take up to 10min I installed delayed_job plugin and called parsing function through send_later function. I have to mention that this is an AJAX app. Imagine that you press an AJAX button that starts upload and after that the source is imported into the database. During the process I want to show the progress bar or message (importing...) and when it completes the task status changes to done. My question is: What is the best way to check for status of the process. What would you do? My idea is to have another controller actions "status" which look into the database and provide the right status.

    Read the article

  • What's my best bet for replacing plain text links with anchor tags in a string? .NET

    - by Craig Bovis
    What is my best option for converting plain text links within a string into anchor tags? Say for example I have "I went and searched on http://www.google.com/ today". I would want to change that to "I went and searched on http://www.google.com/ today". The method will need to be safe from any kind of XSS attack also since the strings are user generated. They will be safe before parsing so I just need to make sure that no vulnerabilities are introduced through parsing the URLs.

    Read the article

  • How can I programmatically read a Adobe DRM'd Epub?

    - by DEzra
    I am writing an ebook reader that supports the epub format (i have the parsing of open epub working), but I would like to support the reading of Adobe DRM locked epubs. I have read through the Adobe digital editions site (faq and support pages) and googled, but alas as yet I have not found any docs on the API to: authorise the PC using the user's Adobe ID credentials and decrypt the epub for parsing by my app. Does anyone have any pointers to docs or APIs? I would prefer APIs in Python, C++. But any API is better than nothing ;-) UPDATE1: I am writing my app on Desktops (linux, mac and windows). UPDATE2: Just to be clear, I am assuming that user has paid for the book legitimately and so does have an Adobe ID. I don't want to crack the DRM, just allow the user to read their books that they bought.

    Read the article

  • Output to jTextArea in realtime

    - by Robert
    I have some code which takes a few minutes to process, it has to connect to the web for each string in a long array, each string is a url. I want to make it so that everytime it connects, it should refresh the jtextarea so that the user is not staring into a blank page that looks frozen for 20 min. or however long it takes. here is an example of something i tried and didnt work: try { ArrayList<String> myLinks = LinkParser.getmyLinksArray(jTextArea1.getText()); for (String s : myLinks) { jTextArea2.append(LinkChecker.checkFileStatus(s) + "\n"); } } catch (IOException ex) { JOptionPane.showMessageDialog(jTextArea1, "Parsing Error", "Parsing Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(MYView.class.getName()).log(Level.SEVERE, null, ex); }

    Read the article

  • Lazy Tables app from iphone

    - by Warrior
    I am new to iphone development. I have parsed a youtube file and displaying its contents with the image in the table view. But the scrolling has become slower because of displaying image.So i want to display the image as the lazy tables program from apple docs.Since they have used navigation based application , their rootviewcontroller loads first and then the delegate class call the parsing ,and when they reload the table view, the contents are displayed. The data array count shows 25. I am using a view controller to display the tables on the present modal view, more over when i run my application, first delegate methods call the parsing. So when i click the youtube icon in my landing page it navigates to table view. So by this time data array count shows 0. I have created table view in interface builder and set the outlets to the file owner properly. Please help me out. I want to increasing the scrolling performance. Thanks.

    Read the article

  • Can .NET load and parse a properties file equivalent to Java Properties class?

    - by Tai Squared
    Is there an easy way in C# to read a properties file that has each property on a separate line followed by an equals sign and the value, such as the following: ServerName=prod-srv1 Port=8888 CustomProperty=Any value In Java, the Properties class handles this parsing easily: Properties myProperties=new Properties(); FileInputStream fis = new FileInputStream (new File("CustomProps.properties")); myProperties.load(fis); System.out.println(myProperties.getProperty("ServerName")); System.out.println(myProperties.getProperty("CustomProperty")); I can easily load the file in C# and parse each line, but is there a built in way to easily get a property without having to parse out the key name and equals sign myself? The C# information I have found seems to always favor XML, but this is an existing file that I don't control and I would prefer to keep it in the existing format as it will require more time to get another team to change it to XML than parsing the existing file.

    Read the article

  • How can I programmatically find the IP address/netmask/gateway configured for a specific network dev

    - by Oren S
    Hi I would like to write a piece of code which checks, for each network device (e.g. eth0, lo, master devices) some statistics and configuration data about that device. I could find the statistics data (and most of the configuration data) in /sys/class/net/..., however, I couldn't find any C/C++ API or any entry in procfs/sysfs listing the inet addr, netmask and gateway. Some alternatives I checked: parsing the output from ifconfig/route/some other utilities: I don't want to start a subprocess every time I need to do the inspection. parsing /etc/sysconfig/network-scripts/: will give me only the start-up configuration, and not the current state. Also, since this code is intended for a product in my workplace, where every external library is inspected thoroughly (meaning it will take me forever to add any external library) I prefer solutions which rely on Linux native API and not external libraries. Thanks!

    Read the article

  • How do I generate different yyparse functions from lex/yacc for use in the same program?

    - by th
    Hi, I want to generate two separate parsing functions from lex/yacc. Normally yacc gives you a function yyparse() that you can call when you need to do some parsing, but I need to have several different yyparses each associated with different lexers and grammars. The man page seems to suggest the -p (prefix) flag, but this didn't work for me. I got errors from gcc that indicated that yylval was not properly being relabeled (i.e. it claims that several different tokens are not defined). Does anyone know the general rpocedure for generating these separate functions? thanks

    Read the article

  • recommended parser for XML in java(absolute beginner to xml)

    - by poeschlorn
    Hi Pro's, which parser (java) would you recommend for parsing GPX data? Im looking for a one that is very intuitive to use and should not need too much RAM (it seems that DOM requires too much, doesn't it?). I have no idea about parsing xml, so it is time for me to learn this ;-) My documents are not very huge and are always read twice(a point for DOM), but I don't want to keep as few things as possible in RAM. What would you do in this situation? Which one would you coose and why?

    Read the article

  • Which Python XML library should I use?

    - by PulpFiction
    Hello. I am going to handle XML files for a project. I had earlier decided to use lxml but after reading the requirements, I think ElemenTree would be better for my purpose. The XML files that have to be processed are: Small in size. Typically < 10 KB. No namespaces. Simple XML structure. Given the small XML size, memory is not an issue. My only concern is fast parsing. What should I go with? Mostly I have seen people recommend lxml, but given my parsing requirements, do I really stand to benefit from it or would ElementTree serve my purpose better?

    Read the article

  • Best practices retrieving XML/stream from HTTP in Android

    - by Jeffrey
    Hello everyone, what are the best practices parsing XML from an HTTP resource in Android? I've been using HttpURLConnection to retrieve an InputStream, wrapping it with a BufferedInputStream, and then using SAX to parse the buffered stream. For the most part it works, though I do receive error reports of SocketTimeoutException: The operation timed out or general parsing error. I believe it's due to the InputStream. Would using HttpClient instead of HttpURLConnection help? If yes, why? Should the stream be output to a file, having the file parsed instead of the stream? Any input or direction would be greatly appreciated. Thanks for your time.

    Read the article

  • datetime command line argument in python 2.4

    - by Ike Walker
    I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, which doesn't have datetime.strptime. How can I pass the datetime value to the script in python 2.4? Here's the code I'm using in 2.6: parser = optparse.OptionParser() parser.add_option("-m", "--max_timestamp", dest="max_timestamp", help="only aggregate items older than MAX_TIMESTAMP", metavar="MAX_TIMESTAMP(YYYY-MM-DD HH24:MM)") options,args = parser.parse_args() if options.max_timestamp: # Try parsing the date argument try: max_timestamp = datetime.datetime.strptime(options.max_timestamp, "%Y-%m-%d %H:%M") except: print "Error parsing date input:",sys.exc_info() sys.exit(1)

    Read the article

  • How to implement buffering with timeout in RX

    - by Gaspar Nagy
    I need to implement an event processing, that is done delayed when there are no new events arriving for a certain period. (I have to queue up a parsing task when the text buffer changed, but I don't want to start the parsing when the user is still typing.) I'm new in RX, but as far as I see, I would need a combination of BufferWithTime and the Timeout methods. I imagine this to be working like this: it buffers the events until they are received regularly within a specified time period between the subsequent events. If there is a gap in the event flow (longer than the timespan) it should return propagate the events buffered so far. Having a look at how Buffer and Timeout is implemented, I could probably implement my BufferWithTimeout method (if everyone have one, please share with me), but I wonder if this can be achieved just by combining the existing methods. Any ideas?

    Read the article

  • transforming binary data using ssis and sql server 2008

    - by Rick
    Hello All - I have a task to import/transform and extract zipped binary files that contain both text data as well as embeded binary data. Within the data is data that is relational in nature and needs to be processed into a defined database structure. Currently I have a C# single threaded app that essentially grabs all the files from the directory (currently there is 13K files of varying sizes) and extracts the data on a single thread line by line inserts to the database. As you could imagine this is a very slow process and unacceptable. There are several different parsing routines used depending on the header record in the file. There are potentially upto a million rows per file when all the data is extracted to the row level of detail. Follow on task is to parse those rows into their appropriate tables based on is content. i.e. the textual content has to be parsed further into "buckets" of like data in the database. That about sums up the big picture. Now for the problem task list. How do i iterate through a packet of data using SSIS? In the app the file is decompressed and then is parsed using streams data type and byte arrays and is routed to the required parsing routine based on the header data of each packet. There is bit swapping involved as well. Should i wrap up the app code into a script task(s) and let it do the custom processing? The data is seperated by year and the sql server tables is partitioned by year as well. I need to be able to "catch" bad file data as well and process by hand most likely. Should i simply load the zipped file to sql as a blob and parse the file with T-SQL? Would that be multi threaded if done that way? Not sure how to do the parsing in tsql that is involved here. Which do you think would be faster? Potentially the data that is currently processed via files could come to us via a socket. Can SSIS collect that data in real time? How would i go about setting that up? Processing these new files from the directorys will become a daily task. I can manage the data once i get it to sql server. Getting it there in a timely fashion seems to be the long pole in the tent for me. I would appreciate any comments or suggestions from the group. Rick

    Read the article

  • Understanding run time code interpretation and execution

    - by Bob
    I'm creating a game in XNA and was thinking of creating my own scripting language (extremely simple mind you). I know there's better ways to go about this (and that I'm reinventing the wheel), but I want the learning experience more than to be productive and fast. When confronted with code at run time, from what I understand, the usual approach is to parse into a machine code or byte code or something else that is actually executable and then execute that, right? But, for instance, when Chrome first came out they said their JavaScript engine was fast because it compiles the JavaScript into machine code. This implies other engines weren't compiling into machine code. I'd prefer not compiling to a lower language, so are there any known modern techniques for parsing and executing code without compiling to low level? Perhaps something like parsing the code into some sort of tree, branching through the tree, and comparing each symbol and calling some function that handles that symbol? (Wild guessing and stabbing in the dark)

    Read the article

  • python threading and performace?

    - by kumar
    I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for each file. ( 4 threads) for file in file_list: t=threading.Thread(target = self.convertfile,args = file) t.start() ts.append(t) for t in ts: t.join() But for my astonishment, there is no performance improvement whatsoever. Now also it takes around 90+ seconds to complete the task. As this is I/o bound operation , I had expected to improve the performance. What am I doing wrong?

    Read the article

  • Android: Send arbitrary objects within Activities?

    - by Sebastian
    I have read some question here but I didn't find a solution. I have read about Parcelable, Intents, and sharing specific data within Activities from the android dev docs (both dev guide and reference). Here's the scenario: I have one ListActivity that fills in an object parsing an xml file, it shows a list of values, and when clicked I want to return the object that represents the item clicked to the activity that has called it, for then, call another activity with this object. I read on how to implement Parcelable but seems not being the way. Implementing Parcelable receives a Parcel for the constructor and then reads the values from it (or at least that was what I understood). This makes no sense for me and I can't see how to implement basing on that issue. I build the object parsing the xml file, not having a Parcel. I appreciate some clarifications on this, regards.

    Read the article

  • code throws std::bad_alloc, not enough memory or can it be a bug?

    - by Andreas
    I am parsing using a pretty large grammar (1.1 GB, it's data-oriented parsing). The parser I use (bitpar) is said to be optimized for highly ambiguous grammars. I'm getting this error: 1terminate called after throwing an instance of 'std::bad_alloc' what(): St9bad_alloc dotest.sh: line 11: 16686 Aborted bitpar -p -b 1 -s top -u unknownwordsm -w pos.dfsa /tmp/gsyntax.pcfg /tmp/gsyntax.lex arbobanko.test arbobanko.results Is there hope? Does it mean that it has ran out of memory? It uses about 15 GB before it crashes. The machine I'm using has 32 GB of RAM, plus swap as well. It crashes before outputting a single parse tree. The parser is an efficient CYK chart parser using bit vector representations; I presume it is already near the limit of memory efficiency. If it really requires too much memory I could sample from the grammar rules, but this will decrease parse accuracy of course.

    Read the article

  • Is it possible to modify ASP.NET to no longer require runat="server"?

    - by sean2078
    I know why runat="server" is currently required (ASP.NET why runat="server"), but the consensus is that it should not be required if you incorporate a simple default into the design (I agree of course). Would it be possible to modify, extend, decompile and recreate, intercept or otherwise change the behavior of how ASP.NET parses ASPX and ASCX files so that runat="server" would no longer be required? For instance, I assume that a version of Mono could be branched to accomplish this goal. In case specific requirements are helpful, the following highlights one design: During parsing, when configured namespace tags are encountered (such as "asp"), default the element's runat property to "server" During parsing, when configured namespace tags are encountered (such as "asp"), if the element's runat property value is available, then that value should be used in place of the default New page-level setting introduced (can be set in the page directive or web.config) that specifies the default runat value for a specific namespace tag

    Read the article

< Previous Page | 60 61 62 63 64 65 66 67 68 69 70 71  | Next Page >