Search Results

Search found 258 results on 11 pages for 'substitution'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • perl regular expressions substitution/replacement using variables with special characters

    - by user961627
    Okay I've checked previous similar questions and I've been juggling with different variations of quotemeta but something's still not right. I have a line with a word ID and two words - the first is the wrong word, the second is right. And I'm using a regex to replace the wrong word with the right one. $line = "ANN20021015_0104_XML_16_21 A$xAS A$xASA"; @splits = split("\t",$line); $wrong_word = quotemeta $splits[1]; $right_word = quotemeta $splits[2]; print $right_word."\n"; print $wrong_word."\n"; $line =~ s/$wrong_word\t/$right_word\t/g; print $line; What's wrong with what I'm doing? Edit The problem is that I'm unable to retain the complete words - they get chopped off at the special characters. This code works perfectly fine for words without special characters. The output I need for the above example is: ANN20021015_0104_XML_16_21 A$xASA A$xASA But what I get is ANN20021015_0104_XML_16_21 A A Because of the $ character.

    Read the article

  • Jquery [name=var] substitution

    - by Ian
    Is there a way to use a variable in the name= parameter. I would like to be able to do: var a = 1; $("#gen_p").html($("input:radio[name='gen'+a]:checked").val())); I am able to do $("#gen_p"+a) but not in the [name=??] Have I missed something? Thanks

    Read the article

  • Perl Substitution

    - by Marlin
    hi, I have a variable which stores the path on Windows. I want to replace all the \ with / in the path. for eg. $path = C:\Users\scripts.ps1 Am new to Perl and tried something like $path = s/\//// But it didnt work. can you please help me out....

    Read the article

  • Substitution for display='table-cell' in IE 7

    - by Jeny
    Hi friends, document.getElementById(id).style.display ='table-cell'. This gives error message in IE, this is IE bug or any other solutions please give any other solutions. IE7 doesn't support this property. this is my coding. Even Firefox and Chrome are accepted. My problem is IE. Please friends give solution... var cont2 = document.createElement('div'); cont2.style.display = "table-cell"; cont2.style.verticalAlign = "middle"; cont2.style.lineHeight = 100+"%"; cont2.style.padding = 10+"px"; cont2.appendChild(body);

    Read the article

  • Recursive multiline sed - remove beginning of file until pattern match.

    - by yaya3
    I have nested subdirectories containing html files. For each of these html files I want to delete from the top of the file until the pattern <div id="left- This is my attempt from osx's terminal: find . -name "*.html" -exec sed "s/.*?<div id=\"left-col/<div id=\"left-col/g" '{}' \; I get a lot of html output in the termainal, but no files contain the substitution or are written Thanks

    Read the article

  • Is there a perl idiom which is the functional equivalent of calling a subroutine from within the sub

    - by Thomas L Holaday
    Perl allows ... $a = "fee"; $result = 1 + f($a) ; # invokes f with the arugment $a but disallows, or rather doesn't do what I want ... s/((fee)|(fie)|(foe)|(foo))/f($1)/ ; # does not invoke f with the argument $1 The desired-end-result is a way to effect a substitution geared off what the regex matched. Do I have to write ... sub lala { my $haha = shift; return $haha . $haha; } my $a = "the giant says foe" ; $a =~ m/((fee)|(fie)|(foe)|(foo))/; my $result = lala($1); $a =~ s/$1/$result/; print "$a\n"; ... ?

    Read the article

  • How can I substitute the nth occurrence of a match in a Perl regex?

    - by Zaid
    Following up from an earlier question on extracting the n'th regex match, I now need to substitute the match, if found. I thought that I could define the extraction subroutine and call it in the substitution with the /e modifier. I was obviously wrong (admittedly, I had an XY problem). use strict; use warnings; sub extract_quoted { # à la codaddict my ($string, $index) = @_; while($string =~ /'(.*?)'/g) { $index--; return $1 if(! $index); } return; } my $string = "'How can I','use' 'PERL','to process this' 'line'"; extract_quoted ( $string, 3 ); $string =~ s/&extract_quoted($string,2)/'Perl'/e; print $string; # Prints 'How can I','use' 'PERL','to process this' 'line' There are, of course, many other issues with this technique: What if there are identical matches at different positions? What if the match isn't found? In light of this situation, I'm wondering in what ways this could be implemented.

    Read the article

  • Maven: properties not being substituted

    - by jobrahms
    I'm using a maven plugin for install4j in my project, located here. That plugin lets you pass variables to install4j using the <compilerVariables> section. Here's the relevant section of my pom: <plugin> <groupId>com.google.code.maven-install4j</groupId> <artifactId>maven-install4j-plugin</artifactId> <version>0.1.1</version> <configuration> <executable>${devenv.install4jc}</executable> <configFile>${basedir}/newinstaller/ehd.install4j</configFile> <releaseId>${project.version}</releaseId> <attach>false</attach> <skipOnMissingExecutable>false</skipOnMissingExecutable> <compilerVariables> <property> <name>m2_home</name> <value>${settings.localRepository}</value> </property> </compilerVariables> </configuration> </plugin> The problem is that ${settings.localRepository} is not being substituted with the actual directory when I run the plugin. Here's the command line script that install4j is generating: [INFO] Running the following command for install4j compile: /bin/sh -c /home/zach/install4j/bin/install4jc --release=9.1-SNAPSHOT --destination="/home/zach/projects/java/ehdtrunk/target/install4j" -D m2_home=${settings.localRepository} /home/zach/projects/java/ehdtrunk/newinstaller/ehd.install4j Is this the fault of the plugin? If so, what needs to change to allow the substitution to happen?

    Read the article

  • What's a good way to parameterize "static" content (e.g. CSS) in a Tomcat webapp?

    - by Steven Huwig
    Some of our CSS files contain parameters that can vary based on the deployment location (dev, QA, prod). For example: background: url(#DOJO_PATH#/dijit/themes...) to avoid hardcoding a path to a particular CDN or locally-hosted Dojo installation. These values are textually substituted with the real values by a deployment script, when it copies the contents of the webapp into the Tomcat webapps directory. That way the same deployment archive file (WAR + TAR file containing other configuration) can be deployed to dev, QA, and prod, with the varying parameters provided by environment-specific configuration files. However, I'd like to make the contents of the WAR (including the templatized CSS files) independent of this in-house deployment script. Since we don't really have control over the deployment script, all I can think to do is configure Tomcat with #DOJO_PATH# etc. as environment variables in the application's context.xml, and use Tomcat to insert those parameters into the CSS at runtime. I could make the CSS files into generated JSPs, but it seems a little ugly to me. Moreover, the substitution only needs to be done once per application deployment, so repeatedly dynamically generating the stylesheets using JSP will be rather wasteful. Does anyone have any alternative ideas or tools to use for this? We're committed to Tomcat and to substituting these parameters at deployment or at runtime (that is, not at build time).

    Read the article

  • How to verify the Liskov substitution principle in an inheritance hierarchy?

    - by Songo
    Inspired by this answer: Liskov Substitution Principle requires that Preconditions cannot be strengthened in a subtype. Postconditions cannot be weakened in a subtype. Invariants of the supertype must be preserved in a subtype. History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Since subtypes may introduce methods that are not present in the supertype, the introduction of these methods may allow state changes in the subtype that are not permissible in the supertype. The history constraint prohibits this. I was hoping if someone would post a class hierarchy that violates these 4 points and how to solve them accordingly. I'm looking for an elaborate explanation for educational purposes on how to identify each of the 4 points in the hierarchy and the best way to fix it. Note: I was hoping to post a code sample for people to work on, but the question itself is about how to identify the faulty hierarchies :)

    Read the article

  • Ubuntu 12.04 Hp G72 Problem Installing proprietary wireless driver

    - by user69402
    I have a fresh Ubuntu 12.04 installed on HP G72 machine. In order for my wireless to work I need the proprietary driver installed - Broadcom STA wireless driver. Trying to install it from the System Settings gives me the error: "Sorry, installation of this driver failed. Please have a look at the log file for details: /var/log/jockey.log". So far I suspect the error to be caused by the bad "bcmwl-kernel-source" installation. What i tried: 1. remove "bcmwl-kernel-source" 2. install "bcmwl-kernel-source" installation through the terminal ends with "error code (1)". I would greatly appreciate any help Here is everything that the terminal returns: Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: bcmwl-kernel-source 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 0 B/1,151 kB of archives. After this operation, 3,514 kB of additional disk space will be used. Selecting previously unselected package bcmwl-kernel-source. (Reading database ... 170331 files and directories currently installed.) Unpacking bcmwl-kernel-source (from .../bcmwl-kernel-source_5.100.82.38+bdcom-0ubuntu6.1_amd64.deb) ... Setting up bcmwl-kernel-source (5.100.82.38+bdcom-0ubuntu6.1) ... Loading new bcmwl-5.100.82.38+bdcom DKMS files... /usr/sbin/dkms: line 467: unset: POST_REMOVE$PRE_BUMLD': not a valid identifier /usr/sbin/dkms: line 467: unset:BUILD_E\CLUWIVE_ARCH': not a valid identifier /usr/sbin/dkms: line 467: unset: $': not a valid identifier /usr/sbin/dkms: line 467: unset:$': not a valid identifier /usr/sbin/dkms: line 467: unset: modules_conf_arra}': not a valid identifier /usr/sbin/dkms: line 467: unset:$': not a valid identifier /usr/sbin/dkms: line 467: unset: $': not a valid identifier /usr/sbin/dkms: line 467: unset:$': not a valid identifier /usr/sbin/dkms: line 467: unset: $': not a valid identifier /usr/sbin/dkms: line 467: unset:$': not a valid identifier /usr/sbin/dkms: line 467: unset: `$': not a valid identifier /usr/sbin/dkms: line 419: ${!POST_REMOVE$PRE_BUMLD[@]}: bad substitution /usr/sbin/dkms: line 419: ${!BUILD_E\CLUWIVE_ARCH[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution /usr/sbin/dkms: line 419: ${!$[@]}: bad substitution malloc: ../bash/subst.c:3671: assertion botched free: start and end chunk sizes differ Aborting.../tmp/tmp.pEXTnftUfI: line 4: modules_conf_arra}[[@]}]=[[@]}]}: command not found dkms.conf: Error! No 'DEST_MODULE_LOCATION' directive specified for record #0. dkms.conf: Error! Directive 'DEST_MODULE_LOCATION' does not begin with '/kernel', '/updates', or '/extra' in record #0. dkms.conf: Error! No 'PACKAGE_VERSION' directive specified. Error! Bad conf file. File: /usr/src/bcmwl-5.100.82.38+bdcom/dkms.conf does not represent a valid dkms.conf file. dpkg: error processing bcmwl-kernel-source (--configure): subprocess installed post-installation script returned error exit status 8 Errors were encountered while processing: bcmwl-kernel-source E: Sub-process /usr/bin/dpkg returned an error code (1)

    Read the article

  • Using C# to detect whether a filename character is considered international

    - by Morten Mertner
    I've written a small console application (source below) to locate and optionally rename files containing international characters, as they are a source of constant pain with most source control systems (some background on this below). The code I'm using has a simple dictionary with characters to look for and replace (and nukes every other character that uses more than one byte of storage), but it feels very hackish. What's the right way to (a) find out whether a character is international? and (b) what the best ASCII substitution character would be? Let me provide some background information on why this is needed. It so happens that the danish Å character has two different encodings in UTF-8, both representing the same symbol. These are known as NFC and NFD encodings. Windows and Linux will create NFC encoding by default but respect whatever encoding it is given. Mac will convert all names (when saving to a HFS+ partition) to NFD and therefore returns a different byte stream for the name of a file created on Windows. This effectively breaks Subversion, Git and lots of other utilities that don't care to properly handle this scenario. I'm currently evaluating Mercurial, which turns out to be even worse at handling international characters.. being fairly tired of these problems, either source control or the international character would have to go, and so here we are. My current implementation: public class Checker { private Dictionary<char, string> internationals = new Dictionary<char, string>(); private List<char> keep = new List<char>(); private List<char> seen = new List<char>(); public Checker() { internationals.Add( 'æ', "ae" ); internationals.Add( 'ø', "oe" ); internationals.Add( 'å', "aa" ); internationals.Add( 'Æ', "Ae" ); internationals.Add( 'Ø', "Oe" ); internationals.Add( 'Å', "Aa" ); internationals.Add( 'ö', "o" ); internationals.Add( 'ü', "u" ); internationals.Add( 'ä', "a" ); internationals.Add( 'é', "e" ); internationals.Add( 'è', "e" ); internationals.Add( 'ê', "e" ); internationals.Add( '¦', "" ); internationals.Add( 'Ã', "" ); internationals.Add( '©', "" ); internationals.Add( ' ', "" ); internationals.Add( '§', "" ); internationals.Add( '¡', "" ); internationals.Add( '³', "" ); internationals.Add( '­', "" ); internationals.Add( 'º', "" ); internationals.Add( '«', "-" ); internationals.Add( '»', "-" ); internationals.Add( '´', "'" ); internationals.Add( '`', "'" ); internationals.Add( '"', "'" ); internationals.Add( Encoding.UTF8.GetString( new byte[] { 226, 128, 147 } )[ 0 ], "-" ); internationals.Add( Encoding.UTF8.GetString( new byte[] { 226, 128, 148 } )[ 0 ], "-" ); internationals.Add( Encoding.UTF8.GetString( new byte[] { 226, 128, 153 } )[ 0 ], "'" ); internationals.Add( Encoding.UTF8.GetString( new byte[] { 226, 128, 166 } )[ 0 ], "." ); keep.Add( '-' ); keep.Add( '=' ); keep.Add( '\'' ); keep.Add( '.' ); } public bool IsInternationalCharacter( char c ) { var s = c.ToString(); byte[] bytes = Encoding.UTF8.GetBytes( s ); if( bytes.Length > 1 && ! internationals.ContainsKey( c ) && ! seen.Contains( c ) ) { Console.WriteLine( "X '{0}' ({1})", c, string.Join( ",", bytes ) ); seen.Add( c ); if( ! keep.Contains( c ) ) { internationals[ c ] = ""; } } return internationals.ContainsKey( c ); } public bool HasInternationalCharactersInName( string name, out string safeName ) { StringBuilder sb = new StringBuilder(); Array.ForEach( name.ToCharArray(), c => sb.Append( IsInternationalCharacter( c ) ? internationals[ c ] : c.ToString() ) ); int length = sb.Length; sb.Replace( " ", " " ); while( sb.Length != length ) { sb.Replace( " ", " " ); } safeName = sb.ToString().Trim(); string namePart = Path.GetFileNameWithoutExtension( safeName ); if( namePart.EndsWith( "." ) ) safeName = namePart.Substring( 0, namePart.Length - 1 ) + Path.GetExtension( safeName ); return name != safeName; } } And this would be invoked like this: FileInfo file = new File( "Århus.txt" ); string safeName; if( checker.HasInternationalCharactersInName( file.Name, out safeName ) ) { // rename file }

    Read the article

  • Why does cd print when run in command substitution?

    - by reasgt
    If I use the 'cd' BASH built-in in a command substitution, it prints extra stuff to stdout, but only when piped to, eg., less. $ echo `cd .` # The output is a single newline, appended by echo. $ echo `cd .` | less # less displays: ESC]2;my.hostname.com - tmp/testenv^G (END) What's going on there? This behavior isn't documented in the bash man page for cd. Obviously, running just 'cd' in a command substitution is silly, but something like NEWDIR=`cd mypath; pwd` could be useful. I solved this by instead using NEWVAR=`cd mypath > /dev/null 2>&1; pwd` but I still want to know what's going on. Bash Version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc. Distro: Scientific Linux SL release 5.5 (Boron)

    Read the article

  • how to replace latex macros with their definitions (using latex)

    - by RamyenHead
    How can I replace all occurrence of user defined latex macros with their definitions? For example, given this file old.tex \newcommand{\blah}[2]{#1 \to #2} ... foo \blah{egg}{spam} bar ... how to generate the file below in an automatic way new.tex ... foo egg \to spam bar ... Instead of reimplementing latex macro logic with perl, can I use latex or tex engine itself to do this?

    Read the article

  • ASP.NET MVC 1.0: OutputCache, RenderPartial and WriteSubstitution

    - by David
    Hi folks, after digging into this topic and having the requirement, that a single page should be totally cached, except for a Html.RenderPartial("LogOnUserControl"); i couldn't find any working solution on this... the only "it getting warmer" thing i foudn was this solution , which unfortunately is not working with a "partial view", which requires the Request.IsAuthenticated attribute ( the fakeContext is losing this info ) Have you heard of any other solution to do this?!

    Read the article

  • Python string formatting when string contains "%s" without escaping

    - by Stephen Gornick
    When formatting a string, my string may contain a modulo "%" that I do not wish to have converted. I can escape the string and change each "%" to "%%" as a workaround. e.g., 'Day old bread, 50%% sale %s' % 'today!' output: 'Day old bread, 50% sale today' But are there any alternatives to escaping? I was hoping that using a dict would make it so Python would ignore any non-keyword conversions. e.g., 'Day old bread, 50% sale %(when)s' % {'when': 'today'} but Python still sees the first modulo % and gives a: TypeError: not enough arguments for format string

    Read the article

  • How do I avoid repetition in Java ResourceBundle strings?

    - by Trejkaz
    We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or product name. The repetition was causing a few issues for ourselves (primarily typos or copy/paste errors) but it also causes issues in that it increases the amount of text our translator has to translate. The solution I came up with went something like this: public class ExpandingResourceBundleControl extends ResourceBundle.Control { public static final ResourceBundle.Control EXPANDING = new ExpandingResourceBundleControl(); private ExpandingResourceBundleControl() { } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { ResourceBundle inner = super.newBundle(baseName, locale, format, loader, reload); return inner == null ? null : new ExpandingResourceBundle(inner, loader); } } ExpandingResourceBundle delegates to the real resource bundle but performs conversion of {{this.kind.of.thing}} to look up the key in the resources. Every time you want to get one of these, you have to go: ResourceBundle.getBundle("com/acme/app/Bundle", EXPANDING); And this works fine -- for a while. What eventually happens is that some new code (in our case autogenerated code which was spat out of Matisse) looks up the same resource bundle without specifying the custom control. This appears to be non-reproducible if you write a simple unit test which calls it with and then without, but it occurs when the application is run for real. Somehow the cache inside ResourceBundle ejects the good value and replaces it with the broken one. I am yet to figure out why and Sun's jar files were compiled without debug info so debugging it is a chore. My questions: Is there some way of globally setting the default ResourceBundle.Control that I might not be aware of? That would solve everything rather elegantly. Is there some other way of handling this kind of thing elegantly, perhaps without tampering with the ResourceBundle classes at all?

    Read the article

  • How can I use Perl's s/// in an expression?

    - by mikeY
    I got a headache looking for this: How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's re.sub(...) when used in the following context: newstring = re.sub('ab', 'cd', oldstring) The only way I know how to do this in perl so far is: $oldstring =~ s/ab/cd/; $newstring = $oldstring; Note the extra assignment.

    Read the article

  • Using s/// in an expression

    - by mikeY
    I got a headache looking for this: How do you use s/// in an expression as opposed to an assignment. To clarify what I mean, I'm looking for a perl equivalent of python's re.sub(...) when used in the following context: newstring = re.sub('ab', 'cd', oldstring) The only way I know how to do this in perl so far is: $oldstring =~ s/ab/cd/; $newstring = $oldstring; Note the extra assignment.

    Read the article

  • Python Speeding Up Retrieving data from extremely large string

    - by Burninghelix123
    I have a list I converted to a very very long string as I am trying to edit it, as you can gather it's called tempString. It works as of now it just takes way to long to operate, probably because it is several different regex subs. They are as follow: tempString = ','.join(str(n) for n in coords) tempString = re.sub(',{2,6}', '_', tempString) tempString = re.sub("[^0-9\-\.\_]", ",", tempString) tempString = re.sub(',+', ',', tempString) clean1 = re.findall(('[-+]?[0-9]*\.?[0-9]+,[-+]?[0-9]*\.?[0-9]+,' '[-+]?[0-9]*\.?[0-9]+'), tempString) tempString = '_'.join(str(n) for n in clean1) tempString = re.sub(',', ' ', tempString) Basically it's a long string containing commas and about 1-5 million sets of 4 floats/ints (mixture of both possible),: -5.65500020981,6.88999986649,-0.454999923706,1,,,-5.65500020981,6.95499992371,-0.454999923706,1,,, The 4th number in each set I don't need/want, i'm essentially just trying to split the string into a list with 3 floats in each separated by a space. The above code works flawlessly but as you can imagine is quite time consuming on large strings. I have done a lot of research on here for a solution but they all seem geared towards words, i.e. swapping out one word for another. EDIT: Ok so this is the solution i'm currently using: def getValues(s): output = [] while s: # get the three values you want, discard the 3 commas, and the # remainder of the string v1, v2, v3, _, _, _, s = s.split(',', 6) output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip())) return output coords = getValues(tempString) Anyone have any advice to speed this up even farther? After running some tests It still takes much longer than i'm hoping for. I've been glancing at numPy, but I honestly have absolutely no idea how to the above with it, I understand that after the above has been done and the values are cleaned up i could use them more efficiently with numPy, but not sure how NumPy could apply to the above. The above to clean through 50k sets takes around 20 minutes, I cant imagine how long it would be on my full string of 1 million sets. I'ts just surprising that the program that originally exported the data took only around 30 secs for the 1 million sets

    Read the article

  • Variable loss in redirected bash while loop

    - by James Hadley
    I have the following code for ip in $(ifconfig | awk -F ":" '/inet addr/{split($2,a," ");print a[1]}') do bytesin=0; bytesout=0; while read line do if [[ $(echo ${line} | awk '{print $1}') == ${ip} ]] then increment=$(echo ${line} | awk '{print $4}') bytesout=$((${bytesout} + ${increment})) else increment=$(echo ${line} | awk '{print $4}') bytesin=$((${bytesin} + ${increment})) fi done < <(pmacct -s | grep ${ip}) echo "${ip} ${bytesin} ${bytesout}" >> /tmp/bwacct.txt done Which I would like to print the incremented values to bwacct.txt, but instead the file is full of zeroes: 91.227.223.66 0 0 91.227.221.126 0 0 127.0.0.1 0 0 My understanding of Bash is that a redirected for loop should preserve variables. What am I doing wrong?

    Read the article

  • Is this a violation of the Liskov Substitution Principle?

    - by Paul T Davies
    Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain: public class Task { public Status Status { get; set; } public virtual void Close() { Status = Status.Closed; } } public ProjectTask : Task { public override void Close() { if (Status == Status.Started) throw new Exception("Cannot close a started Project Task"); base.Close(); } } Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation?

    Read the article

  • Help with Boost Spirit ASTs

    - by Decmac04
    I am writing a small tool for analyzing simple B Machine substitutions as part of a college research work. The code successfully parse test inputs of the form mySubst := var1 + var2. However, I get a pop-up error message saying "This application has requested the Runtime to terminate it in an unusual way. " In the command prompt window, I get an "Assertion failed message". The main program is given below: // BMachineTree.cpp : Defines the entry point for the console application. // /*============================================================================= Copyright (c) 2010 Temitope Onunkun =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // UUsing Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// #define BOOST_SPIRIT_DUMP_PARSETREE_AS_XML #include <boost/spirit/core.hpp> #include <boost/spirit/tree/ast.hpp> #include <boost/spirit/tree/tree_to_xml.hpp> #include "BMachineTreeGrammar.hpp" #include <iostream> #include <stack> #include <functional> #include <string> #include <cassert> #include <vector> #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) #include <map> #endif // Using AST to parse B Machine substitutions //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; typedef char const* iterator_t; typedef tree_match<iterator_t> parse_tree_match_t; typedef parse_tree_match_t::tree_iterator iter_t; //////////////////////////////////////////////////////////////////////////// string evaluate(parse_tree_match_t hit); string eval_machine(iter_t const& i); vector<string> dx; string evaluate(tree_parse_info<> info) { return eval_machine(info.trees.begin()); } string eval_machine(iter_t const& i) { cout << "In eval_machine. i->value = " << string(i->value.begin(), i->value.end()) << " i->children.size() = " << i->children.size() << endl; if (i->value.id() == substitution::leafValueID) { assert(i->children.size() == 0); // extract string tokens string leafValue(i->value.begin(), i->value.end()); dx.push_back(leafValue.c_str()); return leafValue.c_str(); } // else if (i->value.id() == substitution::termID) { if ( (*i->value.begin() == '*') || (*i->value.begin() == '/') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } // else assert(0); } else if (i->value.id() == substitution::expressionID) { if ( (*i->value.begin() == '+') || (*i->value.begin() == '-') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } else assert(0); } // else if (i->value.id() == substitution::simple_substID) { if (*i->value.begin() == (':' >> '=') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + "|->" + eval_machine(i->children.begin()+1); } else assert(0); } else { assert(0); // error } return 0; } //////////////////////////////////////////////////////////////////////////// int main() { // look in BMachineTreeGrammar for the definition of BMachine substitution BMach_subst; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "\t\tB Machine Substitution...\n\n"; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "Type an expression...or [q or Q] to quit\n\n"; string str; while (getline(cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; tree_parse_info<> info = ast_parse(str.c_str(), BMach_subst, space_p); if (info.full) { #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) // dump parse tree as XML std::map<parser_id, std::string> rule_names; rule_names[substitution::identifierID] = "identifier"; rule_names[substitution::leafValueID] = "leafValue"; rule_names[substitution::factorID] = "factor"; rule_names[substitution::termID] = "term"; rule_names[substitution::expressionID] = "expression"; rule_names[substitution::simple_substID] = "simple_subst"; tree_to_xml(cout, info.trees, str.c_str(), rule_names); #endif // print the result cout << "Variables in Vector dx: " << endl; for(vector<string>::iterator idx = dx.begin(); idx < dx.end(); ++idx) cout << *idx << endl; cout << "parsing succeeded\n"; cout << "result = " << evaluate(info) << "\n\n"; } else { cout << "parsing failed\n"; } } cout << "Bye... :-) \n\n"; return 0; } The grammar, defined in BMachineTreeGrammar.hpp file is given below: /*============================================================================= Copyright (c) 2010 Temitope Onunkun http://www.dcs.kcl.ac.uk/pg/onun Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_BMachineTreeGrammar_HPP_ #define BOOST_SPIRIT_BMachineTreeGrammar_HPP_ using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////// // // Using Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // // B Machine Grammar // //////////////////////////////////////////////////////////////////////////// struct substitution : public grammar<substitution> { static const int identifierID = 1; static const int leafValueID = 2; static const int factorID = 3; static const int termID = 4; static const int expressionID = 5; static const int simple_substID = 6; template <typename ScannerT> struct definition { definition(substitution const& ) { // Start grammar definition identifier = alpha_p >> (+alnum_p | ch_p('_') ) ; leafValue = leaf_node_d[ lexeme_d[ identifier | +digit_p ] ] ; factor = leafValue | inner_node_d[ ch_p( '(' ) >> expression >> ch_p(')' ) ] ; term = factor >> *( (root_node_d[ch_p('*') ] >> factor ) | (root_node_d[ch_p('/') ] >> factor ) ); expression = term >> *( (root_node_d[ch_p('+') ] >> term ) | (root_node_d[ch_p('-') ] >> term ) ); simple_subst= leaf_node_d[ lexeme_d[ identifier ] ] >> root_node_d[str_p(":=")] >> expression ; // End grammar definition // turn on the debugging info. BOOST_SPIRIT_DEBUG_RULE(identifier); BOOST_SPIRIT_DEBUG_RULE(leafValue); BOOST_SPIRIT_DEBUG_RULE(factor); BOOST_SPIRIT_DEBUG_RULE(term); BOOST_SPIRIT_DEBUG_RULE(expression); BOOST_SPIRIT_DEBUG_RULE(simple_subst); } rule<ScannerT, parser_context<>, parser_tag<simple_substID> > simple_subst; rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression; rule<ScannerT, parser_context<>, parser_tag<termID> > term; rule<ScannerT, parser_context<>, parser_tag<factorID> > factor; rule<ScannerT, parser_context<>, parser_tag<leafValueID> > leafValue; rule<ScannerT, parser_context<>, parser_tag<identifierID> > identifier; rule<ScannerT, parser_context<>, parser_tag<simple_substID> > const& start() const { return simple_subst; } }; }; #endif The output I get on running the program is: ///////////////////////////////////////////////////////// B Machine Substitution... ///////////////////////////////////////////////////////// Type an expression...or [q or Q] to quit mySubst := var1 - var2 parsing succeeded In eval_machine. i->value = := i->children.size() = 2 Assertion failed: 0, file c:\redmound\bmachinetree\bmachinetree\bmachinetree.cpp , line 114 I will appreciate any help in resolving this problem.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >