I'm trying to re-write this in CoffeeScript. Coming unstuck - coffeescript

function getElementsByClassName(className)
{
// get all elements in the document
if (document.all)
{
var allElements = document.all;
}
else
{
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++)
{
if (allElements[i].className == className)
{
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
var listItems = document.getElementsByClassName("quirky");
for (var i = 0, ii = listItems.length; i < ii; i++)
{
alert(listItems[i].nodeName);
}

getElementsByClassName = (className) ->
# get all elements in the document
if document.all
allElements = document.all
else
allElements = document.getElementsByTagName "*"
el for el in allElements when el.className == className
# NOTE: getElementsByClassName was never assigned as a member
# of document. So this call will likely fail, unless you are
# using a latest-version browser.
listItems = document.getElementsByClassName "quirky"
for i in listItems
alert i.nodeName

Related

DOCX4J conditional paragaph update merge FieldUpdater Does not work

Using a legacy IF field code:
enter image description here
and content controls:
private static byte[] mergingDocxFileWithXml(File file, File fileXml) {WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file)
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart()
ArrayList<String> datas
List<Object> contentControls = ContentControl.getAllContentControl(mainDocumentPart)
List<String> arrayListXpathToBoucle = new ArrayList<>()
for (Object contenControl : contentControls) {
ContentControl cControl = new ContentControl(contenControl)
String xPath = cControl.getXPath()
String title = cControl.getTitle()
if (xPath != null) {
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
}
switch (title) {
case "DateDuJour":
cControl.setValue(getDateDay())
break
case "checkbox":
String checkValue = new String(Character.toChars(0x2612))
if (datas[0] != "1") {
checkValue = new String(Character.toChars(0x2610))
}
cControl.setValue(checkValue)
break
case "Boucle_Ligne":
xPath = cControl.getTag()
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int totalNode = nodeList.getLength()
for (int j = 0; j < totalNode; j++) {
wordMLPackage = mapingDataNode(j, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, null, 0)
}
wordMLPackage.mainDocumentPart.getContent().remove(indexBoucleContent)
break;
case "Boucle_Colonne":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
String boucleValue = ""
for (int i = 0; i < totalNode; i++) {
datas = XmlPath.getXmlDataFrom(fileXml, dataXpath.get(0))
boucleValue += datas.get(i) + ", "
}
boucleValue = boucleValue.substring(0, boucleValue.length() - 2)
addValueInContentControl(contentControls, dataXpath.get(0), 0, boucleValue, null, wordMLPackage)
break
case "Boucle_Ligne_Table":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int nodeIndex = 0
Tbl arraysBoucle = getArraysBoucle(wordMLPackage, indexBoucleContent)
Tr trContent
for (int i = 0; i < totalNode; i++) {
nodeIndex = i + 1
if (arraysBoucle.getContent().stream().count() > 1) {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(1))
} else {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(0))
}
wordMLPackage = mapingDataNode(i, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, trContent, nodeIndex)
}
int lastIndexTr = wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.stream().count()
wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.remove(lastIndexTr - 1)
break
case "IMAGE":
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
byte[] imageByte = base64ToImage(datas.get(0))
Inline inlineImage = newImage(wordMLPackage, imageByte)
cControl.setValue(null, inlineImage)
break
default:
String xpathBoucle = arrayListXpathToBoucle.find { it.startsWith(xPath) }
if (xpathBoucle != xPath) {
addValueInContentControl(contentControls, xPath, 0, "", fileXml,wordMLPackage)
}
break
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wordMLPackage= mergingFieldWordMlPackage(wordMLPackage)
FieldUpdater updater = new FieldUpdater(wordMLPackage)
updater.update(true);
wordMLPackage.save(outputStream);
return outputStream.toByteArray();
}
Docx4j's legacy field processing does not parse IF fields: http://webapp.docx4java.org/OnlineDemo/ecma376/WordML/IF.html
If you need to do that, you'll need to write code to do the parsing.
An alternative would be to use OpenDoPE conditional content controls. With one of these, the content of the SDT is included only if the associated XPath evaluates to true.

VSCode language extension with hierarchical Outline, DocumentSymbol

I'm trying to get outline working with a custom language in VScode. I have the below code but I feel like it is slow because of the way I find a range in class. Are there better ways to find the range and assign children. I've thought about just keeping track of the depth of the brackets and assigning all functions/methods/classes in higher depths into the last item of previous depth.
It was based off of this answer.
class JSLDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
public provideDocumentSymbols(document: vscode.TextDocument,
token: vscode.CancellationToken): Thenable<vscode.DocumentSymbol[]> {
return new Promise((resolve, reject) => {
var symbols: vscode.DocumentSymbol[] = [];
var depth = 0;
for (var i = 0; i < document.lineCount; i++) {
var line = document.lineAt(i);
var txt = line.text;
var ltxt = txt.toLowerCase();
let open_brackets = ltxt.match(/\(/g) || [];
let close_brackets = ltxt.match(/\)/g) || [];
// console.log(ltxt)
// console.log(open_brackets, close_brackets)
//console.log(i, open_brackets.length, close_brackets.length)
depth += open_brackets.length - close_brackets.length;
//console.log(depth);
if (ltxt.includes("define class(")) {
let sname = txt.trim().substr(14, txt.trim().length - 16); //this is hard coded right now but it's kind of working
let detail = "ARGS:x, y returns z";
let start_pos = new vscode.Position(i, 0);
let n_bracket = 1;
let i_char = 0;
//let children: vscode.DocumentSymbol[] = []
let ds = new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Class, line.range, line.range);
for(var i_line = i; n_bracket > 0; i_line++){
let class_line = document.lineAt(i_line);
let mtxt = class_line.text;
let ic;
if(i == i_line) ic = 16;
else ic = 0;
for(i_char = ic; i_char < mtxt.length; i_char++){
if(mtxt[i_char] === "(") n_bracket++;
else if(mtxt[i_char] === ")") n_bracket--;
if(n_bracket === 0) break
}
if (/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i.test(mtxt)) {
let result = mtxt.match(/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let mname = result[1].trim();
let m_details = ""
if(result.length == 3){
m_details = result[2].trim();
}
ds.children.push(new vscode.DocumentSymbol(mname, m_details, vscode.SymbolKind.Method, class_line.range, class_line.range));
}
if(n_bracket === 0) break
}
let end_pos = new vscode.Position(i_line, i_char);
let rng = new vscode.Range(start_pos, end_pos);
ds.range = rng;
//ds.children = children;
symbols.push(ds);
}
else if (/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/.test(ltxt)) {
let result = txt.match(/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let sname = result[1].trim();
let detail = "";
if(result.length == 3){
detail = "(" + result[2].trim() + ")";
}
symbols.push(new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Function, line.range, line.range));
}
}
resolve(symbols);
});
}
}

E4X to JSON conversion fails for duplicate xml elements

Kindly see below code I am using to convert Mirth xml to JSON.
function E4XtoJSON(xml, ignored) {
var r, children = xml.*, attributes = xml.#*, length = children.length();
if(length == 0) {
r = xml.toString();
} else if(length == 1) {
var text = xml.text().toString();
if(text) {
r = text;
}
}
if(r == undefined) {
r = {};
for each (var child in children) {
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if(value) {
if(value.length) {
value.push(json);
} else {
r[name] = [value, json]
}
} else {
r[name] = json;
}
}
}
if(attributes.length()) {
var a = {}, c = 0;
for each (var attribute in attributes) {
var name = attribute.localName();
if(ignored && ignored.indexOf(name) == -1) {
a["_" + name] = attribute.toString();
c ++;
}
}
if(c) {
if(r) a._ = r;
return a;
}
}
return r;
}
My concern is
<AdditionalMessageInformationCount AdditionalMessageInformationCount="02"><AdditionalMessageInformationQualifier>01</AdditionalMessageInformationQualifier><AdditionalMessageInformation>MEMBER MUST USE MAIL ORDER.</AdditionalMessageInformation><AdditionalMessageInformationQualifier>02</AdditionalMessageInformationQualifier><AdditionalMessageInformation>PLAN LIMITATIONS EXCEEDED</AdditionalMessageInformation></AdditionalMessageInformationCount>
Here AdditionalMessageInformation elemt is used two times so function fails to create JSON.
Kindly help if anyone have converted XML in json usingg javascript code not any API
We've had success with this version:
function E4XtoJSON(xml, ignored){
var r, children = xml.*,
attributes = xml.# * ,
length = children.length();
if (length == 0)
{
r = xml.toString();
}
else if (length == 1)
{
var text = xml.text().toString();
if (text)
{
r = text;
}
}
if (r == undefined)
{
r = {};
for each(var child in children)
{
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if (value)
{
if (value instanceof Array)
{
value.push(json);
}
else
{
r[name] = [value, json]
}
}
else
{
r[name] = json;
}
}
}
if (attributes.length())
{
var a = {},
c = 0;
for each(var attribute in attributes)
{
var name = attribute.localName();
if (ignored && ignored.indexOf(name) == -1)
{
a["_" + name] = attribute.toString();
c++;
}
}
if (c)
{
if (r) a._ = r;
return a;
}
}
return r;
}
With the release of Mirth Connect version 3.3.0, you can use Mirth Connect to set your channel's interior data type to JSON. This will all be done for you.

Google Spreadsheet - How to avoid sending email duplicates?

I am having an issue with a script. I used the following script from Google Developers Website in order to do a simple merge mail. See https://developers.google.com/apps-script/articles/mail_merge
I modified a bit the script so to prevent email duplicates. However, even if the script seems to work as it marks 'EMAIL_SENT' in each row every time an email is sent. It does not pay attention if the mail as already been marked and still send the mail.
I believe there is an error at line 16 "var emailSent = rowData[6];"
I would really appreciate if someone could help me. Whoever you are thanks in advance.
Here is the modified script :
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 7);
var templateSheet = ss.getSheets()[1];
var emailTemplate = templateSheet.getRange("A2").getValue();
var objects = getRowsData(dataSheet, dataRange);
for (var i = 0; i < objects.length; ++i) {
var Resume = DriveApp.getFilesByName('Resume.pdf') var Portfolio = DriveApp.getFilesByName('Portfolio.pdf') var rowData = objects[i];
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = "Architectural Internship";
var emailSent = rowData[6];
if (emailSent != EMAIL_SENT) {
MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText, {
attachments: [Resume.next(), Portfolio.next()]
});
dataSheet.getRange(2 + i, 7).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
function fillInTemplateFromObject(template, data) {
var email = template;
var templateVars = template.match(/\${\"[^\"]+\"}/g);
for (var i = 0; i < templateVars.length; ++i) {
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}
return email;
}
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue;
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty. // Arguments: // - cellData: string function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise. function isAlnum(char) { return char >= 'A' && char <= 'Z' || char >= 'a' && char <= 'z' || isDigit(char); }
// Returns true if the character char is a digit, false otherwise. function isDigit(char) { return char >= '0' && char <= '9'; }
Your code is really hard to read and the functions that return 2 or more objects make it even harder...you are using variable names that are also a bit confusing.... but that is probably a personal pov :-)
Anyway, I think I've found the issue: when you write var rowData = objects[i];
This "object" is actually the result of the getRowData function but if you look at this function, you'll see that it returns 2 objects, the first one being itself the result of another function (getObjects) ...
You are checking the value is the 6th element of the array which is actually an object and compare it to a string. The equality will never be true.
I didn't go further in the analyse since I found it really confusing ( as I already said) but at least you have a first element to check .
I would suggest you rewrite this code in a more simple way and use more appropriate variable names to help you while debugging.
I would recommend logging both values before executing to make sure they are the same. I would also guess that the email_sent and EMAIL_SENT are different data types. Can also try forcing the value to string for comparison.
To clarify:
logger.Log(emailSent);
logger.Log(EMAIL_SENT);
if (emailSent.toString() != EMAIL_SENT.toString())
{...
Error is in this line of code -
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
It's considering only 2 columns in the range. Changed 2 to 3 and it worked fine.

Append divs changing his content dynamic

I have a dif called cdefualt that has some inputs from a form inside of it and I want to do something like this to clone it and change that input names:
var i = 2;
function add() {
var item = $('#cdefault').clone();
item.attr({'style': ''});
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
item.id = $xpto;
$('#'+$xpto+' input[id="gtitle1"]').attr('name', $xpto);
$('#'+$xpto+' textarea[id="gmessage1"]').attr('name',$xpto2);
$(item).appendTo('#ccontainer');
i++;
}
But this doesnt work. I've tried this already as well but it only works twice (for the original and first clone):
var i = 2;
function add() {
var item = $('#cdefault').clone();
item.attr({'style': ''});
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
$('#cdefault input[id="gtitle1"]').attr('id', $xpto);
$('#cdefault textarea[id="gmessage1"]').attr('id',$xpto2);
$('#cdefault input[name="gtitle1"]').attr('name', $xpto);
$('#cdefault textarea[name="gmessage1"]').attr('name', $xpto2);
$(item).appendTo('#ccontainer');
i++;
}
Even tryed this way:
function add() {
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
var div = document.getElementById('cdefault');
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = $xpto;
clone.style.display = '';
$("#"+$xpto+" input[id='gtitle1']").attr('name', $xpto);
$("#"+$xpto+" textarea[id='gmessage1']").attr('name',$xpto2);
document.getElementById('ccontainer').appendChild(clone);
i++;
}
http://jsfiddle.net/Theopt/xNfSd/
fixed. changed cdefault id to id0 and this java script:
var i = 2;
var c = 0;
function add() {
$xpto = 'gtitle'+i;
$xpto2 = 'gmessage'+i;
var klon = $( '#id'+ c );
klon.clone().attr('id', 'id'+(++c) ).insertAfter( '#inserthere' );
document.getElementById('id'+(c)).style.display = '' ;
$("#id"+(c)+" input[id='gtitle1']").attr('name', $xpto);
$("#id"+(c)+" textarea[id='gmessage1']").attr('name',$xpto2);
i++;
}