text:
package helpers

import (
	"errors"
	"fmt"
	"github.com/yuin/gopher-lua"
	"strconv"
)

var (
	errFunction = errors.New("cannot encode function to JSON")
	errChannel  = errors.New("cannot encode channel to JSON")
	errState    = errors.New("cannot encode state to JSON")
	errUserData = errors.New("cannot encode userdata to JSON")
	errNested   = errors.New("cannot encode recursively nested tables to JSON")
)

type jsonValue struct {
	lua.LValue
	marshallFunc func(v interface{}) ([]byte, error)
	visited      map[*lua.LTable]bool
}

func (j jsonValue) MarshalJSON() ([]byte, error) {
	return ToJSON(j.LValue, j.visited, j.marshallFunc)
}
func ToGoValue(lv lua.LValue) interface{} {
	switch v := lv.(type) {
	case *lua.LNilType:
		return nil
	case lua.LBool:
		return bool(v)
	case lua.LString:
		return string(v)
	case lua.LNumber:
		return float64(v)
	case *lua.LTable:
		maxn := v.MaxN()
		if maxn == 0 { // table
			ret := make(map[string]interface{})
			v.ForEach(func(key, value lua.LValue) {
				keystr := fmt.Sprint(ToGoValue(key))
				ret[ToCamelCaseOrUnderscore(keystr)] = ToGoValue(value)
			})
			return ret
		}
		ret := make([]interface{}, 0, maxn)
		for i := 1; i <= maxn; i++ {
			ret = append(ret, ToGoValue(v.RawGetInt(i)))
		}
		return ret
	default:
		return v
	}
}
func ToJSON(value lua.LValue, visited map[*lua.LTable]bool, marshallFunc func(v interface{}) ([]byte, error)) (data []byte, err error) {
	switch converted := value.(type) {
	case lua.LBool:
		data, err = marshallFunc(converted)
	case lua.LChannel:
		err = errChannel
	case lua.LNumber:
		data, err = marshallFunc(converted)
	case *lua.LFunction:
		err = errFunction
	case *lua.LNilType:
		data, err = marshallFunc(converted)
	case *lua.LState:
		err = errState
	case lua.LString:
		data, err = marshallFunc(converted)
	case *lua.LTable:
		var arr []jsonValue
		var obj map[string]jsonValue

		if visited[converted] {
			panic(errNested)
		}
		visited[converted] = true

		converted.ForEach(func(k lua.LValue, v lua.LValue) {
			i, numberKey := k.(lua.LNumber)
			if numberKey && obj == nil {
				index := int(i) - 1
				if index != len(arr) {
					// map out of order; convert to map
					obj = make(map[string]jsonValue)
					for i, value := range arr {
						obj[strconv.Itoa(i+1)] = value
					}
					obj[strconv.Itoa(index+1)] = jsonValue{v, marshallFunc, visited}
					return
				}
				arr = append(arr, jsonValue{v, marshallFunc, visited})
				return
			}
			if obj == nil {
				obj = make(map[string]jsonValue)
				for i, value := range arr {
					obj[strconv.Itoa(i+1)] = value
				}
			}
			obj[k.String()] = jsonValue{v, marshallFunc, visited}
		})
		if obj != nil {
			data, err = marshallFunc(obj)
		} else {
			data, err = marshallFunc(arr)
		}
	case *lua.LUserData:
		// TODO: call metatable __tostring?
		err = errUserData
	}
	return
}
func FromJSON(L *lua.LState, value interface{}) lua.LValue {
	switch converted := value.(type) {
	case bool:
		return lua.LBool(converted)
	case float64:
		return lua.LNumber(converted)
	case string:
		return lua.LString(converted)
	case []interface{}:
		arr := L.CreateTable(len(converted), 0)
		for _, item := range converted {
			arr.Append(FromJSON(L, item))
		}
		return arr
	case map[string]interface{}:
		tbl := L.CreateTable(0, len(converted))
		for key, item := range converted {
			tbl.RawSetH(lua.LString(key), FromJSON(L, item))
		}
		return tbl
	}
	return lua.LNil
}


text:
id: babel-plugin-transform-modules-amd
title: @babel/plugin-transform-modules-amd
sidebar_label: transform-modules-amd
---

## Example

**In**

```javascript
export default 42;
```

**Out**

```javascript
define(["exports"], function (exports) {
  "use strict";

  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  exports.default = 42;
});
```

## Installation

```sh
npm install --save-dev @babel/plugin-transform-modules-amd
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
  "plugins": ["@babel/plugin-transform-modules-amd"]
}
```

### Via CLI

```sh
babel --plugins @babel/plugin-transform-modules-amd script.js
```

### Via Node API

```javascript
require("@babel/core").transform("code", {
  plugins: ["@babel/plugin-transform-modules-amd"]
});
```

### Options

See options for `@babel/plugin-transform-modules-commonjs`.

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. K. Small & A. M. Vail, Mem. Torrey Bot. Club 4:112. 1894

#### Original name
null

### Remarks
null


text:
interface TemplateInfo {
    id: string;
    path: string;
}

class TemplateLoader {
    public static onload: () => void;

    static staticlyLoaded(): void {
        if (TemplateLoader.onload) TemplateLoader.onload();
    }

    static load(templates: Array<TemplateInfo>) : void {
        var loadedTemplates = 0;
        for (var i = 0; i < templates.length; i++)
        {
            (function () {

                var tpl = templates[i];
                var id = tpl.id;

                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange =
                    () => {
                        if (xmlhttp.readyState !== 4)
                            return;

                        if (xmlhttp.status !== 200 && xmlhttp.status !== 0)
                            throw "Failed to load template.";

                        var scriptEl = document.createElement("script");

                        var typeAttr = document.createAttribute("type");
                        typeAttr.value = "text/html";

                        var idAttr = document.createAttribute("id");
                        idAttr.value = id;

                        scriptEl.setAttributeNode(typeAttr);
                        scriptEl.setAttributeNode(idAttr);

                        scriptEl.innerHTML = xmlhttp.responseText;
                        document.body.appendChild(scriptEl);

                        loadedTemplates++;

                        if (loadedTemplates == templates.length && TemplateLoader.onload)
                            TemplateLoader.onload();
                    };

                xmlhttp.open("GET", tpl.path, true);
                xmlhttp.send();
            })();
        };
    }
}


text:
package org.apache.commons.vfs2.impl.test;

import java.io.File;
import java.io.FileWriter;

import org.apache.commons.AbstractVfsTestCase;
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;

/**
 * Test to verify DefaultFileMonitor
 */
public class DefaultFileMonitorTests extends AbstractVfsTestCase
{
    private FileSystemManager fsManager;
    private File testDir;
    private int changeStatus = 0;
    private File testFile;

    @Override
    public void setUp() throws Exception
    {
        super.setUp();
        fsManager = VFS.getManager();
        testDir = AbstractVfsTestCase.getTestDirectoryFile();
        changeStatus = 0;
        testFile = new File(testDir, "testReload.properties");

        if (testFile.exists())
        {
            testFile.delete();
        }
    }

    @Override
    public void tearDown() throws Exception
    {
        if (testFile != null && testFile.exists())
        {
            testFile.delete();
        }
        super.tearDown();
    }

    public void testFileCreated() throws Exception
    {
        FileObject fileObj = fsManager.resolveFile(testFile.toURL().toString());
        DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
        monitor.setDelay(100);
        monitor.addFile(fileObj);
        monitor.start();
        writeToFile(testFile);
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event", changeStatus == 3);
        monitor.stop();
    }

    public void testFileDeleted() throws Exception
    {
        writeToFile(testFile);
        FileObject fileObj = fsManager.resolveFile(testFile.toURL().toString());
        DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
        monitor.setDelay(100);
        monitor.addFile(fileObj);
        monitor.start();
        testFile.delete();
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event", changeStatus == 2);
        monitor.stop();
    }

    public void testFileModified() throws Exception
    {
        writeToFile(testFile);
        FileObject fileObj = fsManager.resolveFile(testFile.toURL().toString());
        DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
        monitor.setDelay(100);
        monitor.addFile(fileObj);
        monitor.start();
        // Need a long delay to insure the new timestamp doesn't truncate to be the same as
        // the current timestammp. Java only guarantees the timestamp will be to 1 second.
        Thread.sleep(1000);
        long value = System.currentTimeMillis();
        boolean rc = testFile.setLastModified(value);
        assertTrue("setLastModified succeeded",rc);
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event", changeStatus == 1);
        monitor.stop();
    }

    public void testFileRecreated() throws Exception
    {
        FileObject fileObj = fsManager.resolveFile(testFile.toURL().toString());
        DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
        monitor.setDelay(100);
        monitor.addFile(fileObj);
        monitor.start();
        writeToFile(testFile);
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event " + changeStatus, changeStatus == 3);
        changeStatus = 0;
        testFile.delete();
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event " + changeStatus, changeStatus == 2);
        changeStatus = 0;
        Thread.sleep(500);
        monitor.addFile(fileObj);
        writeToFile(testFile);
        Thread.sleep(300);
        assertTrue("No event occurred", changeStatus != 0);
        assertTrue("Incorrect event " + changeStatus, changeStatus == 3);
        monitor.stop();
    }

    private void writeToFile(File file) throws Exception
    {
        FileWriter out = new FileWriter(file);
        out.write("string=value1");
        out.flush();
        out.close();
    }

    public class TestFileListener implements FileListener
    {
        public void fileChanged(FileChangeEvent event) throws Exception
        {
            changeStatus = 1;
        }

        public void fileDeleted(FileChangeEvent event) throws Exception
        {
            changeStatus = 2;
        }

        public void fileCreated(FileChangeEvent event) throws Exception
        {
            changeStatus = 3;
        }
    }

}


text:
let _private = {};

// @TODO: replace with crypto.randomBytes
_private.getRandomInt = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

/**
 * Return a unique identifier with the given `len`.
 *
 * @param {Number} maxLength
 * @return {String}
 * @api private
 */
module.exports.uid = function uid(maxLength) {
    const buf = [];
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charLength = chars.length;
    let i;

    for (i = 0; i < maxLength; i = i + 1) {
        buf.push(chars[_private.getRandomInt(0, charLength - 1)]);
    }

    return buf.join('');
};


text:
/**
 * Example RF Radio Ping Pair
 *
 * This is an example of how to use the RF24 class.  Write this sketch to two different nodes,
 * connect the role_pin to ground on one.  The ping node sends the current time to the pong node,
 * which responds by sending the value back.  The ping node can then see how long the whole cycle
 * took.
 */

#include <cstdlib>
#include <iostream>

#include "../RF24.h"

//
// Hardware configuration
//

// Set up nRF24L01 radio on SPI bus plus pins 9 & 10

//RF24 radio(9,10);
RF24 radio("/dev/spidev0.0",2000000 , 25);  //spi device, speed and CE,only CE is NEEDED in RPI

// sets the role of this unit in hardware.  Connect to GND to be the 'pong' receiver
// Leave open to be the 'ping' transmitter
const int role_pin = 7;

//
// Topology
//

// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

//
// Role management
//
// Set up role.  This sketch uses the same software for all the nodes
// in this system.  Doing so greatly simplifies testing.  The hardware itself specifies
// which node it is.
//
// This is done through the role_pin
//

// The various roles supported by this sketch
typedef enum { role_ping_out = 1, role_pong_back } role_e;

// The debug-friendly names of those roles
const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

// The role of the current running sketch
role_e role;

void setup(void)
{
  //
  // Role
  //

  // set up the role pin
 // pinMode(role_pin, INPUT);
  //digitalWrite(role_pin,HIGH);
 // delay(20); // Just to get a solid reading on the role pin

  // read the address pin, establish our role
  //if ( ! digitalRead(role_pin) )
  //  role = role_ping_out;
  //else
    role = role_pong_back;

  //
  // Print preamble:
  //

  //Serial.begin(115200);
  //printf_begin();
  printf("\n\rRF24/examples/pingpair/\n\r");
  printf("ROLE: %s\n\r",role_friendly_name[role]);

  //
  // Setup and configure rf radio
  //

  radio.begin();

  // optionally, increase the delay between retries & # of retries
  radio.setRetries(15,15);

  // optionally, reduce the payload size.  seems to
  // improve reliability
//  radio.setPayloadSize(8);
 radio.setChannel(0x4c);
     radio.setPALevel(RF24_PA_LOW);

  //
  // Open pipes to other nodes for communication
  //

  // This simple sketch opens two pipes for these two nodes to communicate
  // back and forth.
  // Open 'our' pipe for writing
  // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)

  if ( role == role_ping_out )
  {
    radio.openWritingPipe(pipes[0]);
    radio.openReadingPipe(1,pipes[1]);
  }
  else
  {
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);
  }

  //
  // Start listening
  //

  radio.startListening();

  //
  // Dump the configuration of the rf unit for debugging
  //

  radio.printDetails();
}

void loop(void)
{
  //
  // Ping out role.  Repeatedly send the current time
  //

  if (role == role_ping_out)
  {
    // First, stop listening so we can talk.
    radio.stopListening();

    // Take the time, and send it.  This will block until complete
    unsigned long time = __millis();
    printf("Now sending %lu...",time);
    bool ok = radio.write( &time, sizeof(unsigned long) );

    if (ok)
      printf("ok...");
    else
      printf("failed.\n\r");

    // Now, continue listening
    radio.startListening();

    // Wait here until we get a response, or timeout (250ms)
    unsigned long started_waiting_at = __millis();
    bool timeout = false;
    while ( ! radio.available() && ! timeout ) {
        // by bcatalin » Thu Feb 14, 2013 11:26 am
        __msleep(5); //add a small delay to let radio.available to check payload
      if (__millis() - started_waiting_at > 200 )
        timeout = true;
    }

    // Describe the results
    if ( timeout )
    {
      printf("Failed, response timed out.\n\r");
    }
    else
    {
      // Grab the response, compare, and send to debugging spew
      unsigned long got_time;
      radio.read( &got_time, sizeof(unsigned long) );

      // Spew it
      printf("Got response %lu, round-trip delay: %lu\n\r",got_time,__millis()-got_time);
    }

    // Try again 1s later
//    delay(1000);
sleep(1);
  }

  //
  // Pong back role.  Receive each packet, dump it out, and send it back
  //

  if ( role == role_pong_back )
  {
    // if there is data ready
    if ( radio.available() )
    {
      // Dump the payloads until we've gotten everything
      unsigned long got_time;
      bool done = false;
      while (!done)
      {
        // Fetch the payload, and see if this was the last one.
        done = radio.read( &got_time, sizeof(unsigned long) );

        // Spew it
        printf("Got payload %lu...",got_time);

	// Delay just a little bit to let the other unit
	// make the transition to receiver
	delay(20);
      }

      // First, stop listening so we can talk
      radio.stopListening();

      // Send the final one back.
      printf("Sent response.\n\r");
      radio.write( &got_time, sizeof(unsigned long) );

      // Now, resume listening so we catch the next packets.
      radio.startListening();
    }
  }
}

int main(int argc, char** argv)
{
        setup();
        while(1)
                loop();

        return 0;
}

// vim:cin:ai:sts=2 sw=2 ft=cpp


text:
--drop proc sspBatchWAU
create proc sspBatchWAU
as
set nocount on
declare @LastRunDT datetimeoffset(7)
declare @CurrentDT datetimeoffset(7)
declare @nowdt datetime
declare @WAU bigint
set @nowdt = (select getutcdate())
--select @nowdt as nowdt
set @CurrentDT = ((SELECT DATETIMEFROMPARTS (DATEPART(year, @nowdt), DATEPART(month,@nowdt), DATEPART(day, @nowdt), 0, 0, 0, 0)))
--select @CurrentDT as CurrentDT
set @LastRunDT = (dateadd(day, -7, @CurrentDT))
--select @LastRunDT as LastRunDT

set @WAU = (select count(*) from members where LastLoginDT between @LastRunDT and @CurrentDT)
insert into StatsData(CategoryName, CountNum, Fields, Groups) values('WAU', @WAU, CONVERT(nvarchar(8), GETUTCDATE(), 112), '')
GO

------------------------------------------------------------------
-- run test
--exec sspBatchWAU
------------------------------------------------------------------

/*
select * from StatsData order by createdat desc
select * from Members
select count(*) from members where LastLoginDT between '2016-05-09 15:00:03.1749825 +00:00' and sysutcdatetime()

-- test data value
update Members set LastLoginDT = sysutcdatetime() where memberid like 'bbb'
update Members set LastLoginDT = sysutcdatetime() where memberid like 'ccc'
update Members set LastLoginDT = sysutcdatetime() where memberid like 'ddd'

select sysutcdatetime()
select dateadd(day, -7, sysutcdatetime())
select CONVERT(nvarchar(20), getutcdate(), 112)

declare @nowdt datetime
set @nowdt = (select getutcdate())
SELECT DATEPART(year, @nowdt) + '-' + DATEPART(month,@nowdt) + '-' +  DATEPART(day, @nowdt);
SELECT convert(datetime, getutcdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm

--test week
declare @nowdt datetime
declare @CurrentDT datetimeoffset(7)
declare @testdt datetimeoffset(7)
declare @testdt2 datetimeoffset(7)

set @nowdt = (select getutcdate())
set @CurrentDT = ((SELECT DATETIMEFROMPARTS (DATEPART(year, @nowdt), DATEPART(month,@nowdt), DATEPART(day, @nowdt), DATEPART(hour, @nowdt), 0, 0,0 )))
set @testdt = (dateadd(day, -6, @CurrentDT))
set @testdt2 = (dateadd(day, -8, @CurrentDT))

update Members set LastLoginDT = @testdt where memberid like 'aaa3'
update Members set LastLoginDT = @testdt2 where memberid like 'aaa4'
exec sspBatchWAU
select * from StatsData where CategoryName like 'WAU' order by createdat desc
*/


text:
import unittest
from core.deal import Deal

class DealTest(unittest.TestCase):
    def test_identifier(self):
        deal = Deal.from_string(
            "23456789TJQKA... .23456789TJQKA.. ..23456789TJQKA. ...23456789TJQKA")
        self.assertEqual(deal.identifier, '0000001555555aaaaaabffffff')
        self.assertEqual(deal.pretty_one_line(), Deal.from_identifier(
            deal.identifier).pretty_one_line())

    def test_random(self):
        # Just make sure the random code path does not assert, and returns something non-None.
        self.assertTrue(bool(Deal.random()))

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


text:
<?php

namespace PerrysLambda\IO;

class DirectoryIteratorNoDots extends \FilterIterator
{

    public function __construct($path)
    {
        parent::__construct(new DirectoryIterator($path));
    }

    public function accept()
    {
        $c = basename($this->getInnerIterator()->current());
        return ($c!="." && $c!="..");
    }

}


text:
<?php
namespace frontend\components;
use yii;
use app\kent\e24PaymentPipe;
require_once(__DIR__ . '/knet/com/aciworldwide/commerce/gateway/plugins/e24PaymentPipe.inc.php');

class KnetPayment {
    public $response_url;
    public $error_url;
    public $ammount;
    public $udf1 = "";
    public $udf2 = "";
    public $udf3 = "";
    public $udf4 = "";
    public $udf5 = "";
    public $action = 1;
    public $currency = 414;
    public $lang = "ARA";
    public $alias = "";
    public function run()
    {
        $Pipe = new e24PaymentPipe();
        $Pipe->setAction($this->action);
        $Pipe->setCurrency($this->currency);
        $Pipe->setLanguage($this->lang); //change it to "ARA" for arabic language
        $Pipe->setResponseURL($this->response_url); // set your respone page URL
        $Pipe->setErrorURL($this->error_url); //set your error page URL
        $Pipe->setAmt($this->ammount); //set the amount for the transaction
        $Pipe->setResourcePath(__DIR__."/knet/resource/"); //change the path where your resource file is
        $Pipe->setAlias($this->alias); //set your alias name here
        $Pipe->setTrackId(rand(45645,4446));//generate the random number here

        $Pipe->setUdf1($this->udf1); //set User defined value
        $Pipe->setUdf2($this->udf2); //set User defined value
        $Pipe->setUdf3($this->udf3); //set User defined value
        $Pipe->setUdf4($this->udf4); //set User defined value
        $Pipe->setUdf5($this->udf5); //set User defined value

        //get results
        if($Pipe->performPaymentInitialization()!= $Pipe->SUCCESS){
            $result['status'] = 'error';
            $result['url'] = '';
            $result['payment_id'] = $Pipe->getPaymentId();
            $result['msg'] = $Pipe->getErrorMsg();
        }else {
            $payID = $Pipe->getPaymentId();
            $payURL = $Pipe->getPaymentPage();
            if(empty($payID)){
                $result['status'] = 'error';
                $result['url'] = '';
                $result['payment_id'] = $Pipe->getPaymentId();
                $result['msg'] = $payURL;
            }else{
                $result['status'] = 'success';
                $result['payment_id'] = $Pipe->getPaymentId();
                $result['url'] = $payURL."?PaymentID=".$payID;
            }
        }
        return json_encode($result);
    }
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:oxm="http://www.springframework.org/schema/oxm"
       xsi:schemaLocation="
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
                        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd">

    <context:property-placeholder location="classpath:*.properties" />

    <!-- JSR-303 support will be detected on classpath and enabled automatically -->
    <mvc:annotation-driven conversion-service="conversionService"/>

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="ai.elimu.logic.converters.StringToAllophoneConverter" />
                <bean class="ai.elimu.logic.converters.StringToApplicationConverter" />
                <bean class="ai.elimu.logic.converters.StringToAppCategoryConverter" />
                <bean class="ai.elimu.logic.converters.StringToContributorConverter" />
                <bean class="ai.elimu.logic.converters.StringToNullConverter" />
                <bean class="ai.elimu.logic.converters.StringToProjectConverter" />
                <bean class="ai.elimu.logic.converters.StringToWordConverter" />
                <bean class="ai.elimu.logic.converters.StringToImageConverter" />
            </list>
        </property>
    </bean>

    <context:component-scan base-package="ai.elimu" />

    <task:annotation-driven />

    <!--
             - This bean resolves specific types of exceptions to corresponding logical
             - view names for error views. The default behaviour of DispatcherServlet
             - is to propagate all exceptions to the servlet container: this will happen
             - here with all other types of exceptions.
     -->
    <bean id="exceptionResolver" class="ai.elimu.web.servlet.CustomSimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.web.servlet.PageNotFound">error/page-not-found</prop>
                <prop key="org.springframework.dao.DataAccessException">error/data-access-failure</prop>
                <prop key="org.springframework.transaction.TransactionException">error/data-access-failure</prop>
            </props>
        </property>
        <property name="warnLogCategory" value="CustomSimpleMappingExceptionResolver" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="209715200" /><!-- 200MB -->
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <!--
             - The BeanNameViewResolver is used to pick up the visits view name (below).
             - It has the order property set to 1, which means that this will
             - be the first view resolver to be used after the delegating content
             - negotiating view resolver.
      -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1" />

    <!--
             - This bean configures the 'prefix' and 'suffix' properties of
             - InternalResourceViewResolver, which resolves logical view names
             - returned by Controllers. For example, a logical view name of "vets"
             - will be mapped to "/WEB-INF/jsp/vets.jsp".
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" p:order="2" />

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    <bean name="viewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/error/403">viewController</prop>
                <prop key="/error/404">viewController</prop>
                <prop key="/error/500">viewController</prop>
                <prop key="/error/data-access-failure">viewController</prop>
                <prop key="/error/page-not-found">viewController</prop>
                <prop key="/error/session-timeout">viewController</prop>

                <prop key="/donate">viewController</prop>
                <prop key="/publish">viewController</prop>

                <prop key="/content/community/issue-management">viewController</prop>
            </props>
        </property>
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
          p:basenames="WEB-INF/i18n/messages, WEB-INF/i18n/errors, WEB-INF/i18n/countries"
          p:defaultEncoding="UTF-8"
          p:fileEncodings="UTF-8"
          p:cacheSeconds="5" />

    <mvc:interceptors>
        <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
              p:paramName="lang" />
        <bean class="ai.elimu.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>

    <bean id="localeResolver" class="ai.elimu.web.servlet.i18n.DomainLocaleResolver"
          p:defaultLocale="en_US" />
</beans>


text:
package software.amazon.awssdk.core.auth.policy.internal;

import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Writer;

public final class JacksonUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    private JacksonUtils() {
    }

    /**
     * Returns the deserialized object from the given json string and target
     * class; or null if the given json string is null.
     */
    public static <T> T fromJsonString(String json, Class<T> clazz) {
        if (json == null) {
            return null;
        }

        return invokeSafely(() -> OBJECT_MAPPER.readValue(json, clazz));
    }

    public static JsonNode jsonNodeOf(String json) {
        return fromJsonString(json, JsonNode.class);
    }

    public static JsonGenerator jsonGeneratorOf(Writer writer) throws IOException {
        return new JsonFactory().createGenerator(writer);
    }
}


text:
(function () {
    angular.module("toastCE", ["ngSanitize", "ngAnimate"]);
})();


text:
import Header from './Header'

export default function Page({ children }) {
  return (
    <div>
      <Header />
      {children}
    </div>
  )
}


text:
def GetChromeApkOsVersion(version_name):
  version = version_name[0]
  assert version.isupper(), (
      'First character of versions name %s was not an uppercase letter.')
  if version < 'L':
    return 'k'
  elif version > 'M':
    return 'n'
  return 'l'


text:
Pattern: Lambda body is too long

Issue: -

## Description

Similar to anonymous inner classes, if lambda body becomes very long it is hard to understand and to see the flow of the method where the lambda is defined. Therefore long lambda body should usually be extracted to method.

## Examples

```java
class Test {
  Runnable r = () -> { // violation, 11 lines
      System.out.println(2); // line 2 of lambda
      System.out.println(3);
      System.out.println(4);
      System.out.println(5);
      System.out.println(6);
      System.out.println(7);
      System.out.println(8);
      System.out.println(9);
      System.out.println(10);
  }; // line 11

  Runnable r2 = () -> // violation, 11 lines
      "someString".concat("1") // line 1 of lambda
                  .concat("2")
                  .concat("3")
                  .concat("4")
                  .concat("5")
                  .concat("6")
                  .concat("7")
                  .concat("8")
                  .concat("9")
                  .concat("10")
                  .concat("11"); // line 11

  Runnable r3 = () -> { // ok, 10 lines
      System.out.println(2); // line 2 of lambda
      System.out.println(3);
      System.out.println(4);
      System.out.println(5);
      System.out.println(6);
      System.out.println(7);
      System.out.println(8);
      System.out.println(9);
  }; // line 10
}

```

## Further Reading

* [checkstyle - LambdaBodyLength](https://checkstyle.org/config_sizes.html#LambdaBodyLength)


text:
import React from 'react'
import HeaderUiComponent from './header_ui.js'
import { notification } from 'antd'
import {connect} from 'react-redux'

class HeaderComponent extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
			selectedKey: "",
			showModal: false
		}

		this.handleSelect = this.handleSelect.bind(this);
		this.handleModelToggle = this.handleModelToggle.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
		this.handleLogOut = this.handleLogOut.bind(this);
	}

	componentDidMount() {
		if(!this.props.categories.length) {
			fetch('/categories.json')
			.then((response) => response.json())
			.then((json) => {

				let categories = json.data.categories;
				(categories.length > 10) && (categories.length = 10);

				this.props.changeCategories(categories);

		   		/*this.setState({
		   			categories: categories
		   		})*/
			})
			.catch((ex) => {
				console.log('parsing failed', ex)
			})
		}
	}

	handleLogOut() {

		notification.open({
		    message: '退出成功',
		    description: '欢迎再来',
		});

		this.props.handleLogout();

	}

	handleSubmit() {

		notification.open({
		    message: '登陆成功',
		    description: '最近有活动,欢迎大家积极参与'
		});

		this.setState({
			showModal: false,
		})

		this.props.handleLogin()
	}

	handleSelect(params) {
		this.setState({
			selectedKey: params.key
		})
	}

	handleModelToggle() {
		this.setState({
			showModal: !this.state.showModal
		})
	}

	render() {
		return (
			<HeaderUiComponent {...this.state} categories={this.props.categories} login={this.props.login} handleLogOut={this.handleLogOut} handleSubmit={this.handleSubmit} handleModelToggle={this.handleModelToggle} handleSelect={this.handleSelect} />
		)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(HeaderComponent)

//state指的就是store里面的state, 实际上是store里的数据
//props 指的是组件里的props
function mapStateToProps(state) {
	return {
		login: state.login,
		categories: state.categories
	}
}

function mapDispatchToProps(dispatch) {
  return {
  	changeCategories: function(categories) {
  		let action = {
  			type: "CHANGE_CATEGORIES",
  			values: categories
  		}
  		dispatch(action)
  	},
  	handleLogout: function() {
  		let action = {
			type: "LOGOUT"
		}

		dispatch(action);
  	},
  	handleLogin: function() {
  		let action = {
			type: "LOGIN"
		}
		dispatch(action);
  	}
  }
}


text:
classdef BaslerCamera < Device
    %BASLERCAMERA Summary of this class goes here
    %   Class representing BaslerCamera object. Any sort of communcation
    %   between the physical Basler Camera installed in the user's
    %   computer environment and the TweezerControl application is done
    %   through the BaslerCamera device object.

    properties
        % Set device type using DeviceType enumeration class
        Type = DeviceType.BaslerCamera;

        % Handle to Camera object (from MATLAB driver)
        CameraHandle

        % .NET assembly created from Basler Camera driver files
        NETAssembly

        % Variable representing serial number of physical camera
        % represented by our BaslerCamera object
        SerialNumber
    end

    properties (Dependent)
        % Various dependent image cropping parameters that, when accesses,
        % always query the Basler Ace Camera model (acA3800-14um) driver
        % methods. All are in units of pixels
        MaxHeight

        MinHeight

        MaxWidth

        MinWidth

        MaxOffsetX

        MinOffsetX

        MaxOffsetY

        MinOffsetY

        Height

        Width

        OffsetX

        OffsetY
        % -------------------END IMAGE CROPPING PARAMETERS-----------------
        % Various dependent parameters representing different sensor
        % parameters for the Basler Ace Camera model (acA3800-14um)

        % Maximum exposure time for each image in microseconds
        MaxExposureTime

        % Minimum exposure time for each image in microseconds
        MinExposureTime

        % Exposure time for each image in microseconds
        ExposureTime

        % Maximum gain for each image in dB
        MaxGain

        % Minimum gain for each image in dB
        MinGain

        % Gain for each image in dB
        Gain

        % Pixel format
        PixelFormat
        % ----------------------END SENSOR PARAMETERS----------------------

        % Various dependent parameters representing information about the
        % physical Basler Camera represented by the BaslerCamera object
        % (e.g., serial number)
    end

    methods
        % Constructor for BaslerCamera object; attempts to discover and
        %   initialize the first Basler Camera that is discovered by the
        %   program
        %
        % index: index of device of type BaslerCamera; all indices for
        %   devices of a specific type should be unique; start the indexing
        %   at 0 for all devices

        function obj = BaslerCamera(index, verbosity, serialNumbers)
            % Call Superclass constructor firt to avoid redundancies
            obj = obj@Device(index, verbosity);

            % Get driver dll for Basler Camera and create an assembly out
            % of it
            dllName=['C:\Users\Endres Lab\Desktop\TweezerControl\'...
                'Dependencies\Devices\Basler Ace camera'...
                '\Drivers\Basler.Pylon.dll'];
            obj.NETAssembly = NET.addAssembly(dllName);

            % Use try loop to avoid crashing program if no Basler is found
            % during initialization process
            try
                obj.SerialNumber = serialNumbers(obj.Index + 1, :);

                % Create the CameraHandle, choosing the serial number based
                % on the position in the serialNumbers array and the index
                % of the specific device
                obj.CameraHandle = Basler.Pylon.Camera(obj.SerialNumber);

                % Open the camera
                obj.CameraHandle.Open();

                % Set ShutterMode to Rolling
                obj.CameraHandle.Parameters.Item(...
                    'ShutterMode').SetValue('Rolling');

                % Set Acqusition Mode to Single Frame
                obj.CameraHandle.Parameters.Item(...
                    'AcquisitionMode').SetValue('Continuous');

                % Select FrameBurstStart trigger and disable it
                obj.CameraHandle.Parameters.Item(...
                    'TriggerSelector').SetValue('FrameBurstStart');
                obj.CameraHandle.Parameters.Item(...
                    'TriggerMode').SetValue('Off');

                % Disable frame rate parameter
                obj.CameraHandle.Parameters.Item(...
                    'AcquisitionFrameRateEnable').SetValue(false);

                % Select FrameBurstStart trigger and disable it
                obj.CameraHandle.Parameters.Item(...
                    'TriggerSelector').SetValue('FrameStart');
                obj.CameraHandle.Parameters.Item(...
                    'TriggerMode').SetValue('On');

                % Set trigger mode to software for higher framerates while
                % grabbing images
                obj.CameraHandle.Parameters.Item(...
                    'TriggerSource').SetValue('Software');

                % Set ExposureMode to timed so we can define our own
                % exposure times
                obj.CameraHandle.Parameters.Item(...
                    'ExposureMode').SetValue('Timed');

                % Set GainAuto to off so that we may set gain manually
                obj.CameraHandle.Parameters.Item(...
                    'GainAuto').SetValue('Off');

                % Enable Chunks from camera, then enable timestamp chunks
                obj.CameraHandle.Parameters.Item(...
                    'ChunkModeActive').SetValue(true);

                obj.CameraHandle.Parameters.Item(...
                    'ChunkSelector').SetValue('Timestamp');

                obj.CameraHandle.Parameters.Item(...
                    'ChunkEnable').SetValue(true);

                % Initialize acquisition so that there is no latency when
                % we need to spontaenously grab frames.
                obj.CameraHandle.Parameters.Item(...
                    'AcquisitionStart').Execute();

                % At this point, the camera has been succesfully
                % initialized so we may set initialized to true
                obj.Initialized = true;

                % Initialize acquisition so that there is no latency when
                % we need to spontaenously grab frames. We use
                % GrabStrategy=2 and GrabLoop=1
                 obj.CameraHandle.StreamGrabber.Start(...
                     Basler.Pylon.GrabStrategy.LatestImages, ...
                     Basler.Pylon.GrabLoop.ProvidedByUser);

                 % Reset sensor parameters
                obj.resetSensor();

            catch ME
                % Display error message
                disp(getReport(ME))
                fprintf('BaslerCamera construction failed. \n');
                obj.Initialized = false;

                % Check if CameraHandle exists before attempting to shutdown
                % the device
                if (~isempty(obj.CameraHandle))
                    if (obj.CameraHandle.IsOpen)
                        obj.shutdownDevice();
                    end
                end
            end
        end

        % Reset sensor parameters to defaults
        function resetSensor(obj)
            % Define offsets first because they directly affect the Height
            % and Width definable for the camera
            obj.OffsetX = obj.MinOffsetX + 1;
            obj.OffsetY = obj.MinOffsetY + 1;
            obj.Height = obj.MaxHeight - 1;
            obj.Width = obj.MaxWidth - 1;
            obj.OffsetX = obj.MinOffsetX + 1;
            obj.OffsetY = obj.MinOffsetY + 1;

            obj.Gain = 1;
            obj.ExposureTime = 10^3; % 1 ms (units of microseconds!)
            % Set Pixel format to 8bit mono (FOR 12BIT MONO: use 'Mono12'
           obj.PixelFormat = 'Mono8';
        end

        % Get image from BaslerCamera object. The timestamp returned is
        % measured in seconds relative to the time the camera was turned
        % on.
        function [success, image, timestamp] = capture(obj)
            if (obj.CameraHandle.IsOpen)
                % Timeout of grabbing frames, always make sure it has
                % enough time regardless of exposure time so give an extra
                % 500 miliseconds. Additionally, make sure that we don't
                % lose any precision from obj.ExposureTime being (most
                % likely) an integer
                timeout=int32(obj.ExposureTime /10^3 + 500.0);
                if (obj.CameraHandle.WaitForFrameTriggerReady(...
                    timeout, Basler.Pylon.TimeoutHandling.ThrowException))
                    % Execute software trigger
                    obj.CameraHandle.ExecuteSoftwareTrigger();
                    framerate = obj.CameraHandle.Parameters.Item(...
                    'ResultingFrameRate').GetValue();

                    % Grab result of camera
                    grabResult=obj.CameraHandle.StreamGrabber.RetrieveResult(...
                    timeout, Basler.Pylon.TimeoutHandling.ThrowException);

                    % Make sure grab succeeded
                    if (grabResult.GrabSucceeded)
                        numCols = obj.Width;

                        switch obj.PixelFormat
                            case 'Mono8'
                                % Convert pixel buffer data to uint8 image
                                 image = vec2mat(uint8(...
                                     grabResult.PixelData), double(numCols));
                            case 'Mono12'
                                image = vec2mat(uint16(...
                                    grabResult.PixelData), double(numCols));
                            case 'Mono12p'
                                image = vec2mat(uint16(...
                                    grabResult.PixelData), double(numCols));
                            otherwise
                                fprintf(['Error: PixelFormat not recognized.'...
                                    ' Receieved:\n']);
                                disp(obj.PixelFormat)
                        end

                        % Get timestamp in units of ticks, where each tick is
                        % equivalent to 1 ns. Thus, we must scale this such that it
                        % is in seconds. The timestamp is measured relative to the
                        % time at which the camera turned on, so the timestamp is
                        % basically the camera on-time until the specific image was
                        % taken
                        timestamp = double(grabResult.Timestamp) / 10^9;

                        % Return success
                        success = true;

                        % Dispose result when completed so that the buffer is
                        % emptied
                        grabResult.Dispose();

                        % Give camera time to breath
                        pause(1/framerate)
                    else
                        success = false;
                        image = [];
                        timestamp = 0;
                        fprintf('Error: Grab failed \n');
                    end
                end
            else
                success = false;
                image = [];
                timestamp = 0;
                fprintf('Error: camera not open, no image acquired\n');
            end
        end

        % Display device info (inherited from Device class)
        function displayDeviceInfo(obj)
            % Extend inherited displayDeviceInfo() function
            displayDeviceInfo@Device(obj);
        end

        % Shutdown device (inherited from Device class)
        function shutdownDevice(obj)
            % Stop streamgrabber so that we may shutdown
            obj.CameraHandle.StreamGrabber.Stop();

            % Stop acquisition
            obj.CameraHandle.Parameters.Item(...
                    'AcquisitionStart').Execute();

            % Release resources
            obj.CameraHandle.Dispose();
            % Delete BaslerCamera so that we can open it up again
            obj.CameraHandle.Close();

            if (obj.Verbose)
                disp('BaslerCamera stopped')
            end
        end
    end

    % Separate helper functions from more high-level functions
    methods

        % ---------------------SETTER FUNCTIONS----------------------------
        % Setter method for setting obj.Height. Includes error checking
        % based on the actual Basler Ace Camera model (acA3800-14um). NOTE:
        % MAKE SURE THAT YOU PASS A SIGNED 64-BIT INTEGER TO SetValue() OR
        % ELSE IT WILL THROW AN ERROR
        function set.Height(obj, height)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinHeight;
            max = obj.MaxHeight;
            if (isnumeric(height) && ((height > min) && (height < max)))
                obj.CameraHandle.Parameters.Item('Height').SetValue(...
                    int64(height));
            else
                fprintf(['Error: expected an integer Height < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(height)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.Width. Includes error checking
        % based on the actual Basler Ace Camera model (acA3800-14um)
        function set.Width(obj, width)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinWidth;
            max = obj.MaxWidth;
            if (isnumeric(width) && ((width > min) && (width < max)))
                obj.CameraHandle.Parameters.Item('Width').SetValue(...
                    int64(width));
            else
                fprintf(['Error: expected an integer Width < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(width)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.OffsetX. Includes error checking
        % based on the actual Basler Ace Camera model (acA3800-14um)
        function set.OffsetX(obj, offsetx)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinOffsetX;
            max = obj.MaxOffsetX;
            if (isnumeric(offsetx) && ((offsetx > min) && (offsetx < max)))
                obj.CameraHandle.Parameters.Item('OffsetX').SetValue(...
                    int64(offsetx));
            else
                fprintf(['Error: expected an integer OffsetX < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(offsetx)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.OffsetY. Includes error checking
        % based on the actual Basler Ace Camera model (acA3800-14um)
        function set.OffsetY(obj, offsety)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinOffsetY;
            max = obj.MaxOffsetY;
            if (isnumeric(offsety) && ((offsety > min) && (offsety < max)))
                obj.CameraHandle.Parameters.Item('OffsetY').SetValue(...
                    int64(offsety));
            else
                fprintf(['Error: expected an integer OffsetY < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(offsety)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.ExposureTime. Includes error
        % checking based on the actual Basler Ace Camera model
        % (acA3800-14um)
        function set.ExposureTime(obj, exptime)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinExposureTime;
            max = obj.MaxExposureTime;
            if (isnumeric(exptime) && ((exptime > min) && (exptime < max)))
                obj.CameraHandle.Parameters.Item(...
                    'ExposureTime').SetValue(int64(exptime));
            else
                fprintf(['Error: expected an integer ExposureTime < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(exptime)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.Gain. Includes error
        % checking based on the actual Basler Ace Camera model
        % (acA3800-14um)
        function set.Gain(obj, gain)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            min = obj.MinGain;
            max = obj.MaxGain;
            if (isnumeric(gain) && ((gain > min) && (gain < max)))
                obj.CameraHandle.Parameters.Item(...
                    'Gain').SetValue(double(gain));
            else
                fprintf(['Error: expected an integer Gain < '...
                    '%d and > %d. Received:\n'], max, min);
                disp(gain)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.PixelFormat. Includes error
        % checking based on the actual Basler Ace Camera model
        % (acA3800-14um)
        function set.PixelFormat(obj, format)
            % Check if stream grabber is grabbing because if it is, we
            % cannot change sensor parameters
            wasGrabbing = obj.CameraHandle.StreamGrabber.IsGrabbing;
            if (wasGrabbing)
               obj.CameraHandle.StreamGrabber.Stop();
            end

            switch format
                case 'Mono8'
                    obj.CameraHandle.Parameters.Item(...
                    'PixelFormat').SetValue(format);
                case 'Mono12'
                    obj.CameraHandle.Parameters.Item(...
                    'PixelFormat').SetValue(format);
                case 'Mono12p'
                    obj.CameraHandle.Parameters.Item(...
                    'PixelFormat').SetValue(format);
                otherwise
                    fprintf(['Error: PixelFormat not recognized. '
                        'Received:\n']);
                    disp(format)
            end

            % If it was grabbing, restart
            if (wasGrabbing)
                obj.CameraHandle.StreamGrabber.Start();
            end
        end

        % Setter method for setting obj.SerialNumber. Includes error
        % checking based on the actual Basler Ace Camera model
        % (acA3800-14um)
        function set.SerialNumber(obj, nums)
            if (ischar(nums))
                obj.SerialNumber = nums;
            else
                fprintf(['Error: expected serial numbers'...
                    'to be char array. '
                        'Received:\n']);
                    disp(nums)
            end
        end

        % --------------------END SETTER FUNCTIONS-------------------------
        % ---------------------GETTER FUNCTIONS----------------------------
        % Getter function abstractions for directly querying the camera for
        % its relevant parameters. Uses methods provided by driver.
        function val = get.MaxHeight(obj)
            val = obj.CameraHandle.Parameters.Item('Height').GetMaximum();
        end

        function val = get.MinHeight(obj)
            val = obj.CameraHandle.Parameters.Item('Height').GetMinimum();
        end

        function val = get.MaxWidth(obj)
            val = obj.CameraHandle.Parameters.Item('Width').GetMaximum();
        end

        function val = get.MinWidth(obj)
            val = obj.CameraHandle.Parameters.Item('Width').GetMinimum();
        end

        function val = get.MaxOffsetX(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetX').GetMaximum();
        end

        function val = get.MinOffsetX(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetX').GetMinimum();
        end

        function val = get.MaxOffsetY(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetY').GetMaximum();
        end

        function val = get.MinOffsetY(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetY').GetMinimum();
        end

        function val = get.Height(obj)
            val = obj.CameraHandle.Parameters.Item('Height').GetValue();
        end

        function val = get.Width(obj)
            val = obj.CameraHandle.Parameters.Item('Width').GetValue();
        end

        function val = get.OffsetX(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetX').GetValue();
        end

        function val = get.OffsetY(obj)
            val = obj.CameraHandle.Parameters.Item('OffsetY').GetValue();
        end

        function val = get.MaxExposureTime(obj)
            val = obj.CameraHandle.Parameters.Item(...
                'ExposureTime').GetMaximum();
        end

        function val = get.MinExposureTime(obj)
            val = obj.CameraHandle.Parameters.Item(...
                'ExposureTime').GetMinimum();
        end

        function val = get.ExposureTime(obj)
            val = obj.CameraHandle.Parameters.Item(...
                'ExposureTime').GetValue();
        end

        function val = get.MaxGain(obj)
            val = obj.CameraHandle.Parameters.Item('Gain').GetMaximum();
        end

        function val = get.MinGain(obj)
            val = obj.CameraHandle.Parameters.Item('Gain').GetMinimum();
        end

        function val = get.Gain(obj)
            val = obj.CameraHandle.Parameters.Item('Gain').GetValue();
        end

        function val = get.PixelFormat(obj)
            val = obj.CameraHandle.Parameters.Item(...
                'PixelFormat').GetValue();
        end
        % ------------------END GETTER FUNCTIONS---------------------------

    end

end


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
using System;
using ITCC.HTTP.API.Enums;

namespace ITCC.HTTP.API.Attributes
{
    /// <summary>
    ///     Says that class or struct represents public API view.
    ///     All API views MUST have this attributes and all other classes MUST NOT
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public class ApiViewAttribute : Attribute
    {
        /// <summary>
        ///     Creates new <see cref="ApiViewAttribute"/> instance
        /// </summary>
        /// <param name="httpMethod">
        ///     Target HTTP method(s). One view SHOULD NOT be used for both reads (GET) and writes (PUT,POST).
        /// </param>
        public ApiViewAttribute(ApiHttpMethod httpMethod)
        {
            HttpMethod = httpMethod;
        }

        public ApiHttpMethod HttpMethod { get; }
    }
}


text:
<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site may use a
 * different template.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package Videoblog
 */

get_header(); ?>

				<?php while ( have_posts() ) : the_post(); ?>

					<?php get_template_part( 'template-parts/content', 'page' ); ?>

					<?php
						// If comments are open or we have at least one comment, load up the comment template
						if ( comments_open() || '0' != get_comments_number() ) {
							comments_template();
						}
					?>

				<?php endwhile; // End of the loop. ?>

			<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
package org.pfl.sonar.plugins.ad;

import javax.naming.directory.DirContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.security.Authenticator;

/**
 * Authenticator for Sonar AD Plugin.
 *
 * @author Jiji_Sasidharan
 */
public class ADAuthenticator extends Authenticator {

    private static final Logger LOG = LoggerFactory.getLogger(ADAuthenticator.class);

    private ADSettings adSettings;

    /**
     * Constructor
     * @param adSettings Active Directory settings
     */
    public ADAuthenticator(ADSettings adSettings) {
        this.adSettings = adSettings;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.sonar.api.security.Authenticator#doAuthenticate(org.sonar.api.security.Authenticator.Context)
     */
    @Override
    public boolean doAuthenticate(Context context) {
        boolean isAuthenticated = false;
        String userName = context.getUsername();
        String password = context.getPassword();
        if (isEmpty(userName) || isEmpty(password)) {
            LOG.error("User name and/or password is empty. user name: {}", userName);
        } else {
            LOG.trace("adSettings: {}", adSettings);
            DirContext dirCtx = ContextUtil.open(adSettings, userName, password);
            isAuthenticated = dirCtx != null;
            LOG.debug("User '{}' authenticated? - {}", userName, isAuthenticated);
            ContextUtil.close(dirCtx);
        }
        return isAuthenticated;
    }

    /**
     * Check if a given string value is null or empty.
     *
     * @param data
     * @return
     */
    private boolean isEmpty(String data) {
        return data == null || data.trim().isEmpty();
    }
}


text:
exports.config = {
  generateCollection: true,
  bundles: [
    { components: ['bs-alert', 'bs-badge', 'bs-button'] },
    { components: ['bs-alert-link', 'bs-alert-heading'] }
  ]
};

exports.devServer = {
  root: 'www',
  watchGlob: '**/**'
}


text:
package examples;

import neural.FFNN;
import neural.NeuralUtils;

public class Containment {
	public static void main(String[] args) {
		FFNN n = new FFNN(new int[] { 64, 16, 1 });
		n.setGammaTruncation(0.1);
		n.setVerbosity(2);
		n.setDisplayVisually(true, 800, 500, 0);

		double[][] problems = new double[1000][];
		double[][] solutions = new double[problems.length][];
		for (int i = 0; i < problems.length; i++) {
			String string = NeuralUtils.randomString(8, 'a', 'z' + 1);
			problems[i] = NeuralUtils.toArray(string);
			if (string.contains("q")) {
				solutions[i] = new double[] { 1 };
			} else {
				solutions[i] = new double[] { 0 };
			}
		}
		n.trainTillPerfection(problems, solutions);
		// Scanner s = new Scanner(System.in);
		// while (s.hasNext()) {
		// String in = s.nextLine();
		// if (in.length() > 8) {
		// in = in.substring(0, 8);
		// }
		// while (in.length() < 8) {
		// in = in + " ";
		// }
		// n.calculateOutput(NeuralUtils.toArray(in));
		// System.out.println(n.getResults());
		// }
		// s.close();
	}
}


text:
/*
 * Taken from ace editor demos and updated to suit the siddhi editor
 * Generates the token tool tips on mouse over
 */

/*
 * Generating tooltips when user hovers over a token
 * The tooltip content is set in siddhi-editor.js
 */
define(["ace/lib/dom", "ace/lib/oop", "ace/lib/event", "ace/range", "ace/tooltip", "./constants", "exports"],
    function (dom, oop, event, range, tooltip, constants, exports) {

        "use strict";   // JS strict mode

        function TokenTooltip(editor) {
            if (editor.tokenTooltip)
                return;
            tooltip.Tooltip.call(this, editor.container);
            editor.tokenTooltip = this;
            this.editor = editor;

            this.update = this.update.bind(this);
            this.onMouseMove = this.onMouseMove.bind(this);
            this.onMouseOut = this.onMouseOut.bind(this);
            event.addListener(editor.renderer.scroller, "mousemove", this.onMouseMove);
            event.addListener(editor.renderer.content, "mouseout", this.onMouseOut);
        }

        oop.inherits(TokenTooltip, tooltip.Tooltip);

        (function () {
            this.token = {};
            this.range = new range.Range();

            this.update = function () {
                this.$updateTooltipTimer = null;
                this.$showTooltipTimer = null;

                var r = this.editor.renderer;
                if (this.lastT - (r.timeStamp || 0) > 1000) {
                    r.rect = null;
                    r.timeStamp = this.lastT;
                    this.maxHeight = window.innerHeight;
                    this.maxWidth = window.innerWidth;
                }

                var canvasPos = r.rect || (r.rect = r.scroller.getBoundingClientRect());
                var offset = (this.x + r.scrollLeft - canvasPos.left - r.$padding) / r.characterWidth;
                var row = Math.floor((this.y + r.scrollTop - canvasPos.top) / r.lineHeight);
                var col = Math.round(offset);

                var screenPos = {row: row, column: col, side: offset - col > 0 ? 1 : -1};
                var session = this.editor.session;
                var docPos = session.screenToDocumentPosition(screenPos.row, screenPos.column);
                var token = session.getTokenAt(docPos.row, docPos.column);

                if (!token && !session.getLine(docPos.row)) {
                    token = {
                        type: "",
                        value: "",
                        state: session.bgTokenizer.getState(0)
                    };
                }
                if (!token) {
                    session.removeMarker(this.marker);
                    this.hide();
                    return;
                }

                /*
                 * This had been added to suit the siddhi editor implementation of token tool tips
                 */
                var tokenText = token.tooltip;
                if (tokenText) {
                    // Showing the tooltip using the tooltip specified in the token

                    // Setting the tooltip html to the tooltip popup
                    if (this.tokenText != tokenText) {
                        this.setHtml(tokenText);
                        this.width = this.getWidth();
                        this.height = this.getHeight();
                        this.tokenText = tokenText;
                    }

                    // Showing the tooltip
                    if (!this.$showTooltipTimer) {
                        if (!this.isOpen) {
                            // Starting the timer to show tooltip if it not already open
                            var self = this;
                            this.$showTooltipTimer = setTimeout(function () {
                                self.show(null, self.x, self.y);
                            }, constants.TOOLTIP_SHOW_DELAY - 100);
                        } else {
                            // Updating the position if it is already open
                            this.show(null, this.x, this.y);
                        }
                    }

                    this.token = token;
                    session.removeMarker(this.marker);
                    this.range =
                        new range.Range(docPos.row, token.start, docPos.row, token.start + token.value.length);
                    this.marker = session.addMarker(this.range, "ace_bracket", "text", false);
                } else {
                    // Hiding the tooltip if there is no tooltip specified for the token
                    clearTimeout(this.$showTooltipTimer);
                    this.$showTooltipTimer = undefined;
                    this.hide();
                }
            };

            this.onMouseMove = function (e) {
                this.x = e.clientX;
                this.y = e.clientY;
                if (this.isOpen) {
                    this.lastT = e.timeStamp;
                    this.setPosition(this.x, this.y);
                }
                if (!this.$updateTooltipTimer) {
                    this.$updateTooltipTimer = setTimeout(this.update, 100);
                }
            };

            this.onMouseOut = function (e) {
                if (e && e.currentTarget.contains(e.relatedTarget)) {
                    return;
                }
                this.hide();
                this.editor.session.removeMarker(this.marker);
                this.$updateTooltipTimer = clearTimeout(this.$updateTooltipTimer);
            };

            this.setPosition = function (x, y) {
                if (x + 10 + this.width > this.maxWidth) {
                    x = window.innerWidth - this.width - 10;
                }
                if (y > window.innerHeight * 0.75 || y + 20 + this.height > this.maxHeight) {
                    y = y - this.height - 30;
                }

                tooltip.Tooltip.prototype.setPosition.call(this, x + 10, y + 20);
            };

            this.destroy = function () {
                this.onMouseOut();
                event.removeListener(this.editor.renderer.scroller, "mousemove", this.onMouseMove);
                event.removeListener(this.editor.renderer.content, "mouseout", this.onMouseOut);
                delete this.editor.tokenTooltip;
            };

        }).call(TokenTooltip.prototype);

        exports.TokenTooltip = TokenTooltip;
    });


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package base
package types

import toplevel.ScTypeBoundsOwner
/**
* @author Alexander Podkhalyuzin
* Date: 11.04.2008
*/

trait ScWildcardTypeElement extends ScTypeElement with ScTypeBoundsOwner {

}


text:
<?php
namespace my\stuff {
    namespace nested {
    }
}


text:
package org.onosproject.k8snetworking.impl;

import org.onlab.packet.Ethernet;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.LeadershipService;
import org.onosproject.cluster.NodeId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.k8snetworking.api.K8sFlowRuleService;
import org.onosproject.k8snetworking.api.K8sNetwork;
import org.onosproject.k8snetworking.api.K8sNetworkEvent;
import org.onosproject.k8snetworking.api.K8sNetworkListener;
import org.onosproject.k8snetworking.api.K8sNetworkService;
import org.onosproject.k8snode.api.K8sHost;
import org.onosproject.k8snode.api.K8sHostService;
import org.onosproject.k8snode.api.K8sNode;
import org.onosproject.k8snode.api.K8sNodeEvent;
import org.onosproject.k8snode.api.K8sNodeListener;
import org.onosproject.k8snode.api.K8sNodeService;
import org.onosproject.k8snode.api.K8sRouterBridge;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleOperations;
import org.onosproject.net.flow.FlowRuleOperationsContext;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;

import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.k8snetworking.api.Constants.ACL_TABLE;
import static org.onosproject.k8snetworking.api.Constants.ARP_TABLE;
import static org.onosproject.k8snetworking.api.Constants.DEFAULT_GATEWAY_MAC;
import static org.onosproject.k8snetworking.api.Constants.FORWARDING_TABLE;
import static org.onosproject.k8snetworking.api.Constants.GROUPING_TABLE;
import static org.onosproject.k8snetworking.api.Constants.HOST_PREFIX;
import static org.onosproject.k8snetworking.api.Constants.JUMP_TABLE;
import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
import static org.onosproject.k8snetworking.api.Constants.NAMESPACE_TABLE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_CIDR_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_DEFAULT_RULE;
import static org.onosproject.k8snetworking.api.Constants.PRIORITY_SNAT_RULE;
import static org.onosproject.k8snetworking.api.Constants.ROUTER_ENTRY_TABLE;
import static org.onosproject.k8snetworking.api.Constants.ROUTING_TABLE;
import static org.onosproject.k8snetworking.api.Constants.STAT_EGRESS_TABLE;
import static org.onosproject.k8snetworking.api.Constants.STAT_INGRESS_TABLE;
import static org.onosproject.k8snetworking.api.Constants.TUN_ENTRY_TABLE;
import static org.onosproject.k8snetworking.api.Constants.VTAG_TABLE;
import static org.onosproject.k8snetworking.api.Constants.VTAP_EGRESS_TABLE;
import static org.onosproject.k8snetworking.api.Constants.VTAP_INGRESS_TABLE;
import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.tunnelPortNumByNetId;
import static org.onosproject.k8snetworking.util.RulePopulatorUtil.buildExtension;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Sets flow rules directly using FlowRuleService.
 */
@Component(immediate = true, service = K8sFlowRuleService.class)
public class K8sFlowRuleManager implements K8sFlowRuleService {

    private final Logger log = getLogger(getClass());

    private static final int DROP_PRIORITY = 0;
    private static final int HIGH_PRIORITY = 30000;
    private static final int TIMEOUT_SNAT_RULE = 60;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected FlowRuleService flowRuleService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected DeviceService deviceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ClusterService clusterService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected LeadershipService leadershipService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected K8sNetworkService k8sNetworkService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected K8sNodeService k8sNodeService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected K8sHostService k8sHostService;

    private final ExecutorService deviceEventExecutor =
            Executors.newSingleThreadExecutor(groupedThreads(
                    getClass().getSimpleName(), "device-event"));
    private final K8sNetworkListener internalNetworkListener = new InternalK8sNetworkListener();
    private final K8sNodeListener internalNodeListener = new InternalK8sNodeListener();

    private ApplicationId appId;
    private NodeId localNodeId;

    @Activate
    protected void activate() {
        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
        coreService.registerApplication(K8S_NETWORKING_APP_ID);
        k8sNodeService.addListener(internalNodeListener);
        k8sNetworkService.addListener(internalNetworkListener);
        localNodeId = clusterService.getLocalNode().id();
        leadershipService.runForLeadership(appId.name());
        k8sNodeService.completeNodes().forEach(this::initializePipeline);

        log.info("Started");
    }

    @Deactivate
    protected void deactivate() {
        k8sNodeService.removeListener(internalNodeListener);
        k8sNetworkService.removeListener(internalNetworkListener);
        leadershipService.withdraw(appId.name());
        deviceEventExecutor.shutdown();

        log.info("Stopped");
    }

    @Override
    public void setRule(ApplicationId appId, DeviceId deviceId,
                        TrafficSelector selector, TrafficTreatment treatment,
                        int priority, int tableType, boolean install) {
        FlowRule.Builder flowRuleBuilder = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector)
                .withTreatment(treatment)
                .withPriority(priority)
                .fromApp(appId)
                .forTable(tableType);

        if (priority == PRIORITY_SNAT_RULE) {
            flowRuleBuilder.makeTemporary(TIMEOUT_SNAT_RULE);
        } else {
            flowRuleBuilder.makePermanent();
        }

        applyRule(flowRuleBuilder.build(), install);
    }

    @Override
    public void setUpTableMissEntry(DeviceId deviceId, int table) {
        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
        TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

        treatment.drop();

        FlowRule flowRule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector.build())
                .withTreatment(treatment.build())
                .withPriority(DROP_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(table)
                .build();

        applyRule(flowRule, true);
    }

    @Override
    public void connectTables(DeviceId deviceId, int fromTable, int toTable) {
        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
        TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

        treatment.transition(toTable);

        FlowRule flowRule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector.build())
                .withTreatment(treatment.build())
                .withPriority(DROP_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(fromTable)
                .build();

        applyRule(flowRule, true);
    }

    private void applyRule(FlowRule flowRule, boolean install) {
        FlowRuleOperations.Builder flowOpsBuilder = FlowRuleOperations.builder();

        flowOpsBuilder = install ? flowOpsBuilder.add(flowRule) : flowOpsBuilder.remove(flowRule);

        flowRuleService.apply(flowOpsBuilder.build(new FlowRuleOperationsContext() {
            @Override
            public void onSuccess(FlowRuleOperations ops) {
                log.debug("Provisioned vni or forwarding table");
            }

            @Override
            public void onError(FlowRuleOperations ops) {
                log.debug("Failed to provision vni or forwarding table");
            }
        }));
    }

    protected void initializePipeline(K8sNode k8sNode) {

        DeviceId deviceId = k8sNode.intgBridge();

        // for inbound table transition
        connectTables(deviceId, STAT_INGRESS_TABLE, VTAP_INGRESS_TABLE);
        connectTables(deviceId, VTAP_INGRESS_TABLE, VTAG_TABLE);

        // for vTag and ARP table transition
        connectTables(deviceId, VTAG_TABLE, ARP_TABLE);

        // for jump and namespace table transition
        connectTables(deviceId, JUMP_TABLE, NAMESPACE_TABLE);

        // for ARP and ACL table transition
        connectTables(deviceId, ARP_TABLE, NAMESPACE_TABLE);

        // for namespace table transition to grouping table
        connectTables(deviceId, NAMESPACE_TABLE, GROUPING_TABLE);

        // for grouping table transition to ACL table
        connectTables(deviceId, GROUPING_TABLE, ACL_TABLE);

        // for ACL table transition to routing table
        connectTables(deviceId, ACL_TABLE, ROUTING_TABLE);

        // for grouping table transition
        // we need grouping table for bypassing routing table which contains large
        // amount of flow rules which might cause performance degradation during
        // table lookup
        // setupJumpTable(k8sNode);

        // for routing and outbound table transition
        connectTables(deviceId, ROUTING_TABLE, STAT_EGRESS_TABLE);

        // for outbound table transition
        connectTables(deviceId, STAT_EGRESS_TABLE, VTAP_EGRESS_TABLE);
        connectTables(deviceId, VTAP_EGRESS_TABLE, FORWARDING_TABLE);
    }

    private void setupRouter(K8sNode k8sNode, K8sRouterBridge bridge) {
        if (k8sNode.routerPortNum() == null) {
            return;
        }

        TrafficSelector selector = DefaultTrafficSelector.builder().build();
        TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                .setOutput(PortNumber.NORMAL)
                .build();

        FlowRule flowRule = DefaultFlowRule.builder()
                .forDevice(bridge.deviceId())
                .withSelector(selector)
                .withTreatment(treatment)
                .withPriority(PRIORITY_DEFAULT_RULE)
                .fromApp(appId)
                .makePermanent()
                .forTable(ROUTER_ENTRY_TABLE)
                .build();

        applyRule(flowRule, true);
    }

    private void setupJumpTable(K8sNode k8sNode) {
        DeviceId deviceId = k8sNode.intgBridge();

        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
        TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

        selector.matchEthDst(DEFAULT_GATEWAY_MAC);
        treatment.transition(ROUTING_TABLE);

        FlowRule flowRule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector.build())
                .withTreatment(treatment.build())
                .withPriority(HIGH_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(GROUPING_TABLE)
                .build();

        applyRule(flowRule, true);

        selector = DefaultTrafficSelector.builder();
        treatment = DefaultTrafficTreatment.builder();

        treatment.transition(STAT_EGRESS_TABLE);

        flowRule = DefaultFlowRule.builder()
                .forDevice(deviceId)
                .withSelector(selector.build())
                .withTreatment(treatment.build())
                .withPriority(DROP_PRIORITY)
                .fromApp(appId)
                .makePermanent()
                .forTable(GROUPING_TABLE)
                .build();

        applyRule(flowRule, true);
    }

    private void setAnyRoutingRule(IpPrefix srcIpPrefix, MacAddress mac,
                                   K8sNetwork k8sNetwork) {
        TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder()
                .matchEthType(Ethernet.TYPE_IPV4)
                .matchIPSrc(srcIpPrefix)
                .matchIPDst(IpPrefix.valueOf(k8sNetwork.cidr()));

        for (K8sNode node : k8sNodeService.completeNodes()) {
            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
                    .setTunnelId(Long.valueOf(k8sNetwork.segmentId()));

            if (node.hostname().equals(k8sNetwork.name())) {
                if (mac != null) {
                    tBuilder.setEthSrc(mac);
                }
                tBuilder.transition(STAT_EGRESS_TABLE);
            } else {
                K8sNode localNode = k8sNodeService.node(k8sNetwork.name());
                tBuilder.setOutput(node.intgToTunPortNum());

                // install flows into tunnel bridge
                PortNumber portNum = tunnelPortNumByNetId(k8sNetwork.networkId(),
                        k8sNetworkService, node);
                TrafficTreatment treatmentToRemote = DefaultTrafficTreatment.builder()
                        .extension(buildExtension(
                                deviceService,
                                node.tunBridge(),
                                localNode.dataIp().getIp4Address()),
                                node.tunBridge())
                        .setTunnelId(Long.valueOf(k8sNetwork.segmentId()))
                        .setOutput(portNum)
                        .build();

                FlowRule remoteFlowRule = DefaultFlowRule.builder()
                        .forDevice(node.tunBridge())
                        .withSelector(sBuilder.build())
                        .withTreatment(treatmentToRemote)
                        .withPriority(PRIORITY_CIDR_RULE)
                        .fromApp(appId)
                        .makePermanent()
                        .forTable(TUN_ENTRY_TABLE)
                        .build();
                applyRule(remoteFlowRule, true);
            }

            FlowRule flowRule = DefaultFlowRule.builder()
                    .forDevice(node.intgBridge())
                    .withSelector(sBuilder.build())
                    .withTreatment(tBuilder.build())
                    .withPriority(PRIORITY_CIDR_RULE)
                    .fromApp(appId)
                    .makePermanent()
                    .forTable(ROUTING_TABLE)
                    .build();
            applyRule(flowRule, true);
        }
    }

    private void setupHostRoutingRule(K8sNetwork k8sNetwork) {
        setAnyRoutingRule(IpPrefix.valueOf(
                k8sNetwork.gatewayIp(), HOST_PREFIX), null, k8sNetwork);
    }

    private class InternalK8sNodeListener implements K8sNodeListener {
        private boolean isRelevantHelper() {
            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
        }

        @Override
        public void event(K8sNodeEvent event) {
            switch (event.type()) {
                case K8S_NODE_COMPLETE:
                    deviceEventExecutor.execute(() -> processNodeCompletion(event.subject()));
                    break;
                case K8S_NODE_CREATED:
                default:
                    // do nothing
                    break;
            }
        }

        private void processNodeCompletion(K8sNode node) {
            log.info("COMPLETE node {} is detected", node.hostname());

            if (!isRelevantHelper()) {
                return;
            }

            initializePipeline(node);

            k8sNetworkService.networks().forEach(K8sFlowRuleManager.this::setupHostRoutingRule);

            for (K8sHost host : k8sHostService.completeHosts()) {
                if (host.nodeNames().contains(node.hostname())) {
                    host.routerBridges().stream()
                            .filter(b -> b.segmentId() == node.segmentId())
                            .findAny().ifPresent(bridge -> setupRouter(node, bridge));
                }
            }
        }
    }

    private class InternalK8sNetworkListener implements K8sNetworkListener {

        private boolean isRelevantHelper() {
            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
        }

        @Override
        public void event(K8sNetworkEvent event) {

            switch (event.type()) {
                case K8S_NETWORK_CREATED:
                    deviceEventExecutor.execute(() -> processNetworkCreation(event.subject()));
                    break;
                case K8S_NETWORK_REMOVED:
                default:
                    // do nothing
                    break;
            }
        }

        private void processNetworkCreation(K8sNetwork network) {
            if (!isRelevantHelper()) {
                return;
            }

            setupHostRoutingRule(network);
        }
    }
}


text:
- order: 5

限制选择 `20:30` 到 `23:30` 这个时间段。

---

````jsx
import { TimePicker } from 'antd';

function newArray(start, end) {
  let result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}

function disabledHours() {
  let hours = newArray(0, 60);
  hours.splice(20, 4);
  return hours;
}

function disabledMinutes(h) {
  if (h === 20) {
    return newArray(0, 31);
  } else if (h === 23) {
    return newArray(30, 60);
  } else {
    return [];
  }
}

ReactDOM.render(
  <TimePicker disabledHours={disabledHours} disabledMinutes={disabledMinutes} />
, document.getElementById('components-time-picker-demo-disable-options'));
````


text:
package com.thedeanda.ajaxproxy.ui.resourceviewer;

import java.awt.CardLayout;
import java.util.concurrent.ExecutionException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.tree.DefaultTreeModel;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thedeanda.ajaxproxy.ui.resourceviewer.util.DocumentContainer;
import com.thedeanda.ajaxproxy.ui.resourceviewer.util.DocumentParser;
import com.thedeanda.ajaxproxy.ui.viewer.ImageViewer;
import com.thedeanda.javajson.JsonArray;

/**
 * this is a content viewer used to show input/ouput content of http requests.
 * it may have a nested tab view to switch between raw, formatted and tree view
 *
 * @author mdeanda
 *
 */
@Slf4j
public class ContentViewer extends JPanel {
	private static final long serialVersionUID = 1L;
	private JTabbedPane tabs;
	private CardLayout cardLayout;

	private static final String EMPTY_CARD = "empty";
	private static final String NORMAL_CARD = "normal";

	public ContentViewer() {
		cardLayout = new CardLayout();
		setLayout(cardLayout);
		JTextArea empty = new JTextArea();
		empty.setEditable(false);
		add(new JScrollPane(empty), EMPTY_CARD);

		tabs = new JTabbedPane();
		add(tabs, NORMAL_CARD);
		tabs.add("", new JButton(""));

		setBorder(BorderFactory.createEmptyBorder());
		tabs.setBorder(BorderFactory.createEmptyBorder());
	}

	private void clearContents() {
		cardLayout.show(this, EMPTY_CARD);
		tabs.removeAll();
	}

	public void setContent(final byte[] input) {
		clearContents();

		if (ArrayUtils.isEmpty(input)) {
			log.debug("empty content, stop here");
			return;
		}

		log.debug("setting content");
		new TreeLoader(input).execute();
	}

	public void setContent(JsonArray message) {
		clearContents();

		if (message == null) {
			log.debug("empty content, stop here");
			return;
		}

		log.debug("setting content");
		new TreeLoader(message).execute();
	}

	private class TreeLoader extends SwingWorker<DocumentContainer, DocumentContainer> {

		private byte[] bytes;
		private JsonArray message;

		public TreeLoader(JsonArray message) {
			this.message = message;
		}

		public TreeLoader(byte[] input) {
			this.bytes = input;
		}

		@Override
		protected DocumentContainer doInBackground() throws Exception {
			log.debug("start parsing");

			DocumentParser parser = new DocumentParser();
			DocumentContainer document;
			if (bytes != null) {
				document = parser.parse(bytes);
			} else {
				document = parser.parse(message);
			}

			log.debug("done parsing");

			return document;
		}

		@Override
		protected void done() {
			log.debug("start of done");
			DocumentContainer data;
			try {
				data = get();
			} catch (InterruptedException | ExecutionException e) {
				log.error(e.getMessage(), e);
				return;
			}

			if (data.image != null) {
				log.debug("setting image");
				tabs.add("Image", new ImageViewer(data.image));
			} else {
				if (data.formattedText != null) {
					log.debug("setting formatted");
					tabs.add("Formatted", data.formattedTextArea);
				}
				if (data.treeNode != null) {
					log.debug("setting tree");
					JTree tree = new JTree(new DefaultTreeModel(data.treeNode));
					tree.setBorder(BorderFactory.createEmptyBorder());
					tree.setShowsRootHandles(true);
					JScrollPane scroll = new JScrollPane(tree);
					scroll.setBorder(BorderFactory.createEmptyBorder());
					tabs.add("Tree View", scroll);
				}
				if (data.rawText != null && data.rawText.length() < DocumentParser.MAX_TEXT_SIZE) {
					log.debug("setting raw: " + data.rawText.length());
					tabs.add("Raw Text", data.rawTextArea);
				}
			}
			if (data.hex != null) {
				log.debug("setting hex");
				tabs.add("Hex", data.hex);
			}

			log.debug("end of done");
			cardLayout.show(ContentViewer.this, NORMAL_CARD);
		}

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Viennese Cookies</title>
      <categories>
        <cat>None</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Parkay margarine</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Egg</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Almond extract</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Grated lemon rind</item></ing>
      <ing>
        <amt>
          <qty>1 3/4</qty>
          <unit>cups</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Ground almonds</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Tsp salt</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Kraft Pure Strawberry; Grape or Peach Preserves</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Confectioners sugar</item></ing></ingredients>
    <directions>
      <step>  Cream margarine and sugar until light and fluffy. Blend in egg, almond
  extract and lemon rind. Add flour, almonds and salt; mix well. Chill. Heat
  oven to 375 degrees. Roll out dough on lightly floured surface to 1/8-inch
  thickness; cut with 2-inch round cookie cutter. Cut small hole in center of
  half the cookies. Bake at 375 degrees on ungreased cookie sheets 5 to 7
  minutes or until set. Cool. Sprinkle cookies with hole in center with
  confectioners' sugar. Spread bottom of remaining cookies with approximately
  1/2 tsp preserves. Top with sugar covered cookies. Makes approximately 5
  dozen cookies.

  Posted to brand-name-recipes by vergie1@juno.com (Vergie A Ewing) on Apr
  15, 1998

</step></directions></recipe></recipeml>