text:
local util = require "util"
local struct = require "NoloadCpp_Struct"
local common = require "CommonStyle"

--------------------------------------
-- Common functions.
local function GetIncludeGuard(spec, options)
	local temp =
		options.prefix .. spec.GetIncludeGuardString() .. "_NOLOAD_STYLE_HPP"
	return temp:upper()
end

local function GetFuncPtrName(func, spec, options)
	return func.name
end

local function GetFuncPtrTypedefName(func, spec, options)
	return "PFN" .. GetFuncPtrName(func, spec, options):upper() .. "PROC"
end

local function WriteFuncPtrTypedefStmt(hFile, func, spec, options)
	hFile:fmt("typedef %s (%s *%s)(%s);\n",
		common.GetFuncReturnType(func),
		spec.GetCodegenPtrType(),
		GetFuncPtrTypedefName(func, spec, options),
		common.GetFuncParamList(func))
end

local function GetFuncPtrDefDirect(func, spec, options)
	return string.format("%s (%s *%s)(%s)",
		common.GetFuncReturnType(func),
		spec.GetCodegenPtrType(),
		GetFuncPtrName(func, spec, options),
		common.GetFuncParamList(func, true))
end

local function GetFuncPtrDefTypedef(func, spec, options)
	return string.format("%s %s",
		GetFuncPtrTypedefName(func, spec, options),
		GetFuncPtrName(func, spec, options))
end

--------------------------------------
-- All style functions.
local my_style = {}

function my_style.WriteLargeHeader(hFile, value, options)
	local len = #value
	hFile:write("///", string.rep("/", len), "///\n")
	hFile:write("// ", value, "\n")
end

function my_style.WriteSmallHeader(hFile, value, options)
	hFile:write("// ", value, "\n")
end

function my_style.WriteBlockBeginMainNamespace(hFile, spec, options)
	if(#options.prefix > 0) then
		common.WriteNamespaceBegin(hFile, options.prefix)
	end

	common.WriteNamespaceBegin(hFile, spec.FuncNamePrefix())
end

function my_style.WriteBlockEndMainNamespace(hFile, spec, options)
	common.WriteNamespaceEnd(hFile, spec.FuncNamePrefix())

	if(#options.prefix > 0) then
		common.WriteNamespaceEnd(hFile, options.prefix)
	end
end

function my_style.WriteBlockBeginExtVariables(hFile, spec, options)
	common.WriteNamespaceBegin(hFile, "exts")
end

function my_style.WriteBlockEndExtVariables(hFile, spec, options)
	common.WriteNamespaceEnd(hFile, "exts")
end

function my_style.WriteBlockBeginSystem(hFile, spec, options)
	common.WriteNamespaceBegin(hFile, "sys")
end

function my_style.WriteBlockEndSystem(hFile, spec, options)
	common.WriteNamespaceEnd(hFile, "sys")
end

function my_style.WriteFilePreamble(hFile, specData, spec, options)
	common.WriteCPPGeneratorInfo(hFile, specData, spec, options)
end

function my_style.WriteFilePreamble(hFile, specData, spec, options)
	common.WriteCPPGeneratorInfo(hFile, specData, spec, options)
end

---------------------------------------------
-- Header functions.
local hdr = {}
my_style.hdr = hdr

function hdr.GetFilename(basename, spec, options)
	return basename .. ".hpp"
end

function hdr.WriteBlockBeginIncludeGuard(hFile, spec, options)
	local guard = GetIncludeGuard(spec, options)
	hFile:fmt("#ifndef %s\n", guard)
	hFile:fmt("#define %s\n", guard)
end

function hdr.WriteBlockEndIncludeGuard(hFile, spec, options)
	hFile:fmt("#endif //%s\n", GetIncludeGuard(spec, options))
end

function hdr.WriteGuards(hFile, spec, options)
	hFile:rawwrite(spec.GetHeaderInit())
end

function hdr.WriteTypedefs(hFile, specData, spec, options)
	local defArray = common.GetStdTypedefs()

	--Use include-guards for the typedefs, since they're common among
	--headers in this style.
	hFile:write("#ifndef GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS\n")
	hFile:write("#define GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS\n")
	hFile:write("\n")
	hFile:inc()

	for _, def in ipairs(defArray) do
		hFile:write(def)
	end

	hFile:dec()
	hFile:write("\n")
	hFile:write("#endif /*GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS*/\n")
	hFile:write("\n")

	common.WritePassthruData(hFile, specData.funcData.passthru)
end

function hdr.WriteExtension(hFile, extName, spec, options)
	hFile:fmt("extern bool var_%s;\n", extName)
end

function hdr.WriteBlockBeginEnumerators(hFile, spec, options)
	hFile:writeblock("enum\n{\n")
	hFile:inc()
end

function hdr.WriteBlockEndEnumerators(hFile, spec, options)
	hFile:dec()
	hFile:write("};\n")
end

function hdr.WriteEnumerator(hFile, enum, enumTable, spec, options, enumSeen)
	if(enumSeen[enum.name]) then
		hFile:fmt("//%s seen in %s\n", enum.name, enumSeen[enum.name])
	else
		local name = common.GetCppEnumName(enum)
		hFile:fmt("%s%s= %s,\n",
			name,
			common.GetNameLengthPadding(name, 33),
			common.ResolveEnumValue(enum, enumTable))
	end
end

function hdr.WriteFunction(hFile, func, spec, options, funcSeen)
	if(funcSeen[func.name]) then return end

	hFile:write("extern ", GetFuncPtrDefDirect(func, spec, options), ";\n")
end

function hdr.WriteSetupFunction(hFile, specData, spec, options)
	hFile:fmt("void CheckExtensions(%s);\n", spec.GetLoaderParams())
end

function hdr.WriteVersionFunctions(hFile, specData, spec, options)
end

----------------------------------------
-- Source file.
local src = {}
my_style.src = src

function src.GetFilename(basename, spec, options)
	return basename .. ".cpp"
end

function src.WriteIncludes(hFile, basename, spec, options)
	hFile:writeblock([[
#include <algorithm>
#include <string.h>
#include <stddef.h>
]])

	local base = util.ParsePath(hdr.GetFilename(basename, spec, options))
	hFile:fmt('#include "%s"\n', base)

end

function src.WriteLoaderFunc(hFile, spec, options)
	hFile:writeblock(spec.GetLoaderFunc())
end

function src.WriteExtension(hFile, extName, spec, options)
	hFile:fmt("bool var_%s = false;\n", extName)
end

function src.WriteSetupFunction(hFile, specData, spec, options)
	common.WriteNamespaceBegin(hFile, "")

	hFile:write "void ClearExtensionVariables()\n"
	hFile:write "{\n"
	hFile:inc()

	for _, extName in ipairs(options.extensions) do
		hFile:fmt("exts::var_%s = false;\n", extName)
	end

	hFile:dec()
	hFile:write "}\n"
	hFile:write "\n"

	hFile:writeblock[[
struct MapEntry
{
	const char *extName;
	bool *extVariable;
};

struct MapCompare
{
	MapCompare(const char *test_) : test(test_) {}
	bool operator()(const MapEntry &other) { return strcmp(test, other.extName) == 0; }
	const char *test;
};

struct ClearEntry
{
  void operator()(MapEntry &entry) { *(entry.extVariable) = false;}
};

]]
	local arrayLength = #options.extensions
	if(arrayLength == 0) then arrayLength = 1 end

	hFile:fmt("MapEntry g_mappingTable[%i]", arrayLength)
	if(arrayLength == 1) then
		hFile:rawwrite "; //This is intensionally left uninitialized. \n"
	else
		hFile:rawwrite " =\n"
		hFile:write "{\n"
		hFile:inc()
		for _, extName in ipairs(options.extensions) do
			hFile:fmt('{"%s%s", &exts::var_%s},\n',
				spec.ExtNamePrefix(),
				extName,
				extName)
		end
		hFile:dec()
		hFile:write "};\n"
	end

	hFile:write "\n"
	hFile:fmtblock([[
void LoadExtByName(const char *extensionName)
{
	MapEntry *tableEnd = &g_mappingTable[%i];
	MapEntry *entry = std::find_if(&g_mappingTable[0], tableEnd, MapCompare(extensionName));

	if(entry != tableEnd)
		*(entry->extVariable) = true;
}
]], #options.extensions)

	hFile:write "\n"

	local indexed = spec.GetIndexedExtStringFunc(options);
	if(indexed) then
		indexed[1] = specData.functable[indexed[1]]
		indexed[3] = specData.functable[indexed[3]]
		for _, enum in ipairs(specData.enumerators) do
			if(indexed[2] == enum.name) then
				indexed[2] = enum
			end
			if(indexed[4] == enum.name) then
				indexed[4] = enum
			end
		end

		hFile:writeblock([[
void ProcExtsFromExtList()
{
	GLint iLoop;
	GLint iNumExtensions = 0;
	]] .. indexed[1].name
	.. [[(]] .. indexed[2].name
	.. [[, &iNumExtensions);

	for(iLoop = 0; iLoop < iNumExtensions; iLoop++)
	{
		const char *strExtensionName = (const char *)]] ..
		indexed[3].name ..
		[[(]] .. indexed[4].name .. [[, iLoop);
		LoadExtByName(strExtensionName);
	}
}
]])
	else
		hFile:writeblock(
			common.GetProcessExtsFromStringFunc("LoadExtByName(%s)"))
	end

	common.WriteNamespaceEnd(hFile, "")

	hFile:fmt("void CheckExtensions(%s)\n", spec.GetLoaderParams())
	hFile:write "{\n"
	hFile:inc()
	hFile:write "ClearExtensionVariables();\n"
	hFile:fmt("std::for_each(&g_mappingTable[0], &g_mappingTable[%i], ClearEntry());\n", #options.extensions)
	hFile:write "\n"
	if(indexed) then
		hFile:write("ProcExtsFromExtList();\n")
	else
		--First, check if the GetExtStringFuncName is in the specData.
		local funcName = spec.GetExtStringFuncName()
		if(specData.functable[funcName]) then
			--Create a function pointer and load it.
			local func = specData.functable[funcName]
			funcName = "InternalGetExtensionString"

			hFile:fmt("typedef %s (%s *MYGETEXTSTRINGPROC)(%s);\n",
				common.GetFuncReturnType(func),
				spec.GetCodegenPtrType(),
				common.GetFuncParamList(func))
			hFile:fmt('MYGETEXTSTRINGPROC %s = (MYGETEXTSTRINGPROC)%s("%s%s");\n',
				funcName,
				spec.GetPtrLoaderFuncName(),
				spec.FuncNamePrefix(),
				func.name)
			hFile:fmt("if(!%s) return;\n", funcName)
			hFile:write "\n"
		end

		hFile:fmt("ProcExtsFromExtString((const char *)%s(%s));\n",
			funcName,
			spec.GetExtStringParamList(
				function (name) return spec.FuncNamePrefix() .. "::" .. name end))
	end
	hFile:dec()
	hFile:write "}\n"
end

function src.WriteVersionFunctions(hFile, specData, spec, options)
end

local typedefs = {}
src.typedefs = typedefs

function typedefs.WriteFunction(hFile, func, spec, options, funcSeen)
	if(funcSeen[func.name]) then return end
	WriteFuncPtrTypedefStmt(hFile, func, spec, options)
end

local defs = {}
src.defs = defs

function defs.WriteFunction(hFile, func, spec, options, funcSeen)
	if(funcSeen[func.name]) then return end
	hFile:write(GetFuncPtrDefTypedef(func, spec, options), ";\n")
end

local switch = {}
src.switch = switch

function switch.WriteFunction(hFile, func, spec, options, funcSeen)
	if(funcSeen[func.name]) then return end
	hFile:fmt("static %s %s Switch_%s(%s)\n",
		common.GetFuncReturnType(func),
		spec.GetCodegenPtrType(),
		func.name,
		common.GetFuncParamList(func, true))
	hFile:write "{\n"
	hFile:inc()
	hFile:fmt('%s = (%s)%s("%s%s");\n',
		GetFuncPtrName(func, spec, options),
		GetFuncPtrTypedefName(func, spec, options),
		spec.GetPtrLoaderFuncName(),
		spec.FuncNamePrefix(),
		func.name)

	if(common.DoesFuncReturnSomething(func)) then
		hFile:fmt('%s(%s);\n',
			GetFuncPtrName(func, spec, options),
			common.GetFuncParamCallList(func))
	else
		hFile:fmt('return %s(%s);\n',
			GetFuncPtrName(func, spec, options),
			common.GetFuncParamCallList(func))
	end
	hFile:dec()
	hFile:write "}\n\n"
end

function switch.WriteGetExtString(hFile, specData, spec, options, funcSeen)
	if(funcSeen[spec.GetExtStringFuncName()]) then
		return
	end

	local func = specData.funcdefs[spec.GetExtStringFuncName()]
	if(func) then
		hFile:write "\n"
		hFile:fmt("static %s %s(%s)\n",
			common.GetFuncReturnType(func),
			func.name,
			common.GetFuncParamList(func, true))
		hFile:write "{\n"
		hFile:inc()
		hFile:fmt('%s = (%s)%s("%s%s");\n',
			GetFuncPtrName(func, spec, options),
			GetFuncPtrTypedefName(func, spec, options),
			spec.GetPtrLoaderFuncName(),
			spec.FuncNamePrefix(),
			func.name)

		if(common.DoesFuncReturnSomething(func)) then
			hFile:fmt('%s(%s);\n',
				GetFuncPtrName(func, spec, options),
				common.GetFuncParamCallList(func))
		else
			hFile:fmt('return %s(%s);\n',
				GetFuncPtrName(func, spec, options),
				common.GetFuncParamCallList(func))
		end
		hFile:dec()
		hFile:write "}\n\n"
	end
end

local init = {}
src.init = init

function init.WriteBlockBeginStruct(hFile, spec, options)
	common.WriteNamespaceBegin(hFile, "")
	hFile:write("struct InitializeVariables\n")
	hFile:write "{\n"
	hFile:inc()

	hFile:write("InitializeVariables()\n")
	hFile:write "{\n"
	hFile:inc()
end

function init.WriteBlockEndStruct(hFile, spec, options)
	hFile:dec()
	hFile:write "}\n"
	hFile:dec()
	hFile:write "};\n\n"
	hFile:write("InitializeVariables g_initVariables;\n")
	common.WriteNamespaceEnd(hFile, "")
end

function init.WriteFunction(hFile, func, spec, options, funcSeen)
	if(funcSeen[func.name]) then return end

	hFile:fmt("%s = Switch_%s;\n", func.name, func.name)
end

local function Create()
	return util.DeepCopyTable(my_style), struct
end

return { Create = Create }


text:
package com.biard.batch.mapper;

import com.biard.batch.dto.ResourceMap;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.springframework.batch.item.file.LineMapper;

/**
 * {@code org.springframework.batch.item.file.mapping.JSonLineMapper} without Map<String, Object>.
 * ResourceMap is an extends of HashMap<String, Object> with resource to have the resource of file.
 */
public class JSonResourceLineMapper implements LineMapper<ResourceMap> {
    private final MappingJsonFactory factory = new MappingJsonFactory();

    /**
     * Constructor empty by default
     */
    public JSonResourceLineMapper() {
        // Constructor empty by default
    }

    /**
     * Interpret the line as a Json object and create a Map from it.
     *
     * @see LineMapper#mapLine(String, int)
     */
    @Override
    public ResourceMap mapLine(String line, int lineNumber) throws Exception {
        final ResourceMap result;
        final JsonParser parser = factory.createJsonParser(line);
        @SuppressWarnings("unchecked")
        final ResourceMap token = parser.readValueAs(ResourceMap.class);
        result = token;
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.context.environment;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

/**
 * Entry point for making local (but volatile) changes to the {@link Environment} of a
 * running application. Allows properties to be added and values changed, simply by adding
 * them to a high-priority property source in the existing Environment.
 *
 * @author Dave Syer
 *
 */
@Component
@ManagedResource
public class EnvironmentManager implements ApplicationEventPublisherAware {

	private static final String MANAGER_PROPERTY_SOURCE = "manager";

	private Map<String, Object> map = new LinkedHashMap<>();

	private ConfigurableEnvironment environment;

	private ApplicationEventPublisher publisher;

	public EnvironmentManager(ConfigurableEnvironment environment) {
		this.environment = environment;
		MutablePropertySources sources = environment.getPropertySources();
		if (sources.contains(MANAGER_PROPERTY_SOURCE)) {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = (Map<String, Object>) sources.get(MANAGER_PROPERTY_SOURCE).getSource();
			this.map = map;
		}
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}

	@ManagedOperation
	public Map<String, Object> reset() {
		Map<String, Object> result = new LinkedHashMap<>(this.map);
		if (!this.map.isEmpty()) {
			this.map.clear();
			publish(new EnvironmentChangeEvent(this.publisher, result.keySet()));
		}
		return result;
	}

	@ManagedOperation
	public void setProperty(String name, String value) {

		if (!this.environment.getPropertySources().contains(MANAGER_PROPERTY_SOURCE)) {
			synchronized (this.map) {
				if (!this.environment.getPropertySources().contains(MANAGER_PROPERTY_SOURCE)) {
					MapPropertySource source = new MapPropertySource(MANAGER_PROPERTY_SOURCE, this.map);
					this.environment.getPropertySources().addFirst(source);
				}
			}
		}

		if (!value.equals(this.environment.getProperty(name))) {
			this.map.put(name, value);
			publish(new EnvironmentChangeEvent(this.publisher, Collections.singleton(name)));
		}

	}

	@ManagedOperation
	public Object getProperty(String name) {
		return this.environment.getProperty(name);
	}

	private void publish(EnvironmentChangeEvent environmentChangeEvent) {
		if (this.publisher != null) {
			this.publisher.publishEvent(environmentChangeEvent);
		}
	}

}


text:
  package stack.compiler.analysis;

import java.util.HashSet;
import java.util.Vector;

import stack.sir.model.BasicBlock;

public class PhiRenaming {
	public static int renameVariable(BasicBlock srcBB, BasicBlock targetBB, int var) {
		return targetBB.rename(var, srcBB);
	}

	/*
	public static HashSet<Integer> renameTransferSet(BasicBlock srcBB, BasicBlock targetBB, HashSet<Integer> transferSet){
		// Rename the variables on stack according to target's phi table

		HashSet<Integer> renamedSet = new HashSet<Integer>();

		for (int variable : transferSet){
			renamedSet.add(targetBB.rename(variable, srcBB));
		}

		return renamedSet;
	}
	*/
	public static Vector<Integer> renameTransferStack(BasicBlock srcBB, BasicBlock targetBB, Vector<Integer> transferStack){
		// Rename the variables on stack according to target's phi table

		Vector<Integer> renamedStack = new Vector<Integer>();

		// TODO: trips up here sometimes

		for (int variable : transferStack){
			renamedStack.add(targetBB.rename(variable, srcBB));
		}

		return renamedStack;
	}

	public static HashSet<Integer> getPhiDefines(BasicBlock BB) {
		return BB.getPhiDefines();
	}

}


text:
@interface YYJokePicturesResponseResult : NSObject

@property (nonatomic, assign) NSInteger showapi_res_code;

@property (nonatomic, copy) NSString *showapi_res_error;

@property (nonatomic, strong) YYJokePicBodyModel *showapi_res_body;

@end


text:
<?php
namespace common\models;

use common\lib\traits\ActiveRecordTrait;
/**
 *
 * @author Yong
 */
class BaseActiveRecord extends \yii\db\ActiveRecord
{
    use ActiveRecordTrait;

    /**
     * 复写insert方法,防止数据库驱动为pgsql,id值设置为null而引起sql报错
     * (non-PHPdoc)
     * @see \yii\db\ActiveRecord::insert()
     */
    public function insert($runValidation = true, $attributes = null)
    {
        $tableSchema = $this->getTableSchema(self::tableName());
        $insertAttributes = array_keys($this->attributes);
        if(self::getDb()->driverName === 'pgsql' && $attributes === null &&
         ($pos = array_search('id', $insertAttributes)) !== false &&
         $tableSchema->columns['id']->autoIncrement &&
         !$this->attributes['id'] && !is_numeric($this->attributes['id'])
         ){
            unset($insertAttributes[$pos]);
            $attributes = $insertAttributes;
        }
        return parent::insert($runValidation, $attributes);
    }
}


text:
<?php

namespace Longman\TelegramBot\Commands\AdminCommands;

use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

/**
 * Admin "/sendtoall" command
 */
class SendtoallCommand extends AdminCommand
{
    /**
     * @var string
     */
    protected $name = 'sendtoall';

    /**
     * @var string
     */
    protected $description = 'Send the message to all of the bot\'s users';

    /**
     * @var string
     */
    protected $usage = '/sendtoall <message to send>';

    /**
     * @var string
     */
    protected $version = '1.3.0';

    /**
     * @var bool
     */
    protected $need_mysql = true;

    /**
     * Execute command
     *
     * @return boolean
     * @throws \Longman\TelegramBot\Exception\TelegramException
     */
    public function execute()
    {
        $message = $this->getMessage();

        $chat_id = $message->getChat()->getId();
        $text    = $message->getText(true);

        if ($text === '') {
            $text = 'Write the message to send: /sendtoall <message>';
        } else {
            $results = Request::sendToActiveChats(
                'sendMessage', //callback function to execute (see Request.php methods)
                ['text' => $text], //Param to evaluate the request
                true, //Send to groups (group chat)
                true, //Send to super groups chats (super group chat)
                true, //Send to users (single chat)
                null, //'yyyy-mm-dd hh:mm:ss' date range from
                null  //'yyyy-mm-dd hh:mm:ss' date range to
            );

            $total  = 0;
            $failed = 0;

            $text = 'Message sent to:' . PHP_EOL;

            /** @var ServerResponse $result */
            foreach ($results as $result) {
                $name = '';
                $type = '';
                if ($result->isOk()) {
                    $status = '✔';

                    /** @var Message $message */
                    $message = $result->getResult();
                    $chat    = $message->getChat();
                    if ($chat->isPrivateChat()) {
                        $name = $chat->getFirstName();
                        $type = 'user';
                    } else {
                        $name = $chat->getTitle();
                        $type = 'chat';
                    }
                } else {
                    $status = '✖';
                    ++$failed;
                }
                ++$total;

                $text .= $total . ') ' . $status . ' ' . $type . ' ' . $name . PHP_EOL;
            }
            $text .= 'Delivered: ' . ($total - $failed) . '/' . $total . PHP_EOL;

            if ($total === 0) {
                $text = 'No users or chats found..';
            }
        }

        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
        ];

        return Request::sendMessage($data);
    }
}


text:
Project development is moved to monorepo: https://github.com/emmetio/emmet

---

# Emmet output formatters [![Build Status](https://travis-ci.org/emmetio/markup-formatters.svg?branch=master)](https://travis-ci.org/emmetio/markup-formatters)

A collection of output formatters for Emmet abbreviations. Takes [parsed abbreviation](https://github.com/emmetio/abbreviation) and returns its string representation, formatted according to given [output profile](https://github.com/emmetio/output-profile), in one of supported syntax:

* HTML (including XML and XHTML)
* HAML
* Pug
* Slim

## Bundles

The default bundle contains all supported syntaxes. If you don't need all of them and want to cut-down your own bundle size a bit, you can import required formatters directly:

```js
// import all formatters
import format from '@emmetio/markup-formatters';

// import HTML formatter only
import html from '@emmetio/markup-formatters/dist/html.es.js';
// ...also available as CommonJS module, e.g. dist/html.cjs.js
```

## Examples

```js
import parse from '@emmetio/abbreviation';
import Profile from '@emmetio/output-profile';
import format from '@emmetio/markup-formatters';

// parse abbreviation first
const abbr = parse('ul>li.item*3>img');

// output as HTML
const htmlProfile = new Profile({
	compactBooleanAttributes: true
});
console.log(format(abbr, htmlProfile, 'html'));

// output as XML
const xmlProfile = new Profile({
	selfClosingStyle: 'xml',
	inlineBreak: 0
});
console.log(format(abbr, xmlProfile, 'html'));

// output as Slim
console.log(format(abbr, new Profile(), 'slim'));
```


text:
#ifndef SDLAUDIO_H
#define SDLAUDIO_H

#include <SDL2/SDL_mixer.h>

typedef struct {
	Mix_Chunk** chunks;
	Mix_Music** musics;
} sdl_audio;

#endif /* SDLAUDIO_H */


text:
<?xml version="1.0"?>
<Document>

	<sentence>

		<value>	Anatoly Nikolayevich Berezovoy (???????? ?????????? ?????????) is a former Soviet cosmonaut.	</value>

		<annotated-sentence>	[[Anatoly Nikolayevich Berezovoy|Anatoly_Berezovoy]] (???????? ?????????? ?????????) is a former Soviet [[cosmonaut|Astronaut]].	</annotated-sentence>

		<pattern_crowdsource>	Anatoly Nikolayevich Berezovoy (???????? ?????????? ?????????) is a former Soviet cosmonaut.	</pattern_crowdsource>

		<tree>
				nn(Berezovoy/NNP-3,Anatoly/NNP-1)
				nn(Berezovoy/NNP-3,Nikolayevich/NNP-2)
				nsubj(cosmonaut/NN-13,Berezovoy/NNP-3)
				nn(?????????/NNP-7,????????/NNP-5)
				nn(?????????/NNP-7,??????????/NNP-6)
				appos(Berezovoy/NNP-3,?????????/NNP-7)
				cop(cosmonaut/NN-13,is/VBZ-9)
				det(cosmonaut/NN-13,a/DT-10)
				amod(cosmonaut/NN-13,former/JJ-11)
				amod(cosmonaut/NN-13,Soviet/JJ-12)

		</tree>

		<annotations>

			<annotation>
				<surface-form>Anatoly Nikolayevich Berezovoy</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Anatoly_Berezovoy</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>cosmonaut</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Astronaut</RDF-ID>
			</annotation>

		</annotations>

		<triples>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	Berezovoy was born on April 11, 1942 in Enem, Adyghe Autonomous Oblast, Russian SFSR in a Ukrainian family.	</value>

		<annotated-sentence>	[[Berezovoy|Anatoly_Berezovoy]] was born on April 11, 1942 in [[Enem|Exame_Nacional_do_Ensino_M%C3%A9dio]], [[Adyghe Autonomous Oblast|Adyghe_Autonomous_Oblast]], [[Russian SFSR|Russian_Soviet_Federative_Socialist_Republic]] in a [[Ukrainian|Ukraine]] [[family|Family]].	</annotated-sentence>

		<pattern_crowdsource>	[[Berezovoy|Anatoly_Berezovoy]] was born on April 11, 1942 in Enem, Adyghe Autonomous Oblast, [[Russian SFSR|Russian_Soviet_Federative_Socialist_Republic]] in a Ukrainian family.	</pattern_crowdsource>

		<tree>
				nsubjpass(born/VBN-3,Berezovoy/NNP-1)
				auxpass(born/VBN-3,was/VBD-2)
				prep_on(born/VBN-3,April/NNP-5)
				num(April/NNP-5,11/CD-6)
				num(April/NNP-5,1942/CD-8)
				nn(Oblast/NNP-14,Enem/NNP-10)
				appos(Oblast/NNP-14,Adyghe/NNP-12)
				nn(Oblast/NNP-14,Autonomous/NNP-13)
				prep_in(April/NNP-5,Oblast/NNP-14)
				nn(SFSR/NNP-17,Russian/NNP-16)
				appos(Oblast/NNP-14,SFSR/NNP-17)
				det(family/NN-21,a/DT-19)
				amod(family/NN-21,Ukrainian/JJ-20)
				prep_in(SFSR/NNP-17,family/NN-21)

		</tree>

		<annotations>

			<annotation>
				<surface-form>Berezovoy</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Anatoly_Berezovoy</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Enem</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Exame_Nacional_do_Ensino_M%C3%A9dio</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Adyghe Autonomous Oblast</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Adyghe_Autonomous_Oblast</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Russian SFSR</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Russian_Soviet_Federative_Socialist_Republic</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Ukrainian</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Ukraine</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>family</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Family</RDF-ID>
			</annotation>

		</annotations>

		<triples>

			<triple>
				http://dbpedia.org/resource/Anatoly_Berezovoy http://dbpedia.org/ontology/birthPlace http://dbpedia.org/resource/Russian_Soviet_Federative_Socialist_Republic
			</triple>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	He is married with two children.	</value>

		<annotated-sentence>	He is married with [[two children|Child]].	</annotated-sentence>

		<pattern_crowdsource>	He is married with two children.	</pattern_crowdsource>

		<tree>
				nsubjpass(married/VBN-3,He/PRP-1)
				auxpass(married/VBN-3,is/VBZ-2)
				num(children/NNS-6,two/CD-5)
				prep_with(married/VBN-3,children/NNS-6)

		</tree>

		<annotations>

			<annotation>
				<surface-form>two children</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Child</RDF-ID>
			</annotation>

		</annotations>

		<triples>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	He graduated from the Air Force Academy He was selected as a cosmonaut on April 27, 1970.	</value>

		<annotated-sentence>	He graduated from [[the Air Force Academy|Air_force_academy]] He was selected as a cosmonaut on April 27, 1970.	</annotated-sentence>

		<pattern_crowdsource>	He graduated from the Air Force Academy He was selected as a cosmonaut on April 27, 1970.	</pattern_crowdsource>

		<tree>
				nsubj(graduated/VBD-2,He/PRP-1)
				det(Academy/NNP-7,the/DT-4)
				nn(Academy/NNP-7,Air/NNP-5)
				nn(Academy/NNP-7,Force/NNP-6)
				prep_from(graduated/VBD-2,Academy/NNP-7)
				nsubjpass(selected/VBN-10,He/PRP-8)
				auxpass(selected/VBN-10,was/VBD-9)
				ccomp(graduated/VBD-2,selected/VBN-10)
				det(cosmonaut/NN-13,a/DT-12)
				prep_as(selected/VBN-10,cosmonaut/NN-13)
				prep_on(cosmonaut/NN-13,April/NNP-15)
				num(April/NNP-15,27/CD-16)
				num(April/NNP-15,1970/CD-18)

		</tree>

		<annotations>

			<annotation>
				<surface-form>the Air Force Academy</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Air_force_academy</RDF-ID>
			</annotation>

		</annotations>

		<triples>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	He flew as Commander on Soyuz T-5.	</value>

		<annotated-sentence>	He flew as [[Commander|Commander]] on [[Soyuz T-5|Soyuz_T-5]].	</annotated-sentence>

		<pattern_crowdsource>	He flew as Commander on [[Soyuz T-5|Soyuz_T-5]].	</pattern_crowdsource>

		<tree>
				nsubj(flew/VBD-2,He/PRP-1)
				prep(flew/VBD-2,as/RB-3)
				pobj(as/RB-3,Commander/NNP-4)
				nn(T-5/NNP-7,Soyuz/NNP-6)
				prep_on(flew/VBD-2,T-5/NNP-7)

		</tree>

		<annotations>

			<annotation>
				<surface-form>Commander</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Commander</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Soyuz T-5</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Soyuz_T-5</RDF-ID>
			</annotation>

		</annotations>

		<triples>

			<triple>
				http://dbpedia.org/resource/Anatoly_Berezovoy http://dbpedia.org/ontology/mission http://dbpedia.org/resource/Soyuz_T-5
			</triple>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	He retired on October 31, 1992 due to medical reasons after injuries he got as a victim of an armed robbery.	</value>

		<annotated-sentence>	He retired on October 31, 1992 due to medical reasons after [[injuries|Injury]] he got as a victim of [[an armed robbery|Robbery]].	</annotated-sentence>

		<pattern_crowdsource>	He retired on October 31, 1992 due to medical reasons after injuries he got as a victim of an armed robbery.	</pattern_crowdsource>

		<tree>
				nsubj(retired/VBD-2,He/PRP-1)
				prep_on(retired/VBD-2,October/NNP-4)
				num(October/NNP-4,31/CD-5)
				num(October/NNP-4,1992/CD-7)
				acomp(retired/VBD-2,due/JJ-8)
				amod(reasons/NNS-11,medical/JJ-10)
				prep_to(retired/VBD-2,reasons/NNS-11)
				prep_after(retired/VBD-2,injuries/NNS-13)
				nsubj(got/VBD-15,he/PRP-14)
				rcmod(injuries/NNS-13,got/VBD-15)
				det(victim/NN-18,a/DT-17)
				prep_as(got/VBD-15,victim/NN-18)
				det(robbery/NN-22,an/DT-20)
				amod(robbery/NN-22,armed/JJ-21)
				prep_of(victim/NN-18,robbery/NN-22)

		</tree>

		<annotations>

			<annotation>
				<surface-form>injuries</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Injury</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>an armed robbery</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Robbery</RDF-ID>
			</annotation>

		</annotations>

		<triples>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

	<sentence>

		<value>	From 1992 to 1999, he was a Deputy President Russian Space Federation.	</value>

		<annotated-sentence>	From [[1992|1992]] to [[1999|1999]], he was a [[Deputy President|President]] Russian [[Space|Space]] [[Federation|Federation]].	</annotated-sentence>

		<pattern_crowdsource>	From 1992 to 1999, he was a Deputy President Russian Space Federation.	</pattern_crowdsource>

		<tree>
				num(1999/CD-4,1992/CD-2)
				dep(1999/CD-4,to/TO-3)
				prep_from(Federation/NNP-13,1999/CD-4)
				nsubj(Federation/NNP-13,he/PRP-6)
				cop(Federation/NNP-13,was/VBD-7)
				det(Federation/NNP-13,a/DT-8)
				nn(Federation/NNP-13,Deputy/NNP-9)
				nn(Federation/NNP-13,President/NNP-10)
				nn(Federation/NNP-13,Russian/NNP-11)
				nn(Federation/NNP-13,Space/NNP-12)

		</tree>

		<annotations>

			<annotation>
				<surface-form>1992</surface-form>
				<RDF-ID>http://dbpedia.org/resource/1992</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>1999</surface-form>
				<RDF-ID>http://dbpedia.org/resource/1999</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Deputy President</surface-form>
				<RDF-ID>http://dbpedia.org/ontology/President</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Space</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Space</RDF-ID>
			</annotation>

			<annotation>
				<surface-form>Federation</surface-form>
				<RDF-ID>http://dbpedia.org/resource/Federation</RDF-ID>
			</annotation>

		</annotations>

		<triples>

		</triples>

		<pattern>

			null

		</pattern>

	</sentence>

</Document>


text:
#include "backup.h"

#include <encoding/base32.h>
#include <encoding/sha256.h>
#include <encoding/pbkdf2-sha256.h>
#include <logging/logging.h>

namespace ceema {

    const unsigned HASH_LEN = 2u;
    const unsigned SALT_LEN = 8u;
    const unsigned PBKDF_ITER = 100000u;

    std::string make_backup(Account const& client, std::string const& password) {
        byte_array<SALT_LEN + CLIENTID_SIZE + crypto_box_SECRETKEYBYTES + HASH_LEN> data;
        randombytes_buf(data.data(), SALT_LEN);
        auto iter = data.begin() + SALT_LEN;
        iter = std::copy(client.id().begin(), client.id().end(), iter);
        iter = std::copy(client.sk().begin(), client.sk().end(), iter);

        byte_array<hash_256_len> hash = hash_sha256(data.begin()+SALT_LEN, CLIENTID_SIZE + crypto_box_SECRETKEYBYTES);
        iter = std::copy(hash.begin(), hash.begin()+2, iter);

        // pbkdf2+HMAC hash the password, salt with client ID. Result is encryption key
        byte_array<crypto_stream_KEYBYTES> enckey;
        PBKDF2_SHA256(reinterpret_cast<const uint8_t*>(password.data()), password.size(),
                data.data(), SALT_LEN, PBKDF_ITER, enckey.data(), enckey.size());

        /* Encrypt backup with derived key and zero nonce */
        byte_array<crypto_stream_NONCEBYTES> nonce{};
        crypto_stream_xor(data.data() + SALT_LEN, data.data() + SALT_LEN,
                          CLIENTID_SIZE + crypto_box_SECRETKEYBYTES + HASH_LEN, nonce.data(), enckey.data());

        std::string backupString = base32_encode(data);
        for(size_t i = backupString.size(); (i -= 4) > 3;) {
            backupString.insert(i, 1, '-');
        }
        return backupString;
    }

    Account decrypt_backup(std::string const &backup_string, std::string const &password) {
        byte_array<SALT_LEN + CLIENTID_SIZE + crypto_box_SECRETKEYBYTES + HASH_LEN> backup;

        /* decode Base32 */
        if (base32_decode(backup_string, backup.data(), backup.size()) != backup.size()) {
            throw std::runtime_error("Invalid backup length");
        }

        // 0.. 7 : salt
        auto salt = slice_array<0, SALT_LEN>(backup);
        // 8 .. 49 : encrypted data
        auto enc_data = slice_array<SALT_LEN, CLIENTID_SIZE + crypto_box_SECRETKEYBYTES + 2>(backup);

        // pbkdf2+HMAC hash the password, salt with client ID. Result is encryption key
        //TODO: when there is platform support, switch to libsodium implementation
        byte_array<crypto_stream_KEYBYTES> enckey;
        PBKDF2_SHA256(reinterpret_cast<const uint8_t*>(password.data()), password.size(),
                      salt.data(), salt.size(), PBKDF_ITER, enckey.data(), enckey.size());

        /* Decrypt backup with derived key and zero nonce */
        byte_array<crypto_stream_NONCEBYTES> nonce{0};
        crypto_stream_xor(enc_data.data(), enc_data.data(), enc_data.size(), nonce.data(), enckey.data());

        // Backup now contains following data:
        // 8 .. 15 : client ID
        auto clientid = slice_array<SALT_LEN, CLIENTID_SIZE>(backup);
        // 16 .. 47 : private key
        auto clientsk = slice_array<SALT_LEN + CLIENTID_SIZE, crypto_box_SECRETKEYBYTES>(backup);
        // 48 .. 49 : hash prefix
        auto hash_prefix = slice_array<SALT_LEN + CLIENTID_SIZE + crypto_box_SECRETKEYBYTES, HASH_LEN>(backup);

        /* Sanity check on result by comparing truncated SHA256 hash */
        byte_array<hash_256_len> hash = hash_sha256(backup.begin() + SALT_LEN, CLIENTID_SIZE + crypto_box_SECRETKEYBYTES);

        if (!std::equal(hash_prefix.begin(), hash_prefix.end(), hash.begin())) {
            throw std::runtime_error("Backup corrupted"); // Invalid hash
        }

        client_id id;
        std::copy(clientid.begin(), clientid.end(), id.begin());
        private_key sk;
        std::copy(clientsk.begin(), clientsk.end(), sk.begin());
        return Account(id, sk);
    }
}


text:
define(["UpgradeCard", "process/ui/UpgradeTypeUI"],
   function(UpgradeCard, UpgradeTypeUI)
   {
      "use strict";
      var UpgradeCardUI = React.createClass(
      {
         propTypes:
         {
            imageBase: PropTypes.string.isRequired,
            upgradeCard: PropTypes.object.isRequired,
         },

         render: function()
         {
            var upgrade = this.props.upgradeCard;
            var rows = [];

            var cells0 = [];
            var colspan0 = (upgrade.weaponValue ? 1 : 2);
            cells0.push(React.DOM.td(
            {
               key: cells0.length,
               colSpan: colspan0,
               className: "upgradeCardUIName",
            }, UpgradeCard.getName(upgrade.value)));

            if (upgrade.weaponValue)
            {
               cells0.push(React.DOM.td(
               {
                  key: cells0.length,
                  className: "upgradeCardUIWeaponValue",
               }, upgrade.weaponValue));
            }
            rows.push(React.DOM.tr(
            {
               key: rows.length,
            }, cells0));

            if (upgrade.header)
            {
               var cells1 = [];
               var colspan1 = (upgrade.ranges ? 1 : 2);
               cells1.push(React.DOM.td(
               {
                  key: cells1.length,
                  colSpan: colspan1,
                  className: "upgradeCardUIHeader",
               }, upgrade.header.name));

               if (upgrade.ranges)
               {
                  var ranges = UpgradeCardUI.createRangesLabel(upgrade.value);
                  cells1.push(React.DOM.td(
                  {
                     key: cells1.length,
                     className: "upgradeCardUIRanges",
                  }, ranges));
               }

               rows.push(React.DOM.tr(
               {
                  key: rows.length,
               }, cells1));
            }

            rows.push(React.DOM.tr(
            {
               key: rows.length,
            }, React.DOM.td(
            {
               colSpan: 2,
            }, upgrade.description)));

            var cells3 = [];
            cells3.push(React.DOM.td(
            {
               key: cells3.length,
               className: "upgradeCardUIImage"
            }, React.createElement(UpgradeTypeUI,
            {
               upgradeType: upgrade.type,
               imageBase: this.props.imageBase,
            })));
            cells3.push(React.DOM.td(
            {
               key: cells3.length,
               className: "upgradeCardUISquadPoints",
               title: "Squad Point cost"
            }, upgrade.squadPointCost));
            rows.push(React.DOM.tr(
            {
               key: rows.length,
            }, cells3));

            return React.DOM.table(
            {
               className: "upgradeCardUI"
            }, React.DOM.tbody(
            {}, rows));
         },
      });

      UpgradeCardUI.createRangesLabel = function(upgradeKey)
      {
         InputValidator.validateNotNull("upgradeKey", upgradeKey);

         var upgrade = UpgradeCard.properties[upgradeKey];
         var minRange;
         var maxRange;
         upgrade.ranges.forEach(function(range)
         {
            var myDistance = range.minDistance;

            if (!minRange || myDistance < minRange.minDistance)
            {
               minRange = range;
            }

            if (!maxRange || myDistance > maxRange.minDistance)
            {
               maxRange = range;
            }
         });

         var answer = minRange.name;

         if (minRange !== maxRange)
         {
            answer += "-" + maxRange.name;
         }

         return answer;
      };

      return UpgradeCardUI;
   });


text:
// Runs a suite of cuDNN benchmarks, from cudnn_benchmarks.textproto and from
// instances generated in this file. Benchmark time is measured in GPU kernel
// runtime.
//
// Potentially relevant use cases, but not yet benchmarked:
// - Double precision and half precision (pseudo, fp16 math, and tensor ops).
// - NHWC input to NCHW output, and NCHW input to NHWC output.
// - NHWC tensors with NCHW filter (forward only).
// - Using non-default scaling factors (alpha and beta).
//
#include <algorithm>
#include <functional>

#include "gflags/gflags.h"
#include "ostream_nullptr.h"
#include "glog/logging.h"
#include "ostream_nullptr.h"
#include "glog/logging.h"
#include "google/protobuf/repeated_field.h"
#include "benchmark/benchmark.h"
#include "cuda_util.h"
#include "cudnn_util.h"
#include "kernel_timer.h"
#include "load_textproto.h"

DEFINE_string(timing, "kernel-duration",
              "How to measure benchmark time. One of kernel-cycles, "
              "kernel-duration, or host-duration");
DEFINE_string(proto_path, "cudnn_benchmarks.textproto",
              "Path to text proto file containing benchmarks to run.");

namespace nvidia_libs_test {
namespace {
bool has_errors = false;

// If timing GPU cycles or duration, enable manual timing.
void ConfigureTime(benchmark::internal::Benchmark* benchmark) {
  string timing = FLAGS_timing;
  if (timing == "kernel-cycles" || timing == "kernel-duration") {
    benchmark->UseManualTime();
  }
}

// Returns the KernelTimer requested by the --timing flag.
std::unique_ptr<KernelTimer> GetTimer() {
  string timing = FLAGS_timing;
  if (timing == "kernel-cycles") {
    return KernelTimer::CreateCyclesTimer();
  }
  if (timing == "kernel-duration") {
    return KernelTimer::CreateDurationTimer();
  }
  if (timing == "host-duration") {
    return KernelTimer::CreateNopTimer();
  }
  LOG(FATAL) << "Unrecognized 'timing' flag: '" << timing << "', should be one "
             << "of 'kernel-cycles', 'kernel-duration', or 'host-duration'";
  return nullptr;
}

Status ConvolutionBenchmark(benchmark::State& state,
                            proto::ConvolutionConfig proto) {
  if (CUDNN_MAJOR < 7 && proto.convolution().group_count() > 1) {
    return ErrorStatus("Skipped: Grouped convolution requires cuDNN 7");
  }

  CudnnHandle handle = CreateCudnnHandle();
  RandomGenerator rand_gen(/*seed=*/0);

  ASSIGN_OR_RETURN_STATUS(Convolution benchmark,
                          CreateConvolution(proto, 0., 1., rand_gen));

  ASSIGN_OR_RETURN_STATUS(size_t workspace_limit, GetWorkspaceLimit(proto));

  ConvolutionAlgo algo;
  switch (proto.algo_oneof_case()) {
    case proto::ConvolutionConfig::kFindAlgo: {
      ASSIGN_OR_RETURN_STATUS(
          algo,
          FindConvolutionAlgo(handle, proto.find_algo(), benchmark.input_desc,
                              benchmark.input_data, benchmark.filter_desc,
                              benchmark.filter_data, benchmark.conv_desc,
                              benchmark.output_desc, benchmark.output_data,
                              workspace_limit));
    } break;
    case proto::ConvolutionConfig::kFwdAlgo:
      algo = static_cast<cudnnConvolutionFwdAlgo_t>(proto.fwd_algo());
      break;
    case proto::ConvolutionConfig::kBwdDataAlgo:
      algo = static_cast<cudnnConvolutionBwdDataAlgo_t>(proto.bwd_data_algo());
      break;
    case proto::ConvolutionConfig::kBwdFilterAlgo:
      algo =
          static_cast<cudnnConvolutionBwdFilterAlgo_t>(proto.bwd_filter_algo());
      break;
    default:
      LOG(FATAL) << "Invalid algo_oneof_case.";
  }

  ASSIGN_OR_RETURN_STATUS(
      size_t workspace_size,
      GetWorkspaceSize(handle, benchmark.input_desc, benchmark.filter_desc,
                       benchmark.conv_desc, benchmark.output_desc, algo));

  ASSIGN_OR_RETURN_STATUS(auto workspace, AllocateDeviceMemory(workspace_size));

  double alpha = 1.0 - proto.one_minus_alpha();
  double beta = proto.beta();

  auto timer = GetTimer();
  timer->StartTiming();
  while (state.KeepRunning()) {
    RETURN_IF_ERROR_STATUS(RunConvolution(
        handle, algo, alpha, beta, benchmark.input_desc, benchmark.input_data,
        benchmark.filter_desc, benchmark.filter_data, benchmark.conv_desc,
        benchmark.output_desc, benchmark.output_data, workspace,
        workspace_size));
    RETURN_IF_ERROR_STATUS(GetStatus(cudaDeviceSynchronize()));
    state.SetIterationTime(timer->GetTime());
    timer->ResetTime();
  }
  timer->StopTiming();

  std::ostringstream oss;
  // proto.clear_algo_oneof() has private accessibility, set oneof member and
  // clear it again instead.
  proto.set_find_algo(proto::CONVOLUTION_DIRECTION_UNSPECIFIED);
  proto.clear_find_algo();
  proto.clear_label();
  oss << "algo: " << algo << " " << proto.ShortDebugString()
      << " workspace_size: " << workspace_size;
  state.SetLabel(oss.str());

  return OkStatus();
}

Status TransformationBenchmark(benchmark::State& state,
                               const proto::TensorDescriptor& first,
                               const proto::TensorDescriptor& second) {
  CudnnHandle handle = CreateCudnnHandle();
  RandomGenerator rand_gen(/*seed=*/0);

  TensorDescriptor first_desc = CreateTensorDescriptor(first);
  TensorDescriptor second_desc = CreateTensorDescriptor(second);

  ASSIGN_OR_RETURN_STATUS(auto first_data,
                          CreateTensorData(first_desc, 0., 1., rand_gen));

  ASSIGN_OR_RETURN_STATUS(auto second_data,
                          CreateTensorData(second_desc, 0., 1., rand_gen));

  auto kernel_timer = GetTimer();
  kernel_timer->StartTiming();
  while (state.KeepRunning()) {
    RETURN_IF_ERROR_STATUS(TransformTensor(handle, first_desc, first_data,
                                           second_desc, second_data));
    RETURN_IF_ERROR_STATUS(GetStatus(cudaDeviceSynchronize()));
    state.SetIterationTime(kernel_timer->GetTime());
    kernel_timer->ResetTime();
  }
  kernel_timer->StopTiming();

  std::ostringstream oss;
  for (int dim : first.dimension()) {
    oss << "x" << dim;
  }
  state.SetLabel(oss.str().substr(1));

  return OkStatus();
}

proto::Benchmarks GetCudnnBenchmarksFromFile() {
  proto::Benchmarks benchmarks;
  LoadTextProto(FLAGS_proto_path, &benchmarks);
  return benchmarks;
}

google::protobuf::RepeatedPtrField<proto::ConvolutionConfig> GetTensorFlowBenchmarks() {
  // SAME cooresponds to the amount padding so that input and output image
  // have the same width and height. VALID corresponds to no padding.
  enum Padding { SAME, VALID };

  google::protobuf::RepeatedPtrField<proto::ConvolutionConfig> benchmarks;

  auto add_benchmark = [&](int batch, int in_height, int in_width,
                           int in_channels, int out_channels, int filter_height,
                           int filter_width, int unused_stride, Padding padding,
                           const string& label_suffix) {
    proto::TensorDescriptor input;
    input.add_dimension(batch);
    input.add_dimension(in_channels);
    input.add_dimension(in_height);
    input.add_dimension(in_width);
    input.set_data_type(proto::DATA_FLOAT);

    proto::FilterDescriptor filter;
    filter.add_dimension(out_channels);
    filter.add_dimension(in_channels);
    filter.add_dimension(filter_height);
    filter.add_dimension(filter_width);
    filter.set_data_type(proto::DATA_FLOAT);

    proto::ConvolutionDescriptor convolution;
    convolution.add_pad(padding == SAME ? filter_height / 2 : 0);
    convolution.add_pad(padding == SAME ? filter_width / 2 : 0);
    convolution.set_compute_mode(proto::DATA_FLOAT);
    if (CUDNN_MAJOR >= 7) {
      convolution.set_math_type(proto::TENSOR_OP_MATH);
    }

    proto::ConvolutionConfig benchmark;
    *benchmark.mutable_input() = std::move(input);
    *benchmark.mutable_filter() = std::move(filter);
    *benchmark.mutable_convolution() = std::move(convolution);

    for (auto direction : {proto::CONVOLUTION_FWD, proto::CONVOLUTION_BWD_DATA,
                           proto::CONVOLUTION_BWD_FILTER}) {
      for (auto format : {proto::TENSOR_NCHW, proto::TENSOR_NHWC}) {
        benchmark.set_find_algo(direction);
        benchmark.mutable_input()->set_format(format);
        // Use the same format for the filter as well.
        //
        // For NHWC forward convolution, this is usually faster than with a
        // NCHW filter but has certain restrictions (see cuDNN documentation for
        // details).
        //
        // For NHWC backward data and filter convolution, this is required.
        benchmark.mutable_filter()->set_format(format);
        benchmark.set_label(proto::ConvolutionDirection_Name(direction) + '/' +
                            proto::TensorFormat_Name(format) + '/' +
                            label_suffix);
        *benchmarks.Add() = benchmark;
      }
    }
  };

  add_benchmark(32, 5, 5, 1248, 128, 1, 1, 1, SAME, "conv0");
  add_benchmark(32, 8, 8, 384, 384, 1, 3, 1, SAME, "conv1");
  add_benchmark(32, 8, 8, 384, 384, 3, 1, 1, SAME, "conv2");
  add_benchmark(32, 8, 8, 2048, 192, 1, 1, 1, SAME, "conv3");
  add_benchmark(32, 8, 8, 448, 384, 3, 3, 1, SAME, "conv4");
  add_benchmark(32, 8, 8, 2048, 320, 1, 1, 1, SAME, "conv5");
  add_benchmark(32, 8, 8, 2048, 448, 1, 1, 1, SAME, "conv6");
  add_benchmark(32, 8, 8, 2048, 384, 1, 1, 1, SAME, "conv7");
  add_benchmark(32, 8, 8, 1760, 384, 1, 1, 1, SAME, "conv8");
  add_benchmark(32, 8, 8, 1760, 192, 1, 1, 1, SAME, "conv9");
  add_benchmark(32, 8, 8, 1760, 448, 1, 1, 1, SAME, "conv10");
  add_benchmark(32, 8, 8, 1760, 320, 1, 1, 1, SAME, "conv11");
  add_benchmark(32, 17, 17, 192, 192, 3, 3, 2, VALID, "conv12");
  add_benchmark(32, 17, 17, 192, 192, 3, 3, 1, SAME, "conv13");
  add_benchmark(32, 17, 17, 1248, 192, 1, 1, 1, SAME, "conv14");
  add_benchmark(32, 17, 17, 128, 320, 3, 3, 2, VALID, "conv15");
  add_benchmark(32, 17, 17, 1248, 128, 1, 1, 1, SAME, "conv16");
  add_benchmark(32, 17, 17, 224, 224, 1, 3, 1, SAME, "conv17");
  add_benchmark(32, 17, 17, 192, 256, 3, 1, 1, SAME, "conv18");
  add_benchmark(32, 17, 17, 192, 256, 1, 3, 1, SAME, "conv19");
  add_benchmark(32, 17, 17, 1216, 192, 1, 1, 1, SAME, "conv20");
  add_benchmark(32, 17, 17, 1216, 96, 1, 1, 1, SAME, "conv21");
  add_benchmark(32, 17, 17, 224, 224, 3, 1, 1, SAME, "conv22");
  add_benchmark(32, 17, 17, 192, 224, 3, 3, 1, SAME, "conv23");
  add_benchmark(32, 17, 17, 192, 192, 1, 3, 1, SAME, "conv24");
  add_benchmark(32, 17, 17, 1152, 192, 1, 1, 1, SAME, "conv25");
  add_benchmark(32, 17, 17, 1152, 128, 1, 1, 1, SAME, "conv26");
  add_benchmark(32, 17, 17, 192, 192, 3, 1, 1, SAME, "conv27");
  add_benchmark(32, 17, 17, 160, 192, 3, 3, 1, SAME, "conv28");
  add_benchmark(32, 17, 17, 1152, 160, 1, 1, 1, SAME, "conv29");
  add_benchmark(32, 17, 17, 1024, 128, 1, 1, 1, SAME, "conv30");
  add_benchmark(32, 17, 17, 128, 192, 1, 3, 1, SAME, "conv31");
  add_benchmark(32, 17, 17, 1024, 160, 1, 1, 1, SAME, "conv32");
  add_benchmark(32, 17, 17, 128, 192, 3, 1, 1, SAME, "conv33");
  add_benchmark(32, 17, 17, 1024, 256, 1, 1, 1, SAME, "conv34");
  add_benchmark(32, 17, 17, 128, 128, 3, 1, 1, SAME, "conv35");
  add_benchmark(32, 17, 17, 768, 192, 1, 1, 1, SAME, "conv36");
  add_benchmark(32, 17, 17, 128, 128, 1, 3, 1, SAME, "conv37");
  add_benchmark(32, 17, 17, 128, 128, 3, 3, 1, SAME, "conv38");
  add_benchmark(32, 17, 17, 768, 128, 1, 1, 1, SAME, "conv39");
  add_benchmark(32, 17, 17, 768, 320, 1, 1, 1, SAME, "conv40");
  add_benchmark(32, 35, 35, 96, 96, 3, 3, 2, VALID, "conv41");
  add_benchmark(32, 35, 35, 288, 384, 3, 3, 2, VALID, "conv42");
  add_benchmark(32, 35, 35, 64, 96, 3, 3, 1, SAME, "conv43");
  add_benchmark(32, 35, 35, 288, 64, 1, 1, 1, SAME, "conv44");
  add_benchmark(32, 35, 35, 256, 64, 1, 1, 1, SAME, "conv45");
  add_benchmark(32, 35, 35, 48, 64, 5, 5, 1, SAME, "conv46");
  add_benchmark(32, 35, 35, 256, 48, 1, 1, 1, SAME, "conv47");
  add_benchmark(32, 35, 35, 96, 96, 3, 3, 1, SAME, "conv48");
  add_benchmark(32, 35, 35, 192, 32, 1, 1, 1, SAME, "conv49");
  add_benchmark(32, 35, 35, 192, 64, 1, 1, 1, SAME, "conv50");
  add_benchmark(32, 35, 35, 192, 48, 1, 1, 1, SAME, "conv51");
  add_benchmark(32, 73, 73, 64, 192, 3, 3, 1, VALID, "conv52");
  add_benchmark(32, 73, 73, 64, 64, 1, 1, 1, VALID, "conv53");
  add_benchmark(32, 147, 147, 24, 64, 1, 1, 1, VALID, "conv54");

  std::stable_sort(benchmarks.begin(), benchmarks.end(),
                   [](const proto::ConvolutionConfig& left,
                      const proto::ConvolutionConfig& right) {
                     return left.find_algo() < right.find_algo();
                   });

  return benchmarks;
}

google::protobuf::RepeatedPtrField<proto::ConvolutionConfig> GetDepthwiseBenchmarks() {
  google::protobuf::RepeatedPtrField<proto::ConvolutionConfig> benchmarks;

  if (CUDNN_MAJOR < 7) {
    return benchmarks;  // No grouped convolution before cuDNN 7.
  }

  auto add_benchmark = [&](int batch, int in_height, int in_width,
                           int in_channels, int out_channels, int filter_height,
                           int filter_width, const string& label_suffix) {
    proto::TensorDescriptor input;
    input.add_dimension(batch);
    input.add_dimension(in_channels);
    input.add_dimension(in_height);
    input.add_dimension(in_width);

    proto::FilterDescriptor filter;
    filter.add_dimension(out_channels);
    filter.add_dimension(1);
    filter.add_dimension(filter_height);
    filter.add_dimension(filter_width);

    proto::ConvolutionDescriptor convolution;
    convolution.add_pad(filter_height / 2);
    convolution.add_pad(filter_width / 2);
    convolution.set_group_count(in_channels);
    // Note: tensor cores are not currently (cuDNN 7.1) supported for grouped
    // convolutions.
    convolution.set_math_type(proto::TENSOR_OP_MATH);

    proto::TensorDescriptor output;
    output.add_dimension(batch);
    output.add_dimension(out_channels);
    output.add_dimension(in_height);
    output.add_dimension(in_width);

    proto::ConvolutionConfig benchmark;
    *benchmark.mutable_input() = std::move(input);
    *benchmark.mutable_filter() = std::move(filter);
    *benchmark.mutable_convolution() = std::move(convolution);
    *benchmark.mutable_output() = std::move(output);

    for (auto direction : {proto::CONVOLUTION_FWD, proto::CONVOLUTION_BWD_DATA,
                           proto::CONVOLUTION_BWD_FILTER}) {
      for (auto data_type : {proto::DATA_FLOAT, proto::DATA_HALF}) {
        benchmark.mutable_input()->set_data_type(data_type);
        benchmark.mutable_filter()->set_data_type(data_type);
        benchmark.mutable_output()->set_data_type(data_type);
        std::vector<proto::DataType> compute_modes = {proto::DATA_FLOAT};
        if (data_type == proto::DATA_HALF) {
          compute_modes.push_back(proto::DATA_HALF);
        }
        for (auto compute_mode : compute_modes) {
          // Note: true half configuration is terribly slow.
          benchmark.mutable_convolution()->set_compute_mode(compute_mode);
          std::vector<proto::TensorFormat> formats = {proto::TENSOR_NCHW};
          if (direction == proto::CONVOLUTION_FWD) {
            formats.push_back(proto::TENSOR_NHWC);
          }
          for (auto format : formats) {
            benchmark.set_find_algo(direction);
            benchmark.mutable_input()->set_format(format);
            // Note: OHWI filter format is not supported for grouped
            // convolutions.
            benchmark.mutable_filter()->set_format(proto::TENSOR_NCHW);
            benchmark.mutable_output()->set_format(format);
            benchmark.set_label(proto::ConvolutionDirection_Name(direction) +
                                '/' + proto::TensorFormat_Name(format) + '/' +
                                proto::DataType_Name(data_type) + '/' +
                                proto::DataType_Name(compute_mode) + '/' +
                                label_suffix);
            *benchmarks.Add() = benchmark;
          }
        }
      }
    }
  };

  add_benchmark(128, 64, 64, 32, 32, 3, 3, "depthwise0");

  std::stable_sort(benchmarks.begin(), benchmarks.end(),
                   [](const proto::ConvolutionConfig& left,
                      const proto::ConvolutionConfig& right) {
                     return left.label() < right.label();
                   });

  return benchmarks;
}

void RegisterConvolutionBenchmarks(
    const string& prefix,
    const google::protobuf::RepeatedPtrField<proto::ConvolutionConfig>& benchmarks) {
  for (const auto& benchmark : benchmarks) {
    ConfigureTime(benchmark::RegisterBenchmark(
        ("BM_CudnnConvolution/" + prefix + "/" + benchmark.label()).c_str(),
        [benchmark](benchmark::State& state) {
          auto status = ConvolutionBenchmark(state, benchmark);
          if (!status.ok()) {
            state.SkipWithError(status.message().c_str());
            ResetDevice();
          }
        }));
  }
}

void RegisterTransformationBenchmarks() {
  auto add_benchmark = [](int batch, int height, int width, int channels,
                          const string& label_suffix) {
    auto runner = [](benchmark::State& state,
                     const proto::TensorDescriptor& first,
                     const proto::TensorDescriptor& second) {
      auto status = TransformationBenchmark(state, first, second);
      if (!status.ok()) {
        state.SkipWithError(status.message().c_str());
        ResetDevice();
      }
    };

    proto::TensorDescriptor nchw;
    nchw.add_dimension(batch);
    nchw.add_dimension(channels);
    nchw.add_dimension(height);
    nchw.add_dimension(width);
    nchw.set_format(proto::TENSOR_NCHW);
    nchw.set_data_type(proto::DATA_FLOAT);

    proto::TensorDescriptor nhwc = nchw;
    nchw.set_format(proto::TENSOR_NHWC);

    ConfigureTime(benchmark::RegisterBenchmark(
        ("BM_CudnnTransformation/NchwToNhwc/" + label_suffix).c_str(),
        std::bind(runner, std::placeholders::_1, nchw, nhwc)));

    ConfigureTime(benchmark::RegisterBenchmark(
        ("BM_CudnnTransformation/NhwcToNchw/" + label_suffix).c_str(),
        std::bind(runner, std::placeholders::_1, nhwc, nchw)));
  };

  // Uses the same tensor sizes and indices as GetTensorFlowBenchmarks() above.
  add_benchmark(32, 5, 5, 1248, "trans0");
  add_benchmark(32, 8, 8, 384, "trans1");
  add_benchmark(32, 8, 8, 2048, "trans3");
  add_benchmark(32, 8, 8, 448, "trans4");
  add_benchmark(32, 8, 8, 1760, "trans8");
  add_benchmark(32, 17, 17, 192, "trans12");
  add_benchmark(32, 17, 17, 1248, "trans14");
  add_benchmark(32, 17, 17, 128, "trans15");
  add_benchmark(32, 17, 17, 224, "trans17");
  add_benchmark(32, 17, 17, 1216, "trans20");
  add_benchmark(32, 17, 17, 1152, "trans25");
  add_benchmark(32, 17, 17, 160, "trans28");
  add_benchmark(32, 17, 17, 1024, "trans30");
  add_benchmark(32, 17, 17, 768, "trans36");
  add_benchmark(32, 35, 35, 96, "trans41");
  add_benchmark(32, 35, 35, 288, "trans42");
  add_benchmark(32, 35, 35, 64, "trans43");
  add_benchmark(32, 35, 35, 256, "trans45");
  add_benchmark(32, 35, 35, 48, "trans46");
  add_benchmark(32, 35, 35, 192, "trans49");
  add_benchmark(32, 73, 73, 64, "trans52");
  add_benchmark(32, 147, 147, 24, "trans54");
}

void RegisterBenchmarks() {
  RegisterConvolutionBenchmarks(
      "FromFile", GetCudnnBenchmarksFromFile().convolution_benchmark());
  RegisterConvolutionBenchmarks("TensorFlow", GetTensorFlowBenchmarks());
  RegisterConvolutionBenchmarks("Depthwise", GetDepthwiseBenchmarks());
  RegisterTransformationBenchmarks();
}

}  // namespace
}  // namespace nvidia_libs_test

int main(int argc, char** argv) {
  // Initialize benchmarks before parsing flags. Both consume recognized flags,
  // but only the latter reports an error if a flag is not recognized.
  benchmark::Initialize(&argc, argv);
  // Parse flags before initializing logging, otherwise logs are not printed.
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  if (benchmark::ReportUnrecognizedArguments(argc, argv)) {
    return 1;
  }
  nvidia_libs_test::RegisterBenchmarks();
  benchmark::RunSpecifiedBenchmarks();
  return nvidia_libs_test::has_errors;
}


text:
//
//  CountryCode.h
//  CountryCode
//
//  Created by dennis on 2015/9/22.
//  Copyright © 2015年 dennis. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface CountryCode : NSObject

+ (CountryCode *)sharedInstance;
/**
 *  搜尋國家名稱
 *
 *  @param keyword 輸入要搜尋的關鍵字
 *
 *  @return 回傳一陣列為有關鍵字的國家
 */
-(NSMutableArray *)searchCountryCodeWithKeyword:(NSString *)keyword;
/**
 *  搜尋國家代號
 *
 *  @param keyword 輸入要搜尋的國家代號
 *
 *  @return 回傳一陣列為有此關鍵字的國家
 */
-(NSMutableArray *)searchCountryIDWithKeyword:(NSString *)keyword;
@property(nonatomic, strong) NSMutableArray *resultArray;
@property(nonatomic, strong) NSDictionary *countryDictionary;
@end


text:
@interface UtilityTests : XCTestCase

@end

@implementation UtilityTests

- (void)setUp
{
    [super setUp];
    [Utility commonSettins];
    [Utility cleanUpAllDatabase];
}

- (void)testCleanUpAllDatabase
{
    [Utility enumerateAllTwitterStorageUsingBlock:^(TwitterStorage *twitterStorage) {
        [Utility addTweetsWithTwitterStorage:twitterStorage count:100];
    }];

    [Utility cleanUpAllDatabase];

    XCTAssertFalse([YSFileManager fileExistsAtPath:[Utility coreDataDocumentPathWithStoreType:UtilityStoreTypeSQLite]]);
    XCTAssertFalse([YSFileManager fileExistsAtPath:[Utility coreDataDocumentPathWithStoreType:UtilityStoreTypeBinary]]);
    XCTAssertFalse([YSFileManager fileExistsAtPath:[Utility twitterStorageDocumentPathWithStoreType:UtilityStoreTypeSQLite]]);
    XCTAssertFalse([YSFileManager fileExistsAtPath:[Utility twitterStorageDocumentPathWithStoreType:UtilityStoreTypeBinary]]);

    XCTAssertTrue([YSFileManager fileExistsAtPath:[Utility twitterStorageMainBundlePath]]);

    for (YSCoreData *coreData in @[[Utility twitterStorageOfMainBundle],
                                   [Utility coreDataWithStoreType:UtilityStoreTypeInMemory],
                                   [Utility twitterStorageWithStoreType:UtilityStoreTypeInMemory]])
    {
        for (NSNumber *count in [[coreData countAllEntitiesByName] allValues]) {
            XCTAssertEqual(count.integerValue, 0);
        }
    }

    XCTAssertFalse([YSFileManager fileExistsAtPath:[TwitterStorage sharedInstance].databaseFullPath]);
}

- (void)testCreateCoreData
{
    for (NSNumber *storeTypeNum in @[@(UtilityStoreTypeSQLite), @(UtilityStoreTypeBinary)]) {
        UtilityStoreType storeType = [storeTypeNum unsignedIntegerValue];
        XCTAssertNotNil([Utility coreDataWithStoreType:storeType]);
        XCTAssertTrue([YSFileManager fileExistsAtPath:[Utility coreDataDocumentPathWithStoreType:storeType]]);
    }
}

- (void)testCreateTwitterStorage
{
    for (NSNumber *storeTypeNum in @[@(UtilityStoreTypeSQLite), @(UtilityStoreTypeBinary)]) {
        UtilityStoreType storeType = [storeTypeNum unsignedIntegerValue];
        XCTAssertNotNil([Utility twitterStorageWithStoreType:storeType]);
        XCTAssertTrue([YSFileManager fileExistsAtPath:[Utility twitterStorageDocumentPathWithStoreType:storeType]]);
    }
}

- (void)testExistsTwitterStorageOfMainBundle
{
    XCTAssertNotNil([Utility twitterStorageOfMainBundle]);
    XCTAssertTrue([YSFileManager fileExistsAtPath:[Utility twitterStorageMainBundlePath]]);
}

@end


text:
<?php

namespace Sonata\IntlBundle\Templating\Helper;

use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\HttpFoundation\Session;

/**
 * DateHelper displays culture information. More information here
 * http://userguide.icu-project.org/formatparse/datetime
 *
 * @author Thomas Rabaix <thomas.rabaix@ekino.com>
 */
class DateTimeHelper extends Helper
{
    protected $session;

    /**
     * Constructor.
     *
     * @param Session $session A Session instance
     * @param array $attributes The default attributes to apply to the NumberFormatter instance
     * @param array $textAttributes The default text attributes to apply to the NumberFormatter instance
     */
    public function __construct(Session $session)
    {
        $this->session          = $session;
    }

    public function formatDate($date, $locale = null)
    {
        $formatter = new \IntlDateFormatter(
            $locale ?: $this->session->getLocale() ,
            \IntlDateFormatter::MEDIUM,
            \IntlDateFormatter::NONE
        );

        return $formatter->format($this->getTimestamp($date));
    }

    public function formatDateTime($datetime, $locale = null)
    {
        $formatter = new \IntlDateFormatter(
            $locale ?: $this->session->getLocale() ,
            \IntlDateFormatter::MEDIUM,
            \IntlDateFormatter::MEDIUM
        );

        return $formatter->format($this->getTimestamp($datetime));
    }

    public function formatTime($time, $locale = null)
    {
        $formatter = new \IntlDateFormatter(
            $locale ?: $this->session->getLocale() ,
            \IntlDateFormatter::NONE,
            \IntlDateFormatter::MEDIUM
        );

        return $formatter->format($this->getTimestamp($time));
    }

    public function format($datetime, $pattern, $locale = null)
    {
        $formatter = new \IntlDateFormatter(
            $locale ?: $this->session->getLocale() ,
            \IntlDateFormatter::FULL,
            \IntlDateFormatter::FULL,
            $datetime instanceof DateTime ? $datetime->getTimeZone()->getName() : null,
            \IntlDateFormatter::GREGORIAN,
            $pattern
        );

        return $formatter->format($this->getTimestamp($datetime));
    }

    public function getTimestamp($data)
    {
        if($data instanceof \DateTime) {
            $data = $data->format('U');
        }

        // the format method accept array or integer
        if(is_numeric($data)) {
            return (int)$data;
        }

        return $data;
    }
    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        return 'sonata_intl_datetime';
    }

}


text:
package com.model.bitbucket;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

class Links implements Parcelable {

    @SerializedName("avatar")
    @Expose
    Avatar avatar;

    public Links() {
    }

    protected Links(Parcel in) {
        avatar = (Avatar) in.readValue(Avatar.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(avatar);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Links> CREATOR = new Parcelable.Creator<Links>() {
        @Override
        public Links createFromParcel(Parcel in) {
            return new Links(in);
        }

        @Override
        public Links[] newArray(int size) {
            return new Links[size];
        }
    };
}


text:
package objektwerks

import com.typesafe.config.ConfigFactory
import com.datastax.oss.driver.api.core.CqlSession

import java.net.InetSocketAddress

import org.apache.spark.sql.streaming.OutputMode
import org.apache.spark.sql.types.{StringType, StructType}
import org.apache.spark.sql.{DataFrame, SparkSession}

object KafkaStructuredStreamingCassandraApp {
  def main(args: Array[String]): Unit = {
    val conf = ConfigFactory.load("app.conf").getConfig("app")
    val (kafkaBootstrapServers, urls) = ("kafka.bootstrap.servers", conf.getString("kafka-bootstrap-servers"))
    val sourceTopic = conf.getString("source-topic")

    val sparkEventLogDir = conf.getString("spark.eventLog.dir")
    val sparkEventDirCreated = createSparkEventsDir(sparkEventLogDir)
    println(s"*** $sparkEventLogDir exists or was created: $sparkEventDirCreated")

    val keyValueStructType = new StructType()
      .add(name = "key", dataType = StringType, nullable = false)
      .add(name = "value", dataType = StringType, nullable = false)

    val address = new InetSocketAddress("127.0.0.1", 9042)
    val datacenter = "datacenter1"
    val session = CqlSession
      .builder()
      .addContactPoint(address)
      .withLocalDatacenter(datacenter)
      .build()
    session.execute("DROP KEYSPACE IF EXISTS kssc;")
    session.execute("CREATE KEYSPACE kssc WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1 };")
    session.execute("CREATE TABLE kssc.keyvalue(key text PRIMARY KEY, value text);")

    val sparkSession = SparkSession.builder
      .master(conf.getString("master"))
      .appName(conf.getString("name"))
      .config("spark.eventLog.enabled", conf.getBoolean("spark.eventLog.enabled"))
      .config("spark.eventLog.dir", sparkEventLogDir)
      .config("spark.cassandra.connection.host", conf.getString("cassandra-host"))
      .config("spark.cassandra.auth.username", conf.getString("cassandra-username"))
      .config("spark.cassandra.auth.password", conf.getString("cassandra-password"))
      .getOrCreate()
    println("*** Initialized Spark KafkaStructuredStreamingCassandraApp. Press Ctrl C to terminate.")

    sys.addShutdownHook {
      sparkSession.stop
      println("*** Terminated Spark KafkaStructuredStreamingCassandraApp.")
    }

    val consoleQuery = sparkSession
      .readStream
      .format("kafka")
      .option(kafkaBootstrapServers, urls)
      .option("subscribe", sourceTopic)
      .load
      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)", "CAST(topic AS STRING)")
      .writeStream
      .outputMode(OutputMode.Append)
      .format("console")
      .start

    val jsonToSourceTopic = sparkSession
      .readStream
      .option("basePath", conf.getString("key-value-json-path"))
      .schema(keyValueStructType)
      .json(conf.getString("key-value-json-path"))
      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
      .writeStream
      .format("kafka")
      .option(kafkaBootstrapServers, urls)
      .option("topic", sourceTopic)
      .option("checkpointLocation", conf.getString("source-topic-checkpoint-location"))
      .start

    import org.apache.spark.sql.functions._

    val sourceTopicToCassandraTable = sparkSession
      .readStream
      .format("kafka")
      .option(kafkaBootstrapServers, urls)
      .option("subscribe", sourceTopic)
      .load
      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
      .withColumn("value", upper(col("value")))
      .writeStream
      .foreachBatch { (batchDF: DataFrame, _: Long) =>
        batchDF
          .write
          .format("org.apache.spark.sql.cassandra")
          .options(Map("keyspace" -> "kssc", "table" -> "keyvalue"))
          .mode("append")
          .save()
      }
      .option("checkpointLocation", conf.getString("cassandra-checkpoint-location"))
      .outputMode("update")
      .start

    consoleQuery.awaitTermination
    jsonToSourceTopic.awaitTermination
    sourceTopicToCassandraTable.awaitTermination

    ()
  }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>help</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module help

Classes

    Cmd

Variables

    __package__

[hide private]


text:
package io.cloudslang.lang.compiler.modeller.transformers;

import io.cloudslang.lang.compiler.SlangTextualKeys;
import io.cloudslang.lang.compiler.modeller.model.SeqStep;
import io.cloudslang.lang.compiler.modeller.result.BasicTransformModellingResult;
import io.cloudslang.lang.compiler.modeller.result.TransformModellingResult;
import io.cloudslang.lang.compiler.validator.PreCompileValidator;
import io.cloudslang.lang.entities.ScoreLangConstants;
import io.cloudslang.lang.entities.SensitivityLevel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Sets.newHashSet;
import static io.cloudslang.lang.compiler.CompilerConstants.DEFAULT_SENSITIVITY_LEVEL;
import static io.cloudslang.lang.compiler.SlangTextualKeys.SEQ_ACTION_KEY;
import static io.cloudslang.lang.compiler.SlangTextualKeys.SEQ_EXTERNAL_KEY;
import static io.cloudslang.lang.compiler.modeller.transformers.Transformer.Scope.ACTION;
import static java.lang.Boolean.FALSE;
import static java.util.Collections.singletonList;

public class SeqActionTransformer extends AbstractTransformer
        implements Transformer<Map<String, Serializable>, Map<String, Serializable>> {
    private final DependencyFormatValidator dependencyFormatValidator;
    private final PreCompileValidator preCompileValidator;
    private final SeqStepsTransformer seqStepsTransformer;

    public SeqActionTransformer(DependencyFormatValidator dependencyFormatValidator,
                                PreCompileValidator preCompileValidator,
                                SeqStepsTransformer seqStepsTransformer) {
        this.dependencyFormatValidator = dependencyFormatValidator;
        this.preCompileValidator = preCompileValidator;
        this.seqStepsTransformer = seqStepsTransformer;
    }

    private static final Set<String> MANDATORY_KEY_SET = newHashSet(SlangTextualKeys.SEQ_ACTION_GAV_KEY);
    private static final Set<String> OPTIONAL_KEY_SET = newHashSet(SlangTextualKeys.SEQ_STEPS_KEY,
            SlangTextualKeys.SEQ_EXTERNAL_KEY, SlangTextualKeys.SEQ_SETTINGS_KEY, SlangTextualKeys.SEQ_SKILLS_KEY,
            SlangTextualKeys.OBJECT_REPOSITORY_KEY);

    @Override
    public TransformModellingResult<Map<String, Serializable>> transform(Map<String, Serializable> rawData) {
        return transform(rawData, DEFAULT_SENSITIVITY_LEVEL);
    }

    @Override
    public TransformModellingResult<Map<String, Serializable>> transform(Map<String, Serializable> rawData,
                                                                         SensitivityLevel sensitivityLevel) {
        List<RuntimeException> errors = new ArrayList<>();
        Map<String, Serializable> transformedData = null;

        try {
            if (rawData != null) {
                validateKeySet(rawData.keySet(), MANDATORY_KEY_SET, OPTIONAL_KEY_SET);
                transformGav(rawData);
                transformSteps(rawData, errors, sensitivityLevel);
                transformedData = rawData;
            }
        } catch (RuntimeException rex) {
            errors.add(rex);
        }

        return new BasicTransformModellingResult<>(transformedData, errors);
    }

    private void transformGav(Map<String, Serializable> rawData) {
        String gav = (String) rawData.remove(SlangTextualKeys.SEQ_ACTION_GAV_KEY);
        dependencyFormatValidator.validateDependency(gav);
        rawData.put(ScoreLangConstants.SEQ_ACTION_GAV_KEY, gav);
    }

    private void transformSteps(Map<String, Serializable> rawData,
                                List<RuntimeException> errors,
                                SensitivityLevel sensitivityLevel) {
        Serializable externalValue = rawData.remove(SlangTextualKeys.SEQ_EXTERNAL_KEY);
        Boolean external = parseExternalValue(errors, externalValue);
        rawData.put(ScoreLangConstants.SEQ_EXTERNAL_KEY, external);

        List<Map<String, Map<String, String>>> steps = preCompileValidator
                .validateSeqActionSteps(rawData.remove(SlangTextualKeys.SEQ_STEPS_KEY), errors, external);
        TransformModellingResult<ArrayList<SeqStep>> transformedSteps = seqStepsTransformer
                .transform(steps, sensitivityLevel);
        errors.addAll(transformedSteps.getErrors());
        ArrayList<SeqStep> transformedData = transformedSteps.getTransformedData();

        rawData.put(ScoreLangConstants.SEQ_STEPS_KEY, transformedData);
    }

    private Boolean parseExternalValue(List<RuntimeException> errors, Serializable externalValue) {
        Boolean external;
        if (externalValue instanceof Boolean) {
            external = (Boolean) externalValue;
        } else if (externalValue instanceof String) {
            external = Boolean.valueOf((String) externalValue);
        } else {
            external = FALSE;
            if (externalValue != null) {
                errors.add(new RuntimeException("Unsupported value found for '" + SEQ_EXTERNAL_KEY + "' key. " +
                        "Supported values are: [true, false]."));
            }
        }
        return external;
    }

    @Override
    public List<Scope> getScopes() {
        return singletonList(ACTION);
    }

    @Override
    public String keyToTransform() {
        return SEQ_ACTION_KEY;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/datalabeling/v1beta1/operations.proto

namespace Google\Cloud\DataLabeling\V1beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Response used for ExportDataset longrunning operation.
 *
 * Generated from protobuf message google.cloud.datalabeling.v1beta1.ExportDataOperationResponse
 */
class ExportDataOperationResponse extends \Google\Protobuf\Internal\Message
{
    /**
     * Ouptut only. The name of dataset.
     * "projects/*/datasets/*"
     *
     * Generated from protobuf field string dataset = 1;
     */
    private $dataset = '';
    /**
     * Output only. Total number of examples requested to export
     *
     * Generated from protobuf field int32 total_count = 2;
     */
    private $total_count = 0;
    /**
     * Output only. Number of examples exported successfully.
     *
     * Generated from protobuf field int32 export_count = 3;
     */
    private $export_count = 0;
    /**
     * Output only. Statistic infos of labels in the exported dataset.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.LabelStats label_stats = 4;
     */
    private $label_stats = null;
    /**
     * Output only. output_config in the ExportData request.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.OutputConfig output_config = 5;
     */
    private $output_config = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $dataset
     *           Ouptut only. The name of dataset.
     *           "projects/*/datasets/*"
     *     @type int $total_count
     *           Output only. Total number of examples requested to export
     *     @type int $export_count
     *           Output only. Number of examples exported successfully.
     *     @type \Google\Cloud\DataLabeling\V1beta1\LabelStats $label_stats
     *           Output only. Statistic infos of labels in the exported dataset.
     *     @type \Google\Cloud\DataLabeling\V1beta1\OutputConfig $output_config
     *           Output only. output_config in the ExportData request.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Datalabeling\V1Beta1\Operations::initOnce();
        parent::__construct($data);
    }

    /**
     * Ouptut only. The name of dataset.
     * "projects/*/datasets/*"
     *
     * Generated from protobuf field string dataset = 1;
     * @return string
     */
    public function getDataset()
    {
        return $this->dataset;
    }

    /**
     * Ouptut only. The name of dataset.
     * "projects/*/datasets/*"
     *
     * Generated from protobuf field string dataset = 1;
     * @param string $var
     * @return $this
     */
    public function setDataset($var)
    {
        GPBUtil::checkString($var, True);
        $this->dataset = $var;

        return $this;
    }

    /**
     * Output only. Total number of examples requested to export
     *
     * Generated from protobuf field int32 total_count = 2;
     * @return int
     */
    public function getTotalCount()
    {
        return $this->total_count;
    }

    /**
     * Output only. Total number of examples requested to export
     *
     * Generated from protobuf field int32 total_count = 2;
     * @param int $var
     * @return $this
     */
    public function setTotalCount($var)
    {
        GPBUtil::checkInt32($var);
        $this->total_count = $var;

        return $this;
    }

    /**
     * Output only. Number of examples exported successfully.
     *
     * Generated from protobuf field int32 export_count = 3;
     * @return int
     */
    public function getExportCount()
    {
        return $this->export_count;
    }

    /**
     * Output only. Number of examples exported successfully.
     *
     * Generated from protobuf field int32 export_count = 3;
     * @param int $var
     * @return $this
     */
    public function setExportCount($var)
    {
        GPBUtil::checkInt32($var);
        $this->export_count = $var;

        return $this;
    }

    /**
     * Output only. Statistic infos of labels in the exported dataset.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.LabelStats label_stats = 4;
     * @return \Google\Cloud\DataLabeling\V1beta1\LabelStats|null
     */
    public function getLabelStats()
    {
        return $this->label_stats;
    }

    public function hasLabelStats()
    {
        return isset($this->label_stats);
    }

    public function clearLabelStats()
    {
        unset($this->label_stats);
    }

    /**
     * Output only. Statistic infos of labels in the exported dataset.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.LabelStats label_stats = 4;
     * @param \Google\Cloud\DataLabeling\V1beta1\LabelStats $var
     * @return $this
     */
    public function setLabelStats($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\DataLabeling\V1beta1\LabelStats::class);
        $this->label_stats = $var;

        return $this;
    }

    /**
     * Output only. output_config in the ExportData request.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.OutputConfig output_config = 5;
     * @return \Google\Cloud\DataLabeling\V1beta1\OutputConfig|null
     */
    public function getOutputConfig()
    {
        return $this->output_config;
    }

    public function hasOutputConfig()
    {
        return isset($this->output_config);
    }

    public function clearOutputConfig()
    {
        unset($this->output_config);
    }

    /**
     * Output only. output_config in the ExportData request.
     *
     * Generated from protobuf field .google.cloud.datalabeling.v1beta1.OutputConfig output_config = 5;
     * @param \Google\Cloud\DataLabeling\V1beta1\OutputConfig $var
     * @return $this
     */
    public function setOutputConfig($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\DataLabeling\V1beta1\OutputConfig::class);
        $this->output_config = $var;

        return $this;
    }

}


text:
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-docopt"
	"github.com/flynn/flynn/controller/client"
	ct "github.com/flynn/flynn/controller/types"
)

func init() {
	register("scale", runScale, `
usage: flynn scale [options] [<type>=<qty>...]

Scale changes the number of jobs for each process type in a release.

Ommitting the arguments will show the current scale.

Options:
	-n, --no-wait            don't wait for the scaling events to happen
	-r, --release=<release>  id of release to scale (defaults to current app release)

Example:

	$ flynn scale
	web=4 worker=2

	$ flynn scale web=2 worker=5
	scaling web: 4=>2, worker: 2=>5

	02:28:34.333 ==> web flynn-3f656af6f1e44092aa7037046236b203 down
	02:28:34.466 ==> web flynn-ee83def0b8e4455793a43c8c70f5b34e down
	02:28:35.479 ==> worker flynn-84f70ca18c9641ef83a178a19db867a3 up
	02:28:36.508 ==> worker flynn-a3de8c326cc542aa89235e53ba304260 up
	02:28:37.601 ==> worker flynn-e24760c511af4733b01ed5b98aa54647 up

	scale completed in 3.944629056s
`)
}

const scaleTimeout = 20 * time.Second

// takes args of the form "web=1", "worker=3", etc
func runScale(args *docopt.Args, client *controller.Client) error {
	app := mustApp()

	release, err := determineRelease(client, args.String["--release"], app)
	if err != nil {
		return err
	}

	formation, err := client.GetFormation(app, release.ID)
	if err == controller.ErrNotFound {
		formation = &ct.Formation{
			AppID:     app,
			ReleaseID: release.ID,
			Processes: make(map[string]int),
		}
	} else if err != nil {
		return err
	}
	if formation.Processes == nil {
		formation.Processes = make(map[string]int)
	}

	typeCounts := args.All["<type>=<qty>"].([]string)
	if len(typeCounts) == 0 {
		scale := make([]string, 0, len(release.Processes))
		for typ := range release.Processes {
			scale = append(scale, fmt.Sprintf("%s=%d", typ, formation.Processes[typ]))
		}
		fmt.Println(strings.Join(scale, " "))
		return nil
	}

	current := formation.Processes
	processes := make(map[string]int, len(current)+len(typeCounts))
	for k, v := range current {
		processes[k] = v
	}
	for _, arg := range typeCounts {
		i := strings.IndexRune(arg, '=')
		if i < 0 {
			fmt.Println(commands["scale"].usage)
		}
		val, err := strconv.Atoi(arg[i+1:])
		if err != nil {
			fmt.Println(commands["scale"].usage)
		}
		processes[arg[:i]] = val
	}
	formation.Processes = processes

	if scalingComplete(current, processes) {
		fmt.Println("requested scale equals current scale, nothing to do!")
		return nil
	}

	scale := make([]string, 0, len(release.Processes))
	for typ := range release.Processes {
		if current[typ] != processes[typ] {
			scale = append(scale, fmt.Sprintf("%s: %d=>%d", typ, current[typ], processes[typ]))
		}
	}
	fmt.Printf("scaling %s\n\n", strings.Join(scale, ", "))

	events := make(chan *ct.JobEvent)
	stream, err := client.StreamJobEvents(app, 0, events)
	if err != nil {
		return err
	}
	defer stream.Close()

	err = client.PutFormation(formation)
	if err != nil || args.Bool["--no-wait"] {
		return err
	}

	start := time.Now()
loop:
	for {
		select {
		case e, ok := <-events:
			if !ok {
				if err := stream.Err(); err != nil {
					return err
				}
				return fmt.Errorf("event stream unexpectedly ended")
			}
			// ignore one-off jobs or starting events
			if e.Job.State == "starting" || e.Job.Type == "" {
				continue loop
			}
			fmt.Printf("%s ==> %s %s %s\n", time.Now().Format("15:04:05.000"), e.Job.Type, e.JobID, e.Job.State)
			switch e.Job.State {
			case "up":
				current[e.Job.Type]++
			case "down", "crashed":
				current[e.Job.Type]--
			}
			if scalingComplete(current, processes) {
				fmt.Printf("\nscale completed in %s\n", time.Since(start))
				return nil
			}
		case <-time.After(scaleTimeout):
			return fmt.Errorf("timed out waiting for scale events")
		}
	}
}

func determineRelease(client *controller.Client, releaseID, app string) (*ct.Release, error) {
	if releaseID == "" {
		release, err := client.GetAppRelease(app)
		if err == controller.ErrNotFound {
			return nil, errors.New("No app release, specify a release with --release")
		}
		if err != nil {
			return nil, err
		}
		return release, nil
	}
	return client.GetRelease(releaseID)
}

func scalingComplete(actual, expected map[string]int) bool {
	// check all the expected counts are the same in actual
	for typ, count := range expected {
		if actual[typ] != count {
			return false
		}
	}
	// check any counts in actual which aren't in expected are zero
	for typ, count := range actual {
		if _, ok := expected[typ]; !ok && count != 0 {
			return false
		}
	}
	return true
}


text:
@if(client_has_addon('basic'))
    @if(auth()->user()->may('menu.point.sales.pos'))

Point Of Sales

                    Sales

    @endif
@endif

@if(client_has_addon('basic'))
    @if(auth()->user()->may('menu.point.sales'))

Goods Sales

    @endif
@endif

@if(client_has_addon('basic'))
    @if(auth()->user()->may('menu.point.sales.service'))

Service Sales

    @endif
@endif


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

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

import static org.junit.Assert.assertEquals;

/**
 * Utility class for testing {@link EditLogOutputStream} and
 * {@link EditLogInputStream} implementations.
 */
public class FSEditLogTestUtil {

  private static final Log LOG = LogFactory.getLog(FSEditLogTestUtil.class);

  /**
   * Base directory for temporary test data. Populated from the
   * "test.build.data" system property. Default value: <code>/tmp</code>
   */
  private static final String BASE_DATA_DIR =
      System.getProperty("test.build.data", "/tmp");

  private static final LogOpGenerator GENERATOR =
      new LogOpGenerator(1000, 3);

  public static List<FSEditLogOp> getContiguousLogSegment(
      int firstTxId, int lastTxId) {
    return GENERATOR.generateContiguousSegment(firstTxId, lastTxId);
  }

  public static FSEditLogOp getNoOpInstance() {
    return FSEditLogOp.LogSegmentOp.getInstance(
        FSEditLogOpCodes.OP_END_LOG_SEGMENT);
  }

  /**
   * Create a temporary file to use by EditLogFile{Input/Output}Stream which is
   * used to compare against BookKeeperEditLog{Input/Output}Stream
   */
  public static File createTempEditsFile(String testName)
      throws IOException {
    File ret = File.createTempFile(testName, "dat",
        new File(BASE_DATA_DIR));
    LOG.info("Created a temporary file for edits: " + ret.getAbsolutePath());
    return ret;
  }

  /**
   * Sequentially write the same edit log operation to multiple streams.
   * Abort immediately if there is write() method of the stream throws an
   * exception.
   * @param op The edit log operation to write.
   * @param streams The streams to write to.
   * @throws IOException If there is an error writing to any of the streams.
   */
  public static void writeToStreams(FSEditLogOp op,
      EditLogOutputStream... streams) throws IOException {
    for (EditLogOutputStream stream : streams) {
      stream.write(op);
    }
  }

  /**
   * Sequentially set streams ready to flush and then flush them.
   * Abort immediately if either setReadyToFlush() or flush() throws
   * an exception.
   * @param streams The streams to flush
   * @throws IOException If there is an error setting any of the streams
   *                     ready to flush or flushing any of the streams.
   */
  public static void flushStreams(EditLogOutputStream... streams)
      throws IOException {
    for (EditLogOutputStream stream : streams) {
      stream.setReadyToFlush();
      stream.flush();
    }
  }

  /**
   * Try to close multiple streams sequentially. Abort immediately if
   * closing any stream causes an exception
   * @param streams The streams to close
   * @throws IOException If there is an error closing any of the streams.
   */
  public static void closeStreams(EditLogOutputStream... streams)
    throws IOException {
    for (EditLogOutputStream stream : streams) {
      stream.close();
    }
  }

  /**
   * Write the header (using create method), generate a semi random workload
   * using {@link #getContiguousLogSegment(int, int)} and then flush and
   * close the streams.
   * @param firstTxId First transaction id in the workload
   * @param lastTxId Last transaction id in the workload
   * @param streams Streams to write to
   * @throws IOException
   */
  public static void createAndPopulateStreams(int firstTxId, int lastTxId,
      EditLogOutputStream... streams) throws IOException {
    for (EditLogOutputStream stream : streams) {
      stream.create();
    }
    populateStreams(firstTxId, lastTxId, streams);
  }

  public static void populateStreams(int firstTxId, int lastTxId,
      EditLogOutputStream... streams) throws IOException {
    // Semi-randomly generate contiguous transactions starting from firstTxId
    // to lastTxId (inclusive)
    List<FSEditLogOp> ops = getContiguousLogSegment(firstTxId, lastTxId);
    int txId = firstTxId;
    for (FSEditLogOp op : ops) {
      op.setTransactionId(txId++);
      writeToStreams(op, streams);
    }
    flushStreams(streams);
    closeStreams(streams);
  }

  /**
   * Assert that specified {@link EditLogInputStream} instances all contain
   * the same operations in the same order.
   * @param numEdits Number of edit log operations
   * @param streamByName Map of stream name to
   *                     {@link EditLogInputStream} instance
   */
  public static void assertStreamsAreEquivalent(int numEdits,
      Map<String, EditLogInputStream> streamByName) throws IOException {
    LOG.info(" --- Verifying " + numEdits + " edits from " +
        Joiner.on(',').join(streamByName.values()) + " ---");
    for (int i = 1; i <= numEdits; i++) {
      String prevName = null;
      FSEditLogOp prevLogOp = null;
      for (Map.Entry<String, EditLogInputStream> e : streamByName.entrySet()) {
        String name = e.getKey();
        EditLogInputStream stream = e.getValue();
        FSEditLogOp op = stream.readOp();
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              Joiner.on(',').withKeyValueSeparator(" = ").join(
                  ImmutableMap.of("txId", i, "streamName", name, "op", op)));
        }
        if (prevLogOp != null) {
          assertEquals("Operation read from " + prevName + " and " +
              name + " must be equal!", op, prevLogOp);
        }
        prevLogOp = op;
        prevName = name;
      }
    }
  }

  /**
   * Find out how many transactions we can read from a
   * FileJournalManager, starting at a given transaction ID.
   *
   * @param jm              The journal manager
   * @param fromTxId        Transaction ID to start at
   * @param inProgressOk    Should we consider edit logs that are not finalized?
   * @return                The number of transactions
   * @throws IOException
   */
  public static long getNumberOfTransactions(JournalManager jm,
      long fromTxId,
      boolean inProgressOk,
      boolean abortOnGap) throws IOException {
    long numTransactions = 0, txId = fromTxId;
    final PriorityQueue<EditLogInputStream> allStreams =
        new PriorityQueue<EditLogInputStream>(64,
            JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR);
    jm.selectInputStreams(allStreams, fromTxId, inProgressOk, true);
    EditLogInputStream elis = null;
    try {
      while ((elis = allStreams.poll()) != null) {
        elis.skipUntil(txId);
        while (true) {
          FSEditLogOp op = elis.readOp();
          if (op == null) {
            break;
          }
          if (abortOnGap && (op.getTransactionId() != txId)) {
            TestFileJournalManager.LOG.info("getNumberOfTransactions: detected gap at txId " +
                fromTxId);
            return numTransactions;
          }
          txId = op.getTransactionId() + 1;
          numTransactions++;
        }
      }
    } finally {
      IOUtils.cleanup(FSEditLogTestUtil.LOG,
          allStreams.toArray(new EditLogInputStream[0]));
      IOUtils.cleanup(FSEditLogTestUtil.LOG, elis);
    }
    return numTransactions;
  }

  public static EditLogInputStream getJournalInputStream(JournalManager jm,
      long txId, boolean inProgressOk) throws IOException {
    final PriorityQueue<EditLogInputStream> allStreams =
        new PriorityQueue<EditLogInputStream>(64,
            JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR);
    jm.selectInputStreams(allStreams, txId, inProgressOk, true);
    EditLogInputStream elis = null, ret;
    try {
      while ((elis = allStreams.poll()) != null) {
        if (elis.getFirstTxId() > txId) {
          break;
        }
        if (elis.getLastTxId() < txId) {
          elis.close();
          continue;
        }
        elis.skipUntil(txId);
        ret = elis;
        elis = null;
        return ret;
      }
    } finally {
      IOUtils.cleanup(FSEditLogTestUtil.LOG,  allStreams.toArray(new EditLogInputStream[0]));
      IOUtils.cleanup(FSEditLogTestUtil.LOG,  elis);
    }
    return null;
  }
}