How to escape a # in velocity - velocity

I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well
This:
\#\#
prints:
\#\#
I would like:
##

this:
#[[
##
]]#
will yield:
##
anything within #[[ ... ]]# is unparsed.

If you don't want to bother with the EscapeTool, you can do this:
#set( $H = '#' )
$H$H

Maybe, the following site helps? http://velocity.apache.org/tools/1.4/generic/EscapeTool.html

Add the esc tool to your toolbox and then you can use ${esc.hash}

${esc.h} will output # as per
this link

The set technique is a good way to get around any characters you need escaping, like if you want to have $name followed by "_lastname" then you can do:
set ($n = '_lastname)
and have this in your template:
$name$n
and it's all good.

Related

REGEX check only when start of line

Suppose we want to keep the entire line of a string only if a particular word say e.g 'test' appears at starting of line.
If it appears anywhere then the entire line should be removed
e.g
if function_test()=5; //here this entire line should be removed
test sample =5; //here this entire should be there
From Oracle 10g R2 on you should be able to use the anchor \A to require the match at the beginning of the string (will only work for single-line strings thus).
http://www.regular-expressions.info/oracle.html
What do you mean by keep / remove lines? Where is this regex supposed to run? I.e. is it a part of an SQL command, or part of a grep, or sg else?
Regarding SQL you can use LIKE operator:
WHERE line LIKE 'test%'
You can use substring too:
WHERE substring(line, 1, 4) = 'test'
Using grep or any other language, you can specify start of line, e.g.:
grep '^test' bigfile.txt
Try...
...
WHEN REGEXP_LIKE(string,'^test','i') THEN
//this is a good line, do what you want or return string;
END
...

Special Characters in Apache Velocity

How do I get Special Characters to show up in Apache Velocity as a string?
something like:
#include(" <Bundle>")
#include(" <Description>$!{bundle.description}</Description>")
#include(" </Bundle>")
you can use velocity escape tool.
https://velocity.apache.org/tools/devel/generic/EscapeTool.html
I took out the includes and it wrote it all as I needed it.

Regular expression to remove comments from SQL statement

I'm trying to come up with a regular expression to remove comments from an SQL statement.
This regex almost works:
(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|'(?:[^']|'')*'|(--.*)
Excepth that last part doesn't handle "--" comments very well. The problem is handling SQL strings, delimited with ''.
For example, if i have
SELECT ' -- Hello -- ' FROM DUAL
It shouldn't match, but it's matching.
This is in ASP/VBscript.
I've thought about matching right-to-left but i don't think the VBScript's regex engine supports it. Also tried fiddling with negative lookbehind but the results weren't good.
In PHP, i'm using this code to uncomment SQL:
$sqlComments = '#(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+#ms';
/* Commented version
$sqlComments = '#
(([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
|( # $3 : Match comments
(?:\#|--).*?$ # - Single line comments
| # - Multi line (nested) comments
/\* # . comment open marker
(?: [^/*] # . non comment-marker characters
|/(?!\*) # . ! not a comment open
|\*(?!/) # . ! not a comment close
|(?R) # . recursive case
)* # . repeat eventually
\*\/ # . comment close marker
)\s* # Trim after comments
|(?<=;)\s+ # Trim after semi-colon
#msx';
*/
$uncommentedSQL = trim( preg_replace( $sqlComments, '$1', $sql ) );
preg_match_all( $sqlComments, $sql, $comments );
$extractedComments = array_filter( $comments[ 3 ] );
var_dump( $uncommentedSQL, $extractedComments );
This code works for me:
function strip_sqlcomment ($string = '') {
$RXSQLComments = '#(--[^\r\n]*)|(\#[^\r\n]*)|(/\*[\w\W]*?(?=\*/)\*/)#ms';
return (($string == '') ? '' : preg_replace( $RXSQLComments, '', $string ));
}
with a little regex tweak it could be used to strip comments in any language
As you said that the rest of your regex is fine, I focused on the last part. All you need to do is verify that the -- is at the beginning and then make sure it removes all dashes if there are more than 2. The end regex is below
(^[--]+)
The above is just if you want to remove the comment dashes and not the whole line. You can run the below if you do want everything after it to the end of the line, also
(^--.*)
Originally, I used #Adrien Gibrat's solution. However, I came across a situation where it wasn't parsing quoted strings, properly, if I had anything with a preceding '--' inside of them. I ended up writing this, instead:
'[^']*(?!\\)'(*SKIP)(*F) # Make sure we're not matching inside of quotes
|(?m-s:\s*(?:\-{2}|\#)[^\n]*$) # Single line comment
|(?:
\/\*.*?\*\/ # Multi-line comment
(?(?=(?m-s:\h+$)) # Get trailing whitespace if any exists and only if it's the rest of the line
\h+
)
)
# Modifiers used: 'xs' ('g' can be used as well, but is enabled by default in PHP)
Please note that this should be used when PCRE is available. So, in my case, I'm using a variation of this in my PHP library.
Example
remove /**/ and -- comments
function unComment($sql){
$re = '/(--[^\n]*)/i';
$sql = preg_replace( $re, '', $sql );
$sqlComments = '#(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+#ms';
$uncommentedSQL = trim( preg_replace( $sqlComments, '$1', $sql ) );
preg_match_all( $sqlComments, $sql, $comments );
$sql = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', trim($uncommentedSQL));
return $sql;
}
Please see my answer here. It works both for line comments and for block comments, even nested block comments. I guess you need to use regex with balancing groups, which AFAIK is not available in VBScript.
For Node.js, see pg-minify library. It works with PostgreSQL, MS-SQL and MySQL scripts.
It can handle all types of comments, plus compress the resulting SQL to its bare minimum, to optimize what needs to be sent to the server.
Three regular expressions in an array for a preg_replace is just as fast as a single complex expression. Example for PHP:
function removeSqlComment($sqlString){
$regEx = [
'~(?:".*?"|\'.*?\')(*SKIP)(*F)|--.*$~m',
'~(?:".*?"|\'.*?\')(*SKIP)(*F)|/\*.*?\*/~s',
'~^;?\R~m'
];
return trim(preg_replace($regEx, '', $sqlString));
}
//test
$sqlWithComment = <<<SQL
-- first Comment;
Delete * from /* table1 */table where s = '--'; -- comm2
/*
* comment 3
*/
SELECT ' -- Hello -- ' FROM DUAL;
SQL;
$sql = removeSqlComment($sqlWithComment);
$expected = "Delete * from table where s = '--'; \nSELECT ' -- Hello -- ' FROM DUAL;";
var_dump($sql === $expected); //bool(true)
For all PHP folks: please use this library - https://github.com/jdorn/sql-formatter. I have been dealing with stripping comments from SQL for couple years now and the only valid solution would be a tokenizer/state machine, which I lazily resisted to write. Couple days ago I found out this lib and ran 120k queries through it and found only one bug (https://github.com/jdorn/sql-formatter/issues/93), which is fixed immediately in our fork https://github.com/keboola/sql-formatter.
The usage is simple
$query <<<EOF
/*
my comments
*/
SELECT 1;
EOF;
$bareQuery = \SqlFormatter::removeComments($query);
// prints "SELECT 1;"
print $bareQuery;

Is there a way to reformat braces automatically with Vim?

I would like to reformat some code which looks like this :
if (cond) {
foo;
}
to
if (cond)
{
foo;
}
Since this is C code, I have been looking at cindent/cinoptions to use with = but it seems it does not deal with multiline rules.
I have been looking at formatoptionsto use with gq, and it does not seem to be possible either.
So is it possible using default Vim options or should I use a specific plugin or function ?
:%s/^\(\s*\).*\zs{\s*$/\r\1{/
Breakdown:
^\(\s*\) = capture the whitespace at the beginning of the line
.* = everything else
\zs = start replacement after this
{ = open curly brace
\s*$ = trailing whitespace before line end
\r\1{ = newline, captured whitespace, brace
I don't know if this completely solves your problem, but if this is a one-shot operation, you might want to try regular expressions:
:%s/^\(\s*\)\(.*)\)\s*{\s*$/\1\2^M\1{/
Note that ^M is a control character that is usually generated (depending on your terminal) by pressing CTRL-V followed by ENTER.
EDIT: As pointed out in the comments by Jay and Zyx, \r is a better way of inserting a line break into the replaced string. I wasn't aware of that, many thanks for the hint.
If you install Artistic Style you can do something like:
:set formatprg=astyle\ -b
Then use gq to reformat chunks of code.emphasized text
If you want this enabled every time you edit a C file,
you can add the following to your .vimrc file.
autocmd BufNewFile,BufRead *.c set formatprg=astyle\ -b
I don't know if you can do it within vim itself, but you can try the BSD indent command with the -bl option. With the cursor on the first {, you can type !%indent -blEnter.

BASH - Single quote inside double quote for SQL Where clause

I need to send a properly formatted date comparison WHERE clause to a program on the command line in bash.
Once it gets inside the called program, the WHERE clause should be valid for Oracle, and should look exactly like this:
highwater>TO_DATE('11-Sep-2009', 'DD-MON-YYYY')
The date value is in a variable. I've tried a variety of combinations of quotes and backslashes. Rather than confuse the issue and give examples of my mistakes, I'm hoping for a pristine accurate answer unsullied by dreck.
If I were to write it in Perl, the assignment would I think look like this:
$hiwaterval = '11-Sep-2009';
$where = "highwater>TO_DATE(\'$hiwaterval\', \'DD-MON-YYYY\')";
How do I achieve the same effect in bash?
hiwaterval='11-Sep-2009'
where="highwater > TO_DATE('$hiwaterval', 'DD-MON-YYYY')"
optionally add "export " before final variable setting if it is to be visible ourside the current shell.
Have you tried using using double ticks? Like highwater>TO_DATE(''11-Sep-2009'', ''DD-MON-YYYY''). Just a suggestion. I haven't tried it out.
You can assign the where clause like this:
export WHERECLAUSE=`echo "where highwater >TO_DATE('11-Sep-2009', 'DD-MON-YYYY')"`
(with backticks around the echo statement - they're not showing up in my editor here...)
which works with a shell script of the form:
sqlplus /nolog <<EOS
connect $USERNAME/$PASSWD#$DB
select * from test $WHERECLAUSE
;
exit
EOS