text:
import { devices } from '@domojs/devices';
import { State } from "../state";
import * as api from '../api'
import { Socket } from 'net'
import { Container } from "@akala/commands";
import { ISCPProcessor } from "../iscp-processor";

const deviceCollection: { [name: string]: devices.IDevice } = {};

export function getMainDevice(name)
{
    var indexOfDot = name.indexOf('.');
    if (indexOfDot > 0)
        var mainDevice = name.substr(0, indexOfDot);
    else
        var mainDevice = name;

    return deviceCollection[mainDevice];
}

export default async function save(this: State, body: any, device: devices.IDevice)
{
    if (device.name.indexOf('.') > -1)
        return device;
    var socket = new Socket();

    this.collection[device.name] = new Container<object>('iscp-' + device.name, {}, new ISCPProcessor(socket, (message) =>
    {
        switch (message.command)
        {
            case 'PWR':
                this.collection[device.name].state.power = message.arg == '00';
                break;
            default:
                this.collection[device.name].state[message.command] = message.arg;
        }
    }));

    socket.connect({ host: body.IP || device.name, port: body.port || 60128 });
    device.statusMethod = 'push';
    device.subdevices = [
        {
            room: device.room,
            name: "power",
            type: 'iscp',
            category: 'switch',
            class: devices.DeviceClass.Switch,
            statusMethod: 'pull',
            status: function ()
            {
                return api.send('?P', device.name).then(function (result)
                {
                    console.log('result:' + result);
                    if (result)
                        result = result.trim();
                    return { state: result == 'PWR0', color: result == 'PWR0' ? 'green' : 'red' };
                });
            },
            commands: ['on', 'off']
        },
        {
            room: device.room,
            name: "mute",
            type: 'iscp',
            class: devices.DeviceClass.Switch,
            category: 'switch',
            statusMethod: 'pull',
            status: function ()
            {
                console.log('mute status');
                return api.send('?M', device.name).then((result) =>
                {
                    console.log(result);
                    return { state: result == 'MUT0', color: result == 'MUT0' ? 'green' : 'red' };
                });
            },
            commands: ['on', 'off']
        },
        {
            room: device.room,
            name: "volume",
            type: 'iscp',
            class: devices.DeviceClass.Range,
            category: 'input',
            statusMethod: 'pull',
            status: function ()
            {
                return api.send('?V', device.name).then(function (result)
                {
                    return { state: Number(/\d+/.exec(result)) * 100 / 185 };
                });
            },
            commands: ['up', 'down', 'set']
        },
        {
            room: device.room,
            name: "input",
            type: 'iscp',
            class: devices.DeviceClass.Discrete,
            category: 'values',
            statusMethod: 'pull',
            status: function ()
            {
                return api.send('?FN', device.name).then(function (result)
                {
                    console.log(result);
                    switch (Number(/[0-9]+/.exec(result)))
                    {
                        case 49:
                            return { state: 'Game' };
                        case 25:
                            return { state: 'BD' };
                        case 4:
                            return { state: 'Dvd' };
                        case 6:
                            return { state: 'Sat/Cbl' };
                        case 15:
                            return { state: 'Dvr/Bdr' };
                        case 17:
                            return { state: 'iPod' };
                        case 10:
                            return { state: 'Video' };
                        default:
                            return null;
                    }
                });
            },
            commands: ['Game', 'Dvd', 'Sat/Cbl', 'Dvr/Bdr', 'iPod', 'Video', 'BD']
        }
    ]
    return device;
}


text:
package com.clouck.wrapper.aws;
//package com.fleeio.dao;
//
//import java.util.List;
//
//import org.joda.time.DateTime;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import com.amazonaws.auth.AWSCredentials;
//import com.amazonaws.auth.BasicAWSCredentials;
//import com.amazonaws.services.rds.AmazonRDS;
//import com.amazonaws.services.rds.AmazonRDSClient;
//import com.amazonaws.services.rds.model.DescribeDBInstancesRequest;
//import com.amazonaws.services.rds.model.DescribeDBInstancesResult;
//import com.fleeio.converter.rds.RdsConverter;
//import com.fleeio.model.Account;
//import com.fleeio.model.Region;
//import com.fleeio.model.aws.rds.RdsDBInstanceVersion;
//
///**
// * This exists as a rds service isolation.
// * @author steng
// */
////TODO: properly catch all exceptions from all aws service call
//@Component
//public class RdsWrapperImpl implements RdsWrapper {
//	private static final Logger log = LoggerFactory.getLogger(RdsWrapperImpl.class);
//
//	@Autowired
//	private RdsConverter converter;
//
//    private AmazonRDS findClient(Account account, Region region) {
//        // TODO: need to config client config parameter. ignore it for now.
//        // TODO: need a cached version based on account and region as key
//        AWSCredentials credential = new BasicAWSCredentials(account.getAccessKeyId(), account.getSecretAccessKey());
//        AmazonRDS rds = new AmazonRDSClient(credential);
//        rds.setEndpoint(region.toEndpoint());
//        return rds;
//    }
//
//	@Override
//    public List<RdsDBInstanceVersion> describeDBInstances(Account account, Region region, DateTime dt) {
//	    AmazonRDS rds = findClient(account, region);
//
//        DescribeDBInstancesRequest req = new DescribeDBInstancesRequest();
//
//        log.debug("start describing db instances for account:{} in region:{} via api", account.getId() + "=>" + account.getDisplayName(), region);
//        DescribeDBInstancesResult res = rds.describeDBInstances(req);
//
//        return converter.toRdsDBInstanceVersion(res.getDBInstances(), region, dt);
//    }
//}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2015-2017 Hypha
#pragma once

#include <hypha/core/core_api.h>
#include <hypha/core/database/database.h>

#include <list>
#include <string>

namespace hypha {
namespace settings {

/**
 * PluginSettings loads settings of plugins from Database and represents them.
 * You can get access to name, host or config for given plugin id.
 */
class CORE_API PluginSettings {
 public:
  static PluginSettings *instance();

  explicit PluginSettings(hypha::database::Database *database);
  ~PluginSettings();

  /**
   * @brief getAllPluginIds get sender and receiver
   * @return
   */
  std::list<std::string> getAllPluginIds();

  /**
   * @brief getLocalPluginIds get sender and receiver running on localhost
   * @return
   */
  std::list<std::string> getLocalPluginIds();

  std::string getName(std::string id);
  std::string getHost(std::string id);
  std::string getConfig(std::string id);
  std::list<std::string> getConnectedReceiver(std::string senderId);
  bool exists(std::string id);

 protected:
  static PluginSettings *singleton;

  hypha::database::Database *database;
};
}
}


text:
cask :v1 => 'charles-applejava' do
  version '3.10.2'
  sha256 'ab848f02d034860aa1ded7758c629a79dac70a79ef6b380d4d98169d36998c26'

  url "http://www.charlesproxy.com/assets/release/#{version.gsub(/b\d$/, '')}/charles-proxy-#{version}-applejava.dmg"
  homepage 'http://www.charlesproxy.com/download/'
  license :commercial

  app 'Charles.app'

  zap :delete => [
                  '~/Library/Application Support/Charles',
                  '~/Library/Preferences/com.xk72.charles.config',
                 ]
end


text:
title:  "UICollectionView Tutorial"
description: UICollectionView Tutorial From raywenderlich.com
---

출처 : [UICollectionView Tutorial Part 1: Getting Started]

UICollectiveView 의 사용법을 알려주는 튜토리얼

iOS8 버전에 맞추어진 튜토리얼이라 약간의 수정이 필요하다.

[UICollectionView Tutorial Part 1: Getting Started]: http://www.raywenderlich.com/78550/beginning-ios-collection-views-swift-part-1


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
    JBoss, Home of Professional Open Source
    Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual contributors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.jboss.quickstarts.eap</groupId>
    <artifactId>jboss-helloworld-ws</artifactId>
    <version>7.1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>JBoss EAP Quickstart: helloworld-ws</name>
    <description>This project demonstrates a Hello World JAX-WS web service</description>
    <url>http://www.jboss.org/products/eap</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <!-- Activate the JBoss Enterprise Maven Repository.

        NOTE: Configuring the Maven repository in the pom.xml file is not a recommended procedure
        and is only done here to make it easier to use the quickstarts.

        For more information about how to configure Maven for your application,
        see the section entitled 'Use the Maven Repository'
        in the Development Guide for Red Hat JBoss Enterprise Application Platform located here:

        https://access.redhat.com/documentation/en/red-hat-jboss-enterprise-application-platform/
    -->
    <repositories>
        <repository>
            <id>jboss-developer-staging-repository</id>
            <url>http://jboss-developer.github.io/temp-maven-repo/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>jboss-enterprise-maven-repository</id>
            <url>https://maven.repository.redhat.com/ga/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>jboss-developer-staging-repository</id>
            <url>http://jboss-developer.github.io/temp-maven-repo/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>jboss-enterprise-maven-repository</id>
            <url>https://maven.repository.redhat.com/ga/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <!-- Explicitly declaring the source encoding eliminates the following
            message: [WARNING] Using platform encoding (UTF-8 actually) to copy
            filtered resources, i.e. build is platform dependent! -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- JBoss dependency versions -->

        <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

        <!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
        <version.jboss.bom.eap>7.0.0-build-12</version.jboss.bom.eap>

        <!-- other plug-in versions -->
        <version.war.plugin>2.6</version.war.plugin>
        <version.surefire.plugin>2.10</version.surefire.plugin>

        <!-- maven-compiler-plugin -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>

        <!-- Remote Server URL -->
        <remote.server.url>http://localhost:8080/</remote.server.url>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- JBoss distributes a complete set of Java EE APIs including a Bill
                of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
                of artifacts. We use this here so that we always get the correct versions
                of artifacts. Here we use the jboss-javaee-7.0 stack (you can read this as
                the JBoss stack of the Java EE APIs). You can actually use this stack with
                any version of JBoss EAP that implements Java EE. -->
            <dependency>
                <groupId>org.jboss.bom</groupId>
                <artifactId>jboss-eap-javaee7-with-tools</artifactId>
                <version>${version.jboss.bom.eap}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- Import the CDI API, we use provided scope as the API is included
            in JBoss EAP -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the Servlet API, we use provided scope as the API is
            included in JBoss EAP -->
        <dependency>
            <groupId>org.jboss.spec.javax.servlet</groupId>
            <artifactId>jboss-servlet-api_3.1_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the Common Annotations API (JSR-250), we use provided
            scope as the API is included in JBoss EAP -->
        <dependency>
            <groupId>org.jboss.spec.javax.annotation</groupId>
            <artifactId>jboss-annotations-api_1.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <!-- Set the name of the WAR, used as the context root when the app is deployed -->
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>${version.war.plugin}</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <!-- WildFly plug-in to deploy the WAR -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>${version.wildfly.maven.plugin}</version>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!-- The default profile skips all tests, though you can tune it
                 to run just unit tests based on a custom pattern.
                 Separate profiles are provided for running all tests, including
                 Arquillian tests that execute in the specified container -->
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>${version.war.plugin}</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <!-- An optional Arquillian testing profile that executes tests in your JBoss EAP instance.
                 This profile will start a new JBoss EAP instance, and execute the test, shutting it down when done.
                 Run with: mvn clean test -Parq-wildfly-managed -->
            <id>arq-wildfly-managed</id>
            <dependencies>
                <dependency>
                    <groupId>org.wildfly.arquillian</groupId>
                    <artifactId>wildfly-arquillian-container-managed</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <excludes>
                                <exclude>**/ClientTest.java</exclude>
                            </excludes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
           <!-- An optional Arquillian testing profile that executes tests in a remote JBoss EAP instance.
                Run with: mvn clean test -Parq-wildfly-remote -->
            <id>arq-wildfly-remote</id>
            <dependencies>
                <dependency>
                    <groupId>org.wildfly.arquillian</groupId>
                    <artifactId>wildfly-arquillian-container-remote</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <excludes>
                                <exclude>**/ClientTest.java</exclude>
                            </excludes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
           <!-- An optional Arquillian testing profile that executes tests in a remote JBoss EAP instance
                where the application has already been deployed.
                Run with: mvn clean test -Pjbossas-remote -->
            <id>jbossas-remote</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <systemProperties>
                                <property>
                                    <name>serverUrl</name>
                                    <value>${remote.server.url}</value>
                                </property>
                            </systemProperties>
                            <excludes>
                                <exclude>**/ClientArqTest.java</exclude>
                            </excludes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <!-- When built in OpenShift the 'openshift' profile will be used when invoking mvn.
                 Use this profile for any OpenShift specific customization your app will need.
                 By default that is to put the resulting archive into the 'deployments' folder.
                 http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
            <id>openshift</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>${version.war.plugin}</version>
                        <configuration>
                            <outputDirectory>deployments</outputDirectory>
                            <warName>${project.artifactId}</warName>
                            <webResources>
                                <resource>
                                    <directory>${basedir}/src/main/webapp-openshift/WEB-INF</directory>
                                    <filtering>true</filtering>
                                    <targetPath>WEB-INF</targetPath>
                                    <includes>
                                        <include>jboss-web.xml</include>
                                    </includes>
                                </resource>
                            </webResources>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
const expression = `
  Object.defineProperty(Object.prototype, 'RemoteObject', {
    configurable: true,
    set(v) {
      delete Object.prototype.RemoteObject;
      this.RemoteObject = v;

      detachInspector();
      setTimeout(function() {
        // Attach the inspector again for the sake of establishing a
        // communication channel with the frontend test runner.
        attachInspector();
        console.log("End of test");
      }, 0);
    },
  });

  // Before the whole script runs, the inspector is already attached.
  // Re-attach the inspector and trigger the console API to make sure that the
  // injected inspector script runs again (and triggers the above setter).
  detachInspector();
  attachInspector();
  console.log("First inspector activity after attaching inspector");
`;

Protocol.Runtime.enable();
Protocol.Runtime.evaluate({ expression: expression });

Protocol.Runtime.onConsoleAPICalled(function(result) {
  InspectorTest.logObject(result.params.args[0]);
  if (result.params.args[0].value == "End of test") {
    InspectorTest.completeTest();
  }
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>HexEncoder (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.util.encoders

Class HexEncoder

java.lang.Object

org.bouncycastle.util.encoders.HexEncoder

All Implemented Interfaces:

Encoder

public class HexEncoder
extends java.lang.Object
implements Encoder

A streaming Hex encoder.

Field Summary

Fields

Modifier and Type
Field and Description

protected byte[]
decodingTable

protected byte[]
encodingTable

Constructor Summary

Constructors

Constructor and Description

HexEncoder()

Method Summary

Methods

Modifier and Type
Method and Description

int
decode(byte[] data,
      int off,
      int length,
      java.io.OutputStream out)

decode the Hex encoded byte data writing it to the given output stream,
 whitespace characters will be ignored.

int
decode(java.lang.String data,
      java.io.OutputStream out)

decode the Hex encoded String data writing it to the given output stream,
 whitespace characters will be ignored.

int
encode(byte[] data,
      int off,
      int length,
      java.io.OutputStream out)

encode the input data producing a Hex output stream.

protected void
initialiseDecodingTable()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

encodingTable

protected final byte[] encodingTable

decodingTable

protected final byte[] decodingTable

Constructor Detail

HexEncoder

public HexEncoder()

Method Detail

initialiseDecodingTable

protected void initialiseDecodingTable()

encode

public int encode(byte[] data,
         int off,
         int length,
         java.io.OutputStream out)
           throws java.io.IOException

encode the input data producing a Hex output stream.

Specified by:

encode in interface Encoder

Returns:

the number of bytes produced.

Throws:

java.io.IOException

decode

public int decode(byte[] data,
         int off,
         int length,
         java.io.OutputStream out)
           throws java.io.IOException

decode the Hex encoded byte data writing it to the given output stream,
 whitespace characters will be ignored.

Specified by:

decode in interface Encoder

Returns:

the number of bytes produced.

Throws:

java.io.IOException

decode

public int decode(java.lang.String data,
         java.io.OutputStream out)
           throws java.io.IOException

decode the Hex encoded String data writing it to the given output stream,
 whitespace characters will be ignored.

Specified by:

decode in interface Encoder

Returns:

the number of bytes produced.

Throws:

java.io.IOException

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.geode.distributed.internal.tcpserver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.internal.serialization.BasicSerializable;
import org.apache.geode.internal.serialization.DSFIDSerializer;
import org.apache.geode.internal.serialization.DSFIDSerializerFactory;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.logging.internal.executors.LoggingExecutors;
import org.apache.geode.test.junit.categories.MembershipTest;

@Category({MembershipTest.class})
public class TcpServerTest {

  private static final int TIMEOUT = 60 * 1000;
  private InetAddress localhost;
  private int port;
  private TcpServer server;

  private void startTcpServerWithHandler(TcpHandler handler) throws IOException {
    localhost = InetAddress.getLocalHost();

    DSFIDSerializer serializer = new DSFIDSerializerFactory().create();
    server = new TcpServer(port, localhost, handler,
        "server thread",
        (x, y, z) -> false,
        () -> 0, // stats time
        () -> LoggingExecutors.newCachedThreadPool("test thread", true),
        null,
        serializer.getObjectSerializer(),
        serializer.getObjectDeserializer(),
        "blahblahblah",
        "blahblahblah");
    server.start();
    port = server.getPort();
    assertThat(port).isGreaterThan(0);
    assertThat(server.isShuttingDown()).isFalse();
    assertThat(server.getSocketAddress()).isNotNull();
    assertThat(server.isAlive()).isTrue();
  }

  @Test
  public void testConnectToUnknownHost() {
    final TcpClient tcpClient = createTcpClient();
    @SuppressWarnings("deprecation")
    InfoRequest testInfoRequest = new InfoRequest();
    assertThatThrownBy(
        () -> tcpClient.requestToServer(new HostAndPort("unknown host name", port), testInfoRequest,
            TIMEOUT, true))
                .as("Hostname resolved unexpectedly. Check for DNS hijacking in addition to code errors.")
                .isInstanceOf(UnknownHostException.class);
  }

  @SuppressWarnings("deprecation")
  @Test
  public void testClientGetInfo() throws Exception {
    TcpHandler handler = new InfoRequestHandler();
    startTcpServerWithHandler(handler);

    final TcpClient tcpClient = createTcpClient();

    InfoRequest testInfoRequest = new InfoRequest();
    InfoResponse testInfoResponse =
        (InfoResponse) tcpClient.requestToServer(new HostAndPort(localhost.getHostAddress(), port),
            testInfoRequest, TIMEOUT, true);
    assertThat(testInfoResponse).isNotNull();
    assertThat(testInfoResponse.getInfo()[0]).contains("geode-tcp-server");

    String[] requestedInfo = tcpClient.getInfo(new HostAndPort(localhost.getHostAddress(), port));
    assertNotNull(requestedInfo);
    assertTrue(requestedInfo.length > 1);
    assertThat(requestedInfo[0]).contains("geode-tcp-server");

    stopServer(tcpClient);
  }

  private TcpClient createTcpClient() {
    DSFIDSerializer serializer = new DSFIDSerializerFactory().create();
    TcpSocketCreator socketCreator = new TcpSocketCreatorImpl();
    return new TcpClient(socketCreator,
        serializer.getObjectSerializer(),
        serializer.getObjectDeserializer(), TcpSocketFactory.DEFAULT);
  }

  @Test
  public void testConcurrency() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    DelayHandler handler = new DelayHandler(latch);
    startTcpServerWithHandler(handler);
    final TcpClient tcpClient = createTcpClient();

    final AtomicBoolean done = new AtomicBoolean();
    Thread delayedThread = new Thread(() -> {
      try {
        tcpClient.requestToServer(new HostAndPort(localhost.getHostAddress(), port),
            new TestObject(1), TIMEOUT, true);
      } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
      }
      done.set(true);
    });
    delayedThread.start();
    try {
      Thread.sleep(500);
      assertFalse(done.get());
      tcpClient.requestToServer(new HostAndPort(localhost.getHostAddress(), port),
          new TestObject(0), TIMEOUT, true);
      assertFalse(done.get());

      latch.countDown();
      Thread.sleep(500);
      assertTrue(done.get());
    } finally {
      latch.countDown();
      delayedThread.join(TIMEOUT);
      assertFalse(delayedThread.isAlive()); // GemStoneAddition
      stopServer(tcpClient);
    }
  }

  @Test
  public void testNewConnectionsAcceptedAfterSocketException() throws IOException,
      ClassNotFoundException, InterruptedException {
    // Initially mock the handler to throw a SocketException. We want to verify that the server
    // can recover and serve new client requests after a SocketException is thrown.
    TcpHandler mockTcpHandler = mock(TcpHandler.class);
    doThrow(SocketException.class).when(mockTcpHandler).processRequest(any(Object.class));
    startTcpServerWithHandler(mockTcpHandler);
    final TcpClient tcpClient = createTcpClient();

    // Due to the mocked handler, an EOFException will be thrown on the client. This is expected.
    assertThatThrownBy(
        () -> tcpClient.requestToServer(new HostAndPort(localhost.getHostAddress(), port),
            new TestObject(), TIMEOUT, true))
                .isInstanceOf(EOFException.class);

    // Change the mock handler behavior to echo the request back
    doAnswer(invocation -> invocation.getArgument(0)).when(mockTcpHandler)
        .processRequest(any(Object.class));

    // Perform another request and validate that it was served successfully
    TestObject test = new TestObject();
    test.id = 5;
    TestObject result =
        (TestObject) tcpClient.requestToServer(new HostAndPort(localhost.getHostAddress(), port),
            test, TIMEOUT, true);

    assertThat(result).isNotNull();
    assertEquals(test.id, result.id);

    stopServer(tcpClient);
  }

  private void stopServer(final TcpClient tcpClient) throws InterruptedException {
    try {
      tcpClient.stop(new HostAndPort(localhost.getHostAddress(), port));
    } catch (ConnectException ignore) {
      // must not be running
    }
    server.join(TIMEOUT);
    assertFalse(server.isAlive());
  }

  private static class TestObject implements BasicSerializable {
    int id;

    public TestObject() {}

    public TestObject(int id) {
      this.id = id;
    }

    @Override
    public void fromData(DataInput in, DeserializationContext context) throws IOException {
      id = in.readInt();
    }

    @Override
    public void toData(DataOutput out, SerializationContext context) throws IOException {
      out.writeInt(id);
    }

  }

  private static class DelayHandler implements TcpHandler {

    private final CountDownLatch latch;

    public DelayHandler(CountDownLatch latch) {
      this.latch = latch;
    }

    @Override
    public void init(TcpServer tcpServer) {}

    @Override
    public Object processRequest(Object request) {
      TestObject delay = (TestObject) request;
      if (delay.id > 0) {
        try {
          // noinspection ResultOfMethodCallIgnored
          latch.await(120 * 1000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
      return delay;
    }

    @Override
    public void shutDown() {}

    @Override
    public void endRequest(Object request, long startTime) {}

    @Override
    public void endResponse(Object request, long startTime) {}
  }

  public static class InfoRequestHandler implements TcpHandler {
    public InfoRequestHandler() {}

    @SuppressWarnings("deprecation")
    @Override
    public Object processRequest(final Object request) {
      String[] info = new String[2];
      info[0] = System.getProperty("user.dir");
      info[1] = System.getProperty("java.version");
      return new InfoResponse(info);
    }

    @Override
    public void endRequest(final Object request, final long startTime) {}

    @Override
    public void endResponse(final Object request, final long startTime) {}

    @Override
    public void shutDown() {}

    @Override
    public void init(final TcpServer tcpServer) {}
  }

}


text:
function Graph(core, parent_graph, tree_node)
{
	this.tree_node = tree_node;
	this.listeners = [];
	this.nodes = [];
	this.connections = [];
	this.core = core;
	this.registers = new Registers(core);

	if(tree_node !== null) // Only initialise if we're not deserialising.
	{
		this.uid = this.core.get_graph_uid();
		this.parent_graph = parent_graph;
		this.roots = [];
		this.children = [];
		this.node_uid = 0;

		tree_node.graph = this;
	}
}

Graph.prototype.get_node_uid = function()
{
	return this.node_uid++;
};

Graph.prototype.register_node = function(n)
{
	this.nodes.push(n);

	if(this.nuid_lut)
		this.nuid_lut[n.uid] = n;

	if(n.plugin.output_slots.length === 0 && !n.dyn_outputs)
		this.roots.push(n);
	else if(n.plugin.e2_is_graph)
		this.children.push(n);
};

Graph.prototype.unregister_node = function(n)
{
	this.nodes.remove(n);

	if(this.nuid_lut)
		delete this.nuid_lut[n.uid];

	if(n.plugin.output_slots.length === 0 && !n.dyn_outputs)
		this.roots.remove(n);
	else if(n.plugin.e2_is_graph)
		this.children.remove(n);
};

Graph.prototype.create_instance = function(plugin_id, x, y)
{
	n = new Node(this, plugin_id, x, y);

	this.register_node(n);
	this.emit_event({ type: 'node-created', node: n });

	return n;
};

Graph.prototype.update = function(delta_t)
{
	var nodes = this.nodes;
	var roots = this.roots;
	var children = this.children;
	var dirty = false;

	for(var i = 0, len = nodes.length; i < len; i++)
		nodes[i].update_count = 0;

	for(var i = 0, len = roots.length; i < len; i++)
		dirty = roots[i].update_recursive(this.connections) || dirty;

	for(var i = 0, len = children.length; i < len; i++)
	{
		var c = children[i];

		if(!c.plugin.texture) // TODO: Huh? Comment this.
			dirty = c.update_recursive(this.connections) || dirty;
	}

	if(dirty && this === E2.app.player.core.active_graph)
		E2.app.player.core.active_graph_dirty = dirty;

	for(var i = 0, len = nodes.length; i < len; i++)
		nodes[i].plugin.updated = false;

	return dirty;
};

Graph.prototype.enum_all = function(n_delegate, c_delegate)
{
	if(n_delegate)
	{
		var nodes = this.nodes;

		for(var i = 0, len = nodes.length; i < len; i++)
			n_delegate(nodes[i]);
	}

	if(c_delegate)
	{
		var conns = this.connections;

		for(var i = 0, len = conns.length; i < len; i++)
			c_delegate(conns[i]);
	}
};

Graph.prototype.reset = function()
{
	var nodes = this.nodes, conns = this.connections;

	for(var i = 0, len = nodes.length; i < len; i++)
		nodes[i].reset();

	for(var i = 0, len = conns.length; i < len; i++)
		conns[i].reset();
};

Graph.prototype.play = function()
{
	this.enum_all(function(n)
	{
		if(n.plugin.play)
			n.plugin.play();
	}, null);
};

Graph.prototype.pause = function()
{
	this.enum_all(function(n)
	{
		if(n.plugin.pause)
			n.plugin.pause();
	}, null);
};

Graph.prototype.stop = function()
{
	this.enum_all(function(n)
	{
		if(n.plugin.stop)
			n.plugin.stop();
	}, null);
};

Graph.prototype.destroy_connection = function(c)
{
	var index = this.connections.indexOf(c);

	if(index !== -1)
		this.connections.splice(index, 1);

	c.dst_slot.is_connected = false;

	var slots = c.dst_node.inputs;

	index = slots.indexOf(c);

	if(index !== -1)
		slots.splice(index, 1);

	slots = c.src_node.outputs;
	index = slots.indexOf(c);

	if(index !== -1)
		slots.splice(index, 1);
};

Graph.prototype.create_ui = function()
{
	this.nuid_lut = [];

	for(var i = 0, len = this.nodes.length; i < len; i++)
	{
		var n = this.nodes[i];

		this.nuid_lut[n.uid] = n;
	}

	this.enum_all(function(n)
	{
		n.create_ui();

		if(n.ui && n.plugin.state_changed)
			n.plugin.state_changed(n.ui.plugin_ui);
	},
	function(c)
	{
		c.create_ui();
		c.ui.resolve_slot_divs();
	});
};

Graph.prototype.destroy_ui = function()
{
	this.enum_all(function(n) { n.destroy_ui(); }, function(c) { c.destroy_ui(); });
	delete this.nuid_lut;
};

Graph.prototype.find_connections_from = function(node, slot)
{
	if(slot.type !== E2.slot_type.output)
		return [];

	var conns = this.connections;
	var uid = node.uid;
	var result = [];

	for(var i = 0, len = conns.length; i < len; i++)
	{
		var c = conns[i];

		if(c.src_node.uid === uid && c.src_slot === slot)
			result.push(c);
	}

	return result;
};

Graph.prototype.serialise = function()
{
	var d = {};

	d.node_uid = this.node_uid;
	d.uid = this.uid;
	d.parent_uid = this.parent_graph ? this.parent_graph.uid : -1;
	d.open = this.open;
	d.nodes = [];
	d.conns = [];

	this.enum_all(function(n) { d.nodes.push(n.serialise()); }, function(c) { d.conns.push(c.serialise()); });
	this.registers.serialise(d);

	return d;
};

Graph.prototype.deserialise = function(d)
{
	this.node_uid = d.node_uid;
	this.uid = d.uid;
	this.parent_graph = d.parent_uid;

	this.nodes = [];
	this.roots = [];
	this.children = [];
	this.open = d.open || false;

	for(var i = 0, len = d.nodes.length; i < len; i++)
	{
		var n = new Node(null, null, null, null);

		if(n.deserialise(this.uid, d.nodes[i]))
			this.register_node(n);
	}

	this.connections = [];

	for(var i = 0, len = d.conns.length; i < len; i++)
	{
		var c = new Connection(null, null, null, null);

		c.deserialise(d.conns[i]);
		this.connections.push(c);
	}

	if(d.registers)
		this.registers.deserialise(d.registers);
};

Graph.prototype.patch_up = function(graphs)
{
	this.parent_graph = Graph.resolve_graph(graphs, this.parent_graph);

	// Cannot use enum_all for this!
	var nodes = this.nodes,
	    conns = this.connections;

	for(var i = 0, len = nodes.length; i < len; i++)
		nodes[i].patch_up(graphs);

	prune = [];

	for(var i = 0, len = conns.length; i < len; i++)
	{
		var c = conns[i];

		if(!c.patch_up(this.nodes))
			prune.push(c);
	}

	for(var i = 0, len = prune.length; i < len; i++)
		conns.remove(prune[i]);
};

Graph.prototype.initialise = function()
{
	var nodes = this.nodes;

	for(var i = 0, len = nodes.length; i < len; i++)
		nodes[i].initialise();

	this.reset();
};

Graph.prototype.reg_listener = function(delegate)
{
	if(!this.listeners.indexOf(delegate) !== -1)
		this.listeners.push(delegate);
};

Graph.prototype.emit_event = function(ev)
{
	var l = this.listeners,
	    len = l.length;

	if(len === 0)
		return;

	for(var i = 0; i < len; i++)
		l[i](ev);
};

Graph.prototype.build_breadcrumb = function(parent, add_handler)
{
	var sp = $('<span>' + this.tree_node.title + '</span>');

	sp.css('cursor', 'pointer');

	if(add_handler)
	{
		sp.click(function(self) { return function()
		{
			self.tree_node.activate();
		}}(this));

		sp.css({ 'text-decoration': 'underline' });
	}

	parent.prepend($('<span> / </span>'));
	parent.prepend(sp);

	if(this.parent_graph)
		this.parent_graph.build_breadcrumb(parent, true);
};

Graph.prototype.reorder_children = function(original, sibling, insert_after)
{
	var reorder = function(arr)
	{
		arr.remove(original);

		var i = arr.indexOf(sibling);

		if(insert_after)
			i++;

		arr.splice(i, 0, original);
	};

	reorder(this.children);
	reorder(this.nodes);
};

Graph.resolve_graph = function(graphs, guid)
{
	for(var i = 0, len = graphs.length; i < len; i++)
	{
		if(graphs[i].uid === guid)
			return graphs[i];
	}

	if(guid !== -1)
		msg('ERROR: Failed to resolve graph(' + guid + ')');

	return null;
};


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

Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities

Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
    ''' <summary>
    ''' Intended to be used to create ParameterSymbols for a SignatureOnlyMethodSymbol.
    ''' </summary>
    Friend NotInheritable Class SignatureOnlyParameterSymbol
        Inherits ParameterSymbol
        Private ReadOnly _type As TypeSymbol
        Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier)
        Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier)
        Private ReadOnly _defaultValue As ConstantValue
        Private ReadOnly _isParamArray As Boolean
        Private ReadOnly _isByRef As Boolean
        Private ReadOnly _isOut As Boolean
        Private ReadOnly _isOptional As Boolean

        Public Sub New(ByVal type As TypeSymbol,
                       ByVal customModifiers As ImmutableArray(Of CustomModifier),
                       ByVal refCustomModifiers As ImmutableArray(Of CustomModifier),
                       ByVal defaultConstantValue As ConstantValue,
                       ByVal isParamArray As Boolean,
                       ByVal isByRef As Boolean,
                       ByVal isOut As Boolean,
                       ByVal isOptional As Boolean)

            Me._type = type
            Me._customModifiers = customModifiers
            Me._refCustomModifiers = refCustomModifiers
            Me._defaultValue = defaultConstantValue
            Me._isParamArray = isParamArray
            Me._isByRef = isByRef
            Me._isOut = isOut
            Me._isOptional = isOptional
        End Sub

        Public Overrides ReadOnly Property Type() As TypeSymbol
            Get
                Return _type
            End Get
        End Property

        Public Overrides ReadOnly Property CustomModifiers() As ImmutableArray(Of CustomModifier)
            Get
                Return _customModifiers
            End Get
        End Property

        Public Overrides ReadOnly Property RefCustomModifiers() As ImmutableArray(Of CustomModifier)
            Get
                Return _refCustomModifiers
            End Get
        End Property

        Public Overrides ReadOnly Property IsParamArray As Boolean
            Get
                Return _isParamArray
            End Get
        End Property

        Public Overrides ReadOnly Property Name() As String
            Get
                Return ""
            End Get
        End Property

        Public Overrides ReadOnly Property IsByRef As Boolean
            Get
                Return _isByRef
            End Get
        End Property

        Friend Overrides ReadOnly Property IsExplicitByRef As Boolean
            Get
                Return _isByRef
            End Get
        End Property

        Friend Overrides ReadOnly Property IsMetadataOut As Boolean
            Get
                Return _isOut
            End Get
        End Property

        Friend Overrides ReadOnly Property IsMetadataIn As Boolean
            Get
                Return Not _isOut
            End Get
        End Property

        Public Overrides ReadOnly Property IsOptional() As Boolean
            Get
                Return _isOptional
            End Get
        End Property

        Public Overrides ReadOnly Property HasExplicitDefaultValue() As Boolean
            Get
                Return _defaultValue IsNot Nothing
            End Get
        End Property

        Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue
            Get
                Return _defaultValue
            End Get
        End Property

        Friend Overrides ReadOnly Property HasOptionCompare As Boolean
            Get
                Return False
            End Get
        End Property

#Region "Not used by MethodSignatureComparer"
        Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Public Overrides ReadOnly Property Ordinal() As Integer
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Public Overrides ReadOnly Property ContainingSymbol() As Symbol
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Public Overrides ReadOnly Property Locations() As ImmutableArray(Of Location)
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Public Overrides ReadOnly Property ContainingAssembly() As AssemblySymbol
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Friend Overrides ReadOnly Property IsCallerMemberName As Boolean
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property

        Friend Overrides ReadOnly Property IsCallerFilePath As Boolean
            Get
                Throw ExceptionUtilities.Unreachable
            End Get
        End Property
#End Region
    End Class
End Namespace


text:
/* content script - loaded with all pages
 * (plain js for speed, no zepto.js here)
 * */

// mark initial nodes (not injected)
var data = build_response(null);
var MAX_INLINE_LEN = 400;
chrome.runtime.sendMessage({method: "get_config", key: "limit_inline"}, function(response) {
    MAX_INLINE_LEN = response || 400;
});

// bg calls us, asking data
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    // count html, scripts, css
    var data = build_response(request);
    sendResponse(data);
});

// builds response object
function build_response(request) {
    var arr_html = [], arr_js = [], arr_json=[], arr_other=[], arr_css = [];

    var is_initial = !request;

    try {
        get_js(arr_js, arr_html, arr_json, arr_other, is_initial, request ? request.showonclick : false);
        var response = {"url":location.href, "js":arr_js, "css":arr_css, json:arr_json, other:arr_other };

        // get html body + template scripts
        if (request && !request.badge) {
            get_css(arr_css, is_initial);

            response.html = [{"inline":get_dom(),
                "count":document.getElementsByTagName('*').length}];
                for (var i = 0; i < arr_html.length ; i++) {
                    response.html.push(arr_html[i]);
                }
        }
    } catch (e) {
        return {"err": ""+e};
    }

    return response;
}

// get body as string
function get_dom() {
//    return document.documentElement.outerHTML;

    // truncate long scripts+styles in HTML, they are listed separately

    var dupNode = document.documentElement.cloneNode(true);

    function truncate(nodes) {
        var i, s;
        for(i=0; i<nodes.length; i++){
            s = nodes[i].innerHTML;
            if (s && s.length > MAX_INLINE_LEN)
                nodes[i].innerHTML = s.substr(0, MAX_INLINE_LEN) + " truncated "+s.length+"bytes...";
        }
    }

    truncate(dupNode.getElementsByTagName("script"));
    truncate(dupNode.getElementsByTagName("style"));

    return dupNode.outerHTML;
}

// enumerate JS scripts in page
// returns 2 arrays: js and html content
function get_js(arr_js, arr_html, arr_json, arr_other, mark_initial, show_onclick) {
    var i, node;

    var nodes = document.getElementsByTagName("script");
    for(i=0; i<nodes.length; i++){
        node = nodes[i];
        if (!node.type || node.type === "text/javascript" || node.type === "application/javascript")
            pick_node(node, arr_js, mark_initial);
        else if (node.type === "application/json" || node.type === "application/ld+json")
            pick_node(node, arr_json, mark_initial);
        else if (node.type === "text/template"
            || node.type === "text/x-template"
            || node.type === "text/html")
            pick_node(node, arr_html, mark_initial);
        else
            pick_node(node, arr_other, mark_initial);
    }
    // inline onclick-handlers
    if (show_onclick) {
        nodes = document.getElementsByTagName("*");
        for(i=0; i<nodes.length; i++){
            node = nodes[i];
            if (node.getAttribute("onclick")) {
                var item = pick_node(node, arr_js, mark_initial);
                var s = "/* " + node.tagName.toLowerCase();
                if (node.id)
                    s += "#"+node.id;
                if (node.className)
                    s += "."+node.className;
                s += ".onclick = */\n";
                item.inline = s + node.getAttribute("onclick");
                item.src = null;
                item.dynamic = false;
                item.onclick = true;
            }
        }
    }
}

// enumerate CSS in page
function get_css(a, mark_initial) {
    var i;

	var csslist = document.styleSheets;
	for(i = 0; i < csslist.length; i++){
		var css = csslist[i];

		pick_node(css.ownerNode, a, mark_initial);

		parse_cssrules(css, a, mark_initial, 0);
	}

/*
    var styles = document.getElementsByTagName("link");
    for(i=0; i<styles.length; i++){
        node = styles[i];
        if (node.rel == "stylesheet" || node.type == "text/css")
            pick_node(node, a, mark_initial);
    }

    styles = document.getElementsByTagName("style");
    for(i=0; i<styles.length; i++){
        node = styles[i];
        pick_node(node, a, mark_initial);
    }*/
}

// parse "@import file.css" declarations in given css file
function parse_cssrules(cssNode, a, mark_initial, depth) {
	if (depth > 10 || !cssNode)
        return;

    try {
        var rules = cssNode.cssRules;
    } catch (e) {
        // can't access all cssRules - Chrome 64 returns SecurityError
        // just ignore these items, they seem duplicates anyway
        //var item = {"src":"error "+cssNode.href};
        //a.push(item);
        return;
    }

    if (rules) {
        for (var i =0; i < rules.length; i++) {
            var rule = rules[i];

            if (rule instanceof CSSImportRule) {
                var s = rule.styleSheet;
                var item = pick_node({'href':s.href}, a, mark_initial);
                item.imported = true;
                parse_cssrules(rule.styleSheet, a, mark_initial, depth+1);
            }
        }
    }
}

// picks element's src-url or inline content
function pick_node(node, array, mark_initial) {
    // skip extension scripts
    var src = node.href || node.src;
    if (src && startsWith(""+src, "chrome-extension:"))
        return null;

    var item;
    if (src)
        item = {"src":src};
    else
        item = {"inline":node.innerText || node.text || ''+node};

    // mark initially loaded elems
    if (mark_initial)
        node._xinit = true;

    if (!node._xinit)
        item["dynamic"] = true;

    array.push(item);
    return item;
}

function startsWith(s, sub) {
    return s.indexOf(sub) === 0;
}


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

namespace Microsoft.Research.Uncertain
{
    internal class ForwardSampler<T> : IUncertainVisitor, ISampler<T>
    {
        internal object sample;
        protected readonly Uncertain<T> source;
        protected int generation;
        private IDictionary<object, Tuple<int, object>> cache;

        internal ForwardSampler(Uncertain<T> source)
        {
            this.source = source;
            this.generation = 1;
            this.cache = new Dictionary<object, Tuple<int, object>>();
        }

        private IEnumerable<Weighted<T1>> GetEnumerator<T1>(Uncertain<T1> fromsource)
        {
            while (true)
            {
                this.generation++;
                fromsource.Accept(this);
                yield return (Weighted<T1>)this.sample;
            }
        }

        public IEnumerator<Weighted<T>> GetEnumerator()
        {
            return this.GetEnumerator(this.source).GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public void Visit<T1>(Where<T1> where)
        {
            // rejection sampling!
            foreach (var item in this.GetEnumerator<T1>(where.source))
            {
                if (where.Predicate(item.Value))
                {
                    this.sample = item;
                    break;
                }
            }
        }

        public void Visit<T1>(RandomPrimitive<T1> erp)
        {
            var sample = erp.Sample(this.generation);
            this.sample = new Weighted<T1>(sample);
        }

        public void Visit<TSource, TResult>(Select<TSource, TResult> select)
        {
            select.source.Accept(this);
            var a = (Weighted<TSource>)this.sample;
            var b = select.Projection(a.Value);
            this.sample = new Weighted<TResult>(b.Value, a.Probability * b.Probability);
        }

        public void Visit<TSource, TCollection, TResult>(SelectMany<TSource, TCollection, TResult> selectmany)
        {
            selectmany.source.Accept(this);
            var a = (Weighted<TSource>)this.sample;

            var b = selectmany.CollectionSelector(a.Value);
            b.Accept(this);
            var c = (Weighted<TCollection>)this.sample;

            var result = selectmany.ResultSelector(a.Value, c.Value);
            result.Probability *= (a.Probability * c.Probability);
            this.sample = result;
        }
    }
}


text:
package joshie.harvest.player.command;

import joshie.harvest.api.cooking.Recipe;
import joshie.harvest.core.HFTrackers;
import joshie.harvest.core.commands.CommandManager.CommandLevel;
import joshie.harvest.core.commands.HFCommand;
import joshie.harvest.player.PlayerTrackerServer;
import joshie.harvest.player.tracking.TrackingServer;
import net.minecraft.command.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;

import javax.annotation.Nonnull;

@HFCommand
@SuppressWarnings("unused")
public class HFCommandRecipe extends CommandBase {
    @Override
    @Nonnull
    public String getName() {
        return "recipe";
    }

    @Override
    @Nonnull
    public String getUsage(@Nonnull ICommandSender sender) {
        return "/hf recipe [player] <value|all|clear>";
    }

    @Override
    public int getRequiredPermissionLevel() {
        return CommandLevel.OP_AFFECT_GAMEPLAY.ordinal();
    }

    @Override
    public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] parameters) throws CommandException {
        if (parameters.length == 1 || parameters.length == 2) {
            try {
                EntityPlayerMP player = parameters.length == 1? CommandBase.getCommandSenderAsPlayer(sender) : CommandBase.getPlayer(server, sender, parameters[0]);
                TrackingServer tracking = HFTrackers.<PlayerTrackerServer>getPlayerTrackerFromPlayer(player).getTracking();
                String recipe = parameters[parameters.length - 1];
                switch (recipe) {
                    case "all":
                        Recipe.REGISTRY.values().forEach(tracking::learnRecipe);
                        tracking.sync(player);
                        break;
                    case "clear":
                        tracking.learnRecipe(null);
                        tracking.sync(player);
                        break;
                    default:
                        if (!recipe.contains(":")) recipe = "harvestfestival:" + recipe;
                        tracking.learnRecipe(Recipe.REGISTRY.get(new ResourceLocation(recipe)));
                        tracking.sync(player);
                        break;
                }
            } catch (NumberFormatException | PlayerNotFoundException ignored) {}
        } else throw new WrongUsageException(getUsage(sender));
    }
}


text:
#include <cmn/dns.h>
#include <bind/bind_util.h>
#include <mgr/dns_mgr.h>
#include <mgr/dns_oper.h>
#include <bind/bind_resolver.h>
#include <bind/named_config.h>
#include <agent/agent_xmpp_channel.h>

uint16_t DnsManager::g_trans_id_;

DnsManager::DnsManager()
    : bind_status_(boost::bind(&DnsManager::BindEventHandler, this, _1)),
      pending_done_queue_(TaskScheduler::GetInstance()->GetTaskId("dns::Config"), 0,
                          boost::bind(&DnsManager::PendingDone, this, _1)) {
    std::vector<BindResolver::DnsServer> bind_servers;
    bind_servers.push_back(BindResolver::DnsServer("127.0.0.1",
                                                   Dns::GetDnsPort()));
    BindResolver::Init(*Dns::GetEventManager()->io_service(), bind_servers,
                       boost::bind(&DnsManager::HandleUpdateResponse,
                                   this, _1));

    Dns::SetDnsConfigManager(&config_mgr_);
    DnsConfigManager::Observers obs;
    obs.virtual_dns = boost::bind(&DnsManager::ProcessConfig<VirtualDnsConfig>,
                                  this, _1, _2, _3);
    obs.virtual_dns_record =
        boost::bind(&DnsManager::ProcessConfig<VirtualDnsRecordConfig>,
                    this, _1, _2, _3);
    obs.ipam = boost::bind(&DnsManager::ProcessConfig<IpamConfig>, this, _1, _2, _3);
    obs.vnni = boost::bind(&DnsManager::ProcessConfig<VnniConfig>, this, _1, _2, _3);
    Dns::GetDnsConfigManager()->RegisterObservers(obs);

    DnsConfig::VdnsCallback = boost::bind(&DnsManager::DnsView, this, _1, _2);
    DnsConfig::VdnsRecordCallback = boost::bind(&DnsManager::DnsRecord, this,
                                                _1, _2);
    DnsConfig::VdnsZoneCallback = boost::bind(&DnsManager::DnsPtrZone, this,
                                              _1, _2, _3);
    pending_timer_ =
        TimerManager::CreateTimer(*Dns::GetEventManager()->io_service(),
              "DnsRetransmitTimer",
              TaskScheduler::GetInstance()->GetTaskId("dns::Config"), 0);
    StartPendingTimer();
}

void DnsManager::Initialize(DB *config_db, DBGraph *config_graph,
                            const std::string& named_config_dir,
                            const std::string& named_config_file,
                            const std::string& named_log_file,
                            const std::string& rndc_config_file,
                            const std::string& rndc_secret) {
    NamedConfig::Init(named_config_dir, named_config_file,
                      named_log_file, rndc_config_file, rndc_secret);
    // bind_status_.SetTrigger();
    config_mgr_.Initialize(config_db, config_graph);
}

DnsManager::~DnsManager() {
    pending_timer_->Cancel();
    TimerManager::DeleteTimer(pending_timer_);
    pending_done_queue_.Shutdown();
}

void DnsManager::Shutdown() {
    config_mgr_.Terminate();
    NamedConfig::Shutdown();
    BindResolver::Shutdown();
}

template <typename ConfigType>
void DnsManager::ProcessConfig(IFMapNodeProxy *proxy,
                               const std::string &name,
                               DnsConfigManager::EventType event) {
    IFMapNode *node = proxy->node();
    ConfigType *config = ConfigType::Find(name);
    switch (event) {
        case DnsConfigManager::CFG_ADD:
            if (!config) {
                config = new ConfigType(node);
            }
            config->OnAdd(node);
            break;

        case DnsConfigManager::CFG_CHANGE:
            if (config)
                config->OnChange(node);
            break;

        case DnsConfigManager::CFG_DELETE:
            if (config) {
                config->OnDelete();
                delete config;
            }
            break;

        default:
            assert(0);
    }
}

void DnsManager::ProcessAgentUpdate(BindUtil::Operation event,
                                    const std::string &name,
                                    const std::string &vdns_name,
                                    const DnsItem &item) {
    tbb::mutex::scoped_lock lock(mutex_);
    VirtualDnsRecordConfig *config = VirtualDnsRecordConfig::Find(name);
    switch (event) {
        case BindUtil::ADD_UPDATE:
            if (!config) {
                config = new VirtualDnsRecordConfig(name, vdns_name, item);
            }
            config->OnAdd();
            break;

        case BindUtil::CHANGE_UPDATE:
            if (config)
                config->OnChange(item);
            break;

        case BindUtil::DELETE_UPDATE:
            if (config) {
                config->OnDelete();
                delete config;
            }
            break;

        default:
            assert(0);
    }
}

void DnsManager::DnsView(const DnsConfig *cfg, DnsConfig::DnsConfigEvent ev) {
    if (!bind_status_.IsUp())
        return;

    const VirtualDnsConfig *config = static_cast<const VirtualDnsConfig *>(cfg);
    DNS_BIND_TRACE(DnsBindTrace, "Virtual DNS <" << config->GetName() <<
                   "> " << DnsConfig::ToEventString(ev));
    config->ClearNotified();
    std::string dns_domain = config->GetDomainName();
    if (dns_domain.empty()) {
        DNS_BIND_TRACE(DnsBindTrace, "Virtual DNS <" << config->GetName() <<
                       "> doesnt have domain; ignoring event : " <<
                       DnsConfig::ToEventString(ev));
        return;
    }

    NamedConfig *ncfg = NamedConfig::GetNamedConfigObject();
    if (ev == DnsConfig::CFG_ADD) {
        if (!CheckName(config->GetName(), dns_domain)) {
            return;
        }
        config->MarkNotified();
        ncfg->AddView(config);
    } else if (ev == DnsConfig::CFG_CHANGE) {
        if (CheckName(config->GetName(), dns_domain)) {
            config->MarkNotified();
        }
        ncfg->ChangeView(config);
        if (dns_domain != config->GetOldDomainName()) {
            NotifyAllDnsRecords(config, ev);
        } else if (config->HasReverseResolutionChanged()) {
            bool reverse_resolution = config->IsReverseResolutionEnabled();
            // if reverse resolution is enabled now, add the reverse records
            // if reverse resolution is disabled now, mark them as not notified
            NotifyReverseDnsRecords(config, ev, reverse_resolution);
        }
    } else {
        ncfg->DelView(config);
        PendingListViewDelete(config);
    }
}

void DnsManager::DnsPtrZone(const Subnet &subnet, const VirtualDnsConfig *vdns,
                            DnsConfig::DnsConfigEvent ev) {
    if (!bind_status_.IsUp())
        return;

    bool reverse_resolution = vdns->IsReverseResolutionEnabled();
    std::string dns_domain = vdns->GetDomainName();
    if (dns_domain.empty() || !reverse_resolution) {
        DNS_BIND_TRACE(DnsBindTrace, "Ptr Zone <" << vdns->GetName() <<
                       "> ; ignoring event: " << DnsConfig::ToEventString(ev) <<
                       " Domain: " << dns_domain << " Reverse Resolution: " <<
                       (reverse_resolution ? "enabled" : "disabled"));
        return;
    }

    NamedConfig *ncfg = NamedConfig::GetNamedConfigObject();
    if (ev == DnsConfig::CFG_DELETE) {
        ncfg->DelZone(subnet, vdns);
        PendingListZoneDelete(subnet, vdns);
    } else {
        ncfg->AddZone(subnet, vdns);
    }
    DNS_BIND_TRACE(DnsBindTrace, "Virtual DNS <" << vdns->GetName() << "> " <<
                   subnet.prefix.to_string() << "/" << subnet.plen << " " <<
                   DnsConfig::ToEventString(ev));
}

void DnsManager::DnsRecord(const DnsConfig *cfg, DnsConfig::DnsConfigEvent ev) {
    if (!bind_status_.IsUp())
        return;

    const VirtualDnsRecordConfig *config =
                static_cast<const VirtualDnsRecordConfig *>(cfg);
    config->ClearNotified();
    const DnsItem &item = config->GetRecord();
    if (item.name == "" || item.data == "") {
        DNS_BIND_TRACE(DnsBindError, "Virtual DNS Record <" <<
                       config->GetName() <<
                       "> doesnt have name / data; ignoring event : " <<
                       DnsConfig::ToEventString(ev));
        return;
    }

    if (config->GetViewName() == "" || !config->GetVirtualDns()->IsValid()) {
        return;
    }

    switch (ev) {
        case DnsConfig::CFG_ADD:
        case DnsConfig::CFG_CHANGE:
            if (SendRecordUpdate(BindUtil::ADD_UPDATE, config))
                config->MarkNotified();
            break;

        case DnsConfig::CFG_DELETE:
            if (SendRecordUpdate(BindUtil::DELETE_UPDATE, config))
                config->ClearNotified();
            break;

        default:
            assert(0);
    }
}

bool DnsManager::SendRecordUpdate(BindUtil::Operation op,
                                  const VirtualDnsRecordConfig *config) {
    DnsItem item = config->GetRecord();
    const autogen::VirtualDnsType vdns = config->GetVDns();

    std::string zone;
    if (item.type == DNS_PTR_RECORD) {
        if (!vdns.reverse_resolution) {
            DNS_BIND_TRACE(DnsBindTrace, "Virtual DNS Record <" <<
                           config->GetName() << "> PTR name " << item.name <<
                           " not added - reverse resolution is not enabled");
            return false;
        }
        uint32_t addr;
        if (BindUtil::IsIPv4(item.name, addr)) {
            BindUtil::GetReverseZone(addr, 32, item.name);
        } else {
            if (!BindUtil::GetAddrFromPtrName(item.name, addr)) {
                DNS_BIND_TRACE(DnsBindError, "Virtual DNS Record <" <<
                               config->GetName() << "> invalid PTR name " <<
                               item.name << "; ignoring");
                return false;
            }
        }
        if (!CheckName(config->GetName(), item.data)) {
            return false;
        }
        Subnet net;
        if (!config->GetVirtualDns()->GetSubnet(addr, net)) {
            DNS_BIND_TRACE(DnsBindError, "Virtual DNS Record <" <<
                           config->GetName() <<
                           "> doesnt belong to a known subnet; ignoring");
            return false;
        }
        BindUtil::GetReverseZone(addr, net.plen, zone);
        item.data = BindUtil::GetFQDN(item.data, vdns.domain_name, ".");
    } else {
        // Bind allows special chars in CNAME, NS names and in CNAME data
        if ((item.type == DNS_A_RECORD || item.type == DNS_AAAA_RECORD) &&
            !CheckName(config->GetName(), item.name)) {
            return false;
        }
        zone = config->GetVDns().domain_name;
        item.name = BindUtil::GetFQDN(item.name,
                                      vdns.domain_name, vdns.domain_name);
        if (item.type == DNS_CNAME_RECORD || item.type == DNS_MX_RECORD)
            item.data = BindUtil::GetFQDN(item.data, vdns.domain_name, ".");
        // In case of NS record, ensure that there are no special characters in data.
        // When it is virtual dns name, we could have chars like ':'
        if (item.type == DNS_NS_RECORD)
            BindUtil::RemoveSpecialChars(item.data);
    }
    DnsItems items;
    items.push_back(item);
    std::string view_name = config->GetViewName();
    SendUpdate(op, view_name, zone, items);
    return true;
}

void DnsManager::SendUpdate(BindUtil::Operation op, const std::string &view,
                            const std::string &zone, DnsItems &items) {
    uint8_t *pkt = new uint8_t[BindResolver::max_pkt_size];
    uint16_t xid = GetTransId();
    int len = BindUtil::BuildDnsUpdate(pkt, op, xid, view, zone, items);
    if (BindResolver::Resolver()->DnsSend(pkt, 0, len)) {
        DNS_BIND_TRACE(DnsBindTrace, "DNS Update sent for DNS record; xid = " <<
                   xid << "; View = " << view << "; Zone = " << zone << "; " <<
                   DnsItemsToString(items));
        AddPendingList(xid, view, zone, items, op);
    }
}

void DnsManager::SendRetransmit(uint16_t xid, BindUtil::Operation op,
                                const std::string &view,
                                const std::string &zone, DnsItems &items) {
    uint8_t *pkt = new uint8_t[BindResolver::max_pkt_size];
    int len = BindUtil::BuildDnsUpdate(pkt, op, xid, view, zone, items);
    if (BindResolver::Resolver()->DnsSend(pkt, 0, len)) {
        DNS_BIND_TRACE(DnsBindTrace, "DNS retransmit sent for DNS record; xid = " <<
                   xid << "; View = " << view << "; Zone = " << zone << "; " <<
                   DnsItemsToString(items));
    }
}

void DnsManager::UpdateAll() {
    VirtualDnsConfig::DataMap vmap = VirtualDnsConfig::GetVirtualDnsMap();
    for (VirtualDnsConfig::DataMap::iterator it = vmap.begin();
         it != vmap.end(); ++it) {
        VirtualDnsConfig *vdns = it->second;
        if (!vdns->GetDomainName().empty() &&
            CheckName(vdns->GetName(), vdns->GetDomainName())) {
            vdns->MarkNotified();
            DNS_BIND_TRACE(DnsBindTrace, "Virtual DNS <" << vdns->GetName() <<
                           "> Add");
        } else {
            vdns->ClearNotified();
        }
    }
    NamedConfig *ncfg = NamedConfig::GetNamedConfigObject();
    ncfg->AddAllViews();
    for (VirtualDnsConfig::DataMap::iterator it = vmap.begin();
         it != vmap.end(); ++it) {
        VirtualDnsConfig *vdns = it->second;
        if (!vdns->IsNotified())
            continue;
        NotifyAllDnsRecords(vdns, DnsConfig::CFG_ADD);
    }
}

void DnsManager::HandleUpdateResponse(uint8_t *pkt) {
    dns_flags flags;
    uint16_t xid;
    DnsItems ques, ans, auth, add;
    if (BindUtil::ParseDnsResponse(pkt, xid, flags, ques, ans, auth, add)) {
        if (flags.ret) {
            DNS_BIND_TRACE(DnsBindError, "Update failed : " <<
                           BindUtil::DnsResponseCode(flags.ret) <<
                           "; xid = " << xid);
            // ResendRecord(xid);
        } else {
            DNS_BIND_TRACE(DnsBindTrace, "Update successful; xid = " << xid);
            pending_done_queue_.Enqueue(xid);
        }
    }
    delete [] pkt;
}

bool DnsManager::PendingDone(uint16_t xid) {
    DeletePendingList(xid);
    return true;
}

void DnsManager::ResendAllRecords() {
    for (PendingListMap::iterator it = pending_map_.begin();
         it != pending_map_.end(); ) {
        SendRetransmit(it->first, it->second.op, it->second.view,
                       it->second.zone, it->second.items);
        it->second.retransmit_count++;
        if (it->second.retransmit_count > kMaxRetransmitCount) {
            DNS_BIND_TRACE(DnsBindTrace, "DNS records max retransmits reached;"
                           << "no more retransmission; xid = " << it->first);
            pending_map_.erase(it++);
        } else {
            it++;
        }
    }
}

void DnsManager::AddPendingList(uint16_t xid, const std::string &view,
                                const std::string &zone, const DnsItems &items,
                                BindUtil::Operation op) {
    // delete earlier entries for the same items
    UpdatePendingList(view, zone, items);

    PendingListMap::iterator it = pending_map_.find(xid);
    if (it != pending_map_.end()) {
        it->second.view = view;
        it->second.zone = zone;
        it->second.items = items;
        it->second.op = op;
        it->second.retransmit_count = 0;
        return;
    }
    pending_map_.insert(PendingListPair(xid, PendingList(xid, view, zone,
                                                         items, op)));
}

// if there is an update for an item which is already in pending list,
// remove it from the pending list
void DnsManager::UpdatePendingList(const std::string &view,
                                   const std::string &zone,
                                   const DnsItems &items) {
    for (PendingListMap::iterator it = pending_map_.begin();
         it != pending_map_.end(); ) {
        if (it->second.view == view &&
            it->second.zone == zone &&
            it->second.items == items)
            pending_map_.erase(it++);
        else
            it++;
    }
}

void DnsManager::DeletePendingList(uint16_t xid) {
    pending_map_.erase(xid);
}

void DnsManager::ClearPendingList() {
    pending_map_.clear();
}

// Remove entries from pending list, upon a view delete
void DnsManager::PendingListViewDelete(const VirtualDnsConfig *config) {
    for (PendingListMap::iterator it = pending_map_.begin();
         it != pending_map_.end(); ) {
        if (it->second.view == config->GetViewName())
            pending_map_.erase(it++);
        else
            it++;
    }
}

bool DnsManager::CheckZoneDelete(ZoneList &zones, PendingList &pend) {
    for (uint32_t i = 0; i < zones.size(); i++) {
        if (zones[i] == pend.zone)
            return true;
    }
    return false;
}

// Remove entries from pending list, upon a zone delete
void DnsManager::PendingListZoneDelete(const Subnet &subnet,
                                       const VirtualDnsConfig *config) {
    ZoneList zones;
    BindUtil::GetReverseZones(subnet, zones);

    for (PendingListMap::iterator it = pending_map_.begin();
         it != pending_map_.end(); ) {
        if (it->second.view == config->GetViewName() &&
            CheckZoneDelete(zones, it->second))
            pending_map_.erase(it++);
        else
            it++;
    }
}

void DnsManager::StartPendingTimer() {
    if (!pending_timer_->running()) {
        pending_timer_->Start(kPendingRecordRetransmitTime,
                              boost::bind(&DnsManager::PendingTimerExpiry, this));
    }
}

void DnsManager::CancelPendingTimer() {
    pending_timer_->Cancel();
}

bool DnsManager::PendingTimerExpiry() {
    // TODO: change timer to be per record & resend only on individual timeout
    ResendAllRecords();
    return true;
}

void DnsManager::NotifyAllDnsRecords(const VirtualDnsConfig *config,
                                     DnsConfig::DnsConfigEvent ev) {
    for (VirtualDnsConfig::VDnsRec::const_iterator it =
         config->virtual_dns_records_.begin();
         it != config->virtual_dns_records_.end(); ++it) {
        if ((*it)->IsValid())
            DnsRecord(*it, ev);
    }
}

void DnsManager::NotifyReverseDnsRecords(const VirtualDnsConfig *config,
                                         DnsConfig::DnsConfigEvent ev,
                                         bool notify) {
    for (VirtualDnsConfig::VDnsRec::const_iterator it =
         config->virtual_dns_records_.begin();
         it != config->virtual_dns_records_.end(); ++it) {
        DnsItem item = (*it)->GetRecord();
        if (item.type == DNS_PTR_RECORD) {
            (*it)->ClearNotified();
            if ((*it)->IsValid() && notify) {
                DnsRecord(*it, ev);
            }
        }
    }
}

inline uint16_t DnsManager::GetTransId() {
    return (++g_trans_id_ == 0 ? ++g_trans_id_ : g_trans_id_);
}

inline bool DnsManager::CheckName(std::string rec_name, std::string name) {
    if (BindUtil::HasSpecialChars(name)) {
        DNS_CONFIGURATION_LOG(
            g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
            SandeshLevel::SYS_ERR,
            "Invalid DNS Name - cannot use special characters in DNS name",
            rec_name, name);
        return false;
    }
    return true;
}

void DnsManager::BindEventHandler(BindStatus::Event event) {
    switch (event) {
        case BindStatus::Up: {
            DNS_OPERATIONAL_LOG(
                g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
                SandeshLevel::SYS_NOTICE, "BIND named up; DNS is operational");
            UpdateAll();
            break;
        }

        case BindStatus::Down: {
            DNS_OPERATIONAL_LOG(
                g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
                SandeshLevel::SYS_NOTICE, "BIND named down; DNS is not operational");
            NamedConfig *ncfg = NamedConfig::GetNamedConfigObject();
            ncfg->Reset();
            ClearPendingList();
            break;
        }

        default:
            assert(0);
    }
}

void ShowDnsConfig::HandleRequest() const {
    DnsConfigResponse *resp = new DnsConfigResponse();
    resp->set_context(context());
    VirtualDnsConfig::DataMap vdns = VirtualDnsConfig::GetVirtualDnsMap();

    std::vector<VirtualDnsSandesh> vdns_list_sandesh;
    for (VirtualDnsConfig::DataMap::iterator vdns_it = vdns.begin();
         vdns_it != vdns.end(); ++vdns_it) {
        VirtualDnsConfig *vdns_config = vdns_it->second;
        VirtualDnsSandesh vdns_sandesh;
        VirtualDnsTraceData vdns_trace_data;
        vdns_config->VirtualDnsTrace(vdns_trace_data);

        std::vector<VirtualDnsRecordTraceData> rec_list_sandesh;
        for (VirtualDnsConfig::VDnsRec::iterator rec_it =
             vdns_config->virtual_dns_records_.begin();
             rec_it != vdns_config->virtual_dns_records_.end(); ++rec_it) {
            VirtualDnsRecordTraceData rec_trace_data;
            (*rec_it)->VirtualDnsRecordTrace(rec_trace_data);
            rec_list_sandesh.push_back(rec_trace_data);
        }

        std::vector<std::string> net_list_sandesh;
        for (VirtualDnsConfig::IpamList::iterator ipam_iter =
             vdns_config->ipams_.begin();
             ipam_iter != vdns_config->ipams_.end(); ++ipam_iter) {
            IpamConfig *ipam = *ipam_iter;
            const IpamConfig::VnniList &vnni = ipam->GetVnniList();
            for (IpamConfig::VnniList::iterator vnni_it = vnni.begin();
                 vnni_it != vnni.end(); ++vnni_it) {
                Subnets &subnets = (*vnni_it)->GetSubnets();
                for (unsigned int i = 0; i < subnets.size(); i++) {
                    std::stringstream str;
                    str << subnets[i].prefix.to_string();
                    str << "/";
                    str << subnets[i].plen;
                    net_list_sandesh.push_back(str.str());
                }
            }
        }

        vdns_sandesh.set_virtual_dns(vdns_trace_data);
        vdns_sandesh.set_records(rec_list_sandesh);
        vdns_sandesh.set_subnets(net_list_sandesh);
        vdns_list_sandesh.push_back(vdns_sandesh);
    }

    resp->set_virtual_dns(vdns_list_sandesh);
    resp->Response();
}

void ShowVirtualDnsServers::HandleRequest() const {
    VirtualDnsServersResponse *resp = new VirtualDnsServersResponse();
    resp->set_context(context());
    VirtualDnsConfig::DataMap vdns = VirtualDnsConfig::GetVirtualDnsMap();

    std::vector<VirtualDnsServersSandesh> vdns_list_sandesh;
    for (VirtualDnsConfig::DataMap::iterator vdns_it = vdns.begin();
         vdns_it != vdns.end(); ++vdns_it) {
        VirtualDnsConfig *vdns_config = vdns_it->second;
        VirtualDnsServersSandesh vdns_sandesh;
        VirtualDnsTraceData vdns_trace_data;
        vdns_config->VirtualDnsTrace(vdns_trace_data);

        std::vector<std::string> net_list_sandesh;
        for (VirtualDnsConfig::IpamList::iterator ipam_iter =
             vdns_config->ipams_.begin();
             ipam_iter != vdns_config->ipams_.end(); ++ipam_iter) {
            IpamConfig *ipam = *ipam_iter;
            const IpamConfig::VnniList &vnni = ipam->GetVnniList();
            for (IpamConfig::VnniList::iterator vnni_it = vnni.begin();
                 vnni_it != vnni.end(); ++vnni_it) {
                Subnets &subnets = (*vnni_it)->GetSubnets();
                for (unsigned int i = 0; i < subnets.size(); i++) {
                    std::stringstream str;
                    str << subnets[i].prefix.to_string();
                    str << "/";
                    str << subnets[i].plen;
                    net_list_sandesh.push_back(str.str());
                }
            }
        }

        vdns_sandesh.set_virtual_dns(vdns_trace_data);
        vdns_sandesh.set_records(vdns_config->GetName());
        vdns_sandesh.set_num_records(vdns_config->virtual_dns_records_.size());
        vdns_sandesh.set_subnets(net_list_sandesh);
        vdns_list_sandesh.push_back(vdns_sandesh);
    }

    resp->set_virtual_dns_servers(vdns_list_sandesh);
    resp->Response();
}

void ShowVirtualDnsRecords::HandleRequest() const {
    VirtualDnsRecordsResponse *resp = new VirtualDnsRecordsResponse();
    VirtualDnsConfig::DataMap vdns = VirtualDnsConfig::GetVirtualDnsMap();

    std::stringstream ss(get_virtual_dns_server());
    std::string vdns_server, next_iterator;
    VirtualDnsRecordConfig *next_iterator_key = NULL;
    std::getline(ss, vdns_server, '@');
    std::getline(ss, next_iterator);
    if (!next_iterator.empty()) {
        std::stringstream next_iter(next_iterator);
        uint64_t value = 0;
        next_iter >> value;
        next_iterator_key = (VirtualDnsRecordConfig *) value;
    }
    std::vector<VirtualDnsRecordTraceData> rec_list_sandesh;
    VirtualDnsConfig::DataMap::iterator vdns_it = vdns.find(vdns_server);
    if (vdns_it != vdns.end()) {
        VirtualDnsConfig *vdns_config = vdns_it->second;
        int count = 0;
        for (VirtualDnsConfig::VDnsRec::iterator rec_it =
             vdns_config->virtual_dns_records_.lower_bound(next_iterator_key);
             rec_it != vdns_config->virtual_dns_records_.end(); ++rec_it) {
            VirtualDnsRecordTraceData rec_trace_data;
            (*rec_it)->VirtualDnsRecordTrace(rec_trace_data);
            rec_list_sandesh.push_back(rec_trace_data);
            if (++count == DnsManager::max_records_per_sandesh) {
                if (++rec_it == vdns_config->virtual_dns_records_.end())
                    break;
                std::stringstream str;
                uint64_t value = (uint64_t)(*rec_it);
                str << vdns_server << "@" << value;
                resp->set_getnext_record_set(str.str());
                break;
            }
        }
    }

    resp->set_context(context());
    resp->set_virtual_dns_server(vdns_server);
    resp->set_records(rec_list_sandesh);
    resp->Response();
}


text: from eda.components.ST import *


text:
package com.badlogicgames.superjumper;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Assets {
	public static Texture background;
	public static TextureRegion backgroundRegion;

	public static Texture items;
	public static TextureRegion mainMenu;
	public static TextureRegion pauseMenu;
	public static TextureRegion ready;
	public static TextureRegion gameOver;
	public static TextureRegion highScoresRegion;
	public static TextureRegion logo;
	public static TextureRegion soundOn;
	public static TextureRegion soundOff;
	public static TextureRegion arrow;
	public static TextureRegion pause;
	public static TextureRegion spring;
	public static TextureRegion castle;
	public static Animation coinAnim;
	public static Animation bobJump;
	public static Animation bobFall;
	public static TextureRegion bobHit;
	public static Animation squirrelFly;
	public static TextureRegion platform;
	public static Animation brakingPlatform;
	public static BitmapFont font;

	public static Music music;
	public static Sound jumpSound;
	public static Sound highJumpSound;
	public static Sound hitSound;
	public static Sound coinSound;
	public static Sound clickSound;

	public static Texture loadTexture (String file) {
		return new Texture(Gdx.files.internal(file));
	}

	public static void load () {
		background = loadTexture("data/background.png");
		backgroundRegion = new TextureRegion(background, 0, 0, 320, 480);

		items = loadTexture("data/items.png");
		mainMenu = new TextureRegion(items, 0, 224, 300, 110);
		pauseMenu = new TextureRegion(items, 224, 128, 192, 96);
		ready = new TextureRegion(items, 320, 224, 192, 32);
		gameOver = new TextureRegion(items, 352, 256, 160, 96);
		highScoresRegion = new TextureRegion(Assets.items, 0, 257, 300, 110 / 3);
		logo = new TextureRegion(items, 0, 352, 274, 142);
		soundOff = new TextureRegion(items, 0, 0, 64, 64);
		soundOn = new TextureRegion(items, 64, 0, 64, 64);
		arrow = new TextureRegion(items, 0, 64, 64, 64);
		pause = new TextureRegion(items, 64, 64, 64, 64);

		spring = new TextureRegion(items, 128, 0, 32, 32);
		castle = new TextureRegion(items, 128, 64, 64, 64);
		coinAnim = new Animation(0.2f, new TextureRegion(items, 128, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32),
			new TextureRegion(items, 192, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32));
		bobJump = new Animation(0.2f, new TextureRegion(items, 0, 128, 32, 32), new TextureRegion(items, 32, 128, 32, 32));
		bobFall = new Animation(0.2f, new TextureRegion(items, 64, 128, 32, 32), new TextureRegion(items, 96, 128, 32, 32));
		bobHit = new TextureRegion(items, 128, 128, 32, 32);
		squirrelFly = new Animation(0.2f, new TextureRegion(items, 0, 160, 32, 32), new TextureRegion(items, 32, 160, 32, 32));
		platform = new TextureRegion(items, 64, 160, 64, 16);
		brakingPlatform = new Animation(0.2f, new TextureRegion(items, 64, 160, 64, 16), new TextureRegion(items, 64, 176, 64, 16),
			new TextureRegion(items, 64, 192, 64, 16), new TextureRegion(items, 64, 208, 64, 16));

		font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false);

		music = Gdx.audio.newMusic(Gdx.files.internal("data/music.mp3"));
		music.setLooping(true);
		music.setVolume(0.5f);
		if (Settings.soundEnabled) music.play();
		jumpSound = Gdx.audio.newSound(Gdx.files.internal("data/jump.wav"));
		highJumpSound = Gdx.audio.newSound(Gdx.files.internal("data/highjump.wav"));
		hitSound = Gdx.audio.newSound(Gdx.files.internal("data/hit.wav"));
		coinSound = Gdx.audio.newSound(Gdx.files.internal("data/coin.wav"));
		clickSound = Gdx.audio.newSound(Gdx.files.internal("data/click.wav"));
	}

	public static void playSound (Sound sound) {
		if (Settings.soundEnabled) sound.play(1);
	}
}


text:
module.exports = {
  parse : require("./parse"),
  convert : require("./convert")
};


text:
****************************************
Cloudmesh
****************************************

Documentation:
----------------------------------------------------------------------

The documentation is located on two places. The best way to start is
at

* http://mycloudmesh.org/learning

additional information is published at

* http://cloudmesh.github.io/cloudmesh/

This documentation contains an extensive set of information and
tutorial like setups for cloudmesh. This would be a good start.

Some older doecumentation and the Python API can be found at

* http://mycloudmesh.org

Code
----------------------------------------------------------------------

The code is located at

Code:  https://github.com/cloudmesh/cloudmesh

Git Notifications
----------------------------------------------------------------------

cloudmesh-git@googlegroups.com

Mailinglist
----------------------------------------------------------------------

cloudmesh@googlegroups.com