text:
package org.apache.hadoop.hive.ql.optimizer.physical;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.ConditionalTask;
import org.apache.hadoop.hive.ql.exec.JoinOperator;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.OperatorFactory;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.SerializationUtilities;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.optimizer.GenMapRedUtils;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ConditionalResolverSkewJoin;
import org.apache.hadoop.hive.ql.plan.ConditionalResolverSkewJoin.ConditionalResolverSkewJoinCtx;
import org.apache.hadoop.hive.ql.plan.ConditionalWork;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.FetchWork;
import org.apache.hadoop.hive.ql.plan.JoinDesc;
import org.apache.hadoop.hive.ql.plan.MapJoinDesc;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.MapredLocalWork;
import org.apache.hadoop.hive.ql.plan.MapredWork;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;

/**
 * GenMRSkewJoinProcessor.
 *
 */
public final class GenMRSkewJoinProcessor {

  private GenMRSkewJoinProcessor() {
    // prevent instantiation
  }

  /**
   * Create tasks for processing skew joins. The idea is (HIVE-964) to use
   * separated jobs and map-joins to handle skew joins.
   *

   *

   *

   * Number of mr jobs to handle skew keys is the number of table minus 1 (we
   * can stream the last table, so big keys in the last table will not be a
   * problem).
   *

   * At runtime in Join, we output big keys in one table into one corresponding
   * directories, and all same keys in other tables into different dirs(one for
   * each table). The directories will look like:
   *

   *

   * dir-T1-bigkeys(containing big keys in T1), dir-T2-keys(containing keys
   * which is big in T1),dir-T3-keys(containing keys which is big in T1), ...
   *

   * dir-T1-keys(containing keys which is big in T2), dir-T2-bigkeys(containing
   * big keys in T2),dir-T3-keys(containing keys which is big in T2), ...
   *

   * dir-T1-keys(containing keys which is big in T3), dir-T2-keys(containing big
   * keys in T3),dir-T3-bigkeys(containing keys which is big in T3), ... .....
   *

   *

   * For each table, we launch one mapjoin job, taking the directory containing
   * big keys in this table and corresponding dirs in other tables as input.
   * (Actally one job for one row in the above.)
   *
   *

   * For more discussions, please check
   * https://issues.apache.org/jira/browse/HIVE-964.
   *
   */
  @SuppressWarnings("unchecked")
  public static void processSkewJoin(JoinOperator joinOp,
      Task<? extends Serializable> currTask, ParseContext parseCtx)
      throws SemanticException {

    // We are trying to adding map joins to handle skew keys, and map join right
    // now does not work with outer joins
    if (!GenMRSkewJoinProcessor.skewJoinEnabled(parseCtx.getConf(), joinOp)) {
      return;
    }

    List<Task<? extends Serializable>> children = currTask.getChildTasks();

    Path baseTmpDir = parseCtx.getContext().getMRTmpPath();

    JoinDesc joinDescriptor = joinOp.getConf();
    Map<Byte, List<ExprNodeDesc>> joinValues = joinDescriptor.getExprs();
    int numAliases = joinValues.size();

    Map<Byte, Path> bigKeysDirMap = new HashMap<Byte, Path>();
    Map<Byte, Map<Byte, Path>> smallKeysDirMap = new HashMap<Byte, Map<Byte, Path>>();
    Map<Byte, Path> skewJoinJobResultsDir = new HashMap<Byte, Path>();
    Byte[] tags = joinDescriptor.getTagOrder();
    for (int i = 0; i < numAliases; i++) {
      Byte alias = tags[i];
      bigKeysDirMap.put(alias, getBigKeysDir(baseTmpDir, alias));
      Map<Byte, Path> smallKeysMap = new HashMap<Byte, Path>();
      smallKeysDirMap.put(alias, smallKeysMap);
      for (Byte src2 : tags) {
        if (!src2.equals(alias)) {
          smallKeysMap.put(src2, getSmallKeysDir(baseTmpDir, alias, src2));
        }
      }
      skewJoinJobResultsDir.put(alias, getBigKeysSkewJoinResultDir(baseTmpDir,
          alias));
    }

    joinDescriptor.setHandleSkewJoin(true);
    joinDescriptor.setBigKeysDirMap(bigKeysDirMap);
    joinDescriptor.setSmallKeysDirMap(smallKeysDirMap);
    joinDescriptor.setSkewKeyDefinition(HiveConf.getIntVar(parseCtx.getConf(),
        HiveConf.ConfVars.HIVESKEWJOINKEY));

    HashMap<Path, Task<? extends Serializable>> bigKeysDirToTaskMap =
      new HashMap<Path, Task<? extends Serializable>>();
    List<Serializable> listWorks = new ArrayList<Serializable>();
    List<Task<? extends Serializable>> listTasks = new ArrayList<Task<? extends Serializable>>();
    MapredWork currPlan = (MapredWork) currTask.getWork();

    TableDesc keyTblDesc = (TableDesc) currPlan.getReduceWork().getKeyDesc().clone();
    List<String> joinKeys = Utilities
        .getColumnNames(keyTblDesc.getProperties());
    List<String> joinKeyTypes = Utilities.getColumnTypes(keyTblDesc
        .getProperties());

    Map<Byte, TableDesc> tableDescList = new HashMap<Byte, TableDesc>();
    Map<Byte, RowSchema> rowSchemaList = new HashMap<Byte, RowSchema>();
    Map<Byte, List<ExprNodeDesc>> newJoinValues = new HashMap<Byte, List<ExprNodeDesc>>();
    Map<Byte, List<ExprNodeDesc>> newJoinKeys = new HashMap<Byte, List<ExprNodeDesc>>();
    // used for create mapJoinDesc, should be in order
    List<TableDesc> newJoinValueTblDesc = new ArrayList<TableDesc>();

    for (Byte tag : tags) {
      newJoinValueTblDesc.add(null);
    }

    for (int i = 0; i < numAliases; i++) {
      Byte alias = tags[i];
      List<ExprNodeDesc> valueCols = joinValues.get(alias);
      String colNames = "";
      String colTypes = "";
      int columnSize = valueCols.size();
      List<ExprNodeDesc> newValueExpr = new ArrayList<ExprNodeDesc>();
      List<ExprNodeDesc> newKeyExpr = new ArrayList<ExprNodeDesc>();
      ArrayList<ColumnInfo> columnInfos = new ArrayList<ColumnInfo>();

      boolean first = true;
      for (int k = 0; k < columnSize; k++) {
        TypeInfo type = valueCols.get(k).getTypeInfo();
        String newColName = i + "_VALUE_" + k; // any name, it does not matter.
        ColumnInfo columnInfo = new ColumnInfo(newColName, type, alias.toString(), false);
        columnInfos.add(columnInfo);
        newValueExpr.add(new ExprNodeColumnDesc(columnInfo));
        if (!first) {
          colNames = colNames + ",";
          colTypes = colTypes + ",";
        }
        first = false;
        colNames = colNames + newColName;
        colTypes = colTypes + valueCols.get(k).getTypeString();
      }

      // we are putting join keys at last part of the spilled table
      for (int k = 0; k < joinKeys.size(); k++) {
        if (!first) {
          colNames = colNames + ",";
          colTypes = colTypes + ",";
        }
        first = false;
        colNames = colNames + joinKeys.get(k);
        colTypes = colTypes + joinKeyTypes.get(k);
        ColumnInfo columnInfo = new ColumnInfo(joinKeys.get(k), TypeInfoFactory
            .getPrimitiveTypeInfo(joinKeyTypes.get(k)), alias.toString(), false);
        columnInfos.add(columnInfo);
        newKeyExpr.add(new ExprNodeColumnDesc(columnInfo));
      }

      newJoinValues.put(alias, newValueExpr);
      newJoinKeys.put(alias, newKeyExpr);
      tableDescList.put(alias, Utilities.getTableDesc(colNames, colTypes));
      rowSchemaList.put(alias, new RowSchema(columnInfos));

      // construct value table Desc
      String valueColNames = "";
      String valueColTypes = "";
      first = true;
      for (int k = 0; k < columnSize; k++) {
        String newColName = i + "_VALUE_" + k; // any name, it does not matter.
        if (!first) {
          valueColNames = valueColNames + ",";
          valueColTypes = valueColTypes + ",";
        }
        valueColNames = valueColNames + newColName;
        valueColTypes = valueColTypes + valueCols.get(k).getTypeString();
        first = false;
      }
      newJoinValueTblDesc.set(Byte.valueOf((byte) i), Utilities.getTableDesc(
          valueColNames, valueColTypes));
    }

    joinDescriptor.setSkewKeysValuesTables(tableDescList);
    joinDescriptor.setKeyTableDesc(keyTblDesc);

    for (int i = 0; i < numAliases - 1; i++) {
      Byte src = tags[i];
      MapWork newPlan = PlanUtils.getMapRedWork().getMapWork();

      // This code has been only added for testing
      boolean mapperCannotSpanPartns =
        parseCtx.getConf().getBoolVar(
          HiveConf.ConfVars.HIVE_MAPPER_CANNOT_SPAN_MULTIPLE_PARTITIONS);
      newPlan.setMapperCannotSpanPartns(mapperCannotSpanPartns);

      MapredWork clonePlan = SerializationUtilities.clonePlan(currPlan);

      Operator<? extends OperatorDesc>[] parentOps = new TableScanOperator[tags.length];
      for (int k = 0; k < tags.length; k++) {
        Operator<? extends OperatorDesc> ts =
            GenMapRedUtils.createTemporaryTableScanOperator(
                joinOp.getCompilationOpContext(), rowSchemaList.get((byte)k));
        ((TableScanOperator)ts).setTableDesc(tableDescList.get((byte)k));
        parentOps[k] = ts;
      }
      Operator<? extends OperatorDesc> tblScan_op = parentOps[i];

      ArrayList<String> aliases = new ArrayList<String>();
      String alias = src.toString();
      aliases.add(alias);
      Path bigKeyDirPath = bigKeysDirMap.get(src);
      newPlan.getPathToAliases().put(bigKeyDirPath.toString(), aliases);

      newPlan.getAliasToWork().put(alias, tblScan_op);
      PartitionDesc part = new PartitionDesc(tableDescList.get(src), null);

      newPlan.getPathToPartitionInfo().put(bigKeyDirPath.toString(), part);
      newPlan.getAliasToPartnInfo().put(alias, part);

      Operator<? extends OperatorDesc> reducer = clonePlan.getReduceWork().getReducer();
      assert reducer instanceof JoinOperator;
      JoinOperator cloneJoinOp = (JoinOperator) reducer;

      String dumpFilePrefix = "mapfile"+PlanUtils.getCountForMapJoinDumpFilePrefix();
      MapJoinDesc mapJoinDescriptor = new MapJoinDesc(newJoinKeys, keyTblDesc,
          newJoinValues, newJoinValueTblDesc, newJoinValueTblDesc,joinDescriptor
          .getOutputColumnNames(), i, joinDescriptor.getConds(),
          joinDescriptor.getFilters(), joinDescriptor.getNoOuterJoin(), dumpFilePrefix);
      mapJoinDescriptor.setTagOrder(tags);
      mapJoinDescriptor.setHandleSkewJoin(false);
      mapJoinDescriptor.setNullSafes(joinDescriptor.getNullSafes());

      MapredLocalWork localPlan = new MapredLocalWork(
          new LinkedHashMap<String, Operator<? extends OperatorDesc>>(),
          new LinkedHashMap<String, FetchWork>());
      Map<Byte, Path> smallTblDirs = smallKeysDirMap.get(src);

      for (int j = 0; j < numAliases; j++) {
        if (j == i) {
          continue;
        }
        Byte small_alias = tags[j];
        Operator<? extends OperatorDesc> tblScan_op2 = parentOps[j];
        localPlan.getAliasToWork().put(small_alias.toString(), tblScan_op2);
        Path tblDir = smallTblDirs.get(small_alias);
        localPlan.getAliasToFetchWork().put(small_alias.toString(),
            new FetchWork(tblDir, tableDescList.get(small_alias)));
      }

      newPlan.setMapRedLocalWork(localPlan);

      // construct a map join and set it as the child operator of tblScan_op
      MapJoinOperator mapJoinOp = (MapJoinOperator) OperatorFactory.getAndMakeChild(
          joinOp.getCompilationOpContext(), mapJoinDescriptor, (RowSchema) null, parentOps);
      // change the children of the original join operator to point to the map
      // join operator
      List<Operator<? extends OperatorDesc>> childOps = cloneJoinOp
          .getChildOperators();
      for (Operator<? extends OperatorDesc> childOp : childOps) {
        childOp.replaceParent(cloneJoinOp, mapJoinOp);
      }
      mapJoinOp.setChildOperators(childOps);

      HiveConf jc = new HiveConf(parseCtx.getConf(),
          GenMRSkewJoinProcessor.class);

      newPlan.setNumMapTasks(HiveConf
          .getIntVar(jc, HiveConf.ConfVars.HIVESKEWJOINMAPJOINNUMMAPTASK));
      newPlan
          .setMinSplitSize(HiveConf.getLongVar(jc, HiveConf.ConfVars.HIVESKEWJOINMAPJOINMINSPLIT));
      newPlan.setInputformat(HiveInputFormat.class.getName());

      MapredWork w = new MapredWork();
      w.setMapWork(newPlan);

      Task<? extends Serializable> skewJoinMapJoinTask = TaskFactory.get(w, jc);
      skewJoinMapJoinTask.setFetchSource(currTask.isFetchSource());

      bigKeysDirToTaskMap.put(bigKeyDirPath, skewJoinMapJoinTask);
      listWorks.add(skewJoinMapJoinTask.getWork());
      listTasks.add(skewJoinMapJoinTask);
    }
    if (children != null) {
      for (Task<? extends Serializable> tsk : listTasks) {
        for (Task<? extends Serializable> oldChild : children) {
          tsk.addDependentTask(oldChild);
        }
      }
      currTask.setChildTasks(new ArrayList<Task<? extends Serializable>>());
      for (Task<? extends Serializable> oldChild : children) {
        oldChild.getParentTasks().remove(currTask);
      }
      listTasks.addAll(children);
    }
    ConditionalResolverSkewJoinCtx context =
        new ConditionalResolverSkewJoinCtx(bigKeysDirToTaskMap, children);

    ConditionalWork cndWork = new ConditionalWork(listWorks);
    ConditionalTask cndTsk = (ConditionalTask) TaskFactory.get(cndWork, parseCtx.getConf());
    cndTsk.setListTasks(listTasks);
    cndTsk.setResolver(new ConditionalResolverSkewJoin());
    cndTsk.setResolverCtx(context);
    currTask.setChildTasks(new ArrayList<Task<? extends Serializable>>());
    currTask.addDependentTask(cndTsk);

    return;
  }

  public static boolean skewJoinEnabled(HiveConf conf, JoinOperator joinOp) {

    if (conf != null && !conf.getBoolVar(HiveConf.ConfVars.HIVESKEWJOIN)) {
      return false;
    }

    if (!joinOp.getConf().isNoOuterJoin()) {
      return false;
    }

    byte pos = 0;
    for (Byte tag : joinOp.getConf().getTagOrder()) {
      if (tag != pos) {
        return false;
      }
      pos++;
    }

    return true;
  }

  private static String skewJoinPrefix = "hive_skew_join";
  private static String UNDERLINE = "_";
  private static String BIGKEYS = "bigkeys";
  private static String SMALLKEYS = "smallkeys";
  private static String RESULTS = "results";

  static Path getBigKeysDir(Path baseDir, Byte srcTbl) {
    return new Path(baseDir, skewJoinPrefix + UNDERLINE + BIGKEYS + UNDERLINE + srcTbl);
  }

  static Path getBigKeysSkewJoinResultDir(Path baseDir, Byte srcTbl) {
    return new Path(baseDir, skewJoinPrefix + UNDERLINE + BIGKEYS
        + UNDERLINE + RESULTS + UNDERLINE + srcTbl);
  }

  static Path getSmallKeysDir(Path baseDir, Byte srcTblBigTbl,
      Byte srcTblSmallTbl) {
    return new Path(baseDir, skewJoinPrefix + UNDERLINE + SMALLKEYS
        + UNDERLINE + srcTblBigTbl + UNDERLINE + srcTblSmallTbl);
  }

}


text:
<?php

namespace MyApp\ArticleBundle\Services;

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ArticleManager {

    private $em;
    private $repository;
    private $repositorydebat;

    public function __construct(EntityManager $em) {
        $this->em = $em;
        $this->repository = $em->getRepository('MyAppArticleBundle:article');
        $this->repositorydebat = $em->getRepository('MyAppForumBundle:sujet');
    }

    public function Disponiblitedelapositionchoisie($positiondelarticleenajout) {
        $contenudelapositionchoisie = $this->repository->getDisponiblite($positiondelarticleenajout);
        if (empty($contenudelapositionchoisie)) {
            $lapositionchoisie = 'vide';      /* position disponible */
        }
        if (!empty($contenudelapositionchoisie) && ($contenudelapositionchoisie[0]->getFixedposition() == 1)) {
            $lapositionchoisie = 'contenufixe';      /* position non disponible */
        }
        if (!empty($contenudelapositionchoisie) && ($contenudelapositionchoisie[0]->getFixedposition() == 0)) {
            $lapositionchoisie = 'contenuNONfixe';      /* position non disponible */
        }
        return $lapositionchoisie;
    }

    public function getOne($id) {
        return $this->repository->find($id);
    }

    public function getARnumber() {
        return intval($this->repository->getARnumber()); /* return int qui contient 'number de AR' */
    }

    public function traitementenajout($positiondelarticleenajout, $fixedpositionChecked, $lapositionchoisie, $articleNOfixedposition, $premierepositionlibre, $article) {

        if (($positiondelarticleenajout === 1) && ($fixedpositionChecked === TRUE)) {
            /*             * * j 'affecte l a'rticle a la premiere position libre       ** */
            if ($lapositionchoisie != 'contenufixe') {
                $article->setPosition($positiondelarticleenajout);
                if (!empty($articleNOfixedposition)) {
                    $this->ShiftToLeftNofixedPosition($positiondelarticleenajout);
                }
                $this->persist($article);
            } elseif ($lapositionchoisie === 'contenufixe') {
                $message = "STOP. The chosen position is fixed. Please unfix this position first.";
                return $message;
            }
        }
        if (($positiondelarticleenajout === 1) && ($fixedpositionChecked === FALSE)) {
            /*             * **    j 'affecte l a'rticle a la premiere position libre      *** */
            $article->setPosition($premierepositionlibre);
            $this->persist($article);
        }
        if (($positiondelarticleenajout != 1) && ($fixedpositionChecked === TRUE)) {
            if ($lapositionchoisie != 'contenufixe') {
                if (!empty($articleNOfixedposition)) {
                    $this->ShiftToLeftNofixedPosition($positiondelarticleenajout);
                }
                $article->setPosition($positiondelarticleenajout);
                $this->persist($article);
            } elseif ($lapositionchoisie === 'contenufixe') {
                $message = "STOP. The chosen position is fixed. Please unfix this position first.";
                return $message;
            }
        }
        if (($positiondelarticleenajout != 1) && ($fixedpositionChecked === FALSE)) {
            if ($lapositionchoisie != 'contenufixe') {
                $article->setPosition($positiondelarticleenajout);
                $this->persist($article);
            } elseif ($lapositionchoisie === 'contenufixe') {
                $message = "STOP. The chosen position is fixed. Please unfix this position first.";
                return $message;
            }
        }
    }

    public function ShiftToLeftNofixedPosition($position) {

        $ArticleNOFixedPosition = $this->repository->getArticleNOFixedPosition();
        $totalnumberofar = intval($this->repository->getARnumber()); /* nombre ancien des AR je vais l incrementer +1 */

        if (count($ArticleNOFixedPosition) == 1) {
            $ArticleNOFixedPosition[0]->setPosition($totalnumberofar + 1);
            $this->persist($ArticleNOFixedPosition[0]);
        } elseif (count($ArticleNOFixedPosition) > 1) {

            $index = 1;
            do { /* les ar apres celle en ajout translate */
                if ($position <= $ArticleNOFixedPosition[count($ArticleNOFixedPosition) - $index]->getPosition()) {
                    $ArticleNOFixedPosition[count($ArticleNOFixedPosition) - $index]
                            ->setPosition($ArticleNOFixedPosition[count($ArticleNOFixedPosition) - ($index + 1)]->getPosition());
                }
                $index++;
            } while ((count($ArticleNOFixedPosition) > $index));
        }

        if ($position < $ArticleNOFixedPosition[0]->getPosition()) {
            $ArticleNOFixedPosition[0]->setPosition($totalnumberofar + 1);
            $this->persist($ArticleNOFixedPosition[0]);
        }
    }

    public function ShiftToRightNofixedPositionOneDelete($selectarticle) {
        $ArticleNOFixedPosition = $this->repository->getArticleNOFixedPosition();
        if ($ArticleNOFixedPosition != NULL) {

            $position = $selectarticle->getPosition();
            $pos = array(); /* tableau des objets a translater :D */
            foreach ($ArticleNOFixedPosition as $s) {
                $a = $s->getPosition();
                if ($a > $position) {
                    array_push($pos, $a);  /* ajouter la position au tableau vide */
                }
            }
            $index = 0;

            if ($position < $ArticleNOFixedPosition[$index]->getPosition()) {
                if (count($ArticleNOFixedPosition) > 1) {
                    do {
                        $ArticleNOFixedPosition[$index]->setPosition($ArticleNOFixedPosition[$index + 1]->getPosition());
                        $index++;
                    } while ($index < count($pos));
                } else {
                    $ArticleNOFixedPosition[$index]->setPosition($position);
                }
            }
        }
    }

    public function debatsortedmostcommented() {

        $sujet = $this->repositorydebat->getAllsujetrecent();
        /*  sortedtopic by comment */
        $commentarray = array(); // tableau vide
        $sortedtopic = array(); // tableau vide
        foreach ($sujet as $s) {
            $commentCount = $this->repositorydebat->getCommentCountBySujet($s->getId());
            if ($commentCount > 0) {
                array_push($commentarray, $commentCount);
            }/* inserer la valeur dans l array vide */
        }
        rsort($commentarray); /* tri du tableau selon value */

        for ($index = 0; $index < count($commentarray); $index++) {
            for ($jndex = 0; $jndex < count($sujet); $jndex++) {
                if ($this->repositorydebat->getCommentCountBySujet($sujet[$jndex]->getId()) == $commentarray[$index]) {

                    if (!in_array($sujet[$jndex], $sortedtopic)) {
                        array_push($sortedtopic, $sujet[$jndex]);
                    } /* inserer la valeur si elle n'existe pas deja dans l array vide */
                }
            }
        }
        return $sortedtopic;
    }

    public function makeFixorUnfix($fixedornotvalue) {
        $article = $this->repository->findAll();
        if ($fixedornotvalue != NULL) {
            foreach ($article as $a) {
                if (in_array($a->getId(), array_values($fixedornotvalue))) {
                    $this->makeFIX($a);
                } else {
                    $this->makeUNFIX($a);
                }
            }
        }
    }

    public function getallarticleId($article) {
        if ($article != NULL) {
            return array_values($article);
        }
    }

    public function getfixedarticleId($fixedarticle) {
        if ($fixedarticle != NULL) {
            return array_values($fixedarticle);
        }
    }

    public function UpdatePosition($positions) {
        $article = $this->repository->findAll();
        if ($positions != NULL) {
            for ($index = 0; $index < count($positions); $index++) {
                if (
                        $article[$index]->getPosition() != $positions[$index]) {
                    $article[$index]->setPosition($positions[$index]);
                    $this->persist($article[$index]);
                }
            }
        }
    }

    public function makeFIX($article) {
        $article->setFixedposition(1);
        $this->persist($article);
        return $article;
    }

    public function makeUNFIX($article) {
        $article->setFixedposition(0);
        $this->persist($article);
        return $article;
    }

    public function removemore($article) {
        foreach ($article as $s) {
            $this->em->remove($s);
            $this->em->flush();
        }
        return $article;
    }

    public function getAll() {
        return $this->repository->findAll();
    }

    public function getArticleWithFixedPosition() {
        return $this->repository->getArticleWithFixedPosition();
    }

    public function getArticleNOFixedPosition() {
        return $this->repository->getArticleNOFixedPosition();
    }

    public function getPositionOccuped() {
        return $this->repository->getPositionOccuped();
    }

    public function getFirstPositionFree($lespositionsoccupés) {
        $pos = array(); // tableau vide
        $positionlibre = array(); // tableau vide
        foreach ($lespositionsoccupés as $s) {
            $a = $s->getPosition(); // recupere les positions des artciles ajoutés
            array_push($pos, $a);  // ajouter la position au tableau vide
        }
        if (!in_array("1", $pos)) {
            array_push($positionlibre, 1);
        }
        if (!in_array("2", $pos)) {
            array_push($positionlibre, 2);
        }
        if (!in_array("3", $pos)) {
            array_push($positionlibre, 3);
        }
        if (!in_array("4", $pos)) {
            array_push($positionlibre, 4);
        }
        if (!in_array("5", $pos)) {
            array_push($positionlibre, 5);
        }
        if (!in_array("6", $pos)) {
            array_push($positionlibre, 6);
        }
        if (!in_array("7", $pos)) {
            array_push($positionlibre, 7);
        }
        if (!in_array("8", $pos)) {
            array_push($positionlibre, 8);
        }
        if (!in_array("9", $pos)) {
            array_push($positionlibre, 9);
        }
        if (!in_array("10", $pos)) {
            array_push($positionlibre, 10);
        }
        if (!in_array("11", $pos)) {
            array_push($positionlibre, 11);
        }
        if (!in_array("12", $pos)) {
            array_push($positionlibre, 12);
        }
        if (!in_array("13", $pos)) {
            array_push($positionlibre, 13);
        }
        if (!in_array("14", $pos)) {
            array_push($positionlibre, 14);
        }
        if (!in_array("15", $pos)) {
            array_push($positionlibre, 15);
        }
        $premierepositionlibre = reset($positionlibre); // integer => premiere position libre
        return $premierepositionlibre;
    }

    public function persist($article) {
        $this->doFlush($article);
    }

    public function remove($article) {
        $this->em->remove($article);
        $this->em->flush();
    }

    public function doFlush($article) {
        $this->em->persist($article);
        $this->em->flush();
        return $article;
    }

}

redpajama_set_name: RedPajamaGithub


text:
using std::shared_ptr;
using std::unique_ptr;
using std::vector;
using std::set;

namespace Polarity {
class Canvas;

class World {
    bool loaded;
    b2World physics;
    b2Vec2 graphicsScale;
    b2Vec2 camera;
    ContactListener contactListener;
    b2Vec2 screenDimensions;
    b2Vec2 mapDimensions;
    std::set<int> keyState;
    std::set<int> keyPressedThisTick;
    vector< unique_ptr<GameObject> > objects;
    unique_ptr<LayerCollection> layers;
    shared_ptr<AudioChannelPlayer> fAudioPlayer;
    shared_ptr<PlayerState> fPlayerState;
    shared_ptr<GameState> fGameState;

    shared_ptr<Canvas> graphicsContext;

    std::shared_ptr<World> backgroundWorld;
    std::weak_ptr<World> wthis;
public:
    virtual ~World();
    //int pn = 1; //player polarity, this should prob be set in player state
    //int EMoff = 1; //EM force ON or OFF
    GameObject*player;
    b2Vec2 getCamera()const {
        return camera;
    }
    void updateCamera(GameObject *obj, b2Vec2 player);
    static void init(const shared_ptr<Canvas> &canvas, shared_ptr<AudioChannelPlayer> audioPlayer, shared_ptr<PlayerState> playerState, shared_ptr<GameState> gameState, const char *tmxFile=nullptr);
    shared_ptr<World> loadNewWorld(const std::string& tmxFile);
    void setBackgroundWorld(shared_ptr<World> newWorld);
    void switchToBackgroundWorld();
    World(const shared_ptr<Canvas> &canvas, std::shared_ptr<AudioChannelPlayer> audioPlayer, shared_ptr<PlayerState> _playerState, shared_ptr<GameState> _gameState);
    void addObject(Behavior*behavior, const b2BodyDef&, const std::vector<b2FixtureDef>&fixture, const std::string &name, GameObject::Type type, const PropertyMap &properties);
    void tick();
    void draw(Canvas *screen);
    void keyEvent(int keyCode, bool pressed);
    bool isKeyDown(int keyCode);
    bool wasKeyJustPressed(int keyCode);
    std::weak_ptr<World> weak_ptr()const {return wthis;}
    const shared_ptr<Canvas> &getGraphicsContext() const {
        return graphicsContext;
    }
    class TmxMapWrapper;

    bool isLoaded() const {
        return loaded;
    }

    const std::set<int> &getKeyState() const {
        return keyState;
    }

    shared_ptr<AudioChannelPlayer> audio() {
        return fAudioPlayer;
    }

    shared_ptr<GameState> gameState() {
        return fGameState;
    }

    shared_ptr<PlayerState> playerState() {
        return fPlayerState;
    }

    b2Vec2 graphicsToPhysics(const b2Vec2 &vec, float isBounds=-1) {
        return b2Vec2(vec.x / graphicsScale.x, vec.y / graphicsScale.y * isBounds);
    }

    b2Vec2 physicsToGraphics(const b2Vec2 &vec, float isBounds=-1) {
        return b2Vec2(vec.x * graphicsScale.x, vec.y * graphicsScale.y * isBounds);
    }
    b2World *getPhysicsWorld() {
        return &physics;
    }

private:
    void load(const std::string& tmxFile);
    static void load_async(const std::weak_ptr<World> &weakThis, const std::string &tmxFile,
                           const char * data, int size);
    static void finalizeLoad(const std::weak_ptr<World> &weakThis,
                             const std::string &tmxFile,
                             TmxMapWrapper *data);
};
extern std::shared_ptr<World> world;
}
#endif


text:
#include "pagespeed/kernel/base/md5_hasher.h"

#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
//#include "base/md5.h"
// using base::MD5Digest;

// XXX(oschaaf): hmm, kind of heavyweight.
#include <openssl/md5.h>

namespace net_instaweb {

namespace {

// const int kMD5NumBytes = sizeof(MD5Digest);

}  // namespace

MD5Hasher::~MD5Hasher() {}

GoogleString MD5Hasher::RawHash(const StringPiece& content) const {
  // Note:  It may seem more efficient to initialize the MD5Context
  // in a constructor so it can be re-used.  But a quick inspection
  // of src/third_party/chromium/src/base/md5.cc indicates that
  // the cost of MD5Init is very tiny compared to the cost of
  // MD5Update, so it's better to stay thread-safe.
  // MD5Digest digest;
  // MD5Sum(content.data(), content.size(), &digest);
  //// Note: digest.a is an unsigned char[16] so it's not null-terminated.
  // GoogleString raw_hash(reinterpret_cast<char*>(digest.a), sizeof(digest.a));
  // return raw_hash;
  unsigned char result[MD5_DIGEST_LENGTH];
  MD5(reinterpret_cast<const unsigned char*>(content.data()), content.size(),
      result);
  return GoogleString(reinterpret_cast<char*>(result), MD5_DIGEST_LENGTH);
}

int MD5Hasher::RawHashSizeInBytes() const { return MD5_DIGEST_LENGTH; }

}  // namespace net_instaweb


text:
package com.BASeCamp.SurvivalChests.Events;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

import com.BASeCamp.SurvivalChests.GameTracker;

public class GameEndEvent extends Event {
    private static final HandlerList handlers = new HandlerList();
    private String message;
    private String _winner = null;
    private GameTracker _Tracker = null;

    private HashMap<Integer,String> Placers;

    public GameTracker getTracker(){ return _Tracker;}
    /**
     * @Deprecated use getWinner() method instead.
     * @return
     */
    public Player getPlayer() { return Bukkit.getPlayer(_winner);}

    private void setPlayer(Player value) { _winner = value.getName();}

    public Player getWinner() { return Bukkit.getPlayer(_winner);}

    /**
     * retrieves all Participants for the game that just ended.
     * @return Participants of the ending game.
     */
    public List<Player> getAllParticipants(){
    	LinkedList<Player> buildlisting = new LinkedList<Player>();
    	for(String p:Placers.values()){

    		buildlisting.add(Bukkit.getPlayer(p));

    	}
    	return buildlisting;

    }

    /**
     * returns player that made the given place.
     * @param placement place to retrieve. 1 for 1st place, 2 for second place, etc.
     * @return the Player that made the given place, or null if there is no player at that place.
     */
    public Player getPlacer(int placement){

    	if(!Placers.containsKey(placement)){
    		return null;
    	}

    	return Bukkit.getPlayer(Placers.get(placement));

    }

    public GameEndEvent(Player winner,HashMap<Integer,String> PlaceOrder,GameTracker trackerobject) {
        _winner=winner.getName();
        Placers = PlaceOrder;
        _Tracker = trackerobject;
    }

    public String getMessage() {
        return message;
    }

    public HandlerList getHandlers() {
        return handlers;
    }

    public static HandlerList getHandlerList() {
        return handlers;
    }
}


text:
package com.redhat.ceylon.compiler.java.test.interop.mixed.independent;

public class Java {

}


text:
from django.template import Library

register = Library()

@register.filter
def get_range(value):
    """
    Filter - returns a list containing range made from given value
    Usage (in template):

{% for i in 3|get_range %}

{{ i }}. Do something

    {% endfor %}

    Results with the HTML:

0. Do something

1. Do something

2. Do something

    Instead of 3 one may use the variable set in the sviews
    """
    return range(value)

@register.filter
def get_range1(value):
    return range(1, value + 1)

@register.filter
def get_user_ticket(tickets, user):
    return tickets[user].ticket_type

@register.filter
def get_dict_val(dictionary, key):
    return dictionary.get(key)

@register.simple_tag
def divide(dividend, divisor):
    if divisor == 0:
        return 0
    return dividend / float(divisor)

@register.simple_tag
def divide_percent(dividend, divisor):
    if divisor == 0:
        return '0%'
    return '{val:.2f}%'.format(val=(dividend / float(divisor) * 100))

@register.simple_tag
def subtract(minuend, subtrahend):
    return minuend - subtrahend


text:
<?php

function include_design_element($designElement)
{
  echo get_design_element($designElement);
}

function get_design_element($designElement)
{
  $options = array(
    'params'   => $designElement['params'],
    'subject'  => $designElement['Object'],
    'contents' => $designElement['Contents']
  );

  if(is_string($designElement['config']['include']))
  {
    return get_partial($designElement['config']['include'], $options);
  }

  return get_component($designElement['config']['include'][0], $designElement['config']['include'][1], $options);
}


text:
package com.ait.tooling.server.core.security;

import java.io.Closeable;

public interface ICryptoProvider extends ICryptoKeysGenerator, IStringSigningProvider, IStringCryptoProvider, IBCryptHashProvider, ISHA512HashProvider, Closeable
{
}


text:
package org.secnod.example.webapp;

import org.apache.shiro.SecurityUtils;
import org.secnod.shiro.jersey.TypeFactory;

public class UserFactory extends TypeFactory<User> {

    public UserFactory() {
        super(User.class);
    }

    @Override
    public User provide() {
        return new User(SecurityUtils.getSubject());
    }
}


text:
    <alert type="warning" ng-show="!story">Woah no such story :-/</alert>

        {{story.title}}

        {{story.body}}

            {{story.created | amCalendar}}

            {{story.__creator.profile.name}}

            <button class="btn btn-default btn-xs" ng-click="star()" ng-disabled="!canStar">

              {{ ' ' + (isStarred ? 'Unstar' : 'Star') }}
            </button>

            {{story.stars}}

            {{story.__category.title}}

               Edit

            <button class="btn btn-danger btn-xs btn-block" ng-click="remove()">
               Remove
            </button>


text:
import ma = require('azure-pipelines-task-lib/mock-answer');
import tmrm = require('azure-pipelines-task-lib/mock-run');
import path = require('path');
import { emit } from 'cluster';
import { emitTelemetry } from '../xcodeutils';

let taskPath = path.join(__dirname, '..', 'xcode.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);

tr.setInput('actions', 'test');
tr.setInput('configuration', '$(Configuration)');
tr.setInput('sdk', '$(SDK)');
tr.setInput('xcWorkspacePath', '**/*.xcodeproj/*.xcworkspace');
tr.setInput('scheme', 'myscheme');
tr.setInput('packageApp', 'false');
tr.setInput('signingOption', 'default');
tr.setInput('signingIdentity', '');
tr.setInput('provisioningProfileUuid', '');
tr.setInput('args', '');
tr.setInput('cwd', '/user/build');
tr.setInput('xcodeVersion', 'default');
tr.setInput('xcodeDeveloperDir', '');
tr.setInput('useXcpretty', 'false');
tr.setInput('publishJUnitResults', 'true');

tr.registerMock('./xcodeutils', {
    getUniqueLogFileName: function (logPrefix: string) {
        return '/build/temp' + logPrefix + '.log';
    },
    emitTelemetry: function(area: string, feature: string, taskSpecificTelemetry: { [key: string]: any; }) {
        console.log('Xcode task telemetry');
    }
});

process.env['AGENT_VERSION'] =  '2.122.0';
process.env['BUILD_SOURCESDIRECTORY'] = '/user/build';
process.env['SYSTEM_DEFAULTWORKINGDIRECTORY'] = "/user/build";
process.env['HOME'] = '/users/test'; //replace with mock of setVariable when task-lib has the support

// provide answers for task mock
let a: ma.TaskLibAnswers = <ma.TaskLibAnswers> {
    "which": {
        "xcodebuild": "/home/bin/xcodebuild",
        "xcpretty": "/home/bin/xcpretty"
    },
    "checkPath" : {
        "/home/bin/xcodebuild": true,
        "/home/bin/xcpretty": true
    },
    "findMatch": {
        "**/*.xcodeproj/*.xcworkspace": [
            "/user/build/fun.xcodeproj/project.xcworkspace"
        ],
        "/user/build": [
            "/user/build/build/reports/junit.xml"
        ]
    },
    "getVariable": {
        "build.sourcesDirectory": "/user/build",
        "HOME": "/users/test"
    },
    "exec": {
        "/home/bin/xcodebuild -version": {
            "code": 0,
            "stdout": "Xcode 7.3.1"
        },
        "/home/bin/xcodebuild -sdk $(SDK) -configuration $(Configuration) -workspace /user/build/fun.xcodeproj/project.xcworkspace -scheme myscheme test | /home/bin/xcpretty -r junit --no-color": {
            "code": 0,
            "stdout": "xcodebuild | xcpretty output here"
        },
        "/home/bin/xcodebuild -sdk $(SDK) -configuration $(Configuration) -workspace /user/build/fun.xcodeproj/project.xcworkspace -scheme myscheme test": {
            "code": 0,
            "stdout": "xcodebuild output without xcpretty here"
        }
    }
};
tr.setAnswers(a);

tr.run();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;

namespace BionicLab10
{
    /// <summary>
    /// Логика взаимодействия для ViewLog.xaml
    /// </summary>
    public partial class ViewLog : Window
    {
        private XmlDocument _xmlDoc;
        public ViewLog()
        {
            InitializeComponent();
            _xmlDoc = new XmlDocument();
        }

        private void ViewLog_Load(object sender, EventArgs e)
        {
            _xmlDoc.Load("log.xml");
            XmlNodeList nodes = _xmlDoc.GetElementsByTagName("date");
            TreeViewLog.Items.Clear();
            TreeViewItem core = new TreeViewItem();
            core.Header = "log";
            List<TreeViewItem> firstLevel = new List<TreeViewItem>();
            int n = 0;
            foreach (XmlNode node in nodes)
            {
                firstLevel.Add(new TreeViewItem());
                firstLevel[n].Header = node.Attributes["id"].Value;
                List<TreeViewItem> secondLevel = new List<TreeViewItem>();
                int k=0;
                foreach (XmlNode m in node.ChildNodes)
                {
                    string str = m.Attributes["name"].Value + " " + m.Attributes["status"].Value;
                    secondLevel.Add(new TreeViewItem());
                    secondLevel[k].Header = str;
                    firstLevel[n].Items.Add(secondLevel[k]);
                    k++;
                }
                core.Items.Add(firstLevel[n]);
                n++;
            }
            TreeViewLog.Items.Add(core);
        }
    }
}


text:
namespace BestPlaylists.Services.Data
{
    using System;
    using System.Linq;

    using BestPlaylists.Data.Models;
    using BestPlaylists.Data.Repositories;
    using BestPlaylists.Services.Data.Contracts;

    public class UserService : IUserService
    {
        private readonly IRepository<User> usersRepo;

        public UserService(IRepository<User> usersRepo)
        {
            this.usersRepo = usersRepo;
        }

        public User GetById(string id)
        {
            return this.usersRepo.GetById(id);
        }

        public IQueryable<User> GetAll()
        {
            return this.usersRepo.All();
        }

        public User GetByUserName(string userName)
        {
            return this.usersRepo.All().FirstOrDefault(x => x.UserName == userName);
        }

        public void Update(User user)
        {
            this.usersRepo.Update(user);
            this.usersRepo.SaveChanges();
        }

        public void Remove(string id)
        {
            User userToDelete = this.usersRepo.GetById(id);

            if (userToDelete != null)
            {
                this.usersRepo.Delete(userToDelete);

                this.usersRepo.SaveChanges();
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Drowsy Driving</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/grayscale.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                    Home

                        Experiment

                        Results

                        More

Drowsy Driving

Robert Peters 1999

Experiment

A study to investigate the effects of sleep deprivation on driving performance was conducted by FHWA's Human Factors Laboratory and the Walter Reed Army Institute of Research. The study examined the effects of progressive sleep deprivation on driving performance to assess the rate of crashes and  changes in driving performance resulting from sleepiness. A variety of measures, including continuous electroencephalogram monitoring, and analyses of driving performance data were used to determine the effects of sleep deprivation on driving performance. The experiment setup is visualized in the graph below:

Citation: https://goo.gl/ujstzH

Results

The driving data confirmed that sleepiness is a significant factor that can lead to off-road crashes. As seen in the figure below, crash rates showed a small increase after a moderate reduction in the previous night's sleep, four hours versus eight hours, and a marked increase with progressive sleep deprivation.

While the increase in crash rate after partial sleep deprivation did not reach statistical significance, it should be noted that a relatively small sample of young, healthy subjects was used and that the effects of continuous driving for long periods of time were not assessed.

Citation: https://goo.gl/ujstzH

More

While driving drowsy is dangerous, the following video explores the compounded dangers of driving while drowsy and intoxicated:


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

<title>Uses of Class jason.environment.TimeSteppedEnvironment (Jason - AgentSpeak Java Interpreter)</title>
<meta name="date" content="2013-12-12">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
jason.environment.TimeSteppedEnvironment

Packages that use TimeSteppedEnvironment

Package
Description

jason.environment

Uses of TimeSteppedEnvironment in jason.environment

Subclasses of TimeSteppedEnvironment in jason.environment

Modifier and Type
Class and Description

class
SteppedEnvironment

Deprecated.

this class was renamed to TimeSteppedEnvironment

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.chopin.chopin.fragments.FragmentWithMap">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/tolbar" />

    <ListView
        android:id="@+id/list_view"
        android:listSelector="@android:color/transparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
        android:dividerHeight="5dp" />

</LinearLayout>


text:
/*
 * otr4j, the open source java otr library.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.otr4j.io.messages;

import java.security.PublicKey;

import javax.crypto.interfaces.DHPublicKey;

/**
 *
 * @author George Politis
 */
public class SignatureM {
	// Fields.
	public DHPublicKey localPubKey;
	public DHPublicKey remotePubKey;
	public PublicKey localLongTermPubKey;
	public int keyPairID;

	// Ctor.
	public SignatureM(DHPublicKey localPubKey, DHPublicKey remotePublicKey,
			PublicKey localLongTermPublicKey, int keyPairID) {

		this.localPubKey = localPubKey;
		this.remotePubKey = remotePublicKey;
		this.localLongTermPubKey = localLongTermPublicKey;
		this.keyPairID = keyPairID;
	}

	// Methods.
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + keyPairID;
		// TODO: Needs work.
		result = prime
				* result
				+ ((localLongTermPubKey == null) ? 0 : localLongTermPubKey
						.hashCode());
		result = prime * result
				+ ((localPubKey == null) ? 0 : localPubKey.hashCode());
		result = prime * result
				+ ((remotePubKey == null) ? 0 : remotePubKey.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		// TODO: Needs work.
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SignatureM other = (SignatureM) obj;
		if (keyPairID != other.keyPairID)
			return false;
		if (localLongTermPubKey == null) {
			if (other.localLongTermPubKey != null)
				return false;
		} else if (!localLongTermPubKey.equals(other.localLongTermPubKey))
			return false;
		if (localPubKey == null) {
			if (other.localPubKey != null)
				return false;
		} else if (!localPubKey.equals(other.localPubKey))
			return false;
		if (remotePubKey == null) {
			if (other.remotePubKey != null)
				return false;
		} else if (!remotePubKey.equals(other.remotePubKey))
			return false;
		return true;
	}

}


text:
require_relative 'src/such_userstream_bot.rb'
require "twitter"
require "tweetstream"

Twitter.configure do |config|
  config.consumer_key       = ENV['TWITTER_CONSUMER_KEY']
  config.consumer_secret    = ENV['TWITTER_CONSUMER_SECRET']
  config.oauth_token        = ENV['TWITTER_OAUTH_TOKEN']
  config.oauth_token_secret = ENV['TWITTER_OAUTH_SECRET']
end

TweetStream.configure do |config|
  config.consumer_key       = ENV['TWITTER_CONSUMER_KEY']
  config.consumer_secret    = ENV['TWITTER_CONSUMER_SECRET']
  config.oauth_token        = ENV['TWITTER_OAUTH_TOKEN']
  config.oauth_token_secret = ENV['TWITTER_OAUTH_SECRET']
  config.auth_method        = :oauth
end

TweetStream::Client.new.userstream do |tweet|

  # your bot should have a method called respond_to(text)
  # when someone tweets @ your bot, it will reply back!
  puts "@#{tweet.user.screen_name} asks: #{tweet.text}"
  begin
    puts (answer = SuchUserstreamBot.respond_to tweet.text)
    Twitter.update(answer, :in_reply_to_status_id => tweet.id)
  rescue => e
    puts e
  end
end


text: Tool zur Verwaltung des Online-Videorecorders www.save.tv


text:
namespace serializable {

/// @class member
/// @brief serializable class member.
template <typename T>
class member : public abstract_member {
    public:
        /// init c'tor
        member(const std::string& name,
               const T& value,
               abstract_object& owner)
            : abstract_member(), m_name(name), m_value(value) {
            owner.register_member(this);
        }

        /// @return name of the member
        virtual const std::string& get_name() const noexcept override {
            return m_name;
        }

        /// @return current value of the member
        const T& get_value() const noexcept {
            return m_value;
        }

        /// @param value new value for the member
        void set_value(const T& value) noexcept {
            m_value = value;
        }

        /// @return true when given member is a string value
        virtual bool is_string() const noexcept override {
            return std::is_same<T, std::string>::value;
        }

        /// @return true when given member is a object value
        virtual bool is_object() const noexcept override {
            return false;
        }

        /// @return converts given member into a string value
        virtual std::string to_string() const noexcept override {
            std::stringstream stream;
            stream << m_value;
            return stream.str();
        }

    private:
        /// name of the class member
        const std::string m_name;
        /// value of the class member
        T m_value;
};

/// @class member
/// @brief serializable class member being an object.
/// @note this member takes ownership of the assigned object.
template <typename T>
class object_member : public abstract_member {
    public:
        /// init c'tor
        /// @param name is name of the class member
        /// @param obj is the pointer to the new allocated/assigned object instance
        /// @param owner is the owner of this class member
        object_member(const std::string& name, T* obj, abstract_object& owner)
            : abstract_member(), m_name(name), m_object(obj) {
            static_assert(std::is_base_of<abstract_object, T>::value,
                          "Base class is not serializable::abstract_object!");
            owner.register_member(this);
        }

        /// @return name of the member
        virtual const std::string& get_name() const noexcept override {
            return m_name;
        }

        /// @return true when given member is a string value
        virtual bool is_string() const noexcept override {
            return false;
        }

        /// @return always true (member does keep an object instance only).
        virtual bool is_object() const noexcept override {
            return true;
        }

        /// @return always an empty string (for now)
        virtual std::string to_string() const noexcept override {
            return "";
        }

        /// @return current object instance
        const T* get_value() const noexcept {
            return m_object.get();
        }

        /// @param obj new object for the member
        void set_value(T* obj) noexcept {
            m_object.reset(obj);
        }

    private:
        /// name of the class member
        const std::string m_name;
        /// instance of a serializable object
        std::shared_ptr<T> m_object;
};

}  // namespace serializable

#endif  // INCLUDE_SERIALIZABLE_MEMBER_H_


text:
<?xml version="1.0" encoding="utf-8" ?>
<LearningStandardItem RefId="29419E561D0F4947929F5400799CB6ED" xml:lang="en">
  <StandardHierarchyLevel>
    <Number>4</Number>
    <Description>Cluster</Description>
  </StandardHierarchyLevel>
  <PredecessorItems>
    <LearningStandardItemRefId>193ACFCEF9554E9095FF14921505EB09</LearningStandardItemRefId>
  </PredecessorItems>
  <StatementCodes>
    <StatementCode>Mathematics.8.EE.3</StatementCode>
  </StatementCodes>
  <Statements>
    <Statement>Analyze and solve linear equations and pairs of simultaneous linear equations.</Statement>
  </Statements>
  <GradeLevels>
    <GradeLevel>8</GradeLevel>
  </GradeLevels>
  <LearningStandardDocumentRefId>B62C1C106873438AA0126760075A65A3</LearningStandardDocumentRefId>
</LearningStandardItem>


text:
<?php

namespace JF\CalendarBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use JF\CoreBundle\DependencyInjection\Interfaces\IExtension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class JFCalendarExtension extends Extension implements IExtension, Interfaces\ITipiEventi {

    use Traits\CalendarExtension;

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container) {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $this->configure($container);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.xml');
    }

    public function setInstall(ContainerBuilder $container) {
        $install = $container->getParameter('jf.install');

        $this->newInstall($install, '\JF\CalendarBundle\Controller\InstallController', 'indexAction');

        $container->setParameter('jf.install', $install);
    }

    public function setMenu(ContainerBuilder $container) {
        $menu = $container->getParameter('jf.menu');

        if ($container->getParameter('jf.mode') == 'online') {
            $menu['utility']['submenu'][] = array(
                'label' => 'Calendario personale',
                'route' => 'calendario_personale',
                'show' => array(
                    'logged' => true
                ),
                'order' => 90,
            );
        }

        $container->setParameter('jf.menu', $menu);
    }

    public function setPackage(ContainerBuilder $container) {
        $package = $container->getParameter('jf.package');

        $this->newPackage($package, 'jf.cal', 'CAL', 0, true);

        $container->setParameter('jf.package', $package);
    }

    public function setRoles(ContainerBuilder $container) {

    }

    public function setWidgets(ContainerBuilder $container) {

    }

    public function setTipoEventi(ContainerBuilder $container) {
        $tipiEvento = array();

        $this->newTipoEvento($tipiEvento, 'System', 'JFS', 'JF-System', 'ff0000', false, false, false, false);
        $this->newTipoEvento($tipiEvento, 'System', 'JFP', 'JF-System', 'ff0000', false, false, true, false);
        $this->newTipoEvento($tipiEvento, 'Office', 'APP', 'Appuntamento', '0000aa', true, true, false, true);
        $this->newTipoEvento($tipiEvento, 'Office', 'PRM', 'Promemoria', '00aa00', true, true, false, true);
        $this->newTipoEvento($tipiEvento, 'Office', 'SCD', 'Scadenza', 'aa0000', true, true, false, true);
        $this->newTipoEvento($tipiEvento, 'Office', 'RIC', 'Riunione con cliente', '00aaaa', true, true, false, true);
        $this->newTipoEvento($tipiEvento, 'Office', 'RIU', 'Riunione ufficio', '00aaaa', true, true, true, true);

        $container->setParameter('jf.tipi_evento', $tipiEvento);
    }

    public function setSync(ContainerBuilder $container) {

    }

}


text:
/**
 *  Cracking the coding interview edition 6
 *  Problem 2.4 Partition:
 *  Write code to partition linked list around a value x, such that
 *  nodes less than x come before all the nodes greater than or equal to x.
 *  If x is in the list, the values of x only need to be after the elements less
 *  than x.
 *  Example
 *  3-->5-->8-->5-->10-->2-->1 (x = 5)
 *  3-->1-->2-->10-->5-->5-->8
 *
 *  Approach:
 *  Start with first node, and add every thing bigger or equal to x at tail
 *  and smaller values at head.
 */

#include <iostream>
#include <random>

struct Node {
  int data;
  Node * next;
  Node( int d ) : data{ d }, next{ nullptr } { }
};

void insert( Node * & head, int data ) {
  Node * newNode = new Node(data);
  if ( head == nullptr ) {
    head = newNode;
  } else {
    Node * curr = head;
    while( curr->next ) {
      curr = curr->next;
    }
    curr->next = newNode;
  }
}

void printList( Node * head ) {
  while ( head ) {
    std::cout << head->data << "-->";
    head = head->next;
  }
  std::cout << "nullptr" << std::endl;
}

 /* We start with a new list. Elements bigger than the pivot element are put at the tail list
 and elements smaller are put at the head list*/
Node * partition( Node * listhead , int x ) {
   Node * head = nullptr;
   Node * headInitial = nullptr;   /*The initial node of list head*/
   Node * tail = nullptr;
   Node * tailInitial = nullptr;   /*The initial node of list tail*/
   Node * curr = listhead;
   while( curr != nullptr ) {
     Node * nextNode = curr->next;
     if ( curr->data < x ) {
            if (head == nullptr) {
                head = curr;
                headInitial = head;
            }
       //insert curr node to head list
       head->next = curr;
       head = curr;
     } else {
            if (tail == nullptr) {
                tail = curr;
                tailInitial = tail;
            }
       // insert curr node to tail list
       tail->next = curr;
       tail = curr;
     }
     curr = nextNode;
   }
   head->next = tailInitial;  /*Now, we connect the head list to tail list.*/
   tail->next = nullptr;
   return headInitial;
 }

int main() {
  Node * head = nullptr;
  for ( int i = 0; i < 10; ++i ) {
		insert(head, rand() % 9);
	}
  std::cout << "List before partition around 5:\n";
  printList(head);
  std::cout << "List after partition around 5:\n";
  printList(partition(head, 5));
  return 0;
}


text:
<?php

namespace Mero\Bundle\BaseBundle\Twig;

use Symfony\Component\Intl\Intl;

/**
 * Country filter for Twig.
 *
 * @author Rafael Mello <merorafael@gmail.com>
 * @license https://github.com/merorafael/MeroBaseBundle/blob/master/LICENSE MIT license
 */
class CountryExtension extends \Twig_Extension
{
    public function __construct()
    {
        if (!class_exists('\Locale')) {
            throw new \RuntimeException('The country extension is needed to use intl-based filters.');
        }
    }

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('country', [
                $this,
                'getCountryName',
            ]),
        );
    }

    /**
     * Return the country name using the Locale class.
     *
     * @param string      $isoCode Country ISO 3166-1 alpha 2 code
     * @param null|string $locale  Locale code
     *
     * @return null|string Country name
     */
    public function getCountryName($isoCode, $locale = null)
    {
        if ($isoCode === null) {
            return;
        }
        if ($locale) {
            \Locale::setDefault($locale);
        }

        return Intl::getRegionBundle()->getCountryName($isoCode);
    }

    public function getName()
    {
        return 'country_extension';
    }
}


text:
// Code generated by k8s code-generator DO NOT EDIT.

// Code generated by client-gen. DO NOT EDIT.

package v1beta2

import (
	"context"
	"time"

	v1beta2 "github.com/kubeflow/arena/pkg/operators/spark-operator/apis/sparkoperator.k8s.io/v1beta2"
	scheme "github.com/kubeflow/arena/pkg/operators/spark-operator/client/clientset/versioned/scheme"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
)

// ScheduledSparkApplicationsGetter has a method to return a ScheduledSparkApplicationInterface.
// A group's client should implement this interface.
type ScheduledSparkApplicationsGetter interface {
	ScheduledSparkApplications(namespace string) ScheduledSparkApplicationInterface
}

// ScheduledSparkApplicationInterface has methods to work with ScheduledSparkApplication resources.
type ScheduledSparkApplicationInterface interface {
	Create(*v1beta2.ScheduledSparkApplication) (*v1beta2.ScheduledSparkApplication, error)
	Update(*v1beta2.ScheduledSparkApplication) (*v1beta2.ScheduledSparkApplication, error)
	UpdateStatus(*v1beta2.ScheduledSparkApplication) (*v1beta2.ScheduledSparkApplication, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*v1beta2.ScheduledSparkApplication, error)
	List(opts v1.ListOptions) (*v1beta2.ScheduledSparkApplicationList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta2.ScheduledSparkApplication, err error)
	ScheduledSparkApplicationExpansion
}

// scheduledSparkApplications implements ScheduledSparkApplicationInterface
type scheduledSparkApplications struct {
	client rest.Interface
	ns     string
}

// newScheduledSparkApplications returns a ScheduledSparkApplications
func newScheduledSparkApplications(c *SparkoperatorV1beta2Client, namespace string) *scheduledSparkApplications {
	return &scheduledSparkApplications{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the scheduledSparkApplication, and returns the corresponding scheduledSparkApplication object, and an error if there is any.
func (c *scheduledSparkApplications) Get(name string, options v1.GetOptions) (result *v1beta2.ScheduledSparkApplication, err error) {
	result = &v1beta2.ScheduledSparkApplication{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do(context.TODO()).
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of ScheduledSparkApplications that match those selectors.
func (c *scheduledSparkApplications) List(opts v1.ListOptions) (result *v1beta2.ScheduledSparkApplicationList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1beta2.ScheduledSparkApplicationList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do(context.TODO()).
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested scheduledSparkApplications.
func (c *scheduledSparkApplications) Watch(opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch(context.TODO())
}

// Create takes the representation of a scheduledSparkApplication and creates it.  Returns the server's representation of the scheduledSparkApplication, and an error, if there is any.
func (c *scheduledSparkApplications) Create(scheduledSparkApplication *v1beta2.ScheduledSparkApplication) (result *v1beta2.ScheduledSparkApplication, err error) {
	result = &v1beta2.ScheduledSparkApplication{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		Body(scheduledSparkApplication).
		Do(context.TODO()).
		Into(result)
	return
}

// Update takes the representation of a scheduledSparkApplication and updates it. Returns the server's representation of the scheduledSparkApplication, and an error, if there is any.
func (c *scheduledSparkApplications) Update(scheduledSparkApplication *v1beta2.ScheduledSparkApplication) (result *v1beta2.ScheduledSparkApplication, err error) {
	result = &v1beta2.ScheduledSparkApplication{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		Name(scheduledSparkApplication.Name).
		Body(scheduledSparkApplication).
		Do(context.TODO()).
		Into(result)
	return
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().

func (c *scheduledSparkApplications) UpdateStatus(scheduledSparkApplication *v1beta2.ScheduledSparkApplication) (result *v1beta2.ScheduledSparkApplication, err error) {
	result = &v1beta2.ScheduledSparkApplication{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		Name(scheduledSparkApplication.Name).
		SubResource("status").
		Body(scheduledSparkApplication).
		Do(context.TODO()).
		Into(result)
	return
}

// Delete takes name of the scheduledSparkApplication and deletes it. Returns an error if one occurs.
func (c *scheduledSparkApplications) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		Name(name).
		Body(options).
		Do(context.TODO()).
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *scheduledSparkApplications) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	var timeout time.Duration
	if listOptions.TimeoutSeconds != nil {
		timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Timeout(timeout).
		Body(options).
		Do(context.TODO()).
		Error()
}

// Patch applies the patch and returns the patched scheduledSparkApplication.
func (c *scheduledSparkApplications) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta2.ScheduledSparkApplication, err error) {
	result = &v1beta2.ScheduledSparkApplication{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("scheduledsparkapplications").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do(context.TODO()).
		Into(result)
	return
}


text:
package edu.jhu.hlt.concrete.converters.kelvin

import edu.jhu.hlt.concrete.Concrete._
import edu.jhu.hlt.concrete.Graph.{Vertex,Edge,DirectedAttributes}
import scala.util.matching.Regex
import scala.collection.mutable
import edu.jhu.hlt.concrete.util.scala._

/**
 * @author John Sullivan
 */
trait Vertexable extends Identified[ValUUID]{def toBuilder:Vertex.Builder = Vertex.newBuilder.setUuid(id.asConcrete)}
trait Edgeable extends Identified[(ValUUID, ValUUID)] {def toBuilder:Edge.Builder = Edge.newBuilder.setEdgeId(id.asConcrete)}
trait EntityMentionable extends Identified[ValUUID] {def toBuilder:EntityMention.Builder = EntityMention.newBuilder.setUuid(id.asConcrete)}

trait KelvinLine {
  import KelvinLine._
  def value:String

  val LineRegex(docId, mentionId, bodyString, confidenceString) = value
  val entId = docId + "_" + mentionId

  def commGUID:CommunicationGUID = CommunicationGUID.newBuilder
    .setCommunicationId(docId)
    .setCorpusName(Settings.Corpus.corpusName)
    .build

  def mentionNumber:Int = mentionId.toInt

  def confidence:Float = confidenceString.toFloat

  def uuid = KelvinLine.getMentionUUID(entId)
}

case class MentionType(value:String) extends KelvinLine with Vertexable {
  val TypeRegex = new Regex("""type\t(\w+)""")

  val TypeRegex(typeString) = bodyString

  def id = uuid

  override def toBuilder:Vertex.Builder = super.toBuilder
    .setDataSetId(docId)
    .addKind((typeString -> confidence).asVertexKindAttribute)

}

case class MentionText(value:String) extends KelvinLine with Vertexable {
  val TextValueRegex = new Regex("""[_\w]+\t"(.+)"\t[\w\d_\.]+\t(\d+)\t(\d+)""")

  val TextValueRegex(mentionText, mentionStart, mentionEnd) = bodyString

  def id = uuid

  override def toBuilder:Vertex.Builder = super.toBuilder
    .setDataSetId(docId)
    .addName((mentionText -> confidence).asStringAttribute)
}

case class VertexMentionRelation(value:String, relation:String, otherId:String) extends KelvinLine with Edgeable { // all vertex mentions will be edge builders, some w
  import KelvinLine._

  def id = uuid -> getMentionUUID(otherId)
  def isForward = uuid < getMentionUUID(otherId)

  def directedEdge:DirectedAttributes.Builder = relation match { // todo add other cases
    case _ => DirectedAttributes.newBuilder.addOtherAttributes((relation -> confidence).asLabeledAttribute)
  }

  override def toBuilder:Edge.Builder = if(isForward) {
    super.toBuilder
      .setV1ToV2(directedEdge)
  } else {
    super.toBuilder
      .setV2ToV1(directedEdge)
  }
}

case class ValueMentionRelation(value:String, relation:String, text:String) extends KelvinLine with Vertexable {

  def id = uuid

  override def toBuilder:Vertex.Builder = relation match { // todo add other cases
   // case "per:age" => Vertex.newBuilder.addAge(text)
    case _ => super.toBuilder.setDataSetId(docId).addOtherAttributes((relation, text, confidence).asLabeledAttribute)
  }
}

object KelvinLine extends ((String) => Option[KelvinLine]) {

  private val idToUUIDMap:mutable.Map[String, ValUUID] = mutable.Map[String, ValUUID]()

  val LineRegex = new Regex(""":e_(\w+)_(\d+)\t(.*)\t([\d\.]+)""")
  val IdRegex = new Regex(""":e_(\w+)\t.*""")
  val ValueRelationRegex = new Regex("""([\w:]+)\t"(.+)"\t.*""")
  val VertexRelationRegex = new Regex("""([\w:]+)\t:e_(\w+)\t.*""")

  def getMentionUUID(mentId:String):ValUUID = idToUUIDMap.getOrElseUpdate(mentId, ValUUID.random)

  def apply(value:String):Option[KelvinLine] = value match {
    case LineRegex(_, _, bodyString, _) => bodyString.split("\\t").head match {
      case "type" => Option(MentionType(value))
      case "mention" => Option(MentionText(value))
      case "canonical_mention" => Option(MentionText(value)) // todo how do we mark mentions as canonical?
      case _ => bodyString match {
        case VertexRelationRegex(relation, id) => Option(VertexMentionRelation(value, relation, id))
        case ValueRelationRegex(relation, text) => Option(ValueMentionRelation(value, relation, text))
      }
    }
    case _ => None
  }

}


text:
package com.zimbra.qa.selenium.projects.ajax.tests.calendar.appointments.views.workweek.singleday;

import java.util.Calendar;
import java.util.HashMap;

import org.testng.annotations.Test;

import com.zimbra.qa.selenium.framework.items.*;
import com.zimbra.qa.selenium.framework.items.FolderItem.SystemFolder;
import com.zimbra.qa.selenium.framework.ui.*;
import com.zimbra.qa.selenium.framework.util.*;
import com.zimbra.qa.selenium.projects.ajax.core.*;
import com.zimbra.qa.selenium.projects.ajax.tests.calendar.appointments.views.workweek.allday.CreateAppointment;

public class DragAndDropAppointment extends CalendarWorkWeekTest {

	public DragAndDropAppointment() {
		logger.info("New "+ CreateAppointment.class.getCanonicalName());

		// All tests start at the Calendar page
		super.startingPage = app.zPageCalendar;

		// Make sure we are using an account with work week view
		super.startingAccountPreferences = new HashMap<String, String>() {
			private static final long serialVersionUID = -2913827779459595178L;
		{
		    put("zimbraPrefCalendarInitialView", "workWeek");
		}};
	}

	@Test(	description = "Drag and Drop a appointment from calendar to different calendar",
			groups = { "smoke" })
	public void DragAndDropAppointment_01() throws HarnessException {

		String foldername = "folder"+ ZimbraSeleniumProperties.getUniqueString();

		// Create a calendar to move the appointment into
		//
		FolderItem rootFolder = FolderItem.importFromSOAP(app.zGetActiveAccount(), SystemFolder.UserRoot);

		app.zGetActiveAccount().soapSend(
					"<CreateFolderRequest xmlns='urn:zimbraMail'>" +
						"<folder name='" + foldername +"' l='"+ rootFolder.getId() +"' view='appointment'/>" +
					"</CreateFolderRequest>");
		FolderItem subcalendarFolder = FolderItem.importFromSOAP(app.zGetActiveAccount(), foldername);

		//Refresh view after folder creation
		app.zPageCalendar.zToolbarPressButton(Button.B_REFRESH);

		// Creating objects for appointment data
		String tz = ZTimeZone.TimeZoneEST.getID();
		String apptSubject = ZimbraSeleniumProperties.getUniqueString();
		String apptBody = ZimbraSeleniumProperties.getUniqueString();

		// Absolute dates in UTC zone
		Calendar now = this.calendarWeekDayUTC;
		ZDate startUTC = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 12, 0, 0);
		ZDate endUTC   = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 14, 0, 0);

        app.zGetActiveAccount().soapSend(
    			"<CreateAppointmentRequest xmlns='urn:zimbraMail'>"
    		+		"<m>"
    		+			"<inv method='REQUEST' type='event' fb='B' transp='O' allDay='0' name='"+ apptSubject +"'>"
    		+				"<s d='"+ startUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<e d='"+ endUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<or a='"+ app.zGetActiveAccount().EmailAddress +"'/>"
    		+			"</inv>"
    		+			"<mp content-type='text/plain'>"
    		+				"<content>" + apptBody + "</content>"
    		+			"</mp>"
    		+			"<su>" + apptSubject + "</su>"
    		+		"</m>"
    		+	"</CreateAppointmentRequest>");
        String apptId = app.zGetActiveAccount().soapSelectValue("//mail:CreateAppointmentResponse", "apptId");

        //-- GUI actions

		// Click Refresh
        app.zPageCalendar.zToolbarPressButton(Button.B_REFRESH);

		// Select the item
		app.zPageCalendar.zDragAndDrop(
					"css=div[id^='zli__CLWW__"+ apptId +"'] td.appt_name", //

					"css=td[id='zti__main_Calendar__"+ subcalendarFolder.getId() + "_textCell']"); //

		//-- Server verification
		AppointmentItem newAppointment = AppointmentItem.importFromSOAP(app.zGetActiveAccount(), "subject:("+ apptSubject +")");

		ZAssert.assertEquals(newAppointment.getFolder(), subcalendarFolder.getId(), "Verify the appointment moved folders");

	}

	@Test(	description = "Drag and Drop a appointment from one time to a different time",
			groups = { "smoke" })
	public void DragAndDropAppointment_02() throws HarnessException {

		// We need to create two appointments to make a locator to drag and drop to.
		// Steps:
		// 1. Create appointment1
		// 2. Create appointment2 an hour later
		// 3. Drag and drop appointment1 to appointment2
		// 4. Verify appointment1 happens at appointment2 time

		// Creating objects for appointment data
		String tz = ZTimeZone.TimeZoneEST.getID();
		String apptSubject = ZimbraSeleniumProperties.getUniqueString();
		String apptBody = ZimbraSeleniumProperties.getUniqueString();

		// Absolute dates in UTC zone
		Calendar now = this.calendarWeekDayUTC;
		ZDate startUTC = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 12, 0, 0);
		ZDate endUTC   = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 13, 0, 0);

        app.zGetActiveAccount().soapSend(
    			"<CreateAppointmentRequest xmlns='urn:zimbraMail'>"
    		+		"<m>"
    		+			"<inv method='REQUEST' type='event' fb='B' transp='O' allDay='0' name='"+ apptSubject +"'>"
    		+				"<s d='"+ startUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<e d='"+ endUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<or a='"+ app.zGetActiveAccount().EmailAddress +"'/>"
    		+			"</inv>"
    		+			"<mp content-type='text/plain'>"
    		+				"<content>" + apptBody + "</content>"
    		+			"</mp>"
    		+			"<su>" + apptSubject + "</su>"
    		+		"</m>"
    		+	"</CreateAppointmentRequest>");
        String apptId = app.zGetActiveAccount().soapSelectValue("//mail:CreateAppointmentResponse", "apptId");

        app.zGetActiveAccount().soapSend(
        		"<GetAppointmentRequest id='"+ apptId + "' xmlns='urn:zimbraMail'/>");
        String s = app.zGetActiveAccount().soapSelectValue("//mail:s", "d");
        String e = app.zGetActiveAccount().soapSelectValue("//mail:e", "d");

        //Refresh view after appointment creation
      	app.zPageCalendar.zToolbarPressButton(Button.B_REFRESH);

		String otherSubject = ZimbraSeleniumProperties.getUniqueString();
		ZDate otherStartUTC = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 14, 0, 0);
		ZDate otherEndUTC   = new ZDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH) + 1, now.get(Calendar.DAY_OF_MONTH), 15, 0, 0);
        app.zGetActiveAccount().soapSend(
    			"<CreateAppointmentRequest xmlns='urn:zimbraMail'>"
    		+		"<m>"
    		+			"<inv method='REQUEST' type='event' fb='B' transp='O' allDay='0' name='"+ otherSubject +"'>"
    		+				"<s d='"+ otherStartUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<e d='"+ otherEndUTC.toTimeZone(tz).toYYYYMMDDTHHMMSS() +"' tz='"+ tz +"'/>"
    		+				"<or a='"+ app.zGetActiveAccount().EmailAddress +"'/>"
    		+			"</inv>"
    		+			"<mp content-type='text/plain'>"
    		+				"<content>" + ZimbraSeleniumProperties.getUniqueString() + "</content>"
    		+			"</mp>"
    		+			"<su>" + otherSubject + "</su>"
    		+		"</m>"
    		+	"</CreateAppointmentRequest>");
        String otherApptId = app.zGetActiveAccount().soapSelectValue("//mail:CreateAppointmentResponse", "apptId");

        //-- GUI actions

		// Click Refresh
        app.zPageCalendar.zToolbarPressButton(Button.B_REFRESH);

		// drag and drop the item
        	String sourceLocator = "css=div[id^='zli__CLWW__"+ apptId +"'] td.appt_name";
        	String destinationLocator = "css=div[id^='zli__CLWW__"+ otherApptId +"'] td.appt_name";

        	app.zPageCalendar.zDragAndDropBy(sourceLocator,destinationLocator,0,10);

		//-- Server verification

		// Make sure the time has changed
		// (It is difficult to know for certain what time is correct.  For
		// now, just make sure it was moved somewhere.)
        app.zGetActiveAccount().soapSend(
        		"<GetAppointmentRequest id='"+ apptId + "' xmlns='urn:zimbraMail'/>");
        String s1 = app.zGetActiveAccount().soapSelectValue("//mail:s", "d");
        String e2 = app.zGetActiveAccount().soapSelectValue("//mail:e", "d");

		ZAssert.assertStringDoesNotContain(s1, s, "Verify the start time changed");
		ZAssert.assertStringDoesNotContain(e2, e, "Verify the end time changed");

	}

}


text: Repository of BVIS the car rental student organisation


text:
<?xml version="1.0" encoding="UTF-8"?>
<definition class="Symfony\Bundle\FrameworkBundle\Tests\Console\Descriptor\ClassWithDocComment" public="false" synthetic="false" lazy="false" shared="true" abstract="false" autowired="false" autoconfigured="false" deprecated="false" file="">
  <description><![CDATA[This is a class with a doc comment.]]></description>
</definition>