regexp.test() returns boolean but not on 'if' statement - always evaluates to - google-apps-script

I am working on a standalone interface.
I have several text boxes, and all have Names and IDs.
If I run this code:
var re = /someregexp/g;
var k ="sometext";
textBoxOne.setText(re.test(k)); //textBoxOne was selected first
The correct result 'true' or 'false' is displayed.
asking for a 'typeof(re.test(k))' correctly returns boolean.
However this code:
if (re.test(k)) {
textBoxTwo.setText("matched.");
} else {
textBoxTwo.setText("NOT matched.");
}
Always goes into the 'else' branch. if (re.test(k) == true) renders the same result.
Looks like a bug to me, anyone else also found this?

Edit: AdamL has pointed out (thanks Adam), in his comments below, that there is more to this than I supposed. I leave my original code below for reference.
The myFunction2() below follows the "matched" branch as you would expect a correctly working regex (so perhaps this can be used to work around the bug):
function myFunction2() {
var k ="sometext";
Logger.log( /ome/g.test(k) );
if ( /ome/g.test(k) ) {
Logger.log("matched.");
} else {
Logger.log("NOT matched.");
}
}
Conversely, as you have observed, the myFunction() below unexpectedly follows through to the "NOT matched" branch.
function myFunction() {
var re = /ome/g;
var k ="sometext";
Logger.log(re.test(k));
if (re.test(k)) {
Logger.log("matched.");
} else {
Logger.log("NOT matched.");
}
}

Related

Extra "Space" at end of "If" Requirement AS3

My code works, except it is requiring and extra "Space" at the end to be placed in order for the button to activate? Any ideas? I obviously don't have the space at the end of the user names or passwords in the code. This happens on another frame as well where I have the user type in a web address, I have the conditional set as == "md.website.com" but it is requiring "md.website.com " (extra space at the end) in order for the button to activate.
This code is expecting "AB1234 " and "newuser " instead of "AB1234" "newuser" like I need and I am telling it... I'm sorry, I'm new to AS3 and learning ALL I can, this site rocks for all the help I've already gotten!
username_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
password_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
next_btn.enabled = false;
next_btn.alpha = .5;
function paramChanged3(event:TextEvent):void
{
if (username_txt.text == "AB1234" && password_txt.text == "newuser" )
{
trace("go")
next_btn2.enabled = true;
next_btn2.alpha = 1;
next_btn2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndPlay_20)
}
else
{
next_btn2.enabled = false;
next_btn2.alpha = .5;
}
}
function fl_ClickToGoToAndPlay_20(event:MouseEvent):void
{
gotoAndPlay(20);
}
The problem is that the TextEvent.TEXT_INPUT fires before the text field is actually updated. Try using Event.CHANGE instead (or using two TextEvent.TEXT_INPUT callbacks and appending the input character with event.text within each).
I don't know why AS3 is requiring the extra space, but I removed the exact conditional, and just did a minimum character count. Of course the trainee can then type in anything as long as it matches the minimum requirement, but again, the actual usernames and passwords don't matter, its all simulation anyways, here is the code with the character count....
username_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
password_txt.addEventListener(TextEvent.TEXT_INPUT,paramChanged3);
next_btn.enabled = false;
next_btn.alpha = .5;
function paramChanged3(event:TextEvent):void
{
if (username_txt.text != "" && username_txt.length >=5 &&
password_txt.text != "" && password_txt.length >=6)
{
trace("go")
next_btn2.enabled = true;
next_btn2.alpha = 1;
next_btn2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndPlay_20)
}
else
{
next_btn2.enabled = false;
next_btn2.alpha = .5;
}
}
function fl_ClickToGoToAndPlay_20(event:MouseEvent):void
{
gotoAndPlay(20);
}

Warning messages with EZAPI EzDerivedColumn and input columns

When adding a derived column to a data flow with ezAPI, I get the following warnings
"Add stuff here.Inputs[Derived Column Input].Columns[ad_zip]" on "Add
stuff here" has usage type READONLY, but is not referenced by an
expression. Remove the column from the list of available input
columns, or reference it in an expression.
I've tried to delete the input columns, but either the method is not working or I'm doing it wrong:
foreach (Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSInputColumn100 col in derFull.Meta.InputCollection[0].InputColumnCollection)
{
Console.WriteLine(col.Name);
derFull.DeleteInputColumn(col.Name);
}
I have the following piece of code that fixes the problem.
I got it from a guy called Daniel Otykier. So he is propably the one that should be credited for it... Unlesss he got it from someone else :-)
static public void RemoveUnusedInputColumns(this EzDerivedColumn component)
{
var usedLineageIds = new HashSet<int>();
// Parse all expressions used in new output columns, to determine which input lineage ID's are being used:
foreach (IDTSOutputColumn100 column in component.GetOutputColumns())
{
AddLineageIdsFromExpression(column.CustomPropertyCollection, usedLineageIds);
}
// Parse all expressions in replaced input columns, to determine which input lineage ID's are being used:
foreach (IDTSInputColumn100 column in component.GetInputColumns())
{
AddLineageIdsFromExpression(column.CustomPropertyCollection, usedLineageIds);
}
var inputColumns = component.GetInputColumns();
// Remove all input columns not used in any expressions:
for (var i = inputColumns.Count - 1; i >= 0; i--)
{
if (!usedLineageIds.Contains(inputColumns[i].LineageID))
{
inputColumns.RemoveObjectByIndex(i);
}
}
}
static private void AddLineageIdsFromExpression(IDTSCustomPropertyCollection100 columnProperties, ICollection<int> lineageIds)
{
int lineageId = 1;
var expressionProperty = columnProperties.Cast<IDTSCustomProperty100>().FirstOrDefault(p => p.Name == "Expression");
if (expressionProperty != null)
{
// Input columns used in expressions are always referenced as "#xxx" where xxx is the integer lineage ID.
var expression = expressionProperty.Value.ToString();
var expressionTokens = expression.Split(new[] { ' ', ',', '(', ')' });
foreach (var c in expressionTokens.Where(t => t.Length > 1 && t.StartsWith("#") && int.TryParse(t.Substring(1), out lineageId)))
{
if (!lineageIds.Contains(lineageId)) lineageIds.Add(lineageId);
}
}
}
Simple but not 100% Guaranteed Method
Call ReinitializeMetaData on the base component that EzApi is extending:
dc.Comp.ReinitializeMetaData();
This doesn't always respect some of the customizations and logic checks that EzAPI has, so test it carefully. For most vanilla components, though, this should work fine.
100% Guaranteed Method But Requires A Strategy For Identifying Columns To Ignore
You can set the UsageType property of those VirtualInputColumns to the enumerated value DTSUsageType.UT_IGNORED using EzApi's SetUsageType wrapper method.
But! You have to do this after you're done modifying any of the other metadata of your component (attaching other components, adding new input or output columns, etc.) since each of these triggers the ReinitializeMetaData method on the component, which automatically sets (or resets) all UT_IGNORED VirtualInputColumn's UsageType to UT_READONLY.
So some sample code:
// define EzSourceComponent with SourceColumnToIgnore output column, SomeConnection for destination
EzDerivedColumn dc = new EzDerivedColumn(this);
dc.AttachTo(EzSourceComponent);
dc.Name = "Errors, Go Away";
dc.InsertOutputColumn("NewDerivedColumn");
dc.Expression["NewDerivedColumn"] = "I was inserted!";
// Right here, UsageType is UT_READONLY
Console.WriteLine(dc.VirtualInputCol("SourceColumnToIgnore").UsageType.ToString());
EzOleDbDestination d = new EzOleDbDestination(f);
d.Name = "Destination";
d.Connection = SomeConnection;
d.Table = "dbo.DestinationTable";
d.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD;
d.AttachTo(dc);
// Now we can set usage type on columns to remove them from the available inputs.
// Note the false boolean at the end.
// That's required to not trigger ReinitializeMetadata for usage type changes.
dc.SetUsageType(0, "SourceColumnToIgnore", DTSUsageType.UT_IGNORED, false);
// Now UsageType is UT_IGNORED and if you saved the package and viewed it,
// you'll see this column has been removed from the available input columns
// ... and the warning for it has gone away!
Console.WriteLine(dc.VirtualInputCol("SourceColumnToIgnore").UsageType.ToString());
I was having exactly your problem and found a way to solve it. The problem is that the EzDerivedColumn has not the PassThrough defined in it's class.
You just need to add this to the class:
private PassThroughIndexer m_passThrough;
public PassThroughIndexer PassThrough
{
get
{
if (m_passThrough == null)
m_passThrough = new PassThroughIndexer(this);
return m_passThrough;
}
}
And alter the ReinitializeMetadataNoCast() to this:
public override void ReinitializeMetaDataNoCast()
{
try
{
if (Meta.InputCollection[0].InputColumnCollection.Count == 0)
{
base.ReinitializeMetaDataNoCast();
LinkAllInputsToOutputs();
return;
}
Dictionary<string, bool> cols = new Dictionary<string, bool>();
foreach (IDTSInputColumn100 c in Meta.InputCollection[0].InputColumnCollection)
cols.Add(c.Name, PassThrough[c.Name]);
base.ReinitializeMetaDataNoCast();
foreach (IDTSInputColumn100 c in Meta.InputCollection[0].InputColumnCollection)
{
if (cols.ContainsKey(c.Name))
SetUsageType(0, c.Name, cols[c.Name] ? DTSUsageType.UT_READONLY : DTSUsageType.UT_IGNORED, false);
else
SetUsageType(0, c.Name, DTSUsageType.UT_IGNORED, false);
}
}
catch { }
}
That is the strategy used by other components. If you want to see all the code you can check my EzApi2016#GitHub. I'm updating the original code from Microsoft to SQL Server 2016.

Checking for same values using if statement in actionscript?

I'm working on a match-3 style puzzle game using Flixel, and so I'm working on checking each row and column to see if there is a match at any given time. However, I have 6 different pieces (as of right now) that are active, and each piece is identified by an integer. Given that, I can check, for each and every single piece, by doing something like this:
public function matchingCheck():void
{
if (piecesArray[0][1] == 1 && piecesArray[1][1] == 1 && piecesArray[2][1] == 1) {
FlxG.log("Yay!");
}
}
However, this is rather unwieldy and would basically cause way too much repetition for my liking.
At the very least, I would like to be able to check if the values in these arrays are equal to one another, without having to specify which value it is. At the very best, I'd love to be able to check an entire row for three (or more) adjacent pieces, but I will settle for doing that part manually.
Thanks for your help!
EDIT: Nevermind, my edit didn't work. It was just checking if piecesArray[2][1] == 1, which makes me a sad panda.
EDIT 2: I've selected the correct answer below - it's not exactly what I used, but it definitely got me started. Thanks Apocalyptic0n3!
You could cut down on that code a little bit by using another function
private function checkValid( arrayOfItemsToCheck:Array, value:* ):Boolean {
for ( var i:Number = 0; i < arrayOfItemsToCheck.length; i++ ) {
if ( arrayOfItemsToCheck[i] != value ) {
return false;
}
}
return true;
}
Then you just do this in your if statement:
if ( checkValid( [ piecesArray[0][1], piecesArray[1][1], piecesArray[2][1] ], 1 ) ) {
FlxG.log("Yay!");
}
That does assume all items need to be equal to 1, though. It's still a lot of code, but it cuts out one set of "= 1 &&" for each check.
How about something like this which would tell you both if a match existed and what match it was:
public function checkForMatch():void{
var rows:int = piecesArray.length;
for(var i:int=0; i<rows; i++){
var match:int = checkRow(piecesArray[i]);
if(match > -1) {
FlxG.log("Yay you matched " + match);
}
}
}
private function ckeckRow(row:Array):int{
if(row[0] == row[1] == row[2]){
return row[0];
}
return -1;
}

What does this line of Actionscript do?

I'm looking at the as3delaunay library and most of the code is clear to me. This part is not, however (note the line that I put preceded with an arrow):
public function circles():Vector.<Circle>
{
var circles:Vector.<Circle> = new Vector.<Circle>();
for each (var site:Site in _sites)
{
var radius:Number = 0;
var nearestEdge:Edge = site.nearestEdge();
=======>> !nearestEdge.isPartOfConvexHull() && (radius = nearestEdge.sitesDistance() * 0.5);
circles.push(new Circle(site.x, site.y, radius));
}
return circles;
}
For reference, isPartOfConvexHull() is found in Edge.as and looks like this:
internal function isPartOfConvexHull():Boolean
{
return (_leftVertex == null || _rightVertex == null);
}
What does !nearestEdge.isPartOfConvexHull() do? Does that mean that the radius = nearestEdge.sitesDistance() * 0.5 only executes if false is returned from the call to isPartOfConvexHull()? Does that stop execution of any other code?
It is equivalent to:
if (!nearestEdge.isPartOfConvexHull()) {
radius = nearestEdge.sitesDistance() * 0.5;
}
In the following line:
var b:Boolean = expression1 && expression2;
expression2 will not be evaluated if expression1 is false because we already know the final result: b = false.
Now in the following line:
expression1 && expression2;
The same thing happens except the fact that we are not assigning the result to a variable.
And this is exactly what happens in the line you are asking about where !nearestEdge.isPartOfConvexHull() is the first expression and (radius = nearestEdge.sitesDistance() * 0.5) is the second expression.
To extends #sch answer with some explanations (I didn't knew if editing answer to almost double it was ok).
This is based on lazy execution of the interpreter. If (!nearestEdge.isPartOfConvexHull()) is False then there's no need to execute the second part of the AND statement to know it'll be False, then it's left unexecuted. If it's true the evaluation of the complete statement is needed (and then done) to tell wether or not this boolean is True. So this is equivalent to an if statement.
TMHO this is bad code since it's to much condensed and hard to understand.

AS3 odd or even (mal)function

please
how to fix this AS3 function ?
thank you
function dispari(numero:int):Boolean;
{
//check if the number is odd or even
if (numero % 2 == 0)
{
returns false;
}
else
{
returns true;
}
}
ERROR:
1071: Syntax error: expected a definition keyword (such as function) after attribute returns, not false.
Why do you have a semi-colon (;) at the end of your function statement? I don't do any AS3 coding but it doesn't look right, and a cursory glance at a few samples on the web don't have it there.
I suspect that may be what's causing your problem. Try this instead:
function dispari(numero:int):Boolean
{
//check if the number is odd or even
if (numero % 2 == 0)
{
return false;
}
else
{
return true;
}
}
I've also changed the return statements to match what every other piece of AS3 does to return values (thanks, #Herms, forgot to mention that :-)
Pax is correct with there answer, but you can simplify it by just returning the result:
function dispari(numero:int):Boolean
{
return (numero % 2 != 0);
}