text:
This is a _Requirements Management Tool_. The idea is that you can work in teams (projects) and add requirements to this project.

There are many things to improve/add/change:

* Change to HStore.

* Support for Use cases.

* Support for Test cases.

* A better design.

There's a version running (production) at http://recuariments.us

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Association;

use ActiveCollab\DatabaseStructure\Association\ProgramToInterfaceInterface\Implementation as ProgramToInterfaceInterfaceImplementation;
use ActiveCollab\DatabaseStructure\Association\RequiredInterface\Implementation as RequiredInterfaceImplementation;
use ActiveCollab\DatabaseStructure\AssociationInterface;
use ActiveCollab\DatabaseStructure\AssociationInterface\Implementation as AssociationInterfaceImplementation;
use ActiveCollab\DatabaseStructure\Field\Composite\ForeignKeyField;
use ActiveCollab\DatabaseStructure\Index;
use ActiveCollab\DatabaseStructure\ProtectSetterInterface;
use ActiveCollab\DatabaseStructure\ProtectSetterInterface\Implementation as ProtectSetterInterfaceImplementation;
use ActiveCollab\DatabaseStructure\StructureInterface;
use ActiveCollab\DatabaseStructure\TypeInterface;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use InvalidArgumentException;

class HasOneAssociation extends Association implements
    AssociationInterface,
    InjectFieldsInsterface,
    InjectIndexesInsterface,
    ProgramToInterfaceInterface,
    ProtectSetterInterface,
    RequiredInterface
{
    use
        AssociationInterfaceImplementation,
        ProgramToInterfaceInterfaceImplementation,
        ProtectSetterInterfaceImplementation,
        RequiredInterfaceImplementation;

    /**
     * @param string $name
     * @param string $target_type_name
     */
    public function __construct($name, $target_type_name = null)
    {
        if (empty($name)) {
            throw new InvalidArgumentException("Value '$name' is not a valid association name");
        }

        if (empty($target_type_name)) {
            $target_type_name = $this->getInflector()->pluralize($name);
        }

        $this->name = $name;
        $this->target_type_name = $target_type_name;
    }

    public function getFields(): array
    {
        return [
            (new ForeignKeyField($this->getFieldName()))
                ->required($this->isRequired()),
        ];
    }

    public function getIndexes(): array
    {
        return [new Index($this->getFieldName())];
    }

    /**
     * Return field name.
     *
     * @return string
     */
    public function getFieldName()
    {
        return $this->getName() . '_id';
    }

    /**
     * Return association name.
     *
     * @return string
     */
    public function getConstraintName()
    {
        return 'has_one_' . md5($this->getVerboseConstraintName());
    }

    /**
     * Return verbose constraint name.
     *
     * @return string
     */
    public function getVerboseConstraintName()
    {
        return $this->getInflector()->singularize($this->getSourceTypeName()) . '_' . $this->getName() . '_constraint';
    }

    public function getAttributes(): array
    {
        return [$this->getName()];
    }

    public function buildAssociatedEntitiesManagerConstructionLine(
        StructureInterface $structure,
        TypeInterface $source_type,
        TypeInterface $target_type,
        string $indent,
        array &$result
    )
    {
    }

    public function buildClassPropertiesAndMethods(
        StructureInterface $structure,
        TypeInterface $source_type,
        TypeInterface $target_type,
        array &$result
    )
    {
        $namespace = $structure->getNamespace();

        if ($namespace) {
            $namespace = '\\' . ltrim($namespace, '\\');
        }

        $inflector = $this->getInflector();

        $target_instance_class = $namespace . '\\' . $inflector->classify($inflector->singularize($target_type->getName()));

        $returns_and_accepts = $target_instance_class;
        if ($this->getAccepts()) {
            $returns_and_accepts = '\\' . ltrim($this->getAccepts(), '\\');
        }

        $classified_association_name = $inflector->classify($this->getName());

        $getter_name = "get{$classified_association_name}";
        $setter_name = "set{$classified_association_name}";
        $fk_getter_name = "get{$classified_association_name}Id";
        $fk_setter_name = "set{$classified_association_name}Id";

        $inflector = $this->getInflector();

        $result[] = '';
        $result[] = '    /**';
        $result[] = '     * Return ' . $inflector->singularize($source_type->getName()) . ' ' . $this->getName() . '.';
        $result[] = '     *';
        $result[] = '     * @return ' . $returns_and_accepts . ($this->isRequired() ? '' : '|null');
        $result[] = '     */';
        $result[] = '    public function ' . $getter_name . '(): ' . ($this->isRequired() ? '' : '?') . $returns_and_accepts;
        $result[] = '    {';

        if ($this->isRequired()) {
            $result[] = '        return $this->pool->getById(' . var_export($target_instance_class, true) . ', $this->' . $fk_getter_name . '());';
        } else {
            $result[] = '        return $this->' . $fk_getter_name . '() ?';
            $result[] = '            $this->pool->getById(' . var_export($target_instance_class, true) . ', $this->' . $fk_getter_name . '()) :';
            $result[] = '            null;';
        }

        $result[] = '    }';

        $setter_access_level = $this->getProtectSetter() ? 'protected' : 'public';

        $result[] = '';
        $result[] = '    /**';
        $result[] = '     * Set ' . $inflector->singularize($source_type->getName()) . ' ' . $this->getName() . '.';
        $result[] = '     *';
        $result[] = '     * @param  ' . $returns_and_accepts . ($this->isRequired() ? '' : '|null') . ' $value';
        $result[] = '     * @return $this';
        $result[] = '     */';
        $result[] = '    ' . $setter_access_level . ' function &' . $setter_name . '(' . $returns_and_accepts . ' $value' . ($this->isRequired() ? '' : ' = null') . ')';
        $result[] = '    {';

        if ($this->isRequired()) {
            $result[] = '        if (empty($value) || !$value->isLoaded()) {';
            $result[] = '            throw new \\InvalidArgumentException(\'Valid related instance is required\');';
            $result[] = '        }';
            $result[] = '';
            $result[] = '        $this->' . $fk_setter_name . '($value->getId());';
            $result[] = '';
            $result[] = '        return $this;';
        } else {
            $result[] = '        if (empty($value)) {';
            $result[] = '            $this->' . $fk_setter_name . '(0);';
            $result[] = '        } else {';
            $result[] = '            $this->' . $fk_setter_name . '($value->getId());';
            $result[] = '        }';
            $result[] = '';
            $result[] = '        return $this;';
        }

        $result[] = '    }';
    }

    private ?Inflector $inflector = null;

    private function getInflector(): Inflector
    {
        if ($this->inflector === null) {
            $this->inflector = InflectorFactory::create()->build();
        }

        return $this->inflector;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Galathea Rep. 12: 28.

#### Original name
null

### Remarks
null


text:
package dokan

import (
	"reflect"
	"unsafe"
)

// bufToSlice returns a byte slice aliasing the pointer and length given as arguments.
func bufToSlice(ptr unsafe.Pointer, nbytes uint32) []byte {
	if ptr == nil || nbytes == 0 {
		return nil
	}
	return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
		Data: uintptr(ptr),
		Len:  int(nbytes),
		Cap:  int(nbytes)}))
}


text:
'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var types = 'phone tablet laptop camera software book misc'.split(' ');
var locations = 'Raleigh Chicago'.split(' ');
var locationIds = [697673324, 409625272];
var statuses = 'available in_use missing retired'.split(' ');
var OSnames = 'Android iOS Windows WatchOS FireOS OSX N/A'.split(' ');
var attrTypes = 'string array object integer'.split(' ');

/**
 * Asset Schema
 */
var Location = {
    name: {
        type: String,
        enum: locations,
        default: locations[0],
        required: true
    },
    id: {
        type: Number,
        enum: locationIds,
        default: locationIds[0],
        required: true
    }
};

var OS = {
    name: {
        type: String,
        enum: OSnames,
        required: true
    },
    version: {
        type: String,
        required: true
    }
};

var Categories = {
    type: {
        type: String,
        trim: true,
        required: true,
        enum: types,
        default: types[0],
        index: true
    },
    os: OS
};
var Attribute = {
    type: {
        type: String,
        trim: true,
        required: true,
        enum: attrTypes,
        default: attrTypes[0]
    },
    key: {
        type: String,
        trim: true,
        required: true,
        default: 'Fill this in'
    },
    value: {} //must markmodified when changed
};

var AssetSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        default: '',
        max: 50
    },
    description: {
        type: String,
        trim: true,
        max: 140,
        default: ''
    },
    image: { //images should be base64 encoded
        type: String,
        default: ''
    },
    location: Location,
    categories: Categories,
    attributes: [Attribute],
    status: {
        type: String,
        enum: statuses,
        default: statuses[0],
        required: true,
        index: true
    },
    created: {
        type: Date,
        default: Date.now,
        required: true
    },
    updated: {
        type: Date,
        required: true,
        default: Date.now
    }
});

AssetSchema.pre('save', function(next) {
    if (!this.isModified('updated')) {
        this.updated = new Date();
    }
    this.markModified('attributes');

    next();
});

AssetSchema.static('findByType', function(type, callback) {
    return this.find({
        type: new RegExp(type, 'i')
    }, callback);
});

AssetSchema.static('findAvailableByType', function(type, callback) {
    return this.find({
        $and: [{
            type: new RegExp(type, 'i')
        }, {
            status: 'available'
        }]
    }, callback);
});

AssetSchema.static('findInUse', function(assetID, callback) {
    return this.find({
        $and: [{
            _id: assetID
        }, {
            status: 'in_use'
        }]
    }, callback);
});

mongoose.model('Asset', AssetSchema);


text:
db.getCollection('drugbank').ensureIndex({'type': 1})
db.getCollection('drugbank').ensureIndex({'action': 1})
db.getCollection('drugbank').ensureIndex({'drug.xrefs.id': 1})
db.getCollection('drugbank').ensureIndex({'drug.type': 1})
db.getCollection('drugbank').ensureIndex({'drug.group': 1})
db.getCollection('drugbank').ensureIndex({'drug.category': 1})
db.getCollection('drugbank').ensureIndex({'partner.xrefs.id': 1})
db.getCollection('drugbank').ensureIndex({'partner.essentiality': 1})


text:
package org.apache.directory.server.bridge.http;

import org.apache.directory.api.ldap.model.message.BindResponse;
import org.apache.directory.ldap.client.api.LdapConnection;

/**
 * A holder class for holding LdapConnection and BindResponse object.
 *
 * @author Apache Directory Project
 */
public class BindResponseHolder
{
    /** the ldap connection */
    private LdapConnection connection;

    /** the bind response */
    private BindResponse response;

    public BindResponseHolder( BindResponse response, LdapConnection connection )
    {
        this.response = response;
        this.connection = connection;
    }

    public LdapConnection getConnection()
    {
        return connection;
    }

    public BindResponse getResponse()
    {
        return response;
    }

}


text:
package pl.rafalmag.ev3;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AtomicWrappingCounterTest {

	@Test
	public void should_increment_mod3() {
		// given
		AtomicWrappingCounter atomicWrappingCounter = new AtomicWrappingCounter(
				0, 3);

		// when + then
		assertEquals(atomicWrappingCounter.incrementAndGet(), 1);
		assertEquals(atomicWrappingCounter.incrementAndGet(), 2);
		assertEquals(atomicWrappingCounter.incrementAndGet(), 0);
		assertEquals(atomicWrappingCounter.incrementAndGet(), 1);
	}
}


text:
import path from 'path';
import webpack  from 'webpack';

let JS_REGEX = /\.js$|\.jsx$|\.es6$|\.babel$/;
let rootPath = path.normalize(__dirname + '../../');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-hot-middleware/client',
    './app/index'
  ],
  output: {
    path: path.join(rootPath, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    preLoaders: [
      {
        test: JS_REGEX,
        exclude: /node_modules/,
        loader: 'eslint'
      }
    ],
    loaders: [{
      test: JS_REGEX,
      loaders: ['babel'],
      include: path.join(rootPath, 'app')
    },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
        exclude: /node_modules/
      }
    ]
  },
  eslint: {
    configFile: '.eslintrc'
  },
  // for koa middleware
  devServer: {
    host: process.env.USER_IP || 'localhost',
    port: 3000,
    publicPath: '/',        // Where webpack exposes bundles
                            //  on its own in-memory file system
    hot: true,              // Switch on Hot Module Replacement
    indexEntry: 'index',    // Entry to add HNR code to (EntryChunk or CommonsChunk)
    secure: true,           // use https or http
    stats: {
      colors: true,
      hash: false,
      timings: false,
      assets: true,
      chunks: true,
      chunkModules: true,
      modules: false,
      children: true
    }
  }
};


text:
package org.broadinstitute.sting.gatk.walkers.annotator.interfaces;

public interface StandardAnnotation extends AnnotationType {}


text:
int SampleProbability(const double& probability);

#endif


text:
package co.steeleye.sdk.util;

import com.google.common.collect.ImmutableMap;
import lombok.Data;
import org.testng.annotations.Test;

import static org.testng.Assert.*;

public class ReflectionUtilTest extends ReflectionUtil {

    @Test
    public void testSafeForName() throws Exception {
        assertEquals(safeForName(null), null);
        assertEquals(safeForName("io.pgmodel.DoesNotExist"), null);
        assertEquals(safeForName("co.steeleye.sdk.util.ReflectionUtilTest$MyInner"), MyInner.class);
    }

    @Test
    public void testCreate() throws Exception {
        assertEquals(create(MyInner.class), new MyInner(null, 0));
        assertEquals(create(MyEmptyConstructor.class), new MyEmptyConstructor());
    }

    @Test(expectedExceptions = InstantiationException.class)
    public void testCreateFail() { create(MyAbsConstructor.class); }

    @Test
    public void testAsEnum() throws Exception {
        assertEquals(asEnum(MyInner.class, "STRING"), "STRING");
    }

    @Test
    public void testIsEnum() throws Exception {
        assertFalse(isEnum(MyInner.class));
        assertTrue(isEnum(Thread.State.class));
    }

    @Test
    public void testIsAssignable() throws Exception {
        assertFalse(isAssignable(MyInner.class, null));
        assertFalse(isAssignable(MyChild.class, MyInner.class));
        assertTrue(isAssignable(MyInner.class, MyChild.class));
    }

    @Test
    public void testDeclaredField() throws Exception {
        assertNotNull(declaredField(MyChild.class, "value"));
        assertNull(declaredField(MyChild.class, "foo"));
    }

    @Test
    public void testGetFieldValue() throws Exception {
        assertEquals(fieldValue(new MyInner("hi", 3), "value"), "hi");
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testGetFieldValueFail() throws Exception {
        fieldValue(new MyInner("hi", 3), "boo");
    }

    @Test
    public void testSetFieldValue() throws Exception {
        assertEquals(fieldValue(new MyInner("hi", 3), "value", "hello"), new MyInner("hello", 3));
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testSetFieldValueFail() throws Exception {
        fieldValue(new MyInner("hi", 3), "boo", "boo");
    }

    @Test
    public void testFieldValues() throws Exception {
        assertEquals(fieldValues(new MyInner("hi", 3)), ImmutableMap.of("value", "hi"));
        assertEquals(fieldValues(new MyInner(null, 3)), ImmutableMap.of());
    }

    @Test
    public void testInvoke() throws Exception {
        assertNull(safeInvoke(null, null));
        safeInvoke(new InvokeHelper(), "handleNoResult", (Object) "hello".getBytes());
        assertEquals(safeInvoke(new InvokeHelper(), "handleEmpty"), "hello");
        assertEquals(safeInvoke(new InvokeHelper(), "handle", (Object) "hello".getBytes()), "hello");
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void testInvokeFail() throws Exception {
        safeInvoke(new InvokeHelper(), "handleNotFound");
    }

    @Data
    static class MyInner {
        private final static int STA = 5;
        private final String value;
        private final transient int none;
        private volatile boolean vol = false;
    }

    public static class MyChild extends MyInner {
        public MyChild(String value, int none) { super(value, none); }
    }

    @Data
    private static class MyEmptyConstructor {
    }

    private abstract class MyAbsConstructor {
    }

    @SuppressWarnings({"unused", "WeakerAccess"})
    static class InvokeHelper {
        public void handleNoResult(byte[] message) { assertEquals("hello", handle(message)); }

        public String handleEmpty() { return "hello"; }

        public String handle(byte[] message) { return new String(message); }
    }
}


text:
.. _guide-graphql-eslint:

Setting up Eslint for Graphql and Apollo Client
===============================================

.. image:: ../../../img/platform/manual/guides/eslint.gif

Install the eslint plugin by running the following in the same directory as your ``package.json`` file.

.. code-block:: bash

  $ npm install --save-dev eslint-plugin-graphql

Next, we need to fetch the graphql schema

.. code-block:: Bash

   $ curl -H 'Authorization: Bearer <auth-token>' 'https://data.<cluster-name>.hasura-app.io/v1alpha1/graphql/schema' | jq -r '.schema' > schema.graphql

Now that you have the GraphQL schema, you can generate ``schema.json`` as follows:

.. code-block:: Bash

   $ npm install -g apollo-codegen
   $ apollo-codegen introspect-schema schema.graphql --output schema.json

The above command will save a ``schema.json`` file in your current directory.

Next, create a file named ``.eslintrc.js`` in the directory with your ``package.json`` file

.. code-block:: javascript

  module.exports = {
    parser: "babel-eslint",
    rules: {
      "graphql/template-strings": ['error', {
        env: 'apollo',

        // Import your schema JSON here
        schemaJson: require('./schema.json'),
      }]
    },
    plugins: [
      'graphql'
    ]
  }

To know about the other rules that you can apply, check out the repository `here <https://github.com/apollographql/eslint-plugin-graphql>`_.


text:
// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: mphoward

#include "hoomd/mpcd/SlitGeometryFiller.h"
#ifdef ENABLE_HIP
#include "hoomd/mpcd/SlitGeometryFillerGPU.h"
#endif // ENABLE_HIP

#include "hoomd/SnapshotSystemData.h"
#include "hoomd/test/upp11_config.h"

HOOMD_UP_MAIN()

template<class F> void slit_fill_basic_test(std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
    std::shared_ptr<SnapshotSystemData<Scalar>> snap(new SnapshotSystemData<Scalar>());
    snap->global_box = BoxDim(20.0);
    snap->particle_data.type_mapping.push_back("A");
    std::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(snap, exec_conf));

    auto mpcd_sys_snap = std::make_shared<mpcd::SystemDataSnapshot>(sysdef);
        {
        std::shared_ptr<mpcd::ParticleDataSnapshot> mpcd_snap = mpcd_sys_snap->particles;
        mpcd_snap->resize(1);

        mpcd_snap->position[0] = vec3<Scalar>(1, -2, 3);
        mpcd_snap->velocity[0] = vec3<Scalar>(123, 456, 789);
        }
    auto mpcd_sys = std::make_shared<mpcd::SystemData>(mpcd_sys_snap);
    auto pdata = mpcd_sys->getParticleData();
    mpcd_sys->getCellList()->setCellSize(2.0);
    UP_ASSERT_EQUAL(pdata->getNVirtual(), 0);

    // create slit channel with half width 5
    auto slit = std::make_shared<const mpcd::detail::SlitGeometry>(5.0,
                                                                   1.0,
                                                                   mpcd::detail::boundary::no_slip);
    std::shared_ptr<::Variant> kT = std::make_shared<::VariantConstant>(1.5);
    std::shared_ptr<mpcd::SlitGeometryFiller> filler
        = std::make_shared<F>(mpcd_sys, 2.0, 1, kT, slit);

    /*
     * Test basic filling up for this cell list
     */
    filler->fill(0);
    // volume to fill is from 5->7 (2) on + side, with cross section of 20^2, mirrored on bottom
    UP_ASSERT_EQUAL(pdata->getNVirtual(), 2 * (2 * 20 * 20) * 2);
    // count that particles have been placed on the right sides
        {
        ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::read);
        ArrayHandle<Scalar4> h_vel(pdata->getVelocities(),
                                   access_location::host,
                                   access_mode::read);
        ArrayHandle<unsigned int> h_tag(pdata->getTags(), access_location::host, access_mode::read);

        // ensure first particle did not get overwritten
        CHECK_CLOSE(h_pos.data[0].x, 1, tol_small);
        CHECK_CLOSE(h_pos.data[0].y, -2, tol_small);
        CHECK_CLOSE(h_pos.data[0].z, 3, tol_small);
        CHECK_CLOSE(h_vel.data[0].x, 123, tol_small);
        CHECK_CLOSE(h_vel.data[0].y, 456, tol_small);
        CHECK_CLOSE(h_vel.data[0].z, 789, tol_small);
        UP_ASSERT_EQUAL(h_tag.data[0], 0);

        unsigned int N_lo(0), N_hi(0);
        for (unsigned int i = pdata->getN(); i < pdata->getN() + pdata->getNVirtual(); ++i)
            {
            // tag should equal index on one rank with one filler
            UP_ASSERT_EQUAL(h_tag.data[i], i);
            // type should be set
            UP_ASSERT_EQUAL(__scalar_as_int(h_pos.data[i].w), 1);

            const Scalar z = h_pos.data[i].z;
            if (z < Scalar(-5.0))
                ++N_lo;
            else if (z >= Scalar(5.0))
                ++N_hi;
            }
        UP_ASSERT_EQUAL(N_lo, 2 * (2 * 20 * 20));
        UP_ASSERT_EQUAL(N_hi, 2 * (2 * 20 * 20));
        }

    /*
     * Fill the volume again, which should double the number of virtual particles
     */
    filler->fill(1);
    UP_ASSERT_EQUAL(pdata->getNVirtual(), 2 * 2 * (2 * 20 * 20) * 2);
    // count that particles have been placed on the right sides
        {
        ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::read);
        ArrayHandle<Scalar4> h_vel(pdata->getVelocities(),
                                   access_location::host,
                                   access_mode::read);
        ArrayHandle<unsigned int> h_tag(pdata->getTags(), access_location::host, access_mode::read);

        unsigned int N_lo(0), N_hi(0);
        for (unsigned int i = pdata->getN(); i < pdata->getN() + pdata->getNVirtual(); ++i)
            {
            // tag should equal index on one rank with one filler
            UP_ASSERT_EQUAL(h_tag.data[i], i);

            const Scalar z = h_pos.data[i].z;
            if (z < Scalar(-5.0))
                ++N_lo;
            else if (z >= Scalar(5.0))
                ++N_hi;
            }
        UP_ASSERT_EQUAL(N_lo, 2 * 2 * (2 * 20 * 20));
        UP_ASSERT_EQUAL(N_hi, 2 * 2 * (2 * 20 * 20));
        }

    /*
     * Change the cell size so that we lie exactly on a boundary.
     */
    pdata->removeVirtualParticles();
    mpcd_sys->getCellList()->setCellSize(1.0);
    filler->fill(2);
    // volume to fill is now from 5->5.5 on + side, same other parameters
    UP_ASSERT_EQUAL(pdata->getNVirtual(), 2 * (20 * 20 / 2) * 2);
    // count that particles have been placed on the right sides
        {
        ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::read);
        unsigned int N_lo(0), N_hi(0);
        for (unsigned int i = pdata->getN(); i < pdata->getN() + pdata->getNVirtual(); ++i)
            {
            const Scalar z = h_pos.data[i].z;
            if (z < Scalar(-5.0))
                ++N_lo;
            else if (z >= Scalar(5.0))
                ++N_hi;
            }
        UP_ASSERT_EQUAL(N_lo, 2 * (20 * 20 / 2));
        UP_ASSERT_EQUAL(N_hi, 2 * (20 * 20 / 2));
        }

    /*
     * Test the average properties of the virtual particles.
     */
    mpcd_sys->getCellList()->setCellSize(2.0);
    unsigned int N_lo(0), N_hi(0);
    Scalar3 v_lo = make_scalar3(0, 0, 0);
    Scalar3 v_hi = make_scalar3(0, 0, 0);
    Scalar T_avg(0);
    for (unsigned int t = 0; t < 500; ++t)
        {
        pdata->removeVirtualParticles();
        filler->fill(3 + t);

        ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::read);
        ArrayHandle<Scalar4> h_vel(pdata->getVelocities(),
                                   access_location::host,
                                   access_mode::read);

        for (unsigned int i = pdata->getN(); i < pdata->getN() + pdata->getNVirtual(); ++i)
            {
            const Scalar z = h_pos.data[i].z;
            const Scalar4 vel_cell = h_vel.data[i];
            const Scalar3 vel = make_scalar3(vel_cell.x, vel_cell.y, vel_cell.z);
            if (z < Scalar(-5.0))
                {
                v_lo += vel;
                T_avg += dot(vel - make_scalar3(-1.0, 0, 0), vel - make_scalar3(-1.0, 0, 0));
                ++N_lo;
                }
            else if (z >= Scalar(5.0))
                {
                v_hi += vel;
                T_avg += dot(vel - make_scalar3(1.0, 0, 0), vel - make_scalar3(1.0, 0, 0));
                ++N_hi;
                }
            }
        }
    // make averages
    UP_ASSERT_EQUAL(N_lo, 500 * 2 * (2 * 20 * 20));
    UP_ASSERT_EQUAL(N_hi, 500 * 2 * (2 * 20 * 20));
    v_lo /= N_lo;
    v_hi /= N_hi;
    T_avg /= (3 * (N_lo + N_hi - 1));

    CHECK_CLOSE(v_lo.x, -1.0, tol);
    CHECK_SMALL(v_lo.y, tol);
    CHECK_SMALL(v_lo.z, tol);
    CHECK_CLOSE(v_hi.x, 1.0, tol);
    CHECK_SMALL(v_hi.y, tol);
    CHECK_SMALL(v_hi.z, tol);
    CHECK_CLOSE(T_avg, 1.5, tol);
    }

UP_TEST(slit_fill_basic)
    {
    slit_fill_basic_test<mpcd::SlitGeometryFiller>(
        std::make_shared<ExecutionConfiguration>(ExecutionConfiguration::CPU));
    }
#ifdef ENABLE_HIP
UP_TEST(slit_fill_basic_gpu)
    {
    slit_fill_basic_test<mpcd::SlitGeometryFillerGPU>(
        std::make_shared<ExecutionConfiguration>(ExecutionConfiguration::GPU));
    }
#endif // ENABLE_HIP


text:
package de.tud.vcd.votedevice.municipalElection.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import de.tud.vcd.votedevice.municipalElection.model.Candidate;

/**
 * Zeichnet einen Kandidaten auf die Oberfläche. Die Größe wird dabei auch wieder variabel berechnet.
 *
 * @author Roman Jöris <roman.joeris@googlemail.com>
 *
 */
public class ShowACandiate extends JPanel {

	private static final long serialVersionUID = 1L;
	private Color foreground;
	private Color crossedColor;
	private String id;
	private int id_maxSize;
	private String name;
	private String prename;
	private boolean crossed;
	private int votes;
	private int manualVotes;
	private Font fontId;
	private Font fontName;
	private Font fontForename;
	private int maxVotes;
	private Image imgBallotChecked;
	private Image imgBallotUnchecked;
	private Image imgBallotCheckedGray;

	boolean pressed;
	private ArrayList<ActionListener> al;
	private String actionCommand;
	private JComponent comp;

	/**
	 * Erzeugt ein Zeichenobjekt
	 * @param width
	 * @param height
	 * @param foreground
	 * @param crossedColor
	 * @param maxVotes
	 */
	public ShowACandiate(int width, int height, Color foreground,Color crossedColor, int maxVotes) {
		this.foreground=foreground;
		this.crossedColor=crossedColor;
		setOpaque(false);
		setSize(width, height);
		//
		fontId= new Font("SanfSerif", Font.PLAIN,(int)(this.getSize().height*0.7) );
		fontName=new Font(fontId.getFamily(), Font.BOLD, (int)(this.getSize().height*0.577));
		fontForename=new Font(fontId.getFamily(), Font.PLAIN, (int)(this.getSize().height*0.5));

		id="0000";

		FontMetrics fm = getFontMetrics(fontId);
		id_maxSize=fm.stringWidth(id);

		name="Name";
		prename="Prename";
		crossed=false;
		votes=0;
		manualVotes=0;
		this.maxVotes=maxVotes;

		URL imageURLl =getClass().getClassLoader().getResource("ballotChecked.gif");
		imgBallotChecked=null;
		if (imageURLl != null) {
		    try {
				imgBallotChecked = ImageIO.read(imageURLl);
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}

		imageURLl =getClass().getClassLoader().getResource("ballotUnchecked.gif");
		imgBallotUnchecked=null;
		if (imageURLl != null) {
			try {
				imgBallotUnchecked = ImageIO.read(imageURLl);
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}

		imageURLl =getClass().getClassLoader().getResource("ballotCheckedGray.gif");
		imgBallotCheckedGray=null;
		if (imageURLl != null) {
			try {
				imgBallotCheckedGray = ImageIO.read(imageURLl);
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}

		al=new ArrayList<ActionListener>();
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e)
						&& contains(e.getPoint())) {
					pressed = true;
					//repaint();
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e) && pressed) {
					//call all actionPerformed:
					for(ActionListener a:al){
						a.actionPerformed(new ActionEvent(comp, ActionEvent.ACTION_PERFORMED, actionCommand));
					}

					pressed = false;
					//repaint();
				}
			}
		});

	}

	/**
	 * @param al
	 */
	public void addActionListener(ActionListener al){
		this.al.add(al);
	}

	/**
	 * @param actionCommand
	 */
	public void setActionCommand(String actionCommand){
		this.actionCommand=actionCommand;
		//.paramString=
	}

	/**
	 * @return
	 */
	public String getActionCommmand(){
		return actionCommand;
	}

	/* (non-Javadoc)
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		//Upcast --> more functions in Graphics2D
		Graphics2D g2d=(Graphics2D)g;

		// Antialiasing einschalten
		g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON );

		//g.drawString("FOO", 10, 5);
		g2d.setColor(foreground);
		g2d.drawLine(0 , this.getSize().height-1 , this.getSize().width, this.getSize().height-1);

		//print id:

		//fontId=new Font(fontId.getFamily(), Font.BOLD, fontId.getSize()-2);

		g2d.setFont(fontId);
		g2d.drawString(id, 0, this.getSize().height-5);

		g2d.setFont(fontName);

		g2d.drawString(name, id_maxSize+5, this.getSize().height-5);

		FontMetrics fm = getFontMetrics(fontName);
		int name_Size=fm.stringWidth(name);

		g2d.setFont(fontForename);

		g2d.drawString(", "+prename, id_maxSize+5+name_Size, this.getSize().height-5);

		//paint boxes
		int imgSize=(int)(this.getSize().height*0.77);	// 20/26
		int imgMarginTop=(int)(this.getSize().height*0.15); // 4/26
		int imgPlace=(int)(this.getSize().height*0.846); // (20+2)/26

		for (int i=0;i<maxVotes;i++){
			if (i<votes){
				if (manualVotes<=i){
					g2d.drawImage(imgBallotCheckedGray, this.getSize().width-(maxVotes*(imgPlace) -i*imgPlace) , imgMarginTop, imgSize, imgSize, null, null);
				}else{
					g2d.drawImage(imgBallotChecked, this.getSize().width-(maxVotes*(imgPlace) -i*imgPlace) , imgMarginTop, imgSize, imgSize, null, null);
				}
			}else{
				g2d.drawImage(imgBallotUnchecked, this.getSize().width-(maxVotes*(imgPlace) -i*imgPlace), imgMarginTop, imgSize, imgSize, null, null);
			}
		}
		if (crossed){
			g2d.setColor(crossedColor);
			g2d.drawLine(0 , this.getSize().height/2 , this.getSize().width, this.getSize().height/2);
			g2d.drawLine(0 , this.getSize().height/2+1 , this.getSize().width, this.getSize().height/2+1);
		}

	}

	/**
	 * @param c
	 */
	public void setCandidate(Candidate c) {
		if (!(c == null)) {
			id = c.getId() + "";
			actionCommand = c.getId() + "";
			name=c.getName();
			prename=c.getPrename();
			votes=c.getCountedVotes();
			manualVotes=c.getVotes();
			crossed=c.isCrossedOut();
			setVisible(true);
		} else {
			id="0";
			name="";
			prename="";
			crossed=false;
			votes=0;
			manualVotes=0;
			setVisible(false);
		}
		repaint();
	}

	/**
	 * @return
	 */
	public int getCandidateId(){
		return Integer.parseInt(this.id);
	}

}


text:
from openerp.osv import fields, osv
from openerp import tools

class MassMailingReport(osv.Model):
    _name = 'mail.statistics.report'
    _auto = False
    _description = 'Mass Mailing Statistics'

    _columns = {
        'scheduled_date': fields.datetime('Scheduled Date', readonly=True),
        'name': fields.char('Mass Mail', readonly=True),
        'campaign': fields.char('Mass Mail Campaign', readonly=True),
        'sent': fields.integer('Sent', readonly=True),
        'delivered': fields.integer('Delivered', readonly=True),
        'opened': fields.integer('Opened', readonly=True),
        'bounced': fields.integer('Bounced', readonly=True),
        'replied': fields.integer('Replied', readonly=True),
        'state': fields.selection(
            [('draft', 'Draft'), ('test', 'Tested'), ('done', 'Sent')],
            string='Status', readonly=True,
        ),
        'email_from': fields.char('From', readonly=True),
    }

    def init(self, cr):
        """Mass Mail Statistical Report: based on mail.mail.statistics that models the various
        statistics collected for each mailing, and mail.mass_mailing model that models the
        various mailing performed. """
        tools.drop_view_if_exists(cr, 'mail_statistics_report')
        cr.execute("""
            CREATE OR REPLACE VIEW mail_statistics_report AS (
                SELECT
                    min(ms.id) as id,
                    ms.scheduled as scheduled_date,
                    mm.name as name,
                    mc.name as campaign,
                    count(ms.bounced) as bounced,
                    count(ms.sent) as sent,
                    (count(ms.sent) - count(ms.bounced)) as delivered,
                    count(ms.opened) as opened,
                    count(ms.replied) as replied,
                    mm.state,
                    mm.email_from
                FROM
                    mail_mail_statistics as ms
                    left join mail_mass_mailing as mm ON (ms.mass_mailing_id=mm.id)
                    left join mail_mass_mailing_campaign as mc ON (ms.mass_mailing_campaign_id=mc.id)
                GROUP BY ms.scheduled, mm.name, mc.name, mm.state, mm.email_from
            )""")


text:
function Gallery(container, photoArray) {
    this._galleryHolder = {};
    this._fullsizeGallery = {};
    this._thumbnailCollection = [];

    //Método privado que genera eventos de click sobre la colección de thumbnails
    function associateThumbEvents() {
        var currentInstance = this;

        this._thumbnailCollection = this._galleryHolder.getElementsByClassName("thumbnail");

        for (var x = 0; x < this._thumbnailCollection.length; x++) {
            this._thumbnailCollection[x].addEventListener("click", function (event) { thumbnailClick.call(currentInstance, event); });
        }
    }

    //Método privado que comprueba si se han podido cargar las imágenes tras cinco segundos
    function checkThumbGallery(loadedImages, currentInstance) {
        console.log("No han podido cargarse " + (photoArray.length - loadedImages) + " imágenes de la galería");
        thumbnailGallery.innerHTML = tempGallery;
        associateThumbEvents.call(currentInstance);
    }

    //Método privado que define los eventos de click sobre los thumbnails
    function thumbnailClick(event) {

        var currentInstance = this; //Esta variable se utilizará para poder acceder a this dentro de los listeners.

        function loadImageLayer(image, imageClass) {
            var thisPhoto = document.createElement("img");
            thisPhoto.setAttribute("src", image.src);
            thisPhoto.setAttribute("class", imageClass);
            if (thisPhoto.height > 600 || thisPhoto.width > 800) {
                thisPhoto.setAttribute("height", 600);
                thisPhoto.setAttribute("width", 800);
            }
            this._fullsizeGallery.appendChild(thisPhoto);
            return thisPhoto;
        }

        function repositionButtons(image) {
            var wDisplacement = (image.width + 50) / 2;
            var hDisplacement = 90 + ((image.height) / 2);
            previousButton.setAttribute("style", "top:" + hDisplacement + "px; left:-" + wDisplacement + "px;");
            nextButton.setAttribute("style", "top:" + hDisplacement + "px; left:" + wDisplacement + "px;");
        }

        //Se carga la foto sobre la que se hace click en la galería de tamaño completo, así como las fotos previa y siguiente
        var currentImage = event.target;
        var previousImage = (currentImage.previousElementSibling != null) ? currentImage.previousElementSibling
            : this._thumbnailCollection[this._thumbnailCollection.length - 1];
        var nextImage = (currentImage.nextElementSibling != null) ? currentImage.nextElementSibling : this._thumbnailCollection[0];

        var previousPhoto = loadImageLayer.call(this, previousImage, "previousPhoto");
        var currentPhoto = loadImageLayer.call(this, currentImage, "currentPhoto");
        var nextPhoto = loadImageLayer.call(this, nextImage, "nextPhoto");

        //Se añaden botones para moverse por la galería
        var previousButton = document.createElement("div");
        var nextButton = document.createElement("div");
        previousButton.setAttribute("class", "galleryButton fa fa-chevron-circle-left");
        nextButton.setAttribute("class", "galleryButton fa fa-chevron-circle-right");
        repositionButtons(currentPhoto);

        this._fullsizeGallery.appendChild(previousButton);
        this._fullsizeGallery.appendChild(nextButton);

        //Se hace visible la capa modal de la galería de tamaño completo
        this._fullsizeGallery.style.display = "block";

        //Se añade evento para cerrar la galería cuando se hace click en la capa superior
        this._fullsizeGallery.addEventListener("click", function (event) {
            currentInstance._fullsizeGallery.style.display = "none";
            currentInstance._fullsizeGallery.innerHTML = "";
        });

        //Y otro evento sobre la propia imagen para evitar que el click sobre ella dispare el click superior en la capa y no se cierre
        currentPhoto.addEventListener("click", function (event) { event.cancelBubble = true; });

        //Y los eventos de imagen adelante e imagen atrás.
        previousButton.addEventListener("click", function (event) {
            var newImage = previousImage;
            previousImage = (newImage.previousElementSibling != null) ? newImage.previousElementSibling
                : currentInstance._thumbnailCollection[currentInstance._thumbnailCollection.length - 1];
            nextImage = (newImage.nextElementSibling != null) ? newImage.nextElementSibling : currentInstance._thumbnailCollection[0];
            event.cancelBubble = true;
            repositionButtons(previousPhoto);
            currentPhoto.style.left = "1025px";
            currentPhoto.style.opacity = 0;
            previousPhoto.style.left = 0;
            previousPhoto.style.opacity = 1;
            currentInstance._fullsizeGallery.removeChild(nextPhoto);
            nextPhoto = currentPhoto;
            nextPhoto.setAttribute("class", "nextPhoto");
            currentPhoto = previousPhoto;
            currentPhoto.setAttribute("class", "currentPhoto");
            currentPhoto.addEventListener("click", function (event) { event.cancelBubble = true; });
            previousPhoto = loadImageLayer.call(currentInstance, previousImage, "previousPhoto");
        });

        nextButton.addEventListener("click", function (event) {
            var newImage = nextImage;
            nextImage = (newImage.nextElementSibling != null) ? newImage.nextElementSibling : currentInstance._thumbnailCollection[0];
            previousImage = (newImage.previousElementSibling != null) ? newImage.previousElementSibling
                : currentInstance._thumbnailCollection[currentInstance._thumbnailCollection.length - 1];
            event.cancelBubble = true;
            repositionButtons(nextPhoto);
            currentPhoto.style.left = "-1600px";
            currentPhoto.style.opacity = 0;
            nextPhoto.style.left = 0;
            nextPhoto.style.opacity = 1;
            currentInstance._fullsizeGallery.removeChild(previousPhoto);
            previousPhoto = currentPhoto;
            previousPhoto.setAttribute("class", "previousPhoto");
            currentPhoto = nextPhoto;
            currentPhoto.setAttribute("class", "currentPhoto");
            currentPhoto.addEventListener("click", function (event) { event.cancelBubble = true; });
            nextPhoto = loadImageLayer.call(currentInstance, nextImage, "nextPhoto");
        });
    }

    //Creación de la galería de thumbnails
    var thumbnailGallery = document.createElement("div");
    thumbnailGallery.setAttribute("class", "thumbnailGallery");
    this._galleryHolder = document.getElementById(container);
    this._galleryHolder.appendChild(thumbnailGallery);
    thumbnailGallery.innerHTML = "

 Gallery loading...
"

    if (photoArray.length == 0) {
        thumbnailGallery.innerHTML = "
No hay imágenes asociadas
";
    } else {
        var loadedImages = 0;
        var tempGallery = "";
        var currentThumbnail = [];
        var currentInstance = this;
        var timeout = setTimeout(function () { checkThumbGallery(loadedImages, currentInstance); }, 5000);
        for (var image in photoArray) {
            currentThumbnail[image] = new Image();
            currentThumbnail[image].onload = function () {
                loadedImages++;
                tempGallery += "";
                if (loadedImages >= photoArray.length) {
                    //Una vez cargadas todas las imágenes mostrar la galería y asociar eventos de click a los thumbnails
                    thumbnailGallery.innerHTML = tempGallery;
                    associateThumbEvents.call(currentInstance);
                    window.clearTimeout(timeout); //Si se dispara el evento que carga las imágenes se elimina el check a los 5 segundos.
                }
            }
            currentThumbnail[image].src = photoArray[image];
        }
    }

    //Creación del objeto que contendrá la galería en tamaño grande
    this._fullsizeGallery = document.createElement("div");
    this._fullsizeGallery.setAttribute("id", "fullsizeGallery");
    document.body.appendChild(this._fullsizeGallery);
}


text:
package fi.aalto.trafficsense.regularroutes.backend;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import edu.mit.media.funf.FunfManager;
import fi.aalto.trafficsense.regularroutes.util.LocalBinder;
import fi.aalto.trafficsense.regularroutes.util.LocalServiceConnection;
import timber.log.Timber;

public class BackendService extends Service {

    private static final String FUNF_PIPELINE_NAME = "default";

    /* Private Members */
    private boolean isRunning = false;

    private final IBinder mBinder = new LocalBinder<BackendService>(this);
    private FunfManager mFunfManager;
    private final ServiceConnection mFunfServiceConnection = new LocalServiceConnection<FunfManager>() {

        @Override
        protected FunfManager getService(IBinder binder) {
            return ((FunfManager.LocalBinder) binder).getManager();
        }

        @Override
        protected void onService(FunfManager service) {
            mFunfManager = service;
            onFunfReady();

            Timber.d("funf ready");
        }
    };

    /* Overridden Methods */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.isRunning = true;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startAndBindFunfService();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        setRunning(false);
    }

    /* Getters and Setters */
    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        if (this.isRunning != isRunning) {
            if (isRunning) {
                startAndBindFunfService();
                startService(new Intent(BackendService.this, BackendService.class));
                Timber.d("BackgroundService: Started self");
            } else {
                stopAndUnbindFunfService();
                stopSelf();
                Timber.d("BackgroundService: Stopped self");
            }
            this.isRunning = isRunning;
        }
    }

    /* Private Methods */
    private void startAndBindFunfService() {
        Intent intent = new Intent(this, FunfManager.class);
        startService(intent);
        bindService(intent, mFunfServiceConnection, 0);
    }

    private void stopAndUnbindFunfService() {
        unbindService(mFunfServiceConnection);
        stopService(new Intent(this, FunfManager.class));
    }

    private void onFunfReady() {
        mFunfManager.enablePipeline(FUNF_PIPELINE_NAME);
    }

}


text:
module API
  module Validations
    module Validators
      class GitRef < Grape::Validations::Base
        # There are few checks that a Git reference should pass through to be valid reference.
        # The link contains some rules that have been added to this validator.
        # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
        # We have skipped some checks that are optional and can be skipped for exception.
        # We also check for control characters, More info on ctrl chars - https://ruby-doc.org/core-2.7.0/Regexp.html#class-Regexp-label-Character+Classes
        INVALID_CHARS = Regexp.union('..', '\\', '@', '@{', ' ', '~', '^', ':', '*', '?', '[', /[[:cntrl:]]/).freeze
        GIT_REF_LENGTH = (1..1024).freeze

        def validate_param!(attr_name, params)
          revision = params[attr_name]

          return unless invalid_character?(revision)

          raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)],
                                               message: 'should be a valid reference path'
        end

        private

        def invalid_character?(revision)
          revision.nil? ||
            revision.start_with?('-') ||
            revision.end_with?('.') ||
            GIT_REF_LENGTH.exclude?(revision.length) ||
            INVALID_CHARS.match?(revision)
        end
      end
    end
  end
end


text:
module SpreeShopifyImporter
  module DataSavers
    module Addresses
      class AddressCreator < AddressBase
        def initialize(shopify_data_feed, spree_user, is_order = false)
          super(shopify_data_feed)
          @spree_user = spree_user
          @is_order = is_order
        end

        def create!
          create_spree_address
          create_user_shipping_and_billing_addresses unless @is_order
          assigns_spree_address_to_data_feed unless @is_order
          @spree_address
        end

        private

        def create_user_shipping_and_billing_addresses
          return unless shopify_address.default?

          default_address = Spree::Address.new(attributes)
          @spree_user.ship_address = default_address
          @spree_user.bill_address = default_address
          @spree_user.save(validate: false)
        end

        def create_spree_address
          # Spree Orders should not be users addresses same time.
          @spree_address = (@is_order ? Spree::Address : @spree_user.addresses).new(attributes)

          # Shopify has'n got validation for filed like zipcode, city or province code.
          @spree_address.save(validate: false)
        end
      end
    end
  end
end


text:
package org.apache.lucene.search;

import java.io.IOException;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReaderContext; // javadocs
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.util.Bits;

/**
 * Expert: Calculate query weights and build query scorers.
 *

 * The purpose of {@link Weight} is to ensure searching does not modify a
 * {@link Query}, so that a {@link Query} instance can be reused.

 * {@link IndexSearcher} dependent state of the query should reside in the
 * {@link Weight}.

 * {@link org.apache.lucene.index.LeafReader} dependent state should reside in the {@link Scorer}.
 *

 * Since {@link Weight} creates {@link Scorer} instances for a given
 * {@link org.apache.lucene.index.LeafReaderContext} ({@link #scorer(org.apache.lucene.index.LeafReaderContext, Bits)})
 * callers must maintain the relationship between the searcher's top-level
 * {@link IndexReaderContext} and the context used to create a {@link Scorer}.
 *

 * A Weight is used in the following way:
 *

 *
A Weight is constructed by a top-level query, given a
 * IndexSearcher ({@link Query#createWeight(IndexSearcher)}).
 *
The {@link #getValueForNormalization()} method is called on the
 * Weight to compute the query normalization factor
 * {@link Similarity#queryNorm(float)} of the query clauses contained in the
 * query.
 *
The query normalization factor is passed to {@link #normalize(float, float)}. At
 * this point the weighting is complete.
 *
A Scorer is constructed by
 * {@link #scorer(org.apache.lucene.index.LeafReaderContext, Bits)}.
 *

 *
 * @since 2.9
 */
public abstract class Weight {

  /**
   * An explanation of the score computation for the named document.
   *
   * @param context the readers context to create the {@link Explanation} for.
   * @param doc the document's id relative to the given context's reader
   * @return an Explanation for the score
   * @throws IOException if an {@link IOException} occurs
   */
  public abstract Explanation explain(LeafReaderContext context, int doc) throws IOException;

  /** The query that this concerns. */
  public abstract Query getQuery();

  /** The value for normalization of contained query clauses (e.g. sum of squared weights). */
  public abstract float getValueForNormalization() throws IOException;

  /** Assigns the query normalization factor and boost from parent queries to this. */
  public abstract void normalize(float norm, float topLevelBoost);

  /**
   * Returns a {@link Scorer} which scores documents in/out-of order according
   * to scoreDocsInOrder.
   *

   * NOTE: null can be returned if no documents will be scored by this
   * query.
   *
   * @param context
   *          the {@link org.apache.lucene.index.LeafReaderContext} for which to return the {@link Scorer}.
   * @param acceptDocs
   *          Bits that represent the allowable docs to match (typically deleted docs
   *          but possibly filtering other documents)
   *
   * @return a {@link Scorer} which scores documents in/out-of order.
   * @throws IOException if there is a low-level I/O error
   */
  public abstract Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException;

  /**
   * Optional method, to return a {@link BulkScorer} to
   * score the query and send hits to a {@link Collector}.
   * Only queries that have a different top-level approach
   * need to override this; the default implementation
   * pulls a normal {@link Scorer} and iterates and
   * collects the resulting hits.
   *
   * @param context
   *          the {@link org.apache.lucene.index.LeafReaderContext} for which to return the {@link Scorer}.
   * @param acceptDocs
   *          Bits that represent the allowable docs to match (typically deleted docs
   *          but possibly filtering other documents)
   *
   * @return a {@link BulkScorer} which scores documents and
   * passes them to a collector.
   * @throws IOException if there is a low-level I/O error
   */
  public BulkScorer bulkScorer(LeafReaderContext context, Bits acceptDocs) throws IOException {

    Scorer scorer = scorer(context, acceptDocs);
    if (scorer == null) {
      // No docs match
      return null;
    }

    // This impl always scores docs in order, so we can
    // ignore scoreDocsInOrder:
    return new DefaultBulkScorer(scorer);
  }

  /** Just wraps a Scorer and performs top scoring using it. */
  static class DefaultBulkScorer extends BulkScorer {
    private final Scorer scorer;

    public DefaultBulkScorer(Scorer scorer) {
      if (scorer == null) {
        throw new NullPointerException();
      }
      this.scorer = scorer;
    }

    @Override
    public boolean score(LeafCollector collector, int max) throws IOException {
      // TODO: this may be sort of weird, when we are
      // embedded in a BooleanScorer, because we are
      // called for every chunk of 2048 documents.  But,
      // then, scorer is a FakeScorer in that case, so any
      // Collector doing something "interesting" in
      // setScorer will be forced to use BS2 anyways:
      collector.setScorer(scorer);
      if (max == DocIdSetIterator.NO_MORE_DOCS) {
        scoreAll(collector, scorer);
        return false;
      } else {
        int doc = scorer.docID();
        if (doc < 0) {
          doc = scorer.nextDoc();
        }
        return scoreRange(collector, scorer, doc, max);
      }
    }

    /** Specialized method to bulk-score a range of hits; we
     *  separate this from {@link #scoreAll} to help out
     *  hotspot.
     *  See LUCENE-5487 */
    static boolean scoreRange(LeafCollector collector, Scorer scorer, int currentDoc, int end) throws IOException {
      while (currentDoc < end) {
        collector.collect(currentDoc);
        currentDoc = scorer.nextDoc();
      }
      return currentDoc != DocIdSetIterator.NO_MORE_DOCS;
    }

    /** Specialized method to bulk-score all hits; we
     *  separate this from {@link #scoreRange} to help out
     *  hotspot.
     *  See LUCENE-5487 */
    static void scoreAll(LeafCollector collector, Scorer scorer) throws IOException {
      int doc;
      while ((doc = scorer.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
        collector.collect(doc);
      }
    }
  }
}


text:
<BODY>
    Sample with a model of a voting system. This sample is only used to demonstrate a "complex" model
    and should be avoided for other things, instead using org.datanucleus.samples.models.company wherever possible.
</BODY>


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

<title>Uses of Interface org.hibernate.loader.plan.build.spi.ExpandingCollectionQuerySpace (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.hibernate.loader.plan.build.spi.ExpandingCollectionQuerySpace

Packages that use ExpandingCollectionQuerySpace

Package
Description

org.hibernate.loader.plan.build.internal.returns

org.hibernate.loader.plan.build.internal.spaces

org.hibernate.loader.plan.build.spi

Uses of ExpandingCollectionQuerySpace in org.hibernate.loader.plan.build.internal.returns

Constructors in org.hibernate.loader.plan.build.internal.returns with parameters of type ExpandingCollectionQuerySpace

Constructor and Description

AbstractCollectionReference(ExpandingCollectionQuerySpace collectionQuerySpace,
                           PropertyPath propertyPath,
                           boolean shouldIncludeJoins)

CollectionAttributeFetchImpl(ExpandingFetchSource fetchSource,
                            AssociationAttributeDefinition fetchedAttribute,
                            FetchStrategy fetchStrategy,
                            ExpandingCollectionQuerySpace collectionQuerySpace)

Uses of ExpandingCollectionQuerySpace in org.hibernate.loader.plan.build.internal.spaces

Classes in org.hibernate.loader.plan.build.internal.spaces that implement ExpandingCollectionQuerySpace

Modifier and Type
Class and Description

class
CollectionQuerySpaceImpl

Methods in org.hibernate.loader.plan.build.internal.spaces that return ExpandingCollectionQuerySpace

Modifier and Type
Method and Description

ExpandingCollectionQuerySpace
QuerySpaceHelper.makeCollectionQuerySpace(ExpandingQuerySpace lhsQuerySpace,
                        AssociationAttributeDefinition attributeDefinition,
                        String querySpaceUid,
                        FetchStrategy fetchStrategy)

ExpandingCollectionQuerySpace
QuerySpacesImpl.makeCollectionQuerySpace(String uid,
                        CollectionPersister collectionPersister,
                        boolean canJoinsBeRequired)

ExpandingCollectionQuerySpace
QuerySpacesImpl.makeRootCollectionQuerySpace(String uid,
                            CollectionPersister collectionPersister)

Uses of ExpandingCollectionQuerySpace in org.hibernate.loader.plan.build.spi

Methods in org.hibernate.loader.plan.build.spi that return ExpandingCollectionQuerySpace

Modifier and Type
Method and Description

ExpandingCollectionQuerySpace
ExpandingQuerySpaces.makeCollectionQuerySpace(String uid,
                        CollectionPersister collectionPersister,
                        boolean canJoinsBeRequired)

ExpandingCollectionQuerySpace
ExpandingQuerySpaces.makeRootCollectionQuerySpace(String uid,
                            CollectionPersister collectionPersister)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
package eu.cdevreeze.yaidom.queryapi

import scala.collection.immutable

import eu.cdevreeze.yaidom.core.Path

/**
 * API and implementation trait for functionally updatable elements. This trait extends trait [[eu.cdevreeze.yaidom.queryapi.IsNavigable]],
 * adding knowledge about child nodes in general, and about the correspondence between child path entries and child
 * indexes.
 *
 * More precisely, this trait adds the following abstract methods to the abstract methods required by its super-trait:
 * `children`, `withChildren` and `collectChildNodeIndexes`. Based on these abstract methods (and the super-trait), this
 * trait offers a rich API for functionally updating elements.
 *
 * The purely abstract API offered by this trait is [[eu.cdevreeze.yaidom.queryapi.UpdatableElemApi]]. See the documentation of that trait
 * for examples of usage, and for a more formal treatment.
 *
 * All methods are overridable. Hence element implementations mixing in this partial implementation trait can change the
 * implementation without breaking its API, caused by otherwise needed removal of this mixin. Arguably this trait should not
 * exist as part of the public API, because implementation details should not be part of the public API. Such implementation details
 * may be subtle, such as the (runtime) boundary on the ThisElem type member.
 *
 * @author Chris de Vreeze
 */
trait UpdatableElemLike extends IsNavigable with UpdatableElemApi {

  type ThisElem <: UpdatableElemLike.Aux[_, ThisElem]

  type ThisNode >: ThisElem

  def children: immutable.IndexedSeq[ThisNode]

  def withChildren(newChildren: immutable.IndexedSeq[ThisNode]): ThisElem

  def collectChildNodeIndexes(pathEntries: Set[Path.Entry]): Map[Path.Entry, Int]

  def childNodeIndex(pathEntry: Path.Entry): Int = {
    collectChildNodeIndexes(Set(pathEntry)).getOrElse(pathEntry, -1)
  }

  def withChildSeqs(newChildSeqs: immutable.IndexedSeq[immutable.IndexedSeq[ThisNode]]): ThisElem = {
    withChildren(newChildSeqs.flatten)
  }

  def withUpdatedChildren(index: Int, newChild: ThisNode): ThisElem =
    withChildren(children.updated(index, newChild))

  def withPatchedChildren(from: Int, newChildren: immutable.IndexedSeq[ThisNode], replace: Int): ThisElem =
    withChildren(children.patch(from, newChildren, replace))

  def plusChild(index: Int, child: ThisNode): ThisElem = {
    require(
      index <= thisElem.children.size,
      s"Expected index $index to be at most the number of children: ${thisElem.children.size}")

    if (index == children.size) {
      plusChild(child)
    } else {
      withPatchedChildren(index, Vector(child, children(index)), 1)
    }
  }

  def plusChild(child: ThisNode): ThisElem = withChildren(children :+ child)

  def plusChildOption(index: Int, childOption: Option[ThisNode]): ThisElem = {
    if (childOption.isEmpty) thisElem else plusChild(index, childOption.get)
  }

  def plusChildOption(childOption: Option[ThisNode]): ThisElem = {
    if (childOption.isEmpty) thisElem else plusChild(childOption.get)
  }

  def plusChildren(childSeq: immutable.IndexedSeq[ThisNode]): ThisElem = {
    withChildren(children ++ childSeq)
  }

  def minusChild(index: Int): ThisElem = {
    require(
      index < thisElem.children.size,
      s"Expected index $index to be less than the number of children: ${thisElem.children.size}")

    withPatchedChildren(index, Vector(), 1)
  }

  def updateChildElem(pathEntry: Path.Entry)(f: ThisElem => ThisElem): ThisElem = {
    updateChildElems(Set(pathEntry)) { case (che, pe) => f(che) }
  }

  def updateChildElem(pathEntry: Path.Entry, newElem: ThisElem): ThisElem = {
    updateChildElem(pathEntry) { e => newElem }
  }

  def updateChildElemWithNodeSeq(pathEntry: Path.Entry)(f: ThisElem => immutable.IndexedSeq[ThisNode]): ThisElem = {
    updateChildElemsWithNodeSeq(Set(pathEntry)) { case (che, pe) => f(che) }
  }

  def updateChildElemWithNodeSeq(pathEntry: Path.Entry, newNodes: immutable.IndexedSeq[ThisNode]): ThisElem = {
    updateChildElemWithNodeSeq(pathEntry) { e => newNodes }
  }

  def updateElemOrSelf(path: Path)(f: ThisElem => ThisElem): ThisElem = {
    updateElemsOrSelf(Set(path)) { case (e, path) => f(e) }
  }

  def updateElemOrSelf(path: Path, newElem: ThisElem): ThisElem =
    updateElemOrSelf(path) { e => newElem }

  def updateElemWithNodeSeq(path: Path)(f: ThisElem => immutable.IndexedSeq[ThisNode]): ThisElem = {
    updateElemsWithNodeSeq(Set(path)) { case (e, path) => f(e) }
  }

  def updateElemWithNodeSeq(path: Path, newNodes: immutable.IndexedSeq[ThisNode]): ThisElem = {
    updateElemWithNodeSeq(path) { e => newNodes }
  }

  def updateChildElems(pathEntries: Set[Path.Entry])(f: (ThisElem, Path.Entry) => ThisElem): ThisElem = {
    // For efficiency, not delegating to updateChildElemsWithNodeSeq

    if (pathEntries.isEmpty) {
      thisElem
    } else {
      val indexesByPathEntries: Seq[(Path.Entry, Int)] =
        collectChildNodeIndexes(pathEntries).toSeq.sortBy(_._2)

      // Updating in reverse order of indexes, in order not to invalidate the path entries
      val newChildren = indexesByPathEntries.reverse.foldLeft(thisElem.children.asInstanceOf[IndexedSeq[ThisNode]]) {
        case (acc, (pathEntry, idx)) =>
          val accChildNodes = acc.asInstanceOf[IndexedSeq[ThisNode]]
          val che = accChildNodes.apply(idx).asInstanceOf[ThisElem]
          val retVal = f(che, pathEntry).asInstanceOf[ThisNode]
          accChildNodes.updated(idx, retVal)
      }

      thisElem.asInstanceOf[UpdatableElemLike.this.type].withChildren(newChildren)
    }
  }

  def updateChildElemsWithNodeSeq(pathEntries: Set[Path.Entry])(f: (ThisElem, Path.Entry) => immutable.IndexedSeq[ThisNode]): ThisElem = {
    if (pathEntries.isEmpty) {
      thisElem
    } else {
      val indexesByPathEntries: Seq[(Path.Entry, Int)] =
        collectChildNodeIndexes(pathEntries).toSeq.sortBy(_._2)

      // Updating in reverse order of indexes, in order not to invalidate the path entries
      val newChildren = indexesByPathEntries.reverse.foldLeft(thisElem.children.asInstanceOf[IndexedSeq[ThisNode]]) {
        case (acc, (pathEntry, idx)) =>
          val accChildNodes = acc.asInstanceOf[IndexedSeq[ThisNode]]
          val che = accChildNodes(idx).asInstanceOf[ThisElem]
          val retVal = f(che, pathEntry).asInstanceOf[IndexedSeq[ThisNode]]
          accChildNodes.patch(idx, retVal, 1)
      }
      thisElem.asInstanceOf[UpdatableElemLike.this.type].withChildren(newChildren)
    }
  }

  def updateElemsOrSelf(paths: Set[Path])(f: (ThisElem, Path) => ThisElem): ThisElem = {
    val pathsByFirstEntry: Map[Path.Entry, Set[Path]] = paths.filterNot(_.isEmpty).groupBy(_.firstEntry)

    val descendantUpdateResult =
      updateChildElems(pathsByFirstEntry.keySet) {
        case (che, pathEntry) =>
          // Recursive (but non-tail-recursive) call
          che.updateElemsOrSelf(pathsByFirstEntry(pathEntry).map(_.withoutFirstEntry)) {
            case (elm, path) =>
              f(elm, path.prepend(pathEntry))
          }
      }

    if (paths.contains(Path.Empty)) f(descendantUpdateResult, Path.Empty) else descendantUpdateResult
  }

  def updateElems(paths: Set[Path])(f: (ThisElem, Path) => ThisElem): ThisElem = {
    val pathsByFirstEntry: Map[Path.Entry, Set[Path]] = paths.filterNot(_.isEmpty).groupBy(_.firstEntry)

    updateChildElems(pathsByFirstEntry.keySet) {
      case (che, pathEntry) =>
        che.updateElemsOrSelf(pathsByFirstEntry(pathEntry).map(_.withoutFirstEntry)) {
          case (elm, path) =>
            f(elm, path.prepend(pathEntry))
        }
    }
  }

  def updateElemsOrSelfWithNodeSeq(paths: Set[Path])(f: (ThisElem, Path) => immutable.IndexedSeq[ThisNode]): immutable.IndexedSeq[ThisNode] = {
    val pathsByFirstEntry: Map[Path.Entry, Set[Path]] = paths.filterNot(_.isEmpty).groupBy(_.firstEntry)

    val descendantUpdateResult =
      updateChildElemsWithNodeSeq(pathsByFirstEntry.keySet) {
        case (che, pathEntry) =>
          // Recursive (but non-tail-recursive) call
          che.asInstanceOf[UpdatableElemLike.this.type].updateElemsOrSelfWithNodeSeq(pathsByFirstEntry(pathEntry).map(_.withoutFirstEntry)) {
            case (elm, path) =>
              f(elm, path.prepend(pathEntry))
          }
      }

    if (paths.contains(Path.Empty)) f(descendantUpdateResult, Path.Empty) else Vector(descendantUpdateResult)
  }

  def updateElemsWithNodeSeq(paths: Set[Path])(f: (ThisElem, Path) => immutable.IndexedSeq[ThisNode]): ThisElem = {
    val pathsByFirstEntry: Map[Path.Entry, Set[Path]] = paths.filterNot(_.isEmpty).groupBy(_.firstEntry)

    updateChildElemsWithNodeSeq(pathsByFirstEntry.keySet) {
      case (che, pathEntry) =>
        che.asInstanceOf[UpdatableElemLike.this.type].updateElemsOrSelfWithNodeSeq(pathsByFirstEntry(pathEntry).map(_.withoutFirstEntry)) {
          case (elm, path) =>
            f(elm, path.prepend(pathEntry))
        }
    }
  }
}

object UpdatableElemLike {

  /**
   * This query API type, restricting ThisNode and ThisElem to the passed type parameters.
   *
   * @tparam N The node self type
   * @tparam E The element self type
   */
  type Aux[N, E] = UpdatableElemLike { type ThisNode = N; type ThisElem = E }
}


text:
package io.cloudslang.content.active_directory.entities;

import java.util.List;

public interface ComputerAccountInterface {

    String getHost();

    String getDistinguishedName();

    String getComputerCommonName();

    String getUsername();

    String getPassword();

    String getProtocol();

    Boolean getTrustAllRoots();

    String getTrustKeystore();

    String getTrustPassword();

    String getTimeout();

    String getTlsVersion();

    List<String> getAllowedCiphers();

    String getProxyHost();

    int getProxyPort();

    String getProxyUsername();

    String getProxyPassword();

    String getX509HostnameVerifier();

}


text:
(function() {
    'use strict';
    //Declaring routes that are being used by the API Services
    //Change of the routings will be easily updated for the whole application
    //White labeling or multitenancy friendly
    appDep.Constants.constant("routingConstants", {
        url: "http://127.0.0.1",
        port: "8000",
        moviesAPI: "api/movies"
    });

    appDep.Constants.constant("commonConstants", {
        numberMoviesPageLoad: 20,
    });
})();


text:
/**
 * UsuarioController
 *
 * @description :: Server-side logic for managing usuarios
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {

};


text:
<program xmlns="http://ci.uchicago.edu/swift/2009/02/swiftscript"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <types>
     	<type>
     		<typename>file</typename>
     		<typealias>string</typealias>
     		<typestructure></typestructure>
     	</type>
  </types>
  <procedure name="echo" src="line 3">

      <output
    name="t" type="file"

     xsi:nil="true" />

      <input
    name="s" type="string"

    >
    <stringConstant>default greeting</stringConstant>

      </input>
    <binding>
      <application src="line 4">
        <executable>echo</executable>
        <stdout><function name="filename">
          <variableReference>t</variableReference></function></stdout><variableReference>s</variableReference>  </application>
    </binding>
  </procedure>
  <variable name="hw" type="file" isGlobal="false" xsi:nil="true"/>
  <call proc="echo" src="line 9">
    <output><variableReference>hw</variableReference></output>
  </call>
</program>


text:
package com.example.android.miwok;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class FamilyFragment extends Fragment {

    /** Handles playback of all the sound files */
    private MediaPlayer mMediaPlayer;

    /** Handles audio focus when playing a sound file */
    private AudioManager mAudioManager;

    /**
     * This listener gets triggered whenever the audio focus changes
     * (i.e., we gain or lose audio focus because of another app or device).
     */
    private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                    focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
                // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
                // our app is allowed to continue playing sound but at a lower volume. We'll treat
                // both cases the same way because our app is playing short sound files.

                // Pause playback and reset player to the start of the file. That way, we can
                // play the word from the beginning when we resume playback.
                mMediaPlayer.pause();
                mMediaPlayer.seekTo(0);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
                mMediaPlayer.start();
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                // The AUDIOFOCUS_LOSS case means we've lost audio focus and
                // Stop playback and clean up resources
                releaseMediaPlayer();
            }
        }
    };

    /**
     * This listener gets triggered when the {@link MediaPlayer} has completed
     * playing the audio file.
     */
    private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            // Now that the sound file has finished playing, release the media player resources.
            releaseMediaPlayer();
        }
    };

    public FamilyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.word_list, container, false);

        // Create and setup the {@link AudioManager} to request audio focus
        mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

        final ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("father", "әpә", R.drawable.family_father, R.raw.family_father));
        words.add(new Word("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother));
        words.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son));
        words.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
        words.add(new Word("older brother", "taachi", R.drawable.family_older_brother,
                R.raw.family_older_brother));
        words.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother,
                R.raw.family_younger_brother));
        words.add(new Word("older sister", "teṭe", R.drawable.family_older_sister,
                R.raw.family_older_sister));
        words.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister,
                R.raw.family_younger_sister));
        words.add(new Word("grandmother ", "ama", R.drawable.family_grandmother,
                R.raw.family_grandmother));
        words.add(new Word("grandfather", "paapa", R.drawable.family_grandfather,
                R.raw.family_grandfather));

        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.
        WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_family);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // word_list.xml layout file.
        ListView listView = (ListView) rootView.findViewById(R.id.list);

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.
        listView.setAdapter(adapter);

        // Set a click listener to play the audio when the list item is clicked on
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                // Release the media player if it currently exists because we are about to
                // play a different sound file
                releaseMediaPlayer();

                // Get the {@link Word} object at the given position the user clicked on
                Word word = words.get(position);

                // Request audio focus so in order to play the audio file. The app needs to play a
                // short audio file, so we will request audio focus with a short amount of time
                // with AUDIOFOCUS_GAIN_TRANSIENT.
                int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                        AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                    // We have audio focus now.

                    // Create and setup the {@link MediaPlayer} for the audio resource associated
                    // with the current word
                    mMediaPlayer = MediaPlayer.create(getActivity(), word.getSoundResourceID());

                    // Start the audio file
                    mMediaPlayer.start();

                    // Setup a listener on the media player, so that we can stop and release the
                    // media player once the sound has finished playing.
                    mMediaPlayer.setOnCompletionListener(mCompletionListener);
                }
            }
        });

        return rootView;
    }

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

        // When the activity is stopped, release the media player resources because we won't
        // be playing any more sounds.
        releaseMediaPlayer();
    }

    /**
     * Clean up the media player by releasing its resources.
     */
    private void releaseMediaPlayer() {
        // If the media player is not null, then it may be currently playing a sound.
        if (mMediaPlayer != null) {
            // Regardless of the current state of the media player, release its resources
            // because we no longer need it.
            mMediaPlayer.release();

            // Set the media player back to null. For our code, we've decided that
            // setting the media player to null is an easy way to tell that the media player
            // is not configured to play an audio file at the moment.
            mMediaPlayer = null;

            // Regardless of whether or not we were granted audio focus, abandon it. This also
            // unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
            mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
        }
    }
}


text:
import {Component, Input, OnInit} from "@angular/core";
import {DatePickerContainer} from "./date-picker-container.component";
import {DateFormatter} from "./date-formatter";

const SHOW_WEEKS: boolean = true;
const FORMAT_DAY_TITLE: string = "MMMM yyyy";
const FORMAT_DAY_HEADER: string = "EEE";
const FORMAT_DAY: string = "dd";

@Component({
    selector: "a2-day-picker",
    templateUrl: "/src/bootstrap/datepicker/day-picker.component.html"
})
export class DayPickerComponent implements OnInit {

    public labels: Array<any> = [];
    public title: string;
    public rows: Array<any> = [];
    public weekNumbers: Array<number> = [];

    @Input()
    private showWeeks: boolean = SHOW_WEEKS;
    @Input()
    private showTime: boolean = false;

    private formatDayHeader: string = FORMAT_DAY_HEADER;
    private formatDayTitle: string = FORMAT_DAY_TITLE;
    private formatDay: string = FORMAT_DAY;

    constructor (public container: DatePickerContainer) {
    }

    ngOnInit (): void {
        let self: DayPickerComponent = this;

        this.container.stepDay = {months: 1};

        this.container.setRefreshViewHandler((): void => {
            let year: number = this.container.activeDate.getFullYear();
            let month: number = this.container.activeDate.getMonth();
            let firstDayOfMonth: Date = new Date(year, month, 1);
            let difference: number = this.container.startingDay - firstDayOfMonth.getDay();
            let numDisplayedFromPreviousMonth: number = (difference > 0) ? 7 - difference : -difference;
            let firstDate: Date = new Date(firstDayOfMonth.getTime());

            if (numDisplayedFromPreviousMonth > 0) {
                firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
            }

            // 42 is the number of days on a six-week calendar
            let _days: Array<Date> = DayPickerComponent.getDates(firstDate, 42);
            let days: Array<any> = [];
            for (let i: number = 0; i < 42; i++) {
                let _dateObject: any = this.container.createDateObject(_days[i], self.formatDay);
                _dateObject.secondary = _days[i].getMonth() !== month;
                _dateObject.uid = this.container.uniqueId + "-" + i;
                days[i] = _dateObject;
            }

            self.labels = [];
            for (let j: number = 0; j < 7; j++) {
                self.labels[j] = {};
                self.labels[j].abbr = DateFormatter.format(days[j].date, self.formatDayHeader);
                self.labels[j].full = DateFormatter.format(days[j].date, "EEE");
            }

            self.title = DateFormatter.format(this.container.activeDate, self.formatDayTitle);
            self.rows = DatePickerContainer.split(days, 7);

            if (self.showWeeks) {
                self.weekNumbers = [];
                let thursdayIndex: number = (4 + 7 - this.container.startingDay) % 7,
                    numWeeks: number = self.rows.length;
                for (let curWeek: number = 0; curWeek < numWeeks; curWeek++) {
                    self.weekNumbers.push(DayPickerComponent.getISO8601WeekNumber(self.rows[curWeek][thursdayIndex].date));
                }
            }
        }, "day");

        this.container.setCompareHandler((date1: any, date2: any): number => {
            if (date1 instanceof String) {
                date1 = new Date(date1);
            }
            if (date2 instanceof String) {
                date2 = new Date(date1);
            }
            let d1: Date = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
            let d2: Date = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
            return d1.getTime() - d2.getTime();
        }, "day");

        this.container.refreshView();
    }

    selectToday (): void {
        if (!this.isCurrentDateDisbled()) {
            this.container.select(new Date());
        }
    }

    isCurrentDateDisbled (): boolean {
        return this.container.isDisabled(new Date());
    }

    private static getDates (startDate: Date, n: number): Array<Date> {
        let dates: Array<Date> = new Array(n);
        let current: Date = new Date(startDate.getTime());
        let i: number = 0;
        let date: Date;
        while (i < n) {
            date = new Date(current.getTime());
            dates[i++] = date;
            current.setDate(current.getDate() + 1);
        }
        return dates;
    }

    private static getISO8601WeekNumber (date: Date): number {
        let checkDate: Date = new Date(date.getTime());
        // Thursday
        checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
        let time: number = checkDate.getTime();
        // Compare with Jan 1
        checkDate.setMonth(0);
        checkDate.setDate(1);
        return Math.floor(Math.round((time - checkDate.getTime()) / 86400000) / 7) + 1;
    }
}


text:
package euler

import utils.ScalaMath._

//Answer:
object TaskS_000 extends BaseTask {
  override def solving() {
  }
}


text:
require 'spec_helper'

describe 'Auto-include resources' do
  let(:entries) { vcr('entries') { create_client.entries } } # entries come with asset includes

  it 'replaces Contentful::Links which are actually included with the resource' do
    asset = entries.items[1].fields[:image]

    expect(asset).not_to be_a Contentful::Link
    expect(asset).to be_a Contentful::Asset
  end
end


text:
@interface ___FILEBASENAMEASIDENTIFIER___ : XCTestCase

@end

@implementation ___FILEBASENAMEASIDENTIFIER___

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testSingleton
{
    ___VARIABLE_testedClass:identifier___* a = [___VARIABLE_testedClass:identifier___ sharedInstance];
    ___VARIABLE_testedClass:identifier___* b = [[___VARIABLE_testedClass:identifier___ alloc] init];
    ___VARIABLE_testedClass:identifier___* c = [___VARIABLE_testedClass:identifier___ allocWithZone:nil];
    ___VARIABLE_testedClass:identifier___* d = [___VARIABLE_testedClass:identifier___ new];
    ___VARIABLE_testedClass:identifier___* e = [[___VARIABLE_testedClass:identifier___ alloc] copy];
    ___VARIABLE_testedClass:identifier___* f = [[___VARIABLE_testedClass:identifier___ alloc] mutableCopy];

    XCTAssertEqualObjects(a, b);
    XCTAssertEqualObjects(a, c);
    XCTAssertEqualObjects(a, d);
    XCTAssertEqualObjects(a, e);
    XCTAssertEqualObjects(a, f);
}

- (void)testExample
{
    XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}

@end


text:
package org.apache.poi.xdgf.usermodel.section.geometry;

import java.awt.geom.Point2D;

import org.apache.poi.POIXMLException;
import org.apache.poi.xdgf.geom.SplineRenderer;
import org.apache.poi.xdgf.usermodel.XDGFCell;
import org.apache.poi.xdgf.usermodel.XDGFShape;

import com.graphbuilder.curve.ControlPath;
import com.graphbuilder.curve.ShapeMultiPath;
import com.graphbuilder.curve.ValueVector;
import com.graphbuilder.geom.PointFactory;
import com.microsoft.schemas.office.visio.x2012.main.CellType;
import com.microsoft.schemas.office.visio.x2012.main.RowType;

public class NURBSTo implements GeometryRow {

	NURBSTo _master = null;

	// The x-coordinate of the last control point of a NURBS.
	Double x = null;

	// The y-coordinate of the last control point of a NURBS.
	Double y = null;

	// The second to the last knot of the NURBS.
	Double a = null;

	// The last weight of the NURBS.
	Double b = null;

	// The first knot of the NURBS.
	Double c = null;

	// The first weight of the NURBS.
	Double d = null;

	// A NURBS formula.
	String e = null;

	Boolean deleted = null;

	// TODO: support formulas

	public NURBSTo(RowType row) {

		if (row.isSetDel()) deleted = row.getDel();

		for (CellType cell: row.getCellArray()) {
			String cellName = cell.getN();

			if (cellName.equals("X")) {
				x = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("Y")) {
				y = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("A")) {
				a = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("B")) {
				b = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("C")) {
				c = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("D")) {
				d = XDGFCell.parseDoubleValue(cell);
			} else if (cellName.equals("E")) {
				e = cell.getV();
			} else {
				throw new POIXMLException("Invalid cell '" + cellName + "' in NURBS row");
			}
		}
	}

	public boolean getDel() {
		if (deleted != null)
			return deleted;

		if (_master != null)
			return _master.getDel();

		return false;
	}

	public Double getX() {
		return x == null ? _master.x : x;
	}

	public Double getY() {
		return y == null ? _master.y : y;
	}

	public Double getA() {
		return a == null ? _master.a : a;
	}

	public Double getB() {
		return b == null ? _master.b : b;
	}

	public Double getC() {
		return c == null ? _master.c : c;
	}

	public Double getD() {
		return d == null ? _master.d : d;
	}

	public String getE() {
		return e == null ? _master.e : e;
	}

	@Override
	public void setupMaster(GeometryRow row) {
		_master = (NURBSTo) row;
	}

	@Override
	public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) {
		if (getDel()) return;

		Point2D last = path.getCurrentPoint();

		// A NURBS formula: knotLast, degree, xType, yType, x1, y1, knot1, weight1, ..
		String formula = getE().trim();
		if (!formula.startsWith("NURBS(") || !formula.endsWith(")"))
			throw new POIXMLException("Invalid NURBS formula: " + formula);

		String [] components = formula.substring(6, formula.length()-1).split(",");

		if (components.length < 8)
			throw new POIXMLException("Invalid NURBS formula (not enough arguments)");

		if ((components.length - 4) % 4 != 0)
			throw new POIXMLException("Invalid NURBS formula -- need 4 + n*4 arguments, got " + components.length);

		double lastControlX = getX();
		double lastControlY = getY();
		double secondToLastKnot = getA();
		double lastWeight = getB();
		double firstKnot = getC();
		double firstWeight = getD();

		double lastKnot = Double.parseDouble(components[0].trim());
		int degree = Integer.parseInt(components[1].trim());
		int xType = Integer.parseInt(components[2].trim());
		int yType = Integer.parseInt(components[3].trim());

		double xScale = 1;
		double yScale = 1;

		if (xType == 0)
			xScale = parent.getWidth();
		if (yType == 0)
			yScale = parent.getHeight();

		// setup first knots/weights/control point
		ControlPath controlPath = new ControlPath();
		ValueVector knots = new ValueVector();
		ValueVector weights = new ValueVector();

		knots.add(firstKnot);
		weights.add(firstWeight);
		controlPath.addPoint(PointFactory.create(last.getX(), last.getY()));

		// iterate get knots/weights
		int sets = (components.length - 4) / 4;
		for (int i = 0; i < sets; i++) {
			double x1 = Double.parseDouble(components[4 + i*4 + 0].trim());
			double y1 = Double.parseDouble(components[4 + i*4 + 1].trim());
			double k = Double.parseDouble(components[4 + i*4 + 2].trim());
			double w = Double.parseDouble(components[4 + i*4 + 3].trim());

			controlPath.addPoint(PointFactory.create(x1*xScale, y1*yScale));
			knots.add(k);
			weights.add(w);
		}

		// last knots/weights/control point
		knots.add(secondToLastKnot);
		knots.add(lastKnot);

		weights.add(lastWeight);

		controlPath.addPoint(PointFactory.create(lastControlX, lastControlY));

		ShapeMultiPath shape = SplineRenderer.createNurbsSpline(controlPath, knots, weights, degree);
		path.append(shape, true);
	}
}


text:
namespace views {
class Widget;
}

namespace content {
class WebContents;
}

// Manages protected media identifier permissions flow, and delegates UI
// handling via PermissionQueueController.
class ProtectedMediaIdentifierPermissionContext
    : public permissions::PermissionContextBase {
 public:
  explicit ProtectedMediaIdentifierPermissionContext(
      content::BrowserContext* browser_context);
  ~ProtectedMediaIdentifierPermissionContext() override;

  // PermissionContextBase implementation.
#if defined(OS_CHROMEOS)
  void DecidePermission(
      content::WebContents* web_contents,
      const permissions::PermissionRequestID& id,
      const GURL& requesting_origin,
      const GURL& embedding_origin,
      bool user_gesture,
      permissions::BrowserPermissionCallback callback) override;
#endif  // defined(OS_CHROMEOS)
  ContentSetting GetPermissionStatusInternal(
      content::RenderFrameHost* render_frame_host,
      const GURL& requesting_origin,
      const GURL& embedding_origin) const override;

 private:
  friend class ProtectedMediaIdentifierPermissionContextTest;
  static bool IsOriginWhitelisted(const GURL& origin);

  void UpdateTabContext(const permissions::PermissionRequestID& id,
                        const GURL& requesting_frame,
                        bool allowed) override;
  bool IsRestrictedToSecureOrigins() const override;

  // Returns whether "Protected content" is enabled based on factors other
  // than the protected media identifier content setting itself. For example,
  // it can be disabled by a master switch in content settings, in incognito or
  // guest mode, or by the device policy.
  bool IsProtectedMediaIdentifierEnabled() const;

#if defined(OS_CHROMEOS)
  void OnPlatformVerificationConsentResponse(
      content::WebContents* web_contents,
      const permissions::PermissionRequestID& id,
      const GURL& requesting_origin,
      const GURL& embedding_origin,
      permissions::BrowserPermissionCallback callback,
      chromeos::attestation::PlatformVerificationDialog::ConsentResponse
          response);

  // |this| is shared among multiple WebContents, so we could receive multiple
  // permission requests. This map tracks all pending requests. Note that we
  // only allow one request per WebContents.
  typedef std::map<content::WebContents*,
                   std::pair<views::Widget*, permissions::PermissionRequestID>>
      PendingRequestMap;
  PendingRequestMap pending_requests_;

  // Must be the last member, to ensure that it will be
  // destroyed first, which will invalidate weak pointers
  base::WeakPtrFactory<ProtectedMediaIdentifierPermissionContext> weak_factory_{
      this};
#endif

  DISALLOW_COPY_AND_ASSIGN(ProtectedMediaIdentifierPermissionContext);
};

#endif  // CHROME_BROWSER_MEDIA_PROTECTED_MEDIA_IDENTIFIER_PERMISSION_CONTEXT_H_


text:
package eu.lestard.assertj.javafx.api;

import javafx.beans.binding.Binding;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.binding.IntegerExpression;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableIntegerValue;
import javafx.beans.value.ObservableNumberValue;
import org.junit.Test;

import static eu.lestard.assertj.javafx.api.Assertions.*;

/**
 * This test is used to find problems with overlapping parameter types.
 * In this case all tests are focusing around Properties and Bindings of type Integer.
 */
public class IntegerTest {

    @Test
    public void testSimpleIntegerProperty() {
        SimpleIntegerProperty actual = new SimpleIntegerProperty(1);
        assertThat(actual).hasValue(1);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testIntegerProperty() {
        IntegerProperty actual = new SimpleIntegerProperty(10);
        assertThat(actual).hasValue(10);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testReadOnlyIntegerProperty(){
        ReadOnlyIntegerProperty actual = new SimpleIntegerProperty(30);
        assertThat(actual).hasValue(30);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testIntegerBinding(){
        IntegerProperty value = new SimpleIntegerProperty(10);

        final IntegerBinding actual = value.add(20);

        assertThat(actual).hasValue(30);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testGenericBinding(){
        Binding<Integer> actual = Bindings.createObjectBinding(() -> 20);

        assertThat(actual).hasValue(20);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testObservableIntegerValue(){
        ObservableIntegerValue actual = new SimpleIntegerProperty(10);

        assertThat(actual).hasValue(10);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testObservableNumberValue(){
        ObservableNumberValue actual = new SimpleIntegerProperty(10);

        assertThat(actual).hasValue(10);

        assertThat(actual).hasSameValue(actual);
    }

    @Test
    public void testIntegerExpression(){
        final IntegerExpression actual = IntegerExpression.integerExpression(new SimpleIntegerProperty(12));

        assertThat(actual).hasValue(12);

        assertThat(actual).hasSameValue(actual);
    }

}


text:
package com.siyeh.igtest.migration.unnecessary_unboxing;

public class UnnecessaryUnboxing {

    private void test1(Integer intValue, Long longValue,
                       Byte shortValue, Double doubleValue,
                       Float floatValue, Long byteValue,
                       Boolean booleanValue, Character character) {
        final int bareIntValue = intValue.intValue();
        final long bareLongValue = longValue.longValue();
        final short bareShortValue = shortValue.shortValue();
        final double bareDoubleValue = doubleValue.doubleValue();
        final float bareFloatValue = floatValue.floatValue();
        final byte bareByteValue = byteValue.byteValue();
        final boolean bareBooleanValue = booleanValue.booleanValue();
        final char bareCharValue = character.charValue();
    }

    Integer foo2(String foo, Integer bar) {
        return foo == null ? Integer.valueOf(0) : bar.intValue();
    }

    Integer foo3(String foo, Integer bar) {
        return foo == null ? 0 : bar.intValue();
    }

    UnnecessaryUnboxing(Object object) {}
    UnnecessaryUnboxing(long l) {}

    void user(Long l) {
        new UnnecessaryUnboxing(l.longValue());
    }

    void casting(Byte b) {
        System.out.println((byte)b.byteValue());
    }

    byte cast(Integer v) {
       return (byte)v.intValue();
    }
}

class B23 {
    public void set(double value) {}
}
class A23 extends B23 {
    public void set(Object value) {}
    private A23() {
        Object o = 2d;
        B23 b23 = new B23();
        b23.set(((Double) o).doubleValue());
    }
}