text:
package com.thoughtworks.go.publishers;

import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.work.BuildRepositoryRemoteStub;
import com.thoughtworks.go.remote.work.GoArtifactsManipulatorStub;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.util.CachedDigestUtils;
import com.thoughtworks.go.util.HttpService;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.TempDirUtils;
import com.thoughtworks.go.work.DefaultGoPublisher;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Properties;

import static com.thoughtworks.go.util.SystemUtil.currentWorkingDirectory;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.*;

public class GoArtifactsManipulatorTest {

    private HttpService httpService;
    private File tempFile;
    private GoArtifactsManipulatorStub goArtifactsManipulatorStub;
    private JobIdentifier jobIdentifier;
    private DefaultGoPublisher goPublisher;
    private Path artifactFolder;

    @BeforeEach
    public void setUp(@TempDir Path tempDir) throws Exception {
        httpService = mock(HttpService.class);
        artifactFolder = TempDirUtils.createTempDirectoryIn(tempDir, "artifact_folder");
        tempFile = artifactFolder.resolve("file.txt").toFile();
        FileUtils.writeStringToFile(tempFile, "some-random-data", UTF_8);
        goArtifactsManipulatorStub = new GoArtifactsManipulatorStub(httpService);
        jobIdentifier = new JobIdentifier("pipeline1", 1, "label-1", "stage1", "1", "job1");
        AgentRuntimeInfo agentRuntimeInfo = new AgentRuntimeInfo(new AgentIdentifier("h", "1", "u"), AgentRuntimeStatus.Idle, currentWorkingDirectory(), null);
        goPublisher = new DefaultGoPublisher(goArtifactsManipulatorStub, jobIdentifier, new BuildRepositoryRemoteStub(), agentRuntimeInfo, "utf-8");
    }

    @Test
    public void shouldBombWithErrorWhenStatusCodeReturnedIsRequestEntityTooLarge() throws IOException, InterruptedException {
        when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class))).thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

        CircularFifoQueue buffer = (CircularFifoQueue) ReflectionUtil.getField(ReflectionUtil.getField(goPublisher, "consoleOutputTransmitter"), "buffer");
        synchronized (buffer) {
            try {
                goArtifactsManipulatorStub.publish(goPublisher, "some_dest", tempFile, jobIdentifier);
                fail("should have thrown request entity too large error");
            } catch (RuntimeException e) {
                String expectedMessage = "Artifact upload for file " + tempFile.getAbsolutePath() + " (Size: "+ tempFile.length() +") was denied by the server. This usually happens when server runs out of disk space.";
                assertThat(e.getMessage(), is("java.lang.RuntimeException: " + expectedMessage + ".  HTTP return code is 413"));
                assertThat(buffer.toString().contains(expectedMessage), is(true));
            }
        }
    }

    @Test
    public void uploadShouldBeGivenFileSize() throws IOException {

        when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class))).thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        try {
            goArtifactsManipulatorStub.publish(goPublisher, "dest", tempFile, jobIdentifier);
            fail("should have thrown request entity too large error");
        } catch (RuntimeException e) {
            verify(httpService).upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class));
        }
    }

    @Test
    public void shouldUploadArtifactChecksumAlongWithArtifact() throws IOException {
        String data = "Some text whose checksum can be asserted";
        final String md5 = CachedDigestUtils.md5Hex(data);
        FileUtils.writeStringToFile(tempFile, data, UTF_8);
        Properties properties = new Properties();
        properties.setProperty("dest/path/file.txt", md5);

        when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), eq(properties))).thenReturn(HttpServletResponse.SC_OK);

        goArtifactsManipulatorStub.publish(goPublisher, "/dest/path", tempFile, jobIdentifier);
    }

    @Test
    public void shouldUploadArtifactChecksumWithRightPathWhenArtifactDestinationPathIsEmpty() throws IOException {
        String data = "Some text whose checksum can be asserted";
        final String md5 = CachedDigestUtils.md5Hex(data);
        FileUtils.writeStringToFile(tempFile, data, UTF_8);
        Properties properties = new Properties();
        properties.setProperty("file.txt", md5);

        when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), eq(properties))).thenReturn(HttpServletResponse.SC_OK);

        goArtifactsManipulatorStub.publish(goPublisher, "", tempFile, jobIdentifier);
    }

    @Test
    public void shouldUploadArtifactChecksumForADirectory() throws IOException {
        String data = "Some text whose checksum can be asserted";
        String secondData = "some more";

        FileUtils.writeStringToFile(tempFile, data, UTF_8);

        File anotherFile = artifactFolder.resolve("bond/james_bond/another_file").toFile();
        FileUtils.writeStringToFile(anotherFile, secondData, UTF_8);

        when(httpService.upload(any(String.class), eq(FileUtils.sizeOfDirectory(artifactFolder.toFile())), any(File.class), eq(expectedProperties(data, secondData)))).thenReturn(HttpServletResponse.SC_OK);

        goArtifactsManipulatorStub.publish(goPublisher, "dest", artifactFolder.toFile(), jobIdentifier);
    }

    private Properties expectedProperties(String data, String secondData) {
        Properties properties = new Properties();
        properties.setProperty("dest/artifact_folder/file.txt", CachedDigestUtils.md5Hex(data));
        properties.setProperty("dest/artifact_folder/bond/james_bond/another_file", CachedDigestUtils.md5Hex(secondData));
        return properties;
    }

}


text:
A simple helper to assist with writing MCollective actions in PHP.

Given an action as below:

action "echo" do
   validate :message, String

   implemented_by "/tmp/echo.php"
end

The following PHP script will implement the echo action externally
replying with _message_ and _timestamp_

<?php
    require("mcollective_action.php");

    $mc = new MCollectiveAction();
    $mc->message = $mc->data["message"];
    $mc->timestamp = strftime("%c");
    $mc->info("some text to info log on the server");
?>

Calling it with _mco rpc_ results in:

$ mco rpc test echo message="hello world"
Determining the amount of hosts matching filter for 2 seconds .... 1

 * [ ============================================================> ] 1 / 1

nephilim.ml.org                         : OK
    {:message=>"hello world", :time=>"Tue Mar 15 19:20:53 +0000 2011"}

redpajama_set_name: RedPajamaGithub


text:
package org.datagr4m.viewer.renderer.hit;

import java.util.List;

import org.datagr4m.viewer.mouse.IClickableItem;

public class DefaultHitProcessor implements IHitProcessor{
    @Override
    public List<IClickableItem> hit(int x, int y){
        return null;
    }

    @Override
    public <T> List<IClickableItem> hitOnly(int x, int y, Class<T> type){
        if(type.isInstance(this))
            return hit(x, y);
        else
            return null;
    }

    @Override
    public <T> List<IClickableItem> hitExcluding(int x, int y, Class<T> type){
        if(!type.isInstance(this))
            return hit(x, y);
        else
            return null;
    }
}


text:
char *
sj_string_alloc_join_string_array_with_separator(struct sj_string_array const *string_array,
                                                 char const *separator)
{
  return sj_string_alloc_join_strings_with_separator(
      (char const *const *) string_array->elements,
      string_array->count,
      separator
  );
}

char *
sj_string_alloc_join_string_array_with_suffix(struct sj_string_array const *string_array,
                                              char const *suffix)
{
  return sj_string_alloc_join_strings_with_suffix(
      (char const *const *) string_array->elements,
      string_array->count,
      suffix
  );
}

char *
sj_string_alloc_join_strings_with_separator(char const *const strings[],
                                            int count,
                                            char const *separator)
{
  size_t size = 1;
  size_t separator_size = strlen(separator);
  for (int i = 0; i < count; ++i) {
    if (i) size += separator_size;
    size += strlen(strings[i]);
  }
  char *joined = malloc_or_die(size);
  char *end = joined;
  for (int i = 0; i < count; ++i) {
    if (i) end = stpcpy(end, separator);
    end = stpcpy(end, strings[i]);
  }
  return joined;
}

char *
sj_string_alloc_join_strings_with_suffix(char const *const strings[],
                                         int count,
                                         char const *suffix)
{
  size_t size = 1;
  size_t suffix_size = strlen(suffix);
  for (int i = 0; i < count; ++i) {
    size += strlen(strings[i]);
    size += suffix_size;
  }
  char *joined = malloc_or_die(size);
  char *end = joined;
  for (int i = 0; i < count; ++i) {
    end = stpcpy(end, strings[i]);
    end = stpcpy(end, suffix);
  }
  return joined;
}


text:
using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable restore
namespace Elastic.Clients.Elasticsearch.Aggregations;
public sealed partial class IpRangeAggregate : IAggregate
{
	[JsonInclude]
	[JsonPropertyName("buckets")]
	public IReadOnlyCollection<Elastic.Clients.Elasticsearch.Aggregations.IpRangeBucket> Buckets { get; init; }

	[JsonInclude]
	[JsonPropertyName("meta")]
	public Dictionary<string, object>? Meta { get; init; }
}


text:
.. RailGun documentation master file, created by
   sphinx-quickstart on Tue Oct 12 20:32:26 2010.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to RailGun's documentation!
===================================

.. list-table::

  * - Write less code in *C*

      .. sourcecode:: c

         typedef struct linearode_{
           int num_d, num_s;
           double dt;
           double **a;
           double **x;
         } LinearODE;

         int LinearODE_run(LinearODE *self)
         {
           int s, d1, d2;
           for (s = 1; s < self->num_s; ++s){
             for (d1 = 0; d1 < self->num_d; ++d1){
               self->x[s][d1] = self->x[s-1][d1];
               for (d2 = 0; d2 < self->num_d; ++d2){
                 self->x[s][d1] += self->dt * \
                   self->a[d1][d2] * self->x[s-1][d2];
               }
             }
           }
           return 0;
         }

    - ... *and in Python*! ::

        from railgun import SimObject, relpath

        class LinearODE(SimObject):
            _clibname_ = 'liblode.so'
            _clibdir_ = relpath('.', __file__)
            _cmembers_ = [
                'num_d',
                'num_s = 10000',
                'double dt = 0.001',
                'double a[d][d]',
                'double x[s][d]',
                ]
            _cfuncs_ = ["x run()"]

        lode = LinearODE(num_d=2)
        lode.a = [[0, 1], [-1, 0]]
        lode.x[0] = [1, 0]
        x = lode.run()

        import pylab
        pylab.plot(x)
        pylab.show()

The above pair of C and python code is very short but yet *complete* example!

If you want to write fast program for numerical simulations, you will
always end up with writing it in C (or C++ or FORTRAN, these low-level
languages). Although we have great python packages (not only) for
numerical simulation such as Numpy/Scipy, Pyrex, Cython, Psyco and so
on, sometimes these are not enough. On the other hand, writing code in
C is stressful, especially things like allocating memory and
read/write data which do not require speed so much. So, next thing you
want is to call C function from python and let python do all these
stuff (which python is good at!). Using ctypes, this is very easy.

On top of what ctypes provides, RailGun adds more features to kill
boilerplate that you normally need for simulation coding.

For example, when you write simulation code, you may face situation
like this many times:

    I am accessing array like ``x[i][j]`` and ``y[j][k]``, so I want
    the second axis of the array ``x`` and the first axis of the array
    ``y`` to be of the same length.

RailGun solves this problem by keeping shape of all arrays to be
consistent.  Memory allocation for these arrays is done automatically.

RailGun also provides some value check before passing it to C function.
For example, you may want to pass an index of some array to C function.
When you do that, you need to check if the index is in a certain range,
to avoid segmentation fault.  RailGun provides a short hand notation
to check that automatically.  Also, you can wrap C function to put any
kind of complex value check and pre/post-processing.

With these features and other useful utilities provided by RailGun,
you can really focus on guts of computation in C code.

Installation::

    pip install railgun   # using pip
    easy_install railgun  # using setuptools (if you must)

Requirements:

- Numpy
- six
- (matplotlib for sample code)

Contents:

.. toctree::
   :maxdepth: 2

   tutorial
   simobj
   utils
   samples/index
   changelog

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
"""Translate arguments

Revision ID: 10caa96b2356
Revises: 44090569867
Create Date: 2015-04-24 10:12:47.322973

"""

# revision identifiers, used by Alembic.
revision = '10caa96b2356'
down_revision = '44090569867'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
owner_type_enum = sa.Enum('company', 'individual', name='owner_type_enum')
def upgrade():
    owner_type_enum.create(op.get_bind(), checkfirst=True)
    op.add_column('ADS', sa.Column('category', sa.String(), nullable=False))
    op.add_column('ADS', sa.Column('owner_name', sa.String(), nullable=False))
    op.add_column('ADS', sa.Column('owner_type', owner_type_enum , nullable=False))
    op.alter_column('ADS', 'numero', type_=sa.String(),
               existing_type=sa.INTEGER(),
               nullable=False)
    op.drop_column('ADS', 'personne')
    op.drop_column('ADS', 'artisan')
    op.drop_column('ADS', 'nom_societe')
    op.add_column('driver', sa.Column('birth_date', sa.Date(), nullable=True))
    op.add_column('driver', sa.Column('first_name', sa.String(length=255), nullable=False))
    op.add_column('driver', sa.Column('last_name', sa.String(length=255), nullable=False))
    op.add_column('driver', sa.Column('professional_licence', sa.String(), nullable=False))
    op.drop_column('driver', 'nom')
    op.drop_column('driver', 'carte_pro')
    op.drop_column('driver', 'date_naissance')
    op.drop_column('driver', 'prenom')
    op.add_column('vehicle', sa.Column('air_con', sa.Boolean(), nullable=True))
    op.add_column('vehicle', sa.Column('constructor', sa.String(length=255), nullable=True))
    op.add_column('vehicle', sa.Column('cpam_conventionne', sa.Boolean(), nullable=True))
    op.add_column('vehicle', sa.Column('electronic_toll', sa.Boolean(), nullable=True))
    op.add_column('vehicle', sa.Column('engine', sa.String(length=80), nullable=True))
    op.add_column('vehicle', sa.Column('horse_power', sa.Float(), nullable=True))
    op.add_column('vehicle', sa.Column('licence_plate', sa.String(length=80), nullable=False))
    op.add_column('vehicle', sa.Column('luxury', sa.Boolean(), nullable=True))
    op.add_column('vehicle', sa.Column('model', sa.String(length=255), nullable=True))
    op.add_column('vehicle', sa.Column('model_year', sa.Integer(), nullable=True))
    op.add_column('vehicle', sa.Column('special_need_vehicle', sa.Boolean(), nullable=True))
    op.add_column('vehicle', sa.Column('tablet', sa.Boolean(), nullable=True))
    op.drop_column('vehicle', 'snv')
    op.drop_column('vehicle', 'conventionne')
    op.drop_column('vehicle', 'pmr')
    op.drop_column('vehicle', 'immatriculation')
    op.drop_column('vehicle', 'luxary')
    op.drop_column('vehicle', 'telepeage')
    op.drop_column('vehicle', 'puissance')
    op.drop_column('vehicle', 'marque')
    op.drop_column('vehicle', 'AC_vehicle')
    op.drop_column('vehicle', 'annee')
    op.drop_column('vehicle', 'motorisation')
    op.drop_column('vehicle', 'modele')

def downgrade():
    op.add_column('vehicle', sa.Column('modele', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('motorisation', sa.VARCHAR(length=80), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('annee', sa.INTEGER(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('AC_vehicle', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('marque', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('puissance', postgresql.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('telepeage', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('luxary', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('immatriculation', sa.VARCHAR(length=80), autoincrement=False, nullable=False))
    op.add_column('vehicle', sa.Column('pmr', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('conventionne', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('vehicle', sa.Column('snv', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.drop_column('vehicle', 'tablet')
    op.drop_column('vehicle', 'special_need_vehicle')
    op.drop_column('vehicle', 'model_year')
    op.drop_column('vehicle', 'model')
    op.drop_column('vehicle', 'luxury')
    op.drop_column('vehicle', 'licence_plate')
    op.drop_column('vehicle', 'horse_power')
    op.drop_column('vehicle', 'engine')
    op.drop_column('vehicle', 'electronic_toll')
    op.drop_column('vehicle', 'cpam_conventionne')
    op.drop_column('vehicle', 'constructor')
    op.drop_column('vehicle', 'air_con')
    op.add_column('driver', sa.Column('prenom', sa.VARCHAR(length=255), autoincrement=False, nullable=False))
    op.add_column('driver', sa.Column('date_naissance', sa.DATE(), autoincrement=False, nullable=True))
    op.add_column('driver', sa.Column('carte_pro', sa.VARCHAR(), autoincrement=False, nullable=False))
    op.add_column('driver', sa.Column('nom', sa.VARCHAR(length=255), autoincrement=False, nullable=False))
    op.drop_column('driver', 'professional_licence')
    op.drop_column('driver', 'last_name')
    op.drop_column('driver', 'first_name')
    op.drop_column('driver', 'birth_date')
    op.add_column('ADS', sa.Column('nom_societe', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
    op.add_column('ADS', sa.Column('artisan', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
    owner_type_enum.drop(op.get_bind())
    op.add_column('ADS', sa.Column('personne', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
    op.alter_column('ADS', 'numero',
               existing_type=sa.INTEGER(),
               nullable=True)
    op.alter_column('ADS', 'added_via',
               existing_type=postgresql.ENUM('form', 'api', name='via'),
               nullable=True)
    op.drop_column('ADS', 'owner_type')
    op.drop_column('ADS', 'owner_name')
    op.drop_column('ADS', 'category')
    ### end Alembic commands ###


text:
package com.covisint.cf.broker.dynatrace.provisioning;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Map;

/**
 * Class: ProvisioningController.java
 * Description: ProvisioningController class will be responsible request mapping (PUT , DELETE) of all service_instances.
 * 			    documentationUrl and  supportUrl
 *
 *@version 1.0, 2015-06-01
 *@author lingesh - happiest minds-covisint
 *
 */

@RestController
final class ProvisioningController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * create method
     *
     * @param provisioningRequest json request from RequestBody
     * @return ProvisioningResponse
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/v2/service_instances/*")
    ProvisioningResponse create(@RequestBody ProvisioningRequest provisioningRequest) {
        this.logger.info("Provisioning Request Received: {}", provisioningRequest);
        return new ProvisioningResponse(null);
    }

    /**
     * delete method
     *
     * @param serviceId serviceid
     * @param planId planId
     * @return Map
     */
    @RequestMapping(method = RequestMethod.DELETE, value = "/v2/service_instances/*")
    Map<?, ?> delete(@RequestParam("service_id") String serviceId, @RequestParam("plan_id") String planId) {
        this.logger.info("De-provisioning Request Received: service_id: {}, plan_id: {}", serviceId, planId);
        return Collections.emptyMap();
    }

}


text:
package dynamo

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/crowdmob/goamz/aws"
	"github.com/crowdmob/goamz/dynamodb"
)

// Dynamo
type Dynamo struct {
	Auth            aws.Auth
	Server          dynamodb.Server
	compoundKeys    bool
	consistentReads bool
	getTableName    ProcessTableName
	credz           credentials
}

type credentials struct {
	accessKey string
	secretKey string
	token     string
}

// ProcessTableName allows manipulation of the table name queried.
// Since DynamoDB provides a single data namespace per AWS account this func can
// be used to add a namespace to tables, e.g. prod_users or test_users. The default
// implementation just returns the tableName given.
type ProcessTableName func(tableName string) string

// OptCompoundKeys Compound keys are a shortcut for range and a hash key in the form of "myrange/myhash".
// A key with '/' separating the range and hash.
func OptCompoundKeys(ck bool) func(*Dynamo) error {
	return func(d *Dynamo) error {
		d.compoundKeys = ck
		return nil
	}
}

// OptConsistentReads sets the default consistent read behavior. Can be overridden on a request basis. Defaults to true
func OptConsistentReads(cr bool) func(*Dynamo) error {
	return func(d *Dynamo) error {
		d.consistentReads = cr
		return nil
	}
}

// OptCredentials sets the AWS credentials.  The default AWS lookup is usually sufficient.
func OptCredentials(accessKey, secretKey, token string) func(*Dynamo) error {
	return func(d *Dynamo) error {
		d.credz = credentials{accessKey, secretKey, token}
		return nil
	}
}

// OptProcessTableName allows setting of a function to manipulate the table name used by dynamo.
func OptProcessTableName(tbName ProcessTableName) func(*Dynamo) error {
	return func(d *Dynamo) error {
		d.getTableName = tbName
		return nil
	}
}

// NewDynamo creates a new instance of Dynamo
func NewDynamo(region Region, options ...func(*Dynamo) error) (*Dynamo, error) {
	if region.Address == "" {
		return nil, errors.New("No region/endpoint specified.")
	}
	var r aws.Region
	if strings.Contains(region.Address, "localhost") {
		r = aws.Region{Name: "localhost", DynamoDBEndpoint: region.Address}
	} else {
		r = aws.Regions[region.Name]
	}
	if r.Name == "" {
		return nil, fmt.Errorf("%s is not a valid region", region.Name)
	}

	d := Dynamo{
		compoundKeys:    false,
		consistentReads: true,
		getTableName:    func(t string) string { return t },
	}
	err := d.applyOptions(options)
	if err != nil {
		return nil, err
	}
	auth, err := aws.GetAuth(d.credz.accessKey, d.credz.secretKey, d.credz.token, time.Now())
	if err != nil {
		return nil, err
	}

	d.Auth = auth
	d.Server = dynamodb.Server{Auth: auth, Region: r}
	return &d, nil
}

func (d *Dynamo) Save(table, key string, val interface{}) error {
	attrs, err := dynamodb.MarshalAttributes(val)
	if err != nil {
		return fmt.Errorf("Failed to marshall attributes: %s", err)
	}
	tb, _, err := d.getTable(table)
	if err != nil {
		return err
	}

	fullkey := keyParts{id: key}
	if d.compoundKeys {
		fullkey = parseDataKey(key)
	}
	_, err = tb.PutItem(fullkey.id, fullkey.scope, attrs)
	if err != nil {
		return fmt.Errorf("Put item failed for %s:%s - %s", table, key, err)
	}
	return nil
}

func (d *Dynamo) applyOptions(options []func(*Dynamo) error) error {
	for _, option := range options {
		err := option(d)
		if err != nil {
			return err
		}
	}
	return nil
}

// scanSettings are the settings based on analyzing the tables
// size and configured throughput

func (d *Dynamo) calcScanRoutines(tb *dynamodb.Table) int {
	return 2
}

type Schema struct {
	TableName string
	Key       string
	RangeKey  string
}

func (d *Dynamo) TableSchema(tableName string) (Schema, error) {
	tName := d.getTableName(tableName)
	tableDesc, err := d.Server.DescribeTable(tName)
	if err != nil {
		return Schema{}, fmt.Errorf("Failure describing table '%s - %s'.", tName, err)
	}
	pkey, err := tableDesc.BuildPrimaryKey()
	if err != nil {
		return Schema{}, fmt.Errorf("Failure getting primary key from table '%s - %s'", tName, err)
	}

	rkey := ""
	if pkey.HasRange() {
		rkey = pkey.RangeAttribute.Name
	}
	return Schema{
		TableName: tName,
		Key:       pkey.KeyAttribute.Name,
		RangeKey:  rkey,
	}, nil
}

func (d *Dynamo) getTable(rawName string) (tbl *dynamodb.Table, itemCount int, err error) {
	tName := d.getTableName(rawName)
	// Having to run a describe table just to get a Table instance is terrible
	tableDesc, err := d.Server.DescribeTable(tName)
	if err != nil {
		return nil, itemCount, fmt.Errorf("Failure describing table '%s - %s'.", tName, err)
	}

	itemCount = int(tableDesc.ItemCount)
	pkey, err := tableDesc.BuildPrimaryKey()
	if err != nil {
		return nil, itemCount, fmt.Errorf("Failure getting primary key from table '%s - %s'", tName, err)
	}
	return d.Server.NewTable(tName, pkey), itemCount, nil
}

type keyParts struct {
	scope string
	id    string
}

func parseDataKey(k string) keyParts {
	parts := strings.Split(string(k), "/")
	scope, id := "", ""

	if len(parts) == 1 {
		id = string(k)
	} else {
		scope = parts[0]
		id = parts[1]
	}
	return keyParts{
		scope: scope,
		id:    id,
	}
}


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 br.senac.tads3.pi3b.leonsdev.cliente.classes;

import java.util.Date;

/**
 *
 * @author Nakamura-PC
 */
public class Cliente {

    //
    private int id, pontos;

    public int getPontos() {
        return pontos;
    }

    public void setPontos(int pontos) {
        this.pontos = pontos;
    }
    private String nome, sobrenome, cpf, email, celular, estado, genero, cidade, endereco, cep;
    private Date dataNascimento, dataCadastro;
    private String nivel;

    public String getNivel() {
        return nivel;
    }

    public void setNivel(String nivel) {
        this.nivel = nivel;
    }

    public Date getDataCadastro() {
        return dataCadastro;
    }

    public void setDataCadastro(Date dataCadastro) {
        this.dataCadastro = dataCadastro;
    }
    private boolean ativo;

    public Cliente() {

    }

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

    public Cliente(int id, String nome, String sobrenome, String cpf, String email,
            String celular, String estado, String genero, String cidade, String endereco,
            String cep, Date dataNascimento, boolean ativo) {
        this.id = id;
        this.nome = nome;
        this.sobrenome = sobrenome;
        this.cpf = cpf;
        this.email = email;
        this.celular = celular;
        this.estado = estado;
        this.genero = genero;
        this.cidade = cidade;
        this.endereco = endereco;
        this.cep = cep;
        this.dataNascimento = dataNascimento;
        this.ativo = ativo;
    }

    public Cliente(String nome, String sobrenome, String cpf, String email, String celular, String estado, String genero, String cidade, String endereco, String cep, Date dataNascimento, boolean ativo) {
        this.nome = nome;
        this.sobrenome = sobrenome;
        this.cpf = cpf;
        this.email = email;
        this.celular = celular;
        this.estado = estado;
        this.genero = genero;
        this.cidade = cidade;
        this.endereco = endereco;
        this.cep = cep;
        this.dataNascimento = dataNascimento;
        this.ativo = ativo;
    }

    public Date getDataNascimento() {
        return dataNascimento;
    }

    public void setDataNascimento(Date dataNascimento) {
        this.dataNascimento = dataNascimento;
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSobrenome() {
        return sobrenome;
    }

    public void setSobrenome(String sobrenome) {
        this.sobrenome = sobrenome;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCelular() {
        return celular;
    }

    public void setCelular(String celular) {
        this.celular = celular;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getGenero() {
        return genero;
    }

    public void setGenero(String genero) {
        this.genero = genero;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public boolean getAtivo() {
        return ativo;
    }

    public void setAtivo(boolean ativo) {
        this.ativo = ativo;
    }

}


text:
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.Data.Entity.Spatial

<Table("MemberRelationship")>
Partial Public Class MemberRelationship
    <Key>
    <Column(Order:=0)>
    Public Property MemberID As Guid

    <Key>
    <Column(Order:=1)>
    Public Property RelatedMemberID As Guid

    <Required>
    <StringLength(30)>
    Public Property RelationType As String

    Public Overridable Property Member As Member

    Public Overridable Property RelatedMember As Member
End Class


text:
describe("chorus.pages.GnipDataSourceShowPage", function() {
    beforeEach(function() {
        this.model = backboneFixtures.gnipDataSource({name: "gnip"});
        this.page = new chorus.pages.GnipDataSourceShowPage(this.model.id);
    });

    context('after the data source has loaded successfully', function() {
        beforeEach(function() {
            this.server.completeFetchFor(this.model);
            this.page.render();
        });

        it("displays the breadcrumbs", function() {
            expect(this.page.$(".breadcrumb:eq(0) a").attr("href")).toBe("#/");
            expect(this.page.$(".breadcrumb:eq(0)").text().trim()).toBe(t("breadcrumbs.home"));

            expect(this.page.$(".breadcrumb:eq(1) a").attr("href")).toBe("#/data_sources");
            expect(this.page.$(".breadcrumb:eq(1)").text().trim()).toBe(t("breadcrumbs.data_sources"));

            expect(this.page.$(".breadcrumb:eq(2)").text().trim()).toBe("gnip");
        });

        it("has a title bar with an icon", function() {
            expect(this.page.$(".content_header")).toContainText("gnip");
            expect(this.page.$(".content_header img").attr("src")).toContain("/images/data_sources/icon_gnip_data_source.png");
        });

        it("has a tag box", function() {
            expect(this.page.$('.tag_box')).toExist();
        });

        it("displays the sidebar", function() {
            var sidebar = this.page.sidebar;
            expect(sidebar).toBeDefined();
            expect(sidebar).toBeA(chorus.views.DataSourceListSidebar);
            expect(sidebar.model.id).toBe(this.page.model.id);
            expect(this.page.$('.sidebar_content')).toContainText('Import Stream');
        });

        it("navigates to the data sources index page when the model is destroyed", function() {
            spyOn(chorus.router, "navigate");
            this.page.model.trigger('destroy');
            expect(chorus.router.navigate).toHaveBeenCalledWith("#/data_sources");
        });
    });
});


text:
'use strict';

/**
 * @ngdoc directive
 * @name dockstore.ui.directive:stargazers
 * @restrict AE
 * @description
 * # stargazers
 */
angular.module('dockstore.ui')
  .directive('stargazers', function() {
    return {
      restrict: 'AE',
      //controller: 'StargazersCtrl',
      scope: {
        workflowObj: '=',
        containerObj: '=',
        starGazers: '='
      },

      link: function postLink(scope, element, attrs) {},
      templateUrl: 'templates/stargazers.html'
    };
  });


text:
<?php
namespace detectr\Tests\Mock {
    use observr;
    class User {
        use observr\Subject;
    }
}


text:
#ifndef NUBOT_GAZEBO_HH
#define NUBOT_GAZEBO_HH

#include <boost/bind.hpp>
#include <gazebo/gazebo.hh>             // the core gazebo header files, including gazebo/math/gzmath.hh
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>
// #include <gazebo/transport/TransportTypes.hh>
#include <gazebo/common/Plugin.hh>
#include <gazebo/common/Events.hh>
#include <sdf/sdf.hh>

#include <ros/callback_queue.h>         // Custom Callback Queue
#include <ros/subscribe_options.h>
#include <gazebo_msgs/ModelStates.h>
#include <gazebo_msgs/ModelState.h>
#include "nubot_common/OminiVisionInfo.h"
#include "nubot_common/VelCmd.h"
#include "nubot_common/Shoot.h"
#include "nubot_common/BallHandle.h"
#include <std_msgs/Float64MultiArray.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Twist.h>

#include <ros/ros.h>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <string>

#include "nubot/core/core.hpp"

#include <nubot_gazebo/NubotGazeboConfig.h>
#include <dynamic_reconfigure/server.h>

enum nubot_state
{
    CHASE_BALL,
    DRIBBLE_BALL,
    KICK_BALL,
    RESET
};

enum nubot_substate
{
    MOVE_BALL,
    ROTATE_BALL
};

namespace gazebo{
   struct Pose
   {
       math::Vector3    position;
       math::Quaternion orient;
   };
   struct Twist
   {
       math::Vector3    linear;
       math::Vector3    angular;
   };

   struct model_state
   {
       std::string model_name;
       Pose        pose;
       Twist       twist;
       std::string reference_frame;
   };                                       // similar to the type gazebo_msgs::ModelState;
                                            // use these structs for easy handling of model states.
   struct Obstacles
   {
       std::vector<nubot::PPoint> real_obs_;
       std::vector<nubot::DPoint> world_obs_;
   };

  class NubotGazebo : public ModelPlugin
  {
    private:

        physics::WorldPtr           world_;             // A pointer to the gazebo world.
        physics::ModelPtr           robot_model_;       // Pointer to the model
        physics::ModelPtr           ball_model_;    // Pointer to the football
        physics::LinkPtr            ball_link_;     //Pointer to the football link

        ros::NodeHandle*            rosnode_;           // A pointer to the ROS node.
        ros::Subscriber             ModelStates_sub_;
        ros::Subscriber             Velcmd_sub_;
        ros::Publisher              omin_vision_pub_;      /* four publishers cooresponding to those in world_model.cpp */
        ros::Publisher              debug_pub_;
        ros::ServiceServer          ballhandle_server_;
        ros::ServiceServer          shoot_server_;

        boost::thread               message_callback_queue_thread_;     // Thead object for the running callback Thread.
        boost::thread               service_callback_queue_thread_;
        boost::mutex                msgCB_lock_;        // A mutex to lock access to fields that are used in ROS message callbacks
        boost::mutex                srvCB_lock_;        // A mutex to lock access to fields that are used in ROS service callbacks
        ros::CallbackQueue          message_queue_;     // Custom Callback Queue. Details see http://wiki.ros.org/roscpp/Overview/Callbacks%20and%20Spinning
        ros::CallbackQueue          service_queue_;     // Custom Callback Queue
        event::ConnectionPtr        update_connection_;         // Pointer to the update event connection

        gazebo_msgs::ModelStates    model_states_;          // Container for the ModelStates msg
        model_state                 robot_state_;
        model_state                 ball_state_;
        nubot_common::BallInfo        ball_info_;
        nubot_common::RobotInfo       teamate_info_;
        nubot_common::ObstaclesInfo   obstacles_info_;
        nubot_common::OminiVisionInfo omni_info_;
        //common::Time                  receive_sim_time_;
        std_msgs::Float64MultiArray   debug_msgs_;

        math::Vector3               desired_rot_vector_;
        math::Vector3               desired_trans_vector_;
        math::Vector3               nubot_ball_vec_;
        math::Vector3               kick_vector_world_;
        math::Rand                  rand_;
        std::string                 robot_namespace_;   // robot namespace. Not used yet.
        std::string                 model_name_;
        std::string                 ball_name_;
        std::string                 ball_chassis_;
        std::string                 cyan_pre_;
        std::string                 mag_pre_;
        unsigned int                ball_index_;
        unsigned int                robot_index_;

        double                      nubot_ball_vec_len_;
        double                      dribble_distance_thres_;
        double                      dribble_angle_thres_;
        double                      Vx_cmd_;
        double                      Vy_cmd_;
        double                      w_cmd_;
        double                      force_;                     //kick ball force
        double                      dribble_P_;                 // P gain
        double                      dribble_I_;                 // I gain
        double                      dribble_D_;                 // D gain
        double                      I_term_max_;                // maximum I term
        double                      I_term_min_;                // minimum I term
        double                      field_length_;
        double                      field_width_;
        double                      angle_error_degree_;
        double                      noise_scale_;               // scale of gaussian noise
        double                      noise_rate_;                // how frequent the noise generates
        int                         mode_;                      //kick ball mode
        int                         nubot_num_;

        unsigned int                model_count_;                // Number of models
        bool                        dribble_flag_;
        bool                        shot_flag_;
        bool                        ModelStatesCB_flag_;         // Indicate receiving messages
        bool                        judge_nubot_stuck_;          // decide when to judge
        bool                        is_kick_;
        bool                        flip_cord_;                 // flip the coordinate frame

        int                         AgentID_;

        nubot_state                 state_;
        nubot_substate              sub_state_;
        Obstacles                   *obs_;
        dynamic_reconfigure::Server<nubot_gazebo::NubotGazeboConfig> *reconfigureServer_;

        /// \brief ModelStates message CallBack function
        /// \param[in] _msg model_states msg shared pointer
        void model_states_CB(const gazebo_msgs::ModelStates::ConstPtr& _msg);

        /// \brief VelCmd message CallBack function
        /// \param[in] cmd VelCmd msg shared pointer
        void vel_cmd_CB(const nubot_common::VelCmd::ConstPtr& cmd);

        /// \brief Ball handling service
        /// \param[in] req ball handle service request
        /// \param[out] res ball handle service response
        bool ball_handle_control_service(nubot_common::BallHandle::Request  &req,
                                      nubot_common::BallHandle::Response &res);

        /// \brief Ball shooting service
        /// \param[in] req ball handle service request
        /// \param[out] res ball handle service response
        bool shoot_control_servive(nubot_common::Shoot::Request  &req,
                                 nubot_common::Shoot::Response &res);

        /// \brief Custom message callback queue thread
        void message_queue_thread();

        /// \brief Custom service callback queue thread
        void service_queue_thread();

        /// \brief Updating models' states
        /// \return 1: updating model info success 0: not success
        bool update_model_info(void);

        /// \brief Nubot moving fuction: rotation + translation
        /// \param[in] linear_vel_vector translation velocity 3D vector
        /// \param[in] angular_vel_vector rotation velocity 3D vector
        void nubot_locomotion(math::Vector3 linear_vel_vector, math::Vector3 angular_vel_vector);

        /// \brief Nubot dribbling ball function. The football follows nubot movement.
        void dribble_ball(void);

        /// \brief Nubot kicking ball
        /// \param[in] mode kick ball mode FLY or RUN
        /// \param[in] vel initial velocity of the ball kicked; used in RUN mode; not used in FLY mode
        void kick_ball(int mode, double vel);

        /// \brief  Get the value of flag is_hold_ball_
        /// \return 1: is holding ball 0: is not holding ball
        bool get_is_hold_ball(void);

        /// \brief Determine whether nubot stuck or not.
        /// \return 1: stuck 0: not stuck
        bool get_nubot_stuck(void);

        /// \brief Publish messages to world_model node
        void message_publish(void);

        /// \brief Robot action controlled by real-robot code. Need to connect to coach.
        void nubot_be_control(void);

        /// \brief For testing seprate functions
        void nubot_test(void);

        /// \brief Dynmaic recofigure calback function
        void config(nubot_gazebo::NubotGazeboConfig &config, uint32_t level);

        /// \brief in real world, this flag is determined by the status of power; however, in
        /// simulation, if the robot beyond the green border(carpet), it is not valid.
        /// \param[in]  x,y  x and y component of robot's position
        /// \param[out] if robot is valid, return true, otherwise return false
        bool is_robot_valid(double x, double y);

        /// \brief return a value representing real world noise. The noise complies with Normal(gaussian) distribution
        /// with mean 0 and derivation 1, that is noise~N(0,1)
        /// \param[in] scale            the magnitude of the noise is within [0, scale]
        /// \param[in] probability      the probability of generating noise, probability should be in [0,1]
        double  noise(double scale, double probability=0.01);

    public:
        /// \brief Constructor. Will be called firstly
        NubotGazebo();

        /// \brief Destructor
        virtual ~NubotGazebo();

    protected:
        /// \brief Load the controller.
        /// Required by model plugin. Will be called secondly
        void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/) ;

        /// \brief Update the controller. It is running every simulation iteration.
        /// [realtime factor] = [realtime update rate] * [max step size].
        virtual void update_child();

        /// \brief Model Reset function.
        /// Not required by model plugin. It is triggered when the world resets.
        virtual void Reset();
  };
}

#endif //! NUBOT_GAZEBO_HH


text:
<?php
/**
 * Паттерн Заместитель (Proxy)
 */

namespace Pattern;

/**
 * Интерфейс Subject, описывает интерфейс для реального объекта и его суррогата
 */
interface ISubject
{
    /**
     * Субьект говорит
     *
     * @return string
     */
    public function send();
}

/**
 * Proxy, реализует объект суррогата
 */
class Proxy implements ISubject
{
    /**
     * @var Subject
     */
    protected $realSubject;

    /**
     * Сурогат говорит
     *
     * @return string
     */
    public function send()
    {
        // Подключать реальный объект можно и в контролере.
        // Или агригировать его на этапе создания суррогата.
        // Все зависит от конечных целей.
        if ($this->realSubject == null) {
            $this->realSubject = new RealSubject();
        }

        return "<strong>" . $this->realSubject->send() . "</strong>";
    }
}

/**
 * RealSubject, реализует реальный объект
 */
class RealSubject implements ISubject
{
    /**
     * Реальный объект говорит
     *
     * @return string
     */
    public function send()
    {
        return "I'll be back!";
    }
}


text:
namespace cobalt {
namespace dom {

// The completion of a CSS Transition generates a corresponding DOM Event.
//   https://www.w3.org/TR/2013/WD-css3-transitions-20131119/#transition-events
class TransitionEvent : public web::Event {
 public:
  explicit TransitionEvent(const std::string& type)
      : Event(base::Token(type), kBubbles, kCancelable),
        property_(cssom::kNoneProperty),
        elapsed_time_(0) {}

  TransitionEvent(base::Token type, cssom::PropertyKey property,
                  float elapsed_time)
      : Event(type, kBubbles, kCancelable),
        property_(property),
        elapsed_time_(elapsed_time) {}

  // The name of the CSS property associated with the transition.
  std::string property_name() const { return GetPropertyName(property_); }

  // The amount of time the transition has been running, in seconds, when this
  // event fired. Note that this value is not affected by the value of
  // transition-delay.
  float elapsed_time() const { return elapsed_time_; }

  DEFINE_WRAPPABLE_TYPE(TransitionEvent);

 private:
  ~TransitionEvent() override {}

  cssom::PropertyKey property_;
  float elapsed_time_;
};

}  // namespace dom
}  // namespace cobalt

#endif  // COBALT_DOM_TRANSITION_EVENT_H_


text:
const path = require('path');
const babel = require('rollup-plugin-babel');
const multiEntry = require('rollup-plugin-multi-entry');
const replace = require('rollup-plugin-replace');
const {terser} = require('rollup-plugin-terser');

const pkg = require('./package.json');

const BANNER = `/*!
 Copyright 2018 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/`;

const generateBundleOpts = (file, {transpile, useNatives} = {}) => {
  const plugins = [];

  if (useNatives) {
    plugins.push({
      resolveId: (importee, importer) => {
        if (importee.includes('/shims/')) {
          return path.resolve(
              path.dirname(importer),
              importee.replace('/shims/', '/natives/'));
        }
      },
    });
  }

  if (transpile) {
    plugins.push(replace({
      'IS_CODE_TRANSPILED': JSON.stringify(true),
    }));
    plugins.push(babel({
      presets: [['env', {modules: false}]],
      plugins: ['external-helpers'],
    }));
  } else {
    plugins.push(replace({
      'IS_CODE_TRANSPILED': JSON.stringify(undefined),
    }));
  }

  const terserOpts = {
    output: {
      comments: /^!/,
    },
    compress: true,
    mangle: {
      toplevel: true,
    },
  };
  if (!transpile) {
    // Mangling properties doesn't work with the class transformations done
    // by Babel, since Babel defines class methods using their string names
    // .(passed to `Object.defineProperty()`) and strings are not minifed
    // by terser.
    terserOpts.mangle.properties = {
      regex: /^_/,
    };
  }
  plugins.push(terser(terserOpts));

  return {
    input: 'src/export.mjs',
    output: {
      file,
      format: transpile ? 'umd' : 'es',
      dir: 'dist',
      name: 'lifecycle',
      banner: `${BANNER}\n\n/*! ${file} v${pkg.version} */\n`,
      sourcemap: true,
    },
    plugins,
  };
};

module.exports = [
  generateBundleOpts('lifecycle.mjs'),
  generateBundleOpts('lifecycle.native.mjs', {useNatives: true}),
  generateBundleOpts('lifecycle.es5.js', {transpile: true}),

  {
    input: 'test/*-test.mjs',
    output: {
      file: 'test-bundle.js',
      format: 'iife',
      dir: 'test',
    },
    plugins: [
      multiEntry(),
      babel({
        presets: [['env', {modules: false}]],
        plugins: ['external-helpers'],
      }),
    ],
    watch: {
      include: ['src/**/*.mjs', 'test/**/*.mjs'],
    },
  },
];