IRC String comparison is always true - if-statement

I'm trying to simply compare a line in a text file to today's date.
The line I want help with always seems to evaluate true for my code.
Any examples?
My code:
set %lines $lines(test.txt)
set %date $adate
while (%i <= %lines)
set %read $read(test.txt, n, %i)
if( %date isin %read ){ ; <-- Line in question
do things
}
}

You have a few errors.
Your while loop is missing an open bracket. (And closing at the end)
while (%i <= %lines) {
You must have a space between () { } and the rest of the lines
if<space>(
)<space> {
if ( %date isin %read ) {
I took the liberty of suggesting another version.
Code:
var %filename = test.txt
var %lines = $lines(%filename)
var %currentDate = $adate
var %i = 1
while (%i <= %lines) {
var %line = $read(%filename, n, %i)
if (%currentDate isin %line) {
# do things
# Should uncomment the break in case you want to stop after a match
#break
}
inc %i
}

I am sorry if I didn't understand, but what is the reason for a complex script just to check if there is a date format in a line of a text file?
There is no reason to set a variable %read to store the line of the loop in question, when you can do an IF condition after the loop:
var %x = 1
while (%x <= $lines(test.txt)) {
if ($adate isin $read(test.txt,n,%x)) {
;do things
}
inc %x
}

Related

Google Script - Removing Else statement properly so it skips/ignores

I have a checklist, column C indicates which test is automated by "enabled" or "disabled" written in the cells.
Further down the row is a column for the the Pass / Empty column for each test.
I have code that looks for if Enabled in column C, in X column on that row, mark as Pass automatically (or 'P' in my case).
The problem: If C column contains "Disabled" but also a Pass, when I run the script it replaces that Pass with an empty cell. How can I change the else statement to just ignore that cell and leave whatever is in it for anything but Enabled condition is met
function autoPassPC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Aug 2020');
// What to put in the test result
var values1 = "P";
// Where to look for Auto:
var values2 = sheet.getRange("C10:C15" + sheet.getLastRow()).getValues();
// Keyword to look for in Auto: column
var putValues = [];
for (var i = 0; i < values2.length; i++) {
if (values2[i][0] === "Enabled") {
putValues.push([values1]);
} else {
putValues.push([""]);
}
}
// Put value1 inside row, column# for test result
sheet.getRange(10, 25, putValues.length, 1).setValues(putValues);
}
Basically how do I get rid of
} else {
putValues.push([""]);
}
properly? Just deleting this causes the script to put 'P' on every single row. Just want it to ignore the cells instead.
Thanks!
Removing the else statement will actually skip the row, but as soon as you skip a row, all following values in putValues will be on the wrong row. Instead of "skipping", try pushing the already existing value into putValues.
function autoPassPC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Aug 2020');
// What to put in the test result
var values1 = "P";
// Where to look for Auto:
var enabledDisabled = sheet.getRange("C10:C15" + sheet.getLastRow()).getValues();
var testResultsRange = sheet.getRange("X10:X15" + sheet.getLastRow());
var testResults = testResultsRange.getValues();
// Keyword to look for in Auto: column
var putValues = [];
for (var i = 0; i < enabledDisabled.length; i++) {
if (enabledDisabled[i][0] === "Enabled") {
putValues.push([values1]);
} else {
putValues.push([testResults[i][0]]); // Push the existing cell value
}
}
// Put value1 inside row, column# for test result
testResultsRange.setValues(putValues);
}
You could also try getting the entire table at once thus having only one getValues() call.

Input mask through directive

I want an input to follow the following format:
[00-23]:[00-59]
We use angular 2.4 so we don't have the pattern directive available and I cannot use external libraries (primeNG).
So I'm trying to make a directive for that:
#HostListener('keyup', ['$event']) onKeyUp(event) {
var newVal = this.el.nativeElement.value.replace(/\D/g, '');
var rawValue = newVal;
// show default format for empty value
if(newVal.length === 0) {
newVal = '00:00';
}
// don't show colon for empty groups at the end
else if(newVal.length === 1) {
newVal = newVal.replace(/^(\d{1})/, '00:0$1');
} else {
newVal = newVal.replace(/^(\d{2})(\d{2})/, '$1:$2');
}
// set the new value
this.el.nativeElement.value = newVal;
}
This works for the first 2 digits I enter.
Starting string:
00:00
Pressing numpad 1:
00:01
pressing numpad 2:
00:12
But on the third digit I get:
00:123
Instead of 01:23 and 00:1234 instead of 12:34
Backspace works as expected.
Is there a solution to this problem using only a directive?
In the last rejex try replace(/^(\d{0,2})(\d{0,2})/g, '$1:$2'). Hope this will help.

Eliminate newlines in google app script using regex

I'm trying to write part of an add-on for Google Docs that eliminates newlines within selected text using replaceText. The obvious text.replaceText("\n",""); gives the error Invalid argument: searchPattern. I get the same error with text.replaceText("\r","");. The following attempts do nothing: text.replaceText("/\n/","");, text.replaceText("/\r/","");. I don't know why Google App Script does not allow for the recognition of newlines in regex.
I am aware that there is an add-on that does this already, but I want to incorporate this function into my add-on.
This error occurs even with the basic
DocumentApp.getActiveDocument().getBody().textReplace("\n","");
My full function:
function removeLineBreaks() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only deal with text elements
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
if (element.isPartial()) {
text.replaceText("\n","");
}
// Deal with fully selected text
else {
text.replaceText("\n","");
}
}
}
}
// No text selected
else {
DocumentApp.getUi().alert('No text selected. Please select some text and try again.');
}
}
It seems that in replaceText, to remove soft returns entered with Shift-ENTER, you can use \v:
.replaceText("\\v+", "")
If you want to remove all "other" control characters (C0, DEL and C1 control codes), you may use
.replaceText("\\p{Cc}+", "")
Note that the \v pattern is a construct supported by JavaScript regex engine, and is considered to match a vertical tab character (≡ \013) by the RE2 regex library used in most Google products.
The Google Apps Script function replaceText() still doesn't accept escape characters, but I was able to get around this by using getText(), then the generic JavaScript replace(), then setText():
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var bodyText = body.getText();
//DocumentApp.getUi().alert( "Does document contain \\t? " + /\t/.test( bodyText ) ); // \n true, \r false, \t true
bodyText = bodyText.replace( /\n/g, "" );
bodyText = bodyText.replace( /\t/g, "" );
body.setText( bodyText );
This worked within a Doc. Not sure if the same is possible within a Sheet (and, even if it were, you'd probably have to run this once cell at a time).
here is my pragmatic solution to eliminate newlines in Google Docs, or, more exact, to eliminate newlines from Gmail message.getPlainBody().
It looks that Google uses '\r\n\r\n' as a plain EOL and '\r\n' as a manuell Linefeed (Shift-Enter). The code should be self explainable.
It might help to get alone with the newline problem in Docs.
A solution possibly not very elegant, but works like a charm :-)
function GetEmails2Doc() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var pc = 0; // Paragraph Counter
var label = GmailApp.getUserLabelByName("_Send2Sheet");
var threads = label.getThreads();
var i = threads.length;
// LOOP Messages within a THREAT
for (i=threads.length-1; i>=0; i--) {
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
/* Here I do some ...
body.insertParagraph(pc++, Utilities.formatDate(message.getDate(), "GMT",
"dd.MM.yyyy (HH:mm)")).setHeading(DocumentApp.ParagraphHeading.HEADING4)
str = message.getFrom() + ' to: ' + message.getTo();
if (message.getCc().length >0) str = str + ", Cc: " + message.getCc();
if (message.getBcc().length >0) str = str + ", Bcc: " + message.getBcc();
body.insertParagraph(pc++,str);
*/
// Body !!
var str = processBody(message.getPlainBody()).split("pEOL");
Logger.log(str.length + " EOLs");
for (var k=0; k<str.length; k++) body.insertParagraph(pc++,str[k]);
}
}
}
function processBody(tx) {
var s = tx.split(/\r\n\r\n/g);
// it looks like message.getPlainBody() [of mail] uses \r\n\r\n as EOL
// so, I first substitute the 'EOL's with the string pattern "pEOL"
// to be replaced with body.insertParagraph in the main function
tx = '';
for (k=0; k<s.length; k++) tx = tx + s[k] + "pEOL";
// then replace all remaining simple \r\n with a blank
s = tx.split(/\r\n/g);
tx = '';
for (k=0; k<s.length; k++) tx = tx + s[k] + " ";
return tx;
}
I have now found out through much trial and error -- and some much needed help from Wiktor Stribiżew (see other answer) -- that there is a solution to this, but it relies on the fact that Google Script does not recognise \n or \r in regex searches. The solution is as follows:
function removeLineBreaks() {
var selection = DocumentApp.getActiveDocument()
.getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only deal with text elements
if (element.getElement()
.editAsText) {
var text = element.getElement()
.editAsText();
if (element.isPartial()) {
var start = element.getStartOffset();
var finish = element.getEndOffsetInclusive();
var oldText = text.getText()
.slice(start, finish);
if (oldText.match(/\r/)) {
var number = oldText.match(/\r/g)
.length;
for (var j = 0; j < number; j++) {
var location = oldText.search(/\r/);
text.deleteText(start + location, start + location);
text.insertText(start + location, ' ');
var oldText = oldText.replace(/\r/, ' ');
}
}
}
// Deal with fully selected text
else {
text.replaceText("\\v+", " ");
}
}
}
}
// No text selected
else {
DocumentApp.getUi()
.alert('No text selected. Please select some text and try again.');
}
}
Explanation
Google Docs allows searching for vertical tabs (\v), which match newlines.
Partial text is a whole other problem. The solution to dealing with partially selected text above finds the location of newlines by extracting a text string from the text element and searching in that string. It then uses these locations to delete the relevant characters. This is repeated until the number of newlines in the selected text has been reached.
This Stack Overflow answer removes, specifically, "\n". It may help, it helped me indeed.

AS3 and HTML5 - parse string into array using regex

I've been looking and playing with RegEx for a while now and am trying to find this solution that I can apply to both AS3 and to HTML5.
I've got a custom user entry section, 256 chars that they can customize.
What I would like is for them to use my predefined table of codes 00 - 99 and they can insert them into the box to automatically generate a response that can go through a few hundred examples.
Here is a simple example:
Please call: 04
And ask for help for product ID:
03
I'd be able to take this and say, okay i got the following into an array:
[Please call: ]
[04]
[/n]
[And ask for help for product ID: ]
[/n]
[03]
and possibly apply a flag to say whether this is a database entry or not
[Please call: ][false]
[04][true]
[/n][false]
[And ask for help for product ID: ][false]
[/n][false]
[03][true]
this would be something that my program could read. Where I know that for the ## matches, to find a database entry and insert, though for anything else, use the strings.
I have been playing around on
http://gskinner.com/RegExr/
to try and brute force an answer to no avail so far.
Any help would be greatly appreciated.
The best I've come up with so far for matches is the following. Though this is my first time playing with the regex functions and would need to find out how to push these entries into my ordered array.
\d\d
\D+
And would need some way to combine them to pull an array... or I'll be stuck with a crappy loop:
//AS3 example
database_line_item:int = 127;
previous_value_was_int:boolean = false;
_display_text:string = "";
for(var i:int = 0; i < string.length; i++){
if(string.charAt(i) is int){
if(previous_value_was_in){
previous_value_was_int = true;
}else{
_display_text += getDatabaseValue(string.charAt(i-1)+string.charAt(i), database_line_item);
previous_value_was_int = false;
}
}else{
//Hopefully this handles carriage returns, if not, will have to add that in.
_display_text += string.charAt(i);
}
}
// >>>>>>>>> HTML5 Example <<<<<<<<<<<<<
...
and I would cycle through the database_line_item, though for maybe 400 line items, this will be a taxing, to go through that string. Splitting it into smaller arrays would be easier to handle.
Here is the magic reg : /([^0-9\n\r]+)|(\d+)|(\r\n?|\n)/gi
Exemple output :
[Please call: ][false]
[4][true]
[/n][false]
[And ask for help for product ID:][false]
[/n][false]
[3][true]
Exemple code that do the job and put the data into an array :
package
{
import flash.display.Sprite;
public class TestReg extends Sprite
{
public function TestReg()
{
super();
var data : Array = parse("Please call: 04\n"+
"And ask for help for product ID:\n"+
"03");
// Output
for(var i : uint = 0; i < data.length; i += 2)
trace("[" + data[ i ] + "][" + data[ i + 1 ] + "]");
}
private var _search : RegExp = /([^0-9\n\r]+)|(\d+)|(\r\n?|\n)/gi;
public function parse(str : String) : Array
{
var result : Array = [];
var data : Array = str.match( _search );
for each(var item : * in data)
{
// Replace new line by /n
if(item.charAt( 0 ) == "\n" || item.charAt( 0 ) == "\r")
item = "/n";
// Convert to int if is a number
if( ! isNaN( parseFloat( item.charAt( 0 ) ) ) )
item = parseInt( item );
result.push( item );
result.push( !( item is String ));
}
return result;
}
}
}

Restrict TextField to act like a numeric stepper

I am making a numeric stepper from scratch, so I want my text field to only accept numbers in this format: xx.x, x.x, x, or xx where x is a number. For example:
Acceptable numbers:
1
22
15.5
3.5
None Acceptable numbers:
213
33.15
4332
1.65
Maybe this will help some how:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html#restrict
This is what I got so far:
var tx:TextField = new TextField();
tx.restrict="0-9."; //Maybe there is a regular expression string for this?
tx.type=TextFieldType.INPUT;
tx.border=true;
You can copy past this in flash and it should work.
Thank you very much for your help good sirs.
Very similar to TheDarklins answer, but a little more elegant. And actually renders _tf.restrict obsolete, but I would still recommend using it.
_tf.addEventListener(TextEvent.TEXT_INPUT, _onTextInput_validate);
Both of these event listeners here do the EXACT same function identically. One is written in a one line for those who like smaller code. The other is for those who like to see what's going on line by line.
private function _onTextInput_validate(__e:TextEvent):void
{
if ( !/^\d{1,2}(?:\.(?:\d)?)?$/.test(TextField(__e.currentTarget).text.substring(0, TextField(__e.currentTarget).selectionBeginIndex) + __e.text + TextField(__e.currentTarget).text.substring(TextField(__e.currentTarget).selectionEndIndex)) ) __e.preventDefault();
}
for a more broken down version of the event listener
private function _onTextInput_validate(__e:TextEvent):void
{
var __reg:RegExp;
var __tf:TextField;
var __text:String;
// set the textfield thats causing the event.
__tf = TextField(__e.currentTarget);
// Set the regular expression.
__reg = new RegExp("\\d{1,2}(?:\\.(?:\\d)?)?$");
// or depending on how you like to write it.
__reg = /^\d{1,2}(?:\.(?:\d)?)?$/;
// Set all text before the selection.
__text = __tf.text.substring(0, __tf.selectionBeginIndex);
// Set the text entered.
__text += __e.text;
// Set the text After the selection, since the entered text will replace any selected text that may be entered
__text += __tf.text.substring(__tf.selectionEndIndex);
// If test fails, prevent default
if ( !__reg.test(__text) )
{
__e.preventDefault();
}
}
I have had to allow xx. as a valid response otherwise you would need to type 123 then go back a space and type . for 12.3. That is JUST NOT NICE. So 12. is now technically valid.
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.TextEvent;
public class DecimalPlaces extends Sprite
{
public function DecimalPlaces()
{
var tf:TextField = new TextField();
tf.type = TextFieldType.INPUT;
tf.border = true;
tf.width = 200;
tf.height = 16;
tf.x = tf.y = 20;
tf.restrict = ".0-9"
tf.addEventListener(TextEvent.TEXT_INPUT, restrictDecimalPlaces);
addChild(tf);
}
function restrictDecimalPlaces(evt:TextEvent):void
{
var matches:Array = evt.currentTarget.text.match(/\./g);
var allowedDecimalPlaces:uint = 1;
if ((evt.text == "." && matches.length >= 1) ||
(matches.length == 1 && (evt.currentTarget.text.lastIndexOf(".") + allowedDecimalPlaces < evt.currentTarget.text.length)))
evt.preventDefault();
}
}
}