Codename One - RegexConstraint to check a valid phone number - codenameone

In the following code, the RegexConstraint doesn't work, because the phone number results always incorrect. What's wrong? I need to check a mobile phone number (without the country code). For example, the input 3652312453 should be correct, but in the following code it's evaluated as incorrect.
I copied the regex from the discussion linked in the comment: my only requirement is a valid phone number.
(Note: this question is not for generic Java, but only for Codename One. The class "CountryCodePicker" extends the class "Button": I reported it to make it clear that the phone number and the country code are separated)
TextModeLayout tl = new TextModeLayout(1, 1);
Container loginContainer = new Container(tl);
TextComponent phone = new TextComponent().label("PHONE").errorMessage("INVALID-PHONE");
CountryCodePicker countryCode = new CountryCodePicker();
phone.getField().setConstraint(TextArea.PHONENUMBER);
loginContainer.add(phone);
Container loginContainerWithCodePicker = new Container(new BoxLayout(BoxLayout.X_AXIS_NO_GROW));
loginContainerWithCodePicker.add(countryCode).add(loginContainer);
// https://stackoverflow.com/questions/8634139/phone-validation-regex
String phoneRegEx = "/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/";
val.addConstraint(phone, new RegexConstraint(phoneRegEx, "NOT-VALID-NUMBER"));
Button loginButton = new Button("LOG-IN");
val.addSubmitButtons(loginButton);

[rant]
Personally I really hate regex as I find it damn unreadable for anything other than trivial validation.
[/rant]
So I would prefer this:
val.addConstraint(phone, new Constraint() {
public boolean isValid(Object value) {
String v = (String)value;
for(int i = 0 ; i < v.length() ; i++) {
char c = v.charAt(i);
if(c >= '0' && c <= '9' || c == '+' || c == '-') {
continue;
}
return false;
}
return true;
}
public String getDefaultFailMessage() {
return "Must be valid phone number";
}
});
However, I'm guessing the reason the regex failed for you is related to the syntax with the slashes:
String phoneRegEx = "^\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})";

The following resource on Oracle's Java 8 Lessons helps me always define the RegEx I need. Take the time to study it and you will be successful, especially since the problem seems to be in the initialization of the Constraint object. I had an issue the day before my post here, and managed to solve it elegantly which is the goal, always.
Use this link
https://docs.oracle.com/javase/tutorial/essential/regex/
Oracle Tutorials: "Lesson: Regular Expressions".

Related

Storing story data for text adventure AS3

I've been on and off creating a text adventure using a rudimentary engine I made for about a year.
For the story, I have a object array(is that what it's called?) with various story data stuff that I parse through
I've been told that using it the way I am is stupid because it's supposed to be used for other stuff but I only use it because it was easy to learn how to parse the data since I was a beginner
It's getting tedious writing the story and doing stuff for each part (creating the backgrounds and such) since it's so long.
Is there any kind of way I can make it easier for me to write the story?
Here's the object array with a single part set up (with choices)
public static var parts:Object =
{
"0":
{
"text":"Text here",
"choices":
{
"response1":
{
"text":"Response1",
"nextPart":"1"
},
"response2":
{
"text":"Response2",
"nextPart":"2"
}
},
"background": Assets.AssetClass.Background1,
"BGM":"bg1"
},
}
Here's an example of how my engine deals with parts and changing them:
I have a input checker to check when enter is pressed and then do stuff depending on what is on the screen
public function onEnter(button:KeyboardEvent):void
{
if (button.keyCode == 32 && !Won)
{
if (Dead && textFinished && !choosing) // pressing enter while dead and the text is still writing
{
curPart = parts[curPart]["lastPart"] // lastPart will only be stored in parts that have the player die
textFinished = false
Dead = false;
myTextField.text = ""
counter = 0;
sInt = setInterval(addCharackter, textSpeed)
if (stage.getChildByName("cText"))
{
stage.removeChild(continueText)
}
if (parts[curPart].hasOwnProperty("background")) //check if the background needs to change.
{
if (stage.getChildByName("img"))
{
stage.removeChild(background)
}
background = new Background(parts[curPart], 800, 600)
stage.addChildAt(background, 0)
}
}
if (!textFinished && !choosing)// pressing enter when there's no choices on the screen and the text isn't finished and the text is still writing
{
this.myTextField.text = this.parts[this.curPart]["text"];
clearInterval(this.sInt);
this.textFinished = true;
if (parts[curPart].hasOwnProperty("choices"))
{
choosing = true
createOptions(); // function for parsing through the responses bit of that part and displaying them
}
else
{
stage.addChildAt(continueText, 2)
}
if (parts[curPart].hasOwnProperty("lastPart"))
{
Dead = true;
dead()
}
}
else if (textFinished && !choosing && !Dead) // pressing enter if there's no choices on the screen and there's no choices (it'll take you to the next part)
{
trace("Text finished!!")
curPart = parts[curPart]["nextPart"]
myTextField.text = ""
counter = 0;
sInt = setInterval(addCharackter, textSpeed)
textFinished = false;
if (parts[curPart].hasOwnProperty("background"))
{
if (stage.getChildByName("img"))
{
trace("Removed!")
stage.removeChild(background)
}
background = new Background(parts[curPart], 800, 600)
stage.addChildAt(background, 0)
}
if (parts[curPart].hasOwnProperty("BGM")) // does the current part have a new background music?
{
trace("Music!!!!")
sndBGMusic = musicArray[parts[curPart]["BGM"]]
sndBGMusicChannel.stop()
sndBGMusicChannel = sndBGMusic.play(0, 9999999999)
stage.addChildAt(background, 0)
}
stage.removeChild(continueText)
}
}
}
A couple ideas here. These are just things I would do differently than what you have done. I don't guarantee that they are better in any way, but see what you think.
I would have a global variable for _curPart. And I would have a custom class called Part. That class would have properties like _BGM, _bgImage etc. It could have a _choicesArray as a property as well. I'd have other global variables like _hasCandle. Or you can store items in an array and if you need the candle just check if candle is in the array. These global variables will persist from one part to the next.
Then you can access the properties of the part you are in by doing _curPart._bgImage. To me, that looks and feels cleaner.
And to create a new part it could look like (incomplete):
var p15:Part = new Part();
p15._bgImage = image15;
p15._BGM = song10;
//...
The last thing I'd recommend is to try to refactor where you can. For example, where you have //pressing enter if there's no choic... replace all of that code in that bracket with a one or a few function calls (whatever makes the most sense and allows you to reuse code). It just makes it easier to see what's going on, I think. So instead of all these if blocks, just a function like nextPart(); and then that function will have all your if blocks in it. Make sense? Personal preference, but when things are getting complicated, refactoring helps me clear out the cobwebs. Just like you do with dead() and createOptions() but I'd just take it one step further. This won't make your code more efficient, but it might make writing your code more efficient which is paramount in my book (until it's not).

Bugzilla's "Request System": do other issue tracking tools have it?

I've used Bugzilla for many years and one of my favourite features is the "request system" (http://www.bugzilla.org/features/#rs), also known as "flags". The issue can flagged (?) to a user; the user can then accept the request (+) or deny it (-).
I am in the process of re-evaluating our issue tracking tools and I can't seem to find anything other than Bugzilla that has this feature.
So I am wondering:
Does any other product offer similar functionality?
And if not, then is there a way to mimic it (using labels or custom fields or something)?
Your advice is appreciated (FYI: I am currently leaning towards YouTrack).
Alex V. asked for more details about Bugzilla's request system functionality. Here's an example:
An arbitrary list of flags can be created in the admin interface. When editing an issue, they are listed in a row, here's an example:
Next, someone can set the flag and ask for a followup. The screen shot shows me (dcherk) setting the DJiNNInput flag for john#doe.com:
Note that the same flag can be requested multiple times (not shown).
Later, john#doe.com might act on the flag in some way and mark the request as accepted:
Alternatively, john#doe.com might not be able to accept the request. In that case, he would deny it:
Needless to say, all these changes are tracked in the issue history, and can be searched and reported on.
In YouTrack there's no such functionality. What you can do, however, is you can Star the issue for a user as if the if the user did it themselves. They will then receive a notification about it and can either leave the star on the issue, or remove it.
Don't know exactly how those flags work in Bugzilla, so it's is probably not a complete replacement of that feature. If you elaborate on the desired behaviour, I'll let you know how (if possible) to completely mimic it.
FYI:
This is what we ended up doing in YouTrack:
Created two user[*] fields:
Input Requesting (i.e. the person requesting input)
Input Requested (i.e. the user whose input is needed)
The users can always set these fields manually, but we also added the following workflow rules to speed things up:
Rule 1, relates changes to the two field:
rule Input Requested
when Input Requested.changed {
if (Input Requested.isEmpty) {
Input Requesting.clear;
} else {
Input Requesting.add(loggedInUser);
}
}
Rule 2, closed issues do not need any more input:
rule Clear Input Requests When Issue Becomes Closed
when State.becomes({Closed}) {
Input Requested.clear;
Input Requesting.clear;
}
Rule 3, #mentioning sets the fields; replying clears the fields:
rule Input Requested via #mention
when comments.added.isNotEmpty {
var separators = " `!#%^&*()=[]{}:;'\"\\|,<>/?\n\r\t";
var mentionedUsers = "";
var myComment = comments.added.first;
var originalText = myComment.text;
var text = " " + originalText.lowerCase + " ";
var username = "";
var user = loggedInUser;
var index = -1;
index = text.indexOf("#", opts);
while (index != -1) {
index = index + 1;
username = "";
var nextSymbol = text.substring(index, index + 1);
while (!separators.contains(nextSymbol, opts)) {
username = username + nextSymbol;
index = index + 1;
nextSymbol = text.substring(index, index + 1);
}
if (username.endsWith(".", opts)) {
username = username.substringOfLength(username.length - 1, opts);
}
debug("Extracted #username: |" + username + "|");
if (username.isNotEmpty) {
user = project.getUser(username);
if (user != null && !mentionedUsers.contains("#" + user.login + ",", ignoreCase) && (user.isInGroup(permittedGroup.name) || permittedGroup == null || user == reporter) && (myComment.permittedGroup == null || user.isInGroup(myComment.permittedGroup.name))) {
if (Input Requesting.contains(user)) {
Input Requested.remove(loggedInUser);
if (Input Requested.isEmpty) {
Input Requesting.clear;
}
} else {
Input Requested.add(user);
Input Requesting.add(loggedInUser);
}
mentionedUsers = mentionedUsers + "#" + user.login + ",";
}
}
text = text.substringRelative("#" + username, pos: after);
index = text.indexOf("#", opts);
}
}
Hope that helps anyone along the way.

Dart VM itself implement `eval` in `dart:mirrors` and developers use it. Are planned to make this method public?

Here is code that use this eval method in Dart platform.
This is done via reflection.
runtime/lib/mirrors_impl.dart
_getFieldSlow(unwrapped) {
// ..... Skipped
var atPosition = unwrapped.indexOf('#');
if (atPosition == -1) {
// Public symbol.
f = _eval('(x) => x.$unwrapped', null);
} else {
// Private symbol.
var withoutKey = unwrapped.substring(0, atPosition);
var privateKey = unwrapped.substring(atPosition);
f = _eval('(x) => x.$withoutKey', privateKey);
}
// ..... Skipped
}
static _eval(expression, privateKey)
native "Mirrors_evalInLibraryWithPrivateKey";
runtime/lib/mirrors.cc
DEFINE_NATIVE_ENTRY(Mirrors_evalInLibraryWithPrivateKey, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(String, expression, arguments->NativeArgAt(0));
GET_NATIVE_ARGUMENT(String, private_key, arguments->NativeArgAt(1));
const GrowableObjectArray& libraries =
GrowableObjectArray::Handle(isolate->object_store()->libraries());
const int num_libraries = libraries.Length();
Library& each_library = Library::Handle();
Library& ctxt_library = Library::Handle();
String& library_key = String::Handle();
if (library_key.IsNull()) {
ctxt_library = Library::CoreLibrary();
} else {
for (int i = 0; i < num_libraries; i++) {
each_library ^= libraries.At(i);
library_key = each_library.private_key();
if (library_key.Equals(private_key)) {
ctxt_library = each_library.raw();
break;
}
}
}
ASSERT(!ctxt_library.IsNull());
return ctxt_library.Evaluate(expression);
runtime/vm/bootstrap_natives.h
V(Mirrors_evalInLibraryWithPrivateKey, 2) \
P.S.
I ask question here becuase I cannot ask it at Dart mail lists.
P.S.
As we can see it static private method in mirrors_impl.dart:
static _eval(expression, privateKey) native "Mirrors_evalInLibraryWithPrivateKey";
Does anyone want that this method should be public? (this is not a question but just a thought aloud).
According to the Dart FAQ a pure string eval like that is not likely to make it into the language, even though other dynamic features will likely be added:
So, for example, Dart isn’t likely to support evaluating a string as
code in the current context, but it may support loading that code
dynamically into a new isolate. Dart isn’t likely to support adding
fields to a value, but it may (through a mirror system) support adding
fields to a class, and you can effectively add methods using
noSuchMethod(). Using these features will have a runtime cost; it’s
important to us to minimize the cost for programs that don’t use them.
This area is still under development, so we welcome your thoughts on
what you need from runtime dynamism.

Kentico Global Events (ObjectEvents) Causes Loop

I'm using ObjectEvents to give ActivityPoints to current user based on fields user filled.
Now for example if user register and fill FirstName I will give 10 points to user.
The problem is that I'm handling ObjectEvents.Update.After and inside it I'm updating userSettings.This causes a unlimited loop and application stops working.
is there any work around?
this is the code block:
var className = e.Object.TypeInfo.ObjectClassName;
DataClassInfo dci = DataClassInfoProvider.GetDataClass(className);
if (dci != null)
{
var fi = new FormInfo(dci.ClassFormDefinition);
if (fi != null)
{
var stopProccess = true;
var fields = new List<FormFieldInfo>();
foreach (var changedColumn in e.Object.ChangedColumns())
{
var field = fi.GetFormField(changedColumn);
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
if (!string.IsNullOrEmpty(activityPointMacro))
{
fields.Add(field);
stopProccess = false;
}
}
if (!stopProccess)
{
var contextResolver = CMSContext.CurrentResolver.CreateContextChild();
foreach (FormCategoryInfo info in fi.ItemsList.OfType<FormCategoryInfo>())
{
contextResolver.SetNamedSourceData(info.CategoryName, info);
}
EditingFormControl data = new EditingFormControl();
foreach (FormFieldInfo info2 in fi.ItemsList.OfType<FormFieldInfo>())
{
contextResolver.SetNamedSourceData(info2.Name, data);
}
foreach (var field in fields)
{
{
var activityPointMacro = ValidationHelper.GetString(field.Settings["ActivityPointMacro"], "");
var activityPoint =
ValidationHelper.GetInteger(contextResolver.ResolveMacros(activityPointMacro), 0);
CMSContext.CurrentUser.UserSettings.UserActivityPoints += activityPoint;
CMSContext.CurrentUser.UserSettings.Update();
}
}
}
}
}
If you just need to give points for user fields then you could just use ObjectEvents.Update.Before, check fields are not empty and assign points. But i can see from the code, you want to have something more complex bulit over macro expressions. So I have a few suggestions for you.
1) ObjectEvents.Update.Before instead of ObjectEvents.Update.After still may be a good idea. Ideally you set your additional values and all is set during one update.
2) Watch only the class names you need
3) Always prefer Provider.SetInfo methods over info.Update(). In case of user settings it's best to set whole user info, so UserInfoProvider.SetUserInfo. Provider methods may add some additional important logic.
4) The code seems like it'll add the points with every update of a user
5) if you are still running into a loop, you need to flag somehow, that some part of code should not be executed again. The best way is to use RequestStockHelper class - add a bool value with a specificname like "PointsProcessed".

SharedSizeGroup Naming Rules

I have a question about naming SharedSizeGroups in WPF grids mostly out of curiosity. I noticed on MSDN that they list restrictions for the group's string name:
The SharedSizeGroup property value must satisfy the following rules:
Must not be empty.
Must only consist of letters, digits, and underscore characters.
Must not start with a numeric value.
I have some groups that I named numerically ("1", "2", "3", etc.) and have never had a problem with them. Just for kicks I renamed some groups to something like ",-[]" and they still worked too. So these rules are not enforced and seemingly not necessary. Does anybody know the reason for the rules in the documentation? Is it possible for the names to conflict with something that WPF is doing internally?
Edit: Okay, so WPF does enforce it after all, validation just doesn't fire in my non-compiled templates.
Interesting, I took a look at the DefinitionBase class in reflector and the SharedSizeGroup property.
It creates a dependency property with a validation callback defined as the following:
SharedSizeGroupProperty = DependencyProperty.Register("SharedSizeGroup", typeof(string), typeof(DefinitionBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(DefinitionBase.OnSharedSizeGroupPropertyChanged)), new ValidateValueCallback(DefinitionBase.SharedSizeGroupPropertyValueValid));
private static bool SharedSizeGroupPropertyValueValid(object value)
{
if (value == null)
{
return true;
}
string str = (string)value;
if (str != string.Empty)
{
int num = -1;
while (++num < str.Length)
{
bool flag = char.IsDigit(str[num]);
if (((num == 0) && flag) || ((!flag && !char.IsLetter(str[num])) && ('_' != str[num])))
{
break;
}
}
if (num == str.Length)
{
return true;
}
}
return false;
}
I tested this, and it does in fact return false for anything containing non-numeric, non-alpha, non-underscore characters. It also returns false for any group starting with a number. So it seems to follow general variable name rules..
My guess is this would most likely throw some sort of exception, but perhaps it is being handled. Have you checked the output window?
I tried an invalid name, and I got an XAMLParseException.

Resources