text:
import os

from flake8.api.legacy import StyleGuide
from flake8.main.application import Application

def test_flake8_conformance():
    """Test source code for flake8 conformance."""
    argv = [
        '--ignore=%s' % ','.join([
            'D100', 'D101', 'D102', 'D103', 'D104', 'D105',
            'E501']),
        '--import-order-style=google',
    ]
    style_guide = get_style_guide(argv)
    base_path = os.path.join(os.path.dirname(__file__), '..')
    paths = [
        os.path.join(base_path, 'ros_buildfarm'),
        os.path.join(base_path, 'scripts'),
        os.path.join(base_path, 'test'),
    ]
    report = style_guide.check_files(paths)
    assert report.total_errors == 0, \
        'Found %d code style warnings' % report.total_errors

def get_style_guide(argv=None):
    # this is a fork of flake8.api.legacy.get_style_guide
    # to allow passing command line argument
    application = Application()
    application.find_plugins()
    application.register_plugin_options()
    application.parse_configuration_and_cli(argv)
    application.make_formatter()
    application.make_notifier()
    application.make_guide()
    application.make_file_checker_manager()
    return StyleGuide(application)

if __name__ == '__main__':
    test_flake8_conformance()

redpajama_set_name: RedPajamaGithub


text:
@interface NSDate (ETI)

- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears;
- (NSDate *)dateByAddingDays:(NSInteger)numberOfDays;
- (NSDate *)toGlobalTime;
- (NSDate *)toLocalTime;

@end


text:
'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', function($scope, Countries) {
    $scope.allCountries = Countries.findAll();
    $scope.showDetails = function(country){
        $scope.selectedCountry = country;
    }
});


text:
package com.gentics.mesh.search.verticle.eventhandler;

import static com.gentics.mesh.search.verticle.eventhandler.EventHandler.forEvent;
import static com.gentics.mesh.search.verticle.eventhandler.Util.logElasticSearchError;
import static com.gentics.mesh.search.verticle.eventhandler.Util.toMultiMap;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.gentics.mesh.core.data.project.HibProject;
import com.gentics.mesh.core.data.role.HibRole;
import com.gentics.mesh.core.data.schema.HibMicroschema;
import com.gentics.mesh.core.data.schema.HibSchema;
import com.gentics.mesh.core.data.search.request.SearchRequest;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.rest.MeshEvent;
import com.gentics.mesh.search.verticle.MessageEvent;
import com.gentics.mesh.search.verticle.entity.MeshEntities;
import com.gentics.mesh.search.verticle.eventhandler.node.NodeContentEventHandler;
import com.gentics.mesh.search.verticle.eventhandler.node.NodeMoveEventHandler;
import com.gentics.mesh.search.verticle.eventhandler.node.NodeTagEventHandler;
import com.gentics.mesh.search.verticle.eventhandler.project.ProjectCreateEventHandler;
import com.gentics.mesh.search.verticle.eventhandler.project.ProjectDeleteEventHandler;
import com.gentics.mesh.search.verticle.eventhandler.project.ProjectUpdateEventHandler;

import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

/**
 * Maps events from mesh to elastic search requests.
 * Call {@link #handledEvents()} to get a collection of all supported events
 * Call {@link #handle(MessageEvent)} to map an event to a list of elastic search requests.
 */
@Singleton
public class MainEventHandler implements EventHandler {
	private static final Logger log = LoggerFactory.getLogger(MainEventHandler.class);

	private final EventHandlerFactory eventHandlerFactory;

	private final GroupEventHandler groupEventHandler;
	private final TagEventHandler tagEventHandler;
	private final TagFamilyEventHandler tagFamilyEventHandler;

	private final NodeContentEventHandler nodeContentEventHandler;
	private final NodeTagEventHandler nodeTagEventHandler;
	private final NodeMoveEventHandler nodeMoveEventHandler;

	private final Map<MeshEvent, List<EventHandler>> handlers;
	private final ClearEventHandler clearEventHandler;
	private final SyncEventHandler syncEventHandler;
	private final BranchEventHandler branchEventHandler;
	private final SchemaMigrationEventHandler schemaMigrationEventHandler;
	private final MicroschemaMigrationEventHandler microschemaMigrationEventHandler;
	private final PermissionChangedEventHandler permissionChangedEventHandler;
	private final GroupUserAssignmentHandler userGroupAssignmentHandler;
	private final RoleDeletedEventHandler roleDeletedEventHandler;

	private final ProjectUpdateEventHandler projectUpdateEventHandler;
	private final ProjectCreateEventHandler projectCreateEventHandler;
	private final ProjectDeleteEventHandler projectDeleteEventHandler;

	private final CheckIndicesHandler checkIndicesHandler;

	@Inject
	public MainEventHandler(SyncEventHandler syncEventHandler,
							EventHandlerFactory eventHandlerFactory,
							GroupEventHandler groupEventHandler,
							TagEventHandler tagEventHandler,
							TagFamilyEventHandler tagFamilyEventHandler,
							NodeContentEventHandler nodeContentEventHandler,
							NodeTagEventHandler nodeTagEventHandler, NodeMoveEventHandler nodeMoveEventHandler, RoleDeletedEventHandler roleDeletedEventHandler, ProjectDeleteEventHandler projectDeleteEventHandler,
							ClearEventHandler clearEventHandler,
							BranchEventHandler branchEventHandler,
							SchemaMigrationEventHandler schemaMigrationEventHandler,
							MicroschemaMigrationEventHandler microschemaMigrationEventHandler,
							PermissionChangedEventHandler permissionChangedEventHandler,
							GroupUserAssignmentHandler userGroupAssignmentHandler,
							ProjectUpdateEventHandler projectUpdateEventHandler, ProjectCreateEventHandler projectCreateEventHandler, CheckIndicesHandler checkIndicesHandler) {
		this.syncEventHandler = syncEventHandler;
		this.eventHandlerFactory = eventHandlerFactory;
		this.groupEventHandler = groupEventHandler;
		this.tagEventHandler = tagEventHandler;
		this.tagFamilyEventHandler = tagFamilyEventHandler;
		this.nodeContentEventHandler = nodeContentEventHandler;
		this.nodeTagEventHandler = nodeTagEventHandler;
		this.nodeMoveEventHandler = nodeMoveEventHandler;
		this.roleDeletedEventHandler = roleDeletedEventHandler;
		this.projectDeleteEventHandler = projectDeleteEventHandler;
		this.clearEventHandler = clearEventHandler;
		this.branchEventHandler = branchEventHandler;
		this.schemaMigrationEventHandler = schemaMigrationEventHandler;
		this.microschemaMigrationEventHandler = microschemaMigrationEventHandler;
		this.permissionChangedEventHandler = permissionChangedEventHandler;
		this.userGroupAssignmentHandler = userGroupAssignmentHandler;
		this.projectUpdateEventHandler = projectUpdateEventHandler;
		this.projectCreateEventHandler = projectCreateEventHandler;
		this.checkIndicesHandler = checkIndicesHandler;

		handlers = createHandlers();
	}

	/**
	 * Creates a map of event handlers that will be used to delegate events to the correct handler.
	 * @return
	 */
	private Map<MeshEvent, List<EventHandler>> createHandlers() {
		return Stream.of(
			syncEventHandler,
			clearEventHandler,
			forEvent(MeshEvent.SEARCH_FLUSH_REQUEST, MainEventHandler::flushRequest),
			eventHandlerFactory.createSimpleEventHandler(MeshEntities::getSchema, HibSchema.composeIndexName()),
			eventHandlerFactory.createSimpleEventHandler(MeshEntities::getMicroschema, HibMicroschema.composeIndexName()),
			eventHandlerFactory.createSimpleEventHandler(MeshEntities::getUser, HibUser.composeIndexName()),
			eventHandlerFactory.createSimpleEventHandler(MeshEntities::getRole, HibRole.composeIndexName()),
			eventHandlerFactory.createSimpleEventHandler(MeshEntities::getProject, HibProject.composeIndexName()),
			groupEventHandler,
			tagEventHandler,
			tagFamilyEventHandler,
			nodeContentEventHandler,
			nodeTagEventHandler,
			nodeMoveEventHandler,
			roleDeletedEventHandler,
			projectDeleteEventHandler,
			projectUpdateEventHandler,
			projectCreateEventHandler,
			branchEventHandler,
			schemaMigrationEventHandler,
			microschemaMigrationEventHandler,
			permissionChangedEventHandler,
			userGroupAssignmentHandler,
			checkIndicesHandler
		).collect(toMultiMap(EventHandler::handledEvents));
	}

	/**
	 * Creates a fake elasticsearch request that is not bulkable. This will cause the bulk operator to flush
	 * pending requests.
	 * @param event
	 * @return
	 */
	private static Flowable<SearchRequest> flushRequest(MessageEvent event) {
		log.info("Flush request received");
		return Flowable.just(SearchRequest.create(provider -> Completable.complete()
			.doOnComplete(() -> log.info("Flushing requests"))
		));
	}

	@Override
	public Flowable<? extends SearchRequest> handle(MessageEvent messageEvent) {
		return Flowable.fromIterable(handlers.get(messageEvent.event))
			.flatMap(handler -> handler.handle(messageEvent), 1)
			.doOnError(err -> {
				String body = messageEvent.message == null ? null : messageEvent.message.toJson();
				logElasticSearchError(err, () -> log.error("Error while handling event {} with body {}", messageEvent.event, body, err));
			});
	}

	@Override
	public Collection<MeshEvent> handledEvents() {
		return handlers.keySet();
	}
}


text:
---
layout: page
title: "About"
description: "This is sethbrin."
header-img: "img/about-bg.jpg"
---

<select onchange= "onLanChange(this.options[this.options.selectedIndex].value)">
    <option value="0" selected> 中文 Chinese </option>
    <option value="1"> 英文 English </option>
</select>

基本信息

姓名: 曾平

手机: (+86)13718484207

学历: 硕士

邮箱:13718484207@163.com

英文能力: CET6

教育背景

2014.09-2017.06 中国科学院 计算技术研究所 高性能计算研究中心 工学硕士

2010.09-2014.06 北京邮电大学 软件学院 软件工程 工学学士

实习经历

爱奇艺   广告后端  数据分析实习 2013.11 - 2014.4

    主要项目: 广告库存预估

    项目是爱奇艺广告后端库存预估系统,主要基于历史广告的曝光数和点击量等,再结合节假日,热剧等因素,对广告库存进行预估。

对原有预估方案进行优化,提高预估精确度

提出新的预估方案。

项目与竞赛获奖经历:

RNA-Seq流程优化 2015.10 – 至今

      RNA-Seq流程主要是转录组测序流程。主要负责优化流程各个步骤,优化各个步骤的线程并行方式,提高并发度,同时对热点计算函数用SIMD指令进行加速。

Cufflinks: 更改线程组织方式,增加线程池,以及任务队列,提高线程并发度。

Bwa: 对bwa中耗时的函数利用intel simd指令进行加速。

基于libpcap开发网络嗅探器 2014.10 – 2014.12

      该项目基于libpcap库,开发网络嗅探器,能够显示所捕获的局域网数据包,并且做出相应的分析和统计。主要功能:

能够监控所有网卡数据

捕获流经网卡的数据包,并利用libpcap函数库设置过滤规则。

能够对协议数据进行解析和统计

面向Stencil计算的自动调优框架的设计与实现 2013.11 – 2014.5

      该项目是本科毕业设计的论文题目,在科学计算领域中,Stencil主要集中在数值计算的求偏微分方程的数值解。它是一种非常重要的计算模式。项目针对Stencil计算抽象出一种领域专用语言,针对待优化程序,提取程序特征,然后根据数据挖掘的知识,对代码进行自动调优,获取近似最优参数。

其他主要项目

乐视9.19活动,基于J2EE开发一个小游戏后端,负责统计用户分数以及优惠券的分发(Java)  2014.9

门户网站开发 http://goo.gl/eqHRPO http://goo.gl/vsnpxA http://goo.gl/vaPMvD (PHP)

百度2015中秋h5 http://goo.gl/hPWk8u(H5)

竞赛获奖

全国大学生服务外包创新创业全国二等奖  2013.8

美国大学生数学建模大赛F奖 2013.4

全国数学建模竞赛全市一等奖 2012.10

全国高等数学竞赛全市二等奖 2011.10

专业技能

常用编程语言c/c++,曾在项目中使用过的开发语言:JAVA(J2EE), PHP, HTML, JavaScript, C#, Python, R, Shell, SQL等

常用的开发环境: Linux, Windows

了解使用redis,memcache等工具,熟悉使用mysql.

学习了操作系统、数据结构、计算机网络、计算机体系结构和计算机组成原理等计算机核心课程,对算法与数据结构有一定了解。

Basic Info

Name: Zeng Ping

Mobile: (+86)13718484207

Degree: Master

Email:  13718484207@163.com

English Skill: CET6

Education

2014.09-2017.06 | High Performance Computing | Master | Institute of Computing Technology Chinese Academy of Sciences

2010.09-2014.06 | Software engineer | Bachelor | Beijing University of Posts and Telecommunications

Internship

iQIYI, Ad backend, Data Analysis Intern, 2013.11 - 2014.4

Main Project: Ad Inventory forecast

A Project that serve for iQiYi ad inventory forecast backend system. It is based primarily on the number of impressions and clicks of the video ads, Also take holidays, hot drama and other factors in to consideration.

Optimize original forecast program and improve forecast accuracy

Propose some new forecast methods

Project & Awards:

RNA-Seq workflow optimize ,2015.10 – Present

RNA-Seq workflow mainly is transcriptsome sequencing process. It Primarily responsible for optimizing each step of the process, improving concurrency of each step, and accelerate the hot calculation function with SIMD instructions.

Cufflinks: Change the thread organization, add the thread pool and task queues to improve thread concurrency.

Bwa: Use of Intel SIMDinstructions to accelerate the time-consuming functions.

Libpcap-based network sniffer, 2014.10 – 2014.12

The project is based on libpcap library to develop network sniffer, capable of displaying the captured LAN packets, and making the appropriate analysis and statistics. The main functions:

Be able to monitor all Network cards data

Capture data packets flowing through the Network card, and can set up filtering rules to filter packages.

Be able to parse the protocol data and statistics

Design and implementation of auto tuning framework for Stencil, 2013.11 – 2014.5

A study for scientific computing. Stencil is focused on the numerical solution of the partial differential equations in numerical calculation. It is a very important mode of calculation. The project is a kind of abstract domain-specific language for the program to be optimized. First we extract the features of a stencil kernel, and use data mining methods to gain knowledge and then find the suboptimal parameters. The code is automatically tuning.

Other main projects

Letv 9.19 activities: To develop a small game backend based on J2EE, responsible for statistic scores of users and coupon distribution (Java)                                                                                2014.9

The portal website development: http://goo.gl/eqHRPO http://goo.gl/vsnpxA http://goo.gl/vaPMvD (PHP)

2015 Baidu Mid-Autumn Festival: http://goo.gl/hPWk8u(H5)

Awards

Service outsourcing innovation and entrepreneurship contest for College Students.  Recipient, Second Prize, 2013.8

Mathematical Contest In Modeling , Recipient Finalist, 2013.4

The National Mathematical Modeling Contest, Recipient, city's first prize,  2012.10

Skills:

Familiar programming Language: C/C++. Used Languages: JAVA(J2EE), PHP, HTML, JavaScript, C#, Python, R, Shell, SQL

Development environment: Linux, Windows

Used redis, memcache and other tools, familiar with mysql

Main courses: Operating System, Data Structure, Computer Network, Computer Architecture, etc

Familiar with algorithms and data structure.

<link href='/css/about.css' rel='stylesheet'>

{% if site.duoshuo_username %}

<input id="dsUser" type="hidden" value="{{site.duoshuo_username}}"  />

{% endif %}

{% if site.disqus_username %}

{% endif %}


text:
package conntrack

import (
	"os"
	"path"
	"strconv"
	"strings"
	"testing"

	"github.com/influxdata/telegraf/testutil"
	"github.com/stretchr/testify/require"
)

func restoreDflts(savedFiles, savedDirs []string) {
	dfltFiles = savedFiles
	dfltDirs = savedDirs
}

func TestNoFilesFound(t *testing.T) {
	defer restoreDflts(dfltFiles, dfltDirs)

	dfltFiles = []string{"baz.txt"}
	dfltDirs = []string{"./foo/bar"}
	c := &Conntrack{}
	acc := &testutil.Accumulator{}
	err := c.Gather(acc)

	require.EqualError(t, err, "Conntrack input failed to collect metrics. "+
		"Is the conntrack kernel module loaded?")
}

func TestDefaultsUsed(t *testing.T) {
	defer restoreDflts(dfltFiles, dfltDirs)
	tmpdir := t.TempDir()

	tmpFile, err := os.CreateTemp(tmpdir, "ip_conntrack_count")
	require.NoError(t, err)
	t.Cleanup(func() { require.NoError(t, tmpFile.Close()) })

	dfltDirs = []string{tmpdir}
	fname := path.Base(tmpFile.Name())
	dfltFiles = []string{fname}

	count := 1234321
	require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(strconv.Itoa(count)), 0660))
	c := &Conntrack{}
	acc := &testutil.Accumulator{}

	require.NoError(t, c.Gather(acc))
	acc.AssertContainsFields(t, inputName, map[string]interface{}{
		fname: float64(count)})
}

func TestConfigsUsed(t *testing.T) {
	defer restoreDflts(dfltFiles, dfltDirs)
	tmpdir := t.TempDir()

	cntFile, err := os.CreateTemp(tmpdir, "nf_conntrack_count")
	require.NoError(t, err)
	t.Cleanup(func() { require.NoError(t, cntFile.Close()) })

	maxFile, err := os.CreateTemp(tmpdir, "nf_conntrack_max")
	require.NoError(t, err)
	t.Cleanup(func() { require.NoError(t, maxFile.Close()) })

	dfltDirs = []string{tmpdir}
	cntFname := path.Base(cntFile.Name())
	maxFname := path.Base(maxFile.Name())
	dfltFiles = []string{cntFname, maxFname}

	count := 1234321
	max := 9999999
	require.NoError(t, os.WriteFile(cntFile.Name(), []byte(strconv.Itoa(count)), 0660))
	require.NoError(t, os.WriteFile(maxFile.Name(), []byte(strconv.Itoa(max)), 0660))
	c := &Conntrack{}
	acc := &testutil.Accumulator{}

	require.NoError(t, c.Gather(acc))

	fix := func(s string) string {
		return strings.Replace(s, "nf_", "ip_", 1)
	}

	acc.AssertContainsFields(t, inputName,
		map[string]interface{}{
			fix(cntFname): float64(count),
			fix(maxFname): float64(max),
		})
}


text:
package org.ofbiz.base.concurrent.test;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import org.ofbiz.base.concurrent.TTLObject;
import org.ofbiz.base.lang.ObjectWrapper;
import org.ofbiz.base.lang.SourceMonitored;

@SourceMonitored
public class SyncTTLObjectTest extends TTLObjectTest {
    public SyncTTLObjectTest(String name) {
        super(name, true);
    }

    private static class TTLStaticRegistryObject extends TTLObject<String> {
        @Override
        protected String load(String old, int serial) {
            return old;
        }
    }

    public void testTTLStaticRegistries() throws Exception {
        ObjectWrapper.ConfigurationException caught = null;
        try {
            TTLObject.getTTLForClass(TTLStaticRegistryObject.class);
        } catch (ObjectWrapper.ConfigurationException e) {
            caught = e;
        } finally {
            assertNotNull("no ttl set", caught);
        }
        TTLObject.setDefaultTTLForClass(TTLStaticRegistryObject.class, 100);
        assertEquals("ttl default", 100, TTLObject.getTTLForClass(TTLStaticRegistryObject.class));
        TTLObject.setDefaultTTLForClass(TTLStaticRegistryObject.class, 200);
        assertEquals("can't override ttl default", 100, TTLObject.getTTLForClass(TTLStaticRegistryObject.class));
        TTLObject.setTTLForClass(TTLStaticRegistryObject.class, 200);
        assertEquals("change ttl", 200, TTLObject.getTTLForClass(TTLStaticRegistryObject.class));
        TTLObject.setTTLForClass(TTLStaticRegistryObject.class, 300);
        assertEquals("change ttl", 300, TTLObject.getTTLForClass(TTLStaticRegistryObject.class));
        caught = null;
        assertTrue("default foreground", TTLObject.getForegroundForClass(TTLStaticRegistryObject.class));
        TTLObject.setDefaultForegroundForClass(TTLStaticRegistryObject.class, false);
        assertFalse("set foreground", TTLObject.getForegroundForClass(TTLStaticRegistryObject.class));
        TTLObject.setDefaultForegroundForClass(TTLStaticRegistryObject.class, true);
        assertFalse("can't override foreground", TTLObject.getForegroundForClass(TTLStaticRegistryObject.class));
        TTLObject.setForegroundForClass(TTLStaticRegistryObject.class, true);
        assertTrue("set foreground true", TTLObject.getForegroundForClass(TTLStaticRegistryObject.class));
        TTLObject.setForegroundForClass(TTLStaticRegistryObject.class, false);
        assertFalse("set foreground false", TTLObject.getForegroundForClass(TTLStaticRegistryObject.class));
        // this is only to cause coverage to be 100%
        new TTLStaticRegistryObject().getObject();
    }

    public void testRefresh() throws Exception {
        assertEquals("state:invalid", TTLObject.State.INVALID, object.getState());
        assertEquals("no dones", 0, doneCount.get());
        object.refresh();
        assertEquals("state:generate", TTLObject.State.GENERATE, object.getState());
        assertEquals("no dones", 0, doneCount.get());
        object.refresh();
        assertEquals("state:generate", TTLObject.State.GENERATE, object.getState());
        assertEquals("no dones", 0, doneCount.get());
        object.getObject();
        assertEquals("state:valid", TTLObject.State.VALID, object.getState());
        assertEquals("one done", 1, doneCount.get());
        object.getObject();
        assertEquals("state:valid", TTLObject.State.VALID, object.getState());
        assertEquals("one done", 1, doneCount.get());
        object.getObject();
        assertEquals("state:valid", TTLObject.State.VALID, object.getState());
        assertEquals("one done", 1, doneCount.get());
        object.getObject();
        assertEquals("state:valid", TTLObject.State.VALID, object.getState());
        assertEquals("one done", 1, doneCount.get());
        object.refresh();
        assertEquals("state:generate", TTLObject.State.GENERATE, object.getState());
        assertEquals("one done", 1, doneCount.get());
        object.getObject();
        assertEquals("state:valid", TTLObject.State.VALID, object.getState());
        assertEquals("two dones", 2, doneCount.get());
        object.refresh();
        assertEquals("state:generate", TTLObject.State.GENERATE, object.getState());
        assertEquals("two dones", 2, doneCount.get());
        throwException.set(new Thrower() {
            public void throwException() throws Exception {
                throw new Exception("exc1");
            }
        });
        TTLObject.ObjectException caught = null;
        try {
            object.getObject();
        } catch (TTLObject.ObjectException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertEquals("correct exception thrown", "exc1", caught.getCause().getMessage());
        }
        assertEquals("two dones", 3, doneCount.get());
        caught = null;
        try {
            object.getObject();
        } catch (TTLObject.ObjectException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertEquals("correct exception rethrown", "exc1", caught.getCause().getMessage());
        }
        object.refresh();
        assertEquals("two dones", 3, doneCount.get());
        object.getObject();
        assertEquals("two dones", 4, doneCount.get());
        object.set("one");
        assertEquals("one", "one", object.getObject());
        assertEquals("two dones", 4, doneCount.get());
        object.set("two");
        object.refresh();
        assertEquals("two", (String) null, object.getObject());
        assertEquals("two dones", 5, doneCount.get());
    }

    public void testGetTTL() throws Exception {
        Exception caught = null;
        try {
            new TTLObject<Object>() {
                @Override
                protected Object load(Object old, int serial) {
                    return old;
                }
            }.getObject();
        } catch (TTLObject.ConfigurationException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertTrue("is a ttl configuration exception", caught.getMessage().startsWith("No TTL defined for "));
        }
        new TTLObject<Object>() {
            @Override
            protected long getTTL() {
                return 1000;
            }

            @Override
            protected Object load(Object old, int serial) {
                return old;
            }
        }.getObject();
    }

    public void testGet() throws Exception {
        loadData = "1";
        sleepTime = 1000;
        assertGetObject("Fetch data first time, blocking", loadData, 1, 950000000, 1200000000);
        loadData = "2";
        sleepTime = 100;
        assertGetObject("Not called all the time", "1", 1, 0, 100000000);
        Thread.sleep(200);
        assertGetObject("Auto-refresh", "2", 2, 0, 100000000);
        loadData = "3";
        sleepTime = 200;
        object.refresh();
        assertGetObject("manual-refresh", "3", 3, 0, 100000000);
        assertGetObject("Not called all the time after manual refresh", "3", 3, 0, 100000000);
        Thread.sleep(200);
        loadData = "4";
        sleepTime = 200;
        schedule(new Callable<Void>() {
            public Void call() {
                object.refresh();
                return null;
            }
        }, 50);
        assertGetObject("Refreshed with old data", "4", 5, 0, 100000000);
        object.refresh();
        loadData = "5";
        assertGetObject("syncing after refresh", "5", 6, 0, 100000000);
        loadData = "6";
        assertGetObject("no load after refresh", "5", 6, 0, 100000000);
        TTLObject.pulseAll();
        assertGetObject("new data after pulse all", "6", 7, 0, 100000000);
    }

    public void testSetGetAbort() throws Exception {
        loadData = "1";
        sleepTime = 1000;
        Future<Void> future = setObjectDelayed(300, "override");
        assertGetObject("Fetch data first time, blocking/setting", "override", 1, 250000000, 400000000);
        assertFuture("delayed set", future, null, false, null, null);
    }

    public void testThrowException() throws Exception {
        loadData = "1";
        sleepTime = 100;
        throwException.set(new Thrower() {
            public void throwException() throws Exception {
                throw new Exception("exc1");
            }
        });
        TTLObject.ObjectException caught = null;
        try {
            assertGetObject("Fetch data first time, throw exception", "override", 1, 0, 200000000);
        } catch (TTLObject.ObjectException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertEquals("correct exception thrown", "exc1", caught.getCause().getMessage());
        }
        caught = null;
        try {
            object.getObject();
        } catch (TTLObject.ObjectException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertEquals("correct exception rethrown", "exc1", caught.getCause().getMessage());
        }
        Thread.sleep(300);
        loadData = "2";
        sleepTime = 100;
        assertGetObject("Fetch data after exception, blocked", loadData, 2, 50000000, 200000000);
        loadData = "3";
        sleepTime = 500;
        throwException.set(new Thrower() {
            public void throwException() throws Exception {
                throw new Exception("exc2");
            }
        });
        Thread.sleep(200);
        caught = null;
        try {
            assertGetObject("Fetch data second time, throw exception", "2", 2, 0, 200000000);
        } catch (TTLObject.ObjectException e) {
            caught = e;
        } finally {
            assertNotNull("exception thrown", caught);
            assertEquals("correct exception thrown", "exc2", caught.getCause().getMessage());
        }
    }
}


text:
<?php

namespace Database;

use Support\Str;
use Database\ConnectionFactory;

class DatabaseManager implements ConnectionResolverInterface
{
    /**
     * The application instance.
     *
     * @var \Foundation\Application
     */
    protected $app;

    /**
     * The database connection factory instance.
     *
     * @var \Database\ConnectionFactory
     */
    protected $factory;

    /**
     * The active connection instances.
     *
     * @var array
     */
    protected $connections = array();

    /**
     * The custom connection resolvers.
     *
     * @var array
     */
    protected $extensions = array();

    /**
     * Create a new database manager instance.
     *
     * @param  \Foundation\Application  $app
     * @param  \Database\ConnectionFactory  $factory
     * @return void
     */
    public function __construct($app, ConnectionFactory $factory)
    {
        $this->app = $app;
        $this->factory = $factory;
    }

    /**
     * Get a database connection instance.
     *
     * @param  string  $name
     * @return \Database\Connection
     */
    public function connection($name = null)
    {
        list($name, $type) = $this->parseConnectionName($name);

        if (! isset($this->connections[$name])) {
            $connection = $this->makeConnection($name);

            $this->setPdoForType($connection, $type);

            $this->connections[$name] = $this->prepare($connection);
        }

        return $this->connections[$name];
    }

    /**
     * Parse the connection into an array of the name and read / write type.
     *
     * @param  string  $name
     * @return array
     */
    protected function parseConnectionName($name)
    {
        $name = $name ?: $this->getDefaultConnection();

        return Str::endsWith($name, ['::read', '::write']) ? explode('::', $name, 2) : [$name, null];
    }

    /**
     * Disconnect from the given database and remove from local cache.
     *
     * @param  string  $name
     * @return void
     */
    public function purge($name = null)
    {
        $this->disconnect($name);

        unset($this->connections[$name]);
    }

    /**
     * Disconnect from the given database.
     *
     * @param  string  $name
     * @return void
     */
    public function disconnect($name = null)
    {
        if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) {
            $this->connections[$name]->disconnect();
        }
    }

    /**
     * Reconnect to the given database.
     *
     * @param  string  $name
     * @return \Database\Connection
     */
    public function reconnect($name = null)
    {
        $this->disconnect($name = $name ?: $this->getDefaultConnection());

        if (! isset($this->connections[$name])) {
            return $this->connection($name);
        }

        return $this->refreshPdoConnections($name);
    }

    /**
     * Refresh the PDO connections on a given connection.
     *
     * @param  string  $name
     * @return \Database\Connection
     */
    protected function refreshPdoConnections($name)
    {
        $fresh = $this->makeConnection($name);

        return $this->connections[$name]
            ->setPdo($fresh->getPdo())
            ->setReadPdo($fresh->getReadPdo());
    }

    /**
     * Make the database connection instance.
     *
     * @param  string  $name
     * @return \Database\Connection
     */
    protected function makeConnection($name)
    {
        $config = $this->getConfig($name);

        if (isset($this->extensions[$name])) {
            return call_user_func($this->extensions[$name], $config, $name);
        }

        $driver = $config['driver'];

        if (isset($this->extensions[$driver])) {
            return call_user_func($this->extensions[$driver], $config, $name);
        }

        return $this->factory->make($config, $name);
    }

    /**
     * Prepare the database connection instance.
     *
     * @param  \Database\Connection  $connection
     * @return \Database\Connection
     */
    protected function prepare(Connection $connection)
    {
        $connection->setFetchMode($this->app['config']['database.fetch']);

        if ($this->app->bound('events')) {
            $connection->setEventDispatcher($this->app['events']);
        }

        $app = $this->app;

        $connection->setCacheManager(function() use ($app)
        {
            return $app['cache'];
        });

        $connection->setPaginator(function() use ($app)
        {
            return $app['paginator'];
        });

        $connection->setReconnector(function($connection)
        {
            $this->reconnect($connection->getName());
        });

        return $connection;
    }

    /**
     * Prepare the read write mode for database connection instance.
     *
     * @param  \Database\Connection  $connection
     * @param  string  $type
     * @return \Database\Connection
     */
    protected function setPdoForType(Connection $connection, $type = null)
    {
        if ($type == 'read') {
            $connection->setPdo($connection->getReadPdo());
        } else if ($type == 'write') {
            $connection->setReadPdo($connection->getPdo());
        }

        return $connection;
    }

    /**
     * Get the configuration for a connection.
     *
     * @param  string  $name
     * @return array
     *
     * @throws \InvalidArgumentException
     */
    protected function getConfig($name)
    {
        $name = $name ?: $this->getDefaultConnection();

        //
        $connections = $this->app['config']['database.connections'];

        if (is_null($config = array_get($connections, $name))) {
            throw new \InvalidArgumentException("Database [$name] not configured.");
        }

        return $config;
    }

    /**
     * Get the default connection name.
     *
     * @return string
     */
    public function getDefaultConnection()
    {
        return $this->app['config']['database.default'];
    }

    /**
     * Set the default connection name.
     *
     * @param  string  $name
     * @return void
     */
    public function setDefaultConnection($name)
    {
        $this->app['config']['database.default'] = $name;
    }

    /**
     * Register an extension connection resolver.
     *
     * @param  string    $name
     * @param  callable  $resolver
     * @return void
     */
    public function extend($name, callable $resolver)
    {
        $this->extensions[$name] = $resolver;
    }

    /**
     * Return all of the created connections.
     *
     * @return array
     */
    public function getConnections()
    {
        return $this->connections;
    }

    /**
     * Dynamically pass methods to the default connection.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return call_user_func_array(array($this->connection(), $method), $parameters);
    }

}


text:
<?php
require_once ProjectOxford_ROOT_PATH . '/Module/Base.php';
/**
 * ProjectOxford_Module_Face
 * 云服务器模块类
 */
class ProjectOxford_Module_Face extends ProjectOxford_Module_Base
{
    /**
     * $_serverHost
     * 接口域名
     * @var string
     */
    protected $_serverHost = 'https://api.projectoxford.ai/face/v1.0/';
}


text:
package com.haulmont.cuba.web.testsupport.ui;

import com.vaadin.server.VaadinServletService;
import com.vaadin.server.VaadinSession;
import com.vaadin.server.WebBrowser;

import java.util.Locale;

public class TestVaadinSession extends VaadinSession {

    protected WebBrowser webBrowser;

    public TestVaadinSession(WebBrowser webBrowser, Locale locale) {
        super(new VaadinServletService(){});
        this.webBrowser = webBrowser;

        setLocale(locale);
    }

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

    @Override
    public WebBrowser getBrowser() {
        return webBrowser;
    }
}


text:
/**
 * Registers an event listener on an element
 * and returns a delegator.
 * A delegated event runs matches to find an event target,
 * then executes the handler paired with the matcher.
 * Matchers can check if an event target matches a given selector,
 * or see if an of its parents do.
 * */
module.exports = delegate

function delegate( options ){
  var element = options.element
    , event = options.event
    , capture = !!options.capture||false
    , context = options.context||element

  if( !element ){
    console.log("Can't delegate undefined element")
    return null
  }
  if( !event ){
    console.log("Can't delegate undefined event")
    return null
  }

  var delegator = createDelegator(context)
  element.addEventListener(event, delegator, capture)

  return delegator
}

/**
 * Returns a delegator that can be used as an event listener.
 * The delegator has static methods which can be used to register handlers.
 * */
function createDelegator( context ){
  var matchers = []

  function delegator( e ){
    var l = matchers.length
    if( !l ){
      return true
    }

    var el = this
        , i = -1
        , handler
        , selector
        , delegateElement
        , stopPropagation
        , args

    while( ++i < l ){
      args = matchers[i]
      handler = args[0]
      selector = args[1]

      delegateElement = matchCapturePath(selector, el, e)
      if( delegateElement && delegateElement.length ) {
        stopPropagation = false === handler.apply(context, [e].concat(delegateElement))
        if( stopPropagation ) {
          return false
        }
      }
    }

    return true
  }

  /**
   * Registers a handler with a target finder logic
   * */
  delegator.match = function( selector, handler ){
    matchers.push([handler, selector])
    return delegator
  }

  return delegator
}

function matchCapturePath( selector, el, e ){
  var delegateElements = []
  var delegateElement = null
  if( Array.isArray(selector) ){
    var i = -1
    var l = selector.length
    while( ++i < l ){
      delegateElement = findParent(selector[i], el, e)
      if( !delegateElement ) return null
      delegateElements.push(delegateElement)
    }
  }
  else {
    delegateElement = findParent(selector, el, e)
    if( !delegateElement ) return null
    delegateElements.push(delegateElement)
  }
  return delegateElements
}

/**
 * Check if the target or any of its parent matches a selector
 * */
function findParent( selector, el, e ){
  var target = e.target
  switch( typeof selector ){
    case "string":
      while( target && target != el ){
        if( target.matches && target.matches(selector) ) return target
        target = target.parentNode
      }
      break
    case "function":
      while( target && target != el ){
        if( selector.call(el, target) ) return target
        target = target.parentNode
      }
      break
    default:
      return null
  }
  return null
}


text:
<!DOCTYPE html>

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href='//fonts.googleapis.com/css?family=Arsenal' rel='stylesheet'>

                Erdélyi Helynévtörténeti Adattár

                és interaktív névföldrajzi atlasz

                Szabó T. Attila helynévgyűjtése alapján szerkesztette Bárth M. János


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>The Fellowship of the Ring</title>
  <link rel="stylesheet" href="./stylesheets/style.css">
</head>
<body>
  <div class="overlay">
  </div>
  <audio id="nazgul-screech" src="./media/nazgul_screech.mp3"></audio>
  <audio id="hobbit-theme" src="./media/hobbit_theme.mp3"></audio>

  <script charset="utf-8">
    var nazgulScreech = function () {
      document.getElementById("nazgul-screech").play();
    };
    var playTheme = function () {
      document.getElementById("hobbit-theme").play();
    };
    playTheme();
  </script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script src="./scripts/fellowship.js"></script>
  <scr
</body>
</html>


text:
/* $Id$ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.manifoldcf.authorities.interfaces;

import org.apache.manifoldcf.core.interfaces.*;

import java.util.*;
import java.io.*;

/** An object implementing this interface functions as a pool of authority connectors.
* Coordination and allocation among cluster members is managed within.
* These objects are thread-local, so do not share them among threads.
*/
public interface IAuthorityConnectorPool
{
  public static final String _rcsid = "@(#)$Id$";

  /** Get multiple authority connectors, all at once.  Do this in a particular order
  * so that any connector exhaustion will not cause a deadlock.
  *@param orderingKeys are the keys which determine in what order the connectors are obtained.
  *@param authorityConnections are the connections to use the build the connector instances.
  */
  public IAuthorityConnector[] grabMultiple(String[] orderingKeys, IAuthorityConnection[] authorityConnections)
    throws ManifoldCFException;

  /** Get an authority connector.
  * The connector is specified by an authority connection object.
  *@param authorityConnection is the authority connection to base the connector instance on.
  */
  public IAuthorityConnector grab(IAuthorityConnection authorityConnection)
    throws ManifoldCFException;

  /** Release multiple authority connectors.
  *@param connections are the connections describing the instances to release.
  *@param connectors are the connector instances to release.
  */
  public void releaseMultiple(IAuthorityConnection[] connections, IAuthorityConnector[] connectors)
    throws ManifoldCFException;

  /** Release an authority connector.
  *@param connection is the connection describing the instance to release.
  *@param connector is the connector to release.
  */
  public void release(IAuthorityConnection connection, IAuthorityConnector connector)
    throws ManifoldCFException;

  /** Idle notification for inactive authority connector handles.
  * This method polls all inactive handles.
  */
  public void pollAllConnectors()
    throws ManifoldCFException;

  /** Flush only those connector handles that are currently unused.
  */
  public void flushUnusedConnectors()
    throws ManifoldCFException;

  /** Clean up all open authority connector handles.
  * This method is called when the connector pool needs to be flushed,
  * to free resources.
  */
  public void closeAllConnectors()
    throws ManifoldCFException;

}


text:
WebInspector.FontView = function(resource)
{
    WebInspector.ResourceView.call(this, resource);

    this.element.addStyleClass("font");
}

WebInspector.FontView.prototype = {
    hasContent: function()
    {
        return true;
    },

    _createContentIfNeeded: function()
    {
        if (this.fontPreviewElement)
            return;

        var uniqueFontName = "WebInspectorFontPreview" + this.resource.identifier;

        this.fontStyleElement = document.createElement("style");
        this.fontStyleElement.textContent = "@font-face { font-family: \"" + uniqueFontName + "\"; src: url(" + this.resource.url + "); }";
        document.head.appendChild(this.fontStyleElement);

        this.fontPreviewElement = document.createElement("div");
        this.element.appendChild(this.fontPreviewElement);

        this.fontPreviewElement.style.setProperty("font-family", uniqueFontName, null);
        this.fontPreviewElement.innerHTML = "ABCDEFGHIJKLM
NOPQRSTUVWXYZ
abcdefghijklm
nopqrstuvwxyz
1234567890";
        this._lineCount = this.fontPreviewElement.getElementsByTagName("br").length + 1;

        this.updateFontPreviewSize();
    },

    show: function(parentElement)
    {
        WebInspector.ResourceView.prototype.show.call(this, parentElement);
        this._createContentIfNeeded();
        this.updateFontPreviewSize();
    },

    resize: function()
    {
        this.updateFontPreviewSize();
        WebInspector.ResourceView.prototype.resize.call(this);
    },

    updateFontPreviewSize: function()
    {
        if (!this.fontPreviewElement || !this.visible)
            return;

        var measureFontSize = 50;
        this.fontPreviewElement.style.setProperty("font-size", measureFontSize + "px", null);
        this.fontPreviewElement.style.setProperty("position", "absolute", null);
        this.fontPreviewElement.style.removeProperty("height");

        var height = this.fontPreviewElement.offsetHeight;
        var width = this.fontPreviewElement.offsetWidth;

        // Subtract some padding. This should match the padding in the CSS plus room for the scrollbar.
        var containerWidth = this.element.offsetWidth - 50;

        if (!height || !width || !containerWidth) {
            this.fontPreviewElement.style.removeProperty("font-size");
            this.fontPreviewElement.style.removeProperty("position");
            return;
        }

        var realLineHeight = Math.floor(height / this._lineCount);
        var fontSizeLineRatio = measureFontSize / realLineHeight;
        var widthRatio = containerWidth / width;
        var finalFontSize = Math.floor(realLineHeight * widthRatio * fontSizeLineRatio) - 2;

        this.fontPreviewElement.style.setProperty("font-size", finalFontSize + "px", null);
        this.fontPreviewElement.style.setProperty("height", this.fontPreviewElement.offsetHeight + "px", null);
        this.fontPreviewElement.style.removeProperty("position");
    }
}

WebInspector.FontView.prototype.__proto__ = WebInspector.ResourceView.prototype;


text:
package org.apache.flume.source;

import com.google.common.base.Charsets;
import org.apache.flume.Channel;
import org.apache.flume.ChannelSelector;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.Transaction;
import org.apache.flume.channel.ChannelProcessor;
import org.apache.flume.channel.MemoryChannel;
import org.apache.flume.channel.ReplicatingChannelSelector;
import org.apache.flume.conf.Configurables;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class TestSyslogTcpSource {
  private static final org.slf4j.Logger logger =
      LoggerFactory.getLogger(TestSyslogTcpSource.class);
  private SyslogTcpSource source;
  private Channel channel;
  private static final int TEST_SYSLOG_PORT = 0;
  private final DateTime time = new DateTime();
  private final String stamp1 = time.toString();
  private final String host1 = "localhost.localdomain";
  private final String data1 = "test syslog data";
  private final String bodyWithHostname = host1 + " " +
      data1;
  private final String bodyWithTimestamp = stamp1 + " " +
      data1;
  private final String bodyWithTandH = "<10>" + stamp1 + " " + host1 + " " +
      data1 + "\n";

  private void init(String keepFields) {
    source = new SyslogTcpSource();
    channel = new MemoryChannel();

    Configurables.configure(channel, new Context());

    List<Channel> channels = new ArrayList<>();
    channels.add(channel);

    ChannelSelector rcs = new ReplicatingChannelSelector();
    rcs.setChannels(channels);

    source.setChannelProcessor(new ChannelProcessor(rcs));
    Context context = new Context();
    context.put("port", String.valueOf(TEST_SYSLOG_PORT));
    context.put("keepFields", keepFields);

    source.configure(context);

  }
  /** Tests the keepFields configuration parameter (enabled or disabled)
   using SyslogTcpSource.*/
  private void runKeepFieldsTest(String keepFields) throws IOException {
    init(keepFields);
    source.start();
    // Write some message to the syslog port
    InetSocketAddress addr = source.getBoundAddress();
    for (int i = 0; i < 10 ; i++) {
      try (Socket syslogSocket = new Socket(addr.getAddress(), addr.getPort())) {
        syslogSocket.getOutputStream().write(bodyWithTandH.getBytes());
      }
    }

    List<Event> channelEvents = new ArrayList<>();
    Transaction txn = channel.getTransaction();
    txn.begin();
    for (int i = 0; i < 10; i++) {
      Event e = channel.take();
      if (e == null) {
        throw new NullPointerException("Event is null");
      }
      channelEvents.add(e);
    }

    try {
      txn.commit();
    } catch (Throwable t) {
      txn.rollback();
    } finally {
      txn.close();
    }

    source.stop();
    for (Event e : channelEvents) {
      Assert.assertNotNull(e);
      String str = new String(e.getBody(), Charsets.UTF_8);
      logger.info(str);
      if (keepFields.equals("true") || keepFields.equals("all")) {
        Assert.assertArrayEquals(bodyWithTandH.trim().getBytes(),
            e.getBody());
      } else if (keepFields.equals("false") || keepFields.equals("none")) {
        Assert.assertArrayEquals(data1.getBytes(), e.getBody());
      } else if (keepFields.equals("hostname")) {
        Assert.assertArrayEquals(bodyWithHostname.getBytes(), e.getBody());
      } else if (keepFields.equals("timestamp")) {
        Assert.assertArrayEquals(bodyWithTimestamp.getBytes(), e.getBody());
      }
    }
  }

  @Test
  public void testKeepFields() throws IOException {
    runKeepFieldsTest("all");

    // Backwards compatibility
    runKeepFieldsTest("true");
  }

  @Test
  public void testRemoveFields() throws IOException {
    runKeepFieldsTest("none");

    // Backwards compatibility
    runKeepFieldsTest("false");
  }

  @Test
  public void testKeepHostname() throws IOException {
    runKeepFieldsTest("hostname");
  }

  @Test
  public void testKeepTimestamp() throws IOException {
    runKeepFieldsTest("timestamp");
  }

  @Test
  public void testSourceCounter() throws IOException {
    runKeepFieldsTest("all");
    Assert.assertEquals(10, source.getSourceCounter().getEventAcceptedCount());
    Assert.assertEquals(10, source.getSourceCounter().getEventReceivedCount());
  }
}


text:
#include <jni.h>
#include <stdio.h>
#include "ssw.h"

jstring s_align_cigar_to_jstring(JNIEnv* env, s_align* align) {
	jstring jstrBuf = NULL;
	if (align->cigar != NULL && align->cigarLen > 0) {
		char* buffer = (char *)malloc(16 * align->cigarLen + 1);
		buffer[0] = '\0';
		char* currentBufferPosition = buffer;
		int i;
		for (i = 0; i < align->cigarLen; i++) {
			int charsPrinted = sprintf(currentBufferPosition, "%d%c", cigar_int_to_len(align->cigar[i]), cigar_int_to_op(align->cigar[i]));
			currentBufferPosition += charsPrinted;
		}
		jstrBuf = (*env)->NewStringUTF(env, buffer);
		free(buffer);
	}
	return jstrBuf;
}
jobject s_align_to_ssw_Alignment(JNIEnv* env, s_align* align) {
	if (align == NULL) return NULL;
	jclass clazz = (*env)->FindClass(env, "ssw/Alignment");
	jmethodID constructor = (*env)->GetMethodID(env, clazz, "<init>", "(SSIIIIILjava/lang/String;)V");
	jobject result = (*env)->NewObject(env, clazz, constructor,
		align->score1,
		align->score2,
		align->ref_begin1,
		align->ref_end1,
		align->read_begin1,
		align->read_end1,
		align->ref_end2,
		s_align_cigar_to_jstring(env, align));
	return result;
}
JNIEXPORT jobject JNICALL Java_ssw_Aligner_align(JNIEnv* env, jclass cls,
		jbyteArray read, jbyteArray matrix, jint matrixSize, jint score_size,
		jbyteArray ref,
		jint gapOpen,
		jint gapExtend,
		jint flag,
		jshort filters,
		jint filterd,
		jint maskLen) {
	jbyte* readPtr = (*env)->GetByteArrayElements(env, read, NULL);
	jsize readLen = (*env)->GetArrayLength(env, read);
	jbyte* matrixPtr = (*env)->GetByteArrayElements(env, matrix, NULL);
	/*jsize matrixLen = (*env)->GetArrayLength(env, matrix);*/
	jbyte* refPtr = (*env)->GetByteArrayElements(env, ref, NULL);
	jsize refLen = (*env)->GetArrayLength(env, ref);
	s_profile* profile = ssw_init(readPtr, readLen, matrixPtr, matrixSize, (int8_t)score_size);
	s_align* align = ssw_align(profile, refPtr, refLen, gapOpen, gapExtend, flag, filters, filterd, maskLen);
	jobject jalignment = s_align_to_ssw_Alignment(env, align);
	align_destroy(align);
	init_destroy(profile);
	(*env)->ReleaseByteArrayElements(env, read, readPtr, JNI_ABORT);
	(*env)->ReleaseByteArrayElements(env, matrix, matrixPtr, JNI_ABORT);
	(*env)->ReleaseByteArrayElements(env, ref, refPtr, JNI_ABORT);
	return jalignment;
}


text:
<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

  WORLD OF 10th GRADE HUMANITIES

Course Overview

                  Welcome to 10th grade Language Arts, where much of the material corresponds to what you learn in European History.
                  Each Unit unit features a writing assigment of some sort along with reflection, as well as occasional art projects from time to time.
                  Additionally, there is a End of Semester Portfolio at the end of each semester, where you compile all the essays/reflections
                  from said semester into one portfolio along with a semester evaluation/reflection. So expect a lot of writing in this class!
                  Other than that, a couple of books are assigned at times and sometimes there's even the luxury of movies. Generally, if
                  you pay attention and turn all your work in on time, this class should be a breeze.

Syllabus

                  Topic
                  Description

 Ancient Greece

                    The first unit of the class, the stories you can expect to read are "The Iliad", featuring the perspectives of Achilles and
                    Hecter respectively, as well as several of Aesops Fables. There's two essays for the Iliad and the main themes to look out
                    for are characteristics of communities, consequences for dissenters who don't conform and how opposing forces are
                    highlighted in a community by the author.

 Medieval Era

                    The second unit of the class features stories including: "Lais of the Werewolf", featuring a man turned
                    Bisclarvet/uncivilized, and several portions from "Le Morte d'Arthur" which feature the destruction of everything
                    due to the lack of chivalry. The essay for both stories is pretty hefty so look out for common themes in both, such as
                    common Chivalric values highlighted or behavior disapporoved traditionally.

 Reformation

                    The third unit of the class features the stories "Don Quixote" which is about an old man who tries to revive chivalrous
                    values of the past and "Macbeth" which is about a soldier who tried to become king due to what he heard from 3 witches.
                    Both films feature in class movies and for the "Macbeth" essay, watch out for any themes and lessons highlighted by
                    Shakespeare throughout the book.

 Romantic Era

                    The fourth unit of the class features several Poems by William Wordsworth, Taylor Coleridge, Lord Byron, etc as well as
                    a movie on Jane Austen's novel, "Emma". For the poems, just remember to fill out the packets when needed and for the movie
                    "Emma" make sure to pay attention to character action and take notes if needed as there will be a seminar afterwards on
                    values brought up in the movie.

 Victorian Era

                    The fifth unit of the class features several Sherlock Holmes stories by Arthur Conan Doyle as well as the play/movie
                    "The Importance of being Earnest" by Oscar Wilde. You will be reading the Sherlock Holmes stories in groups though
                    the project can be individual or group and involves creating a video, game, poster, etc on one of the stories. As for "The
                    Importance of being Earnest" pay attention to how Oscar Wilde mocks or highlights certain aspects of Victorian Era society
                    for the essay afterwards.

 Modern Era

                    The sixth and final unit of the class features "Lord of the Flies" a book about how a group of boys stranded on an island turn
                    savage over time. Make sure to fill out all worksheets given to you and read each chapter carefully so that you can can choose a
                    theme that occurs throughout the book and write about it in the essay, such as the symbol of the conch. Additionally there will be
                    an episode of the "Twilight Zone" to correspond to the gang mentality/savageness shown in the book and a seminar afterwards on
                    questions on the book so make sure to READ THE BOOK!

General Tips/Advice

When available, take the honors assignments. Its worth it!

Your essay's thesis should be at the end of the introductory paragraph and supported throughout
                  the essay.

On the topic of essays, don't just list too much evidence. Elaboration of said evidence is key!

Finally the conclusion should connect to Modern Society, not just restate everything in the introduction.

For the DRP and SBAC in the year, take your time and make sure to get enough sleep for those tests!

Talk to Mr. Maher, he's an awesome teacher and a cool guy if you get to know him.
                  But remember, teachers are people too so don't bother him with late work, especially near the end of the school year!

 For additional information/help on a certain unit or if you are in PSA and
                  are for some reason here anyway, you can visit Mr. Maher's website
                   World of Maher.


text:
include(hunter_add_version)
include(hunter_download)
include(hunter_pick_scheme)

hunter_add_version(
    PACKAGE_NAME
    Android-Modules
    VERSION
    "1.0.0"
    URL
    "https://github.com/hunter-packages/android-cmake/archive/v1.0.0.tar.gz"
    SHA1
    3ff05bdfc3d1ed24194922954ddbc9482cd7273b
)

hunter_pick_scheme(DEFAULT url_sha1_unpack)
hunter_download(PACKAGE_NAME Android-Modules)


text:
module.exports = {
  conditions: [''],
  name: 'BitwiseANDExpression',
  rules: [
    'EqualityExpression',
    'BitwiseANDExpression & EqualityExpression',
  ],
  handlers: [
    '$$ = $1;',
    '$$ = new (require(\'./ast/BitwiseExpression\').BitwiseANDExpressionNode)($2, $1, $3, { loc: this._$, yy })',
  ],
  subRules: [
    require('./EqualityExpression'),
  ],
};


text:
#include "Canvas.h"
#include "Picture.h"

#include "SkStream.h"

namespace android {

Picture::Picture(const Picture* src) {
    if (NULL != src) {
        mWidth = src->width();
        mHeight = src->height();
        if (NULL != src->mPicture.get()) {
            mPicture.reset(SkRef(src->mPicture.get()));
        } else if (NULL != src->mRecorder.get()) {
            mPicture.reset(src->makePartialCopy());
        }
        validate();
    } else {
        mWidth = 0;
        mHeight = 0;
    }
}

Canvas* Picture::beginRecording(int width, int height) {
    mPicture.reset(NULL);
    mRecorder.reset(new SkPictureRecorder);
    mWidth = width;
    mHeight = height;
    SkCanvas* canvas = mRecorder->beginRecording(width, height, NULL, 0);
    return Canvas::create_canvas(canvas);
}

void Picture::endRecording() {
    if (NULL != mRecorder.get()) {
        mPicture.reset(mRecorder->endRecording());
        validate();
        mRecorder.reset(NULL);
    }
}

int Picture::width() const {
    validate();
    return mWidth;
}

int Picture::height() const {
    validate();
    return mHeight;
}

Picture* Picture::CreateFromStream(SkStream* stream) {
    Picture* newPict = new Picture;

    SkPicture* skPicture = SkPicture::CreateFromStream(stream);
    if (NULL != skPicture) {
        newPict->mPicture.reset(skPicture);

        const SkIRect cullRect = skPicture->cullRect().roundOut();
        newPict->mWidth = cullRect.width();
        newPict->mHeight = cullRect.height();
    }

    return newPict;
}

void Picture::serialize(SkWStream* stream) const {
    if (NULL != mRecorder.get()) {
        SkAutoTDelete<SkPicture> tempPict(this->makePartialCopy());
        tempPict->serialize(stream);
    } else if (NULL != mPicture.get()) {
        validate();
        mPicture->serialize(stream);
    } else {
        SkPictureRecorder recorder;
        recorder.beginRecording(0, 0);
        SkAutoTUnref<SkPicture> empty(recorder.endRecording());
        empty->serialize(stream);
    }
}

void Picture::draw(Canvas* canvas) {
    if (NULL != mRecorder.get()) {
        this->endRecording();
        SkASSERT(NULL != mPicture.get());
    }
    validate();
    if (NULL != mPicture.get()) {
        mPicture.get()->playback(canvas->asSkCanvas());
    }
}

SkPicture* Picture::makePartialCopy() const {
    SkASSERT(NULL != mRecorder.get());

    SkPictureRecorder reRecorder;

    SkCanvas* canvas = reRecorder.beginRecording(mWidth, mHeight, NULL, 0);
    mRecorder->partialReplay(canvas);
    return reRecorder.endRecording();
}

void Picture::validate() const {
#ifdef SK_DEBUG
    if (NULL != mPicture.get()) {
        SkRect cullRect = mPicture->cullRect();
        SkRect myRect = SkRect::MakeWH(SkIntToScalar(mWidth), SkIntToScalar(mHeight));
        SkASSERT(cullRect == myRect);
    }
#endif
}

}; // namespace android


text:
using System;
using System.Collections.Generic;

namespace Potato.Core.Shared {
    /// <summary>
    /// Command to be executed
    /// </summary>
    /// <remarks><para>Called to execute a command.</para></remarks>
    [Serializable]
    public sealed class CommandDispatch : ICommandDispatch {
        public String Name { get; set; }

        public CommandType CommandType {
            get { return this._mCommandType; }
            set {
                this._mCommandType = value;

                if (this._mCommandType != CommandType.None) {
                    this.Name = value.ToString();
                }
            }
        }
        private CommandType _mCommandType;

        public CommandAttributeType CommandAttributeType { get; set; }

        public List<CommandParameterType> ParameterTypes { get; set; }

        public Func<ICommand, Dictionary<String, ICommandParameter>, ICommandResult> Handler { get; set; }

        /// <summary>
        /// Initializes the dispatch with default values.
        /// </summary>
        public CommandDispatch() {
            this.CommandAttributeType = CommandAttributeType.Handler;
        }

        /// <summary>
        /// Parses a command type from an enum if it is valid.
        /// </summary>
        /// <param name="commandName"></param>
        public ICommandDispatch ParseCommandType(String commandName) {
            if (Enum.IsDefined(typeof(CommandType), commandName)) {
                this.CommandType = (CommandType)Enum.Parse(typeof(CommandType), commandName);
            }
            else {
                this.Name = commandName;
            }

            return this;
        }

        public bool CanDispatch(CommandAttributeType attributeType, ICommand command) {
            return this.CommandAttributeType == attributeType && this.Name == command.Name;
        }

        public Dictionary<String, ICommandParameter> BuildParameterDictionary(IList<ICommandParameter> parameters) {
            Dictionary<String, ICommandParameter> parameterDictionary = new Dictionary<String, ICommandParameter>();

            // If we're not expecting any parameters
            if (this.ParameterTypes != null) {
                if (parameters != null && this.ParameterTypes.Count == parameters.Count) {
                    for (int offset = 0; offset < this.ParameterTypes.Count && parameterDictionary != null; offset++) {

                        if (this.ParameterTypes[offset].IsList == true) {
                            if (parameters[offset].HasMany(this.ParameterTypes[offset].Type, this.ParameterTypes[offset].IsConvertable) == true) {
                                parameterDictionary.Add(this.ParameterTypes[offset].Name, parameters[offset]);
                            }
                            else {
                                // Parameter type mismatch. Return null.
                                parameterDictionary = null;
                            }
                        }
                        else {
                            if (parameters[offset].HasOne(this.ParameterTypes[offset].Type, this.ParameterTypes[offset].IsConvertable) == true) {
                                parameterDictionary.Add(this.ParameterTypes[offset].Name, parameters[offset]);
                            }
                            else {
                                // Parameter type mismatch. Return null.
                                parameterDictionary = null;
                            }
                        }
                    }
                }
                else {
                    // Parameter count mismatch. Return null.
                    parameterDictionary = null;
                }
            }

            return parameterDictionary;
        }
    }
}


text:
module Basket
  # Standard item
  class Item

    attr_accessor :amount, :name, :price, :price_gross, :tax

    EXEMPT_LIST = %w(book chocolate pill)

    def initialize(amount, name, price)
      @amount = amount
      @name = name
      @price = price
    end

    def self.for(*args)
      klass = is_exemp?(*args[1]) ? ExemptItem : Item
      klass.new *args
    end

    def self.is_exemp?(product_name)
      EXEMPT_LIST.find do |root|
        product_name.include?(root)
      end
    end

    def sales_tax
      10.0
    end

    def tax
      raw_tax = (@amount * @price * ((sales_tax + import_tax) / 100))
      # round to nearest 0.05
      (raw_tax * 20).ceil / 20.0
    end

    def price_gross
      (@price + tax).round(2)
    end

    def import_tax
      imported? ? 5.0 : 0.0
    end

    def imported?
      @name.include?("imported ")
    end
  end
end


text:
package org.metaborg.spoofax.core.esv;

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

import javax.annotation.Nullable;

import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;

import com.google.common.collect.Lists;
import org.spoofax.terms.util.TermUtils;

/**
 * Term reading utility class for ESV abstract syntax.
 */
public class ESVReader {
    public static IStrategoAppl findTerm(IStrategoTerm term, String constructor) {
        if(TermUtils.isAppl(term) && cons(term).equals(constructor))
            return (IStrategoAppl) term;

        IStrategoTerm[] subterms = term.getAllSubterms();
        for(int i = subterms.length - 1; i >= 0; i--) {
            IStrategoAppl result = findTerm(subterms[i], constructor);
            if(result != null)
                return result;
        }

        return null;
    }

    public static ArrayList<IStrategoAppl> collectTerms(IStrategoAppl term, String... constructors) {
        ArrayList<IStrategoAppl> results = new ArrayList<>();
        for(String constructor : constructors) {
            collectTerms(term, constructor, results);
        }
        return results;
    }

    private static void collectTerms(IStrategoTerm term, String constructor, ArrayList<IStrategoAppl> results) {
        if(TermUtils.isAppl(term) && cons(term).equals(constructor))
            results.add((IStrategoAppl) term);

        // TODO: optimize: use TermVisitor, avoid indexed access to long lists
        for(int i = 0; i < term.getSubtermCount(); i++) {
            collectTerms(term.getSubterm(i), constructor, results);
        }
    }

    @Nullable
    public static String termContents(IStrategoTerm t) {
        if(t == null)
            return null;

        String result;

        if(TermUtils.isString(t)) {
            result = TermUtils.toJavaString(t);
        } else if(TermUtils.isAppl(t, "Values", 1)) {
            return concatTermStrings(TermUtils.toListAt(t, 0));
        } else if(TermUtils.isAppl(t, null, 1) && TermUtils.isStringAt(t, 0)) {
            result = TermUtils.toJavaStringAt(t, 0);
        } else if(TermUtils.isAppl(t, null, 1)) {
            return termContents(t.getSubterm(0));
        } else {
            return null;
        }

        if(result.startsWith("\"") && result.endsWith("\"") && result.length() > 1)
            result = result.substring(1, result.length() - 1).replace("\\\\", "\"");

        return result;
    }

    @Nullable
    public static List<String> termListContents(IStrategoTerm t) {
        if(t == null)
            return null;

        List<String> results = Lists.newArrayList();

        if(TermUtils.isAppl(t, "Values", 1)) {
            IStrategoList values = TermUtils.toListAt(t, 0);
            for(int i = 0; i < values.getSubtermCount(); i++) {
                results.add(termContents(values.getSubterm(i)));
            }
        } else {
            return null;
        }

        return results;
    }

    public static String getProperty(IStrategoAppl document, String name) {
        return getProperty(document, name, null);
    }

    public static String getProperty(IStrategoAppl document, String name, String defaultValue) {
        IStrategoAppl result = findTerm(document, name);
        if(result == null)
            return defaultValue;

        return termContents(result);
    }

    public static String concatTermStrings(IStrategoList values) {
        StringBuilder results = new StringBuilder();

        if(values.getSubtermCount() > 0)
            results.append(termContents(values.getSubterm(0)));

        for(int i = 1; i < values.getSubtermCount(); i++) {
            results.append(',');
            results.append(termContents(values.getSubterm(i)));
        }
        return results.toString();
    }

    public static String cons(IStrategoTerm t) {
        if(!TermUtils.isAppl(t))
            return null;
        return ((IStrategoAppl) t).getConstructor().getName();
    }
}


text:
#pragma once
#include <aws/wisdom/ConnectWisdomService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ConnectWisdomService
{
namespace Model
{

  /**
   *
The data that is input into Wisdom as a result of the assistant
   * association.

See Also:
   AWS
   * API Reference

   */
  class AWS_CONNECTWISDOMSERVICE_API AssistantAssociationInputData
  {
  public:
    AssistantAssociationInputData();
    AssistantAssociationInputData(Aws::Utils::Json::JsonView jsonValue);
    AssistantAssociationInputData& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The identifier of the knowledge base.

     */
    inline const Aws::String& GetKnowledgeBaseId() const{ return m_knowledgeBaseId; }

    /**
     *
The identifier of the knowledge base.

     */
    inline bool KnowledgeBaseIdHasBeenSet() const { return m_knowledgeBaseIdHasBeenSet; }

    /**
     *
The identifier of the knowledge base.

     */
    inline void SetKnowledgeBaseId(const Aws::String& value) { m_knowledgeBaseIdHasBeenSet = true; m_knowledgeBaseId = value; }

    /**
     *
The identifier of the knowledge base.

     */
    inline void SetKnowledgeBaseId(Aws::String&& value) { m_knowledgeBaseIdHasBeenSet = true; m_knowledgeBaseId = std::move(value); }

    /**
     *
The identifier of the knowledge base.

     */
    inline void SetKnowledgeBaseId(const char* value) { m_knowledgeBaseIdHasBeenSet = true; m_knowledgeBaseId.assign(value); }

    /**
     *
The identifier of the knowledge base.

     */
    inline AssistantAssociationInputData& WithKnowledgeBaseId(const Aws::String& value) { SetKnowledgeBaseId(value); return *this;}

    /**
     *
The identifier of the knowledge base.

     */
    inline AssistantAssociationInputData& WithKnowledgeBaseId(Aws::String&& value) { SetKnowledgeBaseId(std::move(value)); return *this;}

    /**
     *
The identifier of the knowledge base.

     */
    inline AssistantAssociationInputData& WithKnowledgeBaseId(const char* value) { SetKnowledgeBaseId(value); return *this;}

  private:

    Aws::String m_knowledgeBaseId;
    bool m_knowledgeBaseIdHasBeenSet = false;
  };

} // namespace Model
} // namespace ConnectWisdomService
} // namespace Aws


text:
var Codebot = Codebot || {};
Codebot.UI = Codebot.UI || {};

/**
 * [function description]
 */
Codebot.UI.SlideTray = function() {
    var mCodebot,
        mId,
        mStack,
        mOpen;
};

Codebot.UI.SlideTray.prototype.getSlideDuration = function() {
    var aSettings = mCodebot.settings.get().ui;
    return aSettings.slidePanelAnimation ? aSettings.slidePanelAnimationDuration : 5;
};

Codebot.UI.SlideTray.prototype.transform3d = function(theElementId, theX, theY, theZ) {
	document.getElementById(theElementId).style.WebkitTransform = 'translate3d('+ theX +','+ theY +','+ theZ +')';
};

Codebot.UI.SlideTray.prototype.slideElement = function(theId, theX, theDuration) {
    $('#' + theId).css({
        '-webkit-transition': 'all ' + (theDuration || this.getSlideDuration()) + 'ms',
        '-webkit-transform': 'translate3d('+theX+'px, 0px, 0px)'
    });
};

Codebot.UI.SlideTray.prototype.clear = function(theCallback, theCallbackContext) {
    this.close(function() {
        for(var i = 0; i < mStack.length; i++) {
            mStack[i].onDestroy();
            mStack[i].container.remove();
        }
        mStack.splice(0);

        $('#config-dialog').empty();

        if(theCallback) {
            theCallback.call(theCallbackContext || this);
        }
    }, this);
};

Codebot.UI.SlideTray.prototype.getSliderPanelWidth = function() {
    return $('#config-dialog').width();
};

Codebot.UI.SlideTray.prototype.restorePersistentPanelData = function(thePanel) {
    var aPlugin,
        aData,
        aProp;

    // Has the panel asked for persistent data handling?
    if(thePanel && thePanel.dataManager) {
        // Yep! Let's get the plugin that is storing the
        // data for this panel, get the data from it and
        // restore everything.
        aPlugin = mCodebot.plugins.get(thePanel.dataManager);
        aData   = aPlugin && aPlugin.getPanelData ? aPlugin.getPanelData(thePanel) : null;

        // Do we have any data to restore?
        if(aData) {
            thePanel.restore(aData);

            // Emit some debug message so it's easier to track what is going on
            console.debug('Data restored to panel "' + thePanel.title + '" from plugin ' + thePanel.dataManager, aData);

        } else {
            console.debug('No data to be restored to panel "' + thePanel.title + '" from plugin ' + thePanel.dataManager);
        }
    }
};

Codebot.UI.SlideTray.prototype.savePersistentPanelData = function() {
    var aPanel,
        aPlugin;

    aPanel = mStack[mStack.length - 1];

    // Has the panel asked for persistent data handling?
    if(aPanel && aPanel.dataManager) {
        // Yep, so let's save it! First fetch the plugin that will
        // handle the data for this panel
        aPlugin = mCodebot.plugins.get(aPanel.dataManager);

        // If the plugin exists and is ok to receive the data,
        // send the package away.
        if(aPlugin && aPlugin.savePanelData) {
            aPlugin.savePanelData(aPanel, aPanel.getData());

            // Emit some debug message so it's easier to track what is going on
            console.debug('Panel "' + aPanel.title + '" just persisted data to plugin ' + aPanel.dataManager, aPanel.getData());

        } else {
            console.debug('Panel "' + aPanel.title + '" asked to persist data, but plugin ' + aPanel.dataManager + ' has no savePanelData() method.');
        }
    }
};

Codebot.UI.SlideTray.prototype.pushPanel = function(thePanelClass, thePanelParams) {
    var aPanelWidth,
        aPanel,
        aSelf = this;

    if(!thePanelClass) {
        console.error('Unable to push slide panel. The provided argument is invalid: it should be an instance of Codebot.Panel.');
        return;
    }

    aPanelWidth = this.getSliderPanelWidth();
    aPanel = this.instantiatePanelObject(thePanelClass, thePanelParams);

    if(mStack.length > 0) {
        this.slideElement(mStack[mStack.length - 1].containerId, aPanelWidth * -2);
    }

    var aId = mIds++;
    var aContainerId = 'slide-panel-' + aId;

    $('#config-dialog').append('

')

    aPanel.setContainer(aContainerId);
    $('#' + aContainerId).css('left', aPanelWidth + 'px');

    this.open();

    aPanel.render();
    this.restorePersistentPanelData(aPanel);

    mStack.push(aPanel);

    setTimeout(function() {
        aSelf.slideElement(aContainerId, -aPanelWidth, mStack.length != 1 ? aSelf.getSlideDuration() : 1);
    }, 50);
};

Codebot.UI.SlideTray.prototype.popPanel = function() {
    var aPanelWidth = this.getSliderPanelWidth(),
        aStackTop;

    if(mStack.length == 1) {
        this.close();

    } else {
        this.savePersistentPanelData();

        for(var i = 0; i < 2; i++) {
            if(mStack.length > 0) {
                aStackTop = mStack[mStack.length - 1 - i];
                this.slideElement(aStackTop.containerId, i == 1 ? -aPanelWidth : 0);
            }
        }
    }

    setTimeout(function() {
        var aPanel = mStack.pop();

        aPanel.onDestroy();
        aPanel.container.remove();

        if(mStack.length == 0) {
            mCodebot.signals.lastSlidePanelClosed.dispatch();
        }
    }, this.getSlideDuration());
};

Codebot.UI.SlideTray.prototype.instantiatePanelObject = function(thePanelClass, thePanelParams) {
    var aInstance;

    aInstance = new thePanelClass();
    aInstance.panelManager = this;
    aInstance.context = mCodebot;
    aInstance.className = thePanelClass;
    aInstance.params = thePanelParams;

    return aInstance;
};

/**
 * Occupy the slide panel area with a new panel.
 *
 * @param  string thePanelClass  name of the class of the panel to be created.
 * @param  object thePanelParams object with additional data that the panel might use. This object will be available in the panel via getParams().
 * @param  bool theForceNew    if a new panel should override any existing panel that is already occuping the slide panel area.
 */
Codebot.UI.SlideTray.prototype.set = function(thePanelClass, thePanelParams, theForceNew) {
    var aCurrent = this.getCurrentPanel();

    if(!theForceNew && aCurrent && aCurrent.className == thePanelClass) {
        this.toggleOpen();

    } else {
        this.clear(function() {
            this.pushPanel(thePanelClass, thePanelParams);
        }, this);
    }
};

Codebot.UI.SlideTray.prototype.open = function() {
    var aCurrent = this.getCurrentPanel();

    if(!mOpen) {
        if(aCurrent) {
            aCurrent.onResume();
        }

        this.slideElement('content', -this.getSliderPanelWidth());
        this.slideElement('config-dialog', -this.getSliderPanelWidth());
    }

    mOpen = true;
};

Codebot.UI.SlideTray.prototype.close = function(theCallback, theCallbackContext) {
    var aDuration = 0,
        aCurrent;

    if(mOpen) {
        aCurrent = this.getCurrentPanel();

        if(aCurrent) {
            this.savePersistentPanelData();
            aCurrent.onPause();
        }

        this.slideElement('content', 0);
        this.slideElement('config-dialog', 0);

        if(mStack.length == 1) {
            // TODO: rename this signal (e.g. beforeSlideTrayClose)
            mCodebot.signals.beforeLastSlidePanelClose.dispatch();
        }

        mOpen = false;
        aDuration = this.getSlideDuration()
    }

    setTimeout(function() {
        if(theCallback) {
            theCallback.call(theCallbackContext || this);
        }
    }, aDuration);
};

/**
 * [function description]
 *
 */
Codebot.UI.SlideTray.prototype.toggleOpen = function() {
    if(mOpen) {
        this.close();
    } else {
        this.open();
    }
};

/**
 * Invoked by any panel that wants to close itself but
 * is managed by this slide panel.
 *
 * @param  {Codebot.Panel} thePanel The panel that wants to close itself.
 */
Codebot.UI.SlideTray.prototype.closeChild = function(thePanel) {
    if(this.getCurrentPanel() == thePanel) {
        this.popState();

    } else {
        // TODO: remove element from stack, remove from DOM, etc
    }
};

/**
 * [function description]
 *
 * @return {[type]} [description]
 */
Codebot.UI.SlideTray.prototype.getCurrentPanel = function() {
    return mStack.length > 0 ? mStack[mStack.length - 1] : null;
};

/**
 * [function description]
 *
 * @param  {[type]} theCodebot [description]
 * @return {[type]}            [description]
 */
Codebot.UI.SlideTray.prototype.init = function(theCodebot) {
    mCodebot = theCodebot;
    mIds = 0;
    mStack = [];
    mOpen = false;
};


text:
import {stringify as csvStringify} from 'csv-stringify/sync';

import {ResultStatsWithDifferences} from './stats.js';

const precision = 5;

/**
 * Format statistical results as a CSV file string.
 */
export function formatCsvStats(results: ResultStatsWithDifferences[]): string {
  // Note the examples in ./test/csv_test.ts should make this easier to
  // understand.
  const h1 = ['', '', ''];
  const h2 = ['', 'ms', ''];
  const h3 = ['', 'min', 'max'];
  const rows = [];
  for (const result of results) {
    h1.push(`vs ${result.result.name}`, '', '', '');
    h2.push('% change', '', 'ms change', '');
    h3.push('min', 'max', 'min', 'max');
    const row = [];
    row.push(
      result.result.name,
      result.stats.meanCI.low.toFixed(precision),
      result.stats.meanCI.high.toFixed(precision)
    );
    for (const diff of result.differences) {
      if (diff === null) {
        row.push('', '', '', '');
      } else {
        row.push(
          (diff.relative.low * 100).toFixed(precision) + '%',
          (diff.relative.high * 100).toFixed(precision) + '%',
          diff.absolute.low.toFixed(precision),
          diff.absolute.high.toFixed(precision)
        );
      }
    }
    rows.push(row);
  }
  return csvStringify([h1, h2, h3, ...rows]);
}

/**
 * Format raw sample results as a CSV file string.
 *
 * Columns correspond to benchmarks. Rows correspond to sample iterations. The
 * first row is headers containing the benchmark names.
 *
 * For example:
 *
 * foo, bar, baz
 * 1.2, 5.5, 9.4
 * 1.8, 5.6, 9.1
 * 1.3, 5.2, 9.8
 */
export function formatCsvRaw(results: ResultStatsWithDifferences[]): string {
  const headers = [];
  const rows: Array<number[]> = [];
  for (let r = 0; r < results.length; r++) {
    const {result} = results[r];
    headers.push(result.name);
    for (let m = 0; m < result.millis.length; m++) {
      if (rows[m] === undefined) {
        rows[m] = [];
      }
      rows[m][r] = result.millis[m];
    }
  }
  return csvStringify([headers, ...rows]);
}


text:
package com.strategicgains.jbel.expression;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.strategicgains.jbel.exception.EvaluationException;
import com.strategicgains.jbel.function.AccessorFunction;
import com.strategicgains.jbel.function.ElementAccessorFunction;
import com.strategicgains.jbel.function.UnaryFunction;

/**
 * An expression that retrieves a value from an object graph.
 *
 * @author Todd Fredrich
 * @since Aug 26, 2005
 */
public class AccessorExpression
implements Expression
{
	private static final String ARRAY_INDEX_REGEX = "(\\w*)\\[(\\d)\\]";
	private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile(ARRAY_INDEX_REGEX);

	/**
	 * A list of UnaryFunction instances that retrieve the field values from an object.
	 */
	private List<UnaryFunction> accessorFunctions;
	private String name;

	/**
	 * Construct a new empty AccessorExpression instance.
	 */
	public AccessorExpression()
	{
		accessorFunctions = new ArrayList<>();
	}

	/**
	 * Construct a new AccessorExpression instance to access the given field.
	 *
	 * @param attributeName the name of an object attribute.
	 */
	public AccessorExpression(String attributeName)
	{
		this();
		attribute(attributeName);
	}

	/**
	 * Add a new object accessor in the chain of this accessor expression.
	 *
	 * @param attributeName the name of an object attribute
	 * @return AccessorExpression to facilitate chaining (e.g. expression.attribute("x").attribute("y"))
	 */
	public AccessorExpression attribute(String attributeName)
	{
		if (attributeName == null || attributeName.trim().isEmpty())
		{
			throw new NullPointerException("Empty/Null attribute select string");
		}

		this.name = attributeName;
		String[] segments = attributeName.split("\\.");

		for (String segment : segments)
		{
			Matcher m = ARRAY_INDEX_PATTERN.matcher(segment);

			if (m.matches())
			{
				String name = m.group(1);
				int index = Integer.parseInt(m.group(2));
				accessorFunctions.add(new AccessorFunction(name));
				addIndex(index);
			}
			else
			{
				accessorFunctions.add(new AccessorFunction(segment));
			}
		}

		return this;
	}

	/**
	 * Evaluate the accessor function over the elements of a list, returning the retrieved values
	 * as a list.
	 *
	 * @param argument a list of objects.
	 * @return a list of retrieved values.
	 * @throws EvaluationException if the expression cannot be evaluated.
	 */
	public Object evaluate(List<?> argument)
	throws EvaluationException
	{
		List<Object> results = new ArrayList<Object>();

		for (Object element : argument)
		{
			results.add(evaluate(element));
		}

		return results;
	}

	/**
	 * Retrieve the field value from the argument object.
	 *
	 * @return the field value as an object.
	 * @throws EvaluationException if the expression cannot be evaluated.
	 * @see com.strategicgains.jbel.function.UnaryFunction#perform(java.lang.Object)
	 */
	public Object evaluate(Object argument)
	throws EvaluationException
	{
		Object attribute = argument;

		for(UnaryFunction accessor : accessorFunctions)
		{
			attribute = accessor.perform(attribute);
		}

		return attribute;
	}

	public String getAttributeName()
	{
		return name;
	}

	public AccessorExpression addIndex(int index)
	{
		accessorFunctions.add(new ElementAccessorFunction(index));
		return this;
	}
}


text:
#ifndef _SYSTEM_H_
#define _SYSTEM_H_

#include <stdbool.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Control the ambient capability set. */
#ifndef PR_CAP_AMBIENT
#define PR_CAP_AMBIENT 47
#endif

#ifndef PR_CAP_AMBIENT_IS_SET
#define PR_CAP_AMBIENT_IS_SET 1
#endif

#ifndef PR_CAP_AMBIENT_RAISE
#define PR_CAP_AMBIENT_RAISE 2
#endif

#ifndef PR_CAP_AMBIENT_LOWER
#define PR_CAP_AMBIENT_LOWER 3
#endif

#ifndef PR_CAP_AMBIENT_CLEAR_ALL
#define PR_CAP_AMBIENT_CLEAR_ALL 4
#endif

int secure_noroot_set_and_locked(uint64_t mask);
int lock_securebits(uint64_t skip_mask, bool require_keep_caps);

unsigned int get_last_valid_cap(void);
int cap_ambient_supported(void);

int config_net_loopback(void);

int write_pid_to_path(pid_t pid, const char *path);
int write_proc_file(pid_t pid, const char *content, const char *basename);

int mkdir_p(const char *path, mode_t mode, bool isdir);

int get_mount_flags(const char *source, unsigned long *mnt_flags);

int setup_mount_destination(const char *source, const char *dest, uid_t uid,
			    uid_t gid, bool bind);

int lookup_user(const char *user, uid_t *uid, gid_t *gid);
int lookup_group(const char *group, gid_t *gid);

int seccomp_ret_log_available(void);
int seccomp_ret_kill_process_available(void);
bool seccomp_filter_flags_available(unsigned int flags);

/*
 * is_canonical_path: checks whether @path is a canonical path.
 * This means:
 * -Absolute.
 * -No symlinks.
 * -No /./, /../, or extra '/'.
 * -Single trailing '/' is OK.
 */
bool is_canonical_path(const char *path);

#ifdef __cplusplus
}; /* extern "C" */
#endif

#endif /* _SYSTEM_H_ */


text: require 'chatty_active_resource'


text:
define([
  'dojo/_base/declare',
  'jimu/BaseFeatureAction',
  'jimu/WidgetManager'
], function(declare, BaseFeatureAction, WidgetManager){
  var clazz = declare(BaseFeatureAction, {

    iconFormat: 'png',

    isFeatureSupported: function(featureSet){
      return featureSet.features.length > 0 && featureSet.features[0].geometry.type !== 'point';
    },

    onExecute: function(featureSet){
      WidgetManager.getInstance().triggerWidgetOpen(this.widgetId)
      .then(function(myWidget) {
        var vertexCount = 0;
        featureSet.features.forEach(function(f){
          f.geometry.rings.forEach(function(r){
            vertexCount += r.length;
          });
        });
        myWidget.showVertexCount(vertexCount);
      });
    }

  });
  return clazz;
});


text:
.class Lcom/ub/main/util/Tool$2;
.super Ljava/lang/Object;
.source "Tool.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/ub/main/util/Tool;->forwardNetSetDialog(Landroid/app/Activity;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 230
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 1
    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 0
    .parameter "dialog"
    .parameter "whichButton"

    .prologue
    .line 235
    return-void
.end method


text:
package com.yidejia.app.mall;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.yidejia.app.mall.R;
import com.yidejia.app.mall.ctrl.IpAddress;
import com.yidejia.app.mall.jni.JNICallBack;
import com.yidejia.app.mall.net.user.Login;
import com.yidejia.app.mall.util.Consts;
import com.yidejia.app.mall.util.DesUtils;
import com.yidejia.app.mall.util.HttpClientUtil;
import com.yidejia.app.mall.util.IHttpResp;
import com.yidejia.app.mall.widget.WiperSwitch;
import com.yidejia.app.mall.widget.WiperSwitch.OnChangedListener;

public class HomeLoginActivity extends HomeBaseActivity implements
		OnClickListener, OnChangedListener {
//	private MyApplication myApplication;
	private View view;
	private LayoutInflater inflater;
	private FrameLayout frameLayout;
	private ImageView edit1;
	private InputMethodManager inputMethodManager;
	private RelativeLayout findPwd;// 找回密码
	private RelativeLayout rapidRegist;// 快速注册
	private Button mLogin;
	private EditText stringName;
	private EditText stringPassword;
	private IpAddress ipAddress;
	private WiperSwitch mBox;
	private SharedPreferences sp;
	private Consts consts;
//	private RelativeLayout bottomLayout;
	public static boolean isCheck;

	private String name = "";
	private String pwd = "";
	private String ip = "";

	private String saveName;
	private String savePwd;
	private String deflaut;// 获取默认的值

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		Intent intent = getIntent();
		if(null != intent){
			Bundle bundle = intent.getExtras();
			if(null != bundle){
				deflaut = bundle.getString("exit");
			}
		}
		setContentView(R.layout.activity_main_fragment_layout);

//		myApplication = (MyApplication) getApplication();
		inflater = LayoutInflater.from(this);
		view = inflater.inflate(R.layout.my_mall_login, null);
		frameLayout = (FrameLayout) findViewById(R.id.main_fragment);
		frameLayout.addView(view);

		// 设置底部
//		bottomLayout = (RelativeLayout) findViewById(R.id.down_parent_layout);

		// 添加头部
		setActionBarConfigView();
		setCurrentActivityId(5);

		inputMethodManager = (InputMethodManager) HomeLoginActivity.this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		ipAddress = new IpAddress();
		consts = new Consts();
		sp = PreferenceManager
				.getDefaultSharedPreferences(HomeLoginActivity.this);

		saveName = sp.getString("DESMI", null);
		//
		String basePwd = sp.getString("DESPWD", null);
		String keyName = saveName + consts.getMiStr();

		savePwd = DesUtils.decode(keyName, basePwd);

		// 设置默认选中
		mBox = (WiperSwitch) view.findViewById(R.id.cb_my_login_checkbox);
		mBox.setOnChangedListener(this);
		findPwd = (RelativeLayout) view
				.findViewById(R.id.re_my_mall_login_retrieve_password);

		// 设置监听
		findPwd.setOnClickListener(this);
		rapidRegist = (RelativeLayout) view
				.findViewById(R.id.re_my_mall_login_retrieve_regist);
		rapidRegist.setOnClickListener(this);
		mLogin = (Button) view.findViewById(R.id.bt_my_mall_login_button);
		mLogin.setOnClickListener(this);
		stringName = (EditText) view
				.findViewById(R.id.et_my_mall_login__edittext_account);
		stringPassword = (EditText) view
				.findViewById(R.id.et_my_mall_login__edittext_password);

		if (null != deflaut && Consts.EXIT_LOGIN.equals(deflaut)
				&& null != saveName && !"".equals(saveName)) {
			stringName.setText(saveName);
			stringPassword.setText(savePwd);
		}
		// 优化登录账号密码焦点获取
		LinearLayout login_acount = (LinearLayout) view
				.findViewById(R.id.ll_login_acount);
		LinearLayout login_psw = (LinearLayout) view
				.findViewById(R.id.ll_login_psw);
		login_acount
				.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
		login_psw.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
		login_acount.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stringName.requestFocus();
				stringName.setCursorVisible(true);
				stringPassword.setCursorVisible(false);
			}
		});

		login_psw.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stringPassword.requestFocus();
				stringPassword.setCursorVisible(true);
				stringName.setCursorVisible(false);
			}
		});
	}

	/**
	 * 头部
	 */
	private void setActionBarConfigView() {
		setActionbarConfig();
		setTitle(getResources().getString(R.string.login_title_add));
		TextView leftView = (TextView) findViewById(R.id.ab_common_back);
		leftView.setVisibility(View.GONE);
		edit1 = (ImageView) findViewById(R.id.ab_common_iv_share);
		edit1.setImageDrawable(getResources().getDrawable(R.drawable.setting));
		edit1.setVisibility(View.VISIBLE);
		edit1.setOnClickListener(edit);
	}

	/**
	 * 头部的点击事件
	 */
	private OnClickListener edit = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(HomeLoginActivity.this,
					EditorActivity.class);
			startActivity(intent);

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.re_my_mall_login_retrieve_password:// 找回密码
			Intent intent1 = new Intent(HomeLoginActivity.this,
					FindPwActivity.class);
			HomeLoginActivity.this.startActivity(intent1);

			break;

		case R.id.re_my_mall_login_retrieve_regist:// 快速注册
			Intent registIntent = new Intent(HomeLoginActivity.this,
					RegistActivity.class);
			HomeLoginActivity.this.startActivity(registIntent);

			break;
		case R.id.bt_my_mall_login_button:// 登录
			name = stringName.getText().toString();
			pwd = stringPassword.getText().toString();
			ip = ipAddress.getIpAddress();
			if (name == null || "".equals(name)) {
				Toast.makeText(HomeLoginActivity.this, "账号不能为空!",
						Toast.LENGTH_LONG).show();
				return;
			}
			if (pwd == null || "".equals(pwd)) {
				Toast.makeText(HomeLoginActivity.this, "密码不能为空!",
						Toast.LENGTH_LONG).show();
				return;
			}
			// 登录
			login();
			break;
		default:
			break;
		}
	}

	/** 登录操作,向服务器发送登录请求 **/
	private void login() {
		String param = new JNICallBack().getHttp4Login(name, pwd, ip);
		String url = new JNICallBack().HTTPURL;
//		Log.e("system.out", url + "?" + param);
		HttpClientUtil httpClientUtil = new HttpClientUtil(this);
		httpClientUtil.setIsShowLoading(true);
		httpClientUtil.setShowErrMessage(true);
		httpClientUtil.getHttpResp(url, param, new IHttpResp() {

			@Override
			public void onSuccess(String content) {

//				Log.e("system.out", content);

				Login login = new Login();
				boolean issuccess = login.parseLogin(content);
				if (issuccess) { // 登录成功
					Toast.makeText(HomeLoginActivity.this,
							getResources().getString(R.string.login_success),
							Toast.LENGTH_LONG).show();
					Intent intent = new Intent(HomeLoginActivity.this,
							HomeMyMallActivity.class);
					intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					finish();

					sp.edit().putString("DESMI", name).commit();
					sp.edit().putBoolean("CHECK", true).commit();
					String keyName = name + consts.getMiStr();

					try {
						String demi = DesUtils.encode(keyName, pwd);
						sp.edit().putString("DESPWD", demi).commit();
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(null != inputMethodManager)
					inputMethodManager.hideSoftInputFromWindow(HomeLoginActivity.this.getCurrentFocus().getWindowToken(), 0);

				} else {
					Toast.makeText(HomeLoginActivity.this, login.getMsg(),
							Toast.LENGTH_LONG).show();
					sp.edit().remove("CHECK").commit();
					sp.edit().remove("DESMI").commit();
					sp.edit().remove("DESPWD").commit();
				}
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		StatService.onPageEnd(this, getString(R.string.login_title));
	}

	@Override
	protected void onResume() {
		super.onResume();
		StatService.onPageStart(this, getString(R.string.login_title));
	}

	@Override
	public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
		// TODO Auto-generated method stub
		Log.e("info", checkState + "state");
		isCheck = checkState;
	}

}