text:
<?php

namespace App\Pages;

use Exception;
use function The\db;

class FantasyStandingsPage extends BasePage
{
    use WeekSelectorTrait;

    protected function invoke()
    {
        $this->makeWeekSelector();

        $weeks = $this->getWeeksForYear(
            $this->getSelectedSeason(),
            $this->getSelectedWeek()
        );
        $fantasy_standings = $this->getFantasyStandings(
            $weeks,
            $this->getSelectedSeason(),
            $this->getSelectedWeek(),
        );
        $week_stats = $this->getWeekStats($weeks, $fantasy_standings);

        $this->set('title', 'Fantasy standings');
        $this->render('fantasy_standings.phtml', [
            'weeks'          => $weeks,
            'user_standings' => $this->getUserStandings($fantasy_standings, []),
            'week_stats'     => $week_stats,
            'season_stats'   => $this->getSeasonStats($week_stats),
        ]);
    }

    private function getUserStandings(array $fantasy_standings, array $week_stats)
    {
        $users = $this->getUsers(array_keys($fantasy_standings));

        $weeks_template = [];
        foreach ($week_stats as $week_number => $week_stat) {
            $weeks_template[$week_number] = [];
        }

        $user_standings = [];
        foreach ($users as $user) {
            $user_stats = $fantasy_standings[$user['user_id']];
            $total_points = array_sum(array_column($user_stats, 'points'));
            $total_potential = array_sum(array_column($user_stats, 'potential'));

            $user_standings[] = [
                'display_name'     => $user['display_name'],
                'display_color'    => $user['display_color'],
                'short_name'       => $user['short_name'],
                'weeks'            => $fantasy_standings[$user['user_id']],
                'total_points'     => $total_points,
                'total_potential'  => $total_potential,
                'total_percent'    => number_format(100 * $total_points / $total_potential, 1),
                'weighted_percent' => number_format(100 * $total_points / $total_potential, 1),
                'weeks_won'        => 0,
            ];
        }

        usort($user_standings, function ($a, $b) {
            if ($a['total_points'] !== $b['total_points']) {
                return $b['total_points'] <=> $a['total_points'];
            }

            if ($a['weeks_won'] !== $b['weeks_won']) {
                return $b['weeks_won'] <=> $a['weeks_won'];
            }

            return $a['display_name'] <=> $a['display_name'];
        });

        $last_points = 0;
        $rank_ties = 1;
        $rank = 0;
        foreach ($user_standings as &$user_standing) {
            if ($last_points !== $user_standing['total_points']) {
                $rank += $rank_ties;
                $rank_ties = 1;
            } else {
                ++$rank_ties;
            }
            $last_points = $user_standing['total_points'];

            $user_standing['rank'] = $rank;
        }

        return $user_standings;
    }

    private function getUsers($user_ids)
    {
        if (empty($user_ids)) {
            return [];
        }

        $user_id_sql = db()->implodeInts($user_ids);

        $query = db()->query(
            <<<SQL
                SELECT
                    user_id,
                    display_name,
                    display_color
                FROM users
                WHERE user_id IN ({$user_id_sql})
            SQL
        );
        while ($row = $query->fetchRow()) {
            $names = explode(' ', $row['display_name']);
            $row['short_name'] = substr($names[0], 0, 1)
                . substr($names[0], -1, 1)
                . substr($names[1] ?? '', 0, 1);

            $users[$row['user_id']] = $row;
        }

        return $users;
    }

    private function getFantasyStandings($weeks, $year, $week_number)
    {
        if (!isset($weeks[$week_number])) {
            throw new Exception("Week {$year}.{$week_number} not found");
        }

        $first_week     = $weeks[1];
        $selected_week  = $weeks[$week_number];
        $week_numbers   = array_column($weeks, 'week_number', 'week_id');

        $fantasy_standings = [];

        $query = db()->query(
            <<<'SQL'
                WITH awarded_points AS (
                    SELECT
                        game_id,
                        away_team_id AS team_id,
                        week_id,
                        win_weight AS potential,
                        CASE
                            WHEN away_score >= home_score THEN win_weight
                        END AS awarded_points
                    FROM games
                    JOIN weeks USING (week_id)
                    WHERE season_id = (SELECT season_id FROM seasons WHERE year = $1)
                        AND game_time BETWEEN $2 AND $3

                    UNION ALL

                    SELECT
                        game_id,
                        home_team_id AS team_id,
                        week_id,
                        win_weight AS potential,
                        CASE
                            WHEN home_score >= away_score THEN win_weight
                        END AS awarded_points
                    FROM games
                    JOIN weeks USING (week_id)
                    WHERE season_id = (SELECT season_id FROM seasons WHERE year = $1)
                        AND game_time BETWEEN $2 AND $3
                )

                SELECT
                    user_id,
                    week_id,
                    COALESCE(SUM(awarded_points), 0) AS points,
                    COALESCE(SUM(potential), 0) AS potential
                FROM users
                JOIN picks USING (user_id)
                JOIN awarded_points USING (game_id, team_id)
                GROUP BY user_id, week_id
                ORDER BY points
            SQL,
            [$year, $first_week['start_date'], $selected_week['end_date']]
        );
        while ($row = $query->fetchRow()) {
            $week_number = $week_numbers[$row['week_id']];

            if (!$row['potential']) {
                $row['percent'] = 'N/A';
            } else {
                $row['percent'] = number_format(
                    100 * $row['points'] / $row['potential'],
                    1
                );
            }

            $fantasy_standings[$row['user_id']][$week_number] = $row;
        }

        return $fantasy_standings;
    }

    private function getWeeksForYear($year, $selected_week_number)
    {
        $weeks       = [];
        $week_number = 0;

        $query = db()->query(
            <<<'SQL'
                SELECT
                    week_id,
                    start_at::date AS start_date,
                    end_at::date AS end_date,
                    (
                        SELECT
                            JSON_BUILD_OBJECT(
                                'games_scheduled', COUNT(*),
                                'games_played',    COUNT(away_score),
                                'win_weight',      win_weight
                            )
                        FROM games
                        WHERE games.week_id = weeks.week_id
                    ) AS details
                FROM weeks
                WHERE season_id = (SELECT season_id FROM seasons WHERE year = $1)
                ORDER BY start_at
                SQL,
            [$year]
        );
        while ($week = $query->fetchRow()) {
            ++$week_number;

            $week['week_number'] = $week_number;
            $week['is_selected'] = ($selected_week_number === $week_number);
            $week['details']     = json_decode($week['details'], true);
            $weeks[$week_number] = $week;
        }

        return $weeks;
    }

    private function getWeekStats(array $weeks, array $fantasy_standings)
    {
        $week_stats = [];

        foreach ($weeks as $week_number => ['details' => $details]) {
            $user_stats = array_column($fantasy_standings, $week_number);
            $user_aggr = array_reduce(
                array_column($user_stats, 'points'),
                function ($aggr, $points) {
                    return [
                        'min' => min($aggr['min'], $points),
                        'max' => max($aggr['max'], $points),
                    ];
                },
                ['min' => INF, 'max' => 0]
            );

            $week_stats[$week_number] = [
                'points_played'    => $details['games_played'] * $details['win_weight'],
                'points_scheduled' => $details['games_scheduled'] * $details['win_weight'],
                'max_points'       => $user_aggr['max'],
                'min_points'       => $user_aggr['min'],
            ];
        }

        return $week_stats;
    }

    private function getSeasonStats(array $week_stats)
    {
        $season_stats = [
            'points_played'    => array_sum(array_column($week_stats, 'points_played')),
            'points_scheduled' => array_sum(array_column($week_stats, 'points_scheduled')),
            'percent'          => 'N/A',
        ];

        if ($season_stats['points_scheduled']) {
            $season_stats['percent'] = number_format(
                100 * $season_stats['points_played'] / $season_stats['points_scheduled'],
                1
            );
        }

        return $season_stats;
    }
}


text:
Imports LinqToTwitter

Public Class TweetDemos

    Public Shared Async Function RunAsync(twitterCtx As TwitterContext) As Task
        Await twitterCtx.TweetAsync("Test tweet: " & Date.Now)
    End Function

End Class

redpajama_set_name: RedPajamaGithub


text:
#include "HComment.h"
#include "../items/VComment.h"

#include "InteractionBase/src/events/SetCursorEvent.h"

namespace Comments {

HComment::HComment()
{}

HComment* HComment::instance()
{
	static HComment h;
	return &h;
}

void HComment::keyPressEvent(Visualization::Item *target, QKeyEvent *event)
{
	auto vcomment = DCast<VComment>( target );
	event->ignore();

	if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_E)
	{
		event->accept();

		vcomment->node()->beginModification("edit node");
		vcomment->toggleEditing();
		vcomment->node()->endModification();

		target->scene()->addPostEventAction(new Interaction::SetCursorEvent{target});
	}
	else if (event->modifiers() == Qt::ShiftModifier && event->key() == Qt::Key_Delete)
	{
		event->accept();

		auto node = vcomment->node();
		auto parent = DCast<Model::CompositeNode>(node->parent());
		if (parent)
		{
			target->scene()->addPostEventAction(new Interaction::SetCursorEvent{target->parent()});

			parent->beginModification("remove comment");
			parent->remove(node);
			parent->endModification();
		}
	}

	if (!event->isAccepted()) GenericHandler::keyPressEvent(target, event);
}

}


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Xyz.TForce.Collections;

namespace Xyz.TForce
{

    public class UniversalMapper
    {

        public static CollectionToObjectMappingBuilder<TResult> CollectionToObject<TResult>()
        {
            var builder = new CollectionToObjectMappingBuilder<TResult>();
            return builder;
        }

        public static DictionaryToObjectMappingBuilder<TResult> DictionaryToObject<TResult>()
        {
            var builder = new DictionaryToObjectMappingBuilder<TResult>();
            return builder;
        }

        public static NumberToFlagMappingBuilder<TResult> NumberToFlag<TResult>()
        {
            var builder = new NumberToFlagMappingBuilder<TResult>();
            return builder;
        }

        public class CollectionToObjectMappingBuilder<TResult>
        {

            private readonly ExpressionDictionary<object, object, TResult> mappings;

            public CollectionToObjectMappingBuilder()
            {
                this.mappings = new ExpressionDictionary<object, object, TResult>();
            }

            public CollectionToObjectMappingBuilder<TResult> AddMapping(object sourceKey, Expression<Func<TResult, object>> targetExpression)
            {
                mappings.Set(sourceKey, targetExpression);
                return this;
            }

            public TResult Map<TItem>(TItem[] collection, Expression<Func<TItem, object>> keyExpression, Expression<Func<TItem, object>> valueExpression)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map(collection, keyExpression, valueExpression, result);
            }

            public TResult Map<TItem>(IEnumerable<TItem> collection, Expression<Func<TItem, object>> keyExpression, Expression<Func<TItem, object>> valueExpression)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map(collection, keyExpression, valueExpression, result);
            }

            public TResult Map<TItem>(TItem[] collection, Expression<Func<TItem, object>> keyExpression, Expression<Func<TItem, object>> valueExpression, TResult result)
            {
                foreach (var item in collection)
                {
                    var key = item.GetPropertyValue(keyExpression);
                    if (mappings.ContainsKey((object) key))
                    {
                        var value = item.GetPropertyValue(valueExpression);
                        var mapping = mappings[key];
                        result.SetPropertyValue(mapping, value);
                    }
                }
                return result;
            }

            public TResult Map<TItem>(IEnumerable<TItem> collection, Expression<Func<TItem, object>> keyExpression, Expression<Func<TItem, object>> valueExpression, TResult result)
            {
                foreach (var item in collection)
                {
                    var key = item.GetPropertyValue(keyExpression);
                    if (mappings.ContainsKey(key))
                    {
                        var value = item.GetPropertyValue(valueExpression);
                        var mapping = mappings[key];
                        result.SetPropertyValue(mapping, value);
                    }
                }
                return result;
            }
        }

        public class DictionaryToObjectMappingBuilder<TResult>
        {

            private readonly ExpressionDictionary<object, object, TResult> mappings;

            public DictionaryToObjectMappingBuilder()
            {
                this.mappings = new ExpressionDictionary<object, object, TResult>();
            }

            public DictionaryToObjectMappingBuilder<TResult> AddMapping(object sourceKey, Expression<Func<TResult, object>> targetExpression)
            {
                mappings.Set(sourceKey, targetExpression);
                return this;
            }

            public TResult Map<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map(dictionary, result);
            }

            public TResult Map<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TResult result)
            {
                var keys = dictionary.Keys;
                foreach (var key in keys)
                {
                    if (mappings.ContainsKey(key))
                    {
                        var value = dictionary[key];
                        var mapping = mappings[key];
                        result.SetPropertyValue(mapping, value);
                    }
                }
                return result;
            }
        }

        public class NumberToFlagMappingBuilder<TResult>
        {

            private readonly ExpressionDictionary<int, bool, TResult> mappings;

            public NumberToFlagMappingBuilder()
            {
                this.mappings = new ExpressionDictionary<int, bool, TResult>();
            }

            public NumberToFlagMappingBuilder<TResult> AddMapping(int digit, Expression<Func<TResult, bool>> targetExpression)
            {
                mappings.Set(digit, targetExpression);
                return this;
            }

            public NumberToFlagMappingBuilder<TResult> AddMapping(FlagValue digit, Expression<Func<TResult, bool>> targetExpression)
            {
                mappings.Set((int) digit, targetExpression);
                return this;
            }

            public TResult Map(int number)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map((ulong) number, result);
            }

            public TResult Map(int number, TResult result)
            {
                return Map((ulong)number, result);
            }

            public TResult Map(uint number)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map((ulong)number, result);
            }

            public TResult Map(uint number, TResult result)
            {
                return Map((ulong)number, result);
            }

            public TResult Map(long number)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map((ulong)number, result);
            }

            public TResult Map(long number, TResult result)
            {
                return Map((ulong)number, result);
            }

            public TResult Map(ulong number)
            {
                var result = Activator.CreateInstance<TResult>();
                return Map(number, result);
            }

            public TResult Map(ulong number, TResult result)
            {
                var remain = number;
                var digit = 0;
                while (remain > 0)
                {
                    var mod = remain % 2;
                    if (mod == 1 && mappings.ContainsKey(digit))
                    {
                        var mapping = mappings[digit];
                        result.SetPropertyValue(mapping, true);
                    }
                    remain = remain / 2;
                    digit = digit + 1;
                }
                return result;
            }
        }
    }
}


text:
#ifndef CLICK_ATHDESCDECAP_HH
#define CLICK_ATHDESCDECAP_HH
#include <click/element.hh>
#include <clicknet/ether.h>
CLICK_DECLS

/*
=c
AthdescDecap()

=s Wifi

Pulls the click_wifi_athdesc header from a packet and stores it in Packet::anno()

=d
Removes the athdesc header and copies to to Packet->anno(). This contains
informatino such as rssi, noise, bitrate, etc.

=a AthdescEncap
*/

class AthdescDecap : public Element { public:

  AthdescDecap();
  ~AthdescDecap();

  const char *class_name() const	{ return "AthdescDecap"; }
  const char *port_count() const		{ return PORTS_1_1; }

  int configure(Vector<String> &, ErrorHandler *);
  bool can_live_reconfigure() const	{ return true; }

  Packet *simple_action(Packet *);

  void add_handlers();

  bool _debug;
 private:

};

CLICK_ENDDECLS
#endif


text:
package org.apache.ode.bpel.engine;

import java.util.concurrent.TimeUnit;

import junit.framework.TestCase;

/**
 * Test case for {@link InstanceLockManager}.
 *
 * @author mszefler
 */
public class InstanceLockManagerTest extends TestCase {

    InstanceLockManager _ilm;

    public void setUp() {
        _ilm = new InstanceLockManager();
    }

    public void testDistinctness() throws Exception {
        _ilm.lock(1L, 0, TimeUnit.MILLISECONDS);
        _ilm.lock(2L, 0, TimeUnit.MILLISECONDS);
        _ilm.unlock(1L);
        _ilm.unlock(2L);
        _ilm.lock(1L, 0, TimeUnit.MILLISECONDS);
        _ilm.lock(2L, 0, TimeUnit.MILLISECONDS);
    }

    public void testExclusion() throws Exception {
        _ilm.lock(1L, 0, TimeUnit.MILLISECONDS);
        try {
            _ilm.lock(1L, 0, TimeUnit.MILLISECONDS);
            fail("Should have timedout.");
        } catch (InstanceLockManager.TimeoutException te) {
            // expected
        }
    }

    public void testWakeUpQueue() throws Exception {
        _ilm.lock(1L, 0, TimeUnit.MICROSECONDS);
        Thread t1 = new TThread();
        Thread t2 = new TThread();
        Thread t3 = new TThread();
        Thread t4 = new TThread();

        t1.start();
        t2.start();
        t3.start();
        t4.start();

        Thread.sleep(100);
        _ilm.unlock(1L);

        t1.join(2000);
        t2.join(2000);
        t3.join(2000);
        t4.join(2000);

        assertFalse(t1.isAlive());
        assertFalse(t2.isAlive());
        assertFalse(t3.isAlive());
        assertFalse(t4.isAlive());

    }

    private class TThread extends Thread {
        public void run() {
            try {
                _ilm.lock(1L, 1000, TimeUnit.MILLISECONDS);
                Thread.sleep(100);
                _ilm.unlock(1L);
            } catch (Exception ex) {
                ex.printStackTrace();
                fail("Unexpected ex");
            }
        }

    }
}


text:
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union

from google.api_core import grpc_helpers
from google.api_core import operations_v1
from google.api_core import gapic_v1
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore

import grpc  # type: ignore

from google.cloud.gkehub_v1beta1.types import membership
from google.cloud.location import locations_pb2  # type: ignore
from google.iam.v1 import iam_policy_pb2  # type: ignore
from google.iam.v1 import policy_pb2  # type: ignore
from google.longrunning import operations_pb2
from google.longrunning import operations_pb2  # type: ignore
from .base import GkeHubMembershipServiceTransport, DEFAULT_CLIENT_INFO

class GkeHubMembershipServiceGrpcTransport(GkeHubMembershipServiceTransport):
    """gRPC backend transport for GkeHubMembershipService.

    The GKE Hub MembershipService handles the registration of many
    Kubernetes clusters to Google Cloud, represented with the
    [Membership][google.cloud.gkehub.v1beta1.Membership] resource.

    GKE Hub is currently only available in the global region.

    **Membership management may be non-trivial:** it is recommended to
    use one of the Google-provided client libraries or tools where
    possible when working with Membership resources.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends protocol buffers over the wire using gRPC (which is built on
    top of HTTP/2); the ``grpcio`` package must be installed.
    """

    _stubs: Dict[str, Callable]

    def __init__(
        self,
        *,
        host: str = "gkehub.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Sequence[str] = None,
        channel: grpc.Channel = None,
        api_mtls_endpoint: str = None,
        client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
        ssl_channel_credentials: grpc.ChannelCredentials = None,
        client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is ignored if ``channel`` is provided.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            channel (Optional[grpc.Channel]): A ``Channel`` instance through
                which to make calls.
            api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
                If provided, it overrides the ``host`` argument and tries to create
                a mutual TLS channel with client SSL credentials from
                ``client_cert_source`` or application default SSL credentials.
            client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
                Deprecated. A callback to provide client SSL certificate bytes and
                private key bytes, both in PEM format. It is ignored if
                ``api_mtls_endpoint`` is None.
            ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
                for the grpc channel. It is ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
                A callback to provide client certificate bytes and private key bytes,
                both in PEM format. It is used to configure a mutual TLS channel. It is
                ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.

        Raises:
          google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
              creation failed for any reason.
          google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """
        self._grpc_channel = None
        self._ssl_channel_credentials = ssl_channel_credentials
        self._stubs: Dict[str, Callable] = {}
        self._operations_client: Optional[operations_v1.OperationsClient] = None

        if api_mtls_endpoint:
            warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
        if client_cert_source:
            warnings.warn("client_cert_source is deprecated", DeprecationWarning)

        if channel:
            # Ignore credentials if a channel was passed.
            credentials = False
            # If a channel was explicitly provided, set it.
            self._grpc_channel = channel
            self._ssl_channel_credentials = None

        else:
            if api_mtls_endpoint:
                host = api_mtls_endpoint

                # Create SSL credentials with client_cert_source or application
                # default SSL credentials.
                if client_cert_source:
                    cert, key = client_cert_source()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )
                else:
                    self._ssl_channel_credentials = SslCredentials().ssl_credentials

            else:
                if client_cert_source_for_mtls and not ssl_channel_credentials:
                    cert, key = client_cert_source_for_mtls()
                    self._ssl_channel_credentials = grpc.ssl_channel_credentials(
                        certificate_chain=cert, private_key=key
                    )

        # The base transport sets the host, credentials and scopes
        super().__init__(
            host=host,
            credentials=credentials,
            credentials_file=credentials_file,
            scopes=scopes,
            quota_project_id=quota_project_id,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )

        if not self._grpc_channel:
            self._grpc_channel = type(self).create_channel(
                self._host,
                # use the credentials which are saved
                credentials=self._credentials,
                # Set ``credentials_file`` to ``None`` here as
                # the credentials that we saved earlier should be used.
                credentials_file=None,
                scopes=self._scopes,
                ssl_credentials=self._ssl_channel_credentials,
                quota_project_id=quota_project_id,
                options=[
                    ("grpc.max_send_message_length", -1),
                    ("grpc.max_receive_message_length", -1),
                ],
            )

        # Wrap messages. This must be done after self._grpc_channel exists
        self._prep_wrapped_messages(client_info)

    @classmethod
    def create_channel(
        cls,
        host: str = "gkehub.googleapis.com",
        credentials: ga_credentials.Credentials = None,
        credentials_file: str = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        **kwargs,
    ) -> grpc.Channel:
        """Create and return a gRPC channel object.
        Args:
            host (Optional[str]): The host for the channel to use.
            credentials (Optional[~.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
                service. These are only used when credentials are not specified and
                are passed to :func:`google.auth.default`.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            kwargs (Optional[dict]): Keyword arguments, which are passed to the
                channel creation.
        Returns:
            grpc.Channel: A gRPC channel object.

        Raises:
            google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
              and ``credentials_file`` are passed.
        """

        return grpc_helpers.create_channel(
            host,
            credentials=credentials,
            credentials_file=credentials_file,
            quota_project_id=quota_project_id,
            default_scopes=cls.AUTH_SCOPES,
            scopes=scopes,
            default_host=cls.DEFAULT_HOST,
            **kwargs,
        )

    @property
    def grpc_channel(self) -> grpc.Channel:
        """Return the channel designed to connect to this service."""
        return self._grpc_channel

    @property
    def operations_client(self) -> operations_v1.OperationsClient:
        """Create the client designed to process long-running operations.

        This property caches on the instance; repeated calls return the same
        client.
        """
        # Quick check: Only create a new client if we do not already have one.
        if self._operations_client is None:
            self._operations_client = operations_v1.OperationsClient(self.grpc_channel)

        # Return the client from cache.
        return self._operations_client

    @property
    def list_memberships(
        self,
    ) -> Callable[
        [membership.ListMembershipsRequest], membership.ListMembershipsResponse
    ]:
        r"""Return a callable for the list memberships method over gRPC.

        Lists Memberships in a given project and location.

        Returns:
            Callable[[~.ListMembershipsRequest],
                    ~.ListMembershipsResponse]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_memberships" not in self._stubs:
            self._stubs["list_memberships"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ListMemberships",
                request_serializer=membership.ListMembershipsRequest.serialize,
                response_deserializer=membership.ListMembershipsResponse.deserialize,
            )
        return self._stubs["list_memberships"]

    @property
    def get_membership(
        self,
    ) -> Callable[[membership.GetMembershipRequest], membership.Membership]:
        r"""Return a callable for the get membership method over gRPC.

        Gets the details of a Membership.

        Returns:
            Callable[[~.GetMembershipRequest],
                    ~.Membership]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_membership" not in self._stubs:
            self._stubs["get_membership"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GetMembership",
                request_serializer=membership.GetMembershipRequest.serialize,
                response_deserializer=membership.Membership.deserialize,
            )
        return self._stubs["get_membership"]

    @property
    def create_membership(
        self,
    ) -> Callable[[membership.CreateMembershipRequest], operations_pb2.Operation]:
        r"""Return a callable for the create membership method over gRPC.

        Creates a new Membership.

        **This is currently only supported for GKE clusters on Google
        Cloud**. To register other clusters, follow the instructions at
        https://cloud.google.com/anthos/multicluster-management/connect/registering-a-cluster.

        Returns:
            Callable[[~.CreateMembershipRequest],
                    ~.Operation]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "create_membership" not in self._stubs:
            self._stubs["create_membership"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/CreateMembership",
                request_serializer=membership.CreateMembershipRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["create_membership"]

    @property
    def delete_membership(
        self,
    ) -> Callable[[membership.DeleteMembershipRequest], operations_pb2.Operation]:
        r"""Return a callable for the delete membership method over gRPC.

        Removes a Membership.

        **This is currently only supported for GKE clusters on Google
        Cloud**. To unregister other clusters, follow the instructions
        at
        https://cloud.google.com/anthos/multicluster-management/connect/unregistering-a-cluster.

        Returns:
            Callable[[~.DeleteMembershipRequest],
                    ~.Operation]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "delete_membership" not in self._stubs:
            self._stubs["delete_membership"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/DeleteMembership",
                request_serializer=membership.DeleteMembershipRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["delete_membership"]

    @property
    def update_membership(
        self,
    ) -> Callable[[membership.UpdateMembershipRequest], operations_pb2.Operation]:
        r"""Return a callable for the update membership method over gRPC.

        Updates an existing Membership.

        Returns:
            Callable[[~.UpdateMembershipRequest],
                    ~.Operation]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "update_membership" not in self._stubs:
            self._stubs["update_membership"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/UpdateMembership",
                request_serializer=membership.UpdateMembershipRequest.serialize,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["update_membership"]

    @property
    def generate_connect_manifest(
        self,
    ) -> Callable[
        [membership.GenerateConnectManifestRequest],
        membership.GenerateConnectManifestResponse,
    ]:
        r"""Return a callable for the generate connect manifest method over gRPC.

        Generates the manifest for deployment of the GKE connect agent.

        **This method is used internally by Google-provided libraries.**
        Most clients should not need to call this method directly.

        Returns:
            Callable[[~.GenerateConnectManifestRequest],
                    ~.GenerateConnectManifestResponse]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "generate_connect_manifest" not in self._stubs:
            self._stubs["generate_connect_manifest"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateConnectManifest",
                request_serializer=membership.GenerateConnectManifestRequest.serialize,
                response_deserializer=membership.GenerateConnectManifestResponse.deserialize,
            )
        return self._stubs["generate_connect_manifest"]

    @property
    def validate_exclusivity(
        self,
    ) -> Callable[
        [membership.ValidateExclusivityRequest], membership.ValidateExclusivityResponse
    ]:
        r"""Return a callable for the validate exclusivity method over gRPC.

        ValidateExclusivity validates the state of
        exclusivity in the cluster. The validation does not
        depend on an existing Hub membership resource.

        Returns:
            Callable[[~.ValidateExclusivityRequest],
                    ~.ValidateExclusivityResponse]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "validate_exclusivity" not in self._stubs:
            self._stubs["validate_exclusivity"] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/ValidateExclusivity",
                request_serializer=membership.ValidateExclusivityRequest.serialize,
                response_deserializer=membership.ValidateExclusivityResponse.deserialize,
            )
        return self._stubs["validate_exclusivity"]

    @property
    def generate_exclusivity_manifest(
        self,
    ) -> Callable[
        [membership.GenerateExclusivityManifestRequest],
        membership.GenerateExclusivityManifestResponse,
    ]:
        r"""Return a callable for the generate exclusivity manifest method over gRPC.

        GenerateExclusivityManifest generates the manifests
        to update the exclusivity artifacts in the cluster if
        needed.
        Exclusivity artifacts include the Membership custom
        resource definition (CRD) and the singleton Membership
        custom resource (CR). Combined with ValidateExclusivity,
        exclusivity artifacts guarantee that a Kubernetes
        cluster is only registered to a single GKE Hub.

        The Membership CRD is versioned, and may require
        conversion when the GKE Hub API server begins serving a
        newer version of the CRD and corresponding CR. The
        response will be the converted CRD and CR if there are
        any differences between the versions.

        Returns:
            Callable[[~.GenerateExclusivityManifestRequest],
                    ~.GenerateExclusivityManifestResponse]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "generate_exclusivity_manifest" not in self._stubs:
            self._stubs[
                "generate_exclusivity_manifest"
            ] = self.grpc_channel.unary_unary(
                "/google.cloud.gkehub.v1beta1.GkeHubMembershipService/GenerateExclusivityManifest",
                request_serializer=membership.GenerateExclusivityManifestRequest.serialize,
                response_deserializer=membership.GenerateExclusivityManifestResponse.deserialize,
            )
        return self._stubs["generate_exclusivity_manifest"]

    def close(self):
        self.grpc_channel.close()

    @property
    def delete_operation(
        self,
    ) -> Callable[[operations_pb2.DeleteOperationRequest], None]:
        r"""Return a callable for the delete_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "delete_operation" not in self._stubs:
            self._stubs["delete_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/DeleteOperation",
                request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString,
                response_deserializer=None,
            )
        return self._stubs["delete_operation"]

    @property
    def cancel_operation(
        self,
    ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
        r"""Return a callable for the cancel_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "cancel_operation" not in self._stubs:
            self._stubs["cancel_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/CancelOperation",
                request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
                response_deserializer=None,
            )
        return self._stubs["cancel_operation"]

    @property
    def get_operation(
        self,
    ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
        r"""Return a callable for the get_operation method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_operation" not in self._stubs:
            self._stubs["get_operation"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/GetOperation",
                request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
                response_deserializer=operations_pb2.Operation.FromString,
            )
        return self._stubs["get_operation"]

    @property
    def list_operations(
        self,
    ) -> Callable[
        [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
    ]:
        r"""Return a callable for the list_operations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_operations" not in self._stubs:
            self._stubs["list_operations"] = self.grpc_channel.unary_unary(
                "/google.longrunning.Operations/ListOperations",
                request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
                response_deserializer=operations_pb2.ListOperationsResponse.FromString,
            )
        return self._stubs["list_operations"]

    @property
    def list_locations(
        self,
    ) -> Callable[
        [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
    ]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "list_locations" not in self._stubs:
            self._stubs["list_locations"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/ListLocations",
                request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
                response_deserializer=locations_pb2.ListLocationsResponse.FromString,
            )
        return self._stubs["list_locations"]

    @property
    def get_location(
        self,
    ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
        r"""Return a callable for the list locations method over gRPC."""
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_location" not in self._stubs:
            self._stubs["get_location"] = self.grpc_channel.unary_unary(
                "/google.cloud.location.Locations/GetLocation",
                request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
                response_deserializer=locations_pb2.Location.FromString,
            )
        return self._stubs["get_location"]

    @property
    def set_iam_policy(
        self,
    ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
        r"""Return a callable for the set iam policy method over gRPC.
        Sets the IAM access control policy on the specified
        function. Replaces any existing policy.
        Returns:
            Callable[[~.SetIamPolicyRequest],
                    ~.Policy]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "set_iam_policy" not in self._stubs:
            self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary(
                "/google.iam.v1.IAMPolicy/SetIamPolicy",
                request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
                response_deserializer=policy_pb2.Policy.FromString,
            )
        return self._stubs["set_iam_policy"]

    @property
    def get_iam_policy(
        self,
    ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
        r"""Return a callable for the get iam policy method over gRPC.
        Gets the IAM access control policy for a function.
        Returns an empty policy if the function exists and does
        not have a policy set.
        Returns:
            Callable[[~.GetIamPolicyRequest],
                    ~.Policy]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "get_iam_policy" not in self._stubs:
            self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary(
                "/google.iam.v1.IAMPolicy/GetIamPolicy",
                request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
                response_deserializer=policy_pb2.Policy.FromString,
            )
        return self._stubs["get_iam_policy"]

    @property
    def test_iam_permissions(
        self,
    ) -> Callable[
        [iam_policy_pb2.TestIamPermissionsRequest],
        iam_policy_pb2.TestIamPermissionsResponse,
    ]:
        r"""Return a callable for the test iam permissions method over gRPC.
        Tests the specified permissions against the IAM access control
        policy for a function. If the function does not exist, this will
        return an empty set of permissions, not a NOT_FOUND error.
        Returns:
            Callable[[~.TestIamPermissionsRequest],
                    ~.TestIamPermissionsResponse]:
                A function that, when called, will call the underlying RPC
                on the server.
        """
        # Generate a "stub function" on-the-fly which will actually make
        # the request.
        # gRPC handles serialization and deserialization, so we just need
        # to pass in the functions for each.
        if "test_iam_permissions" not in self._stubs:
            self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary(
                "/google.iam.v1.IAMPolicy/TestIamPermissions",
                request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
                response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
            )
        return self._stubs["test_iam_permissions"]

    @property
    def kind(self) -> str:
        return "grpc"

__all__ = ("GkeHubMembershipServiceGrpcTransport",)


text:
import { CreateMUIStyled } from '@material-ui/system';
import { Theme } from './createTheme';

/**
 * Custom styled utility that has a default MUI theme.
 *
 * @param tag HTML tag or component that should serve as base.
 * @param options Styled options for the created component.
 * @returns React component that has styles attached to it.
 */
declare const experimentalStyled: CreateMUIStyled<Theme>;

export default experimentalStyled;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Domain.Semantics;
using DataExplorer.Domain.Sources.Maps;

namespace DataExplorer.Domain.Tests.Sources.Maps
{
    public class SourceMapBuilder
    {
        private SourceMap _sourceMap;

        public SourceMapBuilder()
        {
            _sourceMap = new SourceMap();
        }

        public SourceMapBuilder WithIndex(int index)
        {
            _sourceMap.Index = index;
            return this;
        }

        public SourceMapBuilder WithName(string name)
        {
            _sourceMap.Name = name;
            return this;
        }

        public SourceMapBuilder WithDataType(Type dataType)
        {
            _sourceMap.DataType = dataType;
            return this;
        }

        public SourceMapBuilder WithSemanticType(SemanticType semanticType)
        {
            _sourceMap.SemanticType = semanticType;
            return this;
        }

        public SourceMap Build()
        {
            return _sourceMap;
        }
    }
}


text:
package org.apache.ambari.server.api.services;

import org.apache.ambari.server.api.resources.ResourceInstance;
import org.apache.ambari.server.api.services.parsers.RequestBodyParser;
import org.apache.ambari.server.api.services.serializers.ResultSerializer;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * Unit tests for InstanceService.
 */
public class InstanceServiceTest extends BaseServiceTest {

  public List<ServiceTestInvocation> getTestInvocations() throws Exception {
    List<ServiceTestInvocation> listInvocations = new ArrayList<ServiceTestInvocation>();

    //getInstance
    InstanceService service = new TestInstanceService("clusterName", "instanceName");
    Method m = service.getClass().getMethod("getInstance", String.class, HttpHeaders.class, UriInfo.class, String.class);
    Object[] args = new Object[] {null, getHttpHeaders(), getUriInfo(), "instanceName"};
    listInvocations.add(new ServiceTestInvocation(Request.Type.GET, service, m, args, null));

    //getInstances
    service = new TestInstanceService("clusterName", null);
    m = service.getClass().getMethod("getInstances", String.class, HttpHeaders.class, UriInfo.class);
    args = new Object[] {null, getHttpHeaders(), getUriInfo()};
    listInvocations.add(new ServiceTestInvocation(Request.Type.GET, service, m, args, null));

    //createInstance
    service = new TestInstanceService("clusterName", "instanceName");
    m = service.getClass().getMethod("createInstance", String.class, HttpHeaders.class, UriInfo.class, String.class);
    args = new Object[] {"body", getHttpHeaders(), getUriInfo(), "instanceName"};
    listInvocations.add(new ServiceTestInvocation(Request.Type.POST, service, m, args, "body"));

    //updateInstance
    service = new TestInstanceService("clusterName", "instanceName");
    m = service.getClass().getMethod("updateInstance", String.class, HttpHeaders.class, UriInfo.class, String.class);
    args = new Object[] {"body", getHttpHeaders(), getUriInfo(), "instanceName"};
    listInvocations.add(new ServiceTestInvocation(Request.Type.PUT, service, m, args, "body"));

    //deleteInstance
    service = new TestInstanceService("clusterName", "instanceName");
    m = service.getClass().getMethod("deleteInstance", HttpHeaders.class, UriInfo.class, String.class);
    args = new Object[] {getHttpHeaders(), getUriInfo(), "instanceName"};
    listInvocations.add(new ServiceTestInvocation(Request.Type.DELETE, service, m, args, null));

    return listInvocations;
  }

  private class TestInstanceService extends InstanceService {
    private String m_feedName;
    private String m_instanceId;

    private TestInstanceService(String feedName, String instanceId) {
      super(feedName);
      m_feedName = feedName;
      m_instanceId = instanceId;
    }

    @Override
    ResourceInstance createInstanceResource(String feedName, String instanceID, UriInfo ui) {
      assertEquals(m_feedName, feedName);
      assertEquals(m_instanceId, instanceID);
      return getTestResource();
    }

    @Override
    RequestFactory getRequestFactory() {
      return getTestRequestFactory();
    }

    @Override
    protected RequestBodyParser getBodyParser() {
      return getTestBodyParser();
    }

    @Override
    protected ResultSerializer getResultSerializer() {
      return getTestResultSerializer();
    }
  }
}


text:
/**
 * DataViewer class
 *
 * @author Aaron Ponti
 *
 */

/**
 * A viewer to display DataModel entities to the html page.
 */
function DataViewer() {

    "use strict";

}

/**
 * Displays experiment info.
 */
DataViewer.prototype.initView = function() {

    // Div IDs
    var experimentNameView_div, experimentTagView_div,
        experimentDescriptionView_div, experimentAcquisitionDetailsView_div;

    // Aliases
    var samples = DATAMODEL.samples;
    var microscopyExperimentSample = DATAMODEL.microscopyExperimentSample;

    // Get the experiment name view
    experimentNameView_div = $("#experimentNameView");
    experimentNameView_div.empty();

    // Clear the tags view
    experimentTagView_div = $("#experimentTagView");
    experimentTagView_div.empty();

    // Clear the description view
    experimentDescriptionView_div = $("#experimentDescriptionView");
    experimentDescriptionView_div.empty();

    // Clear the acquisition detail view
    experimentAcquisitionDetailsView_div = $("#experimentAcquisitionDetailsView");
    experimentAcquisitionDetailsView_div.empty();
    experimentAcquisitionDetailsView_div.append(this.prepareTitle("Acquisition details", "default"));
    if (microscopyExperimentSample.properties["MICROSCOPY_EXPERIMENT_ACQ_HARDWARE_FRIENDLY_NAME"]) {
        experimentAcquisitionDetailsView_div.append($("
").html("This experiment was performed on " +
            microscopyExperimentSample.properties["MICROSCOPY_EXPERIMENT_ACQ_HARDWARE_FRIENDLY_NAME"] + " and registered on " +
            (new Date(microscopyExperimentSample.registrationDetails.registrationDate)).toDateString() + "."));

    } else {
        experimentAcquisitionDetailsView_div.append($("
").html("This experiment was registered on " +
            (new Date(microscopyExperimentSample.registrationDetails.registrationDate)).toDateString() + "."));
    }

    // Get the sample view
    var sampleView_div = $("#sampleView");
    sampleView_div.empty();

    // Make sure we have something to display
    if (microscopyExperimentSample == null) {
        experimentNameView_div.append("
Sorry, could not retrieve information!
");
        experimentNameView_div.append("
Please contact your administrator.
");
        return;
    }

    // Display the sample name
    experimentNameView_div.append("
" + microscopyExperimentSample.properties.NAME + "
");

    // Display the experiment description
    var exp_descr;
    if (microscopyExperimentSample.properties.MICROSCOPY_EXPERIMENT_DESCRIPTION) {
        exp_descr = microscopyExperimentSample.properties.MICROSCOPY_EXPERIMENT_DESCRIPTION;
    } else {
        exp_descr = "No description provided.";
    }
    experimentDescriptionView_div.append(this.prepareTitle("Description"));
    experimentDescriptionView_div.append($("
").html(exp_descr));

    // Get sample tags
    var sampleTags = "None";
    if (microscopyExperimentSample.parents) {
        if (microscopyExperimentSample.parents.length === 0) {
            sampleTags = "None";
        } else {
            var tags = [];
            for (let i = 0; i < microscopyExperimentSample.parents.length; i++) {
                if (microscopyExperimentSample.parents[i].sampleTypeCode === "ORGANIZATION_UNIT") {
                    tags.push(microscopyExperimentSample.parents[i].properties["NAME"]);
                }
            }
            sampleTags = tags.join(", ");
        }
    }
    experimentTagView_div.append(this.prepareTitle("Tags", "info"));
    experimentTagView_div.append($("
").html(sampleTags));

    // Display the samples
    if (samples != null) {

        var newThumbRow = null;
        var numSample = 0;

        // Display samples with a link to their corresponding webapp. Later we will reorganize the layout
        // (when the thumbnails are ready to be retrieved from openBIS).
        samples.forEach(function(sample) {

            // Keep track of the number of the sample
            numSample++;

            // Add a new row for the next three thumbnails
            if (numSample % 4 === 1) {
                newThumbRow = $("
", {class: "row"});
                sampleView_div.append(newThumbRow);
            }

            // Prepare the name to be shown
            var name;
            if (sample.properties["NAME"]) {
                name = sample.properties["NAME"];
            } else {
                name = sample.code;
            }

            // Make sure it is not too long
            var displayName;
            var l = name.length;
            if (l > 40) {
                displayName = name.substring(0, 18) + "..." + name.substring(l - 18);
            } else {
                displayName = name;
            }

            // If the size property exists (this was added later), retrieve it and display it as well
            var datasetSize;
            if (sample.properties.MICROSCOPY_SAMPLE_SIZE_IN_BYTES) {
                datasetSize = DATAVIEWER.formatSizeForDisplay(sample.properties.MICROSCOPY_SAMPLE_SIZE_IN_BYTES);
            } else {
                datasetSize = "";
            }

            // A column to be added to current row that will store all
            // elements related to current sample
            var newThumbCol = $("
",
                {
                    class: "col-md-3",
                    display: "inline",
                    "text-align": "center",
                    id : sample.code
                });

            // A div element to contain the thumbnail and its info
            var thumbnailView = $("
", { class: "thumbnailView" });

            // Link to the dataset (sample) viewer.
            var link = $("").addClass("filename").text(displayName).attr("href", "#").attr("title", name).click(
                function() {
                    window.top.location.hash = "#entity=SAMPLE&permId=" + sample.permId
                        + "&ui-subtab=webapp-section_microscopy-viewer&ui-timestamp=" + (new Date().getTime());
                    return false;
                });

            // Actual thumbnail. Initially we display a place holder. Later,
            // we will replace it asynchronously.
            var thumbnailImage = $("",
                {
                    src: "./img/wait.png",
                    class: "img-responsive",
                    display: "inline",
                    id: "image_" + sample.code,
                    title: name
                });

            // Build the thumbnail viewer
            thumbnailView.append(thumbnailImage);
            thumbnailView.append($("
"));
            thumbnailView.append(link);
            if (datasetSize !== "") {
                thumbnailView.append($("
"));
                var spanSz =  $("").addClass("filesize").text(datasetSize);
                thumbnailView.append(spanSz);
            }

            // Add the thumbnail to the column and the row
            newThumbCol.append(thumbnailView);
            newThumbRow.append(newThumbCol);

            // Now retrieve the link to the thumbnail image asynchronously and update the
            DATAVIEWER.displayThumbnailForSample(sample, "image_" + sample.code);

        });

        // Display the export action
        this.displayActions(DATAMODEL.microscopyExperimentSample);

    }

};

/**
 * Display attachment info and link to the Attachments tab.
 * @param dataModelObj DataMover object.
 * @param attachments: list of attachments
 */
DataViewer.prototype.displayAttachments = function(dataModelObj, attachments) {

    // Get the div
    var experimentAttachmentsViewId = $("#experimentAttachmentsView");

    // Clear the attachment div
    experimentAttachmentsViewId.empty();

    // Text
    var text = "";
    if (dataModelObj.attachments.length === 0) {
        text = "There are no attachments.";
    } else if (dataModelObj.attachments.length === 1) {
        text = "There is one attachment."
    } else {
        text = "There are " + dataModelObj.attachments.length + " attachments.";
    }

    // Link to the data-sets tab
    var link = $("").text(text).attr("href", "#").attr("title", text).click(
        function() {
            var url = "#entity=SAMPLE&permId=" + dataModelObj.microscopyExperimentSample.permId +
                "&ui-subtab=data-sets-section&ui-timestamp=" + (new Date().getTime());
            window.top.location.hash = url;
            return false;
        });

    experimentAttachmentsViewId.append(this.prepareTitle("Attachments"));

    // Display the link
    experimentAttachmentsViewId.append(link);

};

/**
 * Build and display the code to trigger the server-side aggregation
 * plugin 'copy_datasets_to_userdir'
 * @param microscopyExperimentSample: Experiment node
 */
DataViewer.prototype.displayActions = function(microscopyExperimentSample) {

    // Get the actionView_div div and empty it
    var actionView_div = $("#actionView");
    actionView_div.empty();
    $("#actionViewExpl").empty();

    // Get the COLLECTION experiment identifier
    var experimentId = microscopyExperimentSample.experimentIdentifierOrNull;

    // Get the MICROSCOPY_EXPERIMENT sample identifier
    var expSamplePermId = microscopyExperimentSample.permId;
    if (undefined === expSamplePermId) {
        DATAVIEWER.displayStatus("Could not retrieve the microscopy experiment identifier!", "error");
        return;
    }

    var img;
    var link;

    // Display the "Export to your folder" button only if enabled in the configuration file
    if (CONFIG['enableExportToUserFolder'] === true) {

        img = $("")
            .attr("src", "img/export.png")
            .attr("width", 32)
            .attr("height", 32);

        link = $("")
            .addClass("action")
            .attr("href", "#")
            .attr("title", "")
            .hover(function () {
                    $("#actionViewExpl").html("Export to your folder.");
                },
                function () {
                    $("#actionViewExpl").html("");
                })
            .html("")
            .click(function() {
                DATAMODEL.copyDatasetsToUserDir(
                    experimentId, expSamplePermId, "", "normal");
                return false;
            });

        link.prepend(img);

        actionView_div.append(link);
    }

    // Display the "Export to your HRM source folder" button only if enabled in the configuration file
    if (CONFIG['enableExportToHRMSourceFolder'] === true) {

        img = $("")
            .attr("src", "img/hrm.png")
            .attr("width", 32)
            .attr("height", 32);

        link = $("")
            .addClass("action")
            .attr("href", "#")
            .attr("title", "")
            .hover(function () {
                    $("#actionViewExpl").html("Export to your HRM source folder.");
                },
                function () {
                    $("#actionViewExpl").html("");
                })
            .html("")
            .click(function() {
                DATAMODEL.copyDatasetsToUserDir(
                    experimentId, expSamplePermId, "", "hrm");
                return false;
            });

        link.prepend(img);

        actionView_div.append(link);

    }

    // Build and display the call for a zip archive
    img = $("")
        .attr("src", "img/zip.png")
        .attr("width", 32)
        .attr("height", 32);

    link = $("")
        .addClass("action")
        .attr("href", "#")
        .attr("title", "")
        .hover(function () {
                $("#actionViewExpl").html("Download archive.");
            },
            function () {
                $("#actionViewExpl").html("");
            })
        .html("")
        .click(function() {
            DATAMODEL.copyDatasetsToUserDir(
                experimentId, expSamplePermId, "", "zip");
            return false;
        });

    link.prepend(img);

    actionView_div.append(link);

};

/**
 * Retrieve and display the experiment thumbnails asynchronously
 * @param sample: sample object
 * @param img_id: id of the  element to update
 */
DataViewer.prototype.displayThumbnailForSample= function(sample, img_id) {

	// Get the datasets with type "MICROSCOPY_IMG_THUMBNAIL" for current sample
    DATAMODEL.getMicroscopyImgThumbnailDataSetsForMicroscopySample(sample.permId,
        function(dataset) {

        // Get the containers
        if (dataset == null) {
            return;
        }

        // Retrieve the file for the dataset and the associated URL
        DATAMODEL.openbisServer.listFilesForDataSet(dataset.code, '/', true,
            function(response) {

                // Make sure that we got some results from the DSS to process
                if (response.error) {

                    // Thumbnail not found!
                    var imD = $("#" + img_id);
                    imD.attr("src", "./img/error.png");
                    imD.attr("title", "Could not find any files associated to this dataset!");

                    return;

                }

                // Find the only fcs file and add its name and URL to the
                // DynaTree
                response.result.forEach(function(f) {

                    if (!f.isDirectory && f.pathInDataSet.toLowerCase() === "thumbnail.png") {

                        // Retrieve the file URL
                        DATAMODEL.openbisServer.getDownloadUrlForFileForDataSetInSession(
                            dataset.code, f.pathInDataSet, function(url){

                                // Replace the image
                                var eUrl = encodeURI(url);
                                eUrl = eUrl.replace('+', '%2B');
                                $("#" + img_id).attr("src", eUrl);
                                $("#" + img_id).css("display", "inline");

                            });
                    } else {

                        // Thumbnail not found!
                        var imD = $("#" + img_id);
                        imD.attr("src", "./img/error.png");
                        imD.attr("title", "Could not find a thumbnail for this dataset!");

                    }
                });

            });

    });

};

/**
 * Display status text color-coded by level.
 * @param status: text to be displayed
 * @param level: one of "success", "info", "warning", "error". Default is "info"
 */
DataViewer.prototype.displayStatus = function(status, level) {

    // Get the the statusView div
    var statusView_div = $("#statusView");

    // Clear the status
    statusView_div.empty();

    // Make sure the status div is visible
    statusView_div.show();

    var cls;
    switch (level) {
        case "success":
            cls = "success";
            break;
        case "info":
            cls = "info";
            break;
        case "warning":
            cls = "warning";
            break;
        case "error":
            cls = "danger";
            break;
        default:
            cls = "info";
            break;
    }

    status = "
" +
        status + "
";
    statusView_div.html(status);

};

/**
 * Format dataset size for display.
 * @param datasetSize: size in bytes
 * @return string: formatted dataset size in the form 322.5 MiB or 3.7 GiB
 */
DataViewer.prototype.formatSizeForDisplay = function(datasetSize) {

    // Output
    var formattedDatasetSize = "";

    // Cast datasetSize to float
    var datasetSizeF = parseFloat(datasetSize);

    var sMB = datasetSizeF / 1024.0 / 1024.0;
    if (sMB < 1024.0) {
        formattedDatasetSize = sMB.toFixed(2) + " MiB";
    } else {
        var sGB = sMB / 1024.0;
        formattedDatasetSize = sGB.toFixed(2) + " GiB";
    }

    return formattedDatasetSize;
};

/**
 * Prepare a title div to be added to the page.
 * @param title Text for the title
 * @param level One of "default", "info", "success", "warning", "danger". Default is "default".
 */
DataViewer.prototype.prepareTitle = function(title, level) {

    // Make sure the level is valid
    if (["default", "success", "info", "warning", "danger"].indexOf(level) === -1) {
        level = "default";
    }

    return ($("
").append($("").addClass("label").addClass("label-" + level).text(title)));

};


text:
define([
    'services/unitofwork',
    'viewmodels/home/reading',
    'commands/deleteReading'
],
  function (unitofwork, readingViewModel, deleteReadingCommand) {

    var command = function (viewmodel) {
      var self = this;

      var cmd = ko.asyncCommand({
        execute: function (complete) {
          var newEntity = unitofwork.readingRepository.create({
            survey: viewmodel.survey,
            energySource: _.find(viewmodel.energySources, function(energySource) {
              return energySource.name() === "electricity";
            }),
            value: 0
          });
          viewmodel.readingViewModels.push(new readingViewModel(newEntity, viewmodel.survey, viewmodel.energySources, new deleteReadingCommand(viewmodel)));
          complete();
        },
        canExecute: function (isExecuting) {
          return true;
        }
      });

      return cmd;

    };

    return command;
  });


text:
require 'spec_helper'

describe BadgeBase do
  let(:repo) { Fabricate(:github_repo) }
  let(:profile) { Fabricate(:github_profile, github_id: repo.owner.github_id) }
  let(:user) { Fabricate(:user, github_id: profile.github_id) }

  it 'should check to see if it needs to award users' do
    stub_request(:get, 'http://octocoder.heroku.com/rails/rails/mdeiters').to_return(body: '{}')
    Octopussy.stub(:new).and_return do |*args|
      octopussy_mock = double("Octopussy")
      octopussy_mock.should_receive(:valid?).and_return(true)
      octopussy_mock.should_receive(:award?).and_return(false)
      octopussy_mock
    end
    BadgeBase.award!(user)
  end

  it 'allows sub classes to have their own description' do
    foo = Class.new(BadgeBase) do
      describe "Foo", description: "Foo", image_name: 'foo.png'
    end

    bar = Class.new(foo) do
      describe "Bar", description: "Bar", image_name: 'bar.png'
    end

    foo.display_name.should == 'Foo'
    foo.description.should == 'Foo'
    foo.image_name.should == 'foo.png'

    bar.display_name.should == 'Bar'
    bar.description.should == 'Bar'
    bar.image_name.should == 'bar.png'
  end

  class NotaBadge < BadgeBase
    def award?;
      true;
    end

    def reasons;
      ["I don't need a reason"];
    end
  end
end


text:
CreativityObjectWrapper

needed for interfacing tree nodes to system's classes


text:
using System.Reflection.Emit;

/// <summary>
/// The wrapper of the <see cref="ILGenerator"/> for the branch clauses of the IL emitting.
/// </summary>
public sealed class BranchILGenerator
{
    internal BranchILGenerator(ILGenerator il, Label label, bool shortForm)
    {
        IL = il;
        Label = label;
        ShortForm = shortForm;
    }

    internal ILGenerator IL { get; }

    internal Label Label { get; }

    internal bool ShortForm { get; }
}


text:
using UnityEditor;
using UnityEngine;

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5
public class MegaUndo
{
	private     Object              defTarget;
	private     string              defName;
	//private     bool                autoSetDirty;
	//private     bool                listeningForGuiChanges;
	//private     bool                isMouseDown;
	//private     Object              waitingToRecordPrefab; // If different than NULL indicates the prefab instance that will need to record its state as soon as the mouse is released.

	public MegaUndo(Object p_target, string p_name) : this(p_target, p_name, true) { }
	public MegaUndo(Object p_target, string p_name, bool p_autoSetDirty)
	{
		defTarget = p_target;
		defName = p_name;
		//autoSetDirty = p_autoSetDirty;
	}

	public void CheckUndo() { CheckUndo(defTarget, defName); }
	public void CheckUndo(Object obj, string name)
	{

	}

	public bool CheckDirty(Object obj)
	{
		if ( GUI.changed )	// Wont work for dragging points
		{
			Undo.RecordObject(obj, defName);
		}
		return false;	//CheckDirty(defTarget, defName);
	}

	public bool CheckDirty()
	{
		return CheckDirty(defTarget);
	}

	public static void SetSnapshotTarget(Object obj, string name)
	{
		Undo.RecordObject(obj, name);
	}

	public static void CreateSnapshot()
	{
		//Undo.CreateSnapshot();
	}

	public static void RegisterSnapshot()
	{
		//Undo.RegisterSnapshot();
	}

	public static void ClearSnapshotTarget()
	{
		//Undo.ClearSnapshotTarget();
	}
}
#else
public class MegaUndo
{
	private     Object              defTarget;
	private     string              defName;
	private     bool                autoSetDirty;
	private     bool                listeningForGuiChanges;
	private     bool                isMouseDown;
	private     Object              waitingToRecordPrefab; // If different than NULL indicates the prefab instance that will need to record its state as soon as the mouse is released.

	public MegaUndo(Object p_target, string p_name) : this(p_target, p_name, true) { }
	public MegaUndo(Object p_target, string p_name, bool p_autoSetDirty)
	{
		defTarget = p_target;
		defName = p_name;
		autoSetDirty = p_autoSetDirty;
	}

	public void CheckUndo() { CheckUndo(defTarget, defName); }
	public void CheckUndo(Object p_target) { CheckUndo(p_target, defName); }
	public void CheckUndo(Object p_target, string p_name)
	{
		Event e = Event.current;

		if ( waitingToRecordPrefab != null )
		{
			// Record eventual prefab instance modification.
			// TODO Avoid recording if nothing changed (no harm in doing so, but it would be nicer).
			switch ( e.type )
			{
				case EventType.MouseDown:
				case EventType.MouseUp:
				case EventType.KeyDown:
				case EventType.KeyUp:
					PrefabUtility.RecordPrefabInstancePropertyModifications(waitingToRecordPrefab);
					break;
			}
		}

		if ( (e.type == EventType.MouseDown && e.button == 0) || (e.type == EventType.KeyUp && e.keyCode == KeyCode.Tab) )
		{
			// When the LMB is pressed or the TAB key is released,
			// store a snapshot, but don't register it as an undo
			// (so that if nothing changes we avoid storing a useless undo).
			Undo.SetSnapshotTarget(p_target, p_name);
			Undo.CreateSnapshot();
			Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
			listeningForGuiChanges = true;
		}

	}

	public bool CheckDirty() { return CheckDirty(defTarget, defName); }
	public bool CheckDirty(Object p_target) { return CheckDirty(p_target, defName); }
	public bool CheckDirty(Object p_target, string p_name)
	{
		if ( listeningForGuiChanges && GUI.changed )
		{
			// Some GUI value changed after pressing the mouse
			// or releasing the TAB key.
			// Register the previous snapshot as a valid undo.
			SetDirty(p_target, p_name);
			return true;
		}
		return false;
	}

	public void ForceDirty() { ForceDirty(defTarget, defName); }
	public void ForceDirty(Object p_target) { ForceDirty(p_target, defName); }
	public void ForceDirty(Object p_target, string p_name)
	{
		if ( !listeningForGuiChanges )
		{
			// Create a new snapshot.
			Undo.SetSnapshotTarget(p_target, p_name);
			Undo.CreateSnapshot();
			Undo.ClearSnapshotTarget();
		}
		SetDirty(p_target, p_name);
	}

	private void SetDirty(Object p_target, string p_name)
	{
		Undo.SetSnapshotTarget(p_target, p_name);
		Undo.RegisterSnapshot();
		Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
		if ( autoSetDirty ) EditorUtility.SetDirty(p_target);
		listeningForGuiChanges = false;

		if ( CheckTargetIsPrefabInstance(p_target) )
		{
			// Prefab instance: record immediately and also wait for value to be changed and than re-record it
			// (otherwise prefab instances are not updated correctly when using Custom Inspectors).
			PrefabUtility.RecordPrefabInstancePropertyModifications(p_target);
			waitingToRecordPrefab = p_target;
		}
		else
		{
			waitingToRecordPrefab = null;
		}
	}

	private bool CheckTargetIsPrefabInstance(Object p_target)
	{
		return (PrefabUtility.GetPrefabType(p_target) == PrefabType.PrefabInstance);
	}

	public static void SetSnapshotTarget(Object obj, string name)
	{
		Undo.SetSnapshotTarget(obj, name);
	}

	public static void CreateSnapshot()
	{
		Undo.CreateSnapshot();
	}

	public static void RegisterSnapshot()
	{
		Undo.RegisterSnapshot();
	}

	public static void ClearSnapshotTarget()
	{
		Undo.ClearSnapshotTarget();
	}
}
#endif


text:
class ColorMap
{
public:
    ColorMap();

    float redDark;
    float redBright;
    float greenDark;
    float greenBright;
    float blueDark;
    float blueBright;
};

#endif // COLORMAP_H


text:
echo "Building documentation"
cd ./website
dotnet restore
dotnet build
dotnet run

echo "Copying files into docfx inputs"
cd ../
cp -f ../README.md ./docfx/index.md
cp -f ./website/www/*.md ./docfx/articles/

echo "Building DoxFX. Will Serve"
cd ./docfx
docfx --serve


text:
class SessionsController < ApplicationController
  def new
    redirect_to '/auth/facebook'
  end

  def create
    auth = request.env["omniauth.auth"]
    session[:token] = auth["credentials"]["token"]
    user = User.where(:provider => auth['provider'],
                      :uid => auth['uid'].to_s).first || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    redirect_to new_slide_show_path, :notice => 'Signed in!'
  end

  def destroy
    reset_session
    redirect_to root_url, :notice => 'Signed out!'
  end

  def failure
    redirect_to root_url, :alert => "Authentication error: #{params[:message].humanize}"
  end
end


text:
package net.qiujuer.genius.ui.drawable;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;

/**
 * A drawable to draw loading form Circle Type
 */
public class LoadingCircleDrawable extends LoadingDrawable {
    private static final int ANGLE_ADD = 5;
    private static final int MIN_ANGLE_SWEEP = 3;
    private static final int MAX_ANGLE_SWEEP = 255;
    private static int DEFAULT_SIZE = 56;

    private int mMinSize = DEFAULT_SIZE;
    private int mMaxSize = DEFAULT_SIZE;
    private RectF mOval = new RectF();

    private float mStartAngle = 0;
    private float mSweepAngle = 0;
    private int mAngleIncrement = -3;

    public LoadingCircleDrawable() {
        super();
        mForegroundPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    public LoadingCircleDrawable(int minSize, int maxSize) {
        super();
        mMinSize = minSize;
        mMaxSize = maxSize;
    }

    @Override
    public int getIntrinsicHeight() {
        float maxLine = Math.max(mBackgroundPaint.getStrokeWidth(), mForegroundPaint.getStrokeWidth());
        int size = (int) (maxLine * 2 + 10);
        return Math.min(mMaxSize, Math.max(size, mMinSize));
    }

    @Override
    public int getIntrinsicWidth() {
        float maxLine = Math.max(mBackgroundPaint.getStrokeWidth(), mForegroundPaint.getStrokeWidth());
        int size = (int) (maxLine * 2 + 10);
        return Math.min(mMaxSize, Math.max(size, mMinSize));
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        if (bounds.left == 0 && bounds.top == 0 && bounds.right == 0 && bounds.bottom == 0) {
            return;
        }

        final int centerX = bounds.centerX();
        final int centerY = bounds.centerY();

        final int radius = Math.min(bounds.height(), bounds.width()) >> 1;
        final int maxStrokeRadius = ((int) Math.max(getForegroundLineSize(), getBackgroundLineSize()) >> 1) + 1;
        final int areRadius = radius - maxStrokeRadius;

        mOval.set(centerX - areRadius, centerY - areRadius, centerX + areRadius, centerY + areRadius);
    }

    @Override
    protected void onProgressChange(float progress) {
        mStartAngle = 0;
        mSweepAngle = 360 * progress;
    }

    @Override
    protected void onRefresh() {
        final float angle = ANGLE_ADD;
        mStartAngle += angle;

        if (mStartAngle > 360) {
            mStartAngle -= 360;
        }

        if (mSweepAngle > MAX_ANGLE_SWEEP) {
            mAngleIncrement = -mAngleIncrement;
        } else if (mSweepAngle < MIN_ANGLE_SWEEP) {
            mSweepAngle = MIN_ANGLE_SWEEP;
            return;
        } else if (mSweepAngle == MIN_ANGLE_SWEEP) {
            mAngleIncrement = -mAngleIncrement;
            getNextForegroundColor();
        }
        mSweepAngle += mAngleIncrement;
    }

    @Override
    protected void drawBackground(Canvas canvas, Paint backgroundPaint) {
        canvas.drawArc(mOval, 0, 360, false, backgroundPaint);
    }

    @Override
    protected void drawForeground(Canvas canvas, Paint foregroundPaint) {
        canvas.drawArc(mOval, mStartAngle, -mSweepAngle, false, foregroundPaint);
    }
}


text:
from __future__ import division
import os
from math import exp, log

from .lexer import lex, ngram

import logging
logger = logging.getLogger(__name__)

class Classifier(object):
    """Bayesian classifier. """

    def __init__(self, model, grams=3):
        self.model = model
        self.grams = grams

    def train(self, corpus_dir):
        """
        Pass in a directory containing sample language files.
        Returns None
        """
        _, langs, _ = os.walk(corpus_dir).next()
        if not langs:
            logger.warning('No language is found under %s', corpus_dir)
        for lang in filter(lambda l: not l.startswith('.'), langs):
            file_paths = []
            for root, _, files in os.walk(os.path.join(corpus_dir, lang)):
                file_paths.extend(map(lambda fn: os.path.join(root, fn), files))
            if not file_paths:
                logger.warning('[%s] no file is found under %s', lang, os.path.join(corpus_dir, lang))
            for fpath in file_paths:
                logger.debug('[%s] parsing %s', lang, fpath)
                try:
                    fcontent = open(fpath).read()
                    tokens = lex(fcontent)
                    map(lambda gram: self.model.put(lang, gram), ngram(tokens, self.grams))
                except UnicodeDecodeError:
                    if fcontent:
                        logger.warning('[%s] cannot decode %s to unicode', lang, fpath)
                    continue
        self.model.save()

    def classify(self, text):
        """
        Guess language of the literal text.
        Returns a sorted array of possible languages. Each item contains
        a language name and a score.
        """
        self.model.load()
        score = {}
        for lang in self.model.languages():
            probs = []
            for gram in ngram(lex(text), self.grams):
                p = self.p_lang_on_token(lang, gram)
                # We should not use 1.0 as a probability, as it will cause
                # a lot of math errors
                # if p >= 1.0:
                #     p = .999
                probs.append(p)
            # probs.sort(reverse=True)
            score[lang] = self.combined_probability(probs, self.p_lang(lang))
            logger.debug('[%s] probability is %s', lang, self.p_lang(lang))
            logger.debug('[%s] combined probability is %s', lang, score[lang])
        return sorted(score.items(), key=lambda s: s[1], reverse=True)

    # For a good explanation of the background, see:
    # https://www.bionicspirit.com/blog/2012/02/09/howto-build-naive-bayes-classifier.html
    def combined_probability(self, tok_probs, lang_prob):
        """
          P(lang | tok1, tok2, tok3...tokN)

          P(tok1, tok2, tok3...tokN | lang) * P(lang)
        = --------------------------------------------
                  P(tok1, tok2, tok3...tokN)

        (naively assume that tokens are independent from each other)

         P(tok1|lang) * P(tok2|lang) * P(tok3|lang) ... P(tokN|lang) * P(lang)
        = ---------------------------------------------------------------------
             P(tok1) * P(tok2) * P(tok3) ... P(tokN)

                P(tok|lang)   P(lang|tok)
              ( ----------- = ----------- )
                  P(tok)        P(lang)

         P(lang|tok1) * P(lang|tok2) * P(lang|tok3) ... P(lang|tokN) * P(lang)
        = ---------------------------------------------------------------------
                               P(lang)**N
        """
        # return reduce(lambda x, y: x*y, tok_probs) / (lang_prob**(len(tok_probs)-1))
        # Usually p is not directly computed using the above formula due to
        # floating-point underflow. Instead, p can be computed in the log domain
        return sum(map(log, tok_probs)) - (len(tok_probs)-1)*log(lang_prob)

    def p_lang_on_token(self, lang, token):
        """"
        Probability of a language given a token
        P(lang | token) = P(token | lang) * P(lang) / P(token)

           n_token_on_lang(token, lang)     n_lang_tokens(lang)     n_token(token)
        = ------------------------------ * -------------------- /  ---------------
           n_lang_tokens(lang)              n_tokens()              n_tokens()

           n_token_on_lang(token, lang)
        = ------------------------------
           n_token(token)
        """
        if not self.model.n_token_on_lang(token, lang):
            # A crude smoothing algo
            logger.debug('[%s] %s is not seen, use %s instead', lang, token,
                    1.0/(self.model.n_tokens()+1))
            return 1.0/(self.model.n_tokens()+1)
        p = self.model.n_token_on_lang(token, lang) / self.model.n_token(token)
        logger.debug('[%s] probability given %s is %s', lang, token, p)
        return p

    def p_lang(self, lang):
        return self.model.n_lang_tokens(lang) / self.model.n_tokens()

if __name__ == '__main__':
    from . import model
    model = model.LanguageModel(open('model.json'))
    classifier = Classifier(model)
    # classifier.train('corpus')
    print classifier.classify('fdsfdsasafds')


text:
package io.netty.testsuite.transport.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.junit.Test;

import java.net.SocketException;
import java.nio.channels.NotYetConnectedException;

import static org.junit.Assert.fail;

public class SocketChannelNotYetConnectedTest extends AbstractClientSocketTest {
    @Test(timeout = 30000)
    public void testShutdownNotYetConnected() throws Throwable {
        run();
    }

    public void testShutdownNotYetConnected(Bootstrap cb) throws Throwable {
        SocketChannel ch = (SocketChannel) cb.handler(new ChannelInboundHandlerAdapter())
                .bind(newSocketAddress()).syncUninterruptibly().channel();
        try {
            try {
                ch.shutdownInput().syncUninterruptibly();
                fail();
            } catch (Throwable cause) {
                checkThrowable(cause);
            }

            try {
                ch.shutdownOutput().syncUninterruptibly();
                fail();
            } catch (Throwable cause) {
                checkThrowable(cause);
            }
        } finally {
            ch.close().syncUninterruptibly();
        }
    }

    private static void checkThrowable(Throwable cause) throws Throwable {
        // Depending on OIO / NIO both are ok
        if (!(cause instanceof NotYetConnectedException) && !(cause instanceof SocketException)) {
            throw cause;
        }
    }
}


text:
@interface TitleViewCell : UICollectionViewCell

@property (nonatomic,strong)UILabel *title;
@property (nonatomic,strong)UIButton *addButton;
@property (nonatomic,strong)UIButton *deleteButton;

@end


text:
package org.caleydo.view.domino.internal;

import java.util.ArrayDeque;
import java.util.Deque;

import org.caleydo.core.util.base.ICallback;
import org.caleydo.view.domino.internal.undo.ICmd;
import org.caleydo.view.domino.internal.undo.IMergeAbleCmd;

/**
 * @author Samuel Gratzl
 *
 */
public class UndoStack {
	private final Deque<ICmd> undo = new ArrayDeque<>();
	private final Deque<ICmd> redo = new ArrayDeque<>();
	private final Domino domino;
	private ICallback<UndoStack> onChanged;

	public UndoStack(Domino domino) {
		this.domino = domino;
	}

	public void onChanged(ICallback<UndoStack> onChanged) {
		this.onChanged = onChanged;
	}

	public void push(ICmd cmd) {
		ICmd undo = cmd.run(domino);
		if (undo != null) {
			if (this.undo.peekLast() instanceof IMergeAbleCmd) {
				IMergeAbleCmd peek = (IMergeAbleCmd) this.undo.peekLast();
				if (!peek.merge(undo))
					this.undo.add(undo);
			} else
				this.undo.add(undo);
		}
		this.redo.clear();
		fire();
	}

	/**
	 *
	 */
	private void fire() {
		if (onChanged != null)
			onChanged.on(this);
	}

	public boolean undo() {
		if (this.undo.isEmpty())
			return false;
		ICmd cmd = this.undo.pollLast();
		ICmd redo = cmd.run(domino);
		if (redo != null)
			this.redo.add(redo);
		fire();
		return true;
	}

	public void clearUndo() {
		this.undo.clear();
		fire();
	}

	public void undoAll() {
		while (!this.undo.isEmpty())
			undo();
	}

	public boolean redo() {
		if (this.redo.isEmpty())
			return false;
		ICmd cmd = this.redo.pollLast();
		ICmd redo = cmd.run(domino);
		if (redo != null)
			this.undo.add(redo);
		fire();
		return true;
	}

	/**
	 * @return
	 */
	public boolean isUndoEmpty() {
		return undo.isEmpty();
	}

	public boolean isRedoEmpty() {
		return this.redo.isEmpty();
	}
}


text:
layout: page
title: Phelps - Bautista Wedding
date: 2016-05-24
author: Steven Ray
tags: weekly links, java
status: published
summary: Phasellus varius tellus quis enim laoreet, vel fermentum.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/07/2017
  endDate: 06/09/2017
  ctyhocn: ARBVWHX
  groupCode: PBW
published: true
---
Nunc rhoncus mauris vel odio dignissim sollicitudin. Duis cursus velit id justo venenatis, non viverra nisi congue. Nunc consequat justo id quam varius venenatis. Etiam non sapien quis leo hendrerit pharetra. Mauris tincidunt, nisi nec tincidunt mattis, arcu nulla porttitor quam, nec venenatis justo magna ut nibh. Ut vel diam vitae purus tincidunt finibus nec vel quam. Integer lacinia vel nisi sit amet imperdiet. Donec sodales orci eu justo varius laoreet. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

* Maecenas in massa tempor, vulputate justo ut, condimentum mi
* Cras vehicula mauris eget rhoncus semper
* Praesent id neque et dui rhoncus tincidunt
* Sed suscipit lectus nec magna faucibus, et ornare ex ornare
* Nulla eget ipsum a diam ultrices vehicula eget vitae ex
* Cras et odio hendrerit eros rhoncus lacinia.

Proin maximus diam et magna placerat luctus. Cras consequat elit eget ligula varius, et scelerisque leo ultricies. Suspendisse vehicula ex vel leo fermentum, nec lacinia lorem mollis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi non sollicitudin velit. Aenean gravida ultrices tempus. Etiam auctor arcu nisl, sed consequat ante luctus in. Etiam ut dolor eu ante ultricies scelerisque eget non urna. Cras elit tellus, sagittis vitae ultrices a, commodo non ante. Fusce mi ligula, vehicula nec sollicitudin at, efficitur nec dolor. Phasellus aliquet eros at quam lacinia, ac facilisis tortor tincidunt. Etiam commodo vel lorem eu tincidunt.