text:
<?php

use app\decibel\debug\DErrorHandler;
use app\decibel\utility\DStr as Str;

/**
 * Debugs a variable.
 *
 * Debugged variables will only be shown if the Application Debug Mode is enabled.
 *
 * @param    mixed $variable              The variable to debug.
 * @param    bool  $includeBacktrace      If set to true, a backtrace will be
 *                                        included. Defaults to false.
 *
 * @return    void
 */
function debug($variable, $includeBacktrace = false)
{
    DErrorHandler::debug($variable, $includeBacktrace);
}

/**
 * Sets a variable to a default value if it has not already been
 * defined.
 *
 * This essentially provides short-hand for the following code:
 *
 * <code>
 * if (!isset($var)) {
 *    $var = 'value';
 * }
 * </code>
 *
 * @param    mixed $var     Pointer to the variable to set.
 * @param    mixed $default The default value.
 *
 * @return    void
 */
function set_default(&$var, $default)
{
    if (!isset($var)) {
        $var = $default;
    }
}

/**
 * @param string $key
 * @param mixed  $default
 *
 * @return mixed
 */
function env($key, $default = null)
{
    $value = getenv($key);
    if ($value === false) {
        return value($default);
    }

    if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
        return substr($value, 1, -1);
    }

    return $value;
}

/**
 * Function that either returns the original value or executes it if
 * it contains a Closure.
 *
 * @param mixed $value
 *
 * @return mixed
 */
function value($value)
{
    return ($value instanceof Closure) ? call_user_func($value) : $value;
}


text:
package io.plasmap.util.test

import io.plasmap.model.geometry.{GeometryCollection, MultiPolygon}
import io.plasmap.util.GeoCalculator
import io.plasmap.model.{OsmDenormalizedObject, OsmDenormalizedRelation}
import io.plasmap.parser.OsmDenormalizedParser
import io.plasmap.parser.impl.OsmGeoJSONParser
import io.plasmap.serializer.GeoJsonSerialiser
import org.specs2.mutable.Specification
import org.specs2.specification.core.Fragment

import scala.io.{Codec, Source}

class GeoCalculatorSpec extends Specification {

  import OsmTestData._

  def fakeGeo(shape: List[(Double, Double)]) = {
    GeometryCollection(
      List(
        MultiPolygon(
          List(
            List(
              shape
            )
          )
        )
      )
    )
  }

  def mockRelation(geos: (Double, Double)*): GeometryCollection = fakeGeo(geos.toList)

  val city = mockRelation(
    (0.0, 0.0),
    (1.0, 0.0),
    (1.0, 1.0),
    (0.0, 1.0),
    (0.0, 0.0)
  )

  def district(moveBy: Double) = mockRelation(
    (0.0 + moveBy, 0.0),
    (1.0 + moveBy, 0.0),
    (1.0 + moveBy, 1.0),
    (0.0 + moveBy, 1.0),
    (0.0 + moveBy, 0.0)
  )

  def test(percentOutside: Double) = GeoCalculator.within(district(percentOutside), city)

  "The GeoCalculator" should {

    s"calculate that Essen districts are contained in Essen" >> {
      Fragment.foreach(districtsEssen) { district =>
        s"${district.tags.filter(_.key == "name")}\n" ! {
          GeoCalculator.within(district.geometry, essen.geometry) must beTrue
        }
      }
    }

    s"calculate that Muehlheim distritcs are not contained in Essen" >> {
      Fragment.foreach(districtsMuehlheim) { district =>
        s"${district.tags.filter(_.key == "name")}\n" ! {
          GeoCalculator.within(district.geometry, essen.geometry) must beFalse
        }
      }
    }
    s"calculate that Muelheim districts are contained in Muehlheim" >> {
      Fragment.foreach(districtsMuehlheim) { district =>
        s"${district.tags.filter(_.key == "name")}\n" ! {
          GeoCalculator.within(district.geometry, muehlheim.geometry) must beTrue
        }
      }
    }

    s"calculate that Essen districts are not contained in Muehlheim" >> {
      Fragment.foreach(districtsEssen) { district =>
        s"${district.tags.filter(_.key == "name")}\n" ! {
          GeoCalculator.within(district.geometry, muehlheim.geometry) must beFalse
        }
      }
    }

    "consider inner polygons as being inner" in {
      test(0.0) must beTrue
    }

    "consider polygons that only overlap 90 percent as being inner" in {
      test(0.1) must beTrue
    }

    "consider polygons that overlap more than 90 percent as NOT being inner" in {
      test(0.2) must beFalse
    }

    val path = "util/src/test/resources/"

    "fix https://github.com/plasmap/plasmap/issues/2 (TC1)" in {

      val tc1Inner = GeoJsonSerialiser.geometryFromJSON(Source.fromFile(path + "gh.issue#2.tc1-inner.geojson")(Codec.UTF8).mkString).get.asInstanceOf[MultiPolygon]
      val tc1Outer = GeoJsonSerialiser.geometryFromJSON(Source.fromFile(path + "gh.issue#2.tc1-outer.geojson")(Codec.UTF8).mkString).get.asInstanceOf[MultiPolygon]
      GeoCalculator.fuzzyWithin(List(tc1Inner), List(tc1Outer), 0.9) must beFalse
    }

    "fix https://github.com/plasmap/plasmap/issues/2 (TC2)" in {

      val tc2Inner = GeoJsonSerialiser.geometryFromJSON(Source.fromFile(path + "gh.issue#2.tc2-inner.geojson")(Codec.UTF8).mkString).get.asInstanceOf[MultiPolygon]
      val tc2Outer = GeoJsonSerialiser.geometryFromJSON(Source.fromFile(path + "gh.issue#2.tc2-outer.geojson")(Codec.UTF8).mkString).get.asInstanceOf[MultiPolygon]
      GeoCalculator.fuzzyWithin(List(tc2Inner), List(tc2Outer), 0.9) must beFalse
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

use DTS\eBaySDK\BulkDataExchange\Types\GetItemJobActionType;

class GetItemJobActionTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new GetItemJobActionType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\BulkDataExchange\Types\GetItemJobActionType', $this->obj);
    }

    public function testExtendsBaseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
    }
}


text:
package com.google.googlejavaformat;

import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import java.util.Iterator;
import java.util.NoSuchElementException;

/** Platform-independent newline handling. */
public class Newlines {

  /** Returns the number of line breaks in the input. */
  public static int count(String input) {
    return Iterators.size(lineOffsetIterator(input)) - 1;
  }

  /** Returns the index of the first break in the input, or {@code -1}. */
  public static int firstBreak(String input) {
    Iterator<Integer> it = lineOffsetIterator(input);
    it.next();
    return it.hasNext() ? it.next() : -1;
  }

  private static final ImmutableSet<String> BREAKS = ImmutableSet.of("\r\n", "\n", "\r");

  /** Returns true if the entire input string is a recognized line break. */
  public static boolean isNewline(String input) {
    return BREAKS.contains(input);
  }

  /**
   * Returns the terminating line break in the input, or {@code null} if the input does not end in a
   * break.
   */
  public static String getLineEnding(String input) {
    for (String b : BREAKS) {
      if (input.endsWith(b)) {
        return b;
      }
    }
    return null;
  }

  /**
   * Returns the first line separator in the text, or {@code "\n"} if the text does not contain a
   * single line separator.
   */
  public static String guessLineSeparator(String text) {
    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      switch (c) {
        case '\r':
          if (i + 1 < text.length() && text.charAt(i + 1) == '\n') {
            return "\r\n";
          }
          return "\r";
        case '\n':
          return "\n";
        default:
          break;
      }
    }
    return "\n";
  }

  /** Returns true if the input contains any line breaks. */
  public static boolean containsBreaks(String text) {
    return CharMatcher.anyOf("\n\r").matchesAnyOf(text);
  }

  /** Returns an iterator over the start offsets of lines in the input. */
  public static Iterator<Integer> lineOffsetIterator(String input) {
    return new LineOffsetIterator(input);
  }

  /** Returns an iterator over lines in the input, including trailing whitespace. */
  public static Iterator<String> lineIterator(String input) {
    return new LineIterator(input);
  }

  private static class LineOffsetIterator implements Iterator<Integer> {

    private int curr = 0;
    private int idx = 0;
    private final String input;

    private LineOffsetIterator(String input) {
      this.input = input;
    }

    @Override
    public boolean hasNext() {
      return curr != -1;
    }

    @Override
    public Integer next() {
      if (curr == -1) {
        throw new NoSuchElementException();
      }
      int result = curr;
      advance();
      return result;
    }

    private void advance() {
      for (; idx < input.length(); idx++) {
        char c = input.charAt(idx);
        switch (c) {
          case '\r':
            if (idx + 1 < input.length() && input.charAt(idx + 1) == '\n') {
              idx++;
            }
            // falls through
          case '\n':
            idx++;
            curr = idx;
            return;
          default:
            break;
        }
      }
      curr = -1;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("remove");
    }
  }

  private static class LineIterator implements Iterator<String> {

    int idx;
    String curr;

    private final String input;
    private final Iterator<Integer> indices;

    private LineIterator(String input) {
      this.input = input;
      this.indices = lineOffsetIterator(input);
      idx = indices.next(); // read leading 0
    }

    private void advance() {
      int last = idx;
      if (indices.hasNext()) {
        idx = indices.next();
      } else if (hasNext()) {
        // no terminal line break
        idx = input.length();
      } else {
        throw new NoSuchElementException();
      }
      curr = input.substring(last, idx);
    }

    @Override
    public boolean hasNext() {
      return idx < input.length();
    }

    @Override
    public String next() {
      advance();
      return curr;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("remove");
    }
  }
}


text:
package cn.micro.neural.storage;

import lombok.Getter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.io.Serializable;
import java.util.List;

/**
 * FactoryStorage
 *
 * @author lry
 */
@Getter
public enum FactoryStorage {

    // ===

    INSTANCE;

    private IStorage storage;

    public void setRedisTemplate(RedisTemplate<String, Serializable> redisTemplate) {
        this.storage = new IStorage() {
            @Override
            public Number[] eval(String script, List<String> keys, Object... args) {
                return redisTemplate.execute(new DefaultRedisScript<>(script, Number[].class), keys, args);
            }

            @Override
            public boolean set(String key, Object value) {
                return false;
            }

            @Override
            public boolean setEx(String key, Object value, Long expireTime) {
                return false;
            }

            @Override
            public boolean exists(String key) {
                return false;
            }

            @Override
            public Object get(String key) {
                return null;
            }

            @Override
            public boolean remove(String key) {
                return false;
            }
        };
    }

}


text:
package se.enelefant.service;

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import se.enelefant.core.annotation.HandlerEndpoint;
import se.enelefant.core.annotation.ResponseStatus;
import se.enelefant.core.enums.HttpStatus;
import se.enelefant.core.enums.RequestMethod;
import se.enelefant.core.handler.WebServerHandler;
import se.enelefant.helper.LoggerHelper;
import se.enelefant.helper.PropertyHelper;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.logging.Logger;

public class HandlerEndpointRegistryService {

    private static final Logger logger = LoggerHelper.getMainLogger();
    private static final String PKG_SEPARATOR = ".";
    private static final String CLASS_FILE_SUFFIX = ".class";
    private static final String DIR_SEPARATOR = "/";
    private static final String BAD_PACKAGE_ERROR = "Path '%s' is not valid, input was '%s'";

    public void registerEndpoints(HttpServer server) throws Exception {
        logger.info("Registering endpoints...");
        Map<EndpointMetaData, Class<HttpHandler>> endpoints = findEndpoints(new HashMap<>(), PropertyHelper.getHandlerPackage());

        List<Filter> handlerFilters = findHandlerFilters(new ArrayList<>(), PropertyHelper.getFilterPackage());

        for (EndpointMetaData endpointMetaData : endpoints.keySet()) {
            Class<HttpHandler> httpHandlerClass = endpoints.get(endpointMetaData);
            HttpContext context = server.createContext(endpointMetaData.endpoint, httpHandlerClass.newInstance());
            context.getAttributes().put(WebServerHandler.ACCEPTED_METHOD_KEY, endpointMetaData.requestMethod);
            context.getAttributes().put(WebServerHandler.RESPONSE_STATUS_KEY, endpointMetaData.responseStatus);
            for (Filter filter : handlerFilters) {
                context.getFilters().add(filter);
            }
            logger.info("Registering " + httpHandlerClass.getSimpleName() + ", endpoint = '" + endpointMetaData.endpoint + "', method = '" + endpointMetaData.requestMethod.getStringMethod() + "'");
        }
    }

    private List<Filter> findHandlerFilters(List<Class<Filter>> filterClasses, String scannedPackage) throws IllegalAccessException, InstantiationException {
        String scannedPath = scannedPackage.replace(PKG_SEPARATOR, DIR_SEPARATOR);
        URL scannedUrl = ClassLoader.getSystemClassLoader().getResource(scannedPath);
        if (scannedUrl == null) {
            throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, scannedPackage));
        }
        File scannedDir = new File(scannedUrl.getFile());
        for (File file : scannedDir.listFiles()) {
            findFilters(filterClasses, file, scannedPackage);
        }
        List<Filter> filters = new ArrayList<>();
        for (Class<Filter> filterClass : filterClasses) {
            Filter filter = filterClass.newInstance();
            logger.info("Registering filter " + filterClass.getSimpleName());
            filters.add(filter);
        }
        return filters;
    }

    private void findFilters(List<Class<Filter>> filters, File file, String scannedPackage) {
        String resource = scannedPackage + PKG_SEPARATOR + file.getName();
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                findFilters(filters, child, resource);
            }
        } else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
            int endIndex = resource.length() - CLASS_FILE_SUFFIX.length();
            String className = resource.substring(0, endIndex);
            try {
                Class<?> potentialClass = Class.forName(className);
                if (Filter.class.isAssignableFrom(potentialClass)) {
                    filters.add((Class<Filter>) potentialClass);
                }
            } catch (ClassNotFoundException ignore) {
            }
        }
    }

    private Map<EndpointMetaData, Class<HttpHandler>> findEndpoints(Map<EndpointMetaData, Class<HttpHandler>> endpoints, String scannedPackage) {
        String scannedPath = scannedPackage.replace(PKG_SEPARATOR, DIR_SEPARATOR);
        URL scannedUrl = ClassLoader.getSystemClassLoader().getResource(scannedPath);
        if (scannedUrl == null) {
            throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, scannedPackage));
        }
        File scannedDir = new File(scannedUrl.getFile());
        for (File file : scannedDir.listFiles()) {
            findEndpoints(endpoints, file, scannedPackage);
        }
        return endpoints;
    }

    private void findEndpoints(Map<EndpointMetaData, Class<HttpHandler>> endpoints, File file, String scannedPackage) {
        String resource = scannedPackage + PKG_SEPARATOR + file.getName();
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                findEndpoints(endpoints, child, resource);
            }
        } else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
            int endIndex = resource.length() - CLASS_FILE_SUFFIX.length();
            String className = resource.substring(0, endIndex);
            try {
                Class<?> potentialClass = Class.forName(className);
                if (HttpHandler.class.isAssignableFrom(potentialClass)) {
                    for (Method method : potentialClass.getMethods()) {
                        HandlerEndpoint annotation = method.getAnnotation(HandlerEndpoint.class);
                        ResponseStatus responseStatusAnnotation = method.getAnnotation(ResponseStatus.class);
                        if (annotation != null) {
                            EndpointMetaData metaData = new EndpointMetaData(annotation.value(), annotation.method());
                            if (responseStatusAnnotation != null) {
                                metaData.responseStatus = responseStatusAnnotation.value();
                            } else {
                                metaData.responseStatus = HttpStatus.OK;
                            }
                            endpoints.put(metaData, (Class<HttpHandler>) potentialClass);
                        }
                    }
                }
            } catch (ClassNotFoundException ignore) {
            }
        }
    }

    private class EndpointMetaData {
        String endpoint;
        RequestMethod requestMethod;
        HttpStatus responseStatus;

        public EndpointMetaData(String endpoint, RequestMethod requestMethod) {
            this.endpoint = endpoint;
            this.requestMethod = requestMethod;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            EndpointMetaData that = (EndpointMetaData) o;
            return Objects.equals(endpoint, that.endpoint) &&
                    requestMethod == that.requestMethod;
        }

        @Override
        public int hashCode() {
            return Objects.hash(endpoint, requestMethod);
        }
    }
}


text:
@class EKNKnobInfo;

@protocol EKNPropertyEditor;

@protocol EKNPropertyEditorDelegate <NSObject>

- (void)propertyEditor:(id <EKNPropertyEditor>)editor changedKnob:(EKNKnobInfo*)knob;

@end

@protocol EKNPropertyEditor <NSObject>

@property (weak, nonatomic) IBOutlet id <EKNPropertyEditorDelegate> delegate;
@property (strong, nonatomic) EKNKnobInfo* info;

@end


text:
"""

Python Interchangeable Virtual Instrument Library

Copyright (c) 2014 Alex Forencich

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

"""

from .. import ivi
import time

class diconGP700(ivi.Driver):
    "DiCon Fiberoptics GP700 Programmable Fiberoptic Instrument"

    def __init__(self, *args, **kwargs):
        self.__dict__.setdefault('_instrument_id', 'GP700')

        super(diconGP700, self).__init__(*args, **kwargs)

        self._identity_description = "DiCon Fiberoptics GP700 Programmable Fiberoptic Instrument"
        self._identity_identifier = ""
        self._identity_revision = ""
        self._identity_vendor = ""
        self._identity_instrument_manufacturer = "DiCon Fiberoptics Inc"
        self._identity_instrument_model = ""
        self._identity_instrument_firmware_revision = ""
        self._identity_specification_major_version = 0
        self._identity_specification_minor_version = 0
        self._identity_supported_instrument_models = ['GP700']

        self._memory_size = 9

        self._config = ""

        self._attenuator_count = 0
        self._attenuator_name = list()
        self._attenuator_level = list()
        self._attenuator_level_max = list()

        self._filter_count = 0
        self._filter_name = list()
        self._filter_wavelength = list()
        self._filter_wavelength_max = list()
        self._filter_wavelength_min = list()

        self._matrix_input_count = 0
        self._matrix_input_name = list()
        self._matrix_output_count = 0
        self._matrix_input_output = list()

        self._switch_count = 0
        self._switch_name = list()
        self._switch_output = list()
        self._switch_input = list()
        self._switch_output_count = list()
        self._switch_input_count = list()

        ivi.add_property(self, 'attenuators[].level',
                        self._get_attenuator_level,
                        self._set_attenuator_level,
                        None,
                        ivi.Doc("""
                        Specifies the level of the attenuator module.  The units are dB.
                        """))
        ivi.add_property(self, 'attenuators[].level_max',
                        self._get_attenuator_level_max,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the maximum attenuation level supported.  The units are dB.
                        """))
        ivi.add_property(self, 'attenuators[].name',
                        self._get_attenuator_name,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the name of the attenuator module.
                        """))
        ivi.add_property(self, 'filters[].wavelength',
                        self._get_filter_wavelength,
                        self._set_filter_wavelength,
                        None,
                        ivi.Doc("""
                        Specifies the center wavelength of the filter module.  The units are nm.
                        """))
        ivi.add_property(self, 'filters[].wavelength_max',
                        self._get_filter_wavelength_max,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the maximum center wavelength of the filter.  The units are nm.
                        """))
        ivi.add_property(self, 'filters[].wavelength_min',
                        self._get_filter_wavelength_min,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the minimum center wavelength of the filter.  The units are nm.
                        """))
        ivi.add_property(self, 'filters[].name',
                        self._get_filter_name,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the name of the filter module.
                        """))
        ivi.add_property(self, 'switches[].output',
                        self._get_switch_output,
                        self._set_switch_output,
                        None,
                        ivi.Doc("""
                        Specify switch output connection.
                        """))
        ivi.add_property(self, 'switches[].output_count',
                        self._get_switch_output_count,
                        None,
                        None,
                        ivi.Doc("""
                        Query number of outputs supported by switch.
                        """))
        ivi.add_property(self, 'switches[].input',
                        self._get_switch_input,
                        self._set_switch_input,
                        None,
                        ivi.Doc("""
                        Specify switch input connection.
                        """))
        ivi.add_property(self, 'switches[].input_count',
                        self._get_switch_input_count,
                        None,
                        None,
                        ivi.Doc("""
                        Query number of inputs supported by switch.
                        """))
        ivi.add_method(self, 'switches[].get',
                        self._switch_get,
                        ivi.Doc("""
                        Get current switch input and output configuration.
                        """))
        ivi.add_method(self, 'switches[].set',
                        self._switch_set,
                        ivi.Doc("""
                        Set switch input and output configuration.
                        """))
        ivi.add_property(self, 'switches[].name',
                        self._get_switch_name,
                        None,
                        None,
                        ivi.Doc("""
                        Returns the name of the switch module.
                        """))

        ivi.add_method(self, 'memory.save',
                        self._memory_save,
                        ivi.Doc("""
                        Save device configuration to the specified memory slot.
                        """))
        ivi.add_method(self, 'memory.recall',
                        self._memory_recall,
                        ivi.Doc("""
                        Recall device configuration from the specified memory slot.
                        """))

        if self._initialized_from_constructor:
            self._init_channels()

    def initialize(self, resource = None, id_query = False, reset = False, **keywargs):
        "Opens an I/O session to the instrument."

        super(diconGP700, self).initialize(resource, id_query, reset, **keywargs)

        # interface clear
        if not self._driver_operation_simulate:
            self._clear()

        # check ID
        if id_query and not self._driver_operation_simulate:
            id = self.identity.instrument_model
            id_check = self._instrument_id
            id_short = id[:len(id_check)]
            if id_short != id_check:
                raise Exception("Instrument ID mismatch, expecting %s, got %s", id_check, id_short)

        # reset
        if reset:
            self.utility_reset()

        if not self._initialized_from_constructor:
            self._init_channels()

    def _load_id_string(self):
        if self._driver_operation_simulate:
            self._identity_instrument_manufacturer = "Not available while simulating"
            self._identity_instrument_model = "Not available while simulating"
            self._identity_instrument_firmware_revision = "Not available while simulating"
        else:
            lst = self._ask("*IDN?").split(",")
            self._identity_instrument_manufacturer = lst[0].strip()
            self._identity_instrument_model = lst[1].strip()
            self._identity_instrument_firmware_revision = lst[3].strip()
            self._set_cache_valid(True, 'identity_instrument_manufacturer')
            self._set_cache_valid(True, 'identity_instrument_model')
            self._set_cache_valid(True, 'identity_instrument_firmware_revision')

    def _get_identity_instrument_manufacturer(self):
        if self._get_cache_valid():
            return self._identity_instrument_manufacturer
        self._load_id_string()
        return self._identity_instrument_manufacturer

    def _get_identity_instrument_model(self):
        if self._get_cache_valid():
            return self._identity_instrument_model
        self._load_id_string()
        return self._identity_instrument_model

    def _get_identity_instrument_firmware_revision(self):
        if self._get_cache_valid():
            return self._identity_instrument_firmware_revision
        self._load_id_string()
        return self._identity_instrument_firmware_revision

    def _utility_disable(self):
        pass

    def _utility_error_query(self):
        error_code = 0
        error_message = "No error"
        if not self._driver_operation_simulate:
            error_message = self._ask("err?").strip('"')
            error_code = 1
            if error_message == '0':
                error_code = 0
        return (error_code, error_message)

    def _utility_lock_object(self):
        pass

    def _utility_reset(self):
        if not self._driver_operation_simulate:
            self._write("*RST")
            time.sleep(0.1)
            self._clear()
            self.driver_operation.invalidate_all_attributes()

    def _utility_reset_with_defaults(self):
        self._utility_reset()

    def _utility_self_test(self):
        code = 0
        message = "Self test passed"
        if not self._driver_operation_simulate:
            code = int(self._ask("*TST?"))
            if code != 0:
                message = "Self test failed"
        return (code, message)

    def _utility_unlock_object(self):
        pass

    def _init_channels(self):
        try:
            super(diconGP700, self)._init_channels()
        except AttributeError:
            pass

        config = self._get_config()

        self._attenuator_count = 0
        self._attenuator_name = list()
        self._attenuator_level = list()
        self._attenuator_level_max = list()

        self._filter_count = 0
        self._filter_name = list()
        self._filter_wavelength = list()
        self._filter_wavelength_max = list()
        self._filter_wavelength_min = list()

        self._matrix_input_count = 0
        self._matrix_input_name = list()
        self._matrix_output_count = 0
        self._matrix_input_output = list()

        self._switch_count = 0
        self._switch_name = list()
        self._switch_output = list()
        self._switch_input = list()
        self._switch_output_count = list()
        self._switch_input_count = list()

        lst = config.split(",")
        lst = [x.strip() for x in lst]
        lst.sort()

        for itm in lst:
            v = itm.split(" ")

            if len(itm) == 0:
                continue

            if v[0] == 'MATRIX':
                self._matrix_input_count = int(v[1][5:])
                self._matrix_output_count = int(v[2][6:])
            elif itm[0] == 'A':
                if v[0] not in self._attenuator_name:
                    self._attenuator_count += 1
                    self._attenuator_name.append(v[0])
                    self._attenuator_level.append(0.0)
                    self._attenuator_level_max.append(0.0)

                i = ivi.get_index(self._attenuator_name, v[0])

                self._attenuator_level[i] = 0.0
                self._attenuator_level_max[i] = float(v[1])
            elif itm[0] == 'F':
                if v[0] not in self._filter_name:
                    self._filter_count += 1
                    self._filter_name.append(v[0])
                    self._filter_wavelength.append(0.0)
                    self._filter_wavelength_min.append(0.0)
                    self._filter_wavelength_max.append(0.0)

                i = ivi.get_index(self._filter_name, v[0])

                self._filter_wavelength[i] = 0.0
                self._filter_wavelength_min[i] = float(v[1][3:])
                self._filter_wavelength_max[i] = float(v[2][3:])
            elif itm[0] == 'M':
                if v[0] not in self._switch_name:
                    self._switch_count += 1
                    self._switch_name.append(v[0])
                    self._switch_input.append(0)
                    self._switch_output.append(0)
                    self._switch_input_count.append(0)
                    self._switch_output_count.append(0)

                i = ivi.get_index(self._switch_name, v[0])

                self._switch_input[i] = 1
                self._switch_output[i] = 0
                self._switch_input_count[i] = int(v[2][1:])
                self._switch_output_count[i] = int(v[1][1:])
            elif itm[0] == 'P':
                if v[0] not in self._switch_name:
                    self._switch_count += 1
                    self._switch_name.append(v[0])
                    self._switch_input.append(0)
                    self._switch_output.append(0)
                    self._switch_input_count.append(0)
                    self._switch_output_count.append(0)

                i = ivi.get_index(self._switch_name, v[0])

                self._switch_input[i] = 1
                self._switch_output[i] = 0
                self._switch_input_count[i] = 1
                self._switch_output_count[i] = int(v[1][7:])
            elif itm[0] == 'S':
                cnt = int(v[0][1:])

                for i in range(cnt):
                    n = 'S%02d' % (i+1)

                    if n not in self._switch_name:
                        self._switch_count += 1
                        self._switch_name.append(n)
                        self._switch_input.append(0)
                        self._switch_output.append(0)
                        self._switch_input_count.append(0)
                        self._switch_output_count.append(0)

                    i = ivi.get_index(self._switch_name, n)

                    self._switch_input[i] = 1
                    self._switch_output[i] = 1
                    self._switch_input_count[i] = 1
                    self._switch_output_count[i] = 2

        self.attenuators._set_list(self._attenuator_name)
        self.filters._set_list(self._filter_name)
        self.switches._set_list(self._switch_name)

    def _get_config(self):
        if not self._driver_operation_simulate and not self._get_cache_valid():
            self._config = self._ask("system:config?")
            self._set_cache_valid()
        return self._config

    def _get_attenuator_level(self, index):
        index = ivi.get_index(self._attenuator_name, index)
        name = self._attenuator_name[index]
        if not self._driver_operation_simulate and not self._get_cache_valid():
            resp = self._ask("%s?" % (name))
            self._attenuator_level = float(resp)
            self._set_cache_valid()
        return self._attenuator_level[index]

    def _set_attenuator_level(self, index, value):
        index = ivi.get_index(self._attenuator_name, index)
        name = self._attenuator_name[index]
        value = float(value)
        if value < 0 or value > self._attenuator_level_max[index]:
            raise ivi.OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("%s %f" % (name, value))
        self._attenuator_level[index] = value
        self._set_cache_valid()

    def _get_attenuator_level_max(self, index):
        index = ivi.get_index(self._attenuator_name, index)
        return self._attenuator_level_max[index]

    def _get_attenuator_name(self, index):
        index = ivi.get_index(self._attenuator_name, index)
        return self._attenuator_name[index]

    def _get_filter_wavelength(self, index):
        index = ivi.get_index(self._filter_name, index)
        name = self._filter_name[index]
        if not self._driver_operation_simulate and not self._get_cache_valid():
            resp = self._ask("%s?" % (name))
            self._filter_wavelength = float(resp)
            self._set_cache_valid()
        return self._filter_wavelength[index]

    def _set_filter_wavelength(self, index, value):
        index = ivi.get_index(self._filter_name, index)
        name = self._filter_name[index]
        value = float(value)
        if value < self._filter_wavelength_min[index] or value > self._filter_wavelength_max[index]:
            raise ivi.OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("%s %f" % (name, value))
        self._filter_wavelength[index] = value
        self._set_cache_valid()

    def _get_filter_wavelength_max(self, index):
        index = ivi.get_index(self._filter_name, index)
        return self._filter_wavelength[index]

    def _get_filter_wavelength_min(self, index):
        index = ivi.get_index(self._filter_name, index)
        return self._filter_wavelength[index]

    def _get_filter_name(self, index):
        index = ivi.get_index(self._filter_name, index)
        return self._filter_name[index]

    def _get_switch_output(self, index):
        return self._switch_get(index)[0]

    def _set_switch_output(self, index, value):
        self._switch_set(index, value)

    def _get_switch_output_count(self, index):
        index = ivi.get_index(self._switch_name, index)
        return self._switch_output_count[index]

    def _get_switch_input(self, index):
        return self._switch_get(index)[1]

    def _set_switch_input(self, index, value):
        index = ivi.get_index(self._switch_name, index)
        self._switch_set(index, self._switch_output[index], value)

    def _get_switch_input_count(self, index):
        index = ivi.get_index(self._switch_name, index)
        return self._switch_input_count[index]

    def _switch_get(self, index):
        index = ivi.get_index(self._switch_name, index)
        name = self._switch_name[index]

        if name[0] == 'M':
            if not self._driver_operation_simulate:
                if not self._get_cache_valid('switch_output', index) or not self._get_cache_valid('switch_input', index):
                #if True:
                    resp = self._ask("%s?" % name)
                    lst = resp.split(',')
                    self._switch_output[index] = int(lst[0].strip())
                    self._switch_input[index] = int(lst[1].strip())
                    self._set_cache_valid(True, 'switch_output', index)
                    self._set_cache_valid(True, 'switch_input', index)
            return (self._switch_output[index], self._switch_input[index])
        elif name[0] == 'P' or name[0] == 'S':
            if not self._driver_operation_simulate:
                if not self._get_cache_valid('switch_output', index):
                #if True:
                    resp = self._ask("%s?" % name)
                    self._switch_output[index] = int(resp.strip())
                    self._switch_input[index] = 1
                    self._set_cache_valid(True, 'switch_output', index)
                    self._set_cache_valid(True, 'switch_input', index)
            return (self._switch_output[index], self._switch_input[index])

    def _switch_set(self, index, output, input=None):
        index = ivi.get_index(self._switch_name, index)
        name = self._switch_name[index]

        output = int(output)
        if input is not None:
            input = int(input)

        if name[0] == 'M':
            if output < 0 or output > self._switch_output_count[index]:
                raise ivi.OutOfRangeException()
            if input is not None and (input < 1 or input > self._switch_input_count[index]):
                raise ivi.OutOfRangeException()
            if not self._driver_operation_simulate:
                if input is None:
                    self._write("%s %d" % (name, output))
                else:
                    self._write("%s %d, %d" % (name, output, input))
            else:
                self._switch_output[index] = output
                self._set_cache_valid(True, 'switch_output', index)
                if input is not None:
                    self._switch_input[index] = input
                    self._set_cache_valid(True, 'switch_input', index)
        elif name[0] == 'P' or name[0] == 'S':
            if output < 1 or output > self._switch_output_count[index]:
                raise ivi.OutOfRangeException()
            if input is not None and input != 1:
                raise ivi.OutOfRangeException()
            if not self._driver_operation_simulate:
                self._write("%s %d" % (name, output))
            else:
                self._switch_output[index] = output
                self._switch_input[index] = 1
                self._set_cache_valid(True, 'switch_output', index)
                self._set_cache_valid(True, 'switch_input', index)

    def _get_switch_name(self, index):
        index = ivi.get_index(self._switch_name, index)
        return self._switch_name[index]

    def _memory_save(self, index):
        index = int(index)
        if index < 1 or index > self._memory_size:
            raise OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("*sav %d" % index)

    def _memory_recall(self, index):
        index = int(index)
        if index < 1 or index > self._memory_size:
            raise OutOfRangeException()
        if not self._driver_operation_simulate:
            self._write("*rcl %d" % index)


text:
package dagger.android.processor;

import static com.google.auto.common.GeneratedAnnotationSpecs.generatedAnnotationSpec;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.squareup.javapoet.MethodSpec.constructorBuilder;
import static com.squareup.javapoet.MethodSpec.methodBuilder;
import static com.squareup.javapoet.TypeSpec.classBuilder;
import static com.squareup.javapoet.TypeSpec.interfaceBuilder;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import static javax.lang.model.util.ElementFilter.methodsIn;

import com.google.auto.common.BasicAnnotationProcessor.Step;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import dagger.android.processor.AndroidInjectorDescriptor.Validator;
import java.io.IOException;
import javax.annotation.processing.Filer;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.util.Elements;

/** Generates the implementation specified in {@code ContributesAndroidInjector}. */
final class ContributesAndroidInjectorGenerator implements Step {

  private final AndroidInjectorDescriptor.Validator validator;
  private final Filer filer;
  private final Elements elements;
  private final boolean useStringKeys;
  private final SourceVersion sourceVersion;

  ContributesAndroidInjectorGenerator(
      Validator validator,
      boolean useStringKeys,
      Filer filer,
      Elements elements,
      SourceVersion sourceVersion) {
    this.validator = validator;
    this.useStringKeys = useStringKeys;
    this.filer = filer;
    this.elements = elements;
    this.sourceVersion = sourceVersion;
  }

  @Override
  public ImmutableSet<String> annotations() {
    return ImmutableSet.of(TypeNames.CONTRIBUTES_ANDROID_INJECTOR.toString());
  }

  @Override
  public ImmutableSet<Element> process(ImmutableSetMultimap<String, Element> elementsByAnnotation) {
    ImmutableSet.Builder<Element> deferredElements = ImmutableSet.builder();
    for (ExecutableElement method : methodsIn(elementsByAnnotation.values())) {
      try {
        validator.createIfValid(method).ifPresent(this::generate);
      } catch (TypeNotPresentException e) {
        deferredElements.add(method);
      }
    }
    return deferredElements.build();
  }

  private void generate(AndroidInjectorDescriptor descriptor) {
    ClassName moduleName =
        descriptor
            .enclosingModule()
            .topLevelClassName()
            .peerClass(
                Joiner.on('_').join(descriptor.enclosingModule().simpleNames())
                    + "_"
                    + LOWER_CAMEL.to(UPPER_CAMEL, descriptor.method().getSimpleName().toString()));

    String baseName = descriptor.injectedType().simpleName();
    ClassName subcomponentName = moduleName.nestedClass(baseName + "Subcomponent");
    ClassName subcomponentFactoryName = subcomponentName.nestedClass("Factory");

    TypeSpec.Builder module =
        classBuilder(moduleName)
            .addOriginatingElement(descriptor.method())
            .addAnnotation(
                AnnotationSpec.builder(TypeNames.MODULE)
                    .addMember("subcomponents", "$T.class", subcomponentName)
                    .build())
            .addModifiers(PUBLIC, ABSTRACT)
            .addMethod(bindAndroidInjectorFactory(descriptor, subcomponentFactoryName))
            .addType(subcomponent(descriptor, subcomponentName, subcomponentFactoryName))
            .addMethod(constructorBuilder().addModifiers(PRIVATE).build());
    generatedAnnotationSpec(elements, sourceVersion, AndroidProcessor.class)
        .ifPresent(module::addAnnotation);

    try {
      JavaFile.builder(moduleName.packageName(), module.build())
          .skipJavaLangImports(true)
          .build()
          .writeTo(filer);
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  private MethodSpec bindAndroidInjectorFactory(
      AndroidInjectorDescriptor descriptor, ClassName subcomponentBuilderName) {
    return methodBuilder("bindAndroidInjectorFactory")
        .addAnnotation(TypeNames.BINDS)
        .addAnnotation(TypeNames.INTO_MAP)
        .addAnnotation(androidInjectorMapKey(descriptor))
        .addModifiers(ABSTRACT)
        .returns(
            ParameterizedTypeName.get(
                TypeNames.ANDROID_INJECTOR_FACTORY, WildcardTypeName.subtypeOf(TypeName.OBJECT)))
        .addParameter(subcomponentBuilderName, "builder")
        .build();
  }

  private AnnotationSpec androidInjectorMapKey(AndroidInjectorDescriptor descriptor) {
    if (useStringKeys) {
      return AnnotationSpec.builder(TypeNames.ANDROID_INJECTION_KEY)
          .addMember("value", "$S", descriptor.injectedType().toString())
          .build();
    }
    return AnnotationSpec.builder(TypeNames.CLASS_KEY)
        .addMember("value", "$T.class", descriptor.injectedType())
        .build();
  }

  private TypeSpec subcomponent(
      AndroidInjectorDescriptor descriptor,
      ClassName subcomponentName,
      ClassName subcomponentFactoryName) {
    AnnotationSpec.Builder subcomponentAnnotation = AnnotationSpec.builder(TypeNames.SUBCOMPONENT);
    for (ClassName module : descriptor.modules()) {
      subcomponentAnnotation.addMember("modules", "$T.class", module);
    }

    return interfaceBuilder(subcomponentName)
        .addModifiers(PUBLIC)
        .addAnnotation(subcomponentAnnotation.build())
        .addAnnotations(descriptor.scopes())
        .addSuperinterface(
            ParameterizedTypeName.get(TypeNames.ANDROID_INJECTOR, descriptor.injectedType()))
        .addType(subcomponentFactory(descriptor, subcomponentFactoryName))
        .build();
  }

  private TypeSpec subcomponentFactory(
      AndroidInjectorDescriptor descriptor, ClassName subcomponentFactoryName) {
    return interfaceBuilder(subcomponentFactoryName)
        .addAnnotation(TypeNames.SUBCOMPONENT_FACTORY)
        .addModifiers(PUBLIC, STATIC)
        .addSuperinterface(
            ParameterizedTypeName.get(
                TypeNames.ANDROID_INJECTOR_FACTORY, descriptor.injectedType()))
        .build();
  }
}


text:
///////////////////////////////////
// Server Node.js full websocket //
///////////////////////////////////

/**
 * Declare the server HTTP
 * listen to the port 8080
 */
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});

server.listen(8888, function() {
    console.log((new Date()) + ' Server is listening on port 8888');
});

/**
 * Import websocket module
 * on the server HTTP
 */
var WebSocketServer = require('websocket').server;

/**
 * Create the websocket server
 */
wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

/**
 * Declare the variable connections for rooms and users
 */
var connections = new Array();

/**
 * When a user connects
 */
wsServer.on('request', function(request) {

    //-- Variables declarations--//
    var guest = false;
    var room = '';

    /**
     * Accept the connection
     */
    var connection = request.accept(null, request.origin);
    console.log((new Date()) + ' Connection accepted.');

    /**
     * When we receive signal message from the client
     */
    connection.on('message', function(message) {
        message = JSON.parse(message.utf8Data);
        console.log(message);
        switch(message["type"]) {

            /**
             * When a user is invited
             * join the room
             */
            case "INVITE" :
                guest = true;
                room = message["value"];
                console.log(message);
                connections[room].push(connection);
            break;

            /**
             * If you are the first user to connect
             * create room
             */
            case "GETROOM" :
                room = Math.floor(Math.random()*1000001).toString();
                message = JSON.stringify({'type' : 'GETROOM', 'value': room});
                connection.send(message);
                connections.push(room);
                console.log(room);
                connections[room] = new Array();
                connections[room].push(connection);
            break;

            /**
             * When a user send a SDP message
             * broadcast to all users in the room
             */
            case "candidate" : case "offer" : case "answer" :
                console.log(message);
                connections[room].forEach(function(destination) {
                    if(destination != connection) {
                        message = JSON.stringify(message);
                        destination.send(message);
                    }
                });
            break;
        }
    });

    /**
     * When the user hang up
     * broadcast bye signal to all users in the room
     */
    connection.on('close', function(reasonCode, description) {
        if(connections[room]) {
            connections[room].forEach(function(destination) {
                if(destination != connection) {
                    var message = JSON.stringify({'type' : 'BYE', 'value': ''});
                    destination.send(message);
                }
            });
        }
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

})