How to print string? - easy68k

I can't seem to print the banner A, the # is all on the same line.
I am not allowed to edit the string by adding CR nor LF. Help pls!
START: ; first instruction of program
loop
move.b #5,D0
trap #15
lea str,A1
move.b #0,D0
trap #15
bra loop
SIMHALT ; halt simulator
str
dc.b ' # '
dc.b ' # # '
dc.b ' # # '
dc.b ' # # '
dc.b ' ####### '
dc.b ' # # '
dc.b ' # # '
END START ; last line of source

I have spotted a few things in your code.
When you are passing a task number to the trap 15 call you should store it using move.w, this will ensure that only the value you intend is received by the trap handler. If the register had previously had a number like $12345678 assigned to it, move.b #0,Dr would leave it containing $12345600 and the trap handler would take the task number as being $5600 rather than 0.
In your call for task 0 to display the string held in A1, you have not specified a length of string to display in D1 (as per the manual), this again should be word length. The manual does say that it stops on a NULL, but this is referring to reading a NULL character in the string, not in D1.
So your code becomes:
loop
move.w #5,D0
trap #15
lea str,A1
move.w #0,D0 ; Display string action
move.w #70,d1 ; Maximum number of characters to display
trap #15
bra loop

Related

Can somebody explain this obfuscated perl regexp script?

This code is taken from the HackBack DIY guide to rob banks by Phineas Fisher. It outputs a long text (The Sixth Declaration of the Lacandon Jungle). Where does it fetch it? I don't see any alphanumeric characters at all. What is going on here? And what does the -r switch do? It seems undocumented.
perl -Mre=eval <<\EOF
''
=~(
'(?'
.'{'.(
'`'|'%'
).("\["^
'-').('`'|
'!').("\`"|
',').'"(\\$'
.':=`'.(('`')|
'#').('['^'.').
('['^')').("\`"|
',').('{'^'[').'-'.('['^'(').('{'^'[').('`'|'(').('['^'/').('['^'/').(
'['^'+').('['^'(').'://'.('`'|'%').('`'|'.').('`'|',').('`'|'!').("\`"|
'#').('`'|'%').('['^'!').('`'|'!').('['^'+').('`'|'!').('['^"\/").(
'`'|')').('['^'(').('['^'/').('`'|'!').'.'.('`'|'%').('['^'!')
.('`'|',').('`'|'.').'.'.('`'|'/').('['^')').('`'|"\'").
'.'.('`'|'-').('['^'#').'/'.('['^'(').('`'|('$')).(
'['^'(').('`'|',').'-'.('`'|'%').('['^('(')).
'/`)=~'.('['^'(').'|</'.('['^'+').'>|\\'
.'\\'.('`'|'.').'|'.('`'|"'").';'.
'\\$:=~'.('['^'(').'/<.*?>//'
.('`'|"'").';'.('['^'+').('['^
')').('`'|')').('`'|'.').(('[')^
'/').('{'^'[').'\\$:=~/('.(('{')^
'(').('`'^'%').('{'^'#').('{'^'/')
.('`'^'!').'.*?'.('`'^'-').('`'|'%')
.('['^'#').("\`"| ')').('`'|'#').(
'`'|'!').('`'| '.').('`'|'/')
.'..)/'.('[' ^'(').'"})')
;$:="\."^ '~';$~='#'
|'(';$^= ')'^'[';
$/='`' |'.';
$,= '('
EOF
The basic idea of the code you posted is that each alphanumeric character has been replaced by a bitwise operation between two non-alphanumeric characters. For instance,
'`'|'%'
(5th line of the "star" in your code)
Is a bitwise or between backquote and modulo, whose codepoints are respectively 96 and 37, whose "or" is 101, which is the codepoint of the letter "e". The following few lines all print the same thing:
say '`' | '%' ;
say chr( ord('`' | '%') );
say chr( ord('`') | ord('%') );
say chr( 96 | 37 );
say chr( 101 );
say "e"
Your code starts with (ignore whitespaces which don't matter):
'' =~ (
The corresponding closing bracket is 28 lines later:
^'(').'"})')
(C-f this pattern to see it on the web-page; I used my editor's matching parenthesis highlighting to find it)
We can assign everything in between the opening and closing parenthesis to a variable that we can then print:
$x = '(?'
.'{'.(
'`'|'%'
).("\["^
'-').('`'|
'!').("\`"|
',').'"(\\$'
.':=`'.(('`')|
'#').('['^'.').
('['^')').("\`"|
',').('{'^'[').'-'.('['^'(').('{'^'[').('`'|'(').('['^'/').('['^'/').(
'['^'+').('['^'(').'://'.('`'|'%').('`'|'.').('`'|',').('`'|'!').("\`"|
'#').('`'|'%').('['^'!').('`'|'!').('['^'+').('`'|'!').('['^"\/").(
'`'|')').('['^'(').('['^'/').('`'|'!').'.'.('`'|'%').('['^'!')
.('`'|',').('`'|'.').'.'.('`'|'/').('['^')').('`'|"\'").
'.'.('`'|'-').('['^'#').'/'.('['^'(').('`'|('$')).(
'['^'(').('`'|',').'-'.('`'|'%').('['^('(')).
'/`)=~'.('['^'(').'|</'.('['^'+').'>|\\'
.'\\'.('`'|'.').'|'.('`'|"'").';'.
'\\$:=~'.('['^'(').'/<.*?>//'
.('`'|"'").';'.('['^'+').('['^
')').('`'|')').('`'|'.').(('[')^
'/').('{'^'[').'\\$:=~/('.(('{')^
'(').('`'^'%').('{'^'#').('{'^'/')
.('`'^'!').'.*?'.('`'^'-').('`'|'%')
.('['^'#').("\`"| ')').('`'|'#').(
'`'|'!').('`'| '.').('`'|'/')
.'..)/'.('[' ^'(').'"})';
print $x;
This will print:
(?{eval"(\$:=`curl -s https://enlacezapatista.ezln.org.mx/sdsl-es/`)=~s|</p>|\\n|g;\$:=~s/<.*?>//g;print \$:=~/(SEXTA.*?Mexicano..)/s"})
The remaining of the code is a bunch of assignments into some variables; probably here only to complete the pattern: the end of the star is:
$:="\."^'~';
$~='#'|'(';
$^=')'^'[';
$/='`'|'.';
$,='(';
Which just assigns simple one-character strings to some variables.
Back to the main code:
(?{eval"(\$:=`curl -s https://enlacezapatista.ezln.org.mx/sdsl-es/`)=~s|</p>|\\n|g;\$:=~s/<.*?>//g;print \$:=~/(SEXTA.*?Mexicano..)/s"})
This code is inside a regext which is matched against an empty string (don't forget that we had first '' =~ (...)). (?{...}) inside a regex runs the code in the .... With some whitespaces, and removing the string within the eval, this gives us:
# fetch an url from the web using curl _quitely_ (-s)
($: = `curl -s https://enlacezapatista.ezln.org.mx/sdsl-es/`)
# replace end of paragraphs with newlines in the HTML fetched
=~ s|</p>|\n|g;
# Remove all HTML tags
$: =~ s/<.*?>//g;
# Print everything between SEXTA and Mexicano (+2 chars)
print $: =~ /(SEXTA.*?Mexicano..)/s
You can automate this unobfuscation process by using B::Deparse: running
perl -MO=Deparse yourcode.pl
Will produce something like:
'' =~ m[(?{eval"(\$:=`curl -s https://enlacezapatista.ezln.org.mx/sdsl-es/`)=~s|</p>|\\n|g;\$:=~s/<.*?>//g;print \$:=~/(SEXTA.*?Mexicano..)/s"})];
$: = 'P';
$~ = 'h';
$^ = 'r';
$/ = 'n';
$, = '(';

Perl6 one liner execution. How is the topic updated?

Executing the one liner to process CSV a line at a time from stdin:
perl6 -ne 'my #a; $_.split(",").kv.map: {#a[$^k]+=$^v}; say #a; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"}';
Typing in:
1,1
1,1
^D
Gives the following output:
BEGIN
ENTER
1,1
[1 1]
1,1
[2 2]
LEAVE
END
Here we can see that the one liner is not a block executed multiple times as the ENTER and LEAVE phaser are only executed once.
This makes sense as the variable #a is accumulating. If the one liner was a block the value of #a would be reset each time.
My question is how does the topic variable $_ get updated? The topic variable is a Str (at least that's what $_.^name says). How does its value update without re-entering the block?
What am I missing?
When you add -n it adds a for loop around your code.
You think it adds one like this:
for lines() {
# Your code here
}
The compiler just adds the abstract syntax tree nodes for looping without actually adding a block.
(
# Your code here
) for lines()
(It could potentially be construed as a bug.)
To get it to work like the first one:
( # -n adds this
-> $_ { # <-- add this
# Your code here
}( $_ ) # <-- add this
) for lines() # -n adds this
I tried just adding a bare block, but the way the compiler adds the loop causes that to not work.
In general ENTER and LEAVE are scoped to a block {}, but they are also scoped to the “file” if there isn't a block.
ENTER say 'ENTER file';
LEAVE say 'LEAVE file';
{
ENTER say ' ENTER block';
LEAVE say ' LEAVE block';
}
ENTER file
ENTER block
LEAVE block
LEAVE file
Since there is no block in your code, everything is scoped to the “file”.
The -n command line argument puts a loop around your program,
for $*ARGFILES.lines {
# Program block given on command line
}
whereas the program execution phasers you used (BEGIN and END), are run once either at compile time or after the program block has finished, so they will not be part of the loop at run time.
The ENTER block phaser will run at every block entry time, whereas the
the LEAVE block phaser will run at every block exit time. So these phasers will be run for each line read in the for loop.
Update -- Rakudo 2020.10
Running your original accumulator code (using the -ne linewise flag) gives the following result. Note how the word "final" appears in every line:
~$ perl6 -ne 'my #a; $_.split(",").kv.map: {#a[$^k]+=$^v}; say #a, " final"; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"};' drclaw.txt
BEGIN
ENTER
[1 1] final
[2 3] final
[3 6] final
LEAVE
END
Below, running essentially duplicate scripts back-to-back with the -ne flag gives an interesting result. BEGIN, ENTER,LEAVE, and END show up in the exact same location, duplicated on the order of once-per-call:
~$ perl6 -ne 'my #a; .split(",").kv.map: {#a[$^k]+=$^v}; say #a, " final_a"; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"}; my #b; .split(",").kv.map: {#b[$^k]+=$^v}; say #b, " final_b"; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"};' drclaw.txt
BEGIN
BEGIN
ENTER
ENTER
[1 1] final_a
[1 1] final_b
[2 3] final_a
[2 3] final_b
[3 6] final_a
[3 6] final_b
LEAVE
LEAVE
END
END
However, removing the -ne flag below lets you run a for lines() {...} loop within the Raku code itself (single script, not duplicated back-to-back). This result seems more in line with what you were expecting:
~$ perl6 -e 'my #a; for lines() {.split(",").kv.map: {#a[$^k]+=$^v};}; say #a, " final"; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"};' drclaw.txt
BEGIN
ENTER
[3 6] final
LEAVE
END
I think the short answer to your questions is that Phasers respect Block/Loop semantics, but are limited script-wise as to how many times they will report back to the implementer (apparently only once per call). But the ultimate difference is that the return to the user is linewise for the -ne command line flag, as compared to an internal for lines() {...} loop sans the -ne command line flag.
Finally, you can always force the reloading of the $_ topic variable with the andthen infix operator. Maybe this is what you were looking for all along:
~$ perl6 -e 'my #a; for lines() {.split(",").kv.map: {#a[$^k]+=$^v} andthen $_.say }; say #a, " final"; ENTER {say "ENTER"}; BEGIN {say "BEGIN"}; LEAVE {say "LEAVE"}; END {say "END"};' drclaw.txt
BEGIN
ENTER
(1 1)
(2 3)
(3 6)
[3 6] final
LEAVE
END
[Test file under analysis, below].
~$ cat drclaw.txt
1,1
1,2
1,3
https://docs.raku.org/language/operators#index-entry-andthen

Php Command Line Output on the fly

I am writing a command line php script which does some output to the console window, its all look good only issues is when i type
php myfilename.php -....
in the console window, ONLY AFTER its fully executed it outputs the result to the window ..
Wht i want is to do this on the fly like below
customer id: 1223 skipped.
customer id: 22233 added..
...etc
another question is adding \n\r to the printf functions didn't go to a new line ...
any idea on these issues..
This is probably due to output buffering. You can use ob_flush() to flush the buffer manually when needed.
As for your second issue, the correct sequence for newline on Microsoft Windows is "\r\n", not the other way around.
First, the Windows-style end-of-line marker is \r\n, not \n\r. Not many systems ever used \n\r, but they are rare enough that you can forget about them now.
Second, chances are good the output is being block buffered -- you can either use ob_implicit_flush(1) to automatically insert a flush() command after every output command. Or, you could call flush() manually, when you need to flush output.
About the End-Of-Line marker, always use PHP predefined constant PHP_EOL; it is correctly set based on your platform, so you do not have to worry is it right or wrong.
For the [Enter] issue, it could be the output buffering is on. Add this simple test in your script:
function test()
{
$state = array(' added', ' skipped');
for ($i = 0; $i < 50; $i++)
{
echo 'customer id: ' . rand(1, 1000) . $state[rand(0, 1)] . PHP_EOL;
usleep(50000); // slow it a bit to see the line by line output
}
}
// without ob -------------------------------------------
$start = microtime(true);
test();
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
sleep(1);
// with ob ----------------------------------------------
$start = microtime(true);
ob_start(); // if called somewhere at the top in your script
// some previous code...
echo 'Line 1'.PHP_EOL.'Line 2'.PHP_EOL.uniqid().PHP_EOL;
// flush the buffer and stop ob
// this will echo whatever is in the output buffer!
//ob_end_flush();
// or, store the current buffer content in a variable and use it later
$output = ob_get_clean();
test();
echo $output;
echo 'Finished in ' . round(microtime(true) - $start, 2) . PHP_EOL . str_repeat('-', 78) . PHP_EOL;
// you could start buffering again, if needed
ob_start();
For output control functions see http://www.php.net/manual/en/ref.outcontrol.php. They are very powerful tools.
Hope it helps. Cheers!

How to comment a VIM macro

Is it possible to comment a macro and replay it.
Example
instead of
dddwj
I would like to comment and execute following fragment
dd # Delete line
dw # Delete word
j # Move to next line
Some background
We use PICT to generate testcase inputs (All Pair testing). As this is an iterative process, the macro for generating code needs tweaking between subsequent runs. It's hard to modify a macro when everything is on one line, without comments.
The output of a PICT run might be something like this:
1 cInstallationX Pu380
2 cInstallationY U400
wich can be converted to testcases with a macro
procedure TWatchIntegrationTests.Test1;
begin
//***** Setup
builder
.withInstallation(cInstallationX)
.withIsotope(Pu380)
.Build;
//***** Execute
CreateAndCollectWatches;
//***** Verify
VerifyThat
.toDo;
end;
procedure TWatchIntegrationTests.Test2;
begin
//***** Setup
builder
.withInstallation(cInstallationY)
.withIsotope(U400)
.Build;
//***** Execute
CreateAndCollectWatches;
//***** Verify
VerifyThat
.toDo;
end;
I don't know a good way of doing this with macros, but there are a few options that I can see that might help:
Heavy use of 'normal'
This is the closest to your macro option, but not very nice: make your saved file look like this:
" Delete line
normal dd
" Delete word
normal dw
" Move to next line
normal j
Complicated Substitution
This makes use of regular expressions, but makes those regular expressions be well commented (this is based on your actual example).
let pattern = '^' " Start of line
let pattern .= '\(\d\+\)' " One or more digits (test number)
let pattern .= '\s\+' " Space or tab as delimiter
let pattern .= '\(\k\+\)' " Installation name
let pattern .= '\s\+' " Space or tab as delimiter
let pattern .= '\(\a\+\d\+\)' " One or more alphabetic characters, then one or more spaces (isotope)
let pattern .= '\s*$' " Any spaces up to the end of the line
let result = 'procedure TWatchIntegrationTests.Test\1;\r'
let result .= 'begin\r'
let result .= ' //***** Setup\r'
let result .= ' builder\r'
let result .= ' .withInstallation(\2)\r'
let result .= ' .withIsotope(\3)\r'
let result .= ' .Build;\r'
let result .= '\r'
let result .= ' //***** Execute\r'
let result .= ' CreateAndCollectWatches;\r'
let result .= '\r'
let result .= ' //***** Verify\r'
let result .= ' VerifyThat\r'
let result .= ' .toDo;\r'
let result .= 'end;\r'
exe '%s!' . pattern . '!' . result . '!'
Stick it in a function
Given that this is getting rather complicated, I'd probably do it this way as it gives more room for adjustment. As I see it, you want to split the line on white space and use the three fields, so something like this:
" A command to make it easier to call
" (e.g. :ConvertPICTData or :'<,'>ConvertPICTData)
command! -range=% ConvertPICTData <line1>,<line2>call ConvertPICTData()
" Function that does the work
function! ConvertPICTData() range
" List of lines producing the required template
let template = [
\ 'procedure TWatchIntegrationTests.Test{TestNumber};',
\ 'begin',
\ ' //***** Setup',
\ ' builder',
\ ' .withInstallation({Installation})',
\ ' .withIsotope({Isotope})',
\ ' .Build;',
\ '',
\ ' //***** Execute',
\ ' CreateAndCollectWatches;',
\ '',
\ ' //***** Verify',
\ ' VerifyThat',
\ ' .toDo;',
\ 'end;',
\ '']
" For each line in the provided range (default, the whole file)
for linenr in range(a:firstline,a:lastline)
" Copy the template for this entry
let this_entry = template[:]
" Get the line and split it on whitespace
let line = getline(linenr)
let parts = split(line, '\s\+')
" Make a dictionary from the entries in the line.
" The keys in the dictionary match the bits inside
" the { and } in the template.
let lookup = {'TestNumber': parts[0],
\ 'Installation': parts[1],
\ 'Isotope': parts[2]}
" Iterate through this copy of the template and
" substitute the {..} bits with the contents of
" the dictionary
for template_line in range(len(this_entry))
let this_entry[template_line] =
\ substitute(this_entry[template_line],
\ '{\(\k\+\)}',
\ '\=lookup[submatch(1)]', 'g')
endfor
" Add the filled-in template to the end of the range
call append(a:lastline, this_entry)
endfor
" Now remove the original lines
exe a:firstline.','.a:lastline.'d'
endfunction
Do it in python
This is the sort of task that is probably easier to do in python:
import sys
template = '''
procedure TWatchIntegrationTests.Test%(TestNumber)s;
begin
//***** Setup
builder
.withInstallation(%(Installation)s)
.withIsotope(%(Isotope)s)
.Build;
//***** Execute
CreateAndCollectWatches;
//***** Verify
VerifyThat
.toDo;
end;
'''
input_file = sys.argv[1]
output_file = input_file + '.output'
keys = ['TestNumber', 'Installation', 'Isotope']
fhIn = open(input_file, 'r')
fhOut = open(output_file, 'w')
for line in fhIn:
parts = line.split(' ')
if len(parts) == len(keys):
fhOut.write(template % dict(zip(keys, parts)))
fhIn.close()
fhOut.close()
To use this, save it as (e.g.) pict_convert.py and run:
python pict_convert.py input_file.txt
It will produce input_file.txt.output as a result.
First of all let me point out that #Al has posted several excellent solutions and I suggest you use those and not what I am about to post. Especially since that does not seem to work under all circumstances (for reasons I do not understand).
Having said that, the following seems to do what you want at least in this case. It assumes <Space> in normal mode is not used to move the cursor around. Maps it to :" where " is the comment character for cmline mode. Which means <Space> is the character that starts a comment in this case. The newline at the end stops the comment. The # is just there to make it clearer we are dealing with comments. (^[ should be entered as a single escape character).
:nmap <Space> :"
iHallo wereld^[ # Insert text (in dutch, better change that)
Fe # Move backwards to e
x # Delete
; # Move to next e
ro # Change to o
Fa # Move backwards to a
re # Change to e
A!^[ # Add exclamation mark

How does this obfuscated Perl code work?

How does this code work at all?
#!/usr/bin/perl
$i=4;$|=#f=map{("!"x$i++)."K$_^\x{0e}"}
"BQI!\\","BQI\\","BQI","BQ","B","";push
#f,reverse#f[1..5];#f=map{join"",undef,
map{chr(ord()-1)}split""}#f;{;$f=shift#
f;print$f;push#f,$f;select undef,undef,
undef,.25;redo;last;exit;print or die;}
Lets first put this through perltidy
$i = 5;
$| = #f = map { ("!" x $i++) . "9$_*\x{0e}" } ">>>E!)", ">>>E)", ">>>E", ">>>", ">>", ">", "";
push #f, reverse #f[ 1..5 ];
#f = map {
join "",
map { chr(ord() - 1) }
split //
} #f;
{
$f = shift #f;
print $f;
push #f, $f;
select undef, undef, undef, .25;
redo;
last;
exit;
print or die;
}
The first line is obvious.
The second line makes a list ">>>E!)", ">>>E)", ">>>E", ">>>", ">>", ">", "", and spaces them all to be equally long and appends an asterisk and a 'Shift Out' (the character after a carriage return).
The third line appends items 5 to 1 (in that order) to that list, , so it will be ">>>E!)", ">>>E)", ">>>E", ">>>", ">>", ">", "", ">", ">>", ">>>", ">>>E".
The map decrements the all characters by one, thus creating elements like 8===D ().
The second loop simply prints the elements in the list in a loop every 0.25 seconds. The carriage return causes them to overwrite each other, so that an animation is seen. The last couple of lines are never reached and thus bogus.
Data from the file is loaded into a program called a Perl interpreter. The interpreter parses the code and converts it to a series of "opcodes" -- a bytecode language that is sort of halfway between Perl code and the machine language that the code is running on. If there were no errors in the conversion process (called "compiling"), then the code is executed by another part of the Perl interpreter. During execution, the program may change various states of the machine, such as allocating, deallocating, reading, and writing to memory, or using the input/output and other features of the system.
(CW - More hardcore hackers than I are welcome to correct any errors or misconceptions and to add more information)
There's no magic going on here, just obfuscation. Let's take a high-level view. The first thing to notice is that later on, every character in strings is interpreted as if it were the previous character:
[1] map{chr(ord()-1)} ...
Thus, a string like "6qD" will result in "5rC" (the characters before '6', 'q', and 'D', respectively). The main point of interest is the array of strings near the beginning:
[2] ">>>E!)",">>>E)",">>>E",">>>",">>",">",""
This defines a sequence of "masks" that we will substitute later on, into this string:
[3] "9$_*\x{0e}"
They'll get inserted at the $_ point. The string \x{0e} represents a hex control character; notice that \x{0d}, the character just before it, is a carriage return. That's what'll get substituted into [3] when we do [1].
Before the [3] string is assembled, we prepend a number of ! equal to i to each element in [2]. Each successive element gets one more ! than the element before it. Notice that the character whose value is just before ! is a space .
The rest of the script iterates over each of the assembled array elements, which now look more like this:
[4] "!!!!!9>>>E!)\x{0e}", ---> " 8===D ("
"!!!!!!9>>>E)\x{0e}", ---> " 8===D("
"!!!!!!!9>>>E\x{0e}", ---> " 8===D"
"!!!!!!!!9>>>\x{0e}", ---> " 8==="
"!!!!!!!!!9>>\x{0e}", ---> " 8=="
"!!!!!!!!!!9>\x{0e}", ---> " 8="
"!!!!!!!!!!!9\x{0e}", ---> " 8"
Then the reverse operation appends the same elements in reverse, creating a loop.
At this point you should be able to see the pattern emerge that produces the animation. Now it's just a matter of moving through each step in the animation and back again, which is accomplished by the rest of the script. The timestep delay of each step is governed by the select statement:
[5] select undef, undef, undef, 0.25
which tells us to wait 250 milliseconds between each iteration. You can change this if you want to see it speed up or slow down.