text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Staff.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @link      https://github.com/overtrue
 * @link      http://overtrue.me
 */
namespace EasyWeChat\Staff;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Support\Collection;

/**
 * Class Staff.
 */
class Staff extends AbstractAPI
{
    const API_LISTS = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist';
    const API_ONLINE = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist';
    const API_DELETE = 'https://api.weixin.qq.com/customservice/kfaccount/del';
    const API_UPDATE = 'https://api.weixin.qq.com/customservice/kfaccount/update';
    const API_CREATE = 'https://api.weixin.qq.com/customservice/kfaccount/add';
    const API_INVITE_BIND = 'https://api.weixin.qq.com/customservice/kfaccount/inviteworker';
    const API_MESSAGE_SEND = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
    const API_AVATAR_UPLOAD = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg';
    const API_RECORDS = 'https://api.weixin.qq.com/customservice/msgrecord/getrecord';

    /**
     * List all staffs.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists()
    {
        return $this->parseJSON('get', [self::API_LISTS]);
    }

    /**
     * List all online staffs.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function onlines()
    {
        return $this->parseJSON('get', [self::API_ONLINE]);
    }

    /**
     * Create a staff.
     *
     * @param string $account
     * @param string $nickname
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function create($account, $nickname)
    {
        $params = [
                   'kf_account' => $account,
                   'nickname' => $nickname,
                  ];

        return $this->parseJSON('json', [self::API_CREATE, $params]);
    }

    /**
     * Update a staff.
     *
     * @param string $account
     * @param string $nickname
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($account, $nickname)
    {
        $params = [
                   'kf_account' => $account,
                   'nickname' => $nickname,
                  ];

        return $this->parseJSON('json', [self::API_UPDATE, $params]);
    }

    /**
     * Delete a staff.
     *
     * @param string $account
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($account)
    {
        // XXX: 微信那帮搞技术的都 TM 是 SB,url上的文本居然不 TM urlencode,
        // 这里客服账号因为有 @ 符,而微信不接收urlencode的账号。。
        // 简直是日了...
        // #222
        // PS: 如果你是微信做接口的,奉劝你们,尊重技术,不会别乱搞,笨不是你们的错,你们出来坑人就是大错特错。
        $accessTokenField = sprintf('%s=%s', $this->accessToken->getQueryName(), $this->accessToken->getToken());
        $url = sprintf(self::API_DELETE.'?%s&kf_account=%s', $accessTokenField, $account);

        $contents = $this->getHttp()->parseJSON(file_get_contents($url));

        $this->checkAndThrow($contents);

        return new Collection($contents);
    }

    /**
     * Invite a staff.
     *
     * @param string $account
     * @param string $wechatId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function invite($account, $wechatId)
    {
        $params = [
                   'kf_account' => $account,
                   'invite_wx' => $wechatId,
                  ];

        return $this->parseJSON('json', [self::API_INVITE_BIND, $params]);
    }

    /**
     * Set staff avatar.
     *
     * @param string $account
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function avatar($account, $path)
    {
        return $this->parseJSON('upload', [self::API_AVATAR_UPLOAD, ['media' => $path], [], ['kf_account' => $account]]);
    }

    /**
     * Get message builder.
     *
     * @param \EasyWeChat\Message\AbstractMessage|string $message
     *
     * @return \EasyWeChat\Staff\MessageBuilder
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function message($message)
    {
        $messageBuilder = new MessageBuilder($this);

        return $messageBuilder->message($message);
    }

    /**
     * Send a message.
     *
     * @param string|array $message
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function send($message)
    {
        return $this->parseJSON('json', [self::API_MESSAGE_SEND, $message]);
    }

    /**
     * Get staff session history.
     *
     * @param int $startTime
     * @param int $endTime
     * @param int $page
     * @param int $pageSize
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function records($startTime, $endTime, $page = 1, $pageSize = 10)
    {
        $params = [
                   'starttime' => is_numeric($startTime) ? $startTime : strtotime($startTime),
                   'endtime' => is_numeric($endTime) ? $endTime : strtotime($endTime),
                   'pageindex' => $page,
                   'pagesize' => $pageSize,
                  ];

        return $this->parseJSON('json', [self::API_RECORDS, $params]);
    }
}


text:
#include <ostream>
#include <fstream>
#include <algorithm>

using namespace std;

#include "trees/trees.h"
#include "analysis/x86_analysis.h"
#include "common_defines.h"
#include "utility/defines.h"
#include "utility/print_helper.h"

#include "utilities.h"

Tree::Tree(){

	head = NULL;
	num_nodes = 0;
	tree_num = -1;
	recursive = false;

}

void Tree::set_head(Node * node){
	head = node;
}

void Tree::collect_all_nodes(Node * node, std::vector<Node *> &nodes)
{
	if (find(nodes.begin(), nodes.end(), node) == nodes.end()){
		nodes.push_back(node);
	}

	for (int i = 0; i < node->srcs.size(); i++){
		collect_all_nodes(node->srcs[i], nodes);
	}
}

Tree::~Tree(){

	vector<Node *> nodes;
	collect_all_nodes(head, nodes);
	for (int i = 0; i < nodes.size(); i++){
		delete nodes[i];
	}

}

Node * Tree::get_head()
{
	return head;
}

/* pre-order traversal of the tree */
void * Tree::traverse_tree(Node * node, void * value, node_mutator mutator, return_mutator ret_mutator){

	void * node_val = mutator(node, value);
	vector<void *> traverse_val;

	for (int i = 0; i < node->srcs.size(); i++){
		traverse_val.push_back(traverse_tree(node->srcs[i], value, mutator, ret_mutator));
	}

	return ret_mutator(node_val, traverse_val, value);
}

void Tree::canonicalize_tree()
{
	uint32_t changed_g = 1;
	/* first congregate the tree and then order the nodes */
	while (changed_g){
		changed_g = (uint32_t)traverse_tree(head, this,
			[](Node * node, void * value)->void* {

			Tree * tree = static_cast<Tree *>(value);
			uint32_t changed = node->congregate_node(tree->get_head());
			return (void *)changed;

		}, [](void * node_value, std::vector<void *> traverse_value, void * value)->void*{

			uint32_t changed = (uint32_t)node_value;
			if (changed) return (void *)changed;

			for (int i = 0; i < traverse_value.size(); i++){
				changed = (uint32_t)traverse_value[i];
				if (changed) return (void *)changed;
			}

			return (void *)changed;

		});
	}

	traverse_tree(head, NULL,
		[](Node * node, void * value)->void* {

		node->order_node();
		return NULL;
	}, empty_ret_mutator);

}

void Tree::simplify_tree() /* simplification routines are not written at the moment */
{

}

void Tree::print_dot(std::ostream &file, string name, uint32_t number)
{

	DEBUG_PRINT(("printing tree to dot file\n"), 2);

	/* print the nodes */
	string nodes = "";

	file << "digraph G_" << name << "_" << number << " {" << endl;

	cleanup_visit();

	traverse_tree(head, &nodes,
		[](Node * node, void * value)->void* {

		if (node->visited == false){
			string * node_string = static_cast<string *>(value);
			*node_string += dot_get_node_string(node->order_num, node->get_dot_string()) + "\n";
			node->visited = true;
		}

		return NULL;

	}, empty_ret_mutator);

	file << nodes << endl;

	cleanup_visit();

	/* print the edges */
	string edges = "";

	traverse_tree(head, &edges,
		[](Node * node, void * value)->void* {

		if (node->visited == false){
			string * edge_string = static_cast<string *>(value);
			for (int i = 0; i < node->srcs.size(); i++){
				*edge_string += dot_get_edge_string(node->order_num, node->srcs[i]->order_num) + "\n";
			}
			node->visited = true;

		}

		return NULL;

	}, empty_ret_mutator);

	cleanup_visit();

	file << edges << endl;

	file << "}" << endl;

}

void Tree::print_tree_recursive(Node * node, std::ostream &file){

	int no_srcs = node->srcs.size();

	if (no_srcs == 0){ /* we are at a leaf just print it*/
		file << opnd_to_string(node->symbol);
	}
	else if (no_srcs == 1){ /* unary operation */

		/* we can have a full overlap - partial overlaps will have more than one operand */
		if (node->operation == op_full_overlap){
			file << "{" << opnd_to_string(node->symbol) << " -> " << opnd_to_string(node->srcs[0]->symbol) << "}";
			file << "(";
			print_tree_recursive(node->srcs[0], file);
			file << ")";
		}
		else if (node->operation == op_assign){
			print_tree_recursive(node->srcs[0], file);
		}
		else{
			file << operation_to_string(node->operation) << " ";
			print_tree_recursive(node->srcs[0], file);
		}

	}
	else if ((no_srcs == 2) && (node->operation != op_partial_overlap)){
		file << "(";
		print_tree_recursive(node->srcs[0], file);
		file << " " << operation_to_string(node->operation) << " ";
		print_tree_recursive(node->srcs[1], file);
		file << ")";
	}
	else{
		//ASSERT_MSG((node->operation == op_partial_overlap), ("ERROR: unexpected operation with more than two srcs\n"));
		/*here it is important to see how each source contributes
		another important problem is that what source updates first
		*/
		/*file << "(";
		for (int i = 0; i < no_srcs; i++){
		print_tree(node->srcs[0], file);
		if (i != no_srcs - 1){
		file << "," << endl;
		}
		}
		file << ")";*/
		file << "(";
		file << operation_to_string(node->operation) << " ";
		for (int i = 0; i < no_srcs; i++){
			print_tree_recursive(node->srcs[0], file);
			if (i != no_srcs - 1){
				file << ",";
			}
		}
		file << ")";

	}

}

void Tree::print_tree(std::ostream &file)
{
	print_tree_recursive(head, file);

}

void * node_numbering(Node * node, void * value){
	if (node->order_num == -1){
		node->order_num = (*(int *)value)++;
	}
	return NULL;
}

void * empty_ret_mutator(void * value, vector<void *> values, void * ori_value){
	return NULL;
}

void Tree::number_tree_nodes()
{
	DEBUG_PRINT(("numbering tree\n"), 4);
	traverse_tree(head, &num_nodes, node_numbering, empty_ret_mutator);
	DEBUG_PRINT(("number of nodes %d\n", num_nodes), 4);
}

void Tree::cleanup_visit()
{
	traverse_tree(head, &num_nodes,
		[](Node * node, void * value)->void* {
		node->visited = false;
		return NULL;
		}, empty_ret_mutator);
}

void Tree::copy_exact_tree_structure(Tree * tree, void * peripheral_data, node_to_node node_creation)
{
	/* assumption the tree is numbered and the visited state is cleared */
	ASSERT_MSG((tree->get_head()->order_num != -1), ("ERROR: the concrete tree is not numbered\n"));
	ASSERT_MSG((tree->get_head()->visited == false), ("ERROR: the visit state of the concrete tree is not cleared\n"));

	/* get all the nodes and the nodes to which it is connected */
	vector< pair<Node *, vector<int> > > tree_map;
	tree_map.resize(tree->num_nodes); /* allocate space for the the nodes */
	for (int i = 0; i < tree_map.size(); i++){
		tree_map[i].first = NULL;
	}

	traverse_tree(tree->get_head(), &tree_map,
		[](Node * node, void * value)->void* {

		vector< pair<Node *, vector<int> > > * map = (vector< pair<Node *, vector<int> > > *)value;
		if ((*map)[node->order_num].first == NULL){
			for (int i = 0; i < node->srcs.size(); i++){
				(*map)[node->order_num].second.push_back(node->srcs[i]->order_num);
			}
		}
		return NULL;

	}, empty_ret_mutator);

	/* now create the new tree as a vector */
	vector < pair<Node *, vector<int> > > new_tree_map;

	for (int i = 0; i < new_tree_map.size(); i++){

		new_tree_map.push_back(make_pair(
			node_creation(tree->get_head(),tree_map[i].first, peripheral_data),
			tree_map[i].second)
			);
	}

	set_head(new_tree_map[0].first);
	/* now create the linkage structure */
	for (int i = 0; i < new_tree_map.size(); i++){
		Node * node = new_tree_map[i].first;
		vector<int> srcs = new_tree_map[i].second;
		for (int j = 0; j < srcs.size(); i++){
			node->srcs.push_back(new_tree_map[srcs[j]].first);
			new_tree_map[srcs[j]].first->prev.push_back(node);
			new_tree_map[srcs[j]].first->pos.push_back(j);
		}
	}

	/* done! -> may have a better algorithm check */

}

void Tree::copy_unrolled_tree_structure(Tree * tree, void * peripheral_data, node_to_node node_creation){

	set_head(node_creation(tree->get_head(),tree->get_head(),peripheral_data));
	copy_unrolled_tree_structure(tree->get_head(),tree->get_head(), get_head(), peripheral_data, node_creation);

}

void Tree::copy_unrolled_tree_structure(Node * head, Node * from, Node * to, void * peripheral_data, node_to_node node_creation){

	for (int i = 0; i < from->srcs.size(); i++){
		Node * new_node = node_creation(head, from->srcs[i], peripheral_data);
		to->srcs.push_back(new_node);
		new_node->prev.push_back(to);
		new_node->pos.push_back(i);
		copy_unrolled_tree_structure(head,from->srcs[i], new_node, peripheral_data, node_creation);
	}

}

void Tree::change_head_node()
{
	if (head->operation == op_assign){ /* then this node can be removed */
		ASSERT_MSG((head->srcs.size() == 1), ("ERROR: unexpected number of operands\n"));
		Node * new_head = head->srcs[0];
		new_head->prev.clear();
		new_head->pos.clear();
		delete head;
		head = new_head;
	}
}

bool Tree::are_trees_similar(Tree * tree)
{
	vector<Node *> nodes;
	nodes.push_back(get_head());
	nodes.push_back(tree->get_head());
	return are_trees_similar(nodes);
}

bool Tree::are_trees_similar(std::vector<Tree *> trees)
{

	vector<Node *> nodes;
	for (int i = 0; i < trees.size(); i++){
		nodes.push_back(trees[i]->get_head());
	}

	return are_trees_similar(nodes);

}

bool Tree::are_trees_similar(std::vector<Node *> node)
{
	if (!Node::are_nodes_similar(node)) return false;

	if (node.size() > 0){
		for (int i = 0; i < node[0]->srcs.size(); i++){
			vector<Node *> nodes;
			for (int j = 0; j < node.size(); j++){
				nodes.push_back(node[j]->srcs[i]);
			}
			if (!are_trees_similar(nodes)) return false;
		}
	}

	return true;

}

void Tree::remove_assign_nodes()
{

	cleanup_visit();

	traverse_tree(head, head, [](Node * dst, void * value)->void*{

		Node * head = (Node *)value;

		if (dst->operation == op_assign && dst != head && dst->srcs.size() == 1){

			ASSERT_MSG((dst->srcs.size() == 1), ("ERROR: assign should only have one source\n"));
			Node * src = dst->srcs[0];

			for (int i = 0; i < dst->prev.size(); i++){

				src->prev.push_back(dst->prev[i]);
				src->pos.push_back(dst->pos[i]);
				dst->prev[i]->srcs[dst->pos[i]] = src;

			}

		}

		return NULL;

	}, empty_ret_mutator);
}

std::vector<mem_regions_t *> Tree::identify_intermediate_buffers(std::vector<mem_regions_t *> mem)
{

	vector<mem_regions_t *> regions;

	return regions;

}

bool Tree::is_recursive(Node * node, vector<mem_regions_t *> &regions){

	if (head != node){

		if (node->symbol->type == MEM_HEAP_TYPE || node->symbol->type == MEM_STACK_TYPE){
			if (get_mem_region(head->symbol->value, regions) == get_mem_region(node->symbol->value, regions)){
				return true;
			}
		}

	}

	bool ret = false;
	for (int i = 0; i < node->srcs.size(); i++){
		ret = is_recursive(node->srcs[i], regions);
		if (ret){ break; }
	}

	return ret;

}

bool remove_multiplication_internal(Node * dst){

	if (dst->visited) return false;
	else{

		bool mul = false;
		dst->visited = true;

		if (dst->operation == op_mul){

			int index = -1;
			int imm_value = 0;

			for (int i = 0; i < dst->srcs.size(); i++){
				if (dst->srcs[i]->symbol->type == IMM_INT_TYPE){
					imm_value = dst->srcs[i]->symbol->value; index = i;
					break;
				}
			}

			if (index != -1 && imm_value < 10 && imm_value >= 0){
				mul = true;
				for (int i = 0; i < dst->prev.size(); i++){
					for (int j = 0; j < dst->srcs.size(); j++){
						if (index != j){
							for (int k = 0; k < imm_value; k++){
								dst->prev[i]->add_forward_ref(dst->srcs[j]);
							}
						}
					}
					dst->prev[i]->remove_forward_ref_single(dst);
				}

				for (int i = 0; i < dst->srcs.size(); i++){
					dst->remove_forward_ref(dst->srcs[i]);
				}
			}
		}

		for (int i = 0; i < dst->srcs.size(); i++){
			if (remove_multiplication_internal(dst->srcs[i])) i--;
		}

		return mul;

	}

}

void Tree::remove_multiplication(){

	cleanup_visit();

	/*traverse_tree(head, head, [](Node * dst, void * value)->void*{

		if (!dst->visited){

			dst->visited = true;

			if (dst->operation == op_mul){

				int index = -1;
				int imm_value = 0;

				for (int i = 0; i < dst->srcs.size(); i++){
					if (dst->srcs[i]->symbol->type == IMM_INT_TYPE){
						imm_value = dst->srcs[i]->symbol->value; index = i;
						break;
					}
				}

				if (index != -1 && imm_value < 10 && imm_value >= 0){
					for (int i = 0; i < dst->prev.size(); i++){
						for (int j = 0; j < dst->srcs.size(); j++){
							if (index != j){
								for (int k = 0; k < imm_value; k++){
									dst->prev[i]->add_forward_ref(dst->srcs[j]);
								}
							}
						}
						dst->prev[i]->remove_forward_ref(dst);
					}

					for (int i = 0; i < dst->srcs.size(); i++){
						dst->remove_forward_ref(dst->srcs[i]);
					}
				}
			}
		}
		return NULL;

	}, empty_ret_mutator);*/

	remove_multiplication_internal(head);

	cleanup_visit();

}

/* make sure all nodes are canonicalized before calling this routine */
void Tree::simplify_immediates(){

	traverse_tree(head, head, [](Node * node, void * value)->void *{

		if (node->operation == op_mul || node->operation == op_add){

			vector<uint32_t> indexes;
			int32_t value = 0 ;

			for (int i = 0; i < node->srcs.size(); i++){
				if (node->srcs[i]->symbol->type == IMM_INT_TYPE){
					value += node->srcs[i]->symbol->value;
					indexes.push_back(i);
				}
			}

			if (indexes.size() > 0){

				ASSERT_MSG(indexes[0] == 0, ("ERROR: canonicalized tree has immediates to the left\n"));
				node->srcs[0]->symbol->value = value;
				for (int i = 1; i < indexes.size(); i++){
					node->remove_forward_ref_single(node->srcs[indexes[i] - (i - 1)]);
				}
			}
		}

		return NULL;
	}, empty_ret_mutator);

}

bool remove_redundant_internal(Node * node){

	bool changed = false;
	if (node->operation == op_add){
		if (node->srcs.size() == 1){
			for (int i = 0; i < node->prev.size(); i++){
				node->change_ref(node->prev[i], node->srcs[0]);
				changed = true;
			}
		}
	}

	else if (node->operation == op_full_overlap){
		for (int i = 0; i < node->srcs.size(); i++){
			if (node->srcs[i]->symbol->type == IMM_INT_TYPE){
				for (int j = 0; j < node->prev.size(); j++){
					node->change_ref(node->prev[j], node->srcs[i]);
					changed = true;
				}
			}
		}
	}

	else if (node->symbol->type == IMM_INT_TYPE && node->symbol->value == 0){
		int count = 0;
		for (int i = 0; i < node->prev.size(); i++){
			if (node->prev[i]->operation == op_add){
				node->prev[i]->remove_forward_ref_single(node);
				changed = true;
				count++;
			}
		}
	}

	for (int i = 0; i < node->srcs.size(); i++){
		if (remove_redundant_internal(node->srcs[i])) i = (i - 1 >= 0) ? i-1 : 0;
	}

	return changed;

}

void Tree::remove_redundant_nodes(){

	remove_redundant_internal(head);

}

bool convert_node_sub_internal(Node * node, Node * head){

	bool changed = false;
	if (node->operation == op_sub){

		for (int i = 0; i < node->prev.size(); i++){
			if (node->prev[i]->operation == op_add){
				ASSERT_MSG(node->srcs.size() == 2, ("ERROR: sub\n"));

				node->prev[i]->add_forward_ref(node->srcs[0]);
				node->srcs[1]->minus = true;
				node->prev[i]->add_forward_ref(node->srcs[1]);
				changed = true;

				node->remove_forward_ref_single(node->srcs[0]);
				node->remove_forward_ref_single(node->srcs[0]);
				node->prev[i]->remove_forward_ref_single(node);
			}

		}
	}

	for (int i = 0; i < node->srcs.size(); i++){
		if (convert_node_sub_internal(node->srcs[i], head)) i--;
	}
	return changed;

}

void internal_propogate_minus(Node * node){

	if (node->minus && node->operation == op_add){
		for (int i = 0; i < node->srcs.size(); i++){
			node->srcs[i]->minus = !node->srcs[i]->minus;
		}
	}

	for (int i = 0; i < node->srcs.size(); i++){
		internal_propogate_minus(node->srcs[i]);
	}

}

void Tree::verify_minus(){

	traverse_tree(head, head, [](Node * node, void * value)->void *{

		if (node->operation == op_sub){
			ASSERT_MSG(node->srcs.size() == 2, ("ERROR: minus with <2 nodes\n"));
		}
		return NULL;
	}, empty_ret_mutator);

	DEBUG_PRINT(("sub verified\n"), 2);

}

void Tree::simplify_minus(){

	traverse_tree(head, head, [](Node * node, void * value)->void *{

		if (node->operation == op_add){
			vector<Node *> positive;
			vector<Node *> negative;

			for (int i = 0; i < node->srcs.size(); i++){
				if (node->srcs[i]->minus) negative.push_back(node->srcs[i]);
				else positive.push_back(node->srcs[i]);
			}

			//cout << "minus " << positive.size() << " " << negative.size() << endl;

			for (int i = 0; i < positive.size(); i++){
				for (int j = 0; j < negative.size(); j++){
					if (positive[i]->symbol->type == negative[j]->symbol->type &&
						positive[i]->symbol->width == negative[j]->symbol->width &&
						positive[i]->symbol->value == negative[j]->symbol->value){
						node->remove_forward_ref_single(positive[i]);
						node->remove_forward_ref_single(negative[j]);
						negative.erase(negative.begin() + j);
						break;
					}
				}
			}
		}

		return NULL;

	}, empty_ret_mutator);

}

void Tree::convert_sub_nodes(){

	convert_node_sub_internal(head, head);

	internal_propogate_minus(head);

}

/* unsound transformations */
void Tree::remove_po_nodes(){

	traverse_tree(head, head, [](Node * node, void * value)-> void *{

		if (node->operation == op_partial_overlap){
			for (int i = 0; i < node->prev.size(); i++){
				if (node->prev[i]->symbol->width == node->symbol->width){
					for (int j = 0; j < node->srcs.size(); j++){
						node->change_ref(node->prev[i],node->srcs[j]);
					}
				}
			}
		}

		return NULL;

	}, empty_ret_mutator);

}

void Tree::remove_or_minus_1(){

	traverse_tree(head, head, [](Node * node, void * value)-> void* {

		if (node->operation == op_or){

			int32_t index = -1;
			for (int i = 0; i < node->srcs.size(); i++){

				if (node->srcs[i]->symbol->type == IMM_INT_TYPE && (int32_t)node->srcs[i]->symbol->value == -1){
					index = i; break;
				}
			}

			if (index != -1){
				node->srcs.clear();
				node->symbol->type = IMM_INT_TYPE;
				node->symbol->value = 255;
			}

			return NULL;

		}

		return NULL;

	}, empty_ret_mutator);

}

void Tree::mark_recursive(){

	traverse_tree(head, this, [](Node * node, void * value)-> void * {

		Tree * tree = (Tree *)value;
		Node * head = tree->get_head();

		mem_regions_t * head_region = ((Conc_Node *)head)->region;
		mem_regions_t * conc_region = ((Conc_Node *)node)->region;

		if (head_region == NULL || conc_region == NULL) return NULL;

		if (head_region == conc_region && head->symbol->value != node->symbol->value){
			tree->recursive = true;
		}

		return NULL;

	}, empty_ret_mutator);

}

void Tree::remove_identities(){

	traverse_tree(head, NULL, [](Node * node, void * value)->void*{

		if (node->operation == op_add){

			for (int i = 0; i < node->srcs.size(); i++){
				if (node->srcs[i]->symbol->type == IMM_INT_TYPE && node->srcs[i]->symbol->value == 0){
					node->remove_forward_ref_single(node->srcs[i]);
					i--;
				}
			}

		}

		return NULL;

	}, empty_ret_mutator);

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/* vim: set noexpandtab sw=2 ts=2 sts=2: */
/**
 * A developer who has access to the system
 *
 * phpMyAdmin Error reporting server
 * Copyright (c) phpMyAdmin project (http://www.phpmyadmin.net)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) phpMyAdmin project (http://www.phpmyadmin.net)
 * @package       Server.Model
 * @link          http://www.phpmyadmin.net
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

App::uses('AppModel', 'Model');

/**
 * A developer who has access to the system
 *
 * @package       Server.Model
 */
class Developer extends AppModel {

/**
 * creates a developer record given his github info and his access token
 *
 * @param Array $githubInfo the data gitub has on this developer
 * @param String $accessToken this developer's access token
 * @return Boolean true if the developer was correctly saved otherwise false
 */
	public function saveFromGithub($githubInfo, $accessToken) {
		$userData = array(
			'full_name' => $githubInfo['name'],
			'gravatar_id' => $githubInfo['gravatar_id'],
			'email' => $githubInfo['email'],
			'github_id' => $githubInfo['id'],
			'access_token' => $accessToken,
			'has_commit_access' => $githubInfo['has_commit_access']?1:0,
		);
		return $this->save($userData);
	}
}


text:
function [logZ, nodeBel, edgeBel] = bruteForceInferNodes(factors, edges)
% Compute all node marginals given a set of factors using enuemration
% We assume all nodes are discrete and have the same num states
% factors{f} is a tabular factor
%
% logZ is log normalization constant
% nodeBel(:,t)
%
% Optional: if you pass in edges matrix size E*2, we also compute
% edgeBel(:,:,e) where edges(e,:)=[s t]

nodeSizes = [];
for f=1:numel(factors)
  nodeSizes(factors{f}.domain) = factors{f}.sizes;
end
if ~all(nodeSizes==nodeSizes(1))
  error('all node sizes must be the same')
end
if prod(nodeSizes) > 1024
  fprintf('warning: you are about to create a joint table with %d entries', prod(nodeSizes));
end
Nnodes = numel(nodeSizes);
Nstates = nodeSizes(1);

% Compute marginla prob of each node
queries = num2cell(1:Nnodes);
[logZ, bels] = bruteForceInferQuery(factors, queries);
% Convert the tabular factors to standard matrix
nodeBel = zeros(Nstates, Nnodes);
for i=1:Nnodes
  nodeBel(:,i) = bels{i}.T(:);
end

if nargin < 2, return; end
% Computed joint prob of each edge
Nedges = size(edges, 1);
edgeBel = ones(Nstates, Nstates, Nedges);
queries = num2cell(edges, 2);
[logZ2, bels2] = bruteForceInferQuery(factors, queries); %#ok
if Nedges == 1, bels2 = {bels2}; end
for e=1:Nedges
  edgeBel(:,:,e) = bels2{e}.T;
end
assert(approxeq(logZ, logZ2))

end


text:
package java2typescript.jackson.module.conf.typename;

import com.fasterxml.jackson.databind.JavaType;

/**
 * Used to detect TypeScript type name based on given Java type
 */
public interface TSTypeNamingStrategy {

	/**
	 * @return name of the TypeScript class corresponding to Java class
	 */
	String getName(JavaType type);

}


text:
001
017    package org.apache.commons.math3.util;
018
019
020    import java.io.Serializable;
021    import java.math.BigDecimal;
022    import java.math.BigInteger;
023    import java.math.MathContext;
024    import java.math.RoundingMode;
025
026    import org.apache.commons.math3.Field;
027    import org.apache.commons.math3.FieldElement;
028    import org.apache.commons.math3.exception.MathArithmeticException;
029    import org.apache.commons.math3.exception.util.LocalizedFormats;
030
031    /**
032     * Arbitrary precision decimal number.
033     * <p>
034     * This class is a simple wrapper around the standard <code>BigDecimal</code>
035     * in order to implement the {@link FieldElement} interface.
036     * </p>
037     * @since 2.0
038     * @version $Id: BigReal.java 1416643 2012-12-03 19:37:14Z tn $
039     */
040    public class BigReal implements FieldElement<BigReal>, Comparable<BigReal>, Serializable {
041
042        /** A big real representing 0. */
043        public static final BigReal ZERO = new BigReal(BigDecimal.ZERO);
044
045        /** A big real representing 1. */
046        public static final BigReal ONE = new BigReal(BigDecimal.ONE);
047
048        /** Serializable version identifier. */
049        private static final long serialVersionUID = 4984534880991310382L;
050
051        /** Underlying BigDecimal. */
052        private final BigDecimal d;
053
054        /** Rounding mode for divisions. **/
055        private RoundingMode roundingMode = RoundingMode.HALF_UP;
056
057        /*** BigDecimal scale ***/
058        private int scale = 64;
059
060        /** Build an instance from a BigDecimal.
061         * @param val value of the instance
062         */
063        public BigReal(BigDecimal val) {
064            d =  val;
065        }
066
067        /** Build an instance from a BigInteger.
068         * @param val value of the instance
069         */
070        public BigReal(BigInteger val) {
071            d = new BigDecimal(val);
072        }
073
074        /** Build an instance from an unscaled BigInteger.
075         * @param unscaledVal unscaled value
076         * @param scale scale to use
077         */
078        public BigReal(BigInteger unscaledVal, int scale) {
079            d = new BigDecimal(unscaledVal, scale);
080        }
081
082        /** Build an instance from an unscaled BigInteger.
083         * @param unscaledVal unscaled value
084         * @param scale scale to use
085         * @param mc to used
086         */
087        public BigReal(BigInteger unscaledVal, int scale, MathContext mc) {
088            d = new BigDecimal(unscaledVal, scale, mc);
089        }
090
091        /** Build an instance from a BigInteger.
092         * @param val value of the instance
093         * @param mc context to use
094         */
095        public BigReal(BigInteger val, MathContext mc) {
096            d = new BigDecimal(val, mc);
097        }
098
099        /** Build an instance from a characters representation.
100         * @param in character representation of the value
101         */
102        public BigReal(char[] in) {
103            d = new BigDecimal(in);
104        }
105
106        /** Build an instance from a characters representation.
107         * @param in character representation of the value
108         * @param offset offset of the first character to analyze
109         * @param len length of the array slice to analyze
110         */
111        public BigReal(char[] in, int offset, int len) {
112            d = new BigDecimal(in, offset, len);
113        }
114
115        /** Build an instance from a characters representation.
116         * @param in character representation of the value
117         * @param offset offset of the first character to analyze
118         * @param len length of the array slice to analyze
119         * @param mc context to use
120         */
121        public BigReal(char[] in, int offset, int len, MathContext mc) {
122            d = new BigDecimal(in, offset, len, mc);
123        }
124
125        /** Build an instance from a characters representation.
126         * @param in character representation of the value
127         * @param mc context to use
128         */
129        public BigReal(char[] in, MathContext mc) {
130            d = new BigDecimal(in, mc);
131        }
132
133        /** Build an instance from a double.
134         * @param val value of the instance
135         */
136        public BigReal(double val) {
137            d = new BigDecimal(val);
138        }
139
140        /** Build an instance from a double.
141         * @param val value of the instance
142         * @param mc context to use
143         */
144        public BigReal(double val, MathContext mc) {
145            d = new BigDecimal(val, mc);
146        }
147
148        /** Build an instance from an int.
149         * @param val value of the instance
150         */
151        public BigReal(int val) {
152            d = new BigDecimal(val);
153        }
154
155        /** Build an instance from an int.
156         * @param val value of the instance
157         * @param mc context to use
158         */
159        public BigReal(int val, MathContext mc) {
160            d = new BigDecimal(val, mc);
161        }
162
163        /** Build an instance from a long.
164         * @param val value of the instance
165         */
166        public BigReal(long val) {
167            d = new BigDecimal(val);
168        }
169
170        /** Build an instance from a long.
171         * @param val value of the instance
172         * @param mc context to use
173         */
174        public BigReal(long val, MathContext mc) {
175            d = new BigDecimal(val, mc);
176        }
177
178        /** Build an instance from a String representation.
179         * @param val character representation of the value
180         */
181        public BigReal(String val) {
182            d = new BigDecimal(val);
183        }
184
185        /** Build an instance from a String representation.
186         * @param val character representation of the value
187         * @param mc context to use
188         */
189        public BigReal(String val, MathContext mc)  {
190            d = new BigDecimal(val, mc);
191        }
192
193        /***
194         * Gets the rounding mode for division operations
195         * The default is {@code RoundingMode.HALF_UP}
196         * @return the rounding mode.
197         * @since 2.1
198         */
199        public RoundingMode getRoundingMode() {
200            return roundingMode;
201        }
202
203        /***
204         * Sets the rounding mode for decimal divisions.
205         * @param roundingMode rounding mode for decimal divisions
206         * @since 2.1
207         */
208        public void setRoundingMode(RoundingMode roundingMode) {
209            this.roundingMode = roundingMode;
210        }
211
212        /***
213         * Sets the scale for division operations.
214         * The default is 64
215         * @return the scale
216         * @since 2.1
217         */
218        public int getScale() {
219            return scale;
220        }
221
222        /***
223         * Sets the scale for division operations.
224         * @param scale scale for division operations
225         * @since 2.1
226         */
227        public void setScale(int scale) {
228            this.scale = scale;
229        }
230
231        /** {@inheritDoc} */
232        public BigReal add(BigReal a) {
233            return new BigReal(d.add(a.d));
234        }
235
236        /** {@inheritDoc} */
237        public BigReal subtract(BigReal a) {
238            return new BigReal(d.subtract(a.d));
239        }
240
241        /** {@inheritDoc} */
242        public BigReal negate() {
243            return new BigReal(d.negate());
244        }
245
246        /**
247         * {@inheritDoc}
248         *
249         * @throws MathArithmeticException if {@code a} is zero
250         */
251        public BigReal divide(BigReal a) throws MathArithmeticException {
252            try {
253                return new BigReal(d.divide(a.d, scale, roundingMode));
254            } catch (ArithmeticException e) {
255                // Division by zero has occured
256                throw new MathArithmeticException(LocalizedFormats.ZERO_NOT_ALLOWED);
257            }
258        }
259
260        /**
261         * {@inheritDoc}
262         *
263         * @throws MathArithmeticException if {@code this} is zero
264         */
265        public BigReal reciprocal() throws MathArithmeticException {
266            try {
267                return new BigReal(BigDecimal.ONE.divide(d, scale, roundingMode));
268            } catch (ArithmeticException e) {
269                // Division by zero has occured
270                throw new MathArithmeticException(LocalizedFormats.ZERO_NOT_ALLOWED);
271            }
272        }
273
274        /** {@inheritDoc} */
275        public BigReal multiply(BigReal a) {
276            return new BigReal(d.multiply(a.d));
277        }
278
279        /** {@inheritDoc} */
280        public BigReal multiply(final int n) {
281            return new BigReal(d.multiply(new BigDecimal(n)));
282        }
283
284        /** {@inheritDoc} */
285        public int compareTo(BigReal a) {
286            return d.compareTo(a.d);
287        }
288
289        /** Get the double value corresponding to the instance.
290         * @return double value corresponding to the instance
291         */
292        public double doubleValue() {
293            return d.doubleValue();
294        }
295
296        /** Get the BigDecimal value corresponding to the instance.
297         * @return BigDecimal value corresponding to the instance
298         */
299        public BigDecimal bigDecimalValue() {
300            return d;
301        }
302
303        /** {@inheritDoc} */
304        @Override
305        public boolean equals(Object other) {
306            if (this == other){
307                return true;
308            }
309
310            if (other instanceof BigReal){
311                return d.equals(((BigReal) other).d);
312            }
313            return false;
314        }
315
316        /** {@inheritDoc} */
317        @Override
318        public int hashCode() {
319            return d.hashCode();
320        }
321
322        /** {@inheritDoc} */
323        public Field<BigReal> getField() {
324            return BigRealField.getInstance();
325        }
326    }


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    tools:context="me.kudryavka.bluecon_demo.SPPClientActivity">

    <Button
        android:id="@+id/btn_start_spp_server_single"
        android:text="@string/btn_start_spp_server_single"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_start_spp_server_multi"
        android:text="@string/btn_start_spp_server_multi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_start_spp_server_single"/>
    <TextView
        android:id="@+id/con_device_info"
        android:text="@string/con_device_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:layout_margin="15dp"
        android:layout_below="@+id/btn_start_spp_server_multi"/>

    <ListView
        android:id="@+id/lists"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/con_device_info"
        android:layout_above="@+id/msg_for_send"/>
    <EditText
        android:id="@+id/msg_for_send"
        android:hint="@string/msg_hint_broadcast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_send_to_device"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/btn_send_to_device"
        android:text="@string/btn_send_to_device"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
</RelativeLayout>


text:
'''
The JSON output module converts the return data into JSON.
'''

# Import python libs
import json
import logging

log = logging.getLogger(__name__)

# Define the module's virtual name
__virtualname__ = 'json'

def __virtual__():
    '''
    Rename to json
    '''
    return __virtualname__

def output(data):
    '''
    Print the output data in JSON
    '''
    try:
        if 'output_indent' in __opts__:
            if __opts__['output_indent'] >= 0:
                return json.dumps(data, default=repr, indent=__opts__['output_indent'])
            return json.dumps(data, default=repr)
        return json.dumps(data, default=repr, indent=4)
    except TypeError:
        log.debug('An error occurred while outputting JSON', exc_info=True)
    # Return valid JSON for unserializable objects
    return json.dumps({})


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * Function.prototype.call can't be used as [[create]] caller
 *
 * @path ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T3.js
 * @description Checking if creating "new Function.call" fails
 */

try {
  var obj = new Function.call;
  $ERROR('#1: Function.prototype.call can\'t be used as [[create]] caller');
} catch (e) {
  if (!(e instanceof TypeError)) {
  	$ERROR('#1.1: Function.prototype.call can\'t be used as [[create]] caller');
  }
}


text: Practice C++ Scripts


text:
package net.sf.jsqlparser.test.delete;

import java.io.StringReader;
import static junit.framework.Assert.assertEquals;

import junit.framework.TestCase;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.delete.Delete;
import static net.sf.jsqlparser.test.TestUtils.*;

public class DeleteTest extends TestCase {

	CCJSqlParserManager parserManager = new CCJSqlParserManager();

	public DeleteTest(String arg0) {
		super(arg0);
	}

	public void testDelete() throws JSQLParserException {
		String statement = "DELETE FROM mytable WHERE mytable.col = 9";

		Delete delete = (Delete) parserManager.parse(new StringReader(statement));
		assertEquals("mytable", delete.getTable().getName());
		assertEquals(statement, "" + delete);
	}

	public void testDeleteWhereProblem1() throws JSQLParserException {
		String stmt = "DELETE FROM tablename WHERE a = 1 AND b = 1";
		assertSqlCanBeParsedAndDeparsed(stmt);
	}
}


text:
WD=$(dirname "$0")
WD=$(cd "$WD"; pwd)

set -eu

SOURCE_GCS_BUCKET=${SOURCE_GCS_BUCKET:-istio-prerelease/prerelease}
GCS_BUCKET=${GCS_BUCKET:-istio-release/releases}
DOCKER_HUB=${DOCKER_HUB:-docker.io/istio}
GITHUB_ORG=${GITHUB_ORG:-istio}

VERSION="$(cat "${WD}/trigger-publish")"

cat <<EOF
WARNING
If you are seeing this test, you have modified the trigger-publish file.

This will publish an official build of Istio once merged.

If this is unexpected, do not merge this PR.

If this is expected, this message can be ignored.

Build information
=================
Version: ${VERSION}

GCS Bucket: ${GCS_BUCKET}
Docker Hub: ${DOCKER_HUB}
Github Org: ${GITHUB_ORG}
Source: ${SOURCE_GCS_BUCKET}/${VERSION}
Contents:
$(gsutil cat "gs://${SOURCE_GCS_BUCKET}/${VERSION}/manifest.yaml")
$(gsutil ls -r "gs://${SOURCE_GCS_BUCKET}/${VERSION}")
EOF

exit 2


text:
#ifndef DIY_PARTNERS_SWAP_HPP
#define DIY_PARTNERS_SWAP_HPP

#include "common.hpp"

namespace diy
{

class Master;

/**
 * \ingroup Communication
 * \brief Partners for swap-reduce
 *
 */
struct RegularSwapPartners: public RegularPartners
{
  typedef       RegularPartners                                 Parent;

                // contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion;
                // contiguous is useful when data needs to be united;
                // round-robin is useful for vector-"halving"
                RegularSwapPartners(int dim,               //!< dimensionality of regular block grid
                                    int nblocks,           //!< total number of blocks
                                    int k,                 //!< target k value
                                    bool contiguous = true //!< distance halving (true) or doubling (false)
                    ):
                    Parent(dim, nblocks, k, contiguous)         {}
                RegularSwapPartners(const DivisionVector&   divs, //!< explicit division vector
                                    const KVSVector&        kvs,  //!< explicit k vector
                                    bool  contiguous = true       //!< distance halving (true) or doubling (false)
                    ):
                    Parent(divs, kvs, contiguous)               {}

  bool          active(int round, int gid, const Master&) const                                 { return true; }    // in swap-reduce every block is always active

  void          incoming(int round, int gid, std::vector<int>& partners, const Master&) const   { Parent::fill(round - 1, gid, partners); }
  void          outgoing(int round, int gid, std::vector<int>& partners, const Master&) const   { Parent::fill(round, gid, partners); }
};

} // diy

#endif


text:
import {
  log,
  warn,
  isFunction,
  isString,
  getClassName
} from '../utils';
import {
  fxData,
  _require
} from '../core';
import i18n from '../i18n';
import Dispatcher from './dispatcher';
import {
  getDecoratorToken as getCommandToken
} from '../command/decorator';
import {
  getDecoratorToken as getEventToken
} from '../event/decorator';
import assert from 'assert';

export default class MessageDispatcher extends Dispatcher {
  _dispatchingListeners = []
  _dispatchFailedListeners = []
  _dispatchedListeners = []

  _handlers = {};

  createAndRegisterAlias() {
    this._handlers = {};
    Object.keys(fxData.alias).filter(alias => alias.split('/')[1] === this.type).map(alias => _require(alias)).forEach((type) => this.registerHandler(type));
  }

  getHandlers(name, module) {
    assert(name);
    if (!module) {
      const mn = name.split('/');
      module = mn[0];
      name = mn[1];
    }
    assert(module);
    return this._handlers[`${module}/${name}`] || [];
  }

  registerHandler(handlerType) {
    assert(handlerType);
    let ctoken = this.type === 'event' ?
      getEventToken(handlerType) :
      getCommandToken(handlerType);
    if (!ctoken.name && !ctoken.module) {
      if (!handlerType.prototype) {
        warn(i18n.t('不支持的handler类型'));
      }
      ctoken = {
        module: handlerType.prototype.__module || handlerType.$packageName,
        name: handlerType.name
      };
    }
    for (const p of Object.getOwnPropertyNames(handlerType.prototype)) {
      if (p === 'constructor') {
        continue;
      }
      if (!isFunction(handlerType.prototype[p])) {
        continue;
      }
      let {
        module = ctoken.module,
          name = p
      } = this.type === 'event' ?
        getEventToken(handlerType.prototype[p]) :
        getCommandToken(handlerType.prototype[p]);
      if (module && name) {
        let items = this._handlers[`${module}/${name}`];
        if (!items) {
          this._handlers[`${module}/${name}`] = items = [];
        }
        if (!items.find(item => item.CLS == handlerType && item.method == p)) {
          items.push({
            CLS: handlerType,
            method: p
          });
          log(i18n.t('注册'), getClassName(handlerType) + '.' + p, '=>', `${module}/${name}`);
        } else {
          log(i18n.t('跳过'), getClassName(handlerType) + '.' + p)
        }
      } else {
        warn(i18n.t('注册失败,模块未知'), getClassName(handlerType) + '.' + p)
      }
    }
  }

  unregisterHandler(handler) {
    const ctoken = this.type === 'event' ?
      getEventToken(handlerType) :
      getCommandToken(handlerType);
    for (const p in handlerType.prototype) {
      const {
        module = ctoken.module,
          name
      } = this.type === 'event' ?
        getEventToken(handlerType.prototype[p]) :
        getCommandToken(handlerType.prototype[p]);
      if (module && name) {
        let items = this._handlers[`${module}/${name}`];
        if (!items) {
          continue;
        }
        const item = items.find(item => item.CLS === handler);
        if (!item) {
          continue;
        }
        items.splice(items.indexOf(item), 1);
      }
    }
  }

  // message = {name,module,type,data}
  async dispatch(message) {
    if (!isString(message.id)) {
      this._onDispatchFaild(message, 'nomessage');
      warn(i18n.t('消息id无效'));
      return;
    }
    if (!isString(message.name)) {
      this._onDispatchFaild(message, 'nomessage');
      warn(i18n.t('消息name无效'));
      return;
    }
    if (message.type !== 'event' && message.type !== 'command') {
      this._onDispatchFaild(message, 'nomessage');
      warn(i18n.t('消息type无效'));
      return;
    }
    if (message.type !== this.type) {
      this._onDispatchFaild(message, 'notsupport');
      warn(message.type + i18n.t('消息无法分发'));
      return;
    }
    const id = message.id;
    const module = message.module;
    const name = message.name;
    if (!module) {
      this._onDispatchFaild(message, 'nomodule');
      warn(i18n.t('消息module无效'));
      return;
    }
    const handlers = this.getHandlers(name, module);
    if (!handlers || handlers.length <= 0) {
      this._onDispatchFaild(message, 'nohandler');
      warn(i18n.t('无消息处理器'));
    }
    log(i18n.t('开始执行'), this.type, `${module}/${name} (${id})`);
    await this._onDispatching(message);
    let curHandler;
    try {
      for (const {
          CLS,
          method
        } of handlers) {
        curHandler = null;
        var handler = new CLS();
        curHandler = handler;
        if (!isFunction(handler[method])) {
          warn(i18n.t('处理器无法执行命令'));
          continue;
        }
        await handler[method].bind(handler)(message.data || {});
      }
      await this._onDispatched(message);
      log(i18n.t('完成执行'), this.type, `${module}/${name} (${id})`);
      return true;
    } catch (err) {
      warn(i18n.t('失败执行'), this.type, `${module}/${name} (${id})`, err);
      await this._onDispatchFaild(message, 'error', err, curHandler);
      return false;
    }
  }

  clear() {
    this._dispatchingListeners.clear();
    this._dispatchFailedListeners.clear();
    this._dispatchedListeners.clear();
  }

  addListener(dispatchingListener, dispatchedListener, dispatchFailedListener) {
    if (isFunction(dispatchingListener))
      this._dispatchingListeners.push(dispatchingListener);
    if (isFunction(dispatchedListener))
      this._dispatchedListeners.push(dispatchedListener);
    if (isFunction(dispatchFailedListener))
      this._dispatchFailedListeners.push(dispatchFailedListener);
  }

  removeListener(dispatchingListener, dispatchedListener, dispatchFailedListener) {
    if (isFunction(dispatchingListener))
      this._dispatchingListeners.splice(this._dispatchingListeners.indexOf(dispatchingListener), 1);
    if (isFunction(dispatchedListener))
      this._dispatchedListeners.splice(this._dispatchedListeners.indexOf(dispatchedListener), 1);
    if (isFunction(dispatchFailedListener))
      this._dispatchFailedListeners.splice(this._dispatchFailedListeners.indexOf(dispatchFailedListener), 1);
  }

  async _onDispatching(message) {
    for (const listener of this._dispatchingListeners) {
      try {
        await listener(message);
      } catch (e) {
        warn(e);
      }
    }
  }

  async _onDispatchFaild(message, code, error) {
    for (const listener of this._dispatchFailedListeners) {
      try {
        await listener(message, code, error);
      } catch (e) {
        warn(e);
      }
    }
  }

  async _onDispatched(message) {
    for (const listener of this._dispatchedListeners) {
      try {
        await listener(message, 'ok');
      } catch (e) {
        warn(e);
      }
    }
  }
}


text:
Statistic

                    Points

                    Votes

                        <svg aria-hidden="true" class="slds-button__icon coffee-icon">
                            <use xlink:href="/unicorn-pointing-poker/assets/icons/custom-sprite/svg/symbols.svg#custom65"></use>
                        </svg>
                        Settings

                        Not voted

TOTAL AGREEMENT!!!


text:
doc_sources = $(wildcard doc/*/*.md) $(wildcard doc/*.md)
outdoc_files = $(addprefix out/,$(doc_sources:.md=.html))

docassets = $(addprefix out/,$(wildcard doc/assets/*))

VERSION = $(shell node -e "console.log( require('./src/package.json').version )")
UNAME := $(shell uname -s)

ensure_marked_is_installed:
	set -eu; \
	hash npm; \
	if [ $(shell npm list --prefix bin/doc >/dev/null 2>/dev/null; echo $$?) -ne "0" ]; then \
		npm ci --prefix=bin/doc; \
	fi

docs: ensure_marked_is_installed $(outdoc_files) $(docassets)

out/doc/assets/%: doc/assets/%
	mkdir -p $(@D)
	cp $< $@

out/doc/%.html: doc/%.md
	mkdir -p $(@D)
	node bin/doc/generate.js --format=html --template=doc/template.html $< > $@
ifeq ($(UNAME),Darwin)
	sed -i '' 's/__VERSION__/${VERSION}/' $@
else
	sed -i 's/__VERSION__/${VERSION}/' $@
endif

clean:
	rm -rf out/


text:
I represent a Jenkins job.

A job is regulargly executed. Each execution is named a build.


text:
<?php
/** External module example #2
 *  Engine loading the class (same name as file name) and call three static functions (extends cXVI_AbsModule)
 */
class module_2 extends cXVI_AbsModule{
    private static $_instance;
    private static $xvi_api;

    /** Generate JSON description of this class and provide to module_queue for processing.
     *    For each PH there can be the only single array with class name.
     *    Priority is ignored here and shall set to 0.
     */
    public static function Register() {
        $module_2_queue_json =<<< EOF
{
"TEST_EMPTY": [{ "class":"module_2", "priority":"0" }],
"PH_DEMO": [{ "class":"module_2", "priority":"0" }]
}
EOF;
        return $module_2_queue_json;
    }

    public static function Call($placeholder_id) {
            switch ($placeholder_id) {
                case 'TEST_EMPTY':
                    return self::PH_TestEmpty();
                case 'PH_DEMO':
                    return self::PH_Demo();
                default:
                    return self::PH_Clear();
            }
    }

    private function Parse(&$content,$pattern){
	$tpl = OPEN_PATTERN_SIGN.$pattern.CLOSE_PATTERN_SIGN;
	$repl = "test class";
	return str_replace($tpl, $repl, $content);
    }

    function __construct(){
        self::Register();
        self::$xvi_api =xvi_API::getInstance();
    }
    /*  function __destruct(){ } */
    private function __clone(){ }
    public static function getInstance() {
        if (null === self::$_instance) {
          self::$_instance = new self();
        }
        return self::$_instance;
    }

    /** Replace unknown placeholder by empty string
     */
    private function PH_Clear(){
        return "";
    }

    private function PH_TestEmpty(){
        return "Empty test at module_2.php";
    }
    private function PH_Demo(){
        return "
 Demo test at module_2.php
";
    }

}

?>


text:
<?php

namespace Drupal\Tests\rest\Functional\EntityResource\ModeratedNode;

use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;

/**
 * @group rest
 */
class ModeratedNodeXmlBasicAuthTest extends ModeratedNodeResourceTestBase {

  use BasicAuthResourceTestTrait;
  use XmlEntityNormalizationQuirksTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['basic_auth'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $format = 'xml';

  /**
   * {@inheritdoc}
   */
  protected static $mimeType = 'text/xml; charset=UTF-8';

  /**
   * {@inheritdoc}
   */
  protected static $auth = 'basic_auth';

  /**
   * {@inheritdoc}
   */
  public function testPatchPath() {
    // Deserialization of the XML format is not supported.
    $this->markTestSkipped();
  }

}


text:
package com.sequenceiq.cloudbreak.service.cluster.flow;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sequenceiq.ambari.client.AmbariClient;
import com.sequenceiq.cloudbreak.service.ClusterBasedStatusCheckerTask;

@Component
public class AmbariHostsLeaveStatusCheckerTask extends ClusterBasedStatusCheckerTask<AmbariHostsWithNames> {

    private static final Logger LOGGER = LoggerFactory.getLogger(AmbariHostsLeaveStatusCheckerTask.class);

    private static final String LEFT_STATE = "UNKNOWN";

    @Override
    public boolean checkStatus(AmbariHostsWithNames hosts) {
        try {
            AmbariClient ambariClient = hosts.getAmbariClient();
            List<String> hostNames = hosts.getHostNames();
            Map<String, String> hostStatuses = ambariClient.getHostStatuses();
            for (String hostName : hostNames) {
                String status = hostStatuses.get(hostName);
                if (!LEFT_STATE.equals(status)) {
                    LOGGER.info("{} didn't leave the cluster yet", hostName);
                    return false;
                }
            }
        } catch (Exception e) {
            LOGGER.error("Failed to check the left hosts", e);
            return false;
        }
        return true;
    }

    @Override
    public void handleTimeout(AmbariHostsWithNames t) {
        LOGGER.error("Operation timed out. Hosts didn't leave in time, hosts: '{}' stack: '{}'", t.getHostNames(), t.getStack().getId());
    }

    @Override
    public String successMessage(AmbariHostsWithNames t) {
        return String.format("Hosts left the cluster, hosts: '%s' stack '%s'", t.getHostNames(), t.getStack().getId());
    }

}


text:
package org.apache.cassandra.db.marshal;

import java.nio.ByteBuffer;

import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.Constants;
import org.apache.cassandra.cql3.Term;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.serializers.SimpleDateSerializer;
import org.apache.cassandra.serializers.TypeSerializer;
import org.apache.cassandra.utils.ByteBufferUtil;

public class SimpleDateType extends AbstractType<Integer>
{
    public static final SimpleDateType instance = new SimpleDateType();

    SimpleDateType() {} // singleton

    public int compare(ByteBuffer o1, ByteBuffer o2)
    {
        // We add Integer.MIN_VALUE to overflow to allow unsigned comparison
        return ByteBufferUtil.compareUnsigned(o1, o2);
    }

    @Override
    public boolean isByteOrderComparable()
    {
        return true;
    }

    public ByteBuffer fromString(String source) throws MarshalException
    {
        return ByteBufferUtil.bytes(SimpleDateSerializer.dateStringToDays(source));
    }

    public ByteBuffer fromTimeInMillis(long millis) throws MarshalException
    {
        return ByteBufferUtil.bytes(SimpleDateSerializer.timeInMillisToDay(millis));
    }

    public long toTimeInMillis(ByteBuffer buffer) throws MarshalException
    {
        return SimpleDateSerializer.dayToTimeInMillis(ByteBufferUtil.toInt(buffer));
    }

    @Override
    public boolean isCompatibleWith(AbstractType<?> previous)
    {
        return super.isCompatibleWith(previous);
    }

    @Override
    public boolean isValueCompatibleWithInternal(AbstractType<?> otherType)
    {
        return this == otherType || otherType == Int32Type.instance;
    }

    public Term fromJSONObject(Object parsed) throws MarshalException
    {
        try
        {
            return new Constants.Value(fromString((String) parsed));
        }
        catch (ClassCastException exc)
        {
            throw new MarshalException(String.format(
                    "Expected a string representation of a date value, but got a %s: %s",
                    parsed.getClass().getSimpleName(), parsed));
        }
    }

    @Override
    public String toJSONString(ByteBuffer buffer, int protocolVersion)
    {
        return '"' + SimpleDateSerializer.instance.toString(SimpleDateSerializer.instance.deserialize(buffer)) + '"';
    }

    @Override
    public CQL3Type asCQL3Type()
    {
        return CQL3Type.Native.DATE;
    }

    public TypeSerializer<Integer> getSerializer()
    {
        return SimpleDateSerializer.instance;
    }
}


text:
package docker

import (
	"github.com/kelseyhightower/envconfig"
	"github.com/davidhiendl/telegraf-docker-sd/app/config"
	"github.com/sirupsen/logrus"
)

type DockerConfigSpec struct {
	AutoConfPrefix string `envconfig:"AUTO_CONF_PREFIX",default:"docker_"`
	TagsFromSwarm  bool   `envconfig:"TAGS_FROM_SWARM",default:"true"`

	TagLabelsWhitelistStr string `envconfig:"TAG_LABELS_WHITELIST"`
	TagLabelsBlacklistStr string `envconfig:"TAG_LABELS_BLACKLIST"`

	TagLabelsWhitelist []string `ignored:"true"`
	TagLabelsBlacklist []string `ignored:"true"`
}

func LoadConfig() *DockerConfigSpec {
	cfg := &DockerConfigSpec{}
	err := envconfig.Process("TSD_DOCKER", cfg)

	if err != nil {
		logrus.Fatalf("failed to parse config: %v", err)
	}

	// convert list to array
	cfg.TagLabelsWhitelist = config.ConfigListToArray(cfg.TagLabelsWhitelistStr)
	cfg.TagLabelsBlacklist = config.ConfigListToArray(cfg.TagLabelsBlacklistStr)

	if len(cfg.TagLabelsWhitelist) > 0 && len(cfg.TagLabelsBlacklist) > 0 {
		logrus.Fatalf(LOG_PREFIX+" cannot have label whitelist and blacklist", err)
	}

	return cfg
}


text:
#import "YWBCarModelCell.h"

#import "CarData.h"

@implementation YWBCarModelCell

+ (UINib *)nib
{
    return [UINib nibWithNibName:@"YWBCarModelCell" bundle:nil];
}
- (void)awakeFromNib {
    // Initialization code

    self.backgroundColor = [UIColor whiteColor];
}

-(void)setCarInfo:(CarData *)carInfo{

    _carInfo=carInfo;

        self.carTypeName.text= self.carInfo.modelName;

}
- (void)drawRect:(CGRect)rect
{
//
//    // Drawing code
//    UIBezierPath *path = [UIBezierPath bezierPath];
//    // 添加路径[1条点(100,100)到点(200,100)的线段]到path
//    [path moveToPoint:CGPointMake(0 , self.contentView.bounds.size.height - 1)];
//    // x y
//    [path addLineToPoint:CGPointMake([UIScreen mainScreen].bounds.size.width, self.contentView.bounds.size.height - 1 )];
//    // 将path绘制出来
//    [UIColorFromRGBA(kTableViewSplitLineColor,1.0) setStroke];
//    //[path setLineWidth:2];
//    [path stroke];
//
//    // Drawing code
//    UIBezierPath *pathLeft = [UIBezierPath bezierPath];
//    // 添加路径[1条点(100,100)到点(200,100)的线段]到path
//    [pathLeft moveToPoint:CGPointMake(1 , 1)];
//    [pathLeft addLineToPoint:CGPointMake(0, self.contentView.bounds.size.height - 1 )];
//    // 将path绘制出来
//    [UIColorFromRGBA(kTableViewSplitLineColor,1.0) setStroke];
//    //[path setLineWidth:2];
//    [pathLeft stroke];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
<?php
namespace TYPO3\CMS\Core\Tests\Unit\Html;

use TYPO3\CMS\Core\Html\HtmlParser;

/**
 * Testcase for \TYPO3\CMS\Core\Html\HtmlParser
 */
class HtmlParserTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
{
    /**
     * @var \TYPO3\CMS\Core\Html\HtmlParser
     */
    protected $subject = null;

    protected function setUp()
    {
        $this->subject = new HtmlParser();
    }

    /**
     * @return array
     */
    public function cDataWillRemainUnmodifiedDataProvider()
    {
        return [
            'single-line CDATA' => [
                '/*<![CDATA[*/ <hello world> /*]]>*/',
                '/*<![CDATA[*/ <hello world> /*]]>*/',
            ],
            'multi-line CDATA #1' => [
                '/*<![CDATA[*/' . LF . '<hello world> /*]]>*/',
                '/*<![CDATA[*/' . LF . '<hello world> /*]]>*/',
            ],
            'multi-line CDATA #2' => [
                '/*<![CDATA[*/ <hello world>' . LF . '/*]]>*/',
                '/*<![CDATA[*/ <hello world>' . LF . '/*]]>*/',
            ],
            'multi-line CDATA #3' => [
                '/*<![CDATA[*/' . LF . '<hello world>' . LF . '/*]]>*/',
                '/*<![CDATA[*/' . LF . '<hello world>' . LF . '/*]]>*/',
            ],
        ];
    }

    /**
     * Data provider for splitIntoBlock
     *
     * @return array
     */
    public function splitIntoBlockDataProvider()
    {
        return [
            'splitBlock' => [
                'h1,span',
                '
Title
Note',
                false,
                ['',
                    '
Title
',
                    '',
                    'Note',
                    '']
            ],
            'splitBlock br' => [
                'h1,span',
                '
Title

Note
',
                false,
                ['',
                    '
Title
',
                    '
',
                    'Note',
                    '
']
            ],
            'splitBlock with attribute' => [
                'h1,span',
                '
Title
Note',
                false,
                ['',
                    '
Title
',
                    '',
                    'Note',
                    '']
            ],
            'splitBlock span with attribute' => [
                'span',
                '
Title
Note',
                false,
                ['
Title
',
                    'Note',
                    '']
            ],
            'splitBlock without extra end tags' => [
                'h1,span,div',
                '
Title
Note
',
                true,
                ['',
                    '
Title
',
                    '',
                    'Note',
                    '']
            ],
        ];
    }

    /**
     * @test
     * @param string $tag List of tags, comma separated.
     * @param string $content HTML-content
     * @param bool $eliminateExtraEndTags If set, excessive end tags are ignored - you should probably set this in most cases.
     * @param array $expected The expected result
     * @dataProvider splitIntoBlockDataProvider
     */
    public function splitIntoBlock($tag, $content, $eliminateExtraEndTags, $expected)
    {
        $this->assertSame($expected, $this->subject->splitIntoBlock($tag, $content, $eliminateExtraEndTags));
    }

    /**
     * @test
     * @param string $source
     * @param string $expected
     * @dataProvider cDataWillRemainUnmodifiedDataProvider
     */
    public function xHtmlCleaningDoesNotModifyCDATA($source, $expected)
    {
        $result = $this->subject->XHTML_clean($source);
        $this->assertSame($expected, $result);
    }

    /**
     * Data provider for spanTagCorrectlyRemovedWhenRmTagIfNoAttribIsConfigured
     */
    public static function spanTagCorrectlyRemovedWhenRmTagIfNoAttribIsConfiguredDataProvider()
    {
        return [
            'Span tag with no attrib' => [
                'text',
                'text'
            ],
            'Span tag with allowed id attrib' => [
                'text',
                'text'
            ],
            'Span tag with disallowed style attrib' => [
                'text',
                'text'
            ]
        ];
    }

    /**
     * @test
     * @param string $content
     * @param string $expectedResult
     * @dataProvider spanTagCorrectlyRemovedWhenRmTagIfNoAttribIsConfiguredDataProvider
     */
    public function tagCorrectlyRemovedWhenRmTagIfNoAttribIsConfigured($content, $expectedResult)
    {
        $tsConfig = [
            'allowTags' => 'span',
            'tags.' => [
                'span.' => [
                    'allowedAttribs' => 'id',
                    'rmTagIfNoAttrib' => 1
                ]
            ]
        ];
        $this->assertEquals($expectedResult, $this->parseConfigAndCleanHtml($tsConfig, $content));
    }

    /**
     * @test
     */
    public function rmTagIfNoAttribIsConfiguredDoesNotChangeNestingType()
    {
        $tsConfig = [
            'allowTags' => 'div,span',
            'rmTagIfNoAttrib' => 'span',
            'globalNesting' => 'div,span'
        ];
        $content = '

';
        $expectedResult = '';
        $this->assertEquals($expectedResult, $this->parseConfigAndCleanHtml($tsConfig, $content));
    }

    /**
     * Data provider for localNestingCorrectlyRemovesInvalidTags
     *
     * @return array
     */
    public static function localNestingCorrectlyRemovesInvalidTagsDataProvider()
    {
        return [
            'Valid nesting is untouched' => [
                '',
                ''
            ],
            'Valid nesting with content is untouched' => [
                'testatest1test2test3testb',
                'testatest1test2test3testb'
            ],
            'Superflous tags are removed' => [
                '',
                ''
            ],
            'Superflous tags with content are removed' => [
                'test1test2test3test4test5test6test7',
                'test1test2test3test4test5test6test7'
            ],
            'Another valid nesting test' => [
                '

',
                '

',
            ],
        ];
    }

    /**
     * @test
     * @dataProvider localNestingCorrectlyRemovesInvalidTagsDataProvider
     * @param string $content
     * @param string $expectedResult
     */
    public function localNestingCorrectlyRemovesInvalidTags($content, $expectedResult)
    {
        $tsConfig = [
            'allowTags' => 'div,span,b,i',
            'localNesting' => 'div,span,b,i',
        ];
        $this->assertEquals($expectedResult, $this->parseConfigAndCleanHtml($tsConfig, $content));
    }

    /**
     * Data provider for globalNestingCorrectlyRemovesInvalidTags
     *
     * @return array
     */
    public static function globalNestingCorrectlyRemovesInvalidTagsDataProvider()
    {
        return [
            'Valid nesting is untouched' => [
                '',
                ''
            ],
            'Valid nesting with content is untouched' => [
                'testatest1test2test3testb',
                'testatest1test2test3testb'
            ],
            'Invalid nesting is cleaned' => [
                '',
                ''
            ],
            'Invalid nesting with content is cleaned' => [
                'test1test2test3test4test5test6test7',
                'test1test2test3test4test5test6test7'
            ],
            'Another invalid nesting test' => [
                '

',
                '',
            ],
        ];
    }

    /**
     * @test
     * @dataProvider globalNestingCorrectlyRemovesInvalidTagsDataProvider
     * @param string $content
     * @param string $expectedResult
     */
    public function globalNestingCorrectlyRemovesInvalidTags($content, $expectedResult)
    {
        $tsConfig = [
            'allowTags' => 'span,div,b,i',
            'globalNesting' => 'span,div,b,i',
        ];
        $this->assertEquals($expectedResult, $this->parseConfigAndCleanHtml($tsConfig, $content));
    }

    /**
     * @return array
     */
    public function emptyTagsDataProvider()
    {
        return [
            [0 , null, false, '

', '

'],
            [1 , null, false, '

', ''],
            [1 , null, false, '
hallo
', '
hallo
'],
            [1 , null, false, '

', ''],
            [1 , null, false, '

', ''],
            [1 , 'h2', false, '

', '

'],
            [1 , 'h2, h1', false, '

', ''],
            [1 , null, false, '

', ''],
            [1 , null, false, '

', '

'],
            [1 , null, true, '

', ''],
            [1 , null, true, '

', ''],
            [1 , null, false, '
Some content

', '
Some content
'],
            [1 , null, true, '
Some content

', '
Some content
'],
            [1 , null, false, '
Some content
', '
Some content
'],
            [1 , null, true, '
Some content
', '
Some content
'],
            [1 , null, false, 'Skiplinks ', 'Skiplinks '],
            [1 , null, true, 'Skiplinks ', 'Skiplinks '],
        ];
    }

    /**
     * @test
     * @dataProvider emptyTagsDataProvider
     * @param bool $stripOn TRUE if stripping should be activated.
     * @param string $tagList Comma seperated list of tags that should be stripped.
     * @param bool $treatNonBreakingSpaceAsEmpty If TRUE   will be considered empty.
     * @param string $content The HTML code that should be modified.
     * @param string $expectedResult The expected HTML code result.
     */
    public function stripEmptyTags($stripOn, $tagList, $treatNonBreakingSpaceAsEmpty, $content, $expectedResult)
    {
        $tsConfig = [
            'keepNonMatchedTags' => 1,
            'stripEmptyTags' => $stripOn,
            'stripEmptyTags.' => [
                'tags' => $tagList,
                'treatNonBreakingSpaceAsEmpty' => $treatNonBreakingSpaceAsEmpty
            ],
        ];

        $result = $this->parseConfigAndCleanHtml($tsConfig, $content);
        $this->assertEquals($expectedResult, $result);
    }

    /**
     * Calls HTMLparserConfig() and passes the generated config to the HTMLcleaner() method on the current subject.
     *
     * @param array $tsConfig The TypoScript that should be used to generate the HTML parser config.
     * @param string $content The content that should be parsed by the HTMLcleaner.
     * @return string The parsed content.
     */
    protected function parseConfigAndCleanHtml(array $tsConfig, $content)
    {
        $config = $this->subject->HTMLparserConfig($tsConfig);
        return $this->subject->HTMLcleaner($content, $config[0], $config[1], $config[2], $config[3]);
    }

    /**
     * Data provider for getFirstTag
     *
     * @return array
     */
    public function getFirstTagDataProvider()
    {
        return [
            ['', ''],
            ['Wrapper
Some content
', ''],
            ['Something beforeWrapper
Some content
Something after', 'Something before'],
            ['Something without tag', '']
        ];
    }

    /**
     * Returns the first tag in $str
     * Actually everything from the beginning of the $str is returned, so you better make sure the tag is the first thing...
     *
     * @test
     * @dataProvider getFirstTagDataProvider
     *
     * @param string $str HTML string with tags
     * @param string $expected The expected result.
     */
    public function getFirstTag($str, $expected)
    {
        $this->assertEquals($expected, $this->subject->getFirstTag($str));
    }

    /**
     * Data provider for getFirstTagName
     *
     * @return array
     */
    public function getFirstTagNameDataProvider()
    {
        return [
            ['',
                false,
                'BODY'],
            ['',
                true,
                'body'],
            ['

',
                false,
                'DIV'],
            ['

',
                false,
                'DIV'],
            ['
',
                false,
                'BR'],
            ['',
                false,
                'IMG'],
        ];
    }

    /**
     * Returns the NAME of the first tag in $str
     *
     * @test
     * @dataProvider getFirstTagNameDataProvider
     *
     * @param string $str HTML tag (The element name MUST be separated from the attributes by a space character! Just *whitespace* will not do)
     * @param bool $preserveCase If set, then the tag is NOT converted to uppercase by case is preserved.
     * @param string $expected The expected result.
     */
    public function getFirstTagName($str, $preserveCase, $expected)
    {
        $this->assertEquals($expected, $this->subject->getFirstTagName($str, $preserveCase));
    }

    /**
     * @return array
     */
    public function removeFirstAndLastTagDataProvider()
    {
        return [
            ['Wrapper
Some content
', 'Wrapper
Some content
'],
            ['
Some content
	', '
Some content
'],
            ['Something beforeWrapper
Some content
Something after', 'Wrapper
Some content
'],
            ['Wrapper
Some content
', 'Wrapper
Some content
'],
            ['Wrapper
Some content
', 'Wrapper
Some content
'],
        ];
    }

    /**
     * Removes the first and last tag in the string
     * Anything before the first and after the last tags respectively is also removed
     *
     * @test
     * @dataProvider removeFirstAndLastTagDataProvider
     * @param string $str String to process
     * @param string $expectedResult
     */
    public function removeFirstAndLastTag($str, $expectedResult)
    {
        $this->assertEquals($expectedResult, $this->subject->removeFirstAndLastTag($str));
    }
}


text:
package org.bunkr.core.exceptions;

/**
 * Created At: 2015-12-06
 */
public class TraversalException extends BaseBunkrException
{
    public TraversalException(Throwable e)
    {
        super(e);
    }

    public TraversalException(String message, String... args)
    {
        super(message, args);
    }
}


text:
<?php

use yii\helpers\HtmlPurifier;

/* @var $this yii\web\View */
/* @var $model backend\models\PaymentMethods */

$this->title = $model->name.' '.HtmlPurifier::process('—').' Способы оплаты | '.Yii::$app->name;
$this->params['breadcrumbs'][] = ['label' => 'Способы оплаты', 'url' => ['/payment-methods']];
$this->params['breadcrumbs'][] = $model->name;

$this->params['content-block'] = $model->name;
$this->params['content-additional'] = 'Редактирование существующего типа контрагентов';
?>
<div class="payment-methods-update">
    <?= $this->render('_form', ['model' => $model,]) ?>

</div>


text:
<?php

 /**
   *
   */
require_once(__CA_LIB_DIR__.'/core/BaseRelationshipModel.php');

BaseModel::$s_ca_models_definitions['ca_sets_x_users'] = array(
 	'NAME_SINGULAR' 	=> _t('user-set assocation'),
 	'NAME_PLURAL' 		=> _t('user-set assocations'),
 	'FIELDS' 			=> array(
 		'relation_id' => array(
				'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_HIDDEN,
				'IDENTITY' => true, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
				'IS_NULL' => false,
				'DEFAULT' => '',
				'LABEL' => 'Relation id', 'DESCRIPTION' => 'Identifier for Relation'
		),
		'set_id' => array(
				'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD,
				'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
				'IS_NULL' => false,
				'DEFAULT' => '',
				'LABEL' => 'Set id', 'DESCRIPTION' => 'Identifier for Set'
		),
		'user_id' => array(
				'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD,
				'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
				'IS_NULL' => false,
				'DEFAULT' => '',
				'LABEL' => 'User id', 'DESCRIPTION' => 'Identifier for user'
		),
		'access' => array(
				'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_SELECT,
				'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
				'IS_NULL' => false,
				'DEFAULT' => 1,
				'BOUNDS_CHOICE_LIST' => array(
					_t('can read') => 1,
					_t('can edit') => 2
				),
				'LABEL' => _t('Access'), 'DESCRIPTION' => _t('Indicates user's level of access to the set. ')
		),
		'effective_date' => array(
				'FIELD_TYPE' => FT_DATERANGE, 'DISPLAY_TYPE' => DT_FIELD,
				'DISPLAY_WIDTH' => 20, 'DISPLAY_HEIGHT' => 1,
				'IS_NULL' => true,
				'DEFAULT' => '',
				'START' => 'sdatetime', 'END' => 'edatetime',
				'LABEL' => _t('Effective dates'), 'DESCRIPTION' => _t('Period of time for which this access is in effect. Leave blank if you do not wish to restrict access to a specific period of time.')
		)
 	)
);

class ca_sets_x_users extends BaseRelationshipModel {
	# ---------------------------------
	# --- Object attribute properties
	# ---------------------------------
	# Describe structure of content object's properties - eg. database fields and their
	# associated types, what modes are supported, et al.
	#

	# ------------------------------------------------------
	# --- Basic object parameters
	# ------------------------------------------------------
	# what table does this class represent?
	protected $TABLE = 'ca_sets_x_users';

	# what is the primary key of the table?
	protected $PRIMARY_KEY = 'relation_id';

	# ------------------------------------------------------
	# --- Properties used by standard editing scripts
	#
	# These class properties allow generic scripts to properly display
	# records from the table represented by this class
	#
	# ------------------------------------------------------

	# Array of fields to display in a listing of records from this table
	protected $LIST_FIELDS = array('relation_id');

	# When the list of "list fields" above contains more than one field,
	# the LIST_DELIMITER text is displayed between fields as a delimiter.
	# This is typically a comma or space, but can be any string you like
	protected $LIST_DELIMITER = ' ';

	# What you'd call a single record from this table (eg. a "person")
	protected $NAME_SINGULAR;

	# What you'd call more than one record from this table (eg. "people")
	protected $NAME_PLURAL;

	# List of fields to sort listing of records by; you can use
	# SQL 'ASC' and 'DESC' here if you like.
	protected $ORDER_BY = array('relation_id');

	# If you want to order records arbitrarily, add a numeric field to the table and place
	# its name here. The generic list scripts can then use it to order table records.
	protected $RANK = '';

	# ------------------------------------------------------
	# Hierarchical table properties
	# ------------------------------------------------------
	protected $HIERARCHY_TYPE				=	null;
	protected $HIERARCHY_LEFT_INDEX_FLD 	= 	null;
	protected $HIERARCHY_RIGHT_INDEX_FLD 	= 	null;
	protected $HIERARCHY_PARENT_ID_FLD		=	null;
	protected $HIERARCHY_DEFINITION_TABLE	=	null;
	protected $HIERARCHY_ID_FLD				=	null;
	protected $HIERARCHY_POLY_TABLE			=	null;

	# ------------------------------------------------------
	# Change logging
	# ------------------------------------------------------
	protected $UNIT_ID_FIELD = null;
	protected $LOG_CHANGES_TO_SELF = true;
	protected $LOG_CHANGES_USING_AS_SUBJECT = array(
		"FOREIGN_KEYS" => array(

		),
		"RELATED_TABLES" => array(

		)
	);

	# ------------------------------------------------------
	# --- Relationship info
	# ------------------------------------------------------
	protected $RELATIONSHIP_LEFT_TABLENAME = 'ca_sets';
	protected $RELATIONSHIP_RIGHT_TABLENAME = 'ca_users';
	protected $RELATIONSHIP_LEFT_FIELDNAME = 'set_id';
	protected $RELATIONSHIP_RIGHT_FIELDNAME = 'user_id';
	protected $RELATIONSHIP_TYPE_FIELDNAME = null;

	# ------------------------------------------------------
	# $FIELDS contains information about each field in the table. The order in which the fields
	# are listed here is the order in which they will be returned using getFields()

	protected $FIELDS;

	# ----------------------------------------
	function __construct($pn_id=null) {
		parent::__construct($pn_id);
	}
	# ----------------------------------------
}
?>


text:
#include "qcorewlanengine.h"

#include <QtNetwork/private/qbearerplugin_p.h>

#include <QtCore/qdebug.h>

#ifndef QT_NO_BEARERMANAGEMENT

QT_BEGIN_NAMESPACE

class QCoreWlanEnginePlugin : public QBearerEnginePlugin
{
public:
    QCoreWlanEnginePlugin();
    ~QCoreWlanEnginePlugin();

    QStringList keys() const;
    QBearerEngine *create(const QString &key) const;
};

QCoreWlanEnginePlugin::QCoreWlanEnginePlugin()
{
}

QCoreWlanEnginePlugin::~QCoreWlanEnginePlugin()
{
}

QStringList QCoreWlanEnginePlugin::keys() const
{
    return QStringList() << QLatin1String("corewlan");
}

QBearerEngine *QCoreWlanEnginePlugin::create(const QString &key) const
{
    if (key == QLatin1String("corewlan"))
        return new QCoreWlanEngine;
    else
        return 0;
}

Q_EXPORT_STATIC_PLUGIN(QCoreWlanEnginePlugin)
Q_EXPORT_PLUGIN2(qcorewlanbearer, QCoreWlanEnginePlugin)

QT_END_NAMESPACE

#endif // QT_NO_BEARERMANAGEMENT


text:
<Record>
<Term>Fatal Familial Insomnia</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Sleep Initiation and Maintenance Disorders</ParentTerm>
<ParentTerm>Prion Diseases</ParentTerm>
<ClassificationPath>Nervous System Diseases/Neurodegenerative Diseases/Prion Diseases/Insomnia, Fatal Familial</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Central Nervous System Infections/Prion Diseases/Insomnia, Fatal Familial</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Sleep Disorders/Dyssomnias/Sleep Disorders, Intrinsic/Sleep Initiation and Maintenance Disorders/Insomnia, Fatal Familial</ClassificationPath>
<BroaderTerm>Sleep Initiation and Maintenance Disorders</BroaderTerm>
<BroaderTerm>Central Nervous System Diseases</BroaderTerm>
<BroaderTerm>Dyssomnias</BroaderTerm>
<BroaderTerm>Insomnia, Fatal Familial</BroaderTerm>
<BroaderTerm>Neurodegenerative Diseases</BroaderTerm>
<BroaderTerm>Central Nervous System Infections</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<BroaderTerm>Sleep Disorders, Intrinsic</BroaderTerm>
<BroaderTerm>Sleep Disorders</BroaderTerm>
<BroaderTerm>Prion Diseases</BroaderTerm>
<Synonym>Fatal Familial Insomnias</Synonym>
<Synonym>Fatal Familial Insomnia</Synonym>
<Description>An autosomal dominant disorder characterized by degeneration of the THALAMUS and progressive insomnia. It is caused by a mutation in the prion protein (PRIONS).</Description>
<Source>MeSH</Source>
</Record>


text:
package vod

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// TerrorismItem is a nested struct in vod response
type TerrorismItem struct {
	Score     string `json:"Score" xml:"Score"`
	Timestamp string `json:"Timestamp" xml:"Timestamp"`
	Label     string `json:"Label" xml:"Label"`
}


text:
/** @addtogroup CMSIS
  * @{
  */

/** @addtogroup stm32mp1xx_system
  * @{
  */

/** @addtogroup STM32MP1xx_System_Private_Includes
  * @{
  */

#include "stm32mp1xx_hal.h"

/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_TypesDefinitions
  * @{
  */

/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_Defines
  * @{
  */

/************************* Miscellaneous Configuration ************************/
/*!< Uncomment the following line if you need to use external SRAM mounted
     on EVAL board as data memory  */
/* #define DATA_IN_ExtSRAM */

/*!< Uncomment the following line if you need to relocate your vector Table in
     Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET  0x00 /*!< Vector Table base offset field.
                                   This value must be a multiple of 0x400. */
/******************************************************************************/

/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_Macros
  * @{
  */

/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_Variables
  * @{
  */
  /* This variable is updated in three ways:
      1) by calling CMSIS function SystemCoreClockUpdate()
      2) each time HAL_RCC_ClockConfig() is called to configure the system clock
         frequency
         Note: If you use this function to configure the system clock;
               then there is no need to call the first functions listed above,
               since SystemCoreClock variable is updated automatically.
  */
  uint32_t SystemCoreClock = HSI_VALUE;
/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_FunctionPrototypes
  * @{
  */

#if defined (DATA_IN_ExtSRAM)
  static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */

/**
  * @}
  */

/** @addtogroup STM32MP1xx_System_Private_Functions
  * @{
  */

  /**
  * @brief  Setup the microcontroller system
  *         Initialize the FPU setting, vector table location and External memory
  *         configuration.
  * @param  None
  * @retval None
  */
void SystemInit (void)
{
  /* FPU settings ------------------------------------------------------------*/
#if defined (CORE_CM4)
  #if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
   SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2));  /* set CP10 and CP11 Full Access */
  #endif

  /* Configure the Vector Table location add offset address ------------------*/
#if defined (VECT_TAB_SRAM)
  SCB->VTOR = MCU_AHB_SRAM | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
#endif
  /* Disable all interrupts and events */
  CLEAR_REG(EXTI_C2->IMR1);
  CLEAR_REG(EXTI_C2->IMR2);
  CLEAR_REG(EXTI_C2->IMR3);
  CLEAR_REG(EXTI_C2->EMR1);
  CLEAR_REG(EXTI_C2->EMR2);
  CLEAR_REG(EXTI_C2->EMR3);
#else
#error Please #define CORE_CM4
#endif
}

/**
   * @brief Update SystemCoreClock variable according to Clock Register Values.
  *         The SystemCoreClock variable contains the core clock frequency (Hz),
  *         it can be used by the user application to setup the SysTick timer or
  *         configure other parameters.
  *
  * @note   Each time the core clock changes, this function must be called to
  *         update SystemCoreClock variable value. Otherwise, any configuration
  *         based on this variable will be incorrect.
  *
  * @note   - The system frequency computed by this function is not the real
  *           frequency in the chip. It is calculated based on the predefined
  *           constant and the selected clock source:
  *
  *           - If SYSCLK source is HSI, SystemCoreClock will contain the
  *             HSI_VALUE(*)
  *
  *           - If SYSCLK source is HSE, SystemCoreClock will contain the
  *             HSE_VALUE(**)
  *
  *           - If SYSCLK source is CSI, SystemCoreClock will contain the
  *             CSI_VALUE(***)
  *
  *           - If SYSCLK source is PLL3_P, SystemCoreClock will contain the
  *             HSI_VALUE(*) or the HSE_VALUE(*) or the CSI_VALUE(***)
  *             multiplied/divided by the PLL3 factors.
  *
  *         (*) HSI_VALUE is a constant defined in stm32mp1xx_hal_conf.h file
  *             (default value 64 MHz) but the real value may vary depending
  *             on the variations in voltage and temperature.
  *
  *         (**) HSE_VALUE is a constant defined in stm32mp1xx_hal_conf.h file
  *              (default value 24 MHz), user has to ensure that HSE_VALUE is
  *              same as the real frequency of the crystal used. Otherwise, this
  *              function may have wrong result.
  *
  *         (***) CSI_VALUE is a constant defined in stm32mp1xx_hal_conf.h file
  *              (default value 4 MHz)but the real value may vary depending
  *              on the variations in voltage and temperature.
  *
  *         - The result of this function could be not correct when using
  *           fractional value for HSE crystal.
  *
  * @param  None
  * @retval None
  */
void SystemCoreClockUpdate (void)
{
  uint32_t   pllsource, pll3m, pll3fracen;
  float fracn1, pll3vco;

  switch (RCC->MSSCKSELR & RCC_MSSCKSELR_MCUSSRC)
  {
  case 0x00:  /* HSI used as system clock source */
    SystemCoreClock = (HSI_VALUE >> (RCC->HSICFGR & RCC_HSICFGR_HSIDIV));
    break;

  case 0x01:  /* HSE used as system clock source */
    SystemCoreClock = HSE_VALUE;
    break;

  case 0x02:  /* CSI used as system clock source */
    SystemCoreClock = CSI_VALUE;
    break;

  case 0x03:  /* PLL3_P used as system clock source */
    pllsource = (RCC->RCK3SELR & RCC_RCK3SELR_PLL3SRC);
    pll3m = ((RCC->PLL3CFGR1 & RCC_PLL3CFGR1_DIVM3) >> RCC_PLL3CFGR1_DIVM3_Pos) + 1U;
    pll3fracen = (RCC->PLL3FRACR & RCC_PLL3FRACR_FRACLE) >> 16U;
    fracn1 = (float)(pll3fracen * ((RCC->PLL3FRACR & RCC_PLL3FRACR_FRACV) >> 3U));
    pll3vco = (float)((float)((RCC->PLL3CFGR1 & RCC_PLL3CFGR1_DIVN) + 1U) + (fracn1 / (float) 0x1FFF));

    if (pll3m != 0U)
    {
      switch (pllsource)
      {
        case 0x00:  /* HSI used as PLL clock source */
          pll3vco *= (float)((HSI_VALUE >> (RCC->HSICFGR & RCC_HSICFGR_HSIDIV)) / pll3m);
          break;

        case 0x01:  /* HSE used as PLL clock source */
          pll3vco *= (float)(HSE_VALUE / pll3m);
          break;

        case 0x02:  /* CSI used as PLL clock source */
          pll3vco *= (float)(CSI_VALUE / pll3m);
          break;

        case 0x03:  /* No clock source for PLL */
          pll3vco = 0;
          break;
       }
      SystemCoreClock = (uint32_t)(pll3vco/ ((float)((RCC->PLL3CFGR2 & RCC_PLL3CFGR2_DIVP) + 1U)));
    }
    else
    {
      SystemCoreClock = 0U;
    }
    break;
  }

  /* Compute mcu_ck */
  SystemCoreClock = SystemCoreClock >> (RCC->MCUDIVR & RCC_MCUDIVR_MCUDIV);
}

#ifdef DATA_IN_ExtSRAM
/**
  * @brief  Setup the external memory controller.
  *         Called in startup_stm32mp15xx.s before jump to main.
  *         This function configures the external SRAM mounted on Eval boards
  *         This SRAM will be used as program data memory (including heap and stack).
  * @param  None
  * @retval None
  */
void SystemInit_ExtMemCtl(void)
{

}
#endif /* DATA_IN_ExtSRAM */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package org.apache.aries.blueprint.plugin.handlers.blueprint.service;

import java.util.List;

public class ReferenceListInvalidInterface extends RuntimeException {
    public ReferenceListInvalidInterface(Class<?> received) {
        super("Reference list must be " + List.class.getName() + " but received " + received.getName());
    }
}


text:
package org.jglr.ns.compiler;

import java.util.*;

import org.jglr.ns.*;
import org.jglr.ns.insns.*;

public class NSFuncDef extends NSAbstractMethod {

    public static final String ROOT_ID = "$";
    private List<NSInsn> insns;

    public NSFuncDef() {
        super();
        insns = new ArrayList<NSInsn>();
    }

    public List<NSInsn> instructions() {
        return insns;
    }

    @Override
    public final void run(Stack<NSObject> vars) {
        ; // A user defined function is not allowed to directly use the values stack
    }

}