w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
ANTLR Grammar for while loop
For while loops, you could use predicates in ANTLR4. For the example you posted, you could do something like the following for a while loop:(JAVA target language). grammar SO; sampleRule locals [int A, int B] : IDENTIFIER1 '=' INTEGER {$A = Integer.parseInt($INTEGER.text);} IDENTIFIER2 '=' INTEGER {$B = Integer.parseInt($INTEGER.text);} ( {$A < 30;}? IDENTIFIER1 '=' IDENTIFIER1 '+' IDENTIFIER2 {$A = $A + $B;} )* ; IDENTIFIER1 : 'A' ; IDENTIFIER2 : 'B' ; INTEGER : [0-9]* ; This grammar is limited to the particular example you have provided but should not be too difficult to extend by using the above grammar.

Categories : Ant

Generate BNF diagrams from an antlr grammar?
If it is an ANTLR 3 grammar, you could use http://bottlecaps.de/convert to convert it to W3C notation, with the result, proceed to http://bottlecaps.de/rr/ui for generating syntax diagrams.

Categories : Ant

Antlr grammar unpredicted behavior
CLASS_NAME will not match 8Car or #Car. You're probably using ANTLRWorks' interpreter (or the Eclipse plugin, which uses the same interpreter), which is printing errors on a UI tab you're not aware of, and displaying the incorrect chars in the tokens. Use ANTLRWorks' debugger instead, or write a small test class yourself: T.g grammar T; parse : CLASS_NAME EOF; CLASS_NAME : ('A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9')*; Main.java import org.antlr.runtime.*; public class Main { public static void main(String[] args) throws Exception { TLexer lexer = new TLexer(new ANTLRStringStream("8Car")); TParser parser = new TParser(new CommonTokenStream(lexer)); parser.parse(); } }

Categories : Regex

ANTLR error(99) grammar has no rules
The most likely cause is just what the error message suggests. And the most likely reason for that is that you have not saved your grammar to the file--or if you're using ANTLRWorks2--ANTLRWorks hasn't saved your work to the file. I have no idea why ANTLRWorks doesn't save reliably.

Categories : Ant

Explanation for the following grammar written in ANTLR 4
The exclamation marks is used in ANTLR v3 grammars to denote that a certain node should be omitted from the generated AST. Since ANTLR v4 does not have AST's, this construct is no longer used. In both v3 and v4, the ? denotes that a rule (lexer or parser) is optional and EOF means the end-of-file constant. To summarize ';'!? means: optionally match a ';' and exclude it from the AST. And EOF! means: match the end-of-file and exclude this token from the AST. So, the v3 parser rule: query : select from ';'!? EOF! should look like this in a v4 grammar: query : select from ';'? EOF

Categories : Ant

Looking for C90 Grammar compatible with ANTLR 4 or MPlex/MPPG
The new MSBuild-based Visual C++ toolchain which shipped starting with Visual Studio 2010 provides framework-level support for non-Microsoft toolchains. You'll still need to provide build files specific to your compiler, but you would be able to cleanly integrate the result into Visual Studio. I don't know of any cases where someone's actually done this though.

Categories : C

Why there isn't a option for left-recursion removal of a grammar in Antlr?
Two parts to this answer. ANTLR 4 does remove direct left recursion. In general, left-recursion elimination is more complicated for real grammars. ANTLR produces recursive-descent parsers which look very similar to the grammar they are generated from. Left-recursion elimination must consider predicates, embedded actions, arguments, local variables, and (for ANTLR 3) AST operations. The tool wasn't created because it was bound to be somewhere between incomplete (restrictions on the supported constructs), inaccurate (does not produce a parser that behaves properly), and unrealistically complicated.

Categories : Ant

antlr grammar for tree construction from simple logic string
This rule will disallow expressions containing both AND and OR without parentheses. It will also construct the parse tree you described by making the first AND or OR token the root of the AST, and then hiding the rest of the AND or OR tokens from the same expression. exp : atom ( 'AND'^ atom ('AND'! atom)* | 'OR'^ atom ('OR'! atom)* )? ; Edit: The second problem is unrelated to this. If you don't instruct ANTLR to consume all input by including an explicit EOF symbol in one of your parser rules, then it is allowed to consume only a portion of the input in an attempt to successfully match something. The original parse rule says "match some input as exp". The following modification to the parse rule says "match the entire input as exp". public parse : exp EOF -> ^(ROO

Categories : C#

ANTLR: How the behavior of this grammar which recognizes suffixes of a Java code can be explained?
I think that you will find that it is not backtracking in the manner that you expect. The reason is that it finds the {} and then expects to see a v2_181, which it doesn't find. because it doesn't then backtrack, it doesn't find the alternative that you want. The alternative is to just make the v2_181 optional, then you don't need the backtracking. Something like below: grammar Java; @parser::members {String ruleName; } start : compilationUnitSuf EOF; compilationUnitSuf : {ruleName = "typeDeclarationSuf"; } s2 ; s2: '{' '}' v2_81?; v2_81 : {ruleName.equals("enumBodyDeclarationsSuf")}? t173 | t173 '}'; t173: '}' | '{'*; LBRACKET: '{'; RBRACKET: '}'; WS : [ u000C]+ -> skip ;

Categories : Java

How to effective resolve references in an object model after parsing an ANTLR grammar
Looks like you can avoid having a temporary model if you walk the tree twice. On first walk, create instances of classes with only their name set and add them to a dictionary(class name, IClass). On second iteration, set the references between them, using the dictionary from the first step.

Categories : C#

Antlr token priority
FREE_TEXT_WORD in its current form is capturing everything. You need a non greedy lexer rule. Try changing FREE_TEXT_WORD: NON_SPACE+; to FREE_TEXT_WORD: NON_SPACE+?;.

Categories : Java

How to tell ANTLR not to consume token
I haven't used ANTLR in a few years, but from what I remember ANTLR actions let you store intermediate results in variables, and reference them later. In that case, you can store 2x+3 in some intermediate variable, then once you've read list1 you can go back and evaluate the intermediate value you stored since you now have the necessary context.

Categories : Ant

antlr matching token instead of text
The lexer is not being driven by the parser. So your input "module" gets tokenized as follows: DBL_QUOTE MODULE DBL_QUOTE and is therefor not matched by the parser rule nameDecl: NAME DBL_QUOTE appName DBL_QUOTE;. String literals are usually handled by the lexer, in which case you won't have an issue: ... nameDecl : NAME STRING; ... STRING : '"' ~'"'* '"'; NAME : 'name'; MODULE : 'module'; ...

Categories : Ant

antlr match parser rule instead of token
If you want the lexer to treat var1.x as 3 separate tokens (var1, ., and x), then you need to make sure that no lexer rule can include the . with either of the two other tokens. As a start, you'll need to remove the STYLE_VALUE lexer rule. You'll also want to create the following lexer rule, and '.' should not appear in any other lexer rule. DOT : '.'; Instead of handling the syntax of the style value in the lexer, you'll need to handle it in the parser to ensure that DOT is always treated properly.

Categories : Ant

ANTLR, missmatched token exception, expected u000F
Two things to check. I think I see the problem. Your declaration rule eats the ; but your main rule (expression ';' | declaration ';')* also expects to get the semi colon. Remove the ; from your declaration rule. ie rewrite your declaration rule to be: declaration : type IDENT (':=' expression)? <- don't parse the semi colon here ; One check the source of the file. Unicode character u000F is SHIFT IN which isn't that common but can be used in irc environments to remove formatting. See this link I often use a hex editor for verifying the file format is actually what I think it is. A text file can never lie to a hex editor:) If you want to verify in aonther file you can usually create it by typeing ALT 15 at some other point in your file to see if ANTLR gives you the

Categories : Java

java.lang.ClassNotFoundException: antlr.ANTLRException but I have antlr-2.7.6 in folder lib of project
This is related to the Hibernate API. Hibernate 3.0 uses ANTLR (Another Tool for Language Recognition) for processing HSQL queries - if I remember correctly. You need to add an additional jar (ANTLR-2.7.5H3.jar) to your classpath. Or you can add the below maven dependency to the pom.xml <dependency> <groupId>org.hibernate</groupId> <artifactId>antlr</artifactId> <version>2.7.5H3</version> </dependency>

Categories : Hibernate

Is there a general way to convert an unambiguous context-free-grammar into a LALR(1) grammar?
1 . Are there any general ways to convert such non-LALR(1) grammars into LALR(1) grammars? No. It may or may not be possible to convert an arbitrary context-free grammar (CFG) into an LALR(1) grammar. There is no general algorithm to do so, even if you somehow know that it is possible. Moreover, if you have a CFG and an LALR(1) grammar, you cannot tell whether they recognize the same language. (Worse, there is no algorithm which will even tell you whether an arbitrary CFG recognizes every possible string for its alphabet.) 2 . If two grammars generate exactly the same languages and we know that one is not LALR(1), can we know if the other is LALR(1)? Again, no. As above, there is no algorithm which can verify that two grammars generate the same language, but even supposing that

Categories : Algorithm

Configure web service with both a Username Token and an x509 certificate using SVCConfigEditor
Not possibnle with plain svcutil, you need custom code. However you could create a binding (via code) with username supporting token and then use svcutil to define this binding.

Categories : Wcf

Python configure dict structure
Just use the pickle protocol. You can store virtually anything using that. documentation on pickling: http://docs.python.org/2/library/pickle.html

Categories : Python

Can I configure a grint-contrib-less task to compile into a parallel structure?
I was able to achieve the desired effect wit the following Gruntfile.js var path = require('path'); module.exports = function(grunt) { grunt.initConfig({ less: { options: { paths: 'assets/', yuicompress: false, ieCompat: true, require: [ 'assets/styles/base.less' ] }, src: { expand: true, cwd: 'assets/', src: [ 'styles/**/*.less' ], ext: '.css', dest: 'assets', rename: function(dest, src) { return path.join(dest, src.replace(/^styles/, 'css')); } } }, }); grunt.loadNpmTasks('grunt-contrib-less'); } Explanation Although it is not in the grunt-contrib-less docs there are a bunch more features available for files

Categories : CSS

How to configure grunt-contrib-uglify to minify files while retaining directory structure
Set the flatten property to false. There is a clear explanation on the grunt copy github readme https://github.com/gruntjs/grunt-contrib-copy Excerpt: $ grunt copy Running "copy:main" (copy) task Created 1 directories, copied 1 files Done, without errors. $ tree -I node_modules . ├── Gruntfile.js ├── dest │ └── src │ ├── a │ └── subdir └── src ├── a └── subdir └── b 5 directories, 4 files Flattening the filepath output: copy: { main: { expand: true, cwd: 'src/', src: '**', dest: 'dest/', flatten: true, filter: 'isFile', }, }, $ grunt copy Running "copy:main" (copy) task Copied 2 files Done, without errors. $ tree -I node_modules . ├── Gruntfile.js ├──

Categories : Javascript

The token provider was unable to provide a security token . Token provider returned message: ACS50009: SWT token is invalid
Linesh, The above API is only applicable for use with the ACS service identity and symmetric key. Based on the error it is likely a change is needed to the following line of code: ServiceBusEnvironment.CreateServiceUri("https", <myServiceBusNameSpace>, string.Empty); Can you replace "https" with "sb" and give it a try?

Categories : Misc

Any way configure to configure visual studio mvc build views release mode
Are you specifically setting something to compile the views like the Razor Generator? (http://razorgenerator.codeplex.com/) If not views in MVC are not compiled.

Categories : Asp Net Mvc

TFS 2012 Configure Features Error - Unable to configure Planning Tools
Try this: Rename your User Story to "Product Backlog Item". Set the Initial State of you "Bug" to "Active". Try the Upgrade Rename your User Story Type back to "User Story". Remove the "Active" Initial State. Export your Common Process Config and add in your "Proposed" State into the Bug Configuration (see below). Import your Common Process Config. Example BugWorkItems <BugWorkItems category="Microsoft.BugCategory"> <States> <State type="Proposed" value="Proposed" /> <!-- more --> </States> </BugWorkItems>

Categories : Tfs

There was an error parsing the query. [ Token line number = 2,Token line offset = 3,Token in error = Employee_ID ]
If the database you are using is some version of Microsoft SQL Server Compact Edition (which the error message would suggest) the error stems from the fact that particular database doesn't support thechar/varchardata types as it's purely unicode based. What you need to do is to use the corresponding unicode data typesnchar/nvarcharlike this: Create table Employee ( Employee_ID nchar(5) Primary key, First_Name nchar(20) NOT NULL, Last_Name nchar(20) NOT NULL, Phone_Number nvarchar(20) NULL ); For reference: Data Types Supported in SQL Server CE

Categories : SQL

Syntax Error: Token '21' is an unexpected token at column 12 of the expression [2013-08-28 21:10:14] starting at [21:10:14]
You need to pass the data using a model variable not as a string. For other issue, please have a look at the comments: <div ng-init="testapp" ng-controller="ctrl"> <timer end-time="t">{{hours}} hours, {{minutes}} minutes, {{seconds}} seconds</timer> </div> app = angular.module('testapp', []) app.directive('timer', ['$compile', function ($compile) { return { restrict: 'E', replace: false, scope: { endTimeAttr: '=endTime' }, controller: function ($scope, $element) { var end = new Date($scope.endTimeAttr); //use endTimeAttr instead of endTime var _second = 1000; var _minute = _second * 60; var _hour = _minute * 60; var _day = _hour * 24;

Categories : Javascript

Token used to prove id when clicking on confirmation e-mail. Want token to be reusable after time elapsed
Why would you want to reuse a token anyway? But in general I would setup a table like: token_id (varchar 75) expiry_date (date field) And then lookup the token when requested. The expired tokens can be removed using, for example, a cron that runs daily. When generating a new token I would validate it against the existing token_id's to prevent duplicates. By running a cron you 'cleanup' old tokens to make room for re-use. Although if you generate a 75 char hash the odds of duplicate tokens are minimal (depending on the number of tokens generated daily of course).

Categories : PHP

Exchange code for access token and id token for google oauth java
You can extract the access_token and expires_in from the returned GoogleTokenResponse, e.g., GoogleTokenResponse#getAccessToken(). Take a look at the documentation for GoogleTokenResponse.

Categories : Java

How do i generate a fresh access token from a stale token in django-allauth?
A typical User Access Token is valid for 2 hours, you can extend it to 60 days. But you cannot refresh a Token without user interaction. Else, it would make no sense to limit the validity. Which is an important feature, if a user does not use an app for some days, the app should not be able to use his token anymore. So, you cannot refresh the Token with a cron job. The user has to refresh it (FB.getLoginStatus in the JavaScript SDK, for example). More about Access Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/

Categories : Python

service bus 1.0 and WCF NetMessagingBinding - token provider unable to provide security token
Just got it working! There were two things wrong: One I think by adding the servicebus.windows.net namespace I was trying to call out to azure token provider. So instead I created a windowsTokenProvider, and the URI was the sts address https://mypc:9355/ServiceBusDefaultNamespace you can find this by running this powershell cmd: get-sbclientconfiguration Then I changed my Service endpoint address to: (dropping the servicebus.windows.net) sb://mypcname/servicebusdefaultnamespace/Orders and it is now publishing to service bus. Here is the final code: private static void Main(string[] args) { var ServiceBusEndpointAddress = new Uri("sb://mypc/servicebusdefaultnamespace/Orders"); //SetUp var binding = new NetMessagingBinding();

Categories : Wcf

Spring OAuth2 - Manually creating an access token in the token store
Here it is, your use case may differ slightly based on the flow you are using. This is what works for a password grant flow. There are a few custom class like token store, token enhancer ect. but that is really just extended versions of the spring classes modified for our own needs. HashMap<String, String> authorizationParameters = new HashMap<String, String>(); authorizationParameters.put("scope", "read"); authorizationParameters.put("username", "mobile_client"); authorizationParameters.put("client_id", "mobile-client"); authorizationParameters.put("grant", "password"); DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(authorizationParameters); authorizationRequest.setApproved(true);

Categories : Java

encoding' is an unexpected token. the expected token is '?>' when reading XML data into DataSet
The attribute value for standalone is incorrect. It should be either yes or no. See the Standalone Document Declaration <?xml version="1.0" encoding="UTF-8" standalone="yes"?> You will probably still get an error though assuming this is all you have in your XML doc as you have no root element.

Categories : C#

Requesting token from ACS endpoint in exchange of identity Provider token
Two things will fail here. First is that I doubt Facebook gives you a valid SWT Token. They give just a singed string which they call "token". And this thing is not a valid SWT Token that can be used as SWT Token in other STS-es (such as ACS) (I might be wrong here, as I am not an expert in FB, but since these errors, it is very likely that I am correct). So, if the token from FB is not valid SWT Token, your story ends here. Next thing is - you are generating SWT token on your end. Meaning that now you are signing the token. But you say you need to transform a token from Facebook. Well, there is no way for you to sign a token with Facebook's signing key! You are singing the token with your ACS's key, which makes it invalid, because you present it as Facebook's token. In short - you cann

Categories : Authentication

Java - how to scan a token and check that token after it exists and is a double
Since you are waiting for user commands, kb.hasNext() will never really evaluate to false. So this code is acting how it is supposed to. If you want "Value expected" to appear after the user types value, move the println statement. else { System.out.println("Value expected."); if (kb.hasNextDouble()){ a = kb.nextDouble(); }else { System.out.println("Value expected."); }

Categories : Java

Twitter Access Token URL returns Invalid Request Token
In Main function You write Simply this code redirect_url = "http://myawesomeapp.herokuapp.com/create_users/get_twitter_info" url = URI.parse(URI.encode(redirect_url.strip)) consumer_key=consumer key consumer_secret=consumer secret oauth = OAuth::Consumer.new(consumer_key, consumer_secret, { :site => "http://api.twitter.com" }) request_token = oauth.get_request_token(:oauth_callback => url) session[:twitter_token] = request_token.token session[:twitter_secret] = request_token.secret and in get_twitter_info function you write consumer_key=consumer key consumer_secret=consumer secret oauth = OAuth::Consumer.new(consumer_key,consumer_secret, { :site => "http://api.twitter.com" }) r

Categories : Ruby On Rails

Is the scope of an oauth2 access token bound to the token or the user?
It sounds like your implementation is not quite complete. The client app is requesting a resource on behalf of the resource owner. When the resource server receives a request with an access token, it should check that (1) the token is valid and not expired, (2) the requested resource is within the scope the token was granted for and (3) the resource owner can access the requested resource. For #1, the authorization server will need to keep track of all tokens and when they expire. For #2, the authorization server will have to remember the scope for each token and be able to relate a particular resource to a scope. The resource server should know how to check #3. To answer your question "Is the scope of an oauth2 access token bound to the token or the user?", the scope is associated wi

Categories : Dotnet

Error: Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack
There's a bug for this against the Spring Security Core grails plugin: https://jira.grails.org/browse/GPSPRINGSECURITYCORE-70

Categories : Java

WSSE WCF client with Java server "Cannot find a token authenticator for the 'System.IdentityModel.Tokens.UserNameSecurityToken' token type."
You have two options: Implement a custom message encoder in which you strip out the username from the response Dismiss any security setting from WCF all together (e.g. BasicHttpSecurityMode.None) and push the outgoing user/pass SOAP headers to the message by yourself (they are very simple xml elements) via a message inspector (easiest) or encoder or a custom header.

Categories : C#

CSRFGuard - request token does not match session token
In case anyone stumbles across a similar issue: Turned out that accessing the app using IE wasn't passing a token to an AJAX call, this would in turn result in the tokens being refreshed but the links in the already rendered page remained, causing the mismatch when clicked. Found out the issue by building CSRFGuard myself from source and adding extra logging.

Categories : Misc

Obtaining Access token from refresh token using Google API
For the first time, you need to get the access token from the browser prompt and then save it in some store. Check if the token is expired and then try to refresh it. Code here : private static IAuthorizationState GetAuthentication(NativeApplicationClient arg) { try { // Get the auth URL: var config = new Configuration(); var calendarScope = Google.Apis.Util.Utilities.ConvertToString(CalendarService.Scopes.Calendar); IAuthorizationState state = new AuthorizationState(new[] { calendarScope }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = arg.RequestUserAuthorization(state); var authCode = String.Empty; if (String.IsNullOrWhiteSpace

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.