text:
The server side of RIPACrypt - Remotely store secrets that are destroyed if the specified time has passed without a check-in *(a form of deadman switch)*

This is another thought experiment in defeating the Regulation of Investigatory
Powers Act 2000 Section 49 (compelled decryption) legislation using technology.

## Process
1. Create a RIPACrypt account (on the computer in which the disks are protected by full disk encryption)
2. Store the pass phrase for the full disk encryption in a crypt with a 3 hour timeout *(3x 1 hour check-ins)*
3. Configure `cron` to checkin every hour
4. Time passes...
5. Computer is seized *(Harrassment for running a Tor relay etc etc)*
6. After 3 hours without a successful checkin RIPACryptd deletes the secret from the crypt, locks the crypt and sets `IsDestroyed` to true
7. When issued with a s.49 notice you simply point to https://ripacrypt.download/view/YOURCRYPTID

## Questions
- You no longer possess the key to decrypt the FDE, are you failing to comply? *(RIPA 2000 s.53)*
- You couldn't prevent the destruction of the key because you were no longer in possession of the computer authorised to prevent it's deletion, have you obstructed a Police officer or perverted the course of justice?
- Have the Police 'stolen' your *digital* property by "permanently depriving" you of it? *(Theft Act 1968)*

## Development
- [x] Register
- [x] Create a new crypt
- [x] Checkin with crypt
- [x] View status of a crypt (API)
- [x] View status of a crypt (HTML)
- [x] Generate a challenge
- [x] Generate a new Bitcoin address
- [ ] Delete a crypt
- [ ] Specify a notification method if a checkin period is missed

## Disclaimers
**We are not a lawyers, solictiors or in any way well versed in the law. This software may result in you being found guilty of Failure to comply with a notice under the Regulation of Investigatory Powers Act 2000 and sentenced to up to 5 years in prison (or worse)**

> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# API
RIPACrypt provides an open API so that other clients can work with the service.
It can even be used with simple CURL calls *(see ExampleCurlCalls.md)*

### Endpoints
#### `POST` /1/register/
To register an account all that is needed is a GPG public key. This is used as authentication *(and for encrypting secrets)*

**Send:**

```json
{
 "public_key":"armoured public key (escaped line endings)"
}
```

**Receive:**

```json
{
 "status_code":200,
 "success":true,
 "status_message":"Your account has been successfully created",
 "version":1,
 "btc_addr":"",
 "user_id":10
}
```

#### `POST` /1/challenge
Challenges are nonces that are encrypted with your public key, you will need
to decrypt the challenge and send the nonce back as _plain text_ with the next
request. Successful challenges are deleted so you need to request a new
challenge before each authenticated request.

**Send:**

```json
{
 "fingerprint": "16 char GPG fingerprint",
 "user_id":your user id
}
```

**Receive:**

```json
{
 "challenge":"wcFMAwAx48WIB6+GARAAFBRUQf+IwA <snip>",
 "challenge_id":22,
 "user_id":9,
 "status_code":200,
 "success":true,
 "status_message":"challenge Successfully generated!",
 "version":1
}
```

#### `POST` /1/crypt/new/
Submit a secret to be stored specifying the CheckIn duration *(time between checkins)* in seconds and the miss count

**Send:**

```json
{
 "challenge":"PLAIN TEXT MD5 FROM CHALLENGE",
 "challenge_id":NUMERIC ID OF CHALLENGE,
 "user_id":YOUR ID,
 "crypt_content":"YOUR SECRET (PREFERABLY ENCRYPTED)",
 "description":"Description of your crypt (preferably tying it the computer/secret you are protecting",
 "checkin_duration": 86400,
 "miss_count": 3
}
```

**Receive:**

```json
{
 "status_code":201,
 "success":true,
 "status_message":"Crypt successfully created!",
 "version":1,
 "crypt":
 {
  "crypt_id": "29d48f65cf5899ba6119db5fc37648e5",
  "ciphertext":"W2+6uaow2WwHSitrOw1KmY9yqUykv41cHmdPtMF9pwP4Y9Q/eqOeqOv86+aFFoELgs4=",
  "crypt_timestamp":1459468801,
  "crypt_description":"Description of your crypt (preferably tying it the computer/secret you are protecting",
  "is_crypt_destroyed":false,
  "last_checkin":1459468801,
  "check_in_duration":86400,
  "miss_count":3
 }
}
```

#### `HEAD` /1/crypt/CRYPTID

**Send:**

N/A

**Receive:**

*Note these are HTTP headers*

Live crypt:

```
HTTP/1.1 200 OK
Content-Type: application/json
Date: Mon, 01 Apr 2016 0:0:10 GMT
```

Destroyed Crypt:

```
HTTP/1.1 410 Gone
Content-Type: application/json
Date: Mon, 01 Apr 2016 0:0:10 GMT
```

#### `GET` /1/crypt/CRYPTID
**Send:**

N/A

**Receive:**

*HTTP headers will match the JSON `status_code`*

Live Crypt:

```json
{
 "status_code":200,
 "success":true,
 "status_message":"Crypt Retrieval Successful!",
 "version":1,
 "crypt":
 {
  "crypt_id":"29d48f65cf5899ba6119db5fc37648e5",
  "ciphertext":"hQIMAwAx48WIB6+ <snip>",
  "crypt_timestamp":1459468801,
  "crypt_description":"Description of your crypt (preferably tying it the computer/secret you are protecting",
  "is_crypt_destroyed":false,
  "last_checkin":1459468801,
  "check_in_duration":86400,
  "miss_count":3
 }
}
```

Destroyed crypt:

```json
{
 "status_code":410,
 "success":true,
 "status_message":"Crypt metadata retrived but crypt was wiped",
 "version":1,
 "crypt":
 {
  "crypt_id":"9b759040321a408a5c7768b4511287a6",
  "ciphertext":"",
  "crypt_timestamp":1459468801,
  "crypt_description":"Description of your crypt (preferably tying it the computer/secret you are protecting",
  "is_crypt_destroyed":true,
  "last_checkin":1459468801,
  "check_in_duration":3600,
  "miss_count":20
 }
}
```

#### `DELETE` /1/crypt/CRYPTID
Delete allows you to destroy a crypt immediately, unfortunately the `last_checkin`
will still be valid so an observer can extrapolate that the crypt was destroyed
by an authorised user rather than by the system if they query the crypt before
the requisite amount of time has passed.

**Send:**

*Unspecified*

**Receive:**

*Unspecified*


text:
<?php  $this->load->view('admin/admin/head', $this->data)?>

Cập nhật thông tin quản trị viên

        <form class="form" id="form" action="" method="post" enctype="multipart/form-data">
            <fieldset>

                    Tên:*

                        <input name="name" id="param_name" _autocheck="true" value="<?php echo $info->name?>" type="text" />

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

                    Username:*

                        <input name="username" id="param_username" _autocheck="true" value="<?php echo $info->username ?>" type="text" />

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

                        <img src="<?php echo public_url('admin') ?>/images/icons/color/star.png" alt="">
                        Chú ý: Nếu cập nhật mật khẩu thì mới nhập giá trị

                    Password:*

                            <input name="password" id="param_password" _autocheck="true" value="" type="password" />

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

                    Nhập lại mật khẩu:*

                        <input name="re_password" id="param_re_password" _autocheck="true" value="" type="password" />

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

                    <input type="submit" value="Cập Nhật" class="redB" />

            </fieldset>
        </form>

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var redisModel = require('../models/redis'),
    _ = require('lodash'),
    q = require('q'),
    updateInfo = require('../lib/updateInfo.js');

module.exports = function (app) {
    var getOverviewData = function(req, res){
        var dfd = q.defer();
        redisModel.getAllKeys().done(function(keys){
            redisModel.formatKeys(keys).done(function(keyList){
                redisModel.getStatusCounts().done(function(countObject){
                    updateInfo.getMemoryUsage().done(function(memoryUsage){
                        if(countObject.stuck == 0) keyList = [];
                        else keyList = _.filter(keyList, function(key){ return key.status === "stuck"; });
                        var usage = [];
                        for(var time in memoryUsage.usage){
                            usage.push({time: time, memory: memoryUsage.usage[time]});
                        }
                        memoryUsage.usage = usage;
                        var model = { keys: keyList, counts: countObject, overview: true, memory: memoryUsage };
                        dfd.resolve(model);
                    });
                });
            });
        });
        return dfd.promise;
    }

    app.get('/', function (req, res) {
        getOverviewData(req, res).done(function(model){
            res.render('index', model);
        });
    });

    app.get('/api/', function (req, res) {
        getOverviewData(req, res).done(function(model){
            res.json(model);
        });
    });
};


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2017 Ryo Suzuki
//	Copyright (c) 2016-2017 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <array>
# include "Fwd.hpp"
# include "String.hpp"
# include "Array.hpp"
# include "../ThirdParty/libsvm/svm.h"

namespace s3d
{
	namespace SVM
	{
		using Paramter = svm_parameter;

		using Label = double;

		inline Paramter DefaultParameter(size_t maxIndex)
		{
			Paramter param;
			param.svm_type		= C_SVC;
			param.kernel_type	= RBF;
			param.degree		= 3;
			param.gamma			= 1.0 / maxIndex;
			param.coef0			= 0;
			param.nu			= 0.5;
			param.cache_size	= 100;
			param.C				= 1;
			param.eps			= 1e-3;
			param.p				= 0.1;
			param.shrinking		= 1;
			param.probability	= 0;
			param.nr_weight		= 0;
			param.weight_label	= nullptr;
			param.weight		= nullptr;

			return param;
		}

		template <size_t _Dimensions>
		struct SupportVector
		{
			static constexpr int32 Dimensions = _Dimensions;

			Label label;

			std::array<double, Dimensions> vector;
		};

		struct SparseSupportVector
		{
			Label label;

			Array<std::pair<int32, double>> vector;
		};

		class Problem
		{
		private:

			class CProblem;

			std::shared_ptr<CProblem> pImpl;

		public:

			Problem();

			template <size_t Dimensions>
			Problem(const Array<SupportVector<Dimensions>>& supportVectors)
				: Problem()
			{
				load(supportVectors);
			}

			Problem(const double* pSupportVectors, size_t num_dataset, size_t dimensions);

			Problem(const Array<SparseSupportVector>& supportVectors);

			Problem(const FilePath& path);

			~Problem();

			template <size_t Dimensions>
			bool load(const Array<SupportVector<Dimensions>>& supportVectors)
			{
				release();

				if (supportVectors.isEmpty())
				{
					return false;
				}

				return load(&supportVectors[0].label, supportVectors.size(), Dimensions);
			}

			bool load(const double* pSupportVectors, size_t num_dataset, size_t dimensions);

			bool load(const Array<SparseSupportVector>& supportVectors);

			bool load(const FilePath& path);

			void release();

			explicit operator bool() const;

			bool hasData() const;

			size_t num_SVs() const;

			int32 getMaxIndex() const;

			bool trainAndSaveModel(const FilePath& path, const Paramter& param) const;

			PredictModel trainAndCreateModel(const Paramter& param) const;
		};

		class PredictModel
		{
		private:

			class CPredictModel;

			std::shared_ptr<CPredictModel> pImpl;

		public:

			PredictModel();

			PredictModel(const FilePath& path);

			PredictModel(std::unique_ptr<svm_model*>&& ppModel);

			~PredictModel();
			explicit operator bool() const;

			bool hasData() const;

			bool load(const FilePath& path);

			void release();

			size_t num_classes() const;

			Array<int32> getLabels() const;

			Label predict(const Array<double>& vector) const;

			Label predict(const Array<std::pair<int32, double>>& vector) const;

			Label predictProbability(const Array<double>& vector, Array<double>& probabilities) const;

			Label predictProbability(const Array<std::pair<int32, double>>& vector, Array<double>& probabilities) const;
		};

		SparseSupportVector ParseSVMLight(StringView view);

		Array<SparseSupportVector> LoadSVMLight(const FilePath& path);

		bool SaveSVMLight(const FilePath& path, const Array<SparseSupportVector>& vector);

		double CalculateAccuracy(const PredictModel& model, const Array<SparseSupportVector>& testData);
	}

	void Formatter(FormatData& formatData, const SVM::SparseSupportVector& value);
}


text:
package io.github.yizhiru.thulac4j;

import java.util.List;
import java.util.stream.Collectors;

import static io.github.yizhiru.thulac4j.util.ModelPaths.*;

/**
 * 中文分词.
 */
public final class Segmenter {

	private static final SPChineseTokenizer TOKENIZER = new SPChineseTokenizer(
			Segmenter.class.getResourceAsStream(SEGMENTER_WEIGHT_PATH),
			Segmenter.class.getResourceAsStream(SEGMENTER_FEATURE_PATH),
			Segmenter.class.getResourceAsStream(SEGMENTER_LABEL_PATH));

	/**
	 * 中文分词
	 *
	 * @param text 待分词文本
	 * @return 分词结果
	 */
	public static List<String> segment(String text) {
		return TOKENIZER.tokenize(text)
				.stream()
				.map(item -> (item.word))
				.collect(Collectors.toList());
	}

	/**
	 * 添加自定义词典
	 *
	 * @param words 词典
	 */
	public static void addUserWords(List<String> words) {
		TOKENIZER.addUserWords(words);
	}

	/**
	 * 开启开启书名单独成词
	 */
	public static void enableTitleWord() {
		TOKENIZER.enableTitleWord();
	}

	/**
	 * 开启停用词过滤
	 */
	public static void enableFilterStopWords() {
		TOKENIZER.enableFilterStopWords();
	}

	/**
	 * 开启转简写
	 */
	public static void enableConvertToSimplifiedCHN() {
		TOKENIZER.enableConvertToSimplifiedCHN();
	}
}


text:
"""Tests for the SHA-256 hasher implementation."""

import unittest

from plaso.hashers import sha256

from tests.hashers import test_lib

class SHA256Test(test_lib.HasherTestCase):
  """Tests the SHA-256 hasher."""

  def testFileHashMatches(self):
    """Tests that a few known files match the expected hashes."""
    empty_file_sha256 = u'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca49' \
                        u'5991b7852b855'
    hasher = sha256.SHA256Hasher()
    self._AssertTestPathStringDigestMatch(
        hasher, [u'empty_file'], empty_file_sha256)
    hasher = sha256.SHA256Hasher()
    self._AssertTestPathBinaryDigestMatch(
        hasher, [u'empty_file'], empty_file_sha256.decode('hex'))

    unicode_file_sha256 = u'a9c0220b1dadd1812fc4bbe137f495d2c3b88c7b33b5a4de5' \
                          u'45d201fd31b3bc0'
    hasher = sha256.SHA256Hasher()
    self._AssertTestPathStringDigestMatch(
        hasher, [u'ímynd.dd'], unicode_file_sha256)
    hasher = sha256.SHA256Hasher()
    self._AssertTestPathBinaryDigestMatch(
        hasher, [u'ímynd.dd'], unicode_file_sha256.decode('hex'))

if __name__ == '__main__':
  unittest.main()


text:
<assembly>
	<id>sdk</id>
	<formats>
		<format>zip</format>
		<format>tar.gz</format>
	</formats>
	<includeBaseDirectory>false</includeBaseDirectory>
	<dependencySets>
		<dependencySet>
			<outputDirectory>role-${project.version}-sdk</outputDirectory>
			<outputFileNameMapping>webapps/${artifact.artifactId}.${artifact.extension}
			</outputFileNameMapping>
			<!--<outputFileNameMapping>webapps/${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension}
				</outputFileNameMapping> -->
			<useTransitiveDependencies>false</useTransitiveDependencies>
			<includes>
				<include>org.eclipse.jetty:jetty-runner</include>
			</includes>
		</dependencySet>
		<dependencySet>
			<outputDirectory>role-${project.version}-sdk/webapps/role-uu-prototype</outputDirectory>
			<useTransitiveDependencies>false</useTransitiveDependencies>
			<includes>
				<include>eu.role-project:role-uu-prototype</include>
			</includes>
			<unpack>true</unpack>
		</dependencySet>
	</dependencySets>
	<fileSets>
		<!-- Includes for SDK home directory -->

		<!-- include README -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk</outputDirectory>
			<directory>${basedir}/src/main/webapp</directory>
			<includes>
				<include>README</include>
				<include>CHANGELOG</include>
			</includes>
		</fileSet>

		<!-- Includes for SDK bin directory -->

		<!-- include start scripts for local development server -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/bin</outputDirectory>
			<directory>${basedir}/src/main/webapp/webapps</directory>
			<includes>
				<include>start.cmd</include>
				<include>start.sh</include>
			</includes>
		</fileSet>

		<!-- Includes for SDK doc directory -->

		<!-- Include API docs for ROLE libraries generated with JSDoc (see trunk/assembly/pom.xml
			for integrating further libraries into automatic JSDoc generation -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/doc</outputDirectory>
			<directory>${project.build.directory}/doc</directory>
			<includes>
				<include>**/*</include>
			</includes>
		</fileSet>

		<!-- Includes for SDK lib directory -->

		<!-- Include compiled OpenApp library files (openapp must have been built
			first) -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/lib/openapp
			</outputDirectory>
			<directory>../libraries/openapp/target/classes</directory>
			<includes>
				<include>**/*.js</include>
			</includes>
		</fileSet>

		<!-- Include compiled IWC library files (iwc must have been built first) -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/lib/iwc
			</outputDirectory>
			<directory>../libraries/iwc/target/classes</directory>
			<includes>
				<include>**/*.js</include>
			</includes>
		</fileSet>

		<!-- Includes for SDK src directory -->

		<!-- Include sample gadgets showing instructional or reference implementations
			for ROLE software components -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/src/gadget/samples
			</outputDirectory>
			<directory>../gadgets/widgetSamples</directory>
			<includes>
				<include>**/*</include>
			</includes>
		</fileSet>

		<!-- Include developer gadgets supporting the development of ROLE technology-enabled widgets -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/src/gadget/development
			</outputDirectory>
			<directory>../gadgets/development</directory>
			<includes>
				<include>**/*</include>
			</includes>
		</fileSet>

		<!-- ROLE IWC Test Stub Widget -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/src/gadget/development</outputDirectory>
			<directory>../gadgets/iwc</directory>
			<includes>
				<include>iwc-teststub.xml</include>
			</includes>
		</fileSet>

		<!-- Test SDK Services Widget -->
		<fileSet>
			<outputDirectory>role-${project.version}-sdk/src/gadget/development
			</outputDirectory>
			<directory>../gadgets/development</directory>
			<includes>
				<include>testservices.xml</include>
			</includes>
		</fileSet>

		<!-- Includes for SDK webapps directory -->

	</fileSets>

	<!-- Include development server start page -->
	<!-- Add filtering to files where version number etc. need be added -->
	<files>
		<file>
			<source>${basedir}/src/main/webapp/VERSION</source>
			<outputDirectory>role-${project.version}-sdk</outputDirectory>
			<filtered>true</filtered>
		</file>
		<file>
			<source>${basedir}/src/main/webapp/index.html</source>
			<outputDirectory>role-${project.version}-sdk</outputDirectory>
			<filtered>true</filtered>
		</file>
		<file>
			<source>${basedir}/src/main/webapp/doc/gadget/samples/index.html</source>
			<outputDirectory>role-${project.version}-sdk/src/gadget/samples</outputDirectory>
			<filtered>true</filtered>
		</file>
		<file>
			<source>${basedir}/src/main/webapp/doc/gadget/development/index.html</source>
			<outputDirectory>role-${project.version}-sdk/src/gadget/development</outputDirectory>
			<filtered>true</filtered>
		</file>
	</files>

</assembly>


text:
As práticas de BDD incluem:

 - Envolver as partes interessadas no processo através de Outside-in Development (Desenvolvimento de Fora pra Dentro)
 - Usar exemplos para descrever o comportamento de uma aplicação ou unidades de código
 - Automatizar os exemplos para prover um feedback rápido e testes de regressão
 - Usar deve (should em inglês) na hora de descrever o comportamento de software para ajudar esclarecer responsabilidades e permitir que funcionalidades do software sejam questionadas
 - Usar simuladores de teste (mocks, stubs, fakes, dummies, spies) para auxiliar na colaboração entre módulos e códigos que ainda não foram escritos


text:
<!DOCTYPE html>

<TITLE>Manpage of VOID</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

VOID

Section: Devices and Network Interfaces (4)
Updated: xf86-input-void 1.4.0
Index
Return to Main Contents

NAME

void - null input driver

SYNOPSIS

Section N'34'InputDeviceN'34'
  Identifier N'34'idevnameN'34'
  Driver N'34'voidN'34'
  ...
EndSection

DESCRIPTION

void

is an dummy/null Xorg input driver.  It doesn't connect to any
physical device, and it never delivers any events.  It functions as
both a pointer and keyboard device, and may be used as X server's core
pointer and/or core keyboard.  It's purpose is to allow X servers pre
version 1.4 to operate without a core pointer and/or core keyboard.

CONFIGURATION DETAILS

Please refer to xorg.conf(5) for general configuration
details and for options that can be used with all input drivers.  This
driver doesn't have any configuration options in addition to those.

SEE ALSO

Xorg(1), xorg.conf(5), Xserver(1), X(7).

Index

NAME

SYNOPSIS

DESCRIPTION

CONFIGURATION DETAILS

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:33:54 GMT, December 24, 2015


text:
<?php
/**
 * Created by PhpStorm.
 * User: yourfather
 * Date: 2015/6/16
 * Time: 21:27
 */
namespace Blog\Model;

class Article{

    protected $id;

    protected $title;

    protected $content;

    protected $category;

    protected $author;

    protected $update_time;

    protected $create_time;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param mixed $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return mixed
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * @param mixed $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * @return mixed
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param mixed $category
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }

    /**
     * @return mixed
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * @param mixed $author
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * @return mixed
     */
    public function getUpdateTime()
    {
        return $this->update_time;
    }

    /**
     * @param mixed $update_time
     */
    public function setUpdateTime($update_time)
    {
        $this->update_time = $update_time;
    }

    /**
     * @return mixed
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    /**
     * @param mixed $create_time
     */
    public function setCreateTime($create_time)
    {
        $this->create_time = $create_time;
    }

    public function exchangeArray($data){
        $this->id = (!empty($data['id'])) ? $data['id'] : null;
        $this->title = (!empty($data['title'])) ? $data['title'] : null;
        $this->content = (!empty($data['content'])) ? $data['content'] : null;
        $this->category = (!empty($data['category'])) ? $data['category'] : null;
        $this->author = (!empty($data['author'])) ? $data['author'] : null;
        $this->update_time = (!empty($data['update_time'])) ? $data['update_time'] : null;
        $this->create_time = (!empty($data['create_time'])) ? $data['create_time'] : null;
    }

}


text:
namespace device {

namespace {

constexpr size_t kUsbReportLength = 32;
constexpr size_t kBluetoothReportLength = 78;

constexpr uint8_t kUsbStopVibration[] = {
    0x05,  // report ID
    0x01, 0x00, 0x00,
    0x00,  // weak magnitude
    0x00,  // strong magnitude
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static_assert(sizeof(kUsbStopVibration) == kUsbReportLength,
              "kUsbStopVibration has incorrect size");

constexpr uint8_t kUsbStartVibration[] = {
    0x05,  // report ID
    0x01, 0x00, 0x00,
    0x7f,  // weak magnitude
    0xff,  // strong magnitude
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static_assert(sizeof(kUsbStartVibration) == kUsbReportLength,
              "kUsbStartVibration has incorrect size");

constexpr uint8_t kBtStopVibration[] = {
    0x11,  // report ID
    0xc0, 0x20, 0xf1, 0x04, 0x00,
    0x00,  // weak magnitude
    0x00,  // strong magnitude
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x43, 0x43, 0x00, 0x4d, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // CRC32
    0x30, 0x50, 0xad, 0x07};
static_assert(sizeof(kBtStopVibration) == kBluetoothReportLength,
              "kBtStopVibration has incorrect size");

constexpr uint8_t kBtStartVibration[] = {
    0x11,  // report ID
    0xc0, 0x20, 0xf1, 0x04, 0x00,
    0x7f,  // weak magnitude
    0xff,  // strong magnitude
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x43, 0x43, 0x00, 0x4d, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // CRC32
    0xf7, 0x4e, 0xbe, 0x5a};
static_assert(sizeof(kBtStartVibration) == kBluetoothReportLength,
              "kBtStartVibration has incorrect size");

// Use 1 ms for all non-zero effect durations. There is no reason to test longer
// delays as they will be skipped anyway.
constexpr double kDurationMillis = 1.0;
// Setting |start_delay| to zero can cause additional reports to be sent.
constexpr double kZeroStartDelayMillis = 0.0;
// Vibration magnitudes for the strong and weak channels of a typical
// dual-rumble vibration effect. kStartVibrationData describes a report with
// these magnitudes.
constexpr double kStrongMagnitude = 1.0;  // 100% intensity
constexpr double kWeakMagnitude = 0.5;    // 50% intensity

constexpr base::TimeDelta kPendingTaskDuration =
    base::TimeDelta::FromMillisecondsD(kDurationMillis);

class FakeHidWriter : public HidWriter {
 public:
  FakeHidWriter() = default;
  ~FakeHidWriter() override = default;

  // HidWriter implementation.
  size_t WriteOutputReport(base::span<const uint8_t> report) override {
    output_reports.emplace_back(report.begin(), report.end());
    return report.size_bytes();
  }

  std::vector<std::vector<uint8_t>> output_reports;
};

// Main test fixture
class Dualshock4ControllerTest : public testing::Test {
 public:
  Dualshock4ControllerTest()
      : usb_start_vibration_report_(kUsbStartVibration,
                                    kUsbStartVibration + kUsbReportLength),
        usb_stop_vibration_report_(kUsbStopVibration,
                                   kUsbStopVibration + kUsbReportLength),
        bluetooth_start_vibration_report_(
            kBtStartVibration,
            kBtStartVibration + kBluetoothReportLength),
        bluetooth_stop_vibration_report_(
            kBtStopVibration,
            kBtStopVibration + kBluetoothReportLength),
        callback_count_(0),
        callback_result_(
            mojom::GamepadHapticsResult::GamepadHapticsResultError) {
    // Create two Dualshock4Controller instances, one configured for USB and one
    // for Bluetooth.
    auto usb_writer = std::make_unique<FakeHidWriter>();
    usb_writer_ = usb_writer.get();
    ds4_usb_ = std::make_unique<Dualshock4Controller>(
        GamepadId::kSonyProduct05c4, GAMEPAD_BUS_USB, std::move(usb_writer));

    auto bluetooth_writer = std::make_unique<FakeHidWriter>();
    bluetooth_writer_ = bluetooth_writer.get();
    ds4_bluetooth_ = std::make_unique<Dualshock4Controller>(
        GamepadId::kSonyProduct05c4, GAMEPAD_BUS_BLUETOOTH,
        std::move(bluetooth_writer));
  }

  void TearDown() override {
    ds4_usb_->Shutdown();
    ds4_bluetooth_->Shutdown();
  }

  void PostPlayEffect(
      Dualshock4Controller* gamepad,
      double start_delay,
      double strong_magnitude,
      double weak_magnitude,
      mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback) {
    gamepad->PlayEffect(
        mojom::GamepadHapticEffectType::GamepadHapticEffectTypeDualRumble,
        mojom::GamepadEffectParameters::New(kDurationMillis, start_delay,
                                            strong_magnitude, weak_magnitude),
        std::move(callback), base::ThreadTaskRunnerHandle::Get());
  }

  void PostResetVibration(
      Dualshock4Controller* gamepad,
      mojom::GamepadHapticsManager::ResetVibrationActuatorCallback callback) {
    gamepad->ResetVibration(std::move(callback),
                            base::ThreadTaskRunnerHandle::Get());
  }

  // Callback for PlayEffect or ResetVibration.
  void Callback(mojom::GamepadHapticsResult result) {
    callback_count_++;
    callback_result_ = result;
  }

  const std::vector<uint8_t> usb_start_vibration_report_;
  const std::vector<uint8_t> usb_stop_vibration_report_;
  const std::vector<uint8_t> bluetooth_start_vibration_report_;
  const std::vector<uint8_t> bluetooth_stop_vibration_report_;
  int callback_count_;
  mojom::GamepadHapticsResult callback_result_;
  FakeHidWriter* usb_writer_;
  FakeHidWriter* bluetooth_writer_;
  std::unique_ptr<Dualshock4Controller> ds4_usb_;
  std::unique_ptr<Dualshock4Controller> ds4_bluetooth_;
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  DISALLOW_COPY_AND_ASSIGN(Dualshock4ControllerTest);
};

TEST_F(Dualshock4ControllerTest, PlayEffectUsb) {
  EXPECT_TRUE(usb_writer_->output_reports.empty());
  EXPECT_EQ(0, callback_count_);

  PostPlayEffect(ds4_usb_.get(), kZeroStartDelayMillis, kStrongMagnitude,
                 kWeakMagnitude,
                 base::BindOnce(&Dualshock4ControllerTest::Callback,
                                base::Unretained(this)));

  // Run the queued task and start vibration.
  task_environment_.RunUntilIdle();

  EXPECT_THAT(usb_writer_->output_reports,
              testing::ElementsAre(usb_start_vibration_report_));
  EXPECT_EQ(0, callback_count_);
  EXPECT_GT(task_environment_.GetPendingMainThreadTaskCount(), 0u);

  // Finish the effect.
  task_environment_.FastForwardBy(kPendingTaskDuration);

  EXPECT_THAT(usb_writer_->output_reports,
              testing::ElementsAre(usb_start_vibration_report_));
  EXPECT_EQ(1, callback_count_);
  EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete,
            callback_result_);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
}

TEST_F(Dualshock4ControllerTest, PlayEffectBluetooth) {
  EXPECT_TRUE(bluetooth_writer_->output_reports.empty());
  EXPECT_EQ(0, callback_count_);

  PostPlayEffect(ds4_bluetooth_.get(), kZeroStartDelayMillis, kStrongMagnitude,
                 kWeakMagnitude,
                 base::BindOnce(&Dualshock4ControllerTest::Callback,
                                base::Unretained(this)));

  // Run the queued task and start vibration.
  task_environment_.RunUntilIdle();

  EXPECT_THAT(bluetooth_writer_->output_reports,
              testing::ElementsAre(bluetooth_start_vibration_report_));
  EXPECT_EQ(0, callback_count_);
  EXPECT_GT(task_environment_.GetPendingMainThreadTaskCount(), 0u);

  // Finish the effect.
  task_environment_.FastForwardBy(kPendingTaskDuration);

  EXPECT_THAT(bluetooth_writer_->output_reports,
              testing::ElementsAre(bluetooth_start_vibration_report_));
  EXPECT_EQ(1, callback_count_);
  EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete,
            callback_result_);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
}

TEST_F(Dualshock4ControllerTest, ResetVibrationUsb) {
  EXPECT_TRUE(usb_writer_->output_reports.empty());
  EXPECT_EQ(0, callback_count_);

  PostResetVibration(ds4_usb_.get(),
                     base::BindOnce(&Dualshock4ControllerTest::Callback,
                                    base::Unretained(this)));

  // Run the queued task and reset vibration.
  task_environment_.RunUntilIdle();

  EXPECT_THAT(usb_writer_->output_reports,
              testing::ElementsAre(usb_stop_vibration_report_));
  EXPECT_EQ(1, callback_count_);
  EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete,
            callback_result_);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
}

TEST_F(Dualshock4ControllerTest, ResetVibrationBluetooth) {
  EXPECT_TRUE(bluetooth_writer_->output_reports.empty());
  EXPECT_EQ(0, callback_count_);

  PostResetVibration(ds4_bluetooth_.get(),
                     base::BindOnce(&Dualshock4ControllerTest::Callback,
                                    base::Unretained(this)));

  // Run the queued task and reset vibration.
  task_environment_.RunUntilIdle();

  EXPECT_THAT(bluetooth_writer_->output_reports,
              testing::ElementsAre(bluetooth_stop_vibration_report_));
  EXPECT_EQ(1, callback_count_);
  EXPECT_EQ(mojom::GamepadHapticsResult::GamepadHapticsResultComplete,
            callback_result_);
  EXPECT_EQ(task_environment_.GetPendingMainThreadTaskCount(), 0u);
}

}  // namespace

}  // namespace device


text:
namespace WingEngine
{

	class WING_ENGINE_API RendererSystem :public WingCore::Singleton<RendererSystem>
	{
		friend class WingCore::Singleton<RendererSystem>;

	public:
		~RendererSystem();

		bool				create(void* windowHandle, uint32 width, uint32 height);
		void				destroy();

		void				sort();
		void				render();

		void				addRenderable(SmartPtr<Renderable> able);

		SmartPtr<RenderPass>getRenderPass(std::string name);

		SmartPtr<Camera>	getCamera() { return mCamera; }

		RendererContext*	getRendererContext() { return mRendererContext; }

		uint32				getWidth() { return mWidth; }
		uint32				getHeight() { return mHeight; }

		void				enableShadow(bool enable) { mIsShadow = enable; }
		bool				getEnableShadow() { return mIsShadow; }

		void				enableLight(bool enable) { mIsLight = enable; }
		bool				getEnableLight() { return mIsLight; }

		SmartPtr<Program>	createProgram(std::string name,std::string verFileName, std::string fraFileName);
		void				addProgram(std::string name, SmartPtr<Program> program);
		void				useProgram(std::string name);
		SmartPtr<Program>	getProgram(std::string name);

		int8				getLightsData(int32* type,real* postion,real* direction,real* color,real* shiness);
		SmartPtr<Light>		getLight(uint8 index);
		SmartPtr<Light>		getLight(std::string name);
		void				addLight(std::string name, SmartPtr<Light> light);

	private:
		RendererSystem();

		void				realRender();
	private:
		bool											mCreate;
		bool											mIsShadow;
		bool											mIsLight;

		SmartPtr<Camera>								mCamera;

		std::string										mRendererName;
		RendererContext*								mRendererContext;
		std::map<std::string, RendererContext*>			mRendererContexts;

		SmartPtr<RenderPass>							mCurrRenderPass;
		std::map<std::string, SmartPtr<RenderPass>>		mRenderPass;

		uint32											mWidth;
		uint32											mHeight;

		std::list<SmartPtr<Renderable>>					mRenderables;

		std::map<std::string,SmartPtr<Program>>			mPrograms;
		SmartPtr<Program>								mCurrProgram;

		std::map<std::string, SmartPtr<Light>>			mLights;
	};
}

#endif


text:
<!DOCTYPE html>

		<title>loth FPS</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=11,chrome=1">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

		<canvas id="map" width="256" height="256"></canvas>


text:
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Security;
using System.Threading;
using System.Threading.Tasks;

namespace System.IO.Pipes
{
    public abstract partial class PipeStream : Stream
    {
        // The Windows implementation of PipeStream sets the stream's handle during
        // creation, and as such should always have a handle, but the Unix implementation
        // sometimes sets the handle not during creation but later during connection.
        // As such, validation during member access needs to verify a valid handle on
        // Windows, but can't assume a valid handle on Unix.
        internal const bool CheckOperationsRequiresSetHandle = false;

        internal static string GetPipePath(string serverName, string pipeName)
        {
            if (serverName != "." && serverName != Interop.Sys.GetHostName())
            {
                // Cross-machine pipes are not supported.
                throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
            }

            if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
            {
                // Match Windows constraint
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }

            if (pipeName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                // Since pipes are stored as files in the file system, we don't support
                // pipe names that are actually paths or that otherwise have invalid
                // filename characters in them.
                throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars);
            }

            // Return the pipe path
            return Path.Combine(EnsurePipeDirectoryPath(), pipeName);
        }

        /// Throws an exception if the supplied handle does not represent a valid pipe.
        /// <param name="safePipeHandle">The handle to validate.</param>
        internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
        {
            if (safePipeHandle.NamedPipeSocket == null)
            {
                Interop.Sys.FileStatus status;
                int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
                if (result == 0)
                {
                    if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
                        (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
                    {
                        throw new IOException(SR.IO_InvalidPipeHandle);
                    }
                }
            }
        }

        /// Initializes the handle to be used asynchronously.
        /// <param name="handle">The handle.</param>
        [SecurityCritical]
        private void InitializeAsyncHandle(SafePipeHandle handle)
        {
            // nop
        }

        private void UninitializeAsyncHandle()
        {
            // nop
        }

        private unsafe int ReadCore(byte[] buffer, int offset, int count)
        {
            DebugAssertReadWriteArgs(buffer, offset, count, _handle);

            // For named pipes, receive on the socket.
            Socket socket = _handle.NamedPipeSocket;
            if (socket != null)
            {
                // For a blocking socket, we could simply use the same Read syscall as is done
                // for reading an anonymous pipe.  However, for a non-blocking socket, Read could
                // end up returning EWOULDBLOCK rather than blocking waiting for data.  Such a case
                // is already handled by Socket.Receive, so we use it here.
                try
                {
                    return socket.Receive(buffer, offset, count, SocketFlags.None);
                }
                catch (SocketException e)
                {
                    throw GetIOExceptionForSocketException(e);
                }
            }

            // For anonymous pipes, read from the file descriptor.
            fixed (byte* bufPtr = buffer)
            {
                int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count));
                Debug.Assert(result <= count);

                return result;
            }
        }

        private unsafe void WriteCore(byte[] buffer, int offset, int count)
        {
            DebugAssertReadWriteArgs(buffer, offset, count, _handle);

            // For named pipes, send to the socket.
            Socket socket = _handle.NamedPipeSocket;
            if (socket != null)
            {
                // For a blocking socket, we could simply use the same Write syscall as is done
                // for writing to anonymous pipe.  However, for a non-blocking socket, Write could
                // end up returning EWOULDBLOCK rather than blocking waiting for space available.
                // Such a case is already handled by Socket.Send, so we use it here.
                try
                {
                    while (count > 0)
                    {
                        int bytesWritten = socket.Send(buffer, offset, count, SocketFlags.None);
                        Debug.Assert(bytesWritten <= count);

                        count -= bytesWritten;
                        offset += bytesWritten;
                    }
                }
                catch (SocketException e)
                {
                    throw GetIOExceptionForSocketException(e);
                }
            }

            // For anonymous pipes, write the file descriptor.
            fixed (byte* bufPtr = buffer)
            {
                while (count > 0)
                {
                    int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr + offset, count));
                    Debug.Assert(bytesWritten <= count);

                    count -= bytesWritten;
                    offset += bytesWritten;
                }
            }
        }

        private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");

            Socket socket = InternalHandle.NamedPipeSocket;

            // If a cancelable token is used, we have a choice: we can either ignore it and use a true async operation
            // with Socket.ReceiveAsync, or we can use a polling loop on a worker thread to block for short intervals
            // and check for cancellation in between.  We do the latter.
            if (cancellationToken.CanBeCanceled)
            {
                await Task.CompletedTask.ForceAsync(); // queue the remainder of the work to avoid blocking the caller
                int timeout = 10000;
                const int MaxTimeoutMicroseconds = 500000;
                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (socket.Poll(timeout, SelectMode.SelectRead))
                    {
                        return ReadCore(buffer, offset, count);
                    }
                    timeout = Math.Min(timeout * 2, MaxTimeoutMicroseconds);
                }
            }

            // The token wasn't cancelable, so we can simply use an async receive on the socket.
            try
            {
                return await socket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
            }
            catch (SocketException e)
            {
                throw GetIOExceptionForSocketException(e);
            }
        }

        private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
            try
            {
                while (count > 0)
                {
                    // cancellationToken is (mostly) ignored.  We could institute a polling loop like we do for reads if
                    // cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and
                    // most writes will complete immediately as they simply store data into the socket's buffer.  The only time we end
                    // up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation.
                    cancellationToken.ThrowIfCancellationRequested();

                    int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
                    Debug.Assert(bytesWritten <= count);

                    count -= bytesWritten;
                    offset += bytesWritten;
                }
            }
            catch (SocketException e)
            {
                throw GetIOExceptionForSocketException(e);
            }
        }

        private IOException GetIOExceptionForSocketException(SocketException e)
        {
            if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
            {
                State = PipeState.Broken;
            }
            return new IOException(e.Message, e);
        }

        // Blocks until the other end of the pipe has read in all written buffer.
        [SecurityCritical]
        public void WaitForPipeDrain()
        {
            CheckWriteOperations();
            if (!CanWrite)
            {
                throw Error.GetWriteNotSupported();
            }

            // For named pipes on sockets, we could potentially partially implement this
            // via ioctl and TIOCOUTQ, which provides the number of unsent bytes.  However,
            // that would require polling, and it wouldn't actually mean that the other
            // end has read all of the data, just that the data has left this end's buffer.
            throw new PlatformNotSupportedException();
        }

        // Gets the transmission mode for the pipe.  This is virtual so that subclassing types can
        // override this in cases where only one mode is legal (such as anonymous pipes)
        public virtual PipeTransmissionMode TransmissionMode
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            get
            {
                CheckPipePropertyOperations();
                return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
            }
        }

        // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
        // access. If that passes, call to GetNamedPipeInfo will succeed.
        public virtual int InBufferSize
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
            get
            {
                CheckPipePropertyOperations();
                if (!CanRead)
                {
                    throw new NotSupportedException(SR.NotSupported_UnreadableStream);
                }
                return GetPipeBufferSize();
            }
        }

        // Gets the buffer size in the outbound direction for the pipe. This uses cached version
        // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
        // However, returning cached is good fallback, especially if user specified a value in
        // the ctor.
        public virtual int OutBufferSize
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            get
            {
                CheckPipePropertyOperations();
                if (!CanWrite)
                {
                    throw new NotSupportedException(SR.NotSupported_UnwritableStream);
                }
                return GetPipeBufferSize();
            }
        }

        public virtual PipeTransmissionMode ReadMode
        {
            [SecurityCritical]
            get
            {
                CheckPipePropertyOperations();
                return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
            }
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            set
            {
                CheckPipePropertyOperations();
                if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
                }

                if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
                {
                    throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
                }

                // nop, since it's already the only valid value
            }
        }

        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private static string s_pipeDirectoryPath;

        ///
        /// We want to ensure that only one asynchronous operation is actually in flight
        /// at a time. The base Stream class ensures this by serializing execution via a
        /// semaphore.  Since we don't delegate to the base stream for Read/WriteAsync due
        /// to having specialized support for cancellation, we do the same serialization here.
        ///
        private SemaphoreSlim _asyncActiveSemaphore;

        private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
        {
            return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
        }

        private static string EnsurePipeDirectoryPath()
        {
            const string PipesFeatureName = "pipe";

            // Ideally this would simply use PersistedFiles.GetTempFeatureDirectory(PipesFeatureName) and then
            // Directory.CreateDirectory to ensure it exists.  But this assembly doesn't reference System.IO.FileSystem.
            // As such, we'd be calling GetTempFeatureDirectory, only to then need to parse it in order
            // to create each of the individual directories as part of the path.  We instead access the named portions
            // of the path directly and do the building of the path and directory structure manually.

            // First ensure we know what the full path should be, e.g. /tmp/.dotnet/corefx/pipe/
            string fullPath = s_pipeDirectoryPath;
            string tempPath = null;
            if (fullPath == null)
            {
                tempPath = Path.GetTempPath();
                fullPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory, PersistedFiles.SecondLevelDirectory, PipesFeatureName);
                s_pipeDirectoryPath = fullPath;
            }

            // Then create the directory if it doesn't already exist.  If we get any error back from stat,
            // just proceed to build up the directory, failing in the CreateDirectory calls if there's some
            // problem.  Similarly, it's possible stat succeeds but the path is a file rather than directory; we'll
            // call that success for now and let this fail later when the code tries to create a file in this "directory"
            // (we don't want to overwrite/delete whatever that unknown file may be, and this is similar to other cases
            // we can't control where the file system is manipulated concurrently with and separately from this code).
            Interop.Sys.FileStatus ignored;
            bool pathExists = Interop.Sys.Stat(fullPath, out ignored) == 0;
            if (!pathExists)
            {
                // We need to build up the directory manually.  Ensure we have the temp directory in which
                // we'll create the structure, e.g. /tmp/
                if (tempPath == null)
                {
                    tempPath = Path.GetTempPath();
                }
                Debug.Assert(Interop.Sys.Stat(tempPath, out ignored) == 0, "Path.GetTempPath() directory could not be accessed");

                // Create /tmp/.dotnet/ if it doesn't exist.
                string partialPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory);
                CreateDirectory(partialPath);

                // Create /tmp/.dotnet/corefx/ if it doesn't exist
                partialPath = Path.Combine(partialPath, PersistedFiles.SecondLevelDirectory);
                CreateDirectory(partialPath);

                // Create /tmp/.dotnet/corefx/pipe/ if it doesn't exist
                CreateDirectory(fullPath);
            }

            return fullPath;
        }

        private static void CreateDirectory(string directoryPath)
        {
            int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.S_IRWXU);

            // If successful created, we're done.
            if (result >= 0)
                return;

            // If the directory already exists, consider it a success.
            Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
            if (errorInfo.Error == Interop.Error.EEXIST)
                return;

            // Otherwise, fail.
            throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
        }

        /// Creates an anonymous pipe.
        /// <param name="inheritability">The inheritability to try to use.  This may not always be honored, depending on platform.</param>
        /// <param name="reader">The resulting reader end of the pipe.</param>
        /// <param name="writer">The resulting writer end of the pipe.</param>
        internal static unsafe void CreateAnonymousPipe(
            HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
        {
            // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
            reader = new SafePipeHandle();
            writer = new SafePipeHandle();

            // Create the OS pipe
            int* fds = stackalloc int[2];
            CreateAnonymousPipe(inheritability, fds);

            // Store the file descriptors into our safe handles
            reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
            writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
        }

        internal int CheckPipeCall(int result)
        {
            if (result == -1)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();

                if (errorInfo.Error == Interop.Error.EPIPE)
                    State = PipeState.Broken;

                throw Interop.GetExceptionForIoErrno(errorInfo);
            }

            return result;
        }

        private int GetPipeBufferSize()
        {
            if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
            {
                throw new PlatformNotSupportedException();
            }

            // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
            // If we don't, just return the buffer size that was passed to the constructor.
            return _handle != null ?
                CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
                _outBufferSize;
        }

        internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
        {
            var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
                Interop.Sys.PipeFlags.O_CLOEXEC : 0;
            Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags));
        }

        internal static void ConfigureSocket(
            Socket s, SafePipeHandle pipeHandle,
            PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
        {
            if (inBufferSize > 0)
            {
                s.ReceiveBufferSize = inBufferSize;
            }

            if (outBufferSize > 0)
            {
                s.SendBufferSize = outBufferSize;
            }

            if (inheritability != HandleInheritability.Inheritable)
            {
                Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt
            }

            switch (direction)
            {
                case PipeDirection.In:
                    s.Shutdown(SocketShutdown.Send);
                    break;
                case PipeDirection.Out:
                    s.Shutdown(SocketShutdown.Receive);
                    break;
            }
        }
    }
}


text:
package com.vip.saturn.job.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;

/**
 * 分片项工具类.
 *
 *
 */
public final class ItemUtils {

	private static final String DELIMITER = ",";

	/**
	 * 根据分片项字符串获取分片项列表.
	 *
	 * @param itemsString 分片项字符串
	 * @return 分片项列表
	 */
	public static List<Integer> toItemList(final String itemsString) {
		if (Strings.isNullOrEmpty(itemsString)) {
			return Collections.emptyList();
		}
		String[] items = itemsString.split(DELIMITER);
		List<Integer> result = new ArrayList<>(items.length);
		for (String each : items) {
			int item = Integer.parseInt(each);
			if (!result.contains(item)) {
				result.add(item);
			}
		}
		return result;
	}

	/**
	 * 根据分片项列表获取分片项字符串.
	 *
	 * @param items 分片项列表
	 * @return 分片项字符串
	 */
	public static String toItemsString(final List<Integer> items) {
		return items.isEmpty() ? "" : Joiner.on(ItemUtils.DELIMITER).join(items);
	}
}


text:
'use strict'

var chai = require('chai')
var expect = chai.expect

var GithubEventFactory = require('../../../lib/github_events/factory')
var GithubEventNotImplementedError = require('../../../lib/github_events/errors')
var GithubEventNotValidError = require('../../../lib/github_events/errors')
var GithubPushEvent = require('../../../lib/github_events/push')

describe ('GithubEventFactory', () => {
    var id
    var payload

    before (() => {
        id = 'my_id'
        payload = {
            repository : { full_name : 'test name' },
            organization : { login : 'test org' },
            sender : { login : 'test user' },
            before : 'before hash',
            after : 'after hash',
            ref : 'my branch',
            pusher : { email : 'test email' },
        }
    })

    it ('should return a GithubPushEvent for event of type push', () => {
        try {
            var event = GithubEventFactory.createEvent (id, 'push', payload)
            expect (event).to.be.an.instanceOf (GithubPushEvent)
        } catch (err) {
            expect (true).to.be.false  // fail
        }
    })

    it ('should throw a GithubEventNotImplementedError for gollum event', () => {
        try {
            var event = GithubEventFactory.createEvent (id, 'gollum', payload)
            expect (true).to.be.false  // fail
        } catch (err) {
            expect (err).to.be.an.instanceOf (GithubEventNotImplementedError)
            expect (err.message).to.equal ('gollum')
        }
    })

    it ('should throw a GithubEventNotValidError for made up event', () => {
        try {
            var event = GithubEventFactory.createEvent (id, 'made up', payload)
            expect (true).to.be.false  // fail
        } catch (err) {
            expect (err).to.be.an.instanceOf (GithubEventNotValidError)
            expect (err.message).to.equal ('made up')
        }
    })
})


text:
<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <gradient
            android:startColor="@color/b1"
            android:centerColor="@color/b2"
            android:endColor="@color/b3"
            android:angle="270"
         />

</shape>


text:
set -e -x

if [ -z `getent group admin` ]; then
  groupadd -r admin
fi
usermod -a -G admin root

sed -i -e '/Defaults\s\+env_reset/a Defaults\texempt_group=admin' /etc/sudoers
sed -i -e 's/%admin ALL=(ALL) ALL/%admin ALL=NOPASSWD:ALL/g' /etc/sudoers


text:
class TimeSeriesCanvas
{
protected:
	struct TimeSeriesInternalData* m_internalData;
	void shift1PixelToLeft();

public:
	TimeSeriesCanvas(struct Common2dCanvasInterface* canvasInterface, int width, int height, const char* windowTitle);
	virtual ~TimeSeriesCanvas();

	void setupTimeSeries(float yScale, int ticksPerSecond, int startTime, bool clearCanvas = true);
	void addDataSource(const char* dataSourceLabel, unsigned char red, unsigned char green, unsigned char blue);
	void insertDataAtCurrentTime(float value, int dataSourceIndex, bool connectToPrevious);
	float getCurrentTime() const;
	void grapicalPrintf(const char* str, void* fontData, int rasterposx, int rasterposy, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha);

	virtual void nextTick();
};

#endif  //TIME_SERIES_CANVAS_H


text:
using System.Linq;
using System.Threading.Tasks;
using Mollie.Api.Models.List;
using Mollie.Api.Models.Payment;
using Mollie.Api.Models.PaymentMethod;
using Mollie.Tests.Integration.Framework;
using NUnit.Framework;

namespace Mollie.Tests.Integration.Api {
    [TestFixture]
    public class PaymentMethodTests : BaseMollieApiTestClass {

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrievePaymentMethodList() {
            // When: Retrieve payment list with default settings
            ListResponse<PaymentMethodResponse> response = await this._paymentMethodClient.GetPaymentMethodListAsync();

            // Then: Make sure it can be retrieved
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Items);
        }

        [TestCase(PaymentMethod.Bancontact)]
        [TestCase(PaymentMethod.Sofort)]
        [TestCase(PaymentMethod.BankTransfer)]
        [TestCase(PaymentMethod.Belfius)]
        [TestCase(PaymentMethod.PayPal)]
        [TestCase(PaymentMethod.Kbc)]
        public async Task CanRetrieveSinglePaymentMethod(string method) {
            // When: retrieving a payment method
            PaymentMethodResponse paymentMethod = await this._paymentMethodClient.GetPaymentMethodAsync(method);

            // Then: Make sure it can be retrieved
            Assert.IsNotNull(paymentMethod);
            Assert.IsNotNull(paymentMethod.Id);
            Assert.AreEqual(method, paymentMethod.Id);
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrieveKbcIssuers() {
            // When: retrieving the ideal method we can include the issuers
            PaymentMethodResponse paymentMethod = await this._paymentMethodClient.GetPaymentMethodAsync(PaymentMethod.Kbc, true);

            // Then: We should have one or multiple issuers
            Assert.IsNotNull(paymentMethod);
            Assert.IsTrue(paymentMethod.Issuers.Any());
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task DoNotRetrieveIssuersWhenIncludeIsFalse() {
            // When: retrieving the ideal method with the include parameter set to false
            PaymentMethodResponse paymentMethod = await this._paymentMethodClient.GetPaymentMethodAsync(PaymentMethod.Kbc, false);

            // Then: Issuers should not be included
            Assert.IsNull(paymentMethod.Issuers);
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrievePricing() {
            // When: retrieving the ideal method we can include the issuers
            PaymentMethodResponse paymentMethod = await this._paymentMethodClient.GetPaymentMethodAsync(PaymentMethod.CreditCard, includePricing: true);

            // Then: We should have one or multiple issuers
            Assert.IsNotNull(paymentMethod);
            Assert.IsTrue(paymentMethod.Pricing.Any());
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task DoNotRetrievePricingWhenIncludeIsFalse() {
            // When: retrieving the ideal method with the include parameter set to false
            PaymentMethodResponse paymentMethod = await this._paymentMethodClient.GetPaymentMethodAsync(PaymentMethod.CreditCard, includePricing: false);

            // Then: Issuers should not be included
            Assert.IsNull(paymentMethod.Pricing);
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrieveAllMethods() {
            // When: retrieving the all mollie payment methods
            ListResponse<PaymentMethodResponse> paymentMethods = await this._paymentMethodClient.GetAllPaymentMethodListAsync();

            // Then: We should have multiple issuers
            Assert.IsNotNull(paymentMethods);
            Assert.IsTrue(paymentMethods.Items.Any());
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrievePricingForAllMethods() {
            // When: retrieving the ideal method we can include the issuers
            ListResponse<PaymentMethodResponse> paymentMethods = await this._paymentMethodClient.GetAllPaymentMethodListAsync(includePricing: true);

            // Then: We should have prices available
            Assert.IsTrue(paymentMethods.Items.Any(x => x.Pricing != null && x.Pricing.Any(y => y.Fixed.Value > 0)));
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrieveIssuersForAllMethods() {
            // When: retrieving the all mollie payment methods we can include the issuers
            ListResponse<PaymentMethodResponse> paymentMethods = await this._paymentMethodClient.GetAllPaymentMethodListAsync(includeIssuers: true);

            // Then: We should have one or multiple issuers
            Assert.IsTrue(paymentMethods.Items.Any(x => x.Issuers != null));
        }

        [Test][RetryOnApiRateLimitFailure(BaseMollieApiTestClass.NumberOfRetries)]
        public async Task CanRetrieveIssuersAndPricingInformation() {
            // When: retrieving the all mollie payment methods we can include the issuers
            ListResponse<PaymentMethodResponse> paymentMethods = await this._paymentMethodClient.GetAllPaymentMethodListAsync(includeIssuers: true, includePricing: true);

            // Then: We should have one or multiple issuers
            Assert.IsTrue(paymentMethods.Items.Any(x => x.Issuers != null));
            Assert.IsTrue(paymentMethods.Items.Any(x => x.Pricing != null && x.Pricing.Any(y => y.Fixed.Value > 0)));
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Myxosporium incarnata f. corni Grove

### Remarks
null


text:
package es.weso.typing

import util._

case class PosNegTypingAsMap[Node,Label](m: Map[Node,TypeRow[Label]])
  extends PosNegTyping[Node,Label] {

  override def nodes = m.keys.toSeq

  override def addPosType(node: Node,label: Label): Try[PosNegTypingAsMap[Node,Label]] = {
    val typeRow =
      if (m contains node) m(node)
      else TypeRow.empty[Label]
    for {
        tr <- typeRow.addPos(label)
    } yield {
        PosNegTypingAsMap(m + (node -> tr))
    }
  }

  override def addNegType(node: Node,label: Label): Try[PosNegTypingAsMap[Node,Label]] = {
    val typeRow =
      if (m contains node) m(node)
      else TypeRow.empty[Label]
    for {
        tr <- typeRow.addNeg(label)
    } yield {
        PosNegTypingAsMap(m + (node -> tr))
    }
  }

  override def getPosTypes(node: Node): Seq[(Label)] = m.get(node).getOrElse(TypeRow.empty).pos.toSeq
  override def getNegTypes(node: Node): Seq[(Label)] = m.get(node).getOrElse(TypeRow.empty).neg.toSeq
  override def getAllTypes(node: Node): (Seq[(Label)],Seq[(Label)]) = (getPosTypes(node),getNegTypes(node))
  override def getLabels(node: Node): Seq[Label] = getPosTypes(node) ++ getNegTypes(node)
  override def asMap = m
  override def combine(other: PosNegTyping[Node,Label]): Try[PosNegTyping[Node,Label]] = {
    val zero : Try[PosNegTyping[Node,Label]] = Success(this)
    other.asMap.foldLeft(zero){
      case (Success(rest),(node,typeRow)) => rest.addTypeRow(node, typeRow)
      case (Failure(e),_) => Failure(e)
    }
  }

  def addTypeRow(node: Node, tr: TypeRow[Label]): Try[PosNegTyping[Node,Label]] = {
    //TODO: Simplify the following expression
    if (m contains node) {
      for {
        tr1 <- m(node).combine(tr)
      } yield PosNegTypingAsMap(m = m.updated(node,tr1))
    } else {
     Success(PosNegTypingAsMap(m + (node -> tr)))
    }
  }

  override def toString: String = {
    def next(rest:String, current: (Node, TypeRow[Label])): String = {
      s"${current._1} -> ${current._2}| " + rest
    }
    "{" + m.foldLeft("")(next)  + "}"
  }
}

object PosNegTypingAsMap {
  def empty[Node,Label]: PosNegTyping[Node,Label] = {
    PosNegTypingAsMap(Map())
  }

}


text:
import asyncio
import time

from pprint import pprint

from ruia import Spider, Item, TextField, AttrField

from ruia_ua import middleware as ua_middleware

from owllook.database.mongodb import MotorBase
from owllook.spiders.middlewares import owl_middleware

try:
    import uvloop

    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass

loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)

class ZHNovelInfoItem(Item):
    """
    定义继承自item的Item类
    """
    novel_name = TextField(css_select='div.main div.status h1 a')
    author = TextField(css_select='div.main div.status div.booksub a')
    # 当提取的值是属性的时候,要定义AttrField
    cover = AttrField(css_select='div.main div.book_cover img', attr='src')
    abstract = TextField(css_select='div.main div.status div.info_con p')
    status = AttrField(css_select='div.main div.status h1 em', attr='title')
    novels_type = TextField(css_select='div.main div.status div.booksub a')
    novel_chapter_url = AttrField(css_select='div.main div.status div.book_btn span.list a', attr='href')

    async def clean_author(self, author):
        if isinstance(author, list):
            return author[0].text
        else:
            return author

    async def clean_status(self, status):
        """
        当目标值的对象只有一个,默认将值提取出来,否则返回list,可以在这里定义一个函数进行循环提取
        :param ele_tag:
        :return:
        """
        if isinstance(status, list):
            return '#'.join([i.get('title').strip().replace('作品', '') for i in status])
        else:
            return status

    async def clean_novels_type(self, novels_type):
        if isinstance(novels_type, list):
            try:
                return novels_type[1].text
            except:
                return ''
        else:
            return ''

class ZHNovelInfoSpider(Spider):
    start_urls = []
    request_config = {
        'RETRIES': 3,
        'DELAY': 2,
        'TIMEOUT': 10
    }
    motor_db = MotorBase(loop=loop).get_db()

    async def parse(self, res):
        item = await ZHNovelInfoItem.get_item(html=res.html)

        item_data = {
            'novel_name': item.novel_name,
            'author': item.author,
            'cover': item.cover,
            'abstract': item.abstract,
            'status': item.status,
            'novels_type': item.novels_type,
            'novel_chapter_url': item.novel_chapter_url,
            'target_url': res.url,
            'spider': 'zongheng',
            'updated_at': time.strftime("%Y-%m-%d %X", time.localtime()),
        }

        print('获取 {} 小说信息成功'.format(item_data['novel_name']))
        print(item_data)
        await self.motor_db.all_novels_info.update_one(
            {'novel_name': item_data['novel_name'], 'spider': 'zongheng'},
            {'$set': item_data},
            upsert=True)

if __name__ == '__main__':
    import random

    # 其他多item示例:https://gist.github.com/howie6879/3ef4168159e5047d42d86cb7fb706a2f
    ZHNovelInfoSpider.start_urls = ['http://book.zongheng.com/book/672340.html']
    ZHNovelInfoSpider.start(middleware=[ua_middleware, owl_middleware])

    # def all_novels_info():
    #     all_urls = []
    #
    #     for each in ZHNovelInfoSpider.all_novels_col.find({'spider': 'zongheng'}):
    #         if 'zongheng' in each['novel_url']:
    #             all_urls.append(each['novel_url'])
    #     random.shuffle(all_urls)
    #
    #     ZHNovelInfoSpider.start_urls = all_urls
    #     ZHNovelInfoSpider.start()
    #
    #
    # all_novels_info()


text:
package br.ufrgs.inf.gppd.function;

import br.ufrgs.inf.gppd.nlp.StopWords;
import org.apache.spark.api.java.function.*;
import scala.Tuple2;

import java.util.List;

public class StemmingFunction
    implements Function<Tuple2<Long, String>, Tuple2<Long, String>>
{
    private static final long serialVersionUID = 42l;

    public Tuple2<Long, String> call(Tuple2<Long, String> tweet)
    {
        String text = tweet._2();
        List<String> stopWords = StopWords.getWords();
        for (String word : stopWords)
        {
            text = text.replaceAll("\\b" + word + "\\b", "");
        }
        return new Tuple2<Long, String>(tweet._1(), text);
    }
}


text:
package tests.rescala

import org.scalatest.FunSuite
import rescala.restore.ReStoringEngine

class RestoringTest extends FunSuite {

  test("simple save and restore"){

    val snapshot = {
      implicit val engine = new ReStoringEngine()
      val e = engine.Evt[Unit]()
      val c = e.count()

      assert(c.now == 0)

      e.fire()
      e.fire()

      assert(c.now == 2)
      engine.snapshot()
    }

    println(snapshot.values)

    {
      implicit val engine1 = new ReStoringEngine(restoreFrom = snapshot.toSeq)
      val e = engine1.Evt[Unit]()
      val c = e.count()

      assert(c.now == 2)

      e.fire()

      assert(c.now == 3)
    }
  }

  test("save and restore with changes in between"){

    val snapshot = {
      implicit val engine = new ReStoringEngine()
      val e = engine.Evt[Unit]()
      val c = e.count()

      assert(c.now == 0)

      e.fire()
      e.fire()

      assert(c.now == 2)

      val mapped = c.map(_ + 10)

      assert(mapped.now == 12)

      engine.snapshot()

    }

    println(snapshot)

    {
      implicit val engine1 = new ReStoringEngine(restoreFrom = snapshot.toSeq)
      val e = engine1.Evt[Unit]()
      val c = e.count()

      assert(c.now == 2)

      e.fire()

      assert(c.now == 3)

      val mapped = c.map(_ + 10)

      assert(mapped.now == 13)

    }
  }

}


text:
class CFX_FloatRect;
class CFX_Matrix;
class CFX_RenderDevice;

class CFX_DrawUtils {
 public:
  CFX_DrawUtils() = delete;
  CFX_DrawUtils(const CFX_DrawUtils&) = delete;
  CFX_DrawUtils& operator=(const CFX_DrawUtils&) = delete;

  static void DrawFocusRect(CFX_RenderDevice* render_device,
                            const CFX_Matrix& user_to_device,
                            const CFX_FloatRect& view_bounding_box);
};
#endif  // CORE_FXGE_CFX_DRAWUTILS_H_