text:
var loader = require("@loader");

if(loader.env === 'production') {
	exports.fetch = function(load) {
		// return a thenable for fetching (as per specification)
		// alternatively return new Promise(function(resolve, reject) { ... })
		var cssFile = load.address;

		var link = document.createElement('link');
		link.rel = 'stylesheet';
		link.href = cssFile;

		document.head.appendChild(link);
		return "";
	};
} else {
	exports.instantiate = function(load) {
		var loader = this;

		load.metadata.deps = [];
		load.metadata.execute = function(){
			var source = load.source+"/*# sourceURL="+load.address+" */";
			source = source.replace(/url\(['"]?([^'"\)]*)['"]?\)/g, function(whole, part) {
				return "url(" + steal.joinURIs( load.address, part) + ")";
			});

			if(load.source && typeof document !== "undefined") {
				var doc = document.head ? document : document.getElementsByTagName ?
					document : document.documentElement;

				var head = doc.head || doc.getElementsByTagName('head')[0],
					style = document.createElement('style');

				if(!head) {
					var docEl = doc.documentElement || doc;
					head = document.createElement("head");
					docEl.insertBefore(head, docEl.firstChild);
				}

				// make source load relative to the current page
				style.type = 'text/css';

				if (style.styleSheet){
					style.styleSheet.cssText = source;
				} else {
					style.appendChild(document.createTextNode(source));
				}
				head.appendChild(style);

				if(loader.has("live-reload")) {
					var cssReload = loader["import"]("live-reload", { name: "$css" });
					Promise.resolve(cssReload).then(function(reload){
						loader["import"](load.name).then(function(){
							reload.once(load.name, function(){
								head.removeChild(style);
							});
						});
					});
				}
			}

			return System.newModule({source: source});
		};
		load.metadata.format = "css";
	};

}

exports.buildType = "css";
exports.includeInBuild = true;


text:
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.

## Installation

To install the API client library to your local Maven repository, simply execute:

```shell
mvn install
```

To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:

```shell
mvn deploy
```

Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.

### Maven users

Add this dependency to your project's POM:

```xml
<dependency>
    <groupId>nl.esciencecenter.e3dchem.gpcrdb</groupId>
    <artifactId>nl.esciencecenter.e3dchem.gpcrdb.client</artifactId>
    <version>2.0.3</version>
    <scope>compile</scope>
</dependency>
```

### Gradle users

Add this dependency to your project's build file:

```groovy
compile "nl.esciencecenter.e3dchem.gpcrdb:nl.esciencecenter.e3dchem.gpcrdb.client:2.0.3"
```

### Others

At first generate the JAR by executing:

    mvn package

Then manually install the following JARs:

* target/nl.esciencecenter.e3dchem.gpcrdb.client-2.0.3.jar
* target/lib/*.jar

## Getting Started

Please follow the [installation](#installation) instruction and execute the following Java code:

```java

import nl.esciencecenter.e3dchem.gpcrdb.client.*;
import nl.esciencecenter.e3dchem.gpcrdb.client.auth.*;
import nl.esciencecenter.e3dchem.gpcrdb.client.model.*;
import nl.esciencecenter.e3dchem.gpcrdb.client.ServicesalignmentApi;

import java.io.File;
import java.util.*;

public class ServicesalignmentApiExample {

    public static void main(String[] args) {

        ServicesalignmentApi apiInstance = new ServicesalignmentApi();
        String slug = "slug_example"; // String |
        try {
            Object result = apiInstance.familyAlignmentGET(slug);
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling ServicesalignmentApi#familyAlignmentGET");
            e.printStackTrace();
        }
    }
}

```

## Documentation for API Endpoints

All URIs are relative to *https://gpcrdb.org*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*ServicesalignmentApi* | [**familyAlignmentGET**](docs/ServicesalignmentApi.md#familyAlignmentGET) | **GET** /services/alignment/family/{slug}/ | Get a full sequence alignment of a protein family including a consensus sequence
*ServicesalignmentApi* | [**familyAlignmentGET_0**](docs/ServicesalignmentApi.md#familyAlignmentGET_0) | **GET** /services/alignment/family/{slug}/statistics/ | Get a full sequence alignment of a protein family including a consensus sequence
*ServicesalignmentApi* | [**familyAlignmentPartialGET**](docs/ServicesalignmentApi.md#familyAlignmentPartialGET) | **GET** /services/alignment/family/{slug}/{segments}/ | Get a partial sequence alignment of a protein family
*ServicesalignmentApi* | [**familyAlignmentPartialGET_0**](docs/ServicesalignmentApi.md#familyAlignmentPartialGET_0) | **GET** /services/alignment/family/{slug}/{segments}/statistics/ | Get a partial sequence alignment of a protein family
*ServicesalignmentApi* | [**familyAlignmentPartialSpeciesGET**](docs/ServicesalignmentApi.md#familyAlignmentPartialSpeciesGET) | **GET** /services/alignment/family/{slug}/{segments}/{latin_name}/ | Get a partial sequence alignment of a protein family
*ServicesalignmentApi* | [**familyAlignmentPartialSpeciesGET_0**](docs/ServicesalignmentApi.md#familyAlignmentPartialSpeciesGET_0) | **GET** /services/alignment/family/{slug}/{segments}/{latin_name}/statistics/ | Get a partial sequence alignment of a protein family
*ServicesalignmentApi* | [**proteinAlignmentGET**](docs/ServicesalignmentApi.md#proteinAlignmentGET) | **GET** /services/alignment/protein/{proteins}/ | Get a full sequence alignment of two or more proteins
*ServicesalignmentApi* | [**proteinAlignmentPartialGET**](docs/ServicesalignmentApi.md#proteinAlignmentPartialGET) | **GET** /services/alignment/protein/{proteins}/{segments}/ | Get a partial sequence alignment of two or more proteins
*ServicesalignmentApi* | [**proteinAlignmentStatisticsGET**](docs/ServicesalignmentApi.md#proteinAlignmentStatisticsGET) | **GET** /services/alignment/protein/{proteins}/statistics/ | Add a /statics at the end of an alignment in order to
*ServicesalignmentApi* | [**proteinAlignmentStatisticsGET_0**](docs/ServicesalignmentApi.md#proteinAlignmentStatisticsGET_0) | **GET** /services/alignment/protein/{proteins}/{segments}/statistics/ | Add a /statics at the end of an alignment in order to
*ServicesalignmentApi* | [**proteinSimilaritySearchAlignmentGET**](docs/ServicesalignmentApi.md#proteinSimilaritySearchAlignmentGET) | **GET** /services/alignment/similarity/{proteins}/{segments}/ | Get a segment sequence alignment of two or more proteins ranked by similarity
*ServicesmutantsApi* | [**mutantListGET**](docs/ServicesmutantsApi.md#mutantListGET) | **GET** /services/mutants/{entry_name}/ | Get a list of mutants of single protein instance by entry name
*ServicesplotApi* | [**helixBoxGET**](docs/ServicesplotApi.md#helixBoxGET) | **GET** /services/plot/helixbox/{entry_name}/ | Get SVG source code for a protein's helix box plot
*ServicesplotApi* | [**snakePlotGET**](docs/ServicesplotApi.md#snakePlotGET) | **GET** /services/plot/snake/{entry_name}/ | Get SVG source code for a protein's snake plot
*ServicesproteinApi* | [**proteinByAccessionDetailGET**](docs/ServicesproteinApi.md#proteinByAccessionDetailGET) | **GET** /services/protein/accession/{accession}/ | Get a single protein instance by accession
*ServicesproteinApi* | [**proteinDetailGET**](docs/ServicesproteinApi.md#proteinDetailGET) | **GET** /services/protein/{entry_name}/ | Get a single protein instance by entry name
*ServicesproteinfamilyApi* | [**proteinFamilyChildrenListGET**](docs/ServicesproteinfamilyApi.md#proteinFamilyChildrenListGET) | **GET** /services/proteinfamily/children/{slug}/ | Get a list of child families of a protein family
*ServicesproteinfamilyApi* | [**proteinFamilyDescendantListGET**](docs/ServicesproteinfamilyApi.md#proteinFamilyDescendantListGET) | **GET** /services/proteinfamily/descendants/{slug}/ | Get a list of descendant families of a protein family
*ServicesproteinfamilyApi* | [**proteinFamilyDetailGET**](docs/ServicesproteinfamilyApi.md#proteinFamilyDetailGET) | **GET** /services/proteinfamily/{slug}/ | Get a single protein family instance
*ServicesproteinfamilyApi* | [**proteinFamilyListGET**](docs/ServicesproteinfamilyApi.md#proteinFamilyListGET) | **GET** /services/proteinfamily/ | Get a list of protein families
*ServicesproteinfamilyApi* | [**proteinsInFamilyListGET**](docs/ServicesproteinfamilyApi.md#proteinsInFamilyListGET) | **GET** /services/proteinfamily/proteins/{slug}/ | Get a list of proteins in a protein family
*ServicesproteinfamilyApi* | [**proteinsInFamilySpeciesListGET**](docs/ServicesproteinfamilyApi.md#proteinsInFamilySpeciesListGET) | **GET** /services/proteinfamily/proteins/{slug}/{latin_name}/ | Get a list of proteins in a protein family
*ServicesresiduesApi* | [**residuesExtendedListGET**](docs/ServicesresiduesApi.md#residuesExtendedListGET) | **GET** /services/residues/extended/{entry_name}/ | Get a list of residues of a protein, including alternative generic numbers
*ServicesresiduesApi* | [**residuesListGET**](docs/ServicesresiduesApi.md#residuesListGET) | **GET** /services/residues/{entry_name}/ | Get a list of residues of a protein
*ServicesspeciesApi* | [**speciesDetailGET**](docs/ServicesspeciesApi.md#speciesDetailGET) | **GET** /services/species/{latin_name}/ | Get a single species instance
*ServicesspeciesApi* | [**speciesListGET**](docs/ServicesspeciesApi.md#speciesListGET) | **GET** /services/species/ | Get a list of species
*ServicesstructureApi* | [**representativeStructureListGET**](docs/ServicesstructureApi.md#representativeStructureListGET) | **GET** /services/structure/representative/ | Get a list of representative structures (one for each protein and activation state)
*ServicesstructureApi* | [**representativeStructureListProteinGET**](docs/ServicesstructureApi.md#representativeStructureListProteinGET) | **GET** /services/structure/protein/{entry_name}/representative/ | Get a list of representative structures of a protein (one for each activation state)
*ServicesstructureApi* | [**structureAssignGenericNumbersPOST**](docs/ServicesstructureApi.md#structureAssignGenericNumbersPOST) | **POST** /services/structure/assign_generic_numbers | Assign generic residue numbers (Ballesteros-Weinstein and GPCRdb schemes) to an uploaded pdb file
*ServicesstructureApi* | [**structureDetailGET**](docs/ServicesstructureApi.md#structureDetailGET) | **GET** /services/structure/{pdb_code}/ | Get a single structure instance
*ServicesstructureApi* | [**structureLigandInteractionsGET**](docs/ServicesstructureApi.md#structureLigandInteractionsGET) | **GET** /services/structure/{pdb_code}/interaction/ | Get a list of interactions between structure and ligand
*ServicesstructureApi* | [**structureListGET**](docs/ServicesstructureApi.md#structureListGET) | **GET** /services/structure/ | Get a list of structures
*ServicesstructureApi* | [**structureListProteinGET**](docs/ServicesstructureApi.md#structureListProteinGET) | **GET** /services/structure/protein/{entry_name}/ | Get a list of structures of a protein
*ServicesstructureApi* | [**structureSingleProteinGET**](docs/ServicesstructureApi.md#structureSingleProteinGET) | **GET** /services/structure/protein/{entry_name}/?single | Get the structure of a protein
*ServicesstructureApi* | [**structureTemplateGET**](docs/ServicesstructureApi.md#structureTemplateGET) | **GET** /services/structure/template/{entry_name}/ | Get the most similar structure template for a protein using a 7TM alignment
*ServicesstructureApi* | [**structureTemplatePartialGET**](docs/ServicesstructureApi.md#structureTemplatePartialGET) | **GET** /services/structure/template/{entry_name}/{segments}/ | Get the most similar structure template for a protein using a partial alignment

## Documentation for Models

 - [Ligand](docs/Ligand.md)
 - [MutationSerializer](docs/MutationSerializer.md)
 - [ParentProteinFamilySerializer](docs/ParentProteinFamilySerializer.md)
 - [ProteinFamilySerializer](docs/ProteinFamilySerializer.md)
 - [ProteinSerializer](docs/ProteinSerializer.md)
 - [ProteinSimilarities](docs/ProteinSimilarities.md)
 - [ProteinSimilarity](docs/ProteinSimilarity.md)
 - [ResidueExtendedSerializer](docs/ResidueExtendedSerializer.md)
 - [ResidueGenericNumberSerializer](docs/ResidueGenericNumberSerializer.md)
 - [ResidueSerializer](docs/ResidueSerializer.md)
 - [SpeciesSerializer](docs/SpeciesSerializer.md)
 - [Structure](docs/Structure.md)
 - [StructureLigandInteractionSerializer](docs/StructureLigandInteractionSerializer.md)
 - [WriteMutationSerializer](docs/WriteMutationSerializer.md)
 - [WriteParentProteinFamilySerializer](docs/WriteParentProteinFamilySerializer.md)
 - [WriteProteinFamilySerializer](docs/WriteProteinFamilySerializer.md)
 - [WriteProteinSerializer](docs/WriteProteinSerializer.md)
 - [WriteResidueExtendedSerializer](docs/WriteResidueExtendedSerializer.md)
 - [WriteResidueGenericNumberSerializer](docs/WriteResidueGenericNumberSerializer.md)
 - [WriteResidueSerializer](docs/WriteResidueSerializer.md)
 - [WriteSpeciesSerializer](docs/WriteSpeciesSerializer.md)
 - [WriteStructureLigandInteractionSerializer](docs/WriteStructureLigandInteractionSerializer.md)

## Documentation for Authorization

All endpoints do not require authorization.
Authentication schemes defined for the API:

## Recommendation

It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.

## Author

redpajama_set_name: RedPajamaGithub


text:
"""Message Handler.

# Authors:  MohammadHossein GohariNejad <hoseingohari76@gmail.com>
#           Sajjad Azami <sajjadaazami@gmail.com>
# License:  BSD 3 clause

Plays the server role in communication_node

Relations
----------
subscribes from /message_server topic,
publishes on corresponding nodes /ns/message_status topic

"""
import os
import signal
import sys
from time import gmtime,strftime
import rospy
from communication_node.msg import *
from nav_msgs.msg import *

debuger_mode=False;
information_logger=None;
rate=None
message_handlers_list=[]

def on_exit(*args):
    global information_logger
    print ( "\n EXITING MESSAGE HANDLER")
    if information_logger!=None :
         information_logger.write("\n The Test has finished on "+strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " GMT time \n")
         information_logger.write("\n ======================== \n ======================== \n \n \n")
         information_logger.close()
    sys.exit(0)

class message_handle:
    """
    this class is wrapper around a ros publisher and a ros subscriber
    and a callback function for the ros rossubscirber
    for each data type given to the this script through launch file or
    parameter server this script will create an object to
    handle messages of that type
    """

    def __init__(self,sub_topic="",pub_topic="",data_type=None,tag="",alt_type=None):
            """this is the constructor function for message_handle class
            :parameter
            sub_topic : string, the prefix for the subscribing topic
            pub_topic : string, the topic for publishing the messages to
            data_type : type, the type of the message that's going to be handled
            tag       : string, tag for the data type
            alt_type  : type, alternative type for publishing message

            Relations
            ----------
            subscribes from /"sub_topic"+"tag"
            """
            self.sub_topic=sub_topic;
            self.pub_topic=pub_topic;
            self.data_type=data_type;
            self.alt_type=alt_type;
            self.tag=tag;
            self.subscriber=rospy.Subscriber(self.sub_topic+self.tag,self.data_type, self.callback_function,queue_size=20);
            self.message_publisher=None;

    def callback_function(self,data):
            """this is the callback function for self.subscriber
            :parameter
            data : self.data_type, this is the data received by the Subscriber

            Relations
            ----------
            publishes to "data.source"+"self.pub_topic"
            """
            global information_logger
            global propagation_parameters
            # TODO handle for different message types
            # TODO prop_model = data.prop_model
            if(self.tag!="map"and self.tag!="Odom"):
                print("new "+self.tag+" received")
            robots_list=rospy.get_param("/robots_list")
            if ((data.source not in robots_list )or(data.destination not in robots_list) ):
                return;
            connection_list=[];
            connection_list=(rospy.get_param("/connection_list_"+data.source));
            source_index=robots_list.index(data.destination);
            if (connection_list[1+source_index]==1):
            #if (True):
                    if (self.alt_type!=None):
                       self.message_publisher = rospy.Publisher(data.source +"/g_map", self.alt_type, queue_size=10)
                       i=0
                       while not ( rospy.is_shutdown() or i>1):
                                 self.message_publisher.publish(data.data)
                                 print("from",data.source," to",data.destination);
                                 i+=1
                                 rate.sleep()
                       i=0
                    else:
                       self.message_publisher = rospy.Publisher(data.destination + self.pub_topic, self.data_type, queue_size=10)
                       i=0
                       while not ( rospy.is_shutdown() or i>1):
                                 self.message_publisher.publish(data)
                                 print("from",data.source," to",data.destination);
                                 #print("sent messagne",self.tag)
                                 i+=1
                                 rate.sleep()
                       i=0

                    #print "communication is possible"
                    if debuger_mode==True :
                        # we write infomation to the log file
                       information_logger.write(self.tag+"".join(["-" for k in range(0,11-len(self.tag))]))
                       information_logger.write(data.source+"".join(["-" for k in range(0,11-len(data.source))]))
                       information_logger.write(data.destination+"".join(["-" for k in range(0,20-len(data.destination))]))
                       information_logger.write("message sent"+"\n")

            else:
                    # TODO, ignore the message, send feedback
                    if debuger_mode==True :
                      # we write infomation to the log file
                      information_logger.write(self.tag+"".join(["-" for k in range(0,11-len(self.tag))]))
                      information_logger.write(data.source+"".join(["-" for k in range(0,11-len(data.source))]))
                      information_logger.write(data.destination+"".join(["-" for k in range(0,20-len(data.destination))]))
                      information_logger.write("failed"+"\n")
                    #print "communication is not possible"

def listener():
    global information_logger
    global rate
    global debuger_mode
    global message_handlers_list;
    global propagation_models;
    rospy.init_node('communication_node_message_handler')
    debuger_mode=rospy.get_param("debuger_mode",default=False)
    if debuger_mode==True :
         log_file=rospy.get_param("log_file",default="results")
         if not os.path.exists("/home/user/project_franchesco/communication_node/test_results/"+log_file):
             os.makedirs("/home/user/project_franchesco/communication_node/test_results/"+log_file)
         information_logger =  open("/home/user/project_franchesco/communication_node/test_results/"+log_file+"/"+log_file+".log", "w")
         information_logger.write("\n \n \n ###################### \n ###################### \n")
         information_logger.write("\n This is the result of test on "+strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " GMT time \n")
         information_logger.write("Type-------Source-----Destination---------Outcome\n");
    signal.signal(signal.SIGINT, on_exit)
    signal.signal(signal.SIGTERM, on_exit)
    rate=rospy.Rate(50)
    message_list=[["/message_server_","/inbox_Goal",Data_Goal,"Goal",None],["/message_server_","/inbox_Map",Data_Map,"map",None]];
    for i in range (0,len(message_list)):
        message_handlers_list.append(message_handle(message_list[i][0],message_list[i][1],message_list[i][2],message_list[i][3],message_list[i][4]));
    rospy.spin()

listener()


text:
<?php
namespace Kino\Controller;
use \Zend\Mvc\Controller\AbstractRestfulController;

class RestfulControllerTemplate extends AbstractRestfulController
{

    public function indexAction ()
    {
        return $this->routeNotImplemented();
    }

    public function getList ()
    {
        return $this->routeNotImplemented();
    }

    public function get ($id)
    {
        return $this->routeNotImplemented();
    }

    public function create ($data)
    {
        return $this->routeNotImplemented();
    }

    public function update ($id, $data)
    {
        return $this->routeNotImplemented();
    }

    public function delete ($id)
    {
        return $this->routeNotImplemented();
    }

    function routeNotImplemented ()
    {
        $this->response->setStatusCode(405);
        throw new \Exception('This method is not implemented.');

        // return new JsonModel(
        // array(
        // 'Information:' => 'This route is not implemented.'
        // ));
    }
}

?>


text:
require 'spec_helper'

describe 'bindings test', type: :feature, sauce: true do
  it 'should load the page' do
    visit '/'

    expect(page).to have_content('Kitchen Sink')
  end

  describe 'text/fields' do
    it 'should load the bindings page and update bindings' do
      visit '/'

      click_link 'Bindings'

      # Fill in one field and see if it updates the rest
      fill_in('pageName1', with: 'Page bindings')
      expect(find('#pageName1').value).to eq('Page bindings')
      expect(find('#pageName2').value).to eq('Page bindings')
      expect(find('#pageName3')).to have_content('Page bindings')

      fill_in('pageName2', with: 'Update everywhere')
      expect(find('#pageName1').value).to eq('Update everywhere')
      expect(find('#pageName2').value).to eq('Update everywhere')
      expect(find('#pageName3')).to have_content('Update everywhere')
    end

    it 'should update params bindings and the url' do
      visit '/'

      click_link 'Bindings'

      # phantom does not support the html5 history api
      # TODO: We could probably polyfill this in phantom
      expect(current_path).to eq('/bindings') if ENV['BROWSER'] != 'phantom'

      # Fill in one field and see if it updates the rest
      fill_in('paramsName1', with: 'Params bindings')
      expect(find('#paramsName1').value).to eq('Params bindings')
      expect(find('#paramsName2').value).to eq('Params bindings')
      expect(find('#paramsName3')).to have_content('Params bindings')

      fill_in('paramsName2', with: 'Update everywhere')
      expect(find('#paramsName1').value).to eq('Update everywhere')
      expect(find('#paramsName2').value).to eq('Update everywhere')
      expect(find('#paramsName3')).to have_content('Update everywhere')

      if ENV['BROWSER'] != 'phantom'
        expect(current_url).to match(/\/bindings[?]name[=]Update%20everywhere$/)
      end
    end

    it 'should update the url and fields when bound to a param in the route' do
      visit '/'

      click_link 'Bindings'

      # phantom does not support the html5 history api
      # TODO: We could probably polyfill this in phantom
      expect(current_path).to eq('/bindings') if ENV['BROWSER'] != 'phantom'

      # Fill in one field and see if it updates the rest
      fill_in('routesName1', with: 'Routes bindings')
      expect(find('#routesName1').value).to eq('Routes bindings')
      expect(find('#routesName2').value).to eq('Routes bindings')
      expect(find('#routesName3')).to have_content('Routes bindings')

      fill_in('routesName2', with: 'bound_url')
      expect(find('#routesName1').value).to eq('bound_url')
      expect(find('#routesName2').value).to eq('bound_url')
      expect(find('#routesName3')).to have_content('bound_url')

      if ENV['BROWSER'] != 'phantom'
        expect(current_path).to eq('/bindings/bound_url')
      end
    end

    it 'should go from a url and query to params' do
      visit '/bindings/testing?name=cool'

      expect(find('#paramsName3')).to have_content('cool')
      expect(find('#routesName3')).to have_content('testing')
    end

    it 'should load the bindings page and update bindings' do
      visit '/'

      click_link 'Bindings'

      # Fill in one field and see if it updates the rest
      fill_in('textareaName1', with: 'Page bindings')
      expect(find('#textareaName1').value).to eq('Page bindings')
      expect(find('#textareaName2').value).to eq('Page bindings')
      expect(find('#textareaName3')).to have_content('Page bindings')

      fill_in('textareaName2', with: 'Update everywhere')
      expect(find('#textareaName1').value).to eq('Update everywhere')
      expect(find('#textareaName2').value).to eq('Update everywhere')
      expect(find('#textareaName3')).to have_content('Update everywhere')
    end

    it 'should update local_store bindings' do
      visit '/'

      click_link 'Bindings'

      # Fill in one field and see if it updates the rest
      fill_in('localstoreName1', with: 'Page bindings')
      expect(find('#localstoreName1').value).to eq('Page bindings')
      expect(find('#localstoreName2').value).to eq('Page bindings')
      expect(find('#localstoreName3')).to have_content('Page bindings')

      fill_in('localstoreName2', with: 'Update everywhere')
      expect(find('#localstoreName1').value).to eq('Update everywhere')
      expect(find('#localstoreName2').value).to eq('Update everywhere')
      expect(find('#localstoreName3')).to have_content('Update everywhere')
    end

    # it 'should update local_store bindings' do
    #   visit '/'
    #
    #   click_link 'Bindings'
    #
    #   within '#pageSelect1' do
    #     find("option[value='two']").click
    #   end
    #
    #   # Fill in one field and see if it updates the rest
    #   expect(find('#pageSelect1').value).to eq('two')
    #   expect(find('#pageSelect2').value).to eq('two')
    #   expect(find('#pageSelect3')).to have_content('two')
    #
    #   # Fill in one field and see if it updates the rest
    #   fill_in('pageSelect2', :with => 'three')
    #   expect(find('#pageSelect1').value).to eq('three')
    #   expect(find('#pageSelect2').value).to eq('three')
    #   expect(find('#pageSelect3')).to have_content('three')
    # end
  end

  describe 'check boxes' do
    it 'should load the bindings page and update checkboxes' do
      visit '/'

      click_link 'Bindings'

      expect(find('#pageCheck3')).to have_content('')
      # Fill in one field and see if it updates the rest
      check('pageCheck1')
      expect(find('#pageCheck1')).to be_checked
      expect(find('#pageCheck2')).to be_checked
      expect(find('#pageCheck3')).to have_content('true')

      uncheck('pageCheck1')
      expect(find('#pageCheck1')).to_not be_checked
      expect(find('#pageCheck2')).to_not be_checked
      expect(find('#pageCheck3')).to have_content('')
    end

    it 'should load the bindings page and update checkboxes bound to params' do
      visit '/'

      click_link 'Bindings'

      expect(current_path).to eq('/bindings') if ENV['BROWSER'] != 'phantom'

      expect(find('#paramsCheck3')).to have_content('')
      # Fill in one field and see if it updates the rest
      check('paramsCheck1')
      expect(find('#paramsCheck1')).to be_checked
      expect(find('#paramsCheck2')).to be_checked
      expect(find('#paramsCheck3')).to have_content('true')

      if ENV['BROWSER'] != 'phantom'
        expect(current_url).to match(/\/bindings[?]check[=]true$/)
      end

      uncheck('paramsCheck1')
      expect(find('#paramsCheck1')).to_not be_checked
      expect(find('#paramsCheck2')).to_not be_checked
      expect(find('#paramsCheck3')).to have_content('')

      if ENV['BROWSER'] != 'phantom'
        expect(current_url).to match(/\/bindings[?]check[=]false$/)
      end
    end
  end

  describe 'each binding' do
    it 'should display the last assignment even if the previous assignment resolved afterwards' do
      visit '/'

      click_link 'Bindings'

      click_link 'Show with Delay'

      sleep 0.2

      expect(find('#eachbinding li:first-child')).to have_content('901')
      expect(page).to have_selector('#eachbinding li', count: 100)
    end

    it 'should display the last assignment regardless whether the previous promise has already been resolved' do
      visit '/'

      click_link 'Bindings'

      click_link 'Show without Delay'

      sleep 0.2

      expect(find('#eachbinding li:first-child')).to have_content('1')
      expect(page).to have_selector('#eachbinding li', count: 200)
    end
  end

  describe 'if/unless binding' do
    it 'should show corret text' do
      visit '/'

      click_link 'Bindings'

      click_on 'showtrue'

      expect(find('#ifbinding')).to have_content('If _show')
      expect(find('#unlessbinding')).to have_content('Unless false _show')

      click_on 'showfalse'

      expect(find('#ifbinding')).to have_content('If false _show')
      expect(find('#unlessbinding')).to have_content('Unless _show')
    end
  end

  describe 'content escaping' do
    it 'should escape in a tripple stash' do
      visit '/'

      click_link 'Bindings'

      expect(find('#escapeContent')).to have_content('this is {{escaped}}')
    end
  end

  if ENV['BROWSER'] != 'phantom'
    describe 'input hidden and select' do
      it 'should display binding value' do
        visit '/'

        click_link 'Form'

        expect(find('body')).to have_content('Form Example')
        expect(find('#title')).to have_content('form_ready')
        expect(find('#name-display')).to have_content('Test')
        expect(find('#location-display')).to have_content('AL')
      end
    end
  end
end


text:
require 'tofu'
require 'json'
require 'mogura/card'

module Mogura
  class MoguraSession < Tofu::Session
    @@image_path = ""

    def self.image_path=(path)
      @@image_path = path
    end

    def initialize(bartender, hint='')
      super
      @base = BaseTofu.new(@@image_path, self)
      @state = StateTofu.new(self)
      start_game
    end
    attr_reader :deck

    def finish?
      @finish
    end

    def start_game
      @deck = Deck.new
      @finish = false
    end

    def as_card_name(ary)
      (ary || []).map {|card| "%03d" % card.ser}
    end

    def memory(kind)
      @deck.bag.find_all {|x| x.kind[0] == kind}
    end

    def used_memory(kind)
      @deck.used.find_all {|x| x.kind[0] == kind}
    end

    def to_hash
      h = Hash.new
      h['entrance'] = as_card_name(@deck.ary)
      h['hand'] = as_card_name(@deck.hand)
      h['current'] = as_card_name([@deck.current].compact)
      h['outlet'] = as_card_name(@deck.outlet)
      h['costarea'] = as_card_name(@deck.lost)
      [:candy, :map, :gift, :kanban, :break].each do |key|
        h[key.to_s] = as_card_name(used_memory(key) + memory(key))
      end
      [:red, :yellow, :blue].each do |key|
        h[key.to_s] = as_card_name(used_memory(key)) + [nil] + as_card_name(memory(key))
      end
      more = case it = @deck.prompt.last
      when Card
        it.ser
      else
        it
      end
      h['prompt'] = @deck.prompt.first
      h['prompt_more'] = more
      h['score'] = @deck.summary[:score]
      h
    end

    def empty
      @finish = true
    end

    def lookup_view(context)
      if context.req_path_info.include?('/api')
        @state
      else
        @base
      end
    end

    def do_GET(context)
      context.res_header('pragma', 'no-cache')
      context.res_header('cache-control', 'no-cache')
      context.res_header('expires', 'Thu, 01 Dec 1994 16:00:00 GMT')
      super(context)
    end
  end

  class StateTofu < Tofu::Tofu
    def to_html(context)
      context.res_header('content-type', 'application/json')
      body = @session.to_hash.to_json
      context.res_body(body)
      context.done
    end

    def tofu_id
      'api'
    end

    def do_it(context, params)
      return if @session.finish?
      deck = @session.deck
      kind, opt = deck.prompt
      case kind
      when :spread_else, :outlet_else, :prize
        return
      else
        begin
          deck.send(kind, opt)
        rescue Deck::EmptyError
          @session.empty
        end
      end
    end

    def do_choose(context, params)
      return if @session.finish?
      deck = @session.deck
      kind, opt = deck.prompt
      case kind
      when :spread_else, :outlet_else
        it ,= params['opt']
        num = Integer(it) rescue nil
        return unless num
        if (0...(deck.hand.size)) === num
          card = deck.hand[num]
          deck.send(kind, card)
        end
      end
    end

    def do_prize(context, params)
      return if @session.finish?
      deck = @session.deck
      kind, opt = deck.prompt
      case kind
      when :prize
        it ,= params['opt']
        num = Integer(it) rescue nil
        return unless num
        if (0...(deck.outlet.size)) === num
          card = deck.outlet[num]
          deck.prize(card)
        end
      end
    end

    def do_candy(context, params)
      return if @session.finish?
      deck = @session.deck
      deck.do_candy
    end

    def do_gift(context, params)
      return if @session.finish?
      deck = @session.deck
      deck.do_gift
    end

    def do_new(context, params)
      @session.start_game
    end
  end

  class BaseTofu < Tofu::Tofu
    set_erb(__dir__ + '/dnd.r.html')

    def initialize(image_path, *args)
      @image_path = image_path
      super(*args)
    end

    def do_new(context, params)
      @session.start_game
    end
  end
end

if __FILE__ == $0

require 'webrick'
require 'webrick/httpserver'

tofu = Tofu::Bartender.new(Mogura::MoguraSession, 'mg_8084')
s = WEBrick::HTTPServer.new(:Port => 8084)
s.mount("/", Tofu::Tofulet, tofu)

Dir['../../img/*'].each do |file_path|
  next if File.directory?(file_path)
  asset_path = file_path.sub(%r{.+/img}, "")
  s.mount(asset_path, WEBrick::HTTPServlet::FileHandler, file_path)
end

s.start

end


text:
import { defer, iif, Observable, throwError, timer, concatMap, retryWhen, tap } from 'rxjs';
import { exponentialBackoffDelay, getDelay } from '../utils';

export interface RetryBackoffConfig {
  // Initial interval. It will eventually go as high as maxInterval.
  initialInterval: number;
  // Maximum number of retry attempts.
  maxRetries?: number;
  // Maximum delay between retries.
  maxInterval?: number;
  // When set to `true` every successful emission will reset the delay and the
  // error count.
  resetOnSuccess?: boolean;
  // Conditional retry.
  shouldRetry?: (error: any) => boolean;
  backoffDelay?: (iteration: number, initialInterval: number) => number;
}

/**
 * Returns an Observable that mirrors the source Observable except with an error.
 * If the source Observable calls error, rather than propagating
 * the error call this method will resubscribe to the source Observable with
 * exponentially increasing interval and up to a maximum of count
 * re-subscriptions (if provided). Retrying can be cancelled at any point if
 * shouldRetry returns false.
 */
export function retryBackoff(
  config: number | RetryBackoffConfig
): <T>(source: Observable<T>) => Observable<T> {
  const {
    initialInterval,
    maxRetries = Infinity,
    maxInterval = Infinity,
    shouldRetry = () => true,
    resetOnSuccess = false,
    backoffDelay = exponentialBackoffDelay,
  } = typeof config === 'number' ? { initialInterval: config } : config;
  return <T>(source: Observable<T>) =>
    defer(() => {
      let index = 0;
      return source.pipe(
        retryWhen<T>(errors =>
          errors.pipe(
            concatMap(error => {
              const attempt = index++;
              return iif(
                () => attempt < maxRetries && shouldRetry(error),
                timer(
                  getDelay(backoffDelay(attempt, initialInterval), maxInterval)
                ),
                throwError(error)
              );
            })
          )
        ),
        tap(() => {
          if (resetOnSuccess) {
            index = 0;
          }
        })
      );
    });
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Samples.Hubs.Chat.ContentProviders;

namespace Microsoft.AspNet.SignalR.Samples.Hubs.Chat
{
    public class Chat : Hub
    {
        private static readonly ConcurrentDictionary<string, ChatUser> _users = new ConcurrentDictionary<string, ChatUser>(StringComparer.OrdinalIgnoreCase);
        private static readonly ConcurrentDictionary<string, HashSet<string>> _userRooms = new ConcurrentDictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
        private static readonly ConcurrentDictionary<string, ChatRoom> _rooms = new ConcurrentDictionary<string, ChatRoom>(StringComparer.OrdinalIgnoreCase);

        private static readonly List<IContentProvider> _contentProviders = new List<IContentProvider>() {
            new ImageContentProvider(),
            new YouTubeContentProvider(),
            new CollegeHumorContentProvider()
        };

        public bool Join()
        {
            // Check the user id cookie
            Cookie userIdCookie;

            if (!Context.RequestCookies.TryGetValue("userid", out userIdCookie))
            {
                return false;
            }

            ChatUser user = _users.Values.FirstOrDefault(u => u.Id == userIdCookie.Value);

            if (user != null)
            {
                // Update the users's client id mapping
                user.ConnectionId = Context.ConnectionId;

                // Set some client state
                Clients.Caller.id = user.Id;
                Clients.Caller.name = user.Name;
                Clients.Caller.hash = user.Hash;

                // Leave all rooms
                HashSet<string> rooms;
                if (_userRooms.TryGetValue(user.Name, out rooms))
                {
                    foreach (var room in rooms)
                    {
                        Clients.Group(room).leave(user);
                        ChatRoom chatRoom = _rooms[room];
                        chatRoom.Users.Remove(user.Name);
                    }
                }

                _userRooms[user.Name] = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

                // Add this user to the list of users
                Clients.Caller.addUser(user);
                return true;
            }

            return false;
        }

        public void Send(string content)
        {
            content = content.Replace("<", "<").Replace(">", ">");

            if (!TryHandleCommand(content))
            {
                string roomName = Clients.Caller.room;
                string name = Clients.Caller.name;

                EnsureUserAndRoom();

                HashSet<string> links;
                var messageText = Transform(content, out links);
                var chatMessage = new ChatMessage(name, messageText);

                _rooms[roomName].Messages.Add(chatMessage);

                Clients.Group(roomName).addMessage(chatMessage.Id, chatMessage.User, chatMessage.Text);

                if (links.Any())
                {
                    // REVIEW: is this safe to do? We're holding on to this instance
                    // when this should really be a fire and forget.
                    var contentTasks = links.Select(ExtractContent).ToArray();
                    Task.Factory.ContinueWhenAll(contentTasks, tasks =>
                    {
                        foreach (var task in tasks)
                        {
                            if (task.IsFaulted)
                            {
                                Trace.TraceError(task.Exception.GetBaseException().Message);
                                continue;
                            }

                            if (String.IsNullOrEmpty(task.Result))
                            {
                                continue;
                            }

                            // Try to get content from each url we're resolved in the query
                            string extractedContent = "
" + task.Result + "
";

                            // If we did get something, update the message and notify all clients
                            chatMessage.Text += extractedContent;

                            Clients.Group(roomName).addMessageContent(chatMessage.Id, extractedContent);
                        }
                    });
                }
            }
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            ChatUser user = _users.Values.FirstOrDefault(u => u.ConnectionId == Context.ConnectionId);
            if (user != null)
            {
                ChatUser ignoredUser;
                _users.TryRemove(user.Name, out ignoredUser);

                // Leave all rooms
                HashSet<string> rooms;
                if (_userRooms.TryGetValue(user.Name, out rooms))
                {
                    foreach (var room in rooms)
                    {
                        Clients.Group(room).leave(user);
                        ChatRoom chatRoom = _rooms[room];
                        chatRoom.Users.Remove(user.Name);
                    }
                }

                HashSet<string> ignoredRoom;
                _userRooms.TryRemove(user.Name, out ignoredRoom);
            }

            return null;
        }

        public IEnumerable<ChatUser> GetUsers()
        {
            string room = Clients.Caller.room;

            if (String.IsNullOrEmpty(room))
            {
                return Enumerable.Empty<ChatUser>();
            }

            return from name in _rooms[room].Users
                   select _users[name];
        }

        private string GetMD5Hash(string name)
        {
            return String.Join("", MD5.Create()
                         .ComputeHash(Encoding.Default.GetBytes(name))
                         .Select(b => b.ToString("x2")));
        }

        private bool TryHandleCommand(string message)
        {
            string room = Clients.Caller.room;
            string name = Clients.Caller.name;

            message = message.Trim();
            if (message.StartsWith("/"))
            {
                string[] parts = message.Substring(1).Split(' ');
                string commandName = parts[0];

                if (commandName.Equals("nick", StringComparison.OrdinalIgnoreCase))
                {
                    string newUserName = String.Join(" ", parts.Skip(1));

                    if (String.IsNullOrEmpty(newUserName))
                    {
                        throw new InvalidOperationException("No username specified!");
                    }

                    if (newUserName.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new InvalidOperationException("That's already your username...");
                    }

                    if (!_users.ContainsKey(newUserName))
                    {
                        if (String.IsNullOrEmpty(name) || !_users.ContainsKey(name))
                        {
                            AddUser(newUserName);
                        }
                        else
                        {
                            var oldUser = _users[name];
                            var newUser = new ChatUser
                            {
                                Name = newUserName,
                                Hash = GetMD5Hash(newUserName),
                                Id = oldUser.Id,
                                ConnectionId = oldUser.ConnectionId
                            };

                            _users[newUserName] = newUser;
                            _userRooms[newUserName] = new HashSet<string>(_userRooms[name]);

                            if (_userRooms[name].Any())
                            {
                                foreach (var r in _userRooms[name])
                                {
                                    _rooms[r].Users.Remove(name);
                                    _rooms[r].Users.Add(newUserName);
                                    Clients.Group(r).changeUserName(oldUser, newUser);
                                }
                            }
                            HashSet<string> ignoredRoom;
                            ChatUser ignoredUser;
                            _userRooms.TryRemove(name, out ignoredRoom);
                            _users.TryRemove(name, out ignoredUser);

                            Clients.Caller.hash = newUser.Hash;
                            Clients.Caller.name = newUser.Name;

                            Clients.Caller.changeUserName(oldUser, newUser);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(String.Format("Username '{0}' is already taken!", newUserName));
                    }

                    return true;
                }
                else
                {
                    EnsureUser();
                    if (commandName.Equals("rooms", StringComparison.OrdinalIgnoreCase))
                    {
                        var rooms = _rooms.Select(r => new
                        {
                            Name = r.Key,
                            Count = r.Value.Users.Count
                        });

                        Clients.Caller.showRooms(rooms);

                        return true;
                    }
                    else if (commandName.Equals("join", StringComparison.OrdinalIgnoreCase))
                    {
                        if (parts.Length == 1)
                        {
                            throw new InvalidOperationException("Join which room?");
                        }

                        // Only support one room at a time for now

                        string newRoom = parts[1];
                        ChatRoom chatRoom;
                        // Create the room if it doesn't exist
                        if (!_rooms.TryGetValue(newRoom, out chatRoom))
                        {
                            chatRoom = new ChatRoom();
                            _rooms.TryAdd(newRoom, chatRoom);
                        }

                        // Remove the old room
                        if (!String.IsNullOrEmpty(room))
                        {
                            _userRooms[name].Remove(room);
                            _rooms[room].Users.Remove(name);

                            Clients.Group(room).leave(_users[name]);
                            Groups.Remove(Context.ConnectionId, room);
                        }

                        _userRooms[name].Add(newRoom);
                        if (!chatRoom.Users.Add(name))
                        {
                            throw new InvalidOperationException("You're already in that room!");
                        }

                        Clients.Group(newRoom).addUser(_users[name]);

                        // Set the room on the caller
                        Clients.Caller.room = newRoom;

                        Groups.Add(Context.ConnectionId, newRoom);

                        Clients.Caller.refreshRoom(newRoom);

                        return true;
                    }
                    else if (commandName.Equals("msg", StringComparison.OrdinalIgnoreCase))
                    {
                        if (_users.Count == 1)
                        {
                            throw new InvalidOperationException("You're the only person in here...");
                        }

                        if (parts.Length < 2)
                        {
                            throw new InvalidOperationException("Who are you trying send a private message to?");
                        }

                        string to = parts[1];
                        if (to.Equals(name, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new InvalidOperationException("You can't private message yourself!");
                        }

                        if (!_users.ContainsKey(to))
                        {
                            throw new InvalidOperationException(String.Format("Couldn't find any user named '{0}'.", to));
                        }

                        string messageText = String.Join(" ", parts.Skip(2)).Trim();

                        if (String.IsNullOrEmpty(messageText))
                        {
                            throw new InvalidOperationException(String.Format("What did you want to say to '{0}'.", to));
                        }

                        string recipientId = _users[to].ConnectionId;
                        // Send a message to the sender and the sendee
                        Clients.Group(recipientId).sendPrivateMessage(name, to, messageText);
                        Clients.Caller.sendPrivateMessage(name, to, messageText);

                        return true;
                    }
                    else
                    {
                        EnsureUserAndRoom();
                        if (commandName.Equals("me", StringComparison.OrdinalIgnoreCase))
                        {
                            if (parts.Length == 1)
                            {
                                throw new InvalidProgramException("You what?");
                            }
                            var content = String.Join(" ", parts.Skip(1));

                            Clients.Group(room).sendMeMessage(name, content);
                            return true;
                        }
                        else if (commandName.Equals("leave", StringComparison.OrdinalIgnoreCase))
                        {
                            ChatRoom chatRoom;
                            if (_rooms.TryGetValue(room, out chatRoom))
                            {
                                chatRoom.Users.Remove(name);
                                _userRooms[name].Remove(room);

                                Clients.Group(room).leave(_users[name]);
                            }

                            Groups.Remove(Context.ConnectionId, room);

                            Clients.Caller.room = null;

                            return true;
                        }

                        throw new InvalidOperationException(String.Format("'{0}' is not a valid command.", parts[0]));
                    }
                }
            }
            return false;
        }

        private ChatUser AddUser(string newUserName)
        {
            var user = new ChatUser(newUserName, GetMD5Hash(newUserName));
            user.ConnectionId = Context.ConnectionId;
            _users[newUserName] = user;
            _userRooms[newUserName] = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            Clients.Caller.name = user.Name;
            Clients.Caller.hash = user.Hash;
            Clients.Caller.id = user.Id;

            Clients.Caller.addUser(user);

            return user;
        }

        private void EnsureUserAndRoom()
        {
            EnsureUser();

            // TODO: Restore when groups work
            string room = Clients.Caller.room;
            string name = Clients.Caller.name;

            if (String.IsNullOrEmpty(room) || !_rooms.ContainsKey(room))
            {
                throw new InvalidOperationException("Use '/join room' to join a room.");
            }

            HashSet<string> rooms;
            if (!_userRooms.TryGetValue(name, out rooms) || !rooms.Contains(room))
            {
                throw new InvalidOperationException(String.Format("You're not in '{0}'. Use '/join {0}' to join it.", room));
            }
        }

        private void EnsureUser()
        {
            string name = Clients.Caller.name;
            if (String.IsNullOrEmpty(name) || !_users.ContainsKey(name))
            {
                throw new InvalidOperationException("You don't have a name. Pick a name using '/nick nickname'.");
            }
        }

        private string Transform(string message, out HashSet<string> extractedUrls)
        {
            const string urlPattern = @"((https?|ftp)://|www\.)[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";

            var urls = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            message = Regex.Replace(message, urlPattern, m =>
            {
                string httpPortion = String.Empty;
                if (!m.Value.Contains("://"))
                {
                    httpPortion = "http://";
                }

                string url = httpPortion + m.Value;

                urls.Add(url);

                return String.Format(CultureInfo.InvariantCulture,
                                     "{1}",
                                     url, m.Value);
            });

            extractedUrls = urls;
            return message;
        }

        private Task<string> ExtractContent(string url)
        {
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            var requestTask = Task.Factory.FromAsync((cb, state) => request.BeginGetResponse(cb, state), ar => request.EndGetResponse(ar), null);
            return requestTask.ContinueWith(task => ExtractContent((HttpWebResponse)task.Result));
        }

        private string ExtractContent(HttpWebResponse response)
        {
            return _contentProviders.Select(c => c.GetContent(response))
                                    .FirstOrDefault(content => content != null);
        }

        [Serializable]
        public class ChatMessage
        {
            public string Id { get; private set; }
            public string User { get; set; }
            public string Text { get; set; }
            public ChatMessage(string user, string text)
            {
                User = user;
                Text = text;
                Id = Guid.NewGuid().ToString("d");
            }
        }

        [Serializable]
        public class ChatUser
        {
            public string ConnectionId { get; set; }
            public string Id { get; set; }
            public string Name { get; set; }
            public string Hash { get; set; }

            public ChatUser()
            {
            }

            public ChatUser(string name, string hash)
            {
                Name = name;
                Hash = hash;
                Id = Guid.NewGuid().ToString("d");
            }
        }

        public class ChatRoom
        {
            public List<ChatMessage> Messages { get; set; }
            public HashSet<string> Users { get; set; }

            public ChatRoom()
            {
                Messages = new List<ChatMessage>();
                Users = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Giosh94mhz\GeonamesBundle\Entity\Language" table="language">
    <id name="iso639p3" type="string" column="iso_639_3" length="3">
      <options><option name="fixed">true</option></options>
    </id>
    <field name="iso639p2" type="string" column="iso_639_2" length="3" nullable="true"/>
    <field name="iso639p1" type="string" column="iso_639_1" length="2" nullable="true">
      <options><option name="fixed">true</option></options>
    </field>
    <field name="name" type="string" column="name" length="200" nullable="false"/>
  </entity>
</doctrine-mapping>


text:
var spawn = require('child_process').spawn
	, path = require('path')
	, testDir = path.resolve(__dirname, '../test')
	, input = path.resolve(testDir, 'tests.cs')
	, output = path.resolve(testDir, 'Edge.Tests.dll')
	, buildParameters = ['-target:library', '/debug', '-out:' + output, input]
	, winBuild = []
	, monoBuild = ['-sdk:4.5']
	, mocha = path.resolve(__dirname, '../node_modules/mocha/bin/mocha')
	;

if(process.platform === 'win32') {
	spawn('csc', winBuild.concat(buildParameters), { stdio: 'inherit' })
		.on('close', runOnSuccess);
} else {
	spawn('dmcs', monoBuild.concat(buildParameters), { stdio: 'inherit' })
		.on('close', runOnSuccess);
}

function runOnSuccess(code, signal) {
	if(code === 0) {
		spawn('node', [mocha, testDir, '-R', 'spec'], { stdio: 'inherit' })
			.on('error', function(err) { console.log(err); });
	}
}


text:
package com.jhr;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * author: jinhuari
 * date: 2017/10/23
 * description: 测试java8的lambda
 */
public class Java8Test {

    @Test
    public void test() {
        // java 8 runnable
        new Thread(() -> System.out.println("java 8 runnable")).start();
        // java8 foreach
        List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
        features.forEach(n -> System.out.println(n));
        // java8 list
        //features.forEach(System.out::println);
        //
        testPredicate();

        // test filter
        testFilter();
        // test performance
        testPerformance();
    }

    private void testPerformance() {
        long a = System.currentTimeMillis();
        System.out.println("prepare data begin====");
        List<Integer> src = new ArrayList<>();
        for (int i = 0; i < 2000000; i++) {
            src.add(i);
        }
        long b = System.currentTimeMillis();
        System.out.println("prepare data end:" + (b - a));
        runForeach(src);
        runFor(src);
    }

    private void runFor(List<Integer> src) {
        System.out.println("run lambda begin====");
        long a = System.currentTimeMillis();
        double result = 0L;
        result = src.stream().mapToInt(t -> t).sum();
        System.out.println("result==" + result);
        long b = System.currentTimeMillis();
        System.out.println("run lambda end ,use " + (b - a));

    }

    private void runForeach(List<Integer> src) {
        System.out.println("run foreach begin====");
        long a = System.currentTimeMillis();
        double result = 0L;
        for (int i : src) {
            result += i;
            //System.out.print(i);
        }
        System.out.println("result==" + result);
        long b = System.currentTimeMillis();
        System.out.println("run foreach end ,use " + (b - a));
    }

    private void testFilter() {
        System.out.println("test filter ====");
        List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
        List<String> now = languages.stream().filter(v -> v.startsWith("J")).collect(Collectors.toList());
        now.forEach(v -> System.out.println(v));
    }

    private void testPredicate() {
        List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");

        System.out.println("Languages which starts with J :");
        //filter(languages, (str)->str.startsWith("J"));

        System.out.println("Languages which ends with a ");
        //filter(languages, (str)->str.endsWith("a"));

        System.out.println("Print all languages :");
        filter(languages, str -> true);

        System.out.println("Print no language : ");
        filter(languages, str -> false);

        System.out.println("Print language whose length greater than 4:");
        // filter(languages, (str)->str.length() > 4);
    }

    public void filter(List<String> names, Predicate condition) {
        for (String name : names) {
            if (condition.test(name)) {
                System.out.println(name + " ");
            }
        }
    }

    @Test
    public void testOptional() {
        Optional<User> user = null;
        String name = getUserName(user);
        System.out.println(name);
    }

    public String getUserName(Optional<User> user) {
        return user.map(user1 -> user1.getId())
                .map(id -> id.toUpperCase())
                .orElse(null);
    }

    class User {
        private String userName;
        private String id;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Kreta\TaskManager\Domain\Model\Project;

class ProjectNameEmptyException extends \Exception
{
    public function __construct()
    {
        parent::__construct();
        $this->message = 'Project name must not be empty';
    }
}


text:
title: Holidays
page_title: Holidays - RadScheduler
description: Telerik RadScheduler supports loading holidays from a .hol file.
slug: winforms/scheduler/holidays
tags: scheduler
published: True
position: 10
---

# Holidays

Similar to Outlook, since **R2 2018** **RadScheduler** provides holidays support. It allows loading holidays for different countries from a .hol file or adding them programmatically.

>caption Figure1: Holidays

![scheduler-holidays 001](images/scheduler-holidays001.png)

The RadScheduler.**Holidays** collection stores all special days. It is of type **SchedulerHolidays** which is actually **IEnumerable<Holiday>**. For each **Holiday** object you can specify **Date**, **Location** and **HolidayName**.

## SchedulerHolidays' API

|Method|Description|
|----|----|
|**IsHoliday(DateTime dateTime)**|Check if the specific date is contained in the Holidays collection.|
|**GetHolidays(DateTime dateTime)**|Return all holidays for the specific date (if any).|
|**AddHoliday(Holiday holiday, bool createAppointment)**|Add holiday to the Holidays collection. If 'createAppointment' is true this will create an all day appointment.|
|**AddHolidays(IEnumerable<Holiday> holidays, bool createAppointment)**|Add a collection of holidays to the Holidays collection.If 'createAppointment' is true this will create an all day appointment.|
|**Clear**| Clear the Holidays collections. This does not affect already created appointments.|
|**GetAllLocations(string fileName)**| Return all locations from the file.|
|**GetAllLocations(Stream stream)**| Get all location from the stream.|
|**ReadHolidays(string fileName, bool createAppointment)**|Read the holidays information from the file and create Holidays objects in the holidays collection. Optionally can create also all day appointments for the holidays.|
|**ReadHolidays(string fileName, bool createAppointment, IEnumerable<string> locations)**|Read the holidays information from the file and create Holidays objects in the holidays collection only for holidays in the specific locations. Optionally can create also all day appointments for the holidays.|
|**ReadHolidays(Stream stream, bool createAppointment)**|Read the holidays information from the stream and create Holidays objects in the holidays collection. Optionally can create also and all day appointments for the holidays.|
|**ReadHolidays(Stream stream, bool createAppointment, IEnumerable<string> locations)**|Read the holidays information and create Holidays objects in the holidays collection only for holidays in the specific locations. Optionally can create also all day appointments for the holidays.|

## Add Holidays Programmatically

The following code snippet demonstrates how to add a holiday. The passed Boolean parameter to the **AddHoliday** method indicates whether an all-day appointment will be created for the specific day or not.

#### Add a holiday programmatically

{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=AddHolidayProgrammatically}}
{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=AddHolidayProgrammatically}}

````C#
Holiday holiday = new Holiday();
holiday.Date = new DateTime(2018, 5, 24);
holiday.HolidayName = "Saints Cyril and Methodius Day";
holiday.Location = "Bulgaria";
bool generateAppointment = true;
this.radScheduler1.Holidays.AddHoliday(holiday, generateAppointment);

````
````VB.NET
Dim holiday As Holiday = New Holiday()
holiday.Date = New DateTime(2018, 5, 24)
holiday.HolidayName = "Saints Cyril and Methodius Day"
holiday.Location = "Bulgaria"
Dim generateAppointment As Boolean = True
Me.radScheduler1.Holidays.AddHoliday(holiday, generateAppointment)

````

{{endregion}}

## Load Holidays from a File

{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=LoadFile}}
{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=LoadFile}}

````C#

string fileName = @".hol file location";
bool createAppointment = true;
this.radScheduler1.Holidays.ReadHolidays(fileName, createAppointment);

````
````VB.NET
Dim fileName As String = ".hol file location"
Dim createAppointment As Boolean = True
Me.radScheduler1.Holidays.ReadHolidays(fileName, createAppointment)

````

{{endregion}}

## Load Holidays from a Stream

{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=LoadStream}}
{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=LoadStream}}

````C#

string fileToRead = @".hol file location";
bool generateAppointment = true;
using (System.IO.Stream fileStream = File.OpenRead(fileToRead))
{
    this.radScheduler1.Holidays.ReadHolidays(fileStream, generateAppointment);
}

````
````VB.NET
Dim fileToRead As String = ".hol file location"
Dim generateAppointment As Boolean = True
Using fileStream As System.IO.Stream = File.OpenRead(fileToRead)
    Me.radScheduler1.Holidays.ReadHolidays(fileStream, generateAppointment)
End Using

````

{{endregion}}

## Formatting Holidays

**RadScheduler** allows you to control whether to create all-day appointments for the holidays or not by passing a boolean argument to the **AddHoliday** method. If no appointments are created, there isn't any indication in the scheduler view when a certain day is a holiday. A common case is formatting the holidays' cells in a different color for a better indication. For this purpose, it is necessary to handle the RadScheduler.[CellFormatting]({%slug winforms/scheduler/appearance/formatting-cells%}) event and introduce the desired style for holiday cells. The following example demonstrates how to color in *LightGreen* all holidays in Bulgaria and in *Orange* all the rest of the holidays.

>caption Figure2: Holidays Formatting

![scheduler-holidays 002](images/scheduler-holidays002.png)

#### Formatting the holidays

{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=HolidaysFormatting}}
{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=HolidaysFormatting}}

````C#
private void radScheduler1_CellFormatting(object sender, SchedulerCellEventArgs e)
{
    if (!(e.CellElement is SchedulerHeaderCellElement))
    {
        if (this.radScheduler1.Holidays.IsHoliday(e.CellElement.Date))
        {
            string s = string.Empty;
            foreach (var item in radScheduler1.Holidays.GetHolidays(e.CellElement.Date).OrderBy(ae => ae.HolidayName))
            {
                if (!s.Contains(item.HolidayName))
                    s += item.HolidayName + Environment.NewLine;
            }
            e.CellElement.DrawText = true;
            e.CellElement.Text = s.ToString();
            e.CellElement.TextWrap = true;
            e.CellElement.TextAlignment = ContentAlignment.BottomCenter;
            Padding padding = e.CellElement.Padding;
            if (this.radScheduler1.ActiveViewType == SchedulerViewType.Month)
                padding.Bottom = 22;
            e.CellElement.Padding = padding;
            if (radScheduler1.Holidays.GetHolidays(e.CellElement.Date).Where(l => l.Location == "Bulgaria").Any())
                e.CellElement.BackColor = Color.LightGreen;
            else
                e.CellElement.BackColor = Color.Orange;
        }
        else
        {
            e.CellElement.DrawText = false;
            e.CellElement.ResetValue(RadItem.BackColorProperty, ValueResetFlags.Local);
        }
    }
}

````
````VB.NET
Private Sub radScheduler1_CellFormatting(ByVal sender As Object, ByVal e As SchedulerCellEventArgs)
    If Not (TypeOf e.CellElement Is SchedulerHeaderCellElement) Then
        If Me.radScheduler1.Holidays.IsHoliday(e.CellElement.Date) Then
            Dim s As String = String.Empty
            For Each item In radScheduler1.Holidays.GetHolidays(e.CellElement.Date).OrderBy(Function(ae) ae.HolidayName)
                If Not s.Contains(item.HolidayName) Then s += item.HolidayName + Environment.NewLine
            Next
            e.CellElement.DrawText = True
            e.CellElement.Text = s.ToString()
            e.CellElement.TextWrap = True
            e.CellElement.TextAlignment = ContentAlignment.BottomCenter
            Dim padding As Padding = e.CellElement.Padding
            If Me.radScheduler1.ActiveViewType = SchedulerViewType.Month Then padding.Bottom = 22
            e.CellElement.Padding = padding
            If radScheduler1.Holidays.GetHolidays(e.CellElement.Date).Where(Function(l) l.Location = "Bulgaria").Any() Then e.CellElement.BackColor = Color.LightGreen Else e.CellElement.BackColor = Color.Orange
        Else
            e.CellElement.DrawText = False
            e.CellElement.ResetValue(RadItem.BackColorProperty, ValueResetFlags.Local)
        End If
    End If
End Sub

````

{{endregion}}


text:
<?php

/** Class to hold a reference to another object in the project.
 * @package phing.types
 */
class Reference {

    protected $refid;

    function __construct($id = null) {
        if ($id !== null) {
            $this->setRefId($id);
        }
    }

    function setRefId($id) {
        $this->refid = (string) $id;
    }

    function getRefId() {
        return $this->refid;
    }

    /** returns reference to object in references container of project */
    function getReferencedObject($project) {
        if ($this->refid === null) {
            throw new BuildException("No reference specified");
        }
        $refs = $project->getReferences();
        $o = @$refs[$this->refid];
        if (!is_object($o)) {
            throw new BuildException("Reference {$this->refid} not found.");
        }
        return $o;
    }
}


text:
import {BaseException} from 'angular2/src/facade/lang';
import {ViewRef} from './view_ref';
import {RenderViewRef, RenderElementRef, Renderer} from 'angular2/src/render/api';

/**
 * @exportedAs angular2/view
 */
export class ElementRef implements RenderElementRef {
  constructor(public parentView: ViewRef, public boundElementIndex: number,
              private _renderer: Renderer) {}

  get renderView(): RenderViewRef { return this.parentView.render; }
  // TODO(tbosch): remove this once Typescript supports declaring interfaces
  // that contain getters
  set renderView(viewRef: RenderViewRef) { throw new BaseException('Abstract setter'); }

  /**
   * Exposes the underlying native element.
   * Attention: This won't work in a webworker scenario!
   */
  get nativeElement(): any { return this._renderer.getNativeElementSync(this); }
}


text:
"""
Legacy module for PKCS#1 v1.5 signatures.

:undocumented: __package__
"""

import types

from Cryptodome.Signature import pkcs1_15

def _pycrypto_verify(self, hash_object, signature):
    try:
        self._verify(hash_object, signature)
    except ValueError, TypeError:
        return False
    return True

def new(rsa_key):
    pkcs1 = pkcs1_15.new(rsa_key)
    pkcs1._verify = pkcs1.verify
    pkcs1.verify = types.MethodType(_pycrypto_verify, pkcs1)
    return pkcs1


text:
/*
 * This file is part of jStar Eclipse Plug-in.
 *
 * jStar Eclipse Plug-in is distributed under a BSD license,  see, LICENSE
 */
package com.jstar.eclipse.processing;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.StandardLocation;

import com.jstar.eclipse.processing.annotations.AllAnnotations;
import com.jstar.eclipse.processing.annotations.FileAnnotations;
import com.jstar.eclipse.processing.annotations.objects.ImportObject;
import com.sun.source.tree.Tree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;

@SuppressWarnings("restriction")
@SupportedAnnotationTypes("com.jstar.eclipse.annotations.*")
@SupportedSourceVersion(SourceVersion.RELEASE_6)

public class SpecAnnotationProcessor extends AbstractProcessor {

	@Override
	public boolean process(Set<? extends TypeElement> annotations,
			RoundEnvironment roundEnv) {

		Messager messager = processingEnv.getMessager();

		AllAnnotations allAnnotations = new AllAnnotations();

		for (TypeElement typeElement : annotations){
			for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
				processAnnotation(element, typeElement, allAnnotations, messager);
			}
        }

		if (!allAnnotations.isEmpty()) {
			try {
				generateSpec(processingEnv.getFiler(), allAnnotations);
				generateImports(processingEnv.getFiler(), allAnnotations);
			}
			catch(Exception exc) {
				messager.printMessage(Diagnostic.Kind.ERROR, exc.getMessage());
			}
		}

        return true;
	}

	private void generateSpec(Filer filer, AllAnnotations allAnnotations) throws IOException {
		for (final FileAnnotations fileAnnotations : allAnnotations.getFileAnnotations()) {
		   FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",  fileAnnotations.getBaseSourceFileName() + ".spec");

		   Writer writer = fileObject.openWriter();
		   AnnotationGeneratorService.getInstance().generateFile(fileAnnotations, writer);

		   writer.flush();
		   writer.close();
		}

	}

	private void generateImports(final Filer filer, final AllAnnotations allAnnotations) throws IOException {
		for (final FileAnnotations fileAnnotations : allAnnotations.getFileAnnotations()) {
		   final List<ImportObject> importObjects = fileAnnotations.getImportAnnotations();
		   final FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",  fileAnnotations.getBaseSourceFileName() + ".imports");
		   final Writer writer = fileObject.openWriter();

		   for (final ImportObject object : importObjects) {
			   object.writeImports(writer);
		   }

		   writer.flush();
		   writer.close();
		}
	}

	private void processAnnotation(Element element, TypeElement typeElement,
	    AllAnnotations allAnnotations, Messager messager) {

		List<? extends AnnotationMirror> annotations = element.getAnnotationMirrors();

		for (AnnotationMirror mirror : annotations) {
			final String mirrorAnnotationType = mirror.getAnnotationType().toString();

			if (typeElement.toString().equals(mirrorAnnotationType)) {
				Trees instance = Trees.instance(processingEnv);
				SourcePositions sourcePositions = instance.getSourcePositions();

				TreePath path = instance.getPath(element, mirror);

				CompilationUnitTree cu = path.getCompilationUnit();
				Tree tree =  path.getLeaf();

				Element elementClass;

				if (element.getKind().isClass() || element.getKind().isInterface()) {
					elementClass = element;
				}
				else {
					elementClass = element.getEnclosingElement();
				}

				if (!(elementClass instanceof TypeElement)) {
					throw new RuntimeException("Unknown kind of element. Currently only class and interface are supported.");
				}

				int nameLenght = mirror.getAnnotationType().asElement().getSimpleName().length() + 1;

				allAnnotations.addAnnotation(cu.getSourceFile().toUri().getPath(), (TypeElement)elementClass, element, mirror, sourcePositions.getStartPosition(cu, tree) + 1, sourcePositions.getEndPosition(cu, tree) + nameLenght);
			}
		}
	}

}


text:
<?php

namespace Enqueue\Redis\Tests\Spec;

use Enqueue\Test\RedisExtension;
use Interop\Queue\Spec\ProducerSpec;

/**
 * @group functional
 * @group Redis
 */
class RedisProducerTest extends ProducerSpec
{
    use RedisExtension;

    /**
     * {@inheritdoc}
     */
    protected function createProducer()
    {
        return $this->buildPhpRedisContext()->createProducer();
    }
}


text:
#include <storm/x11/xcb_connection.h>

#include <storm/exception.h>
#include <storm/x11/xcb_pointer.h>

namespace storm {

XcbConnection::XcbConnection() {
    int screenIndex = 0;

    _connection = xcb_connect( nullptr, &screenIndex );

    xcb_screen_iterator_t iterator =
        xcb_setup_roots_iterator( xcb_get_setup(_connection) );

    for( int screen = 0; screen < screenIndex; ++screen ) {
        if( iterator.rem ) {
            xcb_screen_next( &iterator );
        }
    }

    _screen = iterator.data;
}

XcbConnection::~XcbConnection() {
    xcb_disconnect( _connection );
}

XcbConnection::XcbConnection( XcbConnection &&connection ) {
    *this = std::move( connection );
}

XcbConnection& XcbConnection::operator = ( XcbConnection &&connection ) {
    this->~XcbConnection();

    _connection = connection._connection;
    _screen = connection._screen;

    connection._connection = nullptr;
    connection._screen = nullptr;

    return *this;
}

XcbConnection::operator xcb_connection_t* () const {
    return _connection;
}

xcb_screen_t* XcbConnection::getDefaultScreen() const {
    return _screen;
}

xcb_atom_t XcbConnection::getAtom( std::string_view id ) const {
    const xcb_intern_atom_cookie_t request = xcb_intern_atom_unchecked(
        _connection, /* only_if_exists */ 0, id.size(), id.data() );

    const XcbPointer<xcb_intern_atom_reply_t> reply =
        xcb_intern_atom_reply( _connection, request, nullptr );

    return reply ? reply->atom : XCB_ATOM_NONE;
}

XcbConnection XcbConnection::create() {
    XcbConnection connection;

    if( xcb_connection_has_error(connection._connection) ) {
        throw SystemRequirementsNotMet() << "An X server is unavailable";
    }

    return connection;
}

}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { EditorLoaderRenderer } from './EditorLoaderRenderer';
import { Editor } from './Editor';

const code = '<button>MyAwesomeCode</button>';
const newCode = '<button>MyNewAwesomeCode</button>';
const options = {
	context: {
		config: {
			showCode: false,
			highlightTheme: 'base16-light',
			editorConfig: {
				lineWrapping: true,
				mode: 'js',
			},
		},
	},
	childContextTypes: {
		config: PropTypes.object.isRequired,
	},
};

describe('EditorLoaderRenderer', () => {
	it('should renderer should render loader', () => {
		const actual = shallow(<EditorLoaderRenderer classes={{}} />);

		expect(actual).toMatchSnapshot();
	});
});

describe('Editor', () => {
	it('should renderer and editor', () => {
		const actual = shallow(
			<Editor classes={{}} code={code} editorConfig={{ readOnly: true, mode: 'text/html' }} />,
			options
		);

		expect(actual).toMatchSnapshot();
	});

	it('should update code with debounce', done => {
		const onChange = jest.fn();
		const actual = mount(<Editor classes={{}} code={code} onChange={onChange} />, options);

		expect(actual.text()).toMatch(code);

		// Set new value by calling a method on the CodeMirror instance
		actual
			.find('div')
			.getDOMNode()
			.querySelector('.CodeMirror')
			.CodeMirror.setValue(newCode);

		setTimeout(() => {
			expect(onChange).toBeCalledWith(newCode);
			done();
		}, 13);
	});

	it('should not update if not read only', () => {
		const actual = shallow(<Editor classes={{}} code={code} />, options);

		const shouldUpdate = actual.instance().shouldComponentUpdate({ code: newCode });
		expect(shouldUpdate).toBe(false);
	});

	it('should update if read only and code has changed', () => {
		const actual = shallow(
			<Editor classes={{}} code={code} editorConfig={{ readOnly: true }} />,
			options
		);

		const shouldUpdate = actual
			.instance()
			.shouldComponentUpdate({ code: newCode, editorConfig: { readOnly: true } });
		expect(shouldUpdate).toBe(true);
	});
});


text:
package com.nicaiya.canvaslayout;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.view.ViewGroup.LayoutParams;

public interface UIElement {

    public boolean swapHost(UIElementHost host);

    public boolean isAttachedToHost();

    public int getId();

    public int getMeasuredWidth();

    public int getMeasuredHeight();

    public int getPaddingLeft();

    public int getPaddingTop();

    public int getPaddingRight();

    public int getPaddingBottom();

    public void setPadding(int left, int top, int right, int bottom);

    public int getLeft();

    public int getTop();

    public int getRight();

    public int getBottom();

    public int getWidth();

    public int getHeight();

    public void setLayoutParams(LayoutParams lp);

    public LayoutParams getLayoutParams();

    public void onFinishInflate();

    public void measure(int widthMeasureSpec, int heightMeasureSpec);

    public void layout(int left, int top, int right, int bottom);

    public void draw(Canvas canvas);

    public void drawableStateChanged();

    public Context getContext();

    public Resources getResources();

    public void requestLayout();

    public void invalidate();

    public int getVisibility();

    public void setVisibility(int visibility);
}


text:
package uk.ac.ebi.atlas.search;

import org.apache.commons.lang3.StringUtils;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class SearchDescription {
    protected SearchDescription() {
        throw new UnsupportedOperationException();
    }

    public static String get(SemanticQuery geneQuery) {
        return get(geneQuery, SemanticQuery.create(), "");
    }

    public static String get(SemanticQuery geneQuery, SemanticQuery conditionQuery, String species) {
        if (geneQuery.isEmpty() && conditionQuery.isEmpty()) {
            return "default query";
        }

        StringBuilder stringBuilder = new StringBuilder();

        if (geneQuery.isNotEmpty()) {
            String geneQueryString = geneQuery.description();

            if (geneQuery.size() > 1 && conditionQuery.isNotEmpty()) {
                stringBuilder.append("(").append(geneQueryString).append(")");
            } else {
                stringBuilder.append(geneQueryString);
            }
        }

        if (geneQuery.isNotEmpty() && conditionQuery.isNotEmpty()) {
            stringBuilder.append(" AND ");
        }

        if (conditionQuery.isNotEmpty()) {
            String conditionQueryString = conditionQuery.description();

            if (conditionQuery.size() > 1 && geneQuery.isNotEmpty()) {
                stringBuilder.append("(").append(conditionQueryString).append(")");
            } else {
                stringBuilder.append(conditionQueryString);
            }
        }

        if ((geneQuery.isNotEmpty() || conditionQuery.isNotEmpty()) && isNotBlank(species)) {
            stringBuilder.append(" AND ");
        }

        if (isNotBlank(species)) {
            stringBuilder.append(StringUtils.capitalize(species));
        }

        return stringBuilder.toString();
    }
}


text:
@interface RuntimeViewController : GLKViewController

@property (nonatomic, strong) EAGLContext *context;
@property (nonatomic, readonly) GLKView *glView;

@end


text:
import { combineReducers } from 'redux'
import { default as user } from '../account/reducers/LoginReducer'
import { default as browse } from '../browse/reducers/Reducer'
import { default as list } from '../list/reducers/GroceryListReducer'
import { default as recipe } from '../recipe/reducers/Reducer'
import { default as recipeForm } from '../recipe_form/reducers/Reducer'

const reducer = combineReducers({
  list,
  user,
  browse,
  recipe,
  recipeForm,
});

export default reducer


text:
package rpkt

import (
	"time"

	"github.com/scionproto/scion/go/border/rcmn"
	"github.com/scionproto/scion/go/border/rctx"
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/assert"
	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/lib/l4"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/overlay"
	"github.com/scionproto/scion/go/lib/spkt"
)

// RtrPktFromScnPkt creates an RtrPkt from an spkt.ScnPkt.
func RtrPktFromScnPkt(sp *spkt.ScnPkt, ctx *rctx.Ctx) (*RtrPkt, error) {
	rp := NewRtrPkt()
	rp.Ctx = ctx
	totalLen := sp.TotalLen()
	hdrLen := sp.HdrLen() / common.LineLen
	rp.TimeIn = time.Now()
	rp.Id = log.RandId(4)
	rp.Logger = log.New("rpkt", rp.Id)
	rp.DirFrom = rcmn.DirSelf
	// Fill in common header.
	rp.CmnHdr.DstType = sp.DstHost.Type()
	rp.CmnHdr.SrcType = sp.SrcHost.Type()
	rp.CmnHdr.TotalLen = uint16(totalLen) // Updated later as necessary.
	rp.CmnHdr.HdrLen = uint8(hdrLen)
	rp.CmnHdr.CurrInfoF = 0           // Updated later as necessary.
	rp.CmnHdr.CurrHopF = 0            // Updated later as necessary.
	rp.CmnHdr.NextHdr = common.L4None // Updated later as necessary.
	// Fill in address header and indexes.
	rp.idxs.dstIA = spkt.CmnHdrLen
	rp.dstIA = sp.DstIA
	rp.idxs.srcIA = rp.idxs.dstIA + addr.IABytes
	rp.srcIA = sp.SrcIA
	rp.idxs.dstHost = rp.idxs.srcIA + addr.IABytes
	rp.dstHost = sp.DstHost
	rp.idxs.srcHost = rp.idxs.dstHost + rp.dstHost.Size()
	rp.srcHost = sp.SrcHost
	rp.dstIA.Write(rp.Raw[rp.idxs.dstIA:])
	rp.srcIA.Write(rp.Raw[rp.idxs.srcIA:])
	copy(rp.Raw[rp.idxs.dstHost:], rp.dstHost.Pack())
	copy(rp.Raw[rp.idxs.srcHost:], rp.srcHost.Pack())
	// Fill in path
	rp.idxs.path = spkt.CmnHdrLen + sp.AddrLen()
	if sp.Path != nil {
		copy(rp.Raw[rp.idxs.path:], sp.Path.Raw)
		rp.CmnHdr.CurrInfoF = uint8((rp.idxs.path + sp.Path.InfOff) / common.LineLen)
		rp.CmnHdr.CurrHopF = uint8((rp.idxs.path + sp.Path.HopOff) / common.LineLen)
	}
	// Fill in extensions
	// rp.idxs.l4 Will be updated as necessary by extnAddHBH and extnAddE2E
	rp.idxs.l4 = int(hdrLen) * common.LineLen
	for _, se := range sp.HBHExt {
		if err := rp.extnAddHBH(se); err != nil {
			return nil, err
		}
	}
	for _, se := range sp.E2EExt {
		if err := rp.extnAddE2E(se); err != nil {
			return nil, err
		}
	}
	// Fill in L4 Header
	rp.idxs.pld = int(hdrLen) * common.LineLen // Will be updated as necessary by addL4
	if sp.L4 != nil {
		if err := rp.addL4(sp.L4); err != nil {
			return nil, err
		}
		// Fill in payload
		if err := rp.SetPld(sp.Pld); err != nil {
			return nil, err
		}
	} else {
		// Trim buffer to the end of the last extension header (or path header,
		// if there are no extensions), and write common header into buffer.
		rp.Raw = rp.Raw[:rp.idxs.l4]
		rp.CmnHdr.TotalLen = uint16(len(rp.Raw))
		rp.CmnHdr.Write(rp.Raw)
	}
	if _, err := rp.InfoF(); err != nil {
		return nil, err
	}
	if _, err := rp.ConsDirFlag(); err != nil {
		return nil, err
	}
	return rp, nil
}

// addL4 adds a layer 4 header to an RtrPkt during creation.
func (rp *RtrPkt) addL4(l4h l4.L4Header) error {
	rp.L4Type = l4h.L4Type()
	rp.l4 = l4h
	// Reset buffer to full size
	rp.Raw = rp.Raw[:cap(rp.Raw)]
	// Write L4 header into buffer
	if err := rp.l4.Write(rp.Raw[rp.idxs.l4:]); err != nil {
		return err
	}
	// Locate the last extension in the packet, whether HBH (hop-by-hop) or E2E (end-to-end),
	// so that its sub-header can be updated with the L4 prototcol type.
	rp.idxs.pld = rp.idxs.l4 + l4h.L4Len()
	var nextHdr *uint8
	for _, eIdx := range rp.idxs.hbhExt {
		nextHdr = &rp.Raw[eIdx.Index]
	}
	for _, eIdx := range rp.idxs.e2eExt {
		nextHdr = &rp.Raw[eIdx.Index]
	}
	if nextHdr != nil {
		// Last extension sub-header found, update its nextHdr field.
		*nextHdr = uint8(rp.L4Type)
	} else {
		// There are no extensions, so the common header NextHDr field needs to be updated.
		rp.CmnHdr.NextHdr = rp.L4Type
	}
	// Trim buffer to the end of the L4 header, and write common header into buffer.
	rp.Raw = rp.Raw[:rp.idxs.pld]
	rp.CmnHdr.TotalLen = uint16(len(rp.Raw))
	rp.CmnHdr.Write(rp.Raw)
	return nil
}

// SetPld updates/sets the payload of an RtrPkt.
func (rp *RtrPkt) SetPld(pld common.Payload) error {
	rp.pld = pld
	var plen int
	if rp.pld != nil {
		// Reset buffer to full size
		rp.Raw = rp.Raw[:cap(rp.Raw)]
		// Write payload into buffer
		var err error
		if plen, err = rp.pld.WritePld(rp.Raw[rp.idxs.pld:]); err != nil {
			return err
		}
	}
	// Trim buffer to the end of the payload.
	rp.Raw = rp.Raw[:rp.idxs.pld+plen]
	// Update L4 header
	if err := rp.updateL4(); err != nil {
		return err
	}
	// Write common header into buffer.
	rp.CmnHdr.TotalLen = uint16(len(rp.Raw))
	rp.CmnHdr.Write(rp.Raw)
	return nil
}

// CreateReplyScnPkt creates a generic ScnPkt reply, by converting the RtrPkt
// to an ScnPkt, then reversing the ScnPkt, and setting the reply source address.
func (rp *RtrPkt) CreateReplyScnPkt() (*spkt.ScnPkt, error) {
	sp, err := rp.ToScnPkt(false)
	if err != nil {
		return nil, err
	}
	if err = sp.Reverse(); err != nil {
		return nil, err
	}
	sp.SrcIA = rp.Ctx.Conf.IA
	// Use the local address as the source host
	pub := rp.Ctx.Conf.Net.LocAddr.PublicOverlay(rp.Ctx.Conf.Topo.Overlay)
	sp.SrcHost = pub.L3()
	return sp, nil
}

func (rp *RtrPkt) CreateReply(sp *spkt.ScnPkt) (*RtrPkt, error) {
	// Convert back to RtrPkt
	reply, err := RtrPktFromScnPkt(sp, rp.Ctx)
	if err != nil {
		return nil, err
	}
	dstIA, err := reply.DstIA()
	if err != nil {
		return nil, err
	}
	// Only (potentially) call IncPath if the dest is not in the local AS.
	if !dstIA.Eq(rp.Ctx.Conf.IA) {
		hopF, err := reply.HopF()
		if err != nil {
			return nil, err
		}
		if hopF != nil && hopF.Xover {
			// Always increment reversed path on a xover point.
			if _, err := reply.IncPath(); err != nil {
				return nil, err
			}
			// Increment reversed path if it was incremented in the forward direction.
			// Check
			// https://github.com/scionproto/scion/blob/master/doc/PathReversal.md
			// for details.
			if rp.IncrementedPath {
				if _, err := reply.IncPath(); err != nil {
					return nil, err
				}
			}
		} else if rp.DirFrom == rcmn.DirExternal {
			// Increase path if the current HOF is not xover and
			// this router is an ingress router.
			if _, err := reply.IncPath(); err != nil {
				return nil, err
			}
		}
	}
	if err := reply.replyEgress(rp.DirFrom, rp.Ingress.Src, rp.Ingress.IfID); err != nil {
		return nil, err
	}
	return reply, nil
}

// replyEgress calculates the corresponding egress function and destination
// address to use when replying to a packet.
func (rp *RtrPkt) replyEgress(dir rcmn.Dir, dst *overlay.OverlayAddr, ifid common.IFIDType) error {
	// Destination is the local AS
	if rp.dstIA.Eq(rp.Ctx.Conf.IA) {
		// Write to local socket
		rp.Egress = append(rp.Egress, EgressPair{S: rp.Ctx.LocSockOut, Dst: dst})
		return nil
	}
	// Destination AS is not local
	if dir == rcmn.DirExternal {
		rp.Egress = append(rp.Egress, EgressPair{S: rp.Ctx.ExtSockOut[ifid]})
		return nil
	}
	if assert.On {
		assert.Must(dir == rcmn.DirLocal, "Wrong direction value")
	}
	// DirFrom Local and destination is remote AS
	// At this point we should have a valid path to route the packet
	if _, err := rp.IFNext(); err != nil {
		return err
	}
	if err := rp.validateLocalIF(rp.ifNext); err != nil {
		return err
	}
	if _, ok := rp.Ctx.Conf.Net.IFs[*rp.ifNext]; ok {
		// Egress interface is on this BR
		// Re-inject to process the reply as an "Egress br"
		// and make it look like it arrived in the local socket
		rp.hooks.Route = append(rp.hooks.Route, rp.reprocess)
		return nil
	}
	// Egress interface is not on this BR
	// Write to local socket
	rp.Egress = append(rp.Egress, EgressPair{S: rp.Ctx.LocSockOut, Dst: dst})
	return nil
}