text:
package eu.amidst.dynamic.examples.models;

import eu.amidst.core.datastream.DataStream;
import eu.amidst.dynamic.datastream.DynamicDataInstance;
import eu.amidst.dynamic.io.DynamicBayesianNetworkWriter;
import eu.amidst.dynamic.io.DynamicDataStreamLoader;
import eu.amidst.dynamic.models.DynamicBayesianNetwork;
import eu.amidst.dynamic.models.DynamicDAG;
import eu.amidst.dynamic.variables.DynamicVariables;
import eu.amidst.core.variables.Variable;

import java.io.IOException;

/**
 * This class contains examples about how we can create CajaMar's dynamic models using the AMIDST Toolbox.
 * It show how to create 2T-DBNs over multinomial, Gassuian and IndicatorDistribution variables.
 *
 * Created by andresmasegosa on 22/11/14.
 */
public final class CajaMarModels {

    private CajaMarModels(){
        //no called
    }
    /**
     * In this example, we create the proposed dynamic model for making predictions about the defaulting
     * behaviour of a client. We took some fake data with some fake attributes.
     *
     * We show how to create indicator variables and use it in the model.
     *
     * We finally compute the log-likelihood of the data according to the created model (i.e. the probabilty distributions
     * are randomly initialized, there is no parametric learning). The data is a single long temporal sequence.
     */
    public static void cajaMarDefaulterPredictor() throws IOException, ClassNotFoundException {

        /**
         * 1. Our data is on disk and does not fit in memory. So, we use a DataOnDisk object.
         * 2. Our data is dynamic and is on file, so we create the DataStream using a DynamicDataOnDiskFromFile object.
         * 3. Our data is in Weka format, so we use a WekaDataFileReader.
         */
        DataStream<DynamicDataInstance> data = DynamicDataStreamLoader.loadFromFile("datasets/simulated/syntheticDataCajaMar.arff");

        /**
         * 1. Once the data is loaded, we create a random dynamic variable for each of the attributes (i.e. data columns)
         * in our data. Here dynamic variable has the same type than static variables. However, there are two main differences
         *      - If we called to the method "isDynamic" of Variable class, it will return true.
         *      - They have a temporal clone (similarly to Hugin). This temporal clone is another variable object. It is
         *      automatically created for each dynamic variable. It can be queried by the method "getInterfaceVariable" of the
         *      DynamicVariable class.
         *
         * 2. DynamicVariables is the class for doing that. It takes a list of Attributes and internally creates
         * all the variables. We create the variables using DynamicVariables class to guarantee that each variable
         * has a different ID number and make it transparent for the user.
         *
         * 3. We can extract the Variable objects by using the method getVariableByName();
         *
         * 4. The created variables are dynamic. Here in AMIDST toolbox, it implies they have a temporal clone (similarly to Hugin).
         * This temporal clone is automatically created for each dynamic variable.
         */
        DynamicVariables dynamicVariables = new DynamicVariables(data.getAttributes());

        Variable defaulter = dynamicVariables.getVariableByName("DEFAULTER");
        Variable sex = dynamicVariables.getVariableByName("SEX");
        Variable creditCard = dynamicVariables.getVariableByName("CREDITCARD");
        Variable balance = dynamicVariables.getVariableByName("BALANCE");
        Variable withDraw = dynamicVariables.getVariableByName("WITHDRAW");
        Variable salary = dynamicVariables.getVariableByName("SALARY");
        Variable monthlyBalance = dynamicVariables.getVariableByName("MONTHLYBALANCE");
        Variable movements = dynamicVariables.getVariableByName("MOVEMENTS");

        /**
         * We can create indicator variables. For doing that, we just simply call the method "addIndicatorDynamicVariable"
         * of DynamicVariables object.
         */
        //Variable indicatorSalary = dynamicVariables.addIndicatorDynamicVariable(salary);

        /**
         * 1. Once we have defined your DynamicVariables object, including the indicator variable,
         * the next step is to create a dynamic DAG structure over this set of variables.
         *
         * 2. To create a dynamic DAG, we just define the transition graph.
         *
         * 4. To add parents to each dynamic variable, we first recover the ParentSet object by the method
         * getParentSetTimeT(Variable var) and then call the method addParent(Variable var).
         *
         * 4. We can define temporal dependencies by referring to the temporal clones of the variables.
         *
         */
        DynamicDAG dynamicDAG = new DynamicDAG(dynamicVariables);

        dynamicDAG.setName("CajarMarModel");

        dynamicDAG.getParentSetTimeT(defaulter).addParent(dynamicVariables.getInterfaceVariable(defaulter));

        dynamicDAG.getParentSetTimeT(sex).addParent(defaulter);

        dynamicDAG.getParentSetTimeT(creditCard).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(creditCard).addParent(dynamicVariables.getInterfaceVariable(creditCard));

        dynamicDAG.getParentSetTimeT(balance).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(balance).addParent(dynamicVariables.getInterfaceVariable(balance));

        dynamicDAG.getParentSetTimeT(withDraw).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(withDraw).addParent(dynamicVariables.getInterfaceVariable(withDraw));

        dynamicDAG.getParentSetTimeT(salary).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(salary).addParent(dynamicVariables.getInterfaceVariable(salary));
        //dynamicDAG.getParentSetTimeT(salary).addParent(indicatorSalary);

        dynamicDAG.getParentSetTimeT(monthlyBalance).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(monthlyBalance).addParent(dynamicVariables.getInterfaceVariable(balance));
        dynamicDAG.getParentSetTimeT(monthlyBalance).addParent(dynamicVariables.getInterfaceVariable(monthlyBalance));

        dynamicDAG.getParentSetTimeT(movements).addParent(defaulter);
        dynamicDAG.getParentSetTimeT(movements).addParent(creditCard);

        /**
         * 1. We print the graph to see if it is properly created.
         *
         * 2. The printed graph is structured in two layers. We first display the graph structure for time 0 (no
         * temporal dependencies) and, the, we time t (with temporal dependencies).
         */
        System.out.println(dynamicDAG.toString());

        /**
         * 1. We now create the Bayesian network from the previous DAG.
         *
         * 2. The BN object is created from the DAG. It automatically looks at the distribution type
         * of each variable and their parents to initialize the Distributions objects that are stored
         * inside (i.e. Multinomial, Normal, CLG, etc). The parameters defining these distributions are
         * properly initialized.
         *
         * 3. The network is printed and we can have look at the kind of distributions stored in the BN object. Similarly
         * to dynamic DAG, it is printed in two layers. The model for time 0 and the model from time t.
         */

        DynamicBayesianNetwork dynamicBayesianNetwork = new DynamicBayesianNetwork(dynamicDAG);
        System.out.println(dynamicBayesianNetwork.toString());

        /**
         * 1. Now each DataInstance object is composed by two samples (x_{t},x_{t-1}). For the time 0, the data instance
         * object is just (x_0).
         *
         * 2. We compute the following log probs:
         *      - if t=0, we compute log p(x_0)
         *      - it t>0, we comptue log (x_t|x_{t-1)}
         *
         * 3. We accumulate these log-probs and obtain the log-probability that this dynamic model assigns to the provided
         * data sequence. .
         */
        double logProb = 0;

        for (DynamicDataInstance dataInstance: data){
            if (dataInstance.getTimeID()==0) {
                logProb += dynamicBayesianNetwork.getLogProbabiltyOfFullAssignmentTime0(dataInstance);
            }else{
                logProb += dynamicBayesianNetwork.getLogProbabiltyOfFullAssignmentTimeT(dataInstance);
            }
        }
        System.out.println(logProb);

        DynamicBayesianNetworkWriter.save(dynamicBayesianNetwork, "networks/simulated/HuginCajaMarDefaulterPredictor.dbn");

    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        CajaMarModels.cajaMarDefaulterPredictor();
    }
}


text:
eventCaptureControllers.controller('NotesController',
    function($scope,
            $modalInstance,
            dhis2Event){

    $scope.dhis2Event = dhis2Event;

    $scope.close = function () {
        $modalInstance.close();
    };
});

redpajama_set_name: RedPajamaGithub


text:
// The MIT License(MIT)
//
// Copyright (c) 2017 Sergey Odinokov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

namespace Cronos
{
    internal sealed class CronField
    {
        private static readonly string[] MonthNames =
        {
            null, "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
        };

        private static readonly string[] DayOfWeekNames =
        {
            "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"
        };

        private static readonly int[] MonthNamesArray = new int[MonthNames.Length];
        private static readonly int[] DayOfWeekNamesArray = new int[DayOfWeekNames.Length];

        // 0 and 7 are both Sunday, for compatibility reasons.
        public static readonly CronField DaysOfWeek = new CronField("Days of week", 0, 7, DayOfWeekNamesArray, false);

        public static readonly CronField Months = new CronField("Months", 1, 12, MonthNamesArray, false);
        public static readonly CronField DaysOfMonth = new CronField("Days of month", 1, 31, null, false);
        public static readonly CronField Hours = new CronField("Hours", 0, 23, null, true);
        public static readonly CronField Minutes = new CronField("Minutes", 0, 59, null, true);
        public static readonly CronField Seconds = new CronField("Seconds", 0, 59, null, true);

        static CronField()
        {
            for (var i = 1; i < MonthNames.Length; i++)
            {
                var name = MonthNames[i].ToUpperInvariant();
                var array = new char[3];
                array[0] = name[0];
                array[1] = name[1];
                array[2] = name[2];

                var combined = name[0] | (name[1] << 8) | (name[2] << 16);

                MonthNamesArray[i] = combined;
            }

            for (var i = 0; i < DayOfWeekNames.Length; i++)
            {
                var name = DayOfWeekNames[i].ToUpperInvariant();
                var array = new char[3];
                array[0] = name[0];
                array[1] = name[1];
                array[2] = name[2];

                var combined = name[0] | (name[1] << 8) | (name[2] << 16);

                DayOfWeekNamesArray[i] = combined;
            }
        }

        public readonly string Name;
        public readonly int First;
        public readonly int Last;
        public readonly int[] Names;
        public readonly bool CanDefineInterval;
        public readonly long AllBits;

        private CronField(string name, int first, int last, int[] names, bool canDefineInterval)
        {
            Name = name;
            First = first;
            Last = last;
            Names = names;
            CanDefineInterval = canDefineInterval;
            for (int i = First; i <= Last; i++)
            {
                AllBits |= (1L << i);
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}


text:
<atlassian-plugin key="${project.groupId}.${project.artifactId}" name="${project.artifactId}" plugins-version="2">
    <plugin-info>
        <description>${project.description}</description>
        <version>${project.version}</version>
        <vendor name="${project.organization.name}" url="${project.organization.url}" />
    </plugin-info>

    <servlet name="ssocookie" class="net.nordu.crowd.sso.SSOCookieServlet" key="ssocookie">
        <url-pattern>/ssocookie</url-pattern>
    </servlet>

    <servlet name="claimaccount" class="net.nordu.crowd.sso.ClaimAccountServlet" key="claimaccount">
        <url-pattern>/claimAccount</url-pattern>
        <resource type="download" name="style.css" location="skin/style.css">
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/NORDUnet2.jpg" location="skin/images/NORDUnet2.jpg">
            <param name="content-type" value="image/jpeg"/>
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/pipes_back.jpg" location="skin/images/pipes_back.jpg">
            <param name="content-type" value="image/jpeg"/>
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/top_back.gif" location="skin/images/top_back.gif">
            <param name="content-type" value="image/gif"/>
            <param name="batch" value="false"/>
        </resource>
    </servlet>

    <web-resource key="servletSkin" name="Servlet Skin" >
        <resource type="download" name="style.css" location="skin/style.css">
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/NORDUnet2.jpg" location="skin/images/NORDUnet2.jpg">
            <param name="content-type" value="image/jpeg"/>
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/pipes_back.jpg" location="skin/images/pipes_back.jpg">
            <param name="content-type" value="image/jpeg"/>
            <param name="batch" value="false"/>
        </resource>
        <resource type="download" name="images/top_back.gif" location="skin/images/top_back.gif">
            <param name="content-type" value="image/gif"/>
            <param name="batch" value="false"/>
        </resource>
    </web-resource>

</atlassian-plugin>


text:
package com.jeecms.common.web.freemarker;

import freemarker.template.TemplateModelException;

/**
 * 缺少必须参数异常
 */
@SuppressWarnings("serial")
public class ParamsRequiredException extends TemplateModelException {
	public ParamsRequiredException(String paramName) {
		super("The required \"" + paramName + "\" paramter is missing.");
	}
}


text:
<?php

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

class CriarPublicacoes extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('publicacoes', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('autor_id')->unsigned();
            $table->foreign('autor_id')->references('id')->on('usuarios');
            $table->dateTime('data_publicacao');
            $table->string('titulo',200);
            $table->longText('conteudo');
            $table->binary('imagem');
            $table->timestamps();
        });
    }

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


text:
CREATE DATABASE  IF NOT EXISTS `school` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `school`;
-- MySQL dump 10.13  Distrib 5.7.17, for Win64 (x86_64)
--
-- Host: localhost    Database: school
-- ------------------------------------------------------
-- Server version	5.7.15-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `addresses`
--

DROP TABLE IF EXISTS `addresses`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addresses` (
  `id` int(11) NOT NULL,
  `country` varchar(45) NOT NULL,
  `city` varchar(45) NOT NULL,
  `street` varchar(45) NOT NULL,
  `number` varchar(45) NOT NULL,
  `floor` int(11) NOT NULL,
  `apartment_no` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `addresses`
--

LOCK TABLES `addresses` WRITE;
/*!40000 ALTER TABLE `addresses` DISABLE KEYS */;
/*!40000 ALTER TABLE `addresses` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `disciplines`
--

DROP TABLE IF EXISTS `disciplines`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `disciplines` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `disciplines`
--

LOCK TABLES `disciplines` WRITE;
/*!40000 ALTER TABLE `disciplines` DISABLE KEYS */;
INSERT INTO `disciplines` VALUES (1,'Mathematics'),(2,'Geography'),(3,'Physics'),(4,'Informatics');
/*!40000 ALTER TABLE `disciplines` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `disciplines_studied`
--

DROP TABLE IF EXISTS `disciplines_studied`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `disciplines_studied` (
  `discipline_id` int(11) NOT NULL,
  `student_id` int(11) NOT NULL,
  KEY `fk_discipline_studied_idx` (`student_id`),
  KEY `fk_disciplines_study_idx` (`discipline_id`),
  CONSTRAINT `fk_disciplines` FOREIGN KEY (`discipline_id`) REFERENCES `disciplines` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_student` FOREIGN KEY (`student_id`) REFERENCES `students` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `disciplines_studied`
--

LOCK TABLES `disciplines_studied` WRITE;
/*!40000 ALTER TABLE `disciplines_studied` DISABLE KEYS */;
/*!40000 ALTER TABLE `disciplines_studied` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `disciplines_taught`
--

DROP TABLE IF EXISTS `disciplines_taught`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `disciplines_taught` (
  `id_teachers` int(11) NOT NULL,
  `id_discipline` int(11) NOT NULL,
  KEY `key_discipl_idx` (`id_discipline`),
  KEY `id_teachers_idx` (`id_teachers`),
  CONSTRAINT `id_disciplines` FOREIGN KEY (`id_discipline`) REFERENCES `disciplines` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `id_teachers` FOREIGN KEY (`id_teachers`) REFERENCES `teachers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `disciplines_taught`
--

LOCK TABLES `disciplines_taught` WRITE;
/*!40000 ALTER TABLE `disciplines_taught` DISABLE KEYS */;
INSERT INTO `disciplines_taught` VALUES (2,2);
/*!40000 ALTER TABLE `disciplines_taught` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `students`
--

DROP TABLE IF EXISTS `students`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `enrollment_date` varchar(45) NOT NULL,
  `address_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `students_fk_idx` (`address_id`),
  CONSTRAINT `address_id` FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `students`
--

LOCK TABLES `students` WRITE;
/*!40000 ALTER TABLE `students` DISABLE KEYS */;
INSERT INTO `students` VALUES (1,'Georgi Georgiev','22-10-2000',NULL),(2,'Stoyan Ivanov','18-11-2010',NULL),(3,'Mariya Grozdanova','27-05-2008',NULL),(4,'Stefaniya Petkova','12-01-2007',NULL);
/*!40000 ALTER TABLE `students` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `teachers`
--

DROP TABLE IF EXISTS `teachers`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teachers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `email` varchar(45) DEFAULT NULL,
  `salary` decimal(10,0) NOT NULL,
  `address_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_addreses_idx` (`address_id`),
  CONSTRAINT `address_ids` FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `teachers`
--

LOCK TABLES `teachers` WRITE;
/*!40000 ALTER TABLE `teachers` DISABLE KEYS */;
INSERT INTO `teachers` VALUES (1,'Peter Ivanov','pivanov@gmail.com',1922,NULL),(2,'Georgi Stoimenov','stoimenov@gmail.com',1787,NULL),(3,'Nataliya Yordanova','nyyoo@abv.bg',1888,NULL),(4,'Simeon Prodanov','sprod@yahoo.com',1342,NULL);
/*!40000 ALTER TABLE `teachers` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2017-05-31 13:52:15


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const jp = require("jsonpath");
const primitives_1 = require("../std/primitives");
require("reflect-metadata");
const Implementation = JSON;
//
// ─── FILE - IO ───────────────────────────────────────────────────────────────────────
//
function read(file) {
    const size = fs.statSync(file).size, buf = new Buffer(size), fd = fs.openSync(file, 'r');
    if (!size) {
        return '';
    }
    fs.readSync(fd, buf, 0, size, 0);
    fs.closeSync(fd);
    return buf.toString();
}
exports.read = read;
//
// ─── Standard decoder ───────────────────────────────────────────────────────────────────────
//
exports.to = (data, path) => {
    let value = path ? jp.query(data, path)[0] : data;
    let changed = false;
    try {
        if (primitives_1.isString(value)) {
            value = JSON.parse(value);
            changed = true;
        }
    }
    catch (e) {
        console.error('error decoding json', e);
    }
    changed && path && jp.value(data, path, value);
    return data;
};
//
// ─── API abbreviation ───────────────────────────────────────────────────────────────────────
//
exports.serialize = (value, replacer, space) => {
    return Implementation.stringify(value, replacer, space);
};
exports.deserialize = (value) => {
    return Implementation.parse(value);
};
//
// ─── UTILS ──────────────────────────────────────────────────────────────────────
//
/**
 * Calls JSON.Stringify with a replacer to break apart any circular references.
 * This prevents JSON.stringify from throwing the exception
 *  "Uncaught TypeError: Converting circular structure to JSON"
 */
exports.safe = (obj) => {
    let seen = [];
    return exports.serialize(obj, (key, value) => {
        if (primitives_1.isObject(value) || primitives_1.isArray(value)) {
            if (seen.indexOf(value) !== -1) {
                return '[Circular]';
            }
            else {
                seen.push(value);
            }
        }
        return value;
    });
};
//
// ─── JSON-MAPPING ────────────────────────────────────────────────────────────────
//
const jsonMetadataKey = 'jsonProperty';
/**
 * Decorator to map/support dashed property names
 *
 * @export
 * @template T
 * @param {(IJsonMetaData<T> | string)} [metadata]
 * @returns {*}
 */
function JsonProperty(metadata) {
    if (metadata instanceof String || typeof metadata === 'string') {
        return Reflect.metadata(jsonMetadataKey, {
            name: metadata,
            clazz: undefined
        });
    }
    else {
        const metadataObj = metadata;
        return Reflect.metadata(jsonMetadataKey, {
            name: metadataObj ? metadataObj.name : undefined,
            clazz: metadataObj ? metadataObj.clazz : undefined
        });
    }
}
exports.JsonProperty = JsonProperty;
function getClazz(target, propertyKey) {
    return Reflect.getMetadata('design:type', target, propertyKey);
}
exports.getClazz = getClazz;
function getJsonProperty(target, propertyKey) {
    return Reflect.getMetadata(jsonMetadataKey, target, propertyKey);
}
exports.getJsonProperty = getJsonProperty;
/**
* @example
// Example - JSON-Mapping
class Address {
    @JsonProperty('first-line')
    firstLine: string;
    @JsonProperty('second-line')
    secondLine: string;
    city: string;

    // Default constructor will be called by mapper
    constructor() {
        this.firstLine = undefined;
        this.secondLine = undefined;
        this.city = undefined;
    }
}

class Person {
    name: string;
    surname: string;
    age: number;
    @JsonProperty('address')
    address: Address;

    // Default constructor will be called by mapper
    constructor() {Array.
        this.name = undefined;
        this.surname = undefined;
        this.age = undefined;
        this.address = undefined;
    }
}
let example = {
    "name": "Mark",
    "surname": "Galea",
    "age": 30,
    "address": {
        "first-line": "Some where",
        "second-line": "Over Here",
        "city": "In This City"
    }
};
const Person2 = Map.deserialize(Person, example);
*/
class Map {
    static isPrimitive(obj) {
        switch (typeof obj) {
            case 'string':
            case 'number':
            case 'boolean':
                return true;
        }
        return !!(obj instanceof String || obj === String ||
            obj instanceof Number || obj === Number ||
            obj instanceof Boolean || obj === Boolean);
    }
    static isArray(object) {
        if (object === Array) {
            return true;
        }
        else if (typeof Array.isArray === 'function') {
            return Array.isArray(object);
        }
        else {
            return !!(object instanceof Array);
        }
    }
    static deserialize(clazz, jsonObject) {
        if ((clazz === undefined) || (jsonObject === undefined)) {
            return undefined;
        }
        const obj = new clazz();
        Object.keys(obj).forEach((key) => {
            const propertyMetadataFn = (propertyMetadata) => {
                let propertyName = propertyMetadata.name || key;
                let innerJson = jsonObject ? jsonObject[propertyName] : undefined;
                let clazz = getClazz(obj, key);
                if (Map.isArray(clazz)) {
                    let metadata = getJsonProperty(obj, key);
                    if (metadata.clazz || Map.isPrimitive(clazz)) {
                        if (innerJson && Map.isArray(innerJson)) {
                            return innerJson.map((item) => Map.deserialize(metadata.clazz, item));
                        }
                        else {
                            return undefined;
                        }
                    }
                    else {
                        return innerJson;
                    }
                }
                else if (!Map.isPrimitive(clazz)) {
                    return Map.deserialize(clazz, innerJson);
                }
                else {
                    return jsonObject ? jsonObject[propertyName] : undefined;
                }
            };
            const propertyMetadata = getJsonProperty(obj, key);
            if (propertyMetadata) {
                obj[key] = propertyMetadataFn(propertyMetadata);
            }
            else {
                if (jsonObject && jsonObject[key] !== undefined) {
                    obj[key] = jsonObject[key];
                }
            }
        });
        return obj;
    }
}
exports.Map = Map;
//# sourceMappingURL=json.js.map


text:
import os

def env(*vars, **kwargs):
    """Search for the first defined of possibly many env vars

    Returns the first environment variable defined in vars, or
    returns the default defined in kwargs.
    """
    for v in vars:
        value = os.environ.get(v, None)
        if value:
            return value
    return kwargs.get('default', '')


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;

public class BitManipulator
{
    Int32 mask;
    Int32 shift;

    public BitManipulator(Int32 mask, Int32 shift)
    {
        this.mask = mask;
        this.shift = shift;
    }

    public Int32 GetBitsValue(Int32 input)
    {
        return (input & this.mask) >> this.shift;
    }

    public void SetBits(ref Int32 value, Int32 bitsValue)
    {
        Int32 iT = bitsValue << this.shift;
        iT = iT & this.mask;
        value = value | iT;
    }
}


text:
<?php

/**
 * This class defines the structure of the 'item' table.
 *
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    propel.generator..map
 */
class ItemTableMap extends TableMap
{

	/**
	 * The (dot-path) name of this class
	 */
	const CLASS_NAME = '.map.ItemTableMap';

	/**
	 * Initialize the table attributes, columns and validators
	 * Relations are not initialized by this method since they are lazy loaded
	 *
	 * @return     void
	 * @throws     PropelException
	 */
	public function initialize()
	{
		// attributes
		$this->setName('item');
		$this->setPhpName('Item');
		$this->setClassname('Item');
		$this->setPackage('');
		$this->setUseIdGenerator(true);
		// columns
		$this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null);
		$this->addForeignKey('ISBN', 'Isbn', 'VARCHAR', 'book', 'ISBN', false, 13, null);
		$this->addForeignKey('PACKAGE_ID', 'PackageId', 'INTEGER', 'item', 'ID', false, null, null);
		$this->addColumn('IS_PACKAGE', 'IsPackage', 'BOOLEAN', false, 1, false);
		$this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null);
		$this->addColumn('AUTHOR', 'Author', 'VARCHAR', false, 255, null);
		$this->addColumn('EDITION', 'Edition', 'VARCHAR', false, 255, null);
		$this->addColumn('PUBLISHER', 'Publisher', 'VARCHAR', false, 255, null);
		$this->addColumn('B_NEW', 'BNew', 'DECIMAL', false, 6, null);
		$this->addColumn('B_USED', 'BUsed', 'DECIMAL', false, 6, null);
		$this->addColumn('B_EBOOK', 'BEbook', 'DECIMAL', false, 6, null);
		$this->addColumn('IMAGE_URL', 'ImageUrl', 'VARCHAR', false, 255, null);
		$this->addColumn('PRODUCT_ID', 'ProductId', 'VARCHAR', false, 255, null);
		$this->addColumn('PART_NUMBER', 'PartNumber', 'VARCHAR', false, 255, null);
		$this->addColumn('SPIDERED_AT', 'SpideredAt', 'TIMESTAMP', false, null, null);
		$this->addColumn('SHALLOW_SPIDERED_AT', 'ShallowSpideredAt', 'TIMESTAMP', false, null, null);
		$this->addColumn('TOUCHED', 'Touched', 'BOOLEAN', false, 1, null);
		$this->addColumn('B_ID', 'BId', 'VARCHAR', false, 255, null);
		$this->addColumn('BOOKSTORE_TYPE', 'BookstoreType', 'VARCHAR', false, 32, null);
		$this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null);
		$this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null);
		// validators
	} // initialize()

	/**
	 * Build the RelationMap objects for this table relationships
	 */
	public function buildRelations()
	{
		$this->addRelation('Book', 'Book', RelationMap::MANY_TO_ONE, array('isbn' => 'isbn', ), 'SET NULL', null);
		$this->addRelation('ItemRelatedByPackageId', 'Item', RelationMap::MANY_TO_ONE, array('package_id' => 'id', ), 'CASCADE', null);
		$this->addRelation('ItemRelatedById', 'Item', RelationMap::ONE_TO_MANY, array('id' => 'package_id', ), 'CASCADE', null, 'ItemsRelatedById');
		$this->addRelation('SectionHasItem', 'SectionHasItem', RelationMap::ONE_TO_MANY, array('id' => 'item_id', ), 'CASCADE', null, 'SectionHasItems');
		$this->addRelation('Section', 'Section', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Sections');
	} // buildRelations()

	/**
	 *
	 * Gets the list of behaviors registered for this table
	 *
	 * @return array Associative array (name => parameters) of behaviors
	 */
	public function getBehaviors()
	{
		return array(
			'spiderable' => array('parent' => '', 'bookstore_type_column' => 'bookstore_type', 'spidered_column' => 'spidered_at', 'shallow_spidered_column' => 'shallow_spidered_at', 'touched_column' => 'touched', 'id_column' => 'b_id', 'id_size' => '255', ),
			'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ),
			'custom_db' => array('original_name' => 'gbpropel', 'db_name_constant' => 'GB_DATABASE', ),
		);
	} // getBehaviors()

} // ItemTableMap


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))

describe DataMapper::Associations::ManyToMany do

  load_models_for_metaphor :vehicles, :content

  it 'should allow a declaration' do
    lambda do
      class ::Supplier
        has n, :manufacturers, :through => Resource
      end
    end.should_not raise_error
  end

  it 'should handle models inside modules' do
    lambda do
      module ::Content
        class Dialect
          has n, :locales, :through => Resource, :class_name => "Language::Locale"
        end

        class Locale
          has n, :dialects, :through => Resource, :class_name => "Language::Dialect"
        end
      end
    end.should_not raise_error
  end

end

describe DataMapper::Associations::ManyToMany::Proxy do
end


text:
import React, { Component } from 'react';

import './App.css';

class TabContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedTab: 0,
      displayMessage: ''
    };
  }

  update = (id, tabInfo) => {
    if (this.state.selectedTab === id) {
      this.setState({
        selectedTab: 0,
        displayMessage: ''
      });
    } else {
      this.setState({
        selectedTab: id,
        displayMessage: tabInfo[id - 1]
      });
    }
  };

  render() {
    const tabInfo = [
      'Abraham Lincoln was an American politician and lawyer who served as the 16th President of the United States from March 1861 until his assassination in April 1865.',
      'Franklin Delano Roosevelt, commonly known as FDR, was an American statesman and political leader who served as the 32nd President of the United States from 1933 until his death in 1945.',
      'Barack Hussein Obama II is an American politician who served as the 44th President of the United States from 2009 to 2017. He is the first African American to have served as president.'
    ];
    return (

          <Tab
            name="Tab 1"
            selectedTab={this.state}
            onSelect={() => this.update(1, tabInfo)}
          />
          <Tab
            name="Tab 2"
            selectedTab={this.state}
            onSelect={() => this.update(2, tabInfo)}
          />
          <Tab
            name="Tab 3"
            selectedTab={this.state}
            onSelect={() => this.update(3, tabInfo)}
          />

        <TabContent message={this.state.displayMessage} />

    );
  }
}

class Tab extends Component {
  render() {
    return (

        {this.props.name}

    );
  }
}

class TabContent extends Component {
  render() {
    return (

        {this.props.message}

    );
  }
}

export default TabContainer;


text:
@interface GameViewController : UIViewController <UITextFieldDelegate, GPGLeaderboardControllerDelegate>

@property (nonatomic) TNDifficultyLevel difficulty;
@property (nonatomic, copy) NSDictionary *incomingChallenge;
@end


text:
const keyMirror = require('keymirror');

module.exports = keyMirror({
    USER_AUTH_SUCCEED: null,
    USER_LOGOUT_SUCCEED: null
});


text: Minimal Datepicker


text:
- `utils.py` - module of utility functions
- `label.py` - adds miRNA labelling: intragenic/intergenic/unknown/NA based on an annotation file
- `plots.py` - generate plots based on miRNA labelling

## Creating the training set
1. `tc_normalization.py` - performs rle normalization on tag counts (used for creating the negative training set)
2. `create-training-set.py` - using script 1, creates the positive and negative training set

```
## You need to first update "config.ini" and "tcnorm.ini"

python2.7 create-training-set.py -f '/path/to/*.gff' -o ../Testout-tset -c config.ini
```
**Note:** `-f` globs all sample.gff files from which to pick the positive training set; you will need quotations around `*`; and an example of the input format is found [here](../test/test.gff).

## Training the model
1. `training.py` - performs training to get model parameters

```
## You need to first update "config.ini"

python2.7 training.py -i ../Test-tset/TrainingSet.gff -c config.ini
```
**Note:** See below if you want to enable training with the correlation feature

## Using the model
1. `features.py` - performs sequence feature extraction of CpG content, conservation, and TATA box affinity
2. `mirna_proximity.py` - performs miRNA proximity feature extraction (requires the use of miRBase files)
3. `correlation.py` - **new feature**; performs correlation feature extraction
                      (requires 'srnaseqmatrix' and 'cageseqmatrix', in the config file, to be filled;
                       see instructions below for enabling this feature)
4. `gff_unify_features.py` - performs `bedtools intersect ... -s -f 1 -r -wao`
5. `promirna.py` - module of core mathematical formulas from PROmiRNA
6. `promi2.py` - runs scripts 1-5 of "using the model"

```
## You need to first update "config.ini"

python2.7 promi2.py -i ../test/test.gff -o ../Testout-promi2 -c config.ini
```
**Note:** `-p` enables plotting of results with `plot.py` (plotting dependencies need to first be installed)

- **About: the gff input file**
 - This is the file containing the putative TSSs you want to classify
 - The format consists of 9 tab-delimited columns:
  - 1. chromosome
  - 2. source (field is not used)
  - 3. feature (field is not used)
  - 4. start of 1kb region around TSS (-500 of mid putative TSS)
  - 5. stop of 1kb region around TSS (+500 of mid putative TSS)
  - 6. normalized tag counts
  - 7. strand
  - 8. '.' (field is not used)
  - 9. 'start:<start>;stop:<stop>' of putative TSS
 - An example of the format is shown [here](../test/test.gff)

- **About: the config.ini file**
 - You will need to update the paths in the [config](config.ini) file

**Tip:** When you already have the extracted-features.gff file ([example](../test/test-features.gff)), you can run PROmiRNA directly with `-f`.
```
python2.7 promi2.py -i ../test/test-features.gff -f -o ../Testout-promi2predict
```
_(Note: In the config file, you will still need to fill in `params =` and `features =`)_

## Summarizing results
1. `summarize-results.py` - summarize promi2 predictions from a series of samples

```
python2.7 summarize-results.py -f '../test/test-summary/Predictions.*' -o ../Testout-summary.gff -s
```
**Note:** `-s` is to print only results where mirna_prox score is > 0

* * *
## Using the model2: custom
- `custom.py` - given a gff input file ([example](../test/test-custom.gff)) containing a list of positions (and possibly miRNA partners in column 9), performs feature extraction, calculation of probabilities, labelling of positions, and plotting of results

```
## You need to first update "config.ini" as well as "tcnorm.ini"
python2.7 custom.py -i ../test/test-custom.gff -o ../Testout-custom -p
```
**Note:** `-p` enables plotting of results with `plot.py` (plotting dependencies need to first be installed)

**Note:** `-m` designate that the infile has miRNA partners in column 9
(and that miRNA partners do not been to be found)

* * *
One main difference between `promi2.py` and `custom.py` is that `promi2.py` assumes you start with normalized CAGE tag counts in a matrix, whereas `custom.py` pulls the tag counts from raw data and normalizes them.

* * *
# Enabling Correlation
## Using correlation feature with promi2/custom
1. At the "**Creating the training set**" step, you will need to create a dataset which contains the extracted correlation
 - Make sure `srnaseqmatrix =` and `cageseqmatrix =`, in the [config](config.ini) file, is filled in
2. At the "**Training the model**" step, you will neet to tell the program to include correlation as a feature
 - In `trainingfeatures =`, change `cpg,cons,tata,mirna_prox` to `cpg,cons,tata,mirna_prox,corr`
 - Also make sure to train with training set with the extracted correlations
   (e.g. "TrainingSet-corr.gff" -- not "TrainingSet.gff")
3. At the "**Using the model**" step, you will need to tell promi2 (or custom) to use the corrlelation feature as well as the new parameters
 - Update `params =` to the resulting `*finalparams` file generated in the previous step
 - In `features =`, change `cpg,cons,tata,mirna_prox` to `cpg,cons,tata,mirna_prox,corr`
 - **Note:** promi2 also expects `cageseqmatrix =` to be filled out


text:
layout: post
microblog: true
audio:
photo:
date: 2017-08-31 07:47:52 -0700
guid: http://curt.micro.blog/2017/08/31/beautiful-poignant-convicting.html
---
Beautiful, poignant, convicting. [99% Invisible: 273- Notes on an Imagined Plaque](https://overcast.fm/+DAQdzvUhttps://overcast.fm/+DAQdzvU)


text:
class GITRepo
  def initialize(topdir)
    @topdir = topdir
  end

  def parse_git_blame_porcelain(command)
    out, status = Open3.capture2(*command)
    out.force_encoding('locale').scrub!
    if !status.success?
      raise "git blame failed: #{command.join(" ")}"
    end

    header_hash = {}
    prev_header = {}
    block = []
    out.each_line {|line|
      line.force_encoding('locale').scrub!
      if /\A\t/ !~ line
        block << line
      else
        content_line = line.sub(/\A\t/, '')
        rev, original_file_line_number, final_file_line_number, numlines = block.shift.split(/\s+/)
        if !header_hash[rev]
          header = {}
          block.each {|header_line|
            if / / =~ header_line.chomp
              header[$`] = $'
            end
          }
          header_hash[rev] = header
        end
        header = header_hash[rev]
        yield rev, original_file_line_number, final_file_line_number, numlines, header, content_line
        block = []
      end
    }
  end

  def git_blame_forward_each(topdir, relpath, rev, &b)
    command = ['git', "--git-dir=#{topdir}/.git", "--work-tree=#{topdir}", 'blame', '--porcelain', rev, '--', relpath]
    parse_git_blame_porcelain(command, &b)
  end

  def git_blame_reverse_each(topdir, relpath, rev, &b)
    command = ['git', "--git-dir=#{topdir}/.git", "--work-tree=#{topdir}", 'blame', '--porcelain', '--reverse', rev, '--', relpath]
    parse_git_blame_porcelain(command, &b)
  end

  def format_file(list)
    rev = list[0]
    relpath = list[1..-1].join('/')

    result = '
'

    forward_data = []
    forward_author_name_width = 0
    git_blame_forward_each(@topdir.to_s, relpath, rev) {|rev, original_file_line_number, final_file_line_number, numlines, header, content_line|
      author_time = Time.at(header['author-time'].to_i).strftime("%Y-%m-%d")
      author_name = header['author'] || 'no author'
      content_line = content_line.chomp.expand_tab
      forward_author_name_width = author_name.length if forward_author_name_width < author_name.length
      forward_data << [rev, author_time, author_name, content_line, header['filename'], original_file_line_number]
    }

    reverse_data = []
    git_blame_reverse_each(@topdir.to_s, relpath, rev) {|rev, original_file_line_number, final_file_line_number, numlines, header, content_line|
      author_time = Time.at(header['author-time'].to_i).strftime("%Y-%m-%d")
      author_name = header['author']
      content_line = content_line.chomp.expand_tab
      reverse_data << [rev, author_time, author_name, content_line, header['filename'], original_file_line_number]
    }

    if forward_data.length != reverse_data.length
      raise "different length with forward and reverse blame: forward=#{forward_data.length} != reverse=#{reverse_data.length}"
    end

    f_prev_rev = nil
    r_prev_rev = nil
    0.upto(forward_data.length-1) {|ln|
      f_rev, f_author_time, f_author_name, f_content_line, f_filename, f_original_file_line_number = forward_data[ln]
      r_rev, r_author_time, r_author_name, r_content_line, r_filename, r_original_file_line_number = reverse_data[ln]

      ln += 1
      result << %{}

      f_formatted_author_time = f_prev_rev == f_rev ? ' ' * 10 : f_author_time
      f_formatted_author_name = "%-#{forward_author_name_width}s" % f_author_name
      f_commit_url = "/diff-parents/#{f_rev}\##{u(f_rev+"/"+f_filename.to_s+":"+f_original_file_line_number.to_s)}"

      r_formatted_author_time = r_prev_rev == r_rev ? ' ' * 10 : r_author_time
      r_commit_url = "/diff-children/#{r_rev}\##{u(r_rev+"/"+r_filename.to_s+":"+r_original_file_line_number.to_s)}"

      f_prev_rev = f_rev
      r_prev_rev = r_rev

      result << %{#{h f_formatted_author_time} }
      result << %{#{h r_formatted_author_time} }
      result << %{#{h f_formatted_author_name} }
      result << %{#{h f_content_line}\n}
    }

    result << '
'

    result
  end

  def format_commit(list)
    target_rev = list[0]
    log_out, log_status = Open3.capture2({'LC_ALL'=>'C'},
	'git', "--git-dir=#{@topdir.to_s}/.git", "--work-tree=#{@topdir.to_s}", 'log', '--name-status', '--date=iso', '-1', '--parents', target_rev)
    log_out.force_encoding('locale').scrub!
    if !log_status.success?
      raise "git log failed."
    end

    if /^commit ([0-9a-f]+)(.*)\n/ !~ log_out
      raise "git log doesn't produce 'commit' line."
    end
    commit_rev = $1
    parent_revs = $2.strip.split(/\s+/)

    result = '
'
    log_out.each_line {|line|
      result << "#{h line.chomp}\n"
    }
    result << '
'

    if parent_revs.empty?
      result << "no diffs since no parents: #{target_rev}"
    else
      parent_revs.each {|parent_rev|
        result << format_diff(parent_rev, commit_rev)
      }
    end

    result
  end

  def format_diff_children(list)
    target_rev = list[0]

    log_out, log_status = Open3.capture2({'LC_ALL'=>'C'},
	'git', "--git-dir=#{@topdir.to_s}/.git", "--work-tree=#{@topdir.to_s}", 'log', '--pretty=format:%H %P')
    log_out.force_encoding('locale').scrub!
    if !log_status.success?
      raise "git log failed."
    end

    children = {}
    log_out.each_line {|line|
      rev, *parent_revs = line.strip.split(/\s+/)
      parent_revs.each {|parent_rev|
        children[parent_rev] ||= []
        children[parent_rev] << rev
      }
    }

    unless children[target_rev]
      return "no diffs since no children: #{target_rev}"
    end

    result = String.new

    children[target_rev].each {|child_rev|
      log_out, log_status = Open3.capture2({'LC_ALL'=>'C'},
          'git', "--git-dir=#{@topdir.to_s}/.git", "--work-tree=#{@topdir.to_s}", 'log', '--name-status', '--date=iso', '-1', child_rev)
      log_out.force_encoding('locale').scrub!
      if !log_status.success?
        raise "git log failed."
      end

      result = '
'
      log_out.each_line {|line|
        result << "#{h line.chomp}\n"
      }
      result << '
'

      result << format_diff(target_rev, child_rev)
    }

    result
  end

  def format_diff(rev1, rev2)
    result = String.new
    diff_out, diff_status = Open3.capture2({'LC_ALL'=>'C'},
        'git', "--git-dir=#{@topdir.to_s}/.git", "--work-tree=#{@topdir.to_s}", 'diff', rev1, rev2)
    diff_out.force_encoding('locale').scrub!
    if !diff_status.success?
      raise "git diff failed."
    end
    filename1 = filename2 = '?'
    result << '
'
    scan_udiff(diff_out) {|tag, *rest|
      case tag
      when :filename1
        line, filename1 = rest
        filename1.sub!(%r{\Aa/}, '')
        result << " "
        result << (h line.chomp.expand_tab) << "\n"
      when :filename2
        line, filename2 = rest
        filename2.sub!(%r{\Ab/}, '')
        result << " "
        result << (h line.chomp.expand_tab) << "\n"
      when :hunk_header
        line, ln_cur1, ln_num1, ln_cur2, ln_num2 = rest
        result << " "
        result << (h line.chomp.expand_tab) << "\n"
      when :del
        line, content_line, ln_cur1 = rest
        content_line = content_line.chomp.expand_tab
        rev1_url = "/file/#{rev1}/#{filename1}\##{ln_cur1}"
        result << %{}
        result << %{ -}
        result << (h content_line) << "\n"
      when :add
        line, content_line, ln_cur2 = rest
        content_line = content_line.chomp.expand_tab
        rev2_url = "/file/#{rev2}/#{filename2}\##{ln_cur2}"
        result << %{}
        result << %{ +}
        result << (h content_line) << "\n"
      when :com
        line, content_line, ln_cur1, ln_cur2 = rest
        content_line = content_line.chomp.expand_tab
        rev1_url = "/file/#{rev1}/#{filename1}\##{ln_cur1}"
        rev2_url = "/file/#{rev2}/#{filename2}\##{ln_cur2}"
        result << %{}
        result << %{}
        result << %{ }
        result << %{ }
        result << (h content_line) << "\n"
      when :other
        line, = rest
        result << " "
        result << (h line.chomp.expand_tab) << "\n"
      else
        raise "unexpected udiff line tag"
      end
    }
    result << '
'
    result
  end
end


text:
exports.toSearchTitle = function(show) {
	var returnShow = show.replace(/\s/g, '.').replace(/["'()]/g, '').replace(/&/g, 'and');
	return returnShow;
};


text:
package org.camunda.bpm.integrationtest.functional.bpmnmodelapi.beans;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.FlowElement;

/**
 * @author Daniel Meyer
 *
 */
@Named
@ApplicationScoped
public class BpmnElementRetrievalDelegate implements JavaDelegate {

  private FlowElement bpmnModelElementInstance;
  private BpmnModelInstance bpmnModelInstance;

  @Override
  public void execute(DelegateExecution execution) throws Exception {

    bpmnModelElementInstance = execution.getBpmnModelElementInstance();
    bpmnModelInstance = execution.getBpmnModelInstance();

  }

  public FlowElement getBpmnModelElementInstance() {
    return bpmnModelElementInstance;
  }

  public BpmnModelInstance getBpmnModelInstance() {
    return bpmnModelInstance;
  }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Reports_fd_marketing extends Root_Controller
{
    private $message;
    public $permissions;
    public $controller_url;
    public $locations;

    public function __construct()
    {
        parent::__construct();
        $this->message="";
        $this->permissions=User_helper::get_permission('Reports_fd_marketing');
        $this->locations=User_helper::get_locations();
        if(!is_array($this->locations))
        {
            if($this->locations=='wrong')
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line('MSG_LOCATION_INVALID');
                $this->jsonReturn($ajax);
            }
            else
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line('MSG_LOCATION_NOT_ASSIGNED');
                $this->jsonReturn($ajax);
            }
        }
        $this->controller_url='reports_fd_marketing';
    }

    public function index($action="search",$id=0)
    {
        if($action=="search")
        {
            $this->system_search();
        }
        elseif($action=="list")
        {
            $this->system_list();
        }
        elseif($action=='details')
        {
            $this->system_details($id);
        }
        elseif($action=="get_items")
        {
            $this->system_get_items();
        }
        elseif($action=="get_items_area")
        {
            $this->system_get_items_from_fd_area();
        }
        else
        {
            $this->system_search();
        }
    }

    private function system_search()
    {
        if(isset($this->permissions['view'])&&($this->permissions['view']==1))
        {
            $data['title']="Field Day Report Search";
            $ajax['status']=true;
            $data['divisions']=Query_helper::get_info($this->config->item('table_setup_location_divisions'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));
            $data['zones']=array();
            $data['territories']=array();
            $data['districts']=array();
            $data['upazillas']=array();
            if($this->locations['division_id']>0)
            {
                $data['zones']=Query_helper::get_info($this->config->item('table_setup_location_zones'),array('id value','name text'),array('division_id ='.$this->locations['division_id']));
                if($this->locations['zone_id']>0)
                {
                    $data['territories']=Query_helper::get_info($this->config->item('table_setup_location_territories'),array('id value','name text'),array('zone_id ='.$this->locations['zone_id']));
                    if($this->locations['territory_id']>0)
                    {
                        $data['districts']=Query_helper::get_info($this->config->item('table_setup_location_districts'),array('id value','name text'),array('territory_id ='.$this->locations['territory_id']));
                        if($this->locations['district_id']>0)
                        {
                            $data['upazillas']=Query_helper::get_info($this->config->item('table_setup_location_upazillas'),array('id value','name text'),array('district_id ='.$this->locations['district_id'],'status ="'.$this->config->item('system_status_active').'"'));
                        }
                    }
                }
            }
            $data['crops']=Query_helper::get_info($this->config->item('table_setup_classification_crops'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));

            $fiscal_years=Query_helper::get_info($this->config->item('table_basic_setup_fiscal_year'),'*',array());
            $data['fiscal_years']=array();
            foreach($fiscal_years as $year)
            {
                $data['fiscal_years'][]=array('text'=>$year['name'],'value'=>System_helper::display_date($year['date_start']).'/'.System_helper::display_date($year['date_end']));
            }

            $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view($this->controller_url."/search",$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $ajax['system_page_url']=site_url($this->controller_url);
            $this->jsonReturn($ajax);
        }
    }

    private function check_my_editable($security)
    {
        if(($this->locations['division_id']>0)&&($this->locations['division_id']!=$security['division_id']))
        {
            return false;
        }
        if(($this->locations['zone_id']>0)&&($this->locations['zone_id']!=$security['zone_id']))
        {
            return false;
        }
        if(($this->locations['territory_id']>0)&&($this->locations['territory_id']!=$security['territory_id']))
        {
            return false;
        }
        if(($this->locations['district_id']>0)&&($this->locations['district_id']!=$security['district_id']))
        {
            return false;
        }
        if(($this->locations['upazilla_id']>0)&&($this->locations['upazilla_id']!=$security['upazilla_id']))
        {
            return false;
        }
        return true;
    }

    private function system_list()
    {
        if(isset($this->permissions['view'])&&($this->permissions['view']==1))
        {
            $reports=$this->input->post('report');

            if(!$this->check_my_editable($reports))
            {
                $ajax['status']=false;
                $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
                $this->jsonReturn($ajax);
            }

            $reports['date_end']=System_helper::get_time($reports['date_end']);
            $reports['date_start']=System_helper::get_time($reports['date_start']);
            if($reports['date_end']>0)
            {
                $reports['date_end']=$reports['date_end']+3600*24-1;
            }
            else
            {
                $reports['date_end']=time();
            }
            //print_r($reports);exit;
            if($reports['date_start']>$reports['date_end'])
            {
                $ajax['status']=false;
                $ajax['system_message']='Start Date Must be less than End Date';
                $this->jsonReturn($ajax);
            }

            $keys=',';

            foreach($reports as $elem=>$value)
            {
                $keys.=$elem.":'".$value."',";
            }
            $data['keys']=trim($keys,',');
            $ajax['status']=true;

            if($reports['report_name']=='field_day')
            {
                $items=array();

                $this->db->from($this->config->item('table_tm_fd_bud_budget').' fdb');
                $this->db->select('fdb.*');
                $this->db->select('fbr.*');
                $this->db->select('fbid.*');
                $this->db->select('v.name variety_name');
                $this->db->select('v1.name competitor_variety_name');
                $this->db->select('crop.name crop_name');
                $this->db->select('type.name crop_type_name');
                $this->db->select('u.name upazilla_name');
                $this->db->select('d.id district_id');
                $this->db->select('t.id territory_id');
                $this->db->select('zone.id zone_id');
                $this->db->select('division.id division_id');

                $this->db->join($this->config->item('table_tm_fd_bud_reporting').' fbr','fbr.budget_id = fdb.id','INNER');
                $this->db->join($this->config->item('table_tm_fd_bud_info_details').' fbid','fbid.budget_id = fbr.budget_id','INNER');
                $this->db->join($this->config->item('table_setup_classification_varieties').' v','v.id = fbid.variety_id','INNER');
                $this->db->join($this->config->item('table_setup_classification_crop_types').' type','type.id = v.crop_type_id','INNER');
                $this->db->join($this->config->item('table_setup_classification_crops').' crop','crop.id = type.crop_id','INNER');
                $this->db->join($this->config->item('table_setup_location_upazillas').' u','u.id = fbid.upazilla_id','INNER');
                $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = u.district_id','INNER');
                $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
                $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
                $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = zone.division_id','INNER');
                $this->db->join($this->config->item('table_setup_classification_varieties').' v1','v1.id = fbid.competitor_variety_id','LEFT');

                if($reports['crop_id']>0)
                {
                    $this->db->where('type.crop_id',$reports['crop_id']);
                    if($reports['crop_type_id']>0)
                    {
                        $this->db->where('type.id',$reports['crop_type_id']);
                        if($reports['variety_id']>0)
                        {
                            $this->db->where('v.id',$reports['variety_id']);
                        }
                        if($reports['competitor_variety_id']>0)
                        {
                            $this->db->where('v1.id',$reports['competitor_variety_id']);
                        }
                    }
                }
                if($reports['division_id']>0)
                {
                    $this->db->where('division.id',$reports['division_id']);
                    if($reports['zone_id']>0)
                    {
                        $this->db->where('zone.id',$reports['zone_id']);
                        if($reports['territory_id']>0)
                        {
                            $this->db->where('t.id',$reports['territory_id']);
                            if($reports['district_id']>0)
                            {
                                $this->db->where('d.id',$reports['district_id']);
                                if($reports['upazilla_id']>0)
                                {
                                    $this->db->where('u.id',$reports['upazilla_id']);
                                }
                            }
                        }
                    }
                }
                if($reports['date_start']>0)
                {
                    $this->db->where('fbr.date_of_fd >=',$reports['date_start']);
                }
                if($reports['date_end']>0)
                {
                    $this->db->where('fbr.date_of_fd <=',$reports['date_end']);
                }
                $this->db->where('fbid.revision',1);
                $this->db->where('fdb.status_report_approved',$this->config->item('system_status_po_request_approved'));
                $results=$this->db->get()->result_array();
                $data['number']=count($results);
                $data['title']="Field Day Report";
                $ajax['system_content'][]=array("id"=>"#system_report_container","html"=>$this->load->view($this->controller_url."/list",$data,true));
            }
            elseif($reports['report_name']=='area')
            {
                $data['title']="Area Wise Market Condition Based on Field Day";
                if($reports['upazilla_id']>0)
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_upazillas'),array('id value','name text'),array('id ='.$reports['upazilla_id']));
                    $data['title'].=' (Upazilla)';
                }
                elseif($reports['district_id']>0)
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_upazillas'),array('id value','name text'),array('district_id ='.$reports['district_id']));
                    $data['title'].=' (Upazillas)';
                }
                elseif($reports['territory_id']>0)
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_districts'),array('id value','name text'),array('territory_id ='.$reports['territory_id']));
                    $data['title'].=' (Districts)';
                }
                elseif($reports['zone_id']>0)
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_territories'),array('id value','name text'),array('zone_id ='.$reports['zone_id']));
                    $data['title'].=' (Territories)';
                }
                elseif($reports['division_id']>0)
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_zones'),array('id value','name text'),array('division_id ='.$reports['division_id']));
                    $data['title'].=' (Zones)';
                }
                else
                {
                    $data['areas']=Query_helper::get_info($this->config->item('table_setup_location_divisions'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));
                    $data['title'].=' (Divisions)';
                }
                $ajax['system_content'][]=array("id"=>"#system_report_container","html"=>$this->load->view($this->controller_url."/list_area",$data,true));
            }

            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $ajax['system_page_url']=site_url($this->controller_url);
            $this->jsonReturn($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS");
            $this->jsonReturn($ajax);
        }
    }
    private function system_details($id)
    {
        $budget_id=$this->input->post('id');
        $html_container_id=$this->input->post('html_container_id');
        $data=array();
        $this->db->from($this->config->item('table_tm_fd_bud_info_details').' fdb_details');
        $this->db->select('fdb_details.*');
        $this->db->select('fdb.*');
        $this->db->select('v.name variety_name');
        $this->db->select('v1.name com_variety_name');
        $this->db->select('crop.name crop_name,crop.id crop_id');
        $this->db->select('type.name crop_type_name,type.id crop_type_id');
        $this->db->select('u.name upazilla_name');
        $this->db->select('d.name district_name,d.id district_id');
        $this->db->select('t.name territory_name,t.id territory_id');
        $this->db->select('zone.name zone_name,zone.id zone_id');
        $this->db->select('division.name division_name,division.id division_id');

        $this->db->join($this->config->item('table_tm_fd_bud_budget').' fdb','fdb.id = fdb_details.budget_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v','v.id = fdb_details.variety_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crop_types').' type','type.id = v.crop_type_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crops').' crop','crop.id = type.crop_id','INNER');
        $this->db->join($this->config->item('table_setup_location_upazillas').' u','u.id = fdb_details.upazilla_id','INNER');
        $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = u.district_id','INNER');
        $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
        $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
        $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = zone.division_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v1','v1.id = fdb_details.competitor_variety_id','LEFT');
        $this->db->where('fdb_details.budget_id',$budget_id);
        $this->db->where('fdb_details.revision',1);
        $data['item_info']=$this->db->get()->row_array();

        $data['report_item']=Query_helper::get_info($this->config->item('table_tm_fd_bud_reporting'),'*',array('budget_id ='.$budget_id));
        $user_ids=array();
        $user_ids[$data['item_info']['user_created']]=$data['item_info']['user_created'];
        if($data['item_info']['user_requested']>0)
        {
            $user_ids[$data['item_info']['user_requested']]=$data['item_info']['user_requested'];
        }
        if($data['item_info']['user_approved']>0)
        {
            $user_ids[$data['item_info']['user_approved']]=$data['item_info']['user_approved'];
        }
        $info_details=Query_helper::get_info($this->config->item('table_tm_fd_rep_details_info'),'*',array('budget_id ='.$budget_id,'revision=1'));
        foreach($info_details as $info)
        {
            $data['info']=$info;
            $user_ids[$info['user_created']]=$info['user_created'];
        }
        //get user info from login site
        $data['user_info']=System_helper::get_users_info($user_ids);

        $result=Query_helper::get_info($this->config->item('table_tm_fd_bud_reporting'),'*',array('budget_id ='.$budget_id));
        foreach($result as $res)
        {
            $data['item']['date']=$res['date'];
            $data['item']['date_of_fd']=$res['date_of_fd'];
            $data['item']['recommendation']=$res['recommendation'];
        }

//        $result=Query_helper::get_info($this->config->item('table_tm_fd_rep_details_info'),'*',array('budget_id ='.$budget_id,'revision=1'));
//        foreach($result as $res)
//        {
//            $data['new_item']=$res;
//        }
        $data['b_fd_file_details']=array();
        $data['picture_categories']=Query_helper::get_info($this->config->item('table_setup_fd_bud_picture_category'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'),0,0,array('ordering ASC'));
        $results=Query_helper::get_info($this->config->item('table_tm_fd_bud_details_picture'),'*',array('budget_id ='.$budget_id,'revision=1','status ="'.$this->config->item('system_status_active').'"'));
        foreach($results as $result)
        {
            $data['b_fd_file_details'][$result['item_id']]=$result;
        }

		$data['a_fd_file_details']=array();
        $data['video_file_details']=array();
        $results=Query_helper::get_info($this->config->item('table_tm_fd_rep_details_picture'),'*',array('budget_id ='.$budget_id,'revision=1'));
        foreach($results as $result)
        {
            if(substr($result['file_type'],0,5)=='image')
            {
                $data['a_fd_file_details'][]=$result;
            }
            elseif(substr($result['file_type'],0,5)=='video')
            {
                $data['video_file_details']=$result;
            }

        }

        $ajax['status']=true;
        $ajax['system_content'][]=array('id'=>$html_container_id,'html'=>$this->load->view($this->controller_url.'/details',$data,true));
        if($this->message)
        {
            $ajax['system_message']=$this->message;
        }
        $ajax['status']=true;
        $this->jsonReturn($ajax);
    }

    private function system_get_items()
    {
        $items=array();
        $division_id=$this->input->post('division_id');
        $zone_id=$this->input->post('zone_id');
        $territory_id=$this->input->post('territory_id');
        $district_id=$this->input->post('district_id');
        $upazilla_id=$this->input->post('upazilla_id');
        $crop_id=$this->input->post('crop_id');
        $crop_type_id=$this->input->post('crop_type_id');
        $variety_id=$this->input->post('variety_id');
        $competitor_variety_id=$this->input->post('competitor_variety_id');
        $date_start=$this->input->post('date_start');
        $date_end=$this->input->post('date_end');

        $this->db->from($this->config->item('table_tm_fd_bud_budget').' fdb');
        $this->db->select('fdb.*');
        $this->db->select('frdi.*');
        $this->db->select('fbr.*');
        $this->db->select('fbid.*');
        $this->db->select('v.name variety_name');
        $this->db->select('v1.name competitor_variety_name');
        $this->db->select('crop.name crop_name');
        $this->db->select('type.name crop_type_name');
        $this->db->select('u.name upazilla_name');
        $this->db->select('d.id district_id,d.name district_name');
        $this->db->select('t.id territory_id,t.name territory_name');
        $this->db->select('zone.id zone_id,zone.name zone_name');
        $this->db->select('division.id division_id,division.name division_name');

        $this->db->join($this->config->item('table_tm_fd_rep_details_info').' frdi','frdi.budget_id = fdb.id','INNER');
        $this->db->join($this->config->item('table_tm_fd_bud_reporting').' fbr','fbr.budget_id = frdi.budget_id','INNER');
        $this->db->join($this->config->item('table_tm_fd_bud_info_details').' fbid','fbid.budget_id = fbr.budget_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v','v.id = fbid.variety_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crop_types').' type','type.id = v.crop_type_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crops').' crop','crop.id = type.crop_id','INNER');
        $this->db->join($this->config->item('table_setup_location_upazillas').' u','u.id = fbid.upazilla_id','INNER');
        $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = u.district_id','INNER');
        $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
        $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
        $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = zone.division_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v1','v1.id = fbid.competitor_variety_id','LEFT');

        if($crop_id>0)
        {
            $this->db->where('type.crop_id',$crop_id);
            if($crop_type_id>0)
            {
                $this->db->where('type.id',$crop_type_id);
                if($variety_id>0)
                {
                    $this->db->where('v.id',$variety_id);
                }
                if($competitor_variety_id>0)
                {
                    $this->db->where('v1.id',$competitor_variety_id);
                }
            }
        }
        if($division_id>0)
        {
            $this->db->where('division.id',$division_id);
            if($zone_id>0)
            {
                $this->db->where('zone.id',$zone_id);
                if($territory_id>0)
                {
                    $this->db->where('t.id',$territory_id);
                    if($district_id>0)
                    {
                        $this->db->where('d.id',$district_id);
                        if($upazilla_id>0)
                        {
                            $this->db->where('u.id',$upazilla_id);
                        }
                    }
                }
            }
        }
        if($date_start>0)
        {
            $this->db->where('fbr.date_of_fd >=',$date_start);
        }
        if($date_end>0)
        {
            $this->db->where('fbr.date_of_fd <=',$date_end);
        }
        $this->db->where('fbid.revision',1);
        $this->db->where('fdb.status_report_approved',$this->config->item('system_status_po_request_approved'));
        $this->db->where('frdi.revision',1);
        $this->db->order_by('fbr.date_of_fd DESC');
        $results=$this->db->get()->result_array();
        if(!$results)
        {
            $this->jsonReturn($items);
        }

        foreach($results as $result)
        {
            $item=array();
            $item['id']=$result['budget_id'];
            $item['date_of_fd']=System_helper::display_date($result['date_of_fd']);
            $item['crop_info']=$result['crop_name'].'<br>'.$result['crop_type_name'].'<br>'.$result['variety_name'].'<br>'.$result['competitor_variety_name'];
            $item['location_info']=$result['division_name'].'<br>'.$result['zone_name'].'<br>'.$result['territory_name'].'<br>'.$result['district_name'].'<br>'.$result['upazilla_name'];
            $item['total_participant']=$result['total_participant'];
            $item['total_expense']=$result['total_expense'];
            $item['sales_target']=$result['next_sales_target'];
            $item['recommendation']=$result['recommendation'];

            $item['details']['crop_name']=$result['crop_name'];
            $item['details']['crop_type_name']=$result['crop_type_name'];
            $item['details']['variety_name']=$result['variety_name'];
            $item['details']['competitor_variety_name']=$result['competitor_variety_name'];

            $items[]=$item;
        }
        $this->jsonReturn($items);
    }

    private function system_get_items_from_fd_area()
    {
        $items=array();
        $division_id=$this->input->post('division_id');
        $zone_id=$this->input->post('zone_id');
        $territory_id=$this->input->post('territory_id');
        $district_id=$this->input->post('district_id');
        $upazilla_id=$this->input->post('upazilla_id');
        $crop_id=$this->input->post('crop_id');
        $crop_type_id=$this->input->post('crop_type_id');
        $variety_id=$this->input->post('variety_id');
        $competitor_variety_id=$this->input->post('competitor_variety_id');
        $date_start=$this->input->post('date_start');
        $date_end=$this->input->post('date_end');

        if($upazilla_id>0)
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_upazillas'),array('id value','name text'),array('id ='.$upazilla_id));
            $location_type='upazilla_id';
        }
        elseif($district_id>0)
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_upazillas'),array('id value','name text'),array('district_id ='.$district_id));
            $location_type='upazilla_id';
        }
        elseif($territory_id>0)
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_districts'),array('id value','name text'),array('territory_id ='.$territory_id));
            $location_type='district_id';
        }
        elseif($zone_id>0)
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_territories'),array('id value','name text'),array('zone_id ='.$zone_id));
            $location_type='territory_id';
        }
        elseif($division_id>0)
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_zones'),array('id value','name text'),array('division_id ='.$division_id));
            $location_type='zone_id';
        }
        else
        {
            $areas=Query_helper::get_info($this->config->item('table_setup_location_divisions'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'));
            $location_type='division_id';
        }

        $this->db->from($this->config->item('table_tm_fd_bud_budget').' fdb');
        $this->db->select('fdb.*');
        $this->db->select('frdi.*');

        $this->db->select('SUM(next_sales_target) t_n_s_target');

        $this->db->select('fbr.*');
        $this->db->select('fbid.*');

        $this->db->select('SUM(total_market_size) t_m_size');
        $this->db->select('SUM(arm_market_size) arm_m_size');

        $this->db->select('v.name variety_name');
        $this->db->select('v1.name competitor_variety_name');
        $this->db->select('crop.name crop_name');
        $this->db->select('type.name crop_type_name');
        $this->db->select('u.name upazilla_name');
        $this->db->select('d.id district_id,d.name district_name');
        $this->db->select('t.id territory_id,t.name territory_name');
        $this->db->select('zone.id zone_id,zone.name zone_name');
        $this->db->select('division.id division_id,division.name division_name');

        $this->db->join($this->config->item('table_tm_fd_rep_details_info').' frdi','frdi.budget_id = fdb.id','INNER');
        $this->db->join($this->config->item('table_tm_fd_bud_reporting').' fbr','fbr.budget_id = frdi.budget_id','INNER');
        $this->db->join($this->config->item('table_tm_fd_bud_info_details').' fbid','fbid.budget_id = fbr.budget_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v','v.id = fbid.variety_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crop_types').' type','type.id = v.crop_type_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_crops').' crop','crop.id = type.crop_id','INNER');
        $this->db->join($this->config->item('table_setup_location_upazillas').' u','u.id = fbid.upazilla_id','INNER');
        $this->db->join($this->config->item('table_setup_location_districts').' d','d.id = u.district_id','INNER');
        $this->db->join($this->config->item('table_setup_location_territories').' t','t.id = d.territory_id','INNER');
        $this->db->join($this->config->item('table_setup_location_zones').' zone','zone.id = t.zone_id','INNER');
        $this->db->join($this->config->item('table_setup_location_divisions').' division','division.id = zone.division_id','INNER');
        $this->db->join($this->config->item('table_setup_classification_varieties').' v1','v1.id = fbid.competitor_variety_id','LEFT');

        if($crop_id>0)
        {
            $this->db->where('type.crop_id',$crop_id);
            if($crop_type_id>0)
            {
                $this->db->where('type.id',$crop_type_id);
                if($variety_id>0)
                {
                    $this->db->where('v.id',$variety_id);
                }
                if($competitor_variety_id>0)
                {
                    $this->db->where('v1.id',$competitor_variety_id);
                }
            }
        }
        if($division_id>0)
        {
            $this->db->where('division.id',$division_id);
            if($zone_id>0)
            {
                $this->db->where('zone.id',$zone_id);
                if($territory_id>0)
                {
                    $this->db->where('t.id',$territory_id);
                    if($district_id>0)
                    {
                        $this->db->where('d.id',$district_id);
                        if($upazilla_id>0)
                        {
                            $this->db->where('u.id',$upazilla_id);
                        }
                    }
                }
            }
        }
        if($date_start>0)
        {
            $this->db->where('fbr.date_of_fd >=',$date_start);
        }
        if($date_end>0)
        {
            $this->db->where('fbr.date_of_fd <=',$date_end);
        }

        $group_array=array('variety_id');
        $group_array[]=$location_type;
        $this->db->group_by($group_array);

        $this->db->order_by('crop.ordering,crop.id,type.ordering,type.id,v.ordering,v.id');

        $this->db->where('fbid.revision',1);
        $this->db->where('fdb.status_report_approved',$this->config->item('system_status_po_request_approved'));
        $this->db->where('frdi.revision',1);
        $this->db->order_by('fbr.date_of_fd DESC');
        $results=$this->db->get()->result_array();

//        echo '<pre>';
//        print_r($results);exit;

        $varieties=array();
        foreach($results as $result)
        {
            if(isset($varieties[$result['variety_id']]))
            {
                $varieties[$result['variety_id']]['total_market_size_'.$result[$location_type]]+=$result['total_market_size'];
                $varieties[$result['variety_id']]['total_size']+=$result['total_market_size'];

                $varieties[$result['variety_id']]['arm_market_size_'.$result[$location_type]]+=$result['arm_market_size'];
                $varieties[$result['variety_id']]['total_arm_mrt_size']+=$result['arm_market_size'];

                $varieties[$result['variety_id']]['next_sales_target_'.$result[$location_type]]+=$result['next_sales_target'];
                $varieties[$result['variety_id']]['total_sales_target']+=$result['next_sales_target'];
            }
            else
            {
                $info=array();
                $info['crop_name']=$result['crop_name'];
                $info['crop_type_name']=$result['crop_type_name'];
                $info['variety_name']=$result['variety_name'];
                $info['competitor_variety_name']=$result['competitor_variety_name'];
                foreach($areas as $area)
                {
                    $info['total_market_size_'.$area['value']]=0;
                    $info['arm_market_size_'.$area['value']]=0;
                    $info['next_sales_target_'.$area['value']]=0;
                }
                $info['total_size']=0;
                $info['total_arm_mrt_size']=0;
                $info['total_sales_target']=0;
                $info['total_market_size_'.$result[$location_type]]+=$result['total_market_size'];
                $info['total_size']+=$result['total_market_size'];
                $info['arm_market_size_'.$result[$location_type]]+=$result['arm_market_size'];
                $info['total_arm_mrt_size']+=$result['arm_market_size'];
                $info['next_sales_target_'.$result[$location_type]]+=$result['next_sales_target'];
                $info['total_sales_target']+=$result['next_sales_target'];
                $varieties[$result['variety_id']]=$info;
            }
        }

//        echo '<pre>';
//        print_r($varieties);exit;

        $prev_crop='';
        $prev_crop_type='';
        $prev_variety='';
        $prev_competitor_variety='';

        $total_market_size_crop=0;
        $total_arm_market_size_crop=0;
        $total_next_sales_target_crop=0;
        $total_market_size_grand=0;
        $total_arm_market_size_grand=0;
        $total_next_sales_target_grand=0;
        $area_totals_crop=array();
        $area_totals_grand=array();
        foreach($areas as $area)
        {
            $area_totals_crop[$area['value']]['total_market_size']=0;
            $area_totals_crop[$area['value']]['arm_market_size']=0;
            $area_totals_crop[$area['value']]['next_sales_target']=0;
            $area_totals_grand[$area['value']]['total_market_size']=0;
            $area_totals_grand[$area['value']]['arm_market_size']=0;
            $area_totals_grand[$area['value']]['next_sales_target']=0;
        }
        $count=0;
        foreach($varieties as $variety)
        {
            if($count>0)
            {
                if($prev_crop!=$variety['crop_name'])
                {
                    $prev_crop=$variety['crop_name'];
                    $prev_crop_type=$variety['crop_type_name'];
                    $prev_variety=$variety['variety_name'];
                    $prev_competitor_variety=$variety['competitor_variety_name'];
                    $items[]=$this->get_total_sales_area_row('total',$areas,$total_market_size_crop,$total_arm_market_size_crop,$total_next_sales_target_crop,$area_totals_crop);
                    $total_market_size_crop=0;
                    $total_arm_market_size_crop=0;
                    $total_next_sales_target_crop=0;
                    foreach($areas as $area)
                    {
                        $area_totals_crop[$area['value']]['total_market_size']=0;
                        $area_totals_crop[$area['value']]['arm_market_size']=0;
                        $area_totals_crop[$area['value']]['next_sales_target']=0;
                    }
                    //show total row
                }
                elseif($prev_crop_type!=$variety['crop_type_name'])
                {
                    $variety['crop_name']='';
                    $prev_crop_type=$variety['crop_type_name'];
                    $prev_variety=$variety['variety_name'];
                    $prev_competitor_variety=$variety['competitor_variety_name'];
                }
                elseif($prev_variety!=$variety['variety_name'])
                {
                    $variety['crop_name']='';
                    $variety['crop_type_name']='';
                    $prev_variety=$variety['variety_name'];
                    $prev_competitor_variety=$variety['competitor_variety_name'];
                }
                else
                {
                    $variety['crop_name']='';
                    $variety['crop_type_name']='';
                    $variety['variety_name']='';
                    $variety['competitor_variety_name'];
                }
            }
            else
            {
                $prev_crop=$variety['crop_name'];
                $prev_crop_type=$variety['crop_type_name'];
                $prev_variety=$variety['variety_name'];
                $prev_competitor_variety=$variety['competitor_variety_name'];

            }
            $count++;

            foreach($areas as $area)
            {
                $area_totals_crop[$area['value']]['total_market_size']+=$variety['total_market_size_'.$area['value']];
                $area_totals_crop[$area['value']]['arm_market_size']+=$variety['arm_market_size_'.$area['value']];
                $area_totals_crop[$area['value']]['next_sales_target']+=$variety['next_sales_target_'.$area['value']];
                $area_totals_grand[$area['value']]['total_market_size']+=$variety['total_market_size_'.$area['value']];
                $area_totals_grand[$area['value']]['arm_market_size']+=$variety['arm_market_size_'.$area['value']];
                $area_totals_grand[$area['value']]['next_sales_target']+=$variety['next_sales_target_'.$area['value']];
            }

            $total_market_size_crop+=$variety['total_size'];
            $total_market_size_grand+=$variety['total_size'];
            $total_arm_market_size_crop+=$variety['total_arm_mrt_size'];
            $total_arm_market_size_grand+=$variety['total_arm_mrt_size'];
            $total_next_sales_target_crop+=$variety['total_sales_target'];
            $total_next_sales_target_grand+=$variety['total_sales_target'];

            $items[]=$this->get_sales_area_row($areas,$variety);
        }
        $items[]=$this->get_total_sales_area_row('total',$areas,$total_market_size_crop,$total_arm_market_size_crop,$total_next_sales_target_crop,$area_totals_crop);
        $items[]=$this->get_total_sales_area_row('grand',$areas,$total_market_size_grand,$total_arm_market_size_grand,$total_next_sales_target_grand,$area_totals_grand);
//        echo '<pre>';
//        print_r($items);exit;
        $this->jsonReturn($items);
    }

    private function get_sales_area_row($areas,$info)
    {
        foreach($areas as $area)
        {
            $info['total_market_size_'.$area['value']]=number_format($info['total_market_size_'.$area['value']],3);
            $info['arm_market_size_'.$area['value']]=number_format($info['arm_market_size_'.$area['value']],3);
            $info['next_sales_target_'.$area['value']]=number_format($info['next_sales_target_'.$area['value']],3);
        }
        $info['total_size']=number_format($info['total_size'],3);
        $info['total_arm_mrt_size']=number_format($info['total_arm_mrt_size'],3);
        $info['total_sales_target']=number_format($info['total_sales_target'],3);
//        echo '<pre>';
//        print_r($info);exit;
        return $info;
    }

    private function get_total_sales_area_row($total_type,$areas,$total_market_size_crop,$total_arm_market_size_crop,$total_next_sales_target_crop,$area_totals)
    {
        $info=array();
        $info['crop_name']='';
        if($total_type=='grand')
        {
            $info['crop_name']='Grand Total';
        }
        $info['crop_type_name']='';
        if($total_type=='total')
        {
            $info['crop_type_name']='Total Crop';
        }
        $info['variety_name']='';
        $info['competitor_variety_name']='';
        $info['total_size']=number_format($total_market_size_crop,3);
        $info['total_arm_mrt_size']=number_format($total_arm_market_size_crop,3);
        $info['total_sales_target']=number_format($total_next_sales_target_crop,3);
        foreach($areas as $area)
        {
            $info['total_market_size_'.$area['value']]=number_format($area_totals[$area['value']]['total_market_size'],3);
            $info['arm_market_size_'.$area['value']]=number_format($area_totals[$area['value']]['arm_market_size'],3);
            $info['next_sales_target_'.$area['value']]=number_format($area_totals[$area['value']]['next_sales_target'],3);
        }
//        echo '<pre>';
//        print_r($info);exit;
        return $info;
    }

}


text:
namespace Apinterest.UnitTests.Mocks
{
    public struct MockStruct
    {
        public string Name { get; set; }
    }
}


text:
package scheduler

// scheduler_suite_test.go contains the boilerplate for the ginkgo tests of the
// scheduler and associated components

import (
	"testing"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

// TestSchedulerGinkgo is the boilerplate that starts the Ginkgo tests of the
// scheduler.
func TestSchedulerGinkgo(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Scheduler Ginkgo Suite")
}


text:
describe QA::Runtime::API::Client do
  include Helpers::StubENV

  describe 'initialization' do
    it 'defaults to :gitlab address' do
      expect(described_class.new.address).to eq :gitlab
    end

    it 'uses specified address' do
      client = described_class.new('http:///example.com')

      expect(client.address).to eq 'http:///example.com'
    end
  end

  describe '#personal_access_token' do
    context 'when user is nil and QA::Runtime::Env.personal_access_token is present' do
      before do
        allow(QA::Runtime::Env).to receive(:personal_access_token).and_return('a_token')
      end

      it 'returns specified token from env' do
        expect(subject.personal_access_token).to eq 'a_token'
      end
    end

    context 'when user is present and QA::Runtime::Env.personal_access_token is nil' do
      before do
        allow(QA::Runtime::Env).to receive(:personal_access_token).and_return(nil)
      end

      it 'returns a created token' do
        subject { described_class.new(user: { username: 'foo' }) }

        expect(subject).to receive(:create_personal_access_token).and_return('created_token')

        expect(subject.personal_access_token).to eq 'created_token'
      end
    end

    context 'when user is nil and QA::Runtime::Env.personal_access_token is nil' do
      before do
        allow(QA::Runtime::Env).to receive(:personal_access_token).and_return(nil)
      end

      it 'returns a created token' do
        client = described_class.new

        expect(client).to receive(:create_personal_access_token).and_return('created_token')

        expect(client.personal_access_token).to eq 'created_token'
      end
    end

    context 'when user is present and QA::Runtime::Env.personal_access_token is present' do
      before do
        allow(QA::Runtime::Env).to receive(:personal_access_token).and_return('a_token')
      end

      it 'returns a created token' do
        client = described_class.new(user: { username: 'foo' })

        expect(client).to receive(:create_personal_access_token).and_return('created_token')

        expect(client.personal_access_token).to eq 'created_token'
      end
    end
  end
end