text:
<?php
namespace Order\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

/**
 * updateController
 *
 * @author
 *
 * @version
 *
 */
class UpdateController extends AbstractActionController
{

    /**
     * The default action - show the home page
     */
    public function indexAction()
    {
        // TODO Auto-generated updateController::indexAction() default action
        return new ViewModel();
    }

    public function addAction()
    {
    	$check=new \Order\Model\UpdateFormChecker(3);
        $request=$this->getRequest();
        $form=new \Order\Form\UpdateForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'),3);
        $form->setInputFilter($check->getInputFilter());
    	$form->get('send')->setValue('Add this order');
    	if ($request->isPost())
    	{
    	    $form->setData($request->getPost());
    	    if ($form->isValid())
    	    {
    	        $orderTable=$this->getServiceLocator()->get('OrderTable');
    	        $PO_Number=$form->get('PO_Number')->getValue();
                $customer_id=$form->get('customer_id')->getValue();
                if ($orderTable->select(array('customer_id'=>$customer_id, 'PO_Number'=>$PO_Number))->count())
                {
                    $this->flashMessenger()->addMessage('Error! Duplicated Item!');
                    return $this->redirect()->toUrl('/order/');
                }
                else
                {
                    $data=$form->getPureData();

        	        $orderTable=$this->getServiceLocator()->get('OrderTable');
        	        $res=$orderTable->insert($data);
        	        if ($res)
        	        {
        	           $id=$orderTable->select(array('customer_id'=>$customer_id, 'PO_Number'=>$PO_Number))->current()->id;
        	           $this->flashMessenger()->addMessage('You have Successfully added order, now please add items for this order!!');
        			   return $this->redirect()->toUrl('/order/search/show?id='.$id);
        	        }
        	        else
        	        {
        	            $this->flashMessenger()->addMessage('Error!No record added!!');
        	            return $this->redirect()->toUrl('/order/search/show?id='.$id);
        	        }
                }

    	  }

        }
    	return array('form'=>$form);
    }

    public function updateAction()
    {
        $request=$this->getRequest();
        $form=new \Order\Form\UpdateForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter') );
        if(!$request->isPost())
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can update !!');
            return $this->redirect()->toUrl('/order');
        }
        $data=$request->getPost();
        if(!isset($data['id']))
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can update!!');
            return $this->redirect()->toUrl('/order');
        }
        $id=$data['id'];
        $orderTable=$this->getServiceLocator()->get('OrderTable');
        if(!isset($data['PO_Number']))
        {
            $order=$orderTable->getOrderById($id);
            if($order)
                $form->bind($order);
            return array('form'=>$form);
        }
        $form->setData($data);
        $checker=new \Order\Model\UpdateFormChecker();
        $form->setInputFilter($checker->getInputFilter());
        if ($form->isValid())
        {
        $PO_Number=$form->get('PO_Number')->getValue();
        $customer_id=$form->get('customer_id')->getValue();

            $orderRow=$this->getServiceLocator()->get('OrderRow');
            $orderRow->populate($form->getPureData());
            $res=$orderRow->save();
            if($res)
            {
            	$this->flashMessenger()->addMessage('You have successfully updated the order!!');
            	return $this->redirect()->toUrl('/order/search/show?id='.$id);
            }
            else
            {
            	$this->flashMessenger()->addMessage('Error! No Item updated!');
            	return $this->redirect()->toUrl('/order/search/show?id='.$id);
            }

        }
        else
            return array('form->$form');
    }

    public function deleteAction()
    {
        $request=$this->getRequest();
        if (!$request->isPost())
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can delete !!');
            return $this->redirect()->toUrl('/order');
        }
        $data=$request->getPost();
        if(!isset($data['id']))
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can delete !!');
            return $this->redirect()->toUrl('/order');
        }
        $id=$data['id'];
        $orderTable=$this->getServiceLocator()->get('OrderTable');
        $row=$orderTable->getOrderById($id);
        if(!isset($data['del']))
            return array('row'=>$row);
        if ($data['del']=='Yes')
        {
            $itemTable=$this->getServiceLocator()->get('ItemTable');
            $itemRes=$itemTable->delete(array('order_id'=>$id));
            $orderRes=$orderTable->delete(array('id'=>$id));
            $this->flashMessenger()->addMessage($orderRes.' order(s) deleted from order table and '.$itemRes. 'item(s) deleted from po_items table!');
            return $this->redirect()->toUrl('/order');

        }
        else
            return $this->redirect()->toUrl('/order');
    }

    public function additemAction()
    {
        $form=new \Order\Form\ItemForm();
        $view=new \Zend\View\Model\ViewModel();
        $request=$this->getRequest();
        if(!$request->isPost())
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can add item to!!');
            return $this->redirect()->toUrl('/order');
        }

        $data=$request->getPost();

        if (!isset($data['order_id']))
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can add item to!!');
            return $this->redirect()->toUrl('/order');
        }
        $order_id=$data['order_id'];
        if(!isset($data['catalogNo']))
        {
            $form->get('order_id')->setValue($order_id);

            $view->form=$form;
             return $view;
        }
        $form->setData($data);
        $dbAdapter=$this->getServiceLocator()->get('Adapter');
        $check=new \Order\Model\ItemFormChecker($dbAdapter);
        $form->setInputFilter($check->getInputFilter());
        if ($form->isValid())
        {
            $itemTable=$this->getServiceLocator()->get('ItemTable');
            $catalogNo=$form->get('catalogNo')->getValue();
            $order_id=$form->get('order_id')->getValue();
            $catalogTable=new \Catalog\Model\CatalogTable($itemTable->getAdapter());
            if (!($catalogTable->getItemByCatalogNo($catalogNo)))
            {
                $this->flashMessenger()->addMessage('This Catalog Number is not valid!!');
                return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
            }
            if ($itemTable->select(array('order_id'=>$order_id,'catalogNo'=>$catalogNo))->count()==0)
            {
                $res=$itemTable->insert($form->getPureData());
                if ($res)
                {
                    $this->flashMessenger()->addMessage('You have Successfully added item!');
                    return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
                }
                else
                {
                    $this->flashMessenger()->addMessage('Error! No Item added!');
                    return $this->redirect()->toUrl('/order/search/show?id='.$form->get('order_id')->getValue());
                }

            }
            else
            {
                $this->flashMessenger()->addMessage('Error! Duplicated Item!');
                return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
            }

        }
        else
            $view->form=$form;
        return $view;
    }

    public function deleteitemAction()
    {
        $request=$this->getRequest();
        if (!$request->isPost())
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can delete item from!!');
            return $this->redirect()->toUrl('/order');
        }
        $data=$request->getPost();
        if(!isset($data['id']))
        {
            $this->flashMessenger()->addMessage('You need to find the order before you can delete item from!!');
            return $this->redirect()->toUrl('/order');
        }else
        {
            $id=$data['id'];
            $itemTable=$this->getServiceLocator()->get('ItemTable');
            $row=$itemTable->getItemById($id);

            $order_id=$row->order_id;
            if (!isset($data['del']))
            {

                return array('row'=>$row);
            }else
            {
                if ($data['del']=='Yes')
                {
                    $res=$itemTable->delete(array('id'=>$id));
                    if ($res)
                    {
                    	$this->flashMessenger()->addMessage('You have successfully deleted an item!!');
                    	return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
                    }
                    else
                    {
                    	$this->flashMessenger()->addMessage('Error! No Item deleted!');
                    	return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
                    }
                }
                else
                {
                    return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
                }
            }

        }
    }

        public function updateitemAction()
        {
        	$request=$this->getRequest();
        	$form=new \Order\Form\ItemForm();
        	$form->get('send')->setValue('Update this item');
        	if (!$request->isPost())
        	{
        		$this->flashMessenger()->addMessage('You need to find the order before you can modify item from!!');
        		return $this->redirect()->toUrl('/order');
        	}
        	$data=$request->getPost();
        	if(!isset($data['id']))
        	{
        		$this->flashMessenger()->addMessage('You need to find the order before you can modify item from!!');
        		return $this->redirect()->toUrl('/order');
        	}
        	if (!isset($data['catalogNo']))
        	{
        		$id=$data['id'];
        		$itemTable=$this->getServiceLocator()->get('ItemTable');
        		$row=$itemTable->getItemById($id);

        		if($row)
        			$form->bind($row);
        		return array('form'=>$form);

        	}

    	    $form->setData($data);
    	    $dbAdapter=$this->getServiceLocator()->get('Adapter');
    	    $checker=new \Order\Model\ItemFormChecker($dbAdapter);
    	    $form->setInputFilter($checker->getInputFilter());
    	    if($form->isValid())
    	    {
    	        $itemTable=$this->getServiceLocator()->get('ItemTable');
    	        $catalogNo=$form->get('catalogNo')->getValue();
    	        $id=$form->get('id')->getValue();
    	        $order_id=$form->get('order_id')->getValue();
    	        $catalogTable=new \Catalog\Model\CatalogTable($itemTable->getAdapter());
    	        if (!($catalogTable->getItemByCatalogNo($catalogNo)))
    	        {
    	        	$this->flashMessenger()->addMessage('This Catalog Number is not valid!!');
    	        	return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
    	        }

	            $itemRow=$this->getServiceLocator()->get('ItemRow');
	            $itemRow->populate($form->getPureData());
	            $res=$itemRow->save();
	            if($res)
	            {
	                $this->flashMessenger()->addMessage('You have successfully updated an item!!');
	                return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
	            }
	            else
	            {
	                $this->flashMessenger()->addMessage('Error! No Item updated!');
	                return $this->redirect()->toUrl('/order/search/show?id='.$order_id);
    	            }
    	        }
    	        else
    	        	return array('form'=>$form);

    	    }

    }


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

package org.apache.tez.mapreduce.grouper;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.util.RackResolver;
import org.apache.tez.dag.api.TezUncheckedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class TezSplitGrouper {

  private static final Logger LOG = LoggerFactory.getLogger(TezSplitGrouper.class);

  /**
   * Specify the number of splits desired to be created
   */
  public static final String TEZ_GROUPING_SPLIT_COUNT = "tez.grouping.split-count";
  /**
   * Limit the number of splits in a group by the total length of the splits in the group
   */
  public static final String TEZ_GROUPING_SPLIT_BY_LENGTH = "tez.grouping.by-length";
  public static final boolean TEZ_GROUPING_SPLIT_BY_LENGTH_DEFAULT = true;
  /**
   * Limit the number of splits in a group by the number of splits in the group
   */
  public static final String TEZ_GROUPING_SPLIT_BY_COUNT = "tez.grouping.by-count";
  public static final boolean TEZ_GROUPING_SPLIT_BY_COUNT_DEFAULT = false;

  /**
   * The multiplier for available queue capacity when determining number of
   * tasks for a Vertex. 1.7 with 100% queue available implies generating a
   * number of tasks roughly equal to 170% of the available containers on the
   * queue. This enables multiple waves of mappers where the final wave is slightly smaller
   * than the remaining waves. The gap helps overlap the final wave with any slower tasks
   * from previous waves and tries to hide the delays from the slower tasks. Good values for
   * this are 1.7, 2.7, 3.7 etc. Increase the number of waves to make the tasks smaller or
   * shorter.
   */
  public static final String TEZ_GROUPING_SPLIT_WAVES = "tez.grouping.split-waves";
  public static final float TEZ_GROUPING_SPLIT_WAVES_DEFAULT = 1.7f;

  /**
   * Upper bound on the size (in bytes) of a grouped split, to avoid generating excessively large splits.
   */
  public static final String TEZ_GROUPING_SPLIT_MAX_SIZE = "tez.grouping.max-size";
  public static final long TEZ_GROUPING_SPLIT_MAX_SIZE_DEFAULT = 1024*1024*1024L;

  /**
   * Lower bound on the size (in bytes) of a grouped split, to avoid generating too many small splits.
   */
  public static final String TEZ_GROUPING_SPLIT_MIN_SIZE = "tez.grouping.min-size";
  public static final long TEZ_GROUPING_SPLIT_MIN_SIZE_DEFAULT = 50*1024*1024L;

  /**
   * This factor is used to decrease the per group desired (length and count) limits for groups
   * created by combining splits within a rack. Since reading this split involves reading data intra
   * rack, the group is made smaller to cover up for the increased latencies in doing intra rack
   * reads. The value should be a fraction <= 1.
   */
  public static final String TEZ_GROUPING_RACK_SPLIT_SIZE_REDUCTION =
      "tez.grouping.rack-split-reduction";
  public static final float TEZ_GROUPING_RACK_SPLIT_SIZE_REDUCTION_DEFAULT = 0.75f;

  /**
   * Repeated invocations of grouping on the same splits with the same parameters will produce the
   * same groups. This may help in cache reuse but may cause hot-spotting on nodes when there are a
   * large number of jobs reading the same hot data. True by default.
   */
  public static final String TEZ_GROUPING_REPEATABLE = "tez.grouping.repeatable";
  public static final boolean TEZ_GROUPING_REPEATABLE_DEFAULT = true;

  static class LocationHolder {
    List<SplitContainer> splits;
    int headIndex = 0;
    LocationHolder(int capacity) {
      splits = new ArrayList<SplitContainer>(capacity);
    }
    boolean isEmpty() {
      return (headIndex == splits.size());
    }
    SplitContainer getUnprocessedHeadSplit() {
      while (!isEmpty()) {
        SplitContainer holder = splits.get(headIndex);
        if (!holder.isProcessed()) {
          return holder;
        }
        incrementHeadIndex();
      }
      return null;
    }
    void incrementHeadIndex() {
      headIndex++;
    }
  }

  private static final SplitSizeEstimatorWrapper DEFAULT_SPLIT_ESTIMATOR = new DefaultSplitSizeEstimatorWrapper();

  static final class DefaultSplitSizeEstimatorWrapper implements SplitSizeEstimatorWrapper {

    @Override
    public long getEstimatedSize(SplitContainer splitContainer) throws IOException,
        InterruptedException {
      return splitContainer.getLength();
    }
  }

  Map<String, LocationHolder> createLocationsMap(Configuration conf) {
    if (conf.getBoolean(TEZ_GROUPING_REPEATABLE,
        TEZ_GROUPING_REPEATABLE_DEFAULT)) {
      return new TreeMap<String, LocationHolder>();
    }
    return new HashMap<String, LocationHolder>();
  }

  public List<GroupedSplitContainer> getGroupedSplits(Configuration conf,
                                                      List<SplitContainer> originalSplits,
                                                      int desiredNumSplits,
                                                      String wrappedInputFormatName,
                                                      SplitSizeEstimatorWrapper estimator) throws
      IOException, InterruptedException {
    LOG.info("Grouping splits in Tez");
    Preconditions.checkArgument(originalSplits != null, "Splits must be specified");

    int configNumSplits = conf.getInt(TEZ_GROUPING_SPLIT_COUNT, 0);
    if (configNumSplits > 0) {
      // always use config override if specified
      desiredNumSplits = configNumSplits;
      LOG.info("Desired numSplits overridden by config to: " + desiredNumSplits);
    }

    if (estimator == null) {
      estimator = DEFAULT_SPLIT_ESTIMATOR;
    }

    if (! (configNumSplits > 0 ||
        originalSplits.size() == 0)) {
      // numSplits has not been overridden by config
      // numSplits has been set at runtime
      // there are splits generated
      // desired splits is less than number of splits generated
      // Do sanity checks
      long totalLength = 0;
      for (SplitContainer split : originalSplits) {
        totalLength += estimator.getEstimatedSize(split);
      }

      int splitCount = desiredNumSplits>0?desiredNumSplits:originalSplits.size();
      long lengthPerGroup = totalLength/splitCount;

      long maxLengthPerGroup = conf.getLong(
          TEZ_GROUPING_SPLIT_MAX_SIZE,
          TEZ_GROUPING_SPLIT_MAX_SIZE_DEFAULT);
      long minLengthPerGroup = conf.getLong(
          TEZ_GROUPING_SPLIT_MIN_SIZE,
          TEZ_GROUPING_SPLIT_MIN_SIZE_DEFAULT);
      if (maxLengthPerGroup < minLengthPerGroup ||
          minLengthPerGroup <=0) {
        throw new TezUncheckedException(
            "Invalid max/min group lengths. Required min>0, max>=min. " +
                " max: " + maxLengthPerGroup + " min: " + minLengthPerGroup);
      }
      if (lengthPerGroup > maxLengthPerGroup) {
        // splits too big to work. Need to override with max size.
        int newDesiredNumSplits = (int)(totalLength/maxLengthPerGroup) + 1;
        LOG.info("Desired splits: " + desiredNumSplits + " too small. " +
            " Desired splitLength: " + lengthPerGroup +
            " Max splitLength: " + maxLengthPerGroup +
            " New desired splits: " + newDesiredNumSplits +
            " Total length: " + totalLength +
            " Original splits: " + originalSplits.size());

        desiredNumSplits = newDesiredNumSplits;
      } else if (lengthPerGroup < minLengthPerGroup) {
        // splits too small to work. Need to override with size.
        int newDesiredNumSplits = (int)(totalLength/minLengthPerGroup) + 1;
        LOG.info("Desired splits: " + desiredNumSplits + " too large. " +
            " Desired splitLength: " + lengthPerGroup +
            " Min splitLength: " + minLengthPerGroup +
            " New desired splits: " + newDesiredNumSplits +
            " Total length: " + totalLength +
            " Original splits: " + originalSplits.size());

        desiredNumSplits = newDesiredNumSplits;
      }
    }

    List<GroupedSplitContainer> groupedSplits = null;

    if (desiredNumSplits == 0 ||
        originalSplits.size() == 0 ||
        desiredNumSplits >= originalSplits.size()) {
      // nothing set. so return all the splits as is
      LOG.info("Using original number of splits: " + originalSplits.size() +
          " desired splits: " + desiredNumSplits);
      groupedSplits = new ArrayList<GroupedSplitContainer>(originalSplits.size());
      for (SplitContainer split : originalSplits) {
        GroupedSplitContainer newSplit =
            new GroupedSplitContainer(1, wrappedInputFormatName, split.getPreferredLocations(),
                null);
        newSplit.addSplit(split);
        groupedSplits.add(newSplit);
      }
      return groupedSplits;
    }

    String emptyLocation = "EmptyLocation";
    String[] emptyLocations = {emptyLocation};
    groupedSplits = new ArrayList<GroupedSplitContainer>(desiredNumSplits);

    long totalLength = 0;
    Map<String, LocationHolder> distinctLocations = createLocationsMap(conf);
    // go through splits and add them to locations
    for (SplitContainer split : originalSplits) {
      totalLength += estimator.getEstimatedSize(split);
      String[] locations = split.getPreferredLocations();
      if (locations == null || locations.length == 0) {
        locations = emptyLocations;
      }
      for (String location : locations ) {
        if (location == null) {
          location = emptyLocation;
        }
        distinctLocations.put(location, null);
      }
    }

    long lengthPerGroup = totalLength/desiredNumSplits;
    int numNodeLocations = distinctLocations.size();
    int numSplitsPerLocation = originalSplits.size()/numNodeLocations;
    int numSplitsInGroup = originalSplits.size()/desiredNumSplits;

    // allocation loop here so that we have a good initial size for the lists
    for (String location : distinctLocations.keySet()) {
      distinctLocations.put(location, new LocationHolder(numSplitsPerLocation+1));
    }

    Set<String> locSet = new HashSet<String>();
    for (SplitContainer split : originalSplits) {
      locSet.clear();
      String[] locations = split.getPreferredLocations();
      if (locations == null || locations.length == 0) {
        locations = emptyLocations;
      }
      for (String location : locations) {
        if (location == null) {
          location = emptyLocation;
        }
        locSet.add(location);
      }
      for (String location : locSet) {
        LocationHolder holder = distinctLocations.get(location);
        holder.splits.add(split);
      }
    }

    boolean groupByLength = conf.getBoolean(
        TEZ_GROUPING_SPLIT_BY_LENGTH,
        TEZ_GROUPING_SPLIT_BY_LENGTH_DEFAULT);
    boolean groupByCount = conf.getBoolean(
        TEZ_GROUPING_SPLIT_BY_COUNT,
        TEZ_GROUPING_SPLIT_BY_COUNT_DEFAULT);
    if (!(groupByLength || groupByCount)) {
      throw new TezUncheckedException(
          "None of the grouping parameters are true: "
              + TEZ_GROUPING_SPLIT_BY_LENGTH + ", "
              + TEZ_GROUPING_SPLIT_BY_COUNT);
    }
    LOG.info("Desired numSplits: " + desiredNumSplits +
        " lengthPerGroup: " + lengthPerGroup +
        " numLocations: " + numNodeLocations +
        " numSplitsPerLocation: " + numSplitsPerLocation +
        " numSplitsInGroup: " + numSplitsInGroup +
        " totalLength: " + totalLength +
        " numOriginalSplits: " + originalSplits.size() +
        " . Grouping by length: " + groupByLength + " count: " + groupByCount);

    // go through locations and group splits
    int splitsProcessed = 0;
    List<SplitContainer> group = new ArrayList<SplitContainer>(numSplitsInGroup);
    Set<String> groupLocationSet = new HashSet<String>(10);
    boolean allowSmallGroups = false;
    boolean doingRackLocal = false;
    int iterations = 0;
    while (splitsProcessed < originalSplits.size()) {
      iterations++;
      int numFullGroupsCreated = 0;
      for (Map.Entry<String, LocationHolder> entry : distinctLocations.entrySet()) {
        group.clear();
        groupLocationSet.clear();
        String location = entry.getKey();
        LocationHolder holder = entry.getValue();
        // KKK rename to splitContainer
        SplitContainer splitContainer = holder.getUnprocessedHeadSplit();
        if (splitContainer == null) {
          // all splits on node processed
          continue;
        }
        int oldHeadIndex = holder.headIndex;
        long groupLength = 0;
        int groupNumSplits = 0;
        do {
          group.add(splitContainer);
          groupLength += estimator.getEstimatedSize(splitContainer);
          groupNumSplits++;
          holder.incrementHeadIndex();
          splitContainer = holder.getUnprocessedHeadSplit();
        } while(splitContainer != null
            && (!groupByLength ||
            (groupLength + estimator.getEstimatedSize(splitContainer) <= lengthPerGroup))
            && (!groupByCount ||
            (groupNumSplits + 1 <= numSplitsInGroup)));

        if (holder.isEmpty()
            && !allowSmallGroups
            && (!groupByLength || groupLength < lengthPerGroup/2)
            && (!groupByCount || groupNumSplits < numSplitsInGroup/2)) {
          // group too small, reset it
          holder.headIndex = oldHeadIndex;
          continue;
        }

        numFullGroupsCreated++;

        // One split group created
        String[] groupLocation = {location};
        if (location == emptyLocation) {
          groupLocation = null;
        } else if (doingRackLocal) {
          for (SplitContainer splitH : group) {
            String[] locations = splitH.getPreferredLocations();
            if (locations != null) {
              for (String loc : locations) {
                if (loc != null) {
                  groupLocationSet.add(loc);
                }
              }
            }
          }
          groupLocation = groupLocationSet.toArray(groupLocation);
        }
        GroupedSplitContainer groupedSplit =
            new GroupedSplitContainer(group.size(), wrappedInputFormatName,
                groupLocation,
                // pass rack local hint directly to AM
                ((doingRackLocal && location != emptyLocation)?location:null));
        for (SplitContainer groupedSplitContainer : group) {
          groupedSplit.addSplit(groupedSplitContainer);
          Preconditions.checkState(groupedSplitContainer.isProcessed() == false,
              "Duplicates in grouping at location: " + location);
          groupedSplitContainer.setIsProcessed(true);
          splitsProcessed++;
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug("Grouped " + group.size()
              + " length: " + groupedSplit.getLength()
              + " split at: " + location);
        }
        groupedSplits.add(groupedSplit);
      }

      if (!doingRackLocal && numFullGroupsCreated < 1) {
        // no node could create a node-local group. go rack-local
        doingRackLocal = true;
        // re-create locations
        int numRemainingSplits = originalSplits.size() - splitsProcessed;
        Set<SplitContainer> remainingSplits = new HashSet<SplitContainer>(numRemainingSplits);
        // gather remaining splits.
        for (Map.Entry<String, LocationHolder> entry : distinctLocations.entrySet()) {
          LocationHolder locHolder = entry.getValue();
          while (!locHolder.isEmpty()) {
            SplitContainer splitHolder = locHolder.getUnprocessedHeadSplit();
            if (splitHolder != null) {
              remainingSplits.add(splitHolder);
              locHolder.incrementHeadIndex();
            }
          }
        }
        if (remainingSplits.size() != numRemainingSplits) {
          throw new TezUncheckedException("Expected: " + numRemainingSplits
              + " got: " + remainingSplits.size());
        }

        // doing all this now instead of up front because the number of remaining
        // splits is expected to be much smaller
        RackResolver.init(conf);
        Map<String, String> locToRackMap = new HashMap<String, String>(distinctLocations.size());
        Map<String, LocationHolder> rackLocations = createLocationsMap(conf);
        for (String location : distinctLocations.keySet()) {
          String rack = emptyLocation;
          if (location != emptyLocation) {
            rack = RackResolver.resolve(location).getNetworkLocation();
          }
          locToRackMap.put(location, rack);
          if (rackLocations.get(rack) == null) {
            // splits will probably be located in all racks
            rackLocations.put(rack, new LocationHolder(numRemainingSplits));
          }
        }
        distinctLocations.clear();
        HashSet<String> rackSet = new HashSet<String>(rackLocations.size());
        int numRackSplitsToGroup = remainingSplits.size();
        for (SplitContainer split : originalSplits) {
          if (numRackSplitsToGroup == 0) {
            break;
          }
          // Iterate through the original splits in their order and consider them for grouping.
          // This maintains the original ordering in the list and thus subsequent grouping will
          // maintain that order
          if (!remainingSplits.contains(split)) {
            continue;
          }
          numRackSplitsToGroup--;
          rackSet.clear();
          String[] locations = split.getPreferredLocations();
          if (locations == null || locations.length == 0) {
            locations = emptyLocations;
          }
          for (String location : locations ) {
            if (location == null) {
              location = emptyLocation;
            }
            rackSet.add(locToRackMap.get(location));
          }
          for (String rack : rackSet) {
            rackLocations.get(rack).splits.add(split);
          }
        }

        remainingSplits.clear();
        distinctLocations = rackLocations;
        // adjust split length to be smaller because the data is non local
        float rackSplitReduction = conf.getFloat(
            TEZ_GROUPING_RACK_SPLIT_SIZE_REDUCTION,
            TEZ_GROUPING_RACK_SPLIT_SIZE_REDUCTION_DEFAULT);
        if (rackSplitReduction > 0) {
          long newLengthPerGroup = (long)(lengthPerGroup*rackSplitReduction);
          int newNumSplitsInGroup = (int) (numSplitsInGroup*rackSplitReduction);
          if (newLengthPerGroup > 0) {
            lengthPerGroup = newLengthPerGroup;
          }
          if (newNumSplitsInGroup > 0) {
            numSplitsInGroup = newNumSplitsInGroup;
          }
        }

        LOG.info("Doing rack local after iteration: " + iterations +
            " splitsProcessed: " + splitsProcessed +
            " numFullGroupsInRound: " + numFullGroupsCreated +
            " totalGroups: " + groupedSplits.size() +
            " lengthPerGroup: " + lengthPerGroup +
            " numSplitsInGroup: " + numSplitsInGroup);

        // dont do smallGroups for the first pass
        continue;
      }

      if (!allowSmallGroups && numFullGroupsCreated <= numNodeLocations/10) {
        // a few nodes have a lot of data or data is thinly spread across nodes
        // so allow small groups now
        allowSmallGroups = true;
        LOG.info("Allowing small groups after iteration: " + iterations +
            " splitsProcessed: " + splitsProcessed +
            " numFullGroupsInRound: " + numFullGroupsCreated +
            " totalGroups: " + groupedSplits.size());
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("Iteration: " + iterations +
            " splitsProcessed: " + splitsProcessed +
            " numFullGroupsInRound: " + numFullGroupsCreated +
            " totalGroups: " + groupedSplits.size());
      }
    }
    LOG.info("Number of splits desired: " + desiredNumSplits +
        " created: " + groupedSplits.size() +
        " splitsProcessed: " + splitsProcessed);
    return groupedSplits;
  }

  /**
   * Builder that can be used to configure grouping in Tez
   *
   * @param conf
   *          {@link Configuration} This will be modified in place. If
   *          configuration values may be changed at runtime via a config file
   *          then pass in a {@link Configuration} that is initialized from a
   *          config file. The parameters that are not overridden in code will
   *          be derived from the Configuration object.
   * @return {@link org.apache.tez.mapreduce.grouper.TezSplitGrouper.TezMRSplitsGrouperConfigBuilder}
   */
  public static TezMRSplitsGrouperConfigBuilder newConfigBuilder(Configuration conf) {
    return new TezMRSplitsGrouperConfigBuilder(conf);
  }

  public static final class TezMRSplitsGrouperConfigBuilder {
    private final Configuration conf;

    /**
     * This configuration will be modified in place
     */
    private TezMRSplitsGrouperConfigBuilder(@Nullable Configuration conf) {
      if (conf == null) {
        conf = new Configuration(false);
      }
      this.conf = conf;
    }

    public TezMRSplitsGrouperConfigBuilder setGroupSplitCount(int count) {
      this.conf.setInt(TEZ_GROUPING_SPLIT_COUNT, count);
      return this;
    }

    public TezMRSplitsGrouperConfigBuilder setGroupSplitByCount(boolean enabled) {
      this.conf.setBoolean(TEZ_GROUPING_SPLIT_BY_COUNT, enabled);
      return this;
    }

    public TezMRSplitsGrouperConfigBuilder setGroupSplitByLength(boolean enabled) {
      this.conf.setBoolean(TEZ_GROUPING_SPLIT_BY_LENGTH, enabled);
      return this;
    }

    public TezMRSplitsGrouperConfigBuilder setGroupSplitWaves(float multiplier) {
      this.conf.setFloat(TEZ_GROUPING_SPLIT_WAVES, multiplier);
      return this;
    }

    public TezMRSplitsGrouperConfigBuilder setGroupingRackSplitSizeReduction(float rackSplitSizeReduction) {
      this.conf.setFloat(TEZ_GROUPING_RACK_SPLIT_SIZE_REDUCTION, rackSplitSizeReduction);
      return this;
    }

    /**
     * upper and lower bounds for the splits
     */
    public TezMRSplitsGrouperConfigBuilder setGroupingSplitSize(long lowerBound, long upperBound) {
      this.conf.setLong(TEZ_GROUPING_SPLIT_MIN_SIZE, lowerBound);
      this.conf.setLong(TEZ_GROUPING_SPLIT_MAX_SIZE, upperBound);
      return this;
    }

    public Configuration build() {
      return this.conf;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.daisy.common.xproc.calabash;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import javax.xml.namespace.QName;

import org.daisy.common.saxon.SaxonHelper;
import org.daisy.common.transform.InputValue;

import com.xmlcalabash.model.RuntimeValue;

public class XMLCalabashParameterInputValue extends InputValue<Map<QName,XMLCalabashOptionValue>> {

	private final Map<net.sf.saxon.s9api.QName,RuntimeValue> runtimeValueMap;

	public XMLCalabashParameterInputValue(Map<net.sf.saxon.s9api.QName,RuntimeValue> value) {
		super(value.entrySet()
		           .stream()
		           .collect(Collectors.toMap(
		                        e -> SaxonHelper.jaxpQName(e.getKey()),
		                        e -> new XMLCalabashOptionValue(e.getValue()))));
		runtimeValueMap = value;
	}

	public static XMLCalabashParameterInputValue of(InputValue<?> value) {
		if (value instanceof XMLCalabashParameterInputValue)
			return (XMLCalabashParameterInputValue)value;
		Map<net.sf.saxon.s9api.QName,RuntimeValue> runtimeValueMap = new HashMap<>();
		Map<?,?> map; {
			try {
				map = value.asObject(Map.class);
			} catch (UnsupportedOperationException e) {
				throw new IllegalArgumentException("unsupported interface for parameter input");
			}
		}
		for (Object k : map.keySet()) {
			QName name; {
				if (!(k instanceof QName))
					throw new IllegalArgumentException("unsupported interface for parameter input");
				name = (QName)k;
			}
			RuntimeValue val; {
				Object v = map.get(k);
				if (!(v instanceof InputValue))
					throw new IllegalArgumentException("unsupported interface for parameter input");
				try {
					val = XMLCalabashOptionValue.of((InputValue<?>)v).asRuntimeValue();
				} catch (UnsupportedOperationException e) {
					throw new IllegalArgumentException("unsupported interface for parameter input");
				}
			}
			runtimeValueMap.put(new net.sf.saxon.s9api.QName(name), val);
		}
		return new XMLCalabashParameterInputValue(runtimeValueMap);
	}

	public Map<net.sf.saxon.s9api.QName,RuntimeValue> asRuntimeValueMap() {
		return runtimeValueMap;
	}
}


text:
{% extends '_base.html' %}
{% load buttons %}
{% load humanize %}

{% block content %}

    {% if perms.ipam.add_aggregate %}
        {% add_button 'ipam:aggregate_add' %}
        {% import_button 'ipam:aggregate_import' %}
    {% endif %}
    {% export_button content_type %}

{% block title %}Aggregates{% endblock %}

        {% include 'utilities/obj_table.html' with bulk_edit_url='ipam:aggregate_bulk_edit' bulk_delete_url='ipam:aggregate_bulk_delete' %}

		{% include 'inc/search_panel.html' %}
		{% include 'inc/tags_panel.html' %}

                 Statistics

Total IPv4 IPs {{ ipv4_total|intcomma }}

Total IPv6 /64s {{ ipv6_total|intcomma }}

{% endblock %}


text:
<?php

/* @Twig/Exception/exception.atom.twig */
class __TwigTemplate_b1f87bb5e8588b1a9c2bd1c0b39056757e13307bf8c1ab69434346c9e75792e9 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_9d92d030aa24db8fcd655e316283a9ffeb63d4018a64fbcfcda79a008e8ef547 = $this->env->getExtension("native_profiler");
        $__internal_9d92d030aa24db8fcd655e316283a9ffeb63d4018a64fbcfcda79a008e8ef547->enter($__internal_9d92d030aa24db8fcd655e316283a9ffeb63d4018a64fbcfcda79a008e8ef547_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Twig/Exception/exception.atom.twig"));

        // line 1
        $this->loadTemplate("@Twig/Exception/exception.xml.twig", "@Twig/Exception/exception.atom.twig", 1)->display(array_merge($context, array("exception" => (isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")))));

        $__internal_9d92d030aa24db8fcd655e316283a9ffeb63d4018a64fbcfcda79a008e8ef547->leave($__internal_9d92d030aa24db8fcd655e316283a9ffeb63d4018a64fbcfcda79a008e8ef547_prof);

    }

    public function getTemplateName()
    {
        return "@Twig/Exception/exception.atom.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  22 => 1,);
    }
}
/* {% include '@Twig/Exception/exception.xml.twig' with { 'exception': exception } %}*/
/* */


text:
namespace sandbox {
#endif

// These are command line switches that may be used by other programs
// (e.g. Chrome) to construct a command line for the sandbox.
static const char kSuidSandboxGetApiSwitch[] = "--get-api";
static const char kAdjustOOMScoreSwitch[] = "--adjust-oom-score";

static const char kSandboxDescriptorEnvironmentVarName[] = "SBX_D";
static const char kSandboxHelperPidEnvironmentVarName[] = "SBX_HELPER_PID";

static const int kSUIDSandboxApiNumber = 1;
static const char kSandboxEnvironmentApiRequest[] = "SBX_CHROME_API_RQ";
static const char kSandboxEnvironmentApiProvides[] = "SBX_CHROME_API_PRV";

// This number must be kept in sync with common/zygote_commands_linux.h
static const int kZygoteIdFd = 7;

// These are the magic byte values which the sandboxed process uses to request
// that it be chrooted.
static const char kMsgChrootMe = 'C';
static const char kMsgChrootSuccessful = 'O';

// These are set if we have respectively switched to a new PID or NET namespace
// by going through the setuid binary helper.
static const char kSandboxPIDNSEnvironmentVarName[] = "SBX_PID_NS";
static const char kSandboxNETNSEnvironmentVarName[] = "SBX_NET_NS";

#if defined(__cplusplus)
}  // namespace sandbox
#endif

#endif  // SANDBOX_LINUX_SUID_COMMON_SANDBOX_H_


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class DirectoryLibrary extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('directory_libraries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            // $table->string('type')->nullable();
            $table->integer('type_id')->nullable();
            $table->string('description', 1200)->nullable();
            $table->integer('directory_id')->nullable();
            $table->integer('document_english_id')->nullable();
            $table->integer('document_khmer_id')->nullable();
            $table->integer('document_english_download')->default(0);
            $table->integer('document_khmer_download')->default(0);
            $table->integer('seq_no')->default(0);
            $table->boolean('is_active')->default(0);
            $table->integer('created_by')->nullable();
            $table->integer('updated_by')->nullable();
            $table->integer('deleted_by')->nullable();
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('directory_libraries');
    }
}


text:
import Axon
from Kamaelia.UI.OpenGL.SimpleCube import SimpleCube
from Kamaelia.UI.OpenGL.Movement import LinearPath, PathMover, SimpleMover, SimpleRotator, SimpleBuzzer

points = [(3,3,-20),
          (4,0,-20),
          (3,-3,-20),
          (0,-4,-20),
          (-3,-3,-20),
          (-4,0,-20),
          (-3,3,-20),
          (0,4,-20),
          (3,3,-20),
         ]
path = LinearPath(points, 1000)

cube1 = SimpleCube(size=(1,1,1)).activate()
pathmover = PathMover(path).activate()
pathmover.link((pathmover,"outbox"), (cube1,"position"))

cube2 = SimpleCube(size=(1,1,1)).activate()
simplemover = SimpleMover(borders=(3,5,7)).activate()
simplemover.link((simplemover,"outbox"), (cube2,"position"))

cube3 = SimpleCube(size=(1,1,1), position=(-1,0,-15)).activate()
rotator = SimpleRotator().activate()
rotator.link((rotator,"outbox"), (cube3,"rel_rotation"))

cube4 = SimpleCube(size=(1,1,1), position=(1,0,-15)).activate()
buzzer = SimpleBuzzer().activate()
buzzer.link((buzzer,"outbox"), (cube4,"scaling"))

Axon.Scheduler.scheduler.run.runThreads()
# Licensed to the BBC under a Contributor Agreement: THF


text:
GatherMySteps is a web application (UI component) to process personal GPS tracks. It provides a track editor and a semantic editor.

The processing is divided into three stages: preview, adjust, and annotate. Tracks are grouped by days, for each day, it is possible to preview (and make changes) before advancing to the adjust stage. Tracks are sent back to the [server](https://github.com/ruipgil/processmysteps) where they are [transformed into trips](https://github.com/ruipgil/GatherMySteps). At the adjust stage, just like when previewing, the tracks (now trips) can be validated or changed to better represent the day being processed. Finally, in the annotate stage, users can annotate their day with personally relevant information.

You can check out the standalone editor, GPXplorer, at [http://ruipgil.com/GatherMySteps](http://ruipgil.com/GatherMySteps).

## Run

There are several ways to run GatherMySteps

+ Download the latest build from [GatherMySteps](https://github.com/ruipgil/GatherMySteps/releases), extract and open the ``` index.html ``` file.
+ Clone and install, then run the code
  - Compile (once) & run:

    ```
      npm run build
    ```

    Open the file at ``` build/index.html ```
  - Run as a server (with hot-loading):

    ```
      npm run dev
    ```

    Open the browser at ``` http://localhost:8080 ```

### Clone and install

```
git clone https://github.com/ruipgil/gathermysteps
cd gathermysteps
npm install --save-dev
```

> Note that GatherMySteps is the **UI component** of the system!
> You'll need to install and run [ProcessMySteps](https://github.com/ProcessMySteps).

## Technical Overview

GatherMySteps is essentially a track editor -- that allows the manipulation of GPS tracks -- and a semantic editor.
All the information is fetched from the [server](https://github.com/ruipgil/processmysteps), it also manages the progression of the application.

We use React and Redux to display information and propagate state changes. The root state of our application is an [immutable map](https://facebook.github.io/immutable-js/docs/#/Map) with the keys:
```js
{
  // display map data
  'map': {
    // last user defined bounds. Update to fit bounds
    'bounds': <BoundsRecords>,
    // last user defined center
    'center': { lat, lon },
    // array with ids of highlighted segments
    'highlighted': []
    // array with points highlighted
    'highlightedPoints': [],
    // callback for click
    'pointPrompt': null,
    // map provider
    'provider': 'OSM_VANILLA'
  }
  // last information received from the server
  'progress': {
    // day being processed
    'daySelected': '2016-10-02',
    // life received
    'life': '',
    // remaining tracks/days to be processed
    'remainingTracks': [],
    // server address
    'server': 'http://localhost:5000',
    // stage of processing (preview, adjust, annotate)
    'step': 0
  },
  'tracks': {
    // undo & redo history of tracks/trips
    'history': {
      'future': [...],
      'past': [...]
    },
    // map of segments, where the key is the id of the segment
    'segments': {
      '0': <SegmentRecord>
      // ...
    }
    // map of tracks, where the key is the id of the track
    'tracks': {
      '0': <TrackRecord>
      // ...
    }
  // ui stuff
  'ui': {}
}
```

Records and complex data structures reside in [``` src/records ```](./src/records/index.js). The actions and reducers are also organized around the structure presented above. From those, I'd highlight [segments reducers](./src/reducers/segments.js) which apply the logic necessary to execute actions such as split, join, or edit a segment.

### Track Editor (aka [GPXplorer](http://ruipgil.com/GatherMySteps))

![Track Editor Screenshot](docs/track-editor.png)

The track editor, used in the preview and adjust stages, is of the main modules of our system. It allows to edit tracks (and trips) with a fine grain of detail.
It displays tracks on a map and in a side pane, for better navigation and identification of the tracks being processed.
It is comprised of several components/containers. [` Map `](./src/map) and [` TrackPane `](src/containers/TrackPane) are its main components.

Some of the actions of the track editor are the following:
+ Remove a track segment
+ Create a new track segment
+ Edit points individually
+ Split a track segment into two
+ Join two track segments into one
+ Inspect points
+ Undo/redo actions

Tracks may have thousands of points, which make [naive undo/redo](http://redux.js.org/docs/recipes/ImplementingUndoHistory.html) of destructive actions memory intensive or even impossible. To prevent that, instead of storing the entire state (to later restore), we store a revert function that generally accepts a few parameters and has a small memory footprint. For instance, the join track stores an undo function that is similar to the split of the resulting segment, in the point joined.

### Semantic Editor

![Semantic Editor Screenshot](docs/semantic-editor.png)

The semantic editor harnesses the power and flexibility of plain text editing, with the help of personally relevant suggestions and syntax highlighting. In fact, the semantic editor was inspired by IDEs. The annotation follow the [LIFE format](https://github.com/domiriel/LIFE).

We have developed [a PEG parser](src/Editor/life.peg.js) (using [`PEGjs`](http://pegjs.org/)) that implements the specification and builds an AST. With the AST and the tracks/trips (received from the server) we are able to [associate the LIFE annotations with the tracks](src/Editor/buildLifeAst.js).

We use [Draft.js](https://facebook.github.io/draft-js/) to manage, decorate the semantic editor.

### Map

Both the track editor and the semantic editor are supported by the [map component](src/map/index.jsx). We implemented a custom wrapper around [Leaflet](leafletjs.com) that taps into our internal structure, allowing us to fine tune the performance. It was designed to support the following features:
+ display/hide track segments
+ handle changes in segments (join, split, and point editing)
+ manage overlays over segments

## Parallel projects

[*GatherMySteps*](https://github.com/ruipgil/GatherMySteps) is a webapp, that doubles as a track editor and semantic annotator. It is supported by [*ProcessMySteps*](https://github.com/ruipgil/ProcessMySteps), a python backend application that uses *TrackToTrip*.

[*GPXplorer*](http://ruipgil.com/GatherMySteps) is the track editor-only fork of [*GatherMySteps*](https://github.com/ruipgil/GatherMySteps)

These three projects are part of my master thesis.

## License
[MIT](./LICENSE)


text:
set -e

SCRIPT_DIR=$(dirname $0)
ADDED_DIR="$SCRIPT_DIR/added"
SOURCES_DIR="/tmp/artifacts"

pushd "$ADDED_DIR" &> /dev/null
    # Necessary to permit running with a randomised UID
    chmod ug+x kieserver-setup.sh kieserver-config.sh kieserver-install.sh kieserver-pull.sh kieserver-verify.sh kieserver-launch.sh
    cp -p kieserver-config.sh kieserver-install.sh kieserver-pull.sh kieserver-verify.sh kieserver-launch.sh quartz.properties ${JBOSS_HOME}/bin/
    cp -p kieserver-setup.sh ${JBOSS_HOME}/bin/launch
popd &> /dev/null

# supplementary tools only exist in kieserver > 6.2
if [ -e ${SOURCES_DIR}/jboss-bpmsuite-*-supplementary-tools.zip ]; then
    # Get the DDL files and copy to $JBOSS_HOME/bin/
    unzip -qj ${SOURCES_DIR}/jboss-bpmsuite-*-supplementary-tools.zip jboss-brms-bpmsuite-*-supplementary-tools/ddl-scripts/mysql5/quartz_tables_mysql.sql -d ${SCRIPT_DIR}
    unzip -qj ${SOURCES_DIR}/jboss-bpmsuite-*-supplementary-tools.zip jboss-brms-bpmsuite-*-supplementary-tools/ddl-scripts/postgresql/quartz_tables_postgres.sql -d ${SCRIPT_DIR}
    cp -p ${SCRIPT_DIR}/quartz_tables_mysql.sql ${JBOSS_HOME}/bin/
    cp -p ${SCRIPT_DIR}/quartz_tables_postgres.sql ${JBOSS_HOME}/bin/
fi


text:
using namespace rapidjson;

namespace chrono {
namespace vehicle {

// -----------------------------------------------------------------------------
// Default constructor.
// -----------------------------------------------------------------------------
RigidTerrain::RigidTerrain(ChSystem* system) {
    // Create the ground body and add it to the system.
    m_ground = ChSharedPtr<ChBody>(new ChBody(system->GetContactMethod()));
    m_ground->SetIdentifier(-1);
    m_ground->SetName("ground");
    m_ground->SetPos(ChVector<>(0, 0, 0));
    m_ground->SetBodyFixed(true);
    m_ground->SetCollide(true);
    system->AddBody(m_ground);

    // Create the default color asset
    m_color = ChSharedPtr<ChColorAsset>(new ChColorAsset);
    m_color->SetColor(ChColor(1, 1, 1));
    m_ground->AddAsset(m_color);
}

// -----------------------------------------------------------------------------
// Constructor from JSON file
// -----------------------------------------------------------------------------
static ChColor loadColor(const Value& a) {
    assert(a.IsArray());
    assert(a.Size() == 3);

    return ChColor(a[0u].GetDouble(), a[1u].GetDouble(), a[2u].GetDouble());
}

RigidTerrain::RigidTerrain(ChSystem* system, const std::string& filename) {
    // Create the ground body and add it to the system.
    m_ground = ChSharedPtr<ChBody>(new ChBody(system->GetContactMethod()));
    m_ground->SetIdentifier(-1);
    m_ground->SetName("ground");
    m_ground->SetPos(ChVector<>(0, 0, 0));
    m_ground->SetBodyFixed(true);
    m_ground->SetCollide(true);
    system->AddBody(m_ground);

    // Create the default color asset
    m_color = ChSharedPtr<ChColorAsset>(new ChColorAsset);
    m_color->SetColor(ChColor(1, 1, 1));
    m_ground->AddAsset(m_color);

    // Open the JSON file and read data
    FILE* fp = fopen(filename.c_str(), "r");

    char readBuffer[65536];
    FileReadStream is(fp, readBuffer, sizeof(readBuffer));

    fclose(fp);

    Document d;
    d.ParseStream(is);

    // Read top-level data
    assert(d.HasMember("Type"));
    assert(d.HasMember("Template"));
    assert(d.HasMember("Name"));

    // Read material properties
    float mu = d["Material Properties"]["Coefficient of Friction"].GetDouble();
    float cr = d["Material Properties"]["Coefficient of Restitution"].GetDouble();
    float ym = d["Material Properties"]["Young Modulus"].GetDouble();
    float pr = d["Material Properties"]["Poisson Ratio"].GetDouble();
    SetContactMaterial(mu, cr, ym, pr);

    // Read visualization data
    if (d.HasMember("Visualization")) {
        if (d["Visualization"].HasMember("Color")) {
            ChColor color = loadColor(d["Visualization"]["Color"]);
            SetColor(color);
        }

        if (d["Visualization"].HasMember("Texture File")) {
            std::string tex_file = d["Visualization"]["Texture File"].GetString();
            double sx = 1;
            double sy = 1;
            if (d["Visualization"].HasMember("Texture Scaling")) {
                sx = d["Visualization"]["Texture Scaling"][0u].GetDouble();
                sy = d["Visualization"]["Texture Scaling"][1u].GetDouble();
            }
            SetTexture(vehicle::GetDataFile(tex_file), sx, sy);
        }
    }

    // Read geometry and initialize terrain
    if (d["Geometry"].HasMember("Height")) {
        double sx = d["Geometry"]["Size"][0u].GetDouble();
        double sy = d["Geometry"]["Size"][1u].GetDouble();
        double h = d["Geometry"]["Height"].GetDouble();
        Initialize(h, sx, sy);
    } else if (d["Geometry"].HasMember("Mesh Filename")) {
        std::string mesh_file = d["Geometry"]["Mesh Filename"].GetString();
        std::string mesh_name = d["Geometry"]["Mesh Name"].GetString();
        Initialize(vehicle::GetDataFile(mesh_file), mesh_name);
    } else if (d["Geometry"].HasMember("Height Map Filename")) {
        std::string bmp_file = d["Geometry"]["Height Map Filename"].GetString();
        std::string mesh_name = d["Geometry"]["Mesh Name"].GetString();
        double sx = d["Geometry"]["Size"][0u].GetDouble();
        double sy = d["Geometry"]["Size"][1u].GetDouble();
        double hMin = d["Geometry"]["Height Range"][0u].GetDouble();
        double hMax = d["Geometry"]["Height Range"][1u].GetDouble();
        Initialize(vehicle::GetDataFile(bmp_file), mesh_name, sx, sy, hMin, hMax);
    }
}

// -----------------------------------------------------------------------------
// Set the material properties, according to the underlying contact model
// -----------------------------------------------------------------------------
void RigidTerrain::SetContactMaterial(float friction_coefficient,
                                      float restitution_coefficient,
                                      float young_modulus,
                                      float poisson_ratio) {
    switch (m_ground->GetContactMethod()) {
        case ChMaterialSurfaceBase::DVI:
            m_ground->GetMaterialSurface()->SetFriction(friction_coefficient);
            m_ground->GetMaterialSurface()->SetRestitution(restitution_coefficient);
            break;
        case ChMaterialSurfaceBase::DEM:
            m_ground->GetMaterialSurfaceDEM()->SetFriction(friction_coefficient);
            m_ground->GetMaterialSurfaceDEM()->SetRestitution(restitution_coefficient);
            m_ground->GetMaterialSurfaceDEM()->SetYoungModulus(young_modulus);
            m_ground->GetMaterialSurfaceDEM()->SetPoissonRatio(poisson_ratio);
            break;
    }
}

// -----------------------------------------------------------------------------
// Set the color of the visualization assets
// -----------------------------------------------------------------------------
void RigidTerrain::SetColor(ChColor color) {
    m_color->SetColor(color);
}

// -----------------------------------------------------------------------------
// Set the texture and texture scaling
// -----------------------------------------------------------------------------
void RigidTerrain::SetTexture(const std::string tex_file, float tex_scale_x, float tex_scale_y) {
    ChSharedPtr<ChTexture> texture(new ChTexture);
    texture->SetTextureFilename(tex_file);
    texture->SetTextureScale(tex_scale_x, tex_scale_y);
    m_ground->AddAsset(texture);
}

// -----------------------------------------------------------------------------
// Initialize the terrain as a rigid box
// -----------------------------------------------------------------------------
void RigidTerrain::Initialize(double height, double sizeX, double sizeY) {
    double depth = 10;
    m_ground->GetCollisionModel()->ClearModel();
    m_ground->GetCollisionModel()->AddBox(0.5 * sizeX, 0.5 * sizeY, 0.5 * depth,
                                          ChVector<>(0, 0, height - 0.5 * depth));
    ChSharedPtr<ChBoxShape> box(new ChBoxShape);
    box->GetBoxGeometry().Size = ChVector<>(0.5 * sizeX, 0.5 * sizeY, 0.5 * depth);
    box->GetBoxGeometry().Pos = ChVector<>(0, 0, height - 0.5 * depth);
    m_ground->AddAsset(box);
    m_ground->GetCollisionModel()->BuildModel();

    m_type = FLAT;
    m_height = height;
}

// -----------------------------------------------------------------------------
// Initialize the terrain from a specified mesh file.
// -----------------------------------------------------------------------------
void RigidTerrain::Initialize(const std::string& mesh_file, const std::string& mesh_name) {
    m_trimesh.LoadWavefrontMesh(mesh_file, true, true);

    // Create the visualization asset.
    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(m_trimesh);
    trimesh_shape->SetName(mesh_name);
    m_ground->AddAsset(trimesh_shape);

    // Create contact geometry.
    m_ground->GetCollisionModel()->ClearModel();
    m_ground->GetCollisionModel()->AddTriangleMesh(m_trimesh, true, false, ChVector<>(0, 0, 0));
    m_ground->GetCollisionModel()->BuildModel();

    m_mesh_name = mesh_name;
    m_type = MESH;
}

// -----------------------------------------------------------------------------
// Initialize the terrain from a specified height map.
// -----------------------------------------------------------------------------
void RigidTerrain::Initialize(const std::string& heightmap_file,
                              const std::string& mesh_name,
                              double sizeX,
                              double sizeY,
                              double hMin,
                              double hMax) {
    // Read the BMP file nd extract number of pixels.
    BMP hmap;
    if (!hmap.ReadFromFile(heightmap_file.c_str())) {
        throw ChException("Cannot open height map BMP file");
    }
    int nv_x = hmap.TellWidth();
    int nv_y = hmap.TellHeight();

    // Construct a triangular mesh of sizeX x sizeY.
    // Each pixel in the BMP represents a vertex.
    // The gray level of a pixel is mapped to the height range, with black corresponding
    // to hMin and white corresponding to hMax.
    // UV coordinates are mapped in [0,1] x [0,1].
    // We use smoothed vertex normals.
    double dx = sizeX / (nv_x - 1);
    double dy = sizeY / (nv_y - 1);
    double h_scale = (hMax - hMin) / 255;
    double x_scale = 1.0 / (nv_x - 1);
    double y_scale = 1.0 / (nv_y - 1);
    unsigned int n_verts = nv_x * nv_y;
    unsigned int n_faces = 2 * (nv_x - 1) * (nv_y - 1);

    // Resize mesh arrays.
    m_trimesh.getCoordsVertices().resize(n_verts);
    m_trimesh.getCoordsNormals().resize(n_verts);
    m_trimesh.getCoordsUV().resize(n_verts);
    m_trimesh.getCoordsColors().resize(n_verts);

    m_trimesh.getIndicesVertexes().resize(n_faces);
    m_trimesh.getIndicesNormals().resize(n_faces);

    // Initialize the array of accumulators (number of adjacent faces to a vertex)
    std::vector<int> accumulators(n_verts, 0);

    // Readibility aliases
    std::vector<ChVector<> >& vertices = m_trimesh.getCoordsVertices();
    std::vector<ChVector<> >& normals = m_trimesh.getCoordsNormals();
    std::vector<ChVector<int> >& idx_vertices = m_trimesh.getIndicesVertexes();
    std::vector<ChVector<int> >& idx_normals = m_trimesh.getIndicesNormals();

    // Load mesh vertices.
    // Note that pixels in a BMP start at top-left corner.
    // We order the vertices starting at the bottom-left corner, row after row.
    // The bottom-left corner corresponds to the point (-sizeX/2, -sizeY/2).
    std::cout << "Load vertices..." << std::endl;
    unsigned int iv = 0;
    for (int iy = nv_y - 1; iy >= 0; --iy) {
        double y = 0.5 * sizeY - iy * dy;
        for (int ix = 0; ix < nv_x; ++ix) {
            double x = ix * dx - 0.5 * sizeX;
            // Calculate equivalent gray level (RGB -> YUV)
            ebmpBYTE red = hmap(ix, iy)->Red;
            ebmpBYTE green = hmap(ix, iy)->Green;
            ebmpBYTE blue = hmap(ix, iy)->Blue;
            double gray = 0.299 * red + 0.587 * green + 0.114 * blue;
            // Map gray level to vertex height
            double z = hMin + gray * h_scale;
            // Set vertex location
            vertices[iv] = ChVector<>(x, y, z);
            // Initialize vertex normal to (0, 0, 0).
            normals[iv] = ChVector<>(0, 0, 0);
            // Assign color white to all vertices
            m_trimesh.getCoordsColors()[iv] = ChVector<float>(1, 1, 1);
            // Set UV coordinates in [0,1] x [0,1]
            m_trimesh.getCoordsUV()[iv] = ChVector<>(ix * x_scale, iy * y_scale, 0.0);
            ++iv;
        }
    }

    // Specify triangular faces (two at a time).
    // Specify the face vertices counter-clockwise.
    // Set the normal indices same as the vertex indices.
    std::cout << "Load faces..." << std::endl;
    unsigned int it = 0;
    for (int iy = nv_y - 2; iy >= 0; --iy) {
        for (int ix = 0; ix < nv_x - 1; ++ix) {
            int v0 = ix + nv_x * iy;
            idx_vertices[it] = ChVector<int>(v0, v0 + nv_x + 1, v0 + nv_x);
            idx_normals[it] = ChVector<int>(v0, v0 + nv_x + 1, v0 + nv_x);
            ++it;
            idx_vertices[it] = ChVector<int>(v0, v0 + 1, v0 + nv_x + 1);
            idx_normals[it] = ChVector<int>(v0, v0 + 1, v0 + nv_x + 1);
            ++it;
        }
    }

    // Calculate normals and then average the normals from all adjacent faces.
    for (unsigned int it = 0; it < n_faces; ++it) {
        // Calculate the triangle normal as a normalized cross product.
        ChVector<> nrm = Vcross(vertices[idx_vertices[it].y] - vertices[idx_vertices[it].x],
                                vertices[idx_vertices[it].z] - vertices[idx_vertices[it].x]);
        nrm.Normalize();
        // Increment the normals of all incident vertices by the face normal
        normals[idx_normals[it].x] += nrm;
        normals[idx_normals[it].y] += nrm;
        normals[idx_normals[it].z] += nrm;
        // Increment the count of all incident vertices by 1
        accumulators[idx_normals[it].x] += 1;
        accumulators[idx_normals[it].y] += 1;
        accumulators[idx_normals[it].z] += 1;
    }

    // Set the normals to the average values.
    for (unsigned int in = 0; in < n_verts; ++in) {
        normals[in] /= (double)accumulators[in];
    }

    // Create the visualization asset.
    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(m_trimesh);
    trimesh_shape->SetName(mesh_name);
    m_ground->AddAsset(trimesh_shape);

    // Create contact geometry.
    m_ground->GetCollisionModel()->ClearModel();
    m_ground->GetCollisionModel()->AddTriangleMesh(m_trimesh, true, false, ChVector<>(0, 0, 0));
    m_ground->GetCollisionModel()->BuildModel();

    m_mesh_name = mesh_name;
    m_type = HEIGHT_MAP;
}

// -----------------------------------------------------------------------------
// Export the terrain mesh (if any) as a macro in a PovRay include file.
// -----------------------------------------------------------------------------
void RigidTerrain::ExportMeshPovray(const std::string& out_dir) {
    switch (m_type) {
        case MESH:
            utils::WriteMeshPovray(m_trimesh, m_mesh_name, out_dir, ChColor(1, 1, 1));
            break;
        case HEIGHT_MAP:
            utils::WriteMeshPovray(m_trimesh, m_mesh_name, out_dir, ChColor(1, 1, 1), ChVector<>(0, 0, 0),
                                   ChQuaternion<>(1, 0, 0, 0), true);
            break;
    }
}

// -----------------------------------------------------------------------------
// Return the terrain height at the specified location
// -----------------------------------------------------------------------------
double RigidTerrain::GetHeight(double x, double y) const {
    switch (m_type) {
        case FLAT:
            return m_height;
        case MESH: {
            double height = 0;
            //// TODO
            return height;
        }
        case HEIGHT_MAP: {
            double height = 0;
            //// TODO
            return height;
        }
        default:
            return 0;
    }
}

// -----------------------------------------------------------------------------
// Return the terrain normal at the specified location
// -----------------------------------------------------------------------------
ChVector<> RigidTerrain::GetNormal(double x, double y) const {
    switch (m_type) {
        case FLAT:
            return ChVector<>(0, 0, 1);
        case MESH: {
            ChVector<> normal(0, 0, 1);
            //// TODO
            return normal;
        }
        case HEIGHT_MAP: {
            ChVector<> normal(0, 0, 1);
            //// TODO
            return normal;
        }
        default:
            return ChVector<>(0, 0, 1);
    }
}

}  // end namespace vehicle
}  // end namespace chrono


text:
package registry

import (
	"fmt"
	"sync"

	"k8s.io/klog/v2"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apiserver/pkg/registry/generic"
	"k8s.io/apiserver/pkg/storage"
	cacherstorage "k8s.io/apiserver/pkg/storage/cacher"
	"k8s.io/apiserver/pkg/storage/etcd3"
	"k8s.io/apiserver/pkg/storage/storagebackend"
	"k8s.io/apiserver/pkg/storage/storagebackend/factory"
	"k8s.io/client-go/tools/cache"
)

// Creates a cacher based given storageConfig.
func StorageWithCacher() generic.StorageDecorator {
	return func(
		storageConfig *storagebackend.ConfigForResource,
		resourcePrefix string,
		keyFunc func(obj runtime.Object) (string, error),
		newFunc func() runtime.Object,
		newListFunc func() runtime.Object,
		getAttrsFunc storage.AttrFunc,
		triggerFuncs storage.IndexerFuncs,
		indexers *cache.Indexers) (storage.Interface, factory.DestroyFunc, error) {

		s, d, err := generic.NewRawStorage(storageConfig, newFunc)
		if err != nil {
			return s, d, err
		}
		if klog.V(5).Enabled() {
			klog.InfoS("Storage caching is enabled", objectTypeToArgs(newFunc())...)
		}

		cacherConfig := cacherstorage.Config{
			Storage:        s,
			Versioner:      etcd3.APIObjectVersioner{},
			ResourcePrefix: resourcePrefix,
			KeyFunc:        keyFunc,
			NewFunc:        newFunc,
			NewListFunc:    newListFunc,
			GetAttrsFunc:   getAttrsFunc,
			IndexerFuncs:   triggerFuncs,
			Indexers:       indexers,
			Codec:          storageConfig.Codec,
		}
		cacher, err := cacherstorage.NewCacherFromConfig(cacherConfig)
		if err != nil {
			return nil, func() {}, err
		}
		destroyFunc := func() {
			cacher.Stop()
			d()
		}

		// TODO : Remove RegisterStorageCleanup below when PR
		// https://github.com/kubernetes/kubernetes/pull/50690
		// merges as that shuts down storage properly
		RegisterStorageCleanup(destroyFunc)

		return cacher, destroyFunc, nil
	}
}

func objectTypeToArgs(obj runtime.Object) []interface{} {
	// special-case unstructured objects that tell us their apiVersion/kind
	if u, isUnstructured := obj.(*unstructured.Unstructured); isUnstructured {
		if apiVersion, kind := u.GetAPIVersion(), u.GetKind(); len(apiVersion) > 0 && len(kind) > 0 {
			return []interface{}{"apiVersion", apiVersion, "kind", kind}
		}
	}

	// otherwise just return the type
	return []interface{}{"type", fmt.Sprintf("%T", obj)}
}

// TODO : Remove all the code below when PR
// https://github.com/kubernetes/kubernetes/pull/50690
// merges as that shuts down storage properly
// HACK ALERT : Track the destroy methods to call them
// from the test harness. TrackStorageCleanup will be called
// only from the test harness, so Register/Cleanup will be
// no-op at runtime.

var cleanupLock sync.Mutex
var cleanup []func() = nil

func TrackStorageCleanup() {
	cleanupLock.Lock()
	defer cleanupLock.Unlock()

	if cleanup != nil {
		panic("Conflicting storage tracking")
	}
	cleanup = make([]func(), 0)
}

func RegisterStorageCleanup(fn func()) {
	cleanupLock.Lock()
	defer cleanupLock.Unlock()

	if cleanup == nil {
		return
	}
	cleanup = append(cleanup, fn)
}

func CleanupStorage() {
	cleanupLock.Lock()
	old := cleanup
	cleanup = nil
	cleanupLock.Unlock()

	for _, d := range old {
		d()
	}
}


text:
<?php

/* RecrutementTestBundle::accueil_candidat.html.twig */
class __TwigTemplate_433eac2c143999d071374d4e2b40c91db64d264d3e0b2f7b01cb519b9319e7bb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("RecrutementTestBundle::layout_admin.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "RecrutementTestBundle::layout_admin.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_body($context, array $blocks = array())
    {
        // line 3
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["oCandidat"]) ? $context["oCandidat"] : $this->getContext($context, "oCandidat")), "nom"), "html", null, true);
        echo "

";
        // line 4
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["oTest"]) ? $context["oTest"] : $this->getContext($context, "oTest")), "nom"), "html", null, true);
        echo "

            ";
        // line 6
        $context["i"] = 1;
        // line 7
        echo "            ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["oTest"]) ? $context["oTest"] : $this->getContext($context, "oTest")), "questions"));
        foreach ($context['_seq'] as $context["_key"] => $context["question"]) {
            // line 8
            echo "

                        Question";
            // line 10
            echo twig_escape_filter($this->env, (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")), "html", null, true);
            echo "

";
            // line 11
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["question"]) ? $context["question"] : $this->getContext($context, "question")), "libelle"), "html", null, true);
            echo "

                        ";
            // line 14
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["question"]) ? $context["question"] : $this->getContext($context, "question")), "reponses"));
            foreach ($context['_seq'] as $context["_key"] => $context["oReponse"]) {
                // line 15
                echo "

                                ";
                // line 16
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["oReponse"]) ? $context["oReponse"] : $this->getContext($context, "oReponse")), "intitule"), "html", null, true);
                echo "
                                <input type=\"checkbox\" name=\"reponse";
                // line 17
                echo twig_escape_filter($this->env, (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")), "html", null, true);
                echo "\"/>
                                ";
                // line 18
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["oReponse"]) ? $context["oReponse"] : $this->getContext($context, "oReponse")), "isTrue"), "html", null, true);
                echo "

                        ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['oReponse'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 21
            echo "

            ";
            // line 23
            $context["i"] = ((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) + 1);
            // line 24
            echo "            ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['question'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 25
        echo "

";
    }

    public function getTemplateName()
    {
        return "RecrutementTestBundle::accueil_candidat.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  97 => 25,  91 => 24,  89 => 23,  85 => 21,  76 => 18,  72 => 17,  68 => 16,  65 => 15,  61 => 14,  55 => 11,  51 => 10,  47 => 8,  42 => 7,  40 => 6,  35 => 4,  31 => 3,  28 => 2,);
    }
}


text:
#include "ship.h"

/**
 * Constructor
 * Constructs a battleship.
 * @param length        The size (length) of the battleship.
 */

Ship::Ship(const quint8 length, QString name) :
    m_length(length),
    hits(0),
    m_position(0,0,0,0),
    m_name(name)
{
}

/**
 * Constructor
 * Constructs a battleship with its position on map.
 * @param length        The ships size (lenght).
 * @param position      The position on the map.
 */
Ship::Ship(const quint8 length, const QRect position, QString name) :
    m_length(length),
    m_position(position),
    hits(0),
    m_name(name)
{

}

/**
 * Ship is hidden by a shot.
 */
void Ship::addHit()
{
    ++hits;
}

/**
 * Returns a QPoint list. The points are the position of
 * the ship on the game board.
 * @return list
 */
QList<QPoint> Ship::getPointList() const
{
    QList<QPoint> list;
    QRect shipRect = m_position;
    shipRect.normalized();
    if (shipRect.width() == 1) {
        for (int y=0; y<shipRect.height(); ++y) {
            QPoint point(shipRect.x(), shipRect.y() + y);
            list.append(point);
        }
    } else {
        for (int x=0; x<shipRect.width(); ++x) {
            QPoint point(shipRect.x() + x, shipRect.y());
            list.append(point);
        }
    }

    return list;
}

/**
 * STATIC
 * Creates a rectangle of the ships position in the map.
 * @param point             The point which the user has chosen.
 * @param length            The length of the ship.
 * @param direction         The direction in which the ship is laid.
 * @return rect             A QRect with the ships position in the map.
 */
QRect Ship::getShipPositionRect(const int x, const int y, const quint8 length, const Direction direction)
{
    const int l = length - 1;
    QRect rect;
    switch (direction) {
    case Up:
        rect.setCoords(x, y-l, x, y);
        break;
    case Down:
        rect.setCoords(x, y, x, y+l);
        break;
    case Left:
        rect.setCoords(x-l, y, x, y);
        break;
    case Right:
        rect.setCoords(x, y, x+l, y);
        break;
    default:
        break;
    }

    return rect;
}

/**
 * Get a direction from an angel value.
 * @param angel
 * @return          A Direction value.
 */
Ship::Direction Ship::getDirectionFromAngel(int angel)
{
    switch (angel) {
    case 0:
        return Up;
        break;
    case 90:
        return Right;
        break;
    case 180:
        return Down;
        break;
    case 270:
        return Left;
        break;
    default:
        return Up;
        break;
    }

    return Up;
}


text:
package org.slc.sli.api.client.constants.v1;

import java.util.HashMap;
import java.util.Map;

import org.slc.sli.api.client.constants.ResourceNames;

/**
 * Constants used in URI path requests.
 *
 * @author kmyers
 *
 */
public class PathConstants {

    public static final String STUDENT_SCHOOL_ASSOCIATIONS = "studentSchoolAssociations";
    public static final String TEACHER_SCHOOL_ASSOCIATIONS = "teacherSchoolAssociations";
    public static final String TEACHER_SECTION_ASSOCIATIONS = "teacherSectionAssociations";
    public static final String SCHOOL_SESSION_ASSOCIATIONS = "schoolSessionAssociations";
    public static final String COURSE_OFFERINGS = "courseOfferings";
    public static final String STUDENT_ASSESSMENTS = "studentAssessments";
    public static final String STUDENT_SECTION_ASSOCIATIONS = "studentSectionAssociations";
    public static final String STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS = "staffEducationOrgAssignmentAssociations";
    public static final String EDUCATION_ORGANIZATION_ASSOCIATIONS = "educationOrganizationAssociations";
    public static final String COURSE_SECTION_ASSOCIATIONS = "courseSectionAssociations";
    public static final String COURSE_TRANSCRIPTS = "courseTranscripts";
    public static final String STUDENT_PARENT_ASSOCIATIONS = "studentParentAssociations";
    public static final String STUDENT_DISCIPLINE_INCIDENT_ASSOCIATIONS = "studentDisciplineIncidentAssociations";
    public static final String STAFF_COHORT_ASSOCIATIONS = "staffCohortAssociations";
    public static final String STUDENT_COHORT_ASSOCIATIONS = "studentCohortAssociations";
    public static final String STUDENT_WITH_GRADE = "studentWithGrade";

    public static final String ASSESSMENTS = "assessments";
    public static final String LEARNING_OBJECTIVES = "learningObjectives";
    public static final String PARENT_LEARNING_OBJECTIVES = "parentLearningObjectives";
    public static final String CHILD_LEARNING_OBJECTIVES = "childLearningObjectives";
    public static final String ATTENDANCES = "attendances";
    public static final String COHORTS = "cohorts";
    public static final String COMPETENCY_LEVEL_DESCRIPTORS = "competencyLevelDescriptor";
    public static final String COMPETENCY_LEVEL_DESCRIPTOR_TYPES = "competencyLevelDescriptorTypes";
    public static final String COURSES = "courses";
    public static final String DISCIPLINE_INCIDENTS = "disciplineIncidents";
    public static final String DISCIPLINE_ACTIONS = "disciplineActions";
    public static final String EDUCATION_ORGANIZATIONS = "educationOrganizations";
    public static final String GRADEBOOK_ENTRIES = "gradebookEntries";
    public static final String GRADING_PERIODS = "gradingPeriods";
    public static final String LEARNING_STANDARDS = "learningStandards";
    public static final String PARENTS = "parents";
    public static final String PROGRAMS = "programs";
    public static final String REPORT_CARDS = "reportCards";
    public static final String SECTIONS = "sections";
    public static final String SESSIONS = "sessions";
    public static final String SCHOOLS = "schools";
    public static final String STUDENTS = "students";
    public static final String STUDENT_COMPETENCIES = "studentCompetencies";
    public static final String STUDENT_COMPETENCY_OBJECTIVES = "studentCompetencyObjectives";
    public static final String TEACHERS = "teachers";
    public static final String STAFF = "staff";
    public static final String STUDENT_ACADEMIC_RECORDS = "studentAcademicRecords";
    public static final String STUDENT_GRADEBOOK_ENTRIES = "studentGradebookEntries";
    public static final String STAFF_PROGRAM_ASSOCIATIONS = "staffProgramAssociations";
    public static final String STUDENT_PROGRAM_ASSOCIATIONS = "studentProgramAssociations";
    public static final String GRADES = "grades";

    public static final String CUSTOM_ENTITIES = "custom";

    public static final String AGGREGATES = "aggregates";

    /**
     * Paths to various helper functions
     */
    public static final String SECURITY_SESSION_CHECK = "system/session/check";

    /** resource for security session logout */
    public static final String SECURITY_SESSION_LOGOUT = "system/session/logout";

    /** resource for security session check */
    public static final String SECURITY_SESSION_DEBUG = "system/session/debug";

    /** Home resource */
    public static final String HOME = "home";

    /*
     * This map should go away when we switch basic definition store association names to camel
     * case.
     * This map is used when building the links to be returned. When building links we need to look
     * into definition store to get
     * the resource name. This resource name is then mapped to the new camel case name using this
     * map.
     */
    public static final Map<String, String> TEMP_MAP = new HashMap<String, String>();
    static {
        TEMP_MAP.put(ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, STUDENT_SCHOOL_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, TEACHER_SCHOOL_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.TEACHER_SECTION_ASSOCIATIONS, TEACHER_SECTION_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.SCHOOL_SESSION_ASSOCIATIONS, SCHOOL_SESSION_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.COURSE_OFFERINGS, COURSE_OFFERINGS);
        TEMP_MAP.put(ResourceNames.STUDENT_ASSESSMENTS, STUDENT_ASSESSMENTS);
        TEMP_MAP.put(ResourceNames.STUDENT_SECTION_ASSOCIATIONS, STUDENT_SECTION_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.COURSE_TRANSCRIPTS, COURSE_TRANSCRIPTS);
        TEMP_MAP.put(ResourceNames.STUDENT_PARENT_ASSOCIATIONS, STUDENT_PARENT_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STUDENT_PROGRAM_ASSOCIATIONS, STUDENT_PROGRAM_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STAFF_PROGRAM_ASSOCIATIONS, STAFF_PROGRAM_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STAFF_COHORT_ASSOCIATIONS, STAFF_COHORT_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATIONS, STUDENT_DISCIPLINE_INCIDENT_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STAFF_COHORT_ASSOCIATIONS, STAFF_COHORT_ASSOCIATIONS);
        TEMP_MAP.put(ResourceNames.STUDENT_COHORT_ASSOCIATIONS, STUDENT_COHORT_ASSOCIATIONS);

        TEMP_MAP.put(ResourceNames.ASSESSMENTS, ASSESSMENTS);
        TEMP_MAP.put(ResourceNames.LEARNINGOBJECTIVES, LEARNING_OBJECTIVES);
        TEMP_MAP.put(ResourceNames.LEARNINGSTANDARDS, LEARNING_STANDARDS);
        TEMP_MAP.put(ResourceNames.ATTENDANCES, ATTENDANCES);
        TEMP_MAP.put(ResourceNames.COHORTS, COHORTS);
        TEMP_MAP.put(ResourceNames.COMPETENCY_LEVEL_DESCRIPTORS, COMPETENCY_LEVEL_DESCRIPTORS);
        TEMP_MAP.put(ResourceNames.COMPETENCY_LEVEL_DESCRIPTOR_TYPES, COMPETENCY_LEVEL_DESCRIPTOR_TYPES);
        TEMP_MAP.put(ResourceNames.COURSES, COURSES);
        TEMP_MAP.put(ResourceNames.DISCIPLINE_INCIDENTS, DISCIPLINE_INCIDENTS);
        TEMP_MAP.put(ResourceNames.DISCIPLINE_ACTIONS, DISCIPLINE_ACTIONS);
        TEMP_MAP.put(ResourceNames.EDUCATION_ORGANIZATIONS, EDUCATION_ORGANIZATIONS);
        TEMP_MAP.put(ResourceNames.GRADEBOOK_ENTRIES, GRADEBOOK_ENTRIES);
        TEMP_MAP.put(ResourceNames.GRADING_PERIODS, GRADING_PERIODS);
        TEMP_MAP.put(ResourceNames.PARENTS, PARENTS);
        TEMP_MAP.put(ResourceNames.PROGRAMS, PROGRAMS);
        TEMP_MAP.put(ResourceNames.REPORT_CARDS, REPORT_CARDS);
        TEMP_MAP.put(ResourceNames.SECTIONS, SECTIONS);
        TEMP_MAP.put(ResourceNames.SESSIONS, SESSIONS);
        TEMP_MAP.put(ResourceNames.SCHOOLS, SCHOOLS);
        TEMP_MAP.put(ResourceNames.STUDENTS, STUDENTS);
        TEMP_MAP.put(ResourceNames.STUDENT_COMPETENCIES, STUDENT_COMPETENCIES);
        TEMP_MAP.put(ResourceNames.STUDENT_COMPETENCY_OBJECTIVES, STUDENT_COMPETENCY_OBJECTIVES);
        TEMP_MAP.put(ResourceNames.STAFF, STAFF);
        TEMP_MAP.put(ResourceNames.STUDENT_ACADEMIC_RECORDS, STUDENT_ACADEMIC_RECORDS);
        TEMP_MAP.put(ResourceNames.STUDENT_GRADEBOOK_ENTRIES, STUDENT_GRADEBOOK_ENTRIES);
        TEMP_MAP.put(ResourceNames.TEACHERS, TEACHERS);
        TEMP_MAP.put(ResourceNames.GRADES, GRADES);
    }

    public static final String V1 = "v1";
    /** Main entry point for the SLI API ReSTful web service. */
    public static final String API_SERVER_PATH = "api/rest/v1";
    /** URL to check the validity of a SLI session. */
    public static final String SESSION_CHECK_PATH = "system/session/check";
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('audio-source', 'Integration | Component | audio source', {
  integration: true
});

test('it renders', function(assert) {

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{audio-source}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#audio-source}}
      template block text
    {{/audio-source}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
require_dependency "subscriber/application_controller"
require "ruby_identicon"
module Subscriber
  class Account::UsersController < ApplicationController
    def new
      @user = Subscriber::User.new(params[:user])
      @user.build_organization
      @user.organization.org_type = params[:org_type] rescue nil
    end

    def create
      account = Subscriber::Account.find_by!(:subdomain => request.subdomain)
      p user_params[:organization_attributes][:name]
      organization = Subscriber::Organization.where(name: user_params[:organization_attributes][:name], org_type: user_params[:organization_attributes][:org_type])
      if organization.any?
        params[:user].delete(:organization_attributes)
        @user = account.users.create(user_params)
        if @user.valid?
          @user.organization = organization.last
          @user.member.organization_id = organization.last.id
          @user.member.save!
          @user.save!
          @user.reload
          @user.send_signup_email
          force_authentication!(@user)
          flash[:success] = "You have signed up successfully."
          redirect_to root_path
        else
          flash[:error] = @user.errors.full_messages
          render action: 'new'
        end
      else
        @user = account.users.create(user_params)
        if @user.valid?
          @user.organization.owner_id = @user.id
          @user.organization.avatar = "data:image/png;base64,#{RubyIdenticon.create_base64(SecureRandom.base64(16).tr('+/=lIO0', 'pqrsxyz'))}"
          @user.member.organization_id = @user.organization.id
          @user.organization.save!
          @user.member.save!
          @user.organization.reload
          # @user.organization.send_signup_email
          @user.send_approval_email
          force_authentication!(@user)
          flash[:success] = "You have signed up successfully."
          redirect_to root_path
        else
          flash[:error] = @user.errors.full_messages
          render action: 'new'
        end
        p @user.member
      end
    end

    def edit
      @user = Subscriber::User.find(params[:id])
    end

    def update
      @user = Subscriber::User.find(params[:id])
      if @user.update_attributes(user_params)
        flash[:success] = "Profile updated."
        redirect_to edit_user_path
      else
        flash[:error] = "Profile could not be updated."
        redirect_to edit_user_path
      end
    end

    private
      def user_params
        params.require(:user).permit(:email, :password, :password_confirmation, :full_name, {:organization_attributes => [
          :name, :org_type, :industry, :city, :state, :description, :employees
        ]})
      end
  end
end


text:
// LICENSE : MIT
"use strict";
const EventEmitter = require("events");
const REPOSITORY_CHANGE = "REPOSITORY_CHANGE";
import MemoryDB from "./adpter/MemoryDB";
import Document from "../domain/document/Document";
export class DocumentRepository extends EventEmitter {
    constructor(database = new MemoryDB()) {
        super();
        /**
         * @type {MemoryDB}
         */
        this._database = database;
    }

    /**
     * @param id
     * @private
     */
    _get(id) {
        return this._database.get(`document.${id}`);
    }

    find(document) {
        return this._get(document.id);
    }

    /**
     * @returns {Document|undefined}
     */
    lastUsed() {
        const document = this._database.get(`document.lastUsed`);
        if (!document) {
            return;
        }
        return this._get(document.id);
    }

    /**
     * @param {DocumentModel} document
     */
    save(document) {
        this._database.set(`document.lastUsed`, document);
        this._database.set(`document.${document.id}`, document);
        this.emit(REPOSITORY_CHANGE, document);
    }

    /**
     * @param {DocumentModel} document
     */
    remove(document) {
        this._database.delete(`document.${document.id}`);
        this.emit(REPOSITORY_CHANGE);
    }

    onChange(handler) {
        this.on(REPOSITORY_CHANGE, handler);
    }
}
// singleton
export default new DocumentRepository();


text:
package org.insightech.er.editor.view.action.dbexport;

import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.RetargetAction;
import org.insightech.er.ERDiagramActivator;
import org.insightech.er.ImageKey;
import org.insightech.er.ResourceString;
import org.insightech.er.editor.ERDiagramEditor;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.dbexport.ddl.validator.ValidateResult;
import org.insightech.er.editor.model.dbexport.ddl.validator.Validator;
import org.insightech.er.editor.model.settings.DBSetting;
import org.insightech.er.editor.view.action.AbstractBaseAction;
import org.insightech.er.editor.view.dialog.dbexport.ExportDBSettingDialog;
import org.insightech.er.editor.view.dialog.dbexport.ExportErrorDialog;
import org.insightech.er.editor.view.dialog.dbexport.ExportToDBDialog;

public class ExportToDBAction extends AbstractBaseAction {

    public static final String ID = ExportToDBAction.class.getName();

    private final Validator validator;

    public ExportToDBAction(final ERDiagramEditor editor) {
        super(ID, ResourceString.getResourceString("action.title.export.db"), editor);

        validator = new Validator();
    }

    @Override
    public void execute(final Event event) {
        final ERDiagram diagram = getDiagram();

        final List<ValidateResult> errorList = validator.validate(diagram);

        if (!errorList.isEmpty()) {
            final ExportErrorDialog dialog = new ExportErrorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), errorList);
            dialog.open();
            return;
        }

        final ExportDBSettingDialog dialog = new ExportDBSettingDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), diagram);

        if (dialog.open() == IDialogConstants.OK_ID) {
            final String ddl = dialog.getDdl();

            final DBSetting dbSetting = dialog.getDbSetting();

            final ExportToDBDialog exportToDBDialog = new ExportToDBDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), diagram, dbSetting, ddl);

            exportToDBDialog.open();
        }
    }

    public static class ExportToDBRetargetAction extends RetargetAction {

        public ExportToDBRetargetAction() {
            super(ID, ResourceString.getResourceString("action.title.export.db"));

            setImageDescriptor(ERDiagramActivator.getImageDescriptor(ImageKey.EXPORT_TO_DB));
            setToolTipText(getText());
        }

    }
}