text:
import datetime
import json

from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.test.client import Client
from django.utils import timezone

from bulbs.promotion.models import PZone, PZoneHistory
from bulbs.promotion.operations import PZoneOperation, InsertOperation, DeleteOperation
from bulbs.utils.test import BaseAPITestCase, make_content

class PromotionApiTestCase(BaseAPITestCase):

    def setUp(self):
        # set up client
        super(PromotionApiTestCase, self).setUp()

        # do client stuff
        self.client = Client()
        self.client.login(username="admin", password="secret")

        # set up a test pzone
        self.pzone = PZone.objects.create(name="homepage")
        data = []
        for i in range(10):
            content = make_content(title="Content test #{}".format(i))
            data.append({"id": content.pk})

        self.pzone.data = data
        self.pzone.save()

    def tearDown(self):
        super(PromotionApiTestCase, self).tearDown()
        PZone.objects.all().delete()

    def test_pzone_api(self):

        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        response = self.client.get(endpoint)
        # give permissions
        self.give_permissions()
        response = self.client.get(endpoint)
        # permission allows promotion
        self.assertEqual(response.status_code, 200)

        for index, content in enumerate(response.data["content"]):
            self.assertEqual(content["title"], "Content test #{}".format(index))

        new_data = response.data
        # This sucks, but it just reverses the list
        new_data["content"] = [{"id": content["id"]} for content in response.data["content"]][::-1]

        self.assertEqual(PZoneHistory.objects.count(), 0)

        response = self.client.put(endpoint, json.dumps(new_data), content_type="application/json")
        self.assertEqual(response.status_code, 200)
        for index, content in enumerate(response.data["content"]):
            self.assertEqual(content["title"], "Content test #{}".format(9 - index))

        self.assertEqual(PZoneHistory.objects.count(), 1)
        pzone = PZone.objects.get(name=self.pzone.name)
        self.assertEqual(PZoneHistory.objects.get().data, pzone.data)

    def test_operations_permissions(self):
        """Ensure permissions limit who can edit operations."""

        # create regular user
        regular_user_name = "regularuser"
        regular_user_pass = "12345"
        get_user_model().objects.create_user(
            regular_user_name,
            "regularguy@aol.com",
            regular_user_pass
        )
        self.client.login(username=regular_user_name, password=regular_user_pass)

        # do requests
        response_get = self.client.get(reverse(
            "pzone_operations",
            kwargs={
                "pzone_pk": self.pzone.pk
            }
        ))
        response_post = self.client.post(reverse(
            "pzone_operations",
            kwargs={
                "pzone_pk": self.pzone.pk
            }
        ))
        response_delete = self.client.delete(reverse(
            "pzone_operations_delete",
            kwargs={
                "pzone_pk": self.pzone.pk,
                "operation_pk": 1
            }
        ))

        # check that we get 403 for everything
        self.assertEqual(response_get.status_code, 403)
        self.assertEqual(response_post.status_code, 403)
        self.assertEqual(response_delete.status_code, 403)

    def test_get_operations(self):
        """Test that we can get a pzone's operations."""

        # set up some test operations
        test_time = (timezone.now() + datetime.timedelta(hours=-1)).replace(microsecond=0)
        new_content_1 = make_content()
        op_1 = InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            index=0,
            content=new_content_1
        )
        op_1_type = "{}_{}".format(op_1.polymorphic_ctype.app_label, op_1.polymorphic_ctype.model)
        # this one should end up above the first one
        new_content_2 = make_content()
        op_2 = InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            index=0,
            content=new_content_2
        )
        op_2_type = "{}_{}".format(op_2.polymorphic_ctype.app_label, op_2.polymorphic_ctype.model)

        # query the endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.get(endpoint)

        # check that we got an OK response
        self.assertEqual(response.status_code, 200, msg=response.data)

        # start checking data
        operations = response.data
        self.assertEqual(len(operations), 2)

        # check first operation made it in
        self.assertEqual(operations[0]["type_name"], op_1_type)
        self.assertEqual(operations[0]["content"], new_content_1.pk)
        self.assertEqual(operations[0]["pzone"], self.pzone.pk)
        self.assertEqual(operations[0]["index"], 0)
        self.assertEqual(operations[0]["content_title"], new_content_1.title)
        self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z"))
        # check second operation made it in
        self.assertEqual(operations[1]["type_name"], op_2_type)
        self.assertEqual(operations[1]["content"], new_content_2.pk)
        self.assertEqual(operations[1]["pzone"], self.pzone.pk)
        self.assertEqual(operations[1]["index"], 0)
        self.assertEqual(operations[1]["content_title"], new_content_2.title)
        self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z"))

    def test_get_operations_404(self):
        """Test that a 404 is thrown when an id not associated with a pzone
        is given."""

        # query endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": 1234
        })
        response = self.client.get(endpoint)

        # check that we got a 404
        self.assertEqual(response.status_code, 404)

    def test_get_operations_empty(self):
        """Test that the response of an empty operations list is JSON."""

        # query the endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.get(endpoint)

        # check that we got an OK response
        self.assertEqual(response.status_code, 200, msg=response.data)

        # start checking data
        operations = response.data
        self.assertEqual(len(operations), 0)

    def test_post_operations(self):
        """Test that a new operation can be added to a pzone operations."""

        # test objects
        test_time = (timezone.now() + datetime.timedelta(hours=1)).replace(microsecond=0)

        test_content_1 = make_content(published=timezone.now())
        test_content_2 = make_content(published=timezone.now())

        # setup and query endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.post(
            endpoint,
            json.dumps([
                {
                    "type_name": "promotion_replaceoperation",
                    "pzone": self.pzone.pk,
                    "when": test_time.isoformat(),
                    "index": 1,
                    "content": test_content_1.id
                },
                {
                    "type_name": "promotion_replaceoperation",
                    "pzone": self.pzone.pk,
                    "when": test_time.isoformat(),
                    "index": 2,
                    "content": test_content_2.id
                },
            ]),
            content_type="application/json"
        )

        # check that we got an OK response
        self.assertEqual(response.status_code, 200, msg=response.data)

        # check that operations made it into the db
        self.assertEqual(PZoneOperation.objects.count(), 2)

        # check response data data
        operations = response.data
        self.assertNotEqual(operations[0]["id"], None)
        self.assertEqual(operations[0]["type_name"], "promotion_replaceoperation")
        self.assertEqual(operations[0]["pzone"], self.pzone.pk)
        self.assertEqual(operations[0]["when"], test_time.isoformat().replace("+00:00", "Z"))
        self.assertEqual(operations[0]["index"], 1)
        self.assertEqual(operations[0]["content"], test_content_1.id)

        assert operations[1]["id"] > operations[0]["id"]
        self.assertEqual(operations[1]["type_name"], "promotion_replaceoperation")
        self.assertEqual(operations[1]["pzone"], self.pzone.pk)
        self.assertEqual(operations[1]["when"], test_time.isoformat().replace("+00:00", "Z"))
        self.assertEqual(operations[1]["index"], 2)
        self.assertEqual(operations[1]["content"], test_content_2.id)

    def test_post_operation(self):
        """Test that a new operation can be added to a pzone operations."""

        # test objects
        content = make_content(title="kill me")
        test_time = (timezone.now() + datetime.timedelta(hours=1)).replace(microsecond=0)

        # setup and query endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.post(
            endpoint,
            json.dumps({
                "type_name": "promotion_replaceoperation",
                "pzone": self.pzone.pk,
                "when": test_time.isoformat(),
                "index": 0,
                "content": content.id
            }),
            content_type="application/json"
        )

        # check that we got an OK response
        self.assertEqual(response.status_code, 200, msg=response.data)

        # check that operations made it into the db
        self.assertEqual(PZoneOperation.objects.count(), 1)

        # check response data data
        operation = response.data
        self.assertNotEqual(operation["id"], None)
        self.assertEqual(operation["type_name"], "promotion_replaceoperation")
        self.assertEqual(operation["pzone"], self.pzone.pk)
        self.assertEqual(operation["when"], test_time.isoformat().replace("+00:00", "Z"))
        self.assertEqual(operation["index"], 0)
        self.assertEqual(operation["content"], content.id)

    def test_post_operation_400(self):
        """Test that posting with bad data returns 400 and errors in json."""

        # setup and query endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.post(
            endpoint,
            json.dumps({
                "type_name": "not a real operation type"
            }),
            content_type="application/json"
        )

        # check that we got a 400 response
        self.assertEqual(response.status_code, 400)
        # check the data that came back to see if it has an error
        self.assertEqual(len(response.data["errors"]), 1)

        # let's try another error
        response = self.client.post(
            endpoint,
            json.dumps({
                "type_name": "promotion_replaceoperation",
                "pzone": "123"
            }),
            content_type="application/json"
        )

        # check that we got a 400 response
        self.assertEqual(response.status_code, 400)
        # check that the data came back with 4 errors
        self.assertEqual(len(response.data), 4)

    def test_post_operation_404(self):
        """Test that posting with invalid pzone pk returns a 404."""

        # query endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": 123456789
        })
        response = self.client.post(endpoint)

        # check that we got a 400 response
        self.assertEqual(response.status_code, 404)

    def test_delete_operation(self):
        """Test that we can remove an operation from a pzone."""

        # add an operation to the db
        test_time = timezone.now() + datetime.timedelta(hours=1)
        new_content = make_content()
        new_operation = InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            index=0,
            content=new_content
        )

        # setup and query endpoint
        endpoint = reverse("pzone_operations_delete", kwargs={
            "pzone_pk": self.pzone.pk,
            "operation_pk": new_operation.pk
        })
        response = self.client.delete(endpoint)

        # check that we got an No Content (204) response
        self.assertEqual(response.status_code, 204, msg=response.data)

        # start checking data
        self.assertEqual(InsertOperation.objects.count(), 0)

    def test_delete_operation_404(self):
        """Test that we get a 404 when providing wrong operation info."""

        # query endpoint
        endpoint = reverse("pzone_operations_delete", kwargs={
            "pzone_pk": 1234,
            "operation_pk": 1234
        })
        response = self.client.delete(endpoint)

        # check that we got a 404
        self.assertEqual(response.status_code, 404)

    def test_get_applied(self):
        """Test that we can get a pzone applied when requesting to pzone detail
        without a preview time."""

        # make some testing stuff
        test_time = timezone.now() + datetime.timedelta(hours=-1)
        content_1 = self.pzone[0]
        content_2 = self.pzone[1]
        DeleteOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            content=content_1
        )
        DeleteOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            content=content_2
        )

        # setup endpoint
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        self.give_permissions()
        response = self.client.get(endpoint)

        # get updated pzone
        self.pzone = PZone.objects.get(name=self.pzone.name)

        # check response status
        self.assertEqual(response.status_code, 200)
        # check that response list is correct
        self.assertEqual(len(response.data["content"]), 8)
        self.assertNotEqual(response.data["content"][0]["id"], content_1.id)
        self.assertNotEqual(response.data["content"][0]["id"], content_2.id)
        # check that in db list is correct
        self.assertEqual(len(self.pzone), 8)
        self.assertNotEqual(self.pzone[0].id, content_1.id)
        self.assertNotEqual(self.pzone[0].id, content_2.id)
        # ensure we created a history object and its data matches
        self.assertEqual(self.pzone.history.count(), 1)
        self.assertEqual(self.pzone.history.all()[0].data, self.pzone.data)

    def test_get_preview(self):
        """Test that we can get a pzone preview."""

        # make some testing stuff
        test_time = timezone.now() + datetime.timedelta(hours=1)
        DeleteOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            content=self.pzone[0]
        )
        DeleteOperation.objects.create(
            pzone=self.pzone,
            when=test_time,
            content=self.pzone[1]
        )

        # setup endpoint
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        self.give_permissions()
        response = self.client.get(endpoint, {"preview": test_time.isoformat()})

        # check response status
        self.assertEqual(response.status_code, 200)
        # ensure nothing was actually deleted
        self.assertEqual(len(self.pzone), 10)
        # check that the preview has items deleted
        self.assertEqual(len(response.data["content"]), 8)

    def test_get_preview_403(self):
        """Ensure that we cannot get a preview if we don't have permission."""

        # create regular user
        regular_user_name = "regularuser"
        regular_user_pass = "12345"
        get_user_model().objects.create_user(
            regular_user_name,
            "regularguy@aol.com",
            regular_user_pass
        )
        self.client.login(username=regular_user_name, password=regular_user_pass)

        # setup endpoint and request
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        response = self.client.get(endpoint, {"preview": "1234"})

        self.assertEqual(response.status_code, 403)

    def test_put_pzone(self):
        """Ensure that PUTing a pzone works."""

        # swap two entries
        old_0 = self.pzone[0]
        old_1 = self.pzone[1]
        self.pzone[0], self.pzone[1] = self.pzone[1], self.pzone[0]

        # setup endpoint
        self.give_permissions()
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        response = self.client.put(
            endpoint,
            data=json.dumps({"content": self.pzone.data, "name": "homepage"}),
            content_type="application/json"
        )

        # check status
        self.assertEqual(
            response.status_code, 200,
            msg="Failed ({}): {}".format(response.status_code, response.data))

        # check that the pzone has been modified
        self.pzone = PZone.objects.get(name=self.pzone.name)
        self.assertEqual(self.pzone[0].id, old_1.id)
        self.assertEqual(self.pzone[1].id, old_0.id)

        # try to empy out the pzone
        self.pzone.data = []
        response = self.client.put(
            endpoint,
            data=json.dumps({"content": self.pzone.data, "name": "homepage"}),
            content_type="application/json"
        )
        self.assertEqual(
            response.status_code, 200,
            msg="Failed ({}): {}".format(response.status_code, response.data))
        self.pzone = PZone.objects.get(name=self.pzone.name)
        self.assertEqual(len(self.pzone), 0)

    def test_put_pzone_403(self):
        """Ensure that PUTing to a pzone without permission gives a 403."""

        # create regular user
        regular_user_name = "regularuser"
        regular_user_pass = "12345"
        get_user_model().objects.create_user(
            regular_user_name,
            "regularguy@aol.com",
            regular_user_pass
        )
        self.client.login(username=regular_user_name, password=regular_user_pass)

        # setup endpoint and make request
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        response = self.client.put(endpoint)

        self.assertEqual(response.status_code, 403)

    def test_get_past_pzone(self):
        """Ensure retrieving a past pzone accesses pzone history."""

        # create history, then take timestamp to test again, this order is important for timing
        content_id = make_content(title="whatever").id
        history = self.pzone.history.create(
            data=[{"id": content_id}]
        )
        test_time = timezone.now()

        cache.set('pzone-history-' + self.pzone.name, history)

        # retrieve data
        endpoint = reverse("pzone-detail", kwargs={"pk": self.pzone.pk})
        self.give_permissions()

        response = self.client.get(endpoint, {"preview": test_time.isoformat()})

        # check that history was used
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data["content"]), 1)
        self.assertEqual(response.data["content"][0]["id"], content_id)

    def test_get_operations_filtered_by_date_range(self):
        """Retrieve operations limited to a given date range."""

        test_time_now = timezone.now()

        test_time_lower_bound = test_time_now
        test_time_upper_bound = test_time_now + datetime.timedelta(hours=2)

        test_time_past = (test_time_now + datetime.timedelta(hours=-1)).replace(microsecond=0)
        test_time_future = (test_time_now + datetime.timedelta(hours=1)).replace(microsecond=0)
        test_time_out_of_range = test_time_upper_bound + datetime.timedelta(hours=1)

        # set up some test operations)
        # Past operations
        InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time_past,
            index=0,
            content=make_content(),
            applied=True
        )
        InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time_past,
            index=0,
            content=make_content(),
            applied=True
        )
        # Future operations
        op_future_1 = InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time_future,
            index=0,
            content=make_content(),
            applied=True
        )
        op_future_2 = InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time_future,
            index=0,
            content=make_content(),
            applied=True
        )
        # Out of range
        InsertOperation.objects.create(
            pzone=self.pzone,
            when=test_time_out_of_range,
            index=0,
            content=make_content(),
            applied=True
        )

        # query the endpoint
        endpoint = reverse("pzone_operations", kwargs={
            "pzone_pk": self.pzone.pk
        })
        response = self.client.get(endpoint, {
            "from": test_time_lower_bound,
            "to": test_time_upper_bound
        })

        # check that we got an OK response
        self.assertEqual(response.status_code, 200, msg=response.data)

        # start checking data
        operations = response.data
        self.assertEqual(len(operations), 2)

        self.assertEqual(operations[0]["id"], op_future_1.pk)
        self.assertEqual(operations[1]["id"], op_future_2.pk)


text:
%% Regress confounds for cortical thickness networks

clear all

%% inputs
path_csv = '/Users/AngelaTam/Desktop/adsf/model/preventad_model_20160408.csv';
path_data = '/Users/AngelaTam/Desktop/adsf/ct_subtypes_20160808/raw_ct_net_20160808.mat';
path_out = '/Users/AngelaTam/Desktop/adsf/ct_subtypes_20160808/regressed_ct_net_20160808.mat';
confs = {'age','gender'}; % names of variables to be regressed out in model csv

%% script starts here

load(path_data)
raw_stack = ct_net;
ct_sub = provenance.list_subject;
% Get dimensions of the data
n_sub = size(ct_net,1); % n subjects
n_vox = size(ct_net,2); % n voxels
n_net = size(ct_net,3); % n networks

% Read the csv
[tab,sid,ly,~] = niak_read_csv(path_csv);

n_conf = length(confs);
conf_ids = zeros(n_conf, 1);
for cid = 1:n_conf
    conf_name = confs{cid};
    cidx = find(strcmp(ly, conf_name));
    % Make sure we found the covariate
    if ~isempty(cidx)
        conf_ids(cid) = cidx;
    else
        error('Could not find column for %s in model file');
    end
    % Make sure there are no NaNs in the model
    if any(isnan(tab(:, cidx)))
        % Get the indices of the subjects
        missing = find(isnan(tab(:, cidx)));
        % Matlab error messages only allow for the double to iterate. Not
        % sure how we could tell them both the subject ID and the confound
        % name
        error('Subject #%d has missing data for one or more confounds. Please fix.\n', missing);
    end
end

% Match subjects in model with those we have data for
s_list = zeros(length(ct_sub), 1);
for ss = 1:length(ct_sub)
    ct_id = ct_sub{ss};
    l_sub = find(strcmp(sid, ct_id));
    if ~isempty(l_sub)
        s_list(ss) = l_sub;
    end
end

% Set up the model structure for the regression
opt_mod = struct;
opt_mod.flag_residuals = true;
m = struct;
m.x = zeros(length(s_list), n_conf+1);
for ss = 1:length(s_list)
    m.x(ss,:) = [1 tab(s_list(ss), conf_ids)];
end
stack = zeros(n_sub, n_vox, n_net);

% Loop through the networks for the regression
for net_id = 1:n_net
    % Get the correct network
    m.y = raw_stack(:, :, net_id);
    [res] = niak_glm(m, opt_mod);
    % Store the residuals in the confound stack
    stack(:, :, net_id) = res.e;
end

% Add the model information
provenance.model = struct;
provenance.model.matrix = m.x;
provenance.model.confounds = confs;

% Save the regressed stack and provenance info
save(path_out, 'provenance', 'stack')

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:\Users\Chrilieb\.cargo\registry\src\github.com-1ecc6299db9ec823\futures-0.1.14\src\executor.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>executor.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16

//! Executors
//!
//! This module contains tools for managing the raw execution of futures,
//! which is needed when building *executors* (places where futures can run).
//!
//! More information about executors can be [found online at tokio.rs][online].
//!
//! [online]: https://tokio.rs/docs/going-deeper-futures/tasks/

#[allow(deprecated)]
#[cfg(feature = "use_std")]
pub use task_impl::{Unpark, Executor, Run};

pub use task_impl::{Spawn, spawn, Notify};

pub use task_impl::{UnsafeNotify, NotifyHandle};

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
MStatus initializePlugin( MObject obj )
{
    printf("\n testProjection plugin is loaded -----------------------\n");

	MFnPlugin plugin( obj, "yaoyu", "1.0.0", "Any" );

	CHECK_MSTATUS(
        plugin.registerShape( "quadricShape", quadricShape::id,
                                           &quadricShape::creator,
                                           &quadricShape::initialize,
                                           &quadricShapeUI::creator  )
    );

	return( MS::kSuccess );
}

MStatus uninitializePlugin( MObject obj )
{
	MFnPlugin plugin( obj );

	CHECK_MSTATUS( plugin.deregisterNode( quadricShape::id ) );

	return MS::kSuccess;
}


text:
/* @flow */
import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
} from 'react-native'
import SegmentedControlTab from 'react-native-segmented-control-tab'

class SegmentedView extends Component<*, *> {
  constructor() {
    super()
    this.state = {
      selectedIndex: 0,
      selectedIndices: [0],
      customStyleIndex: 0,
    }
  }

    handleSingleIndexSelect = (index: number) => {
      this.setState(prevState => ({ ...prevState, selectedIndex: index }))
    }

    handleMultipleIndexSelect = (index: number) => {
      const { selectedIndices } = this.state

      if (selectedIndices.includes(index)) {
        this.setState(prevState => ({
          ...prevState,
          selectedIndices: selectedIndices.filter((i) => i !== index),
        }))
      } else {
        this.setState(prevState => ({
          ...prevState,
          selectedIndices: [
            ...selectedIndices,
            index,
          ],
        }))
      }
    }

    handleCustomIndexSelect = (index: number) => {
      this.setState(prevState => ({ ...prevState, customStyleIndex: index }))
    }

    render() {
      const { selectedIndex, selectedIndices, customStyleIndex } = this.state
      return (
        <View style={styles.container}>
          <Text style={styles.headerText}>Default segmented control with single selection</Text>
          <SegmentedControlTab
            selectedIndex={selectedIndex}
            tabStyle={styles.tabStyle}
            activeTabStyle={styles.activeTabStyle}
            onTabPress={this.handleSingleIndexSelect}
          />
          <View style={styles.Seperator} />
          <Text style={styles.headerText}>Default segmented control with multiple selection</Text>
          <SegmentedControlTab
            multiple
            selectedIndices={selectedIndices}
            onTabPress={this.handleMultipleIndexSelect}
          />
          <View style={styles.Seperator} />
          <Text style={styles.headerText}>Default segmented with badges</Text>
          <SegmentedControlTab
            badges={[1, 2, 3]}
            selectedIndex={selectedIndex}
            onTabPress={this.handleSingleIndexSelect}
          />
          <View style={styles.Seperator} />
          <Text style={styles.headerText}>Custom segmented control with custom styles</Text>
          <SegmentedControlTab
            values={['one', 'two']}
            selectedIndex={customStyleIndex}
            onTabPress={this.handleCustomIndexSelect}
            borderRadius={0}
            tabsContainerStyle={{ height: 50, backgroundColor: '#F2F2F2' }}
            tabStyle={{ backgroundColor: '#F2F2F2', borderWidth: 0, borderColor: 'transparent' }}
            activeTabStyle={{ backgroundColor: 'white', marginTop: 2 }}
            tabTextStyle={{ color: '#444444', fontWeight: 'bold' }}
            activeTabTextStyle={{ color: '#888888' }}
          />
          {customStyleIndex === 0
                    && <Text style={styles.tabContent}> Tab one</Text>}
          {customStyleIndex === 1
                    && <Text style={styles.tabContent}> Tab two</Text>}

        </View>
      )
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
    padding: 10,
  },
  tabViewText: {
    color: '#444444',
    fontWeight: 'bold',
    marginTop: 50,
    fontSize: 18,
  },
  titleText: {
    color: '#444444',
    padding: 20,
    fontSize: 14,
    fontWeight: '500',
  },
  headerText: {
    padding: 8,
    fontSize: 14,
    color: '#444444',
  },
  tabContent: {
    color: '#444444',
    fontSize: 18,
    margin: 24,
  },
  Seperator: {
    marginHorizontal: -10,
    alignSelf: 'stretch',
    borderTopWidth: 1,
    borderTopColor: '#888888',
    marginTop: 24,
  },
  tabStyle: {
    borderColor: '#D52C43',
  },
  activeTabStyle: {
    backgroundColor: '#D52C43',
  },
  tabTextStyle: {
    color: '#D52C43',
  },

})

export default SegmentedView


text:
package org.apache.hive.hcatalog.templeton.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/*
 * This is the base class for the output parser.
 * Output parser will parse the output of a Pig/
 * Hive/Hadoop or other job and extract jobid.
 * Note Hadoop jobid extract is rely on the API
 * Hadoop application submitting the job. Different
 * api will result in different console output. The
 * jobid extraction logic is not always working in
 * this case
 */
abstract class JobIDParser {
  private String statusdir;
  private Configuration conf;

  JobIDParser(String statusdir, Configuration conf) {
    this.statusdir = statusdir;
    this.conf = conf;
  }

  private BufferedReader openStatusFile(String fname) throws IOException {
    Path p = new Path(statusdir, fname);
    FileSystem fs = p.getFileSystem(conf);
    BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(p)));
    return in;
  }

  private List<String> findJobID(BufferedReader in, String patternAsString) throws IOException {
    Pattern pattern = Pattern.compile(patternAsString);
    Matcher matcher;
    String line;
    List<String> jobs = new ArrayList<String>();
    while ((line=in.readLine())!=null) {
      matcher = pattern.matcher(line);
      if (matcher.find()) {
        String jobid = matcher.group(1);
        jobs.add(jobid);
      }
    }
    return jobs;
  }

  abstract List<String> parseJobID() throws IOException;

  List<String> parseJobID(String fname, String pattern) throws IOException {
    BufferedReader in=null;
    try {
      in = openStatusFile(fname);
      List<String> jobs = findJobID(in, pattern);
      return jobs;
    } catch (IOException e) {
      throw e;
    } finally {
      if (in!=null) {
        in.close();
      }
    }
  }
}


text:
#include "stdafx.h"
#include "../libpainter/Designer.h"
#include "../libpainter/Point.h"
#include "../libpainter/ShapeFactory.h"
#include "../libpainter/PictureDraft.h"
#include "Canvas.h"

#include <SFML\Graphics.hpp>

using namespace std;

int main()
{
	sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
	CCanvas canvas(window);
	sf::CircleShape shape(100.f);
	sf::RectangleShape rect(sf::Vector2f(120, 50));

	/*std::string pic = "Rectangle 10 10 100 100 \nEllipse 10 10 10 20";
	std::istringstream ss(pic);
*/
	CShapeFactory f;
	CDesigner designer(f);
	//auto draft = designer.CreateDraft(ss);
	try
	{
		auto draft = designer.CreateDraft(cin);
		while (window.isOpen())
		{
			sf::Event event;
			while (window.pollEvent(event))
			{
				if (event.type == sf::Event::Closed)
					window.close();
			}

			window.clear();
			for (const auto & s : draft)
			{
				s.Draw(canvas);
				//window.display();
			}
			window.display();

		}
	}
	catch (std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}

	return 0;
}


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

namespace UIWidgets
{
	/// <summary>
	/// Range slider.
	/// </summary>
	[AddComponentMenu("UI/UIWidgets/RangeSlider")]
	public class RangeSlider : RangeSliderBase<int>
	{
		/// <summary>
		/// Value to position.
		/// </summary>
		/// <returns>Position.</returns>
		/// <param name="value">Value.</param>
		protected override float ValueToPosition(int value)
		{
			var points_per_unit = FillSize() / (limitMax - limitMin);

			return points_per_unit * (InBounds(value) - limitMin) + GetStartPoint();
		}

		/// <summary>
		/// Position to value.
		/// </summary>
		/// <returns>Value.</returns>
		/// <param name="position">Position.</param>
		protected override int PositionToValue(float position)
		{
			var points_per_unit = FillSize() / (limitMax - limitMin);

			var value = position / points_per_unit + LimitMin;

			if (WholeNumberOfSteps)
			{
				return InBounds(Mathf.RoundToInt(value / step) * step);
			}
			else
			{
				return InBounds(Mathf.RoundToInt(value));
			}
		}

		/// <summary>
		/// Position range for minimum handle.
		/// </summary>
		/// <returns>The position limits.</returns>
		protected override Vector2 MinPositionLimits()
		{
			return new Vector2(ValueToPosition(LimitMin), ValueToPosition(valueMax - step));
		}

		/// <summary>
		/// Position range for maximum handle.
		/// </summary>
		/// <returns>The position limits.</returns>
		protected override Vector2 MaxPositionLimits()
		{
			return new Vector2(ValueToPosition(valueMin + step), ValueToPosition(limitMax));
		}

		/// <summary>
		/// Fit value to bounds.
		/// </summary>
		/// <returns>Value.</returns>
		/// <param name="value">Value.</param>
		protected override int InBounds(int value)
		{
			return Mathf.Clamp(value, limitMin, limitMax);
		}

		/// <summary>
		/// Fit minumum value to bounds.
		/// </summary>
		/// <returns>Value.</returns>
		/// <param name="value">Value.</param>
		protected override int InBoundsMin(int value)
		{
			return Mathf.Clamp(value, limitMin, valueMax - step);
		}

		/// <summary>
		/// Fit maximum value to bounds.
		/// </summary>
		/// <returns>Value.</returns>
		/// <param name="value">Value.</param>
		protected override int InBoundsMax(int value)
		{
			return Mathf.Clamp(value, valueMin + step, valueMax);
		}

		/// <summary>
		/// Increases the minimum value.
		/// </summary>
		protected override void IncreaseMin()
		{
			ValueMin += step;
		}

		/// <summary>
		/// Decreases the minimum value.
		/// </summary>
		protected override void DecreaseMin()
		{
			ValueMin -= step;
		}

		/// <summary>
		/// Increases the maximum value.
		/// </summary>
		protected override void IncreaseMax()
		{
			ValueMax += step;
		}

		/// <summary>
		/// Decreases the maximum value.
		/// </summary>
		protected override void DecreaseMax()
		{
			ValueMax -= step;
		}
	}
}


text:
h1 {
    text-align: center;
}

textarea {
    width: 100%;
    box-sizing: border-box;
    background: #ffffff88;
}

.sheet-grid-container {
    display: grid;
    grid-template-columns: 360px 60px 235px 235px 60px 810px;
    grid-template-rows: 80px 1fr 50px max-content;
    gap: 0px 0px;
    grid-template-areas:
    ". . sheet-header sheet-header sheet-header ."
    "sheet-pc . sheet-abilities sheet-skills . sheet-bonds"
    "sheet-pc . . . . sheet-bonds"
    "sheet-pc . sheet-resources sheet-resources . sheet-moves";
    width: 1760px;
}

.sheet-bonds {
    grid-area: sheet-bonds;
}

.sheet-header {
    grid-area: sheet-header;
}

.sheet-pc {
    grid-area: sheet-pc;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: repeat(5, 30px) 55px repeat(2, 30px) 55px repeat(8, 30px);
    gap: 0px 0px;
    grid-template-areas:
    "sheet-name"
    "sheet-player"
    "sheet-fran"
    "sheet-arch"
    "sheet-vice-header"
    "sheet-vice-desc"
    "sheet-motive"
    "sheet-project-header"
    "sheet-project-desc"
    "sheet-faction"
    "sheet-plot-armor-header"
    "sheet-plot-armor-subheader"
    "sheet-plot-armor"
    "sheet-authority-header"
    "sheet-authority-line-one"
    "sheet-authority-line-two";
    margin: 0 5px;
}

.sheet-abilities {
    grid-area: sheet-abilities;

    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: repeat(6, max-content);
    gap: 0px 0px;
    grid-template-areas:
    "sheet-feats-header sheet-feats-header sheet-feats-header sheet-feats-header"
    "sheet-feats-sub sheet-feats-sub sheet-feats-sub sheet-feats-sub"
    "sheet-malice sheet-malice sheet-malice sheet-malice"
    "sheet-deceit sheet-deceit sheet-deceit sheet-deceit"
    "sheet-intimidation sheet-intimidation sheet-intimidation sheet-intimidation"
    "sheet-knowledge sheet-knowledge sheet-knowledge sheet-knowledge";
    margin: 0 5px;
}

.sheet-feats-header { grid-area: sheet-feats-header; }

.sheet-feats-sub { grid-area: sheet-feats-sub; }

.sheet-malice { grid-area: sheet-malice; }

.sheet-five-point-line {
    display: grid;
    grid-template-columns: 1fr max-content;
    grid-template-rows: 1fr;
}

.sheet-deceit { grid-area: sheet-deceit; }

.sheet-intimidation { grid-area: sheet-intimidation; }

.sheet-knowledge { grid-area: sheet-knowledge; }

.sheet-skills {
    grid-area: sheet-skills;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: repeat(10, max-content);
    gap: 0px 0px;
    grid-template-areas:
    "sheet-skills-headers sheet-skills-headers sheet-skills-headers sheet-skills-headers"
    "sheet-skills-sub sheet-skills-sub sheet-skills-sub sheet-skills-sub"
    "sheet-fight sheet-fight sheet-fight sheet-fight"
    "sheet-shooting sheet-shooting sheet-shooting sheet-shooting"
    "sheet-theft sheet-theft sheet-theft sheet-theft"
    "sheet-science sheet-science sheet-science sheet-science"
    "sheet-magic sheet-magic sheet-magic sheet-magic"
    "sheet-business sheet-business sheet-business sheet-business"
    "sheet-torture sheet-torture sheet-torture sheet-torture"
    "sheet-manipulation sheet-manipulation sheet-manipulation sheet-manipulation";
    margin: 0 5px;
}

.sheet-skills-headers { grid-area: sheet-skills-headers; }

.sheet-skills-sub { grid-area: sheet-skills-sub; }

.sheet-fight { grid-area: sheet-fight; }

.sheet-shooting { grid-area: sheet-shooting; }

.sheet-theft { grid-area: sheet-theft; }

.sheet-science { grid-area: sheet-science; }

.sheet-magic { grid-area: sheet-magic; }

.sheet-business { grid-area: sheet-business; }

.sheet-torture { grid-area: sheet-torture; }

.sheet-manipulation { grid-area: sheet-manipulation; }

.sheet-resources {
    grid-area: sheet-resources;

    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: repeat(3, max-content);
    gap: 0px 0px;
    grid-template-areas:
    "sheet-resource-header sheet-resource-header sheet-resource-header sheet-resource-header"
    "sheet-resource-sub sheet-resource-sub sheet-resource-sub sheet-resource-sub"
    "sheet-resource-personal sheet-resource-personal sheet-resource-org sheet-resource-org";
}

.sheet-resource-header { grid-area: sheet-resource-header; }

.sheet-resource-sub { grid-area: sheet-resource-sub; }

.sheet-resource-personal {
    grid-area: sheet-resource-personal;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
    "sheet-personal-header sheet-personal-header sheet-personal-header sheet-personal-header sheet-personal-header sheet-personal-header"
    "sheet-personal-servants sheet-personal-servants sheet-personal-servants sheet-personal-servants sheet-personal-servants sheet-personal-servants"
    "sheet-personal-wealth sheet-personal-wealth sheet-personal-wealth sheet-personal-wealth sheet-personal-wealth sheet-personal-wealth"
    "sheet-personal-power sheet-personal-power sheet-personal-power sheet-personal-power sheet-personal-power sheet-personal-power"
    "sheet-personal-base sheet-personal-base sheet-personal-base sheet-personal-base sheet-personal-base sheet-personal-base"
    "sheet-personal-weapon sheet-personal-weapon sheet-personal-weapon sheet-personal-weapon sheet-personal-weapon sheet-personal-weapon"
    "sheet-personal-reputation sheet-personal-reputation sheet-personal-reputation sheet-personal-reputation sheet-personal-reputation sheet-personal-reputation"
    "sheet-personal-prehistory sheet-personal-prehistory sheet-personal-prehistory sheet-personal-prehistory sheet-personal-prehistory sheet-personal-prehistory";
    margin: 0 5px;
}

.sheet-personal-header { grid-area: sheet-personal-header; }

.sheet-personal-servants { grid-area: sheet-personal-servants; }

.sheet-personal-wealth { grid-area: sheet-personal-wealth; }

.sheet-personal-power { grid-area: sheet-personal-power; }

.sheet-personal-base { grid-area: sheet-personal-base; }

.sheet-personal-weapon { grid-area: sheet-personal-weapon; }

.sheet-personal-reputation { grid-area: sheet-personal-reputation; }

.sheet-personal-prehistory { grid-area: sheet-personal-prehistory; }

.sheet-resource-org {
    grid-area: sheet-resource-org;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
    "sheet-org-header sheet-org-header sheet-org-header sheet-org-header sheet-org-header sheet-org-header"
    "sheet-org-servants sheet-org-servants sheet-org-servants sheet-org-servants sheet-org-servants sheet-org-servants"
    "sheet-org-wealth sheet-org-wealth sheet-org-wealth sheet-org-wealth sheet-org-wealth sheet-org-wealth"
    "sheet-org-power sheet-org-power sheet-org-power sheet-org-power sheet-org-power sheet-org-power"
    "sheet-org-base sheet-org-base sheet-org-base sheet-org-base sheet-org-base sheet-org-base"
    "sheet-org-weapon sheet-org-weapon sheet-org-weapon sheet-org-weapon sheet-org-weapon sheet-org-weapon"
    "sheet-org-reputation sheet-org-reputation sheet-org-reputation sheet-org-reputation sheet-org-reputation sheet-org-reputation"
    ". . . . . .";
    margin: 0 5px;
}
.sheet-org-header { grid-area: sheet-org-header; }

.sheet-org-servants { grid-area: sheet-org-servants; }

.sheet-org-wealth { grid-area: sheet-org-wealth; }

.sheet-org-power { grid-area: sheet-org-power; }

.sheet-org-base { grid-area: sheet-org-base; }

.sheet-org-weapon { grid-area: sheet-org-weapon; }

.sheet-org-reputation { grid-area: sheet-org-reputation; }

.sheet-moves {
    grid-area: sheet-moves;
    margin: 0 5px;
}

.sheet-name {
    grid-area: sheet-name;
}

.sheet-player {
    grid-area: sheet-player;
}

.sheet-fran {
    grid-area: sheet-fran;
}

.sheet-arch {
    grid-area: sheet-arch;
}

.sheet-motive {
    grid-area: sheet-motive;
}

.sheet-project-header {
    grid-area: sheet-project-header;
}

.sheet-project-desc {
    grid-area: sheet-project-desc;
    position: relative;
    cursor: text;
    word-wrap: break-word;
}
.sheet-vice-desc {
    grid-area: sheet-vice-desc;
    position: relative;
    cursor: text;
    word-wrap: break-word;
}

.sheet-vice-desc textarea,
.sheet-project-desc textarea {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    margin: 0;
    overflow: hidden;
    resize: none;
    height: 75%;
    width: 100%;
    display: block;
    box-sizing: border-box;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    color: inherit;
    font: inherit;
    letter-spacing: inherit;
    padding: inherit;
    text-align: inherit;
    text-transform: inherit;
}

.sheet-faction {
    grid-area: sheet-faction;
}

.sheet-plot-armor-header {
    grid-area: sheet-plot-armor-header;
}

.sheet-plot-armor-subheader {
    grid-area: sheet-plot-armor-subheader;
}

.sheet-plot-armor {
    grid-area: sheet-plot-armor;
}

.sheet-authority-header {
    grid-area: sheet-authority-header;
}

.sheet-authority-line-one {
    grid-area: sheet-authority-line-one;
}

.sheet-authority-line-two {
    grid-area: sheet-authority-line-two;

}

.sheet-input-attribute-no-roll {
    display: flex;
    align-items: baseline;
}

.sheet-wide {
    flex: 5 0 240px;
}

.sheet-counter-line {
    display: flex;
    width: 100%;
}

.sheet-pony {
    font-style: italic;
    font-size: x-small;
}

.sheet-dots{
    display:flex;
}
button.sheet-dot {
    padding: 0;
    margin: 1px;
    border: solid 2px black;
    background: white;
    cursor: pointer;
    width: 10px;
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}

button.sheet-dot > span {
    width: 10px;
    height: 10px;
    background: #d80017;
}

input.sheet-dot[value="0"] ~ button.sheet-gt-0 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="1"] ~ button.sheet-gt-1 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="2"] ~ button.sheet-gt-2 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="3"] ~ button.sheet-gt-3 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="4"] ~ button.sheet-gt-4 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="5"] ~ button.sheet-gt-5 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="6"] ~ button.sheet-gt-6 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="7"] ~ button.sheet-gt-7 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="8"] ~ button.sheet-gt-8 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="9"] ~ button.sheet-gt-9 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="10"] ~ button.sheet-gt-10 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="11"] ~ button.sheet-gt-11 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="12"] ~ button.sheet-gt-12 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="13"] ~ button.sheet-gt-13 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="14"] ~ button.sheet-gt-14 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="15"] ~ button.sheet-gt-15 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="16"] ~ button.sheet-gt-16 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="17"] ~ button.sheet-gt-17 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="18"] ~ button.sheet-gt-18 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="19"] ~ button.sheet-gt-19 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="20"] ~ button.sheet-gt-20 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="21"] ~ button.sheet-gt-21 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="22"] ~ button.sheet-gt-22 > span.sheet-checked {
    display: none;
}
input.sheet-dot[value="23"] ~ button.sheet-gt-23 > span.sheet-checked {
    display: none;
}

button.sheet-zero
{
    opacity: 0;
}

button.sheet-zero:hover {
    opacity: 0.25;
}

.sheet-move-main {
    display: flex;
    align-items: baseline;
    justify-content: space-around;
}

.sheet-move-select {
    flex: 0 1 50px;
}

.sheet-move-label {
    flex: 0 1 10px;
}

.sheet-rolltemplate-customcheck {
    border: 2px solid black;
    background: white;
    text-align: center;
}

.sheet-rolltemplate-check-result {
    background: #d80017;
    color: white;
    font-weight: bold;
    text-align: center;
}

.sheet-moves-button {
    background: #d80017;
    word-wrap: break-word;
    color: white;
    text-align: center;
    padding: 0;
    margin: 1px;
    border: solid 2px black;
    cursor: pointer;
}

.sheet-overlay {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    transition: opacity 500ms;
    visibility: hidden;
    opacity: 0;
    z-index: 5;
    overflow: scroll;
}
.sheet-overlay:target {
    visibility: visible;
    opacity: 1;
}
.sheet-popup {
    margin: 70px auto;
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    width: 50%;
    position: relative;
    transition: all 5s ease-in-out;
}
.sheet-popup h2 {
    margin-top: 0;
    color: #333;
    font-family: Tahoma, Arial, sans-serif;
}
.sheet-popup .sheet-close {
    position: absolute;
    top: 20px;
    right: 30px;
    transition: all 200ms;
    font-size: 30px;
    font-weight: bold;
    text-decoration: none;
    color: #333;
}
.sheet-popup .sheet-content {
    max-height: 30%;
}


text:
/*globals describe, require */

var LinearRegression = require('./index').LinearRegression,
    assert = require('assert'),
    euclideanDistance = require('./index').euclideanDistance,
    sinon = require('sinon');

var fixtures = {};

var EPSILON = 0.01; // used to compare floats

describe('LinearRegresssion', function() {
  describe('initialization', function() {
    it('can be initialized with no parameters', function(done) {
      var lr = new LinearRegression();
      assert.ok(lr);
      done();
    });

    it('should throw an error if X is not an array', function(done) {
      var x = 'a string';
      assert.throws(function() {
        var lr = new LinearRegression(x);
      }, Error);
      done();
    });

    it('should throw an error if Y is not an array', function(done) {
      var x = [1];
      var y = 'a string';
      assert.throws(function() {
        var lr = new LinearRegression(x, y);
      }, Error);
      done();
    });
  });

  describe('addColumnOne', function() {
    it('should append a column on all 1 in front of the matrix', function(done) {
      var X = [[4,5], [6,7]];
      var newX = LinearRegression.addColumnOne(X);
      assert.equal(1, newX.e(1,1));
      assert.equal(1, newX.e(2,1));
      assert.equal(4, newX.e(1,2));
      assert.equal(5, newX.e(1,3));
      assert.equal(6, newX.e(2,2));
      assert.equal(7, newX.e(2,3));
      done();
    });
  });

  describe('normalize', function() {
    it('should normalize features correctly', function(done) {
      var features = [[10, 2], [15,2], [20, 2]];
      var lr = new LinearRegression(features, [2,4,5]);
      var X = LinearRegression.addColumnOne(features);
      var normalizedX = lr.normalize(X);
      assert.equal(1, normalizedX.e(1,1));
      assert.equal(1, normalizedX.e(2,1));
      assert.equal(1, normalizedX.e(3,1));
      assert.equal(-0.5, normalizedX.e(1,2));
      assert.equal(0, normalizedX.e(2,2));
      assert.equal(0.5, normalizedX.e(3,2));
      assert.equal(-0, normalizedX.e(1,3));
      assert.equal(0, normalizedX.e(2,3));
      assert.equal(0, normalizedX.e(3,3));
      done();
    });
  });

  describe('train', function() {
    it('should throw an error if there is no data in X', function(done) {
      var lr = new LinearRegression();
      lr.train(function(err) {
        assert.ok(err);
        assert.equal(err.message, 'X is empty');
        done();
      });
    });
    it('should throw an error if there is no data in Y', function(done) {
      var lr = new LinearRegression([0,1,2,3]);
      lr.train(function(err) {
        assert.ok(err);
        assert.equal(err.message, 'Y is empty');
        done();
      });
    });
    it('should throw an error if X and Y have different length', function(done) {
      var lr = new LinearRegression([0,1,2], [0]);
      lr.train(function(err) {
        assert.ok(err);
        assert.equal(err.message, 'X and Y must be of the same length');
        done();
      });
    });
    it('should throw an error on vertical line since we cannot inverse matrix', function(done) {
      var lr = new LinearRegression([0, 0], [1,0]);
      lr.train(function(err) {
        assert.ok(err);
        assert.equal(err.message, 'could not inverse the matrix in normal equation. Try to use Gradient Descent instead.');
        done();
      });
    });
    it('should not save cost function if we are using Normal Equation', function(done) {
      var lr = new LinearRegression([0,1,2,3,4,5,6,7], [0,2,4,3,7,6,8,9], {algorithm: 'NormalEquation'});
      lr.train(function(err) {
        assert.ok(!err);
        assert.ok(!lr.costs);
        done();
      });
    });
    it('should save cost function if using Gradient Descent and asked to do so', function(done) {
      var lr = new LinearRegression([0,1,2,3,4,5,6,7], [0,2,4,3,7,6,8,9], {
        algorithm: 'GradientDescent',
        saveCosts: true,
        learningRate: 0.1,
        numberOfIterations: 100
      });
      lr.train(function(err) {
        assert.ok(!err);
        assert.ok(lr.costs);
        assert.equal(lr.costs.length, 100);
        done();
      });
    });
  });

  describe('predict', function() {
    it('should throw an error if called before training', function(done) {
      var lr = new LinearRegression([0,1,2,3,4], [1,3,4,5,6]);
      assert.throws(function() {
        lr.predict(1);
      }, Error);
      done();
    });
  });

  function predictionTests() {
    describe('simple linear regression', function() {
      it('should correctly generates a line for a 0,0 to 1,1 dataset (slope of 1)', function(done) {
        var lr = new LinearRegression([0, 1], [0,1], fixtures.options);
        lr.train(function(err) {
          assert.ok(lr.predict(0) - 0 < EPSILON);
          assert.ok(lr.predict(0.5) -  0.5 < EPSILON);
          assert.ok(lr.predict(1) - 1 < EPSILON);
          done();
        });
      });
      it('should correctly generates a line for a (0,0) to (1,0) dataset (horizontal line)', function(done) {
        var lr = new LinearRegression([0, 1], [0,0], fixtures.options);
        lr.train(function(err) {
          assert.equal(lr.predict(0), 0);
          assert.equal(lr.predict(0.5), 0);
          assert.equal(lr.predict(1), 0);
          done();
        });
      });
      it('should correctly generates a line for a (0,5) to (1,5) dataset (horizontal line)', function(done) {
        var lr = new LinearRegression([0, 1], [5,5], fixtures.options);
        lr.train(function(err) {
          assert.ok(lr.predict(0) - 5 < EPSILON);
          assert.ok(lr.predict(0.5) - 5 < EPSILON);
          assert.ok(lr.predict(1) - 5 < EPSILON);
          done();
        });
      });
      it('should handle single point input of (0,0)', function(done) {
        var lr = new LinearRegression([0], [0], fixtures.options);
        lr.train(function(err) {
          assert.equal(lr.predict(10), 0);
          done();
        });
      });
      it('should handle a single point example by returning y-intercept', function(done) {
        var lr = new LinearRegression([0], [1], fixtures.options);
        lr.train(function(err) {
          assert.equal(lr.predict(5), 5);
          done();
        });
      });
      it('should predict a simple example correctly', function(done) {
        var lr = new LinearRegression([1, 2, 3, 4, 5], [2, 2, 3, 3, 5], fixtures.options);
        lr.train(function(err) {
          assert.ok(lr.predict(0) - 0.899 < EPSILON);
          assert.ok(lr.predict(1) - 1.599 < EPSILON);
          assert.ok(lr.predict(2) - 2.3 < EPSILON);
          assert.ok(lr.predict(3) - 2.999 < EPSILON);
          assert.ok(lr.predict(4) - 3.699 < EPSILON);
          assert.ok(lr.predict(5) - 4.4 < EPSILON);
          assert.ok(lr.predict(10) - 7.9 < EPSILON);
          done();
        });
      });
    });
    describe('multiple linear regression', function() {
      it('should predict a simple example correctly');
    });
  }

  describe('train and predict', function() {
    it('should train with Normal Equation by default', function(done) {
      var lr = new LinearRegression([1, 2, 3, 4, 5], [2, 2, 3, 3, 5]);
      assert.ok(lr.algorithm, 'NormalEquation');
      var spy = sinon.spy(lr, 'trainWithNormalEquation');
      lr.train(function(err) {
        assert.ok(spy.called);
        done();
      });
    });
    it('should train with Normal Equation if asked to do so', function(done) {
      var lr = new LinearRegression([1, 2, 3, 4, 5], [2, 2, 3, 3, 5], {algorithm: 'NormalEquation'});
      assert.ok(lr.algorithm, 'NormalEquation');
      var spy = sinon.spy(lr, 'trainWithNormalEquation');
      lr.train(function(err) {
        assert.ok(spy.called);
        done();
      });
    });
    it('should train with GradientDescent if asked to do so', function(done) {
      var lr = new LinearRegression([1, 2, 3, 4, 5], [2, 2, 3, 3, 5], {algorithm: 'GradientDescent'});
      assert.ok(lr.algorithm, 'GradientDescent');
      var spy = sinon.spy(lr, 'trainWithGradientDescent');
      lr.train(function(err) {
        assert.ok(spy.called);
        done();
      });
    });
    describe('with Normal Equation', function() {
      predictionTests();
    });
    describe('with Gradient Descent', function() {
      beforeEach(function(callback) {
        fixtures.options = {algorithm: 'GradientDescent'};
        return callback();
      });
      predictionTests();
      describe('multiple linear regression', function() {
        it('should correctly generates a line for a [0,0] -> 0 and [1,1]  -> 1 dataset', function(done) {
          var lr = new LinearRegression([[0,0], [1,1]], [0,1], fixtures.options);
          lr.train(function(err) {
            assert.ok(!err, err);
            assert.ok(lr.predict([0,0]) - 0 < EPSILON);
            assert.ok(lr.predict([0.5,0.5]) -  0.5 < EPSILON);
            assert.ok(lr.predict([1,1]) - 1 < EPSILON);
            done();
          });
        });
      });
    });
  });
});

describe('Euclidean Distance', function() {
  it('the euclidean distance between two identical vectors should be zero', function(done) {
    var a = [5,5];
    var b = [5,5];
    assert.equal(euclideanDistance(a,b), 0);
    done();
  });
  it('should calculate the euclidean distance between two vectors of size 2', function(done) {
    var a = [5,5];
    var b = [0,0];
    assert.equal(euclideanDistance(a,b), 7.0710678118654755);
    done();
  });
});


text:
typedef void(^UIPinchGestureRecognizerEasyCoderBlock) (UIPinchGestureRecognizer * ins);

@interface UIPinchGestureRecognizer (TFEasyCoder)

+( UIPinchGestureRecognizer *)easyCoder:(UIPinchGestureRecognizerEasyCoderBlock)block;
-(UIPinchGestureRecognizer *)easyCoder:(UIPinchGestureRecognizerEasyCoderBlock)block;

-(UIPinchGestureRecognizer  *(^)(double  scale))set_scale;

//superclass pros UIGestureRecognizer
-(UIPinchGestureRecognizer  *(^)(BOOL  enabled))set_enabled;
-(UIPinchGestureRecognizer  *(^)(BOOL  cancelsTouchesInView))set_cancelsTouchesInView;
-(UIPinchGestureRecognizer  *(^)(BOOL  delaysTouchesBegan))set_delaysTouchesBegan;
-(UIPinchGestureRecognizer  *(^)(BOOL  delaysTouchesEnded))set_delaysTouchesEnded;
-(UIPinchGestureRecognizer  *(^)(NSArray *  allowedTouchTypes))set_allowedTouchTypes;
-(UIPinchGestureRecognizer  *(^)(NSArray *  allowedPressTypes))set_allowedPressTypes;
//superclass pros NSObject
-(UIPinchGestureRecognizer  *(^)(NSArray *  accessibilityElements))set_accessibilityElements;
-(UIPinchGestureRecognizer  *(^)(NSArray *  accessibilityCustomActions))set_accessibilityCustomActions;
-(UIPinchGestureRecognizer  *(^)(BOOL  isAccessibilityElement))set_isAccessibilityElement;
-(UIPinchGestureRecognizer  *(^)(NSString *  accessibilityLabel))set_accessibilityLabel;
-(UIPinchGestureRecognizer  *(^)(NSString *  accessibilityHint))set_accessibilityHint;
-(UIPinchGestureRecognizer  *(^)(NSString *  accessibilityValue))set_accessibilityValue;
-(UIPinchGestureRecognizer  *(^)(unsigned long long  accessibilityTraits))set_accessibilityTraits;
-(UIPinchGestureRecognizer  *(^)(UIBezierPath *  accessibilityPath))set_accessibilityPath;
-(UIPinchGestureRecognizer  *(^)(CGPoint  accessibilityActivationPoint))set_accessibilityActivationPoint;
-(UIPinchGestureRecognizer  *(^)(NSString *  accessibilityLanguage))set_accessibilityLanguage;
-(UIPinchGestureRecognizer  *(^)(BOOL  accessibilityElementsHidden))set_accessibilityElementsHidden;
-(UIPinchGestureRecognizer  *(^)(BOOL  accessibilityViewIsModal))set_accessibilityViewIsModal;
-(UIPinchGestureRecognizer  *(^)(BOOL  shouldGroupAccessibilityChildren))set_shouldGroupAccessibilityChildren;
-(UIPinchGestureRecognizer  *(^)(long long  accessibilityNavigationStyle))set_accessibilityNavigationStyle;

-(UIPinchGestureRecognizer *(^)(id value,NSString *key))set_ValueKey;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>three.js - foliage demo</title>

        Loading foliage ...

        Click to play


text:
This document contains a list of pre-defined syscalls
for the SuperVM.

## 0: Exit
This syscall quits the execution of the current program.
It takes no inputs and does not output any value.

## 1: putc(char)
This syscalls prints a single ASCII character which is
stored in *Input0*. It has no outputs.

## 2: puti(int)
This syscalls prints an unsigned integer which is stored
in *Input0*. It has no outputs.

## 3:

## 4:

## 5:

## 6:


text:
<?php
namespace Disqontrol\Exception;

/**
 * @author Martin Patera <mzstic@gmail.com>
 */
class FilesystemException extends \RuntimeException
{
    public static function directoryProblem($dir, $name, $operation)
    {
        return new static(sprintf("Unable to %s the %s directory (%s)\n", $operation, $name, $dir));
    }

    public static function cantCreateDirectory($dir, $name)
    {
        return static::directoryProblem($dir, $name, 'create');
    }

    public static function cantWriteDirectory($dir, $name)
    {
        return static::directoryProblem($dir, $name, 'write');
    }
}


text:
function test() {
    var cats = new Array<WAWA>(); // WAWA is not a valid type
}

//// [invalidSymbolInTypeParameter1.js]
function test() {
    var cats = new Array(); // WAWA is not a valid type
}


text:
<stack>

  <name>quad_cv</name>
  <version>0.0</version>
  <description brief="quadrotor_computer_vision">
    Computer Vision stuff for use with GAVLab's quadrotor</description>
  <author>Robert Cofield</author>
  <maintainer email="robertgcofield@gmail.com">
    Robert G. Cofield</maintainer>
  <license>BSD</license>
  <copyright>GAVLab</copyright>
  <url>https://github.com/ozymandium/quad_cv/wiki</url>

  <depend stack="ros" />
  <depend stack="vision_opencv" />
  <depend stack="openni_kinect"/> <!-- includes all openni stuff -->
  <depend stack="camera_umd"/>
  <depend stack="image_pipeline"/>
  <depend stack="bosch_drivers"/>
  <depend stack="image_common" />
  <depend package="gencam_cu"/>
  <depend package="rospy" />
  <!-- <depend package="std_msgs" /> -->
  <depend stack="common_msgs" />
  <depend stack="ros_comm" />
  <depend stack="multi_master_fkie"/>
  <depend stack="navigation"/>

</stack>


text:
<?php

/**
 * This is the model class for table "mail_template".
 *
 * The followings are the available columns in table 'mail_template':
 *
 * @property string $id
 * @property string $event_id
 * @property string $name
 * @property string $description
 * @property string $from
 * @property string $to
 * @property string $theme
 * @property string $body
 * @property integer $status
 *
 * The followings are the available model relations:
 * @property MailEvent $event
 *
 * MailTemplate model class
 * Класс модели MailTemplate
 *
 * @category YupeModel
 * @package  yupe.modules.models
 * @author   YupeTeam <team@yupe.ru>
 * @license  BSD https://raw.github.com/yupe/yupe/master/LICENSE
 * @link     http://yupe.ru
 **/
class MailTemplate extends yupe\models\YModel
{
    const STATUS_ACTIVE = 1;
    const STATUS_NOT_ACTIVE = 0;

    /**
     * Returns the static model of the specified AR class.
     *
     * @param string $className active record class name.
     *
     * @return MailTemplate the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * Получаем имя таблицы:
     *
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{mail_mail_template}}';
    }

    /**
     * Получаем правила валидации полей таблицы:
     *
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return [
            ['code, name, from, to, theme', 'filter', 'filter' => [$obj = new CHtmlPurifier(), 'purify']],
            ['event_id, code, name, from, to, theme, body', 'required'],
            ['status', 'numerical', 'integerOnly' => true],
            ['event_id', 'length', 'max' => 10],
            ['name, from, to', 'length', 'max' => 300],
            ['code', 'length', 'max' => 100],
            ['code', 'unique'],
            ['description', 'safe'],
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            ['id, event_id, name, description, from, to, theme, body, status', 'safe', 'on' => 'search'],
        ];
    }

    /**
     * Получаем связи данной таблицы:
     *
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return [
            'event' => [self::BELONGS_TO, 'MailEvent', 'event_id'],
        ];
    }

    /**
     * Получаем атрибуты меток полей данной таблицы:
     *
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return [
            'id'          => Yii::t('MailModule.mail', 'ID'),
            'event_id'    => Yii::t('MailModule.mail', 'Event'),
            'name'        => Yii::t('MailModule.mail', 'Title'),
            'description' => Yii::t('MailModule.mail', 'Description'),
            'from'        => Yii::t('MailModule.mail', 'From'),
            'to'          => Yii::t('MailModule.mail', 'For'),
            'theme'       => Yii::t('MailModule.mail', 'Topic'),
            'body'        => Yii::t('MailModule.mail', 'Message'),
            'code'        => Yii::t('MailModule.mail', 'Symbolic code'),
            'status'      => Yii::t('MailModule.mail', 'Status'),
        ];
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria();

        $criteria->compare('id', $this->id, true);
        $criteria->compare('event_id', $this->event_id, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('`from`', $this->from, true);
        $criteria->compare('`to`', $this->to, true);
        $criteria->compare('theme', $this->theme, true);
        $criteria->compare('body', $this->body, true);
        $criteria->compare('status', $this->status);

        return new CActiveDataProvider(get_class($this), ['criteria' => $criteria]);
    }

    /**
     * Получаем массив статусов:
     *
     * @return array status
     **/
    public function getStatusList()
    {
        return [
            self::STATUS_ACTIVE     => Yii::t('MailModule.mail', 'active'),
            self::STATUS_NOT_ACTIVE => Yii::t('MailModule.mail', 'not active'),
        ];
    }

    /**
     * Получаем статусов записи:
     *
     * @return string status
     **/
    public function getStatus()
    {
        $data = $this->statusList;

        return isset($data[$this->status]) ? $data[$this->status] : Yii::t('MailModule.mail', '--unknown--');
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WatchModeSymbol = Symbol('WatchMode');
var CheckerPlugin = (function () {
    function CheckerPlugin() {
    }
    CheckerPlugin.prototype.apply = function (compiler) {
        compiler.plugin("run", function (params, callback) {
            compiler[exports.WatchModeSymbol] = false;
            callback();
        });
        compiler.plugin("watch-run", function (params, callback) {
            compiler[exports.WatchModeSymbol] = true;
            callback();
        });
    };
    return CheckerPlugin;
}());
exports.CheckerPlugin = CheckerPlugin;
//# sourceMappingURL=watch-mode.js.map


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Ximbó</logradouro><bairro>Aclimação</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>04108040</cep></feed>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace PurdueIo.Database.Models
{
    public class Course
    {
        public Guid Id { get; set; }

        // 6 digit code used to identify this course inside of a subject, e.g. "26500" for "MA26500"
        [StringLength(16)]
        public string Number { get; set; }

        // ID of the subject this course belongs to
        public Guid SubjectId { get; set; }

        // Subject this course belongs to
        public virtual Subject Subject { get; set; }

        // Title of the course, e.g. "Intro to Computers"
        public string Title { get; set; }

        // Number of credit hours earned by taking this course
        public double CreditHours { get; set; }

        // Short blurb describing the course
        public string Description { get; set; }

        // Classes that belong to this course
        public virtual ICollection<Class> Classes { get; set; }
    }
}


text:
namespace content {

class CONTENT_EXPORT LocalSetDeclaration {
 public:
  LocalSetDeclaration();

  explicit LocalSetDeclaration(
      const std::string& use_first_party_set_flag_value);

  ~LocalSetDeclaration();

  LocalSetDeclaration(const LocalSetDeclaration&);
  LocalSetDeclaration& operator=(const LocalSetDeclaration&);
  LocalSetDeclaration(LocalSetDeclaration&&);
  LocalSetDeclaration& operator=(LocalSetDeclaration&&);

  bool empty() const { return !parsed_set_.has_value(); }

  size_t size() const { return empty() ? 0 : GetSet().size(); }

  // Gets the set entries. Must not be called if `empty()` returns true.
  const FirstPartySetParser::SingleSet& GetSet() const;

 private:
  explicit LocalSetDeclaration(
      absl::optional<FirstPartySetParser::SingleSet> parsed_set);

  // Stores the result of parsing the inputs. Specifically, this may be empty if
  // no set was locally defined; otherwise, it holds the collection of
  // FirstPartySetEntries and any ccTLD aliases.
  absl::optional<FirstPartySetParser::SingleSet> parsed_set_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_FIRST_PARTY_SETS_LOCAL_SET_DECLARATION_H_


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BooksLibrary.Models
{
    public class Comment
    {
        public int Id { get; set; }

        [Required]
        [MinLength(2)]
        [MaxLength(200)]
        public string Content { get; set; }

        public string UserId { get; set; }

        public virtual User User{ get; set; }

        public int BookId { get; set; }

        public virtual Book Book { get; set; }

        [Required]
        public DateTime Date { get; set; }
    }
}


text:
package org.kie.workbench.common.screens.social.hp.security;

import org.guvnor.structure.backend.repositories.RepositoryServiceImpl;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.guvnor.structure.social.OrganizationalUnitEventType;
import org.kie.uberfire.social.activities.model.SocialActivitiesEvent;
import org.kie.uberfire.social.activities.service.SocialSecurityConstraint;
import org.uberfire.security.authz.AuthorizationManager;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

@ApplicationScoped
public class SocialEventOUConstraint implements SocialSecurityConstraint {

    private OrganizationalUnitService organizationalUnitService;

    private AuthorizationManager authorizationManager;

    private RepositoryServiceImpl repositoryService;

    private UserCDIContextHelper userCDIContextHelper;

    private Collection<OrganizationalUnit> authorizedOrganizationalUnits = new HashSet<OrganizationalUnit>();

    public SocialEventOUConstraint() {
        //Zero argument constructor for CDI proxies
    }

    @Inject
    public SocialEventOUConstraint( final OrganizationalUnitService organizationalUnitService,
                                    final AuthorizationManager authorizationManager,
                                    final RepositoryServiceImpl repositoryService,
                                    final UserCDIContextHelper userCDIContextHelper ) {

        this.organizationalUnitService = organizationalUnitService;
        this.authorizationManager = authorizationManager;
        this.repositoryService = repositoryService;
        this.userCDIContextHelper = userCDIContextHelper;
    }

    @Override
    public void init() {
        if ( userCDIContextHelper.thereIsALoggedUserInScope() ) {
            authorizedOrganizationalUnits = getAuthorizedOrganizationUnits();
        }
    }

    public boolean hasRestrictions( SocialActivitiesEvent event ) {
        if ( !userCDIContextHelper.thereIsALoggedUserInScope() ) {
            return false;
        }

        if ( isOUSocialEvent( event ) ) {
            return hasRestrictionsForThisOU( event );
        }
        return false;
    }

    private boolean hasRestrictionsForThisOU( SocialActivitiesEvent event ) {
        for ( OrganizationalUnit authorizedOrganizationalUnit : authorizedOrganizationalUnits ) {
            if ( authorizedOrganizationalUnit.getName().equals( event.getLinkTarget() ) ) {
                return false;
            }
        }
        return true;
    }

    private boolean isOUSocialEvent( SocialActivitiesEvent event ) {
        if ( event.getLinkType().equals( SocialActivitiesEvent.LINK_TYPE.CUSTOM ) ) {
            if ( isAOUSocialEvent( event ) ) {
                return true;
            }
        }
        return false;
    }

    private boolean isAOUSocialEvent( SocialActivitiesEvent event ) {
        for ( OrganizationalUnitEventType organizationalUnitEventType : OrganizationalUnitEventType.values() ) {
            if ( event.getType().equals( organizationalUnitEventType.name() ) ) {
                return true;
            }
        }
        return false;
    }

    Collection<OrganizationalUnit> getAuthorizedOrganizationUnits() {
        final Collection<OrganizationalUnit> organizationalUnits = organizationalUnitService.getOrganizationalUnits();
        final Collection<OrganizationalUnit> authorizedOrganizationalUnits = new ArrayList<OrganizationalUnit>();
        for ( OrganizationalUnit ou : organizationalUnits ) {
            if ( authorizationManager.authorize( ou,
                                                 userCDIContextHelper.getUser() ) ) {
                authorizedOrganizationalUnits.add( ou );
            }
        }
        return authorizedOrganizationalUnits;
    }

}


text:
import React from 'react';
import Header from './Header';
import Footer from './Footer';
import Home from './Home';
import agent from '../agent';
import { connect } from 'react-redux';

const mapStateToProps = state => ({
  appName: state.common.appName,
  currentUser: state.common.currentUser,
  redirectTo: state.common.redirectTo
});

const mapDispatchToProps = dispatch => ({
  onLoad: (payload, token) => dispatch({ type: 'APP_LOAD', payload, token }),
  onRedirect: () => dispatch({ type: 'REDIRECT' })
});

class App extends React.Component {
  componentWillMount() {
    const token = window.localStorage.getItem('jwt');
    if (token) {
      agent.setToken(token);
    }

    this.props.onLoad(token ? agent.Auth.current() : null, token);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.redirectTo) {
      this.context.router.replace(nextProps.redirectTo);
      this.props.onRedirect();
    }
  }
  render() {
    return (
      <div className="container-fluid" id="main-container">
        <Header currentUser={this.props.currentUser} />
        {this.props.children}
        <Footer />
      </div>
    );
  }
}

App.contextTypes = {
  router: React.PropTypes.object.isRequired
};

export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
obj-$(FLOW_NODE_TYPE_STRING) += string.mod
obj-string-$(FLOW_NODE_TYPE_STRING) := string.json string-uuid.o string-common.o

ifeq (y,$(USE_ICU))
obj-string-$(FLOW_NODE_TYPE_STRING) += string-icu.o string-replace-icu.o
else
obj-string-$(FLOW_NODE_TYPE_STRING) += string-ascii.o string-replace-ascii.o
warning-msg += "You're building the string nodes module without i18n support. That way, some nodes will only act properly on pure ASCII input, not the intended UTF-8 for Soletta. Please re-configure after you have ICU development packages installed to get the intended string nodes behavior."
endif

obj-string-$(FLOW_NODE_TYPE_STRING)-extra-cflags += $(LOCALE_CFLAGS)
obj-string-$(USE_ICU)-extra-cflags += $(ICU_CFLAGS)

obj-string-$(FLOW_NODE_TYPE_STRING)-extra-ldflags += $(LOCALE_LDFLAGS)
obj-string-$(USE_ICU)-extra-ldflags += $(ICU_LDFLAGS)

obj-string-$(FLOW_NODE_TYPE_STRING)-type := flow

requires-private-$(FLOW_NODE_TYPE_STRING) := \
    $(ICU_REQUIRES_PRIVATE)


text:
import pytest
from .test_base_class import TestBaseClass
from aerospike import exception as e

import aerospike

# @pytest.mark.usefixtures("as_connection")

class TestAppend(object):
    @pytest.fixture(autouse=True)
    def setup(self, request, as_connection):
        """
        Setup Method
        """
        for i in range(5):
            key = ("test", "demo", i)
            rec = {"name": "name%s" % (str(i)), "age": i}
            as_connection.put(key, rec)

        key = ("test", "demo", "bytearray_key")
        as_connection.put(key, {"bytearray_bin": bytearray("asd;as[d'as;d", "utf-8")})

        key = ("test", "demo", "bytes_key")
        as_connection.put(key, {"bytes_bin": b""})

        def teardown():
            """
            Teardown Method
            """
            for i in range(5):
                key = ("test", "demo", i)
                as_connection.remove(key)

            key = ("test", "demo", "bytearray_key")
            as_connection.remove(key)

            key = ("test", "demo", "bytes_key")
            as_connection.remove(key)

        request.addfinalizer(teardown)

    def test_pos_append_with_correct_paramters(self):
        """
        Invoke append() with correct parameters
        """
        key = ("test", "demo", 1)
        self.as_connection.append(key, "name", "str")

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}

    def test_pos_append_with_correct_policies(self):
        """
        Invoke append() with correct policies
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "commit_level": aerospike.POLICY_COMMIT_LEVEL_MASTER,
        }
        self.as_connection.append(key, "name", "str", {}, policy)

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}

    def test_pos_append_with_policy_key_send(self):
        """
        Invoke append() with policy key send
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "commit_level": aerospike.POLICY_COMMIT_LEVEL_ALL,
        }
        self.as_connection.append(key, "name", "str", {}, policy)

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    def test_pos_append_with_policy_key_digest(self):
        """
        Invoke append() with policy key digest
        """
        key = ("test", "demo", None, bytearray("asd;as[d'as;djk;uyfl", "utf-8"))
        rec = {"name": "name%s" % (str(1)), "age": 1, "nolist": [1, 2, 3]}
        self.as_connection.put(key, rec)

        policy = {"total_timeout": 1000, "key": aerospike.POLICY_KEY_DIGEST, "retry": aerospike.POLICY_RETRY_NONE}
        self.as_connection.append(key, "name", "str", {}, policy)

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str", "nolist": [1, 2, 3]}
        assert key == ("test", "demo", None, bytearray(b"asd;as[d'as;djk;uyfl"))

        self.as_connection.remove(key)

    def test_pos_append_with_policy_key_gen_EQ_ignore(self):
        """
        Invoke append() with gen eq positive ignore
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "gen": aerospike.POLICY_GEN_IGNORE,
        }

        meta = {"gen": 10, "ttl": 1200}
        self.as_connection.append(key, "name", "str", meta, policy)

        (key, meta, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    def test_pos_append_with_policy_key_gen_EQ_positive(self):
        """
        Invoke append() with gen eq positive
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "gen": aerospike.POLICY_GEN_EQ,
        }
        (key, meta) = self.as_connection.exists(key)

        gen = meta["gen"]

        meta = {"gen": gen, "ttl": 1200}
        self.as_connection.append(key, "name", "str", meta, policy)

        (key, meta, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    def test_pos_append_with_policy_key_gen_GT_positive(self):
        """
        Invoke append() with gen GT positive
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "gen": aerospike.POLICY_GEN_GT,
        }
        (key, meta) = self.as_connection.exists(key)
        gen = meta["gen"]

        meta = {"gen": gen + 2, "ttl": 1200}
        self.as_connection.append(key, "name", "str", meta, policy)

        (key, meta, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    def test_pos_append_with_nonexistent_key(self):
        """
        Invoke append() with non-existent key
        """
        key = ("test", "demo", 1000)
        status = self.as_connection.append(key, "name", "str")

        assert status == 0
        self.as_connection.remove(key)

    def test_pos_append_with_nonexistent_bin(self):
        """
        Invoke append() with non-existent bin
        """
        key = ("test", "demo", 1)
        status = self.as_connection.append(key, "name1", "str")

        assert status == 0

    def test_pos_append_unicode_value(self):
        """
        Invoke append() with unicode string
        """
        key = ("test", "demo", 1)
        self.as_connection.append(key, "name", "address")

        key, _, bins = self.as_connection.get(key)
        assert bins["name"] == "name1address"

    def test_pos_append_unicode_bin_name(self):
        """
        Invoke append() with unicode string
        """
        key = ("test", "demo", 1)
        self.as_connection.append(key, "add", "address")

        key, _, bins = self.as_connection.get(key)
        assert bins["add"] == "address"

    def test_pos_append_with_correct_timeout_policy(self):
        """
        Invoke append() with correct policy
        """
        key = ("test", "demo", 1)
        policy = {
            "gen": 5,
            "total_timeout": 300,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "commit_level": aerospike.POLICY_COMMIT_LEVEL_MASTER,
        }
        self.as_connection.append(key, "name", "str", {}, policy)

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1str"}

    def test_pos_append_with_bytearray(self):
        """
        Invoke append() with bytearray value
        """
        key = ("test", "demo", "bytearray_key")
        self.as_connection.append(key, "bytearray_bin", bytearray("abc", "utf-8"))

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"bytearray_bin": bytearray("asd;as[d'as;dabc", "utf-8")}

    def test_pos_append_with_bytearray_new_key(self):
        """
        Invoke append() with bytearray value with a new record(non-existing)
        """
        key = ("test", "demo", "bytearray_new")
        self.as_connection.append(key, "bytearray_bin", bytearray("asd;as[d'as;d", "utf-8"))

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"bytearray_bin": bytearray("asd;as[d'as;d", "utf-8")}

        self.as_connection.remove(key)

    def test_pos_append_with_bytes(self):
        """
        Invoke append() with bytes value
        """
        key = ("test", "demo", "bytes_key")
        self.as_connection.append(key, "bytes_bin", b"a")

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"bytes_bin": b"a"}

    def test_pos_append_with_bytes_new_key(self):
        """
        Invoke append() with bytes value with a new record(non-existing)
        """
        key = ("test", "demo", "bytes_new")
        self.as_connection.append(key, "bytes_bin", b"a")

        (key, _, bins) = self.as_connection.get(key)

        assert bins == {"bytes_bin": b"a"}

        self.as_connection.remove(key)

    # Negative append tests
    def test_neg_append_with_no_parameters(self):
        """
        Invoke append() without any mandatory parameters.
        """
        with pytest.raises(TypeError) as typeError:
            self.as_connection.append()
        assert "argument 'key' (pos 1)" in str(typeError.value)

    def test_neg_append_with_policy_key_gen_GT_lesser(self):
        """
        Invoke append() with gen GT lesser
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "gen": aerospike.POLICY_GEN_GT,
        }
        (key, meta) = self.as_connection.exists(key)

        gen = meta["gen"]

        meta = {"gen": gen, "ttl": 1200}
        try:
            self.as_connection.append(key, "name", "str", meta, policy)
        except e.RecordGenerationError as exception:
            assert exception.code == 3
            assert exception.bin == "name"
        (key, meta, bins) = self.as_connection.get(key)
        assert bins == {"age": 1, "name": "name1"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    def test_neg_append_with_policy_key_gen_EQ_not_equal(self):
        """
        Invoke append() with policy key EQ not equal
        """
        key = ("test", "demo", 1)
        policy = {
            "total_timeout": 1000,
            "key": aerospike.POLICY_KEY_SEND,
            "retry": aerospike.POLICY_RETRY_ONCE,
            "gen": aerospike.POLICY_GEN_EQ,
        }
        (key, meta) = self.as_connection.exists(key)
        gen = meta["gen"]

        meta = {"gen": gen + 5, "ttl": 1200}
        try:
            self.as_connection.append(key, "name", "str", meta, policy)

        except e.RecordGenerationError as exception:
            assert exception.code == 3
            assert exception.bin == "name"

        (key, meta, bins) = self.as_connection.get(key)

        assert bins == {"age": 1, "name": "name1"}
        assert key == (
            "test",
            "demo",
            None,
            bytearray(b"\xb7\xf4\xb88\x89\xe2\xdag\xdeh>\x1d\xf6\x91\x9a\x1e\xac\xc4F\xc8"),
        )

    @pytest.mark.parametrize(
        "key, bin, value, meta, policy, ex_code, ex_msg",
        [
            (("test", "demo", 1), "name", 2, {}, {}, -2, "Cannot concatenate 'str' and 'non-str' objects"),
            (("test", "demo", 1), "name", "pqr", {}, "", -2, "policy must be a dict"),
            (
                ("test", "demo", 1),
                3,
                "str",
                {},
                {
                    "gen": 5,
                    "total_timeout": 3000,
                    "retry": aerospike.POLICY_RETRY_ONCE,
                    "commit_level": aerospike.POLICY_COMMIT_LEVEL_MASTER,
                },
                -2,
                "Bin name should be of type string",
            ),
            (
                ("test", "name"),
                "name",
                "str",
                {},
                {"gen": 5},
                -2,
                "key tuple must be (Namespace, Set, Key) or (Namespace, Set, None, Digest)",
            ),
            (("test", "demo", 1), "name", "str", {}, {"total_timeout": 0.5}, -2, "total_timeout is invalid"),
        ],
    )
    def test_neg_append_params_of_incorrect_types(self, key, bin, value, meta, policy, ex_code, ex_msg):
        """
        Invoke append() parameters of incorrect datatypes
        """
        with pytest.raises(e.ParamError):
            self.as_connection.append(key, bin, value, meta, policy)

    def test_neg_append_with_extra_parameter(self):
        """
        Invoke append() with extra parameter.
        """
        key = ("test", "demo", 1)
        policy = {"total_timeout": 1000}
        with pytest.raises(TypeError) as typeError:
            self.as_connection.append(key, "name", "str", {}, policy, "")
        msg = "append() takes at most 5 arguments (6 given)"
        assert msg in str(typeError.value)

    @pytest.mark.parametrize(
        "key, bin, ex_code, ex_msg",
        [(None, "name", -2, "key is invalid"), (("test", "demo", 1), None, -2, "Bin name should be of type string")],
    )
    def test_neg_append_parameters_as_none(self, key, bin, ex_code, ex_msg):
        """
        Invoke append() with parametes as None
        """
        with pytest.raises(e.ParamError):
            self.as_connection.append(key, bin, "str")

    def test_neg_append_with_correct_parameters_without_connection(self):
        """
        Invoke append() with correct parameters without connection
        """
        config = TestBaseClass.get_connection_config()
        client1 = aerospike.client(config)
        client1.close()
        key = ("test", "demo", 1)

        try:
            client1.append(key, "name", "str")

        except e.ClusterError as exception:
            assert exception.code == 11

    def test_neg_append_with_low_timeout(self):
        """
        Invoke append() with low timeout in policy
        """
        key = ("test", "demo", 1)
        policy = {
            "gen": 5,
            "total_timeout": 1,
            # 'retry': aerospike.POLICY_RETRY_ONCE,
            "commit_level": aerospike.POLICY_COMMIT_LEVEL_MASTER,
        }
        try:
            self.as_connection.append(key, "name", "str", {}, policy)
        except e.TimeoutError as exception:
            assert exception.code == 9

    def test_neg_append_with_non_existent_ns(self):
        """
        Invoke append() with non existent ns
        """
        key = ("test1", "demo", "name")
        policy = {
            "gen": 5,
            "total_timeout": 300,
        }
        with pytest.raises(e.ClientError):
            self.as_connection.append(key, "name", "str", {}, policy)


text: {% extends "jasmine/base.html" %}


text:
#include <linux/init.h>
#include <linux/types.h>
#include <linux/errno.h>

#include <asm/delay.h>
#include <asm/sched_clock.h>

#include <clocksource/arm_arch_timer.h>

static unsigned long arch_timer_read_counter_long(void)
{
	return arch_timer_read_counter();
}

static u32 sched_clock_mult __read_mostly;

static unsigned long long notrace arch_timer_sched_clock(void)
{
	return arch_timer_read_counter() * sched_clock_mult;
}

static struct delay_timer arch_delay_timer;

static void __init arch_timer_delay_timer_register(void)
{
	/* Use the architected timer for the delay loop. */
	arch_delay_timer.read_current_timer = arch_timer_read_counter_long;
	arch_delay_timer.freq = arch_timer_get_rate();
	register_current_timer_delay(&arch_delay_timer);
}

int __init arch_timer_arch_init(void)
{
        u32 arch_timer_rate = arch_timer_get_rate();

	if (arch_timer_rate == 0)
		return -ENXIO;

	arch_timer_delay_timer_register();

	/* Cache the sched_clock multiplier to save a divide in the hot path. */
	sched_clock_mult = NSEC_PER_SEC / arch_timer_rate;
	sched_clock_func = arch_timer_sched_clock;
	pr_info("sched_clock: ARM arch timer >56 bits at %ukHz, resolution %uns\n",
		arch_timer_rate / 1000, sched_clock_mult);

	return 0;
}


text:
package com.heroku.api.request.team;

import com.heroku.api.Heroku;
import com.heroku.api.Invoice;
import com.heroku.api.TeamApp;
import com.heroku.api.exception.RequestFailedException;
import com.heroku.api.http.Http;
import com.heroku.api.http.HttpUtil;
import com.heroku.api.parser.Json;
import com.heroku.api.request.Request;
import com.heroku.api.util.Range;

import java.util.HashMap;
import java.util.Map;

import static com.heroku.api.http.HttpUtil.noBody;

/**
 * TODO: Javadoc
 *
 * @author Joe Kutner
 */
public class TeamInvoiceList implements Request<Range<Invoice>> {

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

  private String team;

  public TeamInvoiceList(String teamNameOrId) {
    this.team = teamNameOrId;
  }

  public TeamInvoiceList(String teamNameOrId, String range) {
    this(teamNameOrId);
    this.headers.put("Range", range);
  }

  @Override
  public Http.Method getHttpMethod() {
    return Http.Method.GET;
  }

  @Override
  public String getEndpoint() {
    return Heroku.Resource.TeamInvoices.format(team);
  }

  @Override
  public boolean hasBody() {
    return false;
  }

  @Override
  public String getBody() {
    throw HttpUtil.noBody();
  }

  @Override
  public Map<String,Object> getBodyAsMap() {
    throw noBody();
  }

  @Override
  public Http.Accept getResponseType() {
    return Http.Accept.JSON;
  }

  @Override
  public Map<String, String> getHeaders() {
    return headers;
  }

  @Override
  public Range<Invoice> getResponse(byte[] in, int code, Map<String, String> responseHeaders) {
    if (code == 200) {
      return Json.parse(in, TeamInvoiceList.class);
    } else if (code == 206) {
      Range<Invoice> r = Json.parse(in, TeamInvoiceList.class);
      r.setNextRange(responseHeaders.get("Next-Range"));
      return r;
    } else {
      throw new RequestFailedException("TeamInvoiceList Failed", code, in);
    }
  }
}


text:
package org.zerosign.requesto.annotations;

import org.zerosign.requesto.enums.RequestMethod;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An annotation for Request class.
 *
 * @author zerosign
 * @since 20 April 2014
 * @version 1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Request {
    RequestMethod method() default RequestMethod.GET;

    String endpoint() default "";
}


text:
:mod:`cybox.objects.network_route_entry_object` module
======================================================

.. automodule:: cybox.objects.network_route_entry_object
    :members:
    :undoc-members:
    :show-inheritance: