text:
title: "2018-04-01のJS: TypeScript 2.8、React 16.3.0、TensorFlow.js"
author: "azu"
layout: post
date : 2018-04-01T05:56:39.824Z
category: JSer
tags:
- TypeScript
- react
- ML

---

JSer.info #377 - TypeScript 2.8が正式リリースされました。

- [Announcing TypeScript 2.8 | TypeScript](https://blogs.msdn.microsoft.com/typescript/2018/03/27/announcing-typescript-2-8/)
- [TypeScript 2.8.1 変更点 - Qiita](https://qiita.com/vvakame/items/2e32aeded05997f77dfa)

Conditional Typesのサポートされ、またConditional Typesを使ったビルトインの型として`Exclude<T, U>`, `Extract<T, U>`, `NonNullable<T>`, `ReturnType<T>`, `InstanceType<T>`が追加されています。
mapped type modifierの`+`、`-`のサポート、`.d.ts`ファイルだけを出力できる`emitDeclarationOnly`オプションの追加、`@jsx`プラグマコメントのサポートなどが行われています。

----

React 16.3.0がリリースされました。

- [React v16.3.0: New lifecycles and context API - React Blog](https://reactjs.org/blog/2018/03/29/react-v-16-3.html "React v16.3.0: New lifecycles and context API - React Blog")
- [Update on Async Rendering - React Blog](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html "Update on Async Rendering - React Blog")

今後に向けた大きな変更が追加されています。
新しい[Context](https://reactjs.org/docs/context.html "Context") APIの追加、`createRef`メソッドの追加、`forwardRef`メソッドの追加、`StrictMode`コンポーネントの追加などが行われています。

また非同期レンダリングのサポートのためなどにReactコンポーネントのライフサイクルイベントの変更が行われています。
`componentWillMount`、`componentWillReceiveProps`、`componentWillUpdate`は今後削除されていく方向になり、代わりに`getDerivedStateFromProps`と`getSnapshotBeforeUpdate`が追加されています。

次のようなタイムラインで上記のライフサイクルイベントのAPIの削除が行われていくようです。

- 16.3: それぞれaliasとなる`UNSAFE_componentWillMount`, `UNSAFE_componentWillReceiveProps`, ` UNSAFE_componentWillUpdate`の追加
  - `UNSAFE_` prefixへのマイグレーションスクリプトとして[rename-unsafe-lifecycles](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles "rename-unsafe-lifecycles")が公開されている
- A future 16.x release: `componentWillMount`, `componentWillReceiveProps`, `componentWillUpdate`は非推奨となり警告を表示
- 17.0: `componentWillMount`, `componentWillReceiveProps`, `componentWillUpdate`を削除
  - ただし緩やかなマイグレーションのために`UNSAFE_`版は17.xでも動作を維持する

そのため、古いAPIが完全に削除されるのは18.0となる予定です。(`UNSAFE_`版は17.xでも残るため)
詳しくは次の記事で解説されています。

- [Update on Async Rendering - React Blog](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html "Update on Async Rendering - React Blog")

----

[TensorFlow.js](https://js.tensorflow.org/ "TensorFlow.js")はブラウザでTensorFlowのモデルを使った機械学習を行えるライブラリです。
元々Googleが開発していた[deeplearn.js](https://deeplearnjs.org/index.html "deeplearn.js")の後継バージョンとして公開されています。

JavaScriptとhigh-level layers APIで機械学習を行えるため、初めて機械学習を学ぶJavaScript開発者をターゲットについていることなどについてが次の記事で書かれています。

- [Introducing TensorFlow.js: Machine Learning in JavaScript](https://medium.com/tensorflow/introducing-tensorflow-js-machine-learning-in-javascript-bf3eab376db "Introducing TensorFlow.js: Machine Learning in JavaScript")

また、既存のTensorFlowやKerasのモデルを変換してインポートできブラウザ上で再学習なども行えます。
現在はWebGLに依存しているためブラウザのみで動作し、Node.jsのサポートについては検討中であることなどがFAQにかかれています。

- [FAQ – TensorFlow.js](https://js.tensorflow.org/faq/)

----

ヘッドライン

----

## React v16.3.0: New lifecycles and context API - React Blog
[reactjs.org/blog/2018/03/29/react-v-16-3.html](https://reactjs.org/blog/2018/03/29/react-v-16-3.html "React v16.3.0: New lifecycles and context API - React Blog")

React ReleaseNote

React v16.3.0リリース。
新しいContext APIの追加、`createRef`メソッドの追加、`forwardRef`メソッドの追加。
コンポーネントライフサイクルイベントの変更と追加、`StrictMode`コンポーネントの追加など

- [Update on Async Rendering - React Blog](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html "Update on Async Rendering - React Blog")
- [React v16.3.0: New lifecycles and context API【日本語翻訳】 | maesblog](https://mae.chab.in/archives/60040 "React v16.3.0: New lifecycles and context API【日本語翻訳】 | maesblog")

----

## March 2018 Security Releases | Node.js
[nodejs.org/en/blog/vulnerability/march-2018-security-releases/](https://nodejs.org/en/blog/vulnerability/march-2018-security-releases/ "March 2018 Security Releases | Node.js")

node.js ReleaseNote security

Node.jsのセキュリティアップデートとして、それぞれのLTSと開発バージョンのアップデートが公開された

- Node.js 9.10.0
- Node.js 8.11.0 (LTS "Carbon")
- Node.js 6.14.0 (LTS "Boron")
- Node.js 4.9.0 (LTS "Argon")

----

## V8 JavaScript Engine: V8 release v6.6
[v8project.blogspot.com/2018/03/v8-release-66.html](https://v8project.blogspot.com/2018/03/v8-release-66.html "V8 JavaScript Engine: V8 release v6.6")

V8 Chrome ReleaseNote

V8 v6.6(Chrome 66)リリース。
ECMAScript Proposalの対応として`Function#toString()`の仕様追従、JSがJSONのsupersetとなる仕様追従。
また`catch`構文のパラメータを省略に対応、`String#trimStart`や`String#trimEnd`の実装など。
Background compilationの対応やAsync、Arrayのパフォーマンス改善など

- [Function.prototype.toString revision](https://tc39.github.io/Function-prototype-toString-revision/ "Function.prototype.toString revision")
- [tc39/proposal-json-superset: Proposal to make all JSON text valid ECMA-262](https://github.com/tc39/proposal-json-superset "tc39/proposal-json-superset: Proposal to make all JSON text valid ECMA-262")
- [tc39/proposal-string-left-right-trim: A proposal to the ECMAScript standard for including left and right trim of whitespace to strings](https://github.com/tc39/proposal-string-left-right-trim "tc39/proposal-string-left-right-trim: A proposal to the ECMAScript standard for including left and right trim of whitespace to strings")

----

## ZEIT – Next.js 5.1: Faster Page Resolution, Environment Config & More
[zeit.co/blog/next5-1](https://zeit.co/blog/next5-1 "ZEIT – Next.js 5.1: Faster Page Resolution, Environment Config & More")

React node.js library ReleaseNote

Next.js 5.1リリース。
ページロードの速度改善、設定を定義できる`publicRuntimeConfig`と`serverRuntimeConfig`を追加、エラーハンドリングの改善など

----

## Release v3.4.0 · storybooks/storybook
[github.com/storybooks/storybook/releases/tag/v3.4.0](https://github.com/storybooks/storybook/releases/tag/v3.4.0 "Release v3.4.0 · storybooks/storybook")

JavaScript ui  library ReleaseNote Tools

Storybook 3.4.0リリース。
Polymer 2サポート、AngularとVueのstoryshotサポートなど

----

## power-assert/CHANGELOG.md at v1.5.0 · power-assert-js/power-assert
[github.com/power-assert-js/power-assert/blob/v1.5.0/CHANGELOG.md](https://github.com/power-assert-js/power-assert/blob/v1.5.0/CHANGELOG.md "power-assert/CHANGELOG.md at v1.5.0 · power-assert-js/power-assert")

JavaScript testing library Tools ReleaseNote

power-assert 1.5.0リリース。
Node.js 9.9.0で追加された`assert`のstrict modeをサポート

- [Node v9.9.0 (Current) | Node.js](https://nodejs.org/en/blog/release/v9.9.0/ "Node v9.9.0 (Current) | Node.js")
- [Assert | Node.js v9.10.1 Documentation](https://nodejs.org/api/assert.html#assert_strict_mode "Assert | Node.js v9.10.1 Documentation")

----

## 📦 Parcel v1.7.0: – devongovett – Medium
[medium.com/@devongovett/parcel-v1-7-0-9aac0c505837](https://medium.com/@devongovett/parcel-v1-7-0-9aac0c505837 "📦 Parcel v1.7.0: – devongovett – Medium")

JavaScript Tools ReleaseNote

Parcel v1.7.0リリース。
`.vue`とPugのサポート、出力するファイルにハッシュ値を付与するように、absolute pathとtilde(`~`) pathのサポート、必要な依存を自動的にインストールするようになるなど

----

## Dart Sass 1.0.0 is Released « Sass Blog
[sass.logdown.com/posts/7045860-dart-sass-100-is-released](http://sass.logdown.com/posts/7045860-dart-sass-100-is-released "Dart Sass 1.0.0 is Released « Sass Blog")

Sass dart ReleaseNote

Dart Sass 1.0リリース。
Ruby Sassについてはメンテナンスモードとなる。

----

## ESLint v5.0.0-alpha.0 released - ESLint - Pluggable JavaScript linter
[eslint.org/blog/2018/03/eslint-v5.0.0-alpha.0-released](https://eslint.org/blog/2018/03/eslint-v5.0.0-alpha.0-released "ESLint v5.0.0-alpha.0 released - ESLint - Pluggable JavaScript linter")

ESLint serverless

ESLint 5.0.0αリリース。
予定される破壊的な変更についてはマイグレーションガイドで解説されている。

- [ESLint v5.0.0 変更点まとめ (随時更新) - Qiita](https://qiita.com/mysticatea/items/f34097961bf2827b675d "ESLint v5.0.0 変更点まとめ (随時更新) - Qiita")
- [Migrating to v5.0.0 - ESLint - Pluggable JavaScript linter](https://eslint.org/docs/5.0.0/user-guide/migrating-to-5.0.0 "Migrating to v5.0.0 - ESLint - Pluggable JavaScript linter")

----

## Announcing TypeScript 2.8 | TypeScript
[blogs.msdn.microsoft.com/typescript/2018/03/27/announcing-typescript-2-8/](https://blogs.msdn.microsoft.com/typescript/2018/03/27/announcing-typescript-2-8/ "Announcing TypeScript 2.8 | TypeScript")

ReleaseNote TypeScript

TypeScript 2.8リリース。 Conditional Types、d.tsのみの出力に対応、`@jsx` pragmaコメントのサポート、mapped type modifierの`+`、`-`のサポートなど

- [TypeScript 2.8.1 変更点 - Qiita](https://qiita.com/vvakame/items/2e32aeded05997f77dfa "TypeScript 2.8.1 変更点 - Qiita")

----

アーティクル

----

## Server Timing APIを使ってサーバーサイドのベンチマークを手軽にやる | ブログ :: Web notes.log
[blog.wnotes.net/blog/article/server-side-benchmark-using-server-timing-api](http://blog.wnotes.net/blog/article/server-side-benchmark-using-server-timing-api "Server Timing APIを使ってサーバーサイドのベンチマークを手軽にやる | ブログ :: Web notes.log")

node.js server library performance

Server Timinig APIを使いサーバサイドのリクエストごとのベンチマークをとり、Chromeの開発者ツールに表示するライブラリについて

----

## Update on Async Rendering - React Blog
[reactjs.org/blog/2018/03/27/update-on-async-rendering.html](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html "Update on Async Rendering - React Blog")

React article

非同期レンダリングのためのライフサイクルイベントの追加と変更について。
16.3でイベントの追加、16.xで古いイベントに警告を表示、17.0で古いイベントを廃止。
また追加された`getDerivedStateFromProps`と`getSnapshotBeforeUpdate`についての解説

----

## Working with the new CSS Typed Object Model  |  Web  |  Google Developers
[developers.google.com/web/updates/2018/03/cssom](https://developers.google.com/web/updates/2018/03/cssom "Working with the new CSS Typed Object Model  |  Web  |  Google Developers")

CSS article JavaScript

CSS Typed OMについての解説。
すでにある`style`プロパティと新しく追加された`attributeStyleMap`の違いや、CSS Typed OMで追加されたAPIのメリットや実際の使い方について

----

## WebAssembly/esm-integration: ECMAScript module integration
[github.com/WebAssembly/esm-integration](https://github.com/WebAssembly/esm-integration "WebAssembly/esm-integration: ECMAScript module integration")

WebAssembly module ECMAScript

ES Module Integration Proposal for WebAssembly

----

## How display: contents; Works
[bitsofco.de/how-display-contents-works/](https://bitsofco.de/how-display-contents-works/ "How display: contents; Works")

CSS article

`display: contents;` の解説

----

サイト、サービス、ドキュメント

----

## CondeNast/perf-timeline-cli: Generate Chrome Performance Timelines via a command line interface
[github.com/CondeNast/perf-timeline-cli](https://github.com/CondeNast/perf-timeline-cli "CondeNast/perf-timeline-cli: Generate Chrome Performance Timelines via a command line interface")

Chrome performance Tools

Chrome開発者ツールのPerformanceパネルの情報を取得するCLIツール。
Puppeteerを使ってアクセスした結果を取得する

----

## JavaScript in 14 minutes by Jeremy Thomas
[jgthms.com/javascript-in-14-minutes/](https://jgthms.com/javascript-in-14-minutes/ "JavaScript in 14 minutes by Jeremy Thomas")

JavaScript tutorial

ブラウザの開発者ツールで実行しながら学べるJavaScriptチュートリアル

----

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

----

## cmseaton42/task-easy: A simple, customizable, and lightweight priority queue for promises.
[github.com/cmseaton42/task-easy](https://github.com/cmseaton42/task-easy "cmseaton42/task-easy: A simple, customizable, and lightweight priority queue for promises.")

JavaScript Promises library

Promiseスケジュールライブラリ

----

## asfktz/Awaity.js: A functional, lightweight alternative to bluebird.js, built with async / await in mind.
[github.com/asfktz/Awaity.js](https://github.com/asfktz/Awaity.js "asfktz/Awaity.js: A functional, lightweight alternative to bluebird.js, built with async / await in mind.")

JavaScript Promises library

async/awaitベースのコレクション系ライブラリ
map、filter、reduceなどのPromiseに対するコレクション操作を提供するライブラリ

----

## jacobbogers/libRmath.js: Javascript Pure Implementation of Statistical R "core" numerical libRmath.so
[github.com/jacobbogers/libRmath.js](https://github.com/jacobbogers/libRmath.js "jacobbogers/libRmath.js: Javascript Pure Implementation of Statistical R \"core\" numerical libRmath.so")

JavaScript TypeScript R  library

Rの`math`をJavaScriptにポートしたライブラリ

----

## TensorFlow.js
[js.tensorflow.org/](https://js.tensorflow.org/ "TensorFlow.js")

MachineLearning JavaScript library WebGL

tensorflowのJavaScript版。
WebGLを使った機械学習を行え、既存の学習モデルはconverterで変換し利用できる。

- [tensorflow/tfjs-converter: Convert TensorFlow SavedModel and Keras models to TensorFlow.js](https://github.com/tensorflow/tfjs-converter "tensorflow/tfjs-converter: Convert TensorFlow SavedModel and Keras models to TensorFlow.js")

----

## jaywcjlove/hotkeys: ➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
[github.com/jaywcjlove/hotkeys](https://github.com/jaywcjlove/hotkeys "jaywcjlove/hotkeys: ➷ A robust Javascript library for capturing keyboard input. It has no dependencies.")

JavaScript キーボード React library

ショートカットキー管理ライブラリ。

----

書籍関係

----

## React開発 現場の教科書 | マイナビブックス
[book.mynavi.jp/ec/products/detail/id=88735](https://book.mynavi.jp/ec/products/detail/id=88735 "React開発 現場の教科書 | マイナビブックス")

React book

ReactとAtomic Designについての書籍

----

## CSS Pocket Reference, 5th Edition - O'Reilly Media
[shop.oreilly.com/product/0636920146353.do](http://shop.oreilly.com/product/0636920146353.do "CSS Pocket Reference, 5th Edition - O'Reilly Media")

CSS book

2018年4月発売。
CSSリファレンス本

----


text:
/* CVSroot data structures */

/* Access method specified in CVSroot. */
typedef enum {
    null_method = 0,
    local_method,
    server_method,
    pserver_method,
    kserver_method,
    gserver_method,
    ext_method,
    fork_method
} CVSmethod;
extern const char method_names[][16];	/* change this in root.c if you change
					   the enum above */

typedef struct cvsroot_s {
    char *original;		/* The complete source CVSroot string. */
    CVSmethod method;		/* One of the enum values above. */
    char *directory;		/* The directory name. */
    bool isremote;		/* True if we are doing remote access. */
/* The following is required for servers now to allow Redirects to be sent
 * for remote roots when client support is disabled.
 */
#if defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
    char *username;		/* The username or NULL if method == local. */
    char *password;		/* The password or NULL if method == local. */
    char *hostname;		/* The hostname or NULL if method == local. */
    char *cvs_rsh;		/* The $CVS_RSH or NULL if method != ext. */
    char *cvs_server;		/* The $CVS_SERVER or NULL if
				 * method != ext and method != fork. */
    int port;			/* The port or zero if method == local. */
    char *proxy_hostname;	/* The hostname of the proxy server, or NULL
				 * when method == local or no proxy will be
				 * used.
				 */
    int proxy_port;		/* The port of the proxy or zero, as above. */
    bool redirect;		/* False if we are to disable redirects. */
#endif /* defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
} cvsroot_t;

extern cvsroot_t *current_parsed_root;
extern const cvsroot_t *original_parsed_root;

cvsroot_t *Name_Root (const char *dir, const char *update_dir);
cvsroot_t *parse_cvsroot (const char *root)
	__attribute__ ((__malloc__));
cvsroot_t *local_cvsroot (const char *dir)
	__attribute__ ((__malloc__));
void Create_Root (const char *dir, const char *rootdir);
void root_allow_add (const char *, const char *configPath);
void root_allow_free (void);
bool root_allow_ok (const char *);
struct config *get_root_allow_config (const char *arg, const char *configPath);
const char *primary_root_translate (const char *root_in);
const char *primary_root_inverse_translate (const char *root_in);

redpajama_set_name: RedPajamaGithub


text:
package com.akjava.gwt.html5.client.download;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * @deprecated
 * @author aki
 *
 */
public class DownloadBlobBuilder extends JavaScriptObject{

	/**
	 * TODO merge html5 file system
	 *
	 * blobbuilder is deprecated
	 * http://www.w3.org/TR/2012/WD-FileAPI-20120712/#blob
	 */
	protected DownloadBlobBuilder(){}

	public  native final void append(String text)/*-{
	this.append(text);
	}-*/;

	/*
	 *
	 * come from
	 * https://groups.google.com/a/chromium.org/forum/?fromgroups#!topic/chromium-html5/WOxmqfDAaqo
	 * Thanks Eric Bidelman
	 */
	public  native final void appendBase64(String dataURI)/*-{
  var BASE64_MARKER = ';base64,';
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = $wnd.atob(base64);
  var rawLength = raw.length;
  var uInt8Array = new $wnd.Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  this.append(uInt8Array.buffer);
  }-*/;

	//TODO create Blob class
	public  native final JavaScriptObject getBlob(String mimeType)/*-{
	return this.getBlob(mimeType);
	}-*/;
}


text:
<?php
/**
 * Virtual HTTP service client
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * Virtual HTTP service instance that can be mounted on to a VirtualRESTService
 *
 * Sub-classes manage the logic of either:
 *   - a) Munging virtual HTTP request arrays to have qualified URLs and auth headers
 *   - b) Emulating the execution of virtual HTTP requests (e.g. brokering)
 *
 * Authentication information can be cached in instances of the class for performance.
 * Such information should also be cached locally on the server and auth requests should
 * have reasonable timeouts.
 *
 * @since 1.23
 */
abstract class VirtualRESTService {
	/** @var array Key/value map */
	protected $params = array();

	/**
	 * @param array $params Key/value map
	 */
	public function __construct( array $params ) {
		$this->params = $params;
	}

	/**
	 * Prepare virtual HTTP(S) requests (for this service) for execution
	 *
	 * This method should mangle any of the $reqs entry fields as needed:
	 *   - url      : munge the URL to have an absolute URL with a protocol
	 *                and encode path components as needed by the backend [required]
	 *   - query    : include any authentication signatures/parameters [as needed]
	 *   - headers  : include any authentication tokens/headers [as needed]
	 *
	 * The incoming URL parameter will be relative to the service mount point.
	 *
	 * This method can also remove some of the requests as well as add new ones
	 * (using $idGenerator to set each of the entries' array keys). For any existing
	 * or added request, the 'response' array can be filled in, which will prevent the
	 * client from executing it. If an original request is removed, at some point it
	 * must be added back (with the same key) in onRequests() or onResponses();
	 * it's reponse may be filled in as with other requests.
	 *
	 * @param array $reqs Map of Virtual HTTP request arrays
	 * @param Closure $idGeneratorFunc Method to generate unique keys for new requests
	 * @return array Modified HTTP request array map
	 */
	public function onRequests( array $reqs, Closure $idGeneratorFunc ) {
		$result = array();
		foreach ( $reqs as $key => $req ) {
			// The default encoding treats the URL as a REST style path that uses
			// forward slash as a hierarchical delimiter (and never otherwise).
			// Subclasses can override this, and should be documented in any case.
			$parts = array_map( 'rawurlencode', explode( '/', $req['url'] ) );
			$req['url'] = $this->params['baseUrl'] . '/' . implode( '/', $parts );
			$result[$key] = $req;
		}
		return $result;
	}

	/**
	 * Mangle or replace virtual HTTP(S) requests which have been responded to
	 *
	 * This method may mangle any of the $reqs entry 'response' fields as needed:
	 *   - code    : perform any code normalization [as needed]
 	 *   - reason  : perform any reason normalization [as needed]
 	 *   - headers : perform any header normalization [as needed]
	 *
	 * This method can also remove some of the requests as well as add new ones
	 * (using $idGenerator to set each of the entries' array keys). For any existing
	 * or added request, the 'response' array can be filled in, which will prevent the
	 * client from executing it. If an original request is removed, at some point it
	 * must be added back (with the same key) in onRequests() or onResponses();
	 * it's reponse may be filled in as with other requests. All requests added to $reqs
	 * will be passed through onRequests() to handle any munging required as normal.
	 *
	 * The incoming URL parameter will be relative to the service mount point.
	 *
	 * @param array $reqs Map of Virtual HTTP request arrays with 'response' set
	 * @param Closure $idGeneratorFunc Method to generate unique keys for new requests
	 * @return array Modified HTTP request array map
	 */
	public function onResponses( array $reqs, Closure $idGeneratorFunc ) {
		return $reqs;
	}
}


text:
Avatar0

        Director: James Cameron0
        (born August 16, 1954 - 0)

    Science fiction0
    0

Avatar1

        Director: James Cameron1 (born August 16, 1954 - 1)

    Science fiction1
    1


text:
package com.streamsets.datacollector.io;

import com.google.common.annotations.VisibleForTesting;
import com.streamsets.pipeline.api.impl.Utils;
import org.apache.commons.io.input.ProxyInputStream;
import org.apache.commons.io.output.ProxyOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class DataStore {
  private final static Logger LOG = LoggerFactory.getLogger(DataStore.class);
  private final static Map<Path, ReentrantLock> FILE_LOCKS = new HashMap<>();

  private final Path file;
  private final Path fileTmp;
  private final Path fileNew;
  private final Path fileOld;
  private Closeable stream;
  private boolean forWrite;
  private boolean isClosed;

  public DataStore(File file) {
    Utils.checkNotNull(file, "file");
    File absFile = file.getAbsoluteFile();
    this.file = absFile.toPath();
    fileTmp = new File(absFile.getAbsolutePath() + "-tmp").toPath();
    fileNew = new File(absFile.getAbsolutePath() + "-new").toPath();
    fileOld = new File(absFile.getAbsolutePath() + "-old").toPath();
    LOG.trace("Create DataStore for '{}'", file);
  }

  public File getFile() {
    return file.toFile();
  }

  public void close() throws IOException {
    LOG.trace("Close DataStore for '{}'", file);
    synchronized (DataStore.class) {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException ex) {
          LOG.error("DataStore '{}' error while closing stream, {}", file, ex.toString(), ex);
        }
        FILE_LOCKS.remove(file);
        throw new IOException(Utils.format("DataStore '{}' closed while open for '{}'", file,
                                           (forWrite) ? "WRITE" : "READ"));
      }
    }
  }

  @Override
  protected void finalize() throws Throwable {
    close();
  }

  @VisibleForTesting
  void acquireLock() {
    LOG.trace("Acquiring lock for '{}'", file);
    ReentrantLock lock  = null;
    synchronized (DataStore.class) {
      lock = FILE_LOCKS.get(file);
      if (lock == null) {
        lock = new ReentrantLock();
        FILE_LOCKS.put(file, lock);
      } else {
        Utils.checkState(!lock.isHeldByCurrentThread(), Utils.format("The current thread already has a lock on '{}'",
                                                                     file));
      }
    }
    lock.lock();
    LOG.trace("Acquired lock for '{}'", file);
  }

  /**
   * This method must be used after completing the write to output stream which was obtained by calling the
   * {@link #getOutputStream()} method.
   *
   * If the write operation was successful, then this method must be called after calling the
   * {@link #commit(java.io.OutputStream)} method. Otherwise it must be called after calling the {@link #close()} on the
   * output stream.
   *
   * Example usage:
   *
   * DataStore dataStore = new DataStore(...);
   * try (OutputStream os = dataStore.getOutputStream()) {
   *   os.write(..);
   *   dataStore.commit(os);
   * } catch (IOException e) {
   *   ...
   * } finally {
   *   dataStore.release();
   * }
   *
   */
  public void release() {
    ReentrantLock lock;
    synchronized (DataStore.class) {
      lock = FILE_LOCKS.remove(file);
    }
    if (lock != null) {
      LOG.trace("Releasing the lock for '{}'", file);
      lock.unlock();
      LOG.trace("Released the lock for '{}'", file);
    }
  }

  /**
   * Returns an input stream for the requested file.
   *
   * After completing the read the stream must be closed. It is not necessary to call the {@link #release()}
   * method after reading from the input stream.
   *
   * Example usage:
   *
   * DataStore dataStore = new DataStore(...);
   * try (InputStream is = dataStore.getInputStream()) {
   *   // read from is
   * } catch (IOException e) {
   *   ...
   * }
   *
   * @return
   * @throws IOException
   */
  public InputStream getInputStream() throws IOException {
    acquireLock();
    try {
      isClosed = false;
      forWrite = false;
      LOG.trace("Starts read '{}'", file);
      verifyAndRecover();
      InputStream is = new ProxyInputStream(new FileInputStream(file.toFile())) {
        @Override
        public void close() throws IOException {
          if (isClosed) {
            return;
          }
          try {
            super.close();
          } finally {
            release();
            isClosed = true;
            stream = null;
          }
          LOG.trace("Finishes read '{}'", file);
        }
      };
      stream = is;
      return is;
    } catch (Exception ex) {
      release();
      throw ex;
    }
  }

  /**
   * Returns an output stream for the requested file.
   *
   * After completing the write the contents must be committed using the {@link #commit(java.io.OutputStream)}
   * method and the stream must be released using the {@link #release()} method.
   *
   * Example usage:
   *
   * DataStore dataStore = new DataStore(...);
   * try (OutputStream os = dataStore.getOutputStream()) {
   *   os.write(..);
   *   dataStore.commit(os);
   * } catch (IOException e) {
   *   ...
   * } finally {
   *   dataStore.release();
   * }
   *
   * @return
   * @throws IOException
   */
  public OutputStream getOutputStream() throws IOException {
    acquireLock();
    try {
      isClosed = false;
      forWrite = true;
      LOG.trace("Starts write '{}'", file);
      verifyAndRecover();
      if (Files.exists(file)) {
        Files.move(file, fileOld);
        LOG.trace("Starting write, move '{}' to '{}'", file, fileOld);
      }
      OutputStream os = new ProxyOutputStream(new FileOutputStream(fileTmp.toFile())) {
        @Override
        public void close() throws IOException {
          if (isClosed) {
            return;
          }
          try {
            super.close();
          } finally {
            isClosed = true;
            stream = null;
          }
          LOG.trace("Finishes write '{}'", file);
        }
      };
      stream = os;
      return os;
    } catch (Exception ex) {
      release();
      throw ex;
    }
  }

  /**
   * This method must be used to commit contents written to the output stream which is obtained by calling
   * the {@link #getOutputStream()} method. This method closes the argument output stream.
   *
   * Example usage:
   *
   * DataStore dataStore = new DataStore(...);
   * try (OutputStream os = dataStore.getOutputStream()) {
   *   os.write(..);
   *   dataStore.commit(os);
   * } catch (IOException e) {
   *   ...
   * } finally {
   *   dataStore.release();
   * }
   *
   * @throws IOException
   */
  public void commit(OutputStream out) throws IOException {
    // close the stream in order to flush the contents into the disk
    Utils.checkNotNull(out, "Argument output stream cannot be null");
    Utils.checkState(stream == out, "The argument output stream must be the same as the output stream obtained " +
      "from this data store instance");
    out.close();
    Files.move(fileTmp, fileNew);
    LOG.trace("Committing write, move '{}' to '{}'", fileTmp, fileNew);
    Files.move(fileNew, file);
    LOG.trace("Committing write, move '{}' to '{}'", fileNew, file);
    if (Files.exists(fileOld)) {
      Files.delete(fileOld);
      LOG.trace("Committing write, deleting '{}'", fileOld);
    }
    LOG.trace("Committed");
  }

  private void verifyAndRecover() throws IOException {
    if (Files.exists(fileOld) || Files.exists(fileTmp) || Files.exists(fileNew)) {
      if (Files.exists(fileNew)) {
        LOG.warn("File '{}', write completed but not committed, committing", file);
        if (Files.exists(fileTmp)) {
          throw new IOException(Utils.format("File '{}' exists, '{}' should not exist", fileNew, fileTmp));
        }
        if (Files.exists(file)) {
          throw new IOException(Utils.format("File '{}' exists, '{}' should not exist", fileNew, file));
        }
        Files.move(fileNew, file);
        if (Files.exists(fileOld)) {
          Files.delete(fileOld);
          LOG.warn("File '{}', deleted during verification", fileOld);
        }
        LOG.warn("File '{}', committed during verification", file);
      } else if (Files.exists(fileTmp)) {
        LOG.warn("File '{}', write incomplete while writing, rolling back", file);
        if (!Files.exists(fileOld)) {
          throw new IOException(Utils.format("File '{}' exists, '{}' should exists", fileTmp, fileOld));
        }
        if (Files.exists(file)) {
          throw new IOException(Utils.format("File '{}' exists, '{}' should not exist", fileTmp, file));
        }
        Files.delete(fileTmp);
        Files.move(fileOld, file);
        LOG.warn("File '{}', rolled back during verification", file);
      } else if (Files.exists(fileOld)) {
        LOG.warn("File '{}', write incomplete while starting write, rolling back", file);
        if (Files.exists(file)) {
          throw new IOException(Utils.format("File '{}' exists, '{}' should not exist", fileOld, file));
        }
        Files.move(fileOld, file);
        LOG.warn("File '{}', rolled back during verification", file);
      }
    } else {
      LOG.trace("File '{}' no recovery needed", file);
    }
  }

  /**
   * Check if the DataStore exists and contains data.
   * This method will check for the presence of the set of files that can be used to read data from the store.
   */
  public boolean exists() throws IOException {
    verifyAndRecover();
    return Files.exists(file) && Files.size(file) > 0;
  }

  public void delete() throws IOException {
    if (Files.exists(fileTmp)) {
      Files.delete(fileTmp);
    }
    if (Files.exists(fileOld)) {
      Files.delete(fileOld);
    }
    if (Files.exists(fileNew)) {
      Files.delete(fileNew);
    }
    if (Files.exists(file)) {
      Files.delete(file);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using PWLib.FileSyncLib;

namespace AutoUSBBackup.GUI
{
	public class MainFormEventController
	{
		Control mInvokeControl;
		ToolStripProgressBar mProgressBar;
		NotifyIcon mNotifyIcon;

		public event EventHandler SpineInitialised;

		public event VolumeBackupHandler BackupStarted;
		public event VolumeBackupHandler BackupFinished;
		public event VolumeRestoreHandler RestoreStarted;
		public event VolumeRestoreHandler RestoreFinished;

		public event EventHandler FormatUsbFinished;

		public event VolumeDescriptorChangedHandler VolumeNeedsRefreshing;

		public MainFormEventController( Control invokeControl, ToolStripProgressBar progressBar, NotifyIcon notifyIcon )
		{
			mInvokeControl = invokeControl;
			mProgressBar = progressBar;
			mNotifyIcon = notifyIcon;
		}

		public void HookSpineEvents( VolumeEventController eventController )
		{
			eventController.VolumeDescriptorActiveStateChanged += new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged );
			eventController.VolumeSourceActiveStateChanged += new VolumeSourceActiveChangedHandler( eventController_VolumeSourceActiveStateChanged );

			eventController.BackupStarted += new VolumeBackupHandler( Spine_BackupStarted );
			eventController.BackupFinished += new VolumeBackupHandler( Spine_BackupFinished );
			eventController.BackupProgress += new VolumeBackupProgressHandler( Spine_BackupFileFinished );

			eventController.RestoreStarted += new VolumeRestoreHandler( spine_RestoreInitStarted );
			eventController.RestoreFinished += new VolumeRestoreHandler( Spine_RestoreFinished );
			eventController.RestoreProgress += new VolumeRestoreProgressHandler( spine_RestoreFileFinished );

			eventController.ApplicationInitialised += new EventHandler( Spine_SpineInitialised );

			eventController.FormatUsbFinished += new EventHandler( Spine_FormatUsbFinished );

			MainForm.Instance.SetDefaultStatusText();
		}

		void eventController_VolumeSourceActiveStateChanged( Volume volume, bool isActive )
		{
			mInvokeControl.Invoke( new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged_WinThread ), volume.Descriptor, isActive );
		}

		void eventController_VolumeDescriptorActiveStateChanged( VolumeDescriptor volume, bool isActive )
		{
			mInvokeControl.Invoke( new VolumeDescriptorChangedHandler( eventController_VolumeDescriptorActiveStateChanged_WinThread ), volume, isActive );
		}

		void eventController_VolumeDescriptorActiveStateChanged_WinThread( VolumeDescriptor volume, bool isActive )
		{
			if ( VolumeNeedsRefreshing != null )
				VolumeNeedsRefreshing( volume, isActive );
		}

		void ShowBalloonTip( string text )
		{
			if ( MainForm.Instance.WindowState == FormWindowState.Minimized )
			{
				mNotifyIcon.BalloonTipText = text;
				mNotifyIcon.BalloonTipTitle = "AutoBackup";
				mNotifyIcon.ShowBalloonTip( 5000 );
			}
		}

		#region Spine events

		#region Restore events

		void spine_RestoreFileFinished( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes )
		{
			mInvokeControl.Invoke( new VolumeBackupProgressHandler( spine_RestoreFileFinishedWinThread ), volume, snapshot, fileNum, fileCount, bytesTranferred, totalBytes );
		}

		void spine_RestoreFileFinishedWinThread( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes )
		{
			while ( totalBytes > int.MaxValue )
			{
				totalBytes /= 10;
				bytesTranferred /= 10;
			}

			mProgressBar.Maximum = ( int )totalBytes + 1;
			mProgressBar.Value = ( int )bytesTranferred;

			int percentComplete = (int)(((float)bytesTranferred / (float)(totalBytes + 1)) * 100.0f );
			MainForm.Instance.SetTitleText( "Restoring", percentComplete );
			Log.WriteLine( LogType.DebugLog | LogType.TextLog, "File: " + fileNum.ToString() + "/" + fileCount.ToString() + " Progress: " + bytesTranferred.ToString() + "/" + totalBytes.ToString() );
		}

		void spine_RestoreInitStarted( Volume volume, VolumeSnapshot snapshot )
		{
			mInvokeControl.Invoke( new VolumeRestoreHandler( spine_RestoreInitStartedWinThread ), volume, snapshot );
		}

		void spine_RestoreInitStartedWinThread( Volume volume, VolumeSnapshot snapshot )
		{
//			ShowBalloonTip( "Restore of " + volume.Descriptor.Identifier.Name + " started" );
			MainForm.Instance.SetStatusText("Restoring...");
			MainForm.Instance.SetTitleText( "Restoring", 0 );
			if ( RestoreStarted != null )
				RestoreStarted( volume, snapshot );
		}

		void Spine_RestoreFinished( Volume volume, VolumeSnapshot snapshot )
		{
			mInvokeControl.Invoke( new VolumeRestoreHandler( Spine_RestoreFinishedWinThread ), volume, snapshot );
		}

		void Spine_RestoreFinishedWinThread( Volume volume, VolumeSnapshot snapshot )
		{
			ShowBalloonTip( "Restore of " + volume.Descriptor.VolumeName + " finished" );
			mProgressBar.Value = 0;
			MainForm.Instance.SetDefaultStatusText();
			MainForm.Instance.SetTitleText( "", 0 );
			Log.WriteLine( LogType.AppLog | LogType.TextLog | LogType.DebugLog, "Restoration of '" + volume.Descriptor.VolumeName + "' complete" );
			if (RestoreFinished != null)
				RestoreFinished( volume, snapshot );
		}

		#endregion

		#region Backup events

		void Spine_BackupFileFinished( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes )
		{
			mInvokeControl.Invoke( new VolumeBackupProgressHandler( Spine_BackupFileFinishedWinThread ), volume, snapshot, fileNum, fileCount, bytesTranferred, totalBytes );
		}

		void Spine_BackupFileFinishedWinThread( Volume volume, VolumeSnapshot snapshot, ulong fileNum, ulong fileCount, ulong bytesTranferred, ulong totalBytes )
		{
			try
			{
				while ( totalBytes >= int.MaxValue )
				{
					totalBytes /= 10;
					bytesTranferred /= 10;

				}

				mProgressBar.Maximum = ( int )totalBytes + 1;
				mProgressBar.Value = ( int )bytesTranferred;

				int percentComplete = (int)(((float)bytesTranferred / (float)(totalBytes + 1)) * 100.0f);
				MainForm.Instance.SetTitleText( "Backing up", percentComplete );
			}
			catch ( System.Exception )
			{
				throw;
			}
		}

		void Spine_BackupFinished( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad )
		{
			mInvokeControl.Invoke( new VolumeBackupHandler( Spine_BackupFinishedWinThread ), volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad );
		}

		void Spine_BackupStarted( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad )
		{
			mInvokeControl.Invoke( new VolumeBackupHandler( Spine_BackupStartedWinThread ), volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad );
		}

		void Spine_BackupFinishedWinThread( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad )
		{
			if ( !firstBackupOnLoad && snapshotHasBeenSaved )
				ShowBalloonTip( "Backup of " + volume.Descriptor.VolumeName + " finished" );
			MainForm.Instance.SetDefaultStatusText();
			mProgressBar.Value = 0;
			MainForm.Instance.SetTitleText( "", 0 );
			if ( snapshotHasBeenSaved )
				Log.WriteLine( LogType.AppLog | LogType.TextLog | LogType.DebugLog, "Backup of '" + volume.Descriptor.VolumeName + "' complete" );
			if ( BackupFinished != null )
				BackupFinished( volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad );
		}

		void Spine_BackupStartedWinThread( Volume volume, VolumeSnapshot snapshot, bool snapshotHasBeenSaved, bool firstBackupOnLoad )
		{
			MainForm.Instance.SetStatusText( "Backing up..." );
			if ( BackupStarted != null )
				BackupStarted( volume, snapshot, snapshotHasBeenSaved, firstBackupOnLoad );
			mProgressBar.Value = 0;
			MainForm.Instance.SetTitleText( "Backing up", 0 );
//			if ( !firstBackupOnLoad )
//				ShowBalloonTip( "Backup of " + volume.Descriptor.Identifier.Name + " started" );
		}

		#endregion

		#region Format USB events

		void Spine_FormatUsbFinished( object sender, EventArgs e )
		{
			mInvokeControl.Invoke( new EventHandler( Spine_FormatUsbFinishedWinThread ), sender, e );
		}

		void Spine_FormatUsbFinishedWinThread( object sender, EventArgs e )
		{
			MainForm.Instance.SetDefaultStatusText();
			if ( FormatUsbFinished != null )
				FormatUsbFinished( sender, e );
		}

		#endregion

		#region Spine events

		void Spine_SpineInitialised( object sender, EventArgs e )
		{
			mInvokeControl.Invoke( new EventHandler( Spine_SpineInitialisedWinThread ), sender, e );
		}

		void Spine_SpineInitialisedWinThread( object sender, EventArgs e )
		{
			MainForm.Instance.SetDefaultStatusText();
			if ( SpineInitialised != null )
				SpineInitialised( sender, e );
		}

		#endregion

		#endregion

	}
}


text:
package org.apache.arrow.vector;

import static org.apache.arrow.vector.NullCheckingForGet.NULL_CHECKING_ENABLED;

import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.TransferPair;

/**
 * TimeStampVector is an abstract interface for fixed width vector (8 bytes)
 * of timestamp values which could be null. A validity buffer (bit vector) is
 * maintained to track which elements in the vector are null.
 */
public abstract class TimeStampVector extends BaseFixedWidthVector {
  protected static final byte TYPE_WIDTH = 8;

  /**
   * Instantiate a TimeStampVector. This doesn't allocate any memory for
   * the data in vector.
   *
   * @param name name of the vector
   * @param fieldType type of Field materialized by this vector
   * @param allocator allocator for memory management.
   */
  public TimeStampVector(String name, FieldType fieldType, BufferAllocator allocator) {
    this(new Field(name, fieldType, null), allocator);
  }

  /**
   * Instantiate a TimeStampVector. This doesn't allocate any memory for
   * the data in vector.
   *
   * @param field field materialized by this vector
   * @param allocator allocator for memory management.
   */
  public TimeStampVector(Field field, BufferAllocator allocator) {
    super(field, allocator, TYPE_WIDTH);
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |          vector value retrieval methods                        |
   |                                                                |
   *----------------------------------------------------------------*/

  /**
   * Get the element at the given index from the vector.
   *
   * @param index   position of element
   * @return element at given index
   */
  public long get(int index) throws IllegalStateException {
    if (NULL_CHECKING_ENABLED && isSet(index) == 0) {
      throw new IllegalStateException("Value at index is null");
    }
    return valueBuffer.getLong((long) index * TYPE_WIDTH);
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |          vector value setter methods                           |
   |                                                                |
   *----------------------------------------------------------------*/

  protected void setValue(int index, long value) {
    valueBuffer.setLong((long) index * TYPE_WIDTH, value);
  }

  /**
   * Set the element at the given index to the given value.
   *
   * @param index   position of element
   * @param value   value of element
   */
  public void set(int index, long value) {
    BitVectorHelper.setBit(validityBuffer, index);
    setValue(index, value);
  }

  /**
   * Same as {@link #set(int, long)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param value   value of element
   */
  public void setSafe(int index, long value) {
    handleSafe(index);
    set(index, value);
  }

  /**
   * Store the given value at a particular position in the vector. isSet indicates
   * whether the value is NULL or not.
   *
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param value element value
   */
  public void set(int index, int isSet, long value) {
    if (isSet > 0) {
      set(index, value);
    } else {
      BitVectorHelper.unsetBit(validityBuffer, index);
    }
  }

  /**
   * Same as {@link #set(int, int, long)} except that it handles the case
   * when index is greater than or equal to current value capacity of the
   * vector.
   *
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param value element value
   */
  public void setSafe(int index, int isSet, long value) {
    handleSafe(index);
    set(index, isSet, value);
  }

  /**
   * Given a data buffer, get the value stored at a particular position
   * in the vector.
   *
   * <p>This method should not be used externally.
   *
   * @param buffer data buffer
   * @param index position of the element.
   * @return value stored at the index.
   */
  public static long get(final ArrowBuf buffer, final int index) {
    return buffer.getLong((long) index * TYPE_WIDTH);
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |                      vector transfer                           |
   |                                                                |
   *----------------------------------------------------------------*/

  /**
   * {@link TransferPair} for {@link TimeStampVector}.
   */
  public class TransferImpl implements TransferPair {
    TimeStampVector to;

    public TransferImpl(TimeStampVector to) {
      this.to = to;
    }

    @Override
    public TimeStampVector getTo() {
      return to;
    }

    @Override
    public void transfer() {
      transferTo(to);
    }

    @Override
    public void splitAndTransfer(int startIndex, int length) {
      splitAndTransferTo(startIndex, length, to);
    }

    @Override
    public void copyValueSafe(int fromIndex, int toIndex) {
      to.copyFromSafe(fromIndex, toIndex, TimeStampVector.this);
    }
  }
}


text:
package rta.datatypes;

import com.tangosol.io.pof.PortableObject;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;

import java.io.IOException;

import java.util.Calendar;

public class KPI implements PortableObject {
    public KPI() {
        this.classname = this.getClass().getName();
    }

    public KPI(String id, String data) {
        this.classname = this.getClass().getName();
        this.id = id;
        this.data = data;
    }

    public void readExternal(PofReader reader) throws IOException {
        classname = reader.readString(CLASSNAME);
        id = reader.readString(ID);
        data = reader.readString(DATA);
    }

    public void writeExternal(PofWriter writer) throws IOException {
        writer.writeString(CLASSNAME, classname);
        writer.writeString(ID, id);
        writer.writeString(DATA, data);
    }

    public static final int CLASSNAME = 0;
    public static final int ID = 1;
    public static final int DATA = 2;

    private String classname;
    private String id;
    private String data;

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public String getClassname() {
        return classname;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

}


text:
import sys

def main():
	for combination in tokenize_combinations(read_source_file(), 0):
		print evaluate(combination)

def read_source_file():
	source_fname = sys.argv[1]
	with open(source_fname, "r") as fd:
		return fd.read()

def tokenize_combinations(text, index):
	combinations = []
	while index < len(text):
		ch = text[index]
		if ch == "(":
			(combination, new_index) = tokenize_combination(text, index)
			combinations.append(combination)
			index = new_index
			assert text[index] == ")"
		elif ch not in [" ", "\n"]:
			(literal, new_index) = tokenize_word(text, index)
			combinations.append(literal)
			index = new_index
		index += 1
		continue
	return combinations

def tokenize_combination(text, index):
	assert text[index] == "("
	index += 1
	tokens = []
	while index < len(text):
		if text[index] == ")":
			break
		elif text[index] == "(":
			(new_tokens, new_index) = tokenize_combination(text, index)
			tokens.append(new_tokens)
			index = new_index + 1
		elif text[index] in [" ", "\n"]:
			index += 1
			continue
		else:
			(word, new_index) = tokenize_word(text, index)
			if len(word) > 0:
				tokens.append(word)
			index = new_index
	assert len(tokens) > 0
	return (tokens, index)

def tokenize_word(text, index):
	word = ""
	while index < len(text):
		ch = text[index]
		if ch in [" ", "\n", ")"]:
			break
		word += ch
		index += 1
	return (word, index)

def evaluate(combination):
	evaluated_combination = []
	if type(combination) == list:
		for token in combination:
			if type(token) == list:
				evaluated_combination.append(evaluate(token))
			else:
				evaluated_combination.append(token)
	else:
		evaluated_combination = combination
	parsed_combination = parse_combination(evaluated_combination)
	if type(parsed_combination) == list:
		operator = parsed_combination[0]
		operands = parsed_combination[1:]
		return operator(operands)
	else:
		return parsed_combination

def parse_combination(combination):
	if type(combination) == list:
		operator = parse_operator(combination[0])
		operands = [parse_operand(token) for token in combination[1:]]
		return [operator] + operands
	else:
		return parse_operand(combination)

def parse_operand(token):
	if type(token) == str:
		if "." in token:
			return float(token)
		else:
			return int(token)
	else:
		return token

def parse_operator(token):
	if token == "+":
		return add
	elif token == "-":
		return subtract
	elif token == "*":
		return multiply
	elif token == "/":
		return divide
	else:
		assert False, "unknown operator: %s" % token

def add(operands):
	return reduce(lambda x, y: x + y, operands)

def subtract(operands):
	return reduce(lambda x, y: x - y, operands)

def multiply(operands):
	return reduce(lambda x, y: x * y, operands)

def divide(operands):
	return reduce(lambda x, y: x / y, operands)

if __name__ == "__main__":
	main()


text:
.. pynrm documentation master file, created by
   sphinx-quickstart on Fri May  9 21:25:45 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to pynrm's documentation!
=================================

.. toctree::
   :maxdepth: 2

   intro
   pypoise
   aoinstrument
   nirc2


text:
<?php

namespace Acme\DoctrineBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 */
class ProductRepository extends EntityRepository
{
    const MAX_LIMIT = 50;

    public function findAllOrderByName()
    {
        $em = $this->getEntityManager();
        $queryBuilder = $em->createQueryBuilder('product');
        $products = $queryBuilder->select('product')
            ->from('BaseApiBundle:Product', 'product')
            ->orderBy('product.name', 'DESC')
            ->getQuery()
            ->getResult();
        return $products;
    }

    public function findOneByIdJoinedToCategory($id)
    {
        $em = $this->getEntityManager();
        $query = $em->createQuery('
            SELECT p, c FROM BaseApiBundle:Product p
            JOIN p.category c
            WHERE p.id = :id'
        )->setParameter('id', $id);

        try {
            return $query->getSingleResult();
        }
        catch(\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }

    public function findPaginated($from, $limit)
    {
        $from = isset($from) ? $from : 0;
        $limit   = !empty($limit) ? $limit : self::MAX_LIMIT;

        // do not allow
        if($limit > self::MAX_LIMIT) {
            $limit = self::MAX_LIMIT;
        }

        $to = $from + $limit;

        $em = $this->getEntityManager();
        $query = $em->createQuery('SELECT p FROM BaseApiBundle:Product p')
            ->setFirstResult($from)
            ->setMaxResults($to);

        try {
            $paginator = new Paginator($query, false);
        }
        catch(\Doctrine\ORM\NoResultException $e) {
            return null;
        }

        $entities = array();

        foreach ($paginator as $entity) {
            $entities[] = $entity;
        }

        return $entities;
    }
}


text:
/////////////////////////////////////////////////////////////////////////
// $Id: osdep.cc,v 1.18 2008/02/05 22:57:40 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

//
// osdep.cc
//
// Provide definition of library functions that are missing on various
// systems.  The only reason this is a .cc file rather than a .c file
// is so that it can include bochs.h.  Bochs.h includes all the required
// system headers, with appropriate #ifdefs for different compilers and
// platforms.
//

#include "bochs.h"

//////////////////////////////////////////////////////////////////////
// Missing library functions.  These should work on any platform
// that needs them.
//////////////////////////////////////////////////////////////////////

#if !BX_HAVE_SNPRINTF
/* XXX use real snprintf */
/* if they don't have snprintf, just use sprintf */
int bx_snprintf (char *s, size_t maxlen, const char *format, ...)
{
  va_list arg;
  int done;

  va_start (arg, format);
  done = vsprintf (s, format, arg);
  va_end (arg);

  return done;
}

#endif  /* !BX_HAVE_SNPRINTF */

#if !BX_HAVE_VSNPRINTF
int bx_vsnprintf (char *s, size_t maxlen, const char *format, va_list arg)
{
  return vsprintf (s, format, arg);
}
#endif /* !BX_HAVE_VSNPRINTF*/

#if (!BX_HAVE_STRTOULL && !BX_HAVE_STRTOUQ)
/* taken from glibc-2.2.2: strtod.c, and stripped down a lot.  There are
   still a few leftover references to decimal points and exponents,
   but it works for bases 10 and 16 */

#define RETURN(val,end)							      \
    do { if (endptr != NULL) *endptr = (char *) (end);		      \
	 return val; } while (0)

Bit64u
bx_strtoull (const char *nptr, char **endptr, int baseignore)
{
  int negative;			/* The sign of the number.  */
  int exponent;			/* Exponent of the number.  */

  /* Numbers starting `0X' or `0x' have to be processed with base 16.  */
  int base = 10;

  /* Number of bits currently in result value.  */
  int bits;

  /* Running pointer after the last character processed in the string.  */
  const char *cp, *tp;
  /* Start of significant part of the number.  */
  const char *startp, *start_of_digits;
  /* Total number of digit and number of digits in integer part.  */
  int dig_no;
  /* Contains the last character read.  */
  char c;

  Bit64s n = 0;
  char const *p;

  /* Prepare number representation.  */
  exponent = 0;
  negative = 0;
  bits = 0;

  /* Parse string to get maximal legal prefix.  We need the number of
     characters of the integer part, the fractional part and the exponent.  */
  cp = nptr - 1;
  /* Ignore leading white space.  */
  do
    c = *++cp;
  while (isspace (c));

  /* Get sign of the result.  */
  if (c == '-')
    {
      negative = 1;
      c = *++cp;
    }
  else if (c == '+')
    c = *++cp;

  if (c < '0' || c > '9')
    {
      /* It is really a text we do not recognize.  */
      RETURN (0, nptr);
    }

  /* First look whether we are faced with a hexadecimal number.  */
  if (c == '0' && tolower (cp[1]) == 'x')
    {
      /* Okay, it is a hexa-decimal number.  Remember this and skip
	 the characters.  BTW: hexadecimal numbers must not be
	 grouped.  */
      base = 16;
      cp += 2;
      c = *cp;
    }

  /* Record the start of the digits, in case we will check their grouping.  */
  start_of_digits = startp = cp;

  /* Ignore leading zeroes.  This helps us to avoid useless computations.  */
  while (c == '0')
    c = *++cp;

  /* If no other digit but a '0' is found the result is 0.0.
     Return current read pointer.  */
  if ((c < '0' || c > '9')
      && (base == 16 && (c < tolower ('a') || c > tolower ('f')))
      && (base == 16 && (cp == start_of_digits || tolower (c) != 'p'))
      && (base != 16 && tolower (c) != 'e'))
    {
      tp = start_of_digits;
      /* If TP is at the start of the digits, there was no correctly
	 grouped prefix of the string; so no number found.  */
      RETURN (0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp);
    }

  /* Remember first significant digit and read following characters until the
     decimal point, exponent character or any non-FP number character.  */
  startp = cp;
  dig_no = 0;
  while (1)
    {
      if ((c >= '0' && c <= '9')
	  || (base == 16 && tolower (c) >= 'a' && tolower (c) <= 'f'))
	++dig_no;
      else
	break;
      c = *++cp;
    }

  /* The whole string is parsed.  Store the address of the next character.  */
  if (endptr)
    *endptr = (char *) cp;

  if (dig_no == 0)
    return 0;

  for (p=start_of_digits; p!=cp; p++) {
    n = n * (Bit64s)base;
    c = tolower (*p);
    c = (c >= 'a') ? (10+c-'a') : c-'0';
    n = n + (Bit64s)c;
    //printf ("after shifting in digit %c, n is %lld\n", *p, n);
  }
  return negative? -n : n;
}
#endif  /* !BX_HAVE_STRTOULL */

#if BX_TEST_STRTOULL_MAIN
/* test driver for strtoull.  Do not compile by default. */
int main (int argc, char **argv)
{
  char buf[256], *endbuf;
  long l;
  Bit64s ll;
  while (1) {
    printf ("Enter a long int: ");
    gets (buf);
    l = strtoul (buf, &endbuf, 10);
    printf ("As a long, %ld\n", l);
    printf ("Endbuf is at buf[%d]\n", endbuf-buf);
    ll = bx_strtoull (buf, &endbuf, 10);
    printf ("As a long long, %lld\n", ll);
    printf ("Endbuf is at buf[%d]\n", endbuf-buf);
  }
  return 0;
}
#endif  /* BX_TEST_STRTOULL_MAIN */

#if !BX_HAVE_STRDUP
/* XXX use real strdup */
char *bx_strdup(const char *str)
{
	char *temp;

	temp = (char*)malloc(strlen(str)+1);
	sprintf(temp, "%s", str);
	return temp;

	// Well, I'm sure this isn't how strdup is REALLY implemented,
	// but it works...
}
#endif  /* !BX_HAVE_STRDUP */

#if !BX_HAVE_STRREV
char *bx_strrev(char *str)
{
  char *p1, *p2;

  if (! str || ! *str)
    return str;

  for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
    *p1 ^= *p2;
    *p2 ^= *p1;
    *p1 ^= *p2;
  }
  return str;
}
#endif  /* !BX_HAVE_STRREV */

#if BX_WITH_MACOS
namespace std{extern "C" {char *mktemp(char *tpl);}}
#endif
#if !BX_HAVE_MKSTEMP
int bx_mkstemp(char *tpl)
{
  mktemp(tpl);
  return ::open(tpl, O_RDWR | O_CREAT | O_TRUNC
#  ifdef O_BINARY
            | O_BINARY
#  endif
              , S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP);
}
#endif // !BX_HAVE_MKSTEMP

//////////////////////////////////////////////////////////////////////
// Missing library functions, implemented for MacOS only
//////////////////////////////////////////////////////////////////////

#if BX_WITH_MACOS
// these functions are part of MacBochs.  They are not intended to be
// portable!
#include <Devices.h>
#include <Files.h>
#include <Disks.h>

int fd_read(char *buffer, Bit32u offset, Bit32u bytes)
{
	OSErr err;
	IOParam param;

	param.ioRefNum=-5; // Refnum of the floppy disk driver
	param.ioVRefNum=1;
	param.ioPosMode=fsFromStart;
	param.ioPosOffset=offset;
	param.ioBuffer=buffer;
	param.ioReqCount=bytes;
	err = PBReadSync((union ParamBlockRec *)(&param));
	return param.ioActCount;
}

int fd_write(char *buffer, Bit32u offset, Bit32u bytes)
{
	OSErr		err;
	IOParam	param;

	param.ioRefNum=-5; // Refnum of the floppy disk driver
	param.ioVRefNum=1;
	param.ioPosMode=fsFromStart;
	param.ioPosOffset=offset;
	param.ioBuffer=buffer;
	param.ioReqCount=bytes;
	err = PBWriteSync((union ParamBlockRec *)(&param));
	return param.ioActCount;
}

int fd_stat(struct stat *buf)
{
	OSErr		err;
	DrvSts	status;
	int			result;

	result = 0;
	err = DriveStatus(1, &status);
	if (status.diskInPlace <1 || status.diskInPlace > 2)
		result = -1;
	buf->st_mode = S_IFCHR;
	return result;
}
#endif /* BX_WITH_MACOS */

//////////////////////////////////////////////////////////////////////
// New functions to replace library functions
//   with OS-independent versions
//////////////////////////////////////////////////////////////////////

#if BX_HAVE_REALTIME_USEC
#if defined(WIN32)
static Bit64u last_realtime64_top = 0;
static Bit64u last_realtime64_bottom = 0;

Bit64u bx_get_realtime64_usec(void)
{
  Bit64u new_bottom = ((Bit64u) GetTickCount()) & BX_CONST64(0x0FFFFFFFF);
  if(new_bottom < last_realtime64_bottom) {
    last_realtime64_top += BX_CONST64(0x0000000100000000);
  }
  last_realtime64_bottom = new_bottom;
  Bit64u interim_realtime64 =
    (last_realtime64_top & BX_CONST64(0xFFFFFFFF00000000)) |
    (new_bottom          & BX_CONST64(0x00000000FFFFFFFF));
  return interim_realtime64*(BX_CONST64(1000));
}
#elif BX_HAVE_GETTIMEOFDAY
Bit64u bx_get_realtime64_usec(void)
{
  timeval thetime;
  gettimeofday(&thetime,0);
  Bit64u mytime;
  mytime=(Bit64u)thetime.tv_sec*(Bit64u)1000000+(Bit64u)thetime.tv_usec;
  return mytime;
}
#endif
#endif


text:
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.CommitmentsV2.Domain.Interfaces;

namespace SFA.DAS.CommitmentsV2.Application.Commands.SendCohort
{
    public class SendCohortCommandHandler : AsyncRequestHandler<SendCohortCommand>
    {
        private readonly ICohortDomainService _cohortDomainService;

        public SendCohortCommandHandler(ICohortDomainService cohortDomainService)
        {
            _cohortDomainService = cohortDomainService;
        }

        protected override Task Handle(SendCohortCommand request, CancellationToken cancellationToken)
        {
            return _cohortDomainService.SendCohortToOtherParty(request.CohortId, request.Message, request.UserInfo, cancellationToken);
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Options | @storefront/core</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@storefront/core

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					TrackerService

					Options

Interface Options

Hierarchy

						Options

Index

Properties

send<wbr>Add<wbr>ToCart<wbr>Event

send<wbr>More<wbr>Refinements<wbr>Event

send<wbr>Order<wbr>Event

send<wbr>Remove<wbr>From<wbr>Cart<wbr>Event

send<wbr>Search<wbr>Event

send<wbr>View<wbr>Cart<wbr>Event

send<wbr>View<wbr>Product<wbr>Event

warnings

Properties

Optional send<wbr>Add<wbr>ToCart<wbr>Event

send<wbr>Add<wbr>ToCart<wbr>Event: Override<GbTracker.CartEvent, GbTracker.CartEvent>

Defined in services/tracker.ts:151

Optional send<wbr>More<wbr>Refinements<wbr>Event

send<wbr>More<wbr>Refinements<wbr>Event: Override<string, GbTracker.MoreRefinementsEvent>

Defined in services/tracker.ts:155

Optional send<wbr>Order<wbr>Event

send<wbr>Order<wbr>Event: Override<GbTracker.OrderEvent, GbTracker.OrderEvent>

Defined in services/tracker.ts:153

Optional send<wbr>Remove<wbr>From<wbr>Cart<wbr>Event

send<wbr>Remove<wbr>From<wbr>Cart<wbr>Event: Override<GbTracker.CartEvent, GbTracker.CartEvent>

Defined in services/tracker.ts:152

Optional send<wbr>Search<wbr>Event

send<wbr>Search<wbr>Event: Override<string, GbTracker.SearchEvent>

Defined in services/tracker.ts:149

Optional send<wbr>View<wbr>Cart<wbr>Event

send<wbr>View<wbr>Cart<wbr>Event: Override<GbTracker.CartEvent, GbTracker.CartEvent>

Defined in services/tracker.ts:150

Optional send<wbr>View<wbr>Product<wbr>Event

send<wbr>View<wbr>Product<wbr>Event: Override<GbTracker.ViewProductEvent, GbTracker.ViewProductEvent>

Defined in services/tracker.ts:154

Optional warnings

warnings: boolean

Defined in services/tracker.ts:148

						Globals

						Tracker<wbr>Service

								Options

										send<wbr>Add<wbr>ToCart<wbr>Event

										send<wbr>More<wbr>Refinements<wbr>Event

										send<wbr>Order<wbr>Event

										send<wbr>Remove<wbr>From<wbr>Cart<wbr>Event

										send<wbr>Search<wbr>Event

										send<wbr>View<wbr>Cart<wbr>Event

										send<wbr>View<wbr>Product<wbr>Event

										warnings

								constructor

								app

								client

								opts

								transform

								add<wbr>Metadata

								apply<wbr>Opts<wbr>Override

								build<wbr>Event

								get<wbr>Metadata

								get<wbr>Search<wbr>Origin

								init

								send<wbr>Add<wbr>ToCart<wbr>Event

								send<wbr>Event

								send<wbr>More<wbr>Refinements<wbr>Event

								send<wbr>Order<wbr>Event

								send<wbr>Remove<wbr>From<wbr>Cart<wbr>Event

								send<wbr>Search<wbr>Event

								send<wbr>View<wbr>Cart<wbr>Event

								send<wbr>View<wbr>Product<wbr>Event

								set<wbr>Listeners

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
<?php

namespace Seahinet\Retailer\ViewModel;

use Seahinet\Lib\ViewModel\Template;
use Seahinet\Retailer\ViewModel\SalesProducts;
use Seahinet\Retailer\Model\StoreTemplate;
use Seahinet\Retailer\Model\Retailer;
use Seahinet\Retailer\Model\Collection\Retailer as RetailerCollection;
use Seahinet\Retailer\Model\Collection\StoreTemplateCollection;
use Seahinet\Retailer\Model\Collection\StorePicInfoCollection;
use Seahinet\Lib\Session\Segment;

class StoreDecoration extends Template
{

    /**
     * Get store template view
     *
     * @access public
     * @return object
     */
    public function judge_store_id($current_store_id = null)
    {
        if (empty($current_store_id)) {
            $segment = new Segment('customer');
            $r = new Retailer;
            $r->load($segment->get('customer')->getId(), 'customer_id');
            $store_id = $r['store_id'];
        } else {
            $store_id = $current_store_id;
        }
        return $store_id;
    }

    public function getTemplateView($current_store_id = null, $model = 0)
    {
        $templateView = [];
        $id = $this->getQuery('id');
        $key = $this->getQuery('key');
        $store_id = $this->judge_store_id($current_store_id);

        if ($model != 0)
            $id = $model;
        if (!empty($id)) {
            if ($id != '-1') {
                $template = new StoreTemplate;

                $templateView = $template->load($id);
            }
        } else {
            if (empty($key)) {
                $template = new StoreTemplateCollection;

                $templateViewCollection = $template->storeTemplateList($store_id, 1);
                if (!empty($templateViewCollection))
                    $templateView = $templateViewCollection[0];
                else
                    $templateView = [];
            }else {

                $key = base64_decode($key);
                $storeTemplate = new storeTemplate;
                $templateView = $storeTemplate->load($key);
            }
        }

        if (!empty($templateView)) {
            $templateView['code_model'] = $this->changeModel($templateView['code_model'], $store_id);
            $templateView['src_model'] = $this->changeModel($templateView['src_model'], $store_id);
            $templateView['stable_params'] = $this->changeStableParams($templateView['stable_params'], $store_id);
        }

        if (!empty($templateView) && $templateView['store_id'] != $store_id && $templateView['store_id'] != 0 && is_null($current_store_id))
            $templateView = [];

        return $templateView;
    }

    public function getProductDetailTemplateView($store_id)
    {
        $template = new StoreTemplateCollection;
        $template->storeTemplateList($store_id, 1);
        $template_id = count($template) > 0 ? $template[0]['id'] : -2;
        $view = '';
        if ($template_id > 0) {
            $template = new StoreTemplateCollection;
            $template->storeCustomizeTemplate($store_id, $template_id, 2);
            $final_id = count($template) > 0 ? $template[0]['id'] : -2;
            $view = $this->getTemplateView($store_id, $final_id);
        }
        return $view;
    }

    public function changeModel($view, $current_store_id = null)
    {
        $final_view = $view;

        $tempParams = array(
            'long_search',
            'short_search',
            'product_class',
            'sales_amount',
            'hot_product',
            'store_recommend',
            'product_recommend',
            'pic_carousel');

        foreach ($tempParams as $value) {
            $params = $this->divideParam($value, $final_view);
            foreach ($params as $key1 => $value1) {
                $func = 'template_' . $value;
                $final_view = str_replace('{{' . $value . ':' . $value1 . '}}', $this->$func($value1, $current_store_id), $final_view);
            }
        }

        return $final_view;
    }

    public function changeStableParams($params, $current_store_id = null)
    {
        $params = urldecode($params);
        $params = json_decode($params, true);
        return $params;
    }

    public function divideParam($value, $str)
    {

        preg_match_all("|{{" . $value . ":([^^]*?)}}|u", $str, $matches);
        return $matches[1];
    }

    /**
     * Get store template list
     *
     * @access public
     * @return object
     * @param  judge 1:theme template; 0:customer template
     */
    public function getTemplateList($judge = 0)
    {
        $segment = new Segment('customer');
        $template = new StoreTemplateCollection;
        $r = new Retailer;
        $r->load($segment->get('customer')->getId(), 'customer_id');
        if ($judge == 0)
            $template->storeTemplateList($r['store_id']);
        else
            $template->storeTemplateList(0);
        return $template;
    }

    public function getProductDetailPageID($template_id)
    {
        $id = 0;
        $store_id = $this->judge_store_id();
        $template = new StoreTemplateCollection;
        $template->storeCustomizeTemplate($store_id, $template_id, 2);
        if (count($template)) {
            $id = $template[0]['id'];
        } else {
            $template = new StoreTemplate;
            $data = ['parent_id' => $template_id, 'store_id' => $store_id, 'page_type' => 2];
            $template->setData($data);
            $template->save();
            $id = $template->getId();
        }
        return $id;
    }

    public function getStorePicInfo($code, $current_store_id = null, $current_template_id = null, $part_id = null)
    {
        $Scollection = new StorePicInfoCollection;

        $store_id = $this->judge_store_id($current_store_id);
        $filters = ['resource_category_code' => $code, 'store_decoration_picinfo.store_id' => $store_id];

        if (!empty($current_template_id))
            $filters['template_id'] = $current_template_id;
        else
            $filters['template_id'] = null;

        if (!empty($part_id))
            $filters['part_id'] = $part_id;
        else
            $filters['part_id'] = null;

        $Scollection->where($filters)
                ->join('resource', 'store_decoration_picinfo.resource_id = resource.id', ['real_name'], 'left')->order(['resource.created_at' => 'DESC']);

        return $Scollection;
    }

    public function getCustomizeInfo($template_id, $page_type, $current_store_id = null)
    {
        $store_id = $this->judge_store_id($current_store_id);
        $template = new StoreTemplateCollection;
        $template->storeCustomizeTemplate($store_id, $template_id, $page_type);
        $r = new Retailer;
        $r->load($store_id, 'store_id');
        $url = $this->getBaseUrl() . $r->getStoreUrl();
        foreach ($template as $key => $value) {
            $template[$key]['url'] = $url . "?key=" . urlencode(base64_encode($value['id']));
        }
        return $template;
    }

    public function getStoreBanner($current_store_id = null, $current_retailer = null)
    {
        $store_id = $this->judge_store_id($current_store_id);
        if (empty($current_retailer)) {
            $segment = new Segment('customer');
            $customer_id = $segment->get('customer')['id'];
        } else {
            $customer_id = $current_retailer['customer_id'];
        }
        $retailer = new RetailerCollection;
        $retailer->join('retailer_manager', 'retailer_manager.retailer_id=retailer.id', [], 'left')
                ->where(['retailer_manager.customer_id' => $customer_id, 'retailer.store_id' => $store_id])
                ->join('resource', 'retailer.banner = resource.id', ['real_name'], 'left')->order(['resource.created_at' => 'DESC']);
        //return $segment->get('customer');
        return empty($retailer) ? [] : $retailer[0];
    }

    public function getSearchProducts()
    {
        $condition = $this->getQuery();
        $products = new SalesProducts();
        $productsData = $products->getRetailerSalesProducts($condition);
        $content = "";
        foreach ($productsData as $key => $value) {
            $product = new \Seahinet\Catalog\Model\Product;
            $product->load($value['id']);
            $urls = $product->getUrl();
            $thumbnail = $products->getProduct($value['id'])->getThumbnail();
            if (strpos($thumbnail, 'http') === false) {
                $picURL = $this->getResourceUrl('image/resized/228x/' . $thumbnail);
            } else {
                $picURL = $thumbnail;
            }

            $content .= '

' . $products->getCurrency()->format($value['price']) . ' ' . $products->getCurrency()->format($value['price']) . '

' . $value['name'] . '

';
        }
        return $content;
    }

    /*
     * template content
     *
     *
     */

    public function template_logo_top($params = '', $current_store_id = null, $current_retailer = null)
    {
        if (!empty($params)) {
//			if($params['widthSetType'] == "1")
//				$width = $params['widthSet']."px";
//			else
//				$width = '100%';
            $height = $params['heightSet'] . "px";
        } else {
            $width = '1128px';
            $height = '200px';
        }
        $retailer = $this->getStoreBanner($current_store_id, $current_retailer);
//		if(!empty($retailer['real_name']))
//			$content = 'getBaseUrl('/pub/resource/image/'.$retailer['real_name']).'">';
//		else
//			$content = 'getBaseUrl('/pub/theme/default/frontend/dragResource/images/text1.jpg').'">';
        if (!empty($retailer['real_name']))
            $content = $this->getBaseUrl('/pub/resource/image/' . $retailer['real_name']);
        else
            $content = $this->getBaseUrl('/pub/theme/default/frontend/dragResource/images/text1.jpg');
        return $content;
    }

    public function template_menu($params = '', $current_store_id = null)
    {
        $store_id = $this->judge_store_id($current_store_id);
        $r = new Retailer;
        $r->load($store_id, 'store_id');
        $url = $this->getBaseUrl() . $r->getStoreUrl();
        $result = $this->getStorePicInfo('menu', $current_store_id);
        $content = '
首 页
';
        foreach ($result as $key => $value) {
            if (trim($value['url']) != "")
                $content .= '
' . $value['pic_title'] . '
';
            else
                $content .= '
' . $value['pic_title'] . '
';
        }
        return $content;
    }

    public function template_paragraph($params = '', $current_store_id = null)
    {
        $content = '

可以在此模块中通过编辑器自由输入文字以及编排格式

';
        return $content;
    }

    public function template_long_search($params = '', $current_store_id = null)
    {
        $content = '<form target=_blank action="' . $this->getBaseUrl('/retailer/store/viewSearch') . '">本店搜索
                 <input class="keyword" type="text" name="name" value="" />
                <input class="price-from" type="text" name="price_from" value="" />
                 -
                <input class="price-to" type="text" name="price_to" value="" />
                <button class="search-button">搜索</button>
                </form>';
        return $content;
    }

    public function template_short_search($params = '', $current_store_id = null)
    {
        $content = '

本店搜索

                    <form target=_blank action="' . $this->getBaseUrl('/retailer/store/viewSearch') . '">

                            关键字:
                            <input class="keyword" type="text" name="name" value="" />

                            价格:
                            <input class="price-from" type="text" name="price_from" value="" />  <input class="price-to" type="text" name="price_to" value="" />

                            <button class="search-button">搜索</button>

                            热门
                            雄鹰能量棒 吸入式咖啡

                    </form>

';
        return $content;
    }

    public function template_product_class($params = '', $current_store_id = null)
    {
        $content = '

查看所有分类>>

按销量 按价格 按评价 按新品

                            薄荷糖口香糖补充剂等

                            益智开脑洞

                            睡眠放松

                            改善心情

                            能量补充

';
        return $content;
    }

    public function template_sales_amount($params = '', $current_store_id = null)
    {
        if (!empty($params)) {
            $params = urldecode($params);
            $params = json_decode($params, true);
        }

        //$hot_text = empty($params) ? "" : $params['hot_text'];
        //$price_from = empty($params) ? "" : $params['price_from'];
        //$price_to = empty($params) ? "" : $params['price_to'];
        $select_row = empty($params) ? 3 : $params['select_row'];
        //$product_ids = empty($params['product_ids']) ? "" : $params['product_ids'] ;
        //$condition['name'] = $hot_text;
        $condition['limit'] = $select_row;
        //$condition['price_from'] = $price_from;
        //$condition['price_to'] = $price_to;
        //$condition['product_ids'] = $product_ids;
        $products = new SalesProducts();
        $productsData = $products->getRetailerSalesProducts($condition, $current_store_id);

        $content = '
';

        foreach ($productsData as $key => $value) {
            $product = new \Seahinet\Catalog\Model\Product;
            $product->load($value['id']);
            $urls = $product->getUrl();
            $thumbnail = $products->getProduct($value['id'])->getThumbnail();
            if (strpos($thumbnail, 'http') === false) {
                $picURL = $this->getResourceUrl('image/resized/228x/' . $thumbnail);
            } else {
                $picURL = $thumbnail;
            }

            $content .= '

' . $value['name'] . '

' . $products->getCurrency()->format($value['price']) . '

';
        }

        $content .= '
';
        return $content;
    }

    public function template_hot_product($params = '', $current_store_id = null)
    {

        if (!empty($params)) {
            $params = urldecode($params);
            $params = json_decode($params, true);
        }

        $hot_text = empty($params) ? "" : $params['hot_text'];
        $price_from = empty($params) ? "" : $params['price_from'];
        $price_to = empty($params) ? "" : $params['price_to'];
        $select_row = empty($params) ? 1 : $params['select_row'];
        $select_column = empty($params) ? 4 : (int) $params['select_column'];

        $product_ids = empty($params['product_ids']) ? "" : $params['product_ids'];
        $select_col_md = 'col-md-3';
        $pic_height = '225px';
        switch ($select_column) {
            case 3:
                $select_col_md = 'col-md-4';
                $pic_height = '313px';
                break;
            case 2:
                $select_col_md = 'col-md-6';
                $pic_height = '490px';
                break;
            case 1:
                $select_col_md = 'col-md-12';
                $pic_height = '';
                break;
            default:
                $select_col_md = 'col-md-3';
                $pic_height = '225px';
                break;
        }

        $condition['name'] = $hot_text;
        $condition['limit'] = $select_column * $select_row;
        $condition['price_from'] = $price_from;
        $condition['price_to'] = $price_to;
        $condition['product_ids'] = $product_ids;
        $products = new SalesProducts();
        $productsData = $products->getRetailerSalesProducts($condition, $current_store_id);

        $content = '
';
        foreach ($productsData as $key => $value) {
            $product = new \Seahinet\Catalog\Model\Product;
            $product->load($value['id']);
            $urls = $product->getUrl();
            $thumbnail = $products->getProduct($value['id'])->getThumbnail();
            if (strpos($thumbnail, 'http') === false) {
                $picURL = $this->getResourceUrl('image/resized/228x/' . $thumbnail);
            } else {
                $picURL = $thumbnail;
            }

            $content .= '

' . $products->getCurrency()->format($value['price']) . ' ' . $products->getCurrency()->format($value['price']) . '

' . $value['name'] . '

';
        }
        $content .= '
';
        return $content;
    }

    public function func_getProductInfo($condition, $current_store_id = null)
    {
        $products = new SalesProducts();
        $productsData = $products->getRetailerSalesProducts($condition, $current_store_id);
        $productsDataCount = $products->getRetailerSalesProductsCount($condition, $current_store_id);
        foreach ($productsData as $key => $value) {
            $product = new \Seahinet\Catalog\Model\Product;
            $product->load($value['id']);
            $urls = $product->getUrl();
            $thumbnail = $products->getProduct($value['id'])->getThumbnail();
            if (strpos($thumbnail, 'http') === false) {
                $picURL = $this->getResourceUrl('image/' . $thumbnail);
            } else {
                $picURL = $thumbnail;
            }
            $productsData[$key]['productURL'] = $urls;
            $productsData[$key]['picURL'] = $picURL;
            $productsData[$key]['acturalPrice'] = $products->getCurrency()->format($value['price']);
        }
        return ['data' => $productsData, 'count' => $productsDataCount];
    }

    public function template_store_recommend($params = '', $current_store_id = null)
    {

        if (!empty($params)) {
            $params = urldecode($params);
            $params = json_decode($params, true);
        }

        $hot_text = empty($params) ? "" : $params['hot_text'];
        $price_from = empty($params) ? "" : $params['price_from'];
        $price_to = empty($params) ? "" : $params['price_to'];
        $product_ids = empty($params['product_ids']) ? "" : $params['product_ids'];

        $condition['name'] = $hot_text;
        $condition['limit'] = 9;
        $condition['price_from'] = $price_from;
        $condition['price_to'] = $price_to;
        $condition['product_ids'] = $product_ids;

        $result = $this->func_getProductInfo($condition, $current_store_id);
        $products = $result['data'];

        $content = '';
        for ($i = 0; $i < 3; $i++) {
            $content .= '
';

            if ($i == 1) {
                if (!empty($products[0]))
                    $content .= '

' . $products[0]['acturalPrice'] . ' ' . $products[0]['acturalPrice'] . '

' . $products[0]['name'] . '

';
                else
                    $content .= '

';
            }else {
                for ($j = 0; $j < 4; $j++) {
                    if ($i == 0)
                        $index = $j + 1;
                    if ($i == 2)
                        $index = $j + 5;
                    if (!empty($products[$index]))
                        $content .= '

';
                    else
                        $content .= '

';
                }
            }

            $content .= '
';
        }

        return $content;
    }

    public function template_product_recommend($params = '', $current_store_id = null)
    {
        if (!empty($params)) {
            $params = urldecode($params);
            $params = json_decode($params, true);
        }

        $product_ids = empty($params['product_ids']) ? "" : $params['product_ids'];
        $hot_text = empty($params) ? "" : $params['hot_text'];
        $price_from = empty($params) ? "" : $params['price_from'];
        $price_to = empty($params) ? "" : $params['price_to'];
        $select_row = empty($params) ? 1 : $params['select_row'];
        $select_column = empty($params) ? 4 : (int) $params['select_column'];
        $select_col_md = 'col-md-3';
        $pic_height = '225px';
        switch ($select_column) {
            case 3:
                $select_col_md = 'col-md-4';
                $pic_height = '313px';
                break;
            case 2:
                $select_col_md = 'col-md-6';
                $pic_height = '490px';
                break;
            case 1:
                $select_col_md = 'col-md-12';
                $pic_height = '';
                break;
            default:
                $select_col_md = 'col-md-3';
                $pic_height = '225px';
                break;
        }

        $condition['name'] = $hot_text;
        $condition['limit'] = $select_column * $select_row;
        $condition['price_from'] = $price_from;
        $condition['price_to'] = $price_to;
        $condition['product_ids'] = $product_ids;
        //$condition['recomend_status'] = "1";
        $products = new SalesProducts();
        $productsData = $products->getRetailerSalesProducts($condition, $current_store_id);

        $content = '
';
        foreach ($productsData as $key => $value) {
            $product = new \Seahinet\Catalog\Model\Product;
            $product->load($value['id']);
            $urls = $product->getUrl();
            $thumbnail = $products->getProduct($value['id'])->getThumbnail();
            if (strpos($thumbnail, 'http') === false) {
                $picURL = $this->getResourceUrl('image/resized/228x/' . $thumbnail);
            } else {
                $picURL = $thumbnail;
            }

            $content .= '

' . $products->getCurrency()->format($value['price']) . '

' . $value['name'] . '

';
        }
        $content .= '
';
        return $content;
    }

    public function template_pic_carousel($params = '', $current_store_id = null)
    {
        if (!empty($params)) {
            $params = urldecode($params);
            $params = json_decode($params, true);
        }

        $current_template_id = empty($params) ? "" : $params['current_template_id'];
        $part_id = empty($params) ? "" : $params['part_id'];

        $content = '

';
        $result = $this->getStorePicInfo('store_carousel', $current_store_id, $current_template_id, $part_id);
        foreach ($result as $key => $value) {
            if (trim($value['url']) != "")
                $content .= '
getBaseUrl('/pub/resource/image/' . $value['real_name']) . '" alt="' . $value['pic_title'] . '">
';
            else
                $content .= '
getBaseUrl('/pub/resource/image/' . $value['real_name']) . '" alt="' . $value['pic_title'] . '">
';
        }
        $content .= '

';
        return $content;
    }

}


text:
<?php

use Aspose\Cloud\Common\AsposeApp;
use Aspose\Cloud\Common\Product;
use Aspose\Cloud\Tasks\Calendar;

class CalendarTest extends PHPUnit_Framework_TestCase {
    protected $object;

    protected function setUp()
    {
        Product::$baseProductUri = $_SERVER['BASE_PRODUCT_URI'];
        AsposeApp::$appSID = $_SERVER['APP_SID'];
        AsposeApp::$appKey = $_SERVER['APP_KEY'];
        AsposeApp::$outPutLocation = getcwd(). '/Data/Output/';

        // Create calendar object
        $this->object = new Calendar('MyProject.mpp');
    }

    public function testGetCalendars()
    {
        $result = $this->object->getCalendars();
        print_r($result);
        $this->assertInternalType('array',$result);
    }

    public function testGetCalendar()
    {
        $calendarUid = 5;
        $result = $this->object->getCalendar($calendarUid);
        $this->assertInstanceOf('stdClass',$result);
    }

    public function testAddCalendar()
    {
        $jsonData = '';
        $result = $this->object->addCalendar($jsonData);
        $this->assertInstanceOf('stdClass',$result);
    }

    public function testDeleteCalendar()
    {
        $calendarUid = 5;
        $changedFileName = 'changed.mpp';
        $this->object->deleteCalendar($calendarUid, $changedFileName);
        $this->assertFileExists(getcwd(). '/Data/Output/'. $changedFileName);
    }

}