text:
package com.google.template.soy.exprparse;

import static com.google.common.truth.Truth.assertThat;
import static com.google.template.soy.exprparse.ExpressionSubject.assertThatExpression;

import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.exprtree.BooleanNode;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.exprtree.ExprNode.OperatorNode;
import com.google.template.soy.exprtree.FieldAccessNode;
import com.google.template.soy.exprtree.FloatNode;
import com.google.template.soy.exprtree.FunctionNode;
import com.google.template.soy.exprtree.GlobalNode;
import com.google.template.soy.exprtree.IntegerNode;
import com.google.template.soy.exprtree.ItemAccessNode;
import com.google.template.soy.exprtree.ListLiteralNode;
import com.google.template.soy.exprtree.MapLiteralNode;
import com.google.template.soy.exprtree.NullNode;
import com.google.template.soy.exprtree.Operator;
import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode;
import com.google.template.soy.exprtree.OperatorNodes.EqualOpNode;
import com.google.template.soy.exprtree.OperatorNodes.MinusOpNode;
import com.google.template.soy.exprtree.OperatorNodes.NegativeOpNode;
import com.google.template.soy.exprtree.OperatorNodes.NotOpNode;
import com.google.template.soy.exprtree.OperatorNodes.NullCoalescingOpNode;
import com.google.template.soy.exprtree.OperatorNodes.OrOpNode;
import com.google.template.soy.exprtree.OperatorNodes.PlusOpNode;
import com.google.template.soy.exprtree.OperatorNodes.TimesOpNode;
import com.google.template.soy.exprtree.StringNode;
import com.google.template.soy.exprtree.VarRefNode;

import junit.framework.TestCase;

import java.util.List;

/**
 * Unit tests for the Soy expression parser.
 *
 */
public class ExpressionParserTest extends TestCase {

  public void testRecognizeVariable() {
    String[] vars = {"$aaa", "$_", "$a0b1_"};
    for (String var : vars) {
      assertThatExpression(var).isValidVar();
    }

    String[] nonVars = {"$", "$1", "$ aaa", "aaa", "$ij", "$ij.aaa"};
    for (String nonVar : nonVars) {
      assertThatExpression(nonVar).isNotValidVar();
    }
  }

  public void testRecognizeDataReference() {
    String[] dataRefs =
        {"$aaa", "$ij.aaa", "$a0a0.b1b1", "$aaa[0].bbb[12]", "$aaa[0].bbb['ccc'][$eee]",
         "$aaa?.bbb", "$aaa.bbb?[0]?.ccc?['ddd']", "$ij.aaa",
         "$aaa [1] [2] .bbb [ 3 + 4 ]['ccc']. ddd [$eee * $fff]",
         "functionCall($arg).field",
         "['a' : 'b'].a"};
    for (String dataRef : dataRefs) {
      assertThatExpression(dataRef).isValidExpression();
    }

    String[] nonDataRefs =
        {"$", "$ aaa", "1aaa", "$1a1a", "$0", "$[12]", "$[$aaa]", "$aaa[]", "$ij[4]", "$aaa.?bbb"};
    for (String nonDataRef : nonDataRefs) {
      assertThatExpression(nonDataRef).isNotValidExpression();
    }
  }

  public void testRecognizeGlobal() {
    String[] globals = {"aaa", "aaa.bbb.CCC", "a22 . b88_"};
    for (String global : globals) {
      assertThatExpression(global).isValidGlobal();
    }

    String[] nonGlobals = {"$aaa", "1a1a", "aaa.1a1a", "22", "aaa[33]", "aaa[bbb]", "aaa['bbb']"};
    for (String nonGlobal : nonGlobals) {
      assertThatExpression(nonGlobal).isNotValidGlobal();
    }
  }

  public void testRecognizePrimitives() {
    // Null
    assertThatExpression("null").isValidExpression();
    // Boolean.
    assertThatExpression("true").isValidExpression();
    assertThatExpression("false").isValidExpression();
    // Integer. (Note the negative sign is actually parsed as the unary "-" operator.)
    assertThatExpression("0").isValidExpression();
    assertThatExpression("00").isValidExpression();
    assertThatExpression("26").isValidExpression();
    assertThatExpression("-729").isValidExpression();
    assertThatExpression("1234567890").isValidExpression();
    assertThatExpression("0x0").isValidExpression();
    assertThatExpression("0x1A2B").isValidExpression();
    assertThatExpression("-0xCAFE88").isValidExpression();

    assertThatExpression("0x1a2b").isNotValidExpression();
    assertThatExpression("-0xcafe88").isNotValidExpression();

    // Float. (Note the negative sign is actually parsed as the unary "-" operator.)
    assertThatExpression("0.0").isValidExpression();
    assertThatExpression("3.14159").isValidExpression();
    assertThatExpression("-20.0").isValidExpression();
    assertThatExpression("6.02e23").isValidExpression();
    assertThatExpression("3e3").isValidExpression();
    assertThatExpression("3e+3").isValidExpression();
    assertThatExpression("-3e-3").isValidExpression();

    assertThatExpression("0.").isNotValidExpression();
    assertThatExpression(".0").isNotValidExpression();
    assertThatExpression("-20.").isNotValidExpression();
    assertThatExpression(".14159").isNotValidExpression();
    assertThatExpression("6.02E23").isNotValidExpression();
    assertThatExpression("-3E-3").isNotValidExpression();

    // String.
    assertThatExpression("''").isValidExpression();
    assertThatExpression("'abc'").isValidExpression();
    assertThatExpression("'\\\\ \\' \\\" \\n \\r \\t \\b \\f  \\u00A9 \\u2468'").isValidExpression();

    assertThatExpression("'\\xA9'").isNotValidExpression();
    assertThatExpression("'\\077'").isNotValidExpression();
    assertThatExpression("\"\"").isNotValidExpression();
    assertThatExpression("\"abc\"").isNotValidExpression();
  }

  public void testRecognizeListsAndMaps() {
    assertThatExpression("[]").isValidExpression();
    assertThatExpression("[55]").isValidExpression();
    assertThatExpression("[55,]").isValidExpression();
    assertThatExpression("['blah', 123, $boo]").isValidExpression();
    assertThatExpression("['blah', 123, $boo,]").isValidExpression();

    assertThatExpression("[:]").isValidExpression();
    assertThatExpression("['aa': 55]").isValidExpression();
    assertThatExpression("['aa': 55,]").isValidExpression();
    assertThatExpression("['aaa': 'blah', 'bbb': 123, $foo.bar: $boo]").isValidExpression();
    assertThatExpression("['aaa': 'blah', 'bbb': 123, $foo.bar: $boo,]").isValidExpression();
  }

  public void testRecognizeDataRefAsExpression() {
    assertThatExpression("$aaa").isValidExpression();
    assertThatExpression("$a0a0.b1b1").isValidExpression();
    assertThatExpression("$aaa[0].bbb[12]").isValidExpression();
    assertThatExpression("$aaa[0].bbb['ccc'][$eee]").isValidExpression();
    assertThatExpression("$aaa [1] [2] .bbb [ 3 + 4 ]['ccc']. ddd [$eee * $fff]").isValidExpression();

    assertThatExpression("$").isNotValidExpression();
    assertThatExpression("$ aaa").isNotValidExpression();
    assertThatExpression("$1a1a").isNotValidExpression();
    assertThatExpression("$0").isNotValidExpression();
    assertThatExpression("$[12]").isNotValidExpression();
    assertThatExpression("$[$aaa]").isNotValidExpression();
    assertThatExpression("$aaa[]").isNotValidExpression();
  }

  public void testRecognizeGlobalAsExpression() {
    assertThatExpression("aaa").isValidExpression();
    assertThatExpression("aaa.bbb.CCC").isValidExpression();
    assertThatExpression("a22 . b88_").isValidExpression();

    assertThatExpression("1a1a").isNotValidExpression();
    assertThatExpression("aaa.1a1a").isNotValidExpression();
    // These used to be rejected by the parser, now they will be rejected by the type checker.
    assertThatExpression("aaa[33]").isValidExpression();
    assertThatExpression("aaa[bbb]").isValidExpression();
    assertThatExpression("aaa['bbb']").isValidExpression();
  }

  public void testRecognizeFunctionCall() {
    assertThatExpression("isFirst($x)").isValidExpression();
    assertThatExpression("isLast($y)").isValidExpression();
    assertThatExpression("index($z)").isValidExpression();
    assertThatExpression("randomInt()").isValidExpression();
    assertThatExpression("length($x.y.z)").isValidExpression();
    assertThatExpression("round(3.14159)").isValidExpression();
    assertThatExpression("round(3.14159, 2)").isValidExpression();
    assertThatExpression("floor(3.14)").isValidExpression();
    assertThatExpression("ceiling(-8)").isValidExpression();

    assertThatExpression("$isFirst()").isNotValidExpression();
    assertThatExpression("$boo.isFirst()").isNotValidExpression();
  }

  public void testRecognizeOperators() {

    // Level 8.
    assertThatExpression("- $a").isValidExpression();
    assertThatExpression("not true").isValidExpression();
    assertThatExpression("not$a").isValidExpression();
    assertThatExpression("+1").isNotValidExpression();
    assertThatExpression("!$a").isNotValidExpression();
    // Level 7.
    assertThatExpression("$a * $b").isValidExpression();
    assertThatExpression("5/3").isValidExpression();
    assertThatExpression("5 %$x").isValidExpression();
    assertThatExpression("$a * 4 / -7 % 2").isValidExpression();
    // Level 6.
    assertThatExpression("$a+$b").isValidExpression();
    assertThatExpression("7 - 12").isValidExpression();
    assertThatExpression(" - 3 + 4 - 5").isValidExpression();
    // Level 5.
    assertThatExpression("$a < 0xA00").isValidExpression();
    assertThatExpression("$a>$b").isValidExpression();
    assertThatExpression("3<=6").isValidExpression();
    assertThatExpression("7.5>= $c").isValidExpression();
    // Level 4.
    assertThatExpression("$a==0").isValidExpression();
    assertThatExpression("-10 != $b").isValidExpression();
    // Level 3.
    assertThatExpression("true and $b").isValidExpression();
    assertThatExpression("true && $b").isNotValidExpression();
    // Level 2.
    assertThatExpression("$a or null").isValidExpression();
    assertThatExpression("$a || null").isNotValidExpression();
    // Level 1.
    assertThatExpression("$boo?:-1").isValidExpression();
    assertThatExpression("$a ?: $b ?: $c").isValidExpression();
    assertThatExpression("false?4:-3").isValidExpression();
    assertThatExpression("$a ? $b : $c ? $d : $e").isValidExpression();
    // Parentheses.
    assertThatExpression("($a)").isValidExpression();
    assertThatExpression("( 4- $b *$c )").isValidExpression();
  }

  public void testRecognizeAdditional() {
    assertThatExpression("1+2*3-4/5<6==7>=-8%9+10").isValidExpression();
    assertThatExpression("((1+2)*((3)-4))/5<6==7>=-8%(9+10)").isValidExpression();
    assertThatExpression("$a and true or $b or $c and false and $d or $e").isValidExpression();
    assertThatExpression("$a and (true or $b) or ($c and false and ($d or $e))").isValidExpression();
    assertThatExpression("$a != 0 ? 33 : $b <= 4 ? 55 : $c ? 77 : $d").isValidExpression();
    assertThatExpression("( ( $a != 0 ? 33 : $b <= 4 ) ? 55 : $c ) ? 77 : $d").isValidExpression();
    assertThatExpression("round(3.14 + length($boo.foo)) != null").isValidExpression();
  }

  public void testRecognizeExpressionList() {
    assertThatExpression("$aaa, $bbb.ccc + 1, index($ddd)").isValidExpressionList();
    assertThatExpression("").isNotValidExpressionList();
    assertThatExpression("1, , 3").isNotValidExpressionList();
  }

  public void testParseVariable() {
    assertThatExpression("$boo").isValidVarNamed("boo");
  }

  public void testParseDataReference() throws Exception {

    SourceLocation loc = SourceLocation.UNKNOWN;

    ExprNode dataRef = assertThatExpression("$boo").isValidExpression();
    assertNodeEquals(
        new VarRefNode("boo", loc, false, null),
        dataRef);

    dataRef = assertThatExpression("$boo.foo").isValidExpression();
    assertNodeEquals(
        new FieldAccessNode(
            new VarRefNode("boo", loc, false, null),
            "foo",
            false),
        dataRef);

    dataRef = assertThatExpression("$boo[0][$foo]").isValidExpression();
    assertNodeEquals(
        new ItemAccessNode(
            new ItemAccessNode(
                new VarRefNode("boo", loc, false, null),
                new IntegerNode(0, loc),
                false),
            new VarRefNode("foo", loc, false, null),
            false),
        dataRef);

    dataRef = assertThatExpression("$boo?[0]?[$foo]").isValidExpression();
    assertNodeEquals(
        new ItemAccessNode(
            new ItemAccessNode(
                new VarRefNode("boo", loc, false, null),
                new IntegerNode(0, loc),
                true),
            new VarRefNode("foo", loc, false, null),
            true),
        dataRef);

    dataRef = assertThatExpression("$ij.boo?[0][$ij.foo]").isValidExpression();
    assertNodeEquals(
        new ItemAccessNode(
            new ItemAccessNode(
                new VarRefNode("boo", loc, true, null),
                new IntegerNode(0, loc),
                true),
            new VarRefNode("foo", loc, true, null),
            false),
        dataRef);
  }

  public void testParseGlobal() {
    assertThatExpression("MOO_2").isValidGlobalNamed("MOO_2");
    assertThatExpression("aaa.BBB").isValidGlobalNamed("aaa.BBB");
  }

  public void testParsePrimitives() throws Exception {

    ExprNode expr = assertThatExpression("null").isValidExpression();
    assertThat(expr).isInstanceOf(NullNode.class);

    expr = assertThatExpression("true").isValidExpression();
    assertThat(((BooleanNode) expr).getValue()).isTrue();

    expr = assertThatExpression("false").isValidExpression();
    assertThat(((BooleanNode) expr).getValue()).isFalse();

    expr = assertThatExpression("26").isValidExpression();
    assertThat(((IntegerNode) expr).getValue()).isEqualTo(26);

    expr = assertThatExpression("0xCAFE").isValidExpression();
    assertThat(((IntegerNode) expr).getValue()).isEqualTo(0xCAFE);

    expr = assertThatExpression("3.14").isValidExpression();
    assertThat(((FloatNode) expr).getValue()).isEqualTo(3.14);

    expr = assertThatExpression("3e-3").isValidExpression();
    assertThat(((FloatNode) expr).getValue()).isEqualTo(3e-3);

    expr = assertThatExpression("'Aa`! \\n \\r \\t \\\\ \\\' \"'").isValidExpression();
    assertThat(((StringNode) expr).getValue()).isEqualTo("Aa`! \n \r \t \\ \' \"");

    expr = assertThatExpression("'\\u2222 \\uEEEE \\u9EC4 \\u607A'").isValidExpression();
    assertThat(((StringNode) expr).getValue()).isEqualTo("\u2222 \uEEEE \u9EC4 \u607A");

    expr = assertThatExpression("'\u2222 \uEEEE \u9EC4 \u607A'").isValidExpression();
    assertThat(((StringNode) expr).getValue()).isEqualTo("\u2222 \uEEEE \u9EC4 \u607A");
  }

  public void testParseListsAndMaps() throws Exception {

    ExprNode expr = assertThatExpression("[]").isValidExpression();
    assertThat(((ListLiteralNode) expr).numChildren()).isEqualTo(0);
    expr = assertThatExpression("[55]").isValidExpression();
    assertThat(((ListLiteralNode) expr).numChildren()).isEqualTo(1);
    expr = assertThatExpression("[55,]").isValidExpression();
    assertThat(((ListLiteralNode) expr).numChildren()).isEqualTo(1);
    expr = assertThatExpression("['blah', 123, $boo]").isValidExpression();
    assertThat(((ListLiteralNode) expr).numChildren()).isEqualTo(3);
    expr = assertThatExpression("['blah', 123, $boo,]").isValidExpression();
    assertThat(((ListLiteralNode) expr).numChildren()).isEqualTo(3);

    expr = assertThatExpression("[:]").isValidExpression();
    assertThat(((MapLiteralNode) expr).numChildren()).isEqualTo(0);
    expr = assertThatExpression("['aa': 55]").isValidExpression();
    assertThat(((MapLiteralNode) expr).numChildren()).isEqualTo(2);
    expr = assertThatExpression("['aa': 55,]").isValidExpression();
    assertThat(((MapLiteralNode) expr).numChildren()).isEqualTo(2);
    expr = assertThatExpression("['aaa': 'blah', 'bbb': 123, $foo.bar: $boo]").isValidExpression();
    assertThat(((MapLiteralNode) expr).numChildren()).isEqualTo(6);
    expr = assertThatExpression("['aaa': 'blah', 'bbb': 123, $foo.bar: $boo,]").isValidExpression();
    assertThat(((MapLiteralNode) expr).numChildren()).isEqualTo(6);
  }

  public void testParseDataRefAsExpression() {
    assertThatExpression("$boo.foo").generatesASTWithRootOfType(FieldAccessNode.class);
  }

  public void testParseGlobalAsExpression() throws Exception {
    assertThatExpression("aaa.BBB").generatesASTWithRootOfType(GlobalNode.class);
  }

  public void testParseFunctionCall() throws Exception {

    ExprNode expr = assertThatExpression("isFirst($x)").isValidExpression();
    FunctionNode isFirstFn = (FunctionNode) expr;
    assertThat(isFirstFn.getFunctionName()).isEqualTo("isFirst");
    assertThat(isFirstFn.numChildren()).isEqualTo(1);
    assertThat(isFirstFn.getChild(0).toSourceString()).isEqualTo("$x");

    expr = assertThatExpression("round(3.14159, 2)").isValidExpression();
    FunctionNode roundFn = (FunctionNode) expr;
    assertThat(roundFn.getFunctionName()).isEqualTo("round");
    assertThat(roundFn.numChildren()).isEqualTo(2);
    assertThat(((FloatNode) roundFn.getChild(0)).getValue()).isEqualTo(3.14159);
    assertThat(((IntegerNode) roundFn.getChild(1)).getValue()).isEqualTo(2);
  }

  public void testParseOperators() throws Exception {
    ExprNode expr = assertThatExpression("-11").isValidExpression();
    NegativeOpNode negOp = (NegativeOpNode) expr;
    assertThat(((IntegerNode) negOp.getChild(0)).getValue()).isEqualTo(11);

    expr = assertThatExpression("not false").isValidExpression();
    NotOpNode notOp = (NotOpNode) expr;
    assertThat(((BooleanNode) notOp.getChild(0)).getValue()).isFalse();

    expr = assertThatExpression("90 -14.75").isValidExpression();
    MinusOpNode minusOp = (MinusOpNode) expr;
    assertThat(((IntegerNode) minusOp.getChild(0)).getValue()).isEqualTo(90);
    assertThat(((FloatNode) minusOp.getChild(1)).getValue()).isEqualTo(14.75);

    expr = assertThatExpression("$a or true").isValidExpression();
    OrOpNode orOp = (OrOpNode) expr;
    assertThat(orOp.getChild(0).toSourceString()).isEqualTo("$a");
    assertThat(((BooleanNode) orOp.getChild(1)).getValue()).isTrue();

    expr = assertThatExpression("$a ?: $b ?: $c").isValidExpression();
    NullCoalescingOpNode nullCoalOp0 = (NullCoalescingOpNode) expr;
    assertThat(nullCoalOp0.getChild(0).toSourceString()).isEqualTo("$a");
    NullCoalescingOpNode nullCoalOp1 = (NullCoalescingOpNode) nullCoalOp0.getChild(1);
    assertThat(nullCoalOp1.getChild(0).toSourceString()).isEqualTo("$b");
    assertThat(nullCoalOp1.getChild(1).toSourceString()).isEqualTo("$c");

    expr = assertThatExpression("$a?:$b==null?0*1:0x1").isValidExpression();
    NullCoalescingOpNode nullCoalOp = (NullCoalescingOpNode) expr;
    assertThat(nullCoalOp.getChild(0).toSourceString()).isEqualTo("$a");
    ConditionalOpNode condOp = (ConditionalOpNode) nullCoalOp.getChild(1);
    assertThat(condOp.getChild(0)).isInstanceOf(EqualOpNode.class);
    assertThat(condOp.getChild(1)).isInstanceOf(TimesOpNode.class);
    assertThat(condOp.getChild(2)).isInstanceOf(IntegerNode.class);
  }

  public void testParseExpressionList() throws Exception {
    List<ExprNode> exprList
        = assertThatExpression("$aaa, $bbb.ccc + 1, index($ddd)").isValidExpressionList();
    assertThat(exprList.get(0)).isInstanceOf(VarRefNode.class);
    assertThat(exprList.get(1)).isInstanceOf(PlusOpNode.class);
    assertThat(exprList.get(2)).isInstanceOf(FunctionNode.class);
  }

  public void testOperatorPrecedence() throws Exception {
    // + is left associative
    assertThat(precedenceString("1 + 2")).isEqualTo("1 + 2");
    assertThat(precedenceString("1 + 2 + 3")).isEqualTo("(1 + 2) + 3");
    assertThat(precedenceString("1 + 2 + 3 + 4 + 5 + 6"))
        .isEqualTo("((((1 + 2) + 3) + 4) + 5) + 6");

    // ?: is right associative
    assertThat(precedenceString("$a ?: $b ?: $c")).isEqualTo("$a ?: ($b ?: $c)");

    // ternary is right associative (though still confusing)
    assertThat(precedenceString("$a ? $b ? $c : $d : $e ? $f : $g"))
        .isEqualTo("$a ? ($b ? $c : $d) : ($e ? $f : $g)");

    // unary negation ?: is right associative
    assertThat(precedenceString("- - $a")).isEqualTo("- (- $a)");

    // all together now!
    assertThat(precedenceString("1 + - 2 * 3 + 4 % 2 ?: 3"))
        .isEqualTo("((1 + ((- 2) * 3)) + (4 % 2)) ?: 3");

    assertThat(precedenceString("-$a.b > 0 ? $c.d : $c"))
        .isEqualTo("((- $a.b) > 0) ? $c.d : $c");
  }

  // Parses the soy expression and then prints it with copious parens to indicate the associativity
  private String precedenceString(String soyExpr) {
    ExprNode node = assertThatExpression(soyExpr).isValidExpression();
    return formatNode(node, true);
  }

  private String formatNode(ExprNode node, boolean outermost) {
    if (node instanceof OperatorNode) {
      OperatorNode opNode = (OperatorNode) node;
      String formatted = formatOperator(opNode);
      if (!outermost) {
        return "(" + formatted + ")";
      }
      return formatted;
    } else {
      return node.toSourceString();
    }
  }

  private String formatOperator(OperatorNode opNode) {
    Operator op = opNode.getOperator();
    switch (op) {
      case NEGATIVE:
      case NOT:
        // unary
        return op.getTokenString() + " " + formatNode(opNode.getChild(0), false);
      case CONDITIONAL:
        return formatNode(opNode.getChild(0), false)
            + " ? " + formatNode(opNode.getChild(1), false)
            + " : " + formatNode(opNode.getChild(2), false);
      default:
        // everything else is binary
        assertEquals(2, op.getNumOperands());
        return formatNode(opNode.getChild(0), false) + " " + op.getTokenString() + " "
            + formatNode(opNode.getChild(1), false);
    }
  }

  // -----------------------------------------------------------------------------------------------
  // Helpers.

  private void assertNodeEquals(ExprNode expected, ExprNode actual) {
    if (!expected.equals(actual)) {
      fail(String.format(
          "Expected <%s> but was: <%s>", expected.toSourceString(), actual.toSourceString()));
    }
  }

}


text:
<?php

namespace hipanel\modules\client\models\query;

use hiqdev\hiart\ActiveQuery;

class ContactQuery extends ActiveQuery
{
    public function withLocalizations()
    {
        $this->joinWith('localizations');
        $this->andWhere(['with_localizations' => true]);

        return $this;
    }

    public function withDocuments()
    {
        $this->joinWith('documents');
        $this->andWhere(['with_documents' => true]);

        return $this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
PlayerBattleRecord (BattleSys Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-10-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

NBattleSys Doc

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

battlesys

Class PlayerBattleRecord

java.lang.Object
  battlesys.PlayerBattleRecord

All Implemented Interfaces:
java.lang.Cloneable, java.lang.Comparable<PlayerBattleRecord>

public class PlayerBattleRecord
extends java.lang.Object
implements java.lang.Comparable<PlayerBattleRecord>, java.lang.Cloneable

Records how a player plays the battles, that is, number of wins, loses, draws, etc...

Constructor Summary

PlayerBattleRecord(PlayerList team)

          Constructor.

Method Summary

 java.lang.Object
clone()

 int
compareTo(PlayerBattleRecord o)

 boolean
equals(java.lang.Object o)

 long
getDraw()

 long
getLose()

 java.lang.String
getName()

 PlayerList
getPlayers()

 long
getScore()

 long
getWin()

 int
hashCode()

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PlayerBattleRecord

public PlayerBattleRecord(PlayerList team)

Constructor.

Parameters:
team - The Player team concerned

Method Detail

compareTo

public final int compareTo(PlayerBattleRecord o)

Specified by:
compareTo in interface java.lang.Comparable<PlayerBattleRecord>

clone

public java.lang.Object clone()

Overrides:
clone in class java.lang.Object

equals

public final boolean equals(java.lang.Object o)

Overrides:
equals in class java.lang.Object

hashCode

public final int hashCode()

Overrides:
hashCode in class java.lang.Object

getName

public java.lang.String getName()

Returns:
the name

getWin

public long getWin()

Returns:
the win

getLose

public long getLose()

Returns:
the lose

getDraw

public long getDraw()

Returns:
the draw

getScore

public long getScore()

Returns:
the score

getPlayers

public PlayerList getPlayers()

Returns:
the score

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

NBattleSys Doc

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
(function(){

var iNaturalist = window.iNaturalist = new function(){

  // Abitlity to register distant namespases easily
  // based off of http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx
  this.registerNameSpace = function(ns) {
   var nsParts = ns.split(".");
   var root = window;

   for(var i=0; i<nsParts.length; i++) {
    if(typeof root[nsParts[i]] == "undefined")
     root[nsParts[i]] = new Object();

    root = root[nsParts[i]];
   }
  };

  // Execute a RESTful delete by sending a DELETE request to a URL
  this.restfulDelete = function(deleteURL, options, target) {
    if(typeof(options.plural) == 'undefined') {
      var plural = false;
    } else {
      var plural = options.plural;
      options.plural = null;
    }
    var ajaxOptions = $.extend({}, options, {
      type: 'POST',
      data: $.extend({
        '_method': 'delete',
        'authenticity_token': $('meta[name=csrf-token]').attr('content')
      }, options.data),
      url: deleteURL
    });

    if (plural) {
      confirmStr = "Are you sure you want to delete these?";
    } else {
      confirmStr = "Are you sure you want to delete this?";
    };
    if (confirm(confirmStr)) {
      if (typeof(target) != 'undefined') {
        $(target).hide();
        var deleteStatus = $('Deleting...');
        $(target).after(deleteStatus);
      }
      $.ajax(ajaxOptions);
    } else {
      return false;
    }
  };

  this.modalShow = function(o) {
    iNaturalist.modalCenter(o.w)
    o.w.show()
  }

  this.modalCenter = function(elt) {
    elt.height('auto')
    var height = $(window).height()*0.9
    if (elt.height() < height ) { height = elt.height() }
    if (height = elt.height()) {
      elt.height('auto')
    } else {
      elt.height(height)
    }
    var top = $(window).scrollTop() + $(window).height()/2 - elt.height()/2-20
    elt.css('top', top + 'px')
  }

}; // end of the iNaturalist singleton

// Class properties
iNaturalist.version = 0.1;

// Authenticity token placeholder, this allows valid post requests with
// Rails 2.x's new protect_from_forgery methods.  Unfortunately it must be
// set in the page since it is dependent on the user's specific session.
iNaturalist.form_authenticity_token = null;
})();


text:
We are a voice
coming though the waters,
Can you hear us?

We are a memory
turning into real tomorrows,
Will you know us?

We are the silence
in the turbulence,
Can you see us?

We are the struggle
on a waters edge,
Will you join us?

We are a motion
coming to the surface,
Can you feel our wake?

No boundaries, no borders
we are the sunlit join
in the seamless lake.
We are the ponderous
to the deeply divided wake.

We are the silent and the spoken
the gifted and the token
the serious and the jokin'
on a sunstroke day.
We are jumping for the air
falling for the stream
covered and wrapped
so completely like a dream.

We are in and on the horizon at once
our splash has broken
in a calm glass war
pierced clean
in rippled leftovers.

Looking in reflecting deep,
find us
we are the invisible with a voice
a sound but not asleep.

LauraLee K. Harris


text:
package com.momohelp.mapper;

import java.util.List;
import java.util.Map;

import com.momohelp.model.Buy;
import com.momohelp.util.MyMapper;

/**
 *
 * @author Administrator
 *
 */
public interface BuyMapper extends MyMapper<Buy> {

	List<Buy> findUnDealByUserId(Map<String, Object> map);

	void updateNum_deal(Buy buy);
}


text:
PLUGINLIB_DECLARE_CLASS(mapviz_plugins, tile_map, tile_map::TileMapPlugin, mapviz::MapvizPlugin)

namespace tile_map
{
  TileMapPlugin::TileMapPlugin() :
    config_widget_(new QWidget()),
    transformed_(false)
  {
    ui_.setupUi(config_widget_);

    QPalette p(config_widget_->palette());
    p.setColor(QPalette::Background, Qt::white);
    config_widget_->setPalette(p);

    QPalette p2(ui_.status->palette());
    p2.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p2);

    source_frame_ = swri_transform_util::_wgs84_frame;

    QObject::connect(ui_.source_combo, SIGNAL(activated(QString)), this, SLOT(SelectSource(QString)));
  }

  TileMapPlugin::~TileMapPlugin()
  {
  }

  void TileMapPlugin::SelectSource(QString source)
  {
    if (source == "MapQuest (satellite)")
    {
      tile_map_.SetBaseUrl("http://otile1.mqcdn.com/tiles/1.0.0/sat/");
      tile_map_.SetExtension(".jpg");
      tile_map_.SetMaxLevel(18);
    }
    else if (source == "MapQuest (roads)")
    {
      tile_map_.SetBaseUrl("http://otile1.mqcdn.com/tiles/1.0.0/map/");
      tile_map_.SetExtension(".jpg");
      tile_map_.SetMaxLevel(19);
    }
    else if (source == "Stamen (watercolor)")
    {
      tile_map_.SetBaseUrl("http://tile.stamen.com/watercolor/");
      tile_map_.SetExtension(".jpg");
      tile_map_.SetMaxLevel(19);

    }
    else if (source == "Stamen (terrain)")
    {
      tile_map_.SetBaseUrl("http://tile.stamen.com/terrain/");
      tile_map_.SetExtension(".jpg");
      tile_map_.SetMaxLevel(15);
    }
    else if (source == "Stamen (toner)")
    {
      tile_map_.SetBaseUrl("http://tile.stamen.com/toner/");
      tile_map_.SetExtension(".png");
      tile_map_.SetMaxLevel(19);
    }
    else
    {
      tile_map_.SetBaseUrl(source.toStdString());
      tile_map_.SetExtension(".jpg");
      tile_map_.SetMaxLevel(19);
    }

    initialized_ = true;

    canvas_->update();
  }

  void TileMapPlugin::PrintError(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_ERROR("Error: %s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void TileMapPlugin::PrintInfo(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_INFO("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::green);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void TileMapPlugin::PrintWarning(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
      return;

    ROS_WARN("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::darkYellow);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  QWidget* TileMapPlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  bool TileMapPlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = canvas;

    SelectSource("MapQuest (satellite)");

    return true;
  }

  void TileMapPlugin::Draw(double x, double y, double scale)
  {
    //ROS_ERROR("Draw(%lf, %lf, %lf)", x, y, scale);
    swri_transform_util::Transform to_wgs84;
    if (tf_manager_.GetTransform(source_frame_, target_frame_, to_wgs84))
    {
      //ROS_ERROR("%s -> %s", target_frame_.c_str(), source_frame_.c_str());
      tf::Vector3 center(x, y, 0);
      center = to_wgs84 * center;
      tile_map_.SetView(center.y(), center.x(), scale, canvas_->width(), canvas_->height());
      tile_map_.Draw();
    }
  }

  void TileMapPlugin::Transform()
  {
    swri_transform_util::Transform to_target;
    if (tf_manager_.GetTransform(target_frame_, source_frame_, to_target))
    {
      tile_map_.SetTransform(to_target);
      PrintInfo("OK");
    }
    else
    {
      PrintError("No transform between " + source_frame_ + " and " + target_frame_);
    }
  }

  void TileMapPlugin::LoadConfig(const YAML::Node& node, const std::string& path)
  {
    if (swri_yaml_util::FindValue(node, "custom_sources"))
    {
      const YAML::Node& sources = node["custom_sources"];
      for (uint32_t i = 0; i < sources.size(); i++)
      {
        std::string url;
        sources[i] >> url;
        ui_.source_combo->addItem(QString::fromStdString(url));
      }
    }

    if (swri_yaml_util::FindValue(node, "source"))
    {
      std::string source;
      node["source"] >> source;

      int index = ui_.source_combo->findText(QString::fromStdString(source), Qt::MatchExactly);
      if (index < 0)
      {
        ui_.source_combo->addItem(QString::fromStdString(source));
        index = ui_.source_combo->findText(QString::fromStdString(source), Qt::MatchExactly);
      }

      if (index >= 0)
      {
        ui_.source_combo->setCurrentIndex(index);
      }

      SelectSource(QString::fromStdString(source));
    }
  }

  void TileMapPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path)
  {
    if (ui_.source_combo->count() > 5)
    {
      emitter << YAML::Key << "custom_sources" << YAML::Value << YAML::BeginSeq;
      for (int32_t i = 5; i < ui_.source_combo->count(); i++)
      {
        emitter << YAML::Value << ui_.source_combo->itemText(i).toStdString();
      }
      emitter << YAML::EndSeq;
    }

    emitter << YAML::Key << "source" << YAML::Value << boost::trim_copy(ui_.source_combo->currentText().toStdString());
  }
}


text:
<?php namespace z5internet\ReactUserFramework\App\Http\Controllers;

use z5internet\ReactUserFramework\App\Http\Controllers\Controller;

use z5internet\ReactUserFramework\App\Http\Controllers\User\UserController;

use Mail;

use z5internet\ReactUserFramework\App\ChangeEmail;

use z5internet\ReactUserFramework\App\Joined;

use z5internet\ReactUserFramework\App\PasswordResets;

use z5internet\ReactUserFramework\App\Http\Controllers\Image\ImageController;

use z5internet\ReactUserFramework\App\Http\Controllers\Teams\TeamsController;

use z5internet\ReactUserFramework\App\Http\Controllers\StartController;

use Carbon\Carbon;

class SettingsController extends Controller
{

	public function postUploadprofileimage($imageData,$crop) {

		if ($imageData) {

			$filename = (new ImageController)->putBase64Image($imageData,$crop,'p');

		}
		else
		{

			$filename = (new ImageController)->cropImage($crop,'p');

		}

		UserController::updateUser(['image' => json_encode($filename)],app('auth')->id());

		return ['data'=>['image'=>UserController::user(app('auth')->id())->image]];

	}

	public function saveSettings($settings, $uid) {

		$user = UserController::getUser($uid);

		$keys = ['first_name','last_name'];

		$error = '';

		foreach ($keys as $tk) {

			$val = array_get($settings,$tk);

			if ($val) {

				$user->$tk = $val;

			}

		}

		$email = array_get($settings,'email');

		if ($email) {

			if ($email <> $user['email']) {

				$check = UserController::getUserByEmail($email);

				if ($check) {

					return ['errors' => [

						[

							'message' => 'Your email address is already being used and cannot be used on this account.',

						],

					]];

				}

				$code	=	md5($email.microtime());

				$db = new ChangeEmail;

				$db->uid = $uid;
				$db->code = $code;
				$db->email = $email;
				$db->created_at = new Carbon();

				$db->save();

				$id = $db->id;

				$data=array(

					"first_name"	=>	$user['first_name'],
					"email"			=>	$email,
					"link"			=>	config('app.url')."/settings/changeEmail?id=".$id."&code=".$code."&email=".urlencode($email),

				);

				app('mailer')->send('vendor.ruf.email.registeredEmail', $data, function($message) Use ($data) {

					$message->to($data["email"], $data['first_name'])->subject('Verify your '.config('app.name').' email address.');

				});

			}

		}

		if (array_get($settings,'emailChange')) {

			$id = array_get($settings,'id');
			$code = array_get($settings,'code');
			$email = array_get($settings,'email');

			$ce = ChangeEmail::where('id',$id)->where('code',$code)->where('email',$email)->get(['id','email']);

			if (($user->email == $email) || (array_get($ce,0) && ($ce[0]->id == $id))) {

				if ($user->email <> $email) {

					PasswordResets::where('email', $user->email)->delete();

					ChangeEmail::where('email', $email)->delete();

					$user->email = $email;

					joined::where('email', $email)->delete();

				}

			}
			else
			{

				return ['data'=>[
					'ecError' => 1
					]
				];

			}

		}

		$current_password = array_get($settings,'current_password');

		if ($current_password) {

			if (!app('hash')->check($current_password,$user['password'])) {

				$error = 'Your current password is not correct';

			}
			else
			{

				if (array_get($settings,'new_password') <> array_get($settings,'confirm_password')) {

					$error = 'The 2 passwords you entered don\'t match';

				}
				else
				{

					$user->password = app('hash')->make(array_get($settings,'new_password'));

				}

			}

		}

		$user->save();

		UserController::forgetFromCache($uid);

		$ret = ["data" => (new StartController)->show($uid)];

		if ($error) {

			$ret['data']['pwError'] = $error;

		}

		return $ret;

	}

	public function addTeamMember($data) {

		$uid = app('auth')->id();

		$TeamsController = new TeamsController;

		if (!$TeamsController->isUserAnAdminOfTeam($uid, $data['team'])) {
			return [];
		}

		$checkIfEmailExists = UserController::getUserByEmail($data['email']);

		if ($checkIfEmailExists) {

			$checkId = $checkIfEmailExists->id;

			if ($TeamsController->isUserAMemberOfTeam($checkId, $data['team'])) {

				return ['error' => [
					'message' => 'The email address '.$data['email'].' is already a team member.',
				]];

			}

		}

		return UserController::join($data, 'vendor.ruf.email.addTeamMemberEmail');

	}

	public function deleteInvitedTeamMember($id) {

		return joined::where("id", "=", $id)->delete();

	}

}


text:
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create domain_admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create project_admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create project_user
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create domain_user
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create cloud_admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role create admin

openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN domain create domain_A

openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN user create user_AU1 --domain domain_A --password password
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN user create user_AU2 --domain domain_A --password password

openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN project create project_AP1 --domain domain_A
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN project create project_AP2 --domain domain_A

# Use user_id for --user as this openstack client is buggy. If you have two users with same name in two different domain then the following
# command won't work. user_id will work. Same comment is also applicable for projects.

openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user user_AU1 --domain domain_A domain_admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user user_AU2 --domain domain_A domain_user

openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user user_AU1 --project project_AP1 project_admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user user_AU2 --project project_AP2 project_user

#create the data for default stackrc file
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN user create admin --domain default --password password
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN project create admin --domain default
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user admin --project admin admin
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN role add --user admin --domain default admin

#Create a service
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN  service create --name keystone identity

#create endpoint
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN  endpoint create  keystone  public  http://localhost:35357/
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN  endpoint create  keystone  internal http://localhost:35357/
openstack --os-url http://localhost:35357/v3 --os-identity-api-version 3 --os-token=ADMIN  endpoint create  keystone  admin  http://localhost:35357/


text:
#include "El.hpp"

namespace El {
namespace nnls {

// Transform each problem
//
//   min || A x - b ||_2
//   s.t. x >= 0
//
// into the explicit QP
//
//   min (1/2) x^T (A^T A) x + (-A^T b)^T x
//   s.t. x >= 0
//
// and solve the sequence of problems simultaneously with ADMM.
//

template<typename Real>
inline typename enable_if<!IsComplex<Real>::value,Int>::type
ADMM
( const Matrix<Real>& A,
  const Matrix<Real>& B,
        Matrix<Real>& X,
  const ADMMCtrl<Real>& ctrl )
{
    DEBUG_ONLY(CSE cse("nnls::ADMM"))
    const Real maxReal = std::numeric_limits<Real>::max();

    Matrix<Real> Q, C;
    Herk( LOWER, ADJOINT, Real(1), A, Q );
    Gemm( ADJOINT, NORMAL, Real(-1), A, B, C );

    return qp::box::ADMM( Q, C, Real(0), maxReal, X, ctrl );
}

template<typename Real>
inline typename enable_if<!IsComplex<Real>::value,Int>::type
ADMM
( const ElementalMatrix<Real>& APre,
  const ElementalMatrix<Real>& B,
        ElementalMatrix<Real>& X,
  const ADMMCtrl<Real>& ctrl )
{
    DEBUG_ONLY(CSE cse("nnls::ADMM"))
    const Real maxReal = std::numeric_limits<Real>::max();

    DistMatrixReadProxy<Real,Real,MC,MR> AProx( APre );
    auto& A = AProx.GetLocked();

    DistMatrix<Real> Q(A.Grid()), C(A.Grid());
    Herk( LOWER, ADJOINT, Real(1), A, Q );
    Gemm( ADJOINT, NORMAL, Real(-1), A, B, C );

    return qp::box::ADMM( Q, C, Real(0), maxReal, X, ctrl );
}

} // namespace nnls
} // namespace El


text:
<?php

namespace Void;

class JobCollection extends VoidBase implements Job {

  protected $jobs = Array();

  public function add(Job $job) {
    $this->jobs[] = $job;
  }

  public function remove(Job $job) {
    array_diff($this->jobs, array($job));
  }

  public function run() {
    foreach($this->jobs as $job) {
      $job->run();
    }
  }

  public function cleanup() {
    foreach($this->jobs as $job) {
      $job->cleanup();
    }
  }
}


text:
package org.http4s
package server

import cats.effect._
import cats.syntax.all._
import org.http4s.syntax.all._

class HttpRoutesSuite extends Http4sSuite {
  val routes1 = HttpRoutes.of[IO] {
    case req if req.pathInfo == path"/match" =>
      Response[IO](Status.Ok).withEntity("match").pure[IO]

    case req if req.pathInfo == path"/conflict" =>
      Response[IO](Status.Ok).withEntity("routes1conflict").pure[IO]

    case req if req.pathInfo == path"/notfound" =>
      Response[IO](Status.NotFound).withEntity("notfound").pure[IO]
  }

  val routes2 = HttpRoutes.of[IO] {
    case req if req.pathInfo == path"/routes2" =>
      Response[IO](Status.Ok).withEntity("routes2").pure[IO]

    case req if req.pathInfo == path"/conflict" =>
      Response[IO](Status.Ok).withEntity("routes2conflict").pure[IO]
  }

  val aggregate1 = routes1 <+> routes2

  test("Return a valid Response from the first service of an aggregate") {
    aggregate1
      .orNotFound(Request[IO](uri = uri"/match"))
      .flatMap(_.as[String])
      .assertEquals("match")
  }

  test("Return a custom NotFound from the first service of an aggregate") {
    aggregate1
      .orNotFound(Request[IO](uri = uri"/notfound"))
      .flatMap(_.as[String])
      .assertEquals("notfound")
  }

  test("Accept the first matching route in the case of overlapping paths") {
    aggregate1
      .orNotFound(Request[IO](uri = uri"/conflict"))
      .flatMap(_.as[String])
      .assertEquals("routes1conflict")
  }

  test("Fall through the first service that doesn't match to a second matching service") {
    aggregate1
      .orNotFound(Request[IO](uri = uri"/routes2"))
      .flatMap(_.as[String])
      .assertEquals("routes2")
  }

  test("Properly fall through two aggregated service if no path matches") {
    aggregate1
      .apply(Request[IO](uri = uri"/wontMatch"))
      .value
      .map(_ == Option.empty[Response[IO]])
      .assert
  }
}


text:
"""
Backends for embarrassingly parallel code.
"""

import gc
import os
import warnings
import threading
import functools
import contextlib
from abc import ABCMeta, abstractmethod

from .my_exceptions import WorkerInterrupt
from ._multiprocessing_helpers import mp

if mp is not None:
    from .pool import MemmappingPool
    from multiprocessing.pool import ThreadPool
    from .executor import get_memmapping_executor

    # Compat between concurrent.futures and multiprocessing TimeoutError
    from multiprocessing import TimeoutError
    from concurrent.futures._base import TimeoutError as CfTimeoutError
    from .externals.loky import process_executor, cpu_count

class ParallelBackendBase(metaclass=ABCMeta):
    """Helper abc which defines all methods a ParallelBackend must implement"""

    supports_timeout = False
    supports_inner_max_num_threads = False
    nesting_level = None

    def __init__(self, nesting_level=None, inner_max_num_threads=None,
                 **kwargs):
        super().__init__(**kwargs)
        self.nesting_level = nesting_level
        self.inner_max_num_threads = inner_max_num_threads

    MAX_NUM_THREADS_VARS = [
        'OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
        'BLIS_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMBA_NUM_THREADS',
        'NUMEXPR_NUM_THREADS',
    ]

    TBB_ENABLE_IPC_VAR = "ENABLE_IPC"

    @abstractmethod
    def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs that can actually run in parallel

        n_jobs is the number of workers requested by the callers. Passing
        n_jobs=-1 means requesting all available workers for instance matching
        the number of CPU cores on the worker host(s).

        This method should return a guesstimate of the number of workers that
        can actually perform work concurrently. The primary use case is to make
        it possible for the caller to know in how many chunks to slice the
        work.

        In general working on larger data chunks is more efficient (less
        scheduling overhead and better use of CPU cache prefetching heuristics)
        as long as all the workers have enough work to do.
        """

    @abstractmethod
    def apply_async(self, func, callback=None):
        """Schedule a func to be run"""

    def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
                  **backend_args):
        """Reconfigure the backend and return the number of workers.

        This makes it possible to reuse an existing backend instance for
        successive independent calls to Parallel with different parameters.
        """
        self.parallel = parallel
        return self.effective_n_jobs(n_jobs)

    def start_call(self):
        """Call-back method called at the beginning of a Parallel call"""

    def stop_call(self):
        """Call-back method called at the end of a Parallel call"""

    def terminate(self):
        """Shutdown the workers and free the shared memory."""

    def compute_batch_size(self):
        """Determine the optimal batch size"""
        return 1

    def batch_completed(self, batch_size, duration):
        """Callback indicate how long it took to run a batch"""

    def get_exceptions(self):
        """List of exception types to be captured."""
        return []

    def abort_everything(self, ensure_ready=True):
        """Abort any running tasks

        This is called when an exception has been raised when executing a tasks
        and all the remaining tasks will be ignored and can therefore be
        aborted to spare computation resources.

        If ensure_ready is True, the backend should be left in an operating
        state as future tasks might be re-submitted via that same backend
        instance.

        If ensure_ready is False, the implementer of this method can decide
        to leave the backend in a closed / terminated state as no new task
        are expected to be submitted to this backend.

        Setting ensure_ready to False is an optimization that can be leveraged
        when aborting tasks via killing processes from a local process pool
        managed by the backend it-self: if we expect no new tasks, there is no
        point in re-creating new workers.
        """
        # Does nothing by default: to be overridden in subclasses when
        # canceling tasks is possible.
        pass

    def get_nested_backend(self):
        """Backend instance to be used by nested Parallel calls.

        By default a thread-based backend is used for the first level of
        nesting. Beyond, switch to sequential backend to avoid spawning too
        many threads on the host.
        """
        nesting_level = getattr(self, 'nesting_level', 0) + 1
        if nesting_level > 1:
            return SequentialBackend(nesting_level=nesting_level), None
        else:
            return ThreadingBackend(nesting_level=nesting_level), None

    @contextlib.contextmanager
    def retrieval_context(self):
        """Context manager to manage an execution context.

        Calls to Parallel.retrieve will be made inside this context.

        By default, this does nothing. It may be useful for subclasses to
        handle nested parallelism. In particular, it may be required to avoid
        deadlocks if a backend manages a fixed number of workers, when those
        workers may be asked to do nested Parallel calls. Without
        'retrieval_context' this could lead to deadlock, as all the workers
        managed by the backend may be "busy" waiting for the nested parallel
        calls to finish, but the backend has no free workers to execute those
        tasks.
        """
        yield

    def _prepare_worker_env(self, n_jobs):
        """Return environment variables limiting threadpools in external libs.

        This function return a dict containing environment variables to pass
        when creating a pool of process. These environment variables limit the
        number of threads to `n_threads` for OpenMP, MKL, Accelerated and
        OpenBLAS libraries in the child processes.
        """
        explicit_n_threads = self.inner_max_num_threads
        default_n_threads = str(max(cpu_count() // n_jobs, 1))

        # Set the inner environment variables to self.inner_max_num_threads if
        # it is given. Else, default to cpu_count // n_jobs unless the variable
        # is already present in the parent process environment.
        env = {}
        for var in self.MAX_NUM_THREADS_VARS:
            if explicit_n_threads is None:
                var_value = os.environ.get(var, None)
                if var_value is None:
                    var_value = default_n_threads
            else:
                var_value = str(explicit_n_threads)

            env[var] = var_value

        if self.TBB_ENABLE_IPC_VAR not in os.environ:
            # To avoid over-subscription when using TBB, let the TBB schedulers
            # use Inter Process Communication to coordinate:
            env[self.TBB_ENABLE_IPC_VAR] = "1"
        return env

    @staticmethod
    def in_main_thread():
        return isinstance(threading.current_thread(), threading._MainThread)

class SequentialBackend(ParallelBackendBase):
    """A ParallelBackend which will execute all batches sequentially.

    Does not use/create any threading objects, and hence has minimal
    overhead. Used when n_jobs == 1.
    """

    uses_threads = True
    supports_sharedmem = True

    def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel"""
        if n_jobs == 0:
            raise ValueError('n_jobs == 0 in Parallel has no meaning')
        return 1

    def apply_async(self, func, callback=None):
        """Schedule a func to be run"""
        result = ImmediateResult(func)
        if callback:
            callback(result)
        return result

    def get_nested_backend(self):
        # import is not top level to avoid cyclic import errors.
        from .parallel import get_active_backend

        # SequentialBackend should neither change the nesting level, the
        # default backend or the number of jobs. Just return the current one.
        return get_active_backend()

class PoolManagerMixin(object):
    """A helper class for managing pool of workers."""

    _pool = None

    def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel"""
        if n_jobs == 0:
            raise ValueError('n_jobs == 0 in Parallel has no meaning')
        elif mp is None or n_jobs is None:
            # multiprocessing is not available or disabled, fallback
            # to sequential mode
            return 1
        elif n_jobs < 0:
            n_jobs = max(cpu_count() + 1 + n_jobs, 1)
        return n_jobs

    def terminate(self):
        """Shutdown the process or thread pool"""
        if self._pool is not None:
            self._pool.close()
            self._pool.terminate()  # terminate does a join()
            self._pool = None

    def _get_pool(self):
        """Used by apply_async to make it possible to implement lazy init"""
        return self._pool

    def apply_async(self, func, callback=None):
        """Schedule a func to be run"""
        return self._get_pool().apply_async(
            SafeFunction(func), callback=callback)

    def abort_everything(self, ensure_ready=True):
        """Shutdown the pool and restart a new one with the same parameters"""
        self.terminate()
        if ensure_ready:
            self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel,
                           **self.parallel._backend_args)

class AutoBatchingMixin(object):
    """A helper class for automagically batching jobs."""

    # In seconds, should be big enough to hide multiprocessing dispatching
    # overhead.
    # This settings was found by running benchmarks/bench_auto_batching.py
    # with various parameters on various platforms.
    MIN_IDEAL_BATCH_DURATION = .2

    # Should not be too high to avoid stragglers: long jobs running alone
    # on a single worker while other workers have no work to process any more.
    MAX_IDEAL_BATCH_DURATION = 2

    # Batching counters default values
    _DEFAULT_EFFECTIVE_BATCH_SIZE = 1
    _DEFAULT_SMOOTHED_BATCH_DURATION = 0.0

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
        self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION

    def compute_batch_size(self):
        """Determine the optimal batch size"""
        old_batch_size = self._effective_batch_size
        batch_duration = self._smoothed_batch_duration
        if (batch_duration > 0 and
                batch_duration < self.MIN_IDEAL_BATCH_DURATION):
            # The current batch size is too small: the duration of the
            # processing of a batch of task is not large enough to hide
            # the scheduling overhead.
            ideal_batch_size = int(old_batch_size *
                                   self.MIN_IDEAL_BATCH_DURATION /
                                   batch_duration)
            # Multiply by two to limit oscilations between min and max.
            ideal_batch_size *= 2

            # dont increase the batch size too fast to limit huge batch sizes
            # potentially leading to starving worker
            batch_size = min(2 * old_batch_size, ideal_batch_size)

            batch_size = max(batch_size, 1)

            self._effective_batch_size = batch_size
            if self.parallel.verbose >= 10:
                self.parallel._print(
                    "Batch computation too fast (%.4fs.) "
                    "Setting batch_size=%d.", (batch_duration, batch_size))
        elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and
              old_batch_size >= 2):
            # The current batch size is too big. If we schedule overly long
            # running batches some CPUs might wait with nothing left to do
            # while a couple of CPUs a left processing a few long running
            # batches. Better reduce the batch size a bit to limit the
            # likelihood of scheduling such stragglers.

            # decrease the batch size quickly to limit potential starving
            ideal_batch_size = int(
                old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration
            )
            # Multiply by two to limit oscilations between min and max.
            batch_size = max(2 * ideal_batch_size, 1)
            self._effective_batch_size = batch_size
            if self.parallel.verbose >= 10:
                self.parallel._print(
                    "Batch computation too slow (%.4fs.) "
                    "Setting batch_size=%d.", (batch_duration, batch_size))
        else:
            # No batch size adjustment
            batch_size = old_batch_size

        if batch_size != old_batch_size:
            # Reset estimation of the smoothed mean batch duration: this
            # estimate is updated in the multiprocessing apply_async
            # CallBack as long as the batch_size is constant. Therefore
            # we need to reset the estimate whenever we re-tune the batch
            # size.
            self._smoothed_batch_duration = \
                self._DEFAULT_SMOOTHED_BATCH_DURATION

        return batch_size

    def batch_completed(self, batch_size, duration):
        """Callback indicate how long it took to run a batch"""
        if batch_size == self._effective_batch_size:
            # Update the smoothed streaming estimate of the duration of a batch
            # from dispatch to completion
            old_duration = self._smoothed_batch_duration
            if old_duration == self._DEFAULT_SMOOTHED_BATCH_DURATION:
                # First record of duration for this batch size after the last
                # reset.
                new_duration = duration
            else:
                # Update the exponentially weighted average of the duration of
                # batch for the current effective size.
                new_duration = 0.8 * old_duration + 0.2 * duration
            self._smoothed_batch_duration = new_duration

    def reset_batch_stats(self):
        """Reset batch statistics to default values.

        This avoids interferences with future jobs.
        """
        self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
        self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION

class ThreadingBackend(PoolManagerMixin, ParallelBackendBase):
    """A ParallelBackend which will use a thread pool to execute batches in.

    This is a low-overhead backend but it suffers from the Python Global
    Interpreter Lock if the called function relies a lot on Python objects.
    Mostly useful when the execution bottleneck is a compiled extension that
    explicitly releases the GIL (for instance a Cython loop wrapped in a "with
    nogil" block or an expensive call to a library such as NumPy).

    The actual thread pool is lazily initialized: the actual thread pool
    construction is delayed to the first call to apply_async.

    ThreadingBackend is used as the default backend for nested calls.
    """

    supports_timeout = True
    uses_threads = True
    supports_sharedmem = True

    def configure(self, n_jobs=1, parallel=None, **backend_args):
        """Build a process or thread pool and return the number of workers"""
        n_jobs = self.effective_n_jobs(n_jobs)
        if n_jobs == 1:
            # Avoid unnecessary overhead and use sequential backend instead.
            raise FallbackToBackend(
                SequentialBackend(nesting_level=self.nesting_level))
        self.parallel = parallel
        self._n_jobs = n_jobs
        return n_jobs

    def _get_pool(self):
        """Lazily initialize the thread pool

        The actual pool of worker threads is only initialized at the first
        call to apply_async.
        """
        if self._pool is None:
            self._pool = ThreadPool(self._n_jobs)
        return self._pool

class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin,
                             ParallelBackendBase):
    """A ParallelBackend which will use a multiprocessing.Pool.

    Will introduce some communication and memory overhead when exchanging
    input and output data with the with the worker Python processes.
    However, does not suffer from the Python Global Interpreter Lock.
    """

    supports_timeout = True

    def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        """
        if mp is None:
            return 1

        if mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                if inside_dask_worker():
                    msg = (
                        "Inside a Dask worker with daemon=True, "
                        "setting n_jobs=1.\nPossible work-arounds:\n"
                        "- dask.config.set("
                        "{'distributed.worker.daemon': False})"
                        "- set the environment variable "
                        "DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
                        "before creating your Dask cluster."
                    )
                else:
                    msg = (
                        'Multiprocessing-backed parallel loops '
                        'cannot be nested, setting n_jobs=1'
                    )
                warnings.warn(msg, stacklevel=3)
            return 1

        if process_executor._CURRENT_DEPTH > 0:
            # Mixing loky and multiprocessing in nested loop is not supported
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' below loky, setting n_jobs=1',
                    stacklevel=3)
            return 1

        elif not (self.in_main_thread() or self.nesting_level == 0):
            # Prevent posix fork inside in non-main posix threads
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested'
                    ' below threads, setting n_jobs=1',
                    stacklevel=3)
            return 1

        return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs)

    def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
                  **memmappingpool_args):
        """Build a process or thread pool and return the number of workers"""
        n_jobs = self.effective_n_jobs(n_jobs)
        if n_jobs == 1:
            raise FallbackToBackend(
                SequentialBackend(nesting_level=self.nesting_level))

        # Make sure to free as much memory as possible before forking
        gc.collect()
        self._pool = MemmappingPool(n_jobs, **memmappingpool_args)
        self.parallel = parallel
        return n_jobs

    def terminate(self):
        """Shutdown the process or thread pool"""
        super(MultiprocessingBackend, self).terminate()
        self.reset_batch_stats()

class LokyBackend(AutoBatchingMixin, ParallelBackendBase):
    """Managing pool of workers with loky instead of multiprocessing."""

    supports_timeout = True
    supports_inner_max_num_threads = True

    def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
                  idle_worker_timeout=300, **memmappingexecutor_args):
        """Build a process executor and return the number of workers"""
        n_jobs = self.effective_n_jobs(n_jobs)
        if n_jobs == 1:
            raise FallbackToBackend(
                SequentialBackend(nesting_level=self.nesting_level))

        self._workers = get_memmapping_executor(
            n_jobs, timeout=idle_worker_timeout,
            env=self._prepare_worker_env(n_jobs=n_jobs),
            context_id=parallel._id, **memmappingexecutor_args)
        self.parallel = parallel
        return n_jobs

    def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel"""
        if n_jobs == 0:
            raise ValueError('n_jobs == 0 in Parallel has no meaning')
        elif mp is None or n_jobs is None:
            # multiprocessing is not available or disabled, fallback
            # to sequential mode
            return 1
        elif mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                if inside_dask_worker():
                    msg = (
                        "Inside a Dask worker with daemon=True, "
                        "setting n_jobs=1.\nPossible work-arounds:\n"
                        "- dask.config.set("
                        "{'distributed.worker.daemon': False})\n"
                        "- set the environment variable "
                        "DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
                        "before creating your Dask cluster."
                    )
                else:
                    msg = (
                        'Loky-backed parallel loops cannot be called in a'
                        ' multiprocessing, setting n_jobs=1'
                    )
                warnings.warn(msg, stacklevel=3)

            return 1
        elif not (self.in_main_thread() or self.nesting_level == 0):
            # Prevent posix fork inside in non-main posix threads
            if n_jobs != 1:
                warnings.warn(
                    'Loky-backed parallel loops cannot be nested below '
                    'threads, setting n_jobs=1',
                    stacklevel=3)
            return 1
        elif n_jobs < 0:
            n_jobs = max(cpu_count() + 1 + n_jobs, 1)
        return n_jobs

    def apply_async(self, func, callback=None):
        """Schedule a func to be run"""
        future = self._workers.submit(SafeFunction(func))
        future.get = functools.partial(self.wrap_future_result, future)
        if callback is not None:
            future.add_done_callback(callback)
        return future

    @staticmethod
    def wrap_future_result(future, timeout=None):
        """Wrapper for Future.result to implement the same behaviour as
        AsyncResults.get from multiprocessing."""
        try:
            return future.result(timeout=timeout)
        except CfTimeoutError as e:
            raise TimeoutError from e

    def terminate(self):
        if self._workers is not None:
            # Don't terminate the workers as we want to reuse them in later
            # calls, but cleanup the temporary resources that the Parallel call
            # created. This 'hack' requires a private, low-level operation.
            self._workers._temp_folder_manager._unlink_temporary_resources(
                context_id=self.parallel._id
            )
            self._workers = None

        self.reset_batch_stats()

    def abort_everything(self, ensure_ready=True):
        """Shutdown the workers and restart a new one with the same parameters
        """
        self._workers.terminate(kill_workers=True)
        self._workers = None

        if ensure_ready:
            self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel)

class ImmediateResult(object):
    def __init__(self, batch):
        # Don't delay the application, to avoid keeping the input
        # arguments in memory
        self.results = batch()

    def get(self):
        return self.results

class SafeFunction(object):
    """Wrapper that handles the serialization of exception tracebacks.

    TODO python2_drop: check whether SafeFunction is still needed since we
    dropped support for Python 2. If not needed anymore it should be
    deprecated.

    If an exception is triggered when calling the inner function, a copy of
    the full traceback is captured to make it possible to serialize
    it so that it can be rendered in a different Python process.

    """
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        try:
            return self.func(*args, **kwargs)
        except KeyboardInterrupt as e:
            # We capture the KeyboardInterrupt and reraise it as
            # something different, as multiprocessing does not
            # interrupt processing for a KeyboardInterrupt
            raise WorkerInterrupt() from e
        except BaseException:
            # Rely on Python 3 built-in Remote Traceback reporting
            raise

class FallbackToBackend(Exception):
    """Raised when configuration should fallback to another backend"""

    def __init__(self, backend):
        self.backend = backend

def inside_dask_worker():
    """Check whether the current function is executed inside a Dask worker.
    """
    # This function can not be in joblib._dask because there would be a
    # circular import:
    # _dask imports _parallel_backend that imports _dask ...
    try:
        from distributed import get_worker
    except ImportError:
        return False

    try:
        get_worker()
        return True
    except ValueError:
        return False