text:
window.esdocSearchIndex = [
  [
    "ctype-js/src/ctype.js~float32_size",
    "variable/index.html#static-variable-FLOAT32_SIZE",
    "FLOAT32_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~float64_size",
    "variable/index.html#static-variable-FLOAT64_SIZE",
    "FLOAT64_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~int16_size",
    "variable/index.html#static-variable-INT16_SIZE",
    "INT16_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~int32_size",
    "variable/index.html#static-variable-INT32_SIZE",
    "INT32_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~int8_size",
    "variable/index.html#static-variable-INT8_SIZE",
    "INT8_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~uint16_size",
    "variable/index.html#static-variable-UINT16_SIZE",
    "UINT16_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~uint32_size",
    "variable/index.html#static-variable-UINT32_SIZE",
    "UINT32_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~uint8_size",
    "variable/index.html#static-variable-UINT8_SIZE",
    "UINT8_SIZE ctype-js/src/ctype.js",
    "variable"
  ],
  [
    "ctype-js/src/ctype.js~arraytobuffer",
    "function/index.html#static-function-arrayToBuffer",
    "arrayToBuffer ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~buffertoarray",
    "function/index.html#static-function-bufferToArray",
    "bufferToArray ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~buffertostruct",
    "function/index.html#static-function-bufferToStruct",
    "bufferToStruct ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~float32",
    "function/index.html#static-function-float32",
    "float32 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~float64",
    "function/index.html#static-function-float64",
    "float64 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~int16",
    "function/index.html#static-function-int16",
    "int16 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~int32",
    "function/index.html#static-function-int32",
    "int32 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~int8",
    "function/index.html#static-function-int8",
    "int8 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~struct",
    "function/index.html#static-function-struct",
    "struct ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~structtobuffer",
    "function/index.html#static-function-structToBuffer",
    "structToBuffer ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~uint16",
    "function/index.html#static-function-uint16",
    "uint16 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~uint32",
    "function/index.html#static-function-uint32",
    "uint32 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "ctype-js/src/ctype.js~uint8",
    "function/index.html#static-function-uint8",
    "uint8 ctype-js/src/ctype.js",
    "function"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~arraybuffer",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~ArrayBuffer",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~boolean",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Boolean",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~dataview",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~DataView",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~date",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Date",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~error",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Error",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~evalerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~EvalError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~float32array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Float32Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~float64array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Float64Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~function",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Function",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~generator",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Generator",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~generatorfunction",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~GeneratorFunction",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~infinity",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Infinity",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~int16array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Int16Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~int32array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Int32Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~int8array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Int8Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~internalerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~InternalError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~json",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~JSON",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~map",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Map",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~nan",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~NaN",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~number",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Number",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~object",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Object",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~promise",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Promise",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~proxy",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Proxy",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~rangeerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~RangeError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~referenceerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~ReferenceError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~reflect",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Reflect",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~regexp",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~RegExp",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~set",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Set",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~string",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~String",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~symbol",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Symbol",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~syntaxerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~SyntaxError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~typeerror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~TypeError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~urierror",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~URIError",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~uint16array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Uint16Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~uint32array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Uint32Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~uint8array",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Uint8Array",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~uint8clampedarray",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~Uint8ClampedArray",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~weakmap",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~WeakMap",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~weakset",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~WeakSet",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~boolean",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~boolean",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~function",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~function",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~null",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~null",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~number",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~number",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~object",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~object",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~string",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~string",
    "external"
  ],
  [
    "builtinexternal/ecmascriptexternal.js~undefined",
    "external/index.html",
    "BuiltinExternal/ECMAScriptExternal.js~undefined",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~audiocontext",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~AudioContext",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~canvasrenderingcontext2d",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~CanvasRenderingContext2D",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~documentfragment",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~DocumentFragment",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~element",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~Element",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~event",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~Event",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~node",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~Node",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~nodelist",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~NodeList",
    "external"
  ],
  [
    "builtinexternal/webapiexternal.js~xmlhttprequest",
    "external/index.html",
    "BuiltinExternal/WebAPIExternal.js~XMLHttpRequest",
    "external"
  ],
  [
    "src/ctype.js",
    "file/src/ctype.js.html",
    "src/ctype.js",
    "file"
  ]
]


text:
"""Tests for the classroom page."""

from __future__ import absolute_import  # pylint: disable=import-only-modules
from __future__ import unicode_literals  # pylint: disable=import-only-modules

from constants import constants
from core.domain import config_domain
from core.domain import topic_domain
from core.domain import topic_services
from core.tests import test_utils
import feconf

class BaseClassroomControllerTests(test_utils.GenericTestBase):

    def setUp(self):
        """Completes the sign-up process for the various users."""
        super(BaseClassroomControllerTests, self).setUp()
        self.signup(self.NEW_USER_EMAIL, self.NEW_USER_USERNAME)
        self.user_id = self.get_user_id_from_email(self.NEW_USER_EMAIL)

class ClassroomPageTests(BaseClassroomControllerTests):

    def test_any_user_can_access_classroom_page(self):
        config_property = config_domain.Registry.get_config_property(
            'classroom_page_is_accessible')
        config_property.set_value('committer_id', True)
        response = self.get_html_response('/learn/math')
        self.assertIn('<classroom-page></classroom-page>', response)
        config_property.set_value('committer_id', False)

    def test_get_fails_when_classroom_page_is_accessible_not_enabled(self):
        self.get_html_response('/learn/math', expected_status_int=404)

class ClassroomDataHandlerTests(BaseClassroomControllerTests):

    def test_get(self):
        self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME)
        admin_id = self.get_user_id_from_email(self.ADMIN_EMAIL)
        self.set_admins([self.ADMIN_USERNAME])

        self.login(self.ADMIN_EMAIL, is_super_admin=True)
        topic_id_1 = topic_services.get_new_topic_id()
        topic_id_2 = topic_services.get_new_topic_id()
        private_topic = topic_domain.Topic.create_default_topic(
            topic_id_1, 'private_topic_name',
            'private-topic-name', 'description')
        topic_services.save_new_topic(admin_id, private_topic)
        public_topic = topic_domain.Topic.create_default_topic(
            topic_id_2, 'public_topic_name',
            'public-topic-name', 'description')
        public_topic.thumbnail_filename = 'Topic.svg'
        public_topic.thumbnail_bg_color = (
            constants.ALLOWED_THUMBNAIL_BG_COLORS['topic'][0])
        public_topic.subtopics = [
            topic_domain.Subtopic(
                1, 'Title', ['skill_id_1', 'skill_id_2', 'skill_id_3'],
                'image.svg',
                constants.ALLOWED_THUMBNAIL_BG_COLORS['subtopic'][0],
                'dummy-subtopic-three')]
        public_topic.next_subtopic_id = 2
        topic_services.save_new_topic(admin_id, public_topic)
        topic_services.publish_topic(topic_id_2, admin_id)

        csrf_token = self.get_new_csrf_token()
        new_config_value = [{
            'name': 'math',
            'topic_ids': [topic_id_1, topic_id_2],
            'course_details': 'Course details for classroom.',
            'topic_list_intro': 'Topics covered for classroom',
            'url_fragment': 'math',
        }]

        payload = {
            'action': 'save_config_properties',
            'new_config_property_values': {
                config_domain.CLASSROOM_PAGES_DATA.name: (
                    new_config_value),
            }
        }
        self.post_json('/adminhandler', payload, csrf_token=csrf_token)
        self.logout()

        json_response = self.get_json(
            '%s/%s' % (feconf.CLASSROOM_DATA_HANDLER, 'math'))
        topic_summary_dict = (
            topic_services.get_topic_summary_by_id(topic_id_2).to_dict())

        expected_dict = {
            'name': 'math',
            'topic_summary_dicts': [topic_summary_dict],
            'course_details': 'Course details for classroom.',
            'topic_list_intro': 'Topics covered for classroom'
        }
        self.assertDictContainsSubset(expected_dict, json_response)

    def test_get_fails_for_invalid_classroom_name(self):
        self.get_json(
            '%s/%s' % (
                feconf.CLASSROOM_DATA_HANDLER, 'invalid_subject'),
            expected_status_int=404)

class ClassroomPromosStatusHandlerTests(BaseClassroomControllerTests):
    """Unit test for ClassroomPromosStatusHandler."""

    def test_get_request_returns_correct_status(self):
        self.set_config_property(
            config_domain.CLASSROOM_PROMOS_ARE_ENABLED, False)

        response = self.get_json('/classroom_promos_status_handler')
        self.assertEqual(
            response, {
                'classroom_promos_are_enabled': False
            })

        self.set_config_property(
            config_domain.CLASSROOM_PROMOS_ARE_ENABLED, True)
        response = self.get_json('/classroom_promos_status_handler')
        self.assertEqual(
            response, {
                'classroom_promos_are_enabled': True,
            })

redpajama_set_name: RedPajamaGithub


text:
Paperdrone
==========

**Paperdrone** is a framework for writing Telegram bots using the [Telegram Bot Platform][].
Its core is as thin and modular as possible, but it provides a plugin system to add functionality
to bots.

  [Telegram Bot Platform]: https://core.telegram.org/bots/api

> This README is still under construction.  Refer to the `examples` directory in the meantime.


text:
XAML Styler is a visual studio extension that formats XAML source code based on a set of styling rules. This tool can help you/your team maintain a better XAML coding style as well as a much better XAML readability.

|[Documentation](https://github.com/Xavalon/XamlStyler/wiki)|[Script Integration](https://github.com/Xavalon/XamlStyler/wiki/Script-Integration)|[Release Notes](https://github.com/Xavalon/XamlStyler/releases)|[Contributing](https://github.com/Xavalon/XamlStyler/blob/master/CONTRIBUTING.md)|
|---|---|---|---|

[![Build Status](https://dev.azure.com/xavalon/XAML%20Styler/_apis/build/status/Release?branchName=master)](https://dev.azure.com/xavalon/XAML%20Styler/_build/latest?definitionId=2&branchName=master)

## Downloads
[![VS2022](https://img.shields.io/visual-studio-marketplace/v/TeamXavalon.XAMLStyler2022.svg?label=Visual%20Studio%202022%20(Preview))](https://marketplace.visualstudio.com/items?itemName=TeamXavalon.XAMLStyler2022)

[![VS2019](https://img.shields.io/visual-studio-marketplace/v/TeamXavalon.XAMLStyler.svg?label=Visual%20Studio%202019)](https://marketplace.visualstudio.com/items?itemName=TeamXavalon.XAMLStyler)

[![VSMAC](https://img.shields.io/badge/Visual%20Studio%20for%20Mac%202019-v2.0.1-blue.svg)](https://github.com/Xavalon/XamlStyler/files/7992390/Xavalon.XamlStyler_2.0.1.zip)

[![JetBrains IntelliJ Plugins](https://img.shields.io/jetbrains/plugin/v/14932-xaml-styler?label=JetBrains%20Rider)](https://plugins.jetbrains.com/plugin/14932-xaml-styler)

[![NuGet](https://img.shields.io/nuget/v/XamlStyler.Console.svg?label=XAML%20Styler%20Console)](https://www.nuget.org/packages/XamlStyler.Console)
View [other downloads](https://github.com/Xavalon/XamlStyler/wiki)

## Getting Started
Right-click with any file and select "Format XAML" to format your XAML source code.

![Context Menu](http://i.imgur.com/gCcNuIS.png)

[![Join the chat at https://gitter.im/Xavalon/XamlStyler](https://badges.gitter.im/Xavalon/XamlStyler.svg)](https://gitter.im/Xavalon/XamlStyler?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocket4Net;
using System.Threading.Tasks;
using System.Threading;

namespace SuperWebSocket.PerformanceTest.TestClient
{
    class Program
    {
        private static JsonWebSocket[] m_WebSockets;

        private static Semaphore m_Semaphore;

        private static volatile bool m_Stopped = false;

        private static long m_Sent = 0;

        private static long m_Received = 0;

        private static int m_ConnectedClients = 0;

        private static Timer m_PrintTimer;

        static void Main(string[] args)
        {
            int clientCount = 100;
            m_WebSockets = new JsonWebSocket[clientCount];
            m_Semaphore = new Semaphore(0, clientCount);

            m_PrintTimer = new Timer(OnPrintTimerCallback, null, 1000 * 5, 1000 * 5);

            int group = 100;

            for (var i = 0; i < clientCount; i += group)
            {
                int to = Math.Min(i + group, clientCount);

                Parallel.For(i, to, (j) =>
                {
                    m_WebSockets[j] = CreateWebSocket();
                });

                Thread.Sleep(1000);
            }

            Console.WriteLine("All clients have been created!");

            while (!Console.ReadLine().ToLower().Equals("q"))
                continue;

            m_Stopped = true;
            m_PrintTimer.Change(Timeout.Infinite, Timeout.Infinite);

            int closedNumber = 0;

            while (closedNumber < clientCount)
            {
                m_Semaphore.WaitOne();
                closedNumber++;
            }

            Console.WriteLine("All clients quit!");
            Console.ReadLine();
        }

        static JsonWebSocket CreateWebSocket()
        {
            var websocket = new JsonWebSocket("ws://127.0.0.1:2011/");

            websocket.On<string>("ECHO", HandleEchoResponse);
            websocket.Closed += new EventHandler(websocket_Closed);
            websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error);
            websocket.Opened += new EventHandler(websocket_Opened);
            websocket.Open();
            return websocket;
        }

        static void websocket_Opened(object sender, EventArgs e)
        {
            Interlocked.Increment(ref m_ConnectedClients);
            RunTest((JsonWebSocket)sender);
        }

        static void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            Console.WriteLine(e.Exception.Message + Environment.NewLine + e.Exception.StackTrace);
        }

        static void OnPrintTimerCallback(object state)
        {
            Console.WriteLine("Connected: {0}, Sent: {1}, Received: {2}", m_ConnectedClients, m_Sent, m_Received);
        }

        static void websocket_Closed(object sender, EventArgs e)
        {
            m_Semaphore.Release();
        }

        private static void HandleEchoResponse(JsonWebSocket websocket, string content)
        {
            Interlocked.Increment(ref m_Received);

            if (m_Stopped)
            {
                websocket.Close();
                return;
            }

            //Thread.Sleep(10);
            RunTest(websocket);
        }

        private static void RunTest(JsonWebSocket websocket)
        {
            websocket.Send("ECHO", Guid.NewGuid().ToString() + Guid.NewGuid().ToString() + Guid.NewGuid().ToString() + Guid.NewGuid().ToString());
            Interlocked.Increment(ref m_Sent);
        }
    }
}


text:
#include <assert.h>
#include <stdlib.h>

#include "events.h"
#include "kvpair.h"
#include "kvldskey.h"
#include "mpool.h"

#include "btree.h"
#include "btree_node.h"
#include "node.h"

#include "btree_find.h"

/* Leaf-finding state. */
struct findleaf_cookie {
	int (*callback)(void *, struct node *);
	int (*callback_range)(void *, struct node *, struct kvldskey *);
	void * cookie;
	struct btree * T;
	struct node * N;
	const struct kvldskey * k;
	int h;
	struct kvldskey * e;
};

MPOOL(findleaf, struct findleaf_cookie, 4096);

/**
 * btree_find_kvpair(N, k):
 * Search for the key ${k} in the B+Tree node ${N}.  Return a pointer to the
 * key-value pair, or NULL if the key is not present.
 */
struct kvpair_const *
btree_find_kvpair(struct node * N, const struct kvldskey * k)
{
	size_t min, max, mid;
	int rc;

	/* We must be in a leaf node. */
	assert(N->type == NODE_TYPE_LEAF);

	/*
	 * This key could be anywhere from position 0 (less than key #0) up
	 * to position N->nkeys (greater than key #(nkeys - 1)).
	 */
	min = 0;
	max = N->nkeys;

	/* Keep looking until we figure out where it belongs. */
	while (min != max) {
		/* Compare to the midpoint. */
		mid = min + (max - min) / 2;
		rc = kvldskey_cmp2(k, N->u.pairs[mid].k, N->mlen_t);

		/* Adjust endpoints. */
		if (rc < 0) {
			/* The key is less than key #mid. */
			max = mid;
		} else if (rc > 0) {
			/* The key is greater than key #mid. */
			min = mid + 1;
		} else {
			/* Found it! */
			return (&N->u.pairs[mid]);
		}
	};

	/* We didn't find it. */
	return (NULL);
}

/**
 * btree_find_child(N, k):
 * Search for the key ${k} in the B+Tree parent node ${N}.  Return the
 * number of the child responsible for the key ${key}.
 */
size_t
btree_find_child(struct node * N, const struct kvldskey * k)
{
	size_t min, max, mid;
	int rc;

	/* We must be in a parent node. */
	assert(N->type == NODE_TYPE_PARENT);

	/* This key could belong anywhere from child 0 up to N->nkeys. */
	min = 0;
	max = N->nkeys;

	/* Keep looking until we figure out where it belongs. */
	while (min != max) {
		/* Compare to the midpoint. */
		mid = min + (max - min) / 2;
		rc = kvldskey_cmp2(k, N->u.keys[mid], N->mlen_t);

		/* Adjust endpoints. */
		if (rc < 0) {
			/* The key is less than key #mid. */
			max = mid;
		} else if (rc > 0) {
			/* The key is greater than or equal to key #mid. */
			min = mid + 1;
		} else {
			/* Found it! */
			return (mid + 1);
		}
	};

	/* This must be it. */
	return (min);
}

/* Keep looking for a leaf. */
static int
findleaf(void * cookie)
{
	struct findleaf_cookie * C = cookie;
	struct node * NP = NULL;	/* Initialize to keep gcc happy. */
	size_t i;
	int rc;

	/* Sanity-check: We are now at a present node. */
	assert(node_present(C->N));

	/*
	 * Unlock the node we started at.  We don't need this lock as long as
	 * we pick up another lock before we return or make any calls which
	 * might evict a node.
	 */
	btree_node_unlock(C->T, C->N);

	/* Iterate down through parents. */
	while (node_present(C->N) && (C->N->height > C->h)) {
		/* Which child should we iterate into? */
		i = btree_find_child(C->N, C->k);

		/* Iterate into the child. */
		if ((C->e != NULL) && (i < C->N->nkeys)) {
			kvldskey_free(C->e);
			if ((C->e = kvldskey_dup(C->N->u.keys[i])) == NULL)
				goto err0;
		}
		NP = C->N;
		C->N = C->N->v.children[i];
	};

	/* If the node is not present, fetch it; else, do the callback. */
	if (!node_present(C->N)) {
		/*
		 * Lock the parent node, to make sure it doesn't get paged
		 * out before it is locked by the child we're paging in.
		 */
		btree_node_lock(C->T, NP);

		/* Fetch the child node.  This adds a lock to the parent. */
		if (btree_node_fetch(C->T, C->N, findleaf, C))
			goto err0;

		/* Release the lock we acquired on the parent node. */
		btree_node_unlock(C->T, NP);

		/* Success! */
		return (0);
	} else {
		/* We must have found a node of height <= h. */
		assert(C->N->height <= C->h);

		/* Lock the node. */
		btree_node_lock(C->T, C->N);

		/* Perform the callback. */
		if (C->e)
			rc = (C->callback_range)(C->cookie, C->N, C->e);
		else
			rc = (C->callback)(C->cookie, C->N);

		/* Free the cookie. */
		mpool_findleaf_free(C);

		/* Return status code from callback. */
		return (rc);
	}

err0:
	/* Failure! */
	return (-1);
}

/**
 * btree_find_leaf(T, N, k, callback, cookie):
 * Search for the key ${k} in the subtree of ${T} rooted at the node ${N}.
 * Invoke ${callback}(${cookie}, L) with the node ${L} locked, where ${L} is
 * the node under ${N} where the key ${k} should appear.
 */
int
btree_find_leaf(struct btree * T, struct node * N, const struct kvldskey * k,
    int (* callback)(void *, struct node *), void * cookie)
{
	struct findleaf_cookie * C;

	/* Bake a cookie. */
	if ((C = mpool_findleaf_malloc()) == NULL)
		goto err0;
	C->callback = callback;
	C->callback_range = NULL;
	C->cookie = cookie;
	C->T = T;
	C->N = N;
	C->k = k;
	C->h = 0;
	C->e = NULL;

	/* Lock the node. */
	btree_node_lock(C->T, C->N);

	/* Call into findleaf. */
	if (findleaf(C))
		goto err1;

	/* Success! */
	return (0);

err1:
	mpool_findleaf_free(C);
err0:
	/* Failure! */
	return (-1);
}

/**
 * btree_find_range(T, N, k, h, callback, cookie):
 * Search for a node of height ${h} or less in the subtree of ${T} rooted at
 * ${N} which is responsible for a range including the key ${k}.  Invoke
 * ${callback}(${cookie}, L, e} with the node ${L} locked, where ${L} is the
 * node in question and ${e} is the endpoint of the range for which ${L} is
 * responsible (or "" if ${L} extends to the end of the keyspace).  The
 * callback is responsible for freeing e.
 */
int
btree_find_range(struct btree * T, struct node * N,
    const struct kvldskey * k, int h,
    int (* callback)(void *, struct node *, struct kvldskey *),
    void * cookie)
{
	struct findleaf_cookie * C;

	/* Bake a cookie. */
	if ((C = mpool_findleaf_malloc()) == NULL)
		goto err0;
	C->callback = NULL;
	C->callback_range = callback;
	C->cookie = cookie;
	C->T = T;
	C->N = N;
	C->k = k;
	C->h = h;

	if ((C->e = kvldskey_create(NULL, 0)) == NULL)
		goto err1;

	/* Lock the node. */
	btree_node_lock(C->T, C->N);

	/* Call into findleaf. */
	if (findleaf(C))
		goto err2;

	/* Success! */
	return (0);

err2:
	kvldskey_free(C->e);
err1:
	mpool_findleaf_free(C);
err0:
	/* Failure! */
	return (-1);
}


text:
import { Component, ViewChild, ElementRef } from '@angular/core';

import { jqxListBoxComponent } from '../../../../../jqwidgets-ts/angular_jqxlistbox';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    @ViewChild('searchField') searchField: ElementRef;

    url: string = "http://api.geonames.org/searchJSON";
    // prepare the data
    source: any = {
        datatype: "jsonp",
        datafields: [
            { name: 'countryName' },
            { name: 'name' },
            { name: 'population', type: 'float' },
            { name: 'continentCode' },
            { name: 'adminName1' }
        ],
        url: this.url,
        data: {
            featureClass: "P",
            style: "full",
            maxRows: 50,
            username: "jqwidgets"
        }
    };

    dataAdapter: any = new jqx.dataAdapter(this.source, {
            formatData: (data: any): any => {
                data.name_startsWith = this.searchField.nativeElement.value;
                return data;
            }
        }
    );

    renderer: any = (index, label, value) => {
        let item = this.dataAdapter.records[index];
        if (item != null) {
            let label = item.name + "(" + item.countryName + ", " + item.adminName1 + ")";
            return label;
        }

        return "";
    };

    me: any = { timer: null };

    keyup(event: any): void {
        if (this.me.timer) {
            clearTimeout(this.me.timer);
        }

        this.me.timer = setTimeout(_ => {
            this.dataAdapter.dataBind();
        }, 300);
    };
}


text:
package com.github.epiicthundercat.tameablemobs.models.layers;

import com.github.epiicthundercat.tameablemobs.Reference;
import com.github.epiicthundercat.tameablemobs.client.render.RenderTameableSheep;
import com.github.epiicthundercat.tameablemobs.mobs.TameableSheep;
import com.github.epiicthundercat.tameablemobs.models.ModelTameableSheep1;

import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.layers.LayerRenderer;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class LayerTamedSheepWool implements LayerRenderer<TameableSheep>
{
    private static final ResourceLocation TEXTURE = new ResourceLocation(Reference.ID, "textures/entity/tameablesheep/tameablesheep_fur.png");
    private final RenderTameableSheep sheepRenderer;
    private final ModelTameableSheep1 sheepModel = new ModelTameableSheep1();

    public LayerTamedSheepWool(RenderTameableSheep sheepRendererIn)
    {
        this.sheepRenderer = sheepRendererIn;
    }

    public void doRenderLayer(TameableSheep entitylivingbaseIn, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch, float scale)
    {
        if (!entitylivingbaseIn.getSheared() && !entitylivingbaseIn.isInvisible())
        {
            this.sheepRenderer.bindTexture(TEXTURE);

            if (entitylivingbaseIn.hasCustomName() && "jeb_".equals(entitylivingbaseIn.getCustomNameTag()))
            {
                int i1 = 25;
                int i = entitylivingbaseIn.ticksExisted / 25 + entitylivingbaseIn.getEntityId();
                int j = EnumDyeColor.values().length;
                int k = i % j;
                int l = (i + 1) % j;
                float f = ((float)(entitylivingbaseIn.ticksExisted % 25) + partialTicks) / 25.0F;
                float[] afloat1 = TameableSheep.getDyeRgb(EnumDyeColor.byMetadata(k));
                float[] afloat2 = TameableSheep.getDyeRgb(EnumDyeColor.byMetadata(l));
                GlStateManager.color(afloat1[0] * (1.0F - f) + afloat2[0] * f, afloat1[1] * (1.0F - f) + afloat2[1] * f, afloat1[2] * (1.0F - f) + afloat2[2] * f);
            }
            else
            {
                float[] afloat = TameableSheep.getDyeRgb(entitylivingbaseIn.getFleeceColor());
                GlStateManager.color(afloat[0], afloat[1], afloat[2]);
            }

            this.sheepModel.setModelAttributes(this.sheepRenderer.getMainModel());
            this.sheepModel.setLivingAnimations(entitylivingbaseIn, limbSwing, limbSwingAmount, partialTicks);
            this.sheepModel.render(entitylivingbaseIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale);
        }
    }

    public boolean shouldCombineTextures()
    {
        return true;
    }
}


text:
package org.apache.wicket.authorization;

import org.apache.wicket.util.lang.EnumeratedType;
import org.apache.wicket.util.string.Strings;

/**
 * A class for constructing singleton constants that represent a given component action that needs
 * to be authorized. The Wicket core framework defines Component.RENDER and Component.ENABLE
 * actions, but future versions of the framework may add more actions and user defined components
 * can define their own actions as well.
 *
 * @see org.apache.wicket.Component#RENDER
 * @see org.apache.wicket.Component#ENABLE
 *
 * @author Eelco Hillenius
 * @author Jonathan Locke
 * @since 1.2
 */
public class Action extends EnumeratedType
{
	/**
	 * RENDER action name (for consistent name and use in annotations).
	 *

	 * DO NOT use for equals on Action, like
	 *
	 *

	 * action.equals(Action.RENDER)
	 *

	 *
	 * as you'll compare an action with a string. Rather, do:
	 *
	 *

	 * action.equals(Component.RENDER)
	 *

	 *
	 *

	 */
	public static final String RENDER = "RENDER";

	/**
	 * ENABLE action name (for consistent name and use in annotations).
	 *

	 * DO NOT use for equals on Action, like
	 *
	 *

	 * action.equals(Action.ENABLE)
	 *

	 *
	 * as you'll compare an action with a string. Rather, do:
	 *
	 *

	 * action.equals(Component.ENABLE)
	 *

	 *
	 *

	 */
	public static final String ENABLE = "ENABLE";

	private static final long serialVersionUID = -1L;

	/** The name of this action. */
	private final String name;

	/**
	 * Construct.
	 *
	 * @param name
	 *            The name of this action for debug purposes
	 */
	public Action(final String name)
	{
		super(name);
		if (Strings.isEmpty(name))
		{
			throw new IllegalArgumentException(
					"Name argument may not be null, whitespace or the empty string");
		}

		this.name = name;
	}

	/**
	 * @return The name of this action
	 */
	public String getName()
	{
		return name;
	}
}


text:
import client from 'cheerio-httpcli';
import JSON5 from 'json5';

function wait(n){
  return new Promise(resolve => setTimeout(() => resolve(), n));
};

function scrapeAll(urls, delay, alphaCount) {
  return Promise.all(urls.map(async function(url,i) {
    await wait(delay*i);
    return scrape(url, alphaCount);
  }));
}

async function scrape(url, alphaCount) {
  let result = await client.fetch(url);
  const b = JSON5.parse(result.body).bookmarks.slice(-alphaCount).map(bookmark => {return bookmark.user});
  return b;
}

export default {
  scrape: scrape,
  scrapeAll: scrapeAll
};


text:
{% load static %}
{% load core_template_filters %}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="{% static 'core/bootstrap-4.0.0/css/bootstrap.min.css' %}">

    <link rel="stylesheet" type="text/css" href="{% static 'core/datatables.min.css' %}">

    <link rel="stylesheet" href="{% static 'core/highlight.js/default.min.css' %}">

    <link href="{% static 'core/vis-4.21.0/dist/vis.min.css' %}" rel="stylesheet" type="text/css"/>

    <link href="{% static 'core/jsoneditor-5.18.0/dist/jsoneditor.min.css' %}" rel="stylesheet" type="text/css"></link>

    <link rel="stylesheet" href="{% static 'core/line-awesome/css/line-awesome.min.css' %}">

    <link href="{% static 'core/jstree/themes/default/style.min.css' %}" rel="stylesheet" type="text/css"></link>

    <link rel="stylesheet" type="text/css" href="{% static 'core/combine.css' %}">

    <title>Combine{{ page_title }}</title>

    🚜 Combine
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
            aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Organizations

                Analysis

                Published

                All Jobs

                Configuration

                Background Tasks

                Documentation

                System: Spark
                    / Tasks /  {{ COMBINE_GIT_BRANCH }} / {{ COMBINE_VERSION }}

                Log Out

        <form class="form-inline mt-2 mt-md-0" action="{% url 'search' %}" method="GET">
            <input class="form-control mr-sm-2" type="text" name="q" placeholder="search all records..."
                   aria-label="Search" {% if search_string %}value="{{ search_string }}"{% endif %}/>
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>

                {% for gm in request.session.gms %}

                        {{ gm.html|safe }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"
                                onclick="del_gm('{{ gm.id }}');">
                            ×
                        </button>

                {% endfor %}

Home

                    {% if breadcrumbs %}
                        {% for crumb in breadcrumbs %}

{{ crumb.0|safe }}

                        {% endfor %}
                    {% endif %}

    {% block content %}
    {% endblock %}


text:
namespace views {

///////////////////////////////////////////////////////////////////////////////
//
// FillLayout
//  A simple LayoutManager that causes the associated view's one child to be
//  sized to match the bounds of its parent.
//
///////////////////////////////////////////////////////////////////////////////
class VIEWS_EXPORT FillLayout : public LayoutManager {
 public:
  FillLayout();
  virtual ~FillLayout();

  // Overridden from LayoutManager:
  virtual void Layout(View* host) OVERRIDE;
  virtual gfx::Size GetPreferredSize(const View* host) const OVERRIDE;
  virtual int GetPreferredHeightForWidth(const View* host,
                                         int width) const OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(FillLayout);
};

}  // namespace views

#endif  // UI_VIEWS_LAYOUT_FILL_LAYOUT_H_


text:
// <copyright file="Utils.cs" company="Adam Nachman">
// Copyright (c) 2009 All Right Reserved Adam Nachman
// 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.
// </copyright>
// <author>Adam Nachman</author>
namespace UnitTests
{
    using System.IO;
    using System.Reflection;

    public static class Utils
    {
        /// <summary>
        /// The currently running assembly. Static, cause it should only ever get loaded once
        /// </summary>
        private static Assembly assembly = Assembly.GetExecutingAssembly();

        public static string GetResourceString(string name)
        {
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(assembly.GetManifestResourceStream(string.Concat("UnitTests.ScriptResources.", name))))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }

            return result;
        }
    }
}


text:
"""
Nodemon - Tor node monitor
"""

import sys
sys.path.append("../")
from TorCtl import *
import socket
import traceback
import re
from TorCtl.TorUtil import control_port, control_host
from TorCtl.TorUtil import *
import sched, time
import thread

class Reason:
  def __init__(self, reason): self.reason = reason
  ncircs = 0
  count = 0

class RouterStats(TorCtl.Router):
  # Behold, a "Promotion Constructor"!
  # Also allows null superclasses! Python is awesome
  def __init__(self, r=None):
    if r:
      self.__dict__ = r.__dict__
    else:
      self.down = 0
    self.reasons = {} # For a fun time, move this outside __init__
  tot_ncircs = 0
  tot_count = 0
  tot_read = 0
  tot_wrote = 0
  running_read = 0
  running_wrote = 0
  tot_age = 0

errors = {}
errors_lock = thread.allocate_lock()
key_to_name = {}
name_to_key = {}

# TODO: Move these to config file
max_detach = 3

def read_routers(c, nslist):
  bad_key = 0
  errors_lock.acquire()
  for ns in nslist:
    try:
      key_to_name[ns.idhex] = ns.nickname
      name_to_key[ns.nickname] = ns.idhex
      r = RouterStats(c.get_router(ns))
      if ns.nickname in errors:
        if errors[ns.nickname].idhex != r.idhex:
          plog("NOTICE", "Router "+r.nickname+" has multiple keys: "
             +errors[ns.nickname].idhex+" and "+r.idhex)
      errors[r.nickname] = r # XXX: We get names only from ORCONN :(
    except TorCtl.ErrorReply:
      bad_key += 1
      if "Running" in ns.flags:
        plog("INFO", "Running router "+ns.nickname+"="
           +ns.idhex+" has no descriptor")
      pass
    except:
      traceback.print_exception(*sys.exc_info())
      continue
  errors_lock.release()

# Make eventhandler
class NodeHandler(TorCtl.EventHandler):
  def __init__(self, c):
    TorCtl.EventHandler.__init__(self)
    self.c = c

  def or_conn_status_event(self, o):
    # XXX: Count all routers as one?
    if re.search(r"^\$", o.endpoint):
      if o.endpoint not in key_to_name:
        o.endpoint = "AllClients:HASH"
      else: o.endpoint = key_to_name[o.endpoint]
    elif o.endpoint not in name_to_key:
      plog("DEBUG", "IP? " + o.endpoint)
      o.endpoint = "AllClients:IP"

    if o.status == "READ" or o.status == "WRITE":
      #plog("DEBUG", "Read: " + str(read) + " wrote: " + str(wrote))
      errors_lock.acquire()
      if o.endpoint not in errors:
        plog("NOTICE", "Buh?? No "+o.endpoint)
        errors[o.endpoint] = RouterStats()
        errors[o.endpoint].nickname = o.endpoint
      errors[o.endpoint].running_read += o.read_bytes
      errors[o.endpoint].running_wrote += o.wrote_bytes
      errors_lock.release()

    if o.status == "CLOSED" or o.status == "FAILED":
      errors_lock.acquire()
      if o.endpoint not in errors:
        plog("NOTICE", "Buh?? No "+o.endpoint)
        errors[o.endpoint] = RouterStats()
        errors[o.endpoint].nickname = o.endpoint
      if o.status == "FAILED" and not errors[o.endpoint].down:
        o.status = o.status + "(Running)"
      o.reason = o.status+":"+o.reason
      if o.reason not in errors[o.endpoint].reasons:
        errors[o.endpoint].reasons[o.reason] = Reason(o.reason)
      errors[o.endpoint].reasons[o.reason].ncircs += o.ncircs
      errors[o.endpoint].reasons[o.reason].count += 1
      errors[o.endpoint].tot_ncircs += o.ncircs
      errors[o.endpoint].tot_count += 1
      if o.age: errors[o.endpoint].tot_age += o.age
      if o.read_bytes: errors[o.endpoint].tot_read += o.read_bytes
      if o.wrote_bytes: errors[o.endpoint].tot_wrote += o.wrote_bytes
      errors_lock.release()
    else: return

    if o.age: age = "AGE="+str(o.age)
    else: age = ""
    if o.read_bytes: read = "READ="+str(o.read_bytes)
    else: read = ""
    if o.wrote_bytes: wrote = "WRITTEN="+str(o.wrote_bytes)
    else: wrote = ""
    if o.reason: reason = "REASON="+o.reason
    else: reason = ""
    if o.ncircs: ncircs = "NCIRCS="+str(o.ncircs)
    else: ncircs = ""
    plog("DEBUG",
        " ".join((o.event_name, o.endpoint, o.status, age, read, wrote,
               reason, ncircs)))

  def ns_event(self, n):
    read_routers(self.c, n.nslist)

  def new_desc_event(self, d):
    for i in d.idlist: # Is this too slow?
      read_routers(self.c, self.c.get_network_status("id/"+i))

def bw_stats(key, f):
  routers = errors.values()
  routers.sort(lambda x,y: cmp(key(y), key(x))) # Python < 2.4 hack

  for r in routers:
    f.write(r.nickname+"="+str(key(r))+"\n")

  f.close()

def save_stats(s):
  errors_lock.acquire()
  # Yes yes, adding + 0.005 to age is bloody.. but who cares,
  #  1. Routers sorted by bytes read
  bw_stats(lambda x: x.tot_read, file("./data/nodemon/r_by_rbytes", "w"))
  #  2. Routers sorted by bytes written
  bw_stats(lambda x: x.tot_wrote, file("./data/nodemon/r_by_wbytes", "w"))
  #  3. Routers sorted by tot bytes
  bw_stats(lambda x: x.tot_read+x.tot_wrote,
     file("./data/nodemon/r_by_tbytes", "w"))
  #  4. Routers sorted by downstream bw
  bw_stats(lambda x: x.tot_read/(x.tot_age+0.005),
     file("./data/nodemon/r_by_rbw", "w"))
  #  5. Routers sorted by upstream bw
  bw_stats(lambda x: x.tot_wrote/(x.tot_age+0.005),
      file("./data/nodemon/r_by_wbw", "w"))
  #  6. Routers sorted by total bw
  bw_stats(lambda x: (x.tot_read+x.tot_wrote)/(x.tot_age+0.005),
      file("./data/nodemon/r_by_tbw", "w"))

  bw_stats(lambda x: x.running_read,
      file("./data/nodemon/r_by_rrunbytes", "w"))
  bw_stats(lambda x: x.running_wrote,
      file("./data/nodemon/r_by_wrunbytes", "w"))
  bw_stats(lambda x: x.running_read+x.running_wrote,
      file("./data/nodemon/r_by_trunbytes", "w"))

  f = file("./data/nodemon/reasons", "w")
  routers = errors.values()
  def notlambda(x, y):
    if y.tot_ncircs or x.tot_ncircs:
      return cmp(y.tot_ncircs, x.tot_ncircs)
    else:
      return cmp(y.tot_count, x.tot_count)
  routers.sort(notlambda)

  for r in routers:
    f.write(r.nickname+" " +str(r.tot_ncircs)+"/"+str(r.tot_count)+"\n")
    for reason in r.reasons.itervalues():
      f.write("\t"+reason.reason+" "+str(reason.ncircs)+
           "/"+str(reason.count)+"\n")

  errors_lock.release()
  f.close()
  s.enter(60, 1, save_stats, (s,))

def startmon(c):
  global key_to_name, name_to_key
  nslist = c.get_network_status()
  read_routers(c, nslist)

  s=sched.scheduler(time.time, time.sleep)

  s.enter(60, 1, save_stats, (s,))
  s.run();

def main(argv):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((control_host,control_port))
  c = TorCtl.Connection(s)
  c.set_event_handler(NodeHandler(c))
  c.launch_thread()
  c.authenticate()
  c.set_events([TorCtl.EVENT_TYPE.ORCONN,
          TorCtl.EVENT_TYPE.NS,
          TorCtl.EVENT_TYPE.NEWDESC], True)
  startmon(c)

if __name__ == '__main__':
  main(sys.argv)


text:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('async foo', function (t) {
    t.plan(10);
    var dir = path.join(__dirname, 'resolver');

    resolve('./foo', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.name, 'resolve');
    });

    resolve('./foo.js', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.name, 'resolve');
    });

    resolve('./foo', {basedir: dir, 'package': {main: 'resolver'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.main, 'resolver');
    });

    resolve('./foo.js', {basedir: dir, 'package': {main: 'resolver'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg.main, 'resolver');
    });

    resolve('foo', {basedir: dir}, function (err) {
        t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('bar', function (t) {
    t.plan(6);
    var dir = path.join(__dirname, 'resolver');

    resolve('foo', {basedir: dir + '/bar'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('foo', {basedir: dir + '/bar'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('foo', {basedir: dir + '/bar', 'package': {main: 'bar'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg, undefined);
    });
});

test('baz', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, 'resolver');

    resolve('./baz', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'baz/quux.js'));
        t.equal(pkg.main, 'quux.js');
    });

    resolve('./baz', {basedir: dir, 'package': {main: 'resolver'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'baz/quux.js'));
        t.equal(pkg.main, 'quux.js');
    });
});

test('biz', function (t) {
    t.plan(24);
    var dir = path.join(__dirname, 'resolver/biz/node_modules');

    resolve('./grux', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('./grux', {basedir: dir, 'package': {main: 'biz'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg.main, 'biz');
    });

    resolve('./garply', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('./garply', {basedir: dir, 'package': {main: 'biz'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('tiv', {basedir: dir + '/grux'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('tiv', {basedir: dir + '/grux', 'package': {main: 'grux'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('tiv', {basedir: dir + '/garply'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('tiv', {basedir: dir + '/garply', 'package': {main: './lib'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('grux', {basedir: dir + '/tiv'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('grux', {basedir: dir + '/tiv', 'package': {main: 'tiv'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('garply', {basedir: dir + '/tiv'}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('garply', {basedir: dir + '/tiv', 'package': {main: 'tiv'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });
});

test('quux', function (t) {
    t.plan(2);
    var dir = path.join(__dirname, 'resolver/quux');

    resolve('./foo', {basedir: dir, 'package': {main: 'quux'}}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo/index.js'));
        t.equal(pkg.main, 'quux');
    });
});

test('normalize', function (t) {
    t.plan(2);
    var dir = path.join(__dirname, 'resolver/biz/node_modules/grux');

    resolve('../grux', {basedir: dir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'index.js'));
        t.equal(pkg, undefined);
    });
});

test('cup', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, 'resolver');

    resolve('./cup', {basedir: dir, extensions: ['.js', '.coffee']}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'cup.coffee'));
    });

    resolve('./cup.coffee', {basedir: dir}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'cup.coffee'));
    });

    resolve('./cup', {basedir: dir, extensions: ['.js']}, function (err, res) {
        t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('mug', function (t) {
    t.plan(3);
    var dir = path.join(__dirname, 'resolver');

    resolve('./mug', {basedir: dir}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'mug.js'));
    });

    resolve('./mug', {basedir: dir, extensions: ['.coffee', '.js']}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, '/mug.coffee'));
    });

    resolve('./mug', {basedir: dir, extensions: ['.js', '.coffee']}, function (err, res) {
        t.equal(res, path.join(dir, '/mug.js'));
    });
});

test('other path', function (t) {
    t.plan(6);
    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'bar');
    var otherDir = path.join(resolverDir, 'other_path');

    resolve('root', {basedir: dir, paths: [otherDir]}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'other_path/root.js'));
    });

    resolve('lib/other-lib', {basedir: dir, paths: [otherDir]}, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js'));
    });

    resolve('root', {basedir: dir}, function (err, res) {
        t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    resolve('zzz', {basedir: dir, paths: [otherDir]}, function (err, res) {
        t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('incorrect main', function (t) {
    t.plan(1);

    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'incorrect_main');

    resolve('./incorrect_main', {basedir: resolverDir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'index.js'));
    });
});

test('without basedir', function (t) {
    t.plan(1);

    var dir = path.join(__dirname, 'resolver/without_basedir');
    var tester = require(path.join(dir, 'main.js'));

    tester(t, function (err, res, pkg) {
        if (err) {
            t.fail(err);
        } else {
            t.equal(res, path.join(dir, 'node_modules/mymodule.js'));
        }
    });
});

test('#25: node modules with the same name as node stdlib modules', function (t) {
    t.plan(1);

    var resolverDir = path.join(__dirname, 'resolver/punycode');

    resolve('punycode', {basedir: resolverDir}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'node_modules/punycode/index.js'));
    });
});

test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) {
    t.plan(2);

    var dir = path.join(__dirname, 'resolver');

    resolve('./foo', {basedir: path.join(dir, 'same_names')}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo.js'));
    });

    resolve('./foo/', {basedir: path.join(dir, 'same_names')}, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo/index.js'));
    });
});

test('async: #121 - treating an existing file as a dir when no basedir', function (t) {
    var testFile = path.basename(__filename);

    t.test('sanity check', function (st) {
        st.plan(1);
        resolve('./' + testFile, function (err, res, pkg) {
            if (err) t.fail(err);
            st.equal(res, __filename, 'sanity check');
        });
    });

    t.test('with a fake directory', function (st) {
        st.plan(4);

        resolve('./' + testFile + '/blah', function (err, res, pkg) {
            st.ok(err, 'there is an error');
            st.notOk(res, 'no result');

            st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve');
            st.equal(
                err && err.message,
                'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'',
                'can not find nonexistent module'
            );
            st.end();
        });
    });

    t.end();
});


text:
module SnsEntityNotification
  class MessageBase
    MESSAGE_PARTS = [:event, :title, :message]

    def to_json
      {
          title: title,
          type: type,
          message: message
      }
    end
  end
end


text:
L.EditToolbar.Delete = L.Handler.extend({
	statics: {
		TYPE: 'remove' // not delete as delete is reserved in js
	},

	options: {
		icon: new L.DivIcon({
			iconSize: new L.Point(26, 26),
			className: 'leaflet-div-icon leaflet-delete-icon'
		})
	},

	includes: L.Mixin.Events,

	initialize: function (map, options) {
		L.Handler.prototype.initialize.call(this, map);

		L.Util.setOptions(this, options);

		// Store the selectable layer group for ease of access
		this._deletableLayers = this.options.featureGroup;

		if (!(this._deletableLayers instanceof L.FeatureGroup)) {
			throw new Error('options.featureGroup must be a L.FeatureGroup');
		}

		// Save the type so super can fire, need to do this as cannot do this.TYPE :(
		this.type = L.EditToolbar.Delete.TYPE;
	},

	enable: function () {
		if (this._enabled || !this._hasAvailableLayers()) {
			return;
		}
		this.fire('enabled', { handler: this.type});

		this._map.fire('draw:deletestart', { handler: this.type });

		L.Handler.prototype.enable.call(this);

		this._deletableLayers
			.on('layeradd', this._enableLayerDelete, this)
			.on('layerremove', this._disableLayerDelete, this);
	},

	disable: function () {
		if (!this._enabled) { return; }

		this._deletableLayers
			.off('layeradd', this._enableLayerDelete, this)
			.off('layerremove', this._disableLayerDelete, this);

		L.Handler.prototype.disable.call(this);

		this._map.fire('draw:deletestop', { handler: this.type });

		this.fire('disabled', { handler: this.type});
	},

	addHooks: function () {
		var map = this._map;

		if (map) {
			map.getContainer().focus();

			this._deletableLayers.eachLayer(this._enableLayerDelete, this);
			this._deletedLayers = new L.LayerGroup();

//			this._tooltip = new L.Tooltip(this._map);
//			this._tooltip.updateContent({ text: L.drawLocal.edit.handlers.remove.tooltip.text });

//			this._map.on('mousemove', this._onMouseMove, this);

			if (!this._markerGroup) { this._initMarkers(); }
			this._map.addLayer(this._markerGroup);
		}
	},

	removeHooks: function () {
		if (this._map) {
			this._deletableLayers.eachLayer(this._disableLayerDelete, this);
			this._deletedLayers = null;

//			this._tooltip.dispose();
//			this._tooltip = null;
//
//			this._map.off('mousemove', this._onMouseMove, this);

			this._map.removeLayer(this._markerGroup);
			delete this._markerGroup;
			delete this._markers;
		}
	},

	revertLayers: function () {
		// Iterate of the deleted layers and add them back into the featureGroup
		this._deletedLayers.eachLayer(function (layer) {
			this._deletableLayers.addLayer(layer);
			layer.fire('revert-deleted', { layer: layer });
			this._map.fire('revert-edited', { layer: layer });
		}, this);
	},

	save: function () {
		this._map.fire('draw:deleted', { layers: this._deletedLayers });
	},

	_enableLayerDelete: function (e) {
		var layer = e.layer || e.target || e;

		layer.on('click', this._removeLayer, this);
	},

	_disableLayerDelete: function (e) {
		var layer = e.layer || e.target || e;

		layer.off('click', this._removeLayer, this);

		// Remove from the deleted layers so we can't accidently revert if the user presses cancel
		this._deletedLayers.removeLayer(layer);
	},

	_removeLayer: function (e) {
		var layer = e.layer || e.target || e;

		this._deletableLayers.removeLayer(layer);

		this._deletedLayers.addLayer(layer);

		layer.fire('deleted');
	},

//	_onMouseMove: function (e) {
//		this._tooltip.updatePosition(e.latlng);
//	},

	_hasAvailableLayers: function () {
		return this._deletableLayers.getLayers().length !== 0;
	},

	_initMarkers: function () {
		var that = this;

		if (!this._markerGroup) {
			this._markerGroup = new L.LayerGroup();
		}
		this._markers = [];

		var ll1, llDelete, onClick, llngs;

		this._deletableLayers.eachLayer(function (layer) {
			if (layer.editing._poly !== undefined || layer.editing._shape !== undefined) {
				if (layer.editing._poly) { llngs =  layer.editing._poly._latlngs; }
				if (layer.editing._shape) { llngs =  layer.editing._shape._latlngs; }

				if (!llngs || llngs.length < 2) { return; }

				ll1 = llngs[0];

				llDelete = new L.LatLng(ll1.lat, ll1.lng);

				var marker = new L.Marker(llDelete, {
					draggable: false,
					icon: that.options.icon
				});

				marker.setOpacity(0.6);

				marker._origLatLng = llDelete;

				onClick = function () {
					that._removeLayer({layer: layer});

					marker.setOpacity(1.0);
				};
				marker.on('click', onClick);

				that._markerGroup.addLayer(marker);
			}
		});
	}
});


text:
<?php
namespace ARIPD\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="forum_search")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Search {
	/**
	 * @ORM\Column(type="integer")
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\ManyToOne(targetEntity="ARIPD\UserBundle\Entity\User", inversedBy="forumthreadsearches")
	 * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
	 */
	protected $user;

	/**
	 * @ORM\Column()
	 */
	protected $query;

	/**
	 * @ORM\Column(nullable=true)
	 */
	protected $sessionId;

	/**
	 * @ORM\Column(nullable=true)
	 */
	protected $ip;

	/**
	 * @ORM\Column(type="datetime")
	 */
	protected $createdAt;

	public function __construct() {
		$this->setCreatedAt(new \DateTime());
	}

	//******************************//

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

    /**
     * Set query
     *
     * @param string $query
     * @return Search
     */
    public function setQuery($query)
    {
        $this->query = $query;

        return $this;
    }

    /**
     * Get query
     *
     * @return string
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Set sessionId
     *
     * @param string $sessionId
     * @return Search
     */
    public function setSessionId($sessionId)
    {
        $this->sessionId = $sessionId;

        return $this;
    }

    /**
     * Get sessionId
     *
     * @return string
     */
    public function getSessionId()
    {
        return $this->sessionId;
    }

    /**
     * Set ip
     *
     * @param string $ip
     * @return Search
     */
    public function setIp($ip)
    {
        $this->ip = $ip;

        return $this;
    }

    /**
     * Get ip
     *
     * @return string
     */
    public function getIp()
    {
        return $this->ip;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Search
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set user
     *
     * @param \ARIPD\UserBundle\Entity\User $user
     * @return Search
     */
    public function setUser(\ARIPD\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \ARIPD\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
package org.apache.spark.sql.streaming

import org.scalatest.BeforeAndAfterAll

import org.apache.spark.sql.catalyst.streaming.InternalOutputModes._
import org.apache.spark.sql.execution.streaming.MemoryStream
import org.apache.spark.sql.execution.streaming.state.StateStore
import org.apache.spark.sql.functions._

class DeduplicateSuite extends StateStoreMetricsTest with BeforeAndAfterAll {

  import testImplicits._

  override def afterAll(): Unit = {
    super.afterAll()
    StateStore.stop()
  }

  test("deduplicate with all columns") {
    val inputData = MemoryStream[String]
    val result = inputData.toDS().dropDuplicates()

    testStream(result, Append)(
      AddData(inputData, "a"),
      CheckLastBatch("a"),
      assertNumStateRows(total = 1, updated = 1),
      AddData(inputData, "a"),
      CheckLastBatch(),
      assertNumStateRows(total = 1, updated = 0),
      AddData(inputData, "b"),
      CheckLastBatch("b"),
      assertNumStateRows(total = 2, updated = 1)
    )
  }

  test("deduplicate with some columns") {
    val inputData = MemoryStream[(String, Int)]
    val result = inputData.toDS().dropDuplicates("_1")

    testStream(result, Append)(
      AddData(inputData, "a" -> 1),
      CheckLastBatch("a" -> 1),
      assertNumStateRows(total = 1, updated = 1),
      AddData(inputData, "a" -> 2), // Dropped
      CheckLastBatch(),
      assertNumStateRows(total = 1, updated = 0),
      AddData(inputData, "b" -> 1),
      CheckLastBatch("b" -> 1),
      assertNumStateRows(total = 2, updated = 1)
    )
  }

  test("multiple deduplicates") {
    val inputData = MemoryStream[(String, Int)]
    val result = inputData.toDS().dropDuplicates().dropDuplicates("_1")

    testStream(result, Append)(
      AddData(inputData, "a" -> 1),
      CheckLastBatch("a" -> 1),
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)),

      AddData(inputData, "a" -> 2), // Dropped from the second `dropDuplicates`
      CheckLastBatch(),
      assertNumStateRows(total = Seq(1L, 2L), updated = Seq(0L, 1L)),

      AddData(inputData, "b" -> 1),
      CheckLastBatch("b" -> 1),
      assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L))
    )
  }

  test("deduplicate with watermark") {
    val inputData = MemoryStream[Int]
    val result = inputData.toDS()
      .withColumn("eventTime", $"value".cast("timestamp"))
      .withWatermark("eventTime", "10 seconds")
      .dropDuplicates()
      .select($"eventTime".cast("long").as[Long])

    testStream(result, Append)(
      AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*),
      CheckLastBatch(10 to 15: _*),
      assertNumStateRows(total = 6, updated = 6),

      AddData(inputData, 25), // Advance watermark to 15 seconds
      CheckLastBatch(25),
      assertNumStateRows(total = 7, updated = 1),

      AddData(inputData, 25), // Drop states less than watermark
      CheckLastBatch(),
      assertNumStateRows(total = 1, updated = 0),

      AddData(inputData, 10), // Should not emit anything as data less than watermark
      CheckLastBatch(),
      assertNumStateRows(total = 1, updated = 0),

      AddData(inputData, 45), // Advance watermark to 35 seconds
      CheckLastBatch(45),
      assertNumStateRows(total = 2, updated = 1),

      AddData(inputData, 45), // Drop states less than watermark
      CheckLastBatch(),
      assertNumStateRows(total = 1, updated = 0)
    )
  }

  test("deduplicate with aggregate - append mode") {
    val inputData = MemoryStream[Int]
    val windowedaggregate = inputData.toDS()
      .withColumn("eventTime", $"value".cast("timestamp"))
      .withWatermark("eventTime", "10 seconds")
      .dropDuplicates()
      .withWatermark("eventTime", "10 seconds")
      .groupBy(window($"eventTime", "5 seconds") as 'window)
      .agg(count("*") as 'count)
      .select($"window".getField("start").cast("long").as[Long], $"count".as[Long])

    testStream(windowedaggregate)(
      AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*),
      CheckLastBatch(),
      // states in aggregate in [10, 14), [15, 20) (2 windows)
      // states in deduplicate is 10 to 15
      assertNumStateRows(total = Seq(2L, 6L), updated = Seq(2L, 6L)),

      AddData(inputData, 25), // Advance watermark to 15 seconds
      CheckLastBatch(),
      // states in aggregate in [10, 14), [15, 20) and [25, 30) (3 windows)
      // states in deduplicate is 10 to 15 and 25
      assertNumStateRows(total = Seq(3L, 7L), updated = Seq(1L, 1L)),

      AddData(inputData, 25), // Emit items less than watermark and drop their state
      CheckLastBatch((10 -> 5)), // 5 items (10 to 14) after deduplicate
      // states in aggregate in [15, 20) and [25, 30) (2 windows, note aggregate uses the end of
      // window to evict items, so [15, 20) is still in the state store)
      // states in deduplicate is 25
      assertNumStateRows(total = Seq(2L, 1L), updated = Seq(0L, 0L)),

      AddData(inputData, 10), // Should not emit anything as data less than watermark
      CheckLastBatch(),
      assertNumStateRows(total = Seq(2L, 1L), updated = Seq(0L, 0L)),

      AddData(inputData, 40), // Advance watermark to 30 seconds
      CheckLastBatch(),
      // states in aggregate in [15, 20), [25, 30) and [40, 45)
      // states in deduplicate is 25 and 40,
      assertNumStateRows(total = Seq(3L, 2L), updated = Seq(1L, 1L)),

      AddData(inputData, 40), // Emit items less than watermark and drop their state
      CheckLastBatch((15 -> 1), (25 -> 1)),
      // states in aggregate in [40, 45)
      // states in deduplicate is 40,
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L))
    )
  }

  test("deduplicate with aggregate - update mode") {
    val inputData = MemoryStream[(String, Int)]
    val result = inputData.toDS()
      .select($"_1" as "str", $"_2" as "num")
      .dropDuplicates()
      .groupBy("str")
      .agg(sum("num"))
      .as[(String, Long)]

    testStream(result, Update)(
      AddData(inputData, "a" -> 1),
      CheckLastBatch("a" -> 1L),
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)),
      AddData(inputData, "a" -> 1), // Dropped
      CheckLastBatch(),
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)),
      AddData(inputData, "a" -> 2),
      CheckLastBatch("a" -> 3L),
      assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)),
      AddData(inputData, "b" -> 1),
      CheckLastBatch("b" -> 1L),
      assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L))
    )
  }

  test("deduplicate with aggregate - complete mode") {
    val inputData = MemoryStream[(String, Int)]
    val result = inputData.toDS()
      .select($"_1" as "str", $"_2" as "num")
      .dropDuplicates()
      .groupBy("str")
      .agg(sum("num"))
      .as[(String, Long)]

    testStream(result, Complete)(
      AddData(inputData, "a" -> 1),
      CheckLastBatch("a" -> 1L),
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)),
      AddData(inputData, "a" -> 1), // Dropped
      CheckLastBatch("a" -> 1L),
      assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)),
      AddData(inputData, "a" -> 2),
      CheckLastBatch("a" -> 3L),
      assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)),
      AddData(inputData, "b" -> 1),
      CheckLastBatch("a" -> 3L, "b" -> 1L),
      assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L))
    )
  }

  test("deduplicate with file sink") {
    withTempDir { output =>
      withTempDir { checkpointDir =>
        val outputPath = output.getAbsolutePath
        val inputData = MemoryStream[String]
        val result = inputData.toDS().dropDuplicates()
        val q = result.writeStream
          .format("parquet")
          .outputMode(Append)
          .option("checkpointLocation", checkpointDir.getPath)
          .start(outputPath)
        try {
          inputData.addData("a")
          q.processAllAvailable()
          checkDataset(spark.read.parquet(outputPath).as[String], "a")

          inputData.addData("a") // Dropped
          q.processAllAvailable()
          checkDataset(spark.read.parquet(outputPath).as[String], "a")

          inputData.addData("b")
          q.processAllAvailable()
          checkDataset(spark.read.parquet(outputPath).as[String], "a", "b")
        } finally {
          q.stop()
        }
      }
    }
  }

  test("SPARK-19841: watermarkPredicate should filter based on keys") {
    val input = MemoryStream[(Int, Int)]
    val df = input.toDS.toDF("time", "id")
      .withColumn("time", $"time".cast("timestamp"))
      .withWatermark("time", "1 second")
      .dropDuplicates("id", "time") // Change the column positions
      .select($"id")
    testStream(df)(
      AddData(input, 1 -> 1, 1 -> 1, 1 -> 2),
      CheckLastBatch(1, 2),
      AddData(input, 1 -> 1, 2 -> 3, 2 -> 4),
      CheckLastBatch(3, 4),
      AddData(input, 1 -> 0, 1 -> 1, 3 -> 5, 3 -> 6), // Drop (1 -> 0, 1 -> 1) due to watermark
      CheckLastBatch(5, 6),
      AddData(input, 1 -> 0, 4 -> 7), // Drop (1 -> 0) due to watermark
      CheckLastBatch(7)
    )
  }

  test("SPARK-21546: dropDuplicates should ignore watermark when it's not a key") {
    val input = MemoryStream[(Int, Int)]
    val df = input.toDS.toDF("id", "time")
      .withColumn("time", $"time".cast("timestamp"))
      .withWatermark("time", "1 second")
      .dropDuplicates("id")
      .select($"id", $"time".cast("long"))
    testStream(df)(
      AddData(input, 1 -> 1, 1 -> 2, 2 -> 2),
      CheckLastBatch(1 -> 1, 2 -> 2)
    )
  }
}


text:
Home

Edit Data Status Kehadiran

                    Edit Status Kehadiran

                    <?php $this->load->view('layouts/alert')?>
                    <form action="<?php echo site_url('status_kehadiran/update')?>" method="post" class="form-horizontal">

                            Nama Status Kehadiran

                                <input type="hidden" name="id" value="<?php echo $status_kehadiran->id ?>">
                                <input type="text" class="form-control" name="nama" placeholder="Nama Unit" value="<?php echo $status_kehadiran->nama?>">

                                <button type="submit" class="btn btn-primary"> Simpan</button>

                    </form>


text:
package com.morcinek.android.codegenerator.extractor.model;

public class Resource {

    private ResourceId resourceId;

    private ResourceType resourceType;

    public Resource(ResourceId resourceId, ResourceType resourceType) {
        this.resourceId = resourceId;
        this.resourceType = resourceType;
    }

    public ResourceId getResourceId() {
        return resourceId;
    }

    public ResourceType getResourceType() {
        return resourceType;
    }
}


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    os_libgen.h
 *
 *  definitions for pattern matching functions
 *
 *  $Id: os_libgen.h 14 2007-02-01 15:49:12Z mitza $
 *
 *  @author Don Hinton <dhinton@dresystems.com>
 *  @author This code was originally in various places including ace/OS.h.
 */
//=============================================================================

#ifndef ACE_OS_INCLUDE_OS_LIBGEN_H
#define ACE_OS_INCLUDE_OS_LIBGEN_H

#include /**/ "ace/pre.h"

#include /**/ "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if !defined (ACE_LACKS_LIBGEN_H)
# include /**/ <libgen.h>
#endif /* !ACE_LACKS_LIBGEN_H */

// Place all additions (especially function declarations) within extern "C" {}
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */

#ifdef __cplusplus
}
#endif /* __cplusplus */

#include /**/ "ace/post.h"
#endif /* ACE_OS_INCLUDE_OS_LIBGEN_H */


text:
package gv.jleon
package facade

import shapeless.{ HNil }

import config.{ Config }

final class JLeon()(
  implicit
  val actorSystem: ActorSystem = ActorSystem("JLeon"),
  val config:      Config      = Config("jleon")
) extends AnyRef
    with ImplicitConstructions {

  implicit val akkaHttpExt: HttpExt = createAkkaHttpExt
  implicit val materializer: Materializer = createAkkaActorMaterializer

  implicit val fetchStrategyRepository: domain.FetchRepository = createFetchStrategyRepository

  val mirrors: MirrorRepository = {
    implicit val mirrorConfig: MirrorsConfig = config.mirrors
    Mirror.fromConfig
  }

  val storage: Storage = {
    implicit val storageConfig: StorageConfig = config.storage
    Storage.fromConfig
  }

  val fetchManager: FetchManager = mirrors :: storage :: HNil

  @inline def shutdown(): Future[akka.actor.Terminated] = actorSystem.terminate()
}

object JLeon {

  final object MIRROR_PREFIX {
    val ARCH = "arch"
    val all: Traversable[String] = Vector(ARCH)
  }

  final def apply(): JLeon = new JLeon()
}


text:
package com.norconex.committer.googlecloudsearch;

import com.google.common.io.ByteStreams;
import com.norconex.importer.doc.ImporterMetadata;
import com.norconex.importer.handler.ImporterHandlerException;
import com.norconex.importer.handler.tagger.IDocumentTagger;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
import java.util.Base64;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * Provides access to the unparsed document content for the
 * {@code GoogleCloudSearchCommitter} when using the {@code raw} upload format.
 *
 *
XML configuration usage

 *
 *

 *  <tagger class="com.norconex.committer.googlecloudsearch.BinaryContentTagger"/>
 *

 */
public class BinaryContentTagger implements IDocumentTagger {
  private static final Logger LOG = LogManager.getLogger(MethodHandles.lookup().lookupClass());

  @Override
  public void tagDocument(
      String reference, InputStream document, ImporterMetadata metadata, boolean parsed)
      throws ImporterHandlerException {
    if (parsed) {
      String errMsg =
          "Document is already parsed. Please make sure the <tagger ... /> entry is inside the"
              + " <preParseHandlers> list!";
      throw new ImporterHandlerException(errMsg);
    }
    addContentInBase64(document, metadata);
  }

  private void addContentInBase64(InputStream document, ImporterMetadata metadata)
      throws ImporterHandlerException {
    try {
      byte[] content = ByteStreams.toByteArray(document);
      metadata.addString(
          GoogleCloudSearchCommitter.FIELD_BINARY_CONTENT,
          Base64.getEncoder().encodeToString(content));
    } catch (IOException e) {
      throw new ImporterHandlerException(e);
    }
  }
}


text:
package com.github.swierkosz.execasync;

import com.github.swierkosz.execasync.polling.ApplicationTerminatedException;
import com.github.swierkosz.execasync.polling.Poller;
import org.gradle.process.internal.ExecHandle;
import org.gradle.process.internal.ExecHandleBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.gradle.process.internal.ExecHandleState.ABORTED;
import static org.gradle.process.internal.ExecHandleState.STARTED;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class AbstractPollingExecAsyncTaskTest extends AbstractTaskTest {

    @Mock
    private ExecHandleBuilder execHandleBuilder;

    @Mock
    private ExecHandle execHandle;

    @Mock
    private Poller poller;

    private TestableAbstractPollingExecAsyncTask task;

    @Before
    public void setUp() {
        task = createTask(TestableAbstractPollingExecAsyncTask.class);

        task.setExecHandleBuilder(execHandleBuilder);
        given(execHandleBuilder.build()).willReturn(execHandle);
        given(execHandle.getState()).willReturn(STARTED);

        task.setPoller(poller);
    }

    @Test
    public void shouldSetAndReturnTimeout() {
        // Given
        int timeout = 123456;

        // When
        task.setTimeout(timeout);
        int result = task.getTimeout();

        // Then
        assertThat(result).isEqualTo(timeout);
    }

    @Test
    public void shouldReturnDefaultTimeout() {
        // When
        int result = task.getTimeout();

        // Then
        assertThat(result).isEqualTo(300);
    }

    @Test
    public void shouldWaitForApplicationToStart() {
        // Given
        int timeout = 1234;
        task.setTimeout(timeout);

        // When
        task.exec();

        // Then
        verify(poller).awaitAtMost(eq(timeout), eq(TimeUnit.SECONDS), any(Callable.class));
    }

    @Test(expected = ApplicationTerminatedException.class)
    public void shouldThrowExceptionWhenApplicationHasTerminated() throws Exception {
        // Given
        given(execHandle.getState()).willReturn(ABORTED);
        task.exec();
        ArgumentCaptor<Callable> callableArgumentCaptor = ArgumentCaptor.forClass(Callable.class);
        verify(poller).awaitAtMost(anyInt(), any(TimeUnit.class), callableArgumentCaptor.capture());
        Callable callable = callableArgumentCaptor.getValue();

        // When
        callable.call();

        // Then exception is thrown
    }

    @Test
    public void shouldReturnFalseWhenApplicationIsNotReady() throws Exception {
        // Given
        task.exec();
        ArgumentCaptor<Callable> callableArgumentCaptor = ArgumentCaptor.forClass(Callable.class);
        verify(poller).awaitAtMost(anyInt(), any(TimeUnit.class), callableArgumentCaptor.capture());
        Callable<Boolean> callable = (Callable<Boolean>) callableArgumentCaptor.getValue();

        // When
        Boolean result = callable.call();

        // Then
        assertThat(result).isFalse();
    }

    @Test
    public void shouldReturnTrueWhenApplicationIsReady() throws Exception {
        // Given
        task.ready = true;
        task.exec();
        ArgumentCaptor<Callable> callableArgumentCaptor = ArgumentCaptor.forClass(Callable.class);
        verify(poller).awaitAtMost(anyInt(), any(TimeUnit.class), callableArgumentCaptor.capture());
        Callable<Boolean> callable = (Callable<Boolean>) callableArgumentCaptor.getValue();

        // When
        Boolean result = callable.call();

        // Then
        assertThat(result).isTrue();
    }

    public static class TestableAbstractPollingExecAsyncTask extends AbstractPollingExecAsyncTask<TestableAbstractPollingExecAsyncTask> {

        private boolean ready = false;

        public TestableAbstractPollingExecAsyncTask() {
            super(TestableAbstractPollingExecAsyncTask.class);
        }

        @Override
        protected boolean isApplicationReady() {
            return ready;
        }
    }
}


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

namespace SZip
{
    /// <summary>
    /// SZip使用例/テスト
    /// </summary>
    public class SZipExample : MonoBehaviour
    {
        void Start()
        {
            //SZipソースを圧縮
            string SZipDir = Path.Combine(Application.dataPath, "Plugins/SZip/Scripts");
            DirectoryInfo dirInfo = new DirectoryInfo(SZipDir);
            if (!dirInfo.Exists)
            {
                Debug.LogError("not found SZip scripts dir : " + SZipDir);
                return;
            }

            FileInfo[] fileInfos = dirInfo.GetFiles("*.cs", SearchOption.TopDirectoryOnly);
            if (fileInfos == null || fileInfos.Length <= 0)
            {
                Debug.LogError("not found SZip scripts");
                return;
            }

            Debug.Log("SZip is going to containt " + fileInfos.Length + " files");

            SZip.SZipFileDeflate szipDeflate = new SZip.SZipFileDeflate();
            foreach (var info in fileInfos)
            {
                var data = File.ReadAllBytes(info.FullName);
                szipDeflate.EntryContent("SZip/Scripts/" + info.Name, info);
            }

            var compressed = szipDeflate.Deflate();

            //圧縮したデータを解凍して比較
            SZip.SZipFileInflate szipInflate = new SZip.SZipFileInflate();
            szipInflate.Prepare(compressed);

            //要素数チェック
            if (szipInflate.ContentCount != fileInfos.Length)
            {
                Debug.LogError("Content Count does not match");
                return;
            }

            for (int contentIndex = 0; contentIndex < szipInflate.ContentCount; contentIndex++)
            {
                var originalData = File.ReadAllBytes(fileInfos[contentIndex].FullName);
                var originalDataHash = SZip.SZipUtility.FNVHash(originalData);

                //圧縮前データサイズチェック
                if (originalData.Length != szipInflate.GetContent(contentIndex).OriginalDataSize)
                {
                    Debug.LogError("Original Data Size does not match" + fileInfos[contentIndex].Name);
                }

                //解凍後ハッシュ値チェック
                var uncompressData = szipInflate.Inflate(contentIndex);
                var uncompressDataHash = SZip.SZipUtility.FNVHash(uncompressData);
                if (originalDataHash != uncompressDataHash)
                {
                    Debug.LogError("Uncompress Data does not match : " + fileInfos[contentIndex].Name);
                }

                Debug.Log("Uncompressed " + szipInflate.GetContentName(contentIndex));
            }
            Debug.Log("Compress/Uncompress success all");
        }
    }
}


text:
#ifndef otbScalarImageToTexturesFilter_h
#define otbScalarImageToTexturesFilter_h

#include "otbGreyLevelCooccurrenceIndexedList.h"
#include "itkImageToImageFilter.h"

namespace otb
{
/**
 * \class ScalarImageToTexturesFilter
 * \brief This class compute 8 local Haralick textures features. The 8 output
 * image channels are: Energy, Entropy, Correlation, Inverse Difference Moment,
 * Inertia, Cluster Shade, Cluster Prominence and Haralick Correlation. They
 * are provided in this exact order in the output image. Thus, this application
 * computes the following Haralick textures over a neighborhood with user
 * defined radius.
 *
 * To improve the speed of computation, a variant of Grey Level Co-occurrence
 * Matrix(GLCM) called Grey Level Co-occurrence Indexed List (GLCIL) is
 * used. Given below is the mathematical explanation on the computation of each
 * textures. Here $ g(i, j) $ is the frequency of element in the GLCIL whose
 * index is i, j. GLCIL stores a pair of frequency of two pixels from the given
 * offset and the cell index (i, j) of the pixel in the neighborhood
 * window. :(where each element in GLCIL is a pair of pixel index and it's
 * frequency, $ g(i, j) $ is the frequency value of the pair having index is i, j).
 *
 * "Energy" \f$ = f_1 = \sum_{i, j}g(i, j)^2 \f$
 *
 * "Entropy" \f$ = f_2 = -\sum_{i, j}g(i, j) \log_2 g(i, j)\f$, or 0 if \f$g(i, j) = 0\f$
 *
 * "Correlation" \f$ = f_3 = \sum_{i, j}\frac{(i - \mu)(j - \mu)g(i, j)}{\sigma^2} \f$
 *
 * "Difference Moment" \f$= f_4 = \sum_{i, j}\frac{1}{1 + (i - j)^2}g(i, j) \f$
 *
 * "Inertia" \f$ = f_5 = \sum_{i, j}(i - j)^2g(i, j) \f$ (sometimes called "contrast")
 *
 * "Cluster Shade" \f$ = f_6 = \sum_{i, j}((i - \mu) + (j - \mu))^3 g(i, j) \f$
 *
 * "Cluster Prominence" \f$ = f_7 = \sum_{i, j}((i - \mu) + (j - \mu))^4 g(i, j) \f$
 *
 * "Haralick's Correlation" \f$ = f_8 = \frac{\sum_{i, j}(i, j) g(i, j) -\mu_t^2}{\sigma_t^2} \f$
 * where \f$\mu_t\f$ and \f$\sigma_t\f$ are the mean and standard deviation of the row
 * (or column, due to symmetry) sums.
 *
 * Above, \f$ \mu =  \f$ (weighted pixel average) \f$ = \sum_{i, j}i \cdot g(i, j) =
 * \sum_{i, j}j \cdot g(i, j) \f$ (due to matrix symmetry), and
 *
 * \f$ \sigma =  \f$ (weighted pixel variance) \f$ = \sum_{i, j}(i - \mu)^2 \cdot g(i, j) =
 * \sum_{i, j}(j - \mu)^2 \cdot g(i, j)  \f$  (due to matrix symmetry)
 *

 * References:
 *
 * Haralick, R.M., K. Shanmugam and I. Dinstein. 1973.  Textural Features for
 * Image Classification. IEEE Transactions on Systems, Man and Cybernetics.
 * SMC-3(6):610-620.
 *
 * David A. Clausi and Yongping Zhao. 2002. Rapid extraction of image texture by
 * co-occurrence using a hybrid data structure. Comput. Geosci. 28, 6 (July
 * 2002), 763-774. DOI=10.1016/S0098-3004(01)00108-X
 * http://dx.doi.org/10.1016/S0098-3004(01)00108-X
 *
 * de O.Bastos, L.; Liatsis, P.; Conci, A., Automatic texture segmentation based
 * on k-means clustering and efficient calculation of co-occurrence
 * features. Systems, Signals and Image Processing, 2008. IWSSIP 2008. 15th
 * International Conference on , vol., no., pp.141,144, 25-28 June 2008
 * doi: 10.1109/IWSSIP.2008.4604387
 *
 * Neighborhood size can be set using the SetRadius() method. Offset for co-occurence estimation
 * is set using the SetOffset() method.
 *
 * \sa otb::GreyLevelCooccurrenceIndexedList
 * \sa otb::ScalarImageToAdvancedTexturesFiler
 * \sa otb::ScalarImageToHigherOrderTexturesFilter
 *
 * \ingroup Streamed
 * \ingroup Threaded
 *
 *
 * \ingroup OTBTextures
 */
template <class TInpuImage, class TOutputImage>
class ScalarImageToTexturesFilter : public itk::ImageToImageFilter<TInpuImage, TOutputImage>
{
public:
  /** Standard class typedefs */
  typedef ScalarImageToTexturesFilter Self;
  typedef itk::ImageToImageFilter<TInpuImage, TOutputImage> Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Creation through the object factory */
  itkNewMacro(Self);

  /** RTTI */
  itkTypeMacro(ScalarImageToTexturesFilter, ImageToImageFilter);

  /** Template class typedefs */
  typedef TInpuImage                          InputImageType;
  typedef typename InputImageType::Pointer    InputImagePointerType;
  typedef typename InputImageType::PixelType  InputPixelType;
  typedef typename InputImageType::RegionType InputRegionType;
  typedef typename InputRegionType::SizeType  SizeType;
  typedef typename InputImageType::OffsetType OffsetType;

  typedef TOutputImage                         OutputImageType;
  typedef typename OutputImageType::Pointer    OutputImagePointerType;
  typedef typename OutputImageType::RegionType OutputRegionType;

  typedef GreyLevelCooccurrenceIndexedList<InputPixelType>            CooccurrenceIndexedListType;
  typedef typename CooccurrenceIndexedListType::Pointer               CooccurrenceIndexedListPointerType;
  typedef typename CooccurrenceIndexedListType::ConstPointer          CooccurrenceIndexedListConstPointerType;
  typedef typename CooccurrenceIndexedListType::IndexType             CooccurrenceIndexType;
  typedef typename CooccurrenceIndexedListType::PixelValueType        PixelValueType;
  typedef typename CooccurrenceIndexedListType::RelativeFrequencyType RelativeFrequencyType;
  typedef typename CooccurrenceIndexedListType::VectorType            VectorType;

  typedef typename VectorType::iterator       VectorIteratorType;
  typedef typename VectorType::const_iterator VectorConstIteratorType;

  /** Set the radius of the window on which textures will be computed */
  itkSetMacro(Radius, SizeType);
  /** Get the radius of the window on which textures will be computed */
  itkGetMacro(Radius, SizeType);

  /** Set the offset for co-occurence computation */
  itkSetMacro(Offset, OffsetType);

  /** Get the offset for co-occurence computation */
  itkGetMacro(Offset, OffsetType);

  /** Set the number of bin per axis */
  itkSetMacro(NumberOfBinsPerAxis, unsigned int);

  /** Get the number of bin per axis */
  itkGetMacro(NumberOfBinsPerAxis, unsigned int);

  /** Set the input image minimum */
  itkSetMacro(InputImageMinimum, InputPixelType);

  /** Get the input image minimum */
  itkGetMacro(InputImageMinimum, InputPixelType);

  /** Set the input image maximum */
  itkSetMacro(InputImageMaximum, InputPixelType);

  /** Get the input image maximum */
  itkGetMacro(InputImageMaximum, InputPixelType);

  /** Set the sub-sampling factor */
  itkSetMacro(SubsampleFactor, SizeType);

  /** Get the sub-sampling factor */
  itkGetMacro(SubsampleFactor, SizeType);

  /** Set the sub-sampling offset */
  itkSetMacro(SubsampleOffset, OffsetType);

  /** Get the sub-sampling offset */
  itkGetMacro(SubsampleOffset, OffsetType);

  /** Get the energy output image */
  OutputImageType* GetEnergyOutput();

  /** Get the entropy output image */
  OutputImageType* GetEntropyOutput();

  /** Get the correlation output image */
  OutputImageType* GetCorrelationOutput();

  /** Get the inverse difference moment output image */
  OutputImageType* GetInverseDifferenceMomentOutput();

  /** Get the inertia output image */
  OutputImageType* GetInertiaOutput();

  /** Get the cluster shade output image */
  OutputImageType* GetClusterShadeOutput();

  /** Get the cluster prominence image */
  OutputImageType* GetClusterProminenceOutput();

  /** Get the Haralick correlation output image */
  OutputImageType* GetHaralickCorrelationOutput();

protected:
  /** Constructor */
  ScalarImageToTexturesFilter();
  /** Destructor */
  ~ScalarImageToTexturesFilter() override;
  /** Generate the output information */
  void GenerateOutputInformation() override;
  /** Generate the input requested region */
  void GenerateInputRequestedRegion() override;
  /** Before Parallel textures extraction */
  void BeforeThreadedGenerateData() override;
  /** Parallel textures extraction */
  void ThreadedGenerateData(const OutputRegionType& outputRegion, itk::ThreadIdType threadId) override;

private:
  ScalarImageToTexturesFilter(const Self&) = delete;
  void operator=(const Self&) = delete;

  /** Convenient method to compute union of 2 regions */
  static OutputRegionType RegionUnion(const OutputRegionType& region1, const OutputRegionType& region2);

  /** Radius of the window on which to compute textures */
  SizeType m_Radius;

  /** Offset for co-occurence */
  OffsetType m_Offset;

  /** Radius of the neighborhood iterator which is minimum of m_Radius */
  SizeType m_NeighborhoodRadius;

  /** Number of bins per axis */
  unsigned int m_NumberOfBinsPerAxis;

  /** Input image minimum */
  InputPixelType m_InputImageMinimum;

  /** Input image maximum */
  InputPixelType m_InputImageMaximum;

  // TODO: should we use constexpr? only c++11 and problem for msvc
  inline double GetPixelValueTolerance() const
  {
    return 0.0001;
  }

  /** Sub-sampling factor */
  SizeType m_SubsampleFactor;

  /** Sub-sampling offset */
  OffsetType m_SubsampleOffset;
};
} // End namespace otb

#ifndef OTB_MANUAL_INSTANTIATION
#include "otbScalarImageToTexturesFilter.hxx"
#endif

#endif