Action script Error While Compiling the Regular Expression - actionscript-3

public function validemail(email:String):Boolean {
//var emailExpression:RegExp = /^[\w.-]+#\w[\w.-]+\.[\w.-]*[a-z][a-z]$;
//var Result:Object=emailExpression.exec(email);
var pattern1:RegExp =/^[\w.-]+#\w[\w.-]+\.[\w.-]*[a-z][a-z]$;
var Result:Object =pattern1.exec(email);
if(Result==null){
return false;
}
return true;
}
public function validateandsend(event:MouseEvent):void {
if(validemail(txtEmail)==false){
ErrorMessage="Please enter the valid mail di information";
xmlErrorDetails.send();
return;
}
}
For the code above when I compile the Error is :
Multiple markers at this line:
-1084: Syntax error: expecting identifier before var.
-1086: Syntax error: expecting semicolon before colon.
-Result
Receiving the Error please help

You are missing a closing / at the end of the line. It should read:
var pattern1:RegExp = /^[\w.-]+#\w[\w.-]+\.[\w.-]*[a-z][a-z]$/;

Related

Error: "Reference does not exist" when using a custom function

I'm trying to scrape a webpage & to put the value in cache in order to not hit the daily urlFetch limit.
This is the code I'm using, it works without the Cache & Properties service but not when I try to add that element.
function scrapercache(url) {
var url = "https://www.gurufocus.com/term/fscore/nyse:ABBV/Piotroski-F-Score";
var result = [];
var description;
var options = {
'muteHttpExceptions': true,
'followRedirects': false,
};
Logger.log('line 16 OK');
var cache = CacheService.getScriptCache();
var properties = PropertiesService.getScriptProperties();
Logger.log('line 21 OK');
let res = cache.get(url);
// if(res){
// return JSON.parse(res)
//}
Logger.log(res);
Logger.log('line 24 OK');
if (res) {
// trim url to prevent (rare) errors
url.toString().trim();
var r = UrlFetchApp.fetch(url, options);
Logger.log(r);
Logger.log('line 34 OK');
var c = r.getResponseCode();
Logger.log(c);
Logger.log('line 38 OK');
// check for meta refresh if 200 ok
if (c == 200) {
var html = r.getContentText();
cache.put(url, "cached", 21600);
properties.setProperty(url, html);
Logger.log('line 46 OK');
var $ = Cheerio.load(html); // make sure this lib is added to your project!
Logger.log('line 49 OK');
// meta description
if ($('meta[name=description]').attr("content")) {
description = $('meta[name=description]').attr("content").trim();
var trim_des = description.substr(0, 40);
Logger.log('line 55 OK');
}
}
result.push([trim_des]);
Logger.log('line 60 OK');
}
return result;
Logger.log('line 64 OK');
}
I call the function like that:
=scrapercache("https://www.gurufocus.com/term/fscore/nyse:ABBV/Piotroski-F-Score")
& I get the following error message
Error: Reference does not exist
EDIT: I added log lines to see if the script was processing correctly & it looks like it's ok only until like 28
You're not putting the results in the cache, you're putting the string "cached" there. Consider:
let cached = cache.get(url)
if(cached){
return JSON.parse(cached)
}
let results = ["blah","blah"] // stuff we got with cheerio
cache.put(url, JSON.stringify(results), 120)
return results
Error: “Reference does not exist”
This error message is usually returned by calling a custom function in a spreadsheet cell that does not return a value. It is explicitly mentioned by the official docs, but the error message is not provided, so the confusion is understandable.
An empty array is not a valid return value (since there are no elements to return). The error is easily reproducible with the following custom function:
/**
* #customfunction
*/
function testReferenceError() {
const list = [];
return list;
}
Which, when called in a cell, resulting in the "desired" error:
Applied to your case
In your situation, when there is a cached data in cache, the if statement clause evaluates to false (truthy value when negated evaluates to false). When it does, nothing gets pushed to the result, and an empty array is returned in finally (see above for the explanation of consequences). Consider this mock:
const cache = {
get() {
return "cached";
}
};
let res = cache.get("mock_url");
//ternary operator here acts the same as "if...else":
console.log( !res ? "will enter if block" : "will enter else block" );
Note on return in finally: If you put a return statement into a finally block, expect it to override the return statements in try or catch. Consider this example close to how your program is structured:
const final = (add = false) => {
const list = [];
try {
add && list.push(1);
return [1,2]; //this return is skipped
}
catch(error) {
list.push(error);
}
finally {
return list;
}
};
console.log( final() );
Also, the question already has an answer here

Malformed html error thrown from html based object in appscript

I've hit a wall on an issue when I try to display the content.text object in apps script, it returns a malformed html error specifically regarding my fetch to a GET request of
https://www.cloudconnect.xxx...
I get everything I need, but the content.text bit which is throwing a malformed html error in apps script. I'd like to use the html and return the documents as is with proper formatting and believe that I can properly parse this html to apps script using htmloutput as it needs to be sanitized, but I believe it's what's throwing the malformed html object. How can I proceed without escaping html characters? How can I properly parse this? Has anyone been successful at this by any chance?
Example of content.text:
<body>
<!-- [DocumentBodyStart:a63392fa-f859-4513-867e-1f3d2714b006] -->
<div class=\"jive-rendered-content\">
<p>Hi,team!</p>
<p style=\"min-height: 8pt; padding: 0px;\"> </p>
<p>When executing attest () of SafetyNet Attestation API, apkPackageName is obtained as a parameter.</p>
<p>I ran this API several times.</p>
<p>As a result, the apkPackageName parameter was missing only once.</p>
<p>In all other execution results, the parameter apkPackageName is present and will not occur again.</p>
<p style=\"min-height: 8pt; padding: 0px;\"> </p>
<p>Why can't I get the apkPackageName when running the SafetyNet Attestation API on a device that has not been
tampered with?</p>
<p style=\"min-height: 8pt; padding: 0px;\"> </p>
<p>device : Kyocera 704KC</p>
<p style=\"min-height: 8pt; padding: 0px;\"> </p>
<p>Regards,</p>
</div><!-- [DocumentBodyEnd:a63392fa-f859-4513-867e-1f3d2714b006] -->
</body>
Would anyone have any pointers on how to proceed from here? My goal is to obtain the text from the content.text object, which I can see on any regular editor, but not in apps script for some reason while using the html format that it returns as is.
Code.gs
function doGet(request) {
return HtmlService.createTemplateFromFile('Page').evaluate();
}
function include(filename) {
var finalRequest = UrlFetchApp.fetch('https://www.cloudconnect.xxx...');
var data = finalRequest.toString().replace("throw 'allowIllegalResourceCall is false.';", "").trim();
data = JSON.parse(data);
var returnedData = [];
for(var i in data.list){
var content = data.list[i];
var content_subject = JSON.stringify(content.subject);
var content_text = JSON.stringify(content.content.text);
returnedData.push(content_subject + "<br />" + "<br />" + textBody(content_text));
}
return returnedData;
}
function textBody(content){ // <-- where the error throws on the content_text object
return HtmlService.createHtmlOutput(content);
}
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
function myFunction() {
Logger.log(HtmlService
.createTemplateFromFile('Page')
.getCode());
}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Stylesheet'); ?>
</head>
<body>
<script>
var responseSubject;
var responseContent;
function displayData(responseSubject, responseContent) {
document.getElementById('output').innerHTML = responseSubject + <br> + responseContent + <br>;
}
google.script.run.withFailureHandler(displayData).withSuccessHandler(displayData).include();
</script>
</body>
</html>
Update
I have hit a wall returning the Exception: Cannot call SpreadsheetApp.getUi() from this context. (line 21, file "Code")
Code.gs
function doGet(request) {
return HtmlService.createTemplateFromFile('Page').evaluate();
}
function include(filename) {
var finalRequest = UrlFetchApp.fetch('https://www.cloudconnect.xxx....');
var data = finalRequest.toString().replace("throw 'allowIllegalResourceCall is false.';", "").trim();
data = JSON.parse(data);
var returnedData = [];
for(var i in data.list){
var content = data.list[i];
var contentSubject = JSON.stringify(content.subject);
var contentText = JSON.stringify(content.content.text);
returnedData.push(contentSubject + "<br/>" + "<br/>");
var fixedContent = escapeHtml(contentText);// fixes the malformed Html error
var ui = HtmlService.createHtmlOutput(fixedContent);//the attempt to read the onlick event and load the content text - but it throws the error: Exception: Cannot call SpreadsheetApp.getUi() from this context. (line 21, file "Code")
SpreadsheetApp.getUi().showModelessDialog(ui);
Logger.log("returnedData is: " + returnedData);
}
return returnedData;
}
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
function myFunction() {
Logger.log(HtmlService
.createTemplateFromFile('Page')
.getCode());
}
//function contentBody(responseContent){ <-- realized I can't do this from a custom function
//var html = responseContent;
//var ui = HtmlService.createHtmlOutput(html);
//SpreadsheetApp.getUi().showModelessDialog(ui);
//}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Stylesheet'); ?>
<script>
var responseSubject;
var responseContent;
function displaySubjects(responseSubject) {
document.getElementById('output').addEventListener('click', getContentBody).innerHTML = responseSubject;
}
google.script.run.withFailureHandler(displaySubjects).withSuccessHandler(displaySubjects).include();
//function displayContentText(responseContent){
//document.getElementById('projection').innerHTML = responseContent;
//}
//google.script.run.withFailureHandler(displayContentText).withSuccessHandler(displayContentText).contentBody();
</script>
</head>
<body>
<p id = "output"></p>
<p id = "projection"></p>
</body>
</html>
My goal here is to add a click listener to the subjects and have them load the content text through the Html service.
Any help would be highly appreciated please.
Cheers!
This works:
function htmltest() {
var html='<body><!--[DocumentBodyStart:a63392fa-f859-4513-867e-1f3d2714b006]--><div class="jive-rendered-content"><p>Hi,team!</p><p style="min-height:8pt;padding:0px;"> </p><p>When executing at test() of Safety NetAttestationAPI, apkPackageName is obtained as a parameter.</p><p>I ran this API several times.</p><p>As a result,the apkPackageName parameter was missing only once.</p><p>In all other execution results,the parameter apkPackageName is present and will not occur again.</p><p style="min-height:8pt;padding:0px;"> </p><p>Whycan\'t I get the apkPackageName when running the Safety NetAttestation API on a device that has not been tampered with?</p><p style="min-height:8pt;padding:0px;"> </p><p>device:Kyocera704KC</p><p style="min-height:8pt;padding:0px;"> </p><p>Regards,</p></div><!--[DocumentBodyEnd:a63392fa-f859-4513-867e-1f3d2714b006]--></body>';
var ui=HtmlService.createHtmlOutput(html).setHeight(500);
SpreadsheetApp.getUi().showModelessDialog(ui, "HTML Test");
}
Here's what I get when I run it just that way it is.

How to return property while object get undefined

I got this error when trying to grab emails from Gmail inbox.
TypeError: Cannot read property "length" from undefined
I don't know if there is any other functions fit here better.
function getRelevantMessages()
{
var threads = GmailApp.search("newer_than:30d AND label:payments",0,100);
var messages=[];
threads.forEach(function(thread)
{
messages.push(thread.getMessages()[0]);
});
return messages;
}
function parseMessageData(messages)
{
var records=[];
for(var m=0;m<messages.length;m++)
{
var text = messages[m].getPlainBody();
// then regex and objects carry the returns
the code from pastebin https://pastebin.com/TRkEB6yM
Since the original question was getting undefined when searching for emails, MiMi, Cooper and Tedinoz solved it in the comments. Posting it as an answer for further searches.
function getRelevantMessages() {
var threads = GmailApp.search("newer_than:30d",0,100);
var messages=[];
threads.forEach(function(thread) {
messages.push(thread.getMessages()[0].getFrom());
});
Logger.log(messages);
return messages;
}

Problems with HTML5 FileReader

I try to run the FileReader function in my project but it only works pas.Mon project works like so I list all files in a directory. It all works. But when I select a file in the list (my files are local), I end up with this error I do not understand:
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': The argument is not a Blob.
Here is my code:
GetFileName function (fs) {
     var target = event.target || event.srcElement;
     var childs = target.parentNode.childNodes;
     {for (i = 0; i ++; i <childs.length)
         if (target == childs [i]) break;
     }
     console.log (i); // Index li
     console.log (event.target.innerHTML); // li value
     filename = "~ / Downloads / snippets" + event.target.innerHTML;
var fr = new FileReader ();
fr.onload = function (e) {
     console.log (e.target.result);
};
fr.readAsText (filename);
}
Does anyone have an idea of what does not work?
Thank you in advance for your help!
I think the problem is that your filename variable is set to:
filename = "~ / Downloads / snippets" + event.target.innerHTML;
...which is a String, rather than the object that's expected by the readAsText function on FileReader.
Try something like this instead:
var fileInputElement = document.getElementById("fileInputElement");
fr.readAsText(fileInputElement.files[0]);
Where "fileInputElement" is the ID of the HTML <input> element of type file.
This may not fit exactly with what you're doing, but it's not easy to tell without seeing more of your JavaScript and HTML.

Recommended practice for application exception handling in AngularJS

I am currently exploring possible methods to handle application-wide exceptions in AngularJS.
One of the things we really wanted to avoid was wrapping multiple parts of the application in nested try/catch blocks, but handle things cleanly - i.e throw an exception in response to a promise.
Has anyone covered this issue before and have any recommendations?
Any suggestions on how to pick up exceptions in services as well as controllers/directives. (See below - broadcast works ok, but only if you can attach a listener to a scope).
Progress so far
A few short design goals:
Allow exceptions from one part of the application to be handled elsewhere - or possibly multiple places (i.e. 'display error notification to user', 'disable widget').
Provide central management of common error conditions - i.e. log to server, display notification to user, redirect to login.
Allow exceptions to be thrown from controllers, directives, services etc.
Eventually allow localized messages.
The current leaning of my team is to write a service to handle exceptions, which would expose a range of simple calls:
exceptionService.warn('exception_token');
exceptionService.crit('another_exception_token');
This service would then format an 'exception' object and broadcast this from the rootscope. This would allow a default handler to watch for any broadcasts and apply default actions, as well as allow custom listeners to be set in others scopes, which could handle more specific conditions - i.e. disable a part of the UI.
var exception = {
token: 'exception_token',
severity': 'crit'
};
// broadcast exception
$rootScope.$broadcast(
'application_exception',
exception
);
I was thinking about the same recently, and it occurred to me that when it comes to a good error handling in javascript, it is irrelevant which framework you are using, Angular on something else. I wrote one such error handler recently for an AngularJS project, but I did it in a way it can be used in any framework.
Here's the complete code. You can either use it directly, or modify to your needs...
/*
Factory errorFact is to simplify error handling and reporting in other objects.
It supports detailed error output as a text string and into the browser's console.
Usage example:
A function that supports return of an error object would have the following declaration
as its very first line:
var e = errorFact.create("objectName.funcName", arguments);
- in this declaration we specify the full object + method name as the first string parameter,
- and as the second parameter we pass javascript's reserved variable called arguments, which
provides reference to all of the function's parameters for logging.
When an error occurs, the function would return:
return e.error("Error description text");
- this line will create and return a complete error context.
When a function that supports return of an error object makes a call into another
function that also supports the error context, then it can return the nested error
result by passing the embedded error to the current error object instead of the error
text.
Example:
var e = errorFact.create("objectName.funcName", arguments);
var data = callAnotherFunc(...); // calling a function that support an error object;
if(data.isError){ // If an error was triggered;
return e.error(data); // return that error from the current context;
}
The top-level code that calls an error-returning function would do verification
and if an error occurred, log all its details into console (typically).
Example:
var data = getData(...);
if(data.isError){
data.log(); // Output all the error details into the browser's console;
}
*/
"use strict";
app.factory("errorFact", function(){
return {
// creates a new error context;
create: function(method, args){
var result = {
// initiates and returns the error context;
error: function(msg){
this.info.isError = true;
if(msg.isError){
this.info.details.caller = msg;
}else{
this.info.details.msg = msg;
}
return this.info;
},
info:
{
isError: false,
details: {},
log: function(){
if(this.isError){
console.error(this.format());
}
},
// formats complete error details into a text string;
format: function(){
if(this.details.caller){
var txt = this.details.caller.format();
txt += "\nCALLER: " + this.details.method + "(" + this.formatArguments() + ")";
return txt;
}
if(this.details.method){
return "Error calling " + this.details.method + "(" + this.formatArguments() + "): " + this.details.msg;
}else{
return this.details.msg;
}
return "";
},
// formats function argument details into a text string;
formatArguments: function(){
if(!this.details.args){
return "";
}
var params = "";
for(var i = 0;i < this.details.args.length;i ++){
if(params.length > 0){
params += ",";
}
var p = this.details.args[i];
if(p === undefined){
params += "undefined";
}else{
if(p === null){
params += "null";
}else{
if(typeof(p) == "object"){
params += "Object";
}else{
params += p;
}
}
}
}
return params;
}
}
};
if(method){
result.info.details.method = method;
}
if(args){
result.info.details.args = args;
}
return result;
}
}
});
Below is a factory that shows how it is used:
"use strict";
app.factory('moduleFact', ['errorFact', function(errorFact){
return {
// Locates existing module and expands its key Id references
// into corresponding object references:
// - If 'hintGroupId' is present, property 'hints' is added from
// the corresponding hint group.
// - If 'repModules' is present, properties 'question' and 'refs'
// are added.
// On success, return the expanded module object.
// On failure, returns an error object.
//
// NOTE: Currently supports only the first value in repModules.
expandModule: function(moduleData, moduleId){
var e = errorFact.create("moduleFact.expandModule", arguments);
if(!moduleData || !moduleData.modules || !moduleId){
return e.error("Invalid parameters passed");
}
var mod = this.findModule(moduleData, moduleId);
if(mod.isError){
return e.error(mod);
}
var src = mod;
if(mod.repModules){
var repId = mod.repModules[0];
if(!repId){
return e.error("Invalid repModules encountered");
}
///////////////////////////////////////
// temporary check to throw a warning:
if(mod.repModules.length > 1){
console.warn("Multiple values in property repModules: " + JSON.stringify(mod.repModules) +
", which is not supported yet (only the first value is used)");
}
///////////////////////////////////////
src = this.findModule(moduleData, repId);
if(src.isError){
return e.error(src);
}
}
if(src.question){
mod.question = src.question;
}else{
return e.error("Question not specified");
}
if(src.refs){
mod.refs = src.refs;
}
if(src.hintGroupId){
var hg = this.findHintGroup(moduleData, src.hintGroupId);
if(hg.isError){
return e.error(hg);
}
mod.hints = hg.hints;
}
return mod; // needed extra: expand attribute repModules
},
// Expands all the modules and returns the data;
expandAllModules: function(moduleData){
var e = errorFact.create("moduleFact.expandAllModules", arguments);
if(!moduleData || !moduleData.modules){
return e.error("Invalid parameters passed");
}
for(var i = 0;i < moduleData.modules.length;i ++){
var result = this.expandModule(moduleData, moduleData.modules[i].id);
if(result.isError){
return e.error(result);
}
}
return moduleData;
},
// Locates and returns module by its Id;
findModule: function(moduleData, moduleId){
var e = errorFact.create("moduleFact.findModule", arguments);
if(!moduleData || !moduleData.modules || !moduleId){
return e.error("Invalid parameters passed");
}
for(var i = 0;i < moduleData.modules.length;i ++){
if(moduleData.modules[i].id == moduleId){
return moduleData.modules[i];
}
}
return e.error("Module with Id = " + moduleId + " not found");
},
// Locates and returns Hint Group by its Id;
findHintGroup: function(moduleData, hintGroupId){
var e = errorFact.create("moduleFact.findHintGroup", arguments);
if(!moduleData || !moduleData.hintGroups || !hintGroupId){
return e.error("Invalid parameters passed");
}
for(var i = 0;i < moduleData.hintGroups.length;i ++){
if(moduleData.hintGroups[i].id == hintGroupId){
return moduleData.hintGroups[i];
}
}
return e.error("Hint Group with Id = " + hintGroupId + " not found");
}
}
}]);
So, when you have such factory in place, your high-level code, such as in a controller would just log any issues as shown in the example below:
"use strict";
app.controller('standardsCtrl', ['$scope', 'moduleFact', function($scope, moduleFact){
var data = ...//getting data;
var mod = moduleFact.expandAllModules(data);
if(mod.isError){
mod.log(); // log all error details into the console;
}else{
// use the data
}
});
}]);
You can override the $exceptionHandler in order to pass the exceptions to your own central service for exceptions, but the $exceptionHandler seems to only receive the exceptions thrown from your controllers, directives, etc... but not for the exceptions originated from ajax calls. For those exceptions you can implement an interceptor like the one described in this page:
EDITED: Link is dead permanently.
Archive.org link
whats your opinion to create a centralized error handling function for your app
so whenever an error happened with your frontend tear (angular, API calls,...) it executed, so no need to write your error handling every time
so here is my code
(function () {
'use strict';
angular
.module('app')
.factory('$exceptionHandler', ExceptionHandler);
ExceptionHandler.$inject = ['$injector']; //for minification
function ExceptionHandler($injector) {
var $log, sweetAlert, $translate;
return function exceptionHandler(exception, cause) {
// Add DI here to prevent circular dependency
$log = $log || $injector.get('$log');
sweetAlert = sweetAlert || $injector.get('sweetAlert'); //19degrees.ngSweetAlert2
$translate = $translate || $injector.get('$translate');
// $loggerService = $loggerService || $injector.get('$loggerService');
var title, message;
title = $translate.instant('General error title');
message = $translate.instant('General error message', { exceptionMessage: exception.message });
sweetAlert.error(title, message);
$log.error(exception, cause);
// loggerService.logErrorsToBackend(exception, cause);
};
}
})();
I'm not sure if this approach considered to be a best practice but hope it helps you.