text:
Q: Generics can't make correct inferences A generic class can require a matching generic object in it's constructor, like this sscce:
import java.util.ArrayList;
import java.util.List;

public class GenericsIssue<K> {
  public List<K> inner;

  public GenericsIssue(List<K> input) {
    if(input == null) throw new NullPointerException();
    this.inner = input;
  }

  public K getFirst() {
    if(inner.isEmpty()) return null;
    return inner.get(0);
  }
  // Snip, code continues below

Also, factory methods don't specify the generic type in it's arguments. For example, we might do this. Note, there aren't any warnings, not even "unchecked cast".
  // Code borrowed from Guava source
  public static <E> ArrayList<E> newArrayList() {
    return new ArrayList<E>();
  }
  // End Guava borrow

  public static void main(String... args) {
    ArrayList<String> list = newArrayList();
    GenericsIssue<String> gi = new GenericsIssue<String>(list);
    System.out.println(gi.getFirst()); // (Always null. Not relevant.)
  }
}

However, this main is nearly the same thing, but it doesn't compile in JDK 7u25, either in Eclipse or at the command line. Why?
  public static void main(String... args) {
    GenericsIssue<String> gi = new GenericsIssue<String>(newArrayList());
    System.out.println(gi.getFirst());
  }

Here's the compiler error:
$ javac -d . -Xlint:unchecked GenericsIssue.java
GenericsIssue.java:23: error: constructor GenericsIssue in class GenericsIssue<K> cannot be applied to given types;
        GenericsIssue<String> gi = new GenericsIssue<String>(newArrayList());
                               ^
  required: List<String>
  found: ArrayList<Object>
  reason: actual argument ArrayList<Object> cannot be converted to List<String> by method invocation conversion
  where K is a type-variable:
    K extends Object declared in class GenericsIssue
1 error

A: The generics system is limited in the inferences it can make, and assignment is handled differently from method parameters. You should be able to specify
new GenericsIssue<String>(GenericsIssue.<String>newArrayList());

(Theoretically, that inference should be possible, but that level of analysis just isn't implemented yet.)


text:
Q: SOAP : Use both kind of token : UsernameToken and EncryptedToken We wondering if is it compliant soap 1.1 to use 2 different token in the same soap header.
In our case we are currently using only usernameToken for authentification and want to use X509 encryptedToken.
The fact is that we are not unable to identify the source of the message with our X509 Token (the distinguish name is not usable in our case) so we want to use both token :
-The X509 encrypted Token for authentification
-The UsernameToken for carying the name of sender application ( used for routing)
The message are processed by an IBM Datapower Gateway

A: SOAP is an extensible protocol hence it doesn't restrict you from doing so.
The tricky part is how to achieve what you wanted to achieve using datapower.
To do this you need to:

*

*run custom XSLT to extract both the tokens from message and process it the way you want.

*use AAA policy and in the extract identity phase you should choose 'custom template' and provide your XSLT for extraction of both the tokens. In the Authenticate step you can again use custom XSLT to authenticate the identity in the way you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to send notification from mysql to c# form when changes has been made? I have an c# application that makes changes to a mysql database via nusoap server in PHP. i have to open another instance of that same application and it makes changes to the same database. i want to know please ¿how can i notify the first instance of the app when the second one makes any change on the database so the first one updates its interface with the updated data?
i tried implementing a method that every certain time checks the database for any changes but that is not an option because changes has to be made at the moment the second instance changes the database
i've tried this to know if there is another instance with the same name but it's all that i have
instances = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length;


text:
Q: How to constantly consume and output messages from a stream using redis cli? How to constantly consume and output messages from a stream using redis cli?
I tried the command below, however it only consume the last one message but what I want from the redis cli is to constantly consume and output messages on the screen while the publisher is continuously publishing messages.
XREAD BLOCK 0 STREAMS mystream $

A: Regrettably, unlike the special modes for MONITOR and SUBSCRIBE, the redis-cli doesn't feature a "streaming" mode yet. Please feel free to propose the news feature by opening an issue at https://github.com/redis/redis/issues


text:
Q: ANTLR3 Grammar Eating Integers First, I'll admit: this is probably one of the ugliest grammars you will ever see in your life (ironically named SimplePolicy.g). It STARTED as a simple grammar, but I ended up needing more detailed exceptions, so I ended up making multiple exceptions extending RecognitionException. Then a RuntimeException to wrap it so I could get out of the parser methods.
This grammar is supposed to validate a group of one or more IF/THEN/ELSE?/ENDIF statements. Unfortunately, when I try to compare one of the INTEGER_FIELD tokens to a INTEGER token, the INTEGER token has totally disappeared from the TokenInputStream. I've tried sprinkling println()s through to figure out what is going on, with no luck.
Here is an example of a failure:
IF AGE < 21 THEN
WT > 150
ENDIF
What seems to be happening is that the input String is good, but when I feed it to the Lexer via a CharStream, the integer constant disappears that AGE and WT are being compared to disappear.
Here is a unit test:
@Test
public void ifStatement_legalPolicy2_passes() {
    String policy = "IF AGE < 21 THEN "+
                    "WT > 150 "+
                    "ENDIF";

    CharStream charStream = new ANTLRStringStream(policy);
    SimplePolicyLexer lexer = new SimplePolicyLexer(charStream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    System.out.println(tokenStream.toString());
    SimplePolicyParser parser = new SimplePolicyParser(tokenStream);

    try {
        parser.ifStatement();
        parser.reset();
    } catch (RecognitionRuntimeException e) {
        RecognitionException e1 = e.getRecognitionException();
        fail("Legal policy should not have thrown exception. Exception thrown: " + e1.getClass().getName() + ". Line: " + e1.line + ", Column: " + e1.charPositionInLine);
    } catch (RecognitionException e) {
    }

}

Here is the String output of the tokenstream:
13:14:14.978 DEBUG m.a.k.m.impl.SimplePolicyParser - ifStatement: IF AGE <  THEN WT >  ENDIF

I apologize for the uglyness of this grammar, but if anyone can tell me why this dies I would be greatly appreciative.
grammar SimplePolicy;

options {
  language = Java;
  backtrack = true;
}

@header {
package com.manager.impl;

import com.manager.RecognitionRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;

@lexer::header {
package com.manager.impl;

}

@lexer::members {

}

@parser::members {

 private static final Logger log = LoggerFactory.getLogger(SimplePolicyParser.class);

 @Override
 protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException {
   throw new MismatchedTokenException(ttype, input);
 }

  @Override
 public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
   throw e;
 }

 @Override
 public String getErrorMessage(RecognitionException e, String[] tokenNames) {
  // wrap in a runtime exception to escape ANTLR's dungeon
  throw new RecognitionRuntimeException(e);
 }

}

@rulecatch {
    catch (RecognitionException e) {
           System.out.println(getErrorHeader(e));
      //System.out.println(getErrorMessage(e,tokenNames));
        throw new RecognitionRuntimeException(e);
    }
}

// evaluate multiple show statements
policyGroupWithShow
  : show (show)* EOF
  | ifStatement+ EOF
  {
    // nope, this isn't legal
    ShowExpectedException ex = new ShowExpectedException();
    ex.line = 1;
    ex.charPositionInLine=0;
    throw ex;
  }
  ;

policyGroupWithoutShow
  : ifStatement (ifStatement)* EOF
  | show+ EOF
  {
    // not legal
    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    ex.line = 1;
    ex.charPositionInLine = 0;
    throw ex;
  }
  ;

//policyGroup
//  : show (show)* EOF
//  ;

// evaluate a single SHOW statement
show
  //: ifStatement
  : SHOW STRING FOR ifStatement // good
  // missing for (FOR expected)
  | SHOW expr1a=STRING ifStatement // missing for
  {
    int nextTokenPosition = expr1a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(nextTokenPosition + 1);

    ShowWithoutForException ex = new ShowWithoutForException();
    ex.line = expr1a.getLine();
    ex.charPositionInLine = token.getCharPositionInLine();
    throw ex;

  }
  // missing show (SHOW expected)
  | expr1b=STRING FOR ifStatement
  {
    int tokenPosition = expr1b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition);
    ForWithoutShowException ex = new ForWithoutShowException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  ;

ifStatement
  @init {
    log.debug("ifStatement: " + input.toString());
  }
  //: IF logical THEN logical+ (ELSE logical+)? ENDIF
  : IF operation 'THEN' expression+ ENDIF // good
  {
    log.debug("Matched [IF logical THEN expression+ ENDIF]");
  }
  | IF logical THEN expression+ ELSE expression+ ENDIF
  {
    log.debug("Matched [IF logical THEN expression+ ELSE expression+ ENDIF]");
  }
  | logical expr1a=THEN expression* (ELSE expression*)? ENDIF // missing if
  {
    int tokenPosition = expr1a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition);
    MissingIfException ex = new MissingIfException();
    ex.line = token.getLine();
    ex.charPositionInLine = 0;
    throw ex;
  }
  // missing THEN (THEN clause is missing)
  | expr1b=IF logical expression+ (ELSE expression+)? ENDIF
  {
    int tokenPosition = expr1b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);
    MissingThenClauseException ex = new MissingThenClauseException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getCharPositionInLine();
    throw ex;
  }
  // missing ELSE or ENDIF (ENDIF Expected)
  | IF logical expr1c=THEN expression+
  {
    String inputText = input.toString();
    if (inputText.indexOf("ELSE") < 0 && inputText.indexOf("ENDIF") < 0) {
      // best I can do is get the line/column from the THEN keyword
        MissingElseOrEndifException ex = new MissingElseOrEndifException();
        ex.line = expr1c.getLine();
        ex.charPositionInLine = expr1c.getCharPositionInLine();
        throw ex;
    }
  }
  // missing comparison for IF (rule expected)
  | IF expr1d=THEN expression* ENDIF
  {
    int tokenPosition = expr1d.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition - 1);

    RuleExpectedException ex = new RuleExpectedException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStopIndex();
    throw ex;
  }
  // missing body of then (unexpected symbol or construction)
  | IF logical a=THEN b=ENDIF
  {
    int tokenPosition1 = a.getTokenIndex();
    int tokenPosition2 = b.getTokenIndex();
    CommonToken tokenA = (CommonToken) input.get(tokenPosition1);
    CommonToken tokenB = (CommonToken) input.get(tokenPosition2);

    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    //MissingThenBodyException ex = new MissingThenBodyException();
    if (tokenA.getLine() == tokenB.getLine()) {
      ex.line = tokenA.getLine();
      ex.charPositionInLine = tokenA.getCharPositionInLine();
    } else {
      ex.line = tokenA.getLine() + 1;
      ex.charPositionInLine = 0;
    }
    throw ex;
  }
  // missing body of ELSE (Unexpected symbol or construction)
  | IF logical THEN expression+ ELSE expr3e=ENDIF
  {

    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    ex.line = expr3e.getLine();
    ex.charPositionInLine = expr3e.getCharPositionInLine();
    throw ex;
  }
  // body of IF missing (Body of IF clause is missing)
  | IF expr3f=ENDIF
  {
    int tokenPosition = expr3f.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition);

    MissingIfBodyException ex = new MissingIfBodyException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getCharPositionInLine();
    throw ex;
  }
  | expression // expression should just pass through
  ;

expression
  @init {
    log.debug("Expression: " + input.toString());
  }
  : logical
  ;

// deal with AND/OR operator
logical
  @init {
    log.debug("Logical:" + input.toString());
  }
 : operation (AND operation | OR operation)*
 ;

operation
  @init {
    log.debug("Operation:" + input.LT(1) + input.LT(2) + input.LT(3));
  }
  // good rules
  //: ';' ~('/r/n'|EOF)*
  : DATE_FIELD (EQ|NE|LT|LE|GT|GE) (DATE_FIELD|DATE|DATE_CONSTANT)
  {

    log.info("Matched STRING_FIELD (EQ|NE) (STRING_FIELD|STRING) field operation: " + input.toString());
  }
  | DATE_FIELD (PLUS|MINUS) (DATE_FIELD|DATE|DATE_CONSTANT|DATE_PERIOD_FIELD|datePeriod)
  {
    log.info("Matched DATE_FIELD (PLUS|MINUS) (DATE_FIELD|DATE|DATE_CONSTANT|DATE_PERIOD_FIELD|datePeriod) field operation: " + input.toString());
  }
  | DATE_PERIOD_FIELD (EQ|NE|LT|LE|GT|GE) (DATE_PERIOD_FIELD|DATE_PERIOD_CONSTANT)
  {
    log.info("Matched DATE_PERIOD_FIELD (EQ|NE|LT|LE|GT|GE) (DATE_PERIOD_FIELD|DATE_PERIOD_CONSTANT) field operation: " + input.toString());
  }
  | DATE_PERIOD_FIELD (PLUS|MINUS) (DATE_PERIOD_FIELD|datePeriod|DATE_FIELD|DATE_CONSTANT|DATE)
  {
    log.info("Matched DATE_PERIOD_FIELD (PLUS|MINUS) (DATE_PERIOD_FIELD|datePeriod|DATE_FIELD|DATE_CONSTANT|DATE) field operation: " + input.toString());
  }
  | STRING_FIELD (EQ|NE) (STRING_FIELD|STRING)
  {
  log.info("Matched STRING_FIELD (EQ|NE) (STRING_FIELD|STRING) field operation: " + input.toString());
  }
  | INTEGER_FIELD (EQ|NE|LT|LE|GT|GE) test=inAllFields
  {
    Boolean result = $inAllFields.result;
    Integer type = $inAllFields.tokenType;

    //int testType = test.getType();
    if (type != INTEGER && type != INTEGER_FIELD) {

        IncompatibleTypeException ex = new IncompatibleTypeException();
        //ex.line = test.getLine();
        //ex.charPositionInLine = test.getStartIndex();
        throw ex;
    }
  }
  | INTEGER_FIELD (EQ|NE|LT|LE|GT|GE) test1=(INTEGER_FIELD|INTEGER)
  {
    log.info(test1.getText());
    log.info("Matched INTEGER_FIELD (EQ|NE|LT|LE|GT|GE) (INTEGER_FIELD|INTEGER) field operation: " + input.toString());
  }
  | BOOLEAN_FIELD (EQ|NE) (BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
  log.info("Matched BOOLEAN_FIELD (EQ|NE) (BOOLEAN_FIELD|BOOLEAN_CONSTANT) field operation: " + input.toString());
  }
  | COMMENT
  {
  log.info("Matched COMMENT field operation: " + input.toString());

  }
  // specify bad rules
  // defined fields with no operation. The expression will be null if datePeriod isn't split off
  | (INTEGER_FIELD|INTEGER) (PLUS|MINUS|EQ|NE|LT|LE|)
  {
    System.out.println("Will it work?");
  }
  | (datePeriod)|e1=(DATE_PERIOD_FIELD|DATE_FIELD|STRING_FIELD|INTEGER_FIELD|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    RelationalOperatorOrNotExpectedException ex = new RelationalOperatorOrNotExpectedException();
    if (e1 == null) {
        ex.line = 1;
        ex.charPositionInLine = 0;
    } else {
      ex.line = e1.getLine();
      ex.charPositionInLine = e1.getCharPositionInLine();
    }
    throw ex;
  }
  | e2=(INTEGER|DATE|DATE_CONSTANT)
  {
    RuleCannotBeginWithNumberOrDateException ex = new RuleCannotBeginWithNumberOrDateException();
    ex.line = e2.getLine();
    ex.charPositionInLine = e2.getCharPositionInLine();
    throw ex;
  }
  // attempt to compare a date field to a different field type. Incompatable Type exception
  | DATE_FIELD operator1a=(EQ|NE|LT|LE|GT|GE) (DATE_PERIOD_FIELD|datePeriod|STRING_FIELD|STRING|INTEGER_FIELD|INTEGER|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator1a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 2);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  // attempt to add/sub illegal field types to date (Relational Operator or NOT expected)
  | DATE_FIELD operator1b=(PLUS|MINUS)
      (STRING_FIELD|STRING|INTEGER_FIELD|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator1b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition+1);

    RelationalOperatorOrNotExpectedException ex = new RelationalOperatorOrNotExpectedException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  // attempting to add an int to a date field makes it assume it's a bad date period
  | DATE_FIELD operator1c=(PLUS|MINUS) expr1c=(INTEGER)
  {
   int tokenPosition = operator1c.getTokenIndex();
   CommonToken token = (CommonToken) input.get(tokenPosition + 1);

   MissingYearsMonthsWeeksDaysException ex = new MissingYearsMonthsWeeksDaysException();
   ex.line = token.getLine();
   ex.charPositionInLine = token.getStartIndex();
   throw ex;
  }
  // attempt to compare a String field to something besides a String field or String constant
  | STRING_FIELD operator2a=(EQ|NE) ~(STRING_FIELD|STRING)
  {
    int tokenPosition = operator2a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | expr2b=STRING_FIELD operator2b=(LT|LE|GT|GE) (STRING_FIELD|STRING)
  {
    int tokenPosition = operator2b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | stringExpr3=STRING
  {
    RuleCannotBeginWithAStringException ex = new RuleCannotBeginWithAStringException();
    ex.line = stringExpr3.getLine();
    ex.charPositionInLine = stringExpr3.getCharPositionInLine();
    throw ex;
  }
  // attempt to compare a number field to something besides a num field or int constant

  | INTEGER_FIELD operator3a=(EQ|NE|LT|LE|GT|GE) expr3a2=(DATE_FIELD|DATE|STRING_FIELD|STRING|DATE_PERIOD_FIELD|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    Boolean value = $inAllFields.result;
    //System.out.println("Expr text: " + expr3a2.getText());
    int tokenPosition = operator3a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  // attempt to perform a PLUS/MINUS on a number field with something besides a num field or constant int
  | INTEGER_FIELD operator3b=(PLUS|MINUS)
    (DATE_FIELD|DATE|STRING_FIELD|STRING|DATE_PERIOD_FIELD|datePeriod|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator3b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  // attempt to compare date period to something besides a date period field or date period constant
  | DATE_PERIOD_FIELD operator4a=(EQ|NE|LT|LE|GT|GE)
    (INTEGER_FIELD|INTEGER|DATE_FIELD|DATE|DATE_CONSTANT|STRING_FIELD|STRING|BOOLEAN_FIELD|BOOLEAN_CONSTANT|WAIVER_FIELD)
  {
    int tokenPosition = operator4a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | DATE_PERIOD_FIELD operator5a=(PLUS|MINUS) (STRING_FIELD|STRING|INTEGER_FIELD|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator5a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    RelationalOperatorOrNotExpectedException ex = new RelationalOperatorOrNotExpectedException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | DATE_PERIOD_FIELD operator5b=(PLUS|MINUS) INTEGER
  {
    int tokenPosition = operator5b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    MissingYearsMonthsWeeksDaysException ex = new MissingYearsMonthsWeeksDaysException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | WAIVER_FIELD operator6a=(HAS|EQ|NE) ~(STRING)
  {
    int tokenPosition = operator6a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | WAIVER_FIELD operator6b=(PLUS|MINUS|LT|LE|GT|GE)  STRING
  {
    int tokenPosition = operator6b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | BOOLEAN_FIELD operator7a=(EQ|NE) ~(BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator7a.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    IncompatibleTypeException ex = new IncompatibleTypeException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  | BOOLEAN_FIELD operator7b=(PLUS|MINUS|LT|LE|GT|GE) (DATE_FIELD|DATE|DATE_CONSTANT|DATE_PERIOD_FIELD|datePeriod|STRING_FIELD|STRING|INTEGER_FIELD|WAIVER_FIELD|BOOLEAN_FIELD|BOOLEAN_CONSTANT)
  {
    int tokenPosition = operator6b.getTokenIndex();
    CommonToken token = (CommonToken) input.get(tokenPosition + 1);

    UnexpectedSymbolOrConstructionException ex = new UnexpectedSymbolOrConstructionException();
    ex.line = token.getLine();
    ex.charPositionInLine = token.getStartIndex();
    throw ex;
  }
  ;

// this rule checks that a value is valid. It's not in the validation
// chain
atom
  : datePeriod
  | DATE_FIELD
  | INTEGER_FIELD
  | STRING_FIELD
  | DATE_PERIOD_FIELD
  | WAIVER_FIELD
  | BOOLEAN_FIELD
  | INTEGER
  {
    System.out.println("Matched atom INTEGER");
  }
  | DATE
  | DATE_CONSTANT
  | BOOLEAN_CONSTANT
  | STRING
  //| LPAREN expression RPAREN
  ;

datePeriod
  : (DATE_PERIOD_CONSTANT)+
  ;

// "subatomic" rules, meant to feed the atom rule understandable values

fragment DIGIT: ('0'..'9');

DATE_FIELD:('DOB'|'TEST_DATE');
DATE_PERIOD_FIELD:('AFS');
BOOLEAN_FIELD:('CERTIFIED'|'OVERRIDE');
INTEGER_FIELD:('AGE'|'HT'|'WT');
STRING_FIELD:('CURR_LOC'|'LANG_1'|'LANG_2''USER_LEVEL');
WAIVER_FIELD:('WAIVER');

DATE: /* empty */ {System.out.println("Matched DATE");};

INTEGER: DIGIT+
//INTEGER:('0'..'9')+
{
  System.out.println("Matched INTEGER: " + $text);
  //$type = INTEGER;
    // dynamically change the type when we match the date regular expression
  if ($text.matches("(19|20|21)[0-9]{2}[0-1]\\d{3}")) {
  //if ($text.matches("(19|20|21)[0-9]{2}[0-1]\\d{3}")) {
    System.out.println("Matched date pattern");
    $type = DATE;
  }

}
;
DATE_PERIOD_CONSTANT: ((INTEGER ' ' YEAR)|(INTEGER ' ' MONTH)|(INTEGER ' ' WEEK)|(INTEGER ' ' DAY))
{
  System.out.println("Matched DATE_PERIOD_CONSTANT");
};
DATE_CONSTANT:('TODAY'|'YESTERDAY'|'TOMMOROW');
BOOLEAN_CONSTANT:('TRUE'|'FALSE'|'"Y"'|'"N"');
IF: 'IF';
THEN: 'THEN';
ELSE: 'ELSE';
ENDIF: 'ENDIF';
AND: 'AND';
OR: 'OR';
YEAR: ('YEAR'|'YEARS');
MONTH: ('MONTH'|'MONTHS');
WEEK: ('WEEK'|'WEEKS');
DAY: ('DAY'|'DAYS');

STRING: '"' ID  (' ' ID)* '"' {System.out.println("Matched STRING");};
//  {
//    // strip the quotes once we match this token
//    setText(getText().substring(1, getText().length()-1));
//  }
//  ;

EQ: '=' {System.out.println("Matched EQ");};
NE: '<>';
LT: '<';
LE: '<=';
GT: '>';
GE: '>=';
HAS: 'HAS';
LPAREN: '(';
RPAREN: ')';
PLUS: '+';
MINUS: '-';
SHOW: 'SHOW';
FOR: 'FOR';
ID: ('A'..'Z'|'a'..'z'|'0'..'9'|','|'!'|'?'|':')+ {System.out.println("Matched ID: " + $text);};

COMMENT: ';' ~('\r'|'\n')* {skip();};
WS: (' '+|'\r'|'\n'|'\t') {$channel = HIDDEN;};

A: Whenever your lexer "sees" a number followed by a space, it tries to construct a DATE_PERIOD_CONSTANT. Make that a parser rule instead:
date_persiod_constant
 : INTEGER (YEAR | MONTH | WEEK | DAY)
 ;

(and remove DATE_PERIOD_CONSTANT, of course)
Also, your DATE rule matches nothing. I understand you need this rule to change the type of your INTEGER rule, but never ever create lexer rules that (possibly) match nothing. Make DATE a fragment instead:
fragment DATE : ;

Even though it is a fragment you can then still use DATE in your parser rules. By making it a fragment, you're just instructing the lexer to never create DATE tokens on its own, but you know the lexer can produce such tokens since you're changing the type of INTEGER when it looks like a date.
EDIT

Is there any way to keep it as a lexer rule? I would really like the date constant to emit a token that I can use later.

Sure, it's possible. Not pretty, but possible:
INTEGER
 : DIGIT+ ( (' '+ (YEAR | MONTH | WEEK | DAY))=>
             ' '+ (YEAR | MONTH | WEEK | DAY) {$type = DATE_PERIOD_CONSTANT;}
          )?
   {
     if ($text.matches("(19|20|21)[0-9]{2}[0-1]\\d{3}")) {
       $type = DATE;
     }
   }

 ;

fragment DATE_PERIOD_CONSTANT : ;

What this does is after matching one or more digits, DIGIT+, it forces the lexer to look ahead in the character stream to see if there are one or more spaces followed by a YEAR, MONTH, WEEK or DAY, the predicate (' '+ (YEAR | MONTH | WEEK | DAY))=>, and if so, it goes ahead and matches this (and you change the type from INTEGER to DATE_PERIOD_CONSTANT).
EDIT II

One final issue: a DATE period can be something like "1 YEAR 4 MONTHS 2 DAYS", not just a single such as "1 YEAR". Attempting to add a + to the rule was not successful. Can I ask for one more assist in order to make that rule work the way I need it to?

Something like this should do it (but again, a parser rule might be more appropriate!):
INTEGER
 : (DATE_PERIOD_CONSTANT)=> DATE_PERIOD_CONSTANT ((' '+ DATE_PERIOD_CONSTANT)=> ' '+ DATE_PERIOD_CONSTANT)*
   {
     $type=DATE_PERIOD_CONSTANT;
   }
 | DIGIT+
   {
     if ($text.matches("(19|20|21)[0-9]{2}[0-1]\\d{3}")) {
       System.out.println("Matched date pattern");
       $type = DATE;
     }
   }
 ;

fragment DATE_PERIOD_CONSTANT
 : DIGIT+ ' '+ (YEAR | MONTH | WEEK | DAY)
 ;


text:
Q: Select + optgroup : keeps highlight after losing focus on IE / Edge I'm facing a strange issue using Microsoft Edge on Windows 7 64 bits.
When using SELECT without OPTGROUP, the SELECT has no highlight after losing focus.
When using SELECT with OPTGROUP, the SELECT keeps highlight after losing focus.
Here is a simple example :
<html>
    <head></head>
    <body>
        <select name="test1">
            <optgroup label="Groupe 1">
                <option value="G11">Groupe 1 - Element 1</option>
                <option value="G12">Groupe 1 - Element 2</option>
                <option value="G13">Groupe 1 - Element 3</option>
                <option value="G14">Groupe 1 - Element 4</option>
            </optgroup>
            <optgroup label="Groupe 2">
                <option value="G21">Groupe 2 - Element 1</option>
                <option value="G22">Groupe 2 - Element 2</option>
                <option value="G23">Groupe 2 - Element 3</option>
                <option value="G24">Groupe 2 - Element 4</option>
            </optgroup>
        </select>

        <select name="test2">
            <option value="S1">Element 1</option>
            <option value="S2">Element 2</option>
            <option value="S3">Element 3</option>
            <option value="S4">Element 4</option>
        </select>

        <input type="text" value="test3">
    </body>
</html>

It seems that there is an issue with the navigator, but I don't know how to avoid it. Maybe using CSS or a JS hack ?
Thanks for your help !


text:
Q: Understanding 'gslider' function to make interactive plots I am trying to create an interactive histogram in R whose bin width can be adjusted either by moving a slider or entering a value in the text box. In addition to this, I would also like to provide the user with an option of saving the plot for a particular bin width.
To this end, I found the 'gslider' function of 'aplpack' library to be a good starting point. I tried to modify it to meet my purpose as well as learn more about Tcl/Tk constructs. But I am now stuck and can't proceed, mostly because I haven't completely understood how a slider value is captured and transferred between functions.
Following are the snippets of code that I haven't really understood. These are from the source code of the 'gslider' function.
# What is the rationale behind using the 'assign' function here and at
# other instances in the code?

  img <- tkrplot::tkrplot(gr.frame, newpl, vscale = 1, hscale = 1)
  tkpack(img, side = "top")
  assign("img", img, envir = slider.env)

# I understand the below lines when considered individually. But collectively,
# I am having a difficult time comprehending them. Most importantly, where
# exactly is the slider movement captured here?

  sc <- tkscale(fr, from = sl.min, to = sl.max,
              showvalue = TRUE, resolution = sl.delta, orient = "horiz")
  assign("sc", sc, envir = slider.env)
  eval(parse(text = "tkconfigure(sc, variable=inputbw1)"), envir = slider.env)
  sl.fun <- sl.function
  if (!is.function(sl.fun))
    sl.fun <- eval(parse(text = paste("function(...){",
                                    sl.fun, "}")))
    fname <- 'tkrrsl.fun1'
    eval(parse(text = c(paste(fname, " <-"), " function(...){",
                    "tkrreplot(get('img',envir=slider.env),fun=function()",
                    deparse(sl.fun)[-1], ")", "}")))
    eval(parse(text = paste("environment(", fname, ")<-parent.env")))
    if (prompt)
      tkconfigure(sc, command = get(fname))
    else tkbind(sc, "<ButtonRelease>", get(fname))

  if (exists("tkrrsl.fun1")) {
    get("tkrrsl.fun1")()
  }
  assign("slider.values.old", sl.default, envir = slider.env)

Thanks to everyone for the varied scope of answers. Juba's and Greg's answers were the ones I could work upon to write the following code:
slider_txtbox <- function (x, col=1, sl.delta, title)
{
  ## Validations
  require(tkrplot)
  pos.of.panel <- 'bottom'
  if(is.numeric(col))
    col <- names(x)[col]
  x <- x[,col, drop=FALSE]
  if (missing(x) || is.null(dim(x)))
     return("Error: insufficient x values")
  sl.min <- sl.delta # Smarter initialization required
  sl.max <- max(x)
  xrange <- (max(x)-min(x))
  sl.default <- xrange/30
  if (!exists("slider.env")) {
    slider.env <<- new.env(parent = .GlobalEnv)
  }
  if (missing(title))
    title <- "Adjust parameters"

  ## Creating initial dialogs
  require(tcltk)
  nt <- tktoplevel()
  tkwm.title(nt, title)
  if(.Platform$OS.type == 'windows')
    tkwm.geometry(nt, "390x490+0+10")
  else if(.Platform$OS.type == 'unix')
     tkwm.geometry(nt, "480x600+0+10")
  assign("tktop.slider", nt, envir = slider.env)
  "relax"
  nt.bak <- nt
  sl.frame <- tkframe(nt)
  gr.frame <- tkframe(nt)
  tx.frame <- tkframe(nt)
  tkpack(sl.frame, tx.frame, gr.frame, side = pos.of.panel)

  ## Function to create and refresh the plot
  library(ggplot2)
  library(gridExtra)
  makeplot <- function(bwidth, save) {
    if(bwidth <= 0) {
      df <- data.frame('x'=1:10, 'y'=1:10)
       histplot <- ggplot(df, aes(x=x, y=y)) + geom_point(size=0) + xlim(0, 10) +  ylim(0, 100) +
    geom_text(aes(label='Invalid binwidth...', x=5, y=50), size=9)
    } else {

    histplot <- ggplot(data=x, aes_string(x=col)) +
  geom_histogram(binwidth=bwidth, aes(y = ..density..), fill='skyblue') +
  theme(axis.title.x=element_text(size=15), axis.title.y=element_text(size=15),
        axis.text.x=element_text(size=10, colour='black'),
        axis.text.y=element_text(size=10, colour='black'))
    }
    print(histplot)
    if(save){
  filename <- tkgetSaveFile(initialfile=paste('hist_bw_', bwidth, sep=''),
                            filetypes='{{PNG files} {.png}} {{JPEG files} {.jpg .jpeg}}
                            {{PDF file} {.pdf}} {{Postscript file} {.ps}}')
  filepath <- as.character(filename)
  splitpath <- strsplit(filepath, '/')[[1]]
  flname <- splitpath[length(splitpath)]
  pieces <- strsplit(flname, "\\.")[[1]]
  ext <- tolower(pieces[length(pieces)])
  if(ext != 'png' && ext != 'jpeg' && ext != 'jpg' && ext != 'pdf' && ext != 'ps') {
    ext <- 'png'
    filepath <- paste(filepath, '.png', sep='')
    filename <- tclVar(filepath)
  }
  if(ext == 'ps')
    ext <- 'postscript'
  eval(parse(text=paste(ext, '(file=filepath)', sep='')))
  eval(parse(text='print(histplot)'))
  dev.off()
}
  }
  img <- tkrplot::tkrplot(gr.frame, makeplot(sl.default, FALSE), vscale = 1, hscale = 1)
  tkpack(img, side = "top")
  assign("img", img, envir = slider.env)

  ## Creating slider, textbox and labels
  parent.env <- sys.frame(sys.nframe() - 1)
  tkpack(fr <- tkframe(sl.frame), side = 'top')
  sc <- tkscale(fr, from = sl.min, to = sl.max,
            showvalue = TRUE, resolution = sl.delta,
            orient = "horiz")
  tb <- tkentry(fr, width=4)
  labspace <- tklabel(fr, text='\t\t\t')
  tkpack(sc, labspace, tb, side = 'left')

  tkpack(textinfo <- tkframe(tx.frame), side = 'top')
  lab <- tklabel(textinfo, text = '                    Move slider', width = "20")
  orlabel <- tklabel(textinfo, text='          OR', width='10')
  txtboxmsg <- tklabel(textinfo, text = 'Enter binwidth', width='20')
  tkpack(txtboxmsg, orlabel, lab, side='right')

  tkpack(f.but <- tkframe(sl.frame))
  tkpack(tklabel(f.but, text=''))
  tkpack(tkbutton(f.but, text = "Exit", command = function() tkdestroy(nt)),
     side='right')
  tkpack(tkbutton(f.but, text = "Save", command = function(...) {
    bwidth <- as.numeric(tclvalue(get('inputtb', envir=slider.env)))
    tkrreplot(get('img',envir=slider.env),fun=function() { makeplot(bwidth, TRUE); sync_slider()})
  }), side='right')

  ## Creating objects and variables associated with slider and textbox
  assign("sc", sc, envir = slider.env)
  eval(parse(text = "assign('inputsc', tclVar(sl.default), envir=slider.env)"))
  eval(parse(text = "tkconfigure(sc, variable=inputsc)"), envir = slider.env)

  assign("tb", tb, envir = slider.env)
  eval(parse(text = "assign('inputtb', as.character(tclVar(sl.default)),
         envir=slider.env)"))
  eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)

  ## Function to update the textbox value when the slider has changed
  sync_textbox <- function() {
  bwidth_sl <- tclvalue(get('inputsc', envir=slider.env))
  assign('inputtb', tclVar(bwidth_sl), envir=slider.env)
  eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)
}

 ## Function to update the slider value when the textbox has changed
 sync_slider <- function() {
 bwidth_tb <- tclvalue(get('inputtb', envir=slider.env))
 assign('inputsc', tclVar(bwidth_tb), envir=slider.env)
 eval(parse(text = "tkconfigure(sc, variable=inputsc)"), envir = slider.env)
}

  ## Bindings : association of certain functions to certain events for the slider
  ## and the textbox

  tkbind(sc, "<ButtonRelease>", function(...) {
    bwidth <- as.numeric(tclvalue(get('inputsc', envir=slider.env)))
    tkrreplot(get('img',envir=slider.env),fun=function() { makeplot(bwidth, FALSE); sync_textbox()})
  })

  tkbind(tb, "<Return>", function(...) {
    bwidth <- as.numeric(tclvalue(get('inputtb', envir=slider.env)))
    if(bwidth > sl.max && !is.na(bwidth)) {
      bwidth <- sl.max
      assign('inputtb', tclVar(bwidth), envir=slider.env)
      eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)
     } else
    if(bwidth < sl.min || is.na(bwidth)) {
      bwidth <- sl.min
      assign('inputtb', tclVar(bwidth), envir=slider.env)
      eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)
     }
  tkrreplot(get('img',envir=slider.env),fun=function() { makeplot(bwidth, FALSE);    sync_slider()})
})

}

library(ggplot2)
slider_txtbox(movies, 'rating', 0.1, 'Adjust binwidth')

A: If you do not insist on a local solution, you might give rapporter.net a try, which lets you specify such tasks easily with any number of tweakable sliders. Okay, enough of marketing :)
Here goes a quick demo:  Interactive histogram on mtcars which looks like:

There you could choose one of the well-know variables of mtcars, but of course you could provide any data frame to be used here or tweak the above form after a free registration.

How it's done? I have just created a quick rapport template and let it rapplicate. The body of the template is written in brew-style (please see the above "rapport" URL for more details):
<%=
evalsOptions('width', width)
evalsOptions('height', height)
%>

# Histogram

<%=
set.caption(paste('Histogram of', var.name))
hist(var, breaks=seq(min(var), max(var), diff(range(var))/round(binwidth)), main = paste('Histogram of', var.name), xlab = '')
%>

## Parameters

Provided parameters were:

  * variable: <%=var.name%> (<%=var.label%>)
  * bin-width of histogram: <%=binwidth%>
  * height of generated images: <%=height%>
  * width of generated images: <%=width%>

# Kernel density plot

<%=
set.caption('A kernel density plot')
plot(density(var), main = '', xlab = '')
%>

But a bare-minimal example of the task could be also addressed by a simple one-liner template:
<%=hist(var, breaks=seq(min(var), max(var), diff(range(var))/round(binwidth)))%>

There you would only need to create a new template, add two input types with a click (one numeric variable of any data set and a number input field which would hold the binwidth of the histogram), and you are ready to go.

A: Here is a minimal working example with comments, based on the complete code you first submit. As I'm far from an expert in tcl/tk, there may be cleaner or better ways to do it. And it is quite incomplete (for example the textbox values should be checked to be in the range of the slider, etc.) :
library(ggplot2)
library(gridExtra)
title <- "Default title"
data(movies)

## Init dialog
require(tkrplot)
if (!exists("slider.env")) slider.env <<- new.env(parent = .GlobalEnv)
require(tcltk)
nt <- tktoplevel()
tkwm.title(nt, title)
tkwm.geometry(nt, "480x600+0+10")
assign("tktop.slider", nt, envir = slider.env)
"relax"
nt.bak <- nt
sl.frame <- tkframe(nt)
gr.frame <- tkframe(nt)
tx.frame <- tkframe(nt)
tkpack(sl.frame, tx.frame, gr.frame, side = "bottom")
## First default plot
newpl <- function(...) {
  dummydf <- data.frame('x'=1:10, 'y'=1:10)
  dummy <- ggplot(dummydf, aes(x=x, y=y)) + geom_point(size=0) + xlim(0, 10) + ylim(0, 100) +
    geom_text(aes(label='Generating plot...', x=5, y=50), size=9)
  print(dummy)
  }
img <- tkrplot::tkrplot(gr.frame, newpl, vscale = 1, hscale = 1)
tkpack(img, side = "top")
assign("img", img, envir = slider.env)
tkpack(fr <- tkframe(sl.frame), side = 'top')

## Creating slider, textbox and labels
sc <- tkscale(fr, from = 0, to = 5, showvalue = TRUE, resolution = 0.1, orient = "horiz")
tb <- tkentry(fr, width=4)
lab <- tklabel(fr, text = 'Select binwidth ', width = "16")
orlabel <- tklabel(fr, text=' or ', width='4')
tkpack(lab, sc, orlabel, tb, side = 'left')
tkpack(textinfo <- tkframe(tx.frame), side = 'top')

## Creating objects and variables associated with slider and textbox
assign("sc", sc, envir = slider.env)
assign("tb", tb, envir = slider.env)
assign('inputsc', tclVar(2.5), envir=slider.env)
assign('inputtb', tclVar('2.5'), envir=slider.env)
eval(parse(text = "tkconfigure(sc, variable=inputsc)"), envir = slider.env)
eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)

## Function to update the textbox value when the slider has changed
sync_textbox <- function() {
  bwidth_sl <- tclvalue(get('inputsc', envir=slider.env))
  assign('inputtb', tclVar(bwidth_sl), envir=slider.env)
  eval(parse(text = "tkconfigure(tb, textvariable=inputtb)"), envir = slider.env)
}

## Function to update the slider value when the textbox has changed
sync_slider <- function() {
  bwidth_tb <- tclvalue(get('inputtb', envir=slider.env))
  assign('inputsc', tclVar(bwidth_tb), envir=slider.env)
  eval(parse(text = "tkconfigure(sc, variable=inputsc)"), envir = slider.env)
}

## Function to refresh the plot
refresh <- function(bwidth) {
  histplot <- ggplot(data=movies, aes_string(x="rating")) +
     geom_histogram(binwidth=bwidth,
                    aes(y = ..density..), fill='skyblue') +
                      theme(axis.title.x=element_text(size=15), axis.title.y=element_text(size=15),
                            axis.text.x=element_text(size=10, colour='black'),
                            axis.text.y=element_text(size=10, colour='black'))
  print(histplot)
}

## Bindings : association of certain functions to certain events for the slider
## and the textbox

tkbind(sc, "<ButtonRelease>", function(...) {
  bwidth <- as.numeric(tclvalue(get('inputsc', envir=slider.env)))
  tkrreplot(get('img',envir=slider.env),fun=function() { refresh(bwidth); sync_textbox()})
})

tkbind(tb, "<Return>", function(...) {
  bwidth <- as.numeric(tclvalue(get('inputtb', envir=slider.env)))
  tkrreplot(get('img',envir=slider.env),fun=function() { refresh(bwidth); sync_slider()})
})

A: You might want to look at the R package 'rpanel' -- it uses tcltk under the hood but is much simpler to use:
rpanel
rpanel reference

A: I don't know the gslider function and cannot help you there, but here are some alternatives:
One simple option is to use the tkexamp function from the TeachingDemos package, here is one way:
library(TeachingDemos)

myhist <- function(x, s.width, e.width, ...) {
    if( missing(e.width) || is.null(e.width) || is.na(e.width) ) {
        e.width<- s.width
    }
    b <- seq( min(x)-e.width/2, max(x)+e.width, by=e.width )
    hist(x, b, ...)
}

mylist <- list( s.width=list('slider', init=1, from=1, to=10, resolution=1),
    e.width=list('numentry', init='', width=7)
)

sampdata <- rnorm(100, 50, 5)
tkexamp(myhist(sampdata), mylist)

This will create a quick GUI with your histogram and a slider and entry widget.  The width of the bars are determined by the value in the entry widget, and if that is blank (default) then the value of the slider.  Unfortunately the slider and entry widget do not update each other.  There is a button that will print out the current call, so the same plot can be recreated from the command line in the default or current plotting device.  You can edit the mylist variable above to make the controls fit your data better.
If you want the entry and slider to update each other then you can program that more directly.  Here is a basic function that uses tkrplot:
mytkhist <- function(x, ...) {

    width <- tclVar()
    tclvalue(width) <- 1

    replot <- function(...) {
        width <- as.numeric(tclvalue(width))
        b <- seq( min(x) - width/2, max(x)+width, by=width )
        hist(x,b,...)
    }

    tt <- tktoplevel()
    img <- tkrplot(tt, replot)
    tkpack(img, side='top')

    tkpack( tkscale(tt, variable=width, from=1, to=10,
        command=function(...) tkrreplot(img),
        orient='horizontal'), side='top' )
    tkpack( e <- tkentry(tt, textvariable=width), side='top' )
    tkbind(e, "<KeyRelease>", function(...) tkrreplot(img))
}

mytkhist(sampdata)

The fact that both the slider (scale) and the entry widget use the same variable is what makes them automatically update each other (no calls to assign needed).  The command argument in tkscale and the tkbind call mean that any changes to either the slider or the entry will update the plot.  This does not have anything to save the current plot, but you should be able to add that part as well as any other controls that you want to use.


text:
Q: Dictionary print key and value in Swift 4 Hello I tried a print dictionary items at Xcode9. Like this:
var items = ["Bear":"0", "Glass":"1", "Car":"2"]

for (key,value) in items{

print("\(key) : \(value)")

}

output:
Glass : 1
Bear : 0
Car : 2

Why output not like this: Bear: 0, Glass:1, Car:2
I dont understand this output reason.

A: Dictionary in Swift is implemented as hash map. There is no guarantee that items in Dictionary will have the same order you added them.
The only container that retains the order of items is Array. You can use it to store tuples, like so:
var items : [(key: String, value: String)] = [(key: "Bear", value: "0"),(key: "Glass", value: "1"), (key: "Car", value: "2")]

Your iteration will work as expected, but you will lose Dictionary's ability to lookup items by subscript

A: Dictionary :
A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering.
Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.
Array - An array stores values of the same type in an ordered list.
Sets - A set stores distinct values of the same type in a collection with no defined ordering.
From Apple documentation

A: *

*Arrays are ordered collections of values.

*Sets are unordered collections of unique values.

*Dictionaries are unordered
collections of key-value associations.

So, You can not expect the same order, when you are iterating the values from Dictionary.
Reference to Collection Type

A: Dictionary collection isn't ordered, that is it simply doesn't guarantee to be ordered. But Array is. Dictionary adds values in discrete orders whereas Array adds values in continuous order.
You simply can't have an Array like this:
["a", "b", ... , "d", ... , ... , "g"]    //Discrete index aren't allowed. You just can't skip any index in between.

Instead you have to have the above array like this:
["a", "b", "d", "g"]

To be able to get rid of this behavior, Dictionary (where you don't have to maintain previous indexes to have values) was introduced. So you can insert values as you like. It won't bother you for maintaining any index.


text:
Q: Is it appropriate to run a complex enterprise-system configuration and migration project in a similar way to a Scrum development project? I'm just starting out on the implementation of a large enterprise-wide system, which has complex requirements and many stakeholders.
The company has been through high-level evaluation and tender process and determined to purchase a highly configurable "off-the-shelf" product rather than building an entirely bespoke system. The system will replace several existing systems and will require a significant amount of data migration.
I'm thinking that the implementation of this system (which is expected to take over 2 years) could be run in a similar way to a Scrum software development project.
With the first sprints targeted at building the minimal possible functionality needed (across all functional areas), and then iteratively deepening the level of functionality according the stakeholder feedback. I think this will de-risk the project and help ensure a balance of stakeholder needs within the available time.
The user stories are still the same, it's just that to implement them we have work within the constraints of the pre-purchased system. When it comes to 'building stuff', instead of writing custom code the team will be configuring the off-the-shelf package, writing data conversion scripts and the like (and it should be a lot quicker!).
Does this sound like a sensible approach? Does the Agile approach makes sense here?

A: Despite the use of an off-the-shelf product, this is a software development project and will have to be run accordingly (withs SCRUM, Agile and/or other methodologies).
As you said, you will have to write migrations scripts, configuration files and so on. This is software development. Anything else.
You will have to use a source code versioning system like GIT, Hg, Subversion or CVS. You will have to keep track of bugs and requested features.
You will have to document what you are developing.
You will have to test your system.
This is just "software development", so your approach is more than sensible. It is mandatory.
Agile development almost always make (at least some) sense. Sometime it has to be used together with others (more formal) methodologies but it is almost always a good starting point.

A: As AlexBottoni already mentioned SCRUM can be used because even customizing is software development.
But for your approach to do several sprints in creating basic functionality is the wrong way. Get one of the existing systems and replace it with the new solution. This should be done in only a few sprints. Select only few user stories at first to implement. When the first system is replaced get the second one. Don't try to replace everything at once because then it is more likely to fail. Even if it seems to cost more time it is worth to replace one system after another. Also then the management will see faster what will be achived.
If you take two years to replace everything the current systems will be developed further and you have a moving target...


text:
Q: How to reposition the second string of each line to start at the nth character on the same line Ubuntu 16.04
Bash V 4.4
Here is my file:
4u76kumtstring5="${ThisLine__4u76kumtstring5}" # this vreis ethees 445h45thb ervexplanation forevrev
wevdssdstring6="${ThisLine__wevdssdstring6}" # this is theerve explanationver for wevdssdstring6 kj
rjjstring7="${ThisLine__rjjstring7}" # thise isder evervthe explanation for rjjstring7 eji
5trstring8="${ThisLine__5trstring8}" # this is ververthe explanation for 5trstring8 k8bf2kl

If I use column -t I get something like this:
4u76kumtstring5="${ThisLine__4u76kumtstring5}"  #  this   vreis  ethees     445h45thb       ervexplanation  forevrev
wevdssdstring6="${ThisLine__wevdssdstring6}"    #  this   is     theerve    explanationver  for             wevdssdstring6  kj
rjjstring7="${ThisLine__rjjstring7}"            #  thise  isder  evervthe   explanation     for             rjjstring7      eji
5trstring8="${ThisLine__5trstring8}"            #  this   is     ververthe  explanation     for             5trstring8      k8bf2kl

I want the second string to start the nth character of the line
4u76kumtstring5="${ThisLine__4u76kumtstring5}"               # this vreis ethees 445h45thb ervexplanation forevrev
wevdssdstring6="${ThisLine__wevdssdstring6}"                 # this is theerve explanationver for wevdssdstring6 kj
rjjstring7="${ThisLine__rjjstring7}"                         # thise isder evervthe explanation for rjjstring7 eji
5trstring8="${ThisLine__5trstring8}"                         # this is ververthe explanation for 5trstring8 k8bf2kl

A: Give this awk one-liner a try:
awk -v n='60' -F'#' '{printf "%-*s#%s\n",n,$1,$2}' file

You can change the n='60' into other values.

A: Assuming there can't be a # in the leading name="$variable" part of each line:
$ awk -v n=60 '{h=$0; sub(/[[:space:]]*#.*/,"",h); sub(/[^#]+/,""); printf "%-*s%s\n", n, h, $0}' file
4u76kumtstring5="${ThisLine__4u76kumtstring5}"              # this vreis ethees 445h45thb ervexplanation forevrev
wevdssdstring6="${ThisLine__wevdssdstring6}"                # this is theerve explanationver for wevdssdstring6 kj
rjjstring7="${ThisLine__rjjstring7}"                        # thise isder evervthe explanation for rjjstring7 eji
5trstring8="${ThisLine__5trstring8}"                        # this is ververthe explanation for 5trstring8 k8bf2kl

Count the spaces to see if 60 is the right number, massage to suit.

A: Pure Bash -
c2=$columnYouWantTheHash
while IFS='#' read -r a b; do printf "%-$((c2-1))s%s\n" "$a" "#$b"; done < file


text:
Q: AngularJS mis-type between model and controller I am receiving a list of objects from my server with the following format:
[ { 'id' : 1, ... }, { 'id' : 2, ... }, { 'id' : 3, ... } ]

I am trying to allow the user to select objects with a radio button. Here is the following HTML code:
<input type="radio" ng-model="id" value={{ obj.id }} />

I am repeating this piece of code for every object in the list. Problem is, when clicking one of the buttons, the following error shows up:
Error: ngModel:numfmt
Model is not of type `number`

The ID of each object is clearly a number, as the following console log states:
console.log(typeof (obj.id)); <- return 'number'
But it still does not work. Can anyone help me discovering why does it break ?
EDIT The code iterating through the array of objects:

      <input type="radio" string-to-number ng-model="id" value={{ obj.id }} />
      {{ obj.id }}

A: The HTML should be:

      <input type="radio" name=group1 ng-model="group1.id" ng-value='obj.id' />
      {{ obj.id }

Model = {{group1.id}}

There are several problems with the code

*

*The ng-model attribute needs to set to a property of an object. (Use a dot.)

*Use ng-value for Angular Expressions

*The radio button group needs to be defined with the name attribute.
The DEMO on JSFiddle.


text:
Q: PhoneGap: Update Files (.html) for further use offline I want to have an app, that provides only simple information in an table.
I use PhoneGap. I got my information right now and I can write them in the HTML file.
But there will be some changes, do I have to wait with the publish, or is it possible to get the new infos.html file from my server with an click on a refresh button and store it local, so the user still can get it w/out internet connection?

A: You can't replace the local files. What you can do is build your interfaces dynamically using Javascript and use AJAX to download the HTML for them. You can store it locally for offline access using window.localStorage.


text:
Q: $$.getJSON, using a variable instead of a URL? I have JSON key/values saved in my localstorage.
Localhost key/value store:

I need to use template7 to use the handlebar style tags in the code.

View Log Book

          {{#each this}}

{{rearcheckbox}}

          {{/each}}

The problem is that the JSON is in these key/value locally stored objects
and not in a file so when I need to use the code:
$$.getJSON('url', function (json) {
    myApp.template7Data.logs= json ;
});

I can't because it wants a URL and the JSON isn't in a file it's in localstorage.
Any ideas on how I should proceed?

A: Use JSON.parse() to parse JSON you have in a string.
jQuery's getJSON is just a wrapper around that and XMLHttpRequest.

A: do this:
myApp.template7Data.logs=JSON.parse(localStorage.getItem('2016-04-24'))


text:
Q: How to detect if any app goes fullscreen or exiting fullscreen? I need to disable notifications at my app when there is another app fullscreen like powerpoint or VLC to do not bother a user.
For now, I get to this code, but it always returns true. Whether there is some app fullscreen or not. I am not sure whether this should work only for app bars or also taskbar.
HWND  hWnd;
hWnd = FindWindow(L"Shell_TrayWnd", nullptr);
if( hWnd )
{
    APPBARDATA apd;
    apd.cbSize = sizeof(APPBARDATA);
    apd.hWnd = hWnd;
    bool uState = bool(SHAppBarMessage(ABN_FULLSCREENAPP , &apd));
    if(uState)
        qDebug()<<"fullscreen";
    else
        qDebug()<<"not fullscreen";
}

A: ABN_FULLSCREENAPP is not a message you send to the shell, it's a message the shell sends to you when an application enters or leaves full screen mode.  The message is sent to the owner of an app bar created with ABM_NEW.
Documentation is here.
My reading of the documentation is that you have to create an app bar to receive this message but you may be able to set it to zero height or width with ABM_SETPOS if you want to hide it.


text:
Q: Letting user draw a rectangle with mouse in Java I'm writing a program that lets the user draw a hollow rectangle on the screen on top of an image. They can also click on the image and the clicks are joined up to form polygons.
Joining up points works fine, but when the user drags to draw a rectangle, the previously drawn rectangles and polygons disappear. The runnable code is below;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageLabeller extends JFrame {

static boolean drawRectangle = false;
/**
 * some java stuff to get rid of warnings
 */
private static final long serialVersionUID = 1L;

/**
 * main window panel
 */
JPanel appPanel = null;

/**
 * toolbox - put all buttons here
 */
JPanel toolboxPanel = null;

/**
 * image panel - displays image and editing area
 */

static ImagePanel imagePanel;

/**
 * handles New Object button action
 */

public ImageLabeller(String imageFilename) {

    try {

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                System.out.println("Bye bye!");
                System.exit(0);
            }
        });

        // Create and set up the image panel.
        // setup main window panel
        setExtendedState(Frame.MAXIMIZED_BOTH);
        appPanel = new JPanel();
        appPanel.setLayout(new BoxLayout(appPanel, BoxLayout.Y_AXIS));
        this.setContentPane(appPanel);

        imagePanel = new ImagePanel(imageFilename);
        imagePanel.setOpaque(true); // content panes must be opaque
        imagePanel.setBorder(BorderFactory.createLineBorder(Color.green));

        // create toolbox panel
        toolboxPanel = new JPanel();
        toolboxPanel.setBorder(BorderFactory.createLineBorder(Color.black));

        JButton newPolyButton = new JButton("New object");
        newPolyButton.setMnemonic(KeyEvent.VK_N);
        // newPolyButton.setSize(50, 20);
        newPolyButton.setToolTipText("Click to add new object");
        newPolyButton.addActionListener(new DrawListener());

        JButton newSquareButton = new JButton("New Square");
        newSquareButton.setMnemonic(KeyEvent.VK_S);
        // newPolyButton.setSize(50, 20);
        newSquareButton.setEnabled(true);
        newSquareButton.setToolTipText("Click to add new square");
        newSquareButton.addActionListener(new SquareListener());

        // add all buttons to toolboxPanel
        toolboxPanel.add(newPolyButton);
        toolboxPanel.add(newSquareButton);

        // add all panels to appPanel
        appPanel.add(toolboxPanel);
        appPanel.add(imagePanel);
        // appPanel.add(Box.createRigidArea(new Dimension(0,10)));

        // display all the stuff
        this.pack();
        this.setVisible(true);
    } catch (Exception e) {
        System.err.println("Image: ");
        e.printStackTrace();
    }
}

public static void addNewPolygon() {
    imagePanel.addNewPolygon();
}

public static void addNewRectangle() {
    //imagePanel.addNewRectangle();
}

    static class DrawListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            addNewPolygon();
        }
    }

    static class SquareListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            drawRectangle = true;
            imagePanel.drawingRectangle = true;
            System.out.println(imagePanel.drawingRectangle);
        }
    }

    public static void main (String args []) {
        new ImageLabeller("/change to/a photo/ of your choice.jpg");
    }

}

_
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel implements MouseListener,
    MouseMotionListener {

Rectangle currentRectangle = null;
boolean drawingRectangle = false;

/**
 * some java stuff to get rid of warnings
 */
private static final long serialVersionUID = 1L;

/**
 * image to be tagged
 */
BufferedImage image = null;

/**
 * list of current polygon's vertices
 */
ArrayList<Point> currentPolygon = null;

/**
 * list of polygons
 */
ArrayList<ArrayList<Point>> polygonsList = null;

ArrayList<Rectangle> rectangleList = null;

/**
 * extended constructor - loads image to be labelled
 *
 * @param imageName
 *            - path to image
 * @throws Exception
 *             if error loading the image
 */
public ImagePanel(String imageName) throws Exception {

    currentPolygon = new ArrayList<Point>();
    polygonsList = new ArrayList<ArrayList<Point>>();
    rectangleList = new ArrayList<Rectangle>();

    image = ImageIO.read(new File(imageName));
    Dimension panelSize = new Dimension(image.getWidth(), image.getHeight());
    this.setSize(panelSize);
    this.setMinimumSize(panelSize);
    this.setPreferredSize(panelSize);
    this.setMaximumSize(panelSize);

    setBounds(0, 0, image.getWidth(), image.getHeight());
    addMouseListener(this);
    addMouseMotionListener(this);
    this.setVisible(true);

}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("Paint Component");
    Graphics2D g2d = (Graphics2D) g;

    // Paint image on screen
    g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);

    // display all the completed polygons
    for (ArrayList<Point> polygon : polygonsList) {
        drawPolygon(polygon);
        finishPolygon(polygon);
        System.out.println("Polly");
    }

    // Display all completed squares
    for (Rectangle r : rectangleList) {
        drawRectangle(r);
        System.out.println("Square");
    }

    // display current polygon
    if (currentPolygon != null) {
        drawPolygon(currentPolygon);
    }

    // display current square
    if (currentRectangle != null) {
        drawRectangle(currentRectangle);
    }
}

/**
 * displays a polygon without last stroke
 *
 * @param polygon
 *            to be displayed
 */
public void drawPolygon(ArrayList<Point> polygon) {
    Graphics2D g = (Graphics2D) this.getGraphics();
    // set to red so I can see when it's being redrawn
    g.setColor(Color.RED);
    g.setStroke(new BasicStroke(3));
    for (int i = 0; i < polygon.size(); i++) {
        Point currentVertex = polygon.get(i);
        if (i != 0) {
            Point prevVertex = polygon.get(i - 1);
            g.drawLine(prevVertex.getX(), prevVertex.getY(),
                    currentVertex.getX(), currentVertex.getY());
        }
        g.fillOval(currentVertex.getX() - 5, currentVertex.getY() - 5, 10,
                10);
    }
}

public void drawRectangle(Rectangle r) {
    Graphics2D g = (Graphics2D) this.getGraphics();
    g.setStroke(new BasicStroke(3));
    g.setColor(Color.BLUE);
    g.drawLine(r.getX1(), r.getY1(), r.getX2(), r.getY1());
    g.drawLine(r.getX1(), r.getY1(), r.getX1(), r.getY2());
    g.drawLine(r.getX2(), r.getY2(), r.getX2(), r.getY1());
    g.drawLine(r.getX2(), r.getY2(), r.getX1(), r.getY2());

    System.out.println(r.getX1() + " " + r.getY1() + " " + r.getX2());
    System.out.println("Drawn rectangle");
}

/**
 * displays last stroke of the polygon (arch between the last and first
 * vertices)
 *
 * @param polygon
 *            to be finished
 */
public void finishPolygon(ArrayList<Point> polygon) {
    // if there are less than 3 vertices than nothing to be completed
    if (polygon.size() >= 3) {
        Point firstVertex = polygon.get(0);
        Point lastVertex = polygon.get(polygon.size() - 1);

        Graphics2D g = (Graphics2D) this.getGraphics();
        g.setColor(Color.GREEN);
        g.setStroke(new BasicStroke(3));
        g.drawLine(firstVertex.getX(), firstVertex.getY(),
                lastVertex.getX(), lastVertex.getY());
    }
}

/**
 * moves current polygon to the list of polygons and makes pace for a new
 * one
 */
public void addNewPolygon() {
    // finish the current polygon if any
    if (currentPolygon != null) {
        finishPolygon(currentPolygon);
        polygonsList.add(currentPolygon);
    }

    currentPolygon = new ArrayList<Point>();
}

public void mouseClicked(MouseEvent e) {

    if (!drawingRectangle) {
        int x = e.getX();
        int y = e.getY();

        // check if the cursor is within image area
        if (x > image.getWidth() || y > image.getHeight()) {
            // if not do nothing
            return;
        }

        Graphics2D g = (Graphics2D) this.getGraphics();

        // if the left button than we will add a vertex to poly
        if (e.getButton() == MouseEvent.BUTTON1) {
            g.setColor(Color.GREEN);
            if (currentPolygon.size() != 0) {
                Point lastVertex = currentPolygon
                        .get(currentPolygon.size() - 1);

                g.setStroke(new BasicStroke(3));
                g.drawLine(lastVertex.getX(), lastVertex.getY(), x, y);
            }
            g.fillOval(x - 5, y - 5, 10, 10);

            currentPolygon.add(new Point(x, y));
            System.out.println(x + " " + y + " polygon point");
        }
    }
}

public void mouseEntered(MouseEvent arg0) {
}

public void mouseExited(MouseEvent arg0) {
}

public void mousePressed(MouseEvent arg0) {
    if (drawingRectangle) {
        currentRectangle = new Rectangle(arg0.getX(), arg0.getY(),
                arg0.getX(), arg0.getY(), Color.BLACK);

    }
}

public void mouseReleased(MouseEvent arg0) {
    if (drawingRectangle) {
        rectangleList.add(new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor()));

        System.out.println(currentRectangle.getX1() + " "
                + currentRectangle.getY1() + " " + arg0.getX() + " "
                + arg0.getY() + " rectangle point");

        // unnecessary when mouseDragged calls paintComponent directly?
        drawRectangle(new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor()));

        currentRectangle = null;
        drawingRectangle = false;

    }
}

public void mouseDragged(MouseEvent arg0) {

    if (drawingRectangle) {
        currentRectangle = new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor());

        System.out.println(currentRectangle.getX1() + " "
                + currentRectangle.getY1() + " " + arg0.getX() + " "
                + arg0.getX() + " " + "Dragging");
        repaint();

    // It works better using this instead on repaint()

//           Graphics g = this.getGraphics();
//           paintComponent(g);
    }

}

public void mouseMoved(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

}

-
public class Point {
private int x = 0;
private int y = 0;

public Point() {
}

public Point(int x, int y) {
    this.x = x;
    this.y = y;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}

}

-
import java.awt.Color;
import java.awt.Graphics2D;

public class Rectangle {

// Initialize variables
private int x1; // x coordinate of first endpoint
private int y1; // y coordinate of first endpoint
private int x2; // x coordinate of second endpoint
private int y2; // y coordinate of second endpoint
private Color colour; // colour of the shape

// A no-parameter constructor that sets all the coordinates of the shape to
// 0 and the
// colour to Color.BLACK
public Rectangle() {
    x1 = 0;
    y1 = 0;
    x2 = 0;
    y2 = 0;
    colour = Color.BLACK;
}

// A constructor that initializes the coordinates and colour to the values
// of the
// parameters supplied.
public Rectangle(int x1, int y1, int x2, int y2, Color col) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
    this.colour = col;
}

public void setX1(int x1) {
    this.x1 = x1;
}

public void setY1(int y1) {
    this.y1 = y1;
}

public void setX2(int x2) {
    this.x2 = x2;
}

public void setY2(int y2) {
    this.y2 = y2;
}

public void setColor(Color colour) {
    this.colour = colour;
}

public int getX1() {
    return this.x1;
}

public int getY1() {
    return this.y1;
}

public int getX2() {
    return this.x2;
}

public int getY2() {
    return this.y2;
}

public Color getColor() {
    return this.colour;
}

public int getWidth() {
    return (Math.abs(x2 - x1));
}

public int getHeight() {
    return (Math.abs(y2 - y1));
}

public int getUpperLeftX() {
    return (Math.min(x1, x2));
}

public int getUpperLeftY() {
    return (Math.min(y1, y2));
}
}

Sorry for the mass of code, I tried to trim out as much as I could.
Clicking on the image draws points which are joined up to create lines. When the user clicks the "New Object" button, the first and last points are joined to create a polygon. This all works fine, but if you click "New Square" and drag on the image, all previous shapes flicker as the mouse is moved and disappear when the mouse button is released. If "New Square" is clicked again (a necessity of poor coding on my behalf so far) and another square drawn, the 'disappeared' shapes can be seen flickering again, but then disappear once the mouse is released.
I'm calling repaint() in the mouseDragged(...) event, which I thought was all that was necessary. It actually works (almost) as wanted when I change
repaint();

for
Graphics g = this.getGraphics();
paintComponent(g);

but every book and article I've read said I should never call paintComponent myself, ever. An issue with calling paintComponent however is that the background image tends to flicker alot.
If repaint() calls paintComponent, why do they lead to different results?
I also don't understand why, when using repaint() in the mouseDragged event, I must , I must also call drawRectangle(...) in mouseReleased for the square to be seen at all, but when using paintComponent, I don't?
Any advice or pointers are greatly appreciated, thankyou.

A: In your drawRectangle and drawPolygon you are re-getting a graphics object, but you are calling them from paintComponent. this is what's causing the odd behaviour, you should pass the graphics from painComponent in to those methods.
I am seeing other odd behaviour though, like the polygons stay green until I've finished painting a square, when they then turn red, but one of the lines stays green and eventually vanishes. I didn't look in to that too much.
Also, polygon drawing and Point and Rectangle are supported in awt, is there any reason you chose to create your own classes for those?
package test;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel implements MouseListener,
    MouseMotionListener {

Rectangle currentRectangle = null;
boolean drawingRectangle = false;

/**
 * some java stuff to get rid of warnings
 */
private static final long serialVersionUID = 1L;

/**
 * image to be tagged
 */
BufferedImage image = null;

/**
 * list of current polygon's vertices
 */
ArrayList<Point> currentPolygon = null;

/**
 * list of polygons
 */
ArrayList<ArrayList<Point>> polygonsList = null;

ArrayList<Rectangle> rectangleList = null;

/**
 * extended constructor - loads image to be labelled
 *
 * @param imageName
 *            - path to image
 * @throws Exception
 *             if error loading the image
 */
public ImagePanel(String imageName) throws Exception {

    currentPolygon = new ArrayList<Point>();
    polygonsList = new ArrayList<ArrayList<Point>>();
    rectangleList = new ArrayList<Rectangle>();

    image = ImageIO.read(new File(imageName));
    Dimension panelSize = new Dimension(image.getWidth(), image.getHeight());
    this.setSize(panelSize);
    this.setMinimumSize(panelSize);
    this.setPreferredSize(panelSize);
    this.setMaximumSize(panelSize);

    setBounds(0, 0, image.getWidth(), image.getHeight());
    addMouseListener(this);
    addMouseMotionListener(this);
    this.setVisible(true);

}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    System.out.println("Paint Component");
    Graphics2D g2d = (Graphics2D) g;

    // Paint image on screen
    g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);

    // display all the completed polygons
    for (ArrayList<Point> polygon : polygonsList) {
        drawPolygon(polygon,g);
        finishPolygon(polygon);
        System.out.println("Polly");
    }

    // Display all completed squares
    for (Rectangle r : rectangleList) {
        drawRectangle(r,g);
        System.out.println("Square");
    }

    // display current polygon
    if (currentPolygon != null) {
        drawPolygon(currentPolygon, g);
    }

    // display current square
    if (currentRectangle != null) {
        drawRectangle(currentRectangle, g);
    }
}

/**
 * displays a polygon without last stroke
 *
 * @param polygon
 *            to be displayed
 */
public void drawPolygon(ArrayList<Point> polygon,  Graphics gr) {
    Graphics2D g = null;
    if (gr instanceof Graphics2D) {
        g = (Graphics2D) gr;
    }
    else{ return; }
    // set to red so I can see when it's being redrawn
    g.setColor(Color.RED);
    g.setStroke(new BasicStroke(3));
    for (int i = 0; i < polygon.size(); i++) {
        Point currentVertex = polygon.get(i);
        if (i != 0) {
            Point prevVertex = polygon.get(i - 1);
            g.drawLine(prevVertex.getX(), prevVertex.getY(),
                    currentVertex.getX(), currentVertex.getY());
        }
        g.fillOval(currentVertex.getX() - 5, currentVertex.getY() - 5, 10,
                10);
    }
}

public void drawRectangle(Rectangle r, Graphics gr) {
    Graphics2D g = null;
    if (gr instanceof Graphics2D) {
        g = (Graphics2D) gr;
    }
    else{ return; }
    g.setStroke(new BasicStroke(3));
    g.setColor(Color.BLUE);
    g.drawLine(r.getX1(), r.getY1(), r.getX2(), r.getY1());
    g.drawLine(r.getX1(), r.getY1(), r.getX1(), r.getY2());
    g.drawLine(r.getX2(), r.getY2(), r.getX2(), r.getY1());
    g.drawLine(r.getX2(), r.getY2(), r.getX1(), r.getY2());

    System.out.println(r.getX1() + " " + r.getY1() + " " + r.getX2());
    System.out.println("Drawn rectangle");
}

/**
 * displays last stroke of the polygon (arch between the last and first
 * vertices)
 *
 * @param polygon
 *            to be finished
 */
public void finishPolygon(ArrayList<Point> polygon) {
    // if there are less than 3 vertices than nothing to be completed
    if (polygon.size() >= 3) {
        Point firstVertex = polygon.get(0);
        Point lastVertex = polygon.get(polygon.size() - 1);

        Graphics2D g = (Graphics2D) this.getGraphics();
        g.setColor(Color.GREEN);
        g.setStroke(new BasicStroke(3));
        g.drawLine(firstVertex.getX(), firstVertex.getY(),
                lastVertex.getX(), lastVertex.getY());
    }
}

/**
 * moves current polygon to the list of polygons and makes pace for a new
 * one
 */
public void addNewPolygon() {
    // finish the current polygon if any
    if (currentPolygon != null) {
        finishPolygon(currentPolygon);
        polygonsList.add(currentPolygon);
    }

    currentPolygon = new ArrayList<Point>();
}

public void mouseClicked(MouseEvent e) {

    if (!drawingRectangle) {
        int x = e.getX();
        int y = e.getY();

        // check if the cursor is within image area
        if (x > image.getWidth() || y > image.getHeight()) {
            // if not do nothing
            return;
        }

        Graphics2D g = (Graphics2D) this.getGraphics();

        // if the left button than we will add a vertex to poly
        if (e.getButton() == MouseEvent.BUTTON1) {
            g.setColor(Color.GREEN);
            if (currentPolygon.size() != 0) {
                Point lastVertex = currentPolygon
                        .get(currentPolygon.size() - 1);

                g.setStroke(new BasicStroke(3));
                g.drawLine(lastVertex.getX(), lastVertex.getY(), x, y);
            }
            g.fillOval(x - 5, y - 5, 10, 10);

            currentPolygon.add(new Point(x, y));
            System.out.println(x + " " + y + " polygon point");
        }
    }
}

public void mouseEntered(MouseEvent arg0) {
}

public void mouseExited(MouseEvent arg0) {
}

public void mousePressed(MouseEvent arg0) {
    if (drawingRectangle) {
        currentRectangle = new Rectangle(arg0.getX(), arg0.getY(),
                arg0.getX(), arg0.getY(), Color.BLACK);

    }
}

public void mouseReleased(MouseEvent arg0) {
    if (drawingRectangle) {
        rectangleList.add(new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor()));

        System.out.println(currentRectangle.getX1() + " "
                + currentRectangle.getY1() + " " + arg0.getX() + " "
                + arg0.getY() + " rectangle point");

        // unnecessary when mouseDragged calls paintComponent directly?
        /*drawRectangle(new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor()));*/

        currentRectangle = null;
        drawingRectangle = false;

    }
}

public void mouseDragged(MouseEvent arg0) {

    if (drawingRectangle) {
        currentRectangle = new Rectangle(currentRectangle.getX1(),
                currentRectangle.getY1(), arg0.getX(), arg0.getY(),
                currentRectangle.getColor());

        System.out.println(currentRectangle.getX1() + " "
                + currentRectangle.getY1() + " " + arg0.getX() + " "
                + arg0.getX() + " " + "Dragging");
        repaint();

    // It works better using this instead on repaint()

//           Graphics g = this.getGraphics();
//           paintComponent(g);
    }

}

public void mouseMoved(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

}


text:
Q: sending a list as POST requests With python I am trying to debug this PHP code (which is inside a lot of other code that would clutter the question)
$sql = rtrim("INSERT INTO someTable (foo, bar, id) VALUES " . str_repeat("(?, ?, $id)," , count($contents)), ',');

$stmt = $dbh->prepare($sql);

foreach ($contents as $i => $line) {

      $stmt->bindParam(2*$i+1, $line['foo'], PDO::PARAM_STR);
      $stmt->bindParam(2*$i+2, $line['bar'], PDO::PARAM_STR);

      echo $line['dutch'] . '->' . $line['english'] . '\n';

      if (!$stmt->execute()) {
        $dbh->rollBack();
        return false;
      }
}
$dbh->commit();
return true;

for this debugging I made this piece of code
import requests
s = requests.Session()
content = [
{'foo': 'f', 'bar': 'b'},
{'foo': 'o', 'bar': 'a'},
{'foo': 'o', 'bar': 'r'}
]
s.post("http://localhost:8000", data={'content': content})

Which failed to add the data to my database
So, I tried a little debugging
print_r($_POST)

which returned
Array
(
    [someOtherVariables] => otherValues
    [content] => foo
)

I had expected content to contain an array of objects yet it somehow contains only the name of the first index.
Does anyone know why this python code is not sending the full list and how I could modify my code so that it does work?
I have also tried sending the data with the json instead of the data variable s.post("http://localhost:8000", json={'content': content}) but that does not seem to solve my problem.

A: I think it could be that you need to convert your python dict to a json string, before sending it via requests.
import json

# a Python object (dict):
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# convert into JSON:
y = json.dumps(x)

In your case:
contentAsjsonString = json.dumps(content)
s.post("http://localhost:8000", data={'content': contentAsjsonString })


text:
Q: Is balancing the only mechanism that regulates the phase currents in a three phase system? Here is a basic illustration of a distribution system:

In a 3-phase AC system, phases cancel each other out, leaving only a small imbalance current and this is fed to earth at the substation. That is why when we touch neutral it is safe. I can understand up to this point.
Below is a transformer at a 3-phase system:

Here is my question:
Imagine some engineers set the electricity distribution such that it is balanced perfectly. Which means all the phases passes the same amount of current and no current flows from the balanced point to the earth.
But lets say one of the phases started to draw more current than the others, would the system now automatically balance itself by letting currents flowing from the balanced point? This is what I learned if I'm not wrong.
Is there an extra system which limits the current ratios?
I'm wondering whether there is an extra system to keep the three phase currents similar besides earthing the balanced point at the substation.

A: Your question misses the point.
As there is a neutral conductor between the generator and the load, any imbalance between currents in the three phases is taken up by current in the neutral conductor.
Balance, when feeding multiple single phase loads, is purely statistical. If you power enough houses, then you will find that the current flow in neutral is noisy, generally small with the occasional peak.
Balance, when driving 3 phase loads, is part of the specification of the load. 3 phase motors and heaters will usually have a spec for what balance they are intended to achieve.
The connection of neutral to local ground is a different issue. If the whole system was connected to ground at a single point, say at the source, then of course there would be no current flow through that tie conductor, and no voltage difference between those points. However, the neutral conductor arriving at a distant point would have a voltage drop across it due to the current flowing, and a potential maybe a few volts from ground.
If there is a further local tie point, then that potential of a few volts will drive a current through that tie point. What is happening now is that the neutral current is being shared between the neutral conductor, and the ground, between source and load.
Generally, injecting significant currents into ground is deemed to be a BAD THING, and the many regulations around how to load 3 phase systems, how to size neutral conductors, when and where you can and can't tie neutral to local ground, are in pursuit of minimising ground currents.

A: There are two types of loads:

*

*3-phase.

*single-phase.

Large consumers, like businesses and factories, are mostly 3-phase loads, which are balanced.  No neutral current.
Unbalanced loads come from single-phase loads.  You can either have two phases per neighborhood A & B, B & C and C & A, which gives consumers 120V, 208V or single phases A, B or C at 120V and 240V.
Your design engineers design the system so the system is balanced, but the actual usage depends on independent consumers, so classically from Current Balancing ...:

a professional workman measures the current of neutral conductor in the
  substation and main branches of network, and tries to balance the current by exchanging the branches from one phase to another.

These days automation is applied to adjust branch phases.  Your design engineers do statistics on usage and try to adjust physical connections so neutral currents are minimized.  Lots of man-hours, software and automation are applied to minimize neutral current.
As you can tell from the research paper referenced, there is always some current on the neutral wire at sub-stations.


text:
Q: How to use the System.Data.SqlClient namespace in the Azure Function V4 on the portal I have one requirement to use the system.data.sqlclient library in the Azure Function V4 on the portal.
When I tried it this way but it return the error.
Could you please help me how to use the library in the Azure Function on the portal.
My run.csx file
using System.Data.SqlClient;

using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var conn = new SqlConnection("MyConnectionString");
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

I am getting this error while executing the function on the portal.

run.csx(7,20): error CS1069: The type name 'SqlConnection' could not be found in the namespace 'System.Data.SqlClient'. This type has been forwarded to assembly 'System.Data.SqlClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that assembly

I have develop function App on the VS Code and use the library it's working fine as well as when I downgrade my function App from V4 to V3. It's working fine with same code but when I am trying to upgrade the function App with V4, it returns the error.
see here : https://github.com/dotnet/SqlClient/issues/1512


text:
Q: Help with Mathematical Induction $$1^3+2^3+\cdots+n^3=\left[\frac{n(n+1)}2\right]^2$$
so far I have..
$$1^3+2^3+\cdots+k^3+(k+1)^3=\left[\frac{(k+1)(k+2)}2\right]^2$$
then..
$$\left[\frac{k(k+1)}2\right]^2+(k+1)^3=\left[\frac{(k+1)(k+2)}2\right]^2$$
where do I go from here so that the rhs equals the lhs?

A: Inductive step:
$$\begin{align*}\underbrace{1^3+2^3+\ldots+n^3}_{=\left(\dfrac{n(n+1)}{2}\right)^2}+(n+1)^3&=\left(\dfrac{n(n+1)}{2}\right)^2+(n+1)^3=(n+1)^2\cdot\left(\frac{n^2}{4}+(n+1)\right)=\\&=(n+1)^2\cdot\left(\frac{n^2+4n+4}{4}\right)=(n+1)^2\cdot\left(\frac{(n+2)^2}{2^2}\right)=\\&=\left(\frac{(n+1)(n+2)}{2}\right)^2\end{align*}$$


text:
Q: Parse json array into list of struct golang I have a json like below and I am trying to make a struct for below json which can store the data for me when I unmarshall it.
{
  "clientMetrics": [
    {
      "clientId": 951231,
      "customerData": {
        "Process": [
          "ABC"
        ],
        "Mat": [
          "KKK"
        ]
      },
      "legCustomer": [
        8773
      ]
    },
    {
      "clientId": 1234,
      "legCustomer": [
        8789
      ]
    },
    {
      "clientId": 3435,
      "otherIds": [
        4,
        32,
        19
      ],
      "legCustomer": [
        10005
      ]
    },
    {
      "clientId": 9981,
      "catId": 8,
      "legCustomer": [
        13769
      ]
    },
    {
      "clientId": 12124,
      "otherIds": [
        33,
        29
      ],
      "legCustomer": [
        12815
      ]
    },
    {
      "clientId": 8712,
      "customerData": {
        "Process": [
          "College"
        ]
      },
      "legCustomer": [
        951
      ]
    },
    {
      "clientId": 23214,
      "legCustomer": [
        12724,
        12727
      ]
    },
    {
      "clientId": 119812,
      "catId": 8,
      "legCustomer": [
        14519
      ]
    },
    {
      "clientId": 22315,
      "otherIds": [
        32
      ],
      "legCustomer": [
        12725,
        13993
      ]
    },
    {
      "clientId": 765121,
      "catId": 8,
      "legCustomer": [
        14523
      ]
    }
  ]
}

clientMetrics is a json array which contains each clientMetric object. Each clientMetric object can have various fields into it. I tried something like below but I am confuse on how to add rest since I am coming from Java background and I don't see there is set available in golang. Also confuse on how to add customerData object too.
type ClientMetrics struct {
    ClientId    int64
    CatId       int64

}

What is the best way to unmarshall above json into a list of ClientMetrics struct in golang?

A: You can use json to go here : https://mholt.github.io/json-to-go/
But it will repeat CustomerData struct twice make sure you should remove one of them.
I have created a sample struct for your scenario as follows :
type AutoGenerated struct {
        ClientMetrics []struct {
            ClientID     int `json:"clientId"`
            CustomerData struct {
                Process []string `json:"Process"`
                Mat     []string `json:"Mat"`
            } `json:"customerData,omitempty"`
            LegCustomer []int `json:"legCustomer"`
            OtherIds    []int `json:"otherIds,omitempty"`
            CatID       int   `json:"catId,omitempty"`
        } `json:"clientMetrics"`
    }

You can run it here in go playground  : https://go.dev/play/p/R1M1HfzpEny

A: If you're using VS Code, there are a few extensions that can do this job.
One of them is named Paste JSON as Code.

*

*Install the extension

*Copy the JSON and in your clipboard (ctrl+c)

*Press Ctrl+Shift+P and select Paste JSON as code

*Type name of struct and press enter

If this doesn't work for you, you can always use this site https://mholt.github.io/json-to-go/ but it would be a better practice to use the struct obtained after unselecting Inline type definitions option.


text:
Q: gmail authentication for my php website lI have a php website, I want to first authenticate users from gmail and then let him use my website stuff (like idea used by http://stackoverflow.com)
Following is simple idea I want to implement
if user type www.example.com and he already login to gmail account then he will be directed to www.example.com/services.php
if user is not login then he to will be directed to gmail login page.
I need a working example, I searched alot using term openid, sso, federated login etc, but I could not find any working example

A: Everything is explained in the Federated Login for Google Account Users article by Google (here's a general explanation). Unfortunately I don't expect anyone here to write the code from scratch for you.

A: Stackoverflow uses his own extension of openid-selector.
Someone asked this before: Login system just like stackoverflow's, written in php
Here is a tutorial: http://remysharp.com/2007/12/21/how-to-integrate-openid-as-your-login-system/

A: By GMail I assume you mean Google Account?
It's not a quick and simple process, since Google takes privacy very seriously. But here's a full documentation on how to authenticate with Google.


text:
Q: How to close a drop down menu item? I use drop down menu.
When you open a drop down menu, reduce using Windows right bottom corner, menu are not closed. When unminimizing engine (with same corner button, or other ways), sometimes menus remains open and causes problem.
So I want to close all menus when engine is minimized. How can I do it?
I saw that they recommend using HideDropDown(), but it doesn't work in this case.


text:
Q: Печать документов java Мне надо распечатать файл, который хранится на локальном диске, но с такими параметрами: количество страниц, выбор цвет/чорно-белый принт. Вот что у меня есть:
Desktop.getDesktop().print(new File(file_path));

Проблема в том, что таким способом печатается весь файл на дефолтном принтере(черно-белая печать).
Нашел что-то связано с печатью в пакете java.awt.print, но как создать объект файла что нужно напечатать не могу понять.

A: Нашел такой вот способ печати да и добавление атрибутов:
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new PageRanges(1,5));
PrintService[] services =
            PrintServiceLookup.lookupPrintServices(myFormat, aset);
if (services.length > 0) {
    DocPrintJob job = services[0].createPrintJob();
    try {
        job.print(myDoc, aset);
    } catch (PrintException pe) {}
}


text:
Q: Pixelate math formula on purpose AFAIK the standard pdf documents produced by pdflatex are mostly vectorized (you can zoom and it doesn't pixelate).
That is a very good thing, but right now I would like the oposite: is it possible to "pixelate" the whole document (text and math equations) so that the output pdf looks like it was generated by a 8-bit computer? (while still being readable)
Thanks.

A: As Ulrike mentioned in her comment, you could remove the map file to get the old bitmap font loaded instead of vector fonts.
\pdfmapfile{-pdftex.map}
\documentclass{article}
\usepackage{amsmath}
\begin{document}
$a + b = c$
\end{document}

No sure whether this is pixelated enough for you.

To get it even more pixelated, just crank down \pdfpkresolution (thanks  Thérèse!)
\pdfmapfile{-pdftex.map}
\pdfpkresolution=100 % default 600
\documentclass{article}
\usepackage{amsmath}
\begin{document}
$a + b = c$
\end{document}

Otherwise you could just look for a font which has the desired effect online, like from here https://www.fontsquirrel.com/fonts/list/classification/pixel.  For example
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont{VT323-Regular.ttf}
\setmathfont{Latin Modern Math}
\setmathfont[range=it->up]{VT323-Regular.ttf}
\setmathfont[range=]{Latin Modern Math}
\begin{document}
$a + b = c$
\end{document}


text:
Q: Elementary way to show $\lim_{n \rightarrow \infty} \sqrt[n]{a_n} = \lim_{n \rightarrow \infty} \frac{a_{n+1}}{a_n}$? Let $a_n \gt 0$ for $n \in \mathbb{N}$. The convergence radius of the series $\sum_{n=0}^\infty a_n z^n$ is $\frac{1}{q}$ with $q = \lim_{n \rightarrow \infty} \sqrt[n]{a_n}$ or $q = \lim_{n \rightarrow \infty} \frac{a_{n+1}}{a_n}$, if these limits exist. Therefore the $\lim$s must be identical.
However I was wondering whether there exists a more elementary way to show this identity? (Or generally any other way?)

A: The general relation is
$$
\liminf_{n \to \infty} \frac{a_{n+1}}{a_n} \le
\liminf_{n \to \infty} \sqrt[n]{\mathstrut a_n} \le
\limsup_{n \to \infty} \sqrt[n]{\mathstrut a_n}  \le
\limsup_{n \to \infty} \frac{a_{n+1}}{a_n} \quad \text{(*)}
$$
provided that all $a_n$ are positive. It follows that if
$\lim_{n \to \infty} \frac{a_{n+1}}{a_n}$ exists then
$\lim_{n \to \infty} \sqrt[n]{\mathstrut a_n}$ exists as well and they are equal.
To prove the rightmost inequality, define $S := \limsup_{n \to \infty} \frac{a_{n+1}}{a_n}$. For every $\epsilon > 0$ there is a $N \in \mathbb N$
such that
$$
\frac{a_{n+1}}{a_n} < S + \epsilon \quad \text{ for } n \ge N \, .
$$
$$
  \implies a_n < a_N \, (S + \epsilon)^{n - N} \quad  \text{ for }  n \ge N
$$
$$
  \implies \sqrt[n]{\mathstrut a_n} < (S + \epsilon) \sqrt[n]{ a_N (S + \epsilon)^{-N}}
$$
$$
 \implies \limsup_{n \to \infty} \sqrt[n]{\mathstrut a_n} \le S + \epsilon \, .
$$
The leftmost inequality can be proved in the same way, or by taking
the reciprocals.
That the convergence radius $R$ of a power series $\sum_{n=0}^\infty a_n z^n$ can be
determined with the root test or
with the ratio test
is a consequence of the above relation (*), not the other way around.
But note that the tests are slighty different:
$$
  \frac 1R = \limsup_{n \to \infty} \sqrt[n]{\mathstrut |a_n|}
$$
holds even if the limit does not exists.
$$
  \frac 1R = \lim_{n \to \infty} \bigl| \frac{a_{n+1}}{a_n} \bigr|
$$
is only valid if the limit on the right-hand side exists. You cannot
generally replace the $\lim$ by $\limsup$ in the ratio test.


text:
Q: Dynamic DNS with split horizon DNS or hairpin NAT I would like to host a CalDAV and CardDAV server for devices that will roam between being on the LAN to outside my network (such as my iPhone and laptops). A static IP is prohibitively expensive.
I have a my own domain, a Mac Mini with Lion Server, a SonicWall TZ 200 and a dyn.com dynamic address (the SonicWall keeps the dynamic account updated). I would normally set up a static IP and use split horizon DNS so those roaming devices can point to server.mydomain.com and function on and off my LAN.
Is a similar setup possible with the dynamic address? I am happy to set up the clients with either server.mydomain.com or myaccount.dyndns.org but I would prefer to use my domain.
Would either hairpin NAT on the SonicWall or split horizon DNS using the Lion Server allow this to work?

A: The reason split horizon DNS is set up is almost always because an internal service cannot be reached off of the LAN. For example, Active Directory domain controllers that also hold internal DNS. If your all of your services are intended to be externally reachable then split DNS isn't necessary, strictly speaking. Discard any use of split DNS in your design until you find a sure reason to use it.
Hairpin NAT / tromboning would be how anyone behind your firewall would reach your server, which is acceptable. The biggest downside to hairpinning is that it "unnecessarily" engages your SPI engine and anything else running in the firewall like UTM services. However, if that's how you intentionally designed it, then it's hard to call it "unnecessary" - the TZ 200 can take a decent amount of traffic and I highly doubt a CalDAV/CardDAV service will be getting thousands of requests per second from your internal network. =)