text:
// paths.cc            see license.txt for copyright and terms of use
// code for paths.h

#include "paths.h"       // this module

#include "c.ast.gen.h"   // C AST
#include "sobjlist.h"    // SObjList
#include "objlist.h"     // ObjList
#include "c_env.h"       // Env
#include "trace.h"       // tracingSys
#include "treeout.h"     // treeOut

// one thing to note about constness: when an AST node contains a field
// to store the path count, the counting function is declared non-const;
// but when the AST node does not store the count, the counting function
// is declared to accept a const*

// prototypes
void findPathRoots(SObjList<Statement> &list, TF_func const *func);
void findPathRoots(SObjList<Statement> &list, Statement const *stmt);
int countPaths(Env &env, TF_func *func);
int countPathsFrom(Env &env, SObjList<Statement> &path,
                   Statement *node, bool isContinue);
int countExprPaths(Initializer *init);
void printPaths(TF_func const *func);
void printPathFrom(SObjList<Statement /*const*/> &path, int index,
                   Statement const *node, bool isContinue);
void printPath(SObjList<Statement /*const*/> &path, char const *label);

// watch for overflow
static int mult(int a, int b)
{
  int r = a*b;
  if (a>0 && b>0 && (r < a || r < b)) {
    xfailure(stringc << "arithmetic overflow: " << a << " * " << b);
  }
  if (r > 1000) {
    cout << r << " is more than 1000 paths!\n";
  }
  return r;
}

// --------------------- finding roots ----------------------
void findPathRoots(SObjList<Statement> &list, TF_func const *func)
{
  list.reverse();
  list.prepend(func->body);
  findPathRoots(list, func->body);
  list.reverse();
}

void findPathRoots(SObjList<Statement> &list, Statement const *stmt)
{
  ASTSWITCHC(Statement, stmt) {
    ASTCASEC(S_label, l) {
      findPathRoots(list, l->s);
    }
    ASTNEXTC(S_case, c) {
      findPathRoots(list, c->s);
    }
    ASTNEXTC(S_caseRange, c) {
      findPathRoots(list, c->s);
    }
    ASTNEXTC(S_default, d) {
      findPathRoots(list, d->s);
    }
    ASTNEXTC(S_compound, c) {
      FOREACH_ASTLIST(Statement, c->stmts, iter) {
        findPathRoots(list, iter.data());
      }
    }
    ASTNEXTC(S_if, i) {
      findPathRoots(list, i->thenBranch);
      findPathRoots(list, i->elseBranch);
    }
    ASTNEXTC(S_switch, s) {
      findPathRoots(list, s->branches);
    }
    ASTNEXTC(S_while, w) {
      findPathRoots(list, w->body);
    }
    ASTNEXTC(S_doWhile, d) {
      findPathRoots(list, d->body);
    }
    ASTNEXTC(S_for, f) {
      findPathRoots(list, f->init);
      findPathRoots(list, f->body);
    }
    ASTNEXTC(S_invariant, i) {
      list.prepend(const_cast<S_invariant*>(i));       // action!
    }
    ASTENDCASECD
  }
}

// ------------------------ counting paths ------------------
int countPaths(Env &env, TF_func *func)
{
  func->numPaths=0;

  // enumerate the roots
  findPathRoots(func->roots, func);

  // enumerate all paths from each root
  SMUTATE_EACH_OBJLIST(Statement, func->roots, iter) {
    Statement *s = iter.data();

    SObjList<Statement> path;
    countPathsFrom(env, path, s, false /*isContinue*/);
    func->numPaths += s->numPaths;
  }

  return func->numPaths;
}

// need the 'path' to detect circularity;
// this function has similar structure to 'printPathFrom', below
int countPathsFrom(Env &env, SObjList<Statement> &path,
                   Statement *node, bool isContinue)
{
  if (node->kind() != Statement::S_INVARIANT &&
      path.contains(node)) {
    env.warnLoc(node->loc, "circular path");
    if (tracingSys("circular")) {
      // print the circular path
      SFOREACH_OBJLIST(Statement, path, iter) {
        cout << "  " << toString(iter.data()->loc) << endl;
      }
    }
    return 1;
  }

  path.prepend(node);
  int ret;

  if (node->kind() == Statement::S_INVARIANT &&
      path.count() > 1) {
    // we've reached an invariant point, so the path stops here;
    // but we don't change node->paths since that is for the #
    // of paths from 'node' as a path *start*, not end
    ret = 1;
  }

  else {
    // retrieve all successors of this node
    VoidList successors;
    node->getSuccessors(successors, isContinue);

    if (successors.isEmpty()) {
      // this is a return statement (or otherwise end of function)
      ret = 1;
    }
    else {
      // initially, there are 0 paths from here
      ret = 0;

      // consider each choice
      for (VoidListIter iter(successors); !iter.isDone(); iter.adv()) {
        void *np = iter.data();
        // unfortunately I can't easily parameterize a voidlist by whether
        // my interpretation of a field of its contents is 'const' ...
        Statement *s = const_cast<Statement*>(nextPtrStmt(np));
        int ct = countPathsFrom(env, path, s, nextPtrContinue(np));

        // add all paths from this successor to our total
        ret += ct;
      }
    }

    // now, every path through expressions in this statement will be
    // (conservatively) considered to possibly be followed by any control
    // flow path *from* this statement
    ret = mult(ret, countExprPaths(node, isContinue));

    // in this branch (only), we write the # of paths into the statement
    node->numPaths = ret;
  }

  path.removeFirst();
  return ret;
}

// ---------------------- printing paths ---------------------
void printPaths(TF_func const *func)
{
  // enumerate all paths from each root
  SFOREACH_OBJLIST(Statement, func->roots, iter) {
    Statement const *s = iter.data();
    cout << "root at " << toString(iter.data()->loc) << ":\n";

    // the whole point of counting the paths was so I could
    // so easily get a handle on all of them, to be able to
    // write a nice loop like this:
    for (int i=0; i < s->numPaths; i++) {
      cout << "  path " << i << ":\n";
      SObjList<Statement /*const*/> path;
      printPathFrom(path, i, s, false /*isContinue*/);
    }
  }
}

int numPathsThrough(Statement const *stmt)
{
  // how many paths lead from 'stmt'?  usually just s->numPaths, but
  // if it is a path cutpoint then there's exactly one path from 'stmt'
  int ret = stmt->isS_invariant()? 1 : stmt->numPaths;
  return ret;
}

// abstract the "4" slightly..
//#define PATHOUT treeOut(4)
// actually, I didn't want these as headings at all..
#define PATHOUT cout << "  "

// want 'path' to detect circularity (for debugging);
// this function has similar structure to 'countPathsFrom', above
void printPathFrom(SObjList<Statement /*const*/> &path, int index,
                   Statement const *node, bool isContinue)
{
  // validate 'index'
  int exprPaths = countExprPaths(node, isContinue);
  xassert(exprPaths >= 1);
  xassert(0 <= index && index < node->numPaths);
    // this used to say node->numPaths * exprPaths, but it seems clear
    // that numPaths *already* includes the contribution from exprPaths

  // print this node
  PATHOUT << toString(node->loc) << ": "
          << node->kindName() << endl;

  // debugging check
  if (path.contains(node)) {
    PATHOUT << "CIRCULAR path\n";
    return;
  }
  path.prepend(const_cast<Statement*>(node));

  // follow one expression path in this statement
  printExprPath(index % exprPaths, node, isContinue);
  index = index / exprPaths;

  // retrieve all successors of this node
  VoidList successors;
  node->getSuccessors(successors, isContinue);

  if (successors.isEmpty()) {
    // this is a return statement (or otherwise end of function)
    xassert(index == 0);
    PATHOUT << "path ends at a return\n";
  }
  else {
    // consider each choice
    // largely COPIED to vcgen.cc:Statement::vcgenPath
    for (VoidListIter iter(successors); !iter.isDone(); iter.adv()) {
      void *np = iter.data();
      Statement const *s = nextPtrStmt(np);
      int pathsFromS = numPathsThrough(s);

      // are we going to follow 's'?
      if (index < pathsFromS) {
        // yes; is 's' an invariant?
        if (s->isS_invariant()) {
          // terminate the path; print final node
          PATHOUT << toString(s->loc) << ": "
                  << s->kindName() << endl;
          PATHOUT << "path ends at an invariant\n";
        }
        else {
          // continue the path
          printPathFrom(path, index, s, nextPtrContinue(np));
        }
        index = 0;       // remember that we found a path to follow
        break;
      }

      else {
        // no; factor out s's contribution to the path index
        index -= pathsFromS;
      }
    }

    // make sure we followed *some* path
    xassert(index == 0);
  }

  path.removeFirst();
}

// --------- counting/print expression paths in statements ------------
int countExprPaths(Statement const *stmt, bool isContinue)
{
  ASTSWITCHC(Statement, stmt) {
    ASTCASEC(S_expr, e) {
      return e->expr->numPaths1();
    }
    ASTNEXTC(S_if, i) {
      return i->cond->numPaths1();
    }
    ASTNEXTC(S_switch, s) {
      return s->expr->numPaths1();
    }
    ASTNEXTC(S_while, w) {
      return w->cond->numPaths1();
    }
    ASTNEXTC(S_doWhile, d) {
      if (isContinue) {
        // enter at the guard, so as many paths as paths through guard
        return d->cond->numPaths1();
      }
      else {
        // enter at top, no expr is evaluated
        return 1;
      }
    }
    ASTNEXTC(S_for, f) {
      if (isContinue) {
        // enter just before inc and test
        return mult(f->after->numPaths1(), f->cond->numPaths1());
      }
      else {
        // enter at init, immediately apply guard
        //return mult(countExprPaths(f->init, false), f->cond->numPaths1());
        // UPDATE: my CFG does the init before the 'for'
        return f->cond->numPaths1();
      }
    }
    ASTNEXTC(S_return, r) {
      if (r->expr) {
        return r->expr->numPaths1();
      }
      else {
        return 1;
      }
    }
    ASTNEXTC(S_decl, d) {
      // somewhat complicated because we need to dig around in the
      // declaration for paths through initializing expressions
      int ret = 1;
      FOREACH_ASTLIST(Declarator, d->decl->decllist, dcltr) {
        Initializer const *init = dcltr.data()->init;
        if (init) {
          ret = mult(ret, countExprPaths(init));
        }
      }
      return ret;
    }
    ASTDEFAULTC {
      // no expressions in the statement, only 1 path
      return 1;
    }
    ASTENDCASEC
  }
}

void printExprPath(int index, Statement const *stmt, bool isContinue)
{
  xassert(index >= 0);

  ASTSWITCHC(Statement, stmt) {
    ASTCASEC(S_expr, e) {
      printPath(index, e->expr);
    }
    ASTNEXTC(S_if, i) {
      printPath(index, i->cond);
    }
    ASTNEXTC(S_switch, s) {
      printPath(index, s->expr);
    }
    ASTNEXTC(S_while, w) {
      printPath(index, w->cond);
    }
    ASTNEXTC(S_doWhile, d) {
      if (isContinue) {
        // enter at the guard, so as many paths as paths through guard
        printPath(index, d->cond);
      }
      else {
        // enter at top, no expr is evaluated
        xassert(index==0);
      }
    }
    ASTNEXTC(S_for, f) {
      int modulus = f->cond->numPaths1();
      if (isContinue) {
        // enter just before inc and test
        printPath(index / modulus, f->after);
        printPath(index % modulus, f->cond);
      }
      else {
        // enter at init, immediately apply guard
        //printExprPath(index / modulus, f->init, false);
        // UPDATE: CFG does 'init' before 'for'
        xassert(index < modulus);
        printPath(index /* % modulus*/, f->cond);
      }
    }
    ASTNEXTC(S_return, r) {
      if (r->expr) {
        printPath(index, r->expr);
      }
      else {
        xassert(index==0);
      }
    }
    ASTNEXTC(S_decl, d) {
      // somewhat complicated because we need to dig around in the
      // declaration for paths through initializing expressions
      int paths = 1;
      FOREACH_ASTLIST(Declarator, d->decl->decllist, dcltr) {
        Initializer const *init = dcltr.data()->init;
        if (init) {
          paths = countExprPaths(init);
          printExprPath(index % paths, init);
          index = index / paths;
        }
      }

      // if we entered the loop at all, this ensures the last iteration
      // consumed all of 'index'; if we never entered the loop, this
      // checks that index was 0
      xassert(index < paths);
    }
    ASTDEFAULTC {
      // no expressions in the statement, only 1 path
      xassert(index==0);
    }
    ASTENDCASEC
  }
}

// --------------- count/print paths through initializers --------------
int countExprPaths(Initializer const *init)
{
  ASTSWITCHC(Initializer, init) {
    ASTCASEC(IN_expr, ie) {
      return ie->e->numPaths1();
    }
    ASTNEXTC(IN_compound, ic) {
      int ret = 1;
      FOREACH_ASTLIST(Initializer, ic->inits, iter) {
        ret = mult(ret, countExprPaths(iter.data()));
      }
      return ret;
    }
    ASTDEFAULTC {
      xfailure("bad code");
      return 0;
    }
    ASTENDCASEC
  }
}

void printExprPath(int index, Initializer const *init)
{
  ASTSWITCHC(Initializer, init) {
    ASTCASEC(IN_expr, ie) {
      printPath(index, ie->e);
    }
    ASTNEXTC(IN_compound, ic) {
      // this loop is very similar to the one above for S_decl
      int paths = 1;
      FOREACH_ASTLIST(Initializer, ic->inits, iter) {
        Initializer const *i = iter.data();
        paths = countExprPaths(i);
        printExprPath(index % paths, i);
        index = index / paths;
      }
      xassert(index < paths);
    }
    ASTENDCASECD
  }
}

// -------------- count/print paths through expressions --------------
int countPaths(Env &env, Expression *ths)
{
  // default: 1 path, no side effects, is already set: 0
  xassert(ths->numPaths == 0);
  int numPaths = 0;

  // don't bother counting paths in predicates, where everything
  // is side-effect-free
  if (env.inPredicate) {
    return 0;
  }

  #define SIDE_EFFECT() numPaths = max(numPaths,1) /* user ; */

  ASTSWITCH(Expression, ths) {
    ASTCASE(E_funCall, ths) {
      numPaths = ths->func->numPaths;

      FOREACH_ASTLIST_NC(Expression, ths->args, iter) {
        // compute # of paths
        int argPaths = iter.data()->numPaths;
        if (argPaths > 0) {
          if (numPaths > 0) {
            env.warn("more than one argument expression has side effects");
            numPaths = mult(numPaths, argPaths);
          }
          else {
            numPaths = argPaths;
          }
        }
      }

      // the call itself counts as a side-effecting expression (unless I
      // add an annotation to declare something as "functional" ...)
      SIDE_EFFECT();
    }
    ASTNEXT(E_fieldAcc, ths) {
      numPaths = ths->obj->numPaths;
    }
    ASTNEXT(E_sizeof, ths) {
      PRETEND_USED(ths);     // silence warning
      numPaths = 0;
    }
    ASTNEXT(E_unary, ths) {
      numPaths = ths->expr->numPaths;
    }
    ASTNEXT(E_effect, ths) {
      numPaths = ths->expr->numPaths;
      SIDE_EFFECT();
    }
    ASTNEXT(E_binary, ths) {
      // there are at least as many paths as paths through left-hand side
      numPaths = ths->e1->numPaths;

      if (ths->e2->numPaths == 0) {
        // if the RHS has no side effects, it contributes nothing to the
        // paths computation, regardless of whether 'op' is short-circuit,
        // so we just propagate the LHS's numPaths
      }

      else {
        // if the RHS has a side effect, this expression as a whole might
        // have a side effect
        SIDE_EFFECT();

        if (ths->op==BIN_AND || ths->op==BIN_OR) {
          // path computation with short-circuit evaluation: for each LHS
          // path, we could take any one of the RHS paths, *or* skip
          // evaluating the RHS altogether
          numPaths = mult(numPaths, (1 + ths->e2->numPaths));
        }

        else {
          // path computation without short-circuit evaluation: we can
          // take any combination of LHS and RHS paths
          numPaths = mult(numPaths, ths->e2->numPaths);
        }
      }
    }
    ASTNEXT(E_addrOf, ths) {
      numPaths = ths->expr->numPaths;
    }
    ASTNEXT(E_deref, ths) {
      numPaths = ths->ptr->numPaths;
    }
    ASTNEXT(E_cast, ths) {
      numPaths = ths->expr->numPaths;
    }
    ASTNEXT(E_cond, ths) {
      // start with # of paths through conditional
      numPaths = ths->cond->numPaths;

      if (ths->th->numPaths == 0 && ths->el->numPaths == 0) {
        // no side effects in either branch; we're good to go
      }

      else {
        // since at least one branch as a side effect, let's say
        // all three components have at least 1 path
        SIDE_EFFECT();
        int thenPaths = ths->th->numPaths1();
        int elsePaths = ths->el->numPaths1();

        // for every path through the conditional, we could either
        // go through a 'then' path or an 'else' path
        numPaths = mult(numPaths, thenPaths + elsePaths);
      }
    }
    #if 0
    ASTNEXT(E_gnuCond, ths) {
      // degenerate form of E_cond
      numPaths = ths->cond->numPaths;
      if (ths->el->numPaths > 0) {
        ths->recordSideEffect();
        numPaths = mult(numPaths, 1 + ths->el->numPaths);
      }
    }
    #endif // 0
    ASTNEXT(E_comma, ths) {
      numPaths = ths->e1->numPaths;
      if (ths->e2->numPaths > 0) {
        numPaths = mult(max(numPaths,1), ths->e2->numPaths);
      }
    }
    ASTNEXT(E_assign, ths) {
      numPaths = ths->src->numPaths;              // start with paths through src
      SIDE_EFFECT();                              // clearly this expr has a side effect
      numPaths = mult(numPaths, ths->target->numPaths1());       // add paths through target
    }
    ASTNEXT(E_quantifier, ths) {
      xfailure("shouldn't get here because only allowed in predicates");
      PRETEND_USED(ths);
    }
    ASTENDCASED
  }

  return ths->numPaths = numPaths;

  #undef SIDE_EFFECT
}

// print choice point decisions, and side effects
void printPath(int index, Expression const *ths)
{
  xassert(0 <= index && index < ths->numPaths1());

  ASTSWITCHC(Expression, ths) {
    ASTCASEC(E_funCall, ths) {
      PATHOUT << "call to " << ths->func->toString() << endl;

      // 'func'
      int subexpPaths = ths->func->numPaths1();
      printPath(index % subexpPaths, ths->func);
      index = index / subexpPaths;

      // args
      FOREACH_ASTLIST(Expression, ths->args, iter) {
        subexpPaths = iter.data()->numPaths1();
        printPath(index % subexpPaths, iter.data());
        index = index / subexpPaths;
      }
      xassert(index < subexpPaths);
    }
    ASTNEXTC(E_fieldAcc, ths) {
      printPath(index, ths->obj);
    }
    ASTNEXTC(E_sizeof, ths) {
      PRETEND_USED(ths);     // silence warning
    }
    ASTNEXTC(E_unary, ths) {
      printPath(index, ths->expr);
    }
    ASTNEXTC(E_effect, ths) {
      PATHOUT << "side effect: " << ths->toString() << endl;
      printPath(index, ths->expr);
    }
    ASTNEXTC(E_binary, ths) {
      if (ths->e2->numPaths == 0) {
        // if the RHS has no side effects, the encoding is more compact,
        // and only the LHS is relevant
        printPath(index, ths->e1);
      }

      else {
        // print LHS
        int modulus = ths->e1->numPaths1();
        printPath(index % modulus, ths->e1);
        index = index / modulus;

        // consider operator
        if (ths->op==BIN_AND || ths->op==BIN_OR) {
          // print RHS *if* it's followed
          if (index > 0) {
            PATHOUT << "traversing into rhs of " << toString(ths->op) << endl;
            printPath(index-1, ths->e2);
          }
          else {
            PATHOUT << "short-circuiting rhs of " << toString(ths->op) << endl;
          }
        }

        else {
          // non-short-circuit: always evaluate RHS
          printPath(index, ths->e2);
        }
      }
    }
    ASTNEXTC(E_addrOf, ths) {
      printPath(index, ths->expr);
    }
    ASTNEXTC(E_deref, ths) {
      printPath(index, ths->ptr);
    }
    ASTNEXTC(E_cast, ths) {
      printPath(index, ths->expr);
    }
    ASTNEXTC(E_cond, ths) {
      // condition
      int modulus = ths->cond->numPaths1();
      printPath(index % modulus, ths->cond);
      index = index / modulus;

      if (ths->th->numPaths == 0 && ths->el->numPaths == 0) {
        // no side effects in either branch; we're good to go
      }

      else {
        int thenPaths = ths->th->numPaths1();
        int elsePaths = ths->el->numPaths1();

        if (index < thenPaths) {
          PATHOUT << "taking 'then' path through ?:\n";
          printPath(index, ths->th);
        }
        else {
          PATHOUT << "taking 'else' path through ?:\n";
          printPath(index - elsePaths, ths->el);
        }
      }
    }
    #if 0
    ASTNEXTC(E_gnuCond, ths) {
      // degenerate form of E_cond
      PATHOUT << "gnuCond unhandled for now: " << (void*)ths << "\n";
    }
    #endif // 0
    ASTNEXTC(E_comma, ths) {
      int modulus = ths->e1->numPaths1();
      printPath(index % modulus, ths->e1);
      printPath(index / modulus, ths->e2);
    }
    ASTNEXTC(E_assign, ths) {
      PATHOUT << "side effect: " << ths->toString() << endl;
      int modulus = ths->src->numPaths1();
      printPath(index % modulus, ths->src);
      printPath(index / modulus, ths->target);
    }
    ASTENDCASECD
  }
}


text:
package com.metamx.emitter.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.metamx.common.Pair;
import org.junit.Assert;
import org.junit.Test;

import java.util.Properties;

public class HttpEmitterConfigTest
{
  @Test
  public void testDefaults(){
    final Properties props = new Properties();
    props.put("com.metamx.emitter.recipientBaseUrl", "http://example.com/");

    final ObjectMapper objectMapper = new ObjectMapper();
    final HttpEmitterConfig config = objectMapper.convertValue(Emitters.makeCustomFactoryMap(props), HttpEmitterConfig.class);

    Assert.assertEquals(60000, config.getFlushMillis());
    Assert.assertEquals(500, config.getFlushCount());
    Assert.assertEquals("http://example.com/", config.getRecipientBaseUrl());
    Assert.assertEquals(null, config.getBasicAuthentication());
    Assert.assertEquals(BatchingStrategy.ARRAY, config.getBatchingStrategy());
    Pair<Integer, Integer> batchConfigPair = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        Runtime.getRuntime().maxMemory()
    );
    Assert.assertEquals(batchConfigPair.lhs.intValue(), config.getMaxBatchSize());
    Assert.assertEquals(batchConfigPair.rhs.intValue(), config.getBatchQueueSizeLimit());
    Assert.assertEquals(Long.MAX_VALUE, config.getFlushTimeOut());
    Assert.assertEquals(2.0f, config.getHttpTimeoutAllowanceFactor(), 0.0f);
    Assert.assertEquals(0, config.getMinHttpTimeoutMillis());
  }

  @Test
  public void testDefaultsLegacy()
  {
    final Properties props = new Properties();
    props.put("com.metamx.emitter.http.url", "http://example.com/");

    final ObjectMapper objectMapper = new ObjectMapper();
    final HttpEmitterConfig config = objectMapper.convertValue(Emitters.makeHttpMap(props), HttpEmitterConfig.class);

    Assert.assertEquals(60000, config.getFlushMillis());
    Assert.assertEquals(300, config.getFlushCount());
    Assert.assertEquals("http://example.com/", config.getRecipientBaseUrl());
    Assert.assertEquals(null, config.getBasicAuthentication());
    Assert.assertEquals(BatchingStrategy.ARRAY, config.getBatchingStrategy());
    Pair<Integer, Integer> batchConfigPair = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        Runtime.getRuntime().maxMemory()
    );
    Assert.assertEquals(batchConfigPair.lhs.intValue(), config.getMaxBatchSize());
    Assert.assertEquals(batchConfigPair.rhs.intValue(), config.getBatchQueueSizeLimit());
    Assert.assertEquals(Long.MAX_VALUE, config.getFlushTimeOut());
    Assert.assertEquals(2.0f, config.getHttpTimeoutAllowanceFactor(), 0.0f);
    Assert.assertEquals(0, config.getMinHttpTimeoutMillis());
  }

  @Test
  public void testSettingEverything()
  {
    final Properties props = new Properties();
    props.setProperty("com.metamx.emitter.flushMillis", "1");
    props.setProperty("com.metamx.emitter.flushCount", "2");
    props.setProperty("com.metamx.emitter.recipientBaseUrl", "http://example.com/");
    props.setProperty("com.metamx.emitter.basicAuthentication", "a:b");
    props.setProperty("com.metamx.emitter.batchingStrategy", "NEWLINES");
    props.setProperty("com.metamx.emitter.maxBatchSize", "4");
    props.setProperty("com.metamx.emitter.flushTimeOut", "1000");
    props.setProperty("com.metamx.emitter.batchQueueSizeLimit", "2500");
    props.setProperty("com.metamx.emitter.httpTimeoutAllowanceFactor", "3.0");
    props.setProperty("com.metamx.emitter.minHttpTimeoutMillis", "100");

    final ObjectMapper objectMapper = new ObjectMapper();
    final HttpEmitterConfig config = objectMapper.convertValue(Emitters.makeCustomFactoryMap(props), HttpEmitterConfig.class);

    Assert.assertEquals(1, config.getFlushMillis());
    Assert.assertEquals(2, config.getFlushCount());
    Assert.assertEquals("http://example.com/", config.getRecipientBaseUrl());
    Assert.assertEquals("a:b", config.getBasicAuthentication());
    Assert.assertEquals(BatchingStrategy.NEWLINES, config.getBatchingStrategy());
    Assert.assertEquals(4, config.getMaxBatchSize());
    Assert.assertEquals(1000, config.getFlushTimeOut());
    Assert.assertEquals(2500, config.getBatchQueueSizeLimit());
    Assert.assertEquals(3.0f, config.getHttpTimeoutAllowanceFactor(), 0.0f);
    Assert.assertEquals(100, config.getMinHttpTimeoutMillis());
  }

  @Test
  public void testSettingEverythingLegacy()
  {
    final Properties props = new Properties();
    props.setProperty("com.metamx.emitter.flushMillis", "1");
    props.setProperty("com.metamx.emitter.flushCount", "2");
    props.setProperty("com.metamx.emitter.http.url", "http://example.com/");
    props.setProperty("com.metamx.emitter.http.basicAuthentication", "a:b");
    props.setProperty("com.metamx.emitter.http.batchingStrategy", "newlines");
    props.setProperty("com.metamx.emitter.http.maxBatchSize", "4");
    props.setProperty("com.metamx.emitter.http.flushTimeOut", "1000");
    props.setProperty("com.metamx.emitter.http.batchQueueSizeLimit", "2500");
    props.setProperty("com.metamx.emitter.http.httpTimeoutAllowanceFactor", "3.0");
    props.setProperty("com.metamx.emitter.http.minHttpTimeoutMillis", "100");

    final ObjectMapper objectMapper = new ObjectMapper();
    final HttpEmitterConfig config = objectMapper.convertValue(Emitters.makeHttpMap(props), HttpEmitterConfig.class);

    Assert.assertEquals(1, config.getFlushMillis());
    Assert.assertEquals(2, config.getFlushCount());
    Assert.assertEquals("http://example.com/", config.getRecipientBaseUrl());
    Assert.assertEquals("a:b", config.getBasicAuthentication());
    Assert.assertEquals(BatchingStrategy.NEWLINES, config.getBatchingStrategy());
    Assert.assertEquals(4, config.getMaxBatchSize());
    Assert.assertEquals(1000, config.getFlushTimeOut());
    Assert.assertEquals(2500, config.getBatchQueueSizeLimit());
    Assert.assertEquals(3.0f, config.getHttpTimeoutAllowanceFactor(), 0.0f);
    Assert.assertEquals(100, config.getMinHttpTimeoutMillis());
  }

  @Test
  public void testMemoryLimits()
  {
    Pair<Integer, Integer> batchConfigPair = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        64 * 1024 * 1024
    );
    Assert.assertEquals(3355443, batchConfigPair.lhs.intValue());
    Assert.assertEquals(2, batchConfigPair.rhs.intValue());

    Pair<Integer, Integer> batchConfigPair2 = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        128 * 1024 * 1024
    );
    Assert.assertEquals(5242880, batchConfigPair2.lhs.intValue());
    Assert.assertEquals(2, batchConfigPair2.rhs.intValue());

    Pair<Integer, Integer> batchConfigPair3 = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        256 * 1024 * 1024
    );
    Assert.assertEquals(5242880, batchConfigPair3.lhs.intValue());
    Assert.assertEquals(5, batchConfigPair3.rhs.intValue());

    Pair<Integer, Integer> batchConfigPair4 = BaseHttpEmittingConfig.getDefaultBatchSizeAndLimit(
        Long.MAX_VALUE
    );
    Assert.assertEquals(5242880, batchConfigPair4.lhs.intValue());
    Assert.assertEquals(50, batchConfigPair4.rhs.intValue());
  }
}

redpajama_set_name: RedPajamaGithub


text:
var eyeserver = require('../lib/eyeserver.js');
var vows = require('vows'),
    should = require('should'),
    request = require('request'),
    EventEmitter = require('events').EventEmitter;

vows.describe('EyeServer').addBatch({
  'The eyeserver module': {
    topic: function () { return eyeserver; },

    'should be a function': function (eyeserver) {
      eyeserver.should.be.a('function');
    },

    'should make EyeServer objects': function (eyeserver) {
      eyeserver().constructor.should.eql(eyeserver);
      eyeserver().should.be.an.instanceof(eyeserver);
    },

    'should be an EyeServer constructor': function (eyeserver) {
      new eyeserver().constructor.should.eql(eyeserver);
      new eyeserver().should.be.an.instanceof(eyeserver);
    }
  },

  'An EyeServer instance': {
    topic: function () {
      server = new eyeserver({ eye: eyeDummy, debug: true });
      server.listen(13705);
      return server;
    },

    teardown: function () {
      server.close();
    },

    'receiving a request to /':
      respondsWith(200, 'text/n3', 'without data', { data: [], pass: true }),

    'receiving a request to /?quickAnswer':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: true }),

    'receiving a request to /?quickanswer':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: true }),

    'receiving a request to /?quick-answer':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: true }),

    'receiving a request to /?quickAnswer=0':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: false }),

    'receiving a request to /?quickanswer=false':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: false }),

    'receiving a request to /?quick-answer=1':
      respondsWith(200, 'text/n3', 'with quickAnswer', { data: [], pass: true, quickAnswer: true }),

    'receiving a request to /?data=http%3A%2F%2Fex.org%2Ferror':
      respondsWith(400, 'text/plain', 'and receive an error', { data: ['http://ex.org/error'], pass: true }),

    'receiving a request to /?data=http%3A%2F%2Fex.org%2F1':
      respondsWith(200, 'text/n3', 'with one URI', { data: ['http://ex.org/1'], pass: true }),

    'receiving a request to /?data=http%3A%2F%2Fex.org%2F1,http%3A%2F%2Fex.org%2F2':
      respondsWith(200, 'text/n3', 'with two URIs', { data: ['http://ex.org/1', 'http://ex.org/2'], pass: true }),

    'receiving a request to /?data=http%3A%2F%2Fex.org%2F1&data=http%3A%2F%2Fex.org%2F2':
      respondsWith(200, 'text/n3', 'with two URIs', { data: ['http://ex.org/1', 'http://ex.org/2'], pass: true }),

    'receiving a request to /?data=http%3A%2F%2Fex.org%2F1&data=http%3A%2F%2Fex.org%2F2,http%3A%2F%2Fex.org%2F3':
      respondsWith(200, 'text/n3', 'with three URIs', { data: ['http://ex.org/1', 'http://ex.org/2', 'http://ex.org/3'], pass: true }),

    'receiving a request to /?data=%3Aa%20%3Ab%20%3Ac.':
      respondsWith(200, 'text/n3', 'with N3 data', { data: [':a :b :c.'], pass: true }),

    'receiving a request to /?query=http%3A%2F%2Fex.org%2F1':
      respondsWith(200, 'text/n3', 'with a query', { data: [], query: 'http://ex.org/1' }),

    // note: adding query parameters to obtain unique URIs for test validation
    'receiving a request to /?f1 with form data=http%3A%2F%2Fex.org%2F1':
      respondsWith(200, 'text/n3', 'with one URI', { data: ['http://ex.org/1'], pass: true }, "POST"),

    'receiving a request to /?f2 with form data=http%3A%2F%2Fex.org%2F1&data=http%3A%2F%2Fex.org%2F2':
      respondsWith(200, 'text/n3', 'with two URIs', { data: ['http://ex.org/1', 'http://ex.org/2'], pass: true }, "POST"),

    'receiving a request to /?f3&data=http%3A%2F%2Fex.org%2F1 with form data=http%3A%2F%2Fex.org%2F2':
      respondsWith(200, 'text/n3', 'with two URIs', { data: ['http://ex.org/1', 'http://ex.org/2'], pass: true }, "POST"),

    'receiving a request to /?f4&data=http%3A%2F%2Fex.org%2F1 with form data=%3Aa%20%3Ab%20%3Ac.':
      respondsWith(200, 'text/n3', 'with two URIs', { data: ['http://ex.org/1', ':a :b :c.'], pass: true }, "POST"),

    'receiving a request to /?f5&data=http%3A%2F%2Fex.org%2F1 with form query=http%3A%2F%2Fex.org%2F2':
      respondsWith(200, 'text/n3', 'with a URI and a query', { data: ['http://ex.org/1'], query: 'http://ex.org/2' }, "POST"),

    'receiving a request to /?callback=mycallback':
      respondsWith(200, 'application/javascript', 'without data', { data: [], pass: true }, "GET", 'mycallback("out\\"put")'),

    'receiving a request to /?callback=my{illegal}callback':
      respondsWith(400, 'application/javascript', 'without data', { data: [], pass: true }, "GET", 'alert("Illegal callback name.")'),

    'receiving an OPTIONS request on /': {
      topic: function () {
        request({ url: 'http://localhost:13705/', method: 'OPTIONS' }, this.callback);
      },

      'should respond with Access-Control-Allow-Origin *': function (error, response, body) {
        response.headers.should.have.property('access-control-allow-origin', '*');
      }
    },

    'receiving a request that is aborted': (function () {
      var canceled;
      return {
        topic: function () {
          // setup dummy eye with dummy eyeProcess
          var eyeProcess = { cancel: function () { canceled = true; } };
          var server = new eyeserver({ eye: { execute: function () { return eyeProcess; } } });
          // set up dummy request
          var req = new EventEmitter();
          req.query = {};
          server.handleEyeRequest(req, { header: function () {} });
          // abort request
          req.emit('close');

          return true;
        },
        'should cancel Eye': function () {
          should.exist(canceled);
        }
      };
    })()
  }
}).export(module);

var eyeDummy = {
  execute: function (options, callback) {
    var path = options.originalUrl;
    delete options.originalUrl;
    this.options[path] = options;

    if (this.shouldSucceed[path])
      callback(null, 'out"put');
    else
      callback('err"or', null);

    return {};
  },
  options: {},
  shouldSucceed: {}
};

function respondsWith(status, contentType, description, executeArguments, method, output) {
  if (!method) {
    return {
      'using GET' : respondsWith(status, contentType, description, executeArguments, "GET"),
      'using POST': respondsWith(status, contentType, description, executeArguments, "POST")
    };
  }

  var path, form, shouldSucceed = (status >= 200 && status <= 299);
  var context = {
    topic: function () {
      var urlMatch = this.context.title.match(/(\/[^ ]*)(?: with form (.*))?/);
      path = urlMatch[1];
      form = urlMatch[2];
      eyeDummy.shouldSucceed[path] = shouldSucceed;
      request({ url: 'http://localhost:13705' + path,
                body: form,
                headers: { 'content-type': 'application/x-www-form-urlencoded' },
                method: method }, this.callback);
    }
  };

  context['should respond with status ' + status] = function (error, response, body) {
    response.statusCode.should.eql(status);
  };

  context['should respond with Content-Type ' + contentType] = function (error, response, body) {
    response.headers.should.have.property('content-type', contentType);
  };

  if (contentType !== 'application/javascript')
    context['should respond with Access-Control-Allow-Origin *'] = function (error, response, body) {
      response.headers.should.have.property('access-control-allow-origin', '*');
    };

  if (shouldSucceed)
    context['should return the Eye output'] = function (error, response, body) {
      body.should.eql(output || 'out"put\n');
    };
  else
    context['should return the Eye error'] = function (error, response, body) {
      body.should.eql(output || 'err"or\n');
    };

  context['should execute Eye ' + description] = function (error, response, body) {
    eyeDummy.options[path].should.eql(executeArguments);
  };

  return context;
}


text:
package cn.socialclock.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.Calendar;

import cn.socialclock.manager.SocialClockManager;
import cn.socialclock.model.ClockSettings;
import cn.socialclock.ui.AlarmPopActivity;
import cn.socialclock.utils.ConstantData;
import cn.socialclock.utils.DatetimeFormatter;
import cn.socialclock.utils.SocialClockLogger;

/**
 * @author mapler
 *  Alarm Receiver
 *  if today is alarm weekday or alarm is a snooze type
 *  then do alarm
 *  else create next alarm
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        SocialClockLogger.log("AlarmReceiver: onReceive start");

        ClockSettings clockSettings = new ClockSettings(context);

        int alarmType = intent.getIntExtra(ConstantData.BundleArgsName.ALARM_TYPE,
                ConstantData.AlarmType.ALARM_NORMAL);
        String alarmEventId = intent.getStringExtra(ConstantData.BundleArgsName.ALARM_EVENT_ID);

        Calendar now = Calendar.getInstance();

        int weekdayId = now.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
        SocialClockLogger.log("AlarmReceiver: todayOfWeek = " + weekdayId);

        if ((alarmType == ConstantData.AlarmType.ALARM_SNOOZE)
                || (clockSettings.isWeekdayEnable(weekdayId))) {
            /* if today is alarm weekday or alarm is a snooze type then do alarm */
            SocialClockLogger.log("AlarmReceiver: alarmed at " + DatetimeFormatter.calendarToString(now));

            /* start alarm popup activity */
            Intent popupIntent = new Intent(context, AlarmPopActivity.class);
            popupIntent.putExtra(ConstantData.BundleArgsName.ALARM_TYPE, alarmType);
            popupIntent.putExtra(ConstantData.BundleArgsName.ALARM_EVENT_ID, alarmEventId);
            popupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            context.startActivity(popupIntent);
        } else {
            /* else start next alarm */
            SocialClockLogger.log("AlarmReceiver: silence day, " + DatetimeFormatter.calendarToString(now));
            SocialClockManager socialClockManager = new SocialClockManager(context);
            // cancel current Alarm Event
            socialClockManager.cancelAlarm();
            // create next Alarm
            socialClockManager.createAlarm();
        }
    }
}


text:
Considering contributing to nannou? Awesome! Hopefully this section can guide
you in the right direction.

- [**About the Codebase**](./contributing/about-the-codebase.md)
- [**PR Checklist**](./contributing/pr-checklist.md)
- [**PR Reviews**](./contributing/pr-reviews.md)
- [**Publishing New Versions**](./contributing/publishing-new-versions.md)

## Still have questions?

Remember, if you are still unsure about anything, you probably are not the only
one! Feel free to [open an issue][issue-tracker] with your question.

[issue-tracker]: https://github.com/nannou-org/nannou/issues


text:
<?php

namespace EBT\GeoZipLocation\Tests\Translator\PT\Repository;

use EBT\GeoZipLocation\Core\TranslatorFactory;
use EBT\GeoZipLocation\Translator\PT\Repository\RegionRepository;
use PHPUnit_Framework_TestCase;

/**
 * Class TranslatorFactoryTest
 */
class RegionRepositoryTest extends PHPUnit_Framework_TestCase
{
    /**
     * testGetType
     */
    public function testGetType()
    {
        $r = new RegionRepository();
        $this->assertEquals('region', $r->getType());
    }

    /**
     * testGetAll
     */
    public function testGetAll()
    {
        $r = new RegionRepository();
        $this->assertContainsOnlyInstancesOf('EBT\GeoZipLocation\Translator\PT\Location\Region', $r->getAll());
    }
}


text:
name: "\U0001F41BBug report"
about: Something is wrong with Redux.
---

**Do you want to request a _feature_ or report a _bug_?**

(If this is a _usage question_, please **do not post it here**—post it on [Stack Overflow](http://stackoverflow.com/questions/tagged/redux) instead. If this is not a "feature" or a "bug", or the phrase "How do I...?" applies, then it's probably a usage question.)

**What is the current behavior?**

**If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar.**

**What is the expected behavior?**

**Which versions of Redux, and which browser and OS are affected by this issue? Did this work in previous versions of Redux?**


text:
package io.vitess.jdbc;

import io.vitess.util.Constants;
import io.vitess.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * VitessJDBCUrl is responsible for parsing a driver URL and Properties object, returning a new
 * Properties object with configuration from the URL and passed in Properties merged.
 *

 * Parameters passed in through the Properties object take precedence over the parameters in the
 * URL, where there are conflicts.
 *

 * The Passed in URL is expected to conform to the following basic format:
 *

 * jdbc:vitess://username:password@ip1:port1,ip2:port2/keyspace/catalog?property1=value1..
 */
public class VitessJDBCUrl {

  private final String url;
  private final List<HostInfo> hostInfos;
  private final Properties info;

  /*
   Assuming List of vtGate ips could be given in url, separated by ","
  */
  public static class HostInfo {

    private String hostname;
    private int port;

    public HostInfo(String hostname, int port) {
      this.hostname = hostname;
      this.port = port;
    }

    public String getHostname() {
      return hostname;
    }

    public int getPort() {
      return port;
    }

    @Override
    public String toString() {
      return hostname + ":" + port;
    }
  }

  /**
   *
Create VitessJDBC url object for given urls and properties.

   *

   *
To indicate that SSL should be used, URL's follow the MySQL and MariaDB convention of
   * including the property useSSL=true.  To use a keyStore and trustStore other than
   * the JRE default, you can add the following URL properties:

   *

   *

   *

   *
keyStore=path_to_keystore_file

   *
keyStorePassword=password (if set)

   *
keyPassword=password (only needed if the private key password differs from
   * the keyStore password)

   *
keyAlias=alias_under_which_private_key_is_stored (if not set, then the
   * first valid PrivateKeyEntry found in the keyStore will be used)

   *
trustStore=path_to_truststore_file

   *
trustStorePassword=password (if set)

   *
trustAlias=alias_under_which_certificate_chain_is_stored (if not set,
   * then the first valid X509Certificate found in the trustStore will be used)

   *

   *

   *

   *
If useSSL=true, and any of these additional properties are not set on the JDBC
   * URL, then the driver will look to see if these corresponding property was set at JVM startup
   * time:

   *

   *

   *

   *
-Djavax.net.ssl.keyStore

   *
-Djavax.net.ssl.keyStorePassword

   *
-Djavax.net.ssl.keyPassword

   *
-Djavax.net.ssl.keyAlias

   *
-Djavax.net.ssl.trustStore

   *
-Djavax.net.ssl.trustStorePassword

   *
-Djavax.net.ssl.trustStoreAlias

   *

   *

   *

   *
See:

   *
https://mariadb.com/kb/en/mariadb/about-mariadb-connector-j/#tls-ssl

   *
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-using-ssl.html

   */
  public VitessJDBCUrl(String url, Properties info) throws SQLException {

    /* URL pattern e.g. jdbc:vitess://username:password@ip1:port1,ip2:port2/keyspace/catalog?
    property1=value1..
    m.group(1) = "vitess"
    m.group(2) = "username:password@"
    m.group(3) = "username"
    m.group(4) = ":password"
    m.group(5) = "password"
    m.group(6) = "ip1:port1,ip2:port2"
    m.group(7) = "/keyspace"
    m.group(8) = "keyspace"
    m.group(9) = "/catalog"
    m.group(10) = "catalog"
    m.group(11) = "?property1=value1.."
    m.group(12) = "property1=value1.."
    */

    final Pattern p = Pattern.compile(Constants.URL_PATTERN);
    final Matcher m = p.matcher(url);
    if (!m.find()) {
      throw new SQLException(Constants.SQLExceptionMessages.MALFORMED_URL);
    }

    info = getURLParamProperties(m.group(12), info);

    // Will add password property once its supported from vitess
    // this.password = (m.group(5) == null ? info.getProperty("password") : m.group(5));
    String postUrl = m.group(6);
    if (null == postUrl) {
      throw new SQLException(Constants.SQLExceptionMessages.MALFORMED_URL);
    }

    this.hostInfos = getURLHostInfos(postUrl);
    this.url = url;

    // For Backward Compatibility of username in connection url.
    String userName = m.group(3);
    if (!StringUtils.isNullOrEmptyWithoutWS(userName)) {
      info.setProperty(Constants.Property.USERNAME, userName);
    }

    // For Backward Compatibility of keyspace & catalog/database/schema name in connection url.
    String keyspace = m.group(8);
    if (!StringUtils.isNullOrEmptyWithoutWS(keyspace)) {
      info.setProperty(Constants.Property.KEYSPACE, keyspace);
      String catalog = m.group(10);
      if (!StringUtils.isNullOrEmptyWithoutWS(catalog)) {
        info.setProperty(Constants.Property.DBNAME, catalog);
      } else {
        info.setProperty(Constants.Property.DBNAME, keyspace);
      }
    }

    // For Backward Compatibility of old tablet type.
    String oldTabletType = info.getProperty(Constants.Property.OLD_TABLET_TYPE);
    String tabletType = info.getProperty(Constants.Property.TABLET_TYPE);
    if (null != tabletType) {
      info.setProperty(Constants.Property.OLD_TABLET_TYPE, tabletType);
    } else if (null != oldTabletType) {
      info.setProperty(Constants.Property.TABLET_TYPE, oldTabletType);
    }

    this.info = info;
  }

  public String getUrl() {
    return url;
  }

  public List<HostInfo> getHostInfos() {
    return hostInfos;
  }

  /**
   * Get Properties object for params after ? in url.
   *
   * @param paramString Parameter String in the url
   * @param info passed in the connection
   * @return Properties updated with parameters
   */

  private static Properties getURLParamProperties(String paramString, Properties info)
      throws SQLException {
    // If passed in, don't use info properties directly so we don't act upon it accidentally.
    // instead use as defaults for a new properties object
    info = (info == null) ? new Properties() : new Properties(info);

    if (!StringUtils.isNullOrEmptyWithoutWS(paramString)) {
      StringTokenizer queryParams = new StringTokenizer(paramString, "&"); //$NON-NLS-1$
      while (queryParams.hasMoreTokens()) {
        String parameterValuePair = queryParams.nextToken();
        int indexOfEquals = parameterValuePair.indexOf('=');

        String parameter = null;
        String value = null;

        if (indexOfEquals != -1) {
          parameter = parameterValuePair.substring(0, indexOfEquals);

          if (indexOfEquals + 1 < parameterValuePair.length()) {
            value = parameterValuePair.substring(indexOfEquals + 1);
          }
        }

        // Per the mysql-connector-java docs, passed in Properties values should take precedence
        // over
        // those in the URL. See javadoc for NonRegisteringDriver#connect
        if ((null != value && value.length() > 0) && (parameter.length() > 0) && null == info
            .getProperty(parameter)) {
          try {
            info.put(parameter, URLDecoder.decode(value, "UTF-8"));
          } catch (UnsupportedEncodingException | NoSuchMethodError badEncoding) {
            throw new SQLException(Constants.SQLExceptionMessages.MALFORMED_URL);
          }
        }
      }
    }

    return info;
  }

  /**
   * Get List of Hosts for url separated by commas
   */
  private static List<HostInfo> getURLHostInfos(String hostURLs) throws SQLException {
    List<HostInfo> hostInfos = new ArrayList<>();

    StringTokenizer stringTokenizer = new StringTokenizer(hostURLs, ",");
    while (stringTokenizer.hasMoreTokens()) {
      String hostString = stringTokenizer.nextToken();
      /*
          pattern = ip:port
      */
      final Pattern p = Pattern.compile("([^/:]+):(\\d+)?");
      final Matcher m = p.matcher(hostString);
      if (!m.find()) {
        throw new SQLException(Constants.SQLExceptionMessages.MALFORMED_URL);
      }
      String hostname = m.group(1);
      int port;
      if (m.group(2) != null) {
        port = Integer.parseInt(m.group(2));
      } else {
        port = Integer.parseInt(Constants.DEFAULT_PORT);
      }
      HostInfo hostInfo = new HostInfo(hostname, port);
      hostInfos.add(hostInfo);
    }
    if (hostInfos.size() == 0) {
      throw new SQLException(Constants.SQLExceptionMessages.MALFORMED_URL);
    }
    return hostInfos;
  }

  public Properties getProperties() {
    return info;
  }
}


text:
package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

type Recurlyservers struct {
	XMLName     xml.Name `xml:"servers"`
	Version     string   `xml:"version,attr"`
	Svs         []server `xml:"server"`
	Description string   `xml:",innerxml"`
}
type server struct {
	XMLName    xml.Name `xml:"server"`
	ServerName string   `xml:"serverName"`
	ServerIP   string   `xml:"serverIP"`
}

func main() {
	file, err := os.Open("servers.xml") // For read access.
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}
	defer file.Close()
	data, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}
	v := Recurlyservers{}
	err = xml.Unmarshal(data, &v)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}
	fmt.Println(v)
}


text:
<?php
class NullModel extends Model {
	function getSQLTableName() {
		return "null";
	}
}


text:
package org.datavec.api.writable.comparator;

import org.datavec.api.writable.Writable;

public class IntWritableComparator implements WritableComparator {
    @Override
    public int compare(Writable o1, Writable o2) {
        return Integer.compare(o1.toInt(), o2.toInt());
    }

    @Override
    public String toString() {
        return "IntWritableComparator()";
    }
}


text:
![](https://raw.githubusercontent.com/bgilham/Bixlet/develop/ReadMeIcon.png)

# Bixlet [![Build Status](https://travis-ci.org/bgilham/Bixlet.svg?branch=develop)](https://travis-ci.org/bgilham/Bixlet) [![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/)

Bixlet is an open source iOS app, written in Swift, for monitoring the status of the 80 stations in Toronto's [bike sharing](http://www.bikesharetoronto.com) system.

Follow the [@bixletapp](https://twitter.com/bixletapp) Twitter account for updates.

## Requirements
* iOS 9.2+
* Xcode 7.2
* Cocoapods

## Status
**The first version of the app is under active development.** As such, the default branch is currently set to `develop`. Once 1.0 is out the door, this repo will switch to showing the latest release on the `master` branch.

## Credits
* Bike icon by [Scott Lewis](https://thenounproject.com/iconify) from the [Noun Project](https://thenounproject.com).
* Contains information licensed under the [Open Government Licence – Toronto](http://www1.toronto.ca/wps/portal/contentonly?vgnextoid=4a37e03bb8d1e310VgnVCM10000071d60f89RCRD).

## About
Bixlet is maintained by [Brian Gilham](http://twitter.com/bgilham).


text:
package org.kuali.rice.ksb.messaging.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.RequestProcessor;
import org.kuali.rice.krad.UserSession;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADUtils;

/**
 * A RequestProcessor implementation for Struts which handles determining whether or not access
 * should be allowed to the requested KSB page.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class KSBStrutsRequestProcessor extends RequestProcessor {

	/**
	 * This overridden method ...
	 *
	 * @see org.apache.struts.action.RequestProcessor#processPreprocess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected boolean processPreprocess(HttpServletRequest request,
			HttpServletResponse response) {
		final UserSession session = KRADUtils.getUserSessionFromRequest(request);

        if (session == null) {
            throw new IllegalStateException("the user session has not been established");
        }

        GlobalVariables.setUserSession(session);
        GlobalVariables.clear();
		return super.processPreprocess(request, response);
	}
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\AopBundle\JMSAopBundle(),
            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            new Dirigendo\FrontEndBundle\DirigendoFrontEndBundle(),
            new APY\JsFormValidationBundle\APYJsFormValidationBundle(),
            new Bazinga\ExposeTranslationBundle\BazingaExposeTranslationBundle(),
            new Neutron\FormBundle\NeutronFormBundle(),
            new Neutron\DataGridBundle\NeutronDataGridBundle()

        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package de.tblsoft.solr.crawl;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.ArrayList;
import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Breadcrumb {

    private String selector;

    private List<BreadcrumbEntry> breadcrumbs;

    public String getSelector() {
        return selector;
    }

    public void setSelector(String selector) {
        this.selector = selector;
    }

    public List<BreadcrumbEntry> getBreadcrumbs() {
        return breadcrumbs;
    }

    public void setBreadcrumbs(List<BreadcrumbEntry> breadcrumbs) {
        this.breadcrumbs = breadcrumbs;
    }

    public void addBreadcrumbEntry(BreadcrumbEntry breadcrumbEntry) {
        if(this.breadcrumbs == null) {
            this.breadcrumbs = new ArrayList<>();
        }
        this.breadcrumbs.add(breadcrumbEntry);
    }
}


text:
/**
 * Header component for the grid system
 *
 * @mdoule ng.grid
 * @ngdirective nagGridHeader
 *
 * @nghtmlattribute {empty} nag-grid-header Tell AngularJS this element is a grid header component
 */
angular.module('nag.grid')
.directive('nagGridHeader', [
  '$compile',
  '$http',
  '$templateCache',
  'nagHelper',
  'nagDefaults',
  function($compile, $http, $templateCache, nagHelper, nagDefaults) {
    var ngCell = {
      restrict: 'A',
      compile: function() {
        return {
          pre: function(scope, element) {
            var template = nagHelper.getTemplatePath('grid', 'header');
            $(element).addClass('grid-header');

            var html = nagHelper.getAsyncTemplate(template, scope.options);
            element.append($compile(html)(scope));
          }
        };
      }
    };
    return ngCell;
  }
]);


text:
import sys, subprocess
from collections import defaultdict

def get_fasta (index="/home/galaxy/galaxy-dist/bowtie/5.37_Dmel/5.37_Dmel"): # here one must supply the exact base path for the library in galaxy environment
  p = subprocess.Popen(args=["bowtie-inspect","-a", "0", index], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  outputlines = p.stdout.readlines()
  p.wait()
  miR_sequence_liste = {}
  for line in outputlines:
    if line[0] == ">":
      miR_name = line[1:-1].split()[0]
    else:
      miR_sequence_liste[miR_name] = line[:-1]
  return miR_sequence_liste

class Mirna:

  def __init__(self, name, sequence):
    self.name = name
    self.sequence = sequence
    self.matched_reads = []
    self.dicmap = {}

  def addread (self, offset, size):
    #method to add reads to the object
    self.matched_reads.append( (offset, size) )
    self.dicmap[(offset, size)] = self.dicmap.get((offset, size), 0) + 1
    return

  def mircount (self):
    #method to return the raw counts
    return len(self.matched_reads)

  def density (self):
    '''method to output the read coverage by position in the mir'''
    map = [0 for i in range (len(self.sequence))]
    for offset, size in self.dicmap:
      for i in range (offset, offset+size):
        map[i] += self.dicmap[(offset,size)]
    return map

  def normalized_density (self):
    map = self.density ()
    maximum = float (max (map) ) or 1
    length = float (len (map) ) or 1
    Total_NoR = self.mircount()
    output = ["mir\tcoordinate\tdensity\tNoR"]
    for i, D in enumerate (map):
      output.append("%s\t%s\t%s\t%s" % (self.name, (i+1)/length, D/maximum, Total_NoR))
    return "\n".join(output)

  def hitmap (self):
    #method to output the reads above the premir
    output = []
    output.append (self.name)
    output.append ( "%s\t%s\t%s\t%s" % (self.sequence, "offset", "size", "num reads") )
    for pos_size in sorted(self.dicmap):
      seq = self.sequence[ pos_size[0] : pos_size[0]+pos_size[1] ]
      output.append ("%s%s%s\t%s\t%s\t%s" % ("."*len(self.sequence[:pos_size[0]]), seq, "."*len(self.sequence[pos_size[0]+pos_size[1]:]), pos_size[0]+1, pos_size[1], self.dicmap[pos_size] ) ) #attention pos_size[0]+1 because 1-based offset for biologists
    return "\n".join(output)

  def splitcount (self, shift):
    #method to assign counts to 5p and 3p parts
    median = len(self.sequence)/2
    splitsite = 0
    scores = []
    for i in range(median-shift, median+shift+1):
      countsum = 0
      for pos_size in self.dicmap:
        if pos_size[0] <= i <= pos_size[0]+pos_size[1]-1: continue
        else: countsum = countsum + self.dicmap[pos_size]
      scores.append(countsum)
    firstmax = scores.index(max(scores))
    scores.reverse()
    lastmax = scores.index(max(scores))
    scores.reverse()
    split_selected = firstmax + len(scores[firstmax:-lastmax])/2 + median - shift
    mir5p = 0
    mir3p = 0
    for pos_size in self.dicmap:
      if pos_size[0] <= split_selected <= pos_size[0]+pos_size[1]-1: continue
      elif split_selected <= pos_size[0]: mir3p = mir3p + self.dicmap[pos_size]
      else : mir5p = mir5p + self.dicmap[pos_size]
    return  "%s_5p\t%s\n%s_3p\t%s" % (self.name, mir5p, self.name, mir3p)

  def splitcount_2 (self, shift):
    #new method to assign counts to 5p and 3p parts, base on density map
    density_map = self.density()
    median = len(self.sequence)/2
    minimum = 0
    densitydic = dict ([(i, density) for i, density in enumerate (density_map) if median-shift<= i <= median+shift ])
    revdic = dict(map(lambda item: (item[1],item[0]),densitydic.items()))
    mindensity_offset = revdic[min(revdic.keys())]
    mir5p = 0
    mir3p = 0
    for pos_size in self.dicmap:
      if mindensity_offset in range (pos_size[0], pos_size[0]+pos_size[1]): continue
#      if pos_size[0] <= mindensity_offset <= pos_size[0]+pos_size[1]-1: continue
      if mindensity_offset <= pos_size[0]: mir3p = mir3p + self.dicmap[pos_size]
      else : mir5p = mir5p + self.dicmap[pos_size]
    return  "%s_5p\t%s\n%s_3p\t%s" % (self.name, mir5p, self.name, mir3p)

mirdict = get_fasta (sys.argv[2])
dicobject = {}
for mir in mirdict:
  dicobject[mir] = Mirna(mir, mirdict[mir])

F = open (sys.argv[1], "r")
for line in F:
  fields = line.split()
  name = fields[1]
  offset= int(fields[2])
  sequence= fields[3]
  dicobject[name].addread(offset, len(sequence))
F.close()

F = open (sys.argv[4], "w")
for mir in sorted(dicobject):
  print >> F, dicobject[mir].hitmap()
  for i, counts in enumerate (dicobject[mir].density()):
    print >> F, "%s\t%s" % (i+1, counts) # attention 1-based offset for biologists
  print >> F
  print >> F, dicobject[mir].normalized_density()
F.close()

F = open (sys.argv[5], "w")
print >> F, "gene\t%s" % sys.argv[3]
for mir in sorted(dicobject):
  print >> F, dicobject[mir].splitcount_2(15)


text:
*Did you know* Mocha [is a dependency of over 100,000 projects](https://libraries.io/npm/mocha) published to npm alone?

**Despite this, we're currently unable to merge most pull requests due to lack of maintenance resources.**

**Are you interested in triaging issues or reviewing open PRs?  Have some time to hack on its codebase?**  If you would like to help maintain Mocha, please contact `@boneskull` on [Gitter](https://gitter.im/mochajs/mocha).

*Thank you* :kissing_heart: to all of you interested in helping.  These are Mocha's immediate needs:

1. Increase test coverage on Node.js and browser
  - Increase integration coverage for all reporters
    - `html` reporter must be tested in browser
    - Basic console reporters (*not* `nyan`, `landing`, etc.) must be tested in **both** browser and Node.js contexts; PhantomJS can consume all console reporters
    - Filesystem-based reporters must be tested in Node.js context
  - Increase coverage against all interfaces (`exports` in particular).  Ideally this becomes a "matrix" where we repeat sets of integration tests across all interfaces.
  - Refactor non-Node.js-specific tests to allow them to run in a browser context.  Node.js-specific tests include those which *require* the CLI or filesystem.  Most everything else is fair game.
2.  Review current open pull requests
  - We need individuals familiar with Mocha's codebase. Got questions?  Ask them in [our chat room](https://gitter.im/mochajs/mocha).
  - Pull requests **must** have supporting tests.  The only exceptions are pure cosmetic or non-functional changes.
  - Pull request contributors must sign the CLA.
3. Close old, inactive issues and pull requests
  - A bot should do this.  We need a bot. Got a bot?
4. Triage issues
  - If we run into "critical" bugs, they need fixing.
  - "Critical" means Mocha is broken w/o workarounds for a *large percentage* of users
  - Otherwise: respond to issues, close new dupe issues, confirm bugs, ask for more info, etc.

Once we gain ground on the above items, we can work together formalize our contribution guidelines and governance.  For further info & ideas, please see our [projects](https://github.com/mochajs/mocha/projects/).

*You needn't be a maintainer to submit a pull request for test coverage!*

-- @boneskull, *Jan 17 2016*

[![Build Status](https://api.travis-ci.org/mochajs/mocha.svg?branch=master)](http://travis-ci.org/mochajs/mocha)
[![Coverage Status](https://coveralls.io/repos/github/mochajs/mocha/badge.svg)](https://coveralls.io/github/mochajs/mocha)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mochajs/mocha?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![OpenCollective](https://opencollective.com/mochajs/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/mochajs/sponsors/badge.svg)](#sponsors)

  Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser. For more information view the [documentation](http://mochajs.org).

## Links

  - [Changelog](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md)
  - [Google Group](http://groups.google.com/group/mochajs)
  - [Wiki](https://github.com/mochajs/mocha/wiki)
  - Mocha [Extensions and reporters](https://github.com/mochajs/mocha/wiki)

## Backers

[Become a backer]((https://opencollective.com/mochajs#backer)) and show your support to our open source project.

## Sponsors

Does your company use Mocha?  Ask your manager or marketing team if your company would be interested in supporting our project.  Support will allow the maintainers to dedicate more time for maintenance and new features for everyone.  Also, your company's logo will show [on GitHub](https://github.com/mochajs/mocha#readme) and on [our site](https://mochajs.org)--who doesn't want a little extra exposure?  [Here's the info](https://opencollective.com/mochajs#sponsor).

## License

[MIT](LICENSE)


text:
<?php

class Document_Tag_Area extends Document_Tag {

    /**
     * @see Document_Tag_Interface::getType
     * @return string
     */
    public function getType() {
        return "area";
    }

    /**
     * @see Document_Tag_Interface::getData
     * @return mixed
     */
    public function getData() {
        return null;
    }

    /**
     * @see Document_Tag_Interface::admin
     */
    public function admin() {
        // get configuration data for admin
        if (method_exists($this, "getDataEditmode")) {
            $data = $this->getDataEditmode();
        }
        else {
            $data = $this->getData();
        }

        $options = array(
            "options" => $this->getOptions(),
            "data" => $data,
            "name" => $this->getName(),
            "id" => "pimcore_editable_" . $this->getName(),
            "type" => $this->getType(),
            "inherited" => $this->getInherited()
        );
        $options = @Zend_Json::encode($options, false, array('enableJsonExprFinder' => true));

        if($this->editmode) {
            echo '

getName() . '" class="pimcore_editable pimcore_tag_' . $this->getType() . '">
            ';
        }

        $this->frontend();

        if($this->editmode) {
            echo '
';
        }

    }

    /**
     * @see Document_Tag_Interface::frontend
     */
    public function frontend() {

        $count = 0;

        $this->setupStaticEnvironment();
        $suffixes = Zend_Registry::get("pimcore_tag_block_current");
        $suffixes[] = $this->getName();
        Zend_Registry::set("pimcore_tag_block_current", $suffixes);

        $options = $this->getOptions();

        $this->current = $count;

        // don't show disabled bricks
        if(!Pimcore_ExtensionManager::isEnabled("brick", $options["type"]) && $options['dontCheckEnabled'] != true) {
            return;
        }

        // create info object and assign it to the view
        $info = null;
        try {
            $info = new Document_Tag_Area_Info();
            $info->setId($options["type"]);
            $info->setIndex($count);
            $info->setPath(str_replace(PIMCORE_DOCUMENT_ROOT, "", Pimcore_ExtensionManager::getPathForExtension($options["type"],"brick")));
            $info->setConfig(Pimcore_ExtensionManager::getBrickConfig($options["type"]));
        } catch (Exception $e) {
            $info = null;
        }

        $suffixes = Zend_Registry::get("pimcore_tag_block_numeration");
        $suffixes[] = 1;
        Zend_Registry::set("pimcore_tag_block_numeration", $suffixes);

        if($this->getView() instanceof Zend_View) {

            $this->getView()->brick = $info;
            $areas = $this->getAreaDirs();

            $view = $areas[$options["type"]] . "/view.php";
            $action = $areas[$options["type"]] . "/action.php";
            $edit = $areas[$options["type"]] . "/edit.php";
            $options = $this->getOptions();
            $params = array();
            if(is_array($options["params"]) && array_key_exists($options["type"], $options["params"])) {
                if(is_array($options["params"][$options["type"]])) {
                    $params = $options["params"][$options["type"]];
                }
            }

            // assign parameters to view
            foreach ($params as $key => $value) {
                $this->getView()->assign($key, $value);
            }

            // check for action file
            if(is_file($action)) {
                include_once($action);

                $actionClassname = "Document_Tag_Area_" . ucfirst($options["type"]);
                if(Pimcore_Tool::classExists($actionClassname)) {
                    $actionObject = new $actionClassname();

                    if($actionObject instanceof Document_Tag_Area_Abstract) {
                        $actionObject->setView($this->getView());

                        $areaConfig = new Zend_Config_Xml($areas[$options["type"]] . "/area.xml");
                        $actionObject->setConfig($areaConfig);

                        // params
                        $params = array_merge($this->view->getAllParams(), $params);
                        $actionObject->setParams($params);

                        if($info) {
                            $actionObject->setBrick($info);
                        }

                        if(method_exists($actionObject,"action")) {
                            $actionObject->action();
                        }

                        $this->getView()->assign('actionObject',$actionObject);
                    }
                }
            }

            if(is_file($view)) {
                $editmode = $this->getView()->editmode;

                if(method_exists($actionObject,"getBrickHtmlTagOpen")) {
                    echo $actionObject->getBrickHtmlTagOpen($this);
                }else{
                    echo '
';
                }

                if(is_file($edit) && $editmode) {
                    echo '

';

                    // forces the editmode in view.php independent if there's an edit.php or not
                    if(!array_key_exists("forceEditInView",$params) || !$params["forceEditInView"]) {
                        $this->getView()->editmode = false;
                    }
                }

                $this->getView()->template($view);

                if(is_file($edit) && $editmode) {
                    $this->getView()->editmode = true;

                    echo '
';
                    $this->getView()->template($edit);
                    echo '
';
                }

                if(method_exists($actionObject,"getBrickHtmlTagClose")) {
                    echo $actionObject->getBrickHtmlTagClose($this);
                }else{
                    echo '
';
                }

                if(is_object($actionObject) && method_exists($actionObject,"postRenderAction")) {
                    $actionObject->postRenderAction();
                }
            }
        }

        $suffixes = Zend_Registry::get("pimcore_tag_block_numeration");
        array_pop($suffixes);
        Zend_Registry::set("pimcore_tag_block_numeration", $suffixes);

        $suffixes = Zend_Registry::get("pimcore_tag_block_current");
        array_pop($suffixes);
        Zend_Registry::set("pimcore_tag_block_current", $suffixes);
    }

    /**
     * @see Document_Tag_Interface::setDataFromResource
     * @param mixed $data
     * @return void
     */
    public function setDataFromResource($data) {
        return $this;
    }

    /**
     * @see Document_Tag_Interface::setDataFromEditmode
     * @param mixed $data
     * @return void
     */
    public function setDataFromEditmode($data) {
        return $this;
    }

    /**
     * Setup some settings that are needed for blocks
     *
     * @return void
     */
    public function setupStaticEnvironment() {

        // setup static environment for blocks
        if(Zend_Registry::isRegistered("pimcore_tag_block_current")) {
            $current = Zend_Registry::get("pimcore_tag_block_current");
            if (!is_array($current)) {
                $current = array();
            }
        } else {
            $current = array();
        }

        if(Zend_Registry::isRegistered("pimcore_tag_block_numeration")) {
            $numeration = Zend_Registry::get("pimcore_tag_block_numeration");
            if (!is_array($numeration)) {
                $numeration = array();
            }
        } else {
            $numeration = array();
        }

        Zend_Registry::set("pimcore_tag_block_numeration", $numeration);
        Zend_Registry::set("pimcore_tag_block_current", $current);

    }

    /**
     * @return bool
     */
    public function isEmpty () {
        return false;
    }

    /**
     * @return array
     */
    public function getAreaDirs () {
        return Pimcore_ExtensionManager::getBrickDirectories();
    }

    public function getBrickConfigs() {
        return Pimcore_ExtensionManager::getBrickConfigs();
    }
}