Newline in text file created in jscript via activeXObject - activex

Okay from the top:
Using the following code I can create a text file using jscript in an htm file from Internet Explorer via an ActiveX object. Yay!
However, opening the text file in Notepad I noticed new lines appear as mojibake characters (rectangular character) instead of newlines . It's fine in Sublime 2.
<html>
<head>
</head>
<script type="text/javascript">
var myStr = "The self same moment I could pray;\nAnd from my neck so free\nThe Albatross fell off, and sank\nLike lead into the sea.";
var myPath = "C:\\temp\\";
var myTextfile = "Rime.txt"
writeFile(myPath, myTextfile, myStr)
function writeFile(apath, afilename, str)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var outFile = fso.CreateTextFile(apath + afilename, true);
outFile.WriteLine(str);
outFile.Close();
}
</script>
</body>
</html>
I also noticed that it doesn't occur when using the following from Photoshop environment (where I normally script from)
var txtFile = new File(apath + "/" + afilename);
outFile.open('w');
outFile.writeln(str);
outFile.close();
Is this just a quirk (or bonus) of ActiveX? Can I change it so it writes new lines that can be viewed properly in Notepad?
And, yes my Mother did warn me about the dangers of getting involved with ActiveX objects.

Looks like there's something wrong with character encoding. Try this instead of CreateTextFile():
var outFile = fso.OpenTextFile(apath + afilename, 2, true, 0);
2nd arg: 1 = reading, 2 = writing, 8 = appending.
3rd arg: true if non-existing file is created, false if non-existing file is not created. [optional, default = false]
4th arg: 0 = ASCII, -1 = Unicode, -2 = system default. [optional, default = 0]

Related

using katex, '&' alignment symbol displays as 'amp;'

I am using katex to render math.
https://github.com/Khan/KaTeX
Generally, to get this to work I link to the files katex.min.js and katex.min.css from a cdn, which is one of the ways the directions suggest.
I wrap what needs to be rendered in tags and give all the same class. For example:
<span class='math'>\begin{bmatrix}a & b \\c & d\end{bmatrix}</span>
And inside a script tag I apply the following:
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].innerHTML, math[i]);
}
So, my implementation works but there is a problem in what katex returns. The output of the above gives me:
This exact same question is asked here:
https://github.com/j13z/reveal.js-math-katex-plugin/issues/2
But I can't understand any of it.
The solution is to use element.textContent, not element.innerHTML.
If I use a form like what follows, the matrix will be rendered properly.
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].textContent, math[i]); // <--element.textContent
}
A solution that works for me is the following (it is more of a hack rather than a fix):
<script type="text/javascript">
//first we define a function
function replaceAmp(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
//next we use this function to replace all occurences of 'amp;' with ""
var katexText = $(this).html();
var html = katex.renderToString(String.raw``+katexText+``, {
throwOnError: false
});
//hack to fix amp; error
var amp = '<span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">p</span><span class="mpunct">;</span>';
var html = replaceAmp(html, amp, "");
</script>
function convert(input) {
var input = input.replace(/amp;/g, '&'); //Find all 'amp;' and replace with '&'
input=input.replace(/&&/g, '&'); //Find all '&&' and replace with '&'. For leveling 10&x+ &3&y+&125&z = 34232
var html = katex.renderToString(input, {
throwOnError: false});
return html
}
Which version are you using?
Edit the src/utils.js and comment line number 51 to 55 after updated run in terminal npm run build command.

Addons Compatibility with Firefox 48

I have an addon correctly working just up to FF 47.I know that with e10s FF 48, it has some compatibility troubles. Here a brief list of the lines of code I think they are affected by the new multiprocess model of the browser:
1.let { Cc, Ci } = require('chrome');
2.const { Cu } = require("chrome");
3.require("sdk/tabs").on("ready",logURL);
4.Cu.import("resource://gre/modules/FileUtils.jsm");
5.const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
6. file = FileUtils.getFile("Home", [".cp.txt"]); //reopen the file just saved
7. var txt = "";
var fstream = Cc["#mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
var cstream = Cc["#mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
fstream.init(file, -1, 0, 0); cstream.init(fstream, "UTF-8", 0, 0); let str = {};
let read = 0;
do {
read = cstream.readString(0xffffffff, str); // read as much as we can and put it in str.value
txt += str.value;
} while (read != 0);
cstream.close(); // this closes fstream // use 0x02 | 0x10 to open file for appending. // save the domain option in file
foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
converter.init(foStream, "UTF-8", 0, 0);
var sEP = txt + '\n' + 'h' + '\n'; // encrypt new path converter.writeString(sEP); converter.close(); // this closes foStream
console.log('saved h'); }
I need to know, first of all, if all these elements are effectively problematic with new FF (I am pretty sure 6 and 7 are not compatible — the XUL and XPCOM are obsolete and work on the same thread —, but not so sure for the other lines), and finally if there are surrogate constructs for the 48 version in order to solve the same problems (input/output and so on). In particular, it is essential for the add-on the use of the tabs mechanism (for reading the URL of a tab). Thanks for the help.
None of these issues are e10s related, they are all es6 and xpcom questions.
If you use this in a framescript, then its a e10s question, however I avoid using xpcom in framescripts, try to use messaging from framescript to bootstrap such as this - https://github.com/Noitidart/CommPlayground
Re 1 and 2: if you are not using the Cu Ci in require'ed scripts, let and const is fine.
Re 7: Don't do this way, it will be deprecated soon, and is not main ui friendly. It can lock it up. Use OS.File.
Re 4 and 6: I recommend doing Services.dirsvc.get('Home', Ci.nsIFile).path;. This is XPCOM but it is using the common Services.jsm module, which is less likely to be depercated. Also, Services.dirsvc.get caches the files, so its much faster then FileUtils. However, ideally, you should use OS.Path.join and OS.Constants.Path which comes when you import osfile.jsm. So you would do OS.Path.join(OS.Constants.Path.homeDir, '.cp.txt') - try to avoid as much XPCOM as possible.
Re 3: This is fine.

Zebra Printer - Not Printing PNG Stream *Provided my own answer*

I think I'm very close to getting this to print. However it still isn't. There is no exception thrown and it does seem to be hitting the zebra printer, but nothing. Its a long shot as I think most people are in the same position I am and know little about it. Any help anyone can give no matter how small will be welcomed, I'm losing the will to live
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var stream = new MemoryStream())
{
if (responseStream == null)
{
return;
}
responseStream.CopyTo(stream);
stream.Position = 0;
using (var zipout = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
foreach (var e in zipout.Where(e => e.FileName.Contains(".png")))
{
e.Extract(ms);
}
if (ms.Length <= 0)
{
return;
}
var binaryData = ms.ToArray();
byte[] compressedFileData;
// Compress the data using the LZ77 algorithm.
using (var outStream = new MemoryStream())
{
using (var compress = new DeflateStream(outStream, CompressionMode.Compress, true))
{
compress.Write(binaryData, 0, binaryData.Length);
compress.Flush();
compress.Close();
}
compressedFileData = outStream.ToArray();
}
// Encode the compressed data using the MIME Base64 algorithm.
var base64 = Convert.ToBase64String(compressedFileData);
// Calculate a CRC across the encoded data.
var crc = Calc(Convert.FromBase64String(base64));
// Add a unique header to differentiate the new format from the existing ASCII hexadecimal encoding.
var finalData = string.Format(":Z64:{0}:{1}", base64, crc);
var zplToSend = "~DYR:LOGO,P,P," + finalData.Length + ",," + finalData;
const string PrintImage = "^XA^FO0,0^IMR:LOGO.PNG^FS^XZ";
try
{
var client = new System.Net.Sockets.TcpClient();
client.Connect(IpAddress, Port);
var writer = new StreamWriter(client.GetStream(), Encoding.UTF8);
writer.Write(zplToSend);
writer.Flush();
writer.Write(PrintImage);
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
}
}
}
}
}
private static ushort Calc(byte[] data)
{
ushort wCrc = 0;
for (var i = 0; i < data.Length; i++)
{
wCrc ^= (ushort)(data[i] << 8);
for (var j = 0; j < 8; j++)
{
if ((wCrc & 0x8000) != 0)
{
wCrc = (ushort)((wCrc << 1) ^ 0x1021);
}
else
{
wCrc <<= 1;
}
}
}
return wCrc;
}
The following code is working for me. The issue was the commands, these are very very important! Overview of the command I have used below, more can be found here
PrintImage
^XA
Start Format Description The ^XA command is used at the beginning of ZPL II code. It is the opening bracket and indicates the start of a new label format. This command is substituted with a single ASCII control character STX (control-B, hexadecimal 02). Format ^XA Comments Valid ZPL II format requires that label formats should start with the ^XA command and end with the ^XZ command.
^FO
Field Origin Description The ^FO command sets a field origin, relative to the label home (^LH) position. ^FO sets the upper-left corner of the field area by defining points along the x-axis and y-axis independent of the rotation. Format ^FOx,y,z
x = x-axis location (in dots) Accepted Values: 0 to 32000 Default
Value: 0
y = y-axis location (in dots) Accepted Values: 0 to 32000
Default Value: 0
z = justification The z parameter is only
supported in firmware versions V60.14.x, V50.14.x, or later. Accepted
Values: 0 = left justification 1 = right justification 2 = auto
justification (script dependent) Default Value: last accepted ^FW
value or ^FW default
^IM
Image Move Description The ^IM command performs a direct move of an image from storage area into the bitmap. The command is identical to the ^XG command (Recall Graphic), except there are no sizing parameters. Format ^IMd:o.x
d = location of stored object Accepted Values: R:, E:, B:, and A: Default Value: search priority
o = object name Accepted Values: 1 to 8 alphanumeric characters Default Value: if a name is not specified, UNKNOWN is used
x = extension Fixed Value: .GRF, .PNG
^FS
Field Separator Description The ^FS command denotes the end of the field definition. Alternatively, ^FS command can also be issued as a single ASCII control code SI (Control-O, hexadecimal 0F). Format ^FS
^XZ
End Format Description The ^XZ command is the ending (closing) bracket. It indicates the end of a label format. When this command is received, a label prints. This command can also be issued as a single ASCII control character ETX (Control-C, hexadecimal 03). Format ^XZ Comments Label formats must start with the ^XA command and end with the ^XZ command to be in valid ZPL II format.
zplToSend
^MN
Media Tracking Description This command specifies the media type being used and the black mark offset in dots. This bulleted list shows the types of media associated with this command:
Continuous Media – this media has no physical characteristic (such as a web, notch, perforation, black mark) to separate labels. Label length is determined by the ^LL command.
Continuous Media, variable length – same as Continuous Media, but if portions of the printed label fall outside of the defined label length, the label size will automatically be extended to contain them. This label length extension applies only to the current label. Note that ^MNV still requires the use of the ^LL command to define the initial desired label length.
Non-continuous Media – this media has some type of physical characteristic (such as web, notch, perforation, black mark) to separate the labels.
Format ^MNa,b
a = media being used Accepted Values: N = continuous media Y = non-continuous media web sensing d, e W = non-continuous media web sensing d, e M = non-continuous media mark sensing A = auto-detects the type of media during calibration d, f V = continuous media, variable length g Default Value: a value must be entered or the command is ignored
b = black mark offset in dots This sets the expected location of the media mark relative to the point of separation between documents. If set to 0, the media mark is expected to be found at the point of separation. (i.e., the perforation, cut point, etc.) All values are listed in dots. This parameter is ignored unless the a parameter is set to M. If this parameter is missing, the default value is used. Accepted Values: -80 to 283 for direct-thermal only printers -240 to 566 for 600 dpi printers -75 to 283 for KR403 printers -120 to 283 for all other printers Default Value: 0
~DY
Download Objects Description The ~DY command downloads to the printer graphic objects or fonts in any supported format. This command can be used in place of ~DG for more saving and loading options. ~DY is the preferred command to download TrueType fonts on printers with firmware later than X.13. It is faster than ~DU. The ~DY command also supports downloading wireless certificate files. Format ~DYd:f,b,x,t,w,data
Note
When using certificate files, your printer supports:
- Using Privacy Enhanced Mail (PEM) formatted certificate files.
- Using the client certificate and private key as two files, each downloaded separately.
- Using exportable PAC files for EAP-FAST.
- Zebra recommends using Linear sty
d = file location .NRD and .PAC files reside on E: in firmware versions V60.15.x, V50.15.x, or later. Accepted Values: R:, E:, B:, and A: Default Value: R:
f = file name Accepted Values: 1 to 8 alphanumeric characters Default Value: if a name is not specified, UNKNOWN is used
b = format downloaded in data field .TTE and .TTF are only supported in firmware versions V60.14.x, V50.14.x, or later. Accepted Values: A = uncompressed (ZB64, ASCII) B = uncompressed (.TTE, .TTF, binary) C = AR-compressed (used only by Zebra’s BAR-ONE® v5) P = portable network graphic (.PNG) - ZB64 encoded Default Value: a value must be specified
clearDownLabel
^ID
Description The ^ID command deletes objects, graphics, fonts, and stored formats from storage areas. Objects can be deleted selectively or in groups. This command can be used within a printing format to delete objects before saving new ones, or in a stand-alone format to delete objects.
The image name and extension support the use of the asterisk (*) as a wild card. This allows you to easily delete a selected groups of objects. Format ^IDd:o.x
d = location of stored object Accepted Values: R:, E:, B:, and A: Default Value: R:
o = object name Accepted Values: any 1 to 8 character name Default Value: if a name is not specified, UNKNOWN is used
x = extension Accepted Values: any extension conforming to Zebra conventions
Default Value: .GRF
const string PrintImage = "^XA^FO0,0,0^IME:LOGO.PNG^FS^XZ";
var zplImageData = string.Empty;
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var stream = new MemoryStream())
{
if (responseStream == null)
{
return;
}
responseStream.CopyTo(stream);
stream.Position = 0;
using (var zipout = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
foreach (var e in zipout.Where(e => e.FileName.Contains(".png")))
{
e.Extract(ms);
}
if (ms.Length <= 0)
{
return;
}
var binaryData = ms.ToArray();
foreach (var b in binaryData)
{
var hexRep = string.Format("{0:X}", b);
if (hexRep.Length == 1)
{
hexRep = "0" + hexRep;
}
zplImageData += hexRep;
}
var zplToSend = "^XA" + "^FO0,0,0" + "^MNN" + "~DYE:LOGO,P,P," + binaryData.Length + ",," + zplImageData + "^XZ";
var label = GenerateStreamFromString(zplToSend);
var client = new System.Net.Sockets.TcpClient();
client.Connect(IpAddress, Port);
label.CopyTo(client.GetStream());
label.Flush();
client.Close();
var cmd = GenerateStreamFromString(PrintImage);
var client2 = new System.Net.Sockets.TcpClient();
client2.Connect(IpAddress, Port);
cmd.CopyTo(client2.GetStream());
cmd.Flush();
client2.Close();var clearDownLabel = GenerateStreamFromString("^XA^IDR:LOGO.PNG^FS^XZ");
var client3 = new System.Net.Sockets.TcpClient();
client3.Connect(IpAddress, Port);
clearDownLabel.CopyTo(client3.GetStream());
clearDownLabel.Flush();
client3.Close();
}
}
}
}
}
}
Easy once you know how.
Zebra ZPL logo example in base64
Python3
import crcmod
import base64
crc16 = crcmod.predefined.mkCrcFun('xmodem')
s = hex(crc16(ZPL_LOGO.encode()))[2:]
print (f"crc16: {s}")
Poorly documented may I say the least

Doc Shell Swapping Example

I'm trying to write a simple example to show docshell swapping from one iframe to another.
I wrote this, can run from scratchpad with environment browser:
var doc = gBrowser.contentDocument;
var iframeA = doc.createElement('iframe');
iframeA.setAttribute('id', 'a');
iframeA.setAttribute('src', 'http://www.bing.com');
doc.documentElement.appendChild(iframeA);
var iframeB = doc.createElement('iframe');
iframeB.setAttribute('id', 'b');
iframeB.setAttribute('src', 'data:text/html,swap to here');
doc.documentElement.appendChild(iframeB);
doc.defaultView.setTimeout(function() {
var srcFrame = iframeA;
var targetFrame = iframeB;
doc.defaultView.alert('will swap now');
srcFrame.QueryInterface(Ci.nsIFrameLoaderOwner).swapFrameLoaders(targetFrame)
doc.defaultView.alert('swap done');
}, 5000)
However this throws this error when it tries to swap:
/*
TypeError: Argument 1 of HTMLIFrameElement.swapFrameLoaders does not implement interface XULElement. Scratchpad/1:17
*/
Any ideas on how to fix?
Thanks
Thanks to #mook and #mossop from irc #extdev for the help.
The reason it didnt work was because:
pretty sure it needs to be a
Looks like gBrowser.contentDocument might be a html page? You must be using XUL elements
No idea if it even works in content either - I think it doesn't
and the things to be swapped must either both be type=content or neither can be, or something like that (translation: the type attribute of both source and target must be the same. so if one is content-primary the other must be content-primary as well)
This works:
var doc = document; //gBrowser.contentDocument;
var iframeA = doc.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'browser');
iframeA.setAttribute('id', 'a');
iframeA.setAttribute('src', 'http://www.bing.com');
iframeA.setAttribute('style', 'height:100px;');
doc.documentElement.appendChild(iframeA);
var iframeB = doc.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'browser');
iframeB.setAttribute('id', 'b');
iframeB.setAttribute('src', 'data:text/html,swap to here');
iframeB.setAttribute('style', 'height:100px;');
doc.documentElement.appendChild(iframeB);
doc.defaultView.setTimeout(function() {
var srcFrame = iframeA;
var targetFrame = iframeB;
doc.defaultView.alert('will swap now');
srcFrame.QueryInterface(Ci.nsIFrameLoaderOwner).swapFrameLoaders(targetFrame)
doc.defaultView.alert('swap done');
}, 5000)
so in other words even if you made iframe with xul namespace it would not swap if you put it in an html document. like this example here:
var xulDoc = document;
var doc = gBrowser.contentDocument;
var iframeA = xulDoc.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'iframe');
iframeA.setAttribute('id', 'a');
iframeA.setAttribute('src', 'http://www.bing.com');
iframeA.setAttribute('type', 'content');
iframeA.setAttribute('style', 'height:100px;width:100px;');
doc.documentElement.appendChild(iframeA);
var iframeB = xulDoc.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'iframe');
iframeB.setAttribute('id', 'b');
iframeB.setAttribute('src', 'data:text/html,swap to here');
iframeB.setAttribute('type', 'content');
iframeB.setAttribute('style', 'height:100px;width:100px;');
doc.documentElement.appendChild(iframeB);
doc.defaultView.setTimeout(function() {
var srcFrame = iframeA;
var targetFrame = iframeB;
doc.defaultView.alert('will swap now');
srcFrame.QueryInterface(Ci.nsIFrameLoaderOwner).swapFrameLoaders(targetFrame)
doc.defaultView.alert('swap done');
}, 5000)
It throws:
NS_ERROR_NOT_IMPLEMENTED: Scratchpad/2:21
this line is the swapFrameLoaders line
so its recommended to not use iframe with xul namespace as if you do you wont get the DOMContentLoaded and some other events http://forums.mozillazine.org/viewtopic.php?f=19&t=2809781&hilit=iframe+html+namespace
so its recommended to use element

JScript url replacement

Ok here it goes, I'm making a JScirpt for a page so you can press a keyboardbutton to move to the next page. The page URL looks like this; http://example.org/12345 , so what i want my script to do is increase the number by 1 each time you press the button. I think most of the code is right but it wont do anything
function GoThere() {
var url = window.location.pathname;
var ew = 'url'+1
url = eq.replace(location.hostname, location.hostname+ew);
window.location = url;
}
Would be grateful if someone could take a look and try to explain what I have done wrong
//EniM
check that url is an int, and take the quotes off. Might use some cleanup, but:
// strip out the /
var curint = window.location.pathname.replace(/\D/g,'');
// convert string to int
curint = parseInt( curint, 10 );
var nextint = curint + 1;
window.location = 'http://example.org/' + nextint;
Check out the Console in Chrome. You can run JS line by line... just type a function or var and it will print the result. Or set break points under Sources.
i believe your problem relies in this line
var ew = 'url'+1
it should be
var ew = parseInt(url)+1;

Resources