text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\CsvReferenceDetails;
use App\Models\Comments;
use App\Models\Definitions;
use App\Models\Dditems;
use Sentinel;
use Validator;
use Input;
use DB;
use App\Models\Datawizard;
use App\Models\CsvReferenca;
use App\Models\Mappedcoded;

class MappingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex()
    {
        $user = Sentinel::getUser();
        $user_id = Sentinel::check()->id;
        $latestrecord = CsvReferenca::select('conceptReferenceDataId')
            ->orderBy('conceptReferenceDataId','DESC')->first();

        if($user->inRole('administrator')){
            $definitions_data = DB::table('emdefinitionstable')
                ->whereNotIn('definitionID', function($q){
                    $q->select('referenceDetailId')->from('emdatawizard');
                })->get();

            $pending_approval =  Definitions::orderBy('emdefinitionstable.referenceDetailId','DESC')
                ->leftjoin('emdatawizard', 'emdefinitionstable.definitionID', '=', 'emdatawizard.referenceDetailId')
                ->where('emdatawizard.status','=',0)
                ->get();

            $mapped_item =  Definitions::orderBy('emdefinitionstable.referenceDetailId','DESC')
                ->join('emdatawizard', 'emdefinitionstable.definitionID', '=', 'emdatawizard.referenceDetailId')
                ->where('emdatawizard.status','=',1)
                ->get();
        }else{

            $definitions_data = DB::table('emconceptreferencedata')
             ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
             ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
             ->where('userId','=',$user_id)
             ->whereNotIn('definitionID', function($q){
                    $q->select('referenceDetailId')->from('emdatawizard');
                })->get();

            $pending_approval = CsvReferenca::
                 leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
                ->leftjoin('emdatawizard', 'emdefinitionstable.definitionID', '=', 'emdatawizard.referenceDetailId')
                ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
                ->where('userId','=',$user_id)
                ->where('emdatawizard.status','=',0)
                ->orderBy('emdefinitionstable.referenceDetailId','DESC')->get();

            $mapped_item = CsvReferenca::
            leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
                ->leftjoin('emdatawizard', 'emdefinitionstable.definitionID', '=', 'emdatawizard.referenceDetailId')
                ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
                ->where('userId','=',$user_id)
                ->where('emdatawizard.status','=',1)
                ->orderBy('emdefinitionstable.referenceDetailId','DESC')->get();

        }

        $dditems =Dditems::all();
        $selected=[];

        return view('dashboards.mapping',compact('definitions_data','dditems','selected','pending_approval','mapped_item'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function postWizardData(Request $request){
        $data = $request->all();

        if(!empty($data['data_selected'])){
            $data_id = $data['data_selected'];
            $created = date("Y-m-d H:i:s");
            foreach($data_id as $info){
                $dataexist = Datawizard::where('referenceDetailId', '=',  $data_id)->first();

                $wizardinfo=array(
                    'referenceDetailId'=>$info,
                    'datasetBelongs'=>$data['dataset'],
                    'dataItem'=>$request->input('mappinginfo'),
                    'mappingInfo'=>$request->input('mappingdata'),
                    'mappingComments'=>$data['mappingcomments'],
                    'createdDate' => $created,

                );

                $uizardupdate=array(
                    'datasetBelongs'=>$data['dataset'],
                    'dataItem'=>$request->input('mappinginfo'),
                    'mappingInfo'=>$request->input('mappingdata'),
                    'mappingComments'=>$data['mappingcomments'],
                    'createdDate' => $created,

                );

                if(!empty($dataexist))
                {
                    Datawizard::where('referenceDetailId',$data_id)->update($uizardupdate);

                }
                else{
                    Datawizard::insert($wizardinfo);
                }

            }

        }else{
            echo "error";

        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postSelectedData(Request $request){
        $data = $request->all();
        $data_id = $data['data_selected'];

        $user = Sentinel::getUser();
        $user_id = Sentinel::check()->id;
        $definitions_data = DB::table('emconceptreferencedata')
            ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
            ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
            ->where('userId','=',$user_id)
            ->whereIn('emdefinitionstable.definitionID',$data_id)
            ->get();

        return $definitions_data;

    }

    public function postSelectedDataMoremapping(Request $request){
        $data = $request->all();
        $data_id = $data['data_selected'];
        $user = Sentinel::getUser();
        $user_id = Sentinel::check()->id;

        $definitions_data = DB::table('emconceptreferencedata')
            ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
            ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
            ->leftjoin('emmappedcoded','emdefinitionstable.definitionID','=','emmappedcoded.localDataId')
            ->where('dataItemName','=',$data['data_item'])
            ->whereNotIn('definitionID', function($q){
                $q->select('localDataId')->from('emmappedcoded');
            })->get();

        if(!empty($data['nationalvalue'])){
            $nationalstatus="datafound";
            $datanational=$data['nationalvalue'];

            $national_codes = DB::table('emnationalcodedvalues')
                ->where('emnationalcodedvalues.ddItemName', 'LIKE', '%'.$data['nationalvalue'].'%')
               /* ->leftjoin('emmappedcoded','emnationalcodedvalues.codedValueId','=','emmappedcoded.nationaldataId')*/
                ->orderBy('ddItemCodeText','ASC')
                ->groupBy('emnationalcodedvalues.ddItemCodeText')
                /*->whereNotIn('codedValueId', function($q){
                    $q->select('nationaldataId')->from('emmappedcoded');
                })*/->get();
        }else{
            $nationalstatus="nodatafound";
            $national_codes = "";

        }

        echo "

                    Coded Value
                    Data Item
                    Coded Value Description

";

                if(!empty($definitions_data)){
                    foreach($definitions_data as $data) {
                        echo "<input type='hidden' name='selectedlocalvalue[]' value='$data->definitionID' >";

                            echo "
";

                        echo "$data->codedValue
                                $data->dataItemName
                            $data->codedValueDescription	";
                        if($data->mappedCodedStatus==1){
                            echo "	 ";

                        }
                        else{
                            echo "
                              <input class='localchecked' id='localcheck_$data->definitionID' type='checkbox' name='selectedlocalvalue[]' value='$data->definitionID' >
                              	";

                        }

                        echo"

                               ";
                        if($data->mappedCodedStatus==1) {
                            echo "  Mapped To";
                        }else{
                            echo "  dataItemName' data-id='$data->definitionID' class='btn local_national_mapping' style='border: 1px solid #0099cc;'>Map";

                        }
                        echo"

";

                    }
                }else{
                    echo "

                        No Record Found For Mapping

                    ";
                }

                 echo "

                  Coded Value
                   Coded Value Description

";

            if($nationalstatus=="datafound"){
                foreach($national_codes as $nat) {
                    echo

                        "
";

                        echo "
                                    <input type='radio' name='selectednationalvalue' value='$nat->codedValueId' >
                                	";

                        echo "ddItemCodeText'>$nat->ddItemCodeText
                         ddItemCodeText'>$nat->ddCodedValueDescription

                    ";
                }

            }else{

                    echo "

                        No Record Found

                    ";

            }

              echo "

";

    }

    public function postSelectedDataMoremappingFinal(Request $request){
        $data = $request->all();

        $dataItem_from_sql = $data['data_item'];
        $dataItem_value_sql = $data['nationalvalue'];
        $data_id = $data['data_selected'];
        $user = Sentinel::getUser();
        $user_id = Sentinel::check()->id;
        $sql_id = $data['data_item'];

        $definitions_data = DB::table('emconceptreferencedata')
            ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
            ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
            ->leftjoin('emmappedcoded','emdefinitionstable.definitionID','=','emmappedcoded.localDataId')
            ->where('dataItemName','=',$data['data_item'])
            ->get();

        if(!empty($data['nationalvalue'])){
            $nationalstatus="datafound";
            $datanational=$data['nationalvalue'];

            $national_codes = DB::table('emnationalcodedvalues')
                ->where('emnationalcodedvalues.ddItemName', 'LIKE', '%'.$data['nationalvalue'].'%')
                ->join('emmappedcoded','emnationalcodedvalues.codedValueId','=','emmappedcoded.nationaldataId')
                ->orderBy('ddItemCodeText','ASC')
                ->groupBy('emmappedcoded.mappedColor')
                ->get();

        }else{
            $nationalstatus="nodatafound";
            $national_codes = "";

        }

        // dd($national_codes);

        $sql_mapp_code= array();
        $sql_mapp_value = array();
        if(!empty($definitions_data ) && !empty($national_codes))
        {
          foreach ($definitions_data as $definition)
          {
              $sql_mapp_value[] = $definition->codedValue;
            // print($definition->codedValue);
          }

          foreach ($national_codes as $national)
          {

            $sql_mapp_code[] = $national->ddItemCodeText;
          }
        }

        else{

        }

        echo'

';

        echo "

                    Coded Value
                    Coded Value Description

";

                foreach($definitions_data as $data) {

                    echo "<input type='hidden' name='selectedlocalvalue[]' value='$data->definitionID' >";

                    if($data->mappedCodedStatus==1) {
                        echo "
mappedColor'>";
                    }else{
                        echo "
";
                    }

                           echo"$data->codedValue	";
                           echo"$data->codedValueDescription	";
                           echo"
                                     ";
                            if($data->mappedCodedStatus==1) {
                                echo "Mapped To";
                            }else{
                                echo "Local";

                            }
                                 echo"

                              	";

                            echo "
";

                }

                 echo "

                  Coded Value
                   Coded Value Description

";

            if($nationalstatus=="datafound"){
                foreach($national_codes as $nat) {

                    if($nat->mappedCodedStatus==1){
                        echo "
mappedColor !important'>";
                    }else{
                        "
";
                    }

                        echo "ddItemCodeText'>$nat->ddItemCodeText
                         ddItemCodeText'>$nat->ddCodedValueDescription

                    ";
                }

            }else{

                    echo "

                        No Record Found

                    ";

            }

               echo "

              SQL

                                    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>

SQL Code Generator

";
                                  echo("
CASE
");

                                        foreach($sql_mapp_value as $i=>$c )
                                        {
                                            if(in_array($c,$sql_mapp_code)){}
                                            else{
                                               array_push($sql_mapp_code,'Local');
                                            }
                                        }

                                     foreach($sql_mapp_value as $value)
                                     {
                                        echo("WHEN $dataItem_from_sql = '$value'
");

                                     }
                                     echo "

";
                                     echo("
");

                                        foreach ($sql_mapp_code as $code) {
                                           echo("THEN '$code'
");
                                        }

                               echo "

ELSE null
END AS '$dataItem_value_sql'

";

              echo "

";

        echo'

';

    }

    public function postNationalCodes(Request $request){
        $data = $request->all();
        $data_id = $data['data_selected'];
        $user = Sentinel::getUser();
        $user_id = Sentinel::check()->id;

        if(!empty($data['data_item'])){
            $national_codes = DB::table('emnationalcodedvalues')
                ->where('ddItemName', 'LIKE', '%'.$data['data_item'].'%')
                ->orderBy('ddItemCodeText','ASC')
                ->get();

            foreach($national_codes as $codes){
                echo "

                            $codes->ddItemCodeText
							$codes->ddCodedValueDescription

";

            }

        }
        else{
            echo "

                           No Record found

";
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function postSelectedDataItems(Request $request)
    {
       $data = $request->all();

        $highlightdata = $data['dataitemname'];

        $dataitems = DB::table('emdefinitionstable')->select('dataItemName')->groupBy('emdefinitionstable.dataItemName')->get();

        $dataitemsrelated = DB::table('emdefinitionstable')
                            ->select('dataItemName')
                            ->where('dataItemName','=',$data['dataitemname'])
                            ->get();

        foreach($dataitems as $data){

            echo "
";
            if($highlightdata==$data->dataItemName){
                echo  "dataItemName' class=\"col-md-6\" style='background-color:#70ad47'>";
            }else{
                echo  "dataItemName' class=\"col-md-6\">";
            }
                    echo "$data->dataItemName

";

        }
    }

    public function postMappingInformation(Request $request)
    {
       $data = $request->all();

        $dataitems = Datawizard::where('referenceDetailId','=',$data['dataid'])

            ->get();

        foreach($dataitems as $data){

            echo "

                            $data->datasetBelongs
                            $data->dataItem
                            $data->mappingInfo
                            $data->mappingComments
                            $data->sharePointLink

";

        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function postLocaltoNational(Request $request)
    {

        $data = $request->all();

        $localdataname = $data['localdataname'];
        $nationaldataname =$data['nationaldataname'];

        $nationaldata = DB::table('emnationalcodedvalues')
                        ->where('codedValueId','=',$data['national_id'])
                        ->first();

        $previous_color = DB::table('emmappedcoded')
            ->where('nationaldataId','=',$data['national_id'])
            ->orderBy('nationaldataId','ASC')
            ->first();

        if(!empty($previous_color)){
            $color_code = $previous_color->mappedColor;

        }else{
            $color_new = DB::table('emcolorcodes')
                ->select('colorCode')
                ->whereNotIn('colorCode', function($q){
                    $q->select('mappedColor')->from('emmappedcoded');
                })->first();

            $color_code = $color_new->colorCode;

        }

        $local_selected_ids = $data['checked'];
        foreach($local_selected_ids as $local_ids){

            $localdataitem = DB::table('emdefinitionstable')
                ->where('definitionID','=',$local_ids)
                ->first();

            $referencedetailid = $localdataitem->referenceDetailId;

            $mapdataitem=array(
                'localDataId'=>$local_ids,
                'referenceDetailId'=>$localdataitem->referenceDetailId,
                'nationaldataId'=>$data['national_id'],
                'mappedCodedStatus'=>1,
                'mappedColor'=>$color_code,
            );
            Mappedcoded::insert($mapdataitem);

            $infostatus = array(
                'mappedCodedStatus' => 1,
            );
            Definitions::where('definitionID','=',$local_ids)->update($infostatus);

        }

        $approved_count = DB::table('emconceptreferencedata')
            ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
            ->leftjoin('emdatawizard', 'emdefinitionstable.definitionID', '=', 'emdatawizard.referenceDetailId')
            ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
            ->where('emconceptreferencedata.status','=',1)
             ->where('emdefinitionstable.mappedCodedStatus','=',0)
             ->where('emdefinitionstable.dataItemName','=',$localdataname)
            ->count();
        if($approved_count==0){
            $complete = array(
                'mappedCodedComplete' => 1,
            );
            Definitions::where('dataItemName','=',$localdataname)->update($complete);
        }

       /* listing */

        $definitions_data = DB::table('emconceptreferencedata')
            ->leftjoin('emdefinitionstable','emconceptreferencedata.conceptReferenceDataId', '=', 'emdefinitionstable.referenceDetailId')
            ->leftjoin('users','emconceptreferencedata.userId','=','users.id')
            ->leftjoin('emmappedcoded','emdefinitionstable.definitionID','=','emmappedcoded.localDataId')
            ->where('dataItemName','=',$localdataname)
            ->get();

        if(!empty($nationaldataname)){
            $nationalstatus="datafound";
            $datanational=$nationaldataname;

            $national_codes = DB::table('emnationalcodedvalues')
                ->leftjoin('emmappedcoded','emmappedcoded.nationaldataId','=','emnationalcodedvalues.codedValueId')
                ->where('emnationalcodedvalues.ddItemName', 'LIKE', '%'.$nationaldataname.'%')
                /*->where('emmappedcoded.referenceDetailId','=',$referencedetailid)*/

                ->groupBy('emnationalcodedvalues.ddItemCodeText')
                ->orderBy('ddItemCodeText','ASC')

                ->get();

        }else{
            $nationalstatus="nodatafound";
            $national_codes = "";

        }

        echo "

                    Coded Value
                    Coded Value Description

";

        foreach($definitions_data as $data) {

            if($data->mappedCodedStatus==1){
                echo "
mappedColor'>";
            }else{
                echo "
";
             }

            echo "$data->codedValue
                            $data->codedValueDescription	";
            if($data->mappedCodedStatus==1){
                echo "	 ";

            }
            else{
                echo "
                              <input class='localchecked' id='localcheck_$data->definitionID' type='checkbox' name='selectedlocalvalue[]' value='$data->definitionID' >
                              	";

            }

            echo"

                               ";
                                if($data->mappedCodedStatus==1) {
                                    echo " Mapped To";
                                }else{
                                    echo " dataItemName' data-id='$data->definitionID' class='btn local_national_mapping' style='border: 1px solid #0099cc;'>Map";

                                }
                           echo"

";

        }

        echo "

                  Coded Value
                   Coded Value Description

";

        if($nationalstatus=="datafound"){
            foreach($national_codes as $nat) {

                if($nat->mappedCodedStatus==1){
                    echo "
mappedColor !important'>";
                }else{
                    echo "
";
                }

                echo "
                                    <input type='radio' name='selectednationalvalue' value='$nat->codedValueId' >

                      ddItemCodeText'>$nat->ddItemCodeText
                         ddItemCodeText'>$nat->ddCodedValueDescription

                    ";
            }

        }else{

            echo "

                        No Record Found

                    ";

        }

        echo "

";

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}


text:
<?php

namespace Phanbook\Common\Library\Providers;

use Phalcon\Mvc\Router as MvcRouter;
use Phalcon\Cli\Router as CliRouter;
use Phalcon\Mvc\Router\GroupInterface;

/**
 * \Phanbook\Common\Library\Providers\RoutingServiceProvider
 *
 * @package Phanbook\Common\Library\Providers
 */
class RoutingServiceProvider extends AbstractServiceProvider
{
    /**
     * The Service name.
     * @var string
     */
    protected $serviceName = 'router';

    /**
     * {@inheritdoc}
     *
     * @return void
     */
    public function register()
    {
        $this->di->setShared(
            $this->serviceName,
            function () {
                $bootstrap = container('bootstrap');

                if ($bootstrap->getMode() == 'cli') {
                    $router = new CliRouter();
                    $router->setDefaultModule('cli');
                } else {
                    $router = new MvcRouter(false);
                    $router->removeExtraSlashes(true);

                    foreach (container('modules') as $module) {
                        if (empty($module->router)) {
                            continue;
                        }

                        /** @noinspection PhpIncludeInspection */
                        $group = require $module->router;

                        if (!$group || !$group instanceof GroupInterface) {
                            continue;
                        }

                        $router->mount($group);
                        $router->setEventsManager(container('eventsManager'));
                    }
                }

                $router->setDI(container());

                return $router;
            }
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
COHORTE file finder

component that allow the resolve a file that contain multiple includes.
this allow to split a composition file in severals file and get a full resolved file

:author: Aurélien PISU
:license: Apache Software License 2.0

..

    Copyright 2014 isandlaTech

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

# COHORTE constants
import cohorte
from cohorte.config import common
import glob
import json
import logging
import os
from pelix.ipopo.decorators import ComponentFactory, Provides, Instantiate, \
    Validate, Invalidate, Requires
import re

try:
    # Python 3
    # pylint: disable=F0401,E0611
    import urllib.parse as urlparse
except ImportError:
    # Python 2
    # pylint: disable=F0401
    import urlparse

# iPOPO Decorators
# ------------------------------------------------------------------------------

# Bundle version
import cohorte.version
__version__=cohorte.version.__version__

# ------------------------------------------------------------------------------

_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------

class CBadResourceException(Exception):
    def __init__(self, message):
        self._message = message

    def __str__(self):
        return self._message

class CResource(object):
    def get_tag(self):
        return self.tag

    def get_params(self):
        return self.parms

    def get_path(self):
        return self.path

    def getdirpath(self):
        return self.dirpath

    def get_contents(self):
        return self.contents

    def set_contents(self, contents):
        self.contents = contents

    def readall(self):
        """
        return the merge content of all files that correspond to the resource
        """
        join_list = []
        if self.contents != None:
            for content in self.contents:
                if self.tag != None:
                    tag_elem = None
                    json_obj = json.loads(content);
                    idx_obraces = self.tag.find("[")
                    idx_cbraces = self.tag.find("]")
                    tag_key = self.tag
                    if idx_obraces != -1:
                        tag_key = self.tag[:idx_obraces]

                    if not tag_key in json_obj.keys():
                        mess = "include property [{0}]  defined in file [{1}] doesn't exists in file [{2}]".format(
                            tag_key, self.resource_parent.filename, self.filename);
                        raise CBadResourceException(mess)
                    else:
                        arr_elem = json_obj[tag_key]
                    # manage a tag can identified a array or a object and we want a elem of the array or all elemnet or the array
                    if (idx_obraces != -1 and idx_cbraces != -1):
                        if isinstance(arr_elem, list):
                            # want something from the array and not all the array
                            range_idx = self.tag[idx_obraces + 1:idx_cbraces]
                            if range_idx == None:
                                # nothin specify raise an error
                                raise CBadResourceException("include : No index but array ask")

                            elif range_idx.isdigit():
                                # want a specific element
                                idx = int(range_idx)
                                if idx > len(arr_elem):
                                    raise CBadResourceException(
                                        "include : Bad index expect=[{0}] size=[{1}]".format(idx, len(arr_elem)))
                                else:
                                    tag_elem = json.dumps(arr_elem[idx], indent=2)
                            elif range_idx == "*":
                                tag_elem = ",".join([json.dumps(elem) for elem in arr_elem])
                            else:
                                idxs = range_idx.split(":")
                                first = None
                                last = None
                                if idx[0].isdigit():
                                    first = int(idx[0])
                                if idx[1].isdigit():
                                    last = int(idx[1])
                                if last != None and fist != None:
                                    tag_elem = ",".join([json.dumps(elem) for elem in arr_elem[first:last]])
                                elif last != None:
                                    tag_elem = ",".join([json.dumps(elem) for elem in arr_elem[:last]])
                                else:
                                    tag_elem = ",".join([json.dumps(elem) for elem in arr_elem[first:]])

                                # want a specific range
                                pass
                        else:
                            raise CBadResourceException(
                                "include : expect for json array and get a json object urlinclude=[{0}]".format(
                                    self.fullpath))
                    else:
                        tag_elem = json.dumps(json.loads(content)[self.tag])

                    join_list.append(tag_elem)
                else:
                    join_list.append(content)

            return ",".join(join_list)
        return None

    """
    describe a resource that can be file, a http or memory or any kind
    """

    def __init__(self, filename, includer, finder, parent_resource=None):
        """
        construct a resource from a string e.g file:///mypath/foo.txt?k1=v1&#mytag
        @param resource : parent resource , use if path is relative
        @param alternive_dirs : alternative dirs to locate  the file content to include
        @param path : path of the current resource to create
        """
        self.fullpath = filename
        self.protocol_idx = 0
        # use to know the keep the generator due to the manage of import as it is today
        self._include = includer
        # contain the paths possible of location of the file
        self.filename = None
        # list of directory data and base (and home) where the file can be located
        self._finder = finder
        self.params = None
        self.type = "file"
        # contain the subpath of the directory not an absolute path
        self.dirpath = None
        self.contents = None
        self.read_files_name = None  # list of file name read that correspond to the contents . use for error managment

        self.tag = None
        self.resource_parent = parent_resource;
        self._set_filename(filename, parent_resource)

    def _set_filename(self, filename, parent_resource=None):
        """
        @param path : path of the files to load. can identified one file by multiple file via a regexp or wildchar
        """
        if filename != None:
            self.query_idx = filename.find("?")
            self.tag_idx = filename.find("#")
            filename = self._init_type(filename)
            filename = self._init_filename(filename, parent_resource)
            filename = self._init_query(filename)
            if self.tag_idx != -1:
                self.tag = filename[self.tag_idx + 1:]
                _logger.info("property tag {0}".format(self.tag))

            self.contents = self._read_contents()
        else:
            raise CBadResourceException("path parameter has 'None' value")

    def _init_type(self, filename):
        """
        return the protocol to use for resolving the url content
        @param path : a string that start with protocol://
        @return : a type that identified which protocol to use : can be file, http or memory
        """
        if filename != None:
            self.type = "file"
            # prefix that identify the protocol e.g file://
            if filename.startswith("memory://"):
                self.type = "memory"
                self.protocol_idx = 9
            elif filename.startswith("http://"):
                self.type = "http"
                self.protocol_idx = 7
            elif filename.startswith("file://"):
                self.protocol_idx = 7

        return filename

    def _init_query(self, filename):
        """
        return the query string parameter key=value that can be in the url. the substring starts with '#' will be ignored
        @param filename : a string that can contain key value a.g foo?k=v&p=c
        @return : a param dictionnary that contain the key value
        """
        if self.query_idx != -1:

            # set query if exists
            if self.tag_idx != -1:
                query = filename[self.query_idx + 1:self.tag_idx]
            else:
                query = filename[self.query_idx + 1:]

            self.params = urlparse.parse_qs(query)
            _logger.info("replace params {0}".format(self.params))

        return filename

    def _read_contents_file(self):
        """
        if the path contain a wildChar we read o all files else only the first one (compatibilty with the current way to manage import)
        return the contents of the files identified by the path
        @return : a list of String
        """
        contents = []
        path = self.filename

        self.read_files_name = []
        for file in self._finder.find_rel(path, self.dirpath):
            _logger.info("read file {0}".format(file))
            lines = []
            with open(file) as obj_file:
                comment_line = False
                self.read_files_name.append(file)
                for line in obj_file:
                    # remove /* */  comment, the // is manage by the regexp
                    # TODO manage "http://" /*
                    idx_last_str = line.rfind("\"")
                    idx_start = line.find("/*")
                    idx_end = line.find("*/")
                    if idx_start != -1 and idx_end != -1:
                        if not idx_start + 1 < idx_end:
                            lines.append(line)
                        else:
                            lines.append(line[:idx_start] + line[idx_end + 2:])
                    elif idx_start != -1 and idx_last_str < idx_start:
                        comment_line = True
                        lines.append(line[:idx_start])
                    elif idx_end != -1 and comment_line:
                        comment_line = False
                        lines.append(line[idx_end + 2:])
                    elif not comment_line:
                        lines.append(line)
                contents.append("\n".join(lines));

        if len(contents) > 0:
            return contents
        # no content found in list of directory
        return None

    def _read_contents(self):
        """
        return the content of the url with the variable replace
        @return : a  list of String
        """
        if self.type == "file":
            self.contents = self._read_contents_file()
        else:
            # not manager
            self.content = None

        if self.params != None:
            self.contents = common.replace_vars(self.params, self.contents)

        return self.contents

    def _init_filename(self, filename, parent_resource=None):
        """
        return the  filename of the resource to read
        @param filename : path of the resource to read
        @param parent_resource : a parent resource that include the current in order to resolve the relative path if it's necessary
        @return : a String
        """
        if filename != None:

            res_file_name = None
            if self.query_idx != -1:
                res_file_name = filename[self.protocol_idx:self.query_idx]
            elif self.tag_idx != -1:
                res_file_name = filename[self.protocol_idx:self.tag_idx]
            else:
                res_file_name = filename[self.protocol_idx:]

            # compute dir path and filename
            if res_file_name.find(os.sep) != -1:
                split_file = res_file_name.split(os.sep)
                self.dirpath = os.sep.join(split_file[:-1])
                self.filename = split_file[-1]

            else:
                self.dirpath = ""
                self.filename = res_file_name

            # check if parent resource has dirpath
            if parent_resource != None and parent_resource.dirpath != "":
                self.dirpath = parent_resource.dirpath + os.sep + self.dirpath

        _logger.info("filename {0}".format(filename))

        return filename

class FileIncluderAbs(object):
    """
    Simple component that resolve a comment json that can include using { $include : "path"} a subfile json content
    """

    def __init__(self):
        # regexp that manage multiline comment and // comment
        self._check = re.compile("(.*//.*)", re.MULTILINE)
        self._check_slash = re.compile("(\".*//.*\")", re.MULTILINE)
        _simple_include = "((\\n)*\\{(\\n)*\\s*\"\\$include\"\\s*:(\\s*\"[^\\}]*\"\\s*)\\})"
        _complex_include = "((\n)*\\{(\\s|\n|\t)*\"\\$include\"(\\s|\n|\t)*:(\\s|\n|\t)*\\{((\\s|\n|\t)*\"[^\\}]*\"(\\s|\n|\t)*:(\\s|\n|\t)*[^\\}]*(\\s|\n|\t)*,{0,1}(\\s|\n|\t)*)*\\}(\\s|\n|\t)*)\\}"
        self._include = re.compile("(" + _simple_include + ")|(" + _complex_include + ")", re.MULTILINE)
        _simple_merge = "(,{0,1}(\n|\s|\t)*\"\$merge\"(\n|\s|\t)*:((\n|\s|\t)*\[(\n|\s|\t)*\"[^\}]*\"(\n|\s|\t)*\](\n|\s|\t)*,{0,1}))"
        self._merge = re.compile(_simple_merge, re.MULTILINE)

        self._file_generator = {}  # list of generator by file

    def _get_finder(self):
        """
            return the finder component instance abstract method
        """
        pass

    def _get_content(self, filepath, parent_resource=None):
        """
        return a resolved content json string without commentary
        """

        if filepath != None:
            _logger.info("_getContent {0}".format(filepath))

            # return a resolve content json
            resource = CResource(filepath, self, self._get_finder(), parent_resource)

            # remove comment and content of the resource
            self._remove_comment(resource)

            # resolve content
            self._resolve_content(resource);

            return resource.readall()

        return None

    # for using it from jython without osgi and ipopo resolution
    def set_finder(self, finder):
        self._finder = finder

    def get_content(self, filename, want_json=False):
        """
        @param filename: path we want the content. the filename can be a absolute path, a path with key value params or tag to specify what content we want.
        e.g :
            -    file://mydir/myfile.js => this just get the content of the file myfile
            -    file://mydir.myfile.js?k1=v1&k2=v2 => this will get the content of the file myfile but it will replace all variable ${k1} and ${k2} by v1 and v2
            -    file://mydir.myfile.js?k1=v1&k2=v2#myprop => this will get the only the property myprop of the content file myfile wth replace variable

        @param wantJson : boolean to defined if we want a json object as a result or a string
        return a resolved content json string without commentary
        """

        # multi path asked if the filename contains ; separator
        if filename.find(";") != -1:
            content = ",".join([self._get_content(name) for name in filename.split(";")])
        else:
            content = self._get_content(filename)

        merge_content = None
        if content == None:
            raise IOError("file {0} doesn't exists".format(filename))
        json_contents = json.loads("[" + content + "]")

        for json_content in json_contents:
            if isinstance(json_content, dict):
                # must be always a dict to append all json dict

                if merge_content == None:
                    merge_content = json.loads("{}")
                merge_content = common.merge_object(merge_content, json_content)

            elif isinstance(json_content, list):
                # must be always a list to append all json arrays
                if merge_content == None:
                    merge_content = json.loads("[]")
                    for arr in json_content:
                        merge_content.append(arr)

                if merge_content == None:
                    raise IOError("{0} doesn't exists ".format(path))

        if not want_json:
            return json.dumps(merge_content)
        return merge_content

    def _get_include_path(self, json_match):
        if isinstance(json_match, dict):
            paths = json_match["path"]
            if isinstance(paths, basestring):
                paths = paths.split(";")
                # TODO property to manage
        else:
            paths = json_match.split(";")
            _logger.debug("_revolveContent: paths {0}".format(paths))
        return paths

    def _get_include_match(self, matches):
        found_match = None
        for match in matches:
            if match != "":
                found_match = match
                break
        return found_match

    def _resolve_content(self, resource):
        """
        return a resolve content with all include file content
        """
        _logger.debug("_revolveContent")

        contents = resource.get_contents();
        if contents != None:
            resolved_contents = []
            for content in contents:
                resolved_content = content
                # apply regexp to remove content
                for matches in self._include.findall(resolved_content):
                    found_match = self._get_include_match(matches)

                    _logger.debug("_revolveContent: match found {0}".format(found_match))
                    sub_contents = []
                    # load json to get the path and resolve it
                    match_json = json.loads(found_match)
                    if match_json != None:
                        if "$include" in match_json.keys():
                            # match is { $include: "file:///path of a file"}
                            for path in self._get_include_path(match_json["$include"]):
                                _logger.debug("_revolveContent: $include - subContentPath {0}".format(path))

                                sub_content = self._get_content(path, resource)
                                sub_contents.append(sub_content)
                            resolved_content = resolved_content.replace(found_match, str.join(",", sub_contents))

                # apply regexp to remove content
                for matches in self._merge.findall(resolved_content):
                    found_match = self._get_include_match(matches)

                    _logger.debug("_revolveContent: match found {0}".format(found_match))
                    sub_contents = []
                    # load json to get the path and resolve it
                    idx_sep = found_match.find(":")
                    end_coma = found_match.endswith(",")
                    start_coma = found_match.startswith(",")

                    if end_coma:
                        match_json = json.loads(found_match[idx_sep + 1:-1])
                    else:
                        match_json = json.loads(found_match[idx_sep + 1:])

                    if match_json != None:
                        resolved_content = json.loads(
                            resolved_content.replace(found_match, "," if end_coma and start_coma else ""))
                        for path in match_json:
                            _logger.debug("_revolveContent: $merge - subContentPath {0}".format(path))
                            # merge this json with the current one

                            to_merges = json.loads("[" + self._get_content(path, resource) + "]")
                            for to_merge in to_merges:
                                resolved_content = common.merge_object(resolved_content, to_merge)
                        resolved_content = json.dumps(resolved_content)
                        # replace match by list of subcontent
                resolved_contents.append(resolved_content);

            # check if the json is ok and reformat it for the correct application of the regexp
            resource.set_contents(resolved_contents)

    def _remove_comment(self, resource):
        """
        change the content to remove all possible comment // or /* ...*/
        """
        _logger.debug("_removeComment")

        contents = resource.get_contents()
        if contents != None:
            # apply regexp to remove content
            contents_no_comment = []
            for idx, content in enumerate(contents):
                content_no_comment = content
                for match in self._check.findall(content):
                    if match != None and match.find("/") != -1 and len(match) > 1:
                        _logger.debug("match comment {0}".format(match))

                        if self._check_slash.search(match) == None:
                            _logger.debug("_removeComment: match found {0}".format(match))
                            idx = match.find("/")
                            content_no_comment = content_no_comment.replace(match[idx:], "")
                try:
                    content_no_comment = json.dumps(json.loads(content_no_comment), indent=2)
                except Exception as e:
                    raise CBadResourceException(
                        "not valid json for file {0}, Error {1}".format(resource.read_files_name[idx], e.__str__()))
                contents_no_comment.append(content_no_comment)

            resource.set_contents(contents_no_comment)

@ComponentFactory('cohorte-file-includer-factory')
@Provides(cohorte.SERVICE_FILE_INCLUDER)
@Requires("_finder", cohorte.SERVICE_FILE_FINDER)
@Instantiate('cohorte-file-includer')
class FileIncluder(FileIncluderAbs):
    """
    Simple component that resolve a comment json that can include using { $include : "path"} a subfile json content
    """

    def __init__(self):
        super(FileIncluder, self).__init__()
        self._finder = None

    # override
    def _get_finder(self):
        """
            return the finder component instance abstract method
        """
        return self._finder

    @Validate
    def validate(self, context):
        _logger.info(" validating")

        _logger.info("validated")

    @Invalidate
    def invalidate(self, context):
        _logger.info("invalidating")

        _logger.info("invalidated")


text:
<?php include_once(APPPATH."views/fe/common/breadcrumb.tpl.php"); ?>

	<?php include_once(APPPATH."views/fe/common/message.tpl.php"); ?>

Change Password

		   <form name="frm_change_pwd" id="frm_change_pwd" action="<?php echo base_url().'user/change-password/'.$s_email ?>" method="post" >

New Password

					  <input name="txt_new_password" id="txt_new_password" type="password" />

<?php echo form_error('txt_new_password') ?>

Confirm Password

					<input name="txt_confirm_password" id="txt_confirm_password" type="password" />

<?php echo form_error('txt_confirm_password') ?>

				<input class="button-blu" type="button" value="Save" id="btn_change_pwd" />

				</form>


text:
package com.flowpowered.noise.exception;

public class NoModuleException extends NoiseException {
}


text:
namespace net {
class HttpRequestHeaders;
class URLRequest;
}

namespace data_reduction_proxy {

// Class responsible for deciding whether a request should be requested with low
// fidelity (Lo-Fi) or not. Relies on the Lo-Fi mode state stored in the
// request's content::ResourceRequestInfo, which must be fetched using
// content::ResourceRequestInfo::ForRequest. Lo-Fi mode will not be enabled for
// requests that don't have a ResourceRequestInfo, such as background requests.
// Owned by DataReductionProxyIOData and should be called on the IO thread.
class ContentLoFiDecider : public LoFiDecider {
 public:
  ContentLoFiDecider();
  ~ContentLoFiDecider() override;

  // LoFiDecider implementation:
  bool IsUsingLoFiMode(const net::URLRequest& request) const override;
  void MaybeSetAcceptTransformHeader(
      const net::URLRequest& request,
      bool is_previews_disabled,
      net::HttpRequestHeaders* headers) const override;
  bool IsSlowPagePreviewRequested(
      const net::HttpRequestHeaders& headers) const override;
  bool IsLitePagePreviewRequested(
      const net::HttpRequestHeaders& headers) const override;
  void RemoveAcceptTransformHeader(
      net::HttpRequestHeaders* headers) const override;
  void MaybeSetIgnorePreviewsBlacklistDirective(
      net::HttpRequestHeaders* headers) const override;
  bool ShouldRecordLoFiUMA(const net::URLRequest& request) const override;

 private:
  DISALLOW_COPY_AND_ASSIGN(ContentLoFiDecider);
};

}  // namespace data_reduction_proxy

#endif  // COMPONENTS_DATA_REDUCTION_PROXY_CONTENT_BROWSER_CONTENT_LOFI_DECIDER_H_


text:
#ifndef __TMASTER_STATS_INTERFACE_H_
#define __TMASTER_STATS_INTERFACE_H_

#include "network/network.h"
#include "proto/tmaster.pb.h"
#include "basics/basics.h"

namespace heron {
namespace tmaster {

using std::unique_ptr;
using std::shared_ptr;

class TMetricsCollector;
class TMaster;

class StatsInterface {
 public:
  StatsInterface(std::shared_ptr<EventLoop> eventLoop, const NetworkOptions& options,
                 shared_ptr<TMetricsCollector> _collector, TMaster* tmaster);
  virtual ~StatsInterface();

 private:
  void HandleStatsRequest(IncomingHTTPRequest* _request);
  void HandleUnknownRequest(IncomingHTTPRequest* _request);
  void HandleExceptionRequest(IncomingHTTPRequest* _request);
  void HandleExceptionSummaryRequest(IncomingHTTPRequest* _request);
  void HandleStmgrsRegistrationSummaryRequest(IncomingHTTPRequest* _request);

  unique_ptr<HTTPServer> http_server_;  // Our http server
  shared_ptr<TMetricsCollector> metrics_collector_;
  TMaster* tmaster_;
};
}  // namespace tmaster
}  // namespace heron

#endif


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 4: 137 (1886)

#### Original name
Nodulisporium ochraceum Preuss, 1849

### Remarks
null


text:
package com.zegoggles.smssync.service;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.store.imap.XOAuth2AuthenticationFailedException;
import com.zegoggles.smssync.auth.TokenRefreshException;
import com.zegoggles.smssync.auth.TokenRefresher;
import com.zegoggles.smssync.contacts.ContactAccessor;
import com.zegoggles.smssync.contacts.ContactGroup;
import com.zegoggles.smssync.contacts.ContactGroupIds;
import com.zegoggles.smssync.mail.BackupImapStore;
import com.zegoggles.smssync.mail.ConversionResult;
import com.zegoggles.smssync.mail.DataType;
import com.zegoggles.smssync.mail.MessageConverter;
import com.zegoggles.smssync.preferences.AuthPreferences;
import com.zegoggles.smssync.preferences.DataTypePreferences;
import com.zegoggles.smssync.preferences.Preferences;
import com.zegoggles.smssync.service.state.BackupState;
import com.zegoggles.smssync.service.state.SmsSyncState;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;
import org.openintents.openpgp.util.OpenPgpServiceConnection;
import org.robolectric.RuntimeEnvironment;

import java.util.EnumSet;
import java.util.HashMap;

import static com.google.common.truth.Truth.assertThat;
import static com.zegoggles.smssync.mail.DataType.CALLLOG;
import static com.zegoggles.smssync.mail.DataType.MMS;
import static com.zegoggles.smssync.mail.DataType.SMS;
import static com.zegoggles.smssync.service.BackupItemsFetcher.emptyCursor;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.notNull;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.anyListOf;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

@RunWith(RobolectricTestRunner.class)
public class BackupTaskTest {
    BackupTask task;
    BackupConfig config;
    Context context;
    @Mock BackupImapStore store;
    @Mock BackupImapStore.BackupFolder folder;
    @Mock SmsBackupService service;
    @Mock BackupState state;
    @Mock BackupItemsFetcher fetcher;
    @Mock MessageConverter converter;
    @Mock CalendarSyncer syncer;
    @Mock AuthPreferences authPreferences;
    @Mock DataTypePreferences dataTypePreferences;
    @Mock Preferences preferences;
    @Mock ContactAccessor accessor;
    @Mock TokenRefresher tokenRefresher;
    @Mock OpenPgpServiceConnection serviceConnection;

    @Before public void before() {
        initMocks(this);
        config = getBackupConfig(EnumSet.of(SMS));
        when(service.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
        when(service.getState()).thenReturn(state);
        when(preferences.getDataTypePreferences()).thenReturn(dataTypePreferences);

        task = new BackupTask(service, fetcher, converter, syncer, authPreferences, preferences, accessor, tokenRefresher, serviceConnection);
        context = RuntimeEnvironment.application;
    }

    private BackupConfig getBackupConfig(EnumSet<DataType> types) {
        return new BackupConfig(store, 0, 100, new ContactGroup(-1), BackupType.MANUAL, types,
                false
        );
    }

    @Test public void shouldAcquireAndReleaseLocksDuringBackup() throws Exception {
        mockAllFetchEmpty();

        task.doInBackground(config);

        verify(service).acquireLocks();
        verify(service).releaseLocks();
        verify(service).transition(SmsSyncState.FINISHED_BACKUP, null);
    }

    @Test public void shouldVerifyStoreSettings() throws Exception {
        mockFetch(SMS, 1);
        when(converter.convertMessages(any(Cursor.class), eq(SMS))).thenReturn(result(SMS, 1));
        when(store.getFolder(SMS, dataTypePreferences)).thenReturn(folder);
        task.doInBackground(config);
        verify(store).checkSettings();
    }

    @Test public void shouldBackupItems() throws Exception {
        mockFetch(SMS, 1);

        when(converter.convertMessages(any(Cursor.class), eq(SMS))).thenReturn(result(SMS, 1));
        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenReturn(folder);

        BackupState finalState = task.doInBackground(config);

        verify(folder).appendMessages(anyListOf(Message.class));

        verify(service).transition(SmsSyncState.LOGIN, null);
        verify(service).transition(SmsSyncState.CALC, null);

        assertThat(finalState).isNotNull();
        assertThat(finalState.isFinished()).isTrue();
        assertThat(finalState.currentSyncedItems).isEqualTo(1);
        assertThat(finalState.itemsToSync).isEqualTo(1);
        assertThat(finalState.backupType).isEqualTo(config.backupType);
    }

    @Test
    public void shouldBackupMultipleTypes() throws Exception {
        mockFetch(SMS, 1);
        mockFetch(MMS, 2);
        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenReturn(folder);
        when(converter.convertMessages(any(Cursor.class), any(DataType.class))).thenReturn(result(SMS, 1));

        BackupState finalState = task.doInBackground(getBackupConfig(EnumSet.of(SMS, MMS)));

        assertThat(finalState.currentSyncedItems).isEqualTo(3);

        verify(folder, times(3)).appendMessages(anyListOf(Message.class));
    }

    @Test public void shouldCreateFoldersLazilyOnlyForNeededTypes() throws Exception {
        mockFetch(SMS, 1);

        when(converter.convertMessages(any(Cursor.class), eq(SMS))).thenReturn(result(SMS, 1));
        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenReturn(folder);

        task.doInBackground(config);

        verify(store).getFolder(SMS, dataTypePreferences);
        verify(store, never()).getFolder(MMS, dataTypePreferences);
        verify(store, never()).getFolder(CALLLOG, dataTypePreferences);
    }

    @Test public void shouldCloseImapFolderAfterBackup() throws Exception {
        mockFetch(SMS, 1);
        when(converter.convertMessages(any(Cursor.class), eq(SMS))).thenReturn(result(SMS, 1));
        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenReturn(folder);

        task.doInBackground(config);

        verify(store).closeFolders();
    }

    @Test public void shouldCreateNoFoldersIfNoItemsToBackup() throws Exception {
        mockFetch(SMS, 0);
        task.doInBackground(config);
        verifyZeroInteractions(store);
    }

    @Test public void shouldSkipItems() throws Exception {
        when(fetcher.getMostRecentTimestamp(any(DataType.class))).thenReturn(-23L);

        BackupState finalState = task.doInBackground(new BackupConfig(
            store, 0, 100, new ContactGroup(-1), BackupType.SKIP, EnumSet.of(SMS), false
            )
        );
        verify(dataTypePreferences).setMaxSyncedDate(DataType.SMS, -23);
        verifyZeroInteractions(dataTypePreferences);

        assertThat(finalState).isNotNull();
        assertThat(finalState.isFinished()).isTrue();
    }

    @Test public void shouldHandleAuthErrorAndTokenCannotBeRefreshed() throws Exception {
        mockFetch(SMS, 1);
        when(converter.convertMessages(any(Cursor.class), notNull(DataType.class))).thenReturn(result(SMS, 1));

        XOAuth2AuthenticationFailedException exception = mock(XOAuth2AuthenticationFailedException.class);
        when(exception.getStatus()).thenReturn(400);

        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenThrow(exception);

        doThrow(new TokenRefreshException("failed")).when(tokenRefresher).refreshOAuth2Token();

        task.doInBackground(config);

        verify(tokenRefresher, times(1)).refreshOAuth2Token();
        verify(service).transition(SmsSyncState.ERROR, exception);

        // make sure locks only get acquired+released once
        verify(service).acquireLocks();
        verify(service).releaseLocks();
    }

    @Test public void shouldHandleAuthErrorAndTokenCouldBeRefreshed() throws Exception {
        mockFetch(SMS, 1);
        when(converter.convertMessages(any(Cursor.class), notNull(DataType.class))).thenReturn(result(SMS, 1));

        XOAuth2AuthenticationFailedException exception = mock(XOAuth2AuthenticationFailedException.class);
        when(exception.getStatus()).thenReturn(400);

        when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenThrow(exception);
        when(service.getBackupImapStore()).thenReturn(store);

        task.doInBackground(config);

        verify(tokenRefresher).refreshOAuth2Token();

        verify(service, times(2)).transition(SmsSyncState.LOGIN, null);
        verify(service, times(2)).transition(SmsSyncState.CALC, null);
        verify(service).transition(SmsSyncState.ERROR, exception);

        // make sure locks only get acquired+released once
        verify(service).acquireLocks();
        verify(service).releaseLocks();
    }

    private ConversionResult result(DataType type, int n) {
        ConversionResult result = new ConversionResult(type);
        for (int i = 0; i<n; i++) {
            result.add(new MimeMessage(), new HashMap<String, String>());
        }
        return result;
    }

    private void mockFetch(DataType type, final int n) {
        when(fetcher.getItemsForDataType(eq(type), any(ContactGroupIds.class), anyInt())).then(new Answer<Object>() {
            @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                return testMessages(n);
            }
        });
    }

    private Cursor testMessages(int n) {
        MatrixCursor cursor = new MatrixCursor(new String[] {"_id"} );
        for (int i = 0; i < n; i++) {
            cursor.addRow(new Object[]{
                    "12345"
            });
        }
        return cursor;
    }

    private void mockAllFetchEmpty() {
        when(fetcher.getItemsForDataType(any(DataType.class), any(ContactGroupIds.class), anyInt())).thenReturn(emptyCursor());
    }
}


text:
require 'test_helper'

class AzCompaniesHelperTest < ActionView::TestCase
end


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;

#if PUBLICPROTOCOL
namespace Microsoft.Azure.WebJobs.Protocols
#else
namespace Microsoft.Azure.WebJobs.Host.Protocols
#endif
{
    /// Represents a function parameter log for a read-only blob parameter.
    [JsonTypeName("ReadBlob")]
#if PUBLICPROTOCOL
    public class ReadBlobParameterLog : ParameterLog
#else
    internal class ReadBlobParameterLog : ParameterLog
#endif
    {
        /// Gets or sets the number of bytes read.
        public long BytesRead { get; set; }

        /// Gets or sets the total number of bytes available to read.
        public long Length { get; set; }

        /// Gets or sets the approximate amount of time spent performing I/O.
        public TimeSpan ElapsedTime { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace AKW_Simulator
{
    static class Program
    {
        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.Run(new hauptfenster());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Es ist ein Fehler aufgetreten und das Programm muss beendet werden.\n\n Weitere Fehlerinformationen: " + ex.Message,
                                "Fehler!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                Environment.Exit(0);
            }
        }
    }
}


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

/**
 * Message Waiting Indication Group: Discard Message. Message may be discarded.
 *
 * @author uudashr
 *
 */
public class DataCodingFactory1100 extends AbstractDataCodingFactory {
    /**
     * bin: 1111xxxx
     */
    public static final byte MASK = (byte)0xf0; //

    /**
     * bin: 1100xxxx
     */
    public static final byte GROUP = (byte)0xc0; //

    public DataCodingFactory1100() {
        super(MASK, GROUP);
    }

    public DataCoding newInstance(byte dataCoding) {
        /*
         * Mobile may discard the contents of the message, and only present the
         * indication to the user.
         */
        IndicationSense indicationSense = IndicationSense.parseDataCoding(dataCoding);
        IndicationType indicationType = IndicationType.parseDataCoding(dataCoding);
        return new MessageWaitingDataCoding(indicationSense, indicationType, null);
    }
}


text:
package hextostring.evaluate.string;

import hextostring.evaluate.Evaluator;

/**
 * Abstract evaluator for non hexadecimal strings.
 *
 * @author Maxime PIA
 */
public abstract class StringEvaluator implements Evaluator<String> {

	// an invalid character reduces the validity of the string
	public static final int INVALID_CHARS_MALUS = 4;

}


text:
package org.apache.lucene.search;

import java.io.IOException;
import java.util.Objects;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.ToStringUtils;

/**
 * This is a {@link PhraseQuery} which is optimized for n-gram phrase query.
 * For example, when you query "ABCD" on a 2-gram field, you may want to use
 * NGramPhraseQuery rather than {@link PhraseQuery}, because NGramPhraseQuery
 * will {@link #rewrite(IndexReader)} the query to "AB/0 CD/2", while {@link PhraseQuery}
 * will query "AB/0 BC/1 CD/2" (where term/position).
 *
 */
public class NGramPhraseQuery extends Query {

  private final int n;
  private final PhraseQuery phraseQuery;

  /**
   * Constructor that takes gram size.
   * @param n n-gram size
   */
  public NGramPhraseQuery(int n, PhraseQuery query) {
    super();
    this.n = n;
    this.phraseQuery = Objects.requireNonNull(query);
  }

  @Override
  public Query rewrite(IndexReader reader) throws IOException {
    if (getBoost() != 1f) {
      return super.rewrite(reader);
    }
    final Term[] terms = phraseQuery.getTerms();
    final int[] positions = phraseQuery.getPositions();

    boolean isOptimizable = phraseQuery.getSlop() == 0
        && n >= 2 // non-overlap n-gram cannot be optimized
        && terms.length >= 3; // short ones can't be optimized

    if (isOptimizable) {
      for (int i = 1; i < positions.length; ++i) {
        if (positions[i] != positions[i-1] + 1) {
          isOptimizable = false;
          break;
        }
      }
    }

    if (isOptimizable == false) {
      return phraseQuery.rewrite(reader);
    }

    PhraseQuery.Builder builder = new PhraseQuery.Builder();
    for (int i = 0; i < terms.length; ++i) {
      if (i % n == 0 || i == terms.length - 1) {
        builder.add(terms[i], i);
      }
    }
    return builder.build();
  }

  @Override
  public boolean equals(Object o) {
    if (super.equals(o) == false) {
      return false;
    }
    NGramPhraseQuery other = (NGramPhraseQuery) o;
    return n == other.n && phraseQuery.equals(other.phraseQuery);
  }

  @Override
  public int hashCode() {
    int h = super.hashCode();
    h = 31 * h + phraseQuery.hashCode();
    h = 31 * h + n;
    return h;
  }

  /** Return the list of terms. */
  public Term[] getTerms() {
    return phraseQuery.getTerms();
  }

  /** Return the list of relative positions that each term should appear at. */
  public int[] getPositions() {
    return phraseQuery.getPositions();
  }

  @Override
  public String toString(String field) {
    return phraseQuery.toString(field) + ToStringUtils.boost(getBoost());
  }
}


text:
title: "2015-02-02のJS: 6to5 Ver3.0、CoffeeScript 1.9.0、PhantomJS 2.0"
author: azu
layout: post
date : 2015-02-02T20:09
category: JSer
tags:
    - ES6
    - CoffeeScript
    - webkit

---

JSer.info #213 - ES6+αのコードをES5へ変換するツールである6to5のVer3.0がリリースされました。(現在[3.3.4](https://github.com/6to5/6to5/blob/v3.3.4/CHANGELOG.md "3.3.4")まででています)

- [2to3 · 6to5](http://6to5.org/blog/2015/01/27/2to3/ "2to3 · 6to5")

オプションを削除やリネームし整理していて、また[Transformers](http://6to5.org/docs/usage/transformers/ "Transformers")について互換性のない変更が含まれています。

また6to5プロジェクトとして、ES6とES5に限定してるように見える名前の変更や、今後フォーカスを当てていく箇所についての意見を募集しているようです。

- [Name suggestions · Issue #596 · 6to5/6to5](https://github.com/6to5/6to5/issues/596)
- [Project scope and future · Issue #568 · 6to5/6to5](https://github.com/6to5/6to5/issues/568 "Project scope and future · Issue #568 · 6to5/6to5")

----

[CoffeeScript](http://coffeescript.org/#1.9.0 "CoffeeScript") 1.9.0がリリースされました。

Generatorの構文をサポートやパースエラー等のエラーメッセージが改善されました。

- [CoffeeScriptが1.9でgenerator構文をサポート - Qiita](http://qiita.com/mizchi/items/39906871bc0a532b6e71 "CoffeeScriptが1.9でgenerator構文をサポート - Qiita")

----

ヘッドレスブラウザの[PhantomJS 2.0](http://phantomjs.org/release-2.0.html "PhantomJS 2.0")がリリースされました。

またダウンロード出来る一部バイナリがおかしいですが、Qt5へのアップデートをしたためQtWebKitも更新されています。

- [Release of PhantomJS 2.0 · Issue #12897 · ariya/phantomjs](https://github.com/ariya/phantomjs/issues/12897#issuecomment-71651159 "Release of PhantomJS 2.0 · Issue #12897 · ariya/phantomjs")

Qtでは[QtWebEngine](http://qt-project.org/wiki/QtWebEngine "QtWebEngine")というChromiumベースのがあるため、今後のアップデートでここも変わるかもしれません。

----

ヘッドライン

----

## React v0.13.0 Beta 1 | React
[facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html](http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html "React v0.13.0 Beta 1 | React")

React ReleaseNote

React 0.13 β1リリース。
ES6 ClassでReact.Componentを書けるように

----

## 2to3 · 6to5
[6to5.org/blog/2015/01/27/2to3](https://6to5.org/blog/2015/01/27/2to3 "2to3 · 6to5")

JavaScript Tools React

6to5 3.0リリース。
コマンドラインオプションに`--blacklist`と`--whitelist`の追加、パフォーマンス改善、細かいオプションの変更等。

- [Name suggestions · Issue #596 · 6to5/6to5](https://github.com/6to5/6to5/issues/596 "Name suggestions · Issue #596 · 6to5/6to5")

----

## CoffeeScript
[coffeescript.org](http://coffeescript.org "CoffeeScript")

CoffeeScript ReleaseNote

CoffeeScript 1.9.0リリース。
ES6 generatorsのサポート

----

## Node v0.10.36 (Stable)
[blog.nodejs.org/2015/01/26/node-v0-10-36-stable/](http://blog.nodejs.org/2015/01/26/node-v0-10-36-stable/ "Node v0.10.36 (Stable)")

node.js ReleaseNote

Node v0.10.36リリース。

----

## Dev.Opera — Opera 27 released
[dev.opera.com/blog/opera-27/](https://dev.opera.com/blog/opera-27/ "Dev.Opera — Opera 27 released")

Opera ReleaseNote

Opera 27(based on Chromium 40)リリース。
minlength属性、form要素の`reportValidity()`の実装、CSP Lv2の実装、Service Workers等

----

## PhantomJS 2.0 Release Notes | PhantomJS
[phantomjs.org/release-2.0.html](http://phantomjs.org/release-2.0.html "PhantomJS 2.0 Release Notes | PhantomJS")

browser ReleaseNote

ヘッドレスブラウザのPhantomJS 2.0リリース。QtとWebKitのアップデート、CoffeeScriptのデフォルトサポートを廃止

----

アーティクル

----

## Replace CoffeeScript with ES6
[robots.thoughtbot.com/replace-coffeescript-with-es6](http://robots.thoughtbot.com/replace-coffeescript-with-es6 "Replace CoffeeScript with ES6")

CoffeeScript JavaScript

CoffeeScriptのSyntaxをES6に書き換える方法について
[eventualbuddha/decaffeinate](https://github.com/eventualbuddha/decaffeinate "eventualbuddha/decaffeinate")のようなツールではなくて、どういう対応のコードを示しながら解説している。

----

## New string features in ECMAScript 6
[www.2ality.com/2015/01/es6-strings.html](http://www.2ality.com/2015/01/es6-strings.html "New string features in ECMAScript 6")

JavaScript ECMAScript

ES6で追加されるString系のメソッドについて。
Template strings、ユニコードコードポイントを正しく扱う方法、追加された便利メソッドについて

----

## Surfin' Safari - Blog Archive » Building WebKit for iOS Simulator
[www.webkit.org/blog/3457/building-webkit-for-ios-simulator/](https://www.webkit.org/blog/3457/building-webkit-for-ios-simulator/ "Surfin' Safari - Blog Archive » Building WebKit for iOS Simulator")

ios safari

iOSシミュレータ向けにWebKitをビルド出来るように

----

## Canvas 2D: New docs, Path2D objects, hit regions ✩ Mozilla Hacks – the Web developer blog
[hacks.mozilla.org/2015/01/canvas-2d-new-docs-path2d-hit-regions/](http://hacks.mozilla.org/2015/01/canvas-2d-new-docs-path2d-hit-regions/ "Canvas 2D: New docs, Path2D objects, hit regions ✩ Mozilla Hacks – the Web developer blog")

canvas

Canvas 2Dの機能として追加されたPath2Dについて

----

スライド、動画関係

----

## 最近のASTパーサの動き
[azu.github.io/slide/crosushi/shift-ast.html](http://azu.github.io/slide/crosushi/shift-ast.html "最近のASTパーサの動き")

JavaScript AST スライド

Esprima/Esprima-FB/espree、Shift AST、acorn/acorn-6to5とかのJS ASTパーサの近況についてのスライド。
EsprimaがjQuery Foundationに移管した話についてなど

----

## React.js Conf | January 28 & 29 2015
[conf.reactjs.com/schedule.html](http://conf.reactjs.com/schedule.html "React.js Conf | January 28 & 29 2015")

React イベント 動画

React.js Confの動画まとめ

----

## React in 7 Minutes - React Video Tutorial #free @eggheadio
[egghead.io/lessons/react-react-in-7-minutes](https://egghead.io/lessons/react-react-in-7-minutes "React in 7 Minutes - React Video Tutorial #free @eggheadio")

React 動画

7分で分かるReact Componentのスクリーンキャスト。
JSX、Componentのネスト、stateとprops、イベントハンドラについて

----

ソフトウェア、ツール、ライブラリ関係

----

## MaxArt2501/object-observe
[github.com/MaxArt2501/object-observe](https://github.com/MaxArt2501/object-observe "MaxArt2501/object-observe")

JavaScript library

Object.observeの限定的なpolyfill

----

## Contracts.js
[www.contractsjs.org/](http://www.contractsjs.org/ "Contracts.js")

sweet.js JavaScript

sweet.jsを使った実行時型チェック的な機能を提供するマクロ

----

## is.js - micro check library
[arasatasaygin.github.io/is.js/](http://arasatasaygin.github.io/is.js/ "is.js - micro check library")

JavaScript library

`is.*`というメソッドで色々な種類の値をチェック出来るライブラリ。
型や正規表現、環境、時間等

----

## Fluxible | A Pluggable Container for Isomorphic Flux Applications | Fluxible
[www.fluxible.io/](http://www.fluxible.io/ "Fluxible | A Pluggable Container for Isomorphic Flux Applications | Fluxible")

JavaScript Flux library

Yahoo製のFlux実装ライブラリ。

----

## Ramda Documentation
[ramdajs.com/](http://ramdajs.com/ "Ramda Documentation")

JavaScript 関数型プログラミング library

Underscore.jsやlodashよりも関数型スタイル向けに沿った作りとする事を目的としたライブラリ。
Immutable、副作用の排除、関数同士を組み合わせしやすいようなインターフェースにしているのが特徴。

----

## Home | marty.js
[martyjs.org/](http://martyjs.org/ "Home | marty.js")

JavaScript Flux library

Fluxアーキテクチャ実装のライブラリ。
基本的なStore、Dispatcher、Actionがあり、追加でConstant値の作成、Storageを指定して管理出来るStateが用意されてる。
Chromeのデバッグで流れを見られるようになってる

----

## israelidanny/ie8linter
[github.com/israelidanny/ie8linter](https://github.com/israelidanny/ie8linter "israelidanny/ie8linter")

IE Tools browser

IE8でサポートしてないタグやCSSプロパティ等を検出するツール。

----

## douglasduteil/isparta
[github.com/douglasduteil/isparta](https://github.com/douglasduteil/isparta "douglasduteil/isparta")

JavaScript Tools

istanbulと6to5を使ったES6のコードカバレッジツール。

----

## timoxley/pkgfiles
[github.com/timoxley/pkgfiles](https://github.com/timoxley/pkgfiles "timoxley/pkgfiles")

npm Tools

npm publishでどのファイルが公開されるのかをチェック出来るツール

----


text:
<?php

namespace Gerencianet;

class Config
{
    /**
     * @var string Arquivo de configuração dos endpoints
     */
    private static $endpointsConfigfile = __DIR__ . '/config.json';

    /**
     * Altera arquivo de configuração
     * @param string $file Caminho do arquivo
     */
    public static function setEndpointsConfigFile($file)
    {
        self::$endpointsConfigfile = $file;
    }

    /**
     * Carrega as configurações do arquivo de endpoints
     * @param string $property Chave do parâmetro
     * @return mixed
     */
    public static function get($property)
    {
        $file = file_get_contents(self::$endpointsConfigfile);
        $config = json_decode($file, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception('Error loading endpoint file');
        }

        if (isset($config[$property])) {
            return $config[$property];
        } else {
            return $config['APIs'][$property];
        }

        return;
    }

    public static function options($options)
    {
        $conf = [];
        $conf['sandbox'] = isset($options['sandbox']) ? $options['sandbox'] : false;
        $conf['debug'] = isset($options['debug']) ? $options['debug'] : false;

        if (isset($options['client_id'])) {
            $conf['clientId'] = $options['client_id'];
        }

        if (isset($options['client_secret'])) {
            $conf['clientSecret'] = $options['client_secret'];
        }

        if (isset($options['timeout'])) {
            $conf['timeout'] = $options['timeout'];
        }

        if (isset($options['headers'])) {
            $conf['headers'] = $options['headers'];
        }

        if (isset($options['url'])) {
            $conf['baseUri'] = $options['url'];
        }

        if ($options['api'] !== 'DEFAULT') {
            $conf['certificate'] = (isset($options['certificate']) ? $options['certificate'] : $options['pix_cert']);
        }

        if ($conf['debug']) {
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL);
        }

        return $conf;
    }
}


text:
Plugin.define "SillySmart" do
author "Guillaume Delacour <gui@iroqwa.org>" # 2015-07-09
version "0.1"
description "SillySmart is a lightweight and flexible MVC Framework written in PHP5 based on XML/XSL's parsing."

# Dorks #
dorks [
'intext:"var slsBuild ="',
]

# Matches #
matches [
{ :certainty=>85, :text=>'var slsBuild' },
]

end


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<TITLE>CLHS: Issue EVAL-WHEN-OBSOLETE-KEYWORDS:X3J13-MAR-1993 Summary</TITLE>
<META HTTP-EQUIV="Author" CONTENT="Kent M. Pitman">
<META HTTP-EQUIV="Organization" CONTENT="The Harlequin Group Limited">
<LINK REL=TOP HREF="../FrontMatter/index.html">
<LINK REL=COPYRIGHT HREF="../FrontMatter/About-HyperSpec.html#Legal">
<LINK REL=DISCLAIMER HREF="../FrontMatter/About-HyperSpec.html#Disclaimer">
<LINK REL=PREV HREF="../Issues/iss147.html">
<LINK REL=UP HREF="../Issues/Issues-Alphabetical.html">
<LINK REL=NEXT HREF="../Issues/iss149.html">

Issue EVAL-WHEN-OBSOLETE-KEYWORDS:X3J13-MAR-1993 Summary

These passages are relevant to issue <TT>EVAL-WHEN-OBSOLETE-KEYWORDS:X3J13-MAR-1993</TT>:

Deprecated Argument Conventions

Special Operator EVAL-WHEN

Copyright 1996, The Harlequin Group Limited.  All Rights Reserved.


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose       = require('mongoose'),
	slugPlugin     = require('mongoose-url-slugs'),
	filePlugin     = require('mongoose-file').filePlugin,
	paginatePlugin = require('mongoose-paginate'),
	l2rPlugin      = require('mongoose-l2r'),
	crypto	       = require('crypto'),
	path           = require('path'),
	lwip           = require('lwip'),
	Schema 	       = mongoose.Schema;

/**
 * A Validation function for local strategy properties
 */
var validateLocalStrategyProperty = function(property) {
	return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
 * A Validation function for local strategy password
 */
var validateLocalStrategyPassword = function(password) {
	return (this.provider !== 'local' || (password && password.length >= 8));
};

var makeUploadToModel = function(basedir, subdir) {
	var b_dir, s_dir, upload_to_model;

	b_dir = basedir;
    s_dir = subdir;

	upload_to_model = function(fileObj) {
      	var dstdir, id;

		dstdir = b_dir;
      	if (s_dir) {
			dstdir = path.join(dstdir, s_dir);
      	}
      	id = this.get('id');
      	if (id) {
			dstdir = path.join(dstdir, id + '.' + fileObj.extension.toLowerCase());
		} else {
			dstdir = path.join(dstdir, fileObj.name);
		}
      	return dstdir;
    };
    return upload_to_model;
};

var generateAvatarImages = function(pathname, imgFile, oldValue) {
	var fileExt  = path.extname(imgFile),
		fileName = path.dirname(imgFile) + path.sep + path.basename(imgFile, fileExt);

	var generate_image = function(srcFile, dstFile, resizeSize, callback) {
		lwip.open(srcFile, function(err, image) {
			if (err) throw err;

			// Crop to make a square image
			var cropSize = (image.width() > image.height() ) ? image.height() : image.width();

			image.batch()
				.crop(cropSize, cropSize)
				.resize(resizeSize, resizeSize)
				.writeFile(dstFile, function(err) {
					if (callback && typeof callback === 'function') {
						callback(err);
					} else {
						if (err) throw err;
					}
				});
		});
	};

	// Crop and resize the image into supported sizes
	generate_image(imgFile, fileName + '-bg' + fileExt, 256, function(err) {
		generate_image(imgFile, fileName + '-md' + fileExt, 128, function(err) {
			generate_image(imgFile, fileName + '-sm' + fileExt, 48, function(err) {
				if (err) throw err;
			});
		});
	});
};

/**
 * Creates a new Person.
 * @class Person
 */

/**
 * User Schema
 */
var UserSchema = new Schema({
	firstName: {
		type: String,
		trim: true,
		default: '',
		validate: [validateLocalStrategyProperty, 'Please fill in your first name']
	},
	lastName: {
		type: String,
		trim: true,
		default: '',
		validate: [validateLocalStrategyProperty, 'Please fill in your last name']
	},
	displayName: {
		type: String,
		trim: true
	},
	email: {
		type: String,
		trim: true,
		default: '',
		validate: [validateLocalStrategyProperty, 'Please fill in your email'],
		match: [/.+\@.+\..+/, 'Please fill a valid email address']
	},
	username: {
		type: String,
		unique: 'Username is not available. Please select another one.',
		required: 'Please fill in a username',
		trim: true
	},
	homeAddress: {
		type: String,
		trim: true
	},
	password: {
		type: String,
		default: '',
		validate: [validateLocalStrategyPassword, 'Password should be longer'],
	},
	salt: {
		type: String,
	},
	provider: {
		type: String,
		required: 'Provider is required'
	},
	providerData: {
		select: false
	},
	additionalProvidersData: {
		select: false
	},
	roles: {
		type: [{
			type: String,
			enum: ['user', 'premium', 'admin', 'request-suspend']
		}],
		default: [],
		select: true
	},
	updated: {
		type: Date
	},
	created: {
		type: Date,
		default: Date.now
	},
	/* For reset password */
	resetPasswordToken: {
		type: String,
		select: false
	},
	resetPasswordExpires: {
		type: Date,
		select: false
	}
});

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function(next) {
	if (this.password && this.password.length > 6) {
		this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
		this.password = this.hashPassword(this.password);
	}

	next();
});

/**
* Hook a pre save method to modify udpated date.
*/
UserSchema.pre('save', function(next) {
	if (this._id) {
		this.updated = new Date();
	}

	next();
});

/**
 * Create instance method for hashing a password
 */
UserSchema.methods.hashPassword = function(password) {
	if (this.salt && password) {
		return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
	} else {
		return password;
	}
};

/**
 * Create instance method for authenticating user
 */
UserSchema.methods.authenticate = function(password) {
	return this.password === this.hashPassword(password);
};

/**
 * Find possible not used username
 */
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
	var _this = this;
	var possibleUsername = username + (suffix || '');

	_this.findOne({
		username: possibleUsername
	}, function(err, user) {
		if (!err) {
			if (!user) {
				callback(possibleUsername);
			} else {
				return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
			}
		} else {
			callback(null);
		}
	});
};

/**
 * Create instance method for check if an user is platform admin
 */
UserSchema.methods.isAdmin = function() {
	return (this.roles.indexOf('admin') !== -1);
};

/**
 * Add plugins to User schema.
 */
// Slug plugin
UserSchema.plugin(slugPlugin('username', {field: 'name'}));

// Paginate plugin
UserSchema.plugin(paginatePlugin);

// L2r plugin
UserSchema.plugin(l2rPlugin);

// file plugin
var uploads_base = path.join(__dirname, '../../'),
	uploads 	 = path.join(uploads_base, 'uploads');

UserSchema.plugin(filePlugin, {
	name:        'avatar',
	change_cb:   generateAvatarImages,
	upload_to:   makeUploadToModel(uploads, 'avatars'),
	relative_to: uploads_base
});

// Compile a 'User' model using the UserSchema as the structure.
// Mongoose also creates a MongoDB collection called 'users' for these documents.
//
// Notice that the 'User' model is capitalized, this is because when a model is compiled,
// the result is a constructor function that is used to create instances of the model.
// The instances created from the model constructor are documents which will be persisted
// by Mongo.
mongoose.model('User', UserSchema);


text:
import {BaseHarnessFilters} from '@angular/cdk/testing';

/** A set of criteria that can be used to filter a list of `MatTabHarness` instances. */
export interface TabHarnessFilters extends BaseHarnessFilters {
  /** Only find instances whose label matches the given value. */
  label?: string | RegExp;
  /** Only find instances whose selected state matches the given value. */
  selected?: boolean;
}

/** A set of criteria that can be used to filter a list of `MatTabGroupHarness` instances. */
export interface TabGroupHarnessFilters extends BaseHarnessFilters {
  /** Only find instances whose selected tab label matches the given value. */
  selectedTabLabel?: string | RegExp;
}

/** A set of criteria that can be used to filter a list of `MatTabLinkHarness` instances. */
export interface TabLinkHarnessFilters extends BaseHarnessFilters {
  /** Only find instances whose label matches the given value. */
  label?: string | RegExp;
}

/** A set of criteria that can be used to filter a list of `MatTabNavBarHarness` instances. */
export interface TabNavBarHarnessFilters extends BaseHarnessFilters {}

/** A set of criteria that can be used to filter a list of `MatTabNavPanelHarness` instances. */
export interface TabNavPanelHarnessFilters extends BaseHarnessFilters {}


text:
`lx-wrapper-errors` adds validation messages to your field.

Use `formlyValidationMessages.addStringMessage(NAME, MESSAGE)` to add custom validation messages.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gov.hhs.fha.nhinc.taskmanagerclient;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * Task message for notifying external process of task to perform.
 *
 * @author cmatser
 */
public class TaskHandlerMessage
        implements java.io.Serializable {
    private String taskTicket;
    private HashMap<String,String> taskAttributes;
    private String taskID;
    private String taskDescription;
    private String subject;
    private String message;
    private String priority;
    private List<ContactDetails> providers;
    private List<ContactDetails> escalationProviders;
    private Integer escalationMinutes;
    private Date deliveryDate;
    private Date completionDate;
    private String patientUnitNumber;
    private String patientName;
    private String patientSex;
    private String patientFMPSSN;
    private String factNCID;
    private String factName;
    private String factValue;
    private String factType;
    private String actionID;
    private String actionType;
    private String ruleID;
    private String ruleDesc;
    private String ruleName;

    /**
     * @return the taskTicket
     */
    public String getTaskTicket() {
        return taskTicket;
    }

    /**
     * @param taskTicket the taskTicket to set
     */
    public void setTaskTicket(String taskTicket) {
        this.taskTicket = taskTicket;
    }

    /**
     * @return the taskAttributes
     */
    public HashMap<String, String> getTaskAttributes() {
        return taskAttributes;
    }

    /**
     * @param taskAttributes the taskAttributes to set
     */
    public void setTaskAttributes(HashMap<String, String> taskAttributes) {
        this.taskAttributes = taskAttributes;
    }

    /**
     * @return the taskID
     */
    public String getTaskID() {
        return taskID;
    }

    /**
     * @param taskID the taskID to set
     */
    public void setTaskID(String taskID) {
        this.taskID = taskID;
    }

    /**
     * @return the taskDescription
     */
    public String getTaskDescription() {
        return taskDescription;
    }

    /**
     * @param taskDescription the taskDescription to set
     */
    public void setTaskDescription(String taskDescription) {
        this.taskDescription = taskDescription;
    }

    /**
     * @return the subject
     */
    public String getSubject() {
        return subject;
    }

    /**
     * @param subject the subject to set
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the priority
     */
    public String getPriority() {
        return priority;
    }

    /**
     * @param priority the priority to set
     */
    public void setPriority(String priority) {
        this.priority = priority;
    }

    /**
     * @return the providers
     */
    public List<ContactDetails> getProviders() {
        if (providers == null) {
            providers = new LinkedList<ContactDetails>();
        }

        return providers;
    }

    /**
     * @param providers the providers to set
     */
    public void setProviders(List<ContactDetails> providers) {
        this.providers = providers;
    }

    /**
     * @return the escalationProviders
     */
    public List<ContactDetails> getEscalationProviders() {
        if (escalationProviders == null) {
            escalationProviders = new LinkedList<ContactDetails>();
        }

        return escalationProviders;
    }

    /**
     * @param escalationProviders the escalationProviders to set
     */
    public void setEscalationProviders(List<ContactDetails> escalationProviders) {
        this.escalationProviders = escalationProviders;
    }

    /**
     * @return the escalationMinutes
     */
    public Integer getEscalationMinutes() {
        return escalationMinutes;
    }

    /**
     * @param escalationMinutes the escalationMinutes to set
     */
    public void setEscalationMinutes(Integer escalationMinutes) {
        this.escalationMinutes = escalationMinutes;
    }

    /**
     * @return the deliveryDate
     */
    public Date getDeliveryDate() {
        return deliveryDate;
    }

    /**
     * @param deliveryDate the deliveryDate to set
     */
    public void setDeliveryDate(Date deliveryDate) {
        this.deliveryDate = deliveryDate;
    }

    /**
     * @return the completionDate
     */
    public Date getCompletionDate() {
        return completionDate;
    }

    /**
     * @param completionDate the completionDate to set
     */
    public void setCompletionDate(Date completionDate) {
        this.completionDate = completionDate;
    }

    /**
     * @return the patientUnitNumber
     */
    public String getPatientUnitNumber() {
        return patientUnitNumber;
    }

    /**
     * @param patientUnitNumber the patientUnitNumber to set
     */
    public void setPatientUnitNumber(String patientUnitNumber) {
        this.patientUnitNumber = patientUnitNumber;
    }

    /**
     * @return the patientName
     */
    public String getPatientName() {
        return patientName;
    }

    /**
     * @param patientName the patientName to set
     */
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }

    /**
     * @return the patientSex
     */
    public String getPatientSex() {
        return patientSex;
    }

    /**
     * @param patientSex the patientSex to set
     */
    public void setPatientSex(String patientSex) {
        this.patientSex = patientSex;
    }

    /**
     * @return the patientFMPSSN
     */
    public String getPatientFMPSSN() {
        return patientFMPSSN;
    }

    /**
     * @param patientFMPSSN the patientFMPSSN to set
     */
    public void setPatientFMPSSN(String patientFMPSSN) {
        this.patientFMPSSN = patientFMPSSN;
    }

    /**
     * @return the factNCID
     */
    public String getFactNCID() {
        return factNCID;
    }

    /**
     * @param factNCID the factNCID to set
     */
    public void setFactNCID(String factNCID) {
        this.factNCID = factNCID;
    }

    /**
     * @return the factName
     */
    public String getFactName() {
        return factName;
    }

    /**
     * @param factName the factName to set
     */
    public void setFactName(String factName) {
        this.factName = factName;
    }

    /**
     * @return the factValue
     */
    public String getFactValue() {
        return factValue;
    }

    /**
     * @param factValue the factValue to set
     */
    public void setFactValue(String factValue) {
        this.factValue = factValue;
    }

    /**
     * @return the factType
     */
    public String getFactType() {
        return factType;
    }

    /**
     * @param factType the factType to set
     */
    public void setFactType(String factType) {
        this.factType = factType;
    }

    /**
     * @return the actionID
     */
    public String getActionID() {
        return actionID;
    }

    /**
     * @param actionID the actionID to set
     */
    public void setActionID(String actionID) {
        this.actionID = actionID;
    }

    /**
     * @return the actionType
     */
    public String getActionType() {
        return actionType;
    }

    /**
     * @param actionType the actionType to set
     */
    public void setActionType(String actionType) {
        this.actionType = actionType;
    }

    /**
     * @return the ruleID
     */
    public String getRuleID() {
        return ruleID;
    }

    /**
     * @param ruleID the ruleID to set
     */
    public void setRuleID(String ruleID) {
        this.ruleID = ruleID;
    }

    /**
     * @return the ruleDesc
     */
    public String getRuleDesc() {
        return ruleDesc;
    }

    /**
     * @param ruleDesc the ruleDesc to set
     */
    public void setRuleDesc(String ruleDesc) {
        this.ruleDesc = ruleDesc;
    }

    /**
     * @return the ruleName
     */
    public String getRuleName() {
        return ruleName;
    }

    /**
     * @param ruleName the ruleName to set
     */
    public void setRuleName(String ruleName) {
        this.ruleName = ruleName;
    }

}


text:
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Authentication
{
    public enum ServiceClaim
    {
        DAA = 40,
        DAB = 30,
        DAC = 20,
        DAV = 10
    }
}


text:
class AdminController < ApplicationController
  http_basic_authenticate_with name: "cemi", password: "cemi85"
end


text:
@implementation NSLayoutConstraint (AutoLayout)

- (void)ad_installWithPriority:(UILayoutPriority)priority {
    self.priority = priority;
    if (self.firstItem && !self.secondItem) {
        [self.firstItem addConstraint:self];
    } else if (self.firstItem && self.secondItem) {
        UIView *commonSuperView = [self.firstItem ad_commonSuperViewWithView:self.secondItem];
        [commonSuperView addConstraint:self];
    }
}

- (void)ad_installConstraint {
    [self ad_installWithPriority:UILayoutPriorityRequired];
}

+ (void)ad_installConstraints:(NSArray <NSLayoutConstraint *> *)constraints {
    for (id object in constraints) {
        if ([object isKindOfClass:[NSLayoutConstraint class]]) {
            [((NSLayoutConstraint *) object) ad_installConstraint];
        } else if ([object isKindOfClass:[NSArray class]]) {
            [NSLayoutConstraint ad_installConstraints:object];
        }
    }
}

- (void)ad_removeConstraint {
    if (self.secondItem) {
        UIView *commonSuperview = [self.firstItem ad_commonSuperViewWithView:self.secondItem];
        while (commonSuperview) {
            if ([commonSuperview.constraints containsObject:self]) {
                [commonSuperview removeConstraint:self];
                return;
            }
            commonSuperview = commonSuperview.superview;
        }
    } else {
        [self.firstItem removeConstraint:self];
    }
}

+ (void)ad_removeConstraints:(NSArray <NSLayoutConstraint *> *)constraints {
    for (id object in constraints) {
        if ([object isKindOfClass:[NSLayoutConstraint class]]) {
            [((NSLayoutConstraint *) object) ad_removeConstraint];
        } else if ([object isKindOfClass:[NSArray class]]) {
            [NSLayoutConstraint ad_removeConstraints:object];
        }
    }
}

@end