text:
package org.renjin.primitives;

import static org.renjin.util.CDefines.R_UnboundValue;

import java.util.Collections;
import java.util.List;

import org.renjin.eval.Calls;
import org.renjin.eval.ClosureDispatcher;
import org.renjin.eval.Context;
import org.renjin.eval.DispatchChain;
import org.renjin.eval.EvalException;
import org.renjin.primitives.annotations.ArgumentList;
import org.renjin.primitives.annotations.Current;
import org.renjin.primitives.annotations.Primitive;
import org.renjin.sexp.Closure;
import org.renjin.sexp.DoubleVector;
import org.renjin.sexp.Environment;
import org.renjin.sexp.Frame;
import org.renjin.sexp.Function;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.HashFrame;
import org.renjin.sexp.IntVector;
import org.renjin.sexp.ListVector;
import org.renjin.sexp.LogicalArrayVector;
import org.renjin.sexp.Null;
import org.renjin.sexp.PairList;
import org.renjin.sexp.PrimitiveFunction;
import org.renjin.sexp.Promise;
import org.renjin.sexp.PromisePairList;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.StringArrayVector;
import org.renjin.sexp.StringVector;
import org.renjin.sexp.Symbol;
import org.renjin.sexp.Symbols;
import org.renjin.sexp.Vector;

import com.google.common.collect.Lists;

/**
 * Primitives used in the implementation of the S3 object system
 */
public class S3 {

  public static Symbol METHODS_TABLE = Symbol.get(".__S3MethodsTable__.");

  public static SEXP UseMethod(@Current Context context, String genericMethodName) {
    /*
     * When object is not provided, it defaults to the first argument
     * of the calling function
     */
    if(context.getArguments().length() == 0) {
      return UseMethod(context, genericMethodName, Null.INSTANCE);

    } else {
      SEXP object = context.evaluate( context.getArguments().getElementAsSEXP(0),
              context.getParent().getEnvironment());

      return UseMethod(context, genericMethodName, object);
    }
  }

  public static SEXP UseMethod(@Current Context context, String genericMethodName, SEXP object) {

    return Resolver
              .start(context, genericMethodName, object)
              .withDefinitionEnvironment(context.getClosure().getEnclosingEnvironment())
              .next()
              .apply(context, context.getEnvironment());
  }

  @Primitive
 public static SEXP NextMethod(@Current Context context, @Current Environment env,
      SEXP generic, SEXP object, @ArgumentList ListVector extraArgs) {

    return Resolver
           .resume(context)
           .withGenericArgument(generic)
           .withObjectArgument(object)
           .next()
           .applyNext(context, context.getEnvironment());
  }

//
//
////    char buf[512], b[512], bb[512], tbuf[10];
////    const char *sb, *sg, *sk;
////    SEXP ans, s, t, klass, method, matchedarg, generic, nextfun;
////    SEXP sysp, m, formals, actuals, tmp, newcall;
////    SEXP a, group, basename;
////    SEXP callenv, defenv;
////    RCNTXT *cptr;
////    int i, j, cftmp;
//
////    cptr = R_GlobalContext;
////    cftmp = cptr->callflag;
////    cptr->callflag = CTXT_GENERIC;
//
//    /* get the env NextMethod was called from */
////    sysp = R_GlobalContext->sysparent;
////    while (cptr != NULL) {
////        if (cptr->callflag & CTXT_FUNCTION && cptr->cloenv == sysp) break;
////        cptr = cptr->nextcontext;
////    }
////    if (cptr == NULL)
////        error(_("'NextMethod' called from outside a function"));
//
//    Context sysp = context.getParent();
//
//    /* eg get("print.ts")(1) */
////    if (TYPEOF(CAR(cptr->call)) == LANGSXP)
////       error(_("'NextMethod' called from an anonymous function"));
//
//    /* Find dispatching environments. Promises shouldn't occur, but
//       check to be on the safe side.  If the variables are not in the
//       environment (the method was called outside a method dispatch)
//       then chose reasonable defaults. */
//    SEXP callenv = env.getVariable(".GenericCallEnv");
//
//    /*if (TYPEOF(callenv) == PROMSXP)
//        callenv = eval(callenv, R_BaseEnv);
//    else */
//    if (callenv == Symbol.UNBOUND_VALUE) {
//      callenv = env;
//    }
//
//    SEXP defenv = env.getVariable(".GenericDefEnv");
//    /*if (TYPEOF(defenv) == PROMSXP) defenv = eval(defenv, R_BaseEnv);
//    else */
//    if (defenv == Symbol.UNBOUND_VALUE) {
//      defenv = context.getGlobalEnvironment();
//    }
//
//    /* set up the arglist */
//    SEXP s = lookupMethod(context, (Symbol)sysp.getCall().getFunction(), (Environment)env,
//        (Environment)callenv, (Environment)defenv);
//
//    if(s == Symbol.UNBOUND_VALUE) {
//      throw new EvalException("no calling generic was found: was a method called directly?");
//    }
//    if (!(s instanceof Closure)){ /* R_LookupMethod looked for a function */
//      throw new EvalException("function' is not a function, but of type %s", s.getTypeName());
//    }
//    /* get formals and actuals; attach the names of the formals to
//       the actuals, expanding any ... that occurs */
//    PairList formals = ((Closure) s).getFormals();
//    PairList actuals = context.getParent().getArguments();
//    actuals = Calls.matchArguments(formals, actuals);
//    actuals = expandDotDotDot(actuals);
//
//
//    // strip out arguments with missing values. These named arguments may not
//    // be defined in calls further down the chain and we don't want to "generate"
//    // new arguments
//    PairList.Builder noMissing = new PairList.Builder();
//    for(PairList.Node node : actuals.nodes()) {
//      if(node.getValue() != Symbol.MISSING_ARG) {
//        noMissing.add(node.getRawTag(), node.getValue());
//      }
//    }
//    actuals = noMissing.build();
//
////    /* we can't duplicate because it would force the promises */
////    /* so we do our own duplication of the promargs */
////
//
//    PairList.Builder updatedArgs = new PairList.Builder();
//    for(PairList.Node actual : actuals.nodes()) {
//      SEXP temp;
//      if(actual.hasTag()) {
//        // an argument may not have a tag even at this point if was
//        // part of a ... expansion
//        temp = context.getParent().getEnvironment().findVariable(actual.getTag());
//      } else {
//        temp = Symbol.UNBOUND_VALUE;
//      }
//      if(temp != Symbol.UNBOUND_VALUE &&
//          !isDefaultArgValue(temp) &&
//          temp != Symbol.MISSING_ARG) {
//        updatedArgs.add(actual.getRawTag(), Promise.repromise(context.getParent().getEnvironment(), temp));
//      } else {
//        updatedArgs.add(actual.getRawTag(), actual.getValue());
//      }
//    }
//    actuals = updatedArgs.build();
//
//
//
//
////    PROTECT(matchedarg = allocList(length(cptr->promargs)));
////    for (t = matchedarg, s = cptr->promargs; t != R_NilValue;
////         s = CDR(s), t = CDR(t)) {
////        SETCAR(t, CAR(s));
////        SET_TAG(t, TAG(s));
////    }
////    for (t = matchedarg; t != R_NilValue; t = CDR(t)) {
////        for (m = actuals; m != R_NilValue; m = CDR(m))
////            if (CAR(m) == CAR(t))  {
////                if (CAR(m) == R_MissingArg) {
////                    tmp = findVarInFrame3(cptr->cloenv, TAG(m), TRUE);
////                    if (tmp == R_MissingArg) break;
////                }
////                SETCAR(t, mkPROMISE(TAG(m), cptr->cloenv));
////                break;
////           }
////    }
////    /*
////      Now see if there were any other arguments passed in
////      Currently we seem to only allow named args to change
////      or to be added, this is at variance with p. 470 of the
////      White Book
////    */
////
////    s = CADDR(args); /* this is ... and we need to see if it's bound */
////    if (s == R_DotsSymbol) {
////        t = findVarInFrame3(env, s, TRUE);
////        if (t != R_NilValue && t != R_MissingArg) {
////            SET_TYPEOF(t, LISTSXP); /* a safe mutation */
////            s = matchmethargs(matchedarg, t);
////            UNPROTECT(1);
////            PROTECT(matchedarg = s);
////            newcall = fixcall(newcall, matchedarg);
////        }
////    }
////    else
////        error(_("wrong argument ..."));
//
//    /*
//      .Class is used to determine the next method; if it doesn't
//      exist the first argument to the current method is used
//      the second argument to NextMethod is another option but
//      isn't currently used).
//    */
//    SEXP klass = sysp.getEnvironment().getVariable(".Class");
//
//
//    if (klass == Symbol.UNBOUND_VALUE) {
//        s = GetObject(context.getParent());
//        if (!s.isObject()) {
//          throw new EvalException("object not specified");
//        }
//        klass = s.getAttributes().getClassVector();
////      throw new EvalException(".Class attribute not present");
//    }
//
//    /* the generic comes from either the sysparent or it's named */
//    if(generic == Null.INSTANCE) {
//      generic = sysp.getEnvironment().getVariable(".Generic");
//    }
//    if (generic == Symbol.UNBOUND_VALUE) {
//      //  generic = eval(CAR(args), env);
//      throw new EvalException(".Generic not present");
//    }
//    if( generic == Null.INSTANCE ) {
//      throw new EvalException("generic function not specified");
//    }
//
//    if ( !(generic instanceof StringVector) || generic.length() > 1) {
//      throw new EvalException("invalid generic argument to NextMethod");
//    }
//
////    if (CHAR(STRING_ELT(generic, 0))[0] == '\0')
////        error(_("generic function not specified"));
//
//    /* determine whether we are in a Group dispatch */
//
//    SEXP groupExp = context.getParent().getEnvironment().getVariable(".Group");
//    String group;
//    if (groupExp == Symbol.UNBOUND_VALUE) {
//      group = "";
//    } else {
//      group = ((StringVector)groupExp).getElementAsString(0);
//    }
//
////    if (!isString(group) || length(group) > 1)
////        error(_("invalid 'group' argument found in NextMethod"));
//
//    /* determine the root: either the group or the generic will be it */
//
//    String basename;
//    if (group.isEmpty()) {
//      basename = ((StringVector)generic).getElementAsString(0);
//    } else {
//      basename = group;
//    }
//
//    SEXP nextfun = Null.INSTANCE;
//
//    /*
//       Find the method currently being invoked and jump over the current call
//       If t is R_UnboundValue then we called the current method directly
//    */
//
//    SEXP dotMethod = context.getParent().getEnvironment().getVariable(".Method");
//
//    String b=null;
//    if( dotMethod != Symbol.UNBOUND_VALUE) {
//      if( !(dotMethod instanceof StringVector) ) {
//        throw new EvalException("wrong value for .Method");
//      }
//      for(String ss : (StringVector)dotMethod) {
//        if(!ss.isEmpty()) {
//          b = ss;
//          break;
//        }
//      }
////        for(i = 0; i < length(method); i++) {
////            ss = translateChar(STRING_ELT(method, i));
////            if(strlen(ss) >= 512)
////                error(_("method name too long in '%s'"), ss);
////            sprintf(b, "%s", ss);
////            if(strlen(b)) break;
////        }
////        /* for binary operators check that the second argument's method
////           is the same or absent */
////        for(j = i; j < length(method); j++){
////            const char *ss = translateChar(STRING_ELT(method, j));
////            if(strlen(ss) >= 512)
////                error(_("method name too long in '%s'"), ss);
////          sprintf(bb, "%s", ss);
////          if (strlen(bb) && strcmp(b,bb))
////              warning(_("Incompatible methods ignored"));
////        }
//    }
//    else {
////        if(strlen(CHAR(PRINTNAME(CAR(cptr->call)))) >= 512)
////           error(_("call name too long in '%s'"),
////                 CHAR(PRINTNAME(CAR(cptr->call))));
////        sprintf(b, "%s", CHAR(PRINTNAME(CAR(cptr->call))));
//      throw new EvalException(".Method is not set, not sure what to do");
//    }
//
//    String sb = basename;
//    String buf = null;
//    int j;
//    for (j = 0; j < klass.length(); j++) {
//      String sk = ((StringVector)klass).getElementAsString(j);
//      buf = sb + "." + sk;
//      if (!buf.equals(b)) {
//        break;
//      }
//    }
//
//    if (buf != null && buf.equals(b)) { /* we found a match and start from there */
//      j++;
//    } else {
//      j = 0;  /*no match so start with the first element of .Class */
//    }
//    /* we need the value of i on exit from the for loop to figure out
//           how many classes to drop. */
//
//    String sg = ((StringVector)generic).getElementAsString(0);
//    int i;
//    for (i = j ; i < klass.length(); i++) {
//      String sk = ((StringVector)klass).getElementAsString(0);
//      buf = sg + "." + sk;
//      nextfun = lookupMethod(context, Symbol.get(buf), env, (Environment)callenv, (Environment)defenv);
//      if (nextfun instanceof Function) {
//        break;
//      }
//      if (groupExp != Symbol.UNBOUND_VALUE) {
//        /* if not Generic.foo, look for Group.foo */
//        buf = sb + "." + sk;
//        nextfun = lookupMethod(context, Symbol.get(buf), env, (Environment)callenv, (Environment)defenv);
//        if(nextfun instanceof Function) {
//          break;
//        }
//      }
//      if (nextfun instanceof Function) {
//        break;
//      }
//    }
//    if (!(nextfun instanceof Function)) {
//      buf = sg + ".default";
//      nextfun = lookupMethod(context, Symbol.get(buf), env, (Environment)callenv, (Environment)defenv);
//      /* If there is no default method, try the generic itself,
//        provided it is primitive or a wrapper for a .Internal
//        function of the same name.
//      */
//      if (!(nextfun instanceof Function)) {
//        Symbol t = Symbol.get(sg);
//        nextfun = env.findFunction(context, t);
//        if ( nextfun instanceof Promise) {
//          nextfun = context.evaluate( nextfun, env);
//        }
//        if (!(nextfun instanceof Function)) {
//          throw new EvalException("no method to invoke");
//        }
//        if (nextfun instanceof Closure) {
//          PrimitiveFunction internal = Primitives.getInternal(t);
//          if (internal != null)
//            nextfun = internal;
//          else {
//            throw new EvalException("no method to invoke");
//          }
//        }
//      }
//    }
//
//    StringArrayVector.Builder newklass = new StringArrayVector.Builder();
//    for(j=0;j< newklass.length();++j) {
//      newklass.add(((StringVector)klass).getElementAsString(i++));
//    }
//    newklass.setAttribute("previous", klass);
//
//   // PROTECT(m = allocSExp(ENVSXP));
//    Frame m = new HashFrame();
//    m.setVariable(Symbol.get(".Class"), newklass.build());
//
//
//    /* It is possible that if a method was called directly that
//        'method' is unset */
////    if (dotMethod != Symbol.UNBOUND_VALUE) {
////      /* for Ops we need `method' to be a vector */
////
////      PROTECT(method = duplicate(dotMethod));
////      for(j = 0; j < length(method); j++) {
////        if (strlen(CHAR(STRING_ELT(dotMethod,j))))
////          SET_STRING_ELT(dotMethod, j,  mkChar(buf));
////      }
////    } else {
////    dotMethod = Symbol.get(buf);
////    }
//    m.setVariable(Symbol.get(".Method"), StringVector.valueOf(buf));
////    defineVar(install(".GenericCallEnv"), callenv, m);
////    defineVar(install(".GenericDefEnv"), defenv, m);
//
//
//    m.setVariable(Symbol.get(".Generic"), generic);
//    m.setVariable(Symbol.get(".Group"), groupExp);
//
//    FunctionCall newcall = new FunctionCall(Symbol.get(buf), actuals);
//
//
//    if(nextfun instanceof Closure) {
//      return Calls.applyClosure((Closure)nextfun, context, newcall, actuals, env, m);
//    } else {
//      return ((Function)nextfun).apply(context, env, newcall, actuals);
//    }

//
//
//    SETCAR(newcall, method);
//    ans = applyMethod(newcall, nextfun, matchedarg, env, m);
//    UNPROTECT(10);
//    return(ans);
//    throw new EvalException("this and no further");
 // }

  public static boolean isDefaultArgValue(SEXP temp) {
    return temp instanceof Promise;
  }

  public static PairList expandDotDotDot(PairList actuals) {
    PairList.Builder result = new PairList.Builder();
    for(PairList.Node node : actuals.nodes()) {
      if(node.getValue() instanceof PromisePairList) {
        for(PairList.Node dotNode : ((PromisePairList) node.getValue()).nodes()) {
          result.add(dotNode.getRawTag(), dotNode.getValue());
        }
      } else {
        result.add(node.getRawTag(), node.getValue());
      }
    }
    return result.build();
  }

  /* gr needs to be protected on return from this function */
  public static FindResult findmethod(Context context, Vector Class, String group, String generic, Environment rho) {
    int len, whichclass;
    FindResult result = new FindResult();

    len = Class.length();

    /* Need to interleave looking for group and generic methods
     e.g. if class(x) is c("foo", "bar)" then x > 3 should invoke
     "Ops.foo" rather than ">.bar"
     */
    for (whichclass = 0; whichclass < len; whichclass++) {
      String ss = Class.getElementAsString(whichclass);
      result.buf = generic + "." + ss;

      result.meth = Symbol.get(result.buf);
      result.sxp = lookupMethod(context, result.meth, rho, rho, rho.getBaseEnvironment());
      if (result.sxp instanceof Function) {
        result.gr = StringVector.valueOf("");
        break;
      }
      result.buf = group + "." + ss;
      result.meth = Symbol.get(result.buf);
      result.sxp = lookupMethod(context, result.meth, rho, rho, rho.getBaseEnvironment());
      if (result.sxp instanceof Function) {
        result.gr = StringVector.valueOf(group);
        break;
      }
    }
    result.which = whichclass;
    return result;
  }

  public static SEXP lookupMethod(Context context, Symbol method, SEXP rho, Environment callrho, Environment defrho)
  {
//
//    if (callrho == Null.INSTANCE) {
//      throw new EvalException("use of NULL environment is defunct");
//    } else if( callrho instanceof Environment) {
//      throw new EvalException("bad generic call environment");
//    }
//    if (defrho == Null.INSTANCE) {
//      throw new EvalException("use of NULL environment is defunct");
//    } else if(!(defrho instanceof Environment)) {
//      throw new EvalException("bad generic definition environment");
//    }
//    if (defrho == R_BaseEnv)
//      defrho = R_BaseNamespace;

    /* This evaluates promises */
    SEXP val = callrho.findVariable(context, method, CollectionUtils.IS_FUNCTION, true);
    if (val instanceof Function) {
      return val;
    } else {
//      /* We assume here that no one registered a non-function */
//      SEXP table = findVarInFrame3(defrho,
//          install(".__S3MethodsTable__."),
//          TRUE);
//      if (TYPEOF(table) == PROMSXP) table = eval(table, R_BaseEnv);
//      if (TYPEOF(table) == ENVSXP) {
//        val = findVarInFrame3(table, method, TRUE);
//        if (TYPEOF(val) == PROMSXP) val = eval(val, rho);
//        if (val != R_UnboundValue) return val;
//      }
      return R_UnboundValue;
    }
  }

  /**
   * Computes the class list used for normal S3 Dispatch. Note that this
   * is different than the class() function
   */
  public static StringVector computeDataClasses(Context context, SEXP exp) {

    /*
     * Make sure we're dealing with the evaluated expression
     */
    exp = exp.force(context);

    SEXP classAttribute = exp.getAttribute(Symbols.CLASS);

    if(classAttribute.length() > 0) {
      /*
       * S3 Class has been explicitly defined
       */
      return (StringVector)classAttribute;
    } else {
      /*
       * Compute implicit class based on DIM attribute and type
       */
      StringArrayVector.Builder dataClass = new StringArrayVector.Builder();
      SEXP dim = exp.getAttribute(Symbols.DIM);
      if(dim.length() == 2) {
        dataClass.add("matrix");
      } else if(dim.length() == 1) {
        dataClass.add("array");
      }
      if(exp instanceof IntVector || exp instanceof DoubleVector) {
        dataClass.add(exp.getTypeName());
        dataClass.add("numeric");
      } else {
         dataClass.add(exp.getImplicitClass());
      }
      return dataClass.build();
    }
  }

  public static SEXP dispatchGroup(String group, FunctionCall call, String opName, PairList args, Context context, Environment rho) {
    int i, j, nargs;

    /*
     * First we need to see if we've already been through this.
     * (It's complicated)
     *
     * - This method is called by "generic" primitives that, before doing
     *   their normal thing, check to see if there's a user-defined function
     *   out there that provides specific behavior for the object.
     *
     * - It can happen that that user function in turn calls NextMethod()
     *   to defer to the default behavior of the primitive. In this case,
     *   we don't want to check again because we've already been through
     *   that; to do so would be to loop infinitely.
     *
     * - We can only tell whether this is the first or second time around,
     *   because if it's the second, NextMethod() will invoke the primitive
     *   by the name "<primitive>.default", like "as.character.default".
     */
    if(call.getFunction() instanceof Symbol &&
        ((Symbol) call.getFunction()).getPrintName().endsWith(".default")) {
      return null;
    }

    boolean useS4 = true, isOps = false;

    isOps = group.equals("Ops");

//    /* try for formal method */
//    if (length(args) == 1 && !IS_S4_OBJECT(CAR(args)))
//      useS4 = FALSE;
//    if (length(args) == 2 && !IS_S4_OBJECT(CAR(args)) && !IS_S4_OBJECT(CADR(
//        args)))
//      useS4 = FALSE;
//    if (useS4) {
//      /* Remove argument names to ensure positional matching */
//      if (isOps)
//        for (s = args; s != R_NilValue; s = CDR(s))
//          SET_TAG(s, R_NilValue);
//      if (R_has_methods(op) && (value = R_possible_dispatch(call, op, args,
//          rho, FALSE))) {
//        *ans = value;
//        return 1;
//      }
//      /* else go on to look for S3 methods */
//    }

    if (isOps)
      nargs = args.length();
    else
      nargs = 1;

    String generic = opName;

//    lclass = IS_S4_OBJECT(CAR(args)) ? R_data_class2(CAR(args)) : getAttrib(
//        CAR(args), R_ClassSymbol);

    GenericMethod left = Resolver.start(context, group, opName, args.getElementAsSEXP(0))
        .withBaseDefinitionEnvironment()
        .findNext();

    GenericMethod right = null;
    if(nargs == 2) {
      right = Resolver.start(context, group, opName, args.getElementAsSEXP(1))
          .withBaseDefinitionEnvironment()
          .findNext();
    }

    if(left == null && right == null) {
      // no generic method found
      return null;
    }

    if(left == null) {
      left = right;
    }

//
//    lsxp = R_NilValue;
//    lgr = R_NilValue;
//    lmeth = R_NilValue;
//    rsxp = R_NilValue;
//    rgr = R_NilValue;
//    rmeth = R_NilValue;

//    FindResult left = findmethod(context, lclass, group, generic, rho);
//    if (fm.sxp instanceof Function && IS_S4_OBJECT(CAR(args)) && lwhich > 0
//        && isBasicClass(translateChar(STRING_ELT(lclass, lwhich)))) {
//      /* This and the similar test below implement the strategy
//        for S3 methods selected for S4 objects.  See ?Methods */
//      value = CAR(args);
//      if (NAMED(value))
//        SET_NAMED(value, 2);
//      value = R_getS4DataSlot(value, S4SXP); /* the .S3Class obj. or NULL*/
//      if (value != R_NilValue) /* use the S3Part as the inherited object */
//        SETCAR(args, value);
//    }

//    if (isFunction(rsxp) && IS_S4_OBJECT(CADR(args)) && rwhich > 0
//        && isBasicClass(translateChar(STRING_ELT(rclass, rwhich)))) {
//      value = CADR(args);
//      if (NAMED(value))
//        SET_NAMED(value, 2);
//      value = R_getS4DataSlot(value, S4SXP);
//      if (value != R_NilValue)
//        SETCADR(args, value);
//    }
//
//
//
//    if(left == null && right == null) {
//      return null; /* no generic or group method so use default*/
//
//    }
//

//    if (!left.sxp.equals(right.sxp)) {
//      if (isFunction(lsxp) && isFunction(rsxp)) {
//        /* special-case some methods involving difftime */
//        const char *lname = CHAR(PRINTNAME(lmeth)), *rname =
//            CHAR(PRINTNAME(rmeth));
//        if (streql(rname, "Ops.difftime") && (streql(lname, "+.POSIXt")
//            || streql(lname, "-.POSIXt") || streql(lname, "+.Date")
//            || streql(lname, "-.Date")))
//          rsxp = R_NilValue;
//        else if (streql(lname, "Ops.difftime")
//            && (streql(rname, "+.POSIXt") || streql(rname, "+.Date")))
//          lsxp = R_NilValue;
//        else {
//          warning(_("Incompatible methods (\"%s\", \"%s\") for \"%s\""),
//              lname, rname, generic);
//          UNPROTECT(2);
//          return 0;
//        }
//      }
      /* if the right hand side is the one */
//      if (!(left.sxp instanceof Function)) { /* copy over the righthand stuff */
//        lclass = rclass;
//        left = right;
//      }
//    }

    /* we either have a group method or a class method */

//    PROTECT(newrho = allocSExp(ENVSXP));
//    Frame newrho = new HashFrame();
    String[] m = new String[nargs];
    PairList.Node s = (PairList.Node)args;
    for (i = 0; i < nargs; i++) {
      StringVector t = computeDataClasses(context, args.getElementAsSEXP(i));

//      t = IS_S4_OBJECT(CAR(s)) ? R_data_class2(CAR(s)) : getAttrib(CAR(s),
//          R_ClassSymbol);

      boolean set = false;
      for (j = 0; j < t.length(); j++) {
        if ( t.getElementAsString(j).equals(left.className )) {
          m[i] = left.method.getPrintName();
          set = true;
          break;
        }
      }
      if (!set) {
        m[i] = "";
      }
    }
    left.withMethodVector(m);

//    newrho.setVariable(Symbol.get(".Method"), new StringArrayVector(m));
//    newrho.setVariable(Symbol.get(".Generic"), StringVector.valueOf(generic));
//    newrho.setVariable(Symbol.get(".Group"), left.gr);
//
//    StringArrayVector.Builder dotClass = StringVector.newBuilder();
//    for(j=left.which;j<lclass.length();++j) {
//      dotClass.add(lclass.getElementAsString(j));
//    }
//
//    newrho.setVariable(Symbol.get(".Class"), dotClass.build());
//    newrho.setVariable(Symbol.get(".GenericCallEnv"), rho);
//    newrho.setVariable(Symbol.get(".GenericDefEnv"), rho.getBaseEnvironment());
//
//    FunctionCall newCall = FunctionCall.newCall(left.meth, call.getArguments());
//
//    /* the arguments have been evaluated; since we are passing them */
//    /* out to a closure we need to wrap them in promises so that */
//    /* they get duplicated and things like missing/substitute work. */

    PairList promisedArgs = Calls.promiseArgs(call.getArguments(), context, rho);
    if (promisedArgs.length() != args.length()) {
      throw new EvalException("dispatch error in group dispatch");
    }
    if(promisedArgs != Null.INSTANCE) {
      PairList.Node promised = (PairList.Node)promisedArgs;
      PairList.Node evaluated = (PairList.Node)args;

      while(true) {

        ((Promise)promised.getValue()).setResult(evaluated.getValue());
        /* ensure positional matching for operators */
        if (isOps) {
          promised.setTag(Null.INSTANCE);
        }
        if(!promised.hasNextNode()) {
          break;
        }
        promised = promised.getNextNode();
        evaluated = evaluated.getNextNode();
      }
    }
    return left.doApply(context, rho, promisedArgs);
//    return Calls.applyClosure((Closure) left.sxp, context, newCall, promisedArgs, rho, newrho);
  }

  /**
   * There are a few primitive functions (`[[` among them) which are proper builtins, but attempt
   * to dispatch on the class of their first argument before going ahead with the default implementation.
   *
   * @param context
   * @param rho
   * @param name the name of the function
   * @param args the original args from the FunctionCall
   * @param object evaluated first argument
   * @return
   */
  public static SEXP tryDispatchFromPrimitive(Context context, Environment rho, FunctionCall call,
      String name, SEXP object, PairList args) {

    if(call.getFunction() instanceof Symbol &&
        ((Symbol)call.getFunction()).getPrintName().endsWith(".default")) {
      return null;
    }

    GenericMethod method = Resolver
      .start(context, name, object)
      .withBaseDefinitionEnvironment()
      .withObjectArgument(object)
      .withGenericArgument(name)
      .findNext();

    if(method == null) {
      return null;
    }

    return method.doApply(context, rho,
            reassembleAndEvaluateArgs(object, args, context, rho));
  }

  public static SEXP tryDispatchFromPrimitive(Context context, Environment rho, FunctionCall call,
      String name, String[] argumentNames, SEXP[] arguments) {

    if(call.getFunction() instanceof Symbol &&
        ((Symbol)call.getFunction()).getPrintName().endsWith(".default")) {
      return null;
    }

    Vector classVector = (Vector)arguments[0].getAttribute(Symbols.CLASS);
    if(classVector.length() == 0) {
      return null;
    }

    DispatchChain chain = DispatchChain.newChain(context, rho, name, classVector);
    if(chain == null) {
      return null;
    }

    PairList.Builder newArgsBuilder = new PairList.Builder();
    for(int i=0;i!=arguments.length;++i) {
      newArgsBuilder.add(argumentNames[i], arguments[i]);
    }
    PairList newArgs = newArgsBuilder.build();

    FunctionCall newCall = new FunctionCall(chain.getMethodSymbol(), newArgs);

    ClosureDispatcher dispatcher = new ClosureDispatcher(context, rho, newCall);
    return dispatcher.apply(chain, newArgs);
  }

  static PairList reassembleAndEvaluateArgs(SEXP object, PairList args, Context context, Environment rho) {
    PairList.Builder newArgs = new PairList.Builder();
    PairList.Node firstArg = (PairList.Node)args;
    newArgs.add(firstArg.getRawTag(), object);

    args = firstArg.getNext();

    for(PairList.Node node : args.nodes()) {
      newArgs.add(node.getRawTag(), context.evaluate( node.getValue(), rho));
    }

    return newArgs.build();
  }

  public static SEXP tryDispatchGroupFromPrimitive(Context context, Environment rho, FunctionCall call,
      String group, String name, SEXP s0) {

    PairList newArgs = new PairList.Node(s0, Null.INSTANCE);

    return dispatchGroup(group, call, name, newArgs, context, rho);
  }

  public static SEXP tryDispatchGroupFromPrimitive(Context context, Environment rho, FunctionCall call,
      String group, String name, SEXP s0, SEXP s1) {

    PairList newArgs = new PairList.Node(s0, new PairList.Node(s1, Null.INSTANCE));

    return dispatchGroup(group, call, name, newArgs, context, rho);
  }

  public static SEXP tryDispatchSummaryFromPrimitive(Context context, Environment rho, FunctionCall call,
      String name, ListVector evaluatedArguments, boolean naRm) {

    // REpackage the evaluated arguments.
    // this is ghastly but i don't think it will
    // get better until Calls is refactored

    PairList.Builder newArgs = new PairList.Builder();
    int varArgIndex = 0;
    Symbol naRmName = Symbol.get("na.rm");
    for(PairList.Node node : call.getArguments().nodes()) {
      if(node.getRawTag() == naRmName) {
        newArgs.add(node.getTag(), new LogicalArrayVector(naRm));
      } else {
        newArgs.add(node.getRawTag(), evaluatedArguments.get(varArgIndex++));
      }
    }

    return dispatchGroup("Summary", call, name, newArgs.build(), context, rho);
  }

  /**
   * Helper class to deal with all the messy details of resolving
   * generic methods.
   *
   */
  private static class Resolver {

    /**
     * The environment of the call to the generic method.
     */
    private Environment callingEnvironment;

    /**
     * The environment in which the generic was defined. This will be the
     * enclosing environment of the function that calls UseMethod().
     */
    private Environment definitionEnvironment = Environment.EMPTY;

    private String group;

    /**
     * The name of the generic: for example "print" or "summary" or
     * "as.character".
     */
    private String genericMethodName;

    /**
     * The S3 classes associated with this object, each to be tried
     * in turn
     */
    private List<String> classes;

    private Context context;

    private SEXP object;

    /**
     * The context of the *previous* generic method called,
     * or null if this is the first method dispatched from
     * UseMethod().
     */
    private Context previousContext;

    private static Resolver start(Context context, String genericMethodName, SEXP object) {
      return start(context, null, genericMethodName, object);
    }

    private static Resolver start(Context context, String group, String genericMethodName, SEXP object) {
      Resolver resolver = new Resolver();
      resolver.callingEnvironment = context.getEnvironment();
      resolver.genericMethodName = genericMethodName;
      resolver.context = context;
      resolver.object = object;
      resolver.group = group;
      resolver.classes = Lists.newArrayList(computeDataClasses(context, object));
      return resolver;
    }

    /**
     * Resumes a dispatch chain (called by NextMethod)
     */
    public static Resolver resume(Context context) {
      Context parentContext = findParentContext(context);
      GenericMethod method = parentContext.getState(GenericMethod.class);

      Resolver resolver = new Resolver();
      resolver.context = context;
      resolver.previousContext = parentContext;
      resolver.callingEnvironment = context.getEnvironment();
      resolver.definitionEnvironment = method.resolver.definitionEnvironment;
      resolver.genericMethodName = method.resolver.genericMethodName;
      resolver.classes = method.nextClasses();
      resolver.group = method.resolver.group;
      resolver.object = method.resolver.object;
      return resolver;
    }

    public Resolver withObjectArgument(SEXP object) {
      if(object != Null.INSTANCE) {
        this.object = object;
      }
      return this;
    }

    /**
     * Sets the name of the generic method to resolve from
     * an argument provided to UseMethod().
     *
     * @param generic the 'generic' argument, giving the name of the method, like
     * 'as.character', or 'print'.
     */
    public Resolver withGenericArgument(SEXP generic) {
      if(generic != Null.INSTANCE) {
        this.genericMethodName = generic.asString();
      }
      return this;
    }

    /**
     * Sets the name of the generic method to resolve from
     * an argument provided to UseMethod().
     *
     * @param genericName the 'generic' argument, giving the name of the method, like
     * 'as.character', or 'print'.
     */
    public Resolver withGenericArgument(String genericName) {
      this.genericMethodName = genericName;
      return this;
    }

    public Resolver withDefinitionEnvironment(Environment rho) {
      this.definitionEnvironment = rho;
      return this;
    }

    public Resolver withBaseDefinitionEnvironment() {
      this.definitionEnvironment = context.getEnvironment().getBaseEnvironment();
      return this;
    }

    private static Context findParentContext(Context context) {
      for( ; context != null; context = context.getParent() ) {
        if(context.getState(GenericMethod.class) != null) {
          return context;
        }
      }
      throw new EvalException("NextMethod called out of context");
    }

    public GenericMethod next() {

      GenericMethod next = findNextOrDefault();

      if(next == null) {
        throw new EvalException("no applicable method for '%s' applied to an object of class \"%s\"",
          genericMethodName, classes.toString());
      }

      return next;
    }

    private GenericMethod findNextOrDefault() {
      GenericMethod next = findNext();

      if(next != null) {
        return next;
      } else {

        Symbol defaultMethod = Symbol.get(genericMethodName + ".default");
        SEXP function = callingEnvironment.findFunction(context, defaultMethod);
        if(function != null) {
          return new GenericMethod(this, defaultMethod, null, (Function) function);
        }

        // as a last step, we call BACK into the primitive
        // to get the default implementation  - ~ YECK ~
        PrimitiveFunction primitive = Primitives.getBuiltin(genericMethodName);
        if(primitive != null) {
          return new GenericMethod(this, defaultMethod, null, primitive);
        }

        return null;
      }
    }

    public GenericMethod findNext() {
      Environment methodTable = getMethodTable();
      GenericMethod method = null;

      for(String className : classes) {

        method = findNext(methodTable, genericMethodName, className);
        if(method != null) {
          return method;
        }
        if(group != null) {
          method = findNext(methodTable, group, className);
          if(method != null) {
            return method;
          }
        }
      }
      return null;
    }

    private GenericMethod findNext(Environment methodTable, String name, String className) {
      Symbol method = Symbol.get(name + "." + className);
      SEXP function = callingEnvironment.findFunction(context, method);
      if(function != null) {
        return new GenericMethod(this, method, className, (Function) function);

      } else if(methodTable != null && methodTable.hasVariable(method)) {
        return new GenericMethod(this, method, className, (Function) methodTable.getVariable(method).force(context));

      } else {
        return null;
      }
    }

    private Environment getMethodTable() {
      SEXP table = definitionEnvironment.getVariable(METHODS_TABLE).force(context);
      if(table instanceof Environment) {
        return (Environment) table;
      } else if(table == Symbol.UNBOUND_VALUE) {
        return null;
      } else {
        throw new EvalException("Unexpected value for .__S3MethodsTable__. in " + definitionEnvironment.getName());
      }
    }
  }

  public static class GenericMethod {
    private Resolver resolver;

    /**
     * The name of the selected function
     */
    private Symbol method;
    private Function function;
    private String className;

    /**
     * The vector stored in .Method
     *
     * <p>Normally it is just a single string containing the
     * name of the selected method, but for Ops group members,
     * it a two element string vector of the form
     *
     * [ "Ops.factor", ""]
     * [ "", "Ops.factor"] or
     * [ "Ops.factor", "Ops.factor"]
     *
     * depending on which (or both) of the operands belong to
     * the selected class.
     *
     */
    private StringVector methodVector;

    public GenericMethod(Resolver resolver, Symbol method, String className, Function function) {
      assert function != null;
      this.resolver = resolver;
      this.method = method;
      this.methodVector = new StringArrayVector(method.getPrintName());
      this.className = className;
      this.function = function;
    }

    public SEXP apply(Context callContext, Environment callEnvironment) {
      PairList rePromisedArgs = Calls.promiseArgs(callContext.getArguments(), callContext, callEnvironment);
      return doApply(callContext, callEnvironment, rePromisedArgs);
    }

    public SEXP applyNext(Context context, Environment environment) {
      return doApply(context, environment, nextArguments(context, environment));
    }

    public SEXP doApply(Context callContext, Environment callEnvironment, PairList args) {
      FunctionCall newCall = new FunctionCall(method,args);

      callContext.setState(GenericMethod.class, this);

      if(function instanceof Closure) {
        return Calls.applyClosure((Closure) function, callContext, callEnvironment,  newCall,
                args, callEnvironment, persistChain());
      } else {
        // primitive
        return function.apply(callContext, callEnvironment, newCall, args);
      }
    }

    public GenericMethod withMethodVector(String[] methodNames) {
      this.methodVector = new StringArrayVector(methodNames);
      return this;
    }

    public PairList nextArguments(Context callContext, Environment callEnvironment) {

      /*
       * Get the arguments to the function that called NextMethod(),
       * no arguments are really passed to NextMethod() at all.
       *
       * Note that we have to do a bit of climbing here-- it can be that previous
       * method looked like:
       *
       * `[.simple.list <- function(x, i, ...) structure(NextMethod('['], class=class(x))
       *
       * In this case, NextMethod is passed a promise to the closure 'structure',
       * and so our parent context is NOT the function context of `[.simple.list`
       * but that of `structure`.
       *
       */
      Context parentContext = callContext.getParent();
      while(parentContext.getParent() != resolver.previousContext) {
        parentContext = parentContext.getParent();
      }
      PairList actuals = parentContext.getArguments();
      Closure closure = parentContext.getClosure();

      /* get formals and actuals; attach the names of the formals to
         the actuals, expanding any ... that occurs */
      PairList formals = closure.getFormals();
      actuals = Calls.matchArguments(formals, actuals);

      actuals = expandDotDotDot(actuals);

      // strip out arguments with missing values. These named arguments may not
      // be defined in calls further down the chain and we don't want to "generate"
      // new arguments
      PairList.Builder noMissing = new PairList.Builder();
      for(PairList.Node node : actuals.nodes()) {
        if(node.getValue() != Symbol.MISSING_ARG) {
          noMissing.add(node.getRawTag(), node.getValue());
        }
      }
      actuals = noMissing.build();

//    /* we can't duplicate because it would force the promises */
//    /* so we do our own duplication of the promargs */
//
      Environment previousEnv = parentContext.getEnvironment();

      PairList.Builder updatedArgs = new PairList.Builder();
      for(PairList.Node actual : actuals.nodes()) {
        SEXP temp;
        if(actual.hasTag()) {
          // an argument may not have a tag even at this point if was
          // part of a ... expansion
          temp = previousEnv.findVariable(actual.getTag());
        } else {
          temp = Symbol.UNBOUND_VALUE;
        }
        if(temp != Symbol.UNBOUND_VALUE &&
                !isDefaultArgValue(temp) &&
                temp != Symbol.MISSING_ARG) {
          updatedArgs.add(actual.getRawTag(), Promise.repromise(previousEnv, temp));
        } else {
          updatedArgs.add(actual.getRawTag(), actual.getValue());
        }
      }
      return updatedArgs.build();
    }

    private Frame persistChain() {
      HashFrame frame = new HashFrame();
      frame.setVariable(Symbol.get(".Class"), new StringArrayVector(resolver.classes));
      frame.setVariable(Symbol.get(".Method"), methodVector);
      frame.setVariable(Symbol.get(".Generic"), StringVector.valueOf(resolver.genericMethodName));
      frame.setVariable(Symbol.get(".GenericCallEnv"), resolver.callingEnvironment);
      frame.setVariable(Symbol.get(".GenericDefEnv"), resolver.definitionEnvironment);
      return frame;
    }

    /**
     *
     * @return remaining classes to be  tried after this method
     */
    public List<String> nextClasses() {
      if(className == null) {
        return Collections.emptyList();
      }
      int myIndex = resolver.classes.indexOf(className);
      return resolver.classes.subList(myIndex+1, resolver.classes.size());
    }

  }

  public static class FindResult {
    SEXP sxp;
    SEXP gr;
    Symbol meth;
    int which;
    String buf;
  }
}


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""
import sys
from subprocess import *
from resource_management import *

def spark_hs(action):
  if action == "config":
   import params
   configurations = params.config['configurations']['spark']
   File(format(params.spark_conf_dir+"/spark-defaults.conf"),
       content=Template("spark_defaults.j2",configurations=configurations),
       owner=params.spark_user,
       group=params.spark_group
    )

   File(format(params.spark_conf_dir+"/spark-env.sh"),
       content=Template("spark-env.j2",configurations=configurations),
       owner=params.spark_user,
       group=params.spark_group
       )

  if action == "install":
    Logger.info("Installing Spark History Server")

  if action == "start" or action == "stop" or action == "status":
    cmd=Popen(['service','spark-history-server',action],stdout=PIPE,stderr=PIPE)
    out,err=cmd.communicate()

    if action == "start" or action == "stop":
      Logger.info("Spark History Server: "+str(action))
      Logger.info(out)
      Logger.info(err)
    if action == "status":
      from functions import check_rc
      rc=cmd.returncode
      Logger.info("Spark History Server %s: %s" % (action, cmd.returncode == 0))

      check_rc(rc,stdout=out,stderr=err)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
    <title>Toast组件</title>
    <link rel="stylesheet" href="/assets/blend2/dist/cmu.css">
    <link rel="stylesheet" href="/assets/blend2/css/samples.css">

            

            Toast组件

    <button class="blend-button blend-button-primary" onclick="triggerToast()">Toast提示</button>


text:
from pyftpdlib.ftpserver import AbstractedFS

from JumpScale import j
import os

# --- filesystem

class AbstractedFS(object):

    """A class used to interact with the file system, providing a
    cross-platform interface compatible with both Windows and
    UNIX style filesystems where all paths use "/" separator.

    AbstractedFS distinguishes between "real" filesystem paths and
    "virtual" ftp paths emulating a UNIX chroot jail where the user
    can not escape its home directory (example: real "/home/user"
    path will be seen as "/" by the client)

    It also provides some utility methods and wraps around all os.*
    calls involving operations against the filesystem like creating
    files or removing directories.
    """

    def __init__(self, root, cmd_channel):
        """
         - (str) root: the user "real" home directory (e.g. '/home/user')
         - (instance) cmd_channel: the FTPHandler class instance
        """
        # Set initial current working directory.
        # By default initial cwd is set to "/" to emulate a chroot jail.
        # If a different behavior is desired (e.g. initial cwd = root,
        # to reflect the real filesystem) users overriding this class
        # are responsible to set _cwd attribute as necessary.
        self._cwd = '/'
        self._root = root
        self.cmd_channel = cmd_channel
        self.handler = None

    @property
    def root(self):
        """The user home directory."""
        return self._root

    @property
    def cwd(self):
        """The user current working directory."""
        return self._cwd

    @root.setter
    def root(self, path):
        self._root = path

    @cwd.setter
    def cwd(self, path):
        self._cwd = path

    # --- Pathname / conversion utilities

    def ftpnorm(self, ftppath):
        """Normalize a "virtual" ftp pathname (tipically the raw string
        coming from client) depending on the current working directory.

        Example (having "/foo" as current working directory):
        >>> ftpnorm('bar')
        '/foo/bar'

        Note: directory separators are system independent ("/").
        Pathname returned is always absolutized.
        """
        if os.path.isabs(ftppath):
            p = os.path.normpath(ftppath)
        else:
            p = os.path.normpath(os.path.join(self.cwd, ftppath))
        # normalize string in a standard web-path notation having '/'
        # as separator.
        p = p.replace("\\", "/")
        # os.path.normpath supports UNC paths (e.g. "//a/b/c") but we
        # don't need them.  In case we get an UNC path we collapse
        # redundant separators appearing at the beginning of the string
        while p[:2] == '//':
            p = p[1:]
        # Anti path traversal: don't trust user input, in the event
        # that self.cwd is not absolute, return "/" as a safety measure.
        # This is for extra protection, maybe not really necessary.
        if not os.path.isabs(p):
            p = "/"
        return p

    def ftp2fs(self, ftppath):
        """Translate a "virtual" ftp pathname (tipically the raw string
        coming from client) into equivalent absolute "real" filesystem
        pathname.

        Example (having "/home/user" as root directory):
        >>> ftp2fs("foo")
        '/home/user/foo'

        Note: directory separators are system dependent.
        """
        # as far as I know, it should always be path traversal safe...
        if os.path.normpath(self.root) == os.sep:
            return os.path.realpath(os.path.normpath(self.ftpnorm(ftppath)))
        else:
            p = self.ftpnorm(ftppath)[1:]
            return os.path.realpath(os.path.normpath(os.path.join(self.root, p)))

    def fs2ftp(self, fspath):
        """Translate a "real" filesystem pathname into equivalent
        absolute "virtual" ftp pathname depending on the user's
        root directory.

        Example (having "/home/user" as root directory):
        >>> fs2ftp("/home/user/foo")
        '/foo'

        As for ftpnorm, directory separators are system independent
        ("/") and pathname returned is always absolutized.

        On invalid pathnames escaping from user's root directory
        (e.g. "/home" when root is "/home/user") always return "/".
        """
        if os.path.isabs(fspath):
            p = os.path.normpath(fspath)
        else:
            p = os.path.normpath(os.path.join(self.root, fspath))
        if not self.validpath(p):
            return '/'
        p = p.replace(os.sep, "/")
        p = p[len(self.root):]
        if not p.startswith('/'):
            p = '/' + p
        return p

    def validpath(self, path):
        """Check whether the path belongs to user's home directory.
        Expected argument is a "real" filesystem pathname.

        If path is a symbolic link it is resolved to check its real
        destination.

        Pathnames escaping from user's root directory are considered
        not valid.
        """
        return True
        root = self.realpath(self.root)
        path = self.realpath(path)
        if not root.endswith(os.sep):
            root = root + os.sep
        if not path.endswith(os.sep):
            path = path + os.sep
        if path[0:len(root)] == root:
            return True

        return False

    # --- Wrapper methods around open() and tempfile.mkstemp

    def open(self, filename, mode):
        """Open a file returning its handler."""
        return open(filename, mode)

    def mkstemp(self, suffix='', prefix='', dir=None, mode='wb'):
        """A wrap around tempfile.mkstemp creating a file with a unique
        name.  Unlike mkstemp it returns an object with a file-like
        interface.
        """
        class FileWrapper:

            def __init__(self, fd, name):
                self.file = fd
                self.name = name

            def __getattr__(self, attr):
                return getattr(self.file, attr)

        text = not 'b' in mode
        # max number of tries to find out a unique file name
        tempfile.TMP_MAX = 50
        fd, name = tempfile.mkstemp(suffix, prefix, dir, text=text)
        file = os.fdopen(fd, mode)
        return FileWrapper(file, name)

    # --- Wrapper methods around os.* calls

    def chdir(self, ftppath):
        """Change the current directory."""
        # temporarily join the specified directory to see if we have
        # permissions to do so
        path = self.ftp2fs(ftppath)
        print "chdir for %s : %s" % (ftppath, path)
        #basedir = os.getcwd()
        try:
            os.chdir(path)
        except OSError:
            raise
        else:
            self._cwd = ftppath

    def mkdir(self, ftppath):
        """Create the specified directory."""
        ftppath = self.ftpnorm(ftppath)
        path = self.ftp2fs(ftppath)
        j.system.fs.createDir(path)

    def listdir(self, path):
        """List the content of a directory."""
        path1 = self.ftp2fs(path)
        # print "listdir:%s:%s" %(path,path1)
        return os.listdir(path1)

    def rmdir(self, path):
        """Remove the specified directory."""
        path = self.ftp2fs(path)
        os.rmdir(path)

    def remove(self, path):
        """Remove the specified file."""
        path = self.ftpnorm(path)
        path = self.ftp2fs(path)
        os.remove(path)

    def rename(self, src, dst):
        """Rename the specified src file to the dst filename."""
        src = self.ftp2fs(src)
        dst = self.ftp2fs(dst)
        os.rename(src, dst)

    def chmod(self, path, mode):
        """Change file/directory mode."""
        raise NotImplementedError
        path = self.ftp2fs(path)
        if not hasattr(os, 'chmod'):
            raise NotImplementedError
        os.chmod(path, mode)

    def stat(self, path):
        """Perform a stat() system call on the given path."""
        return os.stat(path)

    def lstat(self, path):
        """Like stat but does not follow symbolic links."""
        path = self.ftp2fs(path)
        return os.lstat(path)

    if not hasattr(os, 'lstat'):
        lstat = stat

    # --- Wrapper methods around os.path.* calls

    def isfile(self, path):
        """Return True if path is a file."""
        path = self.ftp2fs(path)
        return os.path.isfile(path)

    def islink(self, path):
        """Return True if path is a symbolic link."""
        path = self.ftp2fs(path)
        return os.path.islink(path)

    def isdir(self, path):
        """Return True if path is a directory."""
        path = self.ftp2fs(path)
        return os.path.isdir(path)

    def getsize(self, path):
        """Return the size of the specified file in bytes."""
        path = self.ftp2fs(path)
        return os.path.getsize(path)

    def getmtime(self, path):
        """Return the last modified time as a number of seconds since
        the epoch."""
        path = self.ftp2fs(path)
        return os.path.getmtime(path)

    # def realpath(self, path):
        #"""Return the canonical version of path eliminating any
        # symbolic links encountered in the path (if they are
        # supported by the operating system).
        #"""
        # return os.path.realpath(path)

    def lexists(self, path):
        """Return True if path refers to an existing path, including
        a broken or circular symbolic link.
        """
        path = self.ftp2fs(path)
        return os.path.lexists(path)

    def get_user_by_uid(self, uid):
        """Return the username associated with user id.
        If this can't be determined return raw uid instead.
        On Windows just return "owner".
        """
        if pwd is not None:
            try:
                return pwd.getpwuid(uid).pw_name
            except KeyError:
                return uid
        else:
            return "owner"

    def get_group_by_gid(self, gid):
        """Return the groupname associated with group id.
        If this can't be determined return raw gid instead.
        On Windows just return "group".
        """
        if grp is not None:
            try:
                return grp.getgrgid(gid).gr_name
            except KeyError:
                return gid
        else:
            return "group"

    if hasattr(os, 'readlink'):
        def readlink(self, path):
            """Return a string representing the path to which a
            symbolic link points.
            """
            return os.readlink(path)

    # --- Listing utilities

    def get_list_dir(self, path):
        """"Return an iterator object that yields a directory listing
        in a form suitable for LIST command.
        """
        if self.isdir(path):
            listing = sorted(self.listdir(path))
            return self.format_list(path, listing)
        # if path is a file or a symlink we return information about it
        else:
            basedir, filename = os.path.split(path)
            self.lstat(path)  # raise exc in case of problems
            return self.format_list(basedir, [filename])

    def format_list(self, basedir, listing, ignore_err=True):
        """Return an iterator object that yields the entries of given
        directory emulating the "/bin/ls -lA" UNIX command output.

         - (str) basedir: the absolute dirname.
         - (list) listing: the names of the entries in basedir
         - (bool) ignore_err: when False raise exception if os.lstat()
         call fails.

        On platforms which do not support the pwd and grp modules (such
        as Windows), ownership is printed as "owner" and "group" as a
        default, and number of hard links is always "1". On UNIX
        systems, the actual owner, group, and number of links are
        printed.

        This is how output appears to client:

        -rw-rw-rw-   1 owner   group    7045120 Sep 02  3:47 music.mp3
        drwxrwxrwx   1 owner   group          0 Aug 31 18:50 e-books
        -rw-rw-rw-   1 owner   group        380 Sep 02  3:40 module.py
        """
        if self.cmd_channel.use_gmt_times:
            timefunc = time.gmtime
        else:
            timefunc = time.localtime
        now = time.time()
        for basename in listing:
            file = os.path.join(basedir, basename)
            try:
                st = self.lstat(file)
            except OSError:
                if ignore_err:
                    continue
                raise
            perms = _filemode(st.st_mode)  # permissions
            nlinks = st.st_nlink  # number of links to inode
            if not nlinks:  # non-posix system, let's use a bogus value
                nlinks = 1
            size = st.st_size  # file size
            uname = self.get_user_by_uid(st.st_uid)
            gname = self.get_group_by_gid(st.st_gid)
            mtime = timefunc(st.st_mtime)
            # if modificaton time > 6 months shows "month year"
            # else "month hh:mm";  this matches proftpd format, see:
            # http://code.google.com/p/pyftpdlib/issues/detail?id=187
            if (now - st.st_mtime) > 180 * 24 * 60 * 60:
                fmtstr = "%d  %Y"
            else:
                fmtstr = "%d %H:%M"
            try:
                mtimestr = "%s %s" % (_months_map[mtime.tm_mon],
                                      time.strftime(fmtstr, mtime))
            except ValueError:
                # It could be raised if last mtime happens to be too
                # old (prior to year 1900) in which case we return
                # the current time as last mtime.
                mtime = timefunc()
                mtimestr = "%s %s" % (_months_map[mtime.tm_mon],
                                      time.strftime("%d %H:%M", mtime))

            # if the file is a symlink, resolve it, e.g. "symlink -> realfile"
            if stat.S_ISLNK(st.st_mode) and hasattr(self, 'readlink'):
                basename = basename + " -> " + self.readlink(file)

            # formatting is matched with proftpd ls output
            yield "%s %3s %-8s %-8s %8s %s %s\r\n" % (perms, nlinks, uname, gname,
                                                      size, mtimestr, basename)

    def format_mlsx(self, basedir, listing, perms, facts, ignore_err=False):
        """Return an iterator object that yields the entries of a given
        directory or of a single file in a form suitable with MLSD and
        MLST commands.

        Every entry includes a list of "facts" referring the listed
        element.  See RFC-3659, chapter 7, to see what every single
        fact stands for.

         - (str) basedir: the absolute dirname.
         - (list) listing: the names of the entries in basedir
         - (str) perms: the string referencing the user permissions.
         - (str) facts: the list of "facts" to be returned.
         - (bool) ignore_err: when False raise exception if os.stat()
         call fails.

        Note that "facts" returned may change depending on the platform
        and on what user specified by using the OPTS command.

        This is how output could appear to the client issuing
        a MLSD request:

        type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3
        type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks
        type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py
        """
        basedir = self.ftp2fs(basedir)
        if self.cmd_channel.use_gmt_times:
            timefunc = time.gmtime
        else:
            timefunc = time.localtime
        permdir = ''.join([x for x in perms if x not in 'arw'])
        permfile = ''.join([x for x in perms if x not in 'celmp'])
        if ('w' in perms) or ('a' in perms) or ('f' in perms):
            permdir += 'c'
        if 'd' in perms:
            permdir += 'p'

        for basename in listing:
            file = os.path.join(basedir, basename)
            retfacts = dict()
            # in order to properly implement 'unique' fact (RFC-3659,
            # chapter 7.5.2) we are supposed to follow symlinks, hence
            # use os.stat() instead of os.lstat()
            try:
                st = self.stat(file)
            except OSError:
                if ignore_err:
                    print "error for %s, cannot list (stat)" % file
                    continue
                raise
            # type + perm
            if stat.S_ISDIR(st.st_mode):
                if 'type' in facts:
                    if basename == '.':
                        retfacts['type'] = 'cdir'
                    elif basename == '..':
                        retfacts['type'] = 'pdir'
                    else:
                        retfacts['type'] = 'dir'
                if 'perm' in facts:
                    retfacts['perm'] = permdir
            else:
                if 'type' in facts:
                    retfacts['type'] = 'file'
                if 'perm' in facts:
                    retfacts['perm'] = permfile
            if 'size' in facts:
                retfacts['size'] = st.st_size  # file size
            # last modification time
            if 'modify' in facts:
                try:
                    retfacts['modify'] = time.strftime("%Y%m%d%H%M%S",
                                                       timefunc(st.st_mtime))
                # it could be raised if last mtime happens to be too old
                # (prior to year 1900)
                except ValueError:
                    pass
            if 'create' in facts:
                # on Windows we can provide also the creation time
                try:
                    retfacts['create'] = time.strftime("%Y%m%d%H%M%S",
                                                       timefunc(st.st_ctime))
                except ValueError:
                    pass
            # UNIX only
            if 'unix.mode' in facts:
                retfacts['unix.mode'] = oct(st.st_mode & 0o777)
            if 'unix.uid' in facts:
                retfacts['unix.uid'] = st.st_uid
            if 'unix.gid' in facts:
                retfacts['unix.gid'] = st.st_gid

            # We provide unique fact (see RFC-3659, chapter 7.5.2) on
            # posix platforms only; we get it by mixing st_dev and
            # st_ino values which should be enough for granting an
            # uniqueness for the file listed.
            # The same approach is used by pure-ftpd.
            # Implementors who want to provide unique fact on other
            # platforms should use some platform-specific method (e.g.
            # on Windows NTFS filesystems MTF records could be used).
            if 'unique' in facts:
                retfacts['unique'] = "%xg%x" % (st.st_dev, st.st_ino)

            # facts can be in any order but we sort them by name
            factstring = "".join(["%s=%s;" % (x, retfacts[x])
                                  for x in sorted(retfacts.keys())])
            yield "%s %s\r\n" % (factstring, basename)

class RootFilesystem(AbstractedFS):

    """
    is our virtual root
    """

    def __init__(self, root, cmd_channel):
        #_Base.__init__(self, root, cmd_channel)
        AbstractedFS.__init__(self, root, cmd_channel)
        # initial cwd was set to "/" to emulate a chroot jail
        self.cwd = "/"

    def validpath(self, path):
        return True

    def mkstemp(self, suffix='', prefix='', dir=None, mode='wb'):
        return None

    def listdir(self, path):
        return ["spaces", "buckets", "actors", "contentdirs", "stor"]

    def chdir(self, path):
        self._cwd = "/"

    def mkdir(self, path):
        j.system.fs.createDir(path)
        raise RuntimeError("not implemented")

    def rmdir(self, path):
        return

    def remove(self, path):
        return

    def rename(self, src, dst):
        return

    def chmod(self, path, mode):
        return

    def stat(self, path):
        return

    def lstat(self, path):
        return self.stat(path)

    def isfile(self, path):
        """Return True if path is a file."""
        return False

    def islink(self, path):
        """Return True if path is a symbolic link."""
        return False

    def isdir(self, path):
        """Return True if path is a directory."""
        return True

    def getsize(self, path):
        """Return the size of the specified file in bytes."""
        return 0

    def getmtime(self, path):
        """Return the last modified time as a number of seconds since
        the epoch."""
        return 0

    def format_list(self, basedir, listing, ignore_err=True):
        mtimestr = "Sep 02  3:40"
        for basename in listing:
            yield "%s %3s %-8s %-8s %8s %s %s\r\n" % ("elc", 0, "", "", 0, mtimestr, basename)

    def format_mlsx(self, basedir, listing, perms, facts, ignore_err=True):
        for dirname in listing:
            item = "type=dir;size=0;perm=el;modify=20071127230206; %s\r\n" % dirname
            # print item,
            yield item

    def open(self, filename, mode):
        return None

class RootFilesystemList(RootFilesystem):

    """
    basis for 1 level down eg spaces
    """

    def __init__(self, root, cmd_channel, list):
        AbstractedFS.__init__(self, root, cmd_channel)
        self.cwd = root
        self.list = list

    def listdir(self, path):
        print "list for rootfilesystemlist: %s" % self.cwd
        return self.list()

    def chdir(self, path):
        print "chdirrootfslist:%s" % path
        self._cwd = path
        #self._cwd = self.fs2ftp(path)

    def fs2ftp(self, path):
        p = j.system.fs.pathRemoveDirPart(path, self.cmd_channel.rootpath).replace("\\", "/")
        if len(p) != 0 and p[0] != "/":
            p = "/" + p
        # print "fs2ftp_list: %s -> %s" % (path,p)
        return p

    def ftp2fs(self, ftppath):
        return self.root

class BaseFilesystem(AbstractedFS):

    """
    is our virtual root
    """

    def __init__(self, root, cmd_channel, ftproot, cwd, readonly=False):
        #_Base.__init__(self, root, cmd_channel)
        AbstractedFS.__init__(self, root, cmd_channel)
        self.cwd = cwd
        self.cwdftp = ""
        self.ftproot = ftproot
        self.readonly = readonly

    # def chdir(self, path):
        # self._cwd=path

    def ftp2fs(self, ftppath):
        if ftppath.find(self.ftproot) == 0:
            ftppath = ftppath[len(self.ftproot):]
        result = j.system.fs.joinPaths(self.root, ftppath)
        return result

    def _ignorePath(self, item):
        # items=[]
        # for item in os.listdir(path):
        ext = j.system.fs.getFileExtension(item)
        if item.find(".quarantine") == 0 or item.find(".tmb") == 0:
            try:
                j.system.fs.remove(item)
            except:
                pass
            return True
        elif ext == "pyc":
            return True
        # else:
            # items.append(item)

    def listdir(self, path):
        """List the content of a directory."""
        path1 = self.ftp2fs(path)
        # print "listdir:%s:%s" %(path,path1)
        items = [item for item in os.listdir(path1) if not self._ignorePath(item)]
        return items

    def mkdir(self, path):
        pathr = self.ftp2fs(path)
        j.system.fs.createDir(pathr)

    def fs2ftp(self, fspath):
        p = j.system.fs.pathRemoveDirPart(fspath, self.root)
        if len(p) != 0 and p[0] != "/":
            p = "/" + p
        p = self.ftproot + p
        # print "fs2ftp: %s -> %s" % (fspath,p)
        return p

    def open(self, filename, mode):
        """Open a file returning its handler."""
        #@todo check on extension .redirect (file path:  $originalpath.$size.redirect) read from redirect where to go and repoint open
        # if self.readonly and "w" in mode:
            # return None

        return open(filename, mode)


text:
package jp.cafebabe.birthmarks.rules;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import org.junit.Test;

public class RuleTest {
    @Test
    public void testToString() {
        Rule rule = new Rule("prefix", "pattern");

        assertThat(rule.toString(), is("PREFIX,pattern"));
    }

    @Test
    public void testPrefixMatching() {
        Rule rule = new Rule("prefix", "pattern");

        assertThat(rule.match("pattern_ok"), is(true));
        assertThat(rule.match("not_prefix_pattern"), is(false));
    }

    @Test
    public void testSuffixMatching() {
        Rule rule = new Rule("suffix", "pattern");

        assertThat(rule.match("pattern_ok"), is(false));
        assertThat(rule.match("not_prefix_pattern"), is(true));
    }

    @Test
    public void testExactMatching() {
        Rule rule = new Rule("exact", "pattern");

        assertThat(rule.match("pattern"), is(true));
        assertThat(rule.match("not_prefix_pattern"), is(false));
    }

    @Test
    public void testRegexMatching() {
        Rule rule = new Rule("regex", "pat+ern");

        assertThat(rule.match("patttttern"), is(true));
        assertThat(rule.match("pattern_ng"), is(false));
    }
}


text:
<?php

namespace troiswa\BackBundle\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class passwordCheckerValidator extends ConstraintValidator
{

    // $constraint est un objet définit dans passwordChecker qui joue le
    // role d'un construct en qielque sorte
    // on peu donc récupérer les paramètres que l'on veux qui
    // ont étaient définit dedans ( message / regex / minimum )
    // ces valeur sont écrasées si l'on les redéfinit en annotation dans
    // l'entitée User.
    public function validate($value, Constraint $constraint)
    {

            if(strlen($value) < $constraint->minimum )
            {
                $this->context->addViolation($constraint->message);

            }elseif(preg_match($constraint->regex,$value) == false )
                   {
                       $this->context->addViolation($constraint->message);
                   }

    }
}

/*

    class StrongPasswordValidator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            if(strlen($value) < $constraint->min)
            {
                $this->context->buildViolation($constraint->messageMin)
                    ->setParameter('{{ limit }}', $constraint->min)
                    ->addViolation();
            }
            elseif($constraint->caractere && !preg_match("#[".$constraint->caractere."]#", $value))
            {
                $this->context->buildViolation($constraint->messageCaractere)
                    ->setParameter('{{ valid }}', $constraint->caractere)
                    ->addViolation();
            }

        }
    }

 */


text:
{-# LANGUAGE OverloadedStrings #-}

module ParionsFDJ.JSON
  ( getEvents
  ) where

import Data.Aeson (eitherDecode)
import Data.ByteString.Lazy (ByteString)
import qualified Network.HTTP.Simple as H
import ParionsFDJ.JSON.Event (Event)

getEvents :: IO (Either String [Event])
getEvents = eitherDecode <$> getJSON

getJSON :: IO ByteString
getJSON = H.getResponseBody <$> getResp
  where
    getResp =
      H.httpLBS "https://www.pointdevente.parionssport.fdj.fr/api/1n2/offre"


text:
/**
 * Users widget.  Sets up dropdowns, modals, etc for a table of users.
 */

/**
 * Set up the form in a modal after being successfully attached to the body.
 */
function attachUserForm() {
    $("body").on('renderSuccess.ufModal', function(data) {
        var modal = $(this).ufModal('getModal');
        var form = modal.find('.js-form');

        // Set up any widgets inside the modal
        form.find(".js-select2").select2({
            width: '100%'
        });

        // Set up the form for submission
        form.ufForm({
            validator: page.validators
        }).on("submitSuccess.ufForm", function() {
            // Reload page on success
            window.location.reload();
        });

        toggleSetPasswordMode(modal, 'link');

        // On submission, submit either the PUT request, or POST for a password reset, depending on the toggle state
        modal.find("input[name='change_password_mode']").click(function() {
            var changePasswordMode = $(this).val();
            toggleSetPasswordMode(modal, changePasswordMode);
        });
    });
}

/**
 * Enable/disable password fields when switch is toggled
 * Applies to 'creating' a user
 */
function toggleSetPasswordMode(el, changePasswordMode) {
    var form = el.find("form");
    if (changePasswordMode == 'link') {
        $(".controls-password").find("input[type='password']").prop('disabled', true);
        // Form submits password reset request

        var validator = form.validate();
        if (validator) {
            //Iterate through named elements inside of the form, and mark them as error free
            el.find("input[type='password']").each(function() {
                validator.successList.push(this); //mark as error free
            });
            validator.resetForm(); //remove error class on name elements and clear history
            validator.reset(); //remove all error and success data
        }
        el.find("input[type='password']").closest('.form-group')
            .removeClass('has-error has-success');
        el.find('.form-control-feedback').each(function() {
            $(this).remove();
        });
    } else {
        $(".controls-password").find("input[type='password']").prop('disabled', false);
    }
}

/**
 * Enable/disable password fields when switch is toggled
 * Applies to 'reseting' a users password
 */
function toggleChangePasswordMode(el, userName, changePasswordMode) {
    var form = el.find("form");
    if (changePasswordMode == 'link') {
        $(".controls-password").find("input[type='password']").prop('disabled', true);
        // Form submits password reset request
        form.attr({
            method: 'POST',
            action: site.uri.public + '/api/users/u/' + userName + '/password-reset'
        });

        var validator = form.validate();
        if (validator) {
            //Iterate through named elements inside of the form, and mark them as error free
            el.find("input[type='password']").each(function() {
                validator.successList.push(this); //mark as error free
            });
            validator.resetForm(); //remove error class on name elements and clear history
            validator.reset(); //remove all error and success data
        }
        el.find("input[type='password']").closest('.form-group')
            .removeClass('has-error has-success');
        el.find('.form-control-feedback').each(function() {
            $(this).remove();
        });
    } else {
        $(".controls-password").find("input[type='password']").prop('disabled', false);
        // Form submits direct password update
        form.attr({
            method: 'PUT',
            action: site.uri.public + '/api/users/u/' + userName + '/password'
        });
    }
}

/**
 * Update user field(s)
 */
function updateUser(userName, fieldName, fieldValue) {

    var data = {};
    data[fieldName] = fieldValue;
    data[site.csrf.keys.name] = site.csrf.name;
    data[site.csrf.keys.value] = site.csrf.value;

    var url = site.uri.public + '/api/users/u/' + userName + '/' + fieldName;
    var debugAjax = (typeof site !== "undefined") && site.debug.ajax;

    return $.ajax({
        type: "PUT",
        url: url,
        data: data,
        dataType: debugAjax ? 'html' : 'json',
        converters: {
            // Override jQuery's strict JSON parsing
            'text json': function(result) {
                try {
                    // First try to use native browser parsing
                    if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
                        return JSON.parse(result);
                    } else {
                        return $.parseJSON(result);
                    }
                } catch (e) {
                    // statements to handle any exceptions
                    console.log("Warning: Could not parse expected JSON response.");
                    return {};
                }
            }
        }
    }).fail(function(jqXHR) {
        // Error messages
        if (debugAjax && jqXHR.responseText) {
            document.write(jqXHR.responseText);
            document.close();
        } else {
            console.log("Error (" + jqXHR.status + "): " + jqXHR.responseText);

            // Display errors on failure
            // TODO: ufAlerts widget should have a 'destroy' method
            if (!$("#alerts-page").data('ufAlerts')) {
                $("#alerts-page").ufAlerts();
            } else {
                $("#alerts-page").ufAlerts('clear');
            }

            $("#alerts-page").ufAlerts('fetch').ufAlerts('render');
        }

        return jqXHR;
    }).done(function(response) {
        window.location.reload();
    });
}

/**
 * Link user action buttons, for example in a table or on a specific user's page.
 * @param {module:jQuery} el jQuery wrapped element to target.
 * @param {{delete_redirect: string}} options Options used to modify behaviour of button actions.
 */
function bindUserButtons(el, options) {
    if (!options) options = {};

    /**
     * Buttons that launch a modal dialog
     */
    // Edit general user details button
    el.find('.js-user-edit').click(function(e) {
        e.preventDefault();

        $("body").ufModal({
            sourceUrl: site.uri.public + "/modals/users/edit",
            ajaxParams: {
                user_name: $(this).data('user_name')
            },
            msgTarget: $("#alerts-page")
        });

        attachUserForm();
    });

    // Manage user roles button
    el.find('.js-user-roles').click(function(e) {
        e.preventDefault();

        var userName = $(this).data('user_name');
        $("body").ufModal({
            sourceUrl: site.uri.public + "/modals/users/roles",
            ajaxParams: {
                user_name: userName
            },
            msgTarget: $("#alerts-page")
        });

        $("body").on('renderSuccess.ufModal', function(data) {
            var modal = $(this).ufModal('getModal');
            var form = modal.find('.js-form');

            // Set up collection widget
            var roleWidget = modal.find('.js-form-roles');
            roleWidget.ufCollection({
                dropdown: {
                    ajax: {
                        url: site.uri.public + '/api/roles'
                    },
                    placeholder: "Select a role"
                },
                dropdownTemplate: modal.find('#user-roles-select-option').html(),
                rowTemplate: modal.find('#user-roles-row').html()
            });

            // Get current roles and add to widget
            $.getJSON(site.uri.public + '/api/users/u/' + userName + '/roles')
                .done(function(data) {
                    $.each(data.rows, function(idx, role) {
                        role.text = role.name;
                        roleWidget.ufCollection('addRow', role);
                    });
                });

            // Set up form for submission
            form.ufForm()
                .on("submitSuccess.ufForm", function() {
                    // Reload page on success
                    window.location.reload();
                });
        });
    });

    // Change user password button
    el.find('.js-user-password').click(function(e) {
        e.preventDefault();

        var userName = $(this).data('user_name');
        $("body").ufModal({
            sourceUrl: site.uri.public + "/modals/users/password",
            ajaxParams: {
                user_name: userName
            },
            msgTarget: $("#alerts-page")
        });

        $("body").on('renderSuccess.ufModal', function() {
            var modal = $(this).ufModal('getModal');
            var form = modal.find('.js-form');

            // Set up form for submission
            form.ufForm({
                validator: page.validators
            }).on("submitSuccess.ufForm", function() {
                // Reload page on success
                window.location.reload();
            });

            toggleChangePasswordMode(modal, userName, 'link');

            // On submission, submit either the PUT request, or POST for a password reset, depending on the toggle state
            modal.find("input[name='change_password_mode']").click(function(e) {

                var changePasswordMode = $(this).val();
                toggleChangePasswordMode(modal, userName, changePasswordMode);
            });
        });
    });

    // Delete user button
    el.find('.js-user-delete').click(function(e) {
        e.preventDefault();

        $("body").ufModal({
            sourceUrl: site.uri.public + "/modals/users/confirm-delete",
            ajaxParams: {
                user_name: $(this).data('user_name')
            },
            msgTarget: $("#alerts-page")
        });

        $("body").on('renderSuccess.ufModal', function() {
            var modal = $(this).ufModal('getModal');
            var form = modal.find('.js-form');

            form.ufForm()
                .on("submitSuccess.ufForm", function() {
                    // Navigate or reload page on success
                    if (options.delete_redirect) window.location.href = options.delete_redirect;
                    else window.location.reload();
                });
        });
    });

    /**
     * Direct action buttons
     */
    el.find('.js-user-activate').click(function(e) {
        e.preventDefault();

        var btn = $(this);
        updateUser(btn.data('user_name'), 'flag_verified', '1');
    });

    el.find('.js-user-enable').click(function() {
        var btn = $(this);
        updateUser(btn.data('user_name'), 'flag_enabled', '1');
    });

    el.find('.js-user-disable').click(function() {
        var btn = $(this);
        updateUser(btn.data('user_name'), 'flag_enabled', '0');
    });
}

function bindUserCreationButton(el) {
    // Link create button
    el.find('.js-user-create').click(function(e) {
        e.preventDefault();

        $("body").ufModal({
            sourceUrl: site.uri.public + "/modals/users/create",
            msgTarget: $("#alerts-page")
        });

        attachUserForm();
    });
};


text:
#ifndef __LINUX_GENERIC_NETLINK_H
#define __LINUX_GENERIC_NETLINK_H

#include <linux/netlink.h>

#define GENL_NAMSIZ	16	/* length of family name */

#define NLMSG_MIN_TYPE 0x10

#define GENL_MIN_ID	NLMSG_MIN_TYPE
#define GENL_MAX_ID	1023

struct genlmsghdr {
	__u8	cmd;
	__u8	version;
	__u16	reserved;
};

#define GENL_HDRLEN	NLMSG_ALIGN(sizeof(struct genlmsghdr))

/*
 * List of reserved static generic netlink identifiers:
 */
#define GENL_ID_GENERATE	0
#define GENL_ID_CTRL		NLMSG_MIN_TYPE

/**************************************************************************
 * Controller
 **************************************************************************/

enum {
	CTRL_CMD_UNSPEC,
	CTRL_CMD_NEWFAMILY,
	CTRL_CMD_DELFAMILY,
	CTRL_CMD_GETFAMILY,
	CTRL_CMD_NEWOPS,
	CTRL_CMD_DELOPS,
	CTRL_CMD_GETOPS,
	__CTRL_CMD_MAX,
};

#define CTRL_CMD_MAX (__CTRL_CMD_MAX - 1)

enum {
	CTRL_ATTR_UNSPEC,
	CTRL_ATTR_FAMILY_ID,
	CTRL_ATTR_FAMILY_NAME,
	__CTRL_ATTR_MAX,
};

#define CTRL_ATTR_MAX (__CTRL_ATTR_MAX - 1)

#endif	/* __LINUX_GENERIC_NETLINK_H */


text:
<idea-plugin>
  <id>org.jetbrains.plugins.textmate</id>
  <name>TextMate bundles</name>
  <category>Other Tools</category>
  <vendor>JetBrains</vendor>

  <description><![CDATA[
      Supports syntax highlighting for arbitrary file types, controlled by TextMate bundles
      ]]></description>

  <depends>com.intellij.modules.lang</depends>

  <extensions defaultExtensionNs="com.intellij">
    <registryKey key="textmate.line.highlighting.limit" defaultValue="20000"
                 description="The maximum length of the line to be highlighted by TextMate lexer."/>

    <fileType name="textmate" implementationClass="org.jetbrains.plugins.textmate.language.TextMateFileType" language="textmate" fieldName="INSTANCE"/>
    <applicationService id="textmateSettings"
                        serviceImplementation="org.jetbrains.plugins.textmate.configuration.TextMateSettings"/>
    <applicationService id="textmateService" serviceInterface="org.jetbrains.plugins.textmate.TextMateService"
                        serviceImplementation="org.jetbrains.plugins.textmate.TextMateServiceImpl"/>
    <editorHighlighterProvider filetype="textmate" implementationClass="org.jetbrains.plugins.textmate.language.syntax.highlighting.TextMateEditorHighlighterProvider"/>
    <lang.syntaxHighlighterFactory language="textmate"
                                   implementationClass="org.jetbrains.plugins.textmate.language.syntax.highlighting.TextMateSyntaxHighlighterFactory"/>
    <applicationConfigurable groupId="editor"
                             bundle="messages.IdeBundle"
                             key="configurable.TextMateConfigurableProvider.display.name"
                             id="reference.settingsdialog.textmate.bundles" provider="org.jetbrains.plugins.textmate.configuration.TextMateConfigurableProvider"/>
    <lang.parserDefinition language="textmate" implementationClass="org.jetbrains.plugins.textmate.psi.TextMateParserDefinition"/>
    <braceMatcher filetype="textmate" implementationClass="org.jetbrains.plugins.textmate.editor.TextMateBraceMatcher"/>
    <typedHandler implementation="org.jetbrains.plugins.textmate.editor.TextMateTypedHandler"/>
    <backspaceHandlerDelegate implementation="org.jetbrains.plugins.textmate.editor.TextMateBackspaceHandler"/>
    <multiLangCommenter implementation="org.jetbrains.plugins.textmate.editor.TextMateCommentProvider"/>
    <lang.commenter language="textmate" implementationClass="org.jetbrains.plugins.textmate.editor.TextMateCommentProvider"/>
    <customLiveTemplate implementation="org.jetbrains.plugins.textmate.editor.TextMateCustomLiveTemplate"/>
    <todoIndexer filetype="textmate" implementationClass="com.intellij.psi.impl.cache.impl.todo.PlainTextTodoIndexer"/>
    <idIndexer filetype="textmate" implementationClass="com.intellij.psi.impl.cache.impl.id.PlainTextIndexer"/>
    <indexPatternBuilder implementation="org.jetbrains.plugins.textmate.TextMatePatternBuilder"/>
    <spellchecker.support language="textmate" implementationClass="org.jetbrains.plugins.textmate.spellchecker.TextMateSpellingStrategy"/>
    <completion.contributor language="textmate" implementationClass="org.jetbrains.plugins.textmate.editor.TextMateCompletionContributor"/>
  </extensions>
  <actions>
    <action id="install-vscode-plugin" class="org.jetbrains.plugins.textmate.actions.InstallVSCodePluginAction"
            text="Install VSCode Plugin..." description="Installs plugin for VSCode"
            internal="true"/>
  </actions>
</idea-plugin>


text:
namespace syncer {

const size_t ProtocolEventBuffer::kDefaultBufferSize = 6;

namespace {

size_t GetBufferSize() {
  base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
  std::string buffer_size =
      cmd_line->GetSwitchValueASCII(kSyncProtocolLogBufferSize);
  size_t result = 0;
  if (!base::StringToSizeT(buffer_size, &result)) {
    result = ProtocolEventBuffer::kDefaultBufferSize;
  }
  return result;
}

}  // namespace

ProtocolEventBuffer::ProtocolEventBuffer() : buffer_size_(GetBufferSize()) {}

ProtocolEventBuffer::~ProtocolEventBuffer() = default;

void ProtocolEventBuffer::RecordProtocolEvent(const ProtocolEvent& event) {
  if (buffer_.size() >= buffer_size_) {
    buffer_.pop_front();
  }
  buffer_.push_back(event.Clone());
}

std::vector<std::unique_ptr<ProtocolEvent>>
ProtocolEventBuffer::GetBufferedProtocolEvents() const {
  std::vector<std::unique_ptr<ProtocolEvent>> ret;
  for (const std::unique_ptr<ProtocolEvent>& event : buffer_) {
    ret.push_back(event->Clone());
  }

  return ret;
}

}  // namespace syncer


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.util.opinion;

import java.util.List;

import ghidra.app.util.Option;
import ghidra.app.util.OptionUtils;
import ghidra.app.util.bin.ByteProvider;
import ghidra.app.util.bin.format.elf.ElfException;
import ghidra.app.util.bin.format.elf.ElfHeader;
import ghidra.app.util.bin.format.elf.extend.ElfExtensionFactory;
import ghidra.app.util.bin.format.elf.extend.ElfLoadAdapter;
import ghidra.program.model.address.*;
import ghidra.program.model.lang.*;
import ghidra.util.NumericUtilities;
import ghidra.util.StringUtilities;

public class ElfLoaderOptionsFactory {

	public static final String PERFORM_RELOCATIONS_NAME = "Perform Symbol Relocations";
	static final boolean PERFORM_RELOCATIONS_DEFAULT = true;

	// NOTE: Using too large of an image base can cause problems for relocation processing
	// for some language scenarios which utilize 32-bit relocations.  This may be due to
	// an assumed virtual memory of 32-bits.

	public static final String IMAGE_BASE_OPTION_NAME = "Image Base";
	public static final long IMAGE_BASE_DEFAULT = 0x00010000;
	public static final long IMAGE64_BASE_DEFAULT = 0x00100000L;

	public static final String IMAGE_DATA_IMAGE_BASE_OPTION_NAME = "Data Image Base";

	public static final String INCLUDE_OTHER_BLOCKS = "Import Non-Loaded Data";// as OTHER overlay blocks
	static final boolean INCLUDE_OTHER_BLOCKS_DEFAULT = true;

	private ElfLoaderOptionsFactory() {
	}

	static void addOptions(List<Option> options, ByteProvider provider, LoadSpec loadSpec)
			throws ElfException, LanguageNotFoundException {

		// NOTE: add-to-program is not supported

		options.add(new Option(PERFORM_RELOCATIONS_NAME, PERFORM_RELOCATIONS_DEFAULT, Boolean.class,
			Loader.COMMAND_LINE_ARG_PREFIX + "-applyRelocations"));

		ElfHeader elf = new ElfHeader(provider, null);

		long imageBase = elf.findImageBase();
		if (imageBase == 0 && (elf.isRelocatable() || elf.isSharedObject())) {
			imageBase = elf.is64Bit() ? IMAGE64_BASE_DEFAULT : IMAGE_BASE_DEFAULT;
		}
		Language language = loadSpec.getLanguageCompilerSpec().getLanguage();
		AddressSpace defaultSpace = language.getDefaultSpace();

		String hexValueStr = getBaseAddressOffsetString(imageBase, defaultSpace);
		options.add(new Option(IMAGE_BASE_OPTION_NAME, hexValueStr, String.class,
			Loader.COMMAND_LINE_ARG_PREFIX + "-imagebase"));

		if (includeDataImageBaseOption(elf, language)) {
			long minDataImageBase = getRecommendedMinimumDataImageBase(elf, language);
			hexValueStr =
				getBaseAddressOffsetString(minDataImageBase, language.getDefaultDataSpace());
			options.add(new Option(IMAGE_DATA_IMAGE_BASE_OPTION_NAME, hexValueStr, String.class,
				Loader.COMMAND_LINE_ARG_PREFIX + "-dataImageBase"));
		}

		options.add(new Option(INCLUDE_OTHER_BLOCKS, INCLUDE_OTHER_BLOCKS_DEFAULT, Boolean.class,
			Loader.COMMAND_LINE_ARG_PREFIX + "-includeOtherBlocks"));

		ElfLoadAdapter extensionAdapter = ElfExtensionFactory.getLoadAdapter(elf);
		if (extensionAdapter != null) {
			extensionAdapter.addLoadOptions(elf, options);
		}

	}

	private static boolean includeDataImageBaseOption(ElfHeader elf, Language language) {
		// only include option if all segments and section have a 0 address
		AddressSpace defaultSpace = language.getDefaultSpace();
		AddressSpace defaultDataSpace = language.getDefaultDataSpace();
		if (defaultDataSpace.equals(defaultSpace)) {
			return false;
		}
		return elf.isRelocatable() && elf.getImageBase() == 0;
	}

	private static long getRecommendedMinimumDataImageBase(ElfHeader elf, Language language) {

		String minDataOffset =
			language.getProperty(GhidraLanguagePropertyKeys.MINIMUM_DATA_IMAGE_BASE);
		if (minDataOffset != null) {
			return NumericUtilities.parseHexLong(minDataOffset);
		}

		AddressSpace defaultDataSpace = language.getDefaultDataSpace();
		int unitSize = defaultDataSpace.getAddressableUnitSize();

		// logic assumes memory mapped registers reside at low-end addresses (e.g., 0)
		long minOffset = 0;
		for (Register reg : language.getRegisters()) {
			Address addr = reg.getAddress();
			if (defaultDataSpace.equals(addr.getAddressSpace())) {
				long offset = addr.getOffset();
				if (offset < 0) {
					continue;
				}
				offset += reg.getMinimumByteSize();
				if (offset > minOffset) {
					minOffset = offset;
				}
			}
		}
		// set minimum align
		int align = 16 * unitSize;
		minOffset += align - (minOffset % align);
		return minOffset / unitSize;
	}

	private static String getBaseAddressOffsetString(long imageBase, AddressSpace space) {
		long maxOffset = space.getMaxAddress().getAddressableWordOffset();
		while (Long.compareUnsigned(imageBase, maxOffset) > 0) {
			imageBase >>>= 4;
		}
		String baseOffsetStr = Long.toHexString(imageBase);
		int minNibbles = Math.min(8, space.getSize() / 4);
		int baseOffsetStrLen = baseOffsetStr.length();
		if (baseOffsetStrLen < minNibbles) {
			baseOffsetStr =
				StringUtilities.pad(baseOffsetStr, '0', minNibbles - baseOffsetStrLen);
		}
		return baseOffsetStr;
	}

	static String validateOptions(LoadSpec loadSpec, List<Option> options) {
		Language language;
		try {
			language = loadSpec.getLanguageCompilerSpec().getLanguage();
		} catch (LanguageNotFoundException e) {
			throw new RuntimeException(e);
		}
		for (Option option : options) {
			String name = option.getName();
			if (name.equals(PERFORM_RELOCATIONS_NAME)) {
				if (!Boolean.class.isAssignableFrom(option.getValueClass())) {
					return "Invalid type for option: " + name + " - " + option.getValueClass();
				}
			}
			else if (name.equals(INCLUDE_OTHER_BLOCKS)) {
				if (!Boolean.class.isAssignableFrom(option.getValueClass())) {
					return "Invalid type for option: " + name + " - " + option.getValueClass();
				}
			}
			else if (name.equals(IMAGE_BASE_OPTION_NAME)) {
				return validateAddressSpaceOffsetOption(option, language.getDefaultSpace());
			}
			else if (name.equals(IMAGE_DATA_IMAGE_BASE_OPTION_NAME)) {
				return validateAddressSpaceOffsetOption(option, language.getDefaultDataSpace());
			}
		}
		return null;
	}

	private static String validateAddressSpaceOffsetOption(Option option, AddressSpace space) {
		String name = option.getName();
		if (!String.class.isAssignableFrom(option.getValueClass())) {
			return "Invalid type for option: " + name + " - " + option.getValueClass();
		}
		String value = (String) option.getValue();
		try {
			space.getAddress(Long.parseUnsignedLong(value, 16), true);// verify valid address
		}
		catch (NumberFormatException e) {
			return "Invalid " + name + " - expecting hexidecimal address offset";
		}
		catch (AddressOutOfBoundsException e) {
			return "Invalid " + name + " - " + e.getMessage();
		}
		return null;
	}

	static boolean performRelocations(List<Option> options) {
		return OptionUtils.getOption(PERFORM_RELOCATIONS_NAME, options,
			PERFORM_RELOCATIONS_DEFAULT);
	}

	static boolean includeOtherBlocks(List<Option> options) {
		return OptionUtils.getOption(INCLUDE_OTHER_BLOCKS, options, INCLUDE_OTHER_BLOCKS_DEFAULT);
	}

	static boolean hasImageBaseOption(List<Option> options) {
		return OptionUtils.containsOption(IMAGE_BASE_OPTION_NAME, options);
	}

	public static String getImageBaseOption(List<Option> options) {
		return OptionUtils.getOption(IMAGE_BASE_OPTION_NAME, options, (String) null);
	}

	public static String getDataImageBaseOption(List<Option> options) {
		return OptionUtils.getOption(IMAGE_DATA_IMAGE_BASE_OPTION_NAME, options, (String) null);
	}

}


text:
var general = general || {
  init: function() {
    $('form:not(.no-focus) input:visible:not(.no-focus):first').focus();
    $('[data-toggle="tooltip"]').tooltip();
    $('[href="#lity-close"]').on('click', this.lity_close_click_listener);
    this.bind_remote_content_for_bootstrap_modals();
  },

  bind_remote_content_for_bootstrap_modals: function() {
    $('[data-toggle="modal"]').on('click', function() {
      var anchor = $(this);
      $(anchor.data('target') + ' .modal-body').load(anchor.data('remote'));
    });
  },

  lity_close_click_listener: function(e) {
    e.preventDefault();
    $(parent.window.document).find('[data-lity-close=""]').trigger('click');
  }
};

$(function(){ general.init(); });