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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Transform (Apache Commons Math 3.6.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.commons.math3.geometry.partitioning

Interface Transform<S extends Space,T extends Space>

Type Parameters:

S - Type of the embedding space.

T - Type of the embedded sub-space.

public interface Transform<S extends Space,T extends Space>

This interface represents an inversible affine transform in a space.

Inversible affine transform include for example scalings,
 translations, rotations.

Transforms are dimension-specific. The consistency rules between
 the three apply methods are the following ones for a
 transformed defined for dimension D:

     the transform can be applied to a point in the
     D-dimension space using its apply(Point)
     method

     the transform can be applied to a (D-1)-dimension
     hyperplane in the D-dimension space using its
     apply(Hyperplane) method

     the transform can be applied to a (D-2)-dimension
     sub-hyperplane in a (D-1)-dimension hyperplane using
     its apply(SubHyperplane, Hyperplane, Hyperplane)
     method

Since:

3.0

Method Summary

Methods

Modifier and Type
Method and Description

Hyperplane<S>
apply(Hyperplane<S> hyperplane)

Transform an hyperplane of a space.

Point<S>
apply(Point<S> point)

Transform a point of a space.

SubHyperplane<T>
apply(SubHyperplane<T> sub,
     Hyperplane<S> original,
     Hyperplane<S> transformed)

Transform a sub-hyperplane embedded in an hyperplane.

Method Detail

apply

Point<S> apply(Point<S> point)

Transform a point of a space.

Parameters:

point - point to transform

Returns:

a new object representing the transformed point

apply

Hyperplane<S> apply(Hyperplane<S> hyperplane)

Transform an hyperplane of a space.

Parameters:

hyperplane - hyperplane to transform

Returns:

a new object representing the transformed hyperplane

apply

SubHyperplane<T> apply(SubHyperplane<T> sub,
                     Hyperplane<S> original,
                     Hyperplane<S> transformed)

Transform a sub-hyperplane embedded in an hyperplane.

Parameters:

sub - sub-hyperplane to transform

original - hyperplane in which the sub-hyperplane is
 defined (this is the original hyperplane, the transform has
 not been applied to it)

transformed - hyperplane in which the sub-hyperplane is
 defined (this is the transformed hyperplane, the transform
 has been applied to it)

Returns:

a new object representing the transformed sub-hyperplane

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2003–2016 The Apache Software Foundation. All rights reserved.


text:
@class MVVMViewModel;

@interface MVVMPaper : NSObject
@property (nonatomic, copy) NSString *content;
- (void)bindingWithViewModel:(MVVMViewModel *)viewMode;
@end

redpajama_set_name: RedPajamaGithub


text:
package metadata

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Client struct {
	url string
}

func NewClient(url string) *Client {
	return &Client{url}
}

func NewClientAndWait(url string) (*Client, error) {
	client := &Client{url}

	if err := testConnection(client); err != nil {
		return nil, err
	}

	return client, nil
}

func (m *Client) SendRequest(path string) ([]byte, error) {
	client := &http.Client{}
	req, err := http.NewRequest("GET", m.url+path, nil)
	req.Header.Add("Accept", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("Error %v accessing %v path", resp.StatusCode, path)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (m *Client) GetVersion() (string, error) {
	resp, err := m.SendRequest("/version")
	if err != nil {
		return "", err
	}
	return string(resp[:]), nil
}

func (m *Client) GetSelfContainer() (Container, error) {
	resp, err := m.SendRequest("/self/container")
	var container Container
	if err != nil {
		return container, err
	}

	if err = json.Unmarshal(resp, &container); err != nil {
		return container, err
	}

	return container, nil
}

func (m *Client) GetSelfServiceByName(name string) (Service, error) {
	resp, err := m.SendRequest("/self/stack/services/" + name)
	var service Service
	if err != nil {
		return service, err
	}

	if err = json.Unmarshal(resp, &service); err != nil {
		return service, err
	}

	return service, nil
}

func (m *Client) GetSelfService() (Service, error) {
	resp, err := m.SendRequest("/self/service")
	var service Service
	if err != nil {
		return service, err
	}

	if err = json.Unmarshal(resp, &service); err != nil {
		return service, err
	}

	return service, nil
}

func (m *Client) GetSelfStack() (Stack, error) {
	resp, err := m.SendRequest("/self/stack")
	var stack Stack
	if err != nil {
		return stack, err
	}

	if err = json.Unmarshal(resp, &stack); err != nil {
		return stack, err
	}

	return stack, nil
}

func (m *Client) GetServices() ([]Service, error) {
	resp, err := m.SendRequest("/services")
	var services []Service
	if err != nil {
		return services, err
	}

	if err = json.Unmarshal(resp, &services); err != nil {
		return services, err
	}
	return services, nil
}

func (m *Client) GetStacks() ([]Stack, error) {
	resp, err := m.SendRequest("/stacks")
	var stacks []Stack
	if err != nil {
		return stacks, err
	}

	if err = json.Unmarshal(resp, &stacks); err != nil {
		return stacks, err
	}
	return stacks, nil
}

func (m *Client) GetContainers() ([]Container, error) {
	resp, err := m.SendRequest("/containers")
	var containers []Container
	if err != nil {
		return containers, err
	}

	if err = json.Unmarshal(resp, &containers); err != nil {
		return containers, err
	}
	return containers, nil
}

func (m *Client) GetServiceContainers(serviceName string, stackName string) ([]Container, error) {
	var serviceContainers = []Container{}
	containers, err := m.GetContainers()
	if err != nil {
		return serviceContainers, err
	}

	for _, container := range containers {
		if container.StackName == stackName && container.ServiceName == serviceName {
			serviceContainers = append(serviceContainers, container)
		}
	}

	return serviceContainers, nil
}

func (m *Client) GetHosts() ([]Host, error) {
	resp, err := m.SendRequest("/hosts")
	var hosts []Host
	if err != nil {
		return hosts, err
	}

	if err = json.Unmarshal(resp, &hosts); err != nil {
		return hosts, err
	}
	return hosts, nil
}

func (m *Client) GetHost(UUID string) (Host, error) {
	var host Host
	hosts, err := m.GetHosts()
	if err != nil {
		return host, err
	}
	for _, host := range hosts {
		if host.UUID == UUID {
			return host, nil
		}
	}

	return host, fmt.Errorf("could not find host by UUID %v", UUID)
}


text:
var TreeLib = artifacts.require("./TreeLib.sol");
var Tree = artifacts.require("./Tree.sol");

module.exports = function(deployer) {
  deployer.deploy(TreeLib);
  deployer.link(TreeLib, Tree);
  deployer.deploy(Tree);
};


text:
package org.apache.beam.sdk.io.kafka;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import org.apache.beam.sdk.coders.CannotProvideCoderException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderRegistry;
import org.apache.beam.sdk.coders.NullableCoder;
import org.apache.kafka.common.serialization.Deserializer;

/**
 * A {@link DeserializerProvider} that given a local {@link Deserializer} class and Beam's {@link
 * CoderRegistry} configures a {@link Deserializer} instance and infers its corresponding {@link
 * Coder}.
 */
class LocalDeserializerProvider<T> implements DeserializerProvider<T> {
  private Class<? extends Deserializer<T>> deserializer;

  private LocalDeserializerProvider(Class<? extends Deserializer<T>> deserializer) {
    checkArgument(deserializer != null, "You should provide a deserializer.");
    this.deserializer = deserializer;
  }

  static <T> LocalDeserializerProvider<T> of(Class<? extends Deserializer<T>> deserializer) {
    return new LocalDeserializerProvider<>(deserializer);
  }

  @Override
  public Deserializer<T> getDeserializer(Map<String, ?> configs, boolean isKey) {
    try {
      Deserializer<T> deserializer = this.deserializer.getDeclaredConstructor().newInstance();
      deserializer.configure(configs, isKey);
      return deserializer;
    } catch (InstantiationException
        | IllegalAccessException
        | InvocationTargetException
        | NoSuchMethodException e) {
      throw new RuntimeException("Could not instantiate deserializers", e);
    }
  }

  /**
   * Attempt to infer a {@link Coder} by extracting the type of the deserialized-class from the
   * deserializer argument using the {@link Coder} registry.
   */
  @Override
  public NullableCoder<T> getCoder(CoderRegistry coderRegistry) {
    for (Type type : deserializer.getGenericInterfaces()) {
      if (!(type instanceof ParameterizedType)) {
        continue;
      }

      // This does not recurse: we will not infer from a class that extends
      // a class that extends Deserializer<T>.
      ParameterizedType parameterizedType = (ParameterizedType) type;

      if (parameterizedType.getRawType() == Deserializer.class) {
        Type parameter = parameterizedType.getActualTypeArguments()[0];

        @SuppressWarnings("unchecked")
        Class<T> clazz = (Class<T>) parameter;

        try {
          return NullableCoder.of(coderRegistry.getCoder(clazz));
        } catch (CannotProvideCoderException e) {
          throw new RuntimeException(
              String.format(
                  "Unable to automatically infer a Coder for "
                      + "the Kafka Deserializer %s: no coder registered for type %s",
                  deserializer, clazz));
        }
      }
    }
    throw new RuntimeException(
        String.format("Could not extract the Kafka Deserializer type from %s", deserializer));
  }
}


text:
'use strict';
/*jshint camelcase: false */
/*global moment: false */

angular.module('core').service('Weather', ['$q', '$http',
	function($q, $http) {
		var nowTimestamp = moment().unix(),
			cachedConditions = null,
			conditionsTimestamp = null,
			cachedForecast = null,
			forecastTimestamp = null;
		return {
			getConditions: function(locale) {
				var def = $q.defer();
				nowTimestamp = moment().unix();
				conditionsTimestamp = parseInt(sessionStorage.getItem(locale.toString() + 'weatherTimestamp'));
				// cachedConditions = sessionStorage.getItem(locale.toString() + 'conditions') ? JSON.parse(sessionStorage.getItem(locale.toString() + 'conditions')) : null;
				if(!cachedConditions || nowTimestamp - conditionsTimestamp >= 900) { // get on first call then get again if cached for more that 15 minutes
					$http.get('/conditions/' + locale)
					.success(function(data, status, headers, config) {
						sessionStorage.setItem(locale.toString() + 'weatherTimestamp', moment().unix().toString());
						sessionStorage.setItem(locale.toString() + 'conditions', JSON.stringify(data.current_observation));
				        def.resolve(data.current_observation);
					}).error(function(data, status, headers, config) {
						if(data === null && cachedConditions) {
							def.resolve(cachedConditions);
						} else {
							console.log('unable to fetch weather ', status);
							def.reject(status);
						}
					});
					return def.promise;
				} else {
					def.resolve(cachedConditions);
					return def.promise;
				}
			}
			// getForecast: function(locale) {
			// 	var def = $q.defer();
			// 	nowTimestamp = moment().unix();
			// 	forecastTimestamp = parseInt(sessionStorage.getItem(locale.toString() + 'forecastTimestamp'));
			// 	cachedForecast = sessionStorage.getItem(locale.toString() + 'forecast') ? JSON.parse(sessionStorage.getItem(locale.toString() + 'forecast')) : null;
			// 	if(!cachedForecast || nowTimestamp - forecastTimestamp >= 900) { // get on first call then get again if cached for more that 15 minutes
			// 		$http.get(weatherURL + 'forecast/q/' + locale + '.json')
			// 		.success(function(data, status, headers, config) {
			// 			sessionStorage.setItem(locale.toString() + 'forecast', JSON.stringify(data.forecast.simpleforecast));
			// 			sessionStorage.setItem(locale.toString() + 'forecastTimestamp', moment().unix().toString());
			// 			def.resolve(data.forecast.simpleforecast);
			// 		}).error(function(data, status, headers, config) {
			// 			if(data === null && cachedForecast) {
			// 				def.resolve(cachedForecast);
			// 			} else {
			// 				console.log('unable to fetch weather ', status);
			// 				def.reject(status);
			// 			}
			// 		});
			// 		return def.promise;
			// 	} else {
			// 		def.resolve(cachedForecast);
			// 		return def.promise;
			// 	}
			// }
		};
	}
]);


text:
package net.liftweb {
package oauth {
package mapper {

  import java.util.Date
  import net.liftweb.mapper._
  import net.liftweb.common._
  import net.liftweb.util.Helpers._
  import oauth._

  trait MOAuthToken[ModelType <: MOAuthToken[ModelType]] extends LongKeyedMapper[ModelType] with OAuthToken {
    self: ModelType =>

    type UserType <: KeyedMapper[Long, UserType] with OAuthUser

    def getUserMeta: KeyedMetaMapper[Long, UserType]

    type MOAuthConsumerType <: MOAuthConsumer[MOAuthConsumerType] with LongKeyedMapper[MOAuthConsumerType]

    def getMOAuthConsumerMeta: MOAuthConsumerMeta[MOAuthConsumerType] with LongKeyedMetaMapper[MOAuthConsumerType]

    def primaryKeyField = id
    object id extends MappedLongIndex(this) {
      override def dbColumnName = "ost_id"
    }
    object _consumer extends MappedLongForeignKey[ModelType, MOAuthConsumerType](this, getMOAuthConsumerMeta) {
      override def dbColumnName = "ost_osr_id_ref"
    }

    def consumer = _consumer.obj.open_!

    object userid extends MappedLongForeignKey(this, getUserMeta) {
      override def dbColumnName = "ost_usa_id_ref"
    }

    def user: UserType = userid.obj.open_!

    object _token extends MappedUniqueId(this, 48) {
      override def dbColumnName = "ost_token"
    }

    def token = _token.is

    object _secret extends MappedUniqueId(this, 48) {
      override def dbColumnName = "ost_token_secret"
    }

    def secret = _secret.is

    object token_type extends MappedString(this, 32) {
      override def dbColumnName = "ost_token_type"
    }

    def tokenType = token_type.is

    object _authorized extends MappedInt(this) {
      override def dbColumnName = "ost_authorized"
      override def defaultValue = 0
    }

    def authorized = _authorized.is

    object referrer_host extends MappedString(this, 128) {
      override def dbColumnName = "ost_referrer_host"
      override def defaultValue = ""
    }

    def referrerHost = referrer_host.is

    object _ttl extends MappedDateTime(this) {
      override def dbColumnName = "ost_token_ttl"
      override def defaultValue = 60.minutes.later
    }

    def ttl = _ttl.is

    object _xdatetime extends MappedDateTime(this) {
      override def dbColumnName = "ost_timestamp"
      override def defaultValue = new Date
    }

    def xdatetime = _xdatetime.is
  }

  trait MOAuthTokenMeta[ModelType <: MOAuthToken[ModelType]] extends MOAuthToken[ModelType] with LongKeyedMetaMapper[ModelType] {
    self: ModelType =>
    override def dbTableName = "oauth_server_token"

    def bulkDelete_!!(what: Long): Unit =
    this.bulkDelete_!!(Cmp[ModelType, Long](_consumer,
                                            OprEnum.Eql, Full(what), Empty, Empty))
  }

}
}
}


text:
using System;

namespace Azure.ResourceManager.AppContainers.Models
{
    internal static partial class ForwardProxyConventionExtensions
    {
        public static string ToSerialString(this ForwardProxyConvention value) => value switch
        {
            ForwardProxyConvention.NoProxy => "NoProxy",
            ForwardProxyConvention.Standard => "Standard",
            ForwardProxyConvention.Custom => "Custom",
            _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ForwardProxyConvention value.")
        };

        public static ForwardProxyConvention ToForwardProxyConvention(this string value)
        {
            if (string.Equals(value, "NoProxy", StringComparison.InvariantCultureIgnoreCase)) return ForwardProxyConvention.NoProxy;
            if (string.Equals(value, "Standard", StringComparison.InvariantCultureIgnoreCase)) return ForwardProxyConvention.Standard;
            if (string.Equals(value, "Custom", StringComparison.InvariantCultureIgnoreCase)) return ForwardProxyConvention.Custom;
            throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ForwardProxyConvention value.");
        }
    }
}


text:
from test.integration.base import DBTIntegrationTest, use_profile

class BaseTestSimpleDependencyWithConfigs(DBTIntegrationTest):

    def setUp(self):
        DBTIntegrationTest.setUp(self)
        self.run_sql_file("seed.sql")

    @property
    def schema(self):
        return "simple_dependency_006"

    @property
    def models(self):
        return "models"

class TestSimpleDependencyWithConfigs(BaseTestSimpleDependencyWithConfigs):
    @property
    def packages_config(self):
        return {
            "packages": [
                {
                    'git': 'https://github.com/fishtown-analytics/dbt-integration-project',
                    'revision': 'with-configs-0.17.0',
                },
            ]
        }

    @property
    def project_config(self):
        return {
            'config-version': 2,
            'vars': {
                'dbt_integration_project': {
                    'bool_config': True
                },
            },
        }

    @use_profile('postgres')
    def test_postgres_simple_dependency(self):
        self.run_dbt(["deps"])
        results = self.run_dbt(["run"])
        self.assertEqual(len(results),  5)

        self.assertTablesEqual('seed_config_expected_1', "config")
        self.assertTablesEqual("seed", "table_model")
        self.assertTablesEqual("seed", "view_model")
        self.assertTablesEqual("seed", "incremental")

class TestSimpleDependencyWithOverriddenConfigs(BaseTestSimpleDependencyWithConfigs):

    @property
    def packages_config(self):
        return {
            "packages": [
                {
                    'git': 'https://github.com/fishtown-analytics/dbt-integration-project',
                    'revision': 'with-configs-0.17.0',
                },
            ]
        }

    @property
    def project_config(self):
        return {
            'config-version': 2,
            "vars": {
                # project-level configs
                "dbt_integration_project": {
                    "config_1": "abc",
                    "config_2": "def",
                    "bool_config": True
                },
            },
        }

    @use_profile('postgres')
    def test_postgres_simple_dependency(self):
        self.run_dbt(["deps"])
        results = self.run_dbt(["run"])
        self.assertEqual(len(results),  5)

        self.assertTablesEqual('seed_config_expected_2', "config")
        self.assertTablesEqual("seed", "table_model")
        self.assertTablesEqual("seed", "view_model")
        self.assertTablesEqual("seed", "incremental")

class TestSimpleDependencyWithModelSpecificOverriddenConfigs(BaseTestSimpleDependencyWithConfigs):

    @property
    def packages_config(self):
        return {
            "packages": [
                {
                    'git': 'https://github.com/fishtown-analytics/dbt-integration-project',
                    'revision': 'with-configs-0.17.0',
                },
            ]
        }

    @property
    def project_config(self):
        # This feature doesn't exist in v2!
        return {
            'config-version': 1,
            "models": {
                "dbt_integration_project": {
                    "config": {
                        # model-level configs
                        "vars": {
                            "config_1": "ghi",
                            "config_2": "jkl",
                            "bool_config": True,
                        }
                    }
                }
            },
        }

    @use_profile('postgres')
    def test_postgres_simple_dependency(self):
        self.use_default_project()

        self.run_dbt(["deps"])
        results = self.run_dbt(["run"], strict=False)  # config is v1, can't use strict here
        self.assertEqual(len(results),  5)

        self.assertTablesEqual('seed_config_expected_3', "config")
        self.assertTablesEqual("seed", "table_model")
        self.assertTablesEqual("seed", "view_model")
        self.assertTablesEqual("seed", "incremental")

class TestSimpleDependencyWithModelSpecificOverriddenConfigsAndMaterializations(BaseTestSimpleDependencyWithConfigs):

    @property
    def packages_config(self):
        return {
            "packages": [
                {
                    'git': 'https://github.com/fishtown-analytics/dbt-integration-project',
                    'revision': 'with-configs-0.17.0',
                },
            ]
        }

    @property
    def project_config(self):
        return {
            'config-version': 1,
            "models": {
                "dbt_integration_project": {
                    # disable config model, but supply vars
                    "config": {
                        "enabled": False,
                        "vars": {
                            "config_1": "ghi",
                            "config_2": "jkl",
                            "bool_config": True

                        }
                    },
                    # disable the table model
                    "table_model": {
                        "enabled": False,
                    },
                    # override materialization settings
                    "view_model": {
                        "materialized": "table"
                    }
                }

            },
        }

    @use_profile('postgres')
    def test_postgres_simple_dependency(self):
        self.run_dbt(["deps"])
        results = self.run_dbt(["run"], strict=False)  # config is v1, can't use strict here
        self.assertEqual(len(results),  3)

        self.assertTablesEqual("seed", "view_model")
        self.assertTablesEqual("seed", "incremental")

        created_models = self.get_models_in_schema()

        # config, table are disabled
        self.assertFalse('config' in created_models)
        self.assertFalse('table_model' in created_models)

        self.assertTrue('view_model' in created_models)
        self.assertEqual(created_models['view_model'], 'table')

        self.assertTrue('incremental' in created_models)
        self.assertEqual(created_models['incremental'], 'table')


text:
<bill session="115" type="h" number="3066" updated="2017-09-11T03:06:00Z">
  <state datetime="2017-06-27">REFERRED</state>
  <status>
    <introduced datetime="2017-06-27"/>
  </status>
  <introduced datetime="2017-06-27"/>
  <titles>
    <title type="official" as="introduced">To direct the Secretary of Defense to carry out a program to protect United States students against foreign agents.</title>
    <title type="display">To direct the Secretary of Defense to carry out a program to protect United States students against foreign agents.</title>
  </titles>
  <sponsor bioguide_id="S001170"/>
  <cosponsors/>
  <actions>
    <action datetime="2017-06-27">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-06-27" state="REFERRED">
      <text>Referred to the Committee on Armed Services, and in addition to the Committee on Intelligence (Permanent Select), for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-06-27">
      <text>Referred to the Committee on Armed Services, and in addition to the Committee on Intelligence (Permanent Select), for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HLIG" name="House Intelligence (Permanent)" activity="Referral"/>
    <committee subcommittee="" code="HSAS" name="House Armed Services" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="unknown" number="2810"/>
  </relatedbills>
  <subjects>
    <term name="Armed forces and national security"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
namespace Microsoft.Azure.Management.Compute.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The Update Resource model definition.
    /// </summary>
    public partial class UpdateResource
    {
        /// <summary>
        /// Initializes a new instance of the UpdateResource class.
        /// </summary>
        public UpdateResource()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the UpdateResource class.
        /// </summary>
        /// <param name="tags">Resource tags</param>
        public UpdateResource(IDictionary<string, string> tags = default(IDictionary<string, string>))
        {
            Tags = tags;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets resource tags
        /// </summary>
        [JsonProperty(PropertyName = "tags")]
        public IDictionary<string, string> Tags { get; set; }

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Shipped System Providers - Zend Framework Manual</title>

                    Creating Providers to use with Zend_Tool_Framework

Zend_Tool_Framework

                        Programmer's Reference Guide

Extending and Configuring Zend_Tool_Framework

Shipped System Providers

        In addition to the more useful project based providers that come shipped
        with Zend_Tool_Project, there are also some more basic, but
        interesting providers that come built into
        Zend_Tool_Framework. Some of these exist for the purpose
        of providing a means via the command line to extract information, such
        as the version, while others are intended to aid the developer when
        creating additional providers.

The Version Provider

            The Version provider is included so that you may determine which
            version of the framework that the zf or
            Zend_Tool is currently set to work with.

            Through the command line, simply run zf show version.

The Manifest Provider

            The Manifest provider is included so that you may determine what
            kind of "manifest" information is available during the
            Zend_Tool runtime. Manifest data is information that
            is attached to specific objects during Zend_Tool's
            runtime. Inside the manifest you will find the console specific
            namings that you are expected to use when calling certain commands.
            Data found in the manifest can be used by any provider or client on
            an as-needed basis.

            Through the command line, simply run zf show manifest.

                    Creating Providers to use with Zend_Tool_Framework

Zend_Tool_Framework

                        Programmer's Reference Guide

Extending and Configuring Zend_Tool_Framework

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Tool_Framework

Introduction

Using the CLI Tool

Architecture

Creating Providers to use with Zend_Tool_Framework

Shipped System Providers

Extending and Configuring Zend_Tool_Framework


text:
namespace BankAccounts.Customers
{
    internal class Company : Customer
    {
        public Company(string name) : base(name)
        {
        }
    }
}


text:
package org.apache.curator.x.discovery.details;

import com.google.common.collect.Lists;
import org.apache.curator.x.discovery.DownInstancePolicy;
import org.apache.curator.x.discovery.InstanceFilter;
import org.apache.curator.x.discovery.ProviderStrategy;
import org.apache.curator.x.discovery.ServiceCache;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * The main interface for Service Discovery. Encapsulates the discovery service for a particular
 * named service along with a provider strategy.
 */
public class ServiceProviderImpl<T> implements ServiceProvider<T>
{
    private final ServiceCache<T> cache;
    private final InstanceProvider<T> instanceProvider;
    private final ServiceDiscoveryImpl<T> discovery;
    private final ProviderStrategy<T> providerStrategy;
    private final DownInstanceManager<T> downInstanceManager;

    public ServiceProviderImpl(ServiceDiscoveryImpl<T> discovery, String serviceName, ProviderStrategy<T> providerStrategy, ThreadFactory threadFactory, List<InstanceFilter<T>> filters, DownInstancePolicy downInstancePolicy)
    {
        this.discovery = discovery;
        this.providerStrategy = providerStrategy;

        downInstanceManager = new DownInstanceManager<T>(downInstancePolicy);
        cache = discovery.serviceCacheBuilder().name(serviceName).threadFactory(threadFactory).build();

        ArrayList<InstanceFilter<T>> localFilters = Lists.newArrayList(filters);
        localFilters.add(downInstanceManager);
        instanceProvider = new FilteredInstanceProvider<T>(cache, localFilters);
    }

    /**
     * The provider must be started before use
     *
     * @throws Exception any errors
     */
    @Override
    public void start() throws Exception
    {
        cache.start();
        discovery.providerOpened(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close() throws IOException
    {
        discovery.providerClosed(this);
        cache.close();
    }

    /**
     * Return the current available set of instances <b>IMPORTANT: </b> users
     * should not hold on to the instance returned. They should always get a fresh list.
     *
     * @return all known instances
     * @throws Exception any errors
     */
    @Override
    public Collection<ServiceInstance<T>> getAllInstances() throws Exception
    {
        return instanceProvider.getInstances();
    }

    /**
     * Return an instance for a single use. <b>IMPORTANT: </b> users
     * should not hold on to the instance returned. They should always get a fresh instance.
     *
     * @return the instance to use
     * @throws Exception any errors
     */
    @Override
    public ServiceInstance<T> getInstance() throws Exception
    {
        return providerStrategy.getInstance(instanceProvider);
    }

    @Override
    public void noteError(ServiceInstance<T> instance)
    {
        downInstanceManager.add(instance);
    }
}


text:
module FailWhale
  class Configuration
    def initialize(&block)
      @matchers = []
      self.instance_eval(&block)
    end

    def fail_on(url, *args, &block)
      @matchers << Matcher.new(url, &block)
    end

    def find_match_for(url)
      @matchers.detect{|matcher| matcher.url =~ url}
    end

    def matchers
      @matchers
    end
  end
end


text:
import EventBus from '../../core/EventBus';
import Events from '../../core/events/Events';
import FactoryMaker from '../../core/FactoryMaker';

function TextController(config) {

    let context = this.context;
    let eventBus = EventBus(context).getInstance();

    let sourceBufferController = config.sourceBufferController;
    let errHandler = config.errHandler;

    let instance,
        isBufferingCompleted,
        initialized,
        mediaSource,
        buffer,
        type,
        streamProcessor,
        representationController;

    function setup() {

        initialized = false;
        mediaSource = null;
        buffer = null;
        type = null;
        streamProcessor = null;
        representationController = null;
        isBufferingCompleted = false;

        eventBus.on(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, this);
        eventBus.on(Events.INIT_FRAGMENT_LOADED, onInitFragmentLoaded, this);
    }

    function initialize(Type, source, StreamProcessor) {
        type = Type;
        setMediaSource(source);
        streamProcessor = StreamProcessor;
        representationController = streamProcessor.getRepresentationController();
    }

    /**
     * @param {MediaInfo }mediaInfo
     * @returns {Object} SourceBuffer object
     * @memberof BufferController#
     */
    function createBuffer(mediaInfo) {
        try {
            buffer = sourceBufferController.createSourceBuffer(mediaSource, mediaInfo);

            if (!initialized) {
                if (buffer.hasOwnProperty('initialize')) {
                    buffer.initialize(type, this);
                }
                initialized = true;
            }
        } catch (e) {
            errHandler.mediaSourceError('Error creating ' + type + ' source buffer.');
        }

        return buffer;
    }

    function getBuffer() {
        return buffer;
    }

    function setBuffer(value) {
        buffer = value;
    }

    function setMediaSource(value) {
        mediaSource = value;
    }

    function getStreamProcessor() {
        return streamProcessor;
    }

    function reset(errored) {

        eventBus.off(Events.DATA_UPDATE_COMPLETED, onDataUpdateCompleted, this);
        eventBus.off(Events.INIT_FRAGMENT_LOADED, onInitFragmentLoaded, this);

        if (!errored) {
            sourceBufferController.abort(mediaSource, buffer);
            sourceBufferController.removeSourceBuffer(mediaSource, buffer);
        }
    }

    function onDataUpdateCompleted(e) {
        if (e.sender.getStreamProcessor() !== streamProcessor) return;
        eventBus.trigger(Events.TIMED_TEXT_REQUESTED, { index: 0, sender: e.sender }); //TODO make index dynamic if referring to MP?
    }

    function onInitFragmentLoaded(e) {
        if (e.fragmentModel !== streamProcessor.getFragmentModel() || (!e.chunk.bytes)) return;
        sourceBufferController.append(buffer, e.chunk);
    }

    function getIsBufferingCompleted() {
        return isBufferingCompleted;
    }

    instance = {
        initialize: initialize,
        createBuffer: createBuffer,
        getBuffer: getBuffer,
        setBuffer: setBuffer,
        getStreamProcessor: getStreamProcessor,
        getIsBufferingCompleted: getIsBufferingCompleted,
        setMediaSource: setMediaSource,
        reset: reset
    };

    setup();

    return instance;
}

TextController.__dashjs_factory_name = 'TextController';
export default FactoryMaker.getClassFactory(TextController);


text:
'use strict';

var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');

module.exports = function (domElement) {
    return function (tree) {
        var element = createElement(tree);
        domElement.parentElement.replaceChild(element, domElement);
        return function update(newTree) {
            element = patch(element, diff(tree, newTree));
            tree = newTree;
            return update;
        };
    };
};


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.airavata.model.messaging.event;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("all") public class messagingEventsConstants {

  public static final String DEFAULT_ID = "DO_NOT_SET_AT_CLIENTS";

}


text:
package v1

import (
	"testing"

	"github.com/gophercloud/gophercloud/acceptance/clients"
	"github.com/gophercloud/gophercloud/openstack/clustering/v1/nodes"
	"github.com/gophercloud/gophercloud/openstack/clustering/v1/webhooks"
	th "github.com/gophercloud/gophercloud/testhelper"
)

func TestClusteringWebhookTrigger(t *testing.T) {

	client, err := clients.NewClusteringV1Client()
	if err != nil {
		t.Fatalf("Unable to create clustering client: %v", err)
	}

	opts := webhooks.TriggerOpts{
		V: "1",
	}

	// create profile, cluster and receiver first
	profile, err := CreateProfile(t, client)
	th.AssertNoErr(t, err)
	defer DeleteProfile(t, client, profile.ID)

	cluster, err := CreateCluster(t, client, profile.ID)
	th.AssertNoErr(t, err)
	defer DeleteCluster(t, client, cluster.ID)

	receiver, err := CreateReceiver(t, client, cluster.ID)
	th.AssertNoErr(t, err)
	defer DeleteReceiver(t, client, receiver.ID)

	// trigger webhook
	actionID, err := webhooks.Trigger(client, receiver.ID, opts).Extract()
	if err != nil {
		t.Fatalf("Unable to extract webhooks trigger: %v", err)
	} else {
		t.Logf("Webhook trigger action id %s", actionID)
	}

	err = WaitForAction(client, actionID)
	if err != nil {
		t.Fatalf("Error scaling out cluster %s as a result from webhook trigger: %s:", cluster.ID, err)
	}

	// check that new node was created
	nodelistopts := nodes.ListOpts{
		ClusterID: cluster.ID,
	}

	allPages, err := nodes.List(client, nodelistopts).AllPages()
	th.AssertNoErr(t, err)

	allNodes, err := nodes.ExtractNodes(allPages)
	th.AssertNoErr(t, err)

	// there should be 2 nodes in the cluster after triggering webhook
	th.AssertEquals(t, len(allNodes), 2)
}


text:
import unittest

from pycellbase.cbclient import CellBaseClient
from pycellbase.cbconfig import ConfigClient

class CellBaseClientTest(unittest.TestCase):
    """Tests the CellBaseClient class"""
    def test_config(self):
        """Checks configuration customization"""
        # Initialization
        cc = ConfigClient()
        cbc = CellBaseClient(cc)

        # Checking some default config params
        assert cbc.get_config()['species'] == 'hsapiens'
        assert cbc.get_config()['version'] == 'v4'

        # Checking some setters for config params
        cc.species = 'mmusculus'
        assert cbc.get_config()['species'] == 'mmusculus'
        cc.version = 'v3'
        assert cbc.get_config()['version'] == 'v3'

    def test_get(self):
        """"Checks generic fetcher for RESTful service"""
        # Initialization
        cc = ConfigClient()
        cbc = CellBaseClient(cc)

        res = cbc.get('feature', 'gene', 'protein', 'BRCA1')
        assert res[0]['result'][0]['name'][0] == 'BRCA1_HUMAN'

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


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.datetime;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.IsoFields;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalField;
import java.util.Objects;

public class DateTimeProcessor extends BaseDateTimeProcessor {

    public enum DateTimeExtractor {
        DAY_OF_MONTH(ChronoField.DAY_OF_MONTH),
        ISO_DAY_OF_WEEK(ChronoField.DAY_OF_WEEK),
        DAY_OF_YEAR(ChronoField.DAY_OF_YEAR),
        HOUR_OF_DAY(ChronoField.HOUR_OF_DAY),
        MINUTE_OF_DAY(ChronoField.MINUTE_OF_DAY),
        MINUTE_OF_HOUR(ChronoField.MINUTE_OF_HOUR),
        MONTH_OF_YEAR(ChronoField.MONTH_OF_YEAR),
        SECOND_OF_MINUTE(ChronoField.SECOND_OF_MINUTE),
        ISO_WEEK_OF_YEAR(IsoFields.WEEK_OF_WEEK_BASED_YEAR),
        YEAR(ChronoField.YEAR);

        private final TemporalField field;

        DateTimeExtractor(TemporalField field) {
            this.field = field;
        }

        public int extract(Temporal time) {
            return time.get(field);
        }
    }

    public static final String NAME = "dt";
    private final DateTimeExtractor extractor;

    public DateTimeProcessor(DateTimeExtractor extractor, ZoneId zoneId) {
        super(zoneId);
        this.extractor = extractor;
    }

    public DateTimeProcessor(StreamInput in) throws IOException {
        super(in);
        extractor = in.readEnum(DateTimeExtractor.class);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeEnum(extractor);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    DateTimeExtractor extractor() {
        return extractor;
    }

    @Override
    public Object doProcess(ZonedDateTime dateTime) {
        return extractor.extract(dateTime);
    }

    public static Integer doProcess(ZonedDateTime dateTime, String tzId, String extractorName) {
        ZonedDateTime zdt = dateTime.withZoneSameInstant(ZoneId.of(tzId));
        return doProcess(zdt, extractorName);
    }

    protected static Integer doProcess(Temporal dateTime, String extractorName) {
        return DateTimeExtractor.valueOf(extractorName).extract(dateTime);
    }

    @Override
    public int hashCode() {
        return Objects.hash(extractor, zoneId());
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || obj.getClass() != getClass()) {
            return false;
        }
        DateTimeProcessor other = (DateTimeProcessor) obj;
        return Objects.equals(extractor, other.extractor)
                && Objects.equals(zoneId(), other.zoneId());
    }

    @Override
    public String toString() {
        return extractor.toString();
    }
}


text:
class PrefService;

namespace ios_feed {

// Tracker for the notice card related actions that also provide signals based
// on those.
class NoticeCardTracker {
 public:
  explicit NoticeCardTracker(PrefService* profile_prefs);

  NoticeCardTracker(const NoticeCardTracker&) = delete;
  NoticeCardTracker& operator=(const NoticeCardTracker&) = delete;

  // Capture the actions.

  void OnSliceViewed(int index);
  void OnOpenAction(int index);

  // Get signals based on the actions.

  // Indicates whether there were enough views or clicks done on the notice
  // card to consider it as acknowledged by the user. This is safe to call in a
  // background thread.
  bool HasAcknowledgedNoticeCard() const;

 private:
  bool HasNoticeCardActionsCountPrerequisites(int index);
  void MaybeUpdateNoticeCardViewsCount(int index);
  void MaybeUpdateNoticeCardClicksCount(int index);

  PrefService* profile_prefs_;

  // The number of views of the notice card.
  mutable base::Lock views_count_lock_;
  int views_count_ GUARDED_BY(views_count_lock_);

  // The number of clicks/taps of the notice card.
  mutable base::Lock clicks_count_lock_;
  int clicks_count_ GUARDED_BY(clicks_count_lock_);

  // The number of views of the notice card to consider it acknowledged by the
  // user.
  int views_count_threshold_;

  // The number of clicks/taps of the notice card to consider it acknowledged by
  // the user.
  int clicks_count_threshold_;
};

}  // namespace ios_feed

#endif  // COMPONENTS_FEED_CORE_V2_PUBLIC_IOS_NOTICE_CARD_TRACKER_H_


text:
import * as React from 'react';
import { connect } from 'react-redux';
import { IStoreState } from '../../../redux/main_reducer';
import {VideoEditor} from "./VideoEditor";

interface IProperties {}

interface ICallbacks {}

interface IProps extends IProperties, ICallbacks {}

interface IState extends IProperties, ICallbacks {}

export class VideoEditorContainer extends React.Component<IProps, IState> {

    public constructor(props?: any, context?: any) {
        super(props, context);
    }

    render(): JSX.Element {
        const styles = {
            container: {
                position: "absolute",
                top: 0,
                left: 0,
                width: "100%",
                height: "100vh",
                textAlign: "center"
            },
            container__object: {
                display: "inline-block",
                width: "80%"
            }
        };
        return (

                    <VideoEditor/>

        );
    }
}

// ------------ redux mappers -------------

function mapStateToProps(state: IStoreState, ownProps: IProps): IProperties {
    return {
    };

}

function mapDispatchToProps(dispatch, ownProps: IProps): ICallbacks {
    return {
    }
}

export let VideoEditorContainerFromStore = connect(
    mapStateToProps, mapDispatchToProps
)(VideoEditorContainer);


text:
using FluentAssertions;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http.Headers;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Toggl.Networking.ApiClients;
using Toggl.Networking.Exceptions;
using Toggl.Networking.Network;
using Toggl.Networking.Tests.Exceptions;
using Toggl.Networking.Tests.Network;
using Xunit;
using static System.Net.HttpStatusCode;

namespace Toggl.Networking.Tests.Clients
{
    public sealed class StatusClientTests
    {
        public sealed class TheIsAvailableMethod
        {
            private readonly StatusApi statusApi;
            private readonly IApiClient apiClient = Substitute.For<IApiClient>();

            public TheIsAvailableMethod()
            {
                var endpoints = new Endpoints(ApiEnvironment.Staging);
                statusApi = new StatusApi(endpoints, apiClient);
            }

            [Fact, LogIfTooSlow]
            public async Task DoesNotHideThrownExceptions()
            {
                bool caughtException = false;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
                apiClient
                    .Send(Arg.Any<IRequest>())
                    .Returns(async x => throw new WebException());
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

                try
                {
                    await statusApi.IsAvailable();
                }
                catch
                {
                    caughtException = true;
                }

                caughtException.Should().BeTrue();
            }

            [Fact, LogIfTooSlow]
            public void ReturnsASingleValueForWorkingApiCalls()
            {
                apiClient
                    .Send(Arg.Any<IRequest>())
                    .Returns(x => new Response("OK", true, "text/plain", new MockHttpHeaders(), OK));

                statusApi.IsAvailable().Wait();
            }

            [Fact, LogIfTooSlow]
            public void ThrowsApiExceptionExceptionWhenApiServerIsNotAvailable()
            {
                apiClient
                    .Send(Arg.Any<IRequest>())
                    .Returns(x => new Response("PANIC", false, "text/plain", new MockHttpHeaders(), InternalServerError));

                Action gettingServerStatus = () => statusApi.IsAvailable().Wait();

                gettingServerStatus.Should().Throw<InternalServerErrorException>();
            }
        }
    }
}


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("ruby_generated_pkg_implicit.proto", :syntax => :proto3) do
    add_message "one.two.a_three.Four" do
      optional :a_string, :string, 1
    end
  end
end

module One
  module Two
    module AThree
      Four = Google::Protobuf::DescriptorPool.generated_pool.lookup("one.two.a_three.Four").msgclass
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Index extends CI_Controller {
	public function __construct(){
		parent::__construct();
	}
	public function index(){
		$this->load->view('login/index');
	}

	public function processLogin(){
		$user = $this->input->post('username');
		$pass = $this->input->post('password');

		$login = $this->m_admin->login($user,$pass);

		if ($login) {
			$this->session->set_userdata('username', $user);
			redirect('blog/index','refresh');
		}
		else{
			redirect(site_url('index'),'refresh');
		}
	}

	public function logout(){
		$this->session->sess_destroy();
		redirect('index','refresh');
	}
}

/* End of file index.php */
/* Location: ./application/controllers/index.php */


text:
@interface FSDViewController ()
@property (weak, nonatomic) IBOutlet FSDAirportFlipLabel *airportLabel;

@property (weak, nonatomic) IBOutlet UIButton *changeButton;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end

@implementation FSDViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.airportLabel.textSize = 14;
    self.airportLabel.useSound = YES;
    self.airportLabel.fixedLenght = 15;
    self.airportLabel.flipDuration = 0.1f;
    self.airportLabel.flipDurationRange = 1.0f;
    self.airportLabel.numberOfFlips = 10;
    self.airportLabel.numberOfFlipsRange = 1.0f;
    self.airportLabel.flipTextColor = [UIColor whiteColor];
    self.airportLabel.flipBackGroundColor = [UIColor blackColor];
    __weak __typeof(self) weakSelf = self;

    self.airportLabel.startedFlippingLabelsBlock = ^{
        weakSelf.changeButton.enabled = NO;
        NSLog(@"started flipping");
    };
    self.airportLabel.finishedFlippingLabelsBlock = ^{
        weakSelf.changeButton.enabled = YES;
        NSLog(@"Stopped flipping");
    };

    self.airportLabel.text = @"FSD Flight 2022";
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)changeLabelText:(id)sender {
    self.airportLabel.text = self.textField.text;
}

@end


text:
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

namespace Python.Runtime
{
    /// <summary>
    /// The managed metatype. This object implements the type of all reflected
    /// types. It also provides support for single-inheritance from reflected
    /// managed types.
    /// </summary>
    internal class MetaType : ManagedType
    {
        private static IntPtr PyCLRMetaType;
        private static SlotsHolder _metaSlotsHodler;

        internal static readonly string[] CustomMethods = new string[]
        {
            "__instancecheck__",
            "__subclasscheck__",
        };

        /// <summary>
        /// Metatype initialization. This bootstraps the CLR metatype to life.
        /// </summary>
        public static IntPtr Initialize()
        {
            PyCLRMetaType = TypeManager.CreateMetaType(typeof(MetaType), out _metaSlotsHodler);
            return PyCLRMetaType;
        }

        public static void Release()
        {
            if (Runtime.Refcount(PyCLRMetaType) > 1)
            {
                _metaSlotsHodler.ResetSlots();
            }
            Runtime.Py_CLEAR(ref PyCLRMetaType);
            _metaSlotsHodler = null;
        }

        internal static void SaveRuntimeData(RuntimeDataStorage storage)
        {
            Runtime.XIncref(PyCLRMetaType);
            storage.PushValue(PyCLRMetaType);
        }

        internal static IntPtr RestoreRuntimeData(RuntimeDataStorage storage)
        {
            PyCLRMetaType = storage.PopValue<IntPtr>();
            _metaSlotsHodler = new SlotsHolder(PyCLRMetaType);
            TypeManager.InitializeSlots(PyCLRMetaType, typeof(MetaType), _metaSlotsHodler);

            IntPtr mdef = Marshal.ReadIntPtr(PyCLRMetaType, TypeOffset.tp_methods);
            foreach (var methodName in CustomMethods)
            {
                var mi = typeof(MetaType).GetMethod(methodName);
                ThunkInfo thunkInfo = Interop.GetThunk(mi, "BinaryFunc");
                _metaSlotsHodler.KeeapAlive(thunkInfo);
                mdef = TypeManager.WriteMethodDef(mdef, methodName, thunkInfo.Address);
            }
            return PyCLRMetaType;
        }

        /// <summary>
        /// Metatype __new__ implementation. This is called to create a new
        /// class / type when a reflected class is subclassed.
        /// </summary>
        public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw)
        {
            var len = Runtime.PyTuple_Size(args);
            if (len < 3)
            {
                return Exceptions.RaiseTypeError("invalid argument list");
            }

            IntPtr name = Runtime.PyTuple_GetItem(args, 0);
            IntPtr bases = Runtime.PyTuple_GetItem(args, 1);
            IntPtr dict = Runtime.PyTuple_GetItem(args, 2);

            // We do not support multiple inheritance, so the bases argument
            // should be a 1-item tuple containing the type we are subtyping.
            // That type must itself have a managed implementation. We check
            // that by making sure its metatype is the CLR metatype.

            if (Runtime.PyTuple_Size(bases) != 1)
            {
                return Exceptions.RaiseTypeError("cannot use multiple inheritance with managed classes");
            }

            IntPtr base_type = Runtime.PyTuple_GetItem(bases, 0);
            IntPtr mt = Runtime.PyObject_TYPE(base_type);

            if (!(mt == PyCLRMetaType || mt == Runtime.PyTypeType))
            {
                return Exceptions.RaiseTypeError("invalid metatype");
            }

            // Ensure that the reflected type is appropriate for subclassing,
            // disallowing subclassing of delegates, enums and array types.

            var cb = GetManagedObject(base_type) as ClassBase;
            if (cb != null)
            {
                try
                {
                    if (!cb.CanSubclass())
                    {
                        return Exceptions.RaiseTypeError("delegates, enums and array types cannot be subclassed");
                    }
                }
                catch (SerializationException)
                {
                    return Exceptions.RaiseTypeError($"Underlying C# Base class {cb.type} has been deleted");
                }
            }

            IntPtr slots = Runtime.PyDict_GetItem(dict, PyIdentifier.__slots__);
            if (slots != IntPtr.Zero)
            {
                return Exceptions.RaiseTypeError("subclasses of managed classes do not support __slots__");
            }

            // If __assembly__ or __namespace__ are in the class dictionary then create
            // a managed sub type.
            // This creates a new managed type that can be used from .net to call back
            // into python.
            if (IntPtr.Zero != dict)
            {
                Runtime.XIncref(dict);
                using (var clsDict = new PyDict(dict))
                {
                    if (clsDict.HasKey("__assembly__") || clsDict.HasKey("__namespace__"))
                    {
                        return TypeManager.CreateSubType(name, base_type, dict);
                    }
                }
            }

            // otherwise just create a basic type without reflecting back into the managed side.
            IntPtr func = Marshal.ReadIntPtr(Runtime.PyTypeType, TypeOffset.tp_new);
            IntPtr type = NativeCall.Call_3(func, tp, args, kw);
            if (type == IntPtr.Zero)
            {
                return IntPtr.Zero;
            }

            int flags = TypeFlags.Default;
            flags |= TypeFlags.Managed;
            flags |= TypeFlags.HeapType;
            flags |= TypeFlags.BaseType;
            flags |= TypeFlags.Subclass;
            flags |= TypeFlags.HaveGC;
            Util.WriteCLong(type, TypeOffset.tp_flags, flags);

            TypeManager.CopySlot(base_type, type, TypeOffset.tp_dealloc);

            // Hmm - the standard subtype_traverse, clear look at ob_size to
            // do things, so to allow gc to work correctly we need to move
            // our hidden handle out of ob_size. Then, in theory we can
            // comment this out and still not crash.
            TypeManager.CopySlot(base_type, type, TypeOffset.tp_traverse);
            TypeManager.CopySlot(base_type, type, TypeOffset.tp_clear);

            // for now, move up hidden handle...
            IntPtr gc = Marshal.ReadIntPtr(base_type, TypeOffset.magic());
            Marshal.WriteIntPtr(type, TypeOffset.magic(), gc);

            return type;
        }

        public static IntPtr tp_alloc(IntPtr mt, int n)
        {
            IntPtr type = Runtime.PyType_GenericAlloc(mt, n);
            return type;
        }

        public static void tp_free(IntPtr tp)
        {
            Runtime.PyObject_GC_Del(tp);
        }

        /// <summary>
        /// Metatype __call__ implementation. This is needed to ensure correct
        /// initialization (__init__ support), because the tp_call we inherit
        /// from PyType_Type won't call __init__ for metatypes it doesn't know.
        /// </summary>
        public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw)
        {
            IntPtr func = Marshal.ReadIntPtr(tp, TypeOffset.tp_new);
            if (func == IntPtr.Zero)
            {
                return Exceptions.RaiseTypeError("invalid object");
            }

            IntPtr obj = NativeCall.Call_3(func, tp, args, kw);
            if (obj == IntPtr.Zero)
            {
                return IntPtr.Zero;
            }

            var init = Runtime.PyObject_GetAttr(obj, PyIdentifier.__init__);
            Runtime.PyErr_Clear();

            if (init != IntPtr.Zero)
            {
                IntPtr result = Runtime.PyObject_Call(init, args, kw);
                Runtime.XDecref(init);

                if (result == IntPtr.Zero)
                {
                    Runtime.XDecref(obj);
                    return IntPtr.Zero;
                }

                Runtime.XDecref(result);
            }

            return obj;
        }

        /// <summary>
        /// Type __setattr__ implementation for reflected types. Note that this
        /// is slightly different than the standard setattr implementation for
        /// the normal Python metatype (PyTypeType). We need to look first in
        /// the type object of a reflected type for a descriptor in order to
        /// support the right setattr behavior for static fields and properties.
        /// </summary>
        public static int tp_setattro(IntPtr tp, IntPtr name, IntPtr value)
        {
            IntPtr descr = Runtime._PyType_Lookup(tp, name);

            if (descr != IntPtr.Zero)
            {
                IntPtr dt = Runtime.PyObject_TYPE(descr);

                if (dt == Runtime.PyWrapperDescriptorType
                    || dt == Runtime.PyMethodType
                    || typeof(ExtensionType).IsInstanceOfType(GetManagedObject(descr))
                )
                {
                    IntPtr fp = Marshal.ReadIntPtr(dt, TypeOffset.tp_descr_set);
                    if (fp != IntPtr.Zero)
                    {
                        return NativeCall.Int_Call_3(fp, descr, name, value);
                    }
                    Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only");
                    return -1;
                }
            }

            int res = Runtime.PyObject_GenericSetAttr(tp, name, value);
            Runtime.PyType_Modified(tp);

            return res;
        }

        /// <summary>
        /// The metatype has to implement [] semantics for generic types, so
        /// here we just delegate to the generic type def implementation. Its
        /// own mp_subscript
        /// </summary>
        public static IntPtr mp_subscript(IntPtr tp, IntPtr idx)
        {
            var cb = GetManagedObject(tp) as ClassBase;
            if (cb != null)
            {
                return cb.type_subscript(idx);
            }
            return Exceptions.RaiseTypeError("unsubscriptable object");
        }

        /// <summary>
        /// Dealloc implementation. This is called when a Python type generated
        /// by this metatype is no longer referenced from the Python runtime.
        /// </summary>
        public static void tp_dealloc(IntPtr tp)
        {
            // Fix this when we dont cheat on the handle for subclasses!

            var flags = Util.ReadCLong(tp, TypeOffset.tp_flags);
            if ((flags & TypeFlags.Subclass) == 0)
            {
                IntPtr gc = Marshal.ReadIntPtr(tp, TypeOffset.magic());
                ((GCHandle)gc).Free();
            }

            IntPtr op = Marshal.ReadIntPtr(tp, TypeOffset.ob_type);
            Runtime.XDecref(op);

            // Delegate the rest of finalization the Python metatype. Note
            // that the PyType_Type implementation of tp_dealloc will call
            // tp_free on the type of the type being deallocated - in this
            // case our CLR metatype. That is why we implement tp_free.

            op = Marshal.ReadIntPtr(Runtime.PyTypeType, TypeOffset.tp_dealloc);
            NativeCall.Void_Call_1(op, tp);
        }

        private static IntPtr DoInstanceCheck(IntPtr tp, IntPtr args, bool checkType)
        {
            var cb = GetManagedObject(tp) as ClassBase;

            if (cb == null || !cb.type.Valid)
            {
                Runtime.XIncref(Runtime.PyFalse);
                return Runtime.PyFalse;
            }

            Runtime.XIncref(args);
            using (var argsObj = new PyList(args))
            {
                if (argsObj.Length() != 1)
                {
                    return Exceptions.RaiseTypeError("Invalid parameter count");
                }

                PyObject arg = argsObj[0];
                PyObject otherType;
                if (checkType)
                {
                    otherType = arg;
                }
                else
                {
                    otherType = arg.GetPythonType();
                }

                if (Runtime.PyObject_TYPE(otherType.Handle) != PyCLRMetaType)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return Runtime.PyFalse;
                }

                var otherCb = GetManagedObject(otherType.Handle) as ClassBase;
                if (otherCb == null || !otherCb.type.Valid)
                {
                    Runtime.XIncref(Runtime.PyFalse);
                    return Runtime.PyFalse;
                }

                return Converter.ToPython(cb.type.Value.IsAssignableFrom(otherCb.type.Value));
            }
        }

        public static IntPtr __instancecheck__(IntPtr tp, IntPtr args)
        {
            return DoInstanceCheck(tp, args, false);
        }

        public static IntPtr __subclasscheck__(IntPtr tp, IntPtr args)
        {
            return DoInstanceCheck(tp, args, true);
        }
    }
}


text:
namespace {

// static
std::unique_ptr<syncer::DeviceInfo> CloneDeviceInfo(
    const syncer::DeviceInfo& device_info) {
  return std::make_unique<syncer::DeviceInfo>(
      device_info.guid(), device_info.client_name(),
      device_info.chrome_version(), device_info.sync_user_agent(),
      device_info.device_type(), device_info.signin_scoped_device_id(),
      device_info.manufacturer_name(), device_info.model_name(),
      device_info.full_hardware_class(), device_info.last_updated_timestamp(),
      device_info.pulse_interval(),
      device_info.send_tab_to_self_receiving_enabled(),
      device_info.sharing_info(), device_info.paask_info(),
      device_info.fcm_registration_token(),
      device_info.interested_data_types());
}

}  // namespace

namespace syncer {

FakeDeviceInfoTracker::FakeDeviceInfoTracker() = default;

FakeDeviceInfoTracker::~FakeDeviceInfoTracker() = default;

bool FakeDeviceInfoTracker::IsSyncing() const {
  return !devices_.empty();
}

std::unique_ptr<DeviceInfo> FakeDeviceInfoTracker::GetDeviceInfo(
    const std::string& client_id) const {
  for (const DeviceInfo* device : devices_) {
    if (device->guid() == client_id) {
      return CloneDeviceInfo(*device);
    }
  }
  return nullptr;
}

std::vector<std::unique_ptr<DeviceInfo>>
FakeDeviceInfoTracker::GetAllDeviceInfo() const {
  std::vector<std::unique_ptr<DeviceInfo>> list;

  for (const DeviceInfo* device : devices_)
    list.push_back(CloneDeviceInfo(*device));

  return list;
}

void FakeDeviceInfoTracker::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void FakeDeviceInfoTracker::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

std::map<sync_pb::SyncEnums_DeviceType, int>
FakeDeviceInfoTracker::CountActiveDevicesByType() const {
  if (device_count_per_type_override_)
    return *device_count_per_type_override_;

  std::map<sync_pb::SyncEnums_DeviceType, int> count_by_type;
  for (const auto* device : devices_)
    count_by_type[device->device_type()]++;
  return count_by_type;
}

void FakeDeviceInfoTracker::ForcePulseForTest() {
  NOTREACHED();
}

bool FakeDeviceInfoTracker::IsRecentLocalCacheGuid(
    const std::string& cache_guid) const {
  return local_device_cache_guid_ == cache_guid;
}

void FakeDeviceInfoTracker::Add(const DeviceInfo* device) {
  devices_.push_back(device);
  for (auto& observer : observers_)
    observer.OnDeviceInfoChange();
}

void FakeDeviceInfoTracker::Replace(const DeviceInfo* old_device,
                                    const DeviceInfo* new_device) {
  std::vector<const DeviceInfo*>::iterator it =
      std::find(devices_.begin(), devices_.end(), old_device);
  DCHECK(devices_.end() != it) << "Tracker doesn't contain device";
  *it = new_device;
  for (auto& observer : observers_)
    observer.OnDeviceInfoChange();
}

void FakeDeviceInfoTracker::OverrideActiveDeviceCount(
    const std::map<sync_pb::SyncEnums_DeviceType, int>& counts) {
  device_count_per_type_override_ = counts;
  for (auto& observer : observers_)
    observer.OnDeviceInfoChange();
}

void FakeDeviceInfoTracker::SetLocalCacheGuid(const std::string& cache_guid) {
  // ensure that this cache guid is present in the tracker.
  DCHECK(GetDeviceInfo(cache_guid));
  local_device_cache_guid_ = cache_guid;
}

}  // namespace syncer