text:
/*
* Package com.rust.reflect
* FileName: DiskClassLoader
* Author:   Rust
* Date:     2017/6/23 11:18
*/
package com.rust.reflect;

import java.io.*;

/**
 * FileName:    DiskClassLoader
 * Author:      Rust
 * Date:        2017/6/23
 * Description:
 */
public class DiskClassLoader extends ClassLoader {
    private String libPath;

    public DiskClassLoader(String $path) {
        libPath = $path;
    }

    public DiskClassLoader() {

    }

    @Override

    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String fileName = getFileName(name);
        File file = new File(libPath, fileName);

        try {
            FileInputStream fileInputStream = new FileInputStream(file);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int len = 0;
            while ((len = fileInputStream.read()) != -1) {
                byteArrayOutputStream.write(len);
            }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            fileInputStream.close();
            byteArrayOutputStream.close();
            return defineClass(fileName, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.findClass(name);
    }

    public String getFileName(String name) {
        int index = name.lastIndexOf(name);
        if (-1 == index) {
            return name + ".class";
        } else {
            return name.substring(index) + ".class";
        }
    }
}


text: Javascript and CSS anims that are triggered as you scroll down

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>admin-linux: _cookbook.func_param Namespace Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />

admin-linux
    0.0.0

Admin Linux

Main Page

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Packages

Package Functions

 All Classes Namespaces Files Functions Variables

_cookbook

func_param

Functions

_cookbook.func_param Namespace Reference

Functions

def 	func_default_value

def 	func_unpack_args

def 	func_vargs

Function Documentation

          def _cookbook.func_param.func_default_value
          (

          arg,

          L = None

          )

Default Values of Function Arguments.

The default values are evaluated at the point of function definition in
the defining scope only once.

**NOTE**: When the default is a mutable object such as a list, dictionary,
or instances of most classes, and if you don't want the default to be
shared between subsequent calls, you can write the function like this
instead.

Definition at line 44 of file func_param.py.

          def _cookbook.func_param.func_unpack_args
          (

          arg1,

          arg2

          )

Unpack arguments from dictionary or tuple, list.

To use it,

    >>> mydict = {'arg1': 1, 'arg2': 2}

    >>> func_unpack_args(**mydict)

    >>> mytuple = ("a", "b")

    >>> func_unpack_args(*mytuple)

Definition at line 61 of file func_param.py.

          def _cookbook.func_param.func_vargs
          (

          arg,

          other = 'o',

          vargs,

          args

          )

Variable Length Arguments List of Function.

1. `*vargs` must be before `**args`.

2. Any formal parameters which occur after the `*vargs` parameter are
   keyword-only arguments, meaning that they can only be used as keywords
   rather than positional arguments.

Definition at line 78 of file func_param.py.

<address class="footer">
Generated on Wed Sep 17 2014 14:49:33 for admin-linux by

 1.8.6
</address>


text:
from mock import patch
import os
import unittest

from ocw.dataset import Dataset, Bounds
from ocw.evaluation import Evaluation
import ocw.metrics as metrics
import configuration_writer as writer

import datetime as dt
import numpy as np
import yaml

class TestLocalDatasetExportGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.origin = {
            'source': 'local',
            'path': '/a/fake/path.nc',
            'lat_name': 'a lat name',
            'lon_name': 'a lon name',
            'time_name': 'a time name',
            'elevation_index': 2
        }
        self.name = 'name'

        self.dataset = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            origin=self.origin,
            name=self.name
        )

        self.exported_info = writer.generate_dataset_config(self.dataset)

    def test_proper_data_source_export(self):
        self.assertTrue('data_source' in self.exported_info)
        self.assertEqual(self.exported_info['data_source'],
                         self.origin['source'])

    def test_proper_path_export(self):
        self.assertEqual(self.exported_info['path'], self.origin['path'])

    def test_proper_variable_name_export(self):
        self.assertEqual(self.exported_info['variable'], self.variable)

    def test_proper_units_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['units'],
                         self.units)

    def test_proper_lats_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['lat_name'],
                         self.origin['lat_name'])

    def test_proper_lons_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['lon_name'],
                         self.origin['lon_name'])

    def test_proper_times_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['time_name'],
                         self.origin['time_name'])

    def test_proper_dataset_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['name'],
                         self.name)

    def test_proper_elevation_index_export(self):
        self.assertEqual(self.exported_info['optional_args']['elevation_index'],
                         self.origin['elevation_index'])

class TestRCMEDDatasetExportGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.origin = {
            'source': 'rcmed',
            'dataset_id': 4,
            'parameter_id': 14
        }
        self.name = 'name'

        self.dataset = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            origin=self.origin,
            name=self.name
        )

        self.exported_info = writer.generate_dataset_config(self.dataset)

    def test_proper_data_source_export(self):
        self.assertTrue('data_source' in self.exported_info)
        self.assertEqual(self.exported_info['data_source'],
                         self.origin['source'])

    def test_proper_dataset_id_export(self):
        self.assertEqual(self.exported_info['dataset_id'],
                         self.origin['dataset_id'])

    def test_proper_parameter_id_export(self):
        self.assertEqual(self.exported_info['parameter_id'],
                         self.origin['parameter_id'])

    def test_proper_min_lat_export(self):
        self.assertEqual(self.exported_info['min_lat'], min(self.lats))

    def test_proper_max_lat_export(self):
        self.assertEqual(self.exported_info['max_lat'], max(self.lats))

    def test_proper_min_lon_export(self):
        self.assertEqual(self.exported_info['min_lon'], min(self.lons))

    def test_proper_max_lon_export(self):
        self.assertEqual(self.exported_info['max_lon'], max(self.lons))

    def test_proper_min_time_export(self):
        self.assertEqual(self.exported_info['start_time'], str(min(self.times)))

    def test_proper_max_time_export(self):
        self.assertEqual(self.exported_info['end_time'], str(max(self.times)))

    def test_proper_dataset_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['name'],
                         self.name)

    def test_proper_units_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['units'],
                         self.units)

class TestESGFDatasetExportGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.origin = {
            'source': 'esgf',
            'dataset_id': 'esgf dataset id',
            'variable': 'var'
        }
        self.name = 'name'

        self.dataset = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            origin=self.origin,
            name=self.name
        )

        self.exported_info = writer.generate_dataset_config(self.dataset)

    def test_proper_data_source_export(self):
        self.assertTrue('data_source' in self.exported_info)
        self.assertEqual(self.exported_info['data_source'],
                     self.origin['source'])

    def test_proper_dataset_id_export(self):
        self.assertEqual(self.exported_info['dataset_id'],
                         self.origin['dataset_id'])

    def test_proper_variable_export(self):
        self.assertEqual(self.exported_info['variable'],
                         self.origin['variable'])

    def test_proper_dummy_username_export(self):
        self.assertTrue('esgf_username' in self.exported_info)

    def test_proper_dummy_password_export(self):
        self.assertTrue('esgf_password' in self.exported_info)

    def test_proper_dataset_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['name'],
                         self.name)

    def test_proper_units_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['units'],
                         self.units)

class TestDAPDatasetExportGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.origin = {
            'source': 'dap',
            'url': 'a fake url',
        }
        self.name = 'name'

        self.dataset = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            origin=self.origin,
            name=self.name
        )

        self.exported_info = writer.generate_dataset_config(self.dataset)

    def test_proper_data_source_export(self):
        self.assertTrue('data_source' in self.exported_info)
        self.assertEqual(self.exported_info['data_source'],
                     self.origin['source'])

    def test_proper_url_export(self):
        self.assertEqual(self.exported_info['url'],
                         self.origin['url'])

    def test_proper_dataset_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['name'],
                         self.name)

    def test_proper_units_name_export(self):
        self.assertEqual(self.exported_info['optional_args']['units'],
                         self.units)

class TestDatasetExportFromEvaluation(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.name = 'name'

        self.local_origin = {
            'source': 'local',
            'path': '/a/fake/path.nc',
            'lat_name': 'a lat name',
            'lon_name': 'a lon name',
            'time_name': 'a time name',
            'elevation_index': 2
        }

        self.rcmed_origin = {
            'source': 'rcmed',
            'dataset_id': 4,
            'parameter_id': 14
        }

        self.esgf_origin = {
            'source': 'esgf',
            'dataset_id': 'esgf dataset id',
            'variable': 'var'
        }

        self.dap_origin = {
            'source': 'dap',
            'url': 'a fake url',
        }

        self.local_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.local_origin
        )

        self.rcmed_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.rcmed_origin
        )

        self.esgf_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.esgf_origin
        )

        self.dap_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.dap_origin
        )

        self.evaluation = Evaluation(
            self.local_ds,
            [self.rcmed_ds, self.esgf_ds, self.dap_ds],
            []
        )

    def test_contains_only_reference_dataset(self):
        new_eval = Evaluation(self.local_ds, [], [])
        out = writer.generate_dataset_information(new_eval)

        self.assertTrue('reference' in out)
        self.assertTrue('targets' not in out)

    def test_contains_only_target_datasets(self):
        new_eval = Evaluation(None, [self.local_ds], [])
        out = writer.generate_dataset_information(new_eval)

        self.assertTrue('reference' not in out)
        self.assertTrue('targets' in out)

    def test_proper_reference_dataset_export(self):
        out = writer.generate_dataset_information(self.evaluation)

        self.assertTrue('reference' in out)
        self.assertTrue(out['reference']['data_source'] == 'local')

    def test_proper_target_datasets_export(self):
        out = writer.generate_dataset_information(self.evaluation)

        self.assertTrue('targets' in out)
        self.assertTrue(type(out['targets']) == type(list()))
        self.assertTrue(len(out['targets']) == 3)

class TestMetricExportGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.bias = metrics.Bias()
        self.tmp_std_dev = metrics.TemporalStdDev()
        loaded_metrics = [self.bias, self.tmp_std_dev]

        self.evaluation = Evaluation(None, [], loaded_metrics)

    def test_proper_export_format(self):
        out = writer.generate_metric_information(self.evaluation)

        self.assertTrue(type(out) == type(list()))

        for name in out:
            self.assertTrue(type(name) == type(str()))

    def test_proper_metric_name_export(self):
        out = writer.generate_metric_information(self.evaluation)

        self.assertTrue(self.bias.__class__.__name__ in out)
        self.assertTrue(self.tmp_std_dev.__class__.__name__ in out)

    def test_empty_metrics_in_evaluation(self):
        new_eval = Evaluation(None, [], [])
        out = writer.generate_metric_information(new_eval)

        self.assertTrue(type(out) == type(list()))
        self.assertTrue(len(out) == 0)

class TestEvaluationSettingsGeneration(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array(range(-10, 10, 1))
        self.lons = np.array(range(-20, 20, 1))
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(9600))
        self.values = flat_array.reshape(12, 20, 40)

        self.dataset = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
        )

        self.evaluation = Evaluation(self.dataset, [], [])

    def test_default_data_return(self):
        new_eval = Evaluation(None, [], [])
        default_output = {
            'temporal_time_delta': 999,
            'spatial_regrid_lats': (-90, 90, 1),
            'spatial_regrid_lons': (-180, 180, 1),
            'subset': [-90, 90, -180, 180, "1500-01-01", "2500-01-01"],
        }

        out = writer.generate_evaluation_information(new_eval)

        self.assertEquals(default_output, out)

    def test_handles_only_reference_dataset(self):
        new_eval = Evaluation(self.dataset, [], [])

        default_output = {
            'temporal_time_delta': 999,
            'spatial_regrid_lats': (-90, 90, 1),
            'spatial_regrid_lons': (-180, 180, 1),
            'subset': [-90, 90, -180, 180, "1500-01-01", "2500-01-01"],
        }

        out = writer.generate_evaluation_information(new_eval)

        self.assertNotEquals(default_output, out)

    def test_handles_only_target_dataset(self):
        new_eval = Evaluation(None, [self.dataset], [])

        default_output = {
            'temporal_time_delta': 999,
            'spatial_regrid_lats': (-90, 90, 1),
            'spatial_regrid_lons': (-180, 180, 1),
            'subset': [-90, 90, -180, 180, "1500-01-01", "2500-01-01"],
        }

        out = writer.generate_evaluation_information(new_eval)

        self.assertNotEquals(default_output, out)

    def test_daily_temporal_bin(self):
        new_times = np.array([dt.datetime(2000, 1, 1, x) for x in range(1, 13)])

        dataset = Dataset(
            self.lats,
            self.lons,
            new_times,
            self.values,
        )
        new_eval = Evaluation(dataset, [], [])

        out = writer.generate_evaluation_information(new_eval)

        self.assertEquals(out['temporal_time_delta'], 1)

    def test_monthly_temporal_bin(self):
        out = writer.generate_evaluation_information(self.evaluation)

        self.assertEquals(out['temporal_time_delta'], 31)

    def test_yearly_temporal_bin(self):
        new_times = np.array([dt.datetime(2000 + x, 1, 1) for x in range(1, 13)])

        dataset = Dataset(
            self.lats,
            self.lons,
            new_times,
            self.values,
        )
        new_eval = Evaluation(dataset, [], [])

        out = writer.generate_evaluation_information(new_eval)

        self.assertEquals(out['temporal_time_delta'], 366)

    def test_spatial_regrid_lats(self):
        out = writer.generate_evaluation_information(self.evaluation)

        lats = out['spatial_regrid_lats']
        lat_range = np.arange(lats[0], lats[1], lats[2])

        self.assertTrue(np.array_equal(lat_range, self.lats))

    def test_spatial_regrid_lons(self):
        out = writer.generate_evaluation_information(self.evaluation)

        lons = out['spatial_regrid_lons']
        lat_range = np.arange(lons[0], lons[1], lons[2])

        self.assertTrue(np.array_equal(lat_range, self.lons))

    def test_subset_with_single_dataset(self):
        out = writer.generate_evaluation_information(self.evaluation)
        subset = out['subset']

        ds_lat_min, ds_lat_max, ds_lon_min, ds_lon_max = self.dataset.spatial_boundaries()
        start, end = self.dataset.time_range()

        self.assertEqual(ds_lat_min, subset[0])
        self.assertEqual(ds_lat_max, subset[1])
        self.assertEqual(ds_lon_min, subset[2])
        self.assertEqual(ds_lon_max, subset[3])
        self.assertEquals(str(start), subset[4])
        self.assertEquals(str(end), subset[5])

    def test_subset_with_multiple_datasets(self):
        new_ds = Dataset(
            np.arange(0, 20, 1),
            self.lons,
            self.times,
            self.values
        )
        new_eval = Evaluation(self.dataset, [new_ds], [])

        out = writer.generate_evaluation_information(new_eval)
        subset = out['subset']

        ds_lat_min, ds_lat_max, ds_lon_min, ds_lon_max = self.dataset.spatial_boundaries()
        start, end = self.dataset.time_range()

        self.assertEqual(ds_lat_min, subset[0])
        # Check that we actually used the different max lat value that we
        # created by adding 'new_ds'.
        self.assertEqual(max(new_ds.lats), subset[1])
        self.assertEqual(ds_lon_min, subset[2])
        self.assertEqual(ds_lon_max, subset[3])
        self.assertEquals(str(start), subset[4])
        self.assertEquals(str(end), subset[5])

class FullExportTest(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.lats = np.array([10, 12, 14, 16, 18])
        self.lons = np.array([100, 102, 104, 106, 108])
        self.times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)])
        flat_array = np.array(range(300))
        self.values = flat_array.reshape(12, 5, 5)
        self.variable = 'var'
        self.units = 'units'
        self.name = 'name'

        self.local_origin = {
            'source': 'local',
            'path': '/a/fake/path.nc',
            'lat_name': 'a lat name',
            'lon_name': 'a lon name',
            'time_name': 'a time name',
            'elevation_index': 2
        }

        self.rcmed_origin = {
            'source': 'rcmed',
            'dataset_id': 4,
            'parameter_id': 14
        }

        self.esgf_origin = {
            'source': 'esgf',
            'dataset_id': 'esgf dataset id',
            'variable': 'var'
        }

        self.dap_origin = {
            'source': 'dap',
            'url': 'a fake url',
        }

        self.local_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.local_origin
        )

        self.rcmed_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.rcmed_origin
        )

        self.esgf_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.esgf_origin
        )

        self.dap_ds = Dataset(
            self.lats,
            self.lons,
            self.times,
            self.values,
            variable=self.variable,
            units=self.units,
            name=self.name,
            origin=self.dap_origin
        )

        self.subregions = [
            Bounds(-10, 10, -20, 20),
            Bounds(-5, 5, -15, 15)
        ]

        self.evaluation = Evaluation(
            self.local_ds,
            [self.rcmed_ds, self.esgf_ds, self.dap_ds],
            [metrics.Bias(), metrics.TemporalStdDev()],
            subregions=self.subregions
        )

    @classmethod
    def tearDownClass(self):
        if os.path.isfile('/tmp/test_config.yaml'):
            os.remove('/tmp/test_config.yaml')

    def test_full_export(self):
        file_path = '/tmp/test_config.yaml'
        writer.export_evaluation_to_config(
            self.evaluation,
            file_path=file_path
        )

        self.assertTrue(os.path.isfile(file_path))

    def test_proper_metric_export(self):
        file_path = '/tmp/test_config.yaml'
        writer.export_evaluation_to_config(
            self.evaluation,
            file_path=file_path
        )

        data = yaml.load(open(file_path, 'r'))

        self.assertTrue('metrics' in data)
        self.assertTrue(type(data['metrics']) == type(list()))

        for metric in self.evaluation.metrics:
            self.assertTrue(metric.__class__.__name__ in data['metrics'])

        for metric in self.evaluation.unary_metrics:
            self.assertTrue(metric.__class__.__name__ in data['metrics'])

        total_eval_metrics = (
            len(self.evaluation.metrics) +
            len(self.evaluation.unary_metrics)
        )

        self.assertTrue(total_eval_metrics, len(data['metrics']))

    def test_proper_dataset_export(self):
        file_path = '/tmp/test_config.yaml'
        writer.export_evaluation_to_config(
            self.evaluation,
            file_path=file_path
        )

        data = yaml.load(open(file_path, 'r'))

        self.assertTrue('datasets' in data)
        self.assertTrue('reference' in data['datasets'])
        self.assertTrue('targets' in data['datasets'])

        self.assertAlmostEqual(
            writer.generate_dataset_information(self.evaluation),
            data['datasets']
        )

    def test_proper_evaluation_setting_export(self):
        file_path = '/tmp/test_config.yaml'
        writer.export_evaluation_to_config(
            self.evaluation,
            file_path=file_path
        )

        data = yaml.load(open(file_path, 'r'))

        self.assertTrue('evaluation' in data)
        self.assertTrue('temporal_time_delta' in data['evaluation'])
        self.assertTrue('spatial_regrid_lats' in data['evaluation'])
        self.assertTrue('spatial_regrid_lons' in data['evaluation'])
        self.assertTrue('subset' in data['evaluation'])

        self.assertAlmostEqual(
            writer.generate_evaluation_information(self.evaluation),
            data['evaluation']
        )

    def test_proper_subregion_export(self):
        file_path = '/tmp/test_config.yaml'
        writer.export_evaluation_to_config(
            self.evaluation,
            file_path=file_path
        )

        data = yaml.load(open(file_path, 'r'))

        self.assertTrue('subregions' in data)

        first_bounds = [
            self.subregions[0].lat_min,
            self.subregions[0].lat_max,
            self.subregions[0].lon_min,
            self.subregions[0].lon_max,
        ]
        second_bounds = [
            self.subregions[1].lat_min,
            self.subregions[1].lat_max,
            self.subregions[1].lon_min,
            self.subregions[1].lon_max,
        ]

        self.assertEqual(first_bounds, data['subregions'][0])
        self.assertEqual(second_bounds, data['subregions'][1])


text:
"use strict";

function render(item) {
	return React.createElement("div", {
		className: 'component__title'
	}, "The ", item.title, " ");
}


text:
<?php
namespace Concrete\Core\Application;
use \Concrete\Core\Foundation\Service\Provider as ServiceProvider;

class ApplicationServiceProvider extends ServiceProvider {

	public function register() {
		$singletons = array(
			'helper/concrete/asset_library' => '\Concrete\Core\Application\Service\FileManager',
			'helper/concrete/file_manager' => '\Concrete\Core\Application\Service\FileManager',
			'helper/concrete/composer' => '\Concrete\Core\Application\Service\Composer',
			'helper/concrete/dashboard' => '\Concrete\Core\Application\Service\Dashboard',
			'helper/concrete/dashboard/sitemap' => '\Concrete\Core\Application\Service\Dashboard\Sitemap',
			'helper/concrete/ui' => '\Concrete\Core\Application\Service\UserInterface',
			'helper/concrete/ui/menu' => '\Concrete\Core\Application\Service\UserInterface\Menu',
			'helper/concrete/ui/help' => '\Concrete\Core\Application\Service\UserInterface\Help',
			'helper/concrete/upgrade' => '\Concrete\Core\Application\Service\Upgrade',
			'helper/concrete/urls' => '\Concrete\Core\Application\Service\Urls',
			'helper/concrete/user' => '\Concrete\Core\Application\Service\User',
			'helper/concrete/validation' => '\Concrete\Core\Application\Service\Validation',
			'helper/rating' => '\Concrete\Attribute\Rating\Service',
            'helper/pagination' => '\Concrete\Core\Legacy\Pagination',

			'help' => '\Concrete\Core\Application\Service\UserInterface\Help',
			'help/core' => '\Concrete\Core\Application\Service\UserInterface\Help\CoreManager',
			'help/dashboard' => '\Concrete\Core\Application\Service\UserInterface\Help\DashboardManager',
			'help/block_type' => '\Concrete\Core\Application\Service\UserInterface\Help\BlockTypeManager',
			'help/panel' => '\Concrete\Core\Application\Service\UserInterface\Help\PanelManager'
		);

		foreach($singletons as $key => $value) {
			$this->app->singleton($key, $value);
		}

        $this->app->bind('error', 'Concrete\Core\Error\Error');

		/**
		 * @deprecated
		 */
		$this->app->singleton('helper/concrete/avatar', '\Concrete\Core\Legacy\Avatar');
	}

}


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button,
} from 'react-native';

import {
  StackNavigator,
} from 'react-navigation';

export default class Preferences extends Component {

  static navigationOptions = {
    title: 'Preferences',
    header: false
  };

  render() {
    const { navigate } = this.props.navigation;

    return (
      <View>
        <Text
          style={{
            fontSize: 42,
          }}
        >
          User Preferences
        </Text>
        <Button
          onPress={() => navigate('Main')}
          title="Curious about Learning?"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  fontStyle: {
    fontSize: 42,
  },
});

AppRegistry.registerComponent('Preferences', () => App);


text:
<?xml version="1.0" encoding="UTF-8"?>
<IndexDescriptor version="1.0" xmlns="http://statsbiblioteket.dk/summa/2008/IndexDescriptor">

    <groups>
        <group name="au">
            <field ref="author_person"/>
        </group>
        <group name="ti">
            <field ref="main_titel"/>
        </group>
        <group name="su">
            <field ref="lsu_oai"/>
        </group>
        <group name="lma">
            <field ref="lma_long"/>
        </group>
    </groups>

    <fields>
        <!-- TODO: Check how defaultType="token" works -->
        <field name="token" indexed="true" inFreeText="true" required="true"/>
        <!-- TODO: Consider compression of shortformat -->
        <field name="shortformat" parent="stored" indexed="false" inFreeText="false" required="true"/>
        <field name="author_person" parent="token" multiValued="true" queryBoost="10"/>
        <field name="main_titel" parent="token" queryBoost="10"/>
        <field name="lsu_oai" parent="keyword" multiValued="false" queryBoost="10"/>
        <field name="no" parent="token" queryBoost="7"/>
        <field name="ma_long" parent="token" multiValued="true"/>
        <field name="lma_long" parent="keyword"/>
        <field name="sort_title" parent="keyword" sortLocale="da"/>
    </fields>

    <defaultSearchFields>
        <field ref="freetext"/>
        <field ref="au"/>
        <field ref="ti"/>
        <field ref="su"/>
        <field ref="lma"/>
    </defaultSearchFields>

    <!-- Used by MoreLikeThis in LucenesearchNode -->
    <lu:moreLikethisFields xmlns:lu="http://statsbiblioteket.dk/summa/2009/LuceneIndexDescriptor">
        <field ref="freetext"/>
        <field ref="title"/>
    </lu:moreLikethisFields>
</IndexDescriptor>
<!--

Old style descriptor

<Index:document xmlns:Index="http://statsbiblioteket.dk/2004/Index" Index:defaultBoost="1" Index:defaultType="token" Index:defaultFreetext="true" Index:defaultSuggest="false" Index:defaultGroup="false" Index:langAutogroup="true" Index:resolver="fagreferent" Index:id="jh@example.com">
  <Index:fields>
    <Index:field Index:name="shortformat" Index:type="stored" Index:freetext="false"><![CDATA[<shortrecord><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description><dc:title>Fagekspert i urukaisk</dc:title><dc:creator>Jens Hansen</dc:creator><dc:type xml:lang="da">person</dc:type><dc:type xml:lang="en">person</dc:type><dc:identifier>jh@example.com</dc:identifier></rdf:Description></rdf:RDF></shortrecord>]]></Index:field>
    <Index:group Index:name="au" Index:navn="fo" Index:suggest="true">
      <Index:field Index:name="author_person" Index:repeat="true" Index:navn="pe" Index:type="token" Index:boostFactor="10">Jens Hansen</Index:field>
    </Index:group>
    <Index:group Index:name="ti" Index:navn="ti" Index:suggest="true">
      <Index:field Index:repeat="true" Index:name="main_titel" Index:navn="ht" Index:type="token" Index:boostFactor="10">Fagekspert i urukaisk</Index:field>
    </Index:group>
    <Index:field Index:name="sort_title" Index:navn="sort_titel" Index:sortLocale="da" Index:type="keyword">Fagekspert i urukaisk</Index:field>
    <Index:group Index:name="su" Index:navn="em" Index:suggest="true">
      <Index:field Index:boostFactor="10" Index:type="keyword" Index:navn="lsu_oai" Index:name="lsu_oai" Index:repeat="false">Urukai</Index:field>
      <Index:field Index:boostFactor="10" Index:type="keyword" Index:navn="lsu_oai" Index:name="lsu_oai" Index:repeat="false">urukaisk</Index:field>
      <Index:field Index:boostFactor="10" Index:type="keyword" Index:navn="lsu_oai" Index:name="lsu_oai" Index:repeat="false">Kaslafniansk myrtologi</Index:field>
      <Index:field Index:boostFactor="10" Index:type="keyword" Index:navn="lsu_oai" Index:name="lsu_oai" Index:repeat="false">palæontofantisme</Index:field>
      <Index:field Index:boostFactor="10" Index:type="keyword" Index:navn="lsu_oai" Index:name="lsu_oai" Index:repeat="false">humus</Index:field>
    </Index:group>
    <Index:field Index:repeat="true" Index:name="no" Index:navn="no" Index:type="token" Index:boostFactor="7">Jeg er cand. phil. i urukaisk og besvarer spørgsmål og hjælper med at finde bøger, kumpolumpos, deep-pan-humus og  andre informationskilder indenfor fagområderne ukuraisk og kaslafnisk myrtologi.
</Index:field>
  </Index:fields>
  <Index:field Index:repeat="true" Index:name="ma_long" Index:navn="ma_lang" Index:type="token">person</Index:field>
  <Index:group Index:freetext="false" Index:navn="lma" Index:name="lma">
    <Index:field Index:repeat="false" Index:name="lma_long" Index:navn="lma_lang" Index:type="keyword">fagekspert</Index:field>
  </Index:group>
</Index:document>
-->


text:
<?php

namespace Gestion\GestionBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Gestion\GestionBundle\Entity\Sites;
use Gestion\GestionBundle\Form\SitesType;

/**
 * Sites controller.
 *
 */
class SitesController extends Controller {

    /**
     * Lists all Sites entities.
     *
     */
    public function indexAction(Request $request) {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('GestionBundle:Sites')->findAll();
        $entity = new Sites();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sites_show', array('id' => $entity->getId())));
        }
        return $this->render('GestionBundle:Sites:index.html.twig', array(
                    'entities' => $entities,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Creates a new Sites entity.
     *
     */
    public function createAction(Request $request) {
        $entity = new Sites();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sites_show', array('id' => $entity->getId())));
        }

        return $this->render('GestionBundle:Sites:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Sites entity.
     *
     * @param Sites $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Sites $entity) {
        $form = $this->createForm(new SitesType(), $entity, array(
            'action' => $this->generateUrl('sites_create'),
            'method' => 'POST',
        ));

        return $form;
    }

    /**
     * Displays a form to create a new Sites entity.
     *
     */
    public function newAction() {
        $entity = new Sites();
        $form = $this->createCreateForm($entity);

        return $this->render('GestionBundle:Sites:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Sites entity.
     *
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GestionBundle:Sites')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sites entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('GestionBundle:Sites:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Sites entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GestionBundle:Sites')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sites entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('GestionBundle:Sites:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Creates a form to edit a Sites entity.
     *
     * @param Sites $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(Sites $entity) {
        $form = $this->createForm(new SitesType(), $entity, array(
            'action' => $this->generateUrl('sites_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        return $form;
    }

    /**
     * Edits an existing Sites entity.
     *
     */
    public function updateAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GestionBundle:Sites')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Sites entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('sites_edit', array('id' => $id)));
        }

        return $this->render('GestionBundle:Sites:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Sites entity.
     *
     */
    public function deleteAction(Request $request, $id) {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('GestionBundle:Sites')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Sites entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('sites'));
    }
    public function effacerSiteAction(Request $request, $id) {

            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('GestionBundle:Sites')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Sites entity.');
            }

            $em->remove($entity);
            $em->flush();

            $response = new JsonResponse();

            return $response->setData(array('info' => 'Client effacée'));
        }
    /**
     * Creates a form to delete a Sites entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id) {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('sites_delete', array('id' => $id)))
                        ->setMethod('DELETE')
                        //->add('submit', 'submit', array('label' => 'Delete'))
                        ->getForm()
        ;
    }

}


text:
<?xml version='1.0' encoding='utf-8'?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="0bf2830c-cc8e-4584-b7e9-91f7858aac95">
    <WebsiteUrl />
    <UserAgent />
    <UserNotes />
    <LastFileSize>28244941</LastFileSize>
    <LastFileDate>2014-08-17T17:27:32.1341491</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>RegularExpression</VariableType>
            <Regex>http://download\.gna\.org/freeciv/packages/windows/Freeciv-([\d\.]+)-win32-gtk2-setup\.exe</Regex>
            <Url>http://www.freeciv.org/download.html</Url>
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation>C:\Chocolatey\_work\Freeciv-2.4.3-win32-gtk2-setup.exe</PreviousLocation>
    <DeletePreviousFile>true</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2014-08-17T17:27:32.1341491</LastUpdated>
    <TargetPath>C:\Chocolatey\_work\</TargetPath>
    <FixedDownloadUrl>http://download.gna.org/freeciv/packages/windows/Freeciv-{version}-win32-gtk2-setup.exe</FixedDownloadUrl>
    <Name>freeciv</Name>
  </ApplicationJob>
</Jobs>


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Mecura Health</title>
        <link rel="icon" href="img/favicon.png" type="image/x-icon">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/nav.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/animate.css">
        <link rel="stylesheet" href="css/phy.css">
        <link href="https://fonts.googleapis.com/css?family=Montserrat|Zilla+Slab|Finger+Paint" rel="stylesheet">
        <link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#Main-nav">

          </button>

Mecura Health

Home

Services

Doctors

Careers

About

Mecura Child

Physiotherapy

                <button class="btn btn-success">Book Now</button>

Physiotherapy

                <button class="btn btn-success">Book Now</button>

Physiotherapy

                <button class="btn btn-success">Book Now</button>

Physiotherapy

                <button class="btn btn-success">Book Now</button>

            Previous

            Next

What is Physiotherapy?

Physiotherapy is a recognized health care discipline that specializes in the assessment, treatment and maintenance of the human body's movement and function.

Physiotherapists integrate the use of many therapeutic modalities with their expertise in exercise and movement rehabilitation to create the optimal plan to meet your therapeutic goals.

Mecura eClinic focuses on providing physiotherapeutic interventions and exercise programs to people of all ages presenting with any type of orthopaedic condition, which is any condition related to bone, muscle and joint problems.

What can I expect at my first physiotherapy visit?

On your initial visit, your physiotherapist will assess your specific condition. A detailed history of your injury will be taken and a full musculoskeletal examination will be performed. A clinical diagnosis will then be established to identify and appropriately treat your condition. Based on your assessment, individual goals will be created with you, and a specific physiotherapeutic treatment plan will be initiated.

What does physiotherapy treatment entail?

Your rehabilitation will include one-on-one manual treatments by your therapist aimed at alleviating pain and increasing movement. Your therapist may also use various modalities to speed your recovery and decrease pain.

Your therapist will also prescribe a specific exercise program to improve your strength, flexibility or function as needed. This program will be closely monitored and progressed by your therapist.

Mecura eClinic, each program is customized to suit your individual needs with the goal of getting you back to normal activity independently and as soon as possible.

Should you require other services, such as massage therapy or custom orthotics assessments to further aid in your recovery.

Book Apointment

      <form action="<?php $_PHP_SELF ?>" method="POST">

           Full Name
           <input type="text" class="form-control" placeholder="Full name" name="name" required>

          Age
          <input type="text" class="form-control" maxlength="2" placeholder="00" name="age" required>

          Mobile
          <input type="text" class="form-control bfh-phone" maxlength="10" placeholder="9996663333" name="mbl" required>

          Address
          <input type="text" class="form-control" placeholder="Address" name="add"  required>

          Gender

          <input type="radio" name="gender" value="male" required>Male
          <input type="radio" name="gender" value="female" required>Female

                            Home
                            Services
                            Doctors
                            Careers
                            About
                            Mecura Child

Contact Us

  4G M. M. Ali Road Kidderpore
  Kolkata, India

  Mecura eClinic: 38 Dent Mission Road kidderpore
 Kolkata :700023

  +91 80170 12294

info@mecurahealth.com

            Mecura e-Clinic &copy 2017


text:
html {
  background-color: white;
  font-family: -apple-system, BlinkMacSystemFont,
    "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
    "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  margin: 0;
  padding: 0;
}

body {
  background-color: #fafafa;
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  margin: 0 auto;
  padding: 20px;
  max-width: 1140px;
  min-height: calc(100vh - 40px);
}


text:
package com.bhrobotics.morcontrol.event;

import java.util.Enumeration;
import java.util.Vector;

public class Branch extends Node {
	private Vector nodes = new Vector();

	public void addChild(Node child)  {
		nodes.addElement(child);
	}

	public void removeChild(Node child)  {
		nodes.removeElement(child);
	}

	public Node[] getChildren() {
		Node[] children = new Node[nodes.size()];
		Enumeration e = nodes.elements();
		int i = 0;
		while (e.hasMoreElements()) {
			children[i] = (Node)e.nextElement();
			i++;
		}
		return children;
	}

	public Deployer register(Handler[] handlers) {
		// TODO register method for Branch
		return null;
	}
}


text:
namespace Google.Cloud.Dialogflow.V2.Snippets
{
    // [START dialogflow_v2_generated_Contexts_DeleteAllContexts_sync_flattened_resourceNames]
    using Google.Cloud.Dialogflow.V2;

    public sealed partial class GeneratedContextsClientSnippets
    {
        /// <summary>Snippet for DeleteAllContexts</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void DeleteAllContextsResourceNames()
        {
            // Create client
            ContextsClient contextsClient = ContextsClient.Create();
            // Initialize request argument(s)
            SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]");
            // Make the request
            contextsClient.DeleteAllContexts(parent);
        }
    }
    // [END dialogflow_v2_generated_Contexts_DeleteAllContexts_sync_flattened_resourceNames]
}


text:
'use strict';

module.exports = {
  POST: mergeCollection,
  PATCH: mergeCollection,
  PUT: overwriteCollection
};

var _          = require('lodash'),
    path       = require('path'),
    util       = require('../helpers/util'),
    Resource   = require('../data-store/resource'),
    JsonSchema = require('../helpers/json-schema');

/**
 * Adds one or more REST resources to the collection, or updates them if they already exist.
 * A unique URL is generated for each new resource, based on the schema definition in the Swagger API,
 * and this URL is used to determine whether a given resource is being created or updated.
 *
 * For example, if you POST the data {id: 123, name: 'John Doe'} to /api/users,
 * then the "id" property will be used to construct the new REST URL: /api/users/123
 *
 * Similarly, if you POST the data {name: 'John Doe', age: 42} to /api/users,
 * then the "name" property will be used to construct the new URL: /api/users/John%20Doe
 *
 * If the data doesn't contain any properties that seem like unique IDs, then a unique ID is generated,
 * which means new resources will always be created, and never updated.
 *
 * @param   {Request}   req
 * @param   {Response}  res
 * @param   {function}  next
 * @param   {DataStore} dataStore
 */
function mergeCollection(req, res, next, dataStore) {
  var collection = util.normalizeRequestPath(req.path, req.swagger);
  var resources = createResources(req);

  // Set the "Location" HTTP header.
  // If the operation allows saving multiple resources, then use the collection path.
  // If the operation only saves a single resource, then use the resource's path.
  res.swagger.location = _.isArray(req.body) ? collection : resources[0].toString();

  // Save/Update the resources
  util.debug('Saving data at %s', res.swagger.location);
  dataStore.save(resources, sendResponse(req, res, next, dataStore));
}

/**
 * Adds one or more REST resources to the collection, or overwrites them if they already exist.
 * A unique URL is generated for each new resource, based on the schema definition in the Swagger API,
 * and this URL is used to determine whether a given resource is being created or overwritten.
 *
 * For example, if you POST the data {id: 123, name: 'John Doe'} to /api/users,
 * then the "id" property will be used to construct the new REST URL: /api/users/123
 *
 * Similarly, if you POST the data {name: 'John Doe', age: 42} to /api/users,
 * then the "name" property will be used to construct the new URL: /api/users/John%20Doe
 *
 * If the data doesn't contain any properties that seem like unique IDs, then a unique ID is generated,
 * which means new resources will always be created, and never overwritten.
 *
 * @param   {Request}   req
 * @param   {Response}  res
 * @param   {function}  next
 * @param   {DataStore} dataStore
 */
function overwriteCollection(req, res, next, dataStore) {
  var collection = util.normalizeRequestPath(req.path, req.swagger);
  var resources = createResources(req);

  // Set the "Location" HTTP header.
  // If the operation allows saving multiple resources, then use the collection path.
  // If the operation only saves a single resource, then use the resource's path.
  res.swagger.location = _.isArray(req.body) ? collection : resources[0].toString();

  // Delete the existing resources
  dataStore.delete(resources, function(err) {
    if (err) {
      next(err);
    }
    else {
      // Save the new resources
      util.debug('Saving data at %s', res.swagger.location);
      dataStore.save(resources, sendResponse(req, res, next, dataStore));
    }
  });
}

/**
 * Creates {@link Resource} objects for each resource in the request
 *
 * @param   {Request}   req
 * @returns {Resource[]}
 */
function createResources(req) {
  var resources = [],
      body      = req.body,
      schema    = util.getRequestSchema(req.swagger.path, req.swagger.operation);

  if (!_.isArray(body)) {
    if (!_.isEmpty(req.files)) {
      // Save file data too
      body = _.extend({}, req.body, req.files);
    }

    // Normalize to an array
    body = [body];
  }

  // Create a REST resource for each item in the array
  for (var i = 0; i < body.length; i++) {
    var data = body[i];

    // Determine the resource's "Name" property
    var propInfo = getResourceName(data, schema);

    if (propInfo.name) {
      // Update the data, so the new name is saved with the resource data
      data = data || {};
      if (data[propInfo.name] === undefined) {
        data[propInfo.name] = propInfo.value;
        body[i] = data;
      }
    }

    // Create a resource name that is a safe URL string (2000 character max)
    var resourceName = new JsonSchema(propInfo.schema).serialize(propInfo.value);
    resourceName = _(resourceName).toString().substring(0, 2000);
    resourceName = encodeURIComponent(resourceName);

    // Create a REST resource
    var reqPath = util.normalizeRequestPath(req.path, req.swagger);
    var resource = new Resource(reqPath, resourceName, data);
    resources.push(resource);
  }

  return resources;
}

/**
 * Returns the property that is the REST resource's "unique" name.
 *
 * @param   {*}         data        The parsed resource data.
 * @param   {object}    schema      The JSON schema for the data.
 * @returns {PropertyInfo}          The resource's name.
 */
function getResourceName(data, schema) {
  // Try to find the "name" property using several different methods
  var propInfo =
        getResourceNameByValue(data, schema) ||
        getResourceNameByName(data, schema) ||
        getResourceNameByRequired(data, schema) ||
        getResourceNameByFile(data, schema);

  if (propInfo) {
    util.debug('The "%s" property (%j) appears to be the REST resource\'s name', propInfo.name, propInfo.value);

    if (propInfo.value === undefined) {
      propInfo.value = new JsonSchema(propInfo.schema).sample();
      util.debug('Generated new value (%j) for the "%s" property', propInfo.value, propInfo.name);
    }

    return propInfo;
  }
  else {
    util.debug('Unable to determine the unique name for the REST resource. Generating a unique value instead');
    return {
      name: '',
      schema: {type: 'string'},
      value: _.uniqueId()
    };
  }
}

/**
 * If the REST resource is a simple value (number, string, date, etc.),
 * then the value is returned as the resource's name.
 *
 * @param   {*}         data        The parsed resource data.
 * @param   {object}    schema      The JSON schema for the data.
 * @returns {PropertyInfo|undefined}
 */
function getResourceNameByValue(data, schema) {
  if (schema.type !== 'object' && schema.type !== undefined) {
    // The resource is a simple value, so just return the raw data as the "name"
    return {
      name: '',
      schema: schema,
      value: data
    };
  }
}

/**
 * Tries to find the REST resource's name by searching for commonly-used property names like "id", "key", etc.
 *
 * @param   {*}         data        The parsed resource data.
 * @param   {object}    schema      The JSON schema for the data.
 * @returns {PropertyInfo|undefined}
 */
function getResourceNameByName(data, schema) {
  /** @name PropertyInfo */
  var propInfo = {
    name: '',
    schema: {
      type: ''
    },
    value: undefined
  };

  // Get a list of all existing and possible properties of the resource
  var propNames = _.union(_.keys(schema.properties), _.keys(data));

  // Lowercase property names, for comparison
  var lowercasePropNames = propNames.map(function(propName) { return propName.toLowerCase(); });

  // These properties are assumed to be unique IDs.
  // If we find any of them in the schema, then use it as the REST resource's name.
  var nameProperties = ['id', 'key', 'slug', 'code', 'number', 'num', 'nbr', 'username', 'name'];
  var foundMatch = nameProperties.some(function(lowercasePropName) {
    var index = lowercasePropNames.indexOf(lowercasePropName);
    if (index >= 0) {
      // We found a property that appears to be the resource's name. Get its info.
      propInfo.name = propNames[index];
      propInfo.value = data ? data[propInfo.name] : undefined;

      if (schema.properties[propInfo.name]) {
        propInfo.schema = schema.properties[propInfo.name];
      }
      else if (_.isDate(data[propInfo.name])) {
        propInfo.schema = {
          type: 'string',
          format: 'date-time'
        };
      }
      else {
        propInfo.schema.type = typeof(data[propInfo.name]);
      }

      // If the property is valid, then we're done
      return isValidResourceName(propInfo);
    }
  });

  return foundMatch ? propInfo : undefined;
}

/**
 * Tries to find the REST resource's name using the required properties in the JSON schema.
 * We're assuming that if the resource has a name, it'll be a required property.
 *
 * @param   {*}         data        The parsed resource data.
 * @param   {object}    schema      The JSON schema for the data.
 * @returns {PropertyInfo|undefined}
 */
function getResourceNameByRequired(data, schema) {
  var propInfo = {
    name: '',
    schema: {
      type: ''
    },
    value: undefined
  };

  var foundMatch = _.some(schema.required, function(propName) {
    propInfo.name = propName;
    propInfo.schema = schema.properties[propName];
    propInfo.value = data[propName];

    // If the property is valid, then we're done
    return isValidResourceName(propInfo);
  });

  return foundMatch ? propInfo : undefined;
}

/**
 * If the REST resource contains a file (e.g. multipart/form-data or application/x-www-form-urlencoded),
 * then we'll use the file name as the resource name.
 *
 * @param   {*}         data        The parsed resource data.
 * @param   {object}    schema      The JSON schema for the data.
 * @returns {PropertyInfo|undefined}
 */
function getResourceNameByFile(data, schema) {
  // Find all file parameters
  var files = _.where(schema.properties, {type: 'file'});

  // If there is exactly ONE file parameter, then we'll use its file name
  if (files.length === 1) {
    var file = data[files[0].name];
    if (file && (file.originalname || file.path)) {
      return {
        name: file.fieldname,
        schema: {
          type: 'string'
        },

        // Use the original file name, if provided. Otherwise, fallback to the server-side file name
        value: file.originalname || path.basename(file.path)
      };
    }
  }
}

/**
 * Determines whether the given property is a valid REST resource name.
 * Only simple types (strings, numbers, booleans) are used as keys.
 * Complex types (arrays, objects, files) are ignored.
 *
 * @param   {PropertyInfo}    propInfo
 * @returns {boolean}
 */
function isValidResourceName(propInfo) {
  var validTypes = ['string', 'number', 'integer', 'boolean'];
  return validTypes.indexOf(propInfo.schema.type.toLocaleLowerCase()) >= 0;
}

/**
 * Returns a function that sends the correct response for the operation.
 *
 * @param   {Request}       req
 * @param   {Response}      res
 * @param   {function}      next
 * @param   {DataStore}     dataStore
 */
function sendResponse(req, res, next, dataStore) {
  return function(err, resources) {
    if (!err) {
      util.debug('%s successfully updated', res.swagger.location);

      if (resources.length > 0) {
        // Determine the max "modifiedOn" date of the resources
        res.swagger.lastModified = _.max(resources, 'modifiedOn').modifiedOn;
      }
      else {
        // There is no data, so use the current date/time as the "last-modified" header
        res.swagger.lastModified = new Date();
      }

      // Extract the "data" of each Resource
      resources = _.pluck(resources, 'data');
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (!res.swagger.isCollection) {
      // Response body is a single value, so only return the first item that was edited
      res.body = _.first(resources);
      next();
    }
    else {
      // Response body is the entire collection (new, edited, and old)
      var reqPath = util.normalizeRequestPath(req.path, req.swagger);
      dataStore.getCollection(reqPath, function(err, collection) {
        res.body = _.pluck(collection, 'data');
        next(err);
      });
    }
  };
}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * URL redirector to avoid leaking Referer with some sensitive information.
 *
 * @package PhpMyAdmin
 */

/**
 * Gets core libraries and defines some variables
 */
require_once './libraries/common.inc.php';

if (! PMA_isValid($_GET['url'])
    || ! preg_match('/^https?:\/\/[^\n\r]*$/', $_GET['url'])
) {
    header('Location: ' . $cfg['PmaAbsoluteUri']);
} else {
    header('Location: ' . $_GET['url']);
}
die();
?>


text:
<?php

/**
 * @namespace
 */
namespace Zend\Tool\Framework\System\Provider;

use Zend\Tool\Framework\Provider,
    Zend\Tool\Framework\Registry,
    Zend\Tool\Framework\RegistryEnabled;

/**
 * Version Provider
 *
 * @uses       \Zend\Tool\Framework\Provider
 * @uses       \Zend\Tool\Framework\Registry\FrameworkRegistry
 * @uses       \Zend\Version
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Version implements Provider, RegistryEnabled
{

    /**
     * @var \Zend\Tool\Framework\Registry
     */
    protected $_registry = null;

    const MODE_MAJOR = 'major';
    const MODE_MINOR = 'minor';
    const MODE_MINI  = 'mini';

    protected $_specialties = array('MajorPart', 'MinorPart', 'MiniPart');

    public function setRegistry(Registry $registry)
    {
        $this->_registry = $registry;
        return $this;
    }

    /**
     * Show Action
     *
     * @param string $mode The mode switch can be one of: major, minor, or mini (default)
     * @param bool $nameincluded
     */
    public function show($mode = self::MODE_MINI, $nameIncluded = true)
    {

        $versionInfo = $this->_splitVersion();

        switch($mode) {
            case self::MODE_MINOR:
                unset($versionInfo['mini']);
                break;
            case self::MODE_MAJOR:
                unset($versionInfo['mini'], $versionInfo['minor']);
                break;
        }

        $output = implode('.', $versionInfo);

        if ($nameIncluded) {
            $output = 'Zend Framework Version: ' . $output;
        }

        $this->_registry->response->appendContent($output);
    }

    public function showMajorPart($nameIncluded = true)
    {
        $versionNumbers = $this->_splitVersion();
        $output = (($nameIncluded == true) ? 'ZF Major Version: ' : null) . $versionNumbers['major'];
        $this->_registry->response->appendContent($output);
    }

    public function showMinorPart($nameIncluded = true)
    {
        $versionNumbers = $this->_splitVersion();
        $output = (($nameIncluded == true) ? 'ZF Minor Version: ' : null) . $versionNumbers['minor'];
        $this->_registry->response->appendContent($output);
    }

    public function showMiniPart($nameIncluded = true)
    {
        $versionNumbers = $this->_splitVersion();
        $output = (($nameIncluded == true) ? 'ZF Mini Version: ' : null)  . $versionNumbers['mini'];
        $this->_registry->response->appendContent($output);
    }

    protected function _splitVersion()
    {
        list($major, $minor, $mini) = explode('.', \Zend\Version::VERSION);
        return array('major' => $major, 'minor' => $minor, 'mini' => $mini);
    }

}


text:
SET gp_create_table_random_default_distribution=off;
-- end_ignore
Alter database dsp_db1 set gp_default_storage_options='appendonly=true, orientation=column, compresslevel=1';
Alter role dsp_role1 set gp_default_storage_options='appendonly=true, orientation=column, compresslevel=3';

Alter database dsp_db2 set gp_default_storage_options='appendonly=true,orientation=row, compresslevel=2';
Alter role dsp_role2 set gp_default_storage_options='appendonly=true, orientation=row, compresslevel=4';

Alter database dsp_db3 set gp_default_storage_options='appendonly=true,orientation=row,compresstype=quicklz,compresslevel=1';
Alter role dsp_role3 set gp_default_storage_options='appendonly=true, orientation=column, compresstype=quicklz,compresslevel=1';

Alter database dsp_db4 set gp_default_storage_options='appendonly=true,orientation=column,compresstype=rle_type,compresslevel=1';
Alter role dsp_role4 set gp_default_storage_options='appendonly=true, orientation=column, compresstype=rle_type,compresslevel=3';

Select datname,datconfig from pg_database where datname in ('dsp_db1', 'dsp_db2', 'dsp_db3', 'dsp_db4');

select rolname, rolconfig from pg_roles where rolname in ('dsp_role1', 'dsp_role2', 'dsp_role3', 'dsp_role4', 'dsp_role4');


text:
<?php

namespace Shrink0r\Sentimental\Classifier\NaiveBayes;

class DocumentFrequencies
{
    protected $frequencies = [];

    protected $total_count = 0;

    public function __construct(array $frequencies, $total_count)
    {
        $this->frequencies = $frequencies;
        $this->total_count = $total_count;
    }

    public function getFrequency($class)
    {
        return isset($this->frequencies[$class]) ? $this->frequencies[$class] : 0;
    }

    public function getTotalCount()
    {
        return $this->total_count;
    }

    public function getFrequencies()
    {
        return $this->frequencies;
    }
}


text:
Node JS
=======

Node JS site, using angular, jade views, mocha
All automated with grunt.

This was mostly written by Will Munn and Raol Millais

Setup
------
To work with this project, you should install nodejs

It is recomended that you have the following npm modules installed globally:
	`mocha` - test framework + runner
	`bower` - client side package manager
	`grunt` - used to run various tasks
	`jshint` - to check your syntax errors
	`karma` - to run client side tests

to get started, run:
```
npm install
bower install
```
If you wish, you can run grunt setupdev which will add a precommit hook preventing you from commiting any red tests or invalid syntax

To run the tests, run:
```
	npm test
```
To start the website run:
```
	node lib/app.js
```
To install the app without dev dependencies, run:
```
	npm install --production
```

Todo
-----
Setup scripts.


text:
#import <UIKit/UIKit.h>

@interface MTTPCStatusCell : UITableViewCell

@end


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**transactionType** | **String** |  | [optional]
**providerTransactionId** | **String** | Provider?s identifier of the settlement transaction |
**relatedProviderAuthorisationEntryId** | **String** | In case of a related authorisation, this is the provider's identifier of the authorisation entry. | [optional]
**relatedProviderAuthorisationTransactionId** | **String** | In case of a related authorisation, this is the provider's identifier of the authorisation transaction. | [optional]
**merchantId** | **String** | Identifier of the merchant where the purchase was performed. |
**merchantName** | **String** | Name of the merchant where the purchase was performed. |
**merchantCategoryCode** | **String** | A four digit numeric code identifying the type of business conducted by the merchant where the purchase was performed. |
**authCode** | **String** | Authorization Code assigned to this settlement. | [optional]
**reasonCode** | **String** | A reply flag given as a response. | [optional]
**acquirerReferenceNumber** | **String** | Used to reference a transaction when it goes from the merchant bank (acquirer?s bank) through to the cardholder?s bank (issuer?s bank) | [optional]
**retrievalReferenceNumber** | **String** | Document reference number identifying the original source information (ATM acquirer). | [optional]
**cardholderPresence** | **String** | Determines if the transaction was performed with the physical presence of the cardholder. | [optional]
**cardPresent** | **String** |  | [optional]
**terminalCode** | **String** |  | [optional]
**terminalCountry** | **String** |  | [optional]
**fee** | [**[SettlementFee]**](SettlementFee.md) |  | [optional]

## Enum: TransactionTypeEnum

* `SALE_PURCHASE` (value: `"SALE_PURCHASE"`)

* `MAIL_OR_TELEPHONE_ORDER` (value: `"MAIL_OR_TELEPHONE_ORDER"`)

* `PURCHASE_REFUND_REVERSAL` (value: `"PURCHASE_REFUND_REVERSAL"`)

* `ORIGINAL_CREDIT_TRANSACTION_REVERSAL` (value: `"ORIGINAL_CREDIT_TRANSACTION_REVERSAL"`)

* `PURCHASE_REFUND` (value: `"PURCHASE_REFUND"`)

* `ORIGINAL_CREDIT_TRANSACTION` (value: `"ORIGINAL_CREDIT_TRANSACTION"`)

## Enum: CardholderPresenceEnum

* `UNSPECIFIED` (value: `"UNSPECIFIED"`)

* `CARD_HOLDER_PRESENT` (value: `"CARD_HOLDER_PRESENT"`)

* `NOT_PRESENT_UNSPECIFIED` (value: `"NOT_PRESENT_UNSPECIFIED"`)

* `NOT_PRESENT_MAIL_ORDER` (value: `"NOT_PRESENT_MAIL_ORDER"`)

* `NOT_PRESENT_TELEPHONE_ORDER` (value: `"NOT_PRESENT_TELEPHONE_ORDER"`)

* `NOT_PRESENT_STANDING_ORDER` (value: `"NOT_PRESENT_STANDING_ORDER"`)

* `NOT_PRESENT_ELECTRONIC_ORDER` (value: `"NOT_PRESENT_ELECTRONIC_ORDER"`)

* `PRESENT_STANDING_ORDER` (value: `"PRESENT_STANDING_ORDER"`)

## Enum: CardPresentEnum

* `NULL` (value: `"NULL"`)

* `TRUE` (value: `"TRUE"`)

* `FALSE` (value: `"FALSE"`)


text:
package monix.eval.instances

import cats.{CoflatMap, Eval, MonadError, SemigroupK}
import monix.eval.Task
import scala.util.Try

/** Cats type class instances for [[monix.eval.Task Task]]
  * for  `cats.MonadError` and `CoflatMap` (and implicitly for
  * `Applicative`, `Monad`, etc).
  *
  * References:
  *
  *  - [[https://typelevel.org/cats/ typelevel/cats]]
  *  - [[https://github.com/typelevel/cats-effect typelevel/cats-effect]]
  */
class CatsBaseForTask extends MonadError[Task, Throwable] with CoflatMap[Task] with SemigroupK[Task] {
  override def pure[A](a: A): Task[A] =
    Task.now(a)
  override val unit: Task[Unit] =
    Task.now(())
  override def flatMap[A, B](fa: Task[A])(f: (A) => Task[B]): Task[B] =
    fa.flatMap(f)
  override def flatten[A](ffa: Task[Task[A]]): Task[A] =
    ffa.flatten
  override def tailRecM[A, B](a: A)(f: (A) => Task[Either[A, B]]): Task[B] =
    Task.tailRecM(a)(f)
  override def ap[A, B](ff: Task[(A) => B])(fa: Task[A]): Task[B] =
    for (f <- ff; a <- fa) yield f(a)
  override def map2[A, B, Z](fa: Task[A], fb: Task[B])(f: (A, B) => Z): Task[Z] =
    for (a <- fa; b <- fb) yield f(a, b)
  override def product[A, B](fa: Task[A], fb: Task[B]): Task[(A, B)] =
    for (a <- fa; b <- fb) yield (a, b)
  override def map[A, B](fa: Task[A])(f: (A) => B): Task[B] =
    fa.map(f)
  override def raiseError[A](e: Throwable): Task[A] =
    Task.raiseError(e)
  override def handleError[A](fa: Task[A])(f: (Throwable) => A): Task[A] =
    fa.onErrorHandle(f)
  override def handleErrorWith[A](fa: Task[A])(f: (Throwable) => Task[A]): Task[A] =
    fa.onErrorHandleWith(f)
  override def recover[A](fa: Task[A])(pf: PartialFunction[Throwable, A]): Task[A] =
    fa.onErrorRecover(pf)
  override def recoverWith[A](fa: Task[A])(pf: PartialFunction[Throwable, Task[A]]): Task[A] =
    fa.onErrorRecoverWith(pf)
  override def attempt[A](fa: Task[A]): Task[Either[Throwable, A]] =
    fa.attempt
  override def catchNonFatal[A](a: => A)(implicit ev: <:<[Throwable, Throwable]): Task[A] =
    Task.eval(a)
  override def catchNonFatalEval[A](a: Eval[A])(implicit ev: <:<[Throwable, Throwable]): Task[A] =
    Task.eval(a.value)
  override def fromTry[A](t: Try[A])(implicit ev: <:<[Throwable, Throwable]): Task[A] =
    Task.fromTry(t)
  override def coflatMap[A, B](fa: Task[A])(f: (Task[A]) => B): Task[B] =
    fa.start.map(fiber => f(fiber.join))
  override def coflatten[A](fa: Task[A]): Task[Task[A]] =
    fa.start.map(_.join)
  override def combineK[A](ta: Task[A], tb: Task[A]): Task[A] =
    ta.onErrorHandleWith(_ => tb)
}


text:
package org.agrona.concurrent.broadcast;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.agrona.concurrent.UnsafeBuffer;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.agrona.BitUtil.align;
import static org.agrona.concurrent.broadcast.RecordDescriptor.*;

public class BroadcastTransmitterTest
{
    private static final int MSG_TYPE_ID = 7;
    private static final int CAPACITY = 1024;
    private static final int TOTAL_BUFFER_LENGTH = CAPACITY + BroadcastBufferDescriptor.TRAILER_LENGTH;
    private static final int TAIL_INTENT_COUNTER_OFFSET =
        CAPACITY + BroadcastBufferDescriptor.TAIL_INTENT_COUNTER_OFFSET;
    private static final int TAIL_COUNTER_INDEX = CAPACITY + BroadcastBufferDescriptor.TAIL_COUNTER_OFFSET;
    private static final int LATEST_COUNTER_INDEX = CAPACITY + BroadcastBufferDescriptor.LATEST_COUNTER_OFFSET;

    private final UnsafeBuffer buffer = mock(UnsafeBuffer.class);
    private BroadcastTransmitter broadcastTransmitter;

    @Before
    public void setUp()
    {
        when(buffer.capacity()).thenReturn(TOTAL_BUFFER_LENGTH);

        broadcastTransmitter = new BroadcastTransmitter(buffer);
    }

    @Test
    public void shouldCalculateCapacityForBuffer()
    {
        assertThat(broadcastTransmitter.capacity(), is(CAPACITY));
    }

    @Test(expected = IllegalStateException.class)
    public void shouldThrowExceptionForCapacityThatIsNotPowerOfTwo()
    {
        final int capacity = 777;
        final int totalBufferLength = capacity + BroadcastBufferDescriptor.TRAILER_LENGTH;

        when(buffer.capacity()).thenReturn(totalBufferLength);

        new BroadcastTransmitter(buffer);
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenMaxMessageLengthExceeded()
    {
        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);

        broadcastTransmitter.transmit(MSG_TYPE_ID, srcBuffer, 0, broadcastTransmitter.maxMsgLength() + 1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenMessageTypeIdInvalid()
    {
        final int invalidMsgId = -1;
        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);

        broadcastTransmitter.transmit(invalidMsgId, srcBuffer, 0, 32);
    }

    @Test
    public void shouldTransmitIntoEmptyBuffer()
    {
        final long tail = 0L;
        final int recordOffset = (int)tail;
        final int length = 8;
        final int recordLength = length + HEADER_LENGTH;
        final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);

        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);
        final int srcIndex = 0;

        broadcastTransmitter.transmit(MSG_TYPE_ID, srcBuffer, srcIndex, length);

        final InOrder inOrder = inOrder(buffer);
        inOrder.verify(buffer).getLong(TAIL_COUNTER_INDEX);

        inOrder.verify(buffer).putLongOrdered(TAIL_INTENT_COUNTER_OFFSET, tail + recordLengthAligned);
        inOrder.verify(buffer).putInt(lengthOffset(recordOffset), recordLength);
        inOrder.verify(buffer).putInt(typeOffset(recordOffset), MSG_TYPE_ID);
        inOrder.verify(buffer).putBytes(msgOffset(recordOffset), srcBuffer, srcIndex, length);

        inOrder.verify(buffer).putLong(LATEST_COUNTER_INDEX, tail);
        inOrder.verify(buffer).putLongOrdered(TAIL_COUNTER_INDEX, tail + recordLengthAligned);
    }

    @Test
    public void shouldTransmitIntoUsedBuffer()
    {
        final long tail = RECORD_ALIGNMENT * 3;
        final int recordOffset = (int)tail;
        final int length = 8;
        final int recordLength = length + HEADER_LENGTH;
        final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);

        when(buffer.getLong(TAIL_COUNTER_INDEX)).thenReturn(tail);

        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);
        final int srcIndex = 0;

        broadcastTransmitter.transmit(MSG_TYPE_ID, srcBuffer, srcIndex, length);

        final InOrder inOrder = inOrder(buffer);
        inOrder.verify(buffer).getLong(TAIL_COUNTER_INDEX);

        inOrder.verify(buffer).putLongOrdered(TAIL_INTENT_COUNTER_OFFSET, tail + recordLengthAligned);
        inOrder.verify(buffer).putInt(lengthOffset(recordOffset), recordLength);
        inOrder.verify(buffer).putInt(typeOffset(recordOffset), MSG_TYPE_ID);
        inOrder.verify(buffer).putBytes(msgOffset(recordOffset), srcBuffer, srcIndex, length);

        inOrder.verify(buffer).putLong(LATEST_COUNTER_INDEX, tail);
        inOrder.verify(buffer).putLongOrdered(TAIL_COUNTER_INDEX, tail + recordLengthAligned);
    }

    @Test
    public void shouldTransmitIntoEndOfBuffer()
    {
        final int length = 8;
        final int recordLength = length + HEADER_LENGTH;
        final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
        final long tail = CAPACITY - recordLengthAligned;
        final int recordOffset = (int)tail;

        when(buffer.getLong(TAIL_COUNTER_INDEX)).thenReturn(tail);

        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);
        final int srcIndex = 0;

        broadcastTransmitter.transmit(MSG_TYPE_ID, srcBuffer, srcIndex, length);

        final InOrder inOrder = inOrder(buffer);
        inOrder.verify(buffer).getLong(TAIL_COUNTER_INDEX);

        inOrder.verify(buffer).putLongOrdered(TAIL_INTENT_COUNTER_OFFSET, tail + recordLengthAligned);
        inOrder.verify(buffer).putInt(lengthOffset(recordOffset), recordLength);
        inOrder.verify(buffer).putInt(typeOffset(recordOffset), MSG_TYPE_ID);
        inOrder.verify(buffer).putBytes(msgOffset(recordOffset), srcBuffer, srcIndex, length);

        inOrder.verify(buffer).putLong(LATEST_COUNTER_INDEX, tail);
        inOrder.verify(buffer).putLongOrdered(TAIL_COUNTER_INDEX, tail + recordLengthAligned);
    }

    @Test
    public void shouldApplyPaddingWhenInsufficientSpaceAtEndOfBuffer()
    {
        long tail = CAPACITY - RECORD_ALIGNMENT;
        int recordOffset = (int)tail;
        final int length = RECORD_ALIGNMENT + 8;
        final int recordLength = length + HEADER_LENGTH;
        final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT);
        final int toEndOfBuffer = CAPACITY - recordOffset;

        when(buffer.getLong(TAIL_COUNTER_INDEX)).thenReturn(tail);

        final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);
        final int srcIndex = 0;

        broadcastTransmitter.transmit(MSG_TYPE_ID, srcBuffer, srcIndex, length);

        final InOrder inOrder = inOrder(buffer);
        inOrder.verify(buffer).getLong(TAIL_COUNTER_INDEX);

        inOrder.verify(buffer).putLongOrdered(TAIL_INTENT_COUNTER_OFFSET, tail + recordLengthAligned + toEndOfBuffer);

        inOrder.verify(buffer).putInt(lengthOffset(recordOffset), toEndOfBuffer);
        inOrder.verify(buffer).putInt(typeOffset(recordOffset), PADDING_MSG_TYPE_ID);

        tail += toEndOfBuffer;
        recordOffset = 0;
        inOrder.verify(buffer).putInt(lengthOffset(recordOffset), recordLength);
        inOrder.verify(buffer).putInt(typeOffset(recordOffset), MSG_TYPE_ID);
        inOrder.verify(buffer).putBytes(msgOffset(recordOffset), srcBuffer, srcIndex, length);

        inOrder.verify(buffer).putLong(LATEST_COUNTER_INDEX, tail);
        inOrder.verify(buffer).putLongOrdered(TAIL_COUNTER_INDEX, tail + recordLengthAligned);
    }
}


text:
              <button class="nav-toggle material-icons" pui-collapse-target="#main_collapse_menu">menu</button>

            <? bloginfo("name"); ?>

                    <? wp_nav_menu("title_li="); ?>

    <?get_search_form()?>

<?php // NOTE: Give the 'href="javascript:$_seacrhformOpen()" attribute the seacrh open link in the navbar!!!!' ?>


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, enableProdMode } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { FeaturesComponent } from './components/features/features.component';
import { WorkComponent } from './components/work/work.component';
import { TeamComponent } from './components/team/team.component';
import { FunFactsComponent } from './components/funfacts/funfacts.component';
import { ContactComponent } from './components/contact/contact.component';

import { AppComponentAdmin } from "./app.component.admin";

enableProdMode();

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    FeaturesComponent,
    WorkComponent,
    TeamComponent,
    FunFactsComponent,
    ContactComponent,
    AppComponentAdmin
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
package org.apache.stratos.custom.handlers.granttype;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.jwt.SignedJWT;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oltu.openidconnect.as.messages.IDTokenBuilder;
import org.apache.oltu.openidconnect.as.messages.IDTokenException;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.util.KeyStoreManager;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler;

import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.text.ParseException;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Grant Handler for Grant Type : client_credentials
 */
public class ClientCredentialsGrantHandler extends AbstractAuthorizationGrantHandler {

    private static Log log = LogFactory.getLog(ClientCredentialsGrantHandler.class);
    private static ConcurrentHashMap<Integer, Key> privateKeys =
            new ConcurrentHashMap<Integer, Key>();
    private static ConcurrentHashMap<Integer, Certificate> publicCerts =
            new ConcurrentHashMap<Integer, Certificate>();

    @Override
    public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
            throws IdentityOAuth2Exception {
        // By this time, we have already validated client credentials.
        tokReqMsgCtx.setScope(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope());
        return true;
    }

    public boolean issueRefreshToken() throws IdentityOAuth2Exception {
        return false;
    }

    public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception {
        return false;
    }

    public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {

        OAuthServerConfiguration config = OAuthServerConfiguration.getInstance();
        String issuer = config.getOpenIDConnectIDTokenIssuerIdentifier();
        String subject = tokReqMsgCtx.getAuthorizedUser();
        String audience = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
        String authorizedParty = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();

        OAuth2AccessTokenRespDTO tokenRespDTO = getTokenDTO(tokReqMsgCtx);
        int lifetime = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000;
        int curTime = (int) Calendar.getInstance().getTimeInMillis();

        String applicationId = tokReqMsgCtx.getScope()[0];

        IDTokenBuilder builder =
                new IDTokenBuilder().setIssuer(issuer)
                        .setSubject(subject)
                        .setAudience(audience)
                        .setAuthorizedParty(authorizedParty)
                        .setExpiration(curTime + lifetime)
                        .setIssuedAt((int) Calendar.getInstance().getTimeInMillis())
                        .setClaim("appId", applicationId);

        String plainIDToken;
        try {
            plainIDToken = builder.buildIDToken();
        } catch (IDTokenException e) {
            String message = "Error while building ID token";
            throw new RuntimeException(message, e);
        }

        String signedJwtKey;
        try {
            PlainJWT plainJWT = PlainJWT.parse(plainIDToken);
            plainIDToken = plainJWT.serialize();
            signedJwtKey = signJWT(plainIDToken, tokReqMsgCtx);
        } catch (ParseException e) {
            String message = "Error while passing ID token";
            throw new RuntimeException(message, e);
        }

        tokenRespDTO.setIDToken(signedJwtKey);
        return tokenRespDTO;
    }

    private OAuth2AccessTokenRespDTO getTokenDTO(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
        return super.issue(tokReqMsgCtx);
    }

    protected String signJWT(String payLoad, OAuthTokenReqMessageContext request)
            throws IdentityOAuth2Exception {
        JWSAlgorithm jwsAlgorithm =
                mapSignatureAlgorithm(OAuthServerConfiguration.getInstance()
                        .getSignatureAlgorithm());
        if (JWSAlgorithm.RS256.equals(jwsAlgorithm) || JWSAlgorithm.RS384.equals(jwsAlgorithm) ||
                JWSAlgorithm.RS512.equals(jwsAlgorithm)) {
            return signJWTWithRSA(payLoad, jwsAlgorithm, request);
        }
        log.error("UnSupported Signature Algorithm");
        throw new IdentityOAuth2Exception("UnSupported Signature Algorithm");
    }

    protected String signJWTWithRSA(String payLoad, JWSAlgorithm jwsAlgorithm,
                                    OAuthTokenReqMessageContext request)
            throws IdentityOAuth2Exception {
        try {
            String tenantDomain = request.getOauth2AccessTokenReqDTO().getTenantDomain();
            int tenantId = request.getTenantID();
            if (tenantDomain == null) {
                tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            }
            if (tenantId == 0) {
                tenantId = MultitenantConstants.SUPER_TENANT_ID;
            }
            Key privateKey = null;

            if (!(privateKeys.containsKey(tenantId))) {
                // get tenant's key store manager
                KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

                if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                    // derive key store name
                    String ksName = tenantDomain.trim().replace(".", "-");
                    String jksName = ksName + ".jks";
                    // obtain private key
                    privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);

                } else {
                    try {
                        privateKey = tenantKSM.getDefaultPrivateKey();
                    } catch (Exception e) {
                        log.error("Error while obtaining private key for super tenant", e);
                    }
                }
                if (privateKey != null) {
                    privateKeys.put(tenantId, privateKey);
                }
            } else {
                privateKey = privateKeys.get(tenantId);
            }

            Certificate publicCert;

            if (!(publicCerts.containsKey(tenantId))) {
                // get tenant's key store manager
                KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

                KeyStore keyStore;
                if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                    // derive key store name
                    String ksName = tenantDomain.trim().replace(".", "-");
                    String jksName = ksName + ".jks";
                    keyStore = tenantKSM.getKeyStore(jksName);
                    publicCert = keyStore.getCertificate(tenantDomain);
                } else {
                    publicCert = tenantKSM.getDefaultPrimaryCertificate();
                }
                if (publicCert != null) {
                    publicCerts.put(tenantId, publicCert);
                }
            } else {
                publicCert = publicCerts.get(tenantId);
            }

            JWSSigner signer = new RSASSASigner((RSAPrivateKey) privateKey);
            SignedJWT signedJWT =
                    new SignedJWT(new JWSHeader(jwsAlgorithm),
                            PlainJWT.parse(payLoad).getJWTClaimsSet());
            signedJWT.sign(signer);
            return signedJWT.serialize();
        } catch (KeyStoreException e) {
            log.error("Error in obtaining tenant's keystore", e);
            throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
        } catch (JOSEException e) {
            log.error("Error in obtaining tenant's keystore", e);
            throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
        } catch (Exception e) {
            log.error("Error in obtaining tenant's keystore", e);
            throw new IdentityOAuth2Exception("Error in obtaining tenant's keystore", e);
        }
    }

    protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm)
            throws IdentityOAuth2Exception {
        if ("SHA256withRSA".equals(signatureAlgorithm)) {
            return JWSAlgorithm.RS256;
        } else if ("SHA384withRSA".equals(signatureAlgorithm)) {
            return JWSAlgorithm.RS384;
        } else if ("SHA512withRSA".equals(signatureAlgorithm)) {
            return JWSAlgorithm.RS512;
        } else if ("SHA256withHMAC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.HS256;
        } else if ("SHA384withHMAC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.HS384;
        } else if ("SHA512withHMAC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.HS512;
        } else if ("SHA256withEC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.ES256;
        } else if ("SHA384withEC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.ES384;
        } else if ("SHA512withEC".equals(signatureAlgorithm)) {
            return JWSAlgorithm.ES512;
        }
        log.error("Unsupported Signature Algorithm in identity.xml");
        throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
    }
}


text:
package org.apereo.cas.support.saml.idp.metadata;

import org.apereo.cas.support.saml.idp.metadata.generator.BaseSamlIdPMetadataGenerator;
import org.apereo.cas.support.saml.idp.metadata.generator.SamlIdPMetadataGeneratorConfigurationContext;
import org.apereo.cas.support.saml.services.idp.metadata.SamlIdPMetadataDocument;

import lombok.SneakyThrows;
import lombok.val;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * This is {@link MongoDbSamlIdPMetadataGenerator}.
 *
 * @author Misagh Moayyed
 * @since 6.0.0
 */
public class MongoDbSamlIdPMetadataGenerator extends BaseSamlIdPMetadataGenerator {
    private final transient MongoTemplate mongoTemplate;
    private final String collectionName;

    public MongoDbSamlIdPMetadataGenerator(final SamlIdPMetadataGeneratorConfigurationContext samlIdPMetadataGeneratorConfigurationContext,
                                           final MongoTemplate mongoTemplate, final String collectionName) {
        super(samlIdPMetadataGeneratorConfigurationContext);
        this.mongoTemplate = mongoTemplate;
        this.collectionName = collectionName;
    }

    @Override
    @SneakyThrows
    public Pair<String, String> buildSelfSignedEncryptionCert() {
        val results = generateCertificateAndKey();
        var update = Update.update("encryptionCertificate", results.getKey()).addToSet("encryptionKey", results.getValue());
        this.mongoTemplate.upsert(new Query(), update, SamlIdPMetadataDocument.class, this.collectionName);
        return results;
    }

    @Override
    @SneakyThrows
    public Pair<String, String> buildSelfSignedSigningCert() {
        val results = generateCertificateAndKey();
        val update = Update.update("signingCertificate", results.getKey()).addToSet("signingKey", results.getValue());
        this.mongoTemplate.upsert(new Query(), update, SamlIdPMetadataDocument.class, this.collectionName);
        return results;
    }

    @Override
    protected String writeMetadata(final String metadata) {
        val update = Update.update("metadata", metadata);
        this.mongoTemplate.upsert(new Query(), update, SamlIdPMetadataDocument.class, this.collectionName);
        return metadata;
    }
}


text:
package nkp.pspValidator.shared;

import javax.xml.namespace.NamespaceContext;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Martin Řehánek on 17.11.16.
 */
public class NamespaceContextImpl implements NamespaceContext {
    private final Map<String, String> namespaceByPrefix = new HashMap<>();

    public void setNamespace(String prefix, String uri) {
        if (namespaceByPrefix.containsKey(prefix)) {
            throw new IllegalStateException(String.format("prefix '%s' je již registrován a to pro uri '%s'", prefix, namespaceByPrefix.get(prefix)));
        } else {
            namespaceByPrefix.put(prefix, uri);
        }
    }

    @Override
    public String getNamespaceURI(String prefix) {
        String uri = namespaceByPrefix.get(prefix);
        return uri;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        if (namespaceByPrefix.values().contains(namespaceURI)) {
            for (String prefix : namespaceByPrefix.keySet()) {
                if (namespaceByPrefix.get(prefix).equals(namespaceURI)) {
                    return prefix;
                }
            }
            return null;
        } else {
            return null;
        }
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        return namespaceByPrefix.keySet().iterator();
    }

}


text:
package com.iggroup.webapi.samples.client.rest.dto.positions.getPositionByDealIdV2;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/*
Open position data
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class GetPositionByDealIdV2Response {

/*
Open position data
*/
private Position position;

/*
Market data
*/
private Market market;

public Position getPosition() { return position; }
public void setPosition(Position position) { this.position=position; }
public Market getMarket() { return market; }
public void setMarket(Market market) { this.market=market; }
}


text: export { default } from 'ember-cli-loaders/components/loader-ball-grid-pulse';