text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;

use app\models\Curso;
use app\models\CursoSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;

/**
 * CursoController implements the CRUD actions for Curso model.
 */
class CursoController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'acess' => [
                'class' => AccessControl::className(),
                'only' => ['create','index','update', 'view', 'delete', 'done'],
                'rules' => [
                    [
                        'actions' => ['create','index','update', 'view', 'delete', 'done'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                            if (!Yii::$app->user->isGuest)
                            {
                                if ( Yii::$app->user->identity->perfil === 'Administrador' )
                                {
                                    return Yii::$app->user->identity->perfil == 'Administrador';
                                }
                            }
                        }
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Curso models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CursoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionDone($id, $mensagem)
    {
        return $this->render('done', [
            'model' => $this->findModel($id),
            'mensagem' => $mensagem,
        ]);
    }

    /**
     * Displays a single Curso model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Curso model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Curso();

        if ( $model->load(Yii::$app->request->post()) )
        {
            $model->nome_curso = strtoupper($model->nome_curso);
            $model->codigo_curso = strtoupper($model->codigo_curso);
            $model->save();
            return $this->redirect(['done', 'id' => $model->id_curso, 'mensagem' => 'Curso cadastrado com sucesso!']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Curso model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ( $model->load(Yii::$app->request->post()) )
        {
            $model->nome_curso = strtoupper($model->nome_curso);
            $model->codigo_curso = strtoupper($model->codigo_curso);
            $model->save();
            return $this->redirect(['done', 'id' => $model->id_curso, 'mensagem' => 'Curso atualizado com sucesso!']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Curso model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if ( Yii::$app->user->identity->perfil === 'Administrador' )
        {
            $this->findModel($id)->delete();

            return $this->redirect(['index']);
        }
    }

    /**
     * Finds the Curso model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Curso the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Curso::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('A página requistada não existe.');
        }
    }
}


text:
<?php

abstract class Document_Tag_Area_Abstract {

    /**
     * @var Zend_View
     */
    protected $view;

    /**
     * @var Zend_Config
     */
    protected $config;

    /**
     * @var Document_Tag_Area_Info
     */
    protected $brick;

    /**
     * @var array
     */
    protected $params = array();

    /**
     * @param $view
     * @return void
     */
    public function setView ($view) {
        $this->view = $view;
        return $this;
    }

    /**
     * @return Zend_View
     */
    public function getView() {
        return $this->view;
    }

    /**
     * @param $config
     * @return void
     */
    public function setConfig ($config) {
        $this->config = $config;
        return $this;
    }

    /**
     * @return Zend_Config
     */
    public function getConfig() {
        return $this->config;
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getParam($key) {
        if(array_key_exists($key, $this->params)) {
            return $this->params[$key];
        }
        return;
    }

    /**
     * @return array
     */
    public function getAllParams () {
        return $this->params;
    }

    /**
     * @deprecated
     * @param $key
     * @return mixed
     */
    public function _getParam($key) {
        return $this->getParam($key);
    }

    /**
     * @deprecated
     * @return array
     */
    public function _getAllParams () {
        return $this->getAllParams();
    }

    /**
     * @param $key
     * @param $value
     * @return void
     */
    public function addParam ($key, $value) {
        $this->params[$key] = $value;
    }

    /**
     * @param $params
     * @return void
     */
    public function setParams ($params) {
        $this->params = $params;
        return $this;
    }

    /**
     * @param \Document_Tag_Area_Info $brick
     */
    public function setBrick($brick)
    {
        $this->brick = $brick;
        return $this;
    }

    /**
     * @return \Document_Tag_Area_Info
     */
    public function getBrick()
    {
        return $this->brick;
    }
}

redpajama_set_name: RedPajamaGithub


text:
aq_pjk
======

old js/jquery project on quran translation/indexing (ID:Indonesian) web app using json as the database.

you can view the online version at [https://aq-pjk.mindhackers.org](https://aq-pjk.mindhackers.org)

> backup url at [https://d2vcn6tp2a6ffw.cloudfront.net](https://d2vcn6tp2a6ffw.cloudfront.net)

> p/s: This app is viewable on mobile web browser

## Features

- 2x grid base indexing surrah / ayyah - fastest navigation
- search translation which accept up to 4 keywords - use spacebar key between keywords


text:
"""
Interfaz de usuario en línea de comandos.

Utiliza *ncurses*.
"""

import curses
import curses.textpad

from . import main

def run():
    """
    Correr la interfaz.
    """

    ui = UI()

class UI:
    """
    Controla la interfaz de usuario.
    """

    def __init__(self):

        self._terminado = False # indica cuando salir del loop principal
        self._calc = main.Calc()

        # encierro en try..finally porque en el caso de error debo cerrar
        # *curses* correctamente, de lo contrario la terminal queda desacomodada
        try:
            self._terminal = _Terminal()
            self._loop()
        finally:
            self._terminal.cerrar()
            print("Hay algo mal que no anda bien")

    def _loop(self):
        """
        Loop principal del programa.
        """

        while not self._terminado:
            self._imprimir_stack()
            self._procesar_entrada()

    def _imprimir_stack(self):
        """
        Limpia la pantalla y muestra el contenido del *stack*.
        """

        self._terminal.limpiar()
        lista = self._calc.lista()
        for i, n in enumerate(lista):
            # dejar una linea en blanco y una para el cuadro de texto, dibujar
            # de arriba a abajo
            y = self._terminal.alto - 2 - len(lista) + i
            self._terminal.escribir(0, y, str(n))

        self._terminal.actualizar()

    def _procesar_entrada(self):
        """
        Permite al usuario ingresar números o comandos.

        En el caso que el comando ingresado sea inválido, vuelve a imprimir el
        *stack*, muestra un mensaje de error y espera un nuevo intento.
        """

        terminado = False
        while not terminado:
            comandos = self._terminal.leer_entrada().strip().split(" ")

            try:
                for comando in comandos:
                    self._calc.ejecutar(comando)
            except ValueError as e:
                # mostrar error arriba de la pantalla
                y = self._terminal.alto - 2
                self._imprimir_stack()
                self._terminal.escribir(0, y, str(e), curses.A_REVERSE)
                self._terminal.actualizar()
            else:
                terminado = True

class _Terminal:
    """
    Implementa el código relacionado a *curses*.

    *curses* es una librería que permite trabajar con la terminal, pero como es
    bastante engorrosa de usar, meto todo lo que necesito en esta clase.

    Implementa una ventana en donde se puede escribir texto, y la última línea
    es un cuadro de texto en donde el usuario puede escribir.

    Attributes:
        alto (int): Alto de la pantalla en líneas.
        ancho (int): Ancho de la pantalla en columnas.
    """

    def __init__(self):

        # crear pantalla
        self._stdscr = curses.initscr()

        self.alto, self.ancho = self._stdscr.getmaxyx()

        # no dejar al usuario escribir en pantalla, solamente cuando nosotros
        # queramos
        curses.noecho()

        # dejar que curses maneje teclas como *Re Pag*
        self._stdscr.keypad(True)

        # crear cuadro de texto abajo de la pantalla
        self._editwin = curses.newwin(1, self.ancho, self.alto - 1, 0)
        self._editbox = curses.textpad.Textbox(self._editwin)

    def limpiar(self):
        """
        Limpiar la pantalla.

        No limpia el cuadro de texto.
        """
        self._stdscr.clear()

    def escribir(self, x, y, texto, estilo=curses.A_NORMAL):
        """
        Escribir texto en una posición específica de la pantalla.

        Opcionalmente se puede especificar un estilo para el texto. Los estilos
        deben ser algunas de las constantes presentes en *curses*, como por
        ejemplo ``curses.A_BOLD``.
        """
        self._stdscr.addstr(y, x, texto, estilo)

    def leer_entrada(self):
        """
        Dar foco al cuadro de texto y devolver lo ingresado por el usuario.

        Da foco al cuadro de texto y bloquea hasta que el usuario haya terminado
        de escribir, luego devuelve lo ingresado y borra el cuadro de texto.
        """

        self._editbox.edit() # lee entrada y bloquea hasta que se presione Enter
        entrada = self._editbox.gather()
        self._editwin.clear()
        return entrada

    def actualizar(self):
        """
        Refresca la pantalla para que se vean reflejados los cambios.

        También refresca el cuadro de texto.
        """

        self._stdscr.refresh()
        self._editwin.refresh()

    def cerrar(self):
        """
        Cierra *curses* correctamente.

        Como *curses* cambia el comportamiento de la terminal, al cerrar hay que
        revertir los cambios sino la terminal queda medio desacomodada.
        """

        curses.nocbreak()
        self._stdscr.keypad(False)
        curses.echo()
        curses.endwin()


text:
package org.apache.vxquery.runtime.functions.aggregate;

import org.apache.vxquery.runtime.functions.comparison.AbstractValueComparisonOperation;
import org.apache.vxquery.runtime.functions.comparison.ValueLtComparisonOperation;

import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;

public class FnMinScalarEvaluatorFactory extends AbstractMaxMinScalarEvaluatorFactory {
    private static final long serialVersionUID = 1L;

    public FnMinScalarEvaluatorFactory(IScalarEvaluatorFactory[] args) {
        super(args);
    }

    @Override
    protected AbstractValueComparisonOperation createValueComparisonOperation() {
        return new ValueLtComparisonOperation();
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>

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

    <var id="lang_input_anchorName"></var><input id="anchorName" value=""/>


text:
@class DBTEAMLOGExternalUserLogInfo;
@class DBTEAMLOGIdentifierType;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `ExternalUserLogInfo` struct.
///
/// A user without a Dropbox account.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGExternalUserLogInfo : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// An external user identifier.
@property (nonatomic, readonly, copy) NSString *userIdentifier;

/// Identifier type.
@property (nonatomic, readonly) DBTEAMLOGIdentifierType *identifierType;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param userIdentifier An external user identifier.
/// @param identifierType Identifier type.
///
/// @return An initialized instance.
///
- (instancetype)initWithUserIdentifier:(NSString *)userIdentifier
                        identifierType:(DBTEAMLOGIdentifierType *)identifierType;

- (instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `ExternalUserLogInfo` struct.
///
@interface DBTEAMLOGExternalUserLogInfoSerializer : NSObject

///
/// Serializes `DBTEAMLOGExternalUserLogInfo` instances.
///
/// @param instance An instance of the `DBTEAMLOGExternalUserLogInfo` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGExternalUserLogInfo` API object.
///
+ (nullable NSDictionary *)serialize:(DBTEAMLOGExternalUserLogInfo *)instance;

///
/// Deserializes `DBTEAMLOGExternalUserLogInfo` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGExternalUserLogInfo` API object.
///
/// @return An instantiation of the `DBTEAMLOGExternalUserLogInfo` object.
///
+ (DBTEAMLOGExternalUserLogInfo *)deserialize:(NSDictionary *)dict;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

    <title>Introducción a Ruby</title>
    <meta name="author" content="Luis Lopez" />
    <meta name="email" content="luigibyte@gmail.com" />
    <meta name="date" content="2013-02-27" />

    <link type="text/css" rel="stylesheet" href="slippy-0.9.0.css"/>

    <link type="text/css" rel="stylesheet" href="slippy-kerryb.css"/>

    <link type="text/css" rel="stylesheet" href="highlighter/shCore.css"/>
    <link type="text/css" rel="stylesheet" href="highlighter/shThemeEclipse.css"/>

Introducción a Ruby

¿Qué es ruby?

        Es un lenguaje de programación poderoso y flexible que puedes usar en el desarrollo aplicaciones desktop, web o simplemente de consola.

        Es un lenguaje de alto nivel, interpretado y orientado a objetos.

De alto nivel, lo que quiere decir que leer y escribir Ruby es realmente fácil; ¡se parece mucho al inglés común y corriente!

Interpretado porque no necesitas un compilador para ejecutar Ruby. Puedes escribirlo en tu propio computador

Orientado a los objetos porque les permite a los usuarios manipular estructuras de datos llamadas objetos, para construir y ejecutar programas. En Ruby, todo es un objeto.

Todo en Ruby es un objeto

          1.class                 # => Fixnum
          1.5.class               # => Float
          "hello".class           # => String
          true.class              # => TrueClass
          false.class             # => FalseClass
          nil.class               # => NilClass
          99999999999999999.class # => Bignum
          :active.class           # => Symbol

Cadena de caracteres

        Una cadena de caracteres es una secuencia de caracteres entre comillas. Este objeto pertenece a la clase String.

          "hello world".class      # => String
          "hello world".length     # => 11
          "hello world".capitalize # => "Hello world"
          "hello world".upcase     # => "HELLO WORLD"
          "hello world"[0]         # => "h"

Array

Un arreglo es un objeto donde es posible almacenar una serie de otros objetos. Los arreglos pertenecen a la clase de Array.

          array = [1, 2, 3, 4, 5]
          array[0] # => 1
          array[1] # => 2
          array[2] # => 3
          array[3] # => 4
          array[4] # => 5

          for i in array
            puts i
          end

          # OR

          array.each{|i| puts i}

Hash

Un hash es como un arreglo en el cual se puede acceder a los valores por una clave.

          hash = {first_name: 'Luis', last_name: 'lopez', age: 29}
          hash[:first_name] # => 'Luis'
          hash[:last_name]  # => 'Lopez'
          hash[:age]        # => 29

Estructuras de control (condicionales)

IF

ELSE

ELSIF

UNLESS

CASE

IF

          if conditional
            # code...
          elsif conditional
            # code...
          else
            # code...
          end

UNLESS

          unless conditional
            # code...
          else
            # code...
          end

CASE

          case expression
            when condition
              # code...
            when condition
              # code...
            else
              # code...
          end

Estructuras de control (iterativas)

WHILE

UNTIL

FOR

WHILE

          while conditional [do]
            # code...
          end

          # OR

          begin
            # code...
          end while condition

UNTIL

          until condition [do]
            # code...
          end

FOR

          for variable [, variable ...] in expresión [do]
            # code...
          end

Método

Un método es como una función que puede recibir o no parámetros

"El return esta implícito"

Ejemplo:

          def say_hello(name)
            return "Hello guys, My name is #{name}"
          end

          # OR

          def say_hello(name)
            "Hello guys, My name is #{name}"
          end

          say_hello('Luis') # => "Hello guys, My name is Luis"

Clase

Una clase se puede definir como una plantilla para crear un objeto. Esta constituida por atributos y métodos:

Podemos pensar a los atributos como las características que definen a un objeto y a los métodos como aquello que define el comportamiento del objeto.

Ejemplo de clase

          class Person
            attr_accessor :first_name, :last_name, :age

            def initialize(first_name, last_name, age)
              @first_name = first_name
              @last_name = last_name
              @age = age
            end

            def name
              "#{first_name.capitalize} #{last_name.capitalize}"
            end

            def say_hello
              puts "Hello guys, My name is #{name}"
            end
          end

Instancia

Una instancia de un objeto es la creación del mismo partiendo de una clase.

Dada nuetra clase Person, podemos instanciar un objeto de la siguiente manera:

          person = Person.new('luis', 'lopez', 29)
          person.first_name # => 'luis'
          person.last_name  # => 'lopez'
          person.age        # => 29
          person.name       # => 'Luis Lopez'
          person.say_hello  # => 'Hello guys, My name is Luis Lopez'

Herencia

La herencia es la relación entre una clase general y otra más específica, padre e hija.

Nos facilita la reutilización y la extensibilidad del código.

          class Worker < Person
            attr_accessor :job
          end

          worker = Worker.new('Joaquín', 'Vicente', 30)
          worker.first_name   # => 'Joaquín'
          worker.last_name    # => 'Vicente'
          worker.age          # => 30
          worker.job          # => nil
          worker.job = 'Programmer'
          worker.job          # => 'Programmer'
          worker.say_hello    # => 'Hello guys, My name is Joaquín Vicente'

Más información en

https://www.ruby-lang.org


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Coll. Agric. imp. Univ. Tokyo 2(4): 260 (1910)

#### Original name
Phaeoseptoria oryzae I. Miyake

### Remarks
null


text:
A simple gem which I have used to try and create my first gem. It is a simple gem which prints a simple string: "Stop asking questions, Alex.". Version 0.2.1 works in the command line.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'inquisitive_alex'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install inquisitive_alex

## Usage

````
$ inquisitive_alex
````

## Contributing

1. Fork it ( https://github.com/[my-github-username]/inquisitive_alex/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package org.apache.camel.component.file;

import org.w3c.dom.Document;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;

public class XPathToFileTest extends ContextTestSupport {

    @Test
    public void testXPathToFile() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(2);

        String xml = "<foo><person id=\"1\">Claus<country>SE</country></person>"
                     + "<person id=\"2\">Jonathan<country>CA</country></person></foo>";
        Document doc = context.getTypeConverter().convertTo(Document.class, xml);

        template.sendBody("direct:start", doc);

        assertMockEndpointsSatisfied();

        assertFileExists(testFile("xpath-0.xml"), "<person id=\"1\">Claus<country>SE</country></person>");
        assertFileExists(testFile("xpath-1.xml"), "<person id=\"2\">Jonathan<country>CA</country></person>");
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").split(xpath("/foo/person")).log("${bodyAs(String)}")
                        .to(fileUri("?fileName=xpath-${exchangeProperty.CamelSplitIndex}.xml"))
                        .to("mock:result");
            }
        };
    }
}


text:
"""Mixins to add common attributes and relationships. Note, all model classes
must also inherit from ``db.Model``. For example:
color
color
  ..

     class Market(BusinessObject, db.Model):
       __tablename__ = 'markets'

"""

# pylint: disable=no-self-argument
# All declared_attr properties that are class level as per sqlalchemy
# documentatio, are reported as false positives by pylint.

from logging import getLogger
from uuid import uuid1
import datetime

from sqlalchemy import event
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import validates
from sqlalchemy.orm.session import Session

from ggrc import db
from ggrc.models import reflection
from ggrc.models.computed_property import computed_property
from ggrc.models.deferred import deferred
from ggrc.models.inflector import ModelInflectorDescriptor
from ggrc.models.reflection import AttributeInfo
from ggrc.models.mixins.customattributable import CustomAttributable
from ggrc.models.mixins.notifiable import Notifiable

# pylint: disable=invalid-name
logger = getLogger(__name__)

class Identifiable(object):

  """A model with an ``id`` property that is the primary key."""
  id = db.Column(db.Integer, primary_key=True)  # noqa

  # REST properties
  _publish_attrs = ['id', 'type']
  _update_attrs = []

  _inflector = ModelInflectorDescriptor()

  @computed_property
  def type(self):
    return self.__class__.__name__

  @classmethod
  def eager_query(cls):
    mapper_class = cls._sa_class_manager.mapper.base_mapper.class_
    return db.session.query(cls).options(
        db.Load(mapper_class).undefer_group(
            mapper_class.__name__ + '_complete'),
    )

  @classmethod
  def eager_inclusions(cls, query, include_links):
    options = []
    for include_link in include_links:
      inclusion_class = getattr(cls, include_link).property.mapper.class_
      options.append(
          orm.subqueryload(include_link)
          .undefer_group(inclusion_class.__name__ + '_complete'))
    return query.options(*options)

  @declared_attr
  def __table_args__(cls):
    extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args')
    table_args = []
    table_dict = {}
    for table_arg in extra_table_args:
      if callable(table_arg):
        table_arg = table_arg()
      if isinstance(table_arg, (list, tuple, set)):
        if isinstance(table_arg[-1], (dict,)):
          table_dict.update(table_arg[-1])
          table_args.extend(table_arg[:-1])
        else:
          table_args.extend(table_arg)
      elif isinstance(table_arg, (dict,)):
        table_dict.update(table_arg)
      else:
        table_args.append(table_arg)
    if len(table_dict) > 0:
      table_args.append(table_dict)
    return tuple(table_args,)

class ChangeTracked(object):

  """A model with fields to tracked the last user to modify the model, the
  creation time of the model, and the last time the model was updated.
  """
  @declared_attr
  def modified_by_id(cls):
    return deferred(db.Column(db.Integer), cls.__name__)

  @declared_attr
  def created_at(cls):
    column = db.Column(
        db.DateTime,
        nullable=False,
        default=db.text('current_timestamp'),
    )
    return deferred(column, cls.__name__)

  @declared_attr
  def updated_at(cls):
    column = db.Column(
        db.DateTime,
        nullable=False,
        default=db.text('current_timestamp'),
        onupdate=db.text('current_timestamp'),
    )
    return deferred(column, cls.__name__)

  @declared_attr
  def modified_by(cls):
    return db.relationship(
        'Person',
        primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__),
        foreign_keys='{0}.modified_by_id'.format(cls.__name__),
        uselist=False,
    )

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('ix_{}_updated_at'.format(cls.__tablename__), 'updated_at'),
    )

  # TODO Add a transaction id, this will be handy for generating etags
  # and for tracking the changes made to several resources together.
  # transaction_id = db.Column(db.Integer)

  # REST properties
  _publish_attrs = [
      'modified_by',
      'created_at',
      'updated_at',
  ]
  _update_attrs = []

class Titled(object):

  @declared_attr
  def title(cls):
    return deferred(db.Column(db.String, nullable=False), cls.__name__)

  @staticmethod
  def _extra_table_args(cls):
    if getattr(cls, '_title_uniqueness', True):
      return (
          db.UniqueConstraint(
              'title', name='uq_t_{}'.format(cls.__tablename__)),
      )
    return ()

  # REST properties
  _publish_attrs = ['title']
  _fulltext_attrs = ['title']
  _sanitize_html = ['title']
  _aliases = {"title": "Title"}

class Described(object):

  @declared_attr
  def description(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['description']
  _fulltext_attrs = ['description']
  _sanitize_html = ['description']
  _aliases = {"description": "Description"}

class Noted(object):

  @declared_attr
  def notes(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['notes']
  _fulltext_attrs = ['notes']
  _sanitize_html = ['notes']
  _aliases = {"notes": "Notes"}

class Hyperlinked(object):

  @declared_attr
  def url(cls):
    return deferred(db.Column(db.String), cls.__name__)

  @declared_attr
  def reference_url(cls):
    return deferred(db.Column(db.String), cls.__name__)

  # REST properties
  _publish_attrs = ['url', 'reference_url']

  _aliases = {
      "url": "Url",
      "reference_url": "Reference URL",
  }

class Hierarchical(object):

  @declared_attr
  def parent_id(cls):
    return deferred(db.Column(
        db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))),
        cls.__name__)

  @declared_attr
  def children(cls):
    return db.relationship(
        cls.__name__,
        backref=db.backref(
            'parent', remote_side='{0}.id'.format(cls.__name__)),
    )

  # REST properties
  _publish_attrs = [
      'children',
      'parent',
  ]

  @classmethod
  def eager_query(cls):
    query = super(Hierarchical, cls).eager_query()
    return query.options(
        orm.subqueryload('children'),
        # orm.joinedload('parent'),
    )

class Timeboxed(object):

  @declared_attr
  def start_date(cls):
    return deferred(db.Column(db.Date), cls.__name__)

  @declared_attr
  def end_date(cls):
    return deferred(db.Column(db.Date), cls.__name__)

  # REST properties
  _publish_attrs = ['start_date', 'end_date']

  _aliases = {
      "start_date": "Effective Date",
      "end_date": "Stop Date",
  }

class Stateful(object):

  @declared_attr
  def status(cls):
    return deferred(
        db.Column(db.String, default=cls.default_status), cls.__name__)

  _publish_attrs = ['status']
  _aliases = {"status": "State"}

  @classmethod
  def default_status(cls):
    return cls.valid_statuses()[0]

  @classmethod
  def valid_statuses(cls):
    return cls.VALID_STATES

  @validates('status')
  def validate_status(self, key, value):
    # Sqlalchemy only uses one validator per status (not necessarily the
    # first) and ignores others. This enables cooperation between validators
    # since there are other mixins that want to touch 'status'.
    if hasattr(super(Stateful, self), "validate_status"):
      value = super(Stateful, self).validate_status(key, value)
    if value is None:
      value = self.default_status()
    if value not in self.valid_statuses():
      message = u"Invalid state '{}'".format(value)
      raise ValueError(message)
    return value

class FinishedDate(object):
  """Adds 'Finished Date' which is set when status is set to a finished state.

  Requires Stateful to be mixed in as well.
  """

  NOT_DONE_STATES = None
  DONE_STATES = {}

  # pylint: disable=method-hidden
  # because validator only sets date per model instance
  @declared_attr
  def finished_date(cls):
    return deferred(
        db.Column(db.Date, nullable=True),
        cls.__name__
    )

  _publish_attrs = [
      reflection.PublishOnly('finished_date')
  ]

  _aliases = {
      "finished_date": "Finished Date"
  }

  @validates('status')
  def validate_status(self, key, value):
    """Update finished_date given the right status change."""
    # Sqlalchemy only uses one validator per status (not necessarily the
    # first) and ignores others. This enables cooperation between validators
    # since 'status' is not defined here.
    if hasattr(super(FinishedDate, self), "validate_status"):
      value = super(FinishedDate, self).validate_status(key, value)
    # pylint: disable=unsupported-membership-test
    # short circuit
    if (value in self.DONE_STATES and
        (self.NOT_DONE_STATES is None or
         self.status in self.NOT_DONE_STATES)):
      self.finished_date = datetime.datetime.now()
    elif ((self.NOT_DONE_STATES is None or
           value in self.NOT_DONE_STATES) and
            self.status in self.DONE_STATES):
      self.finished_date = None
    return value

class VerifiedDate(object):
  """Adds 'Verified Date' which is set when status is set to 'Verified'.

  When object is verified the status is overridden to 'Final' and the
  information about verification exposed as the 'verified' boolean.
  Requires Stateful to be mixed in as well.
  """

  VERIFIED_STATES = {u"Verified"}
  DONE_STATES = {}

  # pylint: disable=method-hidden
  # because validator only sets date per model instance
  @declared_attr
  def verified_date(cls):
    return deferred(
        db.Column(db.Date, nullable=True),
        cls.__name__
    )

  @hybrid_property
  def verified(self):
    return self.verified_date != None  # noqa

  _publish_attrs = [
      reflection.PublishOnly('verified'),
      reflection.PublishOnly('verified_date'),
  ]

  _aliases = {
      "verified_date": "Verified Date"
  }

  @validates('status')
  def validate_status(self, key, value):
    """Update verified_date on status change, make verified status final."""
    # Sqlalchemy only uses one validator per status (not necessarily the
    # first) and ignores others. This enables cooperation between validators
    # since 'status' is not defined here.
    if hasattr(super(VerifiedDate, self), "validate_status"):
      value = super(VerifiedDate, self).validate_status(key, value)
    if (value in self.VERIFIED_STATES and
            self.status not in self.VERIFIED_STATES):
      self.verified_date = datetime.datetime.now()
      value = self.FINAL_STATE
    elif (value not in self.VERIFIED_STATES and
          value not in self.DONE_STATES and
          (self.status in self.VERIFIED_STATES or
           self.status in self.DONE_STATES)):
      self.verified_date = None
    return value

class ContextRBAC(object):

  @declared_attr
  def context_id(cls):
    return db.Column(db.Integer, db.ForeignKey('contexts.id'))

  @declared_attr
  def context(cls):
    return db.relationship('Context', uselist=False)

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('fk_{}_contexts'.format(cls.__tablename__), 'context_id'),
    )

  _publish_attrs = ['context']

  # @classmethod
  # def eager_query(cls):
  # from sqlalchemy import orm

  # query = super(ContextRBAC, cls).eager_query()
  # return query.options(
  # orm.subqueryload('context'))

class Base(ChangeTracked, ContextRBAC, Identifiable):

  """Several of the models use the same mixins. This class covers that common
  case.
  """
  _people_log_mappings = [
      "principal_assessor_id",
      "secondary_assessor_id",
      "contact_id",
      "secondary_contact_id",
      "modified_by_id",
      "attribute_object_id",  # used for person mapping CA
  ]

  @staticmethod
  def _person_stub(id_):
    return {
        'type': u"Person",
        'id': id_,
        'context_id': None,
        'href': u"/api/people/{}".format(id_),
    }

  def log_json(self):
    # to integrate with CustomAttributable without order dependencies
    res = getattr(super(Base, self), "log_json", lambda: {})()
    for column in self.__table__.columns:
      try:
        res[column.name] = getattr(self, column.name)
      except AttributeError:
        pass
    res['display_name'] = self.display_name

    for attr in self._people_log_mappings:
      if hasattr(self, attr):
        value = getattr(self, attr)
        res[attr[:-3]] = self._person_stub(value) if value else None
    if hasattr(self, "owners"):
      res["owners"] = [
          self._person_stub(owner.id) for owner in self.owners if owner
      ]

    return res

  @computed_property
  def display_name(self):
    try:
      return self._display_name()
    except:  # pylint: disable=bare-except
      logger.warning("display_name error in %s", type(self), exc_info=True)
      return ""

  def _display_name(self):
    return getattr(self, "title", None) or getattr(self, "name", "")

  def copy_into(self, target_object, columns, **kwargs):
    """Copy current object values into a target object.

    Copy all values listed in columns from current class to target class and
    use kwargs as defaults with precedence. Note that this is a shallow copy
    and any mutable values will be shared between current and target objects.

    Args:
      target_object: object to which we want to copy current values. This
        function will mutate the target_object parameter if it is set.
      columns: list with all attribute names that we want to set in the
        target_object.
      kwargs: additional default values.

    Returns:
      target_object with all values listed in columns set.
    """
    target = target_object or type(self)()

    columns = set(columns).union(kwargs.keys())
    for name in columns:
      if name in kwargs:
        value = kwargs[name]
      else:
        value = getattr(self, name)
      setattr(target, name, value)

    return target

class Slugged(Base):

  """Several classes make use of the common mixins and additional are
  "slugged" and have additional fields related to their publishing in the
  system.
  """

  @declared_attr
  def slug(cls):
    return deferred(db.Column(db.String, nullable=False), cls.__name__)

  @staticmethod
  def _extra_table_args(cls):
    if getattr(cls, '_slug_uniqueness', True):
      return (
          db.UniqueConstraint('slug', name='uq_{}'.format(cls.__tablename__)),
      )
    return ()

  # REST properties
  _publish_attrs = ['slug']
  _fulltext_attrs = ['slug']
  _sanitize_html = ['slug']
  _aliases = {
      "slug": {
          "display_name": "Code",
          "description": ("Must be unique. Can be left empty for "
                          "auto generation. If updating or deleting, "
                          "code is required"),
      }
  }

  @classmethod
  def generate_slug_for(cls, obj):
    _id = getattr(obj, 'id', uuid1())
    obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id)
    # We need to make sure the generated slug is not already present in the
    # database. If it is, we increment the id until we find a slug that is
    # unique.
    # A better approach would be to query the database for slug uniqueness
    # only if the there was a conflict, but because we can't easily catch a
    # session rollback at this point we are sticking with a
    # suboptimal solution for now.
    INCREMENT = 1000
    while cls.query.filter(cls.slug == obj.slug).count():
      _id += INCREMENT
      obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id)

  @classmethod
  def generate_slug_prefix_for(cls, obj):
    return obj.__class__.__name__.upper()

  @classmethod
  def ensure_slug_before_flush(cls, session, flush_context, instances):
    """Set the slug to a default string so we don't run afoul of the NOT NULL
    constraint.
    """
    for o in session.new:
      if isinstance(o, Slugged) and (o.slug is None or o.slug == ''):
        o.slug = str(uuid1())
        o._replace_slug = True

  @classmethod
  def ensure_slug_after_flush_postexec(cls, session, flush_context):
    """Replace the placeholder slug with a real slug that will be set on the
    next flush/commit.
    """
    for o in session.identity_map.values():
      if isinstance(o, Slugged) and hasattr(o, '_replace_slug'):
        o.generate_slug_for(o)
        delattr(o, '_replace_slug')

event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush)
event.listen(
    Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec)

class Mapping(Stateful, Base):
  VALID_STATES = (
      'Draft',
      'Final',
  )

class WithContact(object):

  @declared_attr
  def contact_id(cls):
    return deferred(
        db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__)

  @declared_attr
  def secondary_contact_id(cls):
    return deferred(
        db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__)

  @declared_attr
  def contact(cls):
    return db.relationship(
        'Person',
        uselist=False,
        foreign_keys='{}.contact_id'.format(cls.__name__))

  @declared_attr
  def secondary_contact(cls):
    return db.relationship(
        'Person',
        uselist=False,
        foreign_keys='{}.secondary_contact_id'.format(cls.__name__))

  @staticmethod
  def _extra_table_args(cls):
    return (
        db.Index('fk_{}_contact'.format(cls.__tablename__), 'contact_id'),
        db.Index('fk_{}_secondary_contact'.format(
            cls.__tablename__), 'secondary_contact_id'),
    )

  _publish_attrs = ['contact', 'secondary_contact']
  _aliases = {
      "contact": {
          "display_name": "Primary Contact",
          "filter_by": "_filter_by_contact",
      },
      "secondary_contact": {
          "display_name": "Secondary Contact",
          "filter_by": "_filter_by_secondary_contact",
      },
  }

  @classmethod
  def _filter_by_contact(cls, predicate):
    # dependency cycle mixins.py <~> person.py
    from ggrc.models.person import Person
    return Person.query.filter(
        (Person.id == cls.contact_id) &
        (predicate(Person.name) | predicate(Person.email))
    ).exists()

  @classmethod
  def _filter_by_secondary_contact(cls, predicate):
    # dependency cycle mixins.py <~> person.py
    from ggrc.models.person import Person
    return Person.query.filter(
        (Person.id == cls.secondary_contact_id) &
        (predicate(Person.name) | predicate(Person.email))
    ).exists()

class BusinessObject(Stateful, Noted, Described, Hyperlinked, WithContact,
                     Titled, Slugged):
  VALID_STATES = (
      'Draft',
      'Final',
      'Effective',
      'Ineffective',
      'Launched',
      'Not Launched',
      'In Scope',
      'Not in Scope',
      'Deprecated',
  )

# This class is just a marker interface/mixin to indicate that a model type
# supports custom attributes.

class TestPlanned(object):

  @declared_attr
  def test_plan(cls):
    return deferred(db.Column(db.Text), cls.__name__)

  # REST properties
  _publish_attrs = ['test_plan']
  _fulltext_attrs = ['test_plan']
  _sanitize_html = ['test_plan']
  _aliases = {"test_plan": "Test Plan"}

__all__ = [
    "Base",
    "BusinessObject",
    "ChangeTracked",
    "ContextRBAC",
    "CustomAttributable",
    "Described",
    "FinishedDate",
    "Hierarchical",
    "Hyperlinked",
    "Identifiable",
    "Mapping",
    "Noted",
    "Notifiable",
    "Slugged",
    "Stateful",
    "TestPlanned",
    "Timeboxed",
    "Titled",
    "VerifiedDate",
    "WithContact",
]


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/dlp.proto

namespace Google\Cloud\Dlp\V2\InspectConfig;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Configuration to control the number of findings returned for inspection.
 * This is not used for de-identification or data profiling.
 * When redacting sensitive data from images, finding limits don't apply. They
 * can cause unexpected or inconsistent results, where only some data is
 * redacted. Don't include finding limits in
 * [RedactImage][google.privacy.dlp.v2.DlpService.RedactImage]
 * requests. Otherwise, Cloud DLP returns an error.
 *
 * Generated from protobuf message google.privacy.dlp.v2.InspectConfig.FindingLimits
 */
class FindingLimits extends \Google\Protobuf\Internal\Message
{
    /**
     * Max number of findings that will be returned for each item scanned.
     * When set within `InspectJobConfig`,
     * the maximum returned is 2000 regardless if this is set higher.
     * When set within `InspectContentRequest`, this field is ignored.
     *
     * Generated from protobuf field int32 max_findings_per_item = 1;
     */
    private $max_findings_per_item = 0;
    /**
     * Max number of findings that will be returned per request/job.
     * When set within `InspectContentRequest`, the maximum returned is 2000
     * regardless if this is set higher.
     *
     * Generated from protobuf field int32 max_findings_per_request = 2;
     */
    private $max_findings_per_request = 0;
    /**
     * Configuration of findings limit given for specified infoTypes.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.InspectConfig.FindingLimits.InfoTypeLimit max_findings_per_info_type = 3;
     */
    private $max_findings_per_info_type;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int $max_findings_per_item
     *           Max number of findings that will be returned for each item scanned.
     *           When set within `InspectJobConfig`,
     *           the maximum returned is 2000 regardless if this is set higher.
     *           When set within `InspectContentRequest`, this field is ignored.
     *     @type int $max_findings_per_request
     *           Max number of findings that will be returned per request/job.
     *           When set within `InspectContentRequest`, the maximum returned is 2000
     *           regardless if this is set higher.
     *     @type array<\Google\Cloud\Dlp\V2\InspectConfig\FindingLimits\InfoTypeLimit>|\Google\Protobuf\Internal\RepeatedField $max_findings_per_info_type
     *           Configuration of findings limit given for specified infoTypes.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Privacy\Dlp\V2\Dlp::initOnce();
        parent::__construct($data);
    }

    /**
     * Max number of findings that will be returned for each item scanned.
     * When set within `InspectJobConfig`,
     * the maximum returned is 2000 regardless if this is set higher.
     * When set within `InspectContentRequest`, this field is ignored.
     *
     * Generated from protobuf field int32 max_findings_per_item = 1;
     * @return int
     */
    public function getMaxFindingsPerItem()
    {
        return $this->max_findings_per_item;
    }

    /**
     * Max number of findings that will be returned for each item scanned.
     * When set within `InspectJobConfig`,
     * the maximum returned is 2000 regardless if this is set higher.
     * When set within `InspectContentRequest`, this field is ignored.
     *
     * Generated from protobuf field int32 max_findings_per_item = 1;
     * @param int $var
     * @return $this
     */
    public function setMaxFindingsPerItem($var)
    {
        GPBUtil::checkInt32($var);
        $this->max_findings_per_item = $var;

        return $this;
    }

    /**
     * Max number of findings that will be returned per request/job.
     * When set within `InspectContentRequest`, the maximum returned is 2000
     * regardless if this is set higher.
     *
     * Generated from protobuf field int32 max_findings_per_request = 2;
     * @return int
     */
    public function getMaxFindingsPerRequest()
    {
        return $this->max_findings_per_request;
    }

    /**
     * Max number of findings that will be returned per request/job.
     * When set within `InspectContentRequest`, the maximum returned is 2000
     * regardless if this is set higher.
     *
     * Generated from protobuf field int32 max_findings_per_request = 2;
     * @param int $var
     * @return $this
     */
    public function setMaxFindingsPerRequest($var)
    {
        GPBUtil::checkInt32($var);
        $this->max_findings_per_request = $var;

        return $this;
    }

    /**
     * Configuration of findings limit given for specified infoTypes.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.InspectConfig.FindingLimits.InfoTypeLimit max_findings_per_info_type = 3;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getMaxFindingsPerInfoType()
    {
        return $this->max_findings_per_info_type;
    }

    /**
     * Configuration of findings limit given for specified infoTypes.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.InspectConfig.FindingLimits.InfoTypeLimit max_findings_per_info_type = 3;
     * @param array<\Google\Cloud\Dlp\V2\InspectConfig\FindingLimits\InfoTypeLimit>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setMaxFindingsPerInfoType($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dlp\V2\InspectConfig\FindingLimits\InfoTypeLimit::class);
        $this->max_findings_per_info_type = $arr;

        return $this;
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(FindingLimits::class, \Google\Cloud\Dlp\V2\InspectConfig_FindingLimits::class);


text:
package xworker.dataObject.swt;

import org.xmeta.ActionContext;
import org.xmeta.Thing;

import xworker.dataObject.DataObject;

public class StaticDataObjectActions {
	public static void bindToDataObjectForm(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		Thing form = actionContext.getObject("dataObjectForm");

		DataObject dataObject = self.doAction("getDataObject", actionContext);
		if(dataObject != null && form != null) {
			form.doAction("setDataObject", actionContext, "dataObject", dataObject);
		}
	}
}


text:
package org.alfasoftware.morf.sql;

import static org.alfasoftware.morf.sql.SelectStatement.select;
import static org.alfasoftware.morf.sql.SqlUtils.literal;

import java.util.Arrays;
import java.util.List;

import org.alfasoftware.morf.sql.element.Criterion;
import org.alfasoftware.morf.sql.element.TableReference;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Checks that {@link SelectStatement} satisfies equals, hashcode, deep copy, shallow copy and driver contracts.
 *
 * @author Copyright (c) Alfa Financial Software 2017
 */
@RunWith(Parameterized.class)
public class TestSelectStatementDeepCopyContractUsingBuilder extends AbstractShallowAndDeepCopyableTest<SelectStatement> {

  private static final SelectStatement SELECT_1 = mockSelectStatement();
  private static final SelectStatement SELECT_2 = mockSelectStatement();
  private static final Criterion CRITERION_1 = mockOf(Criterion.class);
  private static final Criterion CRITERION_2 = mockOf(Criterion.class);
  private static final TableReference TABLE_1 = mockOf(TableReference.class);
  private static final TableReference TABLE_2 = mockOf(TableReference.class);

  @Parameters(name = "{0}")
  public static List<Object[]> data() {
    return Arrays.asList(
      testCaseWithBuilder("select()", select()),
      testCaseWithBuilder("select().distinct()", select().distinct()),
      testCaseWithBuilder("select().alias(\"A\")", select().alias("A")),
      testCaseWithBuilder("select().forUpdate()", select().forUpdate()),
      testCaseWithBuilder("select().useImplicitJoinOrder()", select().useImplicitJoinOrder()),
      testCaseWithBuilder("select().optimiseForRowCount(1)", select().optimiseForRowCount(1)),
      testCaseWithBuilder("select().optimiseForRowCount(2)", select().optimiseForRowCount(2)),
      testCaseWithBuilder("select().useIndex(TABLE_1, \"A\")", select().useIndex(TABLE_1, "A")),
      testCaseWithBuilder("select().useIndex(TABLE_1, \"B\")", select().useIndex(TABLE_1, "B")),
      testCaseWithBuilder("select().useIndex(TABLE_2, \"A\")", select().useIndex(TABLE_2, "A")),
      testCaseWithBuilder("select(literal(1))", select(literal(1))),
      testCaseWithBuilder("select(literal(2))", select(literal(2))),
      testCaseWithBuilder("select(literal(1), literal(2))", select(literal(1), literal(2))),
      testCaseWithBuilder("select(literal(1), literal(3))", select(literal(1), literal(3))),
      testCaseWithBuilder("select().from(\"A\")", select().from("A")),
      testCaseWithBuilder("select().from(\"B\")", select().from("B")),
      testCaseWithBuilder("select().from(SELECT_1)", select().from(SELECT_1)),
      testCaseWithBuilder("select().from(SELECT_2)", select().from(SELECT_2)),
      testCaseWithBuilder("select().from(SELECT_1, SELECT_1)", select().from(SELECT_1, SELECT_1)),
      testCaseWithBuilder("select().from(SELECT_1, SELECT_2)", select().from(SELECT_1, SELECT_2)),
      testCaseWithBuilder("select().from(\"A\").where(CRITERION_1)", select().from("A").where(CRITERION_1)),
      testCaseWithBuilder("select().from(\"A\").where(CRITERION_2)", select().from("A").where(CRITERION_2)),
      testCaseWithBuilder("select().from(\"A\").innerJoin(TABLE_1)", select().from("A").innerJoin(TABLE_1)),
      testCaseWithBuilder("select().from(\"A\").innerJoin(TABLE_2)", select().from("A").innerJoin(TABLE_2)),
      testCaseWithBuilder("select().from(\"A\").innerJoin(TABLE_1).innerJoin(TABLE_1).innerJoin(TABLE_1)", select().from("A").innerJoin(TABLE_1).innerJoin(TABLE_1).innerJoin(TABLE_1)),
      testCaseWithBuilder("select().from(\"A\").innerJoin(TABLE_1).innerJoin(TABLE_2)", select().from("A").innerJoin(TABLE_1).innerJoin(TABLE_2)),
      testCaseWithBuilder("select().from(\"A\").innerJoin(TABLE_1, CRITERION_1).innerJoin(TABLE_2, CRITERION_1)", select().from("A").innerJoin(TABLE_1, CRITERION_1).innerJoin(TABLE_2, CRITERION_1)),
      testCaseWithBuilder("select().from(\"A\").leftOuterJoin(TABLE_1, CRITERION_1)", select().from("A").leftOuterJoin(TABLE_1, CRITERION_1)),
      testCaseWithBuilder("select().from(\"A\").leftOuterJoin(TABLE_1, CRITERION_2)", select().from("A").leftOuterJoin(TABLE_1, CRITERION_2)),
      testCaseWithBuilder("select().from(\"A\").leftOuterJoin(TABLE_2, CRITERION_1)", select().from("A").leftOuterJoin(TABLE_2, CRITERION_1)),
      testCaseWithBuilder("select().orderBy(literal(1), literal(2))", select().orderBy(literal(1), literal(2))),
      testCaseWithBuilder("select().orderBy(literal(1), literal(3))", select().orderBy(literal(1), literal(3))),
      testCaseWithBuilder("select().having(CRITERION_1)", select().having(CRITERION_1)),
      testCaseWithBuilder("select().having(CRITERION_2)", select().having(CRITERION_2)),
      testCaseWithBuilder("select().union(SELECT_1)", select().union(SELECT_1)),
      testCaseWithBuilder("select().union(SELECT_2)", select().union(SELECT_2)),
      testCaseWithBuilder("select().unionAll(SELECT_1)", select().unionAll(SELECT_1)),
      testCaseWithBuilder("select().unionAll(SELECT_2)", select().unionAll(SELECT_2))
    );
  }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.grogshop.services.endpoints.impl;

import com.grogdj.grogshop.core.model.Item;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.validation.constraints.NotNull;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.grogshop.services.api.ItemsService;
import org.grogshop.services.endpoints.api.PublicShopItemsService;
import org.grogshop.services.exceptions.ServiceException;

@Stateless
public class PublicShopItemsServiceImpl implements PublicShopItemsService {

    @Inject
    private ItemsService itemsService;

    public static final String UPLOADED_FILE_PARAMETER_NAME = "file";

    private final static Logger log = Logger.getLogger(PublicShopItemsServiceImpl.class.getName());

    @Override
    public Response getAllItems() throws ServiceException {
        List<Item> allItems = itemsService.getAllItems();
        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
        for (Item i : allItems) {
            jsonObjectBuilder
                    .add("id", (i.getId() == null) ? "" : i.getId().toString())
                    .add("user_id", (i.getUser().getId() == null) ? "" : i.getUser().getId().toString())
                    .add("user_email", (i.getUser().getEmail() == null) ? "" : i.getUser().getEmail())
                    .add("club_id", (i.getClub().getId() == null) ? "" : i.getClub().getId().toString())
                    .add("type", (i.getType() == null) ? "" : i.getType().toString())
                    .add("name", (i.getName() == null) ? "" : i.getName())
                    .add("description", (i.getDescription() == null) ? "" : i.getDescription())
                    .add("hasImage", i.hasImage())
                    .add("minPrice", (i.getMinPrice() == null) ? "" : i.getMinPrice().toString())
                    .add("maxPrice", (i.getMaxPrice() == null) ? "" : i.getMaxPrice().toString());

            if (i.getTags() != null) {
                JsonArrayBuilder jsonArrayBuilderInterest = Json.createArrayBuilder();
                for (String s : i.getTags()) {
                    jsonArrayBuilderInterest.add(Json.createObjectBuilder().add("name", s));
                }
                jsonObjectBuilder.add("tags", jsonArrayBuilderInterest);
            }
            jsonArrayBuilder.add(jsonObjectBuilder);
        }
        JsonArray jsonArray = jsonArrayBuilder.build();
        return Response.ok(jsonArray.toString()).build();

    }

    @Override
    public Response getAllItemsByClub(@PathParam("id") Long club_id) throws ServiceException {
        List<Item> allItems = itemsService.getAllItemsByClub(club_id);
        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
        for (Item i : allItems) {
            jsonObjectBuilder
                    .add("id", (i.getId() == null) ? "" : i.getId().toString())
                    .add("user_id", (i.getUser().getId() == null) ? "" : i.getUser().getId().toString())
                    .add("user_email", (i.getUser().getEmail() == null) ? "" : i.getUser().getEmail())
                    .add("club_id", (i.getClub().getId() == null) ? "" : i.getClub().getId().toString())
                    .add("type", (i.getType() == null) ? "" : i.getType().toString())
                    .add("name", (i.getName() == null) ? "" : i.getName())
                    .add("description", (i.getDescription() == null) ? "" : i.getDescription())
                    .add("hasImage", i.hasImage())
                    .add("minPrice", (i.getMinPrice() == null) ? "" : i.getMinPrice().toString())
                    .add("maxPrice", (i.getMaxPrice() == null) ? "" : i.getMaxPrice().toString());

            if (i.getTags() != null) {
                JsonArrayBuilder jsonArrayBuilderInterest = Json.createArrayBuilder();
                for (String s : i.getTags()) {
                    jsonArrayBuilderInterest.add(Json.createObjectBuilder().add("name", s));
                }
                jsonObjectBuilder.add("tags", jsonArrayBuilderInterest);
            }
            jsonArrayBuilder.add(jsonObjectBuilder);
        }
        JsonArray jsonArray = jsonArrayBuilder.build();
        return Response.ok(jsonArray.toString()).build();

    }

    @Override
    public Response get(@PathParam("id") Long item_id) throws ServiceException {
        Item i = itemsService.getById(item_id);
        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
        jsonObjectBuilder.add("id", (i.getId() == null) ? "" : i.getId().toString())
                    .add("user_id", (i.getUser().getId() == null) ? "" : i.getUser().getId().toString())
                    .add("user_email", (i.getUser().getEmail() == null) ? "" : i.getUser().getEmail())
                    .add("club_id", (i.getClub().getId() == null) ? "" : i.getClub().getId().toString())
                    .add("type", (i.getType() == null) ? "" : i.getType().toString())
                    .add("name", (i.getName() == null) ? "" : i.getName())
                    .add("description", (i.getDescription() == null) ? "" : i.getDescription())
                    .add("hasImage", i.hasImage())
                    .add("minPrice", (i.getMinPrice() == null) ? "" : i.getMinPrice().toString())
                    .add("maxPrice", (i.getMaxPrice() == null) ? "" : i.getMaxPrice().toString());
        if (i.getTags() != null) {
            JsonArrayBuilder jsonArrayBuilderInterest = Json.createArrayBuilder();
            for (String s : i.getTags()) {
                jsonArrayBuilderInterest.add(Json.createObjectBuilder().add("name", s));
            }
            jsonObjectBuilder.add("tags", jsonArrayBuilderInterest);
        }
        JsonObject build = jsonObjectBuilder.build();
        return Response.ok(build.toString()).build();

    }

    @Override
    public Response getItemImage(@NotNull @PathParam("id") Long item_id) throws ServiceException {
        final byte[] itemImage = itemsService.getItemImage(item_id);
        if(itemImage != null){
            return Response.ok().entity(new StreamingOutput() {
                @Override
                public void write(OutputStream output)
                        throws IOException, WebApplicationException {
                    output.write(itemImage);
                    output.flush();
                }
            }).build();
        }else{
            return Response.ok().entity("itemImage not found").build();
        }
    }

}


text:
<?php

namespace Level42\NotJaxbBundle\Exceptions;

/**
 * Specific exception if max depth is reached
 * in annotations reading
 */
class MaxDepthException extends \Exception
{

}


text:
from django.test import TestCase, Client
from django.core.management import call_command
from django.conf import settings

class TestViews(TestCase):
    def setUp(self):
        self.client = Client()

        args = []
        opts = {'dumpfile': settings.MEDIA_ROOT + 'test_db_dump.xml', 'verbosity': 0}
        cmd = 'migrate_db'
        call_command(cmd, *args, **opts)

    def test_index(self):
        response = self.client.get('/blast_local_full/CP100-10/COI/', follow=True)
        self.assertEqual(200, response.status_code)


text:
var configUtils = require('./client/Utils/configUtils.js');
//var path = require('path');

exports.config = {

    suites: {
        sanityTests: './client/sanityTests.spec.js',
    },
    params: {
        targetServerName: 'ADT Pulse Test',
        //requestedSiteName: "GDC Essentel",
        login: {
            user: 'YOURLOGIN@SERVER.com',
            password: 'YOURPASS'
        },

        dimensions: {
            //mobile size
            //width: 375,
            //height: 667

            //tablet size
            //width: 1200,
            //height: 800

            //minimum desktop size
            width: 1200,
            height: 800
        },
        defaultTimeoutInterval: 1000,
        enableDesktopMode: true
    },
    capabilities: {
        // For Internet Explorer Only
        //'browserName': 'internet explorer',
        //'platform': 'ANY'

        'browserName': 'chrome',
        'chromeOptions': {
            args: ['--test-type']
        }

        //'browserName': 'safari' // firefox or safari
    },

    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 60000
    },
    baseUrl: 'http://localhost:9000',
    onPrepare: function () {
        'use strict';
        browser.getProcessedConfig().then(function(config) {

            console.log('Processing Config....');
            browser.params.browserName = config.capabilities.browserName.split(' ').join('_');

            var settingsSuggestion = configUtils.assessClientSelection(browser.params.enableDesktopMode , { 'height' : browser.params.dimensions.height,
                                                                                'width' : browser.params.dimensions.width});

            browser.params.testDeviceType = settingsSuggestion.testDeviceType;

            if (settingsSuggestion.enableDesktopMode) {
                browser.params.enableDesktopMode = settingsSuggestion.enableDesktopMode;
            }

            var testSuites = configUtils.extractTestSuites(config);

            testSuites.forEach(function(suiteName) {
                var fullPath = configUtils.createFolderPath(suiteName);
                configUtils.createFolder(fullPath);
            });

            console.log('Done processing config.');
        });
    }
};


text:
namespace autoboost
{
  namespace csbl
  {
    using ::autoboost::intrusive::pointer_traits;
  }
}
#else
namespace autoboost
{
  namespace csbl
  {
    using ::std::pointer_traits;
  }
}
#endif // AUTOBOOST_NO_CXX11_ALLOCATOR

#endif // header


text:
CSStats Binary Parser
===========
A simple API for reading CSStats.dat binary data with PHP 5.4+

Installation
------------
This library can be found on [Packagist](https://packagist.org/packages/naminator/lyra).
The recommended way to install this is through [composer](http://getcomposer.org).

Edit your `composer.json` and add:

```json
{
    "require": {
        "naminator/cstrike": "dev-master"
    }
}
```

And install dependencies:

```bash
$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar install
```

Features
--------
- PSR-4 compliant for easy interoperability
- Various methods to work with the user data
- Everything is packaged in its own object for easy IDE inspection
- phpDocBlock commented code


text:
<?php

namespace Neptune\Cache;

use Doctrine\Common\Cache\Cache;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerAwareInterface;

/**
 * LoggerAwareCache
 *
 * @author Glynn Forrest <me@glynnforrest.com>
 **/
class LoggerAwareCache implements Cache, LoggerAwareInterface
{
    protected $cache;
    protected $logger;

    public function __construct(Cache $cache, LoggerInterface $logger)
    {
        $this->cache = $cache;
        $this->logger = $logger;
    }

    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function fetch($id)
    {
        if ($result = $this->cache->fetch($id)) {
            $this->logger->debug("CACHE HIT: $id");

            return $result;
        }

        $this->logger->debug("CACHE MISS: $id");

        return $result;
    }

    public function contains($id)
    {
        if ($result = $this->cache->contains($id)) {
            $this->logger->debug("CACHE HIT: $id");

            return $result;
        }
        $this->logger->debug("CACHE MISS: $id");

        return $result;
    }

    public function save($id, $data, $lifeTime = 0)
    {
        $this->logger->debug(sprintf('CACHE SAVE: %s for %d seconds', $id, $lifeTime));

        return $this->cache->save($id, $data, $lifeTime);
    }

    public function delete($id)
    {
        $this->logger->debug("CACHE DELETE: $id");

        return $this->cache->delete($id);
    }

    public function getStats()
    {
        return $this->cache->getStats();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="shortcut icon" type="image/png" href="./img/fav-icon.png"/>

  <title>Reach</title>

  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

  <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

  <link href="css/creative.min.css" rel="stylesheet">

          Reach

Reaching Your

Health Potential

Mission

I am passionate about improving the healthcare ecosystem for everyone involved. I pursue projects that contribute to the common good, working with teams and individuals who really care about what they do. I am a web developer, a strategy consultant, and a proactive patient, ready to partner with you to achieve your objectives.

Mission

I am passionate about improving the healthcare ecosystem for everyone involved. I pursue projects that contribute to the common good, working with teams and individuals who really care about what they do. I am a web developer, a strategy consultant, and a proactive patient, ready to partner with you to achieve your objectives.

             Thacher 2016


text:
package jline;

/**
 * A CursorBuffer is a holder for a {@link StringBuffer} that also contains the
 * current cursor position.
 *
 * @author Marc Prud'hommeaux
 */
public class CursorBuffer {
    public int cursor = 0;

    StringBuffer buffer = new StringBuffer();

    private boolean overtyping = false;

    public int length() {
        return buffer.length();
    }

    public char current() {
        if (cursor <= 0) {
            return 0;
        }

        return buffer.charAt(cursor - 1);
    }

    public boolean clearBuffer() {
        if (buffer.length() == 0) {
            return false;
        }

        buffer.delete(0, buffer.length());
        cursor = 0;
        return true;
    }

    /**
     * Write the specific character into the buffer, setting the cursor position
     * ahead one. The text may overwrite or insert based on the current setting
     * of isOvertyping().
     *
     * @param c
     *            the character to insert
     */
    public void write(final char c) {
        buffer.insert(cursor++, c);
        if (isOvertyping() && cursor < buffer.length()) {
            buffer.deleteCharAt(cursor);
        }
    }

    /**
     * Insert the specified {@link String} into the buffer, setting the cursor
     * to the end of the insertion point.
     *
     * @param str
     *            the String to insert. Must not be null.
     */
    public void write(final String str) {
        if (buffer.length() == 0) {
            buffer.append(str);
        } else {
            buffer.insert(cursor, str);
        }

        cursor += str.length();

        if (isOvertyping() && cursor < buffer.length()) {
            buffer.delete(cursor, (cursor + str.length()));
        }
    }

    public String toString() {
        return buffer.toString();
    }

    public boolean isOvertyping() {
        return overtyping;
    }

    public void setOvertyping(boolean b) {
        overtyping = b;
    }

	public StringBuffer getBuffer() {
		return buffer;
	}

	public void setBuffer(StringBuffer buffer) {
		buffer.setLength(0);
		buffer.append(this.buffer.toString());

		this.buffer = buffer;
	}

}


text:
<!doctype html>
<html>
  <head>
    <title>Jasmine2/Sinon - angular-test-promise</title>

    <link rel="stylesheet" href="../../bower_components/jasmine2/lib/jasmine-core/jasmine.css">
  </head>
  <body>
    <!-- Test framework and mocking -->
    <script src="../../bower_components/jasmine2/lib/jasmine-core/jasmine.js"></script>
    <script src="../../bower_components/jasmine2/lib/jasmine-core/jasmine-html.js"></script>
    <script src="../../bower_components/jasmine2/lib/jasmine-core/boot.js"></script>
    <script src="../../bower_components/sinon/index.js"></script>
    <script src="../../bower_components/jasmine2-sinon/index.js"></script>

    <!-- Angular with mocks -->
    <script src="../../bower_components/angular/angular.js"></script>
    <script src="../../bower_components/angular-mocks/angular-mocks.js"></script>

    <!-- angular-test-promise -->
    <script src="../../index.js"></script>

    <!-- code -->
    <script src="../app/test-app.module.js"></script>
    <script src="../app/main.controller.js"></script>
    <script src="../app/repo.service.js"></script>

    <!-- tests -->
    <script src="main.controller.spec.js"></script>
    <script src="repo.service.spec.js"></script>
  </body>
</html>


text:
package tunnelproxy

import (
	"io"
	"sync"

	"github.com/igm/sockjs-go/sockjs"
)

type Tunnel struct {
	id          uint64         // key in kites's tunnels map
	localConn   sockjs.Session // conn to local kite
	startChan   chan bool      // to signal started state
	closeChan   chan bool      // to signal closed state
	closed      bool           // to prevent closing closeChan again
	closedMutex sync.Mutex     // for protection of closed field
}

func (t *Tunnel) Close() {
	t.closedMutex.Lock()
	defer t.closedMutex.Unlock()

	if t.closed {
		return
	}

	t.localConn.Close(3000, "Go away!")
	close(t.closeChan)
	t.closed = true
}

func (t *Tunnel) CloseNotify() chan bool {
	return t.closeChan
}

func (t *Tunnel) StartNotify() chan bool {
	return t.startChan
}

func (t *Tunnel) Run(remoteConn sockjs.Session) {
	close(t.startChan)
	<-JoinStreams(SessionReadWriteCloser{t.localConn}, SessionReadWriteCloser{remoteConn})
	t.Close()
}

func JoinStreams(local, remote io.ReadWriteCloser) chan error {
	errc := make(chan error, 2)

	copy := func(dst io.WriteCloser, src io.ReadCloser) {
		_, err := io.Copy(dst, src)
		src.Close()
		dst.Close()
		errc <- err
	}

	go copy(local, remote)
	go copy(remote, local)

	return errc
}

type SessionReadWriteCloser struct {
	session sockjs.Session
}

func (s SessionReadWriteCloser) Read(b []byte) (int, error) {
	str, err := s.session.Recv()
	if err != nil {
		return 0, err
	}
	copy(b, []byte(str))
	return len(str), nil
}

func (s SessionReadWriteCloser) Write(b []byte) (int, error) {
	return len(b), s.session.Send(string(b))
}

func (s SessionReadWriteCloser) Close() error {
	return s.session.Close(3000, "Go away!")
}


text:
package io.vertx.example.util;

import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.ext.dropwizard.DropwizardMetricsOptions;

import java.io.File;
import java.io.IOException;
import java.util.function.Consumer;

/*
 * @author Tim Fox
 */
public class Runner {

  public static final VertxOptions DROPWIZARD_OPTIONS = new VertxOptions().
      setMetricsOptions(new DropwizardMetricsOptions().setEnabled(true));

  private static final String METRICS_EXAMPLES_DIR = "metrics-examples";
  private static final String METRICS_EXAMPLES_JAVA_DIR = METRICS_EXAMPLES_DIR + "/src/main/java/";

  public static void runClusteredExample(Class clazz) {
    runExample(METRICS_EXAMPLES_JAVA_DIR, clazz, new VertxOptions(DROPWIZARD_OPTIONS), null, true);
  }

  public static void runExample(Class clazz) {
    runExample(METRICS_EXAMPLES_JAVA_DIR, clazz, new VertxOptions(DROPWIZARD_OPTIONS), null, false);
  }

  public static void runExample(String exampleDir, Class clazz, VertxOptions options, DeploymentOptions deploymentOptions, boolean clustered) {
    runExample(exampleDir + clazz.getPackage().getName().replace(".", "/"), clazz.getName(), options, deploymentOptions, clustered);
  }

  public static void runExample(String exampleDir, String verticleID, VertxOptions options, DeploymentOptions deploymentOptions, boolean clustered) {
    if (options == null) {
      // Default parameter
      options = new VertxOptions();
    }
    // Smart cwd detection

    // Based on the current directory (.) and the desired directory (exampleDir), we try to compute the vertx.cwd
    // directory:
    try {
      // We need to use the canonical file. Without the file name is .
      File current = new File(".").getCanonicalFile();
      if (exampleDir.startsWith(current.getName()) && !exampleDir.equals(current.getName())) {
        exampleDir = exampleDir.substring(current.getName().length() + 1);
      }
    } catch (IOException e) {
      // Ignore it.
    }

    System.setProperty("vertx.cwd", exampleDir);
    Consumer<Vertx> runner = vertx -> {
      try {
        if (deploymentOptions != null) {
          vertx.deployVerticle(verticleID, deploymentOptions);
        } else {
          vertx.deployVerticle(verticleID);
        }
      } catch (Throwable t) {
        t.printStackTrace();
      }
    };
    if (clustered) {
      Vertx.clusteredVertx(options, res -> {
        if (res.succeeded()) {
          Vertx vertx = res.result();
          runner.accept(vertx);
        } else {
          res.cause().printStackTrace();
        }
      });
    } else {
      Vertx vertx = Vertx.vertx(options);
      runner.accept(vertx);
    }
  }
}


text:
'use strict';

/**
 * Properties of a vulnerability assessment scan error.
 *
 */
class VulnerabilityAssessmentScanError {
  /**
   * Create a VulnerabilityAssessmentScanError.
   * @property {string} [code] The error code.
   * @property {string} [message] The error message.
   */
  constructor() {
  }

  /**
   * Defines the metadata of VulnerabilityAssessmentScanError
   *
   * @returns {object} metadata of VulnerabilityAssessmentScanError
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'VulnerabilityAssessmentScanError',
      type: {
        name: 'Composite',
        className: 'VulnerabilityAssessmentScanError',
        modelProperties: {
          code: {
            required: false,
            readOnly: true,
            serializedName: 'code',
            type: {
              name: 'String'
            }
          },
          message: {
            required: false,
            readOnly: true,
            serializedName: 'message',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = VulnerabilityAssessmentScanError;


text:
module KeyManager
  # barbican container
  class Container < ::Core::ServiceLayer::Model
    module Type
      GENERIC = 'generic'
      CERTIFICATE = 'certificate'
      RSA = 'rsa'

      def self.to_hash
        {
          GENERIC.to_sym => 'Used for any type of container that a
                             user may wish to create.',
          CERTIFICATE.to_sym => 'Used for storing secrets: certificate,
                                 private_key (optional), private_key_passphrase
                                 (optional), intermediates (optional).',
          RSA.to_sym => 'Used for storing RSA public keys, private keys, and
                         private key pass phrases.'
        }
      end
    end

    module SecretsName
      CERTIFICATE = 'certificate'
      PRIVATE_KEY = 'private_key'
      PUBLIC_KEY = 'public_key'
      PRIVATE_KEY_PASSPHRASE = 'private_key_passphrase'
      INTERMEDIATES = 'intermediates'
      FREELY_SELECTED = 'freely selected'

      def self.realtion_to_type
        {
          Type::GENERIC.to_sym => [FREELY_SELECTED],
          Type::CERTIFICATE.to_sym => [CERTIFICATE, PRIVATE_KEY, PRIVATE_KEY_PASSPHRASE, INTERMEDIATES],
          Type::RSA.to_sym => [PRIVATE_KEY, PRIVATE_KEY_PASSPHRASE, PUBLIC_KEY]
        }
      end
    end

    strip_attributes
    validates_presence_of :name, :type, :secret_refs

    def attributes_for_create
      {
        'name'         => read('name'),
        'secret_refs'  => read('secret_refs'),
        'type'         => read('type')
      }.delete_if { |_k, v| v.blank? }
    end

    def id
      super || URI(container_ref).path.split('/').last
    rescue
      nil
    end

    def display_name
      name.blank? ? 'Empty name' : name
    end

    def secrets
      secret_refs.each do |secret|
        secret['uuid'] = begin
                           URI(secret['secret_ref']).path.split('/').last
                         rescue => _e
                           nil
                         end
      end
    end

    alias uuid id
  end
end


text:
package binance

import (
	"context"
	"net/http"
)

// RateLimitService get rate limits
type RateLimitService struct {
	c *Client
}

// Do send request
func (s *RateLimitService) Do(ctx context.Context, opts ...RequestOption) (res []*RateLimitFull, err error) {
	res = make([]*RateLimitFull, 0)
	r := &request{
		method:   http.MethodGet,
		endpoint: "/api/v3/rateLimit/order",
		secType:  secTypeSigned,
	}
	data, err := s.c.callAPI(ctx, r, opts...)
	if err != nil {
		return res, err
	}
	err = json.Unmarshal(data, &res)
	if err != nil {
		return res, err
	}
	return res, nil
}

type RateLimitFull struct {
	RateLimitType RateLimitType     `json:"rateLimitType"`
	Interval      RateLimitInterval `json:"interval"`
	IntervalNum   int               `json:"intervalNum"`
	Limit         int               `json:"limit"`
	Count         int               `json:"count"`
}


text:
import React from 'react'
import './styles.css'

const Logo = () =>
Tux Demo

export default Logo


text:
import os, sys
SCRIPTDIR = os.path.dirname(__file__)

ENGINDIR = os.path.join(SCRIPTDIR, '..', '..', 'engines')
sys.path.append(os.path.abspath(ENGINDIR))
from fpsl_cvxpy import map_inference

PROBLEMDIR = os.path.join(SCRIPTDIR, '..', '..', 'problems', 'paper_review')
sys.path.append(os.path.abspath(PROBLEMDIR))
from grounding import ground

from os.path import join as ojoin

def run_model(data_path, out_path):

    rules, hard_rules, _, atoms = ground(data_path)
    results = map_inference(rules, hard_rules)

    reviews = atoms['review']
    with open(ojoin(out_path, 'POSITIVEREVIEW.txt'), 'w') as f:
        for (review, paper), (vid, _) in reviews.items():
            print("'%s'\t'%s'\t%f"%(review, paper, results[vid]), file=f)

    acceptable = atoms['acceptable']
    with open(ojoin(out_path, 'ACCEPTABLE.txt'), 'w') as f:
        for paper, (vid, _) in acceptable.items():
            print("'%s'\t%f"%(paper, results[vid]), file=f)

    presents = atoms['presents']
    with open(ojoin(out_path, 'PRESENTS.txt'), 'w') as f:
        for author, (vid, _) in presents.items():
            print("'%s'\t%f"%(author, results[vid]), file=f)

if __name__ == '__main__':
    data_path = ojoin(PROBLEMDIR, 'data', '1')
    out_path = ojoin('output', 'fpsl_cvxpy')
    run_model(data_path, out_path)


text:
<?php namespace nyx\notify\transports\mail\drivers;

// Internal dependencies
use nyx\notify\transports\mail;

class Sendgrid implements mail\interfaces\Driver
{
    /**
     * The traits of a Sendgrid Mail Driver instance.
     */
    use traits\CountsRecipients;

    /**
     * @var string  The API key (bearer token) used to authorize requests to Sendgrid's API.
     */
    protected $key;

    /**
     * @var \GuzzleHttp\ClientInterface The underlying HTTP Client instance.
     */
    protected $client;

    /**
     * Creates a new Sendgrid Mail Driver instance.
     *
     * @param   \GuzzleHttp\ClientInterface $client     The HTTP Client to use.
     * @param   string                      $key        The API key to be used to authorize requests to SparkPost's API.
     */
    public function __construct(\GuzzleHttp\ClientInterface $client, string $key)
    {
        $this->key    = $key;
        $this->client = $client;
    }

    /**
     * {@inheritDoc}
     */
    public function send(\Swift_Mime_Message $message, &$failures = null)
    {
        $this->client->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
            'headers' => [
                'Authorization' => 'Bearer '.$this->key
            ],
            'json' => $this->messageToPayload($message),
        ]);

        return $this->countRecipients($message);
    }

    /**
     * Converts a MIME Message to an array payload in a structure understood by Sendgrid's "mail/send" endpoint.
     *
     * @param   \Swift_Mime_Message $message    The Message to convert.
     * @return  array                           The resulting payload.
     */
    protected function messageToPayload(\Swift_Mime_Message $message) : array
    {
        $payload = [
            'Subject' => $message->getSubject()
        ];

        $this->processHeaders($message, $payload);
        $this->processAddresses($message, $payload);
        $this->processMimeEntities($message, $payload);
        $this->processAttachments($message, $payload);

        return $payload;
    }

    /**
     * Processes the MIME headers of a MIME Message into the payload structure passed in by reference.
     *
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
     * @param   array&              $payload    A reference to the payload structure.
     */
    protected function processHeaders(\Swift_Mime_Message $message, array &$payload)
    {
        if (!$headers = $message->getHeaders()->getAll()) {
            return;
        }

        $payload['Headers'] = [];

        /** @var \Swift_Mime_Header $header */
        foreach ($headers as $header) {

            // Omit headers which are handled elsewhere.
            if (in_array($fieldName = $header->getFieldName(), ['Subject', 'Content-Type', 'MIME-Version', 'Date', 'From', 'To'])) {
                continue;
            }

            if ($header instanceof \Swift_Mime_Headers_UnstructuredHeader || $header instanceof \Swift_Mime_Headers_OpenDKIMHeader) {
                $payload['Headers'][] = [
                    "Name"  => $fieldName,
                    "Value" => $header->getValue()
                ];

                continue;
            }

            // All other headers are handled in the same fashion.
            $payload['Headers'][] = [
                "Name"  => $fieldName,
                "Value" => $header->getFieldBody()
            ];
        }
    }

    /**
     * Processes the fields containing e-mail addresses (from, to, cc, etc.) in the MIME Message into
     * the payload structure passed in by reference.
     *
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
     * @param   array&              $payload    A reference to the payload structure.
     */
    protected function processAddresses(\Swift_Mime_Message $message, array &$payload)
    {
        // Sendgrid expect the 'from' field to be a single entry at most, according to the docs.
        $payload['from'] = $this->processFirstAddress($message->getFrom());

        if (!isset($payload['personalizations'])) {
            $payload['personalizations'] = [];
        }

        $payload['personalizations']['to'] = $this->processAllAddresses($message->getTo());

        if ($cc = $message->getCc()) {
            $payload['personalizations']['cc'] = $this->processAllAddresses($cc);
        }

        if ($bcc = $message->getBcc()) {
            $payload['personalizations']['bcc'] = $this->processAllAddresses($bcc);
        }

        if ($replyTo = $message->getReplyTo()) {
            $payload['reply_to'] = $this->processFirstAddress($replyTo);
        }
    }

    /**
     * Parses the first and only the first address from the given array of e-mail addresses into a structure
     * understood by Sendgrid's API.
     *
     * @param   array   $addresses  The e-mail addresses to parse.
     * @return  array
     */
    protected function processFirstAddress(array $addresses) : array
    {
        foreach ($addresses as $email => $name) {
            return $name ? [
                'email' => $email,
                'name'  => $name
            ] : [
                'email' => $email
            ];
        }

        return [];
    }

    /**
     * Parses the given array of e-mail addresses into a structure understood by Sendgrid's API.
     *
     * @param   array   $addresses  The e-mail addresses to parse.
     * @return  array
     */
    protected function processAllAddresses(array $addresses) : array
    {
        $result = [];

        foreach ($addresses as $email => $name) {
            $result[] = $name ? [
                'email' => $email,
                'name'  => $name
            ] : [
                'email' => $email
            ];
        }

        return $result;
    }

    /**
     * Processes the MIME entities in the MIME Message into the payload structure passed in by reference.
     *
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
     * @param   array&              $payload    A reference to the payload structure.
     */
    protected function processMimeEntities(\Swift_Mime_Message $message, array &$payload)
    {
        switch ($message->getContentType()) {
            case 'text/html':
            case 'multipart/alternative':
            case 'multipart/mixed':

                // text/plain, if present, must be the first key according to the docs.
                if ($plain = $this->getMimePart($message, 'text/plain')) {
                    $payload['content'][] = [
                        'type'  => 'text/plain',
                        'value' => $plain->getBody()
                    ];
                }

                $payload['content'][] = [
                    'type'  => 'text/html',
                    'value' => $message->getBody()
                ];

                break;

            default:

                $payload['content'][] = [
                    'type'  => 'text/plain',
                    'value' => $message->getBody()
                ];

                if ($html = $this->getMimePart($message, 'text/html')) {
                    $payload['content'][] = [
                        'type'  => 'text/html',
                        'value' => $html->getBody()
                    ];
                }
        }
    }

    /**
     * Returns the MIME part of the specified content type contained in the given MIME message, if it's present.
     *
     * @param   \Swift_Mime_Message     $message    The MIME Message to process.
     * @param   string                  $mimeType   The content type the part to return must be of.
     * @return  \Swift_Mime_MimeEntity
     */
    protected function getMimePart(\Swift_Mime_Message $message, string $mimeType)
    {
        foreach ($message->getChildren() as $part) {
            if (0 === strpos($part->getContentType(), $mimeType) && !$part instanceof \Swift_Mime_Attachment) {
                return $part;
            }
        }
    }

    /**
     * Processes the attachments in the MIME Message into the payload structure passed in by reference.
     *
     * @param   \Swift_Mime_Message $message    The MIME Message to process.
     * @param   array&              $payload    A reference to the payload structure.
     */
    protected function processAttachments(\Swift_Mime_Message $message, array &$payload)
    {
        if (!$children = $message->getChildren()) {
            return;
        }

        $payload['attachments'] = [];

        foreach ($children as $attachment) {

            // Omit all MIME Entities that aren't attachments.
            if (!$attachment instanceof \Swift_Mime_Attachment) {
                continue;
            }

            $data = [
                'filename'    => $attachment->getFilename(),
                'content'     => base64_encode($attachment->getBody()),
                'type'        => $attachment->getContentType(),
                'disposition' => $attachment->getDisposition(),
            ];

            if ($attachment->getDisposition() !== 'attachment' && null !== $cid = $attachment->getId()) {
                $data['content_id'] = 'cid:'.$cid;
            }

            $payload['attachments'][] = $data;
        }
    }
}


text:
RHReliableDatagram::RHReliableDatagram(RHGenericDriver& driver, uint8_t thisAddress)
    : RHDatagram(driver, thisAddress)
{
    _retransmissions = 0;
    _lastSequenceNumber = 0;
    _timeout = RH_DEFAULT_TIMEOUT;
    _retries = RH_DEFAULT_RETRIES;
}

////////////////////////////////////////////////////////////////////
// Public methods
void RHReliableDatagram::setTimeout(uint16_t timeout)
{
    _timeout = timeout;
}

////////////////////////////////////////////////////////////////////
void RHReliableDatagram::setRetries(uint8_t retries)
{
    _retries = retries;
}

////////////////////////////////////////////////////////////////////
uint8_t RHReliableDatagram::retries()
{
    return _retries;
}

////////////////////////////////////////////////////////////////////
bool RHReliableDatagram::sendtoWait(uint8_t* buf, uint8_t len, uint8_t address)
{
    // Assemble the message
    uint8_t thisSequenceNumber = ++_lastSequenceNumber;
    uint8_t retries = 0;
    while (retries++ <= _retries)
    {
	setHeaderId(thisSequenceNumber);
	setHeaderFlags(RH_FLAGS_NONE, RH_FLAGS_ACK); // Clear the ACK flag
	sendto(buf, len, address);
	waitPacketSent();

	// Never wait for ACKS to broadcasts:
	if (address == RH_BROADCAST_ADDRESS)
	    return true;

	if (retries > 1)
	    _retransmissions++;
	unsigned long thisSendTime = millis(); // Timeout does not include original transmit time

	// Compute a new timeout, random between _timeout and _timeout*2
	// This is to prevent collisions on every retransmit
	// if 2 nodes try to transmit at the same time
#if (RH_PLATFORM == RH_PLATFORM_RASPI) // use standard library random(), bugs in random(min, max)
	uint16_t timeout = _timeout + (_timeout * (random() & 0xFF) / 256);
#else
	uint16_t timeout = _timeout + (_timeout * random(0, 256) / 256);
#endif
	int32_t timeLeft;
        while ((timeLeft = timeout - (millis() - thisSendTime)) > 0)
	{
	    if (waitAvailableTimeout(timeLeft))
	    {
		uint8_t from, to, id, flags;
		if (recvfrom(0, 0, &from, &to, &id, &flags)) // Discards the message
		{
		    // Now have a message: is it our ACK?
		    if (   from == address
			   && to == _thisAddress
			   && (flags & RH_FLAGS_ACK)
			   && (id == thisSequenceNumber))
		    {
			// Its the ACK we are waiting for
			return true;
		    }
		    else if (   !(flags & RH_FLAGS_ACK)
				&& (id == _seenIds[from]))
		    {
			// This is a request we have already received. ACK it again
			acknowledge(id, from);
		    }
		    // Else discard it
		}
	    }
	    // Not the one we are waiting for, maybe keep waiting until timeout exhausted
	    YIELD;
	}
	// Timeout exhausted, maybe retry
	YIELD;
    }
    // Retries exhausted
    return false;
}

////////////////////////////////////////////////////////////////////
bool RHReliableDatagram::recvfromAck(uint8_t* buf, uint8_t* len, uint8_t* from, uint8_t* to, uint8_t* id, uint8_t* flags)
{
    uint8_t _from;
    uint8_t _to;
    uint8_t _id;
    uint8_t _flags;
    // Get the message before its clobbered by the ACK (shared rx and tx buffer in some drivers
    if (available() && recvfrom(buf, len, &_from, &_to, &_id, &_flags))
    {
	// Never ACK an ACK
	if (!(_flags & RH_FLAGS_ACK))
	{
	    // Its a normal message for this node, not an ACK
	    if (_to != RH_BROADCAST_ADDRESS)
	    {
		// Its not a broadcast, so ACK it
		// Acknowledge message with ACK set in flags and ID set to received ID
		acknowledge(_id, _from);
	    }
	    // If we have not seen this message before, then we are interested in it
	    if (_id != _seenIds[_from])
	    {
		if (from)  *from =  _from;
		if (to)    *to =    _to;
		if (id)    *id =    _id;
		if (flags) *flags = _flags;
		_seenIds[_from] = _id;
		return true;
	    }
	    // Else just re-ack it and wait for a new one
	}
    }
    // No message for us available
    return false;
}

bool RHReliableDatagram::recvfromAckTimeout(uint8_t* buf, uint8_t* len, uint16_t timeout, uint8_t* from, uint8_t* to, uint8_t* id, uint8_t* flags)
{
    unsigned long starttime = millis();
    int32_t timeLeft;
    while ((timeLeft = timeout - (millis() - starttime)) > 0)
    {
	if (waitAvailableTimeout(timeLeft))
	{
	    if (recvfromAck(buf, len, from, to, id, flags))
		return true;
	}
	YIELD;
    }
    return false;
}

uint32_t RHReliableDatagram::retransmissions()
{
    return _retransmissions;
}

void RHReliableDatagram::resetRetransmissions()
{
    _retransmissions = 0;
}

void RHReliableDatagram::acknowledge(uint8_t id, uint8_t from)
{
    setHeaderId(id);
    setHeaderFlags(RH_FLAGS_ACK);
    // We would prefer to send a zero length ACK,
    // but if an RH_RF22 receives a 0 length message with a CRC error, it will never receive
    // a 0 length message again, until its reset, which makes everything hang :-(
    // So we send an ACK of 1 octet
    // REVISIT: should we send the RSSI for the information of the sender?
    uint8_t ack = '!';
    sendto(&ack, sizeof(ack), from);
    waitPacketSent();
}


text:
require 'fileutils'
FileUtils.rm_rf "#{File.dirname(__FILE__)}/extensions/compass-colors"