text:
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Tests.TraceFailedRequests
{
    using System;
    using System.ComponentModel.Design;
    using System.IO;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    using global::JexusManager.Features.TraceFailedRequests;
    using global::JexusManager.Services;

    using Microsoft.Web.Administration;
    using Microsoft.Web.Management.Client;
    using Microsoft.Web.Management.Client.Win32;
    using Microsoft.Web.Management.Server;

    using Moq;

    using Xunit;
    using System.Xml.Linq;
    using System.Xml.XPath;

    public class TraceFailedRequestssFeatureSiteTestFixture
    {
        private TraceFailedRequestsFeature _feature;

        private ServerManager _server;

        private const string Current = @"applicationHost.config";

        private void SetUp()
        {
            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";
            if (Helper.IsRunningOnMono())
            {
                File.Copy("Website1/original.config", "Website1/web.config", true);
                File.Copy(OriginalMono, Current, true);
            }
            else
            {
                File.Copy("Website1\\original.config", "Website1\\web.config", true);
                File.Copy(Original, Current, true);
            }

            Environment.SetEnvironmentVariable(
                "JEXUS_TEST_HOME",
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            _server = new IisExpressServerManager(Current);

            var serviceContainer = new ServiceContainer();
            serviceContainer.RemoveService(typeof(IConfigurationService));
            serviceContainer.RemoveService(typeof(IControlPanel));
            var scope = ManagementScope.Site;
            serviceContainer.AddService(typeof(IControlPanel), new ControlPanel());
            serviceContainer.AddService(
                typeof(IConfigurationService),
                new ConfigurationService(
                    null,
                    _server.Sites[0].GetWebConfiguration(),
                    scope,
                    null,
                    _server.Sites[0],
                    null,
                    null,
                    null, _server.Sites[0].Name));

            serviceContainer.RemoveService(typeof(IManagementUIService));
            var mock = new Mock<IManagementUIService>();
            mock.Setup(
                action =>
                action.ShowMessage(
                    It.IsAny<string>(),
                    It.IsAny<string>(),
                    It.IsAny<MessageBoxButtons>(),
                    It.IsAny<MessageBoxIcon>(),
                    It.IsAny<MessageBoxDefaultButton>())).Returns(DialogResult.Yes);
            serviceContainer.AddService(typeof(IManagementUIService), mock.Object);

            var module = new TraceFailedRequestsModule();
            module.TestInitialize(serviceContainer, null);

            _feature = new TraceFailedRequestsFeature(module);
            _feature.Load();
        }

        [Fact]
        public void TestBasic()
        {
            SetUp();
            Assert.Equal(2, _feature.Items.Count);
            Assert.Equal("*.asp", _feature.Items[0].Path);
        }

        [Fact]
        public void TestRemoveInherited()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("remove",
                            new XAttribute("path", "*.asp")))));
            document.Save(expected);

            _feature.SelectedItem = _feature.Items[0];
            Assert.Equal("*.asp", _feature.SelectedItem.Path);
            _feature.Remove();
            Assert.Null(_feature.SelectedItem);
            Assert.Single(_feature.Items);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestRemove()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            document.Save(expected);

            var item = new TraceFailedRequestsItem(null);
            item.Path = "*.php";
            item.Codes = "200-999";
            _feature.AddItem(item);

            Assert.Equal("*.php", _feature.SelectedItem.Path);
            Assert.Equal(3, _feature.Items.Count);
            _feature.Remove();
            Assert.Null(_feature.SelectedItem);
            Assert.Equal(2, _feature.Items.Count);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestEditInherited()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("remove",
                            new XAttribute("path", "*.asp")),
                        new XElement("add",
                            new XAttribute("path", "*.asp"),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose"))),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "100-999"))
                            ))));
            document.Save(expected);

            _feature.SelectedItem = _feature.Items[0];
            Assert.Equal("*.asp", _feature.SelectedItem.Path);
            var item = _feature.SelectedItem;
            item.Codes = "100-999";
            _feature.EditItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal("100-999", _feature.SelectedItem.Codes);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestEdit()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("add",
                            new XAttribute("path", "*.php"),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "100-999")),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose")))
                            ))));
            document.Save(expected);

            var item = new TraceFailedRequestsItem(null);
            item.Path = "*.php";
            item.Codes = "200-999";
            _feature.AddItem(item);

            Assert.Equal("*.php", _feature.SelectedItem.Path);
            Assert.Equal(3, _feature.Items.Count);
            item.Codes = "100-999";
            _feature.EditItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal("100-999", _feature.SelectedItem.Codes);
            Assert.Equal(3, _feature.Items.Count);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestAdd()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("add",
                            new XAttribute("path", "*.php"),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose"))),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "200-999"))
                            ))));
            document.Save(expected);

            var item = new TraceFailedRequestsItem(null);
            item.Path = "*.php";
            item.Codes = "200-999";
            _feature.AddItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal("200-999", _feature.SelectedItem.Codes);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestRevert()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(new XElement("tracing"));
            document.Save(expected);

            var item = new TraceFailedRequestsItem(null);
            item.Path = "*.php";
            item.Codes = "200-999";
            _feature.AddItem(item);
            Assert.Equal(3, _feature.Items.Count);

            _feature.Revert();
            Assert.Null(_feature.SelectedItem);
            Assert.Equal(2, _feature.Items.Count);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestMoveUp()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("clear"),
                        new XElement("add",
                            new XAttribute("path", "*.aspx"),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose"))),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "200-999"))),
                        new XElement("add",
                            new XAttribute("path", "*.asp"),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose"))),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "200-999")))
                    )));
            document.Save(expected);

            var last = 1;
            var previous = last - 1;
            _feature.SelectedItem = _feature.Items[last];
            var expectedValue = "*.aspx";
            Assert.Equal(expectedValue, _feature.Items[last].Path);
            var original = "*.asp";
            Assert.Equal(original, _feature.Items[previous].Path);
            _feature.MoveUp();
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal(expectedValue, _feature.SelectedItem.Path);
            Assert.Equal(expectedValue, _feature.Items[previous].Path);
            Assert.Equal(original, _feature.Items[last].Path);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }

        [Fact]
        public void TestMoveDown()
        {
            SetUp();

            const string expected = @"expected_add.site.config";
            var site = Path.Combine("Website1", "web.config");
            var document = XDocument.Load(site);
            var server = document.Root?.XPathSelectElement("/configuration/system.webServer");
            server?.Add(
                new XElement("tracing",
                    new XElement("traceFailedRequests",
                        new XElement("remove",
                            new XAttribute("path", "*.asp")),
                        new XElement("add",
                            new XAttribute("path", "*.asp"),
                            new XElement("traceAreas",
                                new XElement("add",
                                    new XAttribute("provider", "ASP"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ASPNET"),
                                    new XAttribute("areas", "Infrastructure,Module,Page,AppServices"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "ISAPI Extension"),
                                    new XAttribute("verbosity", "Verbose")),
                                new XElement("add",
                                    new XAttribute("provider", "WWW Server"),
                                    new XAttribute("areas", "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,WebSocket"),
                                    new XAttribute("verbosity", "Verbose"))),
                            new XElement("failureDefinitions",
                                new XAttribute("statusCodes", "200-999"))
                    ))));
            document.Save(expected);

            var last = 1;
            var previous = last - 1;
            _feature.SelectedItem = _feature.Items[previous];
            var expectedValue = "*.aspx";
            Assert.Equal(expectedValue, _feature.Items[last].Path);
            var original = "*.asp";
            Assert.Equal(original, _feature.Items[previous].Path);
            _feature.MoveDown();
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal(original, _feature.SelectedItem.Path);
            Assert.Equal(expectedValue, _feature.Items[previous].Path);
            Assert.Equal(original, _feature.Items[last].Path);

            const string Original = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }
    }
}


text:
from codim1.fast_lib import ext_classes
import codim1.fast_lib as cfl

def test_pickle():
    for cls in ext_classes:
        cfl.__dict__[cls].__getinitargs__ == cfl.Pickleable.__getinitargs__

redpajama_set_name: RedPajamaGithub


text:
/*
 * 二楼护层光缆测试页面脚本
 * date : 2013-06-21
 * */
$(function() {

	$("#sub_defective_button_wj").bind("click", function(){
		var contractNum = $("#contractNum").val();
		var plateNum = $("#plateNum").val();
		var fiberTypeName = $("#fiberTypeName").val();
		var specificationNumId = $("#specificationNumId").val();
		var segmentId = $("#segmentId").val();
		var url = "production/defectivegoods?contractNum=" + contractNum + "&plateNum=" + plateNum + "&fiberTypeName=" +
			 fiberTypeName + "&specificationnumId=" + specificationNumId + "&segmentId=" + segmentId;
		window.location = url;
	});

	$("#isTestQualified").bind("click", function(){
		if($("#isTestQualified").prop("checked")){
			$("#isMarkingContentQualified").prop("checked",true);
			$("#isMarkingLengthQualified").prop("checked",true);
			$("#isTestPeelOffQualified").prop("checked",true);
			$("#isCableSurfaceQualified").prop("checked",true);
			$("#isTestQualified").val("1");
			$("#isMarkingContentQualified").val("1");
			$("#isMarkingLengthQualified").val("1");
			$("#isTestPeelOffQualified").val("1");
			$("#isCableSurfaceQualified").val("1");
		}else{
			$("#isMarkingContentQualified").prop("checked",false);
			$("#isMarkingLengthQualified").prop("checked",false);
			$("#isTestPeelOffQualified").prop("checked",false);
			$("#isCableSurfaceQualified").prop("checked",false);
			$("#isTestQualified").val("0");
			$("#isMarkingContentQualified").val("0");
			$("#isMarkingLengthQualified").val("0");
			$("#isTestPeelOffQualified").val("0");
			$("#isCableSurfaceQualified").val("0");
		}
	});

	$("#isMarkingContentQualified").bind("click", function(){
		if(!$("#isMarkingContentQualified").prop("checked")){
			$("#isTestQualified").prop("checked",false);
		}
	});

	$("#isMarkingLengthQualified").bind("click", function(){
		if(!$("#isMarkingLengthQualified").prop("checked")){
			$("#isTestQualified").prop("checked",false);
		}
	});

	$("#isTestPeelOffQualified").bind("click", function(){
		if(!$("#isTestPeelOffQualified").prop("checked")){
			$("#isTestQualified").prop("checked",false);
		}
	});

	$("#isCableSurfaceQualified").bind("click", function(){
		if(!$("#isCableSurfaceQualified").prop("checked")){
			$("#isTestQualified").prop("checked",false);
		}
	});

	/*
	 * 二楼测试护层  验证代码
	 * */
	$("#sheath_test_submit_button_wj").click(function(){
		if(!isInteger($("#sheath_test_testDiameter").val())&&!isDecime($("#sheath_test_testDiameter").val())){
			alert("光缆直径必须为数字!");
			$("#sheath_test_testDiameter").focus();
			return false;
		}else if (!validFibByRow()) {
			return false;
		} else if (!isInteger($("#sheath_test_testInnerMeterMark").val())&&!isDecime($("#sheath_test_testInnerMeterMark").val())) {
			alert("内端米标必须为数字!");
			$("#sheath_test_testInnerMeterMark").focus();
			return false;
		} else if (!isInteger($("#sheath_test_testOuterMeterMark").val())&&!isDecime($("#sheath_test_testOuterMeterMark").val())){
			alert("外端米标必须为数字!");
			$("#sheath_test_testOuterMeterMark").focus();
			return false;
		} else if (!isInteger($("#sheath_test_testCableLength").val())&&!isDecime($("#sheath_test_testCableLength").val())){
			alert("缆长必须为数字!");
			$("#sheath_test_testCableLength").focus();
			return false;
		} else if (!isInteger($("#sheath_test_testFiberLength").val())&&!isDecime($("#sheath_test_testFiberLength").val())){
			alert("纤长必须为数字!");
			$("#sheath_test_testFiberLength").focus();
			return false;
		} else if(!$("#isTestQualified").prop( "checked")){
			alert("产品不合格?--->请填写次品单号\n忘了勾选合格?");
			$("#isTestQualified").focus();
			return false;
		}else {
			$("form:first").submit();
		}

	});
});

/*********************   验证表格里面的数据   *********************************************/
function validFibByRow(){
	var rows = $(".fiber_row");//所有的行
	for(var i = 0; i < rows.length; i++){
		var rt1330 = $(rows[i]).find(".sheath_test_1330Attenuation");
		var rt1550 = $(rows[i]).find(".sheath_test_1550Attenuation");
		if (!isInteger($(rt1330).val())&&!isDecime($(rt1330).val())) {
			alert("单模双模值必须为数字!");
			$(rt1330).focus();
			return false;
		} else if (!isInteger($(rt1550).val())&&!isDecime($(rt1550).val())) {
			alert("单模双模值必须为数字!");
			$(rt1550).focus();
			return false;
		}
	}
	return true;
}
/**************************************** end ***************************************/


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>M-Kernel: drv_if/rtc.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

M-Kernel

EmbeddedRTOS

Main Page

Related Pages

Modules

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

 All Data Structures Functions Variables Typedefs Groups Pages

drv_if

rtc.h

    1

   26

   27 #ifndef RTC_H

   28 #define RTC_H

   29

   30 #include "dev.h"

   31 #include "time.h"

   32

   33 typedef void (*RTC_HANDLER)(RTC_CLASS);

   34

   35 extern void rtc_enable(RTC_CLASS rtc);

   36 extern void rtc_disable(RTC_CLASS rtc);

   37 extern void rtc_enable_second_tick(RTC_CLASS rtc, RTC_HANDLER callback, int priority);

   38 extern void rtc_disable_second_tick(RTC_CLASS rtc);

   39

   40 extern time_t rtc_get(RTC_CLASS rtc);

   41 extern void rtc_set(RTC_CLASS rtc, time_t time);

   42

   43 #endif // RTC_H

<address class="footer">
Generated on Wed Sep 12 2012 19:35:11 for M-Kernel by

 1.8.1.2
</address>


text:
"""
Boston housing dataset.  Contains median house price and other attributes of
506 Boston suburbs.

More info at:
https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names

See: Lichman, M. (2013). UCI Machine Learning Repository
[http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School
of Information and Computer Science.
"""

import logging
import numpy as np
import os

from neon.datasets.dataset import Dataset
from neon.util.param import opt_param

logger = logging.getLogger(__name__)

class Housing(Dataset):

    """
    Sets up a Boston housing dataset.

    Attributes:
        raw_dataset_url (str): where to find the source data
        backend (neon.backends.Backend): backend used for this data
        inputs (dict): structure housing the loaded train/test/validation
                       input data
        targets (dict): structure housing the loaded train/test/validation
                        target data

    Keyword Args:
        repo_path (str, optional): where to locally host this dataset on disk
        test_pct (float, optional): How much of the dataset to reserve as a
                                    holdout for testing.
    """
    raw_dataset_url = ('https://archive.ics.uci.edu/ml/'
                       'machine-learning-databases/housing/housing.data')

    def __init__(self, **kwargs):
        opt_param(self, ['test_pct'])
        self.__dict__.update(kwargs)

    def initialize(self):
        pass

    def read_raw_file(self, fname, dtype=None):
        """
        Carries out the actual loading of the raw housing data file.  We assume
        the dataset is laid out exactly as in:
        https://archive.ics.uci.edu/ml/datasets/Housing

        Arguments:
            fname (str): path to raw housing dataset on disk
            dtype (type, optional): type to use to store the contents

        Returns:
            tuple: 2 tuple of numpy ndarrays containing the input field
                   attributes, and target median home values.
        """
        try:
            full_data = np.fromfile(fname, sep=" ",
                                    dtype=dtype).reshape((506, 14))
        except ValueError:
            raise ValueError("Incorrectly shaped data.  Ensure %s is from %s" %
                             (fname,
                              "https://archive.ics.uci.edu/ml/datasets/Housing"
                              ))
        return (full_data[:, 0:-1],
                full_data[:, -1].reshape(full_data.shape[0], 1))

    def load(self, backend=None, experiment=None):
        if self.inputs['train'] is not None:
            return
        if 'repo_path' in self.__dict__:
            self.repo_path = os.path.expandvars(os.path.expanduser(
                self.repo_path))
            save_dir = os.path.join(self.repo_path,
                                    self.__class__.__name__)
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            name = os.path.basename(self.raw_dataset_url)
            repo_file = os.path.join(save_dir, name)
            if not os.path.exists(repo_file):
                self.download_to_repo(self.raw_dataset_url, save_dir)
            logger.info('loading: %s', name)
            (inp, lab) = self.read_raw_file(repo_file, 'float32')
            if 'test_pct' in self.__dict__ and self.test_pct > 0.0:
                vals = np.random.rand(inp.shape[0]) * 100
                self.inputs['train'] = inp[vals >= self.test_pct]
                self.targets['train'] = lab[vals >= self.test_pct]
                self.inputs['test'] = inp[vals < self.test_pct]
                self.targets['test'] = lab[vals < self.test_pct]
            else:
                self.inputs['train'] = inp
                self.targets['train'] = lab
            if 'sample_pct' in self.__dict__:
                self.sample_training_data()
            self.format()
        else:
            raise AttributeError('repo_path not specified in config')


text:
import java.util.Stack;

/**
 * Created by juanyan.li on 4/3/17.
 */
public class SymmetricTree {
    // recursive
    public boolean isSymmetricI(TreeNode root) {
        if (root == null) return true;
        return mirror(root.left, root.right);
    }

    public boolean mirror(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        if (left.val != right.val) return false;
        return mirror(left.left, right.right)
                & mirror(left.right, right.left);
    }

    // iterative - explicitly showing the recursive stack
    public boolean isSymmetricII(TreeNode root) {
        if (root == null) return true;
        Stack<TreeNode> stack = new Stack<>();
        if (!helper(root.left, root.right, stack)) return false;
        while (!stack.isEmpty()) {
            TreeNode right = stack.pop();
            TreeNode left = stack.pop();
            if (!helper(left.left, right.right, stack)) return false;
            if (!helper(left.right, right.left, stack)) return false;
        }
        return true;
    }

    public boolean helper(TreeNode left, TreeNode right, Stack<TreeNode> stack) {
        if (left != null) {
            if (right == null) return false;
            if (left.val != right.val) return false;
            stack.push(left);
            stack.push(right);
        } else if (right != null) return false;
        return true;
    }
}


text:
#include "gkBone.h"
#include "OgreBone.h"

gkBone::gkBone(const gkString& name)
	:    m_name(name), m_bone(0), m_bind(), m_parent(0)
{
	m_bind.setIdentity();
	m_pose.setIdentity();
}

gkBone::~gkBone()
{
}

void gkBone::setRestPosition(const gkTransformState& st)
{
	m_bind = st;
}

void gkBone::applyRootTransform(const gkTransformState& root)
{
	gkMatrix4 bonemat = m_bind.toMatrix();
	gkMatrix4 objmat = root.toMatrix();

	bonemat = objmat * bonemat;

	m_bind = gkTransformState(bonemat);
}

void gkBone::applyChannelTransform(const gkTransformState& channel, gkScalar weight)
{
	// save previous pose
	gkTransformState blendmat = m_pose;

	// combine relative to binding position
	m_pose.loc = m_bind.loc + m_bind.rot * channel.loc;
	m_pose.rot = m_bind.rot * channel.rot;
	m_pose.scl = m_bind.scl * channel.scl;

	if (weight < 1.0)
	{
		// blend poses
		m_pose.loc = gkMathUtils::interp(blendmat.loc, m_pose.loc, weight);
		m_pose.rot = gkMathUtils::interp(blendmat.rot, m_pose.rot, weight);
		m_pose.rot.normalise();
		m_pose.scl = gkMathUtils::interp(blendmat.scl, m_pose.scl, weight);
	}

	m_bone->setPosition(m_pose.loc);
	m_bone->setOrientation(m_pose.rot);
	m_bone->setScale(m_pose.scl);
}

void gkBone::applyPoseTransform(const gkTransformState& pose)
{
	if (!m_bone)
		return;

	m_bone->setPosition(pose.loc);
	m_bone->setOrientation(pose.rot);
	m_bone->setScale(pose.scl);
}

void gkBone::setParent(gkBone* bone)
{
	if (!bone)
		return;

	if (!m_parent)
	{
		m_parent = bone;
		m_parent->m_children.push_back(this);
	}
}

void gkBone::_setOgreBone(Ogre::Bone* bone)
{
	m_bone = bone;
}

UTsize gkBone::_getBoneIndex(void)
{
	if (!m_bone)
		return UT_NPOS;

	return m_bone->getHandle();
}


text:
#include <thrift/lib/cpp2/transport/rocket/framing/Util.h>

#include <cstdint>
#include <exception>
#include <string>

#include <folly/Conv.h>

namespace {
constexpr size_t kPageSize = 4096;
} // namespace

namespace apache {
namespace thrift {
namespace rocket {
namespace detail {

[[noreturn]] void throwUnexpectedFrameType(uint8_t frameType) {
  throw std::runtime_error(
      folly::to<std::string>("Parsed unexpected frame type: ", frameType));
}

} // namespace detail

StreamId readStreamId(folly::io::Cursor& cursor) {
  return StreamId{cursor.readBE<StreamId::underlying_type>()};
}

size_t readFrameOrMetadataSize(folly::io::Cursor& cursor) {
  std::array<uint8_t, 3> bytes;
  cursor.pull(bytes.data(), bytes.size());

  return (static_cast<size_t>(bytes[0]) << 16) |
      (static_cast<size_t>(bytes[1]) << 8) | static_cast<size_t>(bytes[2]);
}

std::pair<uint8_t, Flags> readFrameTypeAndFlagsUnsafe(
    folly::io::Cursor& cursor) {
  const uint16_t frameTypeAndFlags = cursor.readBE<uint16_t>();
  const uint8_t frameType = frameTypeAndFlags >> Flags::kBits;
  const Flags flags(frameTypeAndFlags & Flags::kMask);
  return {frameType, flags};
}

std::pair<FrameType, Flags> readFrameTypeAndFlags(folly::io::Cursor& cursor) {
  const auto pair = readFrameTypeAndFlagsUnsafe(cursor);
  switch (static_cast<FrameType>(pair.first)) {
    case FrameType::SETUP:
    case FrameType::REQUEST_RESPONSE:
    case FrameType::REQUEST_FNF:
    case FrameType::REQUEST_STREAM:
    case FrameType::REQUEST_CHANNEL:
    case FrameType::REQUEST_N:
    case FrameType::CANCEL:
    case FrameType::PAYLOAD:
    case FrameType::ERROR:
    case FrameType::METADATA_PUSH:
    case FrameType::KEEPALIVE:
    case FrameType::EXT:
      return {static_cast<FrameType>(pair.first), pair.second};

    default:
      apache::thrift::rocket::detail::throwUnexpectedFrameType(pair.first);
  }
}

ExtFrameType readExtFrameType(folly::io::Cursor& cursor) {
  const auto extFrameType = cursor.readBE<uint32_t>();
  switch (static_cast<ExtFrameType>(extFrameType)) {
    case ExtFrameType::ALIGNED_PAGE:
    case ExtFrameType::CUSTOM_ALLOC:
      return static_cast<ExtFrameType>(extFrameType);
    default:
      return ExtFrameType::UNKNOWN;
  }
}

bool alignTo4k(folly::IOBuf& buffer, size_t startOffset, size_t frameSize) {
  auto iobuf = get4kAlignedBuf(
      std::max(buffer.length(), frameSize), startOffset, buffer.length());
  if (UNLIKELY(!iobuf)) {
    return false;
  }

  memcpy(iobuf->writableData(), buffer.writableData(), buffer.length());
  buffer = *std::move(iobuf);
  return true;
}

bool alignTo4kBufQueue(
    folly::IOBufQueue& bufQueue, size_t startOffset, size_t frameSize) {
  auto iobuf = get4kAlignedBuf(
      std::max(bufQueue.chainLength(), frameSize),
      startOffset,
      bufQueue.chainLength());
  if (UNLIKELY(!iobuf)) {
    return false;
  }

  folly::io::Cursor cursor(bufQueue.front());
  cursor.pull(iobuf->writableData(), bufQueue.chainLength());
  folly::IOBufQueue bufQ{folly::IOBufQueue::cacheChainLength()};
  bufQ.append(*std::move(iobuf));
  bufQueue = std::move(bufQ);
  return true;
}

std::unique_ptr<folly::IOBuf> get4kAlignedBuf(
    size_t numBytes, size_t startOffset, size_t trimLength) {
  DCHECK_LE(trimLength, numBytes);
  const size_t padding = kPageSize - (startOffset % kPageSize);
  const size_t size = numBytes + padding;
  void* rawbuf = folly::aligned_malloc(size, kPageSize);
  if (UNLIKELY(!rawbuf)) {
    LOG(ERROR) << "Allocating : " << kPageSize
               << " aligned memory of size: " << numBytes << " failed!";
    return nullptr;
  }
  auto iobuf = folly::IOBuf::takeOwnership(
      rawbuf, size, size, [](void* p, void*) { folly::aligned_free(p); });
  iobuf->trimStart(padding);
  iobuf->trimEnd(size - std::min(numBytes, trimLength) - padding);
  return iobuf;
}

// Has both false positives and false negatives
bool isMaybeRocketFrame(const folly::IOBuf& data) {
  if (data.length() < Serializer::kBytesForFrameOrMetadataLength) {
    return false;
  }

  try {
    folly::io::Cursor cursor(&data);
    auto size = readFrameOrMetadataSize(cursor);
    if (size + Serializer::kBytesForFrameOrMetadataLength != data.length()) {
      return false;
    }
    const size_t kMinFrameSize = 6;
    if (size < kMinFrameSize) {
      return false;
    }

    auto streamId = static_cast<uint32_t>(readStreamId(cursor));
    if (streamId != 0 && streamId % 2 == 0) {
      // Thrift only uses client -> server streams
      return false;
    }

    const uint16_t frameTypeAndFlags = cursor.readBE<uint16_t>();
    const uint16_t flags = frameTypeAndFlags & Flags::kMask;
    const uint16_t kMinFlag = 1 << 5;
    if (flags != 0 && flags < kMinFlag) {
      return false;
    }

    const uint8_t frameType = frameTypeAndFlags >> Flags::kBits;
    switch (static_cast<FrameType>(frameType)) {
      case FrameType::SETUP:
      case FrameType::KEEPALIVE:
      case FrameType::METADATA_PUSH:
        return streamId == 0;
      case FrameType::REQUEST_RESPONSE:
      case FrameType::REQUEST_FNF:
      case FrameType::REQUEST_STREAM:
      case FrameType::REQUEST_CHANNEL:
      case FrameType::REQUEST_N:
      case FrameType::CANCEL:
      case FrameType::PAYLOAD:
        return streamId != 0;
      case FrameType::ERROR:
      case FrameType::EXT:
        return true;
      default:
        return false;
    }
  } catch (...) {
    return false;
  }
}
} // namespace rocket
} // namespace thrift
} // namespace apache


text:
package org.apache.geode.cache.query.internal.cq;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.logging.log4j.Logger;

import org.apache.geode.SystemFailure;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.cache.CacheCallback;
import org.apache.geode.cache.query.CqAttributes;
import org.apache.geode.cache.query.CqAttributesMutator;
import org.apache.geode.cache.query.CqListener;
import org.apache.geode.internal.logging.LogService;

public class CqAttributesImpl implements CqAttributes, CqAttributesMutator, Cloneable {
  private static final Logger logger = LogService.getLogger();

  private volatile ArrayList<CqListener> cqListeners = null;

  @Immutable
  private static final CqListener[] EMPTY_LISTENERS = new CqListener[0];

  /**
   * Used to synchronize access to cqListeners
   */
  private final Object clSync = new Object();

  /**
   * Returns the CqListeners set with the CQ
   *
   * @return CqListener[]
   */
  @Override
  public CqListener[] getCqListeners() {
    final ArrayList listeners = this.cqListeners;
    if (listeners == null) {
      return CqAttributesImpl.EMPTY_LISTENERS;
    }

    CqListener[] result = null;
    synchronized (this.clSync) {
      result = new CqListener[listeners.size()];
      listeners.toArray(result);
    }
    return result;

  }

  /**
   * Returns the CqListener set with the CQ
   *
   */
  @Override
  public CqListener getCqListener() {
    ArrayList<CqListener> listeners = this.cqListeners;
    if (listeners == null) {
      return null;
    }
    synchronized (this.clSync) {
      if (listeners.size() == 0) {
        return null;
      }
      if (listeners.size() == 1) {
        return listeners.get(0);
      }
    }
    throw new IllegalStateException(
        "More than one Cqlistener exists.");
  }

  @Override
  public Object clone() {
    try {
      return super.clone();
    } catch (CloneNotSupportedException e) {
      throw new InternalError(
          "CloneNotSupportedException thrown in class that implements cloneable");
    }
  }

  /**
   * Adds a Cqlistener to the end of the list of Cqlisteners on this CqQuery.
   *
   * @param cql the user defined cq listener to add to the CqQuery.
   * @throws IllegalArgumentException if aListener is null
   */
  @Override
  public void addCqListener(CqListener cql) {
    if (cql == null) {
      throw new IllegalArgumentException(
          "addCqListener parameter was null");
    }
    synchronized (this.clSync) {
      ArrayList<CqListener> oldListeners = this.cqListeners;
      if (oldListeners == null || oldListeners.size() == 0) {
        ArrayList<CqListener> al = new ArrayList<CqListener>(1);
        al.add(cql);
        this.setCqListeners(al);
      } else {
        if (!oldListeners.contains(cql)) {
          oldListeners.add(cql);
        }
      }
    }
  }

  /**
   * Removes all Cqlisteners, calling on each of them, and then adds each listener in the specified
   * array.
   *
   * @param addedListeners a possibly null or empty array of listeners to add to this CqQuery.
   * @throws IllegalArgumentException if the newListeners array has a null element
   */
  @Override
  public void initCqListeners(CqListener[] addedListeners) {
    ArrayList<CqListener> oldListeners;
    synchronized (this.clSync) {
      oldListeners = this.cqListeners;
      if (addedListeners == null || addedListeners.length == 0) {
        this.setCqListeners(null);
      } else { // we have some listeners to add
        List nl = Arrays.asList(addedListeners);
        if (nl.contains(null)) {
          throw new IllegalArgumentException(
              "initCqListeners parameter had a null element");
        }
        this.setCqListeners(new ArrayList(nl));
      }
    }

    if (oldListeners != null) {
      CqListener cql = null;
      for (Iterator<CqListener> iter = oldListeners.iterator(); iter.hasNext();) {
        try {
          cql = iter.next();
          cql.close();
          // Handle client side exceptions.
        } catch (Exception ex) {
          logger.warn("Exception occurred while closing CQ Listener Error: {}",
              ex.getLocalizedMessage());
          if (logger.isDebugEnabled()) {
            logger.debug(ex.getMessage(), ex);
          }
        } catch (VirtualMachineError err) {
          SystemFailure.initiateFailure(err);
          // If this ever returns, rethrow the error. We're poisoned
          // now, so don't let this thread continue.
          throw err;
        } catch (Throwable t) {
          // Whenever you catch Error or Throwable, you must also
          // catch VirtualMachineError (see above). However, there is
          // _still_ a possibility that you are dealing with a cascading
          // error condition, so you also need to check to see if the JVM
          // is still usable:
          SystemFailure.checkFailure();
          logger.warn("Runtime Exception occurred while closing CQ Listener Error: {}",
              t.getLocalizedMessage());
          if (logger.isDebugEnabled()) {
            logger.debug(t.getMessage(), t);
          }
        }
      }
    }
  }

  /**
   * Removes a Cqlistener from the list of Cqlisteners on this CqQuery. Does nothing if the
   * specified listener has not been added. If the specified listener has been added then
   * {@link CacheCallback#close()} will be called on it; otherwise does nothing.
   *
   * @param cql the Cqlistener to remove from the CqQuery.
   * @throws IllegalArgumentException if cl is null
   */
  @Override
  public void removeCqListener(CqListener cql) {
    if (cql == null) {
      throw new IllegalArgumentException(
          "removeCqListener parameter was null");
    }
    synchronized (this.clSync) {
      ArrayList<CqListener> oldListeners = this.cqListeners;
      if (oldListeners != null) {
        if (oldListeners.remove(cql)) {
          if (oldListeners.isEmpty()) {
            this.setCqListeners(null);
          }
          try {
            cql.close();
            // Handle client side exceptions.
          } catch (Exception ex) {
            logger.warn("Exception closing CQ Listener Error: {}",
                ex.getLocalizedMessage());
            if (logger.isDebugEnabled()) {
              logger.debug(ex.getMessage(), ex);
            }
          } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // If this ever returns, rethrow the error. We're poisoned
            // now, so don't let this thread continue.
            throw err;
          } catch (Throwable t) {
            // Whenever you catch Error or Throwable, you must also
            // catch VirtualMachineError (see above). However, there is
            // _still_ a possibility that you are dealing with a cascading
            // error condition, so you also need to check to see if the JVM
            // is still usable:
            SystemFailure.checkFailure();
            logger.warn("Runtime Exception occurred closing CQ Listener Error: {}",
                t.getLocalizedMessage());
            if (logger.isDebugEnabled()) {
              logger.debug(t.getMessage(), t);
            }
          }
        }
      }
    }
  }

  public void setCqListeners(ArrayList<CqListener> cqListeners) {
    synchronized (this.clSync) {
      this.cqListeners = cqListeners;
    }
  }
}


text:
"use strict";
window.mushroom = {

	// reference to the Phaser.Game instance
	game: null,

	// main function
	main: function(){
		this.game = new Phaser.Game(mt.data.map.viewportWidth, mt.data.map.viewportHeight, Phaser.AUTO, document.body, window.mushroom.state.boot);
	},

	// here we will store all states
	state: {}
};

window.addEventListener('DOMContentLoaded', function(){
	window.mushroom.main();
}, false);


text:
package com.opengamma.analytics.financial.interestrate.payments.provider;

import static org.testng.AssertJUnit.assertEquals;

import org.testng.annotations.Test;
import org.threeten.bp.ZonedDateTime;

import com.mcleodmoores.date.CalendarAdapter;
import com.mcleodmoores.date.WorkingDayCalendar;
import com.opengamma.analytics.financial.instrument.index.IborIndex;
import com.opengamma.analytics.financial.instrument.payment.CouponIborAverageIndexDefinition;
import com.opengamma.analytics.financial.instrument.payment.CouponIborDefinition;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIbor;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponIborAverage;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueCurveSensitivityDiscountingCalculator;
import com.opengamma.analytics.financial.provider.calculator.discounting.PresentValueDiscountingCalculator;
import com.opengamma.analytics.financial.provider.description.MulticurveProviderDiscountDataSets;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator;
import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator;
import com.opengamma.analytics.financial.util.AssertSensitivityObjects;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.MultipleCurrencyAmount;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class CouponIborAverageDiscountingMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES = MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex[] IBOR_INDEXES = MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
  private static final IborIndex EURIBOR3M = IBOR_INDEXES[0];
  private static final IborIndex EURIBOR6M = IBOR_INDEXES[1];
  private static final Currency EUR = EURIBOR3M.getCurrency();
  private static final WorkingDayCalendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final DayCount DAY_COUNT_COUPON = DayCounts.ACT_365;
  private static final double NOTIONAL = 1000000; // 1m
  private static final ZonedDateTime FIXING_DATE = DateUtils.getUTCDate(2011, 5, 19);
  private static final ZonedDateTime PAYMENT_DATE = DateUtils.getUTCDate(2011, 11, 22);

  private static final ZonedDateTime ACCRUAL_START_DATE_1 = DateUtils.getUTCDate(2011, 5, 23);
  private static final ZonedDateTime ACCRUAL_END_DATE_1 = DateUtils.getUTCDate(2011, 8, 22);
  private static final double ACCRUAL_FACTOR_1 = DAY_COUNT_COUPON.getDayCountFraction(ACCRUAL_START_DATE_1, ACCRUAL_END_DATE_1);
  private static final CouponIborDefinition CPN_IBOR_DEFINITION_1 = CouponIborDefinition.from(PAYMENT_DATE, ACCRUAL_START_DATE_1,
      ACCRUAL_END_DATE_1, ACCRUAL_FACTOR_1, NOTIONAL, FIXING_DATE,
      EURIBOR3M, CalendarAdapter.of(CALENDAR));

  private static final ZonedDateTime ACCRUAL_START_DATE_2 = DateUtils.getUTCDate(2011, 5, 23);
  private static final ZonedDateTime ACCRUAL_END_DATE_2 = DateUtils.getUTCDate(2011, 11, 22);
  private static final double ACCRUAL_FACTOR_2 = DAY_COUNT_COUPON.getDayCountFraction(ACCRUAL_START_DATE_2, ACCRUAL_END_DATE_2);
  private static final CouponIborDefinition CPN_IBOR_DEFINITION_2 = CouponIborDefinition.from(PAYMENT_DATE, ACCRUAL_START_DATE_2,
      ACCRUAL_END_DATE_2, ACCRUAL_FACTOR_2, NOTIONAL, FIXING_DATE,
      EURIBOR6M, CalendarAdapter.of(CALENDAR));

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2010, 12, 27);
  private static final CouponIbor CPN_IBOR_1 = (CouponIbor) CPN_IBOR_DEFINITION_1.toDerivative(REFERENCE_DATE);
  private static final CouponIbor CPN_IBOR_2 = (CouponIbor) CPN_IBOR_DEFINITION_2.toDerivative(REFERENCE_DATE);

  private static final CouponIborDiscountingMethod METHOD_CPN_IBOR = CouponIborDiscountingMethod.getInstance();
  private static final PresentValueDiscountingCalculator PVDC = PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC = PresentValueCurveSensitivityDiscountingCalculator
      .getInstance();

  private static final ParameterSensitivityParameterCalculator<MulticurveProviderInterface> PSC = new ParameterSensitivityParameterCalculator<>(
      PVCSDC);
  private static final double SHIFT = 5.0E-7;
  private static final ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator PSC_DSC_FD = new ParameterSensitivityMulticurveDiscountInterpolatedFDCalculator(
      PVDC, SHIFT);

  private static final double WEIGHT_1 = 17;
  private static final double WEIGHT_2 = -0.06;
  private static final CouponIborAverageIndexDefinition CPN_IBOR_AVERAGE_DEFINITION = CouponIborAverageIndexDefinition.from(PAYMENT_DATE,
      ACCRUAL_START_DATE_2, ACCRUAL_END_DATE_2, ACCRUAL_FACTOR_2, NOTIONAL,
      FIXING_DATE, EURIBOR3M, EURIBOR6M, WEIGHT_1, WEIGHT_2, CalendarAdapter.of(CALENDAR), CalendarAdapter.of(CALENDAR));
  private static final CouponIborAverage CPN_IBOR_AVERAGE = (CouponIborAverage) CPN_IBOR_AVERAGE_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final CouponIborAverageDiscountingMethod METHOD_CPN_IBOR_AVERAGE = CouponIborAverageDiscountingMethod.getInstance();

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;

  /**
   *
   */
  @Test
  public void presentValueMarketDiscount() {
    final MultipleCurrencyAmount pvComputed = METHOD_CPN_IBOR_AVERAGE.presentValue(CPN_IBOR_AVERAGE, MULTICURVES);
    final double forward1 = MULTICURVES.getSimplyCompoundForwardRate(CPN_IBOR_AVERAGE.getIndex1(),
        CPN_IBOR_AVERAGE.getFixingPeriodStartTime1(), CPN_IBOR_AVERAGE.getFixingPeriodEndTime1(),
        CPN_IBOR_AVERAGE.getFixingAccrualFactor1());
    final double forward2 = MULTICURVES.getSimplyCompoundForwardRate(CPN_IBOR_AVERAGE.getIndex2(),
        CPN_IBOR_AVERAGE.getFixingPeriodStartTime2(), CPN_IBOR_AVERAGE.getFixingPeriodEndTime2(),
        CPN_IBOR_AVERAGE.getFixingAccrualFactor2());

    final double df = MULTICURVES.getDiscountFactor(CPN_IBOR_AVERAGE.getCurrency(), CPN_IBOR_1.getPaymentTime());
    final double pvExpected = CPN_IBOR_AVERAGE.getNotional() * CPN_IBOR_AVERAGE.getPaymentYearFraction()
        * (WEIGHT_1 * forward1 + WEIGHT_2 * forward2) * df;
    assertEquals("CouponIborDiscountingMarketMethod: present value", pvExpected, pvComputed.getAmount(EUR), TOLERANCE_PV);
  }

  /**
   *
   */
  @Test
  public void presentValue() {
    final MultipleCurrencyAmount pvComputed = METHOD_CPN_IBOR_AVERAGE.presentValue(CPN_IBOR_AVERAGE, MULTICURVES);
    final MultipleCurrencyAmount pvComputed1 = METHOD_CPN_IBOR.presentValue(CPN_IBOR_1, MULTICURVES);
    final MultipleCurrencyAmount pvComputed2 = METHOD_CPN_IBOR.presentValue(CPN_IBOR_2, MULTICURVES);
    final double pvExpected = CPN_IBOR_AVERAGE.getPaymentYearFraction() *
        (WEIGHT_1 * pvComputed1.getAmount(EUR) / ACCRUAL_FACTOR_1 + WEIGHT_2 * pvComputed2.getAmount(EUR) / ACCRUAL_FACTOR_2);

    assertEquals("CouponIborDiscountingMarketMethod: present value", pvExpected, pvComputed.getAmount(EUR), TOLERANCE_PV);
  }

  /**
   *
   */
  @Test
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsAnnuityExact = PSC.calculateSensitivity(CPN_IBOR_AVERAGE, MULTICURVES,
        MULTICURVES.getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsAnnuityFD = PSC_DSC_FD.calculateSensitivity(CPN_IBOR_AVERAGE, MULTICURVES);
    AssertSensitivityObjects.assertEquals("CouponIborAverageDiscountingMethod: presentValueCurveSensitivity ", pvpsAnnuityExact,
        pvpsAnnuityFD, TOLERANCE_PV_DELTA);
  }

  /**
   *
   */
  @Test
  public void presentValueMarketSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod = METHOD_CPN_IBOR_AVERAGE.presentValueCurveSensitivity(CPN_IBOR_AVERAGE,
        MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator = CPN_IBOR_AVERAGE.accept(PVCSDC, MULTICURVES);
    AssertSensitivityObjects.assertEquals("CouponFixedDiscountingMarketMethod: presentValueMarketSensitivity", pvcsMethod, pvcsCalculator,
        TOLERANCE_PV_DELTA);
  }
}


text:
#ifndef __Moon3d__ParticleManager__
#define __Moon3d__ParticleManager__

#include "cocos2d.h"

USING_NS_CC;

class ParticleManager
{
public:

    static ParticleManager* getInstance()
    {
        if ( m_pInstance == nullptr )
            m_pInstance = new ParticleManager();
        return m_pInstance;
    }

private:

    ParticleManager();

    static ParticleManager* m_pInstance;

    class CGarbo
    {
    public:
        ~CGarbo()
        {
            if (ParticleManager::m_pInstance!= nullptr)
            {
                delete ParticleManager::m_pInstance;
            }
        }
    };

    static CGarbo m_garbo;

public:

    std::map<std::string, ValueMap> m_plistMap;

    void AddPlistData(std::string strPlist,std::string strName);

    ValueMap GetPlistData(std::string strplist);
};

#endif /* defined(__Moon3d__ParticleManager__) */


text:
package main

import (
	"fmt"
	"net/http"

	"gopkg.in/go-on/method.v1"
	"gopkg.in/go-on/router.v2"
	"gopkg.in/go-on/router.v2/route"
)

var (
	Car        = route.New("/car/:car_id", method.GET, method.POST, method.PUT)
	Cars       = route.New("/car", method.GET)
	MountPoint = "/api/v1"
)

func init() {
	route.Mount(MountPoint, Car, Cars)
}

var Router = router.New()

func carHandler(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "car: %s, method: %s", router.GetRouteParam(req, "car_id"), req.Method)
}

func postCarHandler(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "car: %s, method: POST", router.GetRouteParam(req, "car_id"))
}

func carsHandler(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "all cars")
}

func main() {
	Router.HandleRouteFunc(Car, carHandler, method.GET, method.PUT)
	Router.HandleRouteFunc(Car, postCarHandler, method.POST)
	Router.HandleRouteFunc(Cars, carsHandler, method.GET)
	Router.Mount(MountPoint, nil)

	http.ListenAndServe(":8080", Router.ServingHandler())
}


text:
<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
<head>
    <script src="picogl.min.js"></script>
    <script src="gl-matrix-min.js"></script>
</head>
<body>
    <canvas id="webgl-canvas"></canvas>
<script type="shader/vertex" id="vertex-shader">
    #version 300 es

    layout(location=0) in vec4 position;

    out vec2 vUV;
    void main() {
        vUV = position.xy * 0.5 + 0.5;
        gl_Position = position;
    }
</script>
<script type="shader/fragment" id="fragment-shader-mrt">
    #version 300 es
    precision highp float;

    layout(location=0) out vec4 fragColor1;
    layout(location=1) out vec4 fragColor2;
    void main() {
        fragColor1 = vec4(1.0, 0.0, 0.0, 1.0);
        fragColor2 = vec4(0.0, 0.0, 1.0, 1.0);
    }
</script>
<script type="shader/fragment" id="fragment-shader-blend">
    #version 300 es
    precision highp float;

    in vec2 vUV;

    uniform sampler2D texture1;
    uniform sampler2D texture2;

    out vec4 fragColor;
    void main() {
        vec4 color1 = texture(texture1, vUV);
        vec4 color2 = texture(texture2, vUV);
        fragColor = mix(color1, color2, vUV.x);
    }
</script>
    <script>
        var canvas = document.getElementById("webgl-canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var gl = canvas.getContext("webgl2");

        var app = PicoGL.createApp(canvas)
        .clearColor(0, 0, 0, 1);

        var vSource = document.getElementById("vertex-shader").text.trim();
        var vertexShader = app.createShader(PicoGL.VERTEX_SHADER, vSource);

        var fSourceMRT = document.getElementById("fragment-shader-mrt").text.trim();
        var programMRT = app.createProgram(vertexShader, fSourceMRT);

        var fSourceBlend = document.getElementById("fragment-shader-blend").text.trim();
        var programBlend = app.createProgram(vertexShader, fSourceBlend);

        var triangePositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
             -0.5, -0.5,
             0.5, -0.5,
             0.0, 0.5
        ]));

        var triangleArray = app.createVertexArray()
        .vertexAttributeBuffer(0, triangePositions);

        var quadPositions = app.createVertexBuffer(PicoGL.FLOAT, 2, new Float32Array([
             -1.0, 1.0,
             -1.0, -1.0,
             1.0, -1.0,
             -1.0, 1.0,
             1.0, -1.0,
             1.0, 1.0
        ]));

        var quadArray = app.createVertexArray()
        .vertexAttributeBuffer(0, quadPositions);

        var colorTarget1 = app.createTexture2D(app.width, app.height);
        var colorTarget2 = app.createTexture2D(app.width, app.height);

        var framebuffer = app.createFramebuffer()
        .colorTarget(0, colorTarget1)
        .colorTarget(1, colorTarget2);

        var drawCallMRT = app.createDrawCall(programMRT, triangleArray);
        var drawCallBlend = app.createDrawCall(programBlend, quadArray)
        .texture("texture1", framebuffer.colorTextures[0])
        .texture("texture2", framebuffer.colorTextures[1]);

        app.drawFramebuffer(framebuffer).clear();
        drawCallMRT.draw();

        app.defaultDrawFramebuffer().clear();
        drawCallBlend.draw();
    </script>
</body>


text:
package org.apache.jmeter.extractor;

import static org.junit.Assert.assertThat;

import java.nio.charset.StandardCharsets;

import org.apache.jmeter.extractor.json.jsonpath.JSONPostProcessor;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;

public class TestJSONPostProcessor {

    private static final String VAR_NAME = "varName";

    @Test
    public void testProcessAllElementsOneMatch() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1", true);
        JMeterVariables vars = new JMeterVariables();
        processor.setDefaultValues("NONE");
        processor.setJsonPathExpressions("$[*]");
        processor.setRefNames("varname");
        processor.setScopeVariable("contentvar");
        context.setVariables(vars);
        vars.put("contentvar", "[\"one\"]");
        processor.process();
        assertThat(vars.get("varname"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_1"), CoreMatchers.is("one"));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is("1"));
    }

    @Test
    public void testProcessAllElementsMultipleMatches() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1", true);
        JMeterVariables vars = new JMeterVariables();
        processor.setDefaultValues("NONE");
        processor.setJsonPathExpressions("$[*]");
        processor.setRefNames("varname");
        processor.setScopeVariable("contentvar");
        context.setVariables(vars);
        vars.put("contentvar", "[\"one\", \"two\"]");
        processor.process();
        assertThat(vars.get("varname_1"), CoreMatchers.is("one"));
        assertThat(vars.get("varname_2"), CoreMatchers.is("two"));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is("2"));
    }

    @Test
    public void testProcessRandomElementMultipleMatches() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "0", true);
        JMeterVariables vars = new JMeterVariables();
        processor.setDefaultValues("NONE");
        processor.setJsonPathExpressions("$[*]");
        processor.setRefNames("varname");
        processor.setScopeVariable("contentvar");
        context.setVariables(vars);
        vars.put("contentvar", "[\"one\", \"two\"]");
        processor.process();
        assertThat(vars.get("varname"), CoreMatchers.is(CoreMatchers.anyOf(CoreMatchers.is("one"), CoreMatchers.is("two"))));
        assertThat(vars.get("varname_1"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_2"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is(CoreMatchers.nullValue()));
    }

    @Test
    public void testPR235CaseEmptyResponse() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1", true);
        JMeterVariables vars = new JMeterVariables();
        processor.setDefaultValues("NONE");
        processor.setJsonPathExpressions("$[*]");
        processor.setRefNames("varname");
        processor.setScopeVariable("contentvar");
        context.setVariables(vars);
        vars.put("contentvar", "[\"one\", \"two\"]");
        processor.process();
        assertThat(vars.get("varname_1"), CoreMatchers.is("one"));
        assertThat(vars.get("varname_2"), CoreMatchers.is("two"));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is("2"));
        vars.put("contentvar", "");
        processor.process();
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_1"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_2"), CoreMatchers.is(CoreMatchers.nullValue()));
    }

    @Test
    public void testPR235CaseMatchOneWithZero() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1", true);
        JMeterVariables vars = new JMeterVariables();
        processor.setDefaultValues("NONE");
        processor.setJsonPathExpressions("$[*]");
        processor.setRefNames("varname");
        processor.setScopeVariable("contentvar");
        context.setVariables(vars);
        vars.put("contentvar", "[\"one\", \"two\"]");
        processor.process();
        assertThat(vars.get("varname_1"), CoreMatchers.is("one"));
        assertThat(vars.get("varname_2"), CoreMatchers.is("two"));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is("2"));
        vars.put("contentvar", "[\"A\", \"B\"]");
        processor.setMatchNumbers("0");
        processor.process();
        assertThat(vars.get("varname"), CoreMatchers.is(CoreMatchers.anyOf(CoreMatchers.is("A"), CoreMatchers.is("B"))));
        assertThat(vars.get("varname_matchNr"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_1"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get("varname_2"), CoreMatchers.is(CoreMatchers.nullValue()));
    }

    @Test
    public void testBug59609() throws ParseException {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "0", false);

        String innerValue = "{\"a\":\"one\",\"b\":\"two\"}";
        String data = "{\"context\":" + innerValue + "}";
        SampleResult result = new SampleResult();
        result.setResponseData(data.getBytes(StandardCharsets.UTF_8));

        JMeterVariables vars = new JMeterVariables();
        context.setVariables(vars);
        context.setPreviousResult(result);

        processor.setJsonPathExpressions("$.context");
        processor.process();

        JSONParser parser = new JSONParser(0);
        Object expectedValue = parser.parse(innerValue);
        assertThat(parser.parse(vars.get(VAR_NAME)), CoreMatchers.is(expectedValue));
        assertThat(vars.get(VAR_NAME + "_matchNr"), CoreMatchers.is(CoreMatchers.nullValue()));
        assertThat(vars.get(VAR_NAME + "_1"), CoreMatchers.is(CoreMatchers.nullValue()));
    }

    @Test
    public void testExtractSimpleArrayElements() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1");
        String data = "[1,2,3]";
        SampleResult result = new SampleResult();
        result.setResponseData(data.getBytes(StandardCharsets.UTF_8));
        JMeterVariables vars = new JMeterVariables();
        context.setVariables(vars);
        context.setPreviousResult(result);

        processor.setJsonPathExpressions("$[*]");
        processor.process();

        Assert.assertEquals("1,2,3", vars.get(VAR_NAME+ "_ALL"));
        for (int i = 1; i <= 3; i++) {
            String v = Integer.toString(i);
            Assert.assertEquals(v, vars.get(VAR_NAME + "_" + v));
        }

        Assert.assertEquals("3", vars.get(VAR_NAME + "_matchNr"));
    }

    @Test
    public void testExtractComplexElements() {
        JMeterContext context = JMeterContextService.getContext();
        JSONPostProcessor processor = setupProcessor(context, "-1");
        String data = "[{\"a\":[1,{\"d\":2},3]},[\"b\",{\"h\":23}],3]";
        SampleResult result = new SampleResult();
        result.setResponseData(data.getBytes(StandardCharsets.UTF_8));
        JMeterVariables vars = new JMeterVariables();
        context.setVariables(vars);
        context.setPreviousResult(result);

        processor.setJsonPathExpressions("$[*]");
        processor.process();

        String jsonWithoutOuterParens = data.substring(1, data.length() - 1);
        Assert.assertEquals(jsonWithoutOuterParens, vars.get(VAR_NAME + "_ALL"));

        Assert.assertEquals("{\"a\":[1,{\"d\":2},3]}", vars.get(VAR_NAME + "_1"));
        Assert.assertEquals("[\"b\",{\"h\":23}]", vars.get(VAR_NAME + "_2"));
        Assert.assertEquals("3", vars.get(VAR_NAME + "_3"));

        Assert.assertEquals("3", vars.get(VAR_NAME + "_matchNr"));
    }

    private JSONPostProcessor setupProcessor(JMeterContext context,
    String matchNumbers) {
        return setupProcessor(context, matchNumbers, true);
    }

    private JSONPostProcessor setupProcessor(JMeterContext context,
            String matchNumbers, boolean computeConcatenation) {
        JSONPostProcessor processor = new JSONPostProcessor();
        processor.setThreadContext(context);
        processor.setRefNames(VAR_NAME);
        processor.setMatchNumbers(matchNumbers);
        processor.setComputeConcatenation(computeConcatenation);
        return processor;
    }

}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202211;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CreativeWrapperType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="CreativeWrapperType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="HTML"/>
 *     <enumeration value="VIDEO_TRACKING_URL"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "CreativeWrapperType")
@XmlEnum
public enum CreativeWrapperType {

    /**
     *
     *                 HTML creative wrappers that include header/footer HTML snippets.
     *
     *
     */
    HTML,

    /**
     *
     *                 Video Tracking URL creative wrappers that include tracking URIs.
     *
     *
     */
    VIDEO_TRACKING_URL,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static CreativeWrapperType fromValue(String v) {
        return valueOf(v);
    }

}


text:
package org.maxwe.epub.parser;

/**
 * Created by Pengwei Ding on 2015-12-10 11:39.
 * Email: www.dingpengwei@foxmail.com www.dingpegnwei@gmail.com
 * Description: @TODO
 */
public class UnZipTest {
    public static void main(String[] args) throws Exception {

//        long startTime=System.currentTimeMillis();
//
//        EPubParserUtils.unzip("/Users/dingpengwei/Downloads/wode.epub", "/Users/dingpengwei/Downloads/wode");

//        List<String> stringList = new LinkedList<String>();
//        stringList.add("1");
//        stringList.add("2");
//        stringList.add("3");
//        stringList.add("4");
//        stringList.add("5");
//        stringList.add("6");
//        stringList.add("7");
//        stringList.add("8");
//        stringList.add("9");
//        stringList.add("10");
//        stringList.add("11");
//        stringList.add("12");
//        stringList.add("13");
//        stringList.add("14");
//        stringList.add("15");
//        stringList.add("16");
//        stringList.add("17");
//        stringList.add("18");
//        stringList.add("19");
//        for (String string : stringList) {
//            String epubFilePath = "/Users/dingpengwei/Desktop/epub/dizigui.epub";
//            String outPathString = "/Users/dingpengwei/Desktop/epub/dizigui";
//            try {
//                InputStream is = new FileInputStream(epubFilePath);
//                String filename;
//                ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
//                ZipEntry ze;
//                byte[] buffer = new byte[1024];
//                int count;
//                while ((ze = zis.getNextEntry()) != null) {
//                    filename = ze.getName();
//                    if (ze.isDirectory()) {
//                        File fmd = new File(outPathString, filename);
//                        fmd.mkdirs();
//                        continue;
//                    } else {
//                        File fmd = new File(outPathString, filename);
//                        String parent = fmd.getParentFile().getPath();
//                        File fmd_1 = new File(parent);
//                        fmd_1.mkdirs();
//                    }
//                    FileOutputStream fileOutputStream = new FileOutputStream(new File(outPathString , filename));
//                    while ((count = zis.read(buffer)) != -1) {
//                        fileOutputStream.write(buffer, 0, count);
//                    }
//                    fileOutputStream.close();
//                    zis.closeEntry();
//                }
//                zis.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

//
//
//
//
//
//
//
//
//
//
// System.out.println("耗费时间: " + (endTime - startTime) + " ms");

    }
}


text:
from contextlib import contextmanager
from os import getcwd, chdir

from app.utils.repositoryutils import *
from app.utils.requestutils import *
from app.utils.urlutils import *

__all__ = ['working_directory', 'authenticate', 'RepoUtils', 'flash_and_redirect_to_index']

@contextmanager
def working_directory(path):
    current_dir = getcwd()
    chdir(path)
    try:
        yield
    finally:
        chdir(current_dir)


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-307.js
 * @description Object.defineProperty - 'O' is an Arguments object, 'name' is an index named data property of 'O' but not defined in [[ParameterMap]] of 'O', test TypeError is thrown when updating the [[Enumerable]] attribute value of 'name' which is not configurable (10.6 [[DefineOwnProperty]] step 4)
 */

function testcase() {
        return (function () {
            Object.defineProperty(arguments, "0", {
                value: 0,
                writable: false,
                enumerable: true,
                configurable: false
            });
            try {
                Object.defineProperty(arguments, "0", {
                    enumerable: false
                });
            } catch (e) {
                return e instanceof TypeError && dataPropertyAttributesAreCorrect(arguments, "0", 0, false, true, false);
            }
            return false;
        }());
    }
runTestCase(testcase);


text:
import React, {Component} from 'react'

var LinkComponent = React.createClass({
    render: function(){
        var url = this.props.data;
        return {this.props.data}
    }
});

module.exports = LinkComponent;


text:
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const TextBold24: React.ForwardRefExoticComponent<
  CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default TextBold24;


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace Dnn.PersonaBar.Prompt.Components.Commands.Module
{
    using System.Collections.Generic;
    using System.Net;

    using Dnn.PersonaBar.Library.Prompt;
    using Dnn.PersonaBar.Library.Prompt.Attributes;
    using Dnn.PersonaBar.Library.Prompt.Models;
    using Dnn.PersonaBar.Prompt.Components.Models;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;

    using ModulesControllerLibrary = Dnn.PersonaBar.Library.Controllers.ModulesController;

    [ConsoleCommand("get-module", Constants.ModulesCategory, "Prompt_GetModule_Description")]
    public class GetModule : ConsoleCommandBase
    {
        [FlagParameter("id", "Prompt_GetModule_FlagId", "Integer", true)]
        private const string FlagId = "id";

        [FlagParameter("pageid", "Prompt_GetModule_FlagPageId", "Integer", true)]
        private const string FlagPageId = "pageid";

        public override string LocalResourceFile => Constants.LocalResourcesFile;

        private int ModuleId { get; set; }

        private int PageId { get; set; }

        public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId)
        {

            this.ModuleId = this.GetFlagValue(FlagId, "Module Id", -1, true, true, true);
            this.PageId = this.GetFlagValue(FlagPageId, "Page Id", -1, true, false, true);
        }

        public override ConsoleResultModel Run()
        {
            var lst = new List<ModuleInfoModel>();
            KeyValuePair<HttpStatusCode, string> message;
            var moduleInfo = ModulesControllerLibrary.Instance.GetModule(
                this.PortalSettings,
                this.ModuleId,
                this.PageId,
                out message);
            if (moduleInfo == null && !string.IsNullOrEmpty(message.Value))
            {
                return new ConsoleErrorResultModel(message.Value);
            }
            lst.Add(ModuleInfoModel.FromDnnModuleInfo(moduleInfo));
            return new ConsoleResultModel { Data = lst, Records = lst.Count, Output = string.Format(this.LocalizeString("Prompt_GetModule_Result"), this.ModuleId, this.PageId) };
        }
    }
}


text:
using System.Collections.Generic;

using Chromamboo.Contracts;

namespace Chromamboo
{
    using Providers.Notification;
    using Providers.Presentation;

    public class PresentationService : IPresentationService
    {
        private readonly IPresentationProvider[] presentationProviders;

        private readonly string username;

        public PresentationService(string username, IPresentationProvider[] presentationProviders)
        {
            this.presentationProviders = presentationProviders;
            this.username = username;
        }

        public void Update(List<BuildDetail> buildsDetails)
        {
            foreach (var provider in this.presentationProviders)
            {
                provider.Update(buildsDetails, this.username);
            }
        }

        public void UpdatePullRequestCount(int pullRequestCount)
        {
            foreach (var provider in this.presentationProviders)
            {
                provider.UpdatePullRequestCount(pullRequestCount);
            }
        }

        public void MarkAsInconclusive(AtlassianCiSuiteBuildStatusNotificationProvider.NotificationType notificationType)
        {
            foreach (var provider in this.presentationProviders)
            {
                provider.MarkAsInconclusive(notificationType);
            }
        }
    }
}


text:
'use strict';

const path = require('path');
const SimpleDb = require( path.join( __dirname,  '../lib/SimpleNodeDb' ));
const db = new SimpleDb( path.join( __dirname, 'orderdb' ));

console.log('restore the user list from backup...');
db.restore( path.join( __dirname, 'users.dat'), function(err, count) {
    if (err) throw err;

    console.log('user count: ', count);
    db.stats(function(err, stats) {
        console.log('stats: ', JSON.stringify( stats ));
    });
});


text:
* Added `isMounted` to component scopes.
* Added `Addons.ReactCloneWithProps`.
* Dropped Scalaz 7.0 support. (Scalaz 7.1 still supported.)
* Upgrade Scala.JS to 0.6.0.

# 0.7.1 ([commit log](https://github.com/japgolly/scalajs-react/compare/v0.7.0...v0.7.1))

* Support custom tags, attributes and styles via `"string".react{Attr,Style,Tag}`.
* The `class` attribute now gets some special treatment in that it appends rather than overwrites.
  `<.div(^.cls := "a", ^.cls := "b")` is now the same as `<.div(^.cls := "a b")`.

# 0.7.0 ([commit log](https://github.com/japgolly/scalajs-react/compare/v0.6.1...v0.7.0))

To ease migration, here is a script that perform 98% of the required changes for you:
https://gist.github.com/japgolly/c68482dbadb0077f550c

#### Changes:

* Moved `.experiment` into a new module called `extra`.
* Added a `ext-monocle` module with a few extensions for [Monocle](https://github.com/julien-truffaut/Monocle).
* More supported React tags and attributes.
* More ScalazReact extensions:
  * `stateIO`
  * `setStateIO`
  * `modStateIO`
  * `modStateIOF`
  * `_setStateIO`
  * `_modStateIO`
  * `_modStateIOF`
  * Attr operator `~~>?` which is `~~>` but for optional callbacks.
* Removed deprecated methods marked for removal in 0.7.0.
* Deprecated `modStateO`, `modStateU`, `attr runs callback`.

#### Router
New in this release is a router, type-safe and written entirely in Scala.js, for Single-Page Applications.

See [extra/ROUTER.md](https://github.com/japgolly/scalajs-react/blob/master/extra/ROUTER.md) for details.

#### Refs
* Refs can now be applied to components from the outside, prior to mounting. ([#44](https://github.com/japgolly/scalajs-react/issues/44))
* Refs can now refer to components and keep their types intact.
* Scala-based ReactComponent constructors now have `.set(key = ?, ref = ?)` with `.withKey(k)` being an alias for `.set(key = k)`.
* Instances (not objects) of `Ref` renamed to `RefSimple`, `RefP` renamed to `RefParam`. Creating refs is unchanged, so `val r = Ref("hehe")` still works.

#### Scalatags / `.vdom` major changes
Scalatags has been removed as a dependency.
It is instead now embedded directly and highly customised for React.

Why? What does that mean?

* Less transforms from Scalatags to what React needs.
* Internal runtime checks are now elidable.
* Therefore, improved performance, smaller JS output.
* No more console warnings from React about styles.
* Attributes now match what you do in React JS. (eg. `onClick` instead of `onclick`)
* Fixed bug where numbers weren't convertible to `ReactNode`.
* Attributes, styles, tags, modifiers support being wrapped in `Option`, `js.UndefOr`, or `scalaz.Maybe`.
* Removed Scalatags' `()` to `Tag` implicit conversion. It seems like a good idea but can cause certain issues
  (esp with type inference) to be silently ignored, and is unsafe. Use `EmptyTag` instead.
* An unintended consequence, `bool && (attr := value)` changed to `bool ?= (attr := value)`.
* `Tag` is now `ReactTag`. `Modifier` is now `TagMod`.
* `TagMod` is now composable.
* No more arbitrary subsets of tags and attributes, ie. no more additional importing of `tags2._` etc.
* There are now well-organised modules for imports. This...
  1. Fixes bug with conflicting types for `Tag` being imported.
  2. Gives you the ability to opt-out of messy namespace pollution.
  3. Gives you control to import types, implicits, tags, attrs, styles, separately.
  4. Gives you control to build your own modules.

So instead of this:
```scala
import japgolly.scalajs.react.vdom.ReactVDom.{Tag => _, _}
import all._

def eg(key: String, name: String) =
  div(
    cls := "red",
    keyAttr := key,
    "Hello ", name)
```

it is now recommended that you use prefixes to access tags and attributes.
This means that you don't run into confusing error messages and IDE refactoring issues when using names like
`id`, `a`, `key` for your variables.

The default prefixes (recommended) is available via `vdom.prefix_<^._` and it provides two prefixes.

1. `<` for tags. _(Example: `<.div`)_
2. `^` for attributes and styles. _(Example: `^.onClick`)_

The above example becomes:
```scala
import japgolly.scalajs.react.vdom.prefix_<^._

def eg(key: String, name: String) =
  <.div(
    ^.cls := "red",
    ^.key := key,
    "Hello ", name)
```

If you prefer having all tags and attributes in scope without a prefix, then you can still do that by using this import:
```scala
import japgolly.scalajs.react.vdom.all._
```


text:
var webAuth = new auth0.WebAuth({
    domain: Auth0Config.Auth0Domain,
    clientID: Auth0Config.Auth0ClientID,
    redirectUri: window.location + "/auth0callback.html",
    audience: Auth0Config.Auth0Audience,
    responseType: "token id_token",
    scope: Auth0Config.Auth0Scope
});

webAuth.parseHash(function (err, result) {
   if (err) {
       console.error("Unable to authenticate: " + err);
       webAuth.authorize();
   } else if (result && result.idToken && result.accessToken) {
       window.sessionStorage.setItem("auth0AccessToken", result.accessToken);
       window.sessionStorage.setItem("auth0IDToken", result.idToken);
       window.location = window.location.origin;
   }
});


text:
#include "gtest/gtest.h"
#include "webrtc/modules/media_file/interface/media_file.h"
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/test/testsupport/fileutils.h"

class MediaFileTest : public testing::Test {
 protected:
  void SetUp() {
    // Use number 0 as the the identifier and pass to CreateMediaFile.
    media_file_ = webrtc::MediaFile::CreateMediaFile(0);
    ASSERT_TRUE(media_file_ != NULL);
  }
  void TearDown() {
    webrtc::MediaFile::DestroyMediaFile(media_file_);
    media_file_ = NULL;
  }
  webrtc::MediaFile* media_file_;
};

TEST_F(MediaFileTest, StartPlayingAudioFileWithoutError) {
  // TODO(leozwang): Use hard coded filename here, we want to
  // loop through all audio files in future
  const std::string audio_file = webrtc::test::ProjectRootPath() +
      "data/voice_engine/audio_tiny48.wav";
  ASSERT_EQ(0, media_file_->StartPlayingAudioFile(
      audio_file.c_str(),
      0,
      false,
      webrtc::kFileFormatWavFile));

  ASSERT_EQ(true, media_file_->IsPlaying());

  webrtc::SleepMs(1);

  ASSERT_EQ(0, media_file_->StopPlaying());
}


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import { AppRegistry } from 'react-native';
import App from './src/components/App.js';

AppRegistry.registerComponent('CRMSample', () => App);

// import React from 'react';
// import { TabNavigator } from 'react-navigation';
// import Icon from 'react-native-vector-icons/EvilIcons';
// // import PeopleList from './src/components/PeopleList.js';
// import CompanyList from './src/components/CompanyList.js';
// import AddPerson from './src/components/AddPerson.js';

// const TabBar = TabNavigator({
//   // People: { screen: PeopleList },
//   AddPerson: {
//     screen: AddPerson,
//     navigationOptions: {
//       tabBarLabel: 'Add Person',
//       tabBarIcon: ({tintColor}) => (
//         <Icon
//           name = {'plus'}
//           size = {70}
//           color = {tintColor}
//         />
//       )
//     }
//   },
//   Companies: { screen: CompanyList }
// }, {
//   tabBarOptions: {
//     activeTintColor: '#e91e63',
//     inactiveTintColor: 'white',
//     showLabel: true,
//     style: {
//       backgroundColor: '#26a69a',
//     }
//    }
// });

// AppRegistry.registerComponent('CRMSample', () => TabBar);


text:
/**
 */
package tosca.impl;

import javax.xml.namespace.QName;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import tosca.NodeTypeReferenceType;
import tosca.ToscaPackage;

/**
 *
 * An implementation of the model object 'Node Type Reference Type'.
 *
 *

 * The following features are implemented:
 *

 *
{@link tosca.impl.NodeTypeReferenceTypeImpl#getTypeRef Type Ref}

 *

 *

 *
 * @generated
 */
public class NodeTypeReferenceTypeImpl extends MinimalEObjectImpl.Container implements NodeTypeReferenceType {
	/**
	 * The default value of the '{@link #getTypeRef() Type Ref}' attribute.
	 *
	 *
	 * @see #getTypeRef()
	 * @generated
	 * @ordered
	 */
	protected static final QName TYPE_REF_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getTypeRef() Type Ref}' attribute.
	 *
	 *
	 * @see #getTypeRef()
	 * @generated
	 * @ordered
	 */
	protected QName typeRef = TYPE_REF_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected NodeTypeReferenceTypeImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return ToscaPackage.Literals.NODE_TYPE_REFERENCE_TYPE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public QName getTypeRef() {
		return typeRef;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setTypeRef(QName newTypeRef) {
		QName oldTypeRef = typeRef;
		typeRef = newTypeRef;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.NODE_TYPE_REFERENCE_TYPE__TYPE_REF, oldTypeRef, typeRef));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case ToscaPackage.NODE_TYPE_REFERENCE_TYPE__TYPE_REF:
				return getTypeRef();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case ToscaPackage.NODE_TYPE_REFERENCE_TYPE__TYPE_REF:
				setTypeRef((QName)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case ToscaPackage.NODE_TYPE_REFERENCE_TYPE__TYPE_REF:
				setTypeRef(TYPE_REF_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case ToscaPackage.NODE_TYPE_REFERENCE_TYPE__TYPE_REF:
				return TYPE_REF_EDEFAULT == null ? typeRef != null : !TYPE_REF_EDEFAULT.equals(typeRef);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (typeRef: ");
		result.append(typeRef);
		result.append(')');
		return result.toString();
	}

} //NodeTypeReferenceTypeImpl


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

#if PUBLICPROTOCOL
namespace Microsoft.Azure.WebJobs.Protocols
#else
namespace Microsoft.Azure.WebJobs.Host.Protocols
#endif
{
    /// Represents an item bound using a runtime binder parameter.
#if PUBLICPROTOCOL
    public class BinderParameterLogItem
#else
    internal class BinderParameterLogItem
#endif
    {
        /// Gets or sets the parameter descriptor.
        public ParameterDescriptor Descriptor { get; set; }

        /// Gets or sets the parameter value.
        public string Value { get; set; }

        ///
        /// Gets or sets the parameter log.
        ///
        public ParameterLog Log { get; set; }
    }
}


text:
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="refresh" content="0; url=demo/" />
        <title>mp-calendar</title>
    </head>
    <body>

    </body>
</html>


text:
Order: 55
---

# Asynchronous Tasks

Cake supports having asynchronous tasks since version 0.23.0, this will let you use the `async` and `await` C# features within a task.

Tasks will still execute single threaded and in order as before, but this really simplifies asynchronous programming and utilizing asynchronous APIs within your Cake scripts.

```csharp
Task("Copy-To-Memory-Async")
    .Does(async () =>
    {
        IFile file = Context.FileSystem.GetFile("./test.txt");
        using(Stream
            inputStream = testFile.OpenRead(),
            outputStream = new MemoryStream())
        {
            await inputStream.CopyToAsync(outputStream);
            await outputStream.FlushAsync();
            Information("Copied {0} bytes into memory.",
                outputStream.Length
            );
        }
    });
```

You can also use any parallelization mechanism such as Parallel.ForEach or Parallel.Invoke on your tasks.

```csharp
var projectPaths = new [] {
    "./src/First/First.csproj",
    "./src/Second/Second.csproj",
};

Task("BuildProjectsInParallel")
    .Does(() =>
    {
        BuildInParallel(projectPaths);
    });

Task("Default")
    .IsDependentOn("BuildProjectsInParallel")
    .Does(() =>
    {
    });

RunTarget(target);

public void BuildInParallel(
    IEnumerable<string> filePaths,
    int maxDegreeOfParallelism = -1,
    CancellationToken cancellationToken = default(CancellationToken))
{
    var actions = new List<Action>();
    foreach (var filePath in filePaths) {
        actions.Add(() =>
            MSBuild(filePath, configurator =>
                configurator.SetConfiguration("Release"))
        );
    }

    var options = new ParallelOptions {
        MaxDegreeOfParallelism = maxDegreeOfParallelism,
        CancellationToken = cancellationToken
    };

    Parallel.Invoke(options, actions.ToArray());
}
```