text:
module Autoini
  class Section < Element
    include InlineComment

    attr_accessor :title
    attr_reader   :lines

    def initialize(title, *contents)
      @title = title
      @lines = []
      self << contents
    end

    def self.[](title, hash)
      raise ArgumentError, "must pass a hash" unless hash.is_a?(Hash)
      new title, *hash.map{ |k, v| Pair.new(k, v) }
    end

    def <<(contents)
      Autoini.wrap(contents).each do |c|
        unless c.is_a?(AbstractLine)
          raise ArgumentError, "#{c.class.name} must extend Autoini::AbstractLine"
        end
        @lines << c
      end
    end

    def to_s
      [line_comment("[#{title}]"), lines.map(&:to_s)].flatten.join(Autoini.newline)
    end

    def to_a
      [title.to_sym, lines.map(&:to_a).reject(&:empty?).to_h]
    end

    def ==(e)
      e.is_a?(Section) && e.title == title && e.comment == comment &&
        e.lines.length == lines.length &&
        lines.map.with_index{ |l, i| e.lines[i] == l }.all?
    end

    def pair(key)
      lines.select{ |l| l.is_a?(Pair) && l.key.to_s == key.to_s }.first
    end

    def merge!(other_section)
      unless other_section.is_a?(Section)
        raise ArgumentError, "must pass a Autoini::Section"
      end
      other_section.lines.each do |l|
        next unless l.is_a?(Pair)
        if p = pair(l.key)
          p.value = l.value
        else
          self << l
        end
      end
      self
    end

    def self.parse(line)
      Section.new(line[1]) if line.length == 3 && line[0] == '[' && line[2] == ']'
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import { connect } from 'react-redux'
import { TransitionGroup, Transition } from 'transition-group'
import universal from 'react-universal-component'

import Loading from './Loading'
import Err from './Error'
import isLoading from '../selectors/isLoading'
import styles from '../css/Switcher'

const UniversalComponent = universal(({ page }) => import(`./${page}`), {
  minDelay: 500,
  loading: Loading,
  error: Err,
})

const Switcher = ({ page, direction, isLoading }) =>
  <TransitionGroup
    className={`${styles.switcher} ${direction}`}
    duration={500}
    prefix='fade'
  >
    <Transition key={page}>
      <UniversalComponent page={page} isLoading={isLoading} />
    </Transition>
  </TransitionGroup>

const mapState = ({ page, direction, ...state }) => ({
  page,
  direction,
  isLoading: isLoading(state),
})

export default connect(mapState)(Switcher)


text:
var gutil = require('gulp-util');

/**
 * @param {string} color [black, red, green, yellow, blue, magenta, cyan, white, gray]
 * @param {string[]} messages
 */
function colorLog(color, messages){
    var colorMethod = gutil.colors[color];
    var coloredMessages = colorMethod.apply(this, messages);
    gutil.log(coloredMessages);
}

function argumentsToArray(args){
    return Array.prototype.slice.call(args);
}

var Log = function(){
    gutil.log.apply(this, argumentsToArray(arguments));
};
Log.black =   function(){ colorLog('black',   argumentsToArray(arguments)); };
Log.red =     function(){ colorLog('red',     argumentsToArray(arguments)); };
Log.green =   function(){ colorLog('green',   argumentsToArray(arguments)); };
Log.yellow =  function(){ colorLog('yellow',  argumentsToArray(arguments)); };
Log.blue =    function(){ colorLog('blue',    argumentsToArray(arguments)); };
Log.magenta = function(){ colorLog('magenta', argumentsToArray(arguments)); };
Log.cyan =    function(){ colorLog('cyan',    argumentsToArray(arguments)); };
Log.white =   function(){ colorLog('white',   argumentsToArray(arguments)); };
Log.gray =    function(){ colorLog('gray',    argumentsToArray(arguments)); };

module.exports = Log;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Stilbospora profusa Grev.

### Remarks
null


text:
<resources>
    <dimen name="controls_row_height">60dp</dimen>
    <dimen name="medium_margin">12dp</dimen>
    <dimen name="large_margin">16dp</dimen>
</resources>


text:
package com.codegen;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class CodeGenerator {
	public static void main(String[] args) throws Exception{
		ConfigurableApplicationContext context =
				new ClassPathXmlApplicationContext(new String[] { "project.xml"});

		Project project= (Project)context.getBean("project");

	    /* You should do this ONLY ONCE in the whole application life-cycle:        */

        /* Create and adjust the configuration singleton */
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(project.getFtlBaseDir()));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        for(Entity entity: project.getEntityList()){
        	Map<String,FTLTemplate>  templates = entity.getTemplates();
        	 for(Entry<String,FTLTemplate> entry: templates.entrySet()){
        		 String currentTemplate = entry.getValue().getFtl();
        		 if(entity.inLevel(currentTemplate.substring(0, currentTemplate.lastIndexOf(".")))){
	           	  Template temp = cfg.getTemplate(currentTemplate);
	           	  	Map root = project.getParams( entity);
	                 /* Merge data-model with template */
	                 Writer out = new StringWriter();

	                 temp.process(root, out);
	                 File desc = new File(entry.getValue().getAbsDescPath());
	                 if(!desc.exists()){
	                	 gerateFile(  desc,   out);
	                 }else{
	                	 if(entry.getValue().isReplace()){
	                		 gerateFile(  desc,   out);
	                        }
	                 }
        	 }

           }
        }

        Template temp = cfg.getTemplate(project.getSql());

         /* Merge data-model with template */
         Writer out = new StringWriter();

         temp.process(project, out);

         File desc = new File(project.getTargetBaseDir()+"/db/tables.sql");
         desc.getParentFile().mkdirs();
         System.out.println("gerating desc file: " + desc.getAbsolutePath());
         FileUtils.writeStringToFile(desc, out.toString(), "UTF-8");

	}

	private static void gerateFile(File desc, Writer out) throws IOException{

             desc.getParentFile().mkdirs();
             System.out.println("gerating desc file: " + desc.getAbsolutePath());
             FileUtils.writeStringToFile(desc, out.toString(), "UTF-8");

	}

}


text:
<?php
  require_once("dbConnect.php");

  if(!($cat = $_GET['cat'])){
      die("Error!. Supply Category");
  } else {
    //TODO: Apply regex to allow only alphanumeric.
  }

  $query = "SELECT * FROM place WHERE category='$cat';";

  $result = mysql_query($query);
  $returnArr = array();
  $i = 0;

  while($row = mysql_fetch_array($result)){
    $returnArr[$i]["id"]         = $row['id'];
    $returnArr[$i]["name"]       = $row['name'];
    $returnArr[$i]["category"]   = $row['category'];
    $returnArr[$i]["decision"]   = $row['desc'];
    $returnArr[$i]["totalViews"] = $row['totalviews'];
    $returnArr[$i]["coords"]     = $row['coords'];
    $i++;
  }

  echo json_encode($returnArr);


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

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.

=end

SLIAdmin::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # In the development environment your application's code is reloaded on
  # every request.  This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Log error messages when you accidentally call methods on nil.
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger
  config.active_support.deprecation = :log

  # Only use best-standards-support built into browsers
  config.action_dispatch.best_standards_support = :builtin

  # Do not compress assets
  config.assets.compress = false

  # Expands the lines which load the assets
  config.assets.debug = false
end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.google.code.play2.provider.api (Play! 2.x Provider API 1.0.0-rc4 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.google.code.play2.provider.api

Interfaces

CoffeescriptCompilationResult

JavascriptCompilationResult

LessCompilationResult

Play2Builder

Play2CoffeescriptCompiler

Play2DevServer

Play2EbeanEnhancer

Play2JavaEnhancer

Play2JavascriptCompiler

Play2LessCompiler

Play2Provider

Play2RoutesCompiler

Play2Runner

Play2TemplateCompiler

Classes

Play2Providers

Play2RunnerConfiguration

Exceptions

AssetCompilationException

Play2BuildError

Play2BuildException

Play2BuildFailure

RoutesCompilationException

SourceGenerationException

TemplateCompilationException


text:
require 'assembla_api/request/oauth2'
require 'assembla_api/request/basic_auth'
require 'assembla_api/request/key_auth'
require 'assembla_api/request/jsonize'

require 'assembla_api/connection'

module Assembla
  # A class responsible for dispatching http requests
  class Request
    include Connection

    HTTP_METHODS = [:get, :head, :post, :put, :delete, :patch]

    METHODS_WITH_BODIES = [:post, :put, :patch]

    # Return http verb
    #
    # @return [Symbol]
    attr_reader :action

    # Return url
    #
    # @return [String]
    attr_accessor :path

    # Return api this request is associated with
    #
    # @return [Assembla::API]
    attr_reader :api

    # Create a new Request
    #
    # @return [Assembla::Request]
    #
    # @api public
    def initialize(action, path, api)
      @action = action
      @path   = path
      @api    = api
    end

    # Performs a request
    #
    # @param [Symbol] method - The Symbol the HTTP verb
    # @param [String] path   - String relative URL to access
    # @param [ParamsHash] params - ParamsHash to configure the request API
    #
    # @return [Assembla::ResponseWrapper]
    #
    # @api private
    def call(current_options, params)
      unless HTTP_METHODS.include?(action)
        raise ArgumentError, "unknown http method: #{method}"
      end

      puts "EXECUTED: #{action} - #{path} with PARAMS: #{params}" if ENV['DEBUG']

      request_options    = params.options
      connection_options = current_options.merge(request_options)
      conn               = connection(api, connection_options)

      if conn.path_prefix != '/' && self.path.index(conn.path_prefix) != 0
        self.path = (conn.path_prefix + self.path).gsub(/\/(\/)*/, '/')
      end

      response = conn.send(action) do |request|
        case action.to_sym
        when *(HTTP_METHODS - METHODS_WITH_BODIES)
          request.body = params.data if params.has_key?('data')
          if params.has_key?('encoder')
            request.params.params_encoder(params.encoder)
          end
          request.url(self.path, params.to_hash)
        when *METHODS_WITH_BODIES
          request.url(self.path, connection_options[:query] || {})
          request.body = params.data unless params.empty?
        end
      end
      ResponseWrapper.new(response, api)
    end
  end # Request
end # Assembla


text:
'use strict';

angular
    .module('uploader')
    .controller('UploaderController', UploaderController);
    //.factory('UploaderService');

UploaderController.$inject = ['$scope', '$http','FileUploader', 'UploaderService'];

//app.controller('SecumapsController', ['$rootScope', '$scope', '$compile',

function UploaderController($scope, $http, FileUploader, UploaderService) {

	var uploader = $scope.uploader = new FileUploader({
		url: 'api/uploader',
		alias: 'uploadPictures'
	});

/*

	$scope.setUploaderParams = function () {

		var data = { "dest": './modules/articles/client/img/' };

		var uploaderParams = {
	      "dest": './modules/articles/client/img/', // Profile upload destination path
	      "limits": {
	        "fileSize": 5*1024*1024 // Max file size in bytes (1 MB)
	      }
	    };

	    $http.put('/api/uploader?', uploaderParams)
	    .success(function (data, status, headers) {
	        console.log("success");
	    })
	    .error(function (data, status, header, config) {
	    	console.log("Error");
	    });
	};
*/
	var imageList = [];
	var imagespath = './modules/articles/client/img/';

	// Set file uploader image filter
	$scope.uploader.filters.push({
		name: 'imageFilter',
		fn: function (item, options) {
			var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
			return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
		}
	});

	// CALLBACKS

	uploader.onWhenAddingFileFailed = function(item , filter, options) {
		console.info('onWhenAddingFileFailed', item, filter, options);
	};
	uploader.onAfterAddingFile = function(fileItem) {
		console.info('onAfterAddingFile', fileItem);
	};
	uploader.onAfterAddingAll = function(addedFileItems) {
		console.info('onAfterAddingAll', addedFileItems);
	};
	uploader.onBeforeUploadItem = function(item) {
		console.info('onBeforeUploadItem', item);
	};
	uploader.onProgressItem = function(fileItem, progress) {
		console.info('onProgressItem', fileItem, progress);
	};
	uploader.onProgressAll = function(progress) {
		console.info('onProgressAll', progress);
	};
	uploader.onSuccessItem = function(fileItem, response, status, headers) {
		console.info('onSuccessItem', fileItem, response, status, headers);
	};
	uploader.onErrorItem = function(fileItem, response, status, headers) {
		console.info('onErrorItem', fileItem, response, status, headers);
	};
	uploader.onCancelItem = function(fileItem, response, status, headers) {
		console.info('onCancelItem', fileItem, response, status, headers);
		console.log(response);
	};
	uploader.onCompleteItem = function(fileItem, response, status, headers) {
		console.info('onCompleteItem', fileItem, response, status, headers);

		console.log('response = ' + response);
		UploaderService.addFile(imagespath + response);
		console.log('getListFiles = ' + UploaderService.getListFiles());
		//imageList.push(imagespath + response);
	};
	uploader.onCompleteAll = function() {
		console.info('onCompleteAll');
	};

	console.info('uploader', uploader);
}
/*
function UploaderService() {
	var service = [];

	var uploaderParams = '';
	var listFiles = [];

	service.setUploaderParams = function (value) {
      uploaderParams = value;
      listFiles = [];
    };

    service.getUploaderParams = function () {
      return uploaderParams;
    };

    service.addFile = function (value) {
      listFiles.push(value);
    };

    service.getListFiles = function (value) {
      return listFiles;
    };

	return service;
}
*/


text:
package redistryout.repository;

import java.util.Map;
import java.util.Set;

public interface RedisRepository {
    /**
     * Return a set of keys in Redis: all of them.
     *
     * @return non null.
     */
    Set<String> keys();

    /**
     * Return key-value pairs in Redis: all of them.
     *
     * @return non null.
     */
    Map<String,String> values();

    /**
     * Add key-value pair to Redis.
     */
    void add(String key, String value);

    /**
     * Delete a key-value pair in Redis.
     */
    void delete(String key);
}


text:
<?php

namespace Sodium\Concrete\Processor\Input;

abstract class InputFormatConcrete
{
    protected $formats = array();

    public function setFormats($formats)
    {
        $this->formats = $formats;
    }

    public function getFormats()
    {
        return $this->formats;
    }
}


text:
Puppet::Type.newtype(:tempest_neutron_net_id_setter) do

  ensurable

  newparam(:name, :namevar => true) do
    desc 'The name of the setting to update.'
  end

  newparam(:tempest_conf_path) do
    desc 'The path to tempest conf file.'
  end

  newparam(:network_name) do
    desc 'The name of the neutron network.'
  end

end


text:
@interface MainViewController () <MJGChoiceViewControllerDelegate, MJGFullscreenWebViewControllerDelegate>
@end

@implementation MainViewController

- (id)init {
    if ((self = [super initWithNibName:@"MainViewController" bundle:nil])) {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            self.clearsSelectionOnViewWillAppear = NO;
            self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
        }
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"MJGFoundation UI Catalog";

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    }
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 4; break;
        case 1:
            return 1; break;
        case 2:
            return 1; break;
        default:
            return 0; break;
    }
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return @"View controllers"; break;
        case 1:
            return @"Gesture recognizers"; break;
        case 2:
            return @"Views"; break;
        default:
            return nil; break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int section = indexPath.section;
    int row = indexPath.row;

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }

    if (section == 0) {
        if (row == 0) {
            cell.textLabel.text = @"Choice";
        } else if (row == 1) {
            cell.textLabel.text = @"Fullscreen Image";
        } else if (row == 2) {
            cell.textLabel.text = @"Fullscreen Web";
        } else if (row == 3) {
            cell.textLabel.text = @"Image Gallery";
        }
    } else if (section == 1) {
        if (row == 0) {
            cell.textLabel.text = @"2D Pinch Gesture";
        }
    } else if (section == 2) {
        if (row == 0) {
            cell.textLabel.text = @"Rating View";
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int section = indexPath.section;
    int row = indexPath.row;

    UIViewController *vcToPush = nil;
    UIViewController *vcToModal = nil;

    if (section == 0) {
        if (row == 0) {
            NSDictionary *choices = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"itema", @"Item A",
                                     @"itemb", @"Item B",
                                     @"itemc", @"Item C",
                                     @"itemd", @"Item D",
                                     nil];
            MJGChoiceViewController *vc = [[MJGChoiceViewController alloc] initWithChoices:choices];
            vc.delegate = self;
            vcToModal = vc;
        } else if (row == 1) {
            MJGFullscreenImageViewController *vc = [[MJGFullscreenImageViewController alloc] initWithURL:[NSURL URLWithString:@"http://www.beermap.co/images/home_header_bg.jpg"]];
            vcToPush = vc;
        } else if (row == 2) {
            MJGFullscreenWebViewController *vc = [[MJGFullscreenWebViewController alloc] initWithURL:[NSURL URLWithString:@"http://www.beermap.co/"]];
            vc.delegate = self;
            vcToModal = vc;
        } else if (row == 3) {
            MJGImageGalleryViewController *vc = [[MJGImageGalleryViewController alloc] initWithImages:nil];
            vcToPush = vc;
        }
    } else if (section == 1) {
        if (row == 0) {
            Example2DPinchGestureRecognizerViewController *vc = [[Example2DPinchGestureRecognizerViewController alloc] init];
            vcToPush = vc;
        }
    } else if (section == 2) {
        if (row == 0) {
            ExampleMJGRateViewViewController *vc = [[ExampleMJGRateViewViewController alloc] init];
            vcToPush = vc;
        }
    }

    if (vcToPush) {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            [self.navigationController pushViewController:vcToPush animated:YES];
        } else {
            self.splitViewController.viewControllers = [NSArray arrayWithObjects:self, vcToPush, nil];
        }
    } else if (vcToModal) {
        [self presentModalViewController:vcToModal animated:YES];
    }
}

#pragma mark - MJGChoiceViewControllerDelegate

- (void)choiceViewController:(MJGChoiceViewController *)viewController finishedWithKey:(id)key andValue:(id)value {
    [self dismissModalViewControllerAnimated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Choice"
                                                    message:[NSString stringWithFormat:@"You chose\n%@ => %@", key, value]
                                                                              delegate:nil
                                                                     cancelButtonTitle:nil
                                                                     otherButtonTitles:@"OK", nil];
    [alert show];
}

- (void)choiceViewControllerCancelled:(MJGChoiceViewController *)viewController {
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - MJGFullscreenWebViewControllerDelegate

- (void)fullscreenWebViewControllerDidFinish:(MJGFullscreenWebViewController *)viewController {
    [self dismissModalViewControllerAnimated:YES];
}

@end


text:
package com.cardpay.pccredit.xm_appln.service;

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

import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cardpay.pccredit.common.Cn2Spell;
import com.cardpay.pccredit.customer.constant.WfProcessInfoType;
import com.cardpay.pccredit.customer.filter.CustomerInforFilter;
import com.cardpay.pccredit.customer.model.CustomerInfor;
import com.cardpay.pccredit.customer.service.CustomerInforService;
import com.cardpay.pccredit.intopieces.constant.Constant;
import com.cardpay.pccredit.intopieces.model.CustomerApplicationInfo;
import com.cardpay.pccredit.intopieces.model.CustomerApplicationProcess;
import com.cardpay.pccredit.intopieces.model.LocalExcel;
import com.cardpay.pccredit.intopieces.model.XmModel;
import com.cardpay.pccredit.product.filter.ProductFilter;
import com.cardpay.pccredit.product.model.ProductAttribute;
import com.cardpay.pccredit.product.service.ProductService;
import com.cardpay.pccredit.system.constants.NodeAuditTypeEnum;
import com.cardpay.pccredit.system.constants.YesNoEnum;
import com.cardpay.pccredit.system.model.NodeAudit;
import com.cardpay.pccredit.system.model.NodeControl;
import com.cardpay.pccredit.system.service.NodeAuditService;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_ADDR_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_DBXX_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_DCSC_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_HKSZ_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_HNPF_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_JCZL_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_KHED_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_KHFW_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_KHLB_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_KPMX_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_LXRZL_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_POZL_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_QTXYKXX_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_SPED_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_SQCL_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_SQED_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_TJINFO_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_YWXX_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_ZHSX_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_ZXQSZL_Dao;
import com.cardpay.pccredit.xm_appln.dao.XM_APPLN_ZXXX_Dao;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_ADDR;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_DBXX;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_DCSC;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_HKSZ;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_HNPF;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_JCZL;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_KHED;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_KHFW;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_KHLB;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_KPMX;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_LXRZL;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_POZL;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_QTXYKXX;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_SPED;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_SQCL;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_SQED;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_TJINFO;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_YWXX;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_ZHSX;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_ZXQSZL;
import com.cardpay.pccredit.xm_appln.model.XM_APPLN_ZXXX;
import com.cardpay.pccredit.xm_appln.web.XM_APPLN_ADDR_FORM;
import com.cardpay.pccredit.xm_appln.web.XM_APPLN_FORM;
import com.cardpay.pccredit.xm_appln.web.XM_APPLN_HNPF_FORM;
import com.cardpay.pccredit.xm_appln.web.XM_APPLN_JBZL_FORM;
import com.cardpay.pccredit.xm_appln.web.XM_APPLN_NEW_CUSTOMER_FORM;
import com.cardpay.workflow.models.WfProcessInfo;
import com.cardpay.workflow.models.WfStatusInfo;
import com.cardpay.workflow.models.WfStatusResult;
import com.cardpay.workflow.service.ProcessService;
import com.wicresoft.jrad.base.auth.IUser;
import com.wicresoft.jrad.base.database.dao.common.CommonDao;
import com.wicresoft.jrad.base.database.id.IDGenerator;
import com.wicresoft.jrad.base.web.security.LoginManager;
import com.wicresoft.jrad.modules.privilege.model.User;
import com.wicresoft.util.spring.Beans;

/**
 *
 * @author 谭文华
 *
 */
@Service
public class XM_APPLN_Service {

	@Autowired
	private CustomerInforService customerInforService;

	@Autowired
	private CommonDao commonDao;

	@Autowired
	private NodeAuditService nodeAuditService;

	@Autowired
	private ProcessService processService;
	@Autowired
	private ProductService productService;

	@Autowired
	private XM_APPLN_ADDR_Dao xM_APPLN_ADDR_Dao;
	@Autowired
	private XM_APPLN_Dao xM_APPLN_Dao;
	@Autowired
	private XM_APPLN_DBXX_Dao xM_APPLN_DBXX_Dao;
	@Autowired
	private XM_APPLN_DCSC_Dao xM_APPLN_DCSC_Dao;
	@Autowired
	private XM_APPLN_HKSZ_Dao xM_APPLN_HKSZ_Dao;
	@Autowired
	private XM_APPLN_JCZL_Dao xM_APPLN_JCZL_Dao;
	@Autowired
	private XM_APPLN_KHED_Dao xM_APPLN_KHED_Dao;
	@Autowired
	private XM_APPLN_KHFW_Dao xM_APPLN_KHFW_Dao;
	@Autowired
	private XM_APPLN_KHLB_Dao xM_APPLN_KHLB_Dao;
	@Autowired
	private XM_APPLN_KPMX_Dao xM_APPLN_KPMX_Dao;
	@Autowired
	private XM_APPLN_LXRZL_Dao xM_APPLN_LXRZL_Dao;
	@Autowired
	private XM_APPLN_POZL_Dao xM_APPLN_POZL_Dao;
	@Autowired
	private XM_APPLN_QTXYKXX_Dao xM_APPLN_QTXYKXX_Dao;
	@Autowired
	private XM_APPLN_TJINFO_Dao xM_APPLN_TJINFO_Dao;
	@Autowired
	private XM_APPLN_YWXX_Dao xM_APPLN_YWXX_Dao;
	@Autowired
	private XM_APPLN_ZXQSZL_Dao xM_APPLN_ZXQSZL_Dao;
	@Autowired
	private XM_APPLN_SQED_Dao xM_APPLN_SQED_Dao;
	@Autowired
	private XM_APPLN_SPED_Dao xM_APPLN_SPED_Dao;
	@Autowired
	private XM_APPLN_SQCL_Dao xM_APPLN_SQCL_Dao;
	@Autowired
	private XM_APPLN_ZHSX_Dao xM_APPLN_ZHSX_Dao;
	@Autowired
	private XM_APPLN_ZXXX_Dao xM_APPLN_ZXXX_Dao;
	@Autowired
	private XM_APPLN_HNPF_Dao xM_APPLN_HNPF_Dao;

	/**
	 * 插入数据
	 * @param 基本资料page0
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_NEW_CUSTOMER(XM_APPLN_NEW_CUSTOMER_FORM xM_APPLN_NEW_CUSTOMER_FORM,User user){
		String customerId = xM_APPLN_NEW_CUSTOMER_FORM.getCustomer_id();
		if(customerId.equals("") || customerId == null){
			CustomerInfor customerinfor = new CustomerInfor();
			customerinfor.setCreatedBy(user.getId());
			customerinfor.setCreatedTime(new Date());
			customerinfor.setUserId(user.getId());
			customerinfor.setChineseName(xM_APPLN_NEW_CUSTOMER_FORM.getSurname());
			customerinfor.setPinyinenglishName(Cn2Spell.converterToSpell(xM_APPLN_NEW_CUSTOMER_FORM.getSurname()));
			customerinfor.setNationality("NTC00000000156");//中国
			customerinfor.setTelephone(xM_APPLN_NEW_CUSTOMER_FORM.getMo_phone());
//			customerinfor.setCardType("CST0000000000A");//身份证
			customerinfor.setCardType(xM_APPLN_NEW_CUSTOMER_FORM.getRace_code());//身份证
			customerinfor.setCardId(xM_APPLN_NEW_CUSTOMER_FORM.getCard_id());//身份证
			customerinfor.setSex(xM_APPLN_NEW_CUSTOMER_FORM.getGender().equals("M")?"Male":"Female");//MODIFIED BY NIHC 20150701

			customerId = customerInforService.insertCustomerInfor(customerinfor);
		}else{
			CustomerInfor customerinfor = customerInforService.findCustomerInforById(customerId);
			customerinfor.setChineseName(xM_APPLN_NEW_CUSTOMER_FORM.getSurname());
			customerinfor.setPinyinenglishName(Cn2Spell.converterToSpell(xM_APPLN_NEW_CUSTOMER_FORM.getSurname()));
			customerinfor.setNationality("NTC00000000156");//中国
			customerinfor.setTelephone(xM_APPLN_NEW_CUSTOMER_FORM.getMo_phone());
//			customerinfor.setCardType("CST0000000000A");//身份证
			customerinfor.setCardType(xM_APPLN_NEW_CUSTOMER_FORM.getRace_code());//身份证
			customerinfor.setCardId(xM_APPLN_NEW_CUSTOMER_FORM.getCard_id());//身份证
			customerinfor.setSex(xM_APPLN_NEW_CUSTOMER_FORM.getGender().equals("M")?"Male":"Female");//modified by nihc 20150702
			customerinfor.setModifiedBy(user.getId());
			customerinfor.setModifiedTime(new Date());
			customerInforService.updateCustomerInfor(customerinfor);
		}

		XM_APPLN_JCZL xM_APPLN_JCZL = xM_APPLN_NEW_CUSTOMER_FORM.createXM_APPLN_JCZL(customerId,user.getId());
		XM_APPLN_POZL xM_APPLN_POZL = xM_APPLN_NEW_CUSTOMER_FORM.createXM_APPLN_POZL(customerId,user.getId());

		insertOrUpdateXM_APPLN_JCZL(xM_APPLN_JCZL);
		insertOrUpdateXM_APPLN_POZL(xM_APPLN_POZL);

		return customerId;
	}

	/**
	 * 修改数据
	 * @param 基本资料
	 * @return
	 */
	public void updateXM_APPLN_NEW_CUSTOMER(String cardId){
		XM_APPLN_NEW_CUSTOMER_FORM xM_APPLN_NEW_CUSTOMER_FORM = new XM_APPLN_NEW_CUSTOMER_FORM();
		CustomerInforFilter filter = new CustomerInforFilter();
		filter.setCardId(cardId);
		CustomerInfor infor  = commonDao.findObjectsByFilter(CustomerInfor.class, filter).getItems().get(0);
	}

	/**
	 * 插入数据
	 * @param 基本资料page1
	 * @return
	 */
	public String insertXM_APPLN_JBZL(String customerId,XM_APPLN_JBZL_FORM xM_APPLN_JBZL_FORM,User user){
		/*if(customerId == null){
			CustomerInfor customerinfor = new CustomerInfor();
			customerinfor.setCreatedBy(user.getId());
			customerinfor.setUserId(user.getId());
			customerinfor.setChineseName(xM_APPLN_JBZL_FORM.getSurname());
			customerinfor.setPinyinenglishName(Cn2Spell.converterToSpell(xM_APPLN_JBZL_FORM.getSurname()));
			customerinfor.setNationality("NTC00000000156");//中国
			customerinfor.setCardType(xM_APPLN_JBZL_FORM.getRace_code());//身份证
			customerinfor.setCardId(xM_APPLN_JBZL_FORM.getCard_id());//身份证
			customerinfor.setSex(xM_APPLN_JBZL_FORM.getGender().equals("1")?"Male":"Female");
			customerId = customerInforService.insertCustomerInfor(customerinfor);
		}*/
		/*modified by nihc 20150702 同步更新basic_customer_information begin*/
		CustomerInfor customerinfor = customerInforService.findCustomerInforById(customerId);
		customerinfor.setChineseName(xM_APPLN_JBZL_FORM.getSurname());
		customerinfor.setPinyinenglishName(Cn2Spell.converterToSpell(xM_APPLN_JBZL_FORM.getSurname()));
		customerinfor.setNationality("NTC00000000156");//中国
		customerinfor.setTelephone(xM_APPLN_JBZL_FORM.getMo_phone());
		customerinfor.setCardType(xM_APPLN_JBZL_FORM.getRace_code());//身份证
		customerinfor.setCardId(xM_APPLN_JBZL_FORM.getCard_id());//身份证
		customerinfor.setSex(xM_APPLN_JBZL_FORM.getGender().equals("M")?"Male":"Female");//modified by nihc 20150702
		customerinfor.setModifiedBy(user.getId());
		customerinfor.setModifiedTime(new Date());
		customerinfor.setMaritalStatus(xM_APPLN_JBZL_FORM.getMar_status());
		customerInforService.updateCustomerInfor(customerinfor);
		/*modified by nihc 20150702 end*/
		//CustomerInfor customerinfor = xM_APPLN_JBZL_FORM.createModel(XM_APPLN_JBZL_FORM.class);
		XM_APPLN_JCZL xM_APPLN_JCZL = xM_APPLN_JBZL_FORM.createXM_APPLN_JCZL(customerId,user.getId());
		XM_APPLN_KHFW xM_APPLN_KHFW = xM_APPLN_JBZL_FORM.createXM_APPLN_KHFW(customerId,user.getId());
		XM_APPLN_KHLB xM_APPLN_KHLB = xM_APPLN_JBZL_FORM.createXM_APPLN_KHLB(customerId,user.getId());
		XM_APPLN_KHED xM_APPLN_KHED = xM_APPLN_JBZL_FORM.createXM_APPLN_KHED(customerId,user.getId());
		XM_APPLN_POZL xM_APPLN_POZL = xM_APPLN_JBZL_FORM.createXM_APPLN_POZL(customerId,user.getId());
		List<XM_APPLN_LXRZL> xM_APPLN_LXRZL_ls = xM_APPLN_JBZL_FORM.createXM_APPLN_LXRZL(customerId,user.getId());
		XM_APPLN_ZXQSZL xM_APPLN_ZXQSZL = xM_APPLN_JBZL_FORM.createXM_APPLN_ZXQSZL(customerId,user.getId());

		insertOrUpdateXM_APPLN_JCZL(xM_APPLN_JCZL);
		insertOrUpdateXM_APPLN_KHFW(xM_APPLN_KHFW);
		insertOrUpdateXM_APPLN_KHLB(xM_APPLN_KHLB);
		insertOrUpdateXM_APPLN_KHED(xM_APPLN_KHED);
		insertOrUpdateXM_APPLN_POZL(xM_APPLN_POZL);
		insertOrUpdateXM_APPLN_LXRZL(xM_APPLN_LXRZL_ls);
		insertOrUpdateXM_APPLN_ZXQSZL(xM_APPLN_ZXQSZL);
		return customerId;
	}

	/**
	 * 插入数据
	 * @param 申请信息
	 * @return
	 */
	public void insertXM_APPLN(XM_APPLN_FORM xM_APPLN_FORM,User user){
		XM_APPLN xM_APPLN = xM_APPLN_FORM.createXM_APPLN(user.getId());
		XM_APPLN_SQED xM_APPLN_SQED = xM_APPLN_FORM.createXM_APPLN_SQED(user.getId());
		List<XM_APPLN_KPMX> xM_APPLN_KPMX_ls = xM_APPLN_FORM.createXM_APPLN_KPMX(user.getId());
		XM_APPLN_HKSZ xM_APPLN_HKSZ = xM_APPLN_FORM.createXM_APPLN_HKSZ(user.getId());
		XM_APPLN_DBXX xM_APPLN_DBXX = xM_APPLN_FORM.createXM_APPLN_DBXX(user.getId());
		XM_APPLN_QTXYKXX xM_APPLN_QTXYKXX = xM_APPLN_FORM.createXM_APPLN_QTXYKXX(user.getId());
		XM_APPLN_YWXX xM_APPLN_YWXX = xM_APPLN_FORM.createXM_APPLN_YWXX(user.getId());
		XM_APPLN_DCSC xM_APPLN_DCSC = xM_APPLN_FORM.createXM_APPLN_DCSC(user.getId());

		insertOrUpdateXM_APPLN(xM_APPLN);
		insertOrUpdateXM_APPLN_SQED(xM_APPLN_SQED);
		insertOrUpdateXM_APPLN_KPMX(xM_APPLN_KPMX_ls);
		insertOrUpdateXM_APPLN_HKSZ(xM_APPLN_HKSZ);
		insertOrUpdateXM_APPLN_DBXX(xM_APPLN_DBXX);
		insertOrUpdateXM_APPLN_QTXYKXX(xM_APPLN_QTXYKXX);
		insertOrUpdateXM_APPLN_YWXX(xM_APPLN_YWXX);
		insertOrUpdateXM_APPLN_DCSC(xM_APPLN_DCSC);
	}

	/**
	 * 插入数据
	 * @param 地址信息
	 * @return
	 */
	public void insertXM_APPLN_ADDR(XM_APPLN_ADDR_FORM xM_APPLN_ADDR_FORM,User user){
		XM_APPLN_TJINFO xM_APPLN_TJINFO = xM_APPLN_ADDR_FORM.createXM_APPLN_TJINFO(user.getId());
		XM_APPLN_ADDR xM_APPLN_ADDR = xM_APPLN_ADDR_FORM.createXM_APPLN_ADDR(user.getId());

		XM_APPLN xM_APPLN = xM_APPLN_Dao.findByCustomerId(xM_APPLN_TJINFO.getCustomer_id());
		xM_APPLN.setMail_to(xM_APPLN_ADDR_FORM.getMail_to());
		/*added by nihc 20150706 保存家庭电话、公司电话 begin*/
		XM_APPLN_JCZL xM_APPLN_JCZL = xM_APPLN_ADDR_FORM.createXM_APPLN_JCZL(user.getId());
		insertOrUpdateXM_APPLN_JCZL(xM_APPLN_JCZL);
		/*added by nihc 20150706 end */
		insertOrUpdateXM_APPLN_TJINFO(xM_APPLN_TJINFO);
		insertOrUpdateXM_APPLN_ADDR(xM_APPLN_ADDR);

		insertOrUpdateXM_APPLN(xM_APPLN);
	}

	/**
	 * 插入数据
	 * @param 行内评分
	 * @return
	 */
	public void insertXM_APPLN_HNPF(XM_APPLN_HNPF_FORM xM_APPLN_HNPF_FORM,User user){
		XM_APPLN_HNPF xM_APPLN_HNPF = xM_APPLN_HNPF_FORM.createXM_APPLN_HNPF(user.getId());

		insertOrUpdateXM_APPLN_HNPF(xM_APPLN_HNPF);
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_JCZL基础资料
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_JCZL(XM_APPLN_JCZL xM_APPLN_JCZL) {
		XM_APPLN_JCZL tmp = this.xM_APPLN_JCZL_Dao.findByCustomerId(xM_APPLN_JCZL.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_JCZL.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_JCZL.setId(id);
		xM_APPLN_JCZL.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_JCZL);
		return xM_APPLN_JCZL.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_KHFW客户服务
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_KHFW(XM_APPLN_KHFW xM_APPLN_KHFW) {
		XM_APPLN_KHFW tmp = this.xM_APPLN_KHFW_Dao.findByCustomerId(xM_APPLN_KHFW.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_KHFW.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_KHFW.setId(id);
		xM_APPLN_KHFW.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_KHFW);
		return xM_APPLN_KHFW.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_KHLB客户类别
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_KHLB(XM_APPLN_KHLB xM_APPLN_KHLB) {
		XM_APPLN_KHLB tmp = this.xM_APPLN_KHLB_Dao.findByCustomerId(xM_APPLN_KHLB.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_KHLB.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_KHLB.setId(id);
		xM_APPLN_KHLB.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_KHLB);
		return xM_APPLN_KHLB.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_KHED客户额度
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_KHED(XM_APPLN_KHED xM_APPLN_KHED) {
		XM_APPLN_KHED tmp = this.xM_APPLN_KHED_Dao.findByCustomerId(xM_APPLN_KHED.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_KHED.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_KHED.setId(id);
		xM_APPLN_KHED.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_KHED);
		return xM_APPLN_KHED.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_POZL配偶资料
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_POZL(XM_APPLN_POZL xM_APPLN_POZL) {
		XM_APPLN_POZL tmp = this.xM_APPLN_POZL_Dao.findByCustomerId(xM_APPLN_POZL.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_POZL.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_POZL.setId(id);
		xM_APPLN_POZL.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_POZL);
		return xM_APPLN_POZL.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_LXRZL联系人资料
	 * @return
	 */
	public void insertOrUpdateXM_APPLN_LXRZL(List<XM_APPLN_LXRZL> xM_APPLN_LXRZL_ls) {
		List<XM_APPLN_LXRZL> tmp = this.xM_APPLN_LXRZL_Dao.findByCustomerId(xM_APPLN_LXRZL_ls.get(0).getCustomer_id());
		if(tmp != null){
			for(XM_APPLN_LXRZL obj:tmp){
				commonDao.deleteObject(XM_APPLN_LXRZL.class, obj.getId());
			}
		}
		for(XM_APPLN_LXRZL obj:xM_APPLN_LXRZL_ls){
			String id = IDGenerator.generateID();
			obj.setId(id);
			obj.setCreatedTime(new Date());
			commonDao.insertObject(obj);
		}
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_ZXQSZL直系亲属资料
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_ZXQSZL(XM_APPLN_ZXQSZL xM_APPLN_ZXQSZL) {
		XM_APPLN_ZXQSZL tmp = this.xM_APPLN_ZXQSZL_Dao.findByCustomerId(xM_APPLN_ZXQSZL.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_ZXQSZL.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_ZXQSZL.setId(id);
		xM_APPLN_ZXQSZL.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_ZXQSZL);
		return xM_APPLN_ZXQSZL.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN申请基础资料
	 * @return
	 */
	public String insertOrUpdateXM_APPLN(XM_APPLN xM_APPLN) {
		XM_APPLN tmp = this.xM_APPLN_Dao.findByCustomerId(xM_APPLN.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN.setId(id);
		xM_APPLN.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN);
		return xM_APPLN.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_SQED申请额度
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_SQED(XM_APPLN_SQED xM_APPLN_SQED) {
		XM_APPLN_SQED tmp = this.xM_APPLN_SQED_Dao.findByCustomerId(xM_APPLN_SQED.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_SQED.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_SQED.setId(id);
		xM_APPLN_SQED.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_SQED);
		return xM_APPLN_SQED.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_KPMX卡片明细
	 * @return
	 */
	public void insertOrUpdateXM_APPLN_KPMX(List<XM_APPLN_KPMX> xM_APPLN_KPMX_ls) {
		List<XM_APPLN_KPMX> tmp = this.xM_APPLN_KPMX_Dao.findByCustomerId(xM_APPLN_KPMX_ls.get(0).getCustomer_id());
		if(tmp != null){
			for(XM_APPLN_KPMX obj:tmp){
				commonDao.deleteObject(XM_APPLN_KPMX.class, obj.getId());
			}
		}
		for(XM_APPLN_KPMX obj:xM_APPLN_KPMX_ls){
			String id = IDGenerator.generateID();
			obj.setId(id);
			obj.setCreatedTime(new Date());
			commonDao.insertObject(obj);
		}
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_HKSZ还款设置
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_HKSZ(XM_APPLN_HKSZ xM_APPLN_HKSZ) {
		XM_APPLN_HKSZ tmp = this.xM_APPLN_HKSZ_Dao.findByCustomerId(xM_APPLN_HKSZ.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_HKSZ.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_HKSZ.setId(id);
		xM_APPLN_HKSZ.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_HKSZ);
		return xM_APPLN_HKSZ.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_DBXX担保信息
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_DBXX(XM_APPLN_DBXX xM_APPLN_DBXX) {
		XM_APPLN_DBXX tmp = this.xM_APPLN_DBXX_Dao.findByCustomerId(xM_APPLN_DBXX.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_DBXX.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_DBXX.setId(id);
		xM_APPLN_DBXX.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_DBXX);
		return xM_APPLN_DBXX.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_QTXYKXX其他信用卡信息
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_QTXYKXX(XM_APPLN_QTXYKXX xM_APPLN_QTXYKXX) {
		XM_APPLN_QTXYKXX tmp = this.xM_APPLN_QTXYKXX_Dao.findByCustomerId(xM_APPLN_QTXYKXX.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_QTXYKXX.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_QTXYKXX.setId(id);
		xM_APPLN_QTXYKXX.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_QTXYKXX);
		return xM_APPLN_QTXYKXX.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_YWXX业务信息
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_YWXX(XM_APPLN_YWXX xM_APPLN_YWXX) {
		XM_APPLN_YWXX tmp = this.xM_APPLN_YWXX_Dao.findByCustomerId(xM_APPLN_YWXX.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_YWXX.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_YWXX.setId(id);
		xM_APPLN_YWXX.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_YWXX);
		return xM_APPLN_YWXX.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_DCSC调查审查
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_DCSC(XM_APPLN_DCSC xM_APPLN_DCSC) {
		XM_APPLN_DCSC tmp = this.xM_APPLN_DCSC_Dao.findByCustomerId(xM_APPLN_DCSC.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_DCSC.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_DCSC.setId(id);
		xM_APPLN_DCSC.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_DCSC);
		return xM_APPLN_DCSC.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_TJINFO推荐人信息
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_TJINFO(XM_APPLN_TJINFO xM_APPLN_TJINFO) {
		XM_APPLN_TJINFO tmp = this.xM_APPLN_TJINFO_Dao.findByCustomerId(xM_APPLN_TJINFO.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_TJINFO.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_TJINFO.setId(id);
		xM_APPLN_TJINFO.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_TJINFO);
		return xM_APPLN_TJINFO.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_ADDR地址信息
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_ADDR(XM_APPLN_ADDR xM_APPLN_ADDR) {
		XM_APPLN_ADDR tmp = this.xM_APPLN_ADDR_Dao.findByCustomerId(xM_APPLN_ADDR.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_ADDR.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_ADDR.setId(id);
		xM_APPLN_ADDR.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_ADDR);
		return xM_APPLN_ADDR.getId();
	}

	/**
	 * 插入数据
	 * @param XM_APPLN_HNPF行内评分
	 * @return
	 */
	public String insertOrUpdateXM_APPLN_HNPF(XM_APPLN_HNPF xM_APPLN_HNPF) {
		XM_APPLN_HNPF tmp = this.xM_APPLN_HNPF_Dao.findByCustomerId(xM_APPLN_HNPF.getCustomer_id());
		if(tmp != null){
			commonDao.deleteObject(XM_APPLN_HNPF.class, tmp.getId());
		}
		String id = IDGenerator.generateID();
		xM_APPLN_HNPF.setId(id);
		xM_APPLN_HNPF.setCreatedTime(new Date());
		commonDao.insertObject(xM_APPLN_HNPF);
		return xM_APPLN_HNPF.getId();
	}

	public XM_APPLN findXM_APPLNByCustomerId(String customer_Id){
		return this.xM_APPLN_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_SQED findXM_APPLN_SQEDByCustomerId(String customer_Id){
		return this.xM_APPLN_SQED_Dao.findByCustomerId(customer_Id);
	}
	public List<XM_APPLN_KPMX> findXM_APPLN_KPMXByCustomerId(String customer_Id){
		return this.xM_APPLN_KPMX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_HKSZ findXM_APPLN_HKSZByCustomerId(String customer_Id){
		return this.xM_APPLN_HKSZ_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_DBXX findXM_APPLN_DBXXByCustomerId(String customer_Id){
		return this.xM_APPLN_DBXX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_QTXYKXX findXM_APPLN_QTXYKXXByCustomerId(String customer_Id){
		return this.xM_APPLN_QTXYKXX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_DCSC findXM_APPLN_DCSCByCustomerId(String customer_Id){
		return this.xM_APPLN_DCSC_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_TJINFO findXM_APPLN_TJINFOByCustomerId(String customer_Id){
		return this.xM_APPLN_TJINFO_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_ADDR findXM_APPLN_ADDRByCustomerId(String customer_Id){
		return this.xM_APPLN_ADDR_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_JCZL findXM_APPLN_JCZLByCustomerId(String customer_Id){
		return this.xM_APPLN_JCZL_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_KHFW findXM_APPLN_KHFWByCustomerId(String customer_Id){
		return this.xM_APPLN_KHFW_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_KHLB findXM_APPLN_KHLBByCustomerId(String customer_Id){
		return this.xM_APPLN_KHLB_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_KHED findXM_APPLN_KHEDByCustomerId(String customer_Id){
		return this.xM_APPLN_KHED_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_POZL findXM_APPLN_POZLByCustomerId(String customer_Id){
		return this.xM_APPLN_POZL_Dao.findByCustomerId(customer_Id);
	}
	public List<XM_APPLN_LXRZL> findXM_APPLN_LXRZLByCustomerId(String customer_Id){
		return this.xM_APPLN_LXRZL_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_ZXQSZL findXM_APPLN_ZXQSZLByCustomerId(String customer_Id){
		return this.xM_APPLN_ZXQSZL_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_YWXX findXM_APPLN_YWXXByCustomerId(String customer_Id){
		return this.xM_APPLN_YWXX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_SPED findXM_APPLN_SPEDByCustomerId(String customer_Id){
		return this.xM_APPLN_SPED_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_SQCL findXM_APPLN_SQCLByCustomerId(String customer_Id){
		return this.xM_APPLN_SQCL_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_ZHSX findXM_APPLN_ZHSXByCustomerId(String customer_Id){
		return this.xM_APPLN_ZHSX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_ZXXX findXM_APPLN_ZXXXByCustomerId(String customer_Id){
		return this.xM_APPLN_ZXXX_Dao.findByCustomerId(customer_Id);
	}
	public XM_APPLN_HNPF findXM_APPLN_HNPFByCustomerId(String customer_Id){
		return this.xM_APPLN_HNPF_Dao.findByCustomerId(customer_Id);
	}

	/**
	 * 提交申请,开始流程
	 * @param customer_id
	 */
	public void saveApply(String customer_id,
						  String intopiecesType,
						  String IntopiecesSpareType,
						  String custType,
						  String applyQuota,
						  String productId,
						  String localExeclId,XmModel xm){

		//设置申请
		CustomerApplicationInfo customerApplicationInfo = new CustomerApplicationInfo();
		//customerApplicationInfo.setStatus(status);
		customerApplicationInfo.setId(IDGenerator.generateID());
		customerApplicationInfo.setIntopiecesType(intopiecesType);
		XM_APPLN_SQED xM_APPLN_SQED = findXM_APPLN_SQEDByCustomerId(customer_id);
		if(xM_APPLN_SQED==null||xM_APPLN_SQED.getCrdlmt_req()==null||xM_APPLN_SQED.getCrdlmt_req().equals("")){
			customerApplicationInfo.setApplyQuota("0");//设置额度
		}
		customerApplicationInfo.setCustomerId(customer_id);
		if(customerApplicationInfo.getApplyQuota()!=null){
			customerApplicationInfo.setApplyQuota((Integer.valueOf(customerApplicationInfo.getApplyQuota())*100)+"");
		}

		customerApplicationInfo.setStatus(Constant.APPROVE_INTOPICES);
		//查找默认产品
		ProductFilter filter = new ProductFilter();
		filter.setDefault_type(Constant.DEFAULT_TYPE);
		ProductAttribute productAttribute = productService.findProductsByFilter(filter).getItems().get(0);
		customerApplicationInfo.setProductId(productId);
		//modified by nihc 20150702 begin
		customerApplicationInfo.setCreatedTime(new Date());
		//modified by nihc 20150702 end

		//modified by songchen 20151019 begin
		customerApplicationInfo.setIntopiecesSpareType(IntopiecesSpareType);
		customerApplicationInfo.setCustType(custType);
		customerApplicationInfo.setApplyQuota(applyQuota);
		//modified by songchen 20151019 end

		commonDao.insertObject(customerApplicationInfo);

		//modified by songchen 20151109 start
		if("1".equals(intopiecesType)){//散件
			xm.setApp_id(customerApplicationInfo.getId());
			commonDao.insertObject(xm);
		}
		//modified by songchen 20151109 end
		//绑定appId
		productService.updateLocalExecl(localExeclId, customerApplicationInfo.getId());

		//添加申请件流程
		WfProcessInfo wf=new WfProcessInfo();
		wf.setProcessType(WfProcessInfoType.process_type);
		wf.setVersion("1");
		commonDao.insertObject(wf);
		List<NodeAudit> list=nodeAuditService.findByNodeTypeAndProductId(NodeAuditTypeEnum.Product.name(),productAttribute.getId());
		boolean startBool=false;
		boolean endBool=false;
		//节点id和WfStatusInfo id的映射
		Map<String, String> nodeWfStatusMap = new HashMap<String, String>();
		for(NodeAudit nodeAudit:list){
			if(nodeAudit.getIsstart().equals(YesNoEnum.YES.name())){
				startBool=true;
			}

			if(startBool&&!endBool){
				WfStatusInfo wfStatusInfo=new WfStatusInfo();
				wfStatusInfo.setIsStart(nodeAudit.getIsstart().equals(YesNoEnum.YES.name())?"1":"0");
				wfStatusInfo.setIsClosed(nodeAudit.getIsend().equals(YesNoEnum.YES.name())?"1":"0");
				wfStatusInfo.setRelationedProcess(wf.getId());
				wfStatusInfo.setStatusName(nodeAudit.getNodeName());
				wfStatusInfo.setStatusCode(nodeAudit.getId());
				commonDao.insertObject(wfStatusInfo);

				nodeWfStatusMap.put(nodeAudit.getId(), wfStatusInfo.getId());

				if(nodeAudit.getIsstart().equals(YesNoEnum.YES.name())){
					//添加初始审核
					CustomerApplicationProcess customerApplicationProcess=new CustomerApplicationProcess();
					String serialNumber = processService.start(wf.getId());
					customerApplicationProcess.setSerialNumber(serialNumber);
					customerApplicationProcess.setNextNodeId(nodeAudit.getId());
					customerApplicationProcess.setApplicationId(customerApplicationInfo.getId());
					commonDao.insertObject(customerApplicationProcess);

					CustomerApplicationInfo applicationInfo = commonDao.findObjectById(CustomerApplicationInfo.class, customerApplicationInfo.getId());
					applicationInfo.setSerialNumber(serialNumber);
					commonDao.updateObject(applicationInfo);
				}
			}

			if(nodeAudit.getIsend().equals(YesNoEnum.YES.name())){
				endBool=true;
			}
		}
		//节点关系
		List<NodeControl> nodeControls = nodeAuditService.findNodeControlByNodeTypeAndProductId(NodeAuditTypeEnum.Product.name(), productAttribute.getId());
		for(NodeControl control : nodeControls){
			WfStatusResult wfStatusResult = new WfStatusResult();
			wfStatusResult.setCurrentStatus(nodeWfStatusMap.get(control.getCurrentNode()));
			wfStatusResult.setNextStatus(nodeWfStatusMap.get(control.getNextNode()));
			wfStatusResult.setExamineResult(control.getCurrentStatus());
			commonDao.insertObject(wfStatusResult);
		}
	}
}


text:
package com.sun.syndication.feed.synd.impl;

import com.sun.syndication.io.impl.PluginManager;
import com.sun.syndication.feed.synd.Converter;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: tucu
 * Date: May 21, 2004
 * Time: 5:26:04 PM
 * To change this template use Options | File Templates.
 */
public class Converters extends PluginManager {

    /**
     * Converter.classes=  [className] ...
     *
     */
    public static final String CONVERTERS_KEY = "Converter.classes";

    public Converters() {
        super(CONVERTERS_KEY);
    }

    public Converter getConverter(String feedType) {
        return (Converter) getPlugin(feedType);
    }

    protected String getKey(Object obj) {
        return ((Converter)obj).getType();
    }

    public List getSupportedFeedTypes() {
        return getKeys();
    }

}


text:
import datetime

from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.inclusion_tag('includes/formatted_time.html')
def format_time(date_obj, time_obj=None, datebox=False, dt_type=None, classes=None):
    """
    Returns formatted HTML5 elements based on given datetime object.
    By default returns a time element, but will return a .datebox if requested.

    dt_type allows passing dt_start or dt_end for hcal formatting.
    link allows passing a url to the datebox.

    classes allows sending arbitrary classnames. Useful for properly microformatting elements.

    Usage::

        {% format_time obj.pub_date %}
        {% format_time obj.start_date 'datebox' 'dtstart' %}
        {% format_time obj.end_date obj.end_time 'datebox' 'dt_end' %}

    """
    if not time_obj:
        time_obj = getattr(date_obj, 'time', None)

    if dt_type:
        classes = '{0} {1}'.format(classes, dt_type)
    if datebox:
        classes = '{0} {1}'.format(classes, datebox)
    return {
        'date_obj': date_obj,
        'time_obj': time_obj,
        'datebox': datebox,
        'current_year': datetime.date.today().year,
        'classes': classes
    }

@register.filter
def short_timesince(date):
    """
    A shorter version of Django's built-in timesince filter.
    Selects only the first part of the returned string,
    splitting on the comma.

    Falls back on default Django timesince if it fails.

    Example: 3 days, 20 hours becomes "3 days".

    """
    try:
        t = timesince(date).split(", ")[0]
    except IndexError:
        t = timesince(date)
    return t


text:
class CreateJoinTableConnectionUsers < ActiveRecord::Migration
  def change
    create_table :user_connections, force: true, id: false do |t|
      t.integer "from_user_id", :null => false
      t.integer "to_user_id", :null => false
    end
    add_index :user_connections, [:from_user_id, :to_user_id]
  end

end


text:
describe('ALGO', function() {
  describe('constructor', function() {
    it ('should create ALGO', function() {
      var param = {
        id: 'canvas',
        width: 320,
        height: 320,
        backgroundAuto: true
      };

      var algo = new ALGO(param);
      assert(algo !== null);
    });
  });
});


text:
<?php
	/**
##DOC-SIGNATURE##

    This file is part of WideImage.

    WideImage is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    WideImage is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with WideImage; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    * @package WideImage
  **/

namespace WideImage;

use WideImage\Exception\InvalidImageDimensionException;
use WideImage\Exception\GDFunctionResultException;

/**
 * @package WideImage
 */
class PaletteImage extends Image
{
	/**
	 * Create a palette image
	 *
	 * @param int $width
	 * @param int $height
	 * @return \WideImage\PaletteImage
	 */
	public static function create($width, $height)
	{
		if ($width * $height <= 0 || $width < 0) {
			throw new InvalidImageDimensionException("Can't create an image with dimensions [$width, $height].");
		}

		return new PaletteImage(imagecreate($width, $height));
	}

	public function doCreate($width, $height)
	{
		return static::create($width, $height);
	}

	/**
	 * (non-PHPdoc)
	 * @see \WideImage\Image#isTrueColor()
	 */
	public function isTrueColor()
	{
		return false;
	}

	/**
	 * (non-PHPdoc)
	 * @see \WideImage\Image#asPalette($nColors, $dither, $matchPalette)
	 */
	public function asPalette($nColors = 255, $dither = null, $matchPalette = true)
	{
		return $this->copy();
	}

	/**
	 * Returns a copy of the image
	 *
	 * @param $trueColor True if the new image should be truecolor
	 * @return \WideImage\Image
	 */
	protected function copyAsNew($trueColor = false)
	{
		$width = $this->getWidth();
		$height = $this->getHeight();

		if ($trueColor) {
			$new = TrueColorImage::create($width, $height);
		} else {
			$new = PaletteImage::create($width, $height);
		}

		// copy transparency of source to target
		if ($this->isTransparent()) {
			$rgb = $this->getTransparentColorRGB();

			if (is_array($rgb)) {
				$tci = $new->allocateColor($rgb['red'], $rgb['green'], $rgb['blue']);
				$new->fill(0, 0, $tci);
				$new->setTransparentColor($tci);
			}
		}

		imageCopy($new->getHandle(), $this->handle, 0, 0, 0, 0, $width, $height);

		return $new;
	}

	/**
	 * (non-PHPdoc)
	 * @see \WideImage\Image#asTrueColor()
	 */
	public function asTrueColor()
	{
		$width  = $this->getWidth();
		$height = $this->getHeight();
		$new    = WideImage::createTrueColorImage($width, $height);

		if ($this->isTransparent()) {
			$new->copyTransparencyFrom($this);
		}

		if (!imageCopy($new->getHandle(), $this->handle, 0, 0, 0, 0, $width, $height)) {
			throw new GDFunctionResultException("imagecopy() returned false");
		}

		return $new;
	}

	/**
	 * (non-PHPdoc)
	 * @see \WideImage\Image#getChannels()
	 */
	public function getChannels()
	{
		$args = func_get_args();

		if (count($args) == 1 && is_array($args[0])) {
			$args = $args[0];
		}

		return OperationFactory::get('CopyChannelsPalette')->execute($this, $args);
	}

	/**
	 * (non-PHPdoc)
	 * @see \WideImage\Image#copyNoAlpha()
	 */
	public function copyNoAlpha()
	{
		return WideImage::loadFromString($this->asString('png'));
	}
}


text:
const _ = require('lodash');
const xml = require('xml');
const moment = require('moment');
const urlUtils = require('../../../shared/url-utils');
const localUtils = require('./utils');

const XMLNS_DECLS = {
    _attr: {
        xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9'
    }
};

class SiteMapIndexGenerator {
    constructor(options) {
        options = options || {};
        this.types = options.types;
    }

    getXml() {
        const urlElements = this.generateSiteMapUrlElements();

        const data = {
            // Concat the elements to the _attr declaration
            sitemapindex: [XMLNS_DECLS].concat(urlElements)
        };

        // Return the xml
        return localUtils.getDeclarations() + xml(data);
    }

    generateSiteMapUrlElements() {
        return _.map(this.types, (resourceType) => {
            const url = urlUtils.urlFor({relativeUrl: '/sitemap-' + resourceType.name + '.xml'}, true);
            const lastModified = resourceType.lastModified;

            return {
                sitemap: [
                    {loc: url},
                    {lastmod: moment(lastModified).toISOString()}
                ]
            };
        });
    }
}

module.exports = SiteMapIndexGenerator;


text:
package exec

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"

	"fileutil"
	"tee"
	"tmpfile"
)

// Verbose & Debug
const DEBUG = false
const VERBOSE = true

// Exit codes
const EXITCODE_OK = 0
const EXITCODE_ERROR = 1
const EXITCODE_TIMEOUT = 2

const JAVA_CMD = "java"
const JAVA_MEM = "-Xmx4G"
const JAVA_NATIVE_LIB = "-Djava.library.path="
const JAVA_BDS_CLASS = "org.bds.Bds"

const BDS_NATIVE_LIB_DIR = "lib"

// Command indicating to remove file (taskLogger file)
const CMD_REMOVE_FILE = "rm"

type BdsExec struct {
	args []string 			// Command line arguments invoking 'bds'
	execName string 		// This binary's absolute path

	taskLoggerFile string 	// Task logger file to be used by 'Bds (java)'

	cmd *exec.Cmd 			// BdsExec: Command
	cmdargs []string 		// BdsExec: Command arguments
	command string 			// BdsExec: Command to execute (path to a shell script)
	outFile string 			// BdsExec: Copy (tee) stdout to this file
	errFile string 			// BdsExec: Copy (tee) stderr to this file
	exitFile string 		// BdsExec: Write exit code to this file
	timeSecs int 			// BdsExec: Maximum execution time
	exitCode int 			// Command's Exit code

	randTempFile uint32 	// Random seed
}

/*
	Invoke bds java program

	WARNING:
		It is assumed that bds.jar is in the same executable binary as 'bds'

		This is actually a nice hack used to distribute only one file. Since JAR files
		are actually ZIP files and ZIP files are indexed from the end of the file, you can
		append the JAR to the go binary (cat binary jar > new_binary) and you encapsulate
		both in the same file.

		Idea and implementation of this hack: Hernan Gonzalez
*/
func (be *BdsExec) Bds() int {
	// Create a taskLoggerFile (temp file based on pid number)
	prefix := "bds.pid." + strconv.Itoa(syscall.Getpid())
	pidTmpFile, err := tmpfile.TempFile(prefix)
	if err != nil {
		log.Fatal(err)
	}
	be.taskLoggerFile = pidTmpFile
	defer os.Remove(be.taskLoggerFile) // Make sure the PID file is new
	if DEBUG {
		log.Printf("Info: taskLoggerFile '%s'\n", be.taskLoggerFile)
	}

	bdsLibDir := path.Dir(be.execName) + "/" + BDS_NATIVE_LIB_DIR

	// Append all arguments from command line
	be.cmdargs = []string{ JAVA_CMD,
		JAVA_MEM,
		JAVA_NATIVE_LIB + bdsLibDir,
		"-cp", be.execName,
		JAVA_BDS_CLASS }
	be.cmdargs = append(be.cmdargs, "-pid")
	be.cmdargs = append(be.cmdargs, be.taskLoggerFile)
	for _, arg := range be.args[1:] {
		be.cmdargs = append(be.cmdargs, arg)
	}

	// Execute command
	be.command = JAVA_CMD
	exitCode := be.executeCommand()

	return exitCode
}

/*
  Returns absolute path of executing file.
  WARNING: this must be called before
  changing the current directory
*/
func (be *BdsExec) discoverExecName() string {
	if DEBUG {
		log.Printf("Debug: discoverExecName (%s)\n", be.args[0])
	}

	f := be.args[0]

	if path.IsAbs(f) {
		return f
	}

	wd, err := os.Getwd()
	if err != nil {
		panic(fmt.Sprintf("discoverExecName: Getwd failed '%s'", err))
	}

	_, err = os.Stat(f)
	if err == nil {
		// Relative file exists
		return path.Clean(path.Join(wd, f))
	}

	f2, err := exec.LookPath(f)
	if err != nil {
		panic(fmt.Sprintf("discoverExecName: Lookpath failed '%s'", err))
	}

	if path.IsAbs(f2) {
		return f2
	}

	return path.Clean(path.Join(wd, f2))
}

/*
	Create a new BdsExec structure
*/
func NewBdsExec(args []string) *BdsExec {
	be := &BdsExec{}

	be.args = args
	be.command = ""
	be.outFile = ""
	be.errFile = ""
	be.exitFile = ""
	be.timeSecs = 0

	be.execName = be.discoverExecName()
	f, err := filepath.EvalSymlinks(be.execName)
	if err == nil {
		be.execName = f
	}

	if DEBUG {
		log.Printf("Debug: execName:%s\n", be.execName)
	}

	return be
}

/*
	Execute a command
	Enforce execution time limit
	Redirect stdout and stderr to files
*/
func (be *BdsExec) ExecuteCommandArgs() int {
	if DEBUG {
		log.Print("Debug: ExecuteCommandArgs\n")
	}

	minArgs := 6

	if len(be.args) < minArgs {
		be.Usage("Invalid number of parameters for 'exec' command")
	}

	// Parse command line args
	cmdIdx := 2
	timeStr := be.args[cmdIdx]
	cmdIdx = cmdIdx + 1
	be.outFile = be.args[cmdIdx]
	cmdIdx = cmdIdx + 1
	be.errFile = be.args[cmdIdx]
	cmdIdx = cmdIdx + 1
	be.exitFile = be.args[cmdIdx]
	cmdIdx = cmdIdx + 1
	be.command = be.args[cmdIdx]
	cmdIdx = cmdIdx + 1

	// Append other arguments
	be.cmdargs = []string{be.command}
	for _, arg := range be.args[minArgs:] {
		be.cmdargs = append(be.cmdargs, arg)
	}

	// Parse time argument
	timeSecs, err := strconv.Atoi(timeStr)
	if err != nil {
		log.Fatalf("Invalid time: '%s'\n", timeStr)
	}
	be.timeSecs = timeSecs

	// Show PID info (parent process is expecting this line first)
	fmt.Printf("%d\n", syscall.Getpid())
	os.Stdout.Sync()

	// Execute command
	be.executeCommand()

	if DEBUG {
		log.Printf("Debug, ExecuteCommandArgs: Exit code %d\n", be.exitCode)
	}

	return be.exitCode
}

/*
	Execute a command (using arguments 'args')
	Redirect stdout to outFile    (unless file name is empty)
	Redirect stderr to errFile    (unless file name is empty)
	Write exit code to exitFile   (unless file name is empty)
	Timeout after timeout seconds (unless time is zero)
*/
func (be *BdsExec) executeCommand() int {
	if DEBUG {
		log.Printf("Debug, executeCommand %s\n", be.command)
	}

	// Redirect all signals to channel (e.g. Ctrl-C)
	osSignal := make(chan os.Signal)

	if be.taskLoggerFile != "" {
		// Main bds program
		signal.Notify(osSignal) // Capture all signals
	} else {
		// Set a new process group.
		// We want to be able to kill all child processes, without killing the
		// calling program. E.g. When running using a local executor, the Java Bds
		// calls 'bds exec', so sending a kill to the group when a timeOut occurs,
		// would also kill the parent Java program and kill the whole bds execution
		// (clearly not what we want).
		// To avoid this, we create a new group thus we can send a kill signal to
		// this new process group.

		gpidOri, _ :=  syscall.Getpgid(0);
		if err := syscall.Setpgid(0, 0); err != nil {
			// During an ssh remote execution we will no be albe to do this.
			// In this case, we assume that the SSH daemon will catch the sinals
			// and kill al child processes.
			if DEBUG {
				log.Printf("Error setting process group: %s", err)
			}
		}

		if DEBUG {
			gpidNew, _ :=  syscall.Getpgid(0);
			log.Printf("Info: Setting new process group. Original GPID: %d, new GPID: %d\n", gpidOri, gpidNew)
		}
	}

	// Create command
	be.cmd = exec.Command(be.command)
	be.cmd.Args = be.cmdargs

	// Copy stdout
	stdout := tee.NewTee(be.outFile, false)
	defer stdout.Close()
	be.cmd.Stdout = stdout

	// Copy stderr
	stderr := tee.NewTee(be.errFile, true)
	defer stderr.Close()
	be.cmd.Stderr = stderr

	// Connect to stdin
	be.cmd.Stdin = os.Stdin

	// Start process
	err := be.cmd.Start()
	if err != nil {
		log.Fatal(err)
	}

	be.exitCode = be.executeCommandTimeout(osSignal)
	if DEBUG {
		log.Printf("Debug, executeCommand: Exit code %d\n", be.exitCode)
	}
	return be.exitCode
}

/*
	Execute a command enforcing a timeout and writing exit status to 'exitFile'
*/
func (be *BdsExec) executeCommandTimeout(osSignal chan os.Signal) int {
	if DEBUG {
		log.Printf("Debug, executeCommandTimeout\n")
	}

	// Wait for execution to finish or timeout
	exitStr := ""
	if be.timeSecs <= 0 {
		be.timeSecs = 31536000 // Default: One year
	}

	// Create a timeout process
	// References: http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html
	exitCode := make(chan string, 1)
	go execute(be.cmd, exitCode)

	// Wait until executions ends, timeout or OS signal
	kill := false
	run := true
	for run {
		select {
		case exitStr = <-exitCode:
			kill = false
			run = false
			if DEBUG {
				log.Printf("Debug, executeCommandTimeout: Execution finished (%s)\n", exitStr)
			}

		case <-time.After(time.Duration(be.timeSecs) * time.Second):
			run = false
			kill = true
			exitStr = "Time out"
			if DEBUG {
				log.Printf("Debug, executeCommandTimeout: Timeout!\n")
			}

		case sig := <-osSignal:
			// Ignore some signals (e.g. "window changed")
			sigStr := sig.String()
			if sigStr != "window changed" && sigStr != "child exited" && sigStr != "window size changes" {
				if VERBOSE || DEBUG {
					log.Printf("bds: Received OS signal '%s'\n", sigStr)
				}

				kill = true
				exitStr = "Signal received"
				run = false
			}
		}
	}

	// Write exitCode to file
	if (be.exitFile != "") && (be.exitFile != "-") {
		if DEBUG {
			log.Printf("Info: Writing exit status '%s' to exit file '%s'\n", exitStr, be.exitFile )
		}
		fileutil.WriteFile(be.exitFile, exitStr)
	}

	// Should we kill child process?
	if kill {
		if DEBUG {
			log.Printf("Info: Killing process\n")
		}
		be.cmd.Process.Kill()
		be.cmd.Process.Wait() // Reap their souls
	}

	if kill {
		// Should we kill all process groups from taskLoggerFile?
		if be.taskLoggerFile != "" {
			be.taskLoggerCleanUpAll()
		}

		// Send a SIGKILL to the process group (just in case any child process is still executing)
		if DEBUG {
			log.Printf("Info: Killing process group: kill(0, SIGHUP)\n")
		}
		syscall.Kill(0, syscall.SIGHUP)
	}

	// OK? exit value should be zero
	if exitStr == "0" {
		return EXITCODE_OK
	}

	// Timeout?
	if exitStr == "Time out" {
		return EXITCODE_TIMEOUT
	}

	return EXITCODE_ERROR
}

/*
	Execute a command and writing exit status to 'exitCode'
*/
func execute(cmd *exec.Cmd, exitCode chan string) {
	if DEBUG {
		log.Printf("Debug, execute.\n")
	}

	// Wait for command to finish
	if err := cmd.Wait(); err != nil {
		if DEBUG {
			log.Printf("Debug, execute: Failed (%s)\n", err)
		}

		exitCode <- err.Error()
		return
	}

	if DEBUG {
		log.Printf("Debug, execute: Finished OK\n")
	}

	exitCode <- "0"
}

/*
	Kill a process group
*/
func (be *BdsExec) KillProcessGroup(pid int) {
	if DEBUG {
		log.Printf("Debug, killProcessGroup( %d )\n", pid)
	}

	syscall.Kill(-pid, syscall.SIGHUP)
}

// Loads configuration as map, expects key=val syntax.
// Blank lines, and lines beggining with # are ignored.
func LoadConfig(filename string, dest map[string]string) {
	if DEBUG {
		log.Printf("Debug, LoadConfig(%s)\n", filename)
	}

	re, _ := regexp.Compile("[#].*\\n|\\s+\\n|\\S+[=]|.*\n")
	fi, err := os.Stat(filename)
	if err != nil {
		return
	}
	f, err := os.Open(filename)
	if err != nil {
		return
	}
	buff := make([]byte, fi.Size())
	f.Read(buff)
	f.Close()
	str := string(buff) + "\n"
	s2 := re.FindAllString(str, -1)
	for i := 0; i < len(s2); {
		if strings.HasPrefix(s2[i], "#") {
			i++
		} else if strings.HasSuffix(s2[i], "=") {
			key := strings.ToLower(s2[i])[0 : len(s2[i])-1]
			i++
			if strings.HasSuffix(s2[i], "\n") {
				val := s2[i][0 : len(s2[i])-1]
				if strings.HasSuffix(val, "\r") {
					val = val[0 : len(val)-1]
				}
				i++
				dest[key] = val
			}
		} else if strings.Index(" \t\r\n", s2[i][0:1]) > -1 {
			i++
		} else {
			//
		}
	}
}

/*
	Perform final clean up: Parse taskLoggerFile
		i) Send kill signal to all process groups that have not been marked as 'finished'
		ii) Run commands neede to deallocate processes (e.g. cluster)
		iii) Remove stale output files form unfinshed tasks

	File format:
		"pid \t {+,-} \n"

	where '+' inidicates the process was started and '-' that
	the process finished. So all pid that do not have a '-' entry
	must be killed.
*/
func (be *BdsExec) taskLoggerCleanUpAll() {
	if DEBUG {
		log.Printf("Debug, taskLoggerCleanUpAll\n")
	}

	var (
		err  error
		line string
		file *os.File
	)

	defer os.Remove(be.taskLoggerFile) // Make sure the PID file is removed

	//---
	// Open file and parse it
	//---
	pids := make(map[string]bool)
	cmds := make(map[string]string)

	if file, err = os.Open(be.taskLoggerFile); err != nil {
		log.Printf("Error: Cannot open TaskLogger file '%s' (PID: %d)\n", be.taskLoggerFile, syscall.Getpid())
		return
	}
	defer file.Close() // Make sure the file is deleted

	// Read line by line
	if DEBUG {
		log.Printf("Debug, taskLoggerCleanUpAll: Parsing process pid file '%s'\n", be.taskLoggerFile)
	}
	reader := bufio.NewReader(file)
	for {
		if line, err = fileutil.ReadLine(reader); err != nil {
			break
		}
		recs := strings.Split(line, "\t")

		pid := recs[0]
		addDel := recs[1]
		if DEBUG {
			log.Printf("Debug, taskLoggerCleanUpAll: \t\tpid: '%s'\tadd/del: '%s'\n", pid, addDel)
		}

		// Add or remove from map
		if addDel == "-" {
			delete(pids, pid)
		} else {
			pids[pid] = true
			if len(recs) > 2 && len(recs[2]) > 0 {
				cmds[pid] = recs[2]
			}
		}
	}

	// Kill all pending processes
	runCmds := make(map[string]string)
	for pid, running := range pids {

		// Is it marked as running? Kill it
		if running {
			if cmd, ok := cmds[pid]; !ok {
				if VERBOSE {
					log.Printf("Info: Killing PID '%s'\n", pid)
				}
				pidInt, _ := strconv.Atoi(pid)
				be.KillProcessGroup(pidInt) // No need to run a command, just kill local porcess group
			} else if cmd == CMD_REMOVE_FILE {
				// This is a file to be removed, not a command
				if VERBOSE {
					log.Printf("Info: Deleting file '%s'\n", pid)
				}
				os.Remove(pid)
			} else {
				if DEBUG {
					log.Printf("Info: Killing PID '%s' using command '%s'\n", pid, runCmds[cmd])
				}

				// Create command to be executed
				if _, ok = runCmds[cmd]; ok {
					runCmds[cmd] = runCmds[cmd] + "\t" + pid
				} else {
					runCmds[cmd] = cmd + "\t" + pid
				}
			}
		} else {
			if DEBUG {
				log.Printf("Debug, taskLoggerCleanUpAll: Not killing PID '%s' (finishde running)\n", pid)
			}
		}
	}

	// Run all commands (usually it's only one command)
	for cmd, args := range runCmds {
		if len(cmd) > 0 {
			// fmt.Fprintf(os.Stderr, "\t\trunning command '%s'\n", cmd)
			if VERBOSE {
				log.Printf("Info: Running command '%s'\n", cmd)
			}
			cmdExec := exec.Command(cmd)
			cmdExec.Args = strings.Split(args, "\t")
			err := cmdExec.Run()
			if err != nil {
				log.Fatal(err)
			}
		}
	}
}

/*
	Show usage message and exit
*/
func (be *BdsExec) Usage(msg string) {
	if msg != "" {
		fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
		fmt.Fprintf(os.Stderr, "Arguments:\n")
		for n, arg := range os.Args[1:] {
			fmt.Fprintf(os.Stderr, "\t%d : %s\n", n, arg)
		}
		fmt.Fprintf(os.Stderr, "\n")
	}

	// Show help and exit
	fmt.Fprintf(os.Stderr, "Usage: bds command\n\n")
	fmt.Fprintf(os.Stderr, "Commands:\n\n")
	fmt.Fprintf(os.Stderr, "  default :  Execute bds Java program (compiler and interpreter)\n")
	fmt.Fprintf(os.Stderr, "             Syntax:\n")
	fmt.Fprintf(os.Stderr, "                 bds [options] program.bds\n\n")
	fmt.Fprintf(os.Stderr, "  exec    :  Execute shell scripts and:\n")
	fmt.Fprintf(os.Stderr, "                 i) Show pid.\n")
	fmt.Fprintf(os.Stderr, "                 ii) Enforce maimum execution time.\n")
	fmt.Fprintf(os.Stderr, "                 iii) Redirect STDOUT and STDERR to files.\n")
	fmt.Fprintf(os.Stderr, "                 iv) Write exitCode to a file.\n")
	fmt.Fprintf(os.Stderr, "             Note: If any file name is '-' it is ignored (not redirected).\n")
	fmt.Fprintf(os.Stderr, "             Syntax:\n")
	fmt.Fprintf(os.Stderr, "                 bds exec timeout file.stdout file.stderr file.exit command arguments...\n\n")
	fmt.Fprintf(os.Stderr, "  kill pid :  Kill process group 'pid'.\n")
	os.Exit(1)
}


text:
package main

import (
	"net/url"
	"strconv"
	"strings"
)

type queryNode struct {
	values   url.Values
	prefix   string
	distinct bool
	full     bool
}

func newQueryNode() queryNode {
	return queryNode{
		values:   url.Values{},
		prefix:   "",
		distinct: false,
		full:     false,
	}
}

func (q *queryNode) processFlags(queries arrayFlags) {
	for _, val := range queries {
		parts := strings.Split(val, ":")
		if len(parts) == 2 {
			name := q.prefix + parts[0]
			q.values.Set(name, parts[1])
		}
	}
}

func (q *queryNode) addOptions() {
	if limit != 0 {
		q.values.Set("limit", strconv.Itoa(limit))
	}
	if offset != 0 {
		q.values.Set("offset", strconv.Itoa(offset))
	}
	if (direction != "") && validateCV("direction", direction) {
		q.values.Set("direction", direction)
	}
	if order != "" {
		q.values.Set("order", order)
	}
	if distinct != "" {
		q.distinct = true
		q.values.Set("distinct", distinct)
	}
}