text:
<?php
	defined('BASEPATH') OR exit('No direct script access allowed');

	require_once(dirname(__FILE__).'/../viewModels/LoanStatus_VM.php');

	class LoanService extends CI_Model {

		public function getLoansStatus() {
			$result = $this->db->get('loan_status')->result();
			$status = array();

			foreach ($result as $row)
			{
				$loan_status = new LoanStatus_VM();
				$loan_status->name = $row->name;
				$loan_status->color = $row->color;

				$status[] = $loan_status;
			}

			return $status;
		}

		public function getLoansOfUser($user) {
			$this->load->model('ItemService');

			$result = $this->db->select('l.item, ls.color')
								->from('loans l')
								->join('loan_status ls', 'ls.id = l.status', 'inner')
								->where('l.user', $user)
								->order_by('RAND()')
								->limit(3)
								->get()
								->result();
			$items = array();

			foreach ($result as $row)
			{
				$loan_status = new LoanStatus_VM();
				$loan_status->color = $row->color;
				$item = $this->ItemService->getItem($row->item);
				$item->loan_status = $loan_status;

				$items[] = $item;
			}

			return $items;
		}

		public function getUsersWithItemAvailable($item) {
			$this->load->model('UserService');

			$result = $this->db->select('u.id')
								->from('users u')
								->join('loans l', 'l.user = u.id', 'inner')
								->where('l.item', $item)
								->where('l.status', 1)
								->order_by('RAND()')
								->get()
								->result();
			$users = array();

			foreach ($result as $row)
			{
				$users[] = $this->UserService->getUser($row->id);
			}

			return $users;
		}
	}
?>


text:
package server

import (
	"time"

	"github.com/kubernetes-incubator/cri-o/oci"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"k8s.io/apimachinery/pkg/fields"
	pb "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime"
)

// filterContainer returns whether passed container matches filtering criteria
func filterContainer(c *pb.Container, filter *pb.ContainerFilter) bool {
	if filter != nil {
		if filter.State != nil {
			if c.State != filter.State.State {
				return false
			}
		}
		if filter.LabelSelector != nil {
			sel := fields.SelectorFromSet(filter.LabelSelector)
			if !sel.Matches(fields.Set(c.Labels)) {
				return false
			}
		}
	}
	return true
}

// ListContainers lists all containers by filters.
func (s *Server) ListContainers(ctx context.Context, req *pb.ListContainersRequest) (resp *pb.ListContainersResponse, err error) {
	const operation = "list_containers"
	defer func() {
		recordOperation(operation, time.Now())
		recordError(operation, err)
	}()
	logrus.Debugf("ListContainersRequest %+v", req)

	var ctrs []*pb.Container
	filter := req.GetFilter()
	ctrList, err := s.ContainerServer.ListContainers()
	if err != nil {
		return nil, err
	}

	if filter != nil {

		// Filter using container id and pod id first.
		if filter.Id != "" {
			id, err := s.CtrIDIndex().Get(filter.Id)
			if err != nil {
				// If we don't find a container ID with a filter, it should not
				// be considered an error.  Log a warning and return an empty struct
				logrus.Warn("unable to find container ID %s", filter.Id)
				return &pb.ListContainersResponse{}, nil
			}
			c := s.ContainerServer.GetContainer(id)
			if c != nil {
				if filter.PodSandboxId != "" {
					if c.Sandbox() == filter.PodSandboxId {
						ctrList = []*oci.Container{c}
					} else {
						ctrList = []*oci.Container{}
					}

				} else {
					ctrList = []*oci.Container{c}
				}
			}
		} else {
			if filter.PodSandboxId != "" {
				pod := s.ContainerServer.GetSandbox(filter.PodSandboxId)
				if pod == nil {
					ctrList = []*oci.Container{}
				} else {
					ctrList = pod.Containers().List()
				}
			}
		}
	}

	for _, ctr := range ctrList {
		podSandboxID := ctr.Sandbox()
		cState := s.Runtime().ContainerStatus(ctr)
		created := cState.Created.UnixNano()
		rState := pb.ContainerState_CONTAINER_UNKNOWN
		cID := ctr.ID()
		img := &pb.ImageSpec{
			Image: ctr.Image(),
		}
		c := &pb.Container{
			Id:           cID,
			PodSandboxId: podSandboxID,
			CreatedAt:    created,
			Labels:       ctr.Labels(),
			Metadata:     ctr.Metadata(),
			Annotations:  ctr.Annotations(),
			Image:        img,
			ImageRef:     ctr.ImageRef(),
		}

		switch cState.Status {
		case oci.ContainerStateCreated:
			rState = pb.ContainerState_CONTAINER_CREATED
		case oci.ContainerStateRunning:
			rState = pb.ContainerState_CONTAINER_RUNNING
		case oci.ContainerStateStopped:
			rState = pb.ContainerState_CONTAINER_EXITED
		}
		c.State = rState

		// Filter by other criteria such as state and labels.
		if filterContainer(c, req.Filter) {
			ctrs = append(ctrs, c)
		}
	}

	resp = &pb.ListContainersResponse{
		Containers: ctrs,
	}
	logrus.Debugf("ListContainersResponse: %+v", resp)
	return resp, nil
}

redpajama_set_name: RedPajamaGithub


text:
echo "DATAPROTECTIONPLAN FOR $1"
echo "- read username and passwod"
echo "- dump database"
echo "- make zipped tarball"
echo "- encrypt data"
echo "- send as email"

if [ -e "/srv/crons/conf/db/$1" ]; then

	# read username and password from conf file
	config=$(cat "/srv/crons/conf/db/$1")

	# not working in sh and cronjob runs as sh (not bash)
	# config=$(<"/srv/crons/conf/db/$1")

	# split string
	username=${config%|*}
	password=${config#*|}

	# dump data
	mysqldump -u $username -p$password $1 > $1.sql

	# make tarball
	tar -czvf $1.sql.tar.gz $1.sql

	# encrypt
	openssl aes-128-cbc -k $password < $1.sql.tar.gz > $1.sql.tar.gz.aes

	# decryption done by
	# openssl aes-128-cbc -d < yourfile.txt.aes > yourfile.txt

	# send file
	echo "You are welcome :)" | mail -s "DATA PROTECTION PLAN FOR $1" -A $1.sql.tar.gz.aes $2

	# clean up
	rm $1.sql
	rm $1.sql.tar.gz
	rm $1.sql.tar.gz.aes

	echo
	echo "Data is sent - clean up is done"

else

	echo "Password file is missing for $1"

fi


text:
package org.apache.servicecomb.router.custom;

import java.util.Map;

/**
 * @Author GuoYl123
 * @Date 2019/10/17
 **/
public interface RouterHeaderFilterExt {

  default int getOrder() {
    return 0;
  }

  default boolean enabled() {
    return true;
  }

  Map<String, String> doFilter(Map<String, String> invokeHeader);
}


text:
from itertools import chain
from collections import Sequence as _Seq
from .stream import Stream

class Sequence(Stream, _Seq):
    """
    An indexable, mutable sequence atop a Stream.
    """

    def __init__(self, *args, **kwargs):
        Stream.__init__(self, *args, **kwargs)
        self.cache = []

    def iload(self):
        """
        Lazily yields elements passed either to extend or
        the constructor while storing them into an internal
        list. Yields elements which have not been loaded yet.
        """
        for item in Stream.__iter__(self):
            self.cache.append(item)
            yield item

    def load(self, n):
        """
        Loads at most *n* elements into the internal cache.
        Meant for internal use.
        """
        for count, _ in enumerate(self.iload(), 1):
            if count >= n:
                break

    def __getitem__(self, idx):
        max_idx = len(self) - 1
        if idx > max_idx:
            self.load(idx - max_idx)
        return self.cache[idx]

    def __iter__(self):
        return chain(self.cache, self.iload())

    def __len__(self):
        return len(self.cache)


text:
package org.apache.ignite.cache.store.spring;

import javax.cache.integration.CacheWriterException;
import javax.sql.DataSource;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.store.CacheStoreSession;
import org.apache.ignite.cache.store.CacheStoreSessionListener;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lifecycle.LifecycleAware;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.transactions.Transaction;
import org.apache.ignite.transactions.TransactionIsolation;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * Cache store session listener based on Spring transaction management.
 *

 * This listener starts a new DB transaction for each session and commits
 * or rolls it back when session ends. If there is no ongoing
 * cache transaction, this listener is no-op.
 *

 * Store implementation can use any Spring APIs like {@link JdbcTemplate}
 * and others. The listener will guarantee that if there is an
 * ongoing cache transaction, all store operations within this
 * transaction will be automatically enlisted in the same database
 * transaction.
 *

 * {@link CacheSpringStoreSessionListener} requires that either
 * {@link #setTransactionManager(PlatformTransactionManager) transaction manager}
 * or {@link #setDataSource(DataSource) data source} is configured. If non of them is
 * provided, exception is thrown. Is both are provided, data source will be
 * ignored.
 *

 * If there is a transaction, a {@link TransactionStatus} object will be saved
 * as a store session {@link CacheStoreSession#attachment() attachment}. It
 * can be used to acquire current DB transaction status.
 */
public class CacheSpringStoreSessionListener implements CacheStoreSessionListener, LifecycleAware {
    /** Transaction manager. */
    private PlatformTransactionManager txMgr;

    /** Data source. */
    private DataSource dataSrc;

    /** Logger. */
    @LoggerResource
    private IgniteLogger log;

    /**
     * Sets transaction manager.
     *

     * Either transaction manager or data source is required.
     * If none is provided, exception will be thrown on startup.
     *
     * @param txMgr Transaction manager.
     */
    public void setTransactionManager(PlatformTransactionManager txMgr) {
        this.txMgr = txMgr;
    }

    /**
     * Gets transaction manager.
     *
     * @return Transaction manager.
     */
    public PlatformTransactionManager getTransactionManager() {
        return txMgr;
    }

    /**
     * Sets data source.
     *

     * Either transaction manager or data source is required.
     * If none is provided, exception will be thrown on startup.
     *
     * @param dataSrc Data source.
     */
    public void setDataSource(DataSource dataSrc) {
        this.dataSrc = dataSrc;
    }

    /**
     * Gets data source.
     *
     * @return Data source.
     */
    public DataSource getDataSource() {
        return dataSrc;
    }

    /** {@inheritDoc} */
    @Override public void start() throws IgniteException {
        if (txMgr == null && dataSrc == null)
            throw new IgniteException("Either transaction manager or data source is required by " +
                getClass().getSimpleName() + '.');

        if (dataSrc != null) {
            if (txMgr == null)
                txMgr = new DataSourceTransactionManager(dataSrc);
            else
                U.warn(log, "Data source configured in " + getClass().getSimpleName() +
                    " will be ignored (transaction manager is already set).");
        }

        assert txMgr != null;
    }

    /** {@inheritDoc} */
    @Override public void stop() throws IgniteException {
        // No-op.
    }

    /** {@inheritDoc} */
    @Override public void onSessionStart(CacheStoreSession ses) {
        if (ses.isWithinTransaction() && ses.attachment() == null) {
            try {
                TransactionDefinition def = definition(ses.transaction(), ses.cacheName());

                ses.attach(txMgr.getTransaction(def));
            }
            catch (TransactionException e) {
                throw new CacheWriterException("Failed to start store session [tx=" + ses.transaction() + ']', e);
            }
        }
    }

    /** {@inheritDoc} */
    @Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
        if (ses.isWithinTransaction()) {
            TransactionStatus tx = ses.attach(null);

            if (tx != null) {
                try {
                    if (commit)
                        txMgr.commit(tx);
                    else
                        txMgr.rollback(tx);
                }
                catch (TransactionException e) {
                    throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
                }
            }
        }
    }

    /**
     * Gets DB transaction isolation level based on ongoing cache transaction isolation.
     *
     * @return DB transaction isolation.
     */
    private TransactionDefinition definition(Transaction tx, String cacheName) {
        assert tx != null;

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();

        def.setName("Ignite Tx [cache=" + (cacheName != null ? cacheName : "<default>") + ", id=" + tx.xid() + ']');
        def.setIsolationLevel(isolationLevel(tx.isolation()));

        long timeoutSec = (tx.timeout() + 500) / 1000;

        if (timeoutSec > 0 && timeoutSec < Integer.MAX_VALUE)
            def.setTimeout((int)timeoutSec);

        return def;
    }

    /**
     * Gets DB transaction isolation level based on ongoing cache transaction isolation.
     *
     * @param isolation Cache transaction isolation.
     * @return DB transaction isolation.
     */
    private int isolationLevel(TransactionIsolation isolation) {
        switch (isolation) {
            case READ_COMMITTED:
                return TransactionDefinition.ISOLATION_READ_COMMITTED;

            case REPEATABLE_READ:
                return TransactionDefinition.ISOLATION_REPEATABLE_READ;

            case SERIALIZABLE:
                return TransactionDefinition.ISOLATION_SERIALIZABLE;

            default:
                throw new IllegalStateException(); // Will never happen.
        }
    }
}


text:
neupy.algorithms.associative package
====================================

Submodules
----------

.. toctree::

   neupy.algorithms.associative.base
   neupy.algorithms.associative.hebb
   neupy.algorithms.associative.instar
   neupy.algorithms.associative.kohonen
   neupy.algorithms.associative.oja

Module contents
---------------

.. automodule:: neupy.algorithms.associative
    :members:
    :undoc-members:
    :show-inheritance:


text:
import java.util.Scanner;

public class SwagNArray {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int [] numbers = new int[10];//length of index

		for (int i = 0; i <= numbers.length - 1; i++){ //for loop for array
			System.out.print("Please enter a number: ");
			numbers [i] = in.nextInt();
		}

		printReverse(numbers);
		compute(numbers);
		getLargest(numbers);

		in.close();
	}

	public static void printReverse(int[] numbers){ //method prints array in reverse
		System.out.println("Here are your numbers in reverse: ");
		for (int i = numbers.length-1; i >= 0 ; i--){
			System.out.print(numbers[i] + ", ");
		}
	}

	public static void compute(int[] numbers){ //method adds all array's values
		int solution = 0;
		for (int i = 0; i < numbers.length; i++){
			solution = solution + numbers[i];
		}
		System.out.println("All numbers add up to " + solution + ".");
	}

	public static void getLargest(int[] numbers){ //method retrieves array's largest value
		int max = -9999;
		for(int i = 0; i < numbers.length; i++){
			if (numbers[i] > max){
				max = numbers[i];
			}
		}
		System.out.println("The highest number is " + max + ".");
	}

}


text:
This is part of the [ES-Git](https://github.com/es-git/es-git) project.

## Install

```bash
npm install --save @es-git/mix
```

## Usage

This package provides a helper method for applying multiple mixins to a repo, working well with TypeScript.

```js
import objectsMixin from '@es-git/objects-mixin';
import walkersMixin from '@es-git/mix';
import MemoryRepo from '@es-git/memory-repo';

const Repo = mix(MemoryRepo)
            .with(objectsMixin)
            .with(walkersMixin)
            .with(pushMixin, fetch);
```


text:
package service

import (
	"reflect"
	"testing"

	"github.com/kubernetes/dashboard/src/app/backend/resource/common"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	api "k8s.io/client-go/pkg/api/v1"
)

func TestToServiceDetail(t *testing.T) {
	cases := []struct {
		service  *api.Service
		expected ServiceDetail
	}{
		{
			service: &api.Service{}, expected: ServiceDetail{
				TypeMeta: common.TypeMeta{Kind: common.ResourceKindService},
			},
		}, {
			service: &api.Service{
				ObjectMeta: metaV1.ObjectMeta{
					Name: "test-service", Namespace: "test-namespace",
				}},
			expected: ServiceDetail{
				ObjectMeta: common.ObjectMeta{
					Name:      "test-service",
					Namespace: "test-namespace",
				},
				TypeMeta:         common.TypeMeta{Kind: common.ResourceKindService},
				InternalEndpoint: common.Endpoint{Host: "test-service.test-namespace"},
			},
		},
	}

	for _, c := range cases {
		actual := ToServiceDetail(c.service)

		if !reflect.DeepEqual(actual, c.expected) {
			t.Errorf("ToServiceDetail(%#v) == \ngot %#v, \nexpected %#v", c.service, actual,
				c.expected)
		}
	}
}

func TestToService(t *testing.T) {
	cases := []struct {
		service  *api.Service
		expected Service
	}{
		{
			service: &api.Service{}, expected: Service{
				TypeMeta: common.TypeMeta{Kind: common.ResourceKindService},
			},
		}, {
			service: &api.Service{
				ObjectMeta: metaV1.ObjectMeta{
					Name: "test-service", Namespace: "test-namespace",
				}},
			expected: Service{
				ObjectMeta: common.ObjectMeta{
					Name:      "test-service",
					Namespace: "test-namespace",
				},
				TypeMeta:         common.TypeMeta{Kind: common.ResourceKindService},
				InternalEndpoint: common.Endpoint{Host: "test-service.test-namespace"},
			},
		},
	}

	for _, c := range cases {
		actual := ToService(c.service)

		if !reflect.DeepEqual(actual, c.expected) {
			t.Errorf("ToService(%#v) == \ngot %#v, \nexpected %#v", c.service, actual,
				c.expected)
		}
	}
}


text:
<!DOCTYPE html>

		<title>three.js webgl - custom attributes [particles][billboards]</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js - custom attributes example - particles - billboards


text:
import React from 'react'
import { reset } from 'redux-form'
import axios from 'axios'
import classNames from 'classnames'

import { Field, reduxForm } from 'redux-form'

import WidgetGrid from '../../../../components/widgets/WidgetGrid'
import Datatable from '../../../../components/tables/Datatable'

import { RFField, RFTextArea } from '../../../../components/ui'

import { required, email, number } from '../../../../components/forms/validation/CustomValidation'
import AlertMessage from '../../../../components/common/AlertMessage'
import { submitStudentMedicalDetails } from './submit'
import mapForCombo, {getWebApiRootUrl, instanceAxios} from '../../../../components/utils/functions'
import { upper, lower } from '../../../../components/utils/normalize'
import Msg from '../../../../components/i18n/Msg'

class MedicalDetailsForm extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            studentId: 0,
            activeTab: "add",
            disabledOtherRelation: true
        }
        //this.handleOtherRelationBlur = this.handleOtherRelationBlur.bind(this);
    }

    componentDidMount(){

        this.setState({studentId: this.props.studentId});
        this.props.change('studentId', this.props.studentId); // function provided by redux-form

    }

    // handleOtherRelationBlur(obj, value){
    //     if(isOtherOptionSelected(value)){
    //         this.setState({disabledOtherRelation:true});
    //     }
    //     else{
    //         this.setState({disabledOtherRelation:false});
    //     }
    // }

  //
  render() {
    const { handleSubmit, pristine, reset, submitting, touched, error, warning } = this.props
    const { studentId, activeTab, classOptions, relationOptions, disabledOtherRelation } = this.state;

    return (

        <WidgetGrid>
            <form id="form-emergency-contact-detail" className="smart-form"
                onSubmit={handleSubmit((values)=>{submitStudentMedicalDetails(values, studentId)})}>
                <fieldset>

                        <Field name="bloodGroup" labelClassName="input"
                            labelIconClassName="icon-append fa fa-user"
                            component={RFField} normalize={upper}
                            maxLength="5"
                            type="text" placeholder=""
                            label="BloodGroupText" />

                        <Field name="chronicMedication" labelClassName="input"
                            labelIconClassName="icon-append fa fa-user"
                            validate={required} component={RFField}
                            maxLength="100"
                            type="text" placeholder=""
                            label="ChronicMedicationText" />

                        <Field name="otherMedicalConditions" labelClassName="input"
                            labelIconClassName="icon-append fa fa-book"
                            component={RFTextArea}
                            maxLength="500" type="text"
                            label="OtherMedicalConditionsText"
                            placeholder=""/>

                        <Field name="familyDoctorName" labelClassName="input"
                            labelIconClassName="icon-append fa fa-user"
                            component={RFField} normalize={upper}
                            maxLength="50"
                            type="text" placeholder=""
                            label="FamilyDoctorNameText" />

                        <Field name="familyDoctorContactNo" labelClassName="input"
                            labelIconClassName="icon-append fa fa-user"
                            component={RFField}
                            maxLength="20"
                            type="text" placeholder=""
                            label="FamilyDoctorContactNoText" />

                {/*

 */}

<Msg phrase="StudentMedicalHistoryText"/>

                        <Datatable id="medicalConditionsGrid"
                            options={{
                                columnDefs: [
                                    {
                                        "render": function ( data, type, row ) {
                                        return '<input id="selectRow" type="checkbox" data-tid="' + data + '"></input>';
                                        }.bind(self),
                                        "className": "dt-center",
                                        "sorting": false,
                                        "targets": 0
                                    },
                                    {
                                        "render": function ( data, type, row ) {
                                        return '<input id="probDetail" type="text"></input>';
                                        }.bind(self),
                                        "className": "dt-center",
                                        "sorting": false,
                                        "targets": 2
                                    }
                                ],
                                bFilter: false,
                                bPaginate: false,
                                columns: [
                                {data: "HealthProblemId"},
                                {data: "HealthProblem"},
                                {data: "Details"}
                                ]
                            }}
                            paginationLength={false}
                            className="table table-striped table-bordered table-hover"
                            width="100%">

                                <Msg phrase="HealthProblemText"/>
                                <Msg phrase="DetailsText"/>

                                    General Health

                        </Datatable>

                    {/*

 */}

                {(error!==undefined && <AlertMessage type="w" icon="alert-danger" message={error} />)}

                <Field component="input" type="hidden" name="studentId" />

                    <button type="button" disabled={pristine || submitting} onClick={reset} className="btn btn-primary">
                    <Msg phrase="ResetText"/>
                    </button>
                    <button type="submit" disabled={pristine || submitting} className="btn btn-primary">
                    <Msg phrase="SaveText"/>
                    </button>

                </fieldset>
            </form>

        </WidgetGrid>
    )
  }
}

const afterSubmit = function(result, dispatch) {
    dispatch(reset('MedicalDetailsForm'));
}

export default reduxForm({
  form: 'MedicalDetailsForm',  // a unique identifier for this form
  onSubmitSuccess: afterSubmit,
  keepDirtyOnReinitialize: false
})(MedicalDetailsForm)


text:
package za.org.grassroot.integration.authentication;

import io.jsonwebtoken.impl.crypto.RsaProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.Map;

@Service
public class KeyPairProviderImpl implements KeyPairProvider{

    private static final Logger logger = LoggerFactory.getLogger(KeyPairProviderImpl.class);

    private final Environment environment;

    private Map<String, KeyPair> keyPairMap = new HashMap<>();

    @Autowired
    public KeyPairProviderImpl(Environment environment){
        this.environment = environment;
    }

    @PostConstruct
    void initProvider() {
        String  jwtKeyAlias = getJWTKeyAlias();
        KeyPair keyPair;
        if (StringUtils.isEmpty(environment.getProperty("JWT_KEYSTORE_PATH"))) {
            logger.info("could not find keystore path, generating key in memore");
            keyPair = RsaProvider.generateKeyPair(1024);
        } else {
            try {
                logger.info("found a keystore path, trying to load: {}", environment.getProperty("JWT_KEYSTORE_PATH"));
                File file = new File(environment.getProperty("JWT_KEYSTORE_PATH"));
                FileInputStream is = new FileInputStream(file);
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

                final String password = environment.getProperty("JWT_KEYSTORE_PASS");
                final String keypass = environment.getProperty("JWT_KEY_PASS", password);

                keyStore.load(is, password.toCharArray());
                PrivateKey privateKey = (PrivateKey) keyStore.getKey(jwtKeyAlias, keypass.toCharArray());
                Certificate certificate = keyStore.getCertificate(jwtKeyAlias);
                PublicKey publicKey = certificate.getPublicKey();
                keyPair = new KeyPair(publicKey, privateKey);
                logger.info("successfuly loaded keystore from file, continuing");
            } catch (Exception e) {
                logger.error("Exception loading keystore, defaulting to in-memory generation", e);
                keyPair = RsaProvider.generateKeyPair(1024);
            }
        }
        keyPairMap.put(jwtKeyAlias, keyPair);
    }

    @Override
    public KeyPair getKey(String alias) {
        return keyPairMap.get(alias);
    }

    @Override
    public KeyPair getJWTKey() {
        return getKey(getJWTKeyAlias());
    }

    private String getJWTKeyAlias() {
        String alias = environment.getProperty("JWT_KEY_ALIAS");
        if (alias == null) {
            alias = "grassroot_jwt";
        }
        return alias;
    }
}


text:
'''
This enables the use of version_id as a version column - so that
updates will only be made if the version number is the same and then
incremented by the update!

Created on 19 Feb 2015

@author: peterb
'''
from sqlalchemy.types import Integer, DateTime
from sqlalchemy.schema import Column
import datetime
from blueshed.model_helpers.base import _Base_, Base

_Base_.version_id = Column(Integer, nullable=False)
_Base_.last_updated = Column(DateTime,
                        default=datetime.datetime.now,
                        onupdate=datetime.datetime.now)

_Base_.__mapper_args__ = {
    "version_id_col": _Base_.version_id  # @UndefinedVariable
}


text:
import React from 'react'
import { connect } from 'react-redux'
import i18nURL from 'client/lib/i18nURL';

import submit from '../../../../../actions/Forms/contact_submit'

import {Checkbox} from 'react-bootstrap'
import Head from '../../../../organisms/Head';
import Layout from '../../../../layouts/Standar';
import TextI18n from 'client/components/atoms/TextI18n';
import Row from 'client/components/atoms/Row'
import Col from 'client/components/atoms/Col'
import FormGroup from 'client/components/atoms/FormGroup'
import ButtonLoader from 'client/components/atoms/ButtonLoader'
import MarkerMap from '../../../../molecules/MarkerMap';

import './index.css';

var Page = React.createClass({

  propTypes: {

    id: React.PropTypes.string.isRequired,
    values : React.PropTypes.object.isRequired,
    show : React.PropTypes.bool.isRequired,
    sending: React.PropTypes.bool.isRequired,
    errors: React.PropTypes.array.isRequired,
  },

  contextTypes: {
    __: React.PropTypes.func.isRequired
  },

  componentDidMount (){

    //# al iniciar borramos todo lo que se hubiera escrito
    this.props.dispatch({type: 'FORM_'+this.props.id+'_RESET'});

    var initialData = {language : this.props.lang}

    //# si hay parametros de ruta que coincidan conl os campos, los usamos para iniciar el formulario
    if(this.props.query){

      initialData = Object.assign({}, this.props.query, initialData)
    }

    this.update( initialData );
  },

  update (data) {

    this.props.dispatch({type: 'FORM_'+this.props.id+'_UPDATE', data: data});
  },

  submit (e) {

    if(e) e.preventDefault();

    this.props.dispatch(submit(this.context));
  },

  render: function () {

    const props = this.props;
    const item = props.item;
    const query = props.query;
    const values = props.values;
    const errors = props.errors;

    return (

      <Layout className="Page">

<TextI18n value={item.title}/>

                <Row>
                  <Col sm={6}>

                    <TextI18n value={item.content} html/>

                  </Col>

                  <Col sm={6}>

                    <form className="TemplateContact__form" onSubmit={this.submit}>

                      <Row>

                          <Col md={6}>

                            <FormGroup label={this.context.__("Su nombre *")} errors={errors.name}>
                              <input type="text" className="form-control" value={values.name} onChange={(e) => this.update({name : e.target.value})}/>
                            </FormGroup>

                          </Col>

                          <Col md={6}>

                            <FormGroup label={this.context.__("Su e-mail *")} errors={errors.email}>
                              <input type="text" className="form-control" value={values.email} onChange={(e) => this.update({email : e.target.value})}/>
                            </FormGroup>

                          </Col>

                          <Col md={12}>

                            <FormGroup label={this.context.__("Asunto")}>
                              <input type="text" className="form-control" value={values.subject} onChange={(e) => this.update({subject : e.target.value})}/>
                            </FormGroup>

                            <FormGroup label={this.context.__("Su mensaje")}>
                              <textarea type="text" className="form-control" rows="8" value={values.message} onChange={(e) => this.update({message : e.target.value})}/>
                            </FormGroup>

                            {props.LOPD ?

                              <FormGroup errors={errors.polPrivacy}>

                                <Checkbox checked={values.polPrivacy} onChange={(e) => this.update({polPrivacy : e.target.checked})}>
                                  {this.context.__('Acepto')} {this.context.__('Política de Privacidad')}
                                </Checkbox>

                              </FormGroup>

                            :null}

                            <ButtonLoader loading={props.sending} className="btn btn-primary btn-lg" onClick={this.submit}>{this.context.__("Enviar")}</ButtonLoader>

                          </Col>

                      </Row>

                    </form>

                  </Col>

                </Row>

            { item.haveMap && item.coordinates && item.coordinates.length == 2 ?

              <MarkerMap coords={[item.coordinates[1], item.coordinates[0]]} zoom={16}/>

            :null}

      </Layout>
    )
  }

});

//export default Page;

export default connect((state, ownProps) => {

  return Object.assign({}, state.forms.CONTACT, {

    query : state.routing.locationBeforeTransitions ? state.routing.locationBeforeTransitions.query : {},
    LOPD: state.positions.data.LOPD,
    lang: state.i18nState.lang
  })

})(Page)


text:
namespace ContosoUniversityCore.Features.Department
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Threading.Tasks;
    using AutoMapper;
    using Infrastructure;
    using MediatR;

    public class Index
    {
        public class Query : IRequest<List<Model>>
        {
        }

        public class Model
        {
            public string Name { get; set; }

            public decimal Budget { get; set; }

            public DateTime StartDate { get; set; }

            public int Id { get; set; }

            [Display(Name = "Administrator")]
            public string AdministratorFullName { get; set; }
        }

        public class QueryHandler : AsyncRequestHandler<Query, List<Model>>
        {
            private readonly SchoolContext _context;

            public QueryHandler(SchoolContext context)
            {
                _context = context;
            }

            protected override async Task<List<Model>> HandleCore(Query message)
            {
                return await _context.Departments
                  .ProjectToListAsync<Model>();
            }
        }
    }
}


text:
title: How to TDD effectively
slug: how-to-tdd-effectively
date_published: 2012-05-13T10:38:00.000Z
date_updated: 2016-02-02T00:48:07.000Z
---

*To new readers of my blog. This article was written many years ago, and is no longer the entirety or core of what I believe. It remains here as a historical stepping stone to newer ideas.*

1. Understand the overall functional behaviour of the system you must implement. It's sensible to understand this from the perspective of why (e.g. a customer's need fulfilment). These behaviours are often represented as user stories or business requirements and are the result of business-driven planning.
2. Distinguish different behavioural domains as components and then define the scope of each of these. The scope of each component should describe the behaviour it must implement in a standardized format or ubiquitous language that is well-understood by everybody involved in the project (BDD). This is the result of joint business/technical planning.
3. Ensure that larger components are broken into more manageable sub-components that are simpler to reason about. This is the result of technical planning.
4. As a developer, start at the smallest component and for each:

1. Carefully create a public interface [0]. Plan how to test each of these public methods [1] by writing documentation that explicitly describes each method's usage and behaviour (defined at this point as: expected or unexpected responses) [2]. These are the things which you should think of:

1. What customer needs related to this were expressed in the ubiquitous language earlier?
2. How can it be used?
3. What behaviour does it provide?
4. What responses can it respond with and when?
5. What exceptions can be raised as a result of calling it and when?
6. What usage-behaviour mapping needs to exist for this behaviour to be represented and then tested?

2. Create tests for the interface previously created based on the documented behaviour, usage, responses, and errors. Until the methods of an interface are successfully implemented their tests will fail (TDD).
3. Implement the interfaces methods until they pass. (If an implementation requires growing the list of public methods contained by an interface then repeat the test planning process [3] for each of these.)
4. Check that business needs have been met as a result of the process.

[0] It's worth noting that when I say "interface" I mean this in a generalised form. I mean the way of interacting with the component. I do not mean a particular programming language's "Interface" language construct.

[1] We do not test private methods as they are implementation related and suspect to change often. However encapsulation is contextual. A public interface may be provided to other components in a system, yet there may be an underlying API that is private to external systems, but should be considered public to the components built on top of it — and therefore tested.

[2] In Python it is possible to do this using the [doctest](http://docs.python.org/library/doctest.html) module.

[3] ALWAYS use common sense.


text:
<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Template extends MX_Controller {
    function __construct(){
        parent::__construct();
        $this->load->library('auth/ion_auth');
    }

    public function admin($data = ""){
        if (!$this->ion_auth->is_admin())
        {
            $this->session->set_flashdata('message', 'You must be an admin to view this page');
            redirect('auth/login');
        }
        $this->load->view('layouts/admin_dashboard', $data);
    }

    public function one_col($data = ""){
        $this->load->view('header');
        $this->load->view('navigation');
        $this->load->view('layouts/one_col', $data);
        $this->load->view('footer');
    }

    public function operator_two_col($data = ""){
        if (!$this->ion_auth->logged_in())
        {
            redirect('auth/login');
        }
        $this->load->view('header');
        $this->load->view('navigation');
        $this->load->view('layouts/operator_two_col', $data);
        $this->load->view('footer');
    }

    public function login($data = ""){
   	$this->load->view('layouts/login', $data);
    }
}


text:
(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['ApiClient', 'model/JobIgesOutputPayload', 'model/JobObjOutputPayload', 'model/JobObjOutputPayloadAdvanced', 'model/JobStepOutputPayload', 'model/JobStlOutputPayload', 'model/JobSvfOutputPayload', 'model/JobThumbnailOutputPayload'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'), require('./JobIgesOutputPayload'), require('./JobObjOutputPayload'), require('./JobObjOutputPayloadAdvanced'), require('./JobStepOutputPayload'), require('./JobStlOutputPayload'), require('./JobSvfOutputPayload'), require('./JobThumbnailOutputPayload'));
  } else {
    // Browser globals (root is window)
    if (!root.ForgeModelDerivative) {
      root.ForgeModelDerivative = {};
    }
    root.ForgeModelDerivative.JobPayloadItem = factory(root.ForgeModelDerivative.ApiClient, root.ForgeModelDerivative.JobIgesOutputPayload, root.ForgeModelDerivative.JobObjOutputPayload, root.ForgeModelDerivative.JobObjOutputPayloadAdvanced, root.ForgeModelDerivative.JobStepOutputPayload, root.ForgeModelDerivative.JobStlOutputPayload, root.ForgeModelDerivative.JobSvfOutputPayload, root.ForgeModelDerivative.JobThumbnailOutputPayload);
  }
}(this, function(ApiClient, JobIgesOutputPayload, JobObjOutputPayload, JobObjOutputPayloadAdvanced, JobStepOutputPayload, JobStlOutputPayload, JobSvfOutputPayload, JobThumbnailOutputPayload) {
  'use strict';

  /**
   * The JobPayloadItem model module.
   * @module model/JobPayloadItem
   * @version 2.0.0
   */

  /**
   * Constructs a new JobPayloadItem.
   * Output description object, depends of the type
   * @alias module:model/JobPayloadItem
   * @class
   * @implements module:model/JobSvfOutputPayload
   * @implements module:model/JobThumbnailOutputPayload
   * @implements module:model/JobStlOutputPayload
   * @implements module:model/JobStepOutputPayload
   * @implements module:model/JobIgesOutputPayload
   * @implements module:model/JobObjOutputPayload
   * @param type {module:model/JobObjOutputPayload.TypeEnum} The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   */
  var exports = function(type) {
    var _this = this;

    JobSvfOutputPayload.call(_this, type);
    JobThumbnailOutputPayload.call(_this, type);
    JobStlOutputPayload.call(_this, type);
    JobStepOutputPayload.call(_this, type);
    JobIgesOutputPayload.call(_this, type);
    JobObjOutputPayload.call(_this, type);
  };

  /**
   * Constructs a JobPayloadItem from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/JobPayloadItem} obj Optional instance to populate.
   * @return {module:model/JobPayloadItem} The populated JobPayloadItem instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      JobSvfOutputPayload.constructFromObject(data, obj);
      JobThumbnailOutputPayload.constructFromObject(data, obj);
      JobStlOutputPayload.constructFromObject(data, obj);
      JobStepOutputPayload.constructFromObject(data, obj);
      JobIgesOutputPayload.constructFromObject(data, obj);
      JobObjOutputPayload.constructFromObject(data, obj);
    }
    return obj;
  }

  // Implement JobSvfOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobSvfOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {Array.<module:model/JobSvfOutputPayload.ViewsEnum>} views
   */
exports.prototype['views'] = undefined;

  // Implement JobThumbnailOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobThumbnailOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {module:model/JobThumbnailOutputPayloadAdvanced} advanced
   */
exports.prototype['advanced'] = undefined;

  // Implement JobStlOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobStlOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {module:model/JobStlOutputPayloadAdvanced} advanced
   */
exports.prototype['advanced'] = undefined;

  // Implement JobStepOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobStepOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {module:model/JobStepOutputPayloadAdvanced} advanced
   */
exports.prototype['advanced'] = undefined;

  // Implement JobIgesOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobIgesOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {module:model/JobIgesOutputPayloadAdvanced} advanced
   */
exports.prototype['advanced'] = undefined;

  // Implement JobObjOutputPayload interface:
  /**
   * The requested output types. Possible values include `svf`, `thumbnai`, `stl`, `step`, `iges`, or `obj`. For a list of supported types, call the [GET formats](https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET) endpoint.
   * @member {module:model/JobObjOutputPayload.TypeEnum} type
   */
exports.prototype['type'] = undefined;

  /**
   * @member {module:model/JobObjOutputPayloadAdvanced} advanced
   */
exports.prototype['advanced'] = undefined;

  return exports;
}));


text:
//
//  AKSimpleWaveGuideModel.h
//  AudioKit
//
//  Auto-generated on 2/19/15.
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKAudio.h"
#import "AKParameter+Operation.h"

/** A simple waveguide model consisting of one delay-line and one first-order lowpass filter.

 This is the most elemental waveguide model, consisting of one delay-line and one first-order lowpass filter.
 */

NS_ASSUME_NONNULL_BEGIN
@interface AKSimpleWaveGuideModel : AKAudio
/// Instantiates the simple wave guide model with all values
/// @param input The excitation noise.
/// @param frequency The inverse of delay time. [Default Value: 440]
/// @param cutoff Filter cut-off frequency in Hz Updated at Control-rate. [Default Value: 3000]
/// @param feedback Feedback factor usually between 0 and 1 Updated at Control-rate. [Default Value: 0.8]
- (instancetype)initWithInput:(AKParameter *)input
                    frequency:(AKParameter *)frequency
                       cutoff:(AKParameter *)cutoff
                     feedback:(AKParameter *)feedback;

/// Instantiates the simple wave guide model with default values
/// @param input The excitation noise.
- (instancetype)initWithInput:(AKParameter *)input;

/// Instantiates the simple wave guide model with default values
/// @param input The excitation noise.
+ (instancetype)modelWithInput:(AKParameter *)input;

/// The inverse of delay time. [Default Value: 440]
@property (nonatomic) AKParameter *frequency;

/// Set an optional frequency
/// @param frequency The inverse of delay time. [Default Value: 440]
- (void)setOptionalFrequency:(AKParameter *)frequency;

/// Filter cut-off frequency in Hz [Default Value: 3000]
@property (nonatomic) AKParameter *cutoff;

/// Set an optional cutoff
/// @param cutoff Filter cut-off frequency in Hz Updated at Control-rate. [Default Value: 3000]
- (void)setOptionalCutoff:(AKParameter *)cutoff;

/// Feedback factor usually between 0 and 1 [Default Value: 0.8]
@property (nonatomic) AKParameter *feedback;

/// Set an optional feedback
/// @param feedback Feedback factor usually between 0 and 1 Updated at Control-rate. [Default Value: 0.8]
- (void)setOptionalFeedback:(AKParameter *)feedback;

@end
NS_ASSUME_NONNULL_END


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System.Collections.Generic;
using System.Globalization;
using Org.Apache.REEF.Driver.Evaluator;
using Org.Apache.REEF.Utilities.Attributes;
using Org.Apache.REEF.Utilities.Diagnostics;
using Org.Apache.REEF.Utilities.Logging;

namespace Org.Apache.REEF.IMRU.OnREEF.Driver
{
    /// <summary>
    /// Manages allocated and failed Evaluators for driver.
    /// It keeps tracking allocated Evaluators and failed Evaluator ids. Provides methods to
    /// add, remove evaluators from the collections so that to provide data for fault tolerant.
    /// It also tracks master evaluator.
    /// </summary>
    [NotThreadSafe]
    internal sealed class EvaluatorManager
    {
        private static readonly Logger Logger = Logger.GetLogger(typeof(EvaluatorManager));

        private readonly ISet<string> _allocatedEvaluatorIds = new HashSet<string>();

        private readonly int _totalExpectedEvaluators;
        private readonly int _allowedNumberOfEvaluatorFailures;
        private readonly IEvaluatorRequestor _evaluatorRequestor;
        private string _masterEvaluatorId;

        private int _failedEvaluatorsCount;
        private bool _masterEvaluatorFailed;

        private readonly EvaluatorSpecification _updateEvaluatorSpecification;
        private readonly EvaluatorSpecification _mapperEvaluatorSpecification;

        /// <summary>
        /// Creates a EvaluatorManager for driver which contains specification for the Evaluators
        /// </summary>
        /// <param name="totalEvaluators"></param>
        /// <param name="allowedNumberOfEvaluatorFailures"></param>
        /// <param name="evaluatorRequestor"></param>
        /// <param name="updateEvaluatorSpecification"></param>
        /// <param name="mapperEvaluatorSpecification"></param>
        internal EvaluatorManager(
            int totalEvaluators,
            int allowedNumberOfEvaluatorFailures,
            IEvaluatorRequestor evaluatorRequestor,
            EvaluatorSpecification updateEvaluatorSpecification,
            EvaluatorSpecification mapperEvaluatorSpecification)
        {
            _totalExpectedEvaluators = totalEvaluators;
            _allowedNumberOfEvaluatorFailures = allowedNumberOfEvaluatorFailures;
            _evaluatorRequestor = evaluatorRequestor;
            _updateEvaluatorSpecification = updateEvaluatorSpecification;
            _mapperEvaluatorSpecification = mapperEvaluatorSpecification;
        }

        /// <summary>
        /// Request update/master Evaluator from resource manager
        /// </summary>
        internal void RequestUpdateEvaluator()
        {
            _evaluatorRequestor.Submit(
                _evaluatorRequestor.NewBuilder()
                    .SetCores(_updateEvaluatorSpecification.Core)
                    .SetMegabytes(_updateEvaluatorSpecification.Megabytes)
                    .SetNumber(1)
                    .Build());

            var message = string.Format(CultureInfo.InvariantCulture,
                "Submitted master evaluator with core [{0}], memory [{1}].",
                _updateEvaluatorSpecification.Core,
                _updateEvaluatorSpecification.Megabytes);
            Logger.Log(Level.Info, message);
        }

        /// <summary>
        /// Request map evaluators from resource manager
        /// </summary>
        /// <param name="numEvaluators">Number of evaluators to request</param>
        internal void RequestMapEvaluators(int numEvaluators)
        {
            _evaluatorRequestor.Submit(
                _evaluatorRequestor.NewBuilder()
                    .SetMegabytes(_mapperEvaluatorSpecification.Megabytes)
                    .SetNumber(numEvaluators)
                    .SetCores(_mapperEvaluatorSpecification.Core)
                    .Build());

            var message = string.Format(CultureInfo.InvariantCulture,
                "Submitted [{0}] mapper evaluators with core [{1}], memory [{2}].",
                numEvaluators,
                _mapperEvaluatorSpecification.Core,
                _mapperEvaluatorSpecification.Megabytes);
            Logger.Log(Level.Info, message);
        }

        /// <summary>
        /// Add an Evaluator id to _allocatedEvaluators.
        /// IMRUSystemException will be thrown in the following cases:
        ///   The Evaluator Id is already in the allocated Evaluator collection
        ///   The added IAllocatedEvaluator is the last one expected, and master Evaluator is still not added yet
        ///   The number of AllocatedEvaluators has reached the total expected Evaluators
        /// </summary>
        /// <param name="evaluator">Evaluator to add</param>
        internal void AddAllocatedEvaluator(IAllocatedEvaluator evaluator)
        {
            if (IsAllocatedEvaluator(evaluator.Id))
            {
                string msg = string.Format("The allocated evaluator {0} already exists.", evaluator.Id);
                Exceptions.Throw(new IMRUSystemException(msg), Logger);
            }

            if (NumberOfAllocatedEvaluators >= _totalExpectedEvaluators)
            {
                string msg = string.Format("Trying to add an additional evaluator {0}, but the total expected Evaluator number {1} has been reached. Ignoring new evaluator",
                    evaluator.Id, _totalExpectedEvaluators);
                Logger.Log(Level.Warning, msg);
                return;
            }

            _allocatedEvaluatorIds.Add(evaluator.Id);

            if (_masterEvaluatorId == null && NumberOfAllocatedEvaluators == _totalExpectedEvaluators)
            {
                string msg = string.Format("Added the last evaluator {0} but master evaluator is not added yet.", evaluator.Id);
                Exceptions.Throw(new IMRUSystemException(msg), Logger);
            }
        }

        /// <summary>
        /// Add master evaluator
        /// </summary>
        /// <param name="evaluator">Evaluator to add</param>
        internal void AddMasterEvaluator(IAllocatedEvaluator evaluator)
        {
            SetMasterEvaluatorId(evaluator.Id);
            _allocatedEvaluatorIds.Add(evaluator.Id);
        }

        /// <summary>
        /// Remove an Evaluator from allocated Evaluator collection by evaluator id.
        /// If the given evaluator id is not in allocated Evaluator collection, throw IMRUSystemException.
        /// </summary>
        /// <param name="evaluatorId"></param>
        internal void RemoveAllocatedEvaluator(string evaluatorId)
        {
            if (!IsAllocatedEvaluator(evaluatorId))
            {
                string msg = string.Format("The allocated evaluator to be removed {0} does not exist.", evaluatorId);
                Exceptions.Throw(new IMRUSystemException(msg), Logger);
            }
            _allocatedEvaluatorIds.Remove(evaluatorId);
        }

        /// <summary>
        /// Returns number of allocated Evaluators
        /// </summary>
        internal int NumberOfAllocatedEvaluators
        {
            get { return _allocatedEvaluatorIds.Count; }
        }

        /// <summary>
        /// Checks if the Evaluator with the specified id has been allocated
        /// </summary>
        /// <param name="evaluatorId"></param>
        /// <returns></returns>
        internal bool IsAllocatedEvaluator(string evaluatorId)
        {
            return _allocatedEvaluatorIds.Contains(evaluatorId);
        }

        /// <summary>
        /// Checks if all the expected Evaluators are allocated.
        /// </summary>
        internal bool AreAllEvaluatorsAllocated()
        {
            return _totalExpectedEvaluators == NumberOfAllocatedEvaluators && _masterEvaluatorId != null;
        }

        /// <summary>
        /// Records failed Evaluator
        /// Removes it from allocated Evaluator and adds it to the failed Evaluators collection
        /// If the evaluatorId is already in _failedEvaluators, throw IMRUSystemException
        /// </summary>
        /// <param name="evaluatorId"></param>
        internal void RecordFailedEvaluator(string evaluatorId)
        {
            RemoveAllocatedEvaluator(evaluatorId);
            if (_masterEvaluatorId != null && _masterEvaluatorId.Equals(evaluatorId))
            {
                _masterEvaluatorFailed = true;
            }
            _failedEvaluatorsCount++;
        }

        /// <summary>
        /// Checks if the number of failed Evaluators has reached allowed maximum number of evaluator failures
        /// </summary>
        internal bool ExceededMaximumNumberOfEvaluatorFailures()
        {
            return _failedEvaluatorsCount > AllowedNumberOfEvaluatorFailures;
        }

        /// <summary>
        /// Returns allowed maximum number of evaluator failures
        /// </summary>
        internal int AllowedNumberOfEvaluatorFailures
        {
            get { return _allowedNumberOfEvaluatorFailures; }
        }

        /// <summary>
        /// Reset failed Evaluator collection
        /// </summary>
        internal void ResetFailedEvaluators()
        {
            if (IsMasterEvaluatorFailed())
            {
                ResetMasterEvaluatorId();
            }
            _failedEvaluatorsCount = 0;
        }

        /// <summary>
        /// Sets master Evaluator id.
        /// Throws IMRUSystemException if evaulatorId is null or _masterEvaluatorId is not null.
        /// </summary>
        /// <param name="evaluatorId"></param>
        private void SetMasterEvaluatorId(string evaluatorId)
        {
            if (evaluatorId == null)
            {
                Exceptions.Throw(new IMRUSystemException("Master evaluatorId should not be null."), Logger);
            }

            if (_masterEvaluatorId != null)
            {
                string msg = string.Format("There is already a master evaluator {0}", _masterEvaluatorId);
                Exceptions.Throw(new IMRUSystemException(msg), Logger);
            }
            _masterEvaluatorId = evaluatorId;
        }

        /// <summary>
        /// Sets master Evaluator id to null.
        /// If the master Evaluator is already null, throw IMRUSystemException
        /// </summary>
        private void ResetMasterEvaluatorId()
        {
            if (_masterEvaluatorId == null)
            {
                Exceptions.Throw(new IMRUSystemException("Master evaluator is already null"), Logger);
            }
            _masterEvaluatorId = null;
            _masterEvaluatorFailed = false;
        }

        /// <summary>
        /// Checks if the evaluator id is the master evaluator id
        /// </summary>
        /// <param name="evaluatorId"></param>
        /// <returns></returns>
        internal bool IsMasterEvaluatorId(string evaluatorId)
        {
            if (_masterEvaluatorId != null)
            {
                return _masterEvaluatorId.Equals(evaluatorId);
            }
            return false;
        }

        /// <summary>
        /// Returns true if the master evaluator has been allocated otherwise false
        /// </summary>
        /// <returns></returns>
        internal bool IsMasterEvaluatorAllocated()
        {
            return _masterEvaluatorId != null;
        }

        /// <summary>
        /// Checks if the master Evaluator failed
        /// </summary>
        /// <returns></returns>
        internal bool IsMasterEvaluatorFailed()
        {
            return _masterEvaluatorFailed;
        }

        /// <summary>
        /// Returns number of failed mapper Evaluators
        /// </summary>
        /// <returns></returns>
        internal int NumberofFailedMappers()
        {
            if (IsMasterEvaluatorFailed())
            {
                return _failedEvaluatorsCount - 1;
            }
            return _failedEvaluatorsCount;
        }

        /// <summary>
        /// Returns number of missing Evaluators
        /// </summary>
        internal int NumberOfMissingEvaluators()
        {
            return _totalExpectedEvaluators - NumberOfAllocatedEvaluators;
        }
    }
}


text:
package com.push.mariobros.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.push.mariobros.MarioBros;

/**
 * Created by Rok on 23. 05. 2016.
 */
public class PlayScreen implements Screen {
    private MarioBros game;
    Texture texture;
    private OrthographicCamera gamecam;
    private Viewport gamePort;

    public PlayScreen(MarioBros game) {
        this.game = game;
        texture = new Texture("badlogic.jpg");
        gamecam = new OrthographicCamera();
        gamePort = new FitViewport(800, 480, gamecam);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        game.batch.setProjectionMatrix(gamecam.combined);
        game.batch.begin();
        game.batch.draw(texture, 0, 0);
        game.batch.end();
    }

    @Override
    public void resize(int width, int height) {
        gamePort.update(width, height);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }
}


text:
The OCaml source files for infer live here. The Makefile is
responsible for building them, together with jbuild.in.


text:
import { MethodEnum } from '@algolia/requester-common';
import { RequestOptions } from '@algolia/transporter';

import {
  PersonalizationClient,
  PersonalizationStrategy,
  SetPersonalizationStrategyResponse,
} from '..';

export const setPersonalizationStrategy = (base: PersonalizationClient) => {
  return (
    personalizationStrategy: PersonalizationStrategy,
    requestOptions?: RequestOptions
  ): Readonly<Promise<SetPersonalizationStrategyResponse>> => {
    return base.transporter.write(
      {
        method: MethodEnum.Post,
        path: '1/strategies/personalization',
        data: personalizationStrategy,
      },
      requestOptions
    );
  };
};


text:
package org.apache.samoa.instances;

import java.io.Serializable;

public class Range implements Serializable {

  //Only works for ranges "start-end"
  private int start = 0;
  private int end = 0;
  private int upperLimit = 0;
  private final String rangeText;

  public Range(String range) {
    this.rangeText = range;
    //this.setRange(range); //needs upperLimit
  }

  /**
   * Sets the range from a string representation.
   *
   * @param range the start and end string
   *
   */
  public void setRange(String range) {
    String single = range.trim();
    int hyphenIndex = range.indexOf('-');

    if (hyphenIndex > 0) {
      this.start = rangeSingle(range.substring(0, hyphenIndex));
      this.end = rangeSingle(range.substring(hyphenIndex + 1));
    } else {
      int number = rangeSingle(range);
      if (number >= 0) { // first n attributes
        this.start = 0;
        this.end = number;
      } else { // last n attributes
        this.start = this.upperLimit + number > 0 ? this.upperLimit + number : 0;
        this.end = this.upperLimit - 1;
      }
    }
  }

  /**
   * Translates a single string selection into it's internal 0-based
   * equivalent.
   *
   * @param single the string representing the selection (eg: 1 first last)
   * @return the number corresponding to the selected value
   */
  protected /*@pure@*/ int rangeSingle(/*@non_null@*/String singleSelection) {

    String single = singleSelection.trim();
    if (single.toLowerCase().equals("first")) {
      return 0;
    }
    if (single.toLowerCase().equals("last") || single.toLowerCase().equals("-1")) {
      return -1;
    }
    int index = Integer.parseInt(single);
    if (index >= 1) { //Non for negatives
      index--;
    }
    return index;
  }

  boolean isInRange(int value) {
    boolean ret = false;
    if (value >= start && value <= end) {
      ret = true;
    }
    return ret;
  }

  int getSelectionLength() {
    return end - start + 1;
  }

  public void setUpper(int attributeNumber) {
    this.upperLimit = attributeNumber;
    this.setRange(this.rangeText);
  }

  //JD
  public int getStart() {
    return start;
  }

  //JD

  public int getEnd() {
    return end;
  }

}


text:
  Critot est
       un village
       géographiquement positionné dans le département de Seine-Maritime en Haute-Normandie. Elle totalisait 506 habitants en 2008.

Si vous pensez emmenager à Critot, vous pourrez aisément trouver une maison à acheter.

À Critot, la valorisation moyenne à la vente d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 998 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.

À proximité de Critot sont localisées les communes de
Saint-Germain-sous-Cailly à 4 km, 266 habitants,
Rocquemont située à 2 km, 754 habitants,
Saint-Martin-Osmonville à 4 km, 1 061 habitants,
Estouteville-Écalles située à 5 km, 487 habitants,
Cailly située à 3 km, 736 habitants,
La Rue-Saint-Pierre située à 5 km, 573 habitants,
 entre autres. De plus, Critot est située à seulement 21 km de Rouen.

Le nombre de logements, à Critot, était réparti en 2011 en un appartements et 188 maisons soit
 un marché relativement équilibré.


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Inst Geol Geophys Bucarest Mem 31: 272.

#### Original name
null

### Remarks
null


text:
package main

import (
	"github.com/gorilla/mux"
	"net/http"
	"log"
	"time"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/bandwidth", BandwidthHandler)
	http.Handle("/", &LeServer{r})
	log.Println("Listening on port 8080")
	http.ListenAndServe(":8080", nil)
}

type LeServer struct {
	r *mux.Router
}

func (serv *LeServer) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	if origin := request.Header.Get("Origin"); origin != "" {
		response.Header().Set("Access-Control-Allow-Origin", origin)
		response.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
		response.Header().Set("Access-Control-Allow-Headers",
			"Accept, contentType, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
	}
	if request.Method == "OPTIONS" {
		return
	}
	serv.r.ServeHTTP(response, request)
}

func BandwidthHandler(response http.ResponseWriter, request *http.Request) {
	start := time.Now()
	if request.Method == "POST" {
		params := request.ParseForm()
		log.Println(request)
		log.Println(params)
		//log.Println(params["image"])
		response.Write([]byte("This is a server response"))
	} else {
		http.Error(response, "Can't touch this", http.StatusUnauthorized)
	}
	log.Println(request.URL)
	log.Println(request.Method)
	log.Println("Response took", time.Since(start), "seconds")
}


text:
'use strict';

const store = require('../schema/horizon_protocol').store;
const reql_options = require('./common').reql_options;
const writes = require('./writes');
const hz_v = writes.version_field;

const Joi = require('joi');
const r = require('rethinkdb');

const run = (raw_request, context, ruleset, metadata, send, done) => {
  const parsed = Joi.validate(raw_request.options, store);
  if (parsed.error !== null) { throw new Error(parsed.error.details[0].message); }

  const collection = metadata.collection(parsed.value.collection);
  const conn = metadata.connection();

  writes.retry_loop(parsed.value.data, ruleset, parsed.value.timeout,
    (rows) => // pre-validation, all rows
      r.expr(rows.map((row) => (row.id === undefined ? null : row.id)))
        .map((id) => r.branch(id.eq(null), null, collection.table.get(id)))
        .run(conn, reql_options),
    (row, info) => writes.validate_old_row_optional(context, row, info, row, ruleset),
    (rows) => // write to database, all valid rows
      r.expr(rows)
        .forEach((new_row) =>
          r.branch(new_row.hasFields('id'),
                   collection.table.get(new_row('id')).replace((old_row) =>
                       r.branch(
                         old_row.eq(null),
                         r.branch(
                           // Error if we were expecting the row to exist
                           new_row.hasFields(hz_v),
                           r.error(writes.invalidated_msg),

                           // Otherwise, insert the row
                           writes.apply_version(new_row, 0)
                         ),
                         r.branch(
                           // The row may have changed from the expected version
                           r.and(new_row.hasFields(hz_v),
                                 old_row(hz_v).default(-1).ne(new_row(hz_v))),
                           r.error(writes.invalidated_msg),

                           // Otherwise, we can safely overwrite the row
                           writes.apply_version(new_row, old_row(hz_v).default(-1).add(1))
                         )
                       ), { returnChanges: 'always' }),

                   // The new row does not have an id, so we insert it with an autogen id
                   collection.table.insert(writes.apply_version(new_row, 0),
                                           { returnChanges: 'always' })))
        .run(conn, reql_options)
  ).then(done).catch(done);
};

module.exports = { run };


text:
package eus.ixa.ixa.pipe.ml.resources;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.model.ArtifactSerializer;
import opennlp.tools.util.model.SerializableArtifact;

/**
 *
 * Class to load a {@code PredicateContext} resource containing predicate and
 * window feature information about that predicate. The format of the file
 * contains: predicate, context predicate and region mark in that order. For
 * example: set\tbeen set .\t1
 *
 * @author ragerri
 * @version 2016/07/05
 *
 */
public class PredicateContext implements SerializableArtifact {

  private static final Pattern tabPattern = Pattern.compile("\t");
  /**
   * Turkish capital letter I with dot.
   */
  public static final Pattern dotInsideI = Pattern.compile("\u0130",
      Pattern.UNICODE_CHARACTER_CLASS);

  public static class PredicateContextSerializer
      implements ArtifactSerializer<PredicateContext> {

    @Override
    public PredicateContext create(final InputStream in)
        throws IOException, InvalidFormatException {
      return new PredicateContext(in);
    }

    @Override
    public void serialize(final PredicateContext artifact,
        final OutputStream out) throws IOException {
      artifact.serialize(out);
    }
  }

  List<List<String>> predContexts = new ArrayList<List<String>>();

  public List<List<String>> getPredicateContext() {
    return this.predContexts;
  }

  public PredicateContext(final InputStream in) throws IOException {

    final BufferedReader breader = new BufferedReader(
        new InputStreamReader(in, Charset.forName("UTF-8")));
    String line;
    while ((line = breader.readLine()) != null) {
      final String[] lineArray = tabPattern.split(line);
      populateLists(lineArray);
    }
  }

  private void populateLists(final String[] lineArray) {
    if (lineArray.length == 3) {
      final String normalizedToken = dotInsideI.matcher(lineArray[0])
          .replaceAll("i");
      final String normalizedContext = dotInsideI.matcher(lineArray[1])
          .replaceAll("i");
      final List<String> tokenValues = new ArrayList<>();
      tokenValues.add(normalizedToken);
      tokenValues.add(normalizedContext);
      tokenValues.add(lineArray[2]);
      this.predContexts.add(tokenValues);
    }
  }

  /**
   * Serialize the dictionary to original corpus format
   *
   * @param out
   *          the output stream
   * @throws IOException
   *           if io problems
   */
  public void serialize(final OutputStream out) throws IOException {
    final Writer writer = new BufferedWriter(new OutputStreamWriter(out));

    for (final List<String> entry : this.predContexts) {
      writer.write(
          entry.get(0) + "\t" + entry.get(1) + "\t" + entry.get(2) + "\n");
    }
    writer.flush();
  }

  @Override
  public Class<?> getArtifactSerializerClass() {
    return PredicateContextSerializer.class;
  }
}