Would appreciate some help in identifying the language from this snippet - code-snippets

newbie question here, I'm trying to reuse a code, but since I'm not a programmer I couldn't identify it. I tried googling already some "programming language identifier by syntax" and googling some of the syntax in it and at first I thought it matched vb.net but upon downloading and opening a project there, it had too many syntax errors IIRC, so I don't think this is it.
Here's the snippet:
;==============================================================================================================================
; Function: _MemoryReadStdString($address, $handle, [, $offset=False])
;
; Description: Read memory for string. If str_length > 15 read pointer else read str.
;
; Parameter(s): $address - Address in memory to read.
; $handle - An array containing the Dll handle and the handle of the open
; process as returned by _MemoryOpen().
; $offset - If we wanna read pointer put offset in hex value example:
; $offset[2] = [0x20, 0x264]
;
; Return Value(s): On Success - Returns string value
; On Failure - Returns empty string ''
;
; Author(s): Ascer
;===============================================================================================================================
Func _MemoryReadStdString ($address, $handle, $offset)
; read memory for address of our name and return address to this name.
Local $addr_start = '0x' & Hex(_MemoryPointerRead($address, $handle, $offset)[0], 8) ;==> example 0x8A16308
; read memory for name length, just one byte
Local $str_length = _MemoryRead($addr_start + 0x10, $handle, 'byte') ;==> 0x8A16308 + 0x10 = 0x8A16318
; check if string < 16 then read name from $addr_start
If $str_length < 16 Then
Return BinaryToString(_MemoryRead($addr_start, $handle, 'char[15]')) ;==> 'King Medivius'
; string length is > 15 then we must read memory($addr_start) for new address
Else
$str_pointer = '0x' & Hex(_MemoryRead($addr_start, $handle), 8) ;==> example 0x8C95320
Return BinaryToString(_MemoryRead($str_pointer, $handle, 'char[32]')) ;==> read memory in $str_pointer region to get true name
EndIf
; return empty string if nothing found
Return ""
EndFunc
Sorry about the "EndFunc" there, it's inside the "pre code" but somehow ended up outside it. Any help is appreciated! Thanks!

Googling a portion of the code reveals a possible source at this post about what seems to be a Tibia private server named Medivia.
From the context it seems to be written in AutoIt - there is a screenshot near the bottom of the post showing the user testing code using a program named AutoIt3.exe Here is the download link.

Related

Implement heredocs with trim indent using PEG.js

I working on a language similar to ruby called gaiman and I'm using PEG.js to generate the parser.
Do you know if there is a way to implement heredocs with proper indentation?
xxx = <<<END
hello
world
END
the output should be:
"hello
world"
I need this because this code doesn't look very nice:
def foo(arg) {
if arg == "here" then
return <<<END
xxx
xxx
END
end
end
this is a function where the user wants to return:
"xxx
xxx"
I would prefer the code to look like this:
def foo(arg) {
if arg == "here" then
return <<<END
xxx
xxx
END
end
end
If I trim all the lines user will not be able to use a string with leading spaces when he wants. Does anyone know if PEG.js allows this?
I don't have any code yet for heredocs, just want to be sure if something that I want is possible.
EDIT:
So I've tried to implement heredocs and the problem is that PEG doesn't allow back-references.
heredoc = "<<<" marker:[\w]+ "\n" text:[\s\S]+ marker {
return text.join('');
}
It says that the marker is not defined. As for trimming I think I can use location() function
I don't think that's a reasonable expectation for a parser generator; few if any would be equal to the challenge.
For a start, recognising the here-string syntax is inherently context-sensitive, since the end-delimiter must be a precise copy of the delimiter provided after the <<< token. So you would need a custom lexical analyser, and that means that you need a parser generator which allows you to use a custom lexical analyser. (So a parser generator which assumes you want a scannerless parser might not be the optimal choice.)
Recognising the end of the here-string token shouldn't be too difficult, although you can't do it with a single regular expression. My approach would be to use a custom scanning function which breaks the here-string into a series of lines, concatenating them as it goes until it reaches a line containing only the end-delimiter.
Once you've recognised the text of the literal, all you need to normalise the spaces in the way you want is the column number at which the <<< starts. With that, you can trim each line in the string literal. So you only need a lexical scanner which accurately reports token position. Trimming wouldn't normally be done inside the generated lexical scanner; rather, it would be the associated semantic action. (Equally, it could be a semantic action in the grammar. But it's always going to be code that you write.)
When you trim the literal, you'll need to deal with the cases in which it is impossible, because the user has not respected the indentation requirement. And you'll need to do something with tab characters; getting those right probably means that you'll want a lexical scanner which computes visible column positions rather than character offsets.
I don't know if peg.js corresponds with those requirements, since I don't use it. (I did look at the documentation, and failed to see any indication as to how you might incorporate a custom scanner function. But that doesn't mean there isn't a way to do it.) I hope that the discussion above at least lets you check the detailed documentation for the parser generator you want to use, and otherwise find a different parser generator which will work for you in this use case.
Here is the implementation of heredocs in Peggy successor to PEG.js that is not maintained anymore. This code was based on the GitHub issue.
heredoc = "<<<" begin:marker "\n" text:($any_char+ "\n")+ _ end:marker (
&{ return begin === end; }
/ '' { error(`Expected matched marker "${begin}", but marker "${end}" was found`); }
) {
const loc = location();
const min = loc.start.column - 1;
const re = new RegExp(`\\s{${min}}`);
return text.map(line => {
return line[0].replace(re, '');
}).join('\n');
}
any_char = (!"\n" .)
marker_char = (!" " !"\n" .)
marker "Marker" = $marker_char+
_ "whitespace"
= [ \t\n\r]* { return []; }
EDIT: above didn't work with another piece of code after heredoc, here is better grammar:
{ let heredoc_begin = null; }
heredoc = "<<<" beginMarker "\n" text:content endMarker {
const loc = location();
const min = loc.start.column - 1;
const re = new RegExp(`^\\s{${min}}`, 'mg');
return {
type: 'Literal',
value: text.replace(re, '')
};
}
__ = (!"\n" !" " .)
marker 'Marker' = $__+
beginMarker = m:marker { heredoc_begin = m; }
endMarker = "\n" " "* end:marker &{ return heredoc_begin === end; }
content = $(!endMarker .)*

Valid URL for an FTP site with username containing #

I want to create a valid URL to send to Windows File Explorer (or other file managers like TotalCommander) using the format:
ftp://username:password#ftp.domain.ext/folder/
In Explorer, it works with very straight username and password. But I receive errors (or Explorer just display the My Document instead of the FTP site) when password contains certain special characters. I played with URI encoding to encode the password with some success but not 100% reliable.
Can someone help me finding the correct requirements for a valid FTP URL including username and password? Thanks.
Here is a sample of the code using AutoHotkey "Run" command (on Windows 7 64-bit environment):
#NoEnv
#SingleInstance force
strFTPUrl := "ftp://www.jeanlalonde.ca"
strLoginName := "username#jeanlalonde.ca"
strPassword := "********"
StringReplace, strFTPUrl, strFTPUrl, % "ftp://", % "ftp://" . strLoginName . ":" . UriEncode(strPassword) . "#"
; Before: ftp://ftp.jeanlalonde.ca
; After: ftp://testaccount#jeanlalonde.ca:********#ftp.jeanlalonde.ca
MsgBox, %strFTPUrl%
Run, Explorer "%strFTPUrl%"
return
;------------------------------------------------------------
UriEncode(str)
; from GoogleTranslate by Mikhail Kuropyatnikov
; http://www.autohotkey.net/~sumon/GoogleTranslate.ahk
;------------------------------------------------------------
{
b_Format := A_FormatInteger
data := ""
SetFormat,Integer,H
SizeInBytes := StrPutVar(str,var,"utf-8")
Loop, %SizeInBytes%
{
ch := NumGet(var,A_Index-1,"UChar")
If (ch=0)
Break
if ((ch>0x7f) || (ch<0x30) || (ch=0x3d))
s .= "%" . ((StrLen(c:=SubStr(ch,3))<2) ? "0" . c : c)
Else
s .= Chr(ch)
}
SetFormat,Integer,%b_format%
return s
}
;------------------------------------------------------------
;------------------------------------------------------------
StrPutVar(string, ByRef var, encoding)
;------------------------------------------------------------
{
; Ensure capacity.
SizeInBytes := VarSetCapacity( var, StrPut(string, encoding)
; StrPut returns char count, but VarSetCapacity needs bytes.
* ((encoding="utf-16"||encoding="cp1200") ? 2 : 1) )
; Copy or convert the string.
StrPut(string, &var, encoding)
Return SizeInBytes
}
;------------------------------------------------------------
If there are special characters (# being one) in the username too (not only in the password), you have to URL-encode the username too, the same way you URL-encode the password.
That means you have to apply the UriEncode to strLoginName, the same way you apply it to strPassword.
And you need to update the UriEncode to encode the #, as it does not.
The code for # is 0x40.
if ((ch>0x7f) || (ch<0x30) || (ch=0x3d) || (ch=0x40))
(Though you can compare to # literally too: ch="#").

Passing array into a Global Procedure

So I need to pass an array into a global procedure, but as usual I have to redefine it. I know this is a bit of a noobie question, but can array be passed into as procedure? If not, could it be made global and inserted into a procedure.
$selectedFace = `ls -selection` ;
global proc crTestScripts($selectedFace) {
print ("OMG aren't lists of things awesome?!" + $selectedFace) ;
}
or
$selectedFace = `ls -selection` ;
global array? $selectedFace ;
global proc crTestScripts() {
global array? $selectedFace ;
print ("OMG aren't lists of things awesome?!" + $selectedFace) ;
}
I'm passing in this string and I still get this error:
Error: Wrong number of arguments on call to applyCurrentType
Here is a sample of the code:
string $selectedFace[] = `ls -sl` ;
global proc applyCurrentType (string $selectedFace[]) {
print("Apply Current Type button clicked\n") ;
global int $applyCurrentType ;
$applyCurrentType = 1 ;
select -cl ;
select $selectedFace ;
crTestScripts ;
}
I used proc createControllers(string $name[], int $position) in an auto rig script which is taking an array. I stay away from using the terms global when using mel since maya is picky and just use the rehash function whenever I make changes to my script;
proc buildRig()
{
string $rootNode[]=`ls -sl`;
createControllers($rootNode, 0);
}
proc createControllers(string $name[], int $position)
Worked for me. In the proc createControllers my $name array is equal to my $rootNode array.
Hope this Helps, good luck!
my previous answer was wrong.
so to pass array into proc u need redefine it as global variable,
string $selectedFace[]; will become
global string $selectedFace[];
inside procedure. e.g.:
string $selectedFace[] = filterExpand("-sm", 34, `ls-selection`);
global proc crTestScripts(){
global string $selectedFace[];
print $selectedFace;
}
crTestScripts();
// result: body_skinPrx_finalSkin.f[103]
filterExpand gives two benefits, it flattens array ls -fl, and u can use multiple filters -sm 34 -sm 31
or, i think best way... (i don't like global vars)
simply use normal syntax of variable declaration for args in round brackets:
global proc proc_name( *args_here ){ somecode; return; }
*args:
string $str, string $ls_str[], float $scaleX, float $scale[];.. vector $vec etc.
global proc hide_items(string $items[]){
hide $items;
}
using previous list result $selectedFace:
hide_items($selectedFace);
oops... i forgot maya can't hide faces xD

How to avoid building intermediates and useless AST nodes with ANTLR3?

I wrote an ANTLR3 grammar subdivided into smaller rules to increase readability.
For example:
messageSequenceChart:
'msc' mscHead bmsc 'endmsc' end
;
# Where mscHead is a shortcut to :
mscHead:
mscName mscParameterDecl? timeOffset? end
mscInstInterface? mscGateInterface
;
I know the built-in ANTLR AST building feature allows the user to declare intermediate AST nodes that won't be in the final AST. But what if you build the AST by hand?
messageSequenceChart returns [msc::MessageSequenceChart* n = 0]:
'msc' mscHead bmsc'endmsc' end
{
$n = new msc::MessageSequenceChart(/* mscHead subrules accessors like $mscHead.mscName.n ? */
$bmsc.n);
}
;
mscHead:
mscName mscParameterDecl? timeOffset? end
;
The documentation does not talk about such a thing. So it looks like I will have to create nodes for every intermediate rules to be able to access their subrules result.
Does anyone know a better solution ?
Thank you.
You can solve this by letting your sub-rule(s) return multiple values and accessing only those you're interested in.
The following demo shows how to do it. Although it is not in C, I am confident that you'll be able to adjust it so that it fits your needs:
grammar Test;
parse
: sub EOF {System.out.printf("second=\%s\n", $sub.second);}
;
sub returns [String first, String second, String third]
: a=INT b=INT c=INT
{
$first = $a.text;
$second = $b.text;
$third = $c.text;
}
;
INT
: '0'..'9'+
;
SPACE
: ' ' {$channel=HIDDEN;}
;
And if your parse the input "12 34 56" with the generated parser, second=34 is printed to the console, as you can see after running:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
TestLexer lex = new TestLexer(new ANTLRStringStream("12 34 56"));
TokenStream tokens = new TokenRewriteStream(lex);
TestParser parser = new TestParser(tokens);
parser.parse();
}
}
So, a shortcut from the parse rule like $sub.INT, or $sub.$a to access one of the three INT tokens, in not possible, unfortunately.

Basic problem with yacc/lex

I have some problems with a very simple yacc/lex program. I have maybe forgotten some basic steps (it's been a long time since I've used these tools).
In my lex program I give some basic values like :
word [a-zA-Z][a-zA-Z]*
%%
":" return(PV);
{word} {
yylval = yytext;
printf("yylval = %s\n",yylval);
return(WORD);
}
"\n" return(ENDLINE);
In my yacc program the beginning of my grammar is (where TranslationUnit is my %start) :
TranslationUnit:
/* Nothing */
| InfoBlock Data
;
InfoBlock:
/* Nothing */
| InfoBlock InfoExpression {}
;
InfoExpression:
WORD PV WORD ENDLINE { printf("$1 = %s\n",$1);
printf("$2 = %s\n",$2);
printf("$3 = %s\n",$3);
printf("$4 = %s\n",$4);
}
| ... /* other things */
;
Data:
... /* other things */
When I run my program with input :
keyword : value
I thought that I would get at least :
$1 = keyword
$2 = keyword // yylval not changed for token PV
$3 = value
$4 = value // yylval not changed for token ENDLINE
Actually I get :
$1 = keyword : value
$2 = keyword : value
$3 = value
$4 = value
I do not understand this result. I have studied grammars some time ago and even if I don't remember everything right now, I do not see any important mistake...
Thanks in advance for your help.
The trouble is that unless you save the token, Lex/Yacc goes on to over-write the space, or point to different space, etc. So you need to stash the information that's crucial to you before it gets modified. Your printing in the Lex code should have showed you that the yylval values were accurate at the point when the lexer (lexical analyzer) was called.
See also SO 2696470 where the same basic problem was encountered and diagnosed.

Resources