text:
layout: post
title: Spring Boot - Apache Camel
excerpt: "This article shows how to work with a simple Apache Camel application using Spring Boot."
modified: 2017-12-13T17:00:00-00:00
categories: articles
tags: [Camel, EIP, Swagger, Spring Boot]
image:
  vendor: twitter
  feature: /media/DQx77qwVQAA_At6.jpg:large
  credit: Nat Geo Photography
  creditlink: https://twitter.com/NatGeoPhotos
comments: true
share: true
references:
  - title: "Camel examples: Spring Boot"
    url: "https://github.com/apache/camel/tree/master/examples/camel-example-spring-boot"
  - title: "How to Integrate Spring Boot and Apache Camel"
    url: "https://dzone.com/articles/how-to-integrate-spring-boot-and-apache-camel"

---

* TOC
{:toc}

## Camel

> Apache Camel is an open source Java framework that focuses on making integration easier and more accessible to developers. It does this by providing:
>
> * concrete implementations of all the widely used Enterprise Integration Patterns (EIPs)
> * connectivity to a great variety of transports and APIs
> * easy to use Domain Specific Languages (DSLs) to wire EIPs and transports together
>
> —— [Open Source Integration with Apache Camel and How Fuse IDE Can Help](https://dzone.com/articles/open-source-integration-apache)

> Apache Camel is messaging technology glue with routing. It joins together messaging start and end points allowing the transference of messages from different sources to different destinations. For example: JMS -> JSON, HTTP -> JMS or funneling FTP -> JMS, HTTP -> JMS, JSON -> JMS
>
> —— [What exactly is Apache Camel?](https://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel)

### EIP

[Enterprise Integration Patterns][Enterprise_Integration_Patterns]

> In order to understand what Apache Camel is, you need to understand what Enterprise Integration Patterns are.
>
> Let's start with what we presumably already know: The Singleton pattern, the Factory pattern, etc; They are merely ways of organizing your solution to the problem, but they are not solutions themselves. These patterns were analyzed and extracted for the rest of us by the Gang of Four, when they published their book: Design Patterns. They saved some of us tremendous effort in thinking of how to best structure our code.
>
> Much like the Gang of Four, Gregor Hohpe and Bobby Woolf authored the book Enterprise Integration Patterns (EIP) in which they propose and document a set of new patterns and blueprints for how we could best design large component-based systems, where components can be running on the same process or in a different machine.
>
> They basically propose that we structure our system to be message oriented -- where components communicate with each others using messages as inputs and outputs and absolutely nothing else. They show us a complete set of patterns that we may choose from and implement in our different components that will together form the whole system.
>
> —— [What exactly is Apache Camel?](https://stackoverflow.com/questions/8845186/what-exactly-is-apache-camel)

## Spring Boot with Camel
使用 [Camel][Camel] 做企业集成模式 [EIP][eip] 开发时需要用到大量的不同技术需求的 package,为了方便管理 packages 之间版本依赖关系 Camel 为适应 [Spring Boot][spring-boot] 创建了一个 BOM 。在 *pom.xml* 中添加它,这样你就可以方便地添加 Camel 需要的 package 了

```xml
<dependencyManagement>
  <dependencies>
    <!-- Camel BOM -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring-boot-dependencies</artifactId>
      <version>${camel.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
```

### Dependencies

使用 Spring Boot 开发 Java 应用程序,需要添加

```xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>
```

使用 Spring Boot Web 提供 Servlet container 能力,把它默认的 Tomcat [Embedded Servlet Container][howto-embedded-servlet-containers] 改为 [Undertow][Undertow]

```xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
```

> [Spring Boot Actuator][Spring Boot Actuator] enable production-ready features to a Spring Boot application – without having to actually implement these things yourself.
>
> They're mainly used to expose different types of information about the running application – health, metrics, info, dump, env etc. And while these are no replacement for a production-grade monitoring solution – they're a very good starting point.

```xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-actuator</artifactId>
</dependency>
```

Camel Spring Boot starter package 提供了 Camel 与 Spring Boot 集成所需功能, 例如 Camel 核心包, Actuator, Cloud, HeathCheck, Security 等功能.

```xml
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-spring-boot-starter</artifactId>
</dependency>
```

另外就是再添加具体业务程序所需要的 Camel 依赖包了, `camel-stream-starter` 提供 Camel 输入输出流功能, `camel-test-spring` 提供基于 Spring 的测试能力

```xml
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-stream-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-test-spring</artifactId>
  <scope>test</scope>
</dependency>
```

### Camel Routes

基于 Spring `@Component` 来创建 Camel Routes , 继承 `RouteBuilder` 类, 在 `configure` 方法里创建自己的流程

```java
@Component
public class SampleCamelRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:hello?period={{timer.period}}").routeId("hello")
                .transform().method("myBean", "saySomething")
                .filter(simple("${body} contains 'foo'"))
                    .to("log:foo")
                .end()
                .to("stream:out");
    }

}
```

### Configurations
在 Spring Boot 配置文件中添加程序需要的参数, 和更改一些标准配置, 例如 Spring Boot Actuator 相关配置

```yaml
# the name of Camel
camel:
  springboot:
    name: SpringBootCamel

# what to say
greeting: Hello World

# how often to trigger the timer
timer:
  period: 2000

# Spring Boot Actuator: all access to actuator endpoints without security
management:
  security:
    enabled: false

# Spring Boot Actuator: turn on actuator health check
endpoints:
  health:
    enabled: true
```

到此步骤完整代码 [Github](https://github.com/tiven-wang/spring-boot-guides/tree/camel/spring-web)

## Camel Restful API

Camel 最终要解决的问题就是 __"从哪里来到哪里去"__ , 而数据会从很多地方来,也会去很多地方。Restful API 就是数据的一种来源,本章节讲解如何在 Spring Boot 程序里配置 Camel 的 Restful API endpoints 。

### Camel Rest Dependencies
为了给 Camel 增加服务于 servlet 和 restful api 的能力,我们需要添加几个依赖

```xml
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-servlet-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-jackson-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-swagger-java-starter</artifactId>
</dependency>
```

### Camel Rest Configuration

同样在 `RouteBuilder` 里编写 Camel routes,这里需要注意使用方法 `bean` 可以调用 Spring 的 Component。

```java
@Override
public void configure() throws Exception {
  restConfiguration()
          .contextPath("/camel-rest-jpa").apiContextPath("/api-doc")
              .apiProperty("api.title", "Camel REST API")
              .apiProperty("api.version", "1.0")
              .apiProperty("cors", "true")
              .apiContextRouteId("doc-api")
          .bindingMode(RestBindingMode.json);

  rest("/books").description("Books REST service")
      .get("/").description("The list of all the books")
          .route().routeId("books-api")
          .bean("bookRepository", "getAll")
          .endRest()
      .get("/{id}").description("Details of an book by id")
          .route().routeId("book-api")
          .bean("bookRepository", "getByIsbn(${header.id})");
}
```

这需要在配置文件中增加参数,为 Camel servlet 配置路径

```yaml
camel:
  ...
  component:
      servlet:
        mapping:
          contextPath: /camel-rest-jpa/*
```

其中原理是 `camel-servlet-starter` package 里的代码逻辑把 CamelServlet 和 Spring Context 和 Spring Servlet 做了连接。Camel servlet 本身使用了 [Swagger][swagger] 做 Restful APIs 的管理。

### Test

直接在浏览器中访问以下 Restful API 链接

* *http://localhost:8080/camel-rest-jpa/api-doc*

* http://localhost:8080/camel-rest-jpa/books

* http://localhost:8080/camel-rest-jpa/books/123

完整代码 [Github](https://github.com/tiven-wang/spring-boot-guides/tree/camel/restful-api)

[Camel]:http://camel.apache.org/
[spring-boot]:https://projects.spring.io/spring-boot/
[Undertow]:http://undertow.io/
[howto-embedded-servlet-containers]:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html
[Spring Boot Actuator]:https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready.html
[swagger]:https://swagger.io/

[eip]:http://camel.apache.org/enterprise-integration-patterns.html
[Enterprise_Integration_Patterns]:https://en.wikipedia.org/wiki/Enterprise_Integration_Patterns

[camel-example-spring-boot-rest-jpa]:https://github.com/apache/camel/tree/master/examples/camel-example-spring-boot-rest-jpa


text:
package com.dtwoz.util;

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

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dtwoz.entity.User;

@Repository
public class HibernateUtil {

	@Autowired
    private SessionFactory sessionFactory;

    public <T> Serializable create(final T entity) {
        return sessionFactory.getCurrentSession().save(entity);
    }

    public <T> T update(final T entity) {
        sessionFactory.getCurrentSession().update(entity);
        return entity;
    }

	public <T> void delete(final T entity) {
		sessionFactory.getCurrentSession().delete(entity);
	}

	public <T> void delete(Serializable id, Class<T> entityClass) {
		T entity = fetchById(id, entityClass);
		delete(entity);
	}

    @SuppressWarnings("unchecked")
    public <T> List<T> fetchAll(Class<T> entityClass) {
        return sessionFactory.getCurrentSession().createQuery(" FROM "+entityClass.getName()).list();
    }

    @SuppressWarnings("rawtypes")
	public <T> List fetchAll(String query) {
        return sessionFactory.getCurrentSession().createSQLQuery(query).list();
    }

    @SuppressWarnings("unchecked")
	public <T> T fetchById(Serializable id, Class<T> entityClass) {
        return (T)sessionFactory.getCurrentSession().get(entityClass, id);
    }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'layout.html' %}
            {% block content %}

{{ p_list }}'s Inventory

{{ name }}

                {%- if inv %}

{{ p_list }} {{ inv['health'] }} {{ inv['mana'] }} {{ inv['group'] }}

Inventory

                    {%- for item in inv['inv']['inv'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Coins

                    {%- for item in inv['inv']['coins'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Ammo

                    {%- for item in inv['inv']['ammo'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Armor

                    {%- for item in inv['inv']['armor'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Vanity Armor

                    {%- for item in inv['inv']['vanity'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Dye

                    {%- for item in inv['inv']['dye'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Equipment

                    {%- for item in inv['inv']['equipment'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Equipment Dye

                    {%- for item in inv['inv']['eqdye'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Piggy Bank

                    {%- for item in inv['inv']['piggy'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Safe

                    {%- for item in inv['inv']['safe'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Forge

                    {%- for item in inv['inv']['forge'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Void

                    {%- for item in inv['inv']['void'] %}

                        {%- if item != 0 %}

{{ item[3] }}

                        {%- endif %}

                    {%- endfor %}

Trash

                    {%- set item = inv['inv']['trash'] %}

                    {%- if item != 0 %}

{{ item[3] }}

                    {%- endif %}

                {%- endif %}

        {%- endblock %}


text:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

    Sports News Combinator By Sachin Ohri


text:
<?php
namespace FruitMachine;

class Util {
  static $i = 0;

  public static function uniqueId($prefix = null) {
    $prefix = is_null($prefix)
      ? $prefix
      : 'id';
    return $prefix . ((++static::$i) * round(rand() / getrandmax() * 100000));
  }

}


text:
package org.citygml4j.cityjson.adapter.geometry.serializer;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.citygml4j.cityjson.adapter.Fields;
import org.citygml4j.cityjson.adapter.appearance.serializer.AppearanceSerializer;
import org.citygml4j.cityjson.model.geometry.GeometryType;
import org.citygml4j.cityjson.writer.CityJSONSerializerHelper;
import org.citygml4j.core.model.core.ImplicitGeometry;
import org.xmlobjects.gml.model.geometry.AbstractGeometry;
import org.xmlobjects.gml.model.geometry.DirectPosition;
import org.xmlobjects.gml.model.geometry.primitives.Point;
import org.xmlobjects.gml.util.jama.Matrix;

import java.util.*;

public class GeometrySerializer {
    public static final int DEFAULT_VERTEX_PRECISION = 3;
    public static final int DEFAULT_TEMPLATE_PRECISION = 3;

    private final AppearanceSerializer appearanceSerializer;
    private final CityJSONSerializerHelper helper;
    private final Map<String, TemplateInfo> templates = new HashMap<>();
    private final VerticesBuilder verticesBuilder = new VerticesBuilder(DEFAULT_VERTEX_PRECISION);
    private final VerticesBuilder templatesVerticesBuilder = new VerticesBuilder(DEFAULT_TEMPLATE_PRECISION);

    private boolean transformTemplateGeometries;

    public GeometrySerializer(AppearanceSerializer appearanceSerializer, CityJSONSerializerHelper helper) {
        this.appearanceSerializer = appearanceSerializer;
        this.helper = helper;
    }

    public VerticesBuilder getVerticesBuilder() {
        return verticesBuilder;
    }

    public VerticesBuilder getTemplatesVerticesBuilder() {
        return templatesVerticesBuilder;
    }

    public boolean isTransformTemplateGeometries() {
        return transformTemplateGeometries;
    }

    public void setTransformTemplateGeometries(boolean transformTemplateGeometries) {
        this.transformTemplateGeometries = transformTemplateGeometries;
    }

    public void addGeometry(AbstractGeometry geometry, Number lod, ObjectNode object, EnumSet<GeometryType> allowedTypes) {
        buildGeometry(geometry, lod, helper.getOrPutArray(Fields.GEOMETRY, object), allowedTypes, verticesBuilder);
    }

    public ObjectNode getGeometry(AbstractGeometry geometry, Number lod, EnumSet<GeometryType> allowedTypes) {
        return createGeometry(geometry, lod, verticesBuilder, allowedTypes);
    }

    public void addTemplateGeometry(ImplicitGeometry geometry, Number lod, ObjectNode object, EnumSet<GeometryType> allowedTypes) {
        if (geometry == null
                || geometry.getRelativeGeometry() == null
                || geometry.getRelativeGeometry().getObject() == null
                || geometry.getReferencePoint() == null
                || geometry.getReferencePoint().getObject() == null
                || geometry.getTransformationMatrix() == null) {
            return;
        }

        if (!transformTemplateGeometries) {
            buildTemplateGeometry(geometry, lod, object, allowedTypes);
        } else {
            convertTemplateGeometry(geometry, lod, object, allowedTypes);
        }
    }

    public boolean hasTemplates() {
        return !templates.isEmpty();
    }

    public Iterator<ObjectNode> getTemplates() {
        return templates.values().stream()
                .sorted(Comparator.comparingInt(TemplateInfo::getIndex))
                .map(TemplateInfo::getNode)
                .iterator();
    }

    private ObjectNode createGeometry(AbstractGeometry geometry, Number lod, VerticesBuilder verticesBuilder, EnumSet<GeometryType> allowedTypes) {
        ArrayNode node = helper.createArray();
        buildGeometry(geometry, lod, node, allowedTypes, verticesBuilder);
        return node.size() == 1 ? (ObjectNode) node.get(0) : null;
    }

    private void buildGeometry(AbstractGeometry geometry, Number lod, ArrayNode node, EnumSet<GeometryType> allowedTypes, VerticesBuilder verticesBuilder) {
        if (geometry != null && allowedTypes != null) {
            MultiGeometryBuilder builder = new MultiGeometryBuilder(allowedTypes, appearanceSerializer, verticesBuilder, helper);
            geometry.accept(builder);
            builder.build(geometry, lod, node);
        }
    }

    private void buildTemplateGeometry(ImplicitGeometry geometry, Number lod, ObjectNode object, EnumSet<GeometryType> allowedTypes) {
        AbstractGeometry relativeGeometry = geometry.getRelativeGeometry().getObject();
        TemplateInfo templateInfo = templates.get(helper.getOrCreateId(relativeGeometry));
        if (templateInfo == null) {
            ObjectNode template = createGeometry(relativeGeometry, lod, templatesVerticesBuilder, EnumSet.allOf(GeometryType.class));
            templateInfo = template != null ?
                    new TemplateInfo(template, templates.size()) :
                    TemplateInfo.NULL_TEMPLATE;

            templates.put(relativeGeometry.getId(), templateInfo);
        }

        if (templateInfo == TemplateInfo.NULL_TEMPLATE) {
            return;
        }

        GeometryType type = GeometryType.fromValue(templateInfo.getNode().path(Fields.TYPE).asText());
        if (!allowedTypes.contains(type)) {
            return;
        }

        double[] matrix = geometry.getTransformationMatrix().getValue().getRowPackedCopy();
        Point referencePoint = geometry.getReferencePoint().getObject();

        List<Double> coordinates = referencePoint.toCoordinateList3D();
        coordinates.set(0, coordinates.get(0) + matrix[3]);
        coordinates.set(1, coordinates.get(1) + matrix[7]);
        coordinates.set(2, coordinates.get(2) + matrix[11]);

        matrix[3] = 0;
        matrix[7] = 0;
        matrix[11] = 0;

        ObjectNode boundary = createGeometry(new Point(new DirectPosition(coordinates)), lod, verticesBuilder, EnumSet.of(GeometryType.MULTI_POINT));
        if (boundary == null) {
            return;
        }

        ObjectNode node = helper.getOrPutArray(Fields.GEOMETRY, object).addObject();
        node.put(Fields.TYPE, GeometryType.TEMPLATE_GEOMETRY.toTypeName());
        node.put(Fields.TEMPLATE, templateInfo.getIndex());
        node.set(Fields.BOUNDARIES, boundary.path(Fields.BOUNDARIES));
        ArrayNode transformationMatrix = node.putArray(Fields.TRANSFORMATION_MATRIX);
        Arrays.stream(matrix).forEach(transformationMatrix::add);
    }

    private void convertTemplateGeometry(ImplicitGeometry geometry, Number lod, ObjectNode object, EnumSet<GeometryType> allowedTypes) {
        Matrix matrix = geometry.getTransformationMatrix().getValue();
        List<Double> translate = geometry.getReferencePoint().getObject().toCoordinateList3D();

        VerticesBuilder builder = new VerticesBuilder(0) {
            @Override
            public List<Integer> addVertices(List<Double> vertices) {
                int size = vertices.size();
                for (int i = 0; i < size; i += 3) {
                    if (i + 3 > size) {
                        break;
                    }

                    Matrix v = new Matrix(new double[]{vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), 1}, 4);
                    v = matrix.times(v);

                    vertices.set(i, v.get(0, 0) + translate.get(0));
                    vertices.set(i + 1, v.get(1, 0) + translate.get(1));
                    vertices.set(i + 2, v.get(2, 0) + translate.get(2));
                }

                return verticesBuilder.addVertices(vertices);
            }
        };

        AbstractGeometry relativeGeometry = geometry.getRelativeGeometry().getObject();
        buildGeometry(relativeGeometry, lod, helper.getOrPutArray(Fields.GEOMETRY, object), allowedTypes, builder);
    }

    public void reset() {
        verticesBuilder.reset();
        templatesVerticesBuilder.reset();
        templates.clear();
    }
}


text:
Portal eduCOLTEC

O portal educativo do COLTEC!!

        Novo Vídeo

video_label

Assista

            Aprenda quando e onde quiser assistindo um dos {{videosCtrl.videos.length}} vídeos disponibilizados no portal!!

star

Avalie e Compartilhe

            Gostou do vídeo? Avalie e compartilhe com seus amigos!!

add_to_queue

Adicione novos vídeos

            Deseja adicionar um novo vídeo que viu na web? Deseja disponibilizar um vídeo seu? Basta cadastrá-lo no portal!!

Vídeos Disponíveis Atualmente

              {{video.curso}}more_vert

              {{video.disciplina}}

              {{video.titulo}}

              Resumoclose

{{video.resumo}}

              Vídeo
              Comentários

        Fechar

Comentários

            Nota:  grade

            Comentário

              {{comentario.comentario}}

        Novo
        Fechar


text:
import configureStore from './configure-store.dev.js'
import renderPanels from './render.js'

export const render = props => (
  renderPanels(configureStore, props)
)

if (!window.panelsDontAutoLoad) {
  window.addEventListener('load', () => {
    window._store = render(window.panels)
  })
}


text:
package generic

import "testing"

func TestMockBuffer(t *testing.T) {
	text := "This is text"
	seq := "This is sequence"

	buf := new(mockBuffer)
	buf.WriteString(text)
	buf.WriteANSISequence(seq)

	if buf.Len() != len(text) {
		t.Fatalf("mock buffer length %d differs from text length %d", buf.Len(), len(text))
	}
}


text:
<?php

/**
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
 *
 */

namespace SwaggerPetstore\models;

use \ArrayAccess;

class GoogleMapsResponse implements ArrayAccess {
  static $swaggerTypes = array(
      'locations' => 'array[GoogleMapsLocation]'
  );

  static $attributeMap = array(
      'locations' => 'locations'
  );

  public $locations; /* array[GoogleMapsLocation] */

  public function __construct(array $data = null) {
    $this->locations = $data["locations"];
  }

  public function offsetExists($offset) {
    return isset($this->$offset);
  }

  public function offsetGet($offset) {
    return $this->$offset;
  }

  public function offsetSet($offset, $value) {
    $this->$offset = $value;
  }

  public function offsetUnset($offset) {
    unset($this->$offset);
  }
}


text:
package com.querydsl.codegen;

import com.google.common.base.Function;
import com.mysema.codegen.StringUtils;
import com.querydsl.core.util.JavaSyntaxUtils;

/**
 * Default variable name generation strategy which un-capitalizes the first letter of the class name.
 *
 */
public final class DefaultVariableNameFunction implements Function<EntityType, String> {

    public static final DefaultVariableNameFunction INSTANCE = new DefaultVariableNameFunction();

    @Override
    public String apply(EntityType entity) {
        String uncapSimpleName = StringUtils.uncapitalize(entity.getInnerType().getSimpleName());
        if (JavaSyntaxUtils.isReserved(uncapSimpleName)) {
            uncapSimpleName = uncapSimpleName + "$";
        }
        return uncapSimpleName;
    }
}


text:
icon = Image.load("IMG/cover.png")

timer = 0
font = Font.createProportional()
font:setPixelSizes(0,18)

function printCenteredfont(y,text,color)
  local length = string.len(text)
  local x = 240 - ((length*8)/2)
  screen:fontPrint(font,x,y,text,color)
end

while true do
  screen:clear()
  timer = timer + 1

  screen:blit(0,0,icon)
  printCenteredfont(220,"Chargement de Lua System Mp3 Player...", Color.new(0,255,0))

  if timer >= 40 then
    collectgarbage()
    dofile("loadmp3.lua")
  end

  screen.waitVblankStart()
  screen.flip()
end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText android:id="@+id/edittext1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <EditText android:id="@+id/edittext2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number" />

    <EditText android:id="@+id/edittext3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textUri" />

    <EditText android:id="@+id/edittext4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" />

    <EditText android:id="@+id/edittext5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

</LinearLayout>


text:
{% for row in a.proteins %}>{{ row.protein.entry_name }}
{% for segment, s in row.alignment.items %}{% for r in s %}{{ r.2 }}{% endfor %}{% endfor %}
{% endfor %}


text:
require 'spec_helper'

describe "Stub ajax request", js: true do
  let(:message) { 'my custom message' }
  let(:api_path) { '/api/path' }

  before do
    stub_ajax url: api_path, responseText: { message: message }
    visit home_index_path
  end

  it 'stubs the ajax request and returns the correct message' do
    page.execute_script("$.getJSON('#{api_path}', function(data) { $('body').append(data.message) })")
    wait_until do
      page.has_content?(message)
    end
  end
end


text:
(function () {
  'use strict';

  angular
    .module('files')
    .run(menuConfig);

  menuConfig.$inject = ['menuService'];

  function menuConfig(menuService) {

    // Add the dropdown list item
    menuService.addSubMenuItem('topbar', 'admin', {
      title: 'Files',
      state: 'files.list'
    });
  }
}());


text:
package org.datanucleus.samples.types.timezone;

import java.util.TimeZone;

/**
 * Holder of TimeZone type to use as a test for persisting basic information.
 */
public class TimeZoneHolder
{
    private TimeZone timeZoneField;

    public TimeZoneHolder()
    {
        super();
    }

    public TimeZone getTimeZoneField()
    {
        return timeZoneField;
    }

    public void setTimeZoneField(TimeZone zone)
    {
        this.timeZoneField = zone;
    }

    /**
     * Indicates whether some other object is "equal to" this one.  By comparing
     * against an original copy of the object, compareTo() can be
     * used to verify that the object has been written to a database and read back correctly.
     *
     * @param obj the reference object with which to compare
     * @return true if this object is equal to the obj argument; false otherwise.
     */
    public boolean compareTo(Object obj)
    {
        if (obj == this)
        {
            return true;
        }

        if (!(obj instanceof TimeZoneHolder))
        {
            return false;
        }

        TimeZoneHolder w = (TimeZoneHolder)obj;

        if (timeZoneField == null)
        {
            if (w.timeZoneField != null)
            {
                return false;
            }
        }
        else if (!timeZoneField.toString().equals(w.timeZoneField.toString()))
        {
            return false;
        }

        return true;
    }

    /**
     * Returns a string representation for this object.
     * All of the field values are included in the string for debugging purposes.
     * @return a string representation for this object.
     */
    public String toString()
    {
        StringBuffer s = new StringBuffer(super.toString());

        s.append("  timeZoneField = ").append(timeZoneField);
        s.append('\n');

        return s.toString();
    }
}


text:
<?php

/**
 * CViewAction represents an action that displays a view according to a user-specified parameter.
 *
 * By default, the view being displayed is specified via the view GET parameter.
 * The name of the GET parameter can be customized via {@link viewParam}.
 * If the user doesn't provide the GET parameter, the default view specified by {@link defaultView}
 * will be displayed.
 *
 * Users specify a view in the format of path.to.view, which translates to the view name
 * BasePath/path/to/view where BasePath is given by {@link basePath}.
 *
 * Note, the user specified view can only contain word characters, dots and dashes and
 * the first letter must be a word letter.
 *
 * @property string $requestedView The name of the view requested by the user.
 * This is in the format of 'path.to.view'.
 *
 * @author  Qiang Xue <qiang.xue@gmail.com>
 * @package system.web.actions
 * @since   1.0
 */
class CViewAction extends CAction
{

    /**
     * @var string the name of the GET parameter that contains the requested view name. Defaults to 'view'.
     */
    public $viewParam = 'view';
    /**
     * @var string the name of the default view when {@link viewParam} GET parameter is not provided by user. Defaults to 'index'.
     * This should be in the format of 'path.to.view', similar to that given in
     * the GET parameter.
     * @see basePath
     */
    public $defaultView = 'index';
    /**
     * @var string the name of the view to be rendered. This property will be set
     * once the user requested view is resolved.
     */
    public $view;
    /**
     * @var string the base path for the views. Defaults to 'pages'.
     * The base path will be prefixed to any user-specified page view.
     * For example, if a user requests for tutorial.chap1, the corresponding view name will
     * be pages/tutorial/chap1, assuming the base path is pages.
     * The actual view file is determined by {@link CController::getViewFile}.
     * @see CController::getViewFile
     */
    public $basePath = 'pages';
    /**
     * @var mixed the name of the layout to be applied to the views.
     * This will be assigned to {@link CController::layout} before the view is rendered.
     * Defaults to null, meaning the controller's layout will be used.
     * If false, no layout will be applied.
     */
    public $layout;
    /**
     * @var boolean whether the view should be rendered as PHP script or static text. Defaults to false.
     */
    public $renderAsText = false;

    private $_viewPath;

    /**
     * Returns the name of the view requested by the user.
     * If the user doesn't specify any view, the {@link defaultView} will be returned.
     *
     * @return string the name of the view requested by the user.
     * This is in the format of 'path.to.view'.
     */
    public function getRequestedView()
    {

        if ($this->_viewPath === null) {
            if (!empty($_GET[$this->viewParam]) && is_string($_GET[$this->viewParam])) {
                $this->_viewPath = $_GET[$this->viewParam];
            } else {
                $this->_viewPath = $this->defaultView;
            }
        }
        return $this->_viewPath;
    }

    /**
     * Resolves the user-specified view into a valid view name.
     *
     * @param string $viewPath user-specified view in the format of 'path.to.view'.
     *
     * @return string fully resolved view in the format of 'path/to/view'.
     * @throw CHttpException if the user-specified view is invalid
     */
    protected function resolveView($viewPath)
    {

        // start with a word char and have word chars, dots and dashes only
        if (preg_match('/^\w[\w\.\-]*$/', $viewPath)) {
            $view = strtr($viewPath, '.', '/');
            if (!empty($this->basePath)) {
                $view = $this->basePath . '/' . $view;
            }
            if ($this->getController()->getViewFile($view) !== false) {
                $this->view = $view;
                return;
            }
        }
        throw new CHttpException(404, Yii::t(
            'yii',
            'The requested view "{name}" was not found.',
            array('{name}' => $viewPath)
        ));
    }

    /**
     * Runs the action.
     * This method displays the view requested by the user.
     *
     * @throws CHttpException if the view is invalid
     */
    public function run()
    {

        $this->resolveView($this->getRequestedView());
        $controller = $this->getController();
        if ($this->layout !== null) {
            $layout             = $controller->layout;
            $controller->layout = $this->layout;
        }

        $this->onBeforeRender($event = new CEvent($this));
        if (!$event->handled) {
            if ($this->renderAsText) {
                $text = file_get_contents($controller->getViewFile($this->view));
                $controller->renderText($text);
            } else {
                $controller->render($this->view);
            }
            $this->onAfterRender(new CEvent($this));
        }

        if ($this->layout !== null) {
            $controller->layout = $layout;
        }
    }

    /**
     * Raised right before the action invokes the render method.
     * Event handlers can set the {@link CEvent::handled} property
     * to be true to stop further view rendering.
     *
     * @param CEvent $event event parameter
     */
    public function onBeforeRender($event)
    {

        $this->raiseEvent('onBeforeRender', $event);
    }

    /**
     * Raised right after the action invokes the render method.
     *
     * @param CEvent $event event parameter
     */
    public function onAfterRender($event)
    {

        $this->raiseEvent('onAfterRender', $event);
    }
}


text:
3.0.2

- Fix UnicodeDecodeError being thrown when sending payload due to jsonpickle not pickling large binary values correctly (such as local variable bytestrings or high-codepoint unicode characters)
- Guard added for tracebacks with null method names (such as exceptions from C-wrapper libraries)

3.0.1

- Updated bdist egg to include middleware package
- Fix WSGI logging message

3.0.0

- Added functions: ignore_exceptions, filter_keys, set_proxy, on_before_send
- Added support for local variables, global variables, and environment variables
- Added CLI for testing provider
- Py2: Added web middleware (Django, Flask and WSGI)
- Py2: Added send_exception function (see below)
- send() deprecated in favor of send_exception(); see the Sending Functions in the readme for the available options

2.2.0

- Added new send_exception() method for Py3
- Added support for chained exceptions for Py3
- Automatically detect class name - this no longer needs to be provided on send() and as such this parameter is deprecated.
- Support Google App Engine by disabling multiprocessing module if not available

2.0.1

- Fix bug when exceptions received from C++ libraries

2.0.0

- Added port of library to Python 3
- Minor bugfix where OS version wasn't correctly transmitted (Environment tab in Dashboard)

1.1.3

- Fixed bug when logging with RaygunHandler attached but not passing exception data crashes program

1.1.2

- Fixed a bug where the IP address had invalid casing resulting in it being unable to be read by the API
- Fixed a bug if set_user wasn't called leading to a error
- Renamed samples and moved them to a more appropriate folder
- Added unit tests

1.1.1

- Fixed a critical bug in 1.1.0; the previous version is not recommended - use this instead.

1.1.0

- Added set_user function for unique user tracking; internal refactor to make module more pythonic

1.0.0

- **Breaking change:** changed module name to raygun4py. Now use *from raygun4py import raygunprovider*

- Added ability to send HTTP request data

0.1.2

- PyPi package
- RST file

0.1

- Initial release; basic message creation and transport functionality


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/** @fileoverview Suite of tests for extension-item. */
cr.define('extension_service_tests', function() {
  /** @constructor */
  function ChangeListener() {}

  ChangeListener.prototype = {
    /**
     * @param {!ChromeEvent} chromeEvent
     * @param {!function(...):boolean} matchFunction
     */
    init_: function(chromeEvent, matchFunction) {
      this.onUpdate = new Promise(function(resolve, reject) {
        this.resolvePromise_ = resolve;
      }.bind(this));
      this.listener_ = this.onChanged_.bind(this);
      this.event_ = chromeEvent;
      this.matches_ = matchFunction;
      this.event_.addListener(this.listener_);
    },

    /** @private */
    onChanged_: function() {
      if (this.matches_.apply(null, arguments)) {
        setTimeout(function() {
          this.event_.removeListener(this.listener_);
          this.resolvePromise_();
        }.bind(this));
      }
    },
  };

  /**
   * @param {string} id The id of the item to watch.
   * @param {chrome.developerPrivate.EventType} eventType The type of event
   *     to wait for.
   * @extends {extension_service_tests.ChangeListener}
   * @constructor
   */
  function ItemChangedListener(id, eventType) {
    this.__proto__ = ChangeListener.prototype,
    this.init_(chrome.developerPrivate.onItemStateChanged,
               function(data) {
      return data.event_type == eventType && data.item_id == id;
    });
  }

  /**
   * @extends {extension_service_tests.ChangeListener}
   * @constructor
   */
  function ProfileChangedListener() {
    this.__proto__ = ChangeListener.prototype,
    this.init_(chrome.developerPrivate.onProfileStateChanged,
               function() { return true; });
  }

  /** @enum {string} */
  var TestNames = {
    EnableAndDisable: 'enable and disable',
    ToggleIncognitoMode: 'toggle incognito mode',
    Uninstall: 'uninstall',
    ProfileSettings: 'profile settings',
  };

  function registerTests() {
    suite('ExtensionServiceTest', function() {
      /** @const{string} */
      var kExtensionId = 'ldnnhddmnhbkjipkidpdiheffobcpfmf';

      /** @const */
      var EventType = chrome.developerPrivate.EventType;

      /** @const */
      var ExtensionState = chrome.developerPrivate.ExtensionState;

      /** @type {extensions.Service} */
      var service;

      /** @type {extensions.Manager} */
      var manager;

      suiteSetup(function() {
        return PolymerTest.importHtml('chrome://extensions/service.html');
      });

      // Initialize an extension item before each test.
      setup(function() {
        service = extensions.Service.getInstance();
        manager = document.getElementsByTagName('extensions-manager')[0];
      });

      test(assert(TestNames.EnableAndDisable), function(done) {
        var item = manager.getItem(kExtensionId);
        assertTrue(!!item);
        expectEquals(kExtensionId, item.id);
        expectEquals('My extension 1', item.data.name);
        expectEquals(ExtensionState.ENABLED, item.data.state);

        var disabledListener =
            new ItemChangedListener(kExtensionId, EventType.UNLOADED);
        service.setItemEnabled(kExtensionId, false);
        disabledListener.onUpdate.then(function() {
          expectEquals(ExtensionState.DISABLED, item.data.state);

          enabledListener =
              new ItemChangedListener(kExtensionId, EventType.LOADED);
          service.setItemEnabled(kExtensionId, true);
          return enabledListener.onUpdate;
        }).then(function() {
          expectEquals(ExtensionState.ENABLED, item.data.state);
          done();
        });
      });

      test(assert(TestNames.ToggleIncognitoMode), function(done) {
        var item = manager.getItem(kExtensionId);
        assertTrue(!!item);
        expectTrue(item.data.incognitoAccess.isEnabled);
        expectFalse(item.data.incognitoAccess.isActive);

        var incognitoListener =
            new ItemChangedListener(kExtensionId, EventType.LOADED);
        chrome.test.runWithUserGesture(function() {
          service.setItemAllowedIncognito(kExtensionId, true);
        });
        incognitoListener.onUpdate.then(function() {
          expectTrue(item.data.incognitoAccess.isActive);

          var disabledIncognitoListener =
              new ItemChangedListener(kExtensionId, EventType.LOADED);
          chrome.test.runWithUserGesture(function() {
            service.setItemAllowedIncognito(kExtensionId, false);
          });
          return disabledIncognitoListener.onUpdate;
        }).then(function() {
          expectFalse(item.data.incognitoAccess.isActive);
          done();
        });
      });

      test(assert(TestNames.Uninstall), function(done) {
        var item = manager.getItem(kExtensionId);
        assertTrue(!!item);
        var uninstallListener =
            new ItemChangedListener(kExtensionId, EventType.UNINSTALLED);
        chrome.test.runWithUserGesture(function() {
          service.deleteItem(kExtensionId);
        });
        uninstallListener.onUpdate.then(function() {
          expectFalse(!!manager.getItem(kExtensionId));
          done();
        });
      });

      test(assert(TestNames.ProfileSettings), function(done) {
        var item = manager.getItem(kExtensionId);
        assertTrue(!!item);
        expectFalse(item.inDevMode);

        var profileListener = new ProfileChangedListener();
        service.setProfileInDevMode(true);

        profileListener.onUpdate.then(function() {
          expectTrue(item.inDevMode);

          var noDevModeProfileListener = new ProfileChangedListener();
          service.setProfileInDevMode(false);
          return noDevModeProfileListener.onUpdate;
        }).then(function() {
          expectFalse(item.inDevMode);
          done();
        });
      });
    });
  }

  return {
    ChangeListener: ChangeListener,
    registerTests: registerTests,
    TestNames: TestNames,
  };
});


text:
package org.olap4j.driver.xmla;

import org.olap4j.OlapException;
import org.olap4j.impl.*;
import org.olap4j.metadata.*;

import java.util.List;

/**
 * Implementation of {@link org.olap4j.metadata.Hierarchy}
 * for XML/A providers.
 *
 * @author jhyde
 * @since Dec 4, 2007
 */
class XmlaOlap4jHierarchy
    extends XmlaOlap4jElement
    implements Hierarchy, DisplayFolder, Named
{
    final XmlaOlap4jDimension olap4jDimension;
    final NamedList<XmlaOlap4jLevel> levels;
    private final boolean all;
    private final String defaultMemberUniqueName;
    private final String hierarchyDisplayFolder;

    XmlaOlap4jHierarchy(
        XmlaOlap4jDimension olap4jDimension,
        String uniqueName,
        String name,
        String caption,
        String description,
        String hierarchyDisplayFolder,
        boolean all,
        String defaultMemberUniqueName) throws OlapException
    {
        super(uniqueName, name, caption, description);
        assert olap4jDimension != null;
        this.olap4jDimension = olap4jDimension;
        this.all = all;
        this.defaultMemberUniqueName = defaultMemberUniqueName;
        this.hierarchyDisplayFolder = hierarchyDisplayFolder;

        String[] hierarchyRestrictions = {
            "CATALOG_NAME",
            olap4jDimension.olap4jCube.olap4jSchema.olap4jCatalog.getName(),
            "SCHEMA_NAME",
            olap4jDimension.olap4jCube.olap4jSchema.getName(),
            "CUBE_NAME",
            olap4jDimension.olap4jCube.getName(),
            "DIMENSION_UNIQUE_NAME",
            olap4jDimension.getUniqueName(),
            "HIERARCHY_UNIQUE_NAME",
            getUniqueName()
        };

        this.levels = new DeferredNamedListImpl<XmlaOlap4jLevel>(
            XmlaOlap4jConnection.MetadataRequest.MDSCHEMA_LEVELS,
            new XmlaOlap4jConnection.Context(
                olap4jDimension.olap4jCube.olap4jSchema.olap4jCatalog
                    .olap4jDatabaseMetaData.olap4jConnection,
                olap4jDimension.olap4jCube.olap4jSchema.olap4jCatalog
                    .olap4jDatabaseMetaData,
                olap4jDimension.olap4jCube.olap4jSchema.olap4jCatalog,
                olap4jDimension.olap4jCube.olap4jSchema,
                olap4jDimension.olap4jCube,
                olap4jDimension,
                this, null),
            new XmlaOlap4jConnection.LevelHandler(olap4jDimension.olap4jCube),
            hierarchyRestrictions);
    }

    public Dimension getDimension() {
        return olap4jDimension;
    }

    public NamedList<Level> getLevels() {
        return Olap4jUtil.cast(levels);
    }

    public boolean hasAll() {
        return all;
    }

    public Member getDefaultMember() throws OlapException {
        if (defaultMemberUniqueName == null) {
            return null;
        }
        return olap4jDimension.olap4jCube.getMetadataReader()
            .lookupMemberByUniqueName(
                defaultMemberUniqueName);
    }

    public NamedList<Member> getRootMembers() throws OlapException {
        final List<XmlaOlap4jMember> memberList =
            olap4jDimension.olap4jCube.getMetadataReader().getLevelMembers(
                levels.get(0));
        final NamedList<XmlaOlap4jMember> list =
            new NamedListImpl<XmlaOlap4jMember>(memberList);
        return Olap4jUtil.cast(list);
    }

    @Override
    public String getDisplayFolder() {
        return hierarchyDisplayFolder;
    }

    public boolean equals(Object obj) {
        return (obj instanceof XmlaOlap4jHierarchy)
            && this.uniqueName.equals(
                ((XmlaOlap4jHierarchy) obj).getUniqueName());
    }
}

// End XmlaOlap4jHierarchy.java


text:
namespace ui {

// A class through which an AcceleratedWidget may be bound to draw the contents
// of an NSView. An AcceleratedWidget may be bound to multiple different views
// throughout its lifetime (one at a time, though).
class AcceleratedWidgetMacNSView {
 public:
  // Called when the AcceleratedWidgetMac's CALayerFrameSink interface's
  // UpdateCALayerTree method is called. This is used to update background
  // colors and to suppressing drawing of blank windows until content is
  // available.
  virtual void AcceleratedWidgetCALayerParamsUpdated() = 0;
};

// AcceleratedWidgetMac owns a tree of CALayers. The widget may be passed
// to a ui::Compositor, which will, through its output surface, call the
// CALayerFrameSink interface. The CALayers may be installed in an NSView
// by setting the AcceleratedWidgetMacNSView for the helper.
class ACCELERATED_WIDGET_MAC_EXPORT AcceleratedWidgetMac
    : public CALayerFrameSink {
 public:
  AcceleratedWidgetMac();
  ~AcceleratedWidgetMac() override;

  gfx::AcceleratedWidget accelerated_widget() { return native_widget_; }

  void SetNSView(AcceleratedWidgetMacNSView* view);
  void ResetNSView();

  // Returns the CALayer parameters most recently sent to the CALayerFrameSink
  // interface, or nullptr if none are available.
  const gfx::CALayerParams* GetCALayerParams() const;

  // Return true if the last frame swapped has a size in DIP of |dip_size|.
  bool HasFrameOfSize(const gfx::Size& dip_size) const;

  // If |suspended| is true, then ignore all new frames that come in until
  // a call is made with |suspended| as false.
  void SetSuspended(bool suspended);

 private:
  // For CALayerFrameSink::FromAcceleratedWidget to access Get.
  friend class CALayerFrameSink;

  // Translate from a gfx::AcceleratedWidget handle to the underlying
  // AcceleratedWidgetMac (used by other gfx::AcceleratedWidget translation
  // functions).
  static AcceleratedWidgetMac* Get(gfx::AcceleratedWidget widget);

  // gfx::CALayerFrameSink implementation:
  void UpdateCALayerTree(const gfx::CALayerParams& ca_layer_params) override;

  // The AcceleratedWidgetMacNSView that is using this as its internals.
  AcceleratedWidgetMacNSView* view_ = nullptr;

  // A phony NSView handle used to identify this.
  gfx::AcceleratedWidget native_widget_ = gfx::kNullAcceleratedWidget;

  // If the output surface is suspended, then updates to the layer parameters
  // will be ignored.
  bool is_suspended_ = false;

  // The last CALayer parameter update from the CALayerFrameSink interface.
  bool last_ca_layer_params_valid_ = false;
  gfx::CALayerParams last_ca_layer_params_;

  DISALLOW_COPY_AND_ASSIGN(AcceleratedWidgetMac);
};

}  // namespace ui

#endif  // UI_ACCELERATED_WIDGET_MAC_ACCELERATED_WIDGET_MAC_H_


text:
namespace base {
 class Thread;
}

namespace mojo {

class ServiceManager;

// mojo::Spy is a troubleshooting and debugging aid. It helps tracking
// the mojo system core activities like messages, service creation, etc.
//
// The |options| parameter in the constructor comes from the command
// line of the mojo_shell. Which takes --spy=<options>. Each option is
// separated by ',' and each option is a key+ value pair separated by ':'.
//
// For example --spy=port:13333
//
class Spy {
 public:
  Spy(mojo::ServiceManager* service_manager, const std::string& options);
  ~Spy();

 private:
   // This thread runs the code that talks to the frontend.
   scoped_ptr<base::Thread> control_thread_;
};

}  // namespace mojo

#endif  // MOJO_SPY_SPY_H_


text:
package com.gitblit.transport.ssh.git;

import com.gitblit.git.GitblitReceivePackFactory;
import com.gitblit.git.GitblitUploadPackFactory;
import com.gitblit.git.RepositoryResolver;
import com.gitblit.manager.IGitblit;
import com.gitblit.transport.ssh.SshDaemonClient;
import com.gitblit.transport.ssh.commands.BaseCommand;
import com.gitblit.transport.ssh.commands.CommandMetaData;
import com.gitblit.transport.ssh.commands.DispatchCommand;
import com.gitblit.transport.ssh.commands.SshCommandContext;

@CommandMetaData(name = "git", description="Git repository commands")
public class GitDispatcher extends DispatchCommand {

	protected RepositoryResolver<SshDaemonClient> repositoryResolver;
	protected GitblitUploadPackFactory<SshDaemonClient> uploadPackFactory;
	protected GitblitReceivePackFactory<SshDaemonClient> receivePackFactory;

	@Override
	public void setContext(SshCommandContext context) {
		super.setContext(context);

		IGitblit gitblit = context.getGitblit();
		repositoryResolver = new RepositoryResolver<SshDaemonClient>(gitblit);
		uploadPackFactory = new GitblitUploadPackFactory<SshDaemonClient>(gitblit);
		receivePackFactory = new GitblitReceivePackFactory<SshDaemonClient>(gitblit);
	}

	@Override
	public void destroy() {
		super.destroy();

		repositoryResolver = null;
		receivePackFactory = null;
		uploadPackFactory = null;
	}

	@Override
	protected void setup() {
		register(Upload.class);
		register(Receive.class);
		register(GarbageCollectionCommand.class);
	}

	@Override
	protected void provideStateTo(final BaseCommand cmd) {
		super.provideStateTo(cmd);

		BaseGitCommand a = (BaseGitCommand) cmd;
		a.setRepositoryResolver(repositoryResolver);
		a.setUploadPackFactory(uploadPackFactory);
		a.setReceivePackFactory(receivePackFactory);
	}
}


text:
/** @stable */
export declare class BrowserTestingModule {
}

/** @stable */
export declare const platformBrowserTesting: (extraProviders?: Provider[]) => PlatformRef;


text:
package shop_point.action;

import org.seasar.struts.annotation.Execute;

public class IndexAction {

	public String word;

    @Execute(validator = false)
	public String index() {
    	word = "Hello World";
        return "index.ftl";
	}
}


text:
<?php

namespace WellCommerce\Bundle\GeneratorBundle\Generator;

/**
 * Class FormBuilderGenerator
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class FormBuilderGenerator
{

}


text:
Mailgun - Messages
====================

This is the Mailgun Ruby *Message* utilities.

The below assumes you've already installed the Mailgun Ruby SDK in to your
project. If not, go back to the master README for instructions.

There are two utilities included, Message Builder and Batch Message.

Message Builder: Allows you to build a message object by calling methods for
each MIME attribute.
Batch Message: Inherits Message Builder and allows you to iterate through
recipients from a list. Messages will fire after the 1,000th recipient has been
added.

Usage - Message Builder
-----------------------
Here's how to use Message Builder to build your Message.

```ruby
# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new("your-api-key")
mb_obj = Mailgun::MessageBuilder.new

# Define the from address.
mb_obj.set_from_address("me@example.com", {"first"=>"Ruby", "last" => "SDK"});
# Define a to recipient.
mb_obj.add_recipient(:to, "john.doe@example.com", {"first" => "John", "last" => "Doe"});
# Define a cc recipient.
mb_obj.add_recipient(:cc, "sally.doe@example.com", {"first" => "Sally", "last" => "Doe"});
# Define the subject.
mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");
# Define the body of the message.
mb_obj.set_text_body("This is the text body of the message!");
# Set the Message-Id header. Pass in a valid Message-Id.
mb_obj.set_message_id("<20141014000000.11111.11111@example.com>")
# Clear the Message-Id header. Pass in nil or empty string.
mb_obj.set_message_id(nil)
mb_obj.set_message_id('')
# Other Optional Parameters.
mb_obj.add_campaign_id("My-Awesome-Campaign");
mb_obj.add_custom_parameter("h:Customer-Id", "12345");
mb_obj.add_attachment("@/tron.jpg");
mb_obj.set_delivery_time("tomorrow 8:00AM", "PST");
mb_obj.set_click_tracking(true);

# Send your message through the client
mg_client.send_message("sending_domain.com", mb_obj)
```

Usage - Batch Message
---------------------
Here's how to use Batch Message to easily handle batch sending jobs.

```ruby
# First, instantiate the Mailgun Client with your API key
mg_client = Mailgun::Client.new("your-api-key")
mb_obj = Mailgun::BatchMessage.new(mg_client, "example.com")

# Define the from address.
mb_obj.set_from_address("me@example.com", {"first"=>"Ruby", "last" => "SDK"});
# Define the subject.
mb_obj.set_subject("A message from the Ruby SDK using Message Builder!");
# Define the body of the message.
mb_obj.set_text_body("Hello %recipient.first%,
                     This is the text body of the message
                     using recipient variables!
                     If you need to include custom data,
                     you could do it like this: %account-id%.");

mb_obj.add_recipient(:to, "john.doe@example.com", {"first"      => "John",
                                                   "last"       => "Doe",
                                                   "account-id" => 1234});
mb_obj.add_recipient(:to, "jane.doe@example.com", {"first"      => "Jane",
                                                   "last"       => "Doe",
                                                   "account-id" => 5678});
mb_obj.add_recipient(:to, "bob.doe@example.com", {"first"       => "Bob",
                                                  "last"        => "Doe",
                                                  "account-id"  => 91011});
...
mb_obj.add_recipient(:to, "sally.doe@example.com", {"first"      => "Sally",
                                                    "last"       => "Doe",
                                                    "account-id" => 121314});

# Send your message through the client
message_ids = mb_obj.finalize
```

More Documentation
------------------
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
for more information.


text:
#![cfg(any(target_os = "windows"))]

use ContextError;
use CreationError;
use GlAttributes;
use GlContext;
use GlRequest;
use GlProfile;
use PixelFormat;
use PixelFormatRequirements;
use Robustness;
use Api;

use self::make_current_guard::CurrentContextGuard;

use std::ffi::{CStr, CString, OsStr};
use std::os::raw::{c_void, c_int};
use std::os::windows::ffi::OsStrExt;
use std::{mem, ptr};
use std::io;

use winapi;
use kernel32;
use user32;
use gdi32;

mod make_current_guard;
mod gl;

/// A WGL context.
///
/// Note: should be destroyed before its window.
pub struct Context {
    context: ContextWrapper,

    hdc: winapi::HDC,

    /// Binded to `opengl32.dll`.
    ///
    /// `wglGetProcAddress` returns null for GL 1.1 functions because they are
    ///  already defined by the system. This module contains them.
    gl_library: winapi::HMODULE,

    /// The pixel format that has been used to create this context.
    pixel_format: PixelFormat,
}

/// A simple wrapper that destroys the window when it is destroyed.
struct WindowWrapper(winapi::HWND, winapi::HDC);

impl Drop for WindowWrapper {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            user32::DestroyWindow(self.0);
        }
    }
}

/// Wraps around a context so that it is destroyed when necessary.
struct ContextWrapper(winapi::HGLRC);

impl Drop for ContextWrapper {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            gl::wgl::DeleteContext(self.0 as *const _);
        }
    }
}

impl Context {
    /// Attempt to build a new WGL context on a window.
    ///
    /// The window must **not** have had `SetPixelFormat` called on it.
    ///
    /// # Unsafety
    ///
    /// The `window` must continue to exist as long as the resulting `Context` exists.
    pub unsafe fn new(pf_reqs: &PixelFormatRequirements, opengl: &GlAttributes<winapi::HGLRC>,
                      window: winapi::HWND) -> Result<Context, CreationError>
    {
        let hdc = user32::GetDC(window);
        if hdc.is_null() {
            let err = Err(CreationError::OsError(format!("GetDC function failed: {}",
                                                format!("{}", io::Error::last_os_error()))));
            return err;
        }

        // loading the functions that are not guaranteed to be supported
        let extra_functions = try!(load_extra_functions(window));

        // getting the list of the supported extensions
        let extensions = if extra_functions.GetExtensionsStringARB.is_loaded() {
            let data = extra_functions.GetExtensionsStringARB(hdc as *const _);
            let data = CStr::from_ptr(data).to_bytes().to_vec();
            String::from_utf8(data).unwrap()

        } else if extra_functions.GetExtensionsStringEXT.is_loaded() {
            let data = extra_functions.GetExtensionsStringEXT();
            let data = CStr::from_ptr(data).to_bytes().to_vec();
            String::from_utf8(data).unwrap()

        } else {
            format!("")
        };

        // calling SetPixelFormat
        let pixel_format = {
            let formats = if extensions.split(' ').find(|&i| i == "WGL_ARB_pixel_format")
                                                  .is_some()
            {
                let f = enumerate_arb_pixel_formats(&extra_functions, &extensions, hdc);
                if f.is_empty() {
                    enumerate_native_pixel_formats(hdc)
                } else {
                    f
                }
            } else {
                enumerate_native_pixel_formats(hdc)
            };

            let (id, f) = try!(pf_reqs.choose_pixel_format(formats));
            try!(set_pixel_format(hdc, id));
            f
        };

        // creating the OpenGL context
        let context = try!(create_context(Some((&extra_functions, pf_reqs, opengl, &extensions)),
                                          window, hdc));

        // loading the opengl32 module
        let gl_library = try!(load_opengl32_dll());

        // handling vsync
        if extensions.split(' ').find(|&i| i == "WGL_EXT_swap_control").is_some() {
            let _guard = try!(CurrentContextGuard::make_current(hdc, context.0));

            if extra_functions.SwapIntervalEXT(if opengl.vsync { 1 } else { 0 }) == 0 {
                return Err(CreationError::OsError(format!("wglSwapIntervalEXT failed")));
            }
        }

        Ok(Context {
            context: context,
            hdc: hdc,
            gl_library: gl_library,
            pixel_format: pixel_format,
        })
    }

    /// Returns the raw HGLRC.
    #[inline]
    pub fn get_hglrc(&self) -> winapi::HGLRC {
        self.context.0
    }
}

impl GlContext for Context {
    #[inline]
    unsafe fn make_current(&self) -> Result<(), ContextError> {
        if gl::wgl::MakeCurrent(self.hdc as *const _, self.context.0 as *const _) != 0 {
            Ok(())
        } else {
            Err(ContextError::IoError(io::Error::last_os_error()))
        }
    }

    #[inline]
    fn is_current(&self) -> bool {
        unsafe { gl::wgl::GetCurrentContext() == self.context.0 as *const c_void }
    }

    fn get_proc_address(&self, addr: &str) -> *const () {
        let addr = CString::new(addr.as_bytes()).unwrap();
        let addr = addr.as_ptr();

        unsafe {
            let p = gl::wgl::GetProcAddress(addr) as *const _;
            if !p.is_null() { return p; }
            kernel32::GetProcAddress(self.gl_library, addr) as *const _
        }
    }

    #[inline]
    fn swap_buffers(&self) -> Result<(), ContextError> {
        // TODO: decide how to handle the error
        /*if unsafe { gdi32::SwapBuffers(self.hdc) } != 0 {
            Ok(())
        } else {
            Err(ContextError::IoError(io::Error::last_os_error()))
        }*/
        unsafe { gdi32::SwapBuffers(self.hdc) };
        Ok(())
    }

    #[inline]
    fn get_api(&self) -> Api {
        // FIXME: can be opengl es
        Api::OpenGl
    }

    #[inline]
    fn get_pixel_format(&self) -> PixelFormat {
        self.pixel_format.clone()
    }
}

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

/// Creates an OpenGL context.
///
/// If `extra` is `Some`, this function will attempt to use the latest WGL functions to create the
/// context.
///
/// Otherwise, only the basic API will be used and the chances of `CreationError::NotSupported`
/// being returned increase.
unsafe fn create_context(extra: Option<(&gl::wgl_extra::Wgl, &PixelFormatRequirements,
                                        &GlAttributes<winapi::HGLRC>, &str)>,
                         _: winapi::HWND, hdc: winapi::HDC)
                         -> Result<ContextWrapper, CreationError>
{
    let share;

    if let Some((extra_functions, pf_reqs, opengl, extensions)) = extra {
        share = opengl.sharing.unwrap_or(ptr::null_mut());

        if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context").is_some() {
            let mut attributes = Vec::new();

            match opengl.version {
                GlRequest::Latest => {},
                GlRequest::Specific(Api::OpenGl, (major, minor)) => {
                    attributes.push(gl::wgl_extra::CONTEXT_MAJOR_VERSION_ARB as c_int);
                    attributes.push(major as c_int);
                    attributes.push(gl::wgl_extra::CONTEXT_MINOR_VERSION_ARB as c_int);
                    attributes.push(minor as c_int);
                },
                GlRequest::Specific(Api::OpenGlEs, (major, minor)) => {
                    if extensions.split(' ').find(|&i| i == "WGL_EXT_create_context_es2_profile")
                                            .is_some()
                    {
                        attributes.push(gl::wgl_extra::CONTEXT_PROFILE_MASK_ARB as c_int);
                        attributes.push(gl::wgl_extra::CONTEXT_ES2_PROFILE_BIT_EXT as c_int);
                    } else {
                        return Err(CreationError::OpenGlVersionNotSupported);
                    }

                    attributes.push(gl::wgl_extra::CONTEXT_MAJOR_VERSION_ARB as c_int);
                    attributes.push(major as c_int);
                    attributes.push(gl::wgl_extra::CONTEXT_MINOR_VERSION_ARB as c_int);
                    attributes.push(minor as c_int);
                },
                GlRequest::Specific(_, _) => return Err(CreationError::OpenGlVersionNotSupported),
                GlRequest::GlThenGles { opengl_version: (major, minor), .. } => {
                    attributes.push(gl::wgl_extra::CONTEXT_MAJOR_VERSION_ARB as c_int);
                    attributes.push(major as c_int);
                    attributes.push(gl::wgl_extra::CONTEXT_MINOR_VERSION_ARB as c_int);
                    attributes.push(minor as c_int);
                },
            }

            if let Some(profile) = opengl.profile {
                if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_profile").is_some()
                {
                    let flag = match profile {
                        GlProfile::Compatibility =>
                            gl::wgl_extra::CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
                        GlProfile::Core =>
                            gl::wgl_extra::CONTEXT_CORE_PROFILE_BIT_ARB,
                    };
                    attributes.push(gl::wgl_extra::CONTEXT_PROFILE_MASK_ARB as c_int);
                    attributes.push(flag as c_int);
                } else {
                    return Err(CreationError::NotSupported);
                }
            }

            let flags = {
                let mut flags = 0;

                // robustness
                if extensions.split(' ').find(|&i| i == "WGL_ARB_create_context_robustness").is_some() {
                    match opengl.robustness {
                        Robustness::RobustNoResetNotification | Robustness::TryRobustNoResetNotification => {
                            attributes.push(gl::wgl_extra::CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB as c_int);
                            attributes.push(gl::wgl_extra::NO_RESET_NOTIFICATION_ARB as c_int);
                            flags = flags | gl::wgl_extra::CONTEXT_ROBUST_ACCESS_BIT_ARB as c_int;
                        },
                        Robustness::RobustLoseContextOnReset | Robustness::TryRobustLoseContextOnReset => {
                            attributes.push(gl::wgl_extra::CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB as c_int);
                            attributes.push(gl::wgl_extra::LOSE_CONTEXT_ON_RESET_ARB as c_int);
                            flags = flags | gl::wgl_extra::CONTEXT_ROBUST_ACCESS_BIT_ARB as c_int;
                        },
                        Robustness::NotRobust => (),
                        Robustness::NoError => (),
                    }
                } else {
                    match opengl.robustness {
                        Robustness::RobustNoResetNotification | Robustness::RobustLoseContextOnReset => {
                            return Err(CreationError::RobustnessNotSupported);
                        },
                        _ => ()
                    }
                }

                if opengl.debug {
                    flags = flags | gl::wgl_extra::CONTEXT_DEBUG_BIT_ARB as c_int;
                }

                flags
            };

            attributes.push(gl::wgl_extra::CONTEXT_FLAGS_ARB as c_int);
            attributes.push(flags);

            attributes.push(0);

            let ctxt = extra_functions.CreateContextAttribsARB(hdc as *const c_void,
                                                               share as *const c_void,
                                                               attributes.as_ptr());

            if ctxt.is_null() {
                return Err(CreationError::OsError(format!("wglCreateContextAttribsARB failed: {}",
                                                      format!("{}", io::Error::last_os_error()))));
            } else {
                return Ok(ContextWrapper(ctxt as winapi::HGLRC));
            }
        }

    } else {
        share = ptr::null_mut();
    }

    let ctxt = gl::wgl::CreateContext(hdc as *const c_void);
    if ctxt.is_null() {
        return Err(CreationError::OsError(format!("wglCreateContext failed: {}",
                                                  format!("{}", io::Error::last_os_error()))));
    }

    if !share.is_null() {
        if gl::wgl::ShareLists(share as *const c_void, ctxt) == 0 {
            return Err(CreationError::OsError(format!("wglShareLists failed: {}",
                                                      format!("{}", io::Error::last_os_error()))));
        }
    };

    Ok(ContextWrapper(ctxt as winapi::HGLRC))
}

/// Enumerates the list of pixel formats without using WGL.
///
/// Gives less precise results than `enumerate_arb_pixel_formats`.
unsafe fn enumerate_native_pixel_formats(hdc: winapi::HDC) -> Vec<(c_int, PixelFormat)> {
    let size_of_pxfmtdescr = mem::size_of::<winapi::PIXELFORMATDESCRIPTOR>() as u32;
    let num = gdi32::DescribePixelFormat(hdc, 1, size_of_pxfmtdescr, ptr::null_mut());

    let mut result = Vec::new();

    for index in (0 .. num) {
        let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed();

        if gdi32::DescribePixelFormat(hdc, index, size_of_pxfmtdescr, &mut output) == 0 {
            continue;
        }

        if (output.dwFlags & winapi::PFD_DRAW_TO_WINDOW) == 0 {
            continue;
        }

        if (output.dwFlags & winapi::PFD_SUPPORT_OPENGL) == 0 {
            continue;
        }

        if output.iPixelType != winapi::PFD_TYPE_RGBA {
            continue;
        }

        result.push((index, PixelFormat {
            hardware_accelerated: (output.dwFlags & winapi::PFD_GENERIC_FORMAT) == 0,
            color_bits: output.cRedBits + output.cGreenBits + output.cBlueBits,
            alpha_bits: output.cAlphaBits,
            depth_bits: output.cDepthBits,
            stencil_bits: output.cStencilBits,
            stereoscopy: (output.dwFlags & winapi::PFD_STEREO) != 0,
            double_buffer: (output.dwFlags & winapi::PFD_DOUBLEBUFFER) != 0,
            multisampling: None,
            srgb: false,
        }));
    }

    result
}

/// Enumerates the list of pixel formats by using extra WGL functions.
///
/// Gives more precise results than `enumerate_native_pixel_formats`.
unsafe fn enumerate_arb_pixel_formats(extra: &gl::wgl_extra::Wgl, extensions: &str,
                                      hdc: winapi::HDC) -> Vec<(c_int, PixelFormat)>
{
    let get_info = |index: u32, attrib: u32| {
        let mut value = mem::uninitialized();
        extra.GetPixelFormatAttribivARB(hdc as *const _, index as c_int,
                                        0, 1, [attrib as c_int].as_ptr(),
                                        &mut value);
        value as u32
    };

    // getting the number of formats
    // the `1` is ignored
    let num = get_info(1, gl::wgl_extra::NUMBER_PIXEL_FORMATS_ARB);

    let mut result = Vec::new();

    for index in (0 .. num) {
        if get_info(index, gl::wgl_extra::DRAW_TO_WINDOW_ARB) == 0 {
            continue;
        }
        if get_info(index, gl::wgl_extra::SUPPORT_OPENGL_ARB) == 0 {
            continue;
        }

        if get_info(index, gl::wgl_extra::ACCELERATION_ARB) == gl::wgl_extra::NO_ACCELERATION_ARB {
            continue;
        }

        if get_info(index, gl::wgl_extra::PIXEL_TYPE_ARB) != gl::wgl_extra::TYPE_RGBA_ARB {
            continue;
        }

        result.push((index as c_int, PixelFormat {
            hardware_accelerated: true,
            color_bits: get_info(index, gl::wgl_extra::RED_BITS_ARB) as u8 +
                        get_info(index, gl::wgl_extra::GREEN_BITS_ARB) as u8 +
                        get_info(index, gl::wgl_extra::BLUE_BITS_ARB) as u8,
            alpha_bits: get_info(index, gl::wgl_extra::ALPHA_BITS_ARB) as u8,
            depth_bits: get_info(index, gl::wgl_extra::DEPTH_BITS_ARB) as u8,
            stencil_bits: get_info(index, gl::wgl_extra::STENCIL_BITS_ARB) as u8,
            stereoscopy: get_info(index, gl::wgl_extra::STEREO_ARB) != 0,
            double_buffer: get_info(index, gl::wgl_extra::DOUBLE_BUFFER_ARB) != 0,
            multisampling: {
                if extensions.split(' ').find(|&i| i == "WGL_ARB_multisample").is_some() {
                    match get_info(index, gl::wgl_extra::SAMPLES_ARB) {
                        0 => None,
                        a => Some(a as u16),
                    }
                } else {
                    None
                }
            },
            srgb: if extensions.split(' ').find(|&i| i == "WGL_ARB_framebuffer_sRGB").is_some() {
                get_info(index, gl::wgl_extra::FRAMEBUFFER_SRGB_CAPABLE_ARB) != 0
            } else if extensions.split(' ').find(|&i| i == "WGL_EXT_framebuffer_sRGB").is_some() {
                get_info(index, gl::wgl_extra::FRAMEBUFFER_SRGB_CAPABLE_EXT) != 0
            } else {
                false
            },
        }));
    }

    result
}

/// Calls `SetPixelFormat` on a window.
unsafe fn set_pixel_format(hdc: winapi::HDC, id: c_int) -> Result<(), CreationError> {
    let mut output: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed();

    if gdi32::DescribePixelFormat(hdc, id, mem::size_of::<winapi::PIXELFORMATDESCRIPTOR>()
                                  as winapi::UINT, &mut output) == 0
    {
        return Err(CreationError::OsError(format!("DescribePixelFormat function failed: {}",
                                                  format!("{}", io::Error::last_os_error()))));
    }

    if gdi32::SetPixelFormat(hdc, id, &output) == 0 {
        return Err(CreationError::OsError(format!("SetPixelFormat function failed: {}",
                                                  format!("{}", io::Error::last_os_error()))));
    }

    Ok(())
}

/// Loads the `opengl32.dll` library.
unsafe fn load_opengl32_dll() -> Result<winapi::HMODULE, CreationError> {
    let name = OsStr::new("opengl32.dll").encode_wide().chain(Some(0).into_iter())
                                         .collect::<Vec<_>>();

    let lib = kernel32::LoadLibraryW(name.as_ptr());

    if lib.is_null() {
        return Err(CreationError::OsError(format!("LoadLibrary function failed: {}",
                                                  format!("{}", io::Error::last_os_error()))));
    }

    Ok(lib)
}

/// Loads the WGL functions that are not guaranteed to be supported.
///
/// The `window` must be passed because the driver can vary depending on the window's
/// characteristics.
unsafe fn load_extra_functions(window: winapi::HWND) -> Result<gl::wgl_extra::Wgl, CreationError> {
    let (ex_style, style) = (winapi::WS_EX_APPWINDOW, winapi::WS_POPUP |
                             winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN);

    // creating a dummy invisible window
    let dummy_window = {
        // getting the rect of the real window
        let rect = {
            let mut placement: winapi::WINDOWPLACEMENT = mem::zeroed();
            placement.length = mem::size_of::<winapi::WINDOWPLACEMENT>() as winapi::UINT;
            if user32::GetWindowPlacement(window, &mut placement) == 0 {
                panic!();
            }
            placement.rcNormalPosition
        };

        // getting the class name of the real window
        let mut class_name = [0u16; 128];
        if user32::GetClassNameW(window, class_name.as_mut_ptr(), 128) == 0 {
            return Err(CreationError::OsError(format!("GetClassNameW function failed: {}",
                                              format!("{}", io::Error::last_os_error()))));
        }

        // this dummy window should match the real one enough to get the same OpenGL driver
        let win = user32::CreateWindowExW(ex_style, class_name.as_ptr(),
                                          b"dummy window\0".as_ptr() as *const _, style,
                                          winapi::CW_USEDEFAULT, winapi::CW_USEDEFAULT,
                                          rect.right - rect.left,
                                          rect.bottom - rect.top,
                                          ptr::null_mut(), ptr::null_mut(),
                                          kernel32::GetModuleHandleW(ptr::null()),
                                          ptr::null_mut());

        if win.is_null() {
            return Err(CreationError::OsError(format!("CreateWindowEx function failed: {}",
                                              format!("{}", io::Error::last_os_error()))));
        }

        let hdc = user32::GetDC(win);
        if hdc.is_null() {
            let err = Err(CreationError::OsError(format!("GetDC function failed: {}",
                                               format!("{}", io::Error::last_os_error()))));
            return err;
        }

        WindowWrapper(win, hdc)
    };

    // getting the pixel format that we will use and setting it
    {
        let formats = enumerate_native_pixel_formats(dummy_window.1);
        let id = try!(choose_dummy_pixel_format(formats.into_iter()));
        try!(set_pixel_format(dummy_window.1, id));
    }

    // creating the dummy OpenGL context and making it current
    let dummy_context = try!(create_context(None, dummy_window.0, dummy_window.1));
    let _current_context = try!(CurrentContextGuard::make_current(dummy_window.1,
                                                                  dummy_context.0));

    // loading the extra WGL functions
    Ok(gl::wgl_extra::Wgl::load_with(|addr| {
        let addr = CString::new(addr.as_bytes()).unwrap();
        let addr = addr.as_ptr();
        gl::wgl::GetProcAddress(addr) as *const c_void
    }))
}

/// Given a list of pixel formats, this function chooses one that is likely to be provided by
/// the main video driver of the system.
fn choose_dummy_pixel_format<I>(iter: I) -> Result<c_int, CreationError>
                                where I: Iterator<Item=(c_int, PixelFormat)>
{
    let mut backup_id = None;

    for (id, format) in iter {
        if backup_id.is_none() {
            backup_id = Some(id);
        }

        if format.hardware_accelerated {
            return Ok(id);
        }
    }

    backup_id.ok_or(CreationError::OsError("No available pixel format".to_string()))
}


text:
package org.apache.kylin.storage.hbase.coprocessor.observer;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.kylin.metadata.measure.MeasureAggregator;
import org.apache.kylin.storage.hbase.coprocessor.AggrKey;
import org.apache.kylin.storage.hbase.coprocessor.CoprocessorFilter;
import org.apache.kylin.storage.hbase.coprocessor.CoprocessorProjector;
import org.apache.kylin.storage.hbase.coprocessor.CoprocessorRowType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yangli9
 *
 */
public class AggregationScanner implements RegionScanner {

    private RegionScanner outerScanner;
    private ObserverBehavior behavior;

    public AggregationScanner(CoprocessorRowType type, CoprocessorFilter filter, CoprocessorProjector groupBy, ObserverAggregators aggrs, RegionScanner innerScanner, ObserverBehavior behavior) throws IOException {

        AggregateRegionObserver.LOG.info("Kylin Coprocessor start");

        this.behavior = behavior;

        ObserverAggregationCache aggCache;
        Stats stats = new Stats();

        aggCache = buildAggrCache(innerScanner, type, groupBy, aggrs, filter, stats);
        stats.countOutputRow(aggCache.getSize());
        this.outerScanner = aggCache.getScanner(innerScanner);

        AggregateRegionObserver.LOG.info("Kylin Coprocessor aggregation done: " + stats);
    }

    @SuppressWarnings("rawtypes")
    ObserverAggregationCache buildAggrCache(final RegionScanner innerScanner, CoprocessorRowType type, CoprocessorProjector projector, ObserverAggregators aggregators, CoprocessorFilter filter, Stats stats) throws IOException {

        ObserverAggregationCache aggCache = new ObserverAggregationCache(aggregators);

        ObserverTuple tuple = new ObserverTuple(type);
        boolean hasMore = true;
        List<Cell> results = new ArrayList<Cell>();
        while (hasMore) {
            results.clear();
            hasMore = innerScanner.nextRaw(results);
            if (results.isEmpty())
                continue;

            if (stats != null)
                stats.countInputRow(results);

            Cell cell = results.get(0);
            tuple.setUnderlying(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());

            if (behavior.ordinal() >= ObserverBehavior.SCAN_FILTER.ordinal()) {
                if (filter != null && filter.evaluate(tuple) == false)
                    continue;

                if (behavior.ordinal() >= ObserverBehavior.SCAN_FILTER_AGGR.ordinal()) {
                    AggrKey aggKey = projector.getAggrKey(results);
                    MeasureAggregator[] bufs = aggCache.getBuffer(aggKey);
                    aggregators.aggregate(bufs, results);

                    aggCache.checkMemoryUsage();
                }
            }
        }
        return aggCache;
    }

    @Override
    public boolean next(List<Cell> results) throws IOException {
        return outerScanner.next(results);
    }

    @Override
    public boolean next(List<Cell> result, int limit) throws IOException {
        return outerScanner.next(result, limit);
    }

    @Override
    public boolean nextRaw(List<Cell> result) throws IOException {
        return outerScanner.nextRaw(result);
    }

    @Override
    public boolean nextRaw(List<Cell> result, int limit) throws IOException {
        return outerScanner.nextRaw(result, limit);
    }

    @Override
    public void close() throws IOException {
        outerScanner.close();
    }

    @Override
    public HRegionInfo getRegionInfo() {
        return outerScanner.getRegionInfo();
    }

    @Override
    public boolean isFilterDone() throws IOException {
        return outerScanner.isFilterDone();
    }

    @Override
    public boolean reseek(byte[] row) throws IOException {
        return outerScanner.reseek(row);
    }

    @Override
    public long getMaxResultSize() {
        return outerScanner.getMaxResultSize();
    }

    @Override
    public long getMvccReadPoint() {
        return outerScanner.getMvccReadPoint();
    }

    private static class Stats {
        long inputRows = 0;
        long inputBytes = 0;
        long outputRows = 0;

        // have no outputBytes because that requires actual serialize all the
        // aggregator buffers

        public void countInputRow(List<Cell> row) {
            inputRows++;
            inputBytes += row.get(0).getRowLength();
            for (int i = 0, n = row.size(); i < n; i++) {
                inputBytes += row.get(i).getValueLength();
            }
        }

        public void countOutputRow(long rowCount) {
            outputRows += rowCount;
        }

        public String toString() {
            double percent = (double) outputRows / inputRows * 100;
            return Math.round(percent) + "% = " + outputRows + " (out rows) / " + inputRows + " (in rows); in bytes = " + inputBytes + "; est. out bytes = " + Math.round(inputBytes * percent / 100);
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace OpenAgenda\Test;

use OpenAgenda\Cache;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \OpenAgenda\Cache
 */
class CacheTest extends TestCase
{
    /**
     * @test
     * @covers ::get
     */
    public function testGetNull(): void
    {
        $value = Cache::get('unknown');

        $this->assertNull($value);
    }

    /**
     * @test
     * @covers ::set
     */
    public function testSet(): void
    {
        Cache::set('key', 'testing', 30);

        $value = Cache::get('key');

        $this->assertSame('testing', $value);
    }
}


text:
Simple way of controlling the lamp on the back of your phone from Xamarin and Xamarin.Forms projects

#### Setup
* Available on NuGet: https://www.nuget.org/packages/kphillpotts.Lamp.Plugin/
* Install into your PCL project and Client projects.

**Supports**
* Xamarin.iOS
* Xamarin.iOS (x64 Unified)
* Xamarin.Android
* Windows Phone 8 (Silverlight)
* Windows Phone 8.1 RT

**WINDOWS PHONE Specitic**
Necessary capabilities: ID_CAP_ISV_CAMERA, ID_CAP_MICROPHONE

**ANDROID Specific**
Please ensure you have the following permissions enabled:

```
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />
```

#### API Usage

To gain access to the Lamp class simply use this method:

```
var v = CrossLamp.Current;
```

#### Methods

```
 CrossLamp.Current.TurnOn();
```
Turns on the lamp

```
 CrossLamp.Current.TurnOff();
```
Turns off the lamp

#### Contributors
* [kphillpotts](https://github.com/kphillpotts)

#### License
Licensed under main repo license


text:
class PrefService;

namespace content {
class BrowserContext;
}  // namespace content

namespace speech {

// Provides a mojo endpoint in the browser that allows the renderer process to
// launch and initialize the sandboxed speech recognition service
// process.
class ChromeSpeechRecognitionService : public SpeechRecognitionService {
 public:
  explicit ChromeSpeechRecognitionService(content::BrowserContext* context);
  ChromeSpeechRecognitionService(const ChromeSpeechRecognitionService&) =
      delete;
  ChromeSpeechRecognitionService& operator=(const SpeechRecognitionService&) =
      delete;
  ~ChromeSpeechRecognitionService() override;

  // SpeechRecognitionService:
  void BindSpeechRecognitionContext(
      mojo::PendingReceiver<media::mojom::SpeechRecognitionContext> receiver)
      override;
  void BindAudioSourceSpeechRecognitionContext(
      mojo::PendingReceiver<media::mojom::AudioSourceSpeechRecognitionContext>
          receiver) override;

 private:
  // Launches the speech recognition service in a sandboxed utility process.
  void LaunchIfNotRunning();

  // Gets the path of the SODA configuration file for the selected language.
  base::FilePath GetSodaConfigPath(PrefService* prefs);

  // The browser context associated with the keyed service.
  const raw_ptr<content::BrowserContext> context_;

  // The remote to the speech recognition service. The browser will not launch a
  // new speech recognition service process if this remote is already bound.
  mojo::Remote<media::mojom::SpeechRecognitionService>
      speech_recognition_service_;
};

}  // namespace speech

#endif  // CHROME_BROWSER_SPEECH_CHROME_SPEECH_RECOGNITION_SERVICE_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * (C) Copyright Uwe Schindler (Generics Policeman) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
-->
<project xmlns:au="antlib:org.apache.ant.antunit">

  <condition property="has.sunmisc">
    <available classname="sun.misc.BASE64Encoder"/>
  </condition>

  <target name="testNonPortableSignatures" if="has.sunmisc">
    <au:expectfailure expectedMessage="Check for forbidden API calls failed, see log">
      <forbiddenapis failOnMissingClasses="false" targetVersion="${jdk.version}">
        <file file="OracleInternalRuntime.class"/>
        <bundledsignatures name="jdk-non-portable"/>
      </forbiddenapis>
    </au:expectfailure>
    <au:assertLogContains level="error" text="sun.misc.BASE64Encoder [non-portable or internal runtime class]"/>
    <au:assertLogContains level="error" text=" 2 error(s)"/>
  </target>

  <target name="testDeprecatedInternalRuntimeForbidden" if="has.sunmisc">
    <au:expectfailure expectedMessage="Check for forbidden API calls failed, see log">
      <forbiddenapis internalRuntimeForbidden="true" failOnMissingClasses="false">
        <file file="OracleInternalRuntime.class"/>
      </forbiddenapis>
    </au:expectfailure>
    <au:assertLogContains level="warn" text="The setting 'internalRuntimeForbidden' was deprecated"/>
    <au:assertLogContains level="error" text="sun.misc.BASE64Encoder [non-portable or internal runtime class]"/>
    <au:assertLogContains level="error" text=" 2 error(s)"/>
  </target>

  <!-- this should work also with non-Oracle runtimes, as no heuristics: -->
  <target name="testInternalSignatures">
    <au:expectfailure expectedMessage="Check for forbidden API calls failed, see log">
      <forbiddenapis failOnMissingClasses="false" targetVersion="${jdk.version}">
        <file file="OracleInternalRuntime.class"/>
        <bundledsignatures name="jdk-internal"/>
      </forbiddenapis>
    </au:expectfailure>
    <au:assertLogContains level="error" text="sun.misc.BASE64Encoder [non-public internal runtime class in Java ${jdk.version}]"/>
    <au:assertLogContains level="error" text=" 2 error(s)"/>
  </target>

</project>


text:
from django.utils.translation import ugettext_lazy as _  # noqa

from horizon import exceptions
from horizon import messages
from horizon import tabs

from openstack_dashboard import api
from contrail_openstack_dashboard.openstack_dashboard.api.contrail_quantum import *

from contrail_openstack_dashboard.openstack_dashboard.dashboards.project.\
    networking.tables import NetworksTable

from contrail_openstack_dashboard.openstack_dashboard.dashboards.project.\
    networking.policy.tables import NetworkPolicyTable

from contrail_openstack_dashboard.openstack_dashboard.dashboards.project.\
    networking.ipam.tables import NetworkIpamTable

class NetworksTab(tabs.TableTab):
    table_classes = (NetworksTable,)
    name = _("Networks")
    slug = "networks_tab"
    template_name = "horizon/common/_detail_table.html"

    def get_networks_data(self):
        try:
            tenant_id = self.request.user.tenant_id
            networks = api.neutron.network_list_for_tenant(self.request,
                                                           tenant_id)
        except Exception:
            networks = []
            msg = _('Network list can not be retrieved.')
            exceptions.handle(self.request, msg)
        for n in networks:
            n.set_id_as_name_if_empty()
        return networks

class NetworkPolicyTab(tabs.TableTab):
    table_classes = (NetworkPolicyTable,)
    name = _("Network Policies")
    slug = "policy_tab"
    template_name = "horizon/common/_detail_table.html"

    def get_policy_data(self):
        tenant_id = self.request.user.tenant_id
        try:
            policy = policy_summary_for_tenant(self.request, tenant_id)
        except Exception:
            policy = []
            exceptions.handle(self.request,
                              _('Unable to retrieve network policies.'))
        return policy

class NetworkIpamTab(tabs.TableTab):
    table_classes = (NetworkIpamTable,)
    name = _("Network IPAMs")
    slug = "ipam_tab"
    template_name = "horizon/common/_detail_table.html"

    def get_ipam_data(self):
        tenant_id = self.request.user.tenant_id
        try:
            ipam = ipam_summary_for_tenant(self.request, tenant_id)
        except Exception:
            ipam = []
            exceptions.handle(self.request,
                              _('Unable to retrieve network ipams.'))
        return ipam

class NetworkingTabs(tabs.TabGroup):
    slug = "networking_tabs"
    tabs = (NetworksTab, NetworkPolicyTab, NetworkIpamTab,)
    sticky = True


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="90dp" >

    <ImageView
        android:id="@+id/album_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/deafult_imgloading" />

    <ProgressBar
        android:id="@+id/progressbar"
        style="@style/progressBarHorizontal_color"
        android:layout_width="match_parent"
        android:layout_height="8dip"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="3dip"
        android:layout_marginLeft="3dip"
        android:layout_marginRight="3dip" />

    <ImageView
        android:id="@+id/load_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/materials_isdownload"
        android:visibility="gone" />

</RelativeLayout>


text:
module Thunderbucket
	module Stores
		autoload :Redis, 'thunderbucket/store_backends/redis'
		autoload :Memory, 'thunderbucket/store_backends/memory'

		def id
			@id ||= autoincrement_id
		end

		def autoincrement_id
			Thunderbucket.backend.next_id_for(self.class)
		end

		def save
			Thunderbucket.log("Saving to a #{backend}")
			Thunderbucket.backend.set(Thunderbucket.backend.namespace(self.class, self.id), backend.serialize_attributes(@attribute_values))
			self.class.indexed_attributes.each {|attrib|
				Thunderbucket.log("Updating index for #{attrib}")
				if @attribute_values[attrib] then
					if @saved_attributes[attrib] and (@saved_attributes[attrib] != @attribute_values[attrib]) then
						Thunderbucket.backend.clear(Thunderbucket.backend.namespace(self.class, 'indexes', attrib, @saved_attributes[attrib]))
					else
						p @saved_attributes
						p @attribute_values
					end
					Thunderbucket.backend.set(Thunderbucket.backend.namespace(self.class, 'indexes', attrib, @attribute_values[attrib]), self.id)
				end

				@saved_attributes[attrib] = @attribute_values[attrib]
			}
		end

		def self.free_backend
		end

		def self.initialize_backend(backend)
			Thunderbucket.log("Initializing a backend of #{backend}")
			Memory.new # TODO
		end

		class Store

			def serialize_attributes(attributes)
				Thunderbucket.log("Serializing #{attributes}")
				attributes.to_yaml
			end

			def deserialize_attributes(data)
				YAML.load(data) unless data.nil?
			end

			def namespace(*tree)
				tree.join('.')
			end

			def denamespace(string)
				tree.split('.')
			end

			def set(key,val)
			end

			def get(key)
			end

			def clear(key)
			end

			def transact(&block)
			end

			def next_id_for(object)
			end

		end

	end
end


text:
_LIBCPP_BEGIN_NAMESPACE_STD

namespace __refstring_imp { namespace {
typedef int count_t;

struct _Rep_base {
    std::size_t len;
    std::size_t cap;
    count_t     count;
};

inline _Rep_base* rep_from_data(const char *data_) noexcept {
    char *data = const_cast<char *>(data_);
    return reinterpret_cast<_Rep_base *>(data - sizeof(_Rep_base));
}

inline char * data_from_rep(_Rep_base *rep) noexcept {
    char *data = reinterpret_cast<char *>(rep);
    return data + sizeof(*rep);
}

#if defined(__APPLE__)
inline
const char* compute_gcc_empty_string_storage() _NOEXCEPT
{
    void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD);
    if (handle == nullptr)
        return nullptr;
    void* sym = dlsym(handle, "_ZNSs4_Rep20_S_empty_rep_storageE");
    if (sym == nullptr)
        return nullptr;
    return data_from_rep(reinterpret_cast<_Rep_base *>(sym));
}

inline
const char*
get_gcc_empty_string_storage() _NOEXCEPT
{
    static const char* p = compute_gcc_empty_string_storage();
    return p;
}
#endif

}} // namespace __refstring_imp

using namespace __refstring_imp;

inline
__libcpp_refstring::__libcpp_refstring(const char* msg) {
    std::size_t len = strlen(msg);
    _Rep_base* rep = static_cast<_Rep_base *>(::operator new(sizeof(*rep) + len + 1));
    rep->len = len;
    rep->cap = len;
    rep->count = 0;
    char *data = data_from_rep(rep);
    std::memcpy(data, msg, len + 1);
    __imp_ = data;
}

inline
__libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT
    : __imp_(s.__imp_)
{
    if (__uses_refcount())
        __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1);
}

inline
__libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) _NOEXCEPT {
    bool adjust_old_count = __uses_refcount();
    struct _Rep_base *old_rep = rep_from_data(__imp_);
    __imp_ = s.__imp_;
    if (__uses_refcount())
        __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1);
    if (adjust_old_count)
    {
        if (__libcpp_atomic_add(&old_rep->count, count_t(-1)) < 0)
        {
            ::operator delete(old_rep);
        }
    }
    return *this;
}

inline
__libcpp_refstring::~__libcpp_refstring() {
    if (__uses_refcount()) {
        _Rep_base* rep = rep_from_data(__imp_);
        if (__libcpp_atomic_add(&rep->count, count_t(-1)) < 0) {
            ::operator delete(rep);
        }
    }
}

inline
bool __libcpp_refstring::__uses_refcount() const {
#ifdef __APPLE__
    return __imp_ != get_gcc_empty_string_storage();
#else
    return true;
#endif
}

_LIBCPP_END_NAMESPACE_STD

#endif //_LIBCPPABI_REFSTRING_H