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

	<!--
	<xsd:schema xmlns="http://www.springframework.org/schema/mvc" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:tool="http://www.springframework.org/schema/tool" targetNamespace="http://www.springframework.org/schema/mvc" elementFormDefault="qualified" attributeFormDefault="unqualified">
		<xsd:import namespace="http://www.springframework.org/schema/beans" schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"/>
		<xsd:import namespace="http://www.springframework.org/schema/tool" schemaLocation="http://www.springframework.org/schema/tool/spring-tool-4.1.xsd"/>
		<xsd:element name="annotation-driven">...</xsd:element>
		<xsd:complexType name="content-version-strategy">...</xsd:complexType>
		<xsd:complexType name="fixed-version-strategy">...</xsd:complexType>
		<xsd:complexType name="resource-version-strategy">...</xsd:complexType>
		<xsd:complexType name="version-resolver">...</xsd:complexType>
		<xsd:complexType name="resource-resolvers">...</xsd:complexType>
		<xsd:complexType name="resource-transformers">...</xsd:complexType>
		<xsd:complexType name="resource-chain">...</xsd:complexType>
		<xsd:element name="resources">...</xsd:element>
		<xsd:element name="default-servlet-handler">...</xsd:element>
		<xsd:element name="interceptors">...</xsd:element>
		<xsd:element name="view-controller">...</xsd:element>
		<xsd:element name="redirect-view-controller">...</xsd:element>
		<xsd:element name="status-controller">...</xsd:element>
		<xsd:complexType name="contentNegotiationType">...</xsd:complexType>
		<xsd:complexType name="urlViewResolverType">...</xsd:complexType>
		<xsd:element name="view-resolvers">
		<xsd:annotation>
		<xsd:documentation>
		<![CDATA[
		Configure a chain of ViewResolver instances to resolve view names returned from controllers into actual view instances to use for rendering. All registered resolvers are wrapped in a single (composite) ViewResolver with its order property set to 0 so that other external resolvers may be ordered before or after it. When content negotiation is enabled the order property is set to highest priority instead with the ContentNegotiatingViewResolver encapsulating all other registered view resolver instances. That way the resolvers registered through the MVC namespace form self-encapsulated resolver chain.
		]]>
		</xsd:documentation>
		</xsd:annotation>
		<xsd:complexType>
		<xsd:choice minOccurs="1" maxOccurs="unbounded">
		<xsd:element name="content-negotiation" type="contentNegotiationType">...</xsd:element>
		<xsd:element name="jsp" type="urlViewResolverType">...</xsd:element>
		<xsd:element name="tiles" type="urlViewResolverType">...</xsd:element>
		<xsd:element name="freemarker" type="urlViewResolverType">...</xsd:element>
		<xsd:element name="velocity" type="urlViewResolverType">...</xsd:element>
		<xsd:element name="groovy" type="urlViewResolverType">...</xsd:element>
		<xsd:element name="bean-name" maxOccurs="1">...</xsd:element>
		<xsd:element ref="beans:bean">...</xsd:element>
		<xsd:element ref="beans:ref">...</xsd:element>
		</xsd:choice>
		<xsd:attribute name="order" type="xsd:int">...</xsd:attribute>
		</xsd:complexType>
		</xsd:element>
		<xsd:element name="tiles-configurer">...</xsd:element>
		<xsd:element name="freemarker-configurer">...</xsd:element>
		<xsd:element name="velocity-configurer">...</xsd:element>
		<xsd:element name="groovy-configurer">...</xsd:element>
	</xsd:schema>

	 -->

	<!-- 如果当前请求为"/"时,则转发到"/helloworld/index"。
	<mvc:view-controller path="/" view-name="forward:/helloworld/index"/> -->

	<!-- 静态资源映射 -->
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="/js/**" location="/js/" />

	<!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 -->
	<mvc:default-servlet-handler />

	<!--开启mvc:annotation-driven支持,它是为了简化配置的缩写形式,它相当于启用以下3个<bean>配置:
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver"/>
	从spring mvc 3.1起,对应变更为
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
	<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"/>

	原DefaultAnnotationHandlerMapping、AnnotationMethodHandlerAdapter和AnnotationMethodHandlerExceptionResolver已过时。
	这些创建过程在org.springframework.web.servlet.DispatcherServlet类initStrategies方法初始化,如下:

	protected void initStrategies(ApplicationContext context) {
		initMultipartResolver(context);
		initLocaleResolver(context);
		initThemeResolver(context);
		initHandlerMappings(context);
		initHandlerAdapters(context);
		initHandlerExceptionResolvers(context);
		initRequestToViewNameTranslator(context);
		initViewResolvers(context);
		initFlashMapManager(context);
	}

	关于mvc:annotation-driven究竟做了什么,查看spring-webmvc-4.1.5.RELEASE.jar下/META-INF/spring.handlers内容如下:
	http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
	表明所有以mvc开头的标签使用MvcNamespaceHandler类来处理,再查看MvcNamespaceHandler类有如下方法:
		@Override
		public void init() {
			registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
			registerBeanDefinitionParser("default-servlet-handler", new DefaultServletHandlerBeanDefinitionParser());
			registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser());
			registerBeanDefinitionParser("resources", new ResourcesBeanDefinitionParser());
			registerBeanDefinitionParser("view-controller", new ViewControllerBeanDefinitionParser());
			registerBeanDefinitionParser("redirect-view-controller", new ViewControllerBeanDefinitionParser());
			registerBeanDefinitionParser("status-controller", new ViewControllerBeanDefinitionParser());
			registerBeanDefinitionParser("view-resolvers", new ViewResolversBeanDefinitionParser());
			registerBeanDefinitionParser("tiles-configurer", new TilesConfigurerBeanDefinitionParser());
			registerBeanDefinitionParser("freemarker-configurer", new FreeMarkerConfigurerBeanDefinitionParser());
			registerBeanDefinitionParser("velocity-configurer", new VelocityConfigurerBeanDefinitionParser());
			registerBeanDefinitionParser("groovy-configurer", new GroovyMarkupConfigurerBeanDefinitionParser());
		}

	当然,如果不使用<mvc:annotation-driven/>也可以直接在配置文件使用<bean>定义相应的元素,例如:
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" p:ignoreDefaultModelOnRedirect="true" >
   		<property name="messageConverters">
       		<list>
       		<ref bean="byteArray_hmc" />
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                   <list>
                       <value>text/plain;charset=UTF-8</value>
                       <value>text/html;charset=UTF-8</value>
                       <value>application/json;charset=UTF-8</value>
                   </list>
                </property>
             </bean>
             <ref bean="resource_hmc" />
             <ref bean="source_hmc" />
             <ref bean="xmlAwareForm_hmc" />
             <ref bean="jaxb2RootElement_hmc" />
             <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
       		</list>
   		</property>
	</bean>
    <bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
    <bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter" />
    <bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
    <bean id="xmlAwareForm_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
    <bean id="jaxb2RootElement_hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />

    <bean id="handlerExceptionResolver" class="com.pss.res.base.exceptionresolver.AnnotationHandlerMethodExceptionResolver">
        <property name="defaultErrorView" value="error/500"/>
        <property name="messageConverters">
            <list>
                <bean	class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                <bean	class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
	 -->

	<mvc:annotation-driven conversion-service="conversionService">
	    <!-- mvc:annotation-driven可选属性
	    	conversion-service="conversionService"  validator="validator"
	    	message-codes-resolver="bean ref" content-negotiation-manager="contentNegotiationManager"
	    	enable-matrix-variables="true" ignore-default-model-on-redirect="false"-->
		<!--
		<mvc:return-value-handlers>
	        <bean></bean>
	    </mvc:return-value-handlers>

	    <mvc:argument-resolvers>
    	</mvc:argument-resolvers>

    	<mvc:path-matching/>
    	<mvc:async-support/>
    	-->

		<!--
		<mvc:message-converters register-defaults="true">
		   	<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter "/>
			<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"
			p:supportedMediaTypes="*"/>
		 </mvc:message-converters>
		  -->
	</mvc:annotation-driven>

	<!-- web表单输入校验器,目前使用的实现是-->
	<!--
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.3.Final</version>
		</dependency>

	<bean
		class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
		<property name="validator" ref="validator" />
	</bean>

	<bean id="validator"
		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
		<property name="validationMessageSource" ref="messageSource" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>classpath:messages</value>
				<value>classpath:org/hibernate/validator/ValidationMessages</value>
			</list>
		</property>
		<property name="useCodeAsDefaultMessage" value="false" />
		<property name="defaultEncoding" value="UTF-8" />
		<property name="cacheSeconds" value="60" />
	</bean>
 	-->

 	<!--  -->
	<bean id="contentNegotiationManager3518" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<property name="favorPathExtension" value="false" />
		<property name="favorParameter" value="false" />
		<property name="ignoreAcceptHeader" value="true" />
<!-- 		<property name="parameterName" value="format" /> -->
		<property name="mediaTypes">
			<map>
		        <entry key="plain" value="text/plain;charset=utf-8"/>
		        <entry key="html" value="text/html;charset=utf-8"/>
		        <entry key="json" value="application/json;charset=utf-8"/>
		        <entry key="xml" value="application/xml;charset=utf-8"/>
      		</map>
		</property>
<!-- 		<property name="defaultContentType" value="text/html" /> -->
		<property name="defaultContentType" value="application/json" />
	</bean>

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="0" />
        <property name="contentNegotiationManager" ref="contentNegotiationManager3518"/>
        <property name="defaultViews">
            <list>
            	<!--
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                    <property name="prettyPrint" value="true"/>
                    <property name="extractValueFromSingleKeyModel" value="true"/>
                    <property name="contentType" value="text/plain"/>
                    <property name="jsonpParameterNames">
            			<set>
                			<value>jsonp</value>
               				<value>callback</value>
            			</set>
       				</property>
                </bean>
                  -->
                <!-- 还可以自己扩展view
                <bean class="org.springlearning.views.MappingJacksonJson2ViewExd" />
                -->
                <!--
           		<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <constructor-arg>
                        <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                            <property name="packagesToScan">
                                <list>
                                    <value>com.sample.model.your.packageToScan</value>
                                </list>
                            </property>
                        </bean>
                    </constructor-arg>
                </bean>
                 -->
            </list>
        </property>
		<property name="viewResolvers"><!-- 针对freemarker的视图配置 -->
            <list>
<!--                 <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
                    <property name="viewNames" value=".ftl"/>
                    <property name="contentType" value="text/html; charset=utf-8"/>
                    <property name="cache" value="true" />
                    <property name="prefix" value="" />
                    <property name="suffix" value=".ftl" />
                    <property name="order" value="2"/>
                </bean>  -->
                <!--<bean id="liteDeviceDelegatingViewResolver" class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">-->
                    <!--<constructor-arg>-->
                        <!--<bean-->
                                <!--class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">-->
                            <!--<property name="cache" value="true"/>-->
                            <!--<property name="requestContextAttribute" value="rc"/>-->
                            <!--<property name="prefix" value=""/>-->
                            <!--<property name="suffix" value=".ftl"/>-->
                            <!--<property name="exposeSpringMacroHelpers" value="true"/>-->
                            <!--<property name="exposeRequestAttributes" value="true"/>-->
                            <!--<property name="exposeSessionAttributes" value="true"/>-->
                            <!--<property name="contentType" value="text/html;charset=UTF-8"/>-->
                        <!--</bean>-->
                    <!--</constructor-arg>-->

                    <!--<property name="mobilePrefix" value="mobile/" />-->
                    <!--<property name="tabletPrefix" value="tablet/" />-->
                    <!--<property name="enableFallback" value="true" />-->
                <!--</bean>-->
                <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
					<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
					<property name="prefix" value="/WEB-INF/viewws/" />
					<property name="suffix" value=".jsp" />
				</bean>
            </list>
        </property>
    </bean>

    <!--
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                	告诉视图解析器,返回的类型为json格式
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                 ModelAndView里的数据变成JSON
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
    </bean>
    -->

	<!--
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsps/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    -->

    <!-- Resolve jsp's -->
<!-- 	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean> -->
	<!--
	<bean id="jacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
	 -->
<!-- 	<bean id="jackson2JsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
	 -->

	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    	<property name="converters">
      		<set>
        		<bean class="org.springlearning.converters.UserLevelEnumConverter" />
      		</set>
    	</property>
  	</bean>

	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
		<property name="cookieName" value="cloc" />
		<property name="cookieMaxAge" value="-1" />
		<!-- <property name="defaultLocale" value="en_US"/> -->
	</bean>

	<!--
	<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
		<property name="order" value="1" />
	</bean>

	<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"/>
	<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
	-->

	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10000000" />
	</bean>

	<!--
	Spring为我们提供了:
		org.springframework.web.servlet.HandlerInterceptor接口和
		org.springframework.web.servlet.handler.HandlerInterceptorAdapter适配器,
	实现这个接口或继承此类,可以非常方便的实现自己的拦截器。
	-->
	<!--
	<mvc:interceptors>
	  <mvc:interceptor>
	        <mvc:mapping path="/user/*" />
	        <bean class="com.mvc.MyInteceptor"></bean>
	    </mvc:interceptor>
	</mvc:interceptors>
	-->

	<aop:aspectj-autoproxy proxy-target-class="true" />

</beans>


text:
FactoryGirl.define do
  factory :ingredient do
    name "Whiskey"
    ingredient_type "Spirit"
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.assertj.core.error;

import java.util.Iterator;

/**
 * Creates an error message indicating that an assertion that verifies that an {@link Iterator} has a next element
 * failed.
 *
 * @author Stephan Windmüller
 */
public class ShouldHaveNext extends BasicErrorMessageFactory {

  private static final String SHOULD_HAVE_NEXT = "%nExpecting the iterator under test to contain another value but did not.";

  /**
   * Creates a new <code>{@link ShouldHaveNext}</code>.
   *
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldHaveNext() {
    return new ShouldHaveNext();
  }

  private ShouldHaveNext() {
    super(SHOULD_HAVE_NEXT);
  }

}


text:
namespace boost {

struct square_distance_attractive_force {
  template<typename Graph, typename T>
  T
  operator()(typename graph_traits<Graph>::edge_descriptor,
             T k,
             T d,
             const Graph&) const
  {
    return d * d / k;
  }
};

struct square_distance_repulsive_force {
  template<typename Graph, typename T>
  T
  operator()(typename graph_traits<Graph>::vertex_descriptor,
             typename graph_traits<Graph>::vertex_descriptor,
             T k,
             T d,
             const Graph&) const
  {
    return k * k / d;
  }
};

template<typename T>
struct linear_cooling {
  typedef T result_type;

  linear_cooling(std::size_t iterations)
    : temp(T(iterations) / T(10)), step(0.1) { }

  linear_cooling(std::size_t iterations, T temp)
    : temp(temp), step(temp / T(iterations)) { }

  T operator()()
  {
    T old_temp = temp;
    temp -= step;
    if (temp < T(0)) temp = T(0);
    return old_temp;
  }

 private:
  T temp;
  T step;
};

struct all_force_pairs
{
  template<typename Graph, typename ApplyForce >
  void operator()(const Graph& g, ApplyForce apply_force)
  {
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
    vertex_iterator v, end;
    for (boost::tie(v, end) = vertices(g); v != end; ++v) {
      vertex_iterator u = v;
      for (++u; u != end; ++u) {
        apply_force(*u, *v);
        apply_force(*v, *u);
      }
    }
  }
};

template<typename Topology, typename PositionMap>
struct grid_force_pairs
{
  typedef typename property_traits<PositionMap>::value_type Point;
  BOOST_STATIC_ASSERT (Point::dimensions == 2);
  typedef typename Topology::point_difference_type point_difference_type;

  template<typename Graph>
  explicit
  grid_force_pairs(const Topology& topology,
                   PositionMap position, const Graph& g)
    : topology(topology), position(position)
  {
    two_k = 2. * this->topology.volume(this->topology.extent()) / std::sqrt((double)num_vertices(g));
  }

  template<typename Graph, typename ApplyForce >
  void operator()(const Graph& g, ApplyForce apply_force)
  {
    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef std::list<vertex_descriptor> bucket_t;
    typedef std::vector<bucket_t> buckets_t;

    std::size_t columns = std::size_t(topology.extent()[0] / two_k + 1.);
    std::size_t rows = std::size_t(topology.extent()[1] / two_k + 1.);
    buckets_t buckets(rows * columns);
    vertex_iterator v, v_end;
    for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {
      std::size_t column =
        std::size_t((get(position, *v)[0] + topology.extent()[0] / 2) / two_k);
      std::size_t row    =
        std::size_t((get(position, *v)[1] + topology.extent()[1] / 2) / two_k);

      if (column >= columns) column = columns - 1;
      if (row >= rows) row = rows - 1;
      buckets[row * columns + column].push_back(*v);
    }

    for (std::size_t row = 0; row < rows; ++row)
      for (std::size_t column = 0; column < columns; ++column) {
        bucket_t& bucket = buckets[row * columns + column];
        typedef typename bucket_t::iterator bucket_iterator;
        for (bucket_iterator u = bucket.begin(); u != bucket.end(); ++u) {
          // Repulse vertices in this bucket
          bucket_iterator v = u;
          for (++v; v != bucket.end(); ++v) {
            apply_force(*u, *v);
            apply_force(*v, *u);
          }

          std::size_t adj_start_row = row == 0? 0 : row - 1;
          std::size_t adj_end_row = row == rows - 1? row : row + 1;
          std::size_t adj_start_column = column == 0? 0 : column - 1;
          std::size_t adj_end_column = column == columns - 1? column : column + 1;
          for (std::size_t other_row = adj_start_row; other_row <= adj_end_row;
               ++other_row)
            for (std::size_t other_column = adj_start_column;
                 other_column <= adj_end_column; ++other_column)
              if (other_row != row || other_column != column) {
                // Repulse vertices in this bucket
                bucket_t& other_bucket
                  = buckets[other_row * columns + other_column];
                for (v = other_bucket.begin(); v != other_bucket.end(); ++v) {
                  double dist =
                    topology.distance(get(position, *u), get(position, *v));
                  if (dist < two_k) apply_force(*u, *v);
                }
              }
        }
      }
  }

 private:
  const Topology& topology;
  PositionMap position;
  double two_k;
};

template<typename PositionMap, typename Topology, typename Graph>
inline grid_force_pairs<Topology, PositionMap>
make_grid_force_pairs
  (const Topology& topology,
   const PositionMap& position, const Graph& g)
{ return grid_force_pairs<Topology, PositionMap>(topology, position, g); }

template<typename Graph, typename PositionMap, typename Topology>
void
scale_graph(const Graph& g, PositionMap position, const Topology& topology,
            typename Topology::point_type upper_left, typename Topology::point_type lower_right)
{
  if (num_vertices(g) == 0) return;

  typedef typename Topology::point_type Point;
  typedef typename Topology::point_difference_type point_difference_type;

  // Find min/max ranges
  Point min_point = get(position, *vertices(g).first), max_point = min_point;
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    min_point = topology.pointwise_min(min_point, get(position, v));
    max_point = topology.pointwise_max(max_point, get(position, v));
  }

  Point old_origin = topology.move_position_toward(min_point, 0.5, max_point);
  Point new_origin = topology.move_position_toward(upper_left, 0.5, lower_right);
  point_difference_type old_size = topology.difference(max_point, min_point);
  point_difference_type new_size = topology.difference(lower_right, upper_left);

  // Scale to bounding box provided
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    point_difference_type relative_loc = topology.difference(get(position, v), old_origin);
    relative_loc = (relative_loc / old_size) * new_size;
    put(position, v, topology.adjust(new_origin, relative_loc));
  }
}

namespace detail {
  template<typename Topology, typename PropMap, typename Vertex>
  void
  maybe_jitter_point(const Topology& topology,
                     const PropMap& pm, Vertex v,
                     const typename Topology::point_type& p2)
  {
    double too_close = topology.norm(topology.extent()) / 10000.;
    if (topology.distance(get(pm, v), p2) < too_close) {
      put(pm, v,
          topology.move_position_toward(get(pm, v), 1./200,
                                        topology.random_point()));
    }
  }

  template<typename Topology, typename PositionMap, typename DisplacementMap,
           typename RepulsiveForce, typename Graph>
  struct fr_apply_force
  {
    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
    typedef typename Topology::point_type Point;
    typedef typename Topology::point_difference_type PointDiff;

    fr_apply_force(const Topology& topology,
                   const PositionMap& position,
                   const DisplacementMap& displacement,
                   RepulsiveForce repulsive_force, double k, const Graph& g)
      : topology(topology), position(position), displacement(displacement),
        repulsive_force(repulsive_force), k(k), g(g)
    { }

    void operator()(vertex_descriptor u, vertex_descriptor v)
    {
      if (u != v) {
        // When the vertices land on top of each other, move the
        // first vertex away from the boundaries.
        maybe_jitter_point(topology, position, u, get(position, v));

        double dist = topology.distance(get(position, u), get(position, v));
        typename Topology::point_difference_type dispv = get(displacement, v);
        if (dist == 0.) {
          for (std::size_t i = 0; i < Point::dimensions; ++i) {
            dispv[i] += 0.01;
          }
        } else {
          double fr = repulsive_force(u, v, k, dist, g);
          dispv += (fr / dist) *
                   topology.difference(get(position, v), get(position, u));
        }
        put(displacement, v, dispv);
      }
    }

  private:
    const Topology& topology;
    PositionMap position;
    DisplacementMap displacement;
    RepulsiveForce repulsive_force;
    double k;
    const Graph& g;
  };

} // end namespace detail

template<typename Topology, typename Graph, typename PositionMap,
         typename AttractiveForce, typename RepulsiveForce,
         typename ForcePairs, typename Cooling, typename DisplacementMap>
void
fruchterman_reingold_force_directed_layout
 (const Graph&    g,
  PositionMap     position,
  const Topology& topology,
  AttractiveForce attractive_force,
  RepulsiveForce  repulsive_force,
  ForcePairs      force_pairs,
  Cooling         cool,
  DisplacementMap displacement)
{
  typedef typename graph_traits<Graph>::vertex_iterator   vertex_iterator;
  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits<Graph>::edge_iterator     edge_iterator;

  double volume = topology.volume(topology.extent());

  // assume positions are initialized randomly
  double k = pow(volume / num_vertices(g), 1. / (double)(Topology::point_difference_type::dimensions));

  detail::fr_apply_force<Topology, PositionMap, DisplacementMap,
                         RepulsiveForce, Graph>
    apply_force(topology, position, displacement, repulsive_force, k, g);

  do {
    // Calculate repulsive forces
    vertex_iterator v, v_end;
    for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v)
      put(displacement, *v, typename Topology::point_difference_type());
    force_pairs(g, apply_force);

    // Calculate attractive forces
    edge_iterator e, e_end;
    for (boost::tie(e, e_end) = edges(g); e != e_end; ++e) {
      vertex_descriptor v = source(*e, g);
      vertex_descriptor u = target(*e, g);

      // When the vertices land on top of each other, move the
      // first vertex away from the boundaries.
      ::boost::detail::maybe_jitter_point(topology, position, u, get(position, v));

      typename Topology::point_difference_type delta =
        topology.difference(get(position, v), get(position, u));
      double dist = topology.distance(get(position, u), get(position, v));
      double fa = attractive_force(*e, k, dist, g);

      put(displacement, v, get(displacement, v) - (fa / dist) * delta);
      put(displacement, u, get(displacement, u) + (fa / dist) * delta);
    }

    if (double temp = cool()) {
      // Update positions
      BGL_FORALL_VERTICES_T (v, g, Graph) {
        BOOST_USING_STD_MIN();
        BOOST_USING_STD_MAX();
        double disp_size = topology.norm(get(displacement, v));
        put(position, v, topology.adjust(get(position, v), get(displacement, v) * (min BOOST_PREVENT_MACRO_SUBSTITUTION (disp_size, temp) / disp_size)));
        put(position, v, topology.bound(get(position, v)));
      }
    } else {
      break;
    }
  } while (true);
}

namespace detail {
  template<typename DisplacementMap>
  struct fr_force_directed_layout
  {
    template<typename Topology, typename Graph, typename PositionMap,
             typename AttractiveForce, typename RepulsiveForce,
             typename ForcePairs, typename Cooling,
             typename Param, typename Tag, typename Rest>
    static void
    run(const Graph&    g,
        PositionMap     position,
        const Topology& topology,
        AttractiveForce attractive_force,
        RepulsiveForce  repulsive_force,
        ForcePairs      force_pairs,
        Cooling         cool,
        DisplacementMap displacement,
        const bgl_named_params<Param, Tag, Rest>&)
    {
      fruchterman_reingold_force_directed_layout
        (g, position, topology, attractive_force, repulsive_force,
         force_pairs, cool, displacement);
    }
  };

  template<>
  struct fr_force_directed_layout<param_not_found>
  {
    template<typename Topology, typename Graph, typename PositionMap,
             typename AttractiveForce, typename RepulsiveForce,
             typename ForcePairs, typename Cooling,
             typename Param, typename Tag, typename Rest>
    static void
    run(const Graph&    g,
        PositionMap     position,
        const Topology& topology,
        AttractiveForce attractive_force,
        RepulsiveForce  repulsive_force,
        ForcePairs      force_pairs,
        Cooling         cool,
        param_not_found,
        const bgl_named_params<Param, Tag, Rest>& params)
    {
      typedef typename Topology::point_difference_type PointDiff;
      std::vector<PointDiff> displacements(num_vertices(g));
      fruchterman_reingold_force_directed_layout
        (g, position, topology, attractive_force, repulsive_force,
         force_pairs, cool,
         make_iterator_property_map
         (displacements.begin(),
          choose_const_pmap(get_param(params, vertex_index), g,
                            vertex_index),
          PointDiff()));
    }
  };

} // end namespace detail

template<typename Topology, typename Graph, typename PositionMap, typename Param,
         typename Tag, typename Rest>
void
fruchterman_reingold_force_directed_layout
  (const Graph&    g,
   PositionMap     position,
   const Topology& topology,
   const bgl_named_params<Param, Tag, Rest>& params)
{
  typedef typename get_param_type<vertex_displacement_t, bgl_named_params<Param,Tag,Rest> >::type D;

  detail::fr_force_directed_layout<D>::run
    (g, position, topology,
     choose_param(get_param(params, attractive_force_t()),
                  square_distance_attractive_force()),
     choose_param(get_param(params, repulsive_force_t()),
                  square_distance_repulsive_force()),
     choose_param(get_param(params, force_pairs_t()),
                  make_grid_force_pairs(topology, position, g)),
     choose_param(get_param(params, cooling_t()),
                  linear_cooling<double>(100)),
     get_param(params, vertex_displacement_t()),
     params);
}

template<typename Topology, typename Graph, typename PositionMap>
void
fruchterman_reingold_force_directed_layout
  (const Graph&    g,
   PositionMap     position,
   const Topology& topology)
{
  fruchterman_reingold_force_directed_layout
    (g, position, topology,
     attractive_force(square_distance_attractive_force()));
}

} // end namespace boost

#include BOOST_GRAPH_MPI_INCLUDE(<boost/graph/distributed/fruchterman_reingold.hpp>)

#endif // BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP


text:
using Cosmos.Core;
using Cosmos.HAL.Audio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cosmos.System.Audio.IO {
    /// <summary>
    /// Represents an audio stream that reads from a byte array in memory.
    /// </summary>
    public class MemoryAudioStream : SeekableAudioStream {
        readonly SampleFormat format;
        readonly uint sampleRate;
        readonly int sampleCount;
        readonly byte[] data;

        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryAudioStream"/> class.
        /// </summary>
        /// <param name="format">The format of the provided audio data.</param>
        /// <param name="data">The audio data.</param>
        public MemoryAudioStream(SampleFormat format, uint sampleRate, byte[] data)
        {
            this.format = format;
            this.sampleRate = sampleRate;
            this.data = data;
            sampleCount = data.Length / format.Size;
        }

        #region Standard AudioStream Members
        public SampleFormat Format
        {
            get => format;
            set
            {
                throw new NotSupportedException("Cannot change the format of a MemoryAudioStream");
            }
        }

        public override uint SampleRate {
            get => sampleRate;
            set => throw new InvalidOperationException("Cannot change the sample rate of a MemoryAudioStream.");
        }

        public override uint Position { get; set; }

        public override uint Length => (uint)sampleCount;

        public override bool Depleted => sampleCount <= Position;
        #endregion

        /// <summary>
        /// Creates a <see cref="MemoryAudioStream"/> from a PCM-encoded WAVE (.wav)
        /// file. The file has to have a valid header.
        /// </summary>
        /// <param name="waveFile">The target wave file.</param>
        public unsafe static MemoryAudioStream FromWave(byte[] waveFile)
        {
            if(!ValidateValues(waveFile, 0, 0x52, 0x49, 0x46, 0x46)) {
                throw new ArgumentException("Invalid WAVE file - expected a RIFF header.", nameof(waveFile));
            }

            // chunkSize at offset 4 of size 4

            if (!ValidateValues(waveFile, 8, 0x57, 0x41, 0x56, 0x45)) {
                throw new ArgumentException("Invalid WAVE file - expected a WAVE format in the RIFF header.", nameof(waveFile));
            }

            if (!ValidateValues(waveFile, 12, 0x66, 0x6D, 0x74, 0x20)) {
                throw new ArgumentException("The first subchunk is expected to be the sample format.", nameof(waveFile));
            }

            // This is usually 16 for standard PCM audio, but some old encoding software will
            // include extra, non-standard metadata entries at the end, changing the size.
            // Normally, this is fine, if the metadata is at the end of the chunk and we can safely ignore it.
            int metadataSize = BitConverter.ToInt32(waveFile, 16);

            if (!ValidateValues(waveFile, 20, 0x01, 0x00)) {
                throw new ArgumentException("WAVE compression is not supported.", nameof(waveFile));
            }

            ushort numChannels = BitConverter.ToUInt16(waveFile, 22);

            if (numChannels > byte.MaxValue) {
                throw new ArgumentException($"The maximum amount of channels for an AudioStream is 255 - the input contains {numChannels}.", nameof(waveFile));
            }

            uint sampleRate = BitConverter.ToUInt32(waveFile, 24);
            // byteRate at offset 28 of size 4
            // blockAlign at offset 32 of size 2
            ushort bitsPerSample = BitConverter.ToUInt16(waveFile, 34);

            var bitDepth = bitsPerSample switch {
                8 => AudioBitDepth.Bits8,
                16 => AudioBitDepth.Bits16,
                24 => AudioBitDepth.Bits24,
                32 => AudioBitDepth.Bits32,
                _ => throw new ArgumentException($"{bitsPerSample}-bit WAVE files are not supported.", nameof(waveFile)),
            };

            // ExtraParamSize and ExtraParams would be here for encodings different than PCM
            int dataStart = 20 + metadataSize;

            if (!ValidateValues(waveFile, dataStart, 0x64, 0x61, 0x74, 0x61)) {
                throw new ArgumentException("Expected a 'data' block");
            }

            uint dataSize = BitConverter.ToUInt32(waveFile, dataStart + 4);
            byte[] data = new byte[dataSize];

            fixed (byte* inputPtr = waveFile, outputPtr = data) {
                MemoryOperations.Copy(outputPtr, inputPtr + dataStart + 8, data.Length);
            }

            SampleFormat format = new(
                bitDepth,
                (byte)numChannels,
                bitDepth != AudioBitDepth.Bits8 // only 8-bit PCM is unsigned
            );

            return new MemoryAudioStream(format, sampleRate, data);
        }

        private static bool ValidateValues(byte[] target, int offset, params byte[] values)
        {
            for (int i = 0; i < values.Length; i++) {
                if(target[i + offset] != values[i]) {
                    return false;
                }
            }

            return true;
        }

        // We cache these values, because the heap allocation for these objects is costly.
        AudioBufferWriter cachedWriter;
        AudioBuffer cachedBuffer;

        public unsafe override void Read(AudioBuffer buffer)
        {
            int samplesLeft = sampleCount - (int)Position;
            int actualCopySize = Math.Min(samplesLeft, buffer.Size);

            if(cachedBuffer != buffer)
            {
                cachedWriter = new(buffer, format);
                cachedBuffer = buffer;
            }

            fixed (byte* dataPtr = data) {
                for (int i = 0; i < actualCopySize; i++) {
                    cachedWriter.Write(dataPtr + (i * format.Size) + (Position * format.Size), i);
                }
            }

            uint delta = ((uint)buffer.Size) / buffer.Format.Channels;

            if (actualCopySize < buffer.Size)
            {
                int start = actualCopySize * buffer.Format.Size;
                int size = buffer.RawData.Length - start;

                // Fill the rest of the buffer with 0s
                fixed (byte* rawDataPtr = buffer.RawData)
                {
                    MemoryOperations.Fill(rawDataPtr + start, 0, size);
                }

                Position = Math.Min(Position + delta, Length);
            }
            else {
                Position += delta;
            }

            ApplyPostProcessing(buffer);
        }
    }
}


text:
'use strict';

module.exports = {
  app: require('./app'),
  response: require('./response')
};


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class FaTasks extends React.Component<IconBaseProps> { }
export = FaTasks;


text:
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <!-- 让国内基于webkit的浏览器默认采用webkit内核进行渲染 -->
        <meta name="renderer" content="webkit" />
        <!-- 移动端的响应式特性 -->
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta content="leetcode,算法,Integer-to-English-Words" name="keywords">
        <meta content="leetcodeJS大法之Integer-to-English-Words" name="description">
        <title>leetcodeJS大法之Integer-to-English-Words</title>
        <link rel="stylesheet" href="../../css/common/reset.css" />
    </head>

    <body>
        <script type="text/javascript" src="Integer-to-English-Words.js"></script>
        <script>

            var result = LeetCode.numberToWords(1234567);

            console.log(JSON.stringify(result));

        </script>
    </body>

</html>


text:
from copy import deepcopy
from typing import Any, TYPE_CHECKING

from msrest import Deserializer, Serializer

from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient

from . import models
from ._configuration import AzureDigitalTwinsManagementClientConfiguration
from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, TimeSeriesDatabaseConnectionsOperations

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from azure.core.credentials import TokenCredential

class AzureDigitalTwinsManagementClient:
    """Azure Digital Twins Client for managing DigitalTwinsInstance.

    :ivar digital_twins: DigitalTwinsOperations operations
    :vartype digital_twins:
     azure.mgmt.digitaltwins.v2021_06_30_preview.operations.DigitalTwinsOperations
    :ivar digital_twins_endpoint: DigitalTwinsEndpointOperations operations
    :vartype digital_twins_endpoint:
     azure.mgmt.digitaltwins.v2021_06_30_preview.operations.DigitalTwinsEndpointOperations
    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.digitaltwins.v2021_06_30_preview.operations.Operations
    :ivar private_link_resources: PrivateLinkResourcesOperations operations
    :vartype private_link_resources:
     azure.mgmt.digitaltwins.v2021_06_30_preview.operations.PrivateLinkResourcesOperations
    :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
    :vartype private_endpoint_connections:
     azure.mgmt.digitaltwins.v2021_06_30_preview.operations.PrivateEndpointConnectionsOperations
    :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations
    :vartype time_series_database_connections:
     azure.mgmt.digitaltwins.v2021_06_30_preview.operations.TimeSeriesDatabaseConnectionsOperations
    :param credential: Credential needed for the client to connect to Azure.
    :type credential: ~azure.core.credentials.TokenCredential
    :param subscription_id: The subscription identifier.
    :type subscription_id: str
    :param base_url: Service URL. Default value is "https://management.azure.com".
    :type base_url: str
    :keyword api_version: Api Version. Default value is "2021-06-30-preview". Note that overriding
     this default value may result in unsupported behavior.
    :paramtype api_version: str
    :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
     Retry-After header is present.
    """

    def __init__(
        self,
        credential: "TokenCredential",
        subscription_id: str,
        base_url: str = "https://management.azure.com",
        **kwargs: Any
    ) -> None:
        self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
        self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)
        self._serialize.client_side_validation = False
        self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize)
        self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize)
        self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
        self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize)
        self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)
        self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations(self._client, self._config, self._serialize, self._deserialize)

    def _send_request(
        self,
        request: HttpRequest,
        **kwargs: Any
    ) -> HttpResponse:
        """Runs the network request through the client's chained policies.

        >>> from azure.core.rest import HttpRequest
        >>> request = HttpRequest("GET", "https://www.example.org/")
        <HttpRequest [GET], url: 'https://www.example.org/'>
        >>> response = client._send_request(request)
        <HttpResponse: 200 OK>

        For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart

        :param request: The network request you want to make. Required.
        :type request: ~azure.core.rest.HttpRequest
        :keyword bool stream: Whether the response payload will be streamed. Defaults to False.
        :return: The response of your network call. Does not do error handling on your response.
        :rtype: ~azure.core.rest.HttpResponse
        """

        request_copy = deepcopy(request)
        request_copy.url = self._client.format_url(request_copy.url)
        return self._client.send_request(request_copy, **kwargs)

    def close(self):
        # type: () -> None
        self._client.close()

    def __enter__(self):
        # type: () -> AzureDigitalTwinsManagementClient
        self._client.__enter__()
        return self

    def __exit__(self, *exc_details):
        # type: (Any) -> None
        self._client.__exit__(*exc_details)


text:
package com.google.gerrit.server.git;

import java.util.ArrayList;
import java.util.List;
import org.eclipse.jgit.lib.ObjectId;

public class BanCommitResult {
  private final List<ObjectId> newlyBannedCommits = new ArrayList<>(4);
  private final List<ObjectId> alreadyBannedCommits = new ArrayList<>(4);
  private final List<ObjectId> ignoredObjectIds = new ArrayList<>(4);

  public void commitBanned(ObjectId commitId) {
    newlyBannedCommits.add(commitId);
  }

  public void commitAlreadyBanned(ObjectId commitId) {
    alreadyBannedCommits.add(commitId);
  }

  public void notACommit(ObjectId id) {
    ignoredObjectIds.add(id);
  }

  public List<ObjectId> getNewlyBannedCommits() {
    return newlyBannedCommits;
  }

  public List<ObjectId> getAlreadyBannedCommits() {
    return alreadyBannedCommits;
  }

  public List<ObjectId> getIgnoredObjectIds() {
    return ignoredObjectIds;
  }
}


text:
package org.hawkular.inventory.rest;

import static org.hawkular.inventory.api.Query.path;
import static org.hawkular.inventory.api.Relationships.WellKnown.contains;
import static org.hawkular.inventory.api.filters.With.id;
import static org.hawkular.inventory.api.filters.With.name;
import static org.hawkular.inventory.api.filters.With.type;
import static org.hawkular.inventory.paths.SegmentType.m;
import static org.hawkular.inventory.paths.SegmentType.r;
import static org.junit.Assert.assertEquals;

import org.hawkular.inventory.api.Query;
import org.hawkular.inventory.api.filters.RecurseFilter;
import org.hawkular.inventory.api.filters.Related;
import org.hawkular.inventory.api.filters.RelationWith;
import org.hawkular.inventory.api.filters.SwitchElementType;
import org.hawkular.inventory.api.filters.With;
import org.hawkular.inventory.api.model.Metric;
import org.hawkular.inventory.api.model.Resource;
import org.hawkular.inventory.api.model.ResourceType;
import org.hawkular.inventory.api.model.Tenant;
import org.hawkular.inventory.paths.CanonicalPath;
import org.hawkular.inventory.paths.SegmentType;
import org.junit.Test;

/**
 * @author Lukas Krejci
 * @since 0.16.0.Final
 */
public class TraverserTest {

    @Test
    public void testStartByRelationship_simpleUri() throws Exception {
        testVariant("/rl;id/relationships", path().with(RelationWith.id("id")).get());
    }

    @Test
    public void testStartByRelationship_ignoredDirectionIfNotNeeded() throws Exception {
        testVariant("/rl;id;in/relationships", path().with(RelationWith.id("id")).get());
    }

    @Test
    public void testStartByRelationship_propertyExistence() throws Exception {
        testVariant("/rl;id;propertyName=kachna/relationships",
                path().with(RelationWith.id("id"), RelationWith.property("kachna")).get());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testStartByRelationship_unmatchedPropertyValueSimple() throws Exception {
        testVariant("/rl;id;propertyValue=kachna/relationship", null);
    }

    @Test
    public void testStartByRelationship_propertyValue() throws Exception {
        testVariant("/rl;id;propertyName=kachna;propertyValue=duck/relationships",
                path().with(RelationWith.id("id"), RelationWith.propertyValue("kachna", "duck")).get());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testStartByRelationship_umatchedPropertyValueComplex() throws Exception {
        testVariant("/rl;id;propertyName=kachna;propertyValue=duck;propertyValue=d/relationship",
                null);
    }

    @Test
    public void testStartByRelationship_jumpToTargets_implicitDirection() throws Exception {
        testVariant("/rl;id/entities",
                path().with(RelationWith.id("id"), SwitchElementType.targetEntities()).get());
    }

    @Test
    public void testStartByRelationship_jumpToTargets_out() throws Exception {
        testVariant("/rl;id;out/entities",
                path().with(RelationWith.id("id"), SwitchElementType.targetEntities()).get());
    }

    @Test
    public void testStartByRelationship_jumpToTargets_in() throws Exception {
        testVariant("/rl;id;in/entities",
                path().with(RelationWith.id("id"), SwitchElementType.sourceEntities()).get());
    }

    @Test
    public void testStartByRelationship_traverseToEntities() throws Exception {
        testVariant("/rl;id/r;id/entities", path().with(RelationWith.id("id"), SwitchElementType.targetEntities())
                .path().with(type(Resource.class), id("id")).get());
    }

    @Test
    public void testStartByRelationship_traverseToFilter() throws Exception {
        testVariant("/rl;id;in/type=rt/entities", path().with(RelationWith.id("id"), SwitchElementType.sourceEntities())
                .path().with(type(ResourceType.class)).get());
    }

    @Test
    public void testQueryPrefixUsedForURIsStartingWithEntity() throws Exception {
        testVariant("/r;id/entities", path().with(id("eee"), Related.by(contains))
                .path().with(type(Resource.class), id("id")).get(), Query.builder().path().with(id("eee")));
    }

    @Test
    public void testSimpleEntityQuery() throws Exception {
        testVariant("/r;id", path().with(type(Resource.class), id("id")).get());
        testVariant("/r;id/entities", path().with(type(Resource.class), id("id")).get());
        testVariant("/r;id%20with%20escapes", path().with(type(Resource.class), id("id with escapes")).get());
    }

    @Test
    public void testSimpleEntityQuery_filters() throws Exception {
        testVariant("/r;id;name=kachna/entities", path().with(type(Resource.class), id("id"))
                .filter().with(name("kachna")).get());
    }

    @Test
    public void testSimpleEntityQuery_returnRelationships_implicitDirection() throws Exception {
        testVariant("/r;id/relationships", path().with(type(Resource.class), id("id"))
                .path().with(SwitchElementType.outgoingRelationships()).get());
    }

    @Test
    public void testSimpleEntityQuery_returnRelationships_in() throws Exception {
        testVariant("/r;id/relationships;in", path().with(type(Resource.class), id("id"))
                .path().with(SwitchElementType.incomingRelationships()).get());

    }

    @Test
    public void testSimpleEntityQuery_returnRelationships_filterRels() throws Exception {
        testVariant("/r;id/relationships;name=kachna;propertyName=alois", path().with(type(Resource.class), id("id"))
                .path().with(SwitchElementType.outgoingRelationships(), RelationWith.property("alois"),
                        RelationWith.name("kachna")).get());
    }

    @Test
    public void testSimpleEntityQuery_returnRelationships_out() throws Exception {
        testVariant("/r;id/relationships;out", path().with(type(Resource.class), id("id"))
                .path().with(SwitchElementType.outgoingRelationships()).get());
    }
    @Test
    public void testEntityQuery_implicitContains() throws Exception {
        testVariant("/r;id/rt;id", path().with(type(Resource.class), id("id"))
                .path().with(Related.by(contains))
                .path().with(type(ResourceType.class), id("id")).get());
    }

    @Test
    public void testEntityQuery_implicitContains_cpOptimize() throws Exception {
        testVariant("/t;id/rt;id/entities",
                path().with(With.path(CanonicalPath.of().tenant("id").resourceType("id").get())).get());
    }

    @Test
    public void testEntityQuery_implicitContains_cpOptimize_byPrefix() throws Exception {
        testVariant("/rt;id/entities",
                Query.path().with(With.path(CanonicalPath.of().tenant("id").resourceType("id").get())).get(),
                Query.builder().path().with(With.path(CanonicalPath.of().tenant("id").get()))
                        .with(Related.by(contains)));
    }

    @Test
    public void testEntityQuery_implicitContainsAndFilters() throws Exception {
        testVariant("/t;id;type=metric/rt;id;name=kachna/entities",
                path().with(type(Tenant.class), id("id"), type(Metric.class))
                .path().with(Related.by(contains))
                .path().with(type(ResourceType.class), id("id"))
                .filter().with(name("kachna")).get());
    }

    @Test
    public void testEntityQuery_jumpOverExplicitRelationship() throws Exception {
        testVariant("/t;id/rl;my-rel/rt;id/entities",
                path().with(type(Tenant.class), id("id"))
                .path().with(Related.by("my-rel"))
                .path().with(type(ResourceType.class), id("id")).get());
    }

    @Test
    public void testEntityQuery_recursive_implicitRel() throws Exception {
        testVariant("/t;id/recursive;type=r/name=Kacer",
                path().with(type(Tenant.class), id("id"))
                        .path()
                        .with(RecurseFilter.builder().addChain(Related.by(contains), type(Resource.class)).build())
                        .filter().with(With.name("Kacer")).get());
    }

    @Test
    public void testEntityQuery_recursive_explicitRel() throws Exception {
        testVariant("/t;id/recursive;over=kachna;type=r/entities;name=Kacer",
                path().with(type(Tenant.class), id("id"))
                        .path()
                        .with(RecurseFilter.builder().addChain(Related.by("kachna"), type(Resource.class)).build())
                        .filter().with(With.name("Kacer")).get());
    }

    @Test
    public void testEntityQuery_recursive_noType() throws Exception {
        testVariant("/t;id/recursive;over=kachna/type=m",
                path().with(type(Tenant.class), id("id"))
                        .path()
                        .with(RecurseFilter.builder().addChain(Related.by("kachna")).build())
                        .path().with(type(Metric.class)).get());
    }

    @Test
    public void testEntityQuery_recursive_noType_implicitRel() throws Exception {
        testVariant("/t;id/recursive/type=m",
                path().with(type(Tenant.class), id("id"))
                        .path()
                        .with(RecurseFilter.builder().addChain(Related.by(contains)).build())
                        .path().with(type(Metric.class)).get());
    }

    @Test
    public void testFilterQuery_simple() throws Exception {
        testVariant("/r;id/type=rt/entities",
                path().with(type(Resource.class), id("id"))
                .path().with(Related.by(contains))
                .path().with(type(ResourceType.class)).get());
    }

    @Test
    public void testFilterQuery_multipleFilters() throws Exception {
        testVariant("/r;id/type=resource;name=kachna/entities", path().with(type(Resource.class), id("id"))
                .path().with(Related.by(contains)).path().with(type(Resource.class)).filter().with(name("kachna"))
                .get());
    }

    @Test
    public void testFilterQuery_implicitContains() throws Exception {
        testVariant("/r;id/type=r/type=m/entities",
                path().with(type(Resource.class), id("id"))
                        .path().with(Related.by("contains"))
                        .path().with(type(Resource.class))
                        .path().with(Related.by(contains))
                        .path().with(type(Metric.class)).get());
    }

    @Test
    public void testFilterQuery_relatedByToPairs() throws Exception {
        testVariant("/e;f;relatedTo=%2Ft%3Bid;relatedBy=kachna",
                path().with(type(SegmentType.e), id("f"))
                .filter().with(Related.with(CanonicalPath.of().tenant("id").get(), "kachna"))
                        .get());
    }

    @Test
    public void testFilterQuery_relatedByToWithPairs() throws Exception {
        testVariant("/e;f;relatedTo=%2Ft%3Bid;relatedBy=kachna;relatedWith=%2Ft%3Bid;relatedBy=drachma",
                path().with(type(SegmentType.e), id("f"))
                        .filter().with(Related.with(CanonicalPath.of().tenant("id").get(), "kachna"),
                            Related.asTargetWith(CanonicalPath.of().tenant("id").get(), "drachma"))
                        .get());
    }

    @Test
    public void testPrefixDoesntApplyToStartWithRelationship() throws Exception {
        testVariant("/rl;id/relationships",
                path().with(RelationWith.id("id")).get(),
                Query.builder().with(id("eee")));
    }

    @Test
    public void testPathEndQuery_entity() throws Exception {
        testVariant("/entities", Query.empty());
    }

    @Test
    public void testPathEndQuery_relationships() throws Exception {
        testVariant("/relationships", Query.path().with(SwitchElementType.outgoingRelationships()).get());
    }

    @Test
    public void testPathEndQuery_relationships_explicitDirection() throws Exception {
        testVariant("/relationships;in", Query.path().with(SwitchElementType.incomingRelationships()).get());
    }

    @Test
    public void testPathEndQuery_relationships_filters() throws Exception {
        testVariant("/relationships;name=kachna", Query.path().with(SwitchElementType.outgoingRelationships(),
                RelationWith.name("kachna")).get());
    }

    @Test
    public void testEscapingInFilterNamesAndValues() throws Exception {
        testVariant("/name=A%20B", Query.path().filter().with(name("A B")).get());
    }

    @Test
    public void testIdenticalProgression() throws Exception {
        testVariant("/r;id/identical/name=Kachna/rl;contains/m;id", Query.path()
                .with(type(r), id("id"), With.sameIdentityHash())
                .filter().with(name("Kachna")).path().with(Related.by(contains), type(m), id("id")).get());
    }

    @Test
    public void testRecursiveReturnsAllChildrenOfPrefix() throws Exception {
        testVariant("/recursive",
                Query.path().with(id("prefix"), RecurseFilter.builder().addChain(Related.by(contains)).build()).get(),
                Query.path().with(id("prefix")).rawQueryBuilder());
    }

    private void testVariant(String uri, Query expected) throws Exception {
        testVariant(uri, expected, Query.builder());
    }

    private void testVariant(String uri, Query expected, Query.Builder prefix) throws Exception {
        Traverser traverser = new Traverser(0, prefix, CanonicalPath::fromString);

        Query actual = traverser.navigate(uri);
        assertEquals(expected, actual);
    }
}


text:
import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"

export default () => (
  <Layout>

Anonymous Arrow Function Two

    <Link data-testid="link" to="/anonymous-arrow/">
      First page
    </Link>
  </Layout>
)


text:
namespace Scada.Server.Ctrl
{
    /// <summary>
    /// The phrases used in the application
    /// <para>Фразы, используемые приложением</para>
    /// </summary>
    internal static class AppPhrases
    {
        static AppPhrases()
        {
            SetToDefault();
        }

        // Словарь Scada.Server.Ctrl
        public static string IncorrectFilter { get; private set; }

        // Словарь Scada.Server.Ctrl.FrmBaseTableView
        public static string LoadBaseTableError { get; private set; }

        // Словарь Scada.Server.Ctrl.FrmEventTableEdit
        public static string EditEventTableTitle { get; private set; }
        public static string ViewEventTableTitle { get; private set; }
        public static string LoadEventTableError { get; private set; }
        public static string SaveEventTableError { get; private set; }
        public static string SaveEventTableConfirm { get; private set; }

        // Словарь Scada.Server.Ctrl.FrmMain
        public static string MainFormTitle { get; private set; }
        public static string CommonParamsNode { get; private set; }
        public static string SaveParamsNode { get; private set; }
        public static string FilesNode { get; private set; }
        public static string BaseNode { get; private set; }
        public static string CurSrezNode { get; private set; }
        public static string MinSrezNode { get; private set; }
        public static string HrSrezNode { get; private set; }
        public static string EventsNode { get; private set; }
        public static string ModulesNode { get; private set; }
        public static string GeneratorNode { get; private set; }
        public static string StatsNode { get; private set; }
        public static string ServiceState { get; private set; }
        public static string RestartNeeded { get; private set; }
        public static string GetFileListError { get; private set; }
        public static string LoadModuleError { get; private set; }
        public static string SecondInstanceClosed { get; private set; }
        public static string CheckSecondInstanceError { get; private set; }
        public static string ServiceNotInstalled { get; private set; }
        public static string SaveSettingsConfirm { get; private set; }
        public static string ServiceStartFailed { get; private set; }
        public static string ServiceStopFailed { get; private set; }
        public static string ServiceRestartFailed { get; private set; }
        public static string ChooseItfDir { get; private set; }
        public static string ChooseArcDir { get; private set; }
        public static string ChooseArcCopyDir { get; private set; }
        public static string ModuleAlreadyAdded { get; private set; }
        public static string IncorrectCnlNum { get; private set; }
        public static string IncorrectCnlVal { get; private set; }
        public static string SendDataCompleted { get; private set; }
        public static string IncorrectOldCnlVal { get; private set; }
        public static string IncorrectNewCnlVal { get; private set; }
        public static string SendEventCompleted { get; private set; }
        public static string CheckEventCompleted { get; private set; }
        public static string IncorrectCmdVal { get; private set; }
        public static string IncorrectHexCmdData { get; private set; }
        public static string CmdDataRequired { get; private set; }
        public static string SendCmdCompleted { get; private set; }

        // Словарь Scada.Server.Ctrl.FrmSrezTableEdit
        public static string EditSrezTableTitle { get; private set; }
        public static string ViewSrezTableTitle { get; private set; }
        public static string LoadSrezTableError { get; private set; }
        public static string SaveSrezTableError { get; private set; }
        public static string SaveSrezTableConfirm { get; private set; }

        private static void SetToDefault()
        {
            IncorrectFilter = "Некорректный фильтр.";

            LoadBaseTableError = "Ошибка при загрузке таблицы базы конфигурации";

            EditEventTableTitle = "Редактирование таблицы событий";
            ViewEventTableTitle = "Просмотр таблицы событий";
            LoadEventTableError = "Ошибка при загрузке таблицы событий";
            SaveEventTableError = "Ошибка при сохранении таблицы событий";
            SaveEventTableConfirm = "Таблица событий была изменена.\r\nСохранить изменения?";

            MainFormTitle = "SCADA-Сервер";
            CommonParamsNode = "Общие параметры";
            SaveParamsNode = "Параметры записи";
            FilesNode = "Файлы";
            BaseNode = "База конфигурации";
            CurSrezNode = "Текущий срез";
            MinSrezNode = "Минутные срезы";
            HrSrezNode = "Часовые срезы";
            EventsNode = "События";
            ModulesNode = "Модули";
            GeneratorNode = "Генератор";
            StatsNode = "Статистика";
            ServiceState = "Состояние службы SCADA-Сервера: {0}";
            RestartNeeded = "Изменения настроек вступят в силу после перезапуска службы SCADA-Сервера.";
            GetFileListError = "Ошибка при получении списка файлов данных";
            LoadModuleError = "Ошибка при загрузке модуля";
            SecondInstanceClosed = "Программа для управления SCADA-Сервером уже запущена.\r\nВторая копия будет закрыта.";
            CheckSecondInstanceError = "Ошибка при проверке запуска второй копии программы";
            ServiceNotInstalled = "Служба SCADA-Сервера не установлена.";
            SaveSettingsConfirm = "Настройки SCADA-Сервера были изменены.\r\nСохранить изменения?";
            ServiceStartFailed = "Не удалось запустить службу SCADA-Сервера";
            ServiceStopFailed = "Не удалось остановить службу SCADA-Сервера";
            ServiceRestartFailed = "Не удалось перезапусить службу SCADA-Сервера";
            ChooseItfDir = "Выберите директорию интерфейса";
            ChooseArcDir = "Выберите директорию архива в формате DAT";
            ChooseArcCopyDir = "Выберите директорию копии архива в формате DAT";
            ModuleAlreadyAdded = "Модуль уже добавлен.";
            IncorrectCnlNum = "Некорректный номер канала.";
            IncorrectCnlVal = "Некорректное значение канала.";
            SendDataCompleted = "Данные отправлены успешно.";
            IncorrectOldCnlVal = "Некорректное старое значение канала.";
            IncorrectNewCnlVal = "Некорректное новое значение канала.";
            SendEventCompleted = "Событие отправлено успешно.";
            CheckEventCompleted = "Команда квитирования события отправлена успешно.";
            IncorrectCmdVal = "Некорректное значение команды.";
            IncorrectHexCmdData = "Некорректные 16-ричные данные команды.";
            CmdDataRequired = "Необходимо ввести данные команды.";
            SendCmdCompleted = "Команда отправлена успешно.";

            EditSrezTableTitle = "Редактирование таблицы срезов";
            ViewSrezTableTitle = "Просмотр таблицы срезов";
            LoadSrezTableError = "Ошибка при загрузке таблицы срезов";
            SaveSrezTableError = "Ошибка при сохранении таблицы срезов";
            SaveSrezTableConfirm = "Таблица срезов была изменена.\r\nСохранить изменения?";
        }

        public static void Init()
        {
            Localization.Dict dict;
            if (Localization.Dictionaries.TryGetValue("Scada.Server.Ctrl", out dict))
                IncorrectFilter = dict.GetPhrase("IncorrectFilter", IncorrectFilter);

            if (Localization.Dictionaries.TryGetValue("Scada.Server.Ctrl.FrmBaseTableView", out dict))
                LoadBaseTableError = dict.GetPhrase("LoadBaseTableError", LoadBaseTableError);

            if (Localization.Dictionaries.TryGetValue("Scada.Server.Ctrl.FrmEventTableEdit", out dict))
            {
                EditEventTableTitle = dict.GetPhrase("EditEventTableTitle", EditEventTableTitle);
                ViewEventTableTitle = dict.GetPhrase("ViewEventTableTitle", ViewEventTableTitle);
                LoadEventTableError = dict.GetPhrase("LoadEventTableError", LoadEventTableError);
                SaveEventTableError = dict.GetPhrase("SaveEventTableError", SaveEventTableError);
                SaveEventTableConfirm = dict.GetPhrase("SaveEventTableConfirm", SaveEventTableConfirm);
            }

            if (Localization.Dictionaries.TryGetValue("Scada.Server.Ctrl.FrmMain", out dict))
            {
                MainFormTitle = dict.GetPhrase("this", MainFormTitle);
                CommonParamsNode = dict.GetPhrase("CommonParamsNode", CommonParamsNode);
                SaveParamsNode = dict.GetPhrase("SaveParamsNode", SaveParamsNode);
                FilesNode = dict.GetPhrase("FilesNode", FilesNode);
                BaseNode = dict.GetPhrase("BaseNode", BaseNode);
                CurSrezNode = dict.GetPhrase("CurSrezNode", CurSrezNode);
                MinSrezNode = dict.GetPhrase("MinSrezNode", MinSrezNode);
                HrSrezNode = dict.GetPhrase("HrSrezNode", HrSrezNode);
                EventsNode = dict.GetPhrase("EventsNode", EventsNode);
                ModulesNode = dict.GetPhrase("ModulesNode", ModulesNode);
                GeneratorNode = dict.GetPhrase("GeneratorNode", GeneratorNode);
                StatsNode = dict.GetPhrase("StatsNode", StatsNode);
                ServiceState = dict.GetPhrase("ServiceState", ServiceState);
                RestartNeeded = dict.GetPhrase("RestartNeeded", RestartNeeded);
                GetFileListError = dict.GetPhrase("GetFileListError", GetFileListError);
                LoadModuleError = dict.GetPhrase("LoadModuleError", LoadModuleError);
                SecondInstanceClosed = dict.GetPhrase("SecondInstanceClosed", SecondInstanceClosed);
                CheckSecondInstanceError = dict.GetPhrase("CheckSecondInstanceError", CheckSecondInstanceError);
                ServiceNotInstalled = dict.GetPhrase("ServiceNotInstalled", ServiceNotInstalled);
                SaveSettingsConfirm = dict.GetPhrase("SaveSettingsConfirm", SaveSettingsConfirm);
                ServiceStartFailed = dict.GetPhrase("ServiceStartFailed", ServiceStartFailed);
                ServiceStopFailed = dict.GetPhrase("ServiceStopFailed", ServiceStopFailed);
                ServiceRestartFailed = dict.GetPhrase("ServiceRestartFailed", ServiceRestartFailed);
                ChooseItfDir = dict.GetPhrase("ChooseItfDir", ChooseItfDir);
                ChooseArcDir = dict.GetPhrase("ChooseArcDir", ChooseArcDir);
                ChooseArcCopyDir = dict.GetPhrase("ChooseArcCopyDir", ChooseArcCopyDir);
                ModuleAlreadyAdded = dict.GetPhrase("ModuleAlreadyAdded", ModuleAlreadyAdded);
                IncorrectCnlNum = dict.GetPhrase("IncorrectCnlNum", IncorrectCnlNum);
                IncorrectCnlVal = dict.GetPhrase("IncorrectCnlVal", IncorrectCnlVal);
                SendDataCompleted = dict.GetPhrase("SendDataCompleted", SendDataCompleted);
                IncorrectOldCnlVal = dict.GetPhrase("IncorrectOldCnlVal", IncorrectOldCnlVal);
                IncorrectNewCnlVal = dict.GetPhrase("IncorrectNewCnlVal", IncorrectNewCnlVal);
                SendEventCompleted = dict.GetPhrase("SendEventCompleted", SendEventCompleted);
                CheckEventCompleted = dict.GetPhrase("CheckEventCompleted", CheckEventCompleted);
                IncorrectCmdVal = dict.GetPhrase("IncorrectCmdVal", IncorrectCmdVal);
                IncorrectHexCmdData = dict.GetPhrase("IncorrectHexCmdData", IncorrectHexCmdData);
                CmdDataRequired = dict.GetPhrase("CmdDataRequired", CmdDataRequired);
                SendCmdCompleted = dict.GetPhrase("SendCmdCompleted", SendCmdCompleted);
            }

            if (Localization.Dictionaries.TryGetValue("Scada.Server.Ctrl.FrmSrezTableEdit", out dict))
            {
                EditSrezTableTitle = dict.GetPhrase("EditSrezTableTitle", EditSrezTableTitle);
                ViewSrezTableTitle = dict.GetPhrase("ViewSrezTableTitle", ViewSrezTableTitle);
                LoadSrezTableError = dict.GetPhrase("LoadSrezTableError", LoadSrezTableError);
                SaveSrezTableError = dict.GetPhrase("SaveSrezTableError", SaveSrezTableError);
                SaveSrezTableConfirm = dict.GetPhrase("SaveSrezTableConfirm", SaveSrezTableConfirm);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/_ff9c3c" android:state_focused="true"/>
    <item android:drawable="@color/_ff9c3c" android:state_pressed="true"/>
    <item android:drawable="@color/button_disable_bg" android:state_enabled="false"/>
    <item android:drawable="@color/detail_more_bg"/>
</selector>


text:
"""
Simple testcase for txsclient.py.
"""

__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation

This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.

The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.

You may elect to license modified versions of this file under the
terms and conditions of either the GPL or the CDDL or both.
"""
__version__ = "$Revision: 100880 $"

# Standard python imports.
import os
import sys
import types

# Validation Kit imports.
sys.path.insert(0, '.');
sys.path.insert(0, '..');
import testdriver.txsclient as txsclient
import testdriver.reporter as reporter
from common import utils;

g_cTests = 0;
g_cFailures = 0

def boolRes(rc, fExpect = True):
    """Checks a boolean result."""
    global g_cTests, g_cFailures;
    g_cTests = g_cTests + 1;
    if isinstance(rc, types.BooleanType):
        if rc == fExpect:
            return 'PASSED';
    g_cFailures = g_cFailures + 1;
    return 'FAILED';

def stringRes(rc, sExpect):
    """Checks a string result."""
    global g_cTests, g_cFailures;
    g_cTests = g_cTests + 1;
    if isinstance(rc, basestring):
        if rc == sExpect:
            return 'PASSED';
    g_cFailures = g_cFailures + 1;
    return 'FAILED';

def main(asArgs): # pylint: disable=C0111,R0914,R0915
    cMsTimeout      = 30*1000;
    sAddress        = 'localhost';
    uPort           = None;
    fReversedSetup  = False;
    fReboot         = False;
    fStdTests       = True;

    i = 1;
    while i < len(asArgs):
        if asArgs[i] == '--hostname':
            sAddress = asArgs[i + 1];
            i = i + 2;
        elif asArgs[i] == '--port':
            uPort = int(asArgs[i + 1]);
            i = i + 2;
        elif asArgs[i] == '--reversed-setup':
            fReversedSetup = True;
            i = i + 1;
        elif asArgs[i] == '--timeout':
            cMsTimeout = long(asArgs[i + 1]);
            i = i + 2;
        elif asArgs[i] == '--reboot':
            fReboot   = True;
            fStdTests = False;
            i = i + 1;
        elif asArgs[i] == '--help':
            print 'tst-txsclient.py [--hostname <addr|name>] [--port <num>] [--timeout <cMS>] [--reboot] [--reversed-setup]'
            return 0;
        else:
            print 'Unknown argument: %s' % (asArgs[i]);
            return 2;

    if uPort is None:
        oSession = txsclient.openTcpSession(cMsTimeout, sAddress, fReversedSetup = fReversedSetup);
    else:
        oSession = txsclient.openTcpSession(cMsTimeout, sAddress, uPort = uPort, fReversedSetup = fReversedSetup);
    if oSession is None:
        print 'openTcpSession failed';
        return 1;

    fDone = oSession.waitForTask(30*1000);
    print 'connect: waitForTask -> %s, result %s' % (fDone, oSession.getResult());
    if fDone is True and oSession.isSuccess():
        if fStdTests:
            # Get the UUID of the remote instance.
            sUuid = oSession.syncUuid();
            if sUuid is not False:
                print '%s: UUID = %s' % (boolRes(True), sUuid);
            else:
                print '%s: UUID' % (boolRes(False),);

            # Create and remove a directory on the scratch area.
            rc = oSession.syncMkDir('${SCRATCH}/testdir1');
            print '%s: MKDIR(${SCRATCH}/testdir1) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncIsDir('${SCRATCH}/testdir1');
            print '%s: ISDIR(${SCRATCH}/testdir1) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncRmDir('${SCRATCH}/testdir1');
            print '%s: RMDIR(${SCRATCH}/testdir1) -> %s' % (boolRes(rc), rc);

            # Create a two-level subdir.
            rc = oSession.syncMkDirPath('${SCRATCH}/testdir2/subdir1');
            print '%s: MKDRPATH(${SCRATCH}/testdir2/subdir1) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncIsDir('${SCRATCH}/testdir2');
            print '%s: ISDIR(${SCRATCH}/testdir2) -> %s' % (boolRes(rc), rc);
            rc = oSession.syncIsDir('${SCRATCH}/testdir2/');
            print '%s: ISDIR(${SCRATCH}/testdir2/) -> %s' % (boolRes(rc), rc);
            rc = oSession.syncIsDir('${SCRATCH}/testdir2/subdir1');
            print '%s: ISDIR(${SCRATCH}/testdir2/subdir1) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncRmTree('${SCRATCH}/testdir2');
            print '%s: RMTREE(${SCRATCH}/testdir2) -> %s' % (boolRes(rc), rc);

            # Check out a simple file.
            rc = oSession.syncUploadString('howdy', '${SCRATCH}/howdyfile');
            print '%s: PUT FILE(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncUploadString('howdy-replaced', '${SCRATCH}/howdyfile');
            print '%s: PUT FILE(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc), rc);

            rc = oSession.syncDownloadString('${SCRATCH}/howdyfile');
            print '%s: GET FILE(${SCRATCH}/howdyfile) -> "%s" expected "howdy-replaced"' % (stringRes(rc, 'howdy-replaced'), rc);

            rc = oSession.syncIsFile('${SCRATCH}/howdyfile');
            print '%s: ISFILE(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc), rc);
            rc = oSession.syncIsDir('${SCRATCH}/howdyfile');
            print '%s: ISDIR(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc, False), rc);
            rc = oSession.syncIsSymlink('${SCRATCH}/howdyfile');
            print '%s: ISSYMLNK(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc, False), rc);

            rc = oSession.syncRmFile('${SCRATCH}/howdyfile');
            print '%s: RMFILE(${SCRATCH}/howdyfile) -> %s' % (boolRes(rc), rc);

            # Unicode filename (may or may not work, LANG/LC_TYPE dependent on some hosts).
            rc = oSession.syncUploadString('howdy', u'${SCRATCH}/Schröder');
            print (u'%s: PUT FILE(${SCRATCH}/Schröder) -> %s' % (boolRes(rc), rc)).encode('ascii', 'replace');

            rc = oSession.syncIsFile(u'${SCRATCH}/Schröder');
            print (u'%s: ISFILE(${SCRATCH}/Schröder) -> %s' % (boolRes(rc), rc)).encode('ascii', 'replace');

            rc = oSession.syncRmFile(u'${SCRATCH}/Schröder');
            print (u'%s: RMFILE(${SCRATCH}/Schröder) -> %s' % (boolRes(rc), rc)).encode('ascii', 'replace');

            # Finally, some file uploading and downloading with unicode filenames.
            strUpFile  = 'tst-txsclient-upload.bin';
            strDwnFile = 'tst-txsclient-download.bin';
            try:
                abRandFile = os.urandom(257897);
            except:
                print 'INFO: no urandom... falling back on a simple string.'
                abRandFile = 'asdflkjasdlfkjasdlfkjq023942relwjgkna9epr865u2nm345;hndafgoukhasre5kb2453km';
                for i in range(1, 64):
                    abRandFile += abRandFile;
            try:
                oLocalFile = utils.openNoInherit(strUpFile, 'w+b');
                oLocalFile.write(abRandFile);
                oLocalFile.close();
                rc = True;
            except:
                rc = False;
                print('%s: creating file (%s) to upload failed....' % (boolRes(rc), strUpFile));

            if rc is True:
                rc = oSession.syncUploadFile(strUpFile, '${SCRATCH}/tst-txsclient-uploaded.bin')
                print('%s: PUT FILE(%s, ${SCRATCH}/tst-txsclient-uploaded.bin) -> %s' % (boolRes(rc), strUpFile, rc));

                rc = oSession.syncDownloadFile('${SCRATCH}/tst-txsclient-uploaded.bin', strDwnFile)
                print('%s: GET FILE(${SCRATCH}/tst-txsclient-uploaded.bin, tst-txsclient-downloaded.txt) -> %s'
                      % (boolRes(rc), rc));

                try:
                    oLocalFile = utils.openNoInherit(strDwnFile, "rb");
                    abDwnFile = oLocalFile.read();
                    oLocalFile.close();
                    if abRandFile == abDwnFile:
                        print '%s: downloaded file matches the uploaded file' % (boolRes(True),);
                    else:
                        print '%s: downloaded file does not match the uploaded file' % (boolRes(False),);
                        print 'abRandFile=%s' % (abRandFile,);
                        print 'abDwnFile =%s' % (abRandFile,);
                except:
                    print '%s: reading downloaded file (%s) failed....' % (boolRes(False), strDwnFile);

                rc = oSession.syncRmFile(u'${SCRATCH}/tst-txsclient-uploaded.bin');
                print '%s: RMFILE(${SCRATCH}/tst-txsclient-uploaded.bin) -> %s' % (boolRes(rc), rc);

            try:    os.remove(strUpFile);
            except: pass;
            try:    os.remove(strDwnFile);
            except: pass;

            # Execute some simple thing, if available.
            # Intentionally skip this test if file is not available due to
            # another inserted CD-ROM (e.g. not TestSuite.iso).
            sProg = '${CDROM}/${OS/ARCH}/NetPerf${EXESUFF}';
            rc = oSession.syncIsFile(sProg, 30 * 1000, True);
            if rc is True:
                rc = oSession.syncExecEx(sProg, (sProg, '--help'));
                print '%s: EXEC(%s ${SCRATCH}) -> %s' % (boolRes(rc), sProg, rc);

                rc = oSession.syncExecEx(sProg, (sProg, 'there', 'is no such', 'parameter'), \
                                         oStdOut='${SCRATCH}/stdout', \
                                         oStdErr='${SCRATCH}/stderr');
                print('%s: EXEC(%s there is not such parameter > ${SCRATCH}/stdout 2> ${SCRATCH}/stderr) -> %s'
                      % (boolRes(rc, False), sProg, rc));

                rc = oSession.syncDownloadString('${SCRATCH}/stdout');
                print 'INFO:   GET FILE(${SCRATCH}/stdout) -> "%s"' % (rc);
                rc = oSession.syncDownloadString('${SCRATCH}/stderr');
                print 'INFO:   GET FILE(${SCRATCH}/stderr) -> "%s"' % (rc);

                print 'TESTING: syncExec...'
                rc = oSession.syncExec(sProg, (sProg, '--version'));
                print '%s: EXEC(%s --version) -> %s' % (boolRes(rc), sProg, rc);

                print 'TESTING: syncExec...'
                rc = oSession.syncExec(sProg, (sProg, '--help'));
                print '%s: EXEC(%s --help) -> %s' % (boolRes(rc), sProg, rc);

                #print 'TESTING: syncExec sleep 30...'
                #rc = oSession.syncExec('/usr/bin/sleep', ('/usr/bin/sleep', '30'));
                #print '%s: EXEC(/bin/sleep 30) -> %s' % (boolRes(rc), rc);
            else:
                print 'SKIP:   Execution of %s skipped, does not exist on CD-ROM' % (sProg,);

            # Execute a non-existing file on CD-ROM.
            sProg = '${CDROM}/${OS/ARCH}/NonExisting${EXESUFF}';
            rc = oSession.syncExecEx(sProg, (sProg,), oStdIn = '/dev/null', oStdOut = '/dev/null', \
                                     oStdErr = '/dev/null', oTestPipe = '/dev/null', \
                                     sAsUser = '', cMsTimeout = 3600000, fIgnoreErrors = True);
            if rc is None:
                rc = True;
            else:
                reporter.error('Unexpected value \"%s\" while executing non-existent file "%s"' % (rc, sProg));
            print '%s: EXEC(%s ${SCRATCH}) -> %s' % (boolRes(rc), sProg, rc);

            # Done
            rc = oSession.syncDisconnect();
            print '%s: disconnect() -> %s' % (boolRes(rc), rc);

        elif fReboot:
            print 'TESTING: syncReboot...'
            rc = oSession.syncReboot();
            print '%s: REBOOT() -> %s' % (boolRes(rc), rc);

    if g_cFailures != 0:
        print 'tst-txsclient.py: %u out of %u test failed' % (g_cFailures, g_cTests);
        return 1;
    print 'tst-txsclient.py: all %u tests passed!' % (g_cTests);
    return 0;

if __name__ == '__main__':
    reporter.incVerbosity();
    reporter.incVerbosity();
    reporter.incVerbosity();
    reporter.incVerbosity();
    sys.exit(main(sys.argv));


text:
/**
 *
 */
package com.all.util;

/**
 * @author insidiousnoxious
 *
 */
public class Tree<T> {

  TreeNode<T> root;

  public Tree(){
    root = null;
  }

  public Tree(TreeNode<T> root){
    this.root = root;
  }

  public TreeNode<T> getRoot(){
    return this.root;
  }

  public void setRoot(TreeNode<T> root){
    this.root=root;
  }

  //copy constructor not implemented since it will depend on T (if T can be deep copied)
}


text:
import * as React from "react";

import NotebookPreview from "@nteract/notebook-preview";
import Markdown from "@nteract/markdown";
import { Styles } from "@nteract/core/providers";

import DirectoryListing from "./directory-listing";

// HACK: Temporarily provide jquery for others to use...
const jquery = require("jquery");
global.jquery = jquery;
global.$ = jquery;

import {
  standardTransforms,
  standardDisplayOrder,
  registerTransform
} from "@nteract/transforms";

import type { Content } from "./types";

import DataResourceTransform from "@nteract/transform-dataresource";

import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega";

import { PlotlyNullTransform, PlotlyTransform } from "../../transforms";

// Order is important here. The last transform in the array will have order `0`.
const { transforms, displayOrder } = [
  DataResourceTransform,
  PlotlyNullTransform,
  PlotlyTransform,
  VegaLite1,
  VegaLite2,
  Vega2,
  Vega3
].reduce(registerTransform, {
  transforms: standardTransforms,
  displayOrder: standardDisplayOrder
});

import HTMLView from "./html";
import JSONView from "./json";
import CSVView from "./csv";

const suffixRegex = /(?:\.([^.]+))?$/;

class File extends React.Component<*> {
  shouldComponentUpdate() {
    return false;
  }

  render() {
    const name = this.props.entry.name;
    const suffix = (suffixRegex.exec(name)[1] || "").toLowerCase();

    switch (suffix) {
      case "html":
        return <HTMLView entry={this.props.entry} />;
      case "json":
        return <JSONView entry={this.props.entry} />;
      case "csv":
        return <CSVView entry={this.props.entry} />;
      case "md":
      case "markdown":
      case "rmd":
        return <Markdown source={this.props.entry.content} />;
      case "gif":
      case "jpeg":
      case "jpg":
      case "png":
        return (
          <img
            src={`/files/${this.props.pathname}`}
            alt={this.props.pathname}
          />
        );
      default:
        return <a href={`/files/${this.props.pathname}`}>Download raw file;
    }
  }
}

type EntryProps = {
  entry: Content,
  pathname: string,
  basepath: string
};

export const Entry = (props: EntryProps) => {
  if (props.entry.content === null) {
    return null;
  }

  switch (props.entry.type) {
    case "directory":
      // Dynamic type check on content being an Array
      if (Array.isArray(props.entry.content)) {
        return (
          <DirectoryListing contents={props.entry.content} basepath={"/view"} />
        );
      }
      return null;
    case "file":
      // TODO: Case off various file types (by extension, mimetype)
      return <File entry={props.entry} pathname={props.pathname} />;
    case "notebook":
      return (

      );
    default:
      console.log("Unknown contents ");
      return
{JSON.stringify(props.entry.content)}
;
  }
};


text:
using NBitcoin.BouncyCastle.Math;

namespace NBitcoin.BouncyCastle.Crypto
{
    /**
     * interface for classes implementing the Digital Signature Algorithm
     */
    internal interface IDsa
    {
        string AlgorithmName
        {
            get;
        }

        /**
         * initialise the signer for signature generation or signature
         * verification.
         *
         * @param forSigning true if we are generating a signature, false
         * otherwise.
         * @param param key parameters for signature generation.
         */
        void Init(bool forSigning, ICipherParameters parameters);

        /**
         * sign the passed in message (usually the output of a hash function).
         *
         * @param message the message to be signed.
         * @return two big integers representing the r and s values respectively.
         */
        BigInteger[] GenerateSignature(byte[] message);

        /**
         * verify the message message against the signature values r and s.
         *
         * @param message the message that was supposed to have been signed.
         * @param r the r signature value.
         * @param s the s signature value.
         */
        bool VerifySignature(byte[] message, BigInteger r, BigInteger s);
    }
}


text:
'use strict';
/* eslint-env node */
/* global inject */
define(['angular-mocks', 'portal'], function() {
    describe('portalGroupService', function() {
        var service;
        var httpBackend;
        var URLS = {};
        beforeEach(function() {
          module('portal');
        });

        beforeEach(inject(function(
          _portalGroupService_, _$httpBackend_,
          SERVICE_LOC, MESSAGES, APP_FLAGS
        ) {
          service = _portalGroupService_;
          httpBackend = _$httpBackend_;
          URLS.group = SERVICE_LOC.groupURL;
          URLS.feature = SERVICE_LOC.messagesURL;
        }));

        it('should properly handle filtering nothing', function() {
          // setup
          var array = [];
          var groups = [];
          // test
          var results = service.filterArrayByGroups(array, groups);

          expect(results).toBeTruthy();

          expect(results.length).toEqual(0);
        });

        it('should properly handle filtering with a string ' +
          'or an array with default attribute of group', function() {
          // setup
          var array = [
            {title: 'in crowd', group: 'in'},
            {title: 'out crowd', group: ['out']},
            {title: 'everyone', group: ['in', 'out']},
          ];
          var groups = [{name: 'in'}];
          // test
          var results = service.filterArrayByGroups(array, groups);

          expect(results).toBeTruthy();

          expect(results.length).toEqual(2);
        });

        it('should properly handle filtering ' +
          'with an alternate group field name', function() {
          // setup
          var array = [
            {title: 'in crowd', group: 'in'},
            {title: 'out crowd', group: ['out']},
            {title: 'everyone', group: ['in', 'out']},
          ];
          var groups = [{title: 'in'}];// uPortal inside joke
          // test
          var results =
            service.filterArrayByGroups(array, groups, null, 'title');

            expect(results).toBeTruthy();

            expect(results.length).toEqual(2);
        });

        it('should properly handle filtering ' +
          'with an alternate array field name', function() {
          // setup
          var array = [
            {title: 'in crowd', theGroup: 'in'},
            {title: 'out crowd', theGroup: ['out']},
            {title: 'everyone', theGroup: ['in', 'out']},
          ];
          var groups = [{name: 'in'}];
          // test
          var results = service.filterArrayByGroups(array, groups, 'theGroup');

          expect(httpBackend).toBeTruthy();

          expect(results).toBeTruthy();

          expect(results.length).toEqual(2);
        });
    });
});


text:
<!doctype html>

	<meta charset="utf-8">
	<title>jQuery UI Position - Default functionality</title>
	<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">

	<link rel="stylesheet" href="../demos.css">

	This is the position parent element.

	to position

	to position 2

	position...

		my:
		<select id="my_horizontal">
			<option value="left">left</option>
			<option value="center">center</option>
			<option value="right">right</option>
		</select>
		<select id="my_vertical">
			<option value="top">top</option>
			<option value="middle">center</option>
			<option value="bottom">bottom</option>
		</select>

		at:
		<select id="at_horizontal">
			<option value="left">left</option>
			<option value="center">center</option>
			<option value="right">right</option>
		</select>
		<select id="at_vertical">
			<option value="top">top</option>
			<option value="middle">center</option>
			<option value="bottom">bottom</option>
		</select>

		offset:
		<input id="offset">

		collision:
		<select id="collision_horizontal">
			<option value="flip">flip</option>
			<option value="fit">fit</option>
			<option value="flipfit">flipfit</option>
			<option value="none">none</option>
		</select>
		<select id="collision_vertical">
			<option value="flip">flip</option>
			<option value="fit">fit</option>
			<option value="flipfit">flipfit</option>
			<option value="none">none</option>
		</select>

Use the form controls to configure the positioning, or drag the positioned element to modify its offset.

Drag around the parent element to see collision detection in action.