text:
app.controller('cAdvisorController', [
  '$scope',
  '$routeParams',
  'k8sApi',
  'lodash',
  'cAdvisorService',
  '$q',
  '$interval',
  function($scope, $routeParams, k8sApi, lodash, cAdvisorService, $q, $interval) {
    $scope.k8sApi = k8sApi;

    $scope.activeMinionDataById = {};
    $scope.maxDataByById = {};

    $scope.getData = function() {
      $scope.loading = true;

      k8sApi.getMinions().success(angular.bind(this, function(res) {

        $scope.minions = res;

        var promises = lodash.map(res.items, function(m) {
            var readyCondition = m.status.conditions.filter(function ( obj ) {
                return obj.type === 'Ready';
            })[0];

            return cAdvisorService.getDataForMinion(m.metadata.name, readyCondition && readyCondition.status === 'True')
              .catch(function(errorData) {
                // don't fail the whole promise chain just because one node failed
                return null;
              });
        });
        $q.all(promises).then(
            function(dataArray) {
              lodash.each(dataArray, function(data, i) {
                if (!data) return; // ignore errornous nodes

                var m = res.items[i];

                var maxData = maxMemCpuInfo(m.metadata.name, data.memoryData, data.cpuData, data.filesystemData);

                if(m.status.addresses)
                  hostname = m.status.addresses[0].address;
                else
                  hostname = m.metadata.name;

                cpu = m.status.capacity ? m.status.capacity.cpu : '-';
                $scope.activeMinionDataById[m.metadata.name] =
                    transformMemCpuInfo(data.memoryData, data.cpuData, data.filesystemData, maxData, hostname, cpu);
              });

            },
            function() {
              // console.log("Error: " + errorData);
              $scope.loading = false;
            });

        $scope.loading = false;
      })).finally(function() {
        $scope.loading = false;
      });
    };

    // d3
    function getColorForIndex(i, percentage) {
      // var colors = ['red', 'blue', 'yellow', 'pink', 'purple', 'green', 'orange'];
      // return colors[i];
      var c = "color-" + (i + 1);
      if (percentage && percentage >= 90)
        c = c + ' color-critical';
      else if (percentage && percentage >= 80)
        c = c + ' color-warning';

      return c;
    }

    function getMaxColorForIndex(i, percentage) {
      // var colors = ['red', 'blue', 'yellow', 'pink', 'purple', 'green', 'orange'];
      // return colors[i];
      var c = "color-max-" + (i + 1);
      if (percentage && percentage >= 90)
        c = c + ' color-max-critical';
      else if (percentage && percentage >= 80)
        c = c + ' color-max-warning';

      return c;
    }

    function maxMemCpuInfo(mId, mem, cpu, fsDataArray) {
      if ($scope.maxDataByById[mId] === undefined) $scope.maxDataByById[mId] = {};

      var currentMem = mem.current;
      var currentCpu = cpu;

      var items = [];

      if ($scope.maxDataByById[mId]['cpu'] === undefined ||
          $scope.maxDataByById[mId]['cpu'] < currentCpu.cpuPercentUsage) {
        // console.log("New max cpu " + mId, $scope.maxDataByById[mId].cpu, currentCpu.cpuPercentUsage);
        $scope.maxDataByById[mId]['cpu'] = currentCpu.cpuPercentUsage;
      }
      items.push({
        maxValue: $scope.maxDataByById[mId]['cpu'],
        maxTickClassNames: getColorForIndex(0, $scope.maxDataByById[mId]['cpu']),
        maxClassNames: getMaxColorForIndex(0, $scope.maxDataByById[mId]['cpu'])
      });

      var memPercentage = Math.floor((currentMem.memoryUsage * 100.0) / currentMem.memoryLimit);
      if ($scope.maxDataByById[mId]['mem'] === undefined || $scope.maxDataByById[mId]['mem'] < memPercentage)
        $scope.maxDataByById[mId]['mem'] = memPercentage;
      items.push({
        maxValue: $scope.maxDataByById[mId]['mem'],
        maxTickClassNames: getColorForIndex(1, $scope.maxDataByById[mId]['mem']),
        maxClassNames: getMaxColorForIndex(1, $scope.maxDataByById[mId]['mem'])
      });

      for (var i = 0; i < fsDataArray.length; i++) {
        var f = fsDataArray[i];
        var fid = 'FS #' + f.filesystemNumber;
        if ($scope.maxDataByById[mId][fid] === undefined || $scope.maxDataByById[mId][fid] < f.totalUsage)
          $scope.maxDataByById[mId][fid] = f.totalUsage;
        items.push({
          maxValue: $scope.maxDataByById[mId][fid],
          maxTickClassNames: getColorForIndex(2 + i, $scope.maxDataByById[mId][fid]),
          maxClassNames: getMaxColorForIndex(2 + i, $scope.maxDataByById[mId][fid])
        });
      }

      // console.log("Max Data is now " + mId, $scope.maxDataByById[mId]);
      return items;
    }

    function transformMemCpuInfo(mem, cpu, fsDataArray, maxData, hostName, numCpus) {
      var currentMem = mem.current;
      var currentCpu = cpu;

      var items = [];

      items.push({
        label: 'CPU',
        stats: currentCpu.cpuPercentUsage + '% / ' + numCpus + ' CPU',
        value: currentCpu.cpuPercentUsage,
        classNames: getColorForIndex(0, currentCpu.cpuPercentUsage),
        maxData: maxData[0],
        hostName: hostName
      });

      var memPercentage = Math.floor((currentMem.memoryUsage * 100.0) / currentMem.memoryLimit);
      items.push({
        label: 'Memory',
        stats: currentMem.memoryUsageDescription + ' / ' + currentMem.memoryLimitDescription,
        value: memPercentage,
        classNames: getColorForIndex(1, memPercentage),
        maxData: maxData[1],
        hostName: hostName
      });

      for (var i = 0; i < fsDataArray.length; i++) {
        var f = fsDataArray[i];

        items.push({
          label: 'Filesystem #' + f.filesystemNumber,
          stats: f.usageDescription + ' / ' + f.capacityDescription,
          value: f.totalUsage,
          classNames: getColorForIndex(2 + i, f.totalUsage),
          maxData: maxData[2 + i],
          hostName: hostName

        });
      }

      var a = [];
      var segments = {
        segments: items
      };
      a.push(segments);
      return a;
    };

    // end d3
    var promise = $interval($scope.getData, 3000);

    // Cancel interval on page changes
    $scope.$on('$destroy', function() {
      if (angular.isDefined(promise)) {
        $interval.cancel(promise);
        promise = undefined;
      }
    });

    $scope.getData();

  }
]);


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Single Sign On for you website</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/night.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

						Honza @Novoj Novotný

The task was simple

Client has several high traffic sites and e-shops on different domains.
                            He wanted to consolidate user accounts in a single place and share accounts among them.

www.fraus.cz

seminare.fraus.cz

ucebnice.fraus.cz

frausmedia.cz

www.flexibooks.cz

www.flexilearn.cz

AND SO WE DID IT

... HAVE A LOOK ...

But SSO is "solved" problem, isn't it?

lot of enterprise solutions like CAS, JBoss SSO, JOSSO

alternative approaches - OpenId, MojeId, OAuth

What enterprise solutions offered:

multiple systems federation - email clients, wiki, revision controls

LDAP / ActiveDirectory integration

complexity + costs

They're much more suitable for "intranet" usage than for e-shops.

What OpenId, OAuth offered:

proven concept

several implementations

Very good to accept outside identities to create internal accounts in the e-shop.
                           Not much suitable to transfer logged user among the shops (any idea?).

What were our starting points?

websites are owned by the same organization

no external applications needs to share authentication

single shared database with accounts accessible from all websites

request for natural registration and login process in each of site

request for diversity of the profile and reqistration in some sites

fast homepage access (no redirects if possible!)

Maybe too simple for "enterprise" solutions?!

Why is it so hard?

user sessions are located by cookies

cookies are not shared between different domains of the same level

the only solution is to use shared account domain

Mmm, the problem doesn't sound that difficult. Does it?!

How is it usually done?

SAML message exchange model for achieving Web SSO looks like this:

                            Credit: http://www.cs.wustl.edu/~jain/cse571-07/ftp/websso/

How we did it?

Mechanism #1

1. user visits https://www.fraus.cz

2. page embeds https://account.fraus.cz/user/www.fraus.cz/123abc

3. account server stores into session and DB:

                                    USER NOT LOGGED IN

                                    www.fraus.cz = token 123abc

4. account server returns user is not logged in (public JSON)

5. user logs in on https://www.fraus.cz against shared user DB

6. www.fraus.cz securely sends information to account server about user login

                                    USER novoj LOGGED IN

                                    www.fraus.cz = token 123abc

Mechanism #2

1. user visits https://www.flexibooks.cz

2. page embeds https://account.fraus.cz/user/www.flexibooks.cz/567def

3. account attaches new token to existing session and DB:

                                    USER novoj LOGGED IN

                                    www.fraus.cz = token 123abc

                                    www.flexibooks.cz = token 567def

4. account server returns novoj is logged in (public JSON)

5. www.flexibooks.cz verifies securely that novoj is logged in for token 567def

6. account server confirms novoj is logged in - it paired both tokens through single session

7. www.flexibooks.cz refreshes page contents and display correct user prices

Challenges

clustering - 2x2 nodes

synchronizing session with background API requests

tolerance to different invocation order (login before lead token request)

ensuring single session active for user over all devices

Thats it!

                        Honza Novotný, FG Forrest

                        @novoj

                        http://blog.novoj.net

redpajama_set_name: RedPajamaGithub


text:
"""Implementation of the MediaRemoteTV Protocol used by ATV4 and later."""

import asyncio
import datetime
import logging
import math
import re
from typing import Any, Dict, Generator, List, Mapping, Optional, Set, Tuple

from pyatv import exceptions
from pyatv.auth.hap_srp import SRPAuthHandler
from pyatv.const import (
    DeviceState,
    FeatureName,
    FeatureState,
    InputAction,
    MediaType,
    OperatingSystem,
    PairingRequirement,
    PowerState,
    Protocol,
    RepeatState,
    ShuffleState,
)
from pyatv.core import (
    AbstractPushUpdater,
    Core,
    MutableService,
    ProtocolStateDispatcher,
    SetupData,
    UpdatedState,
    mdns,
)
from pyatv.core.scan import (
    ScanHandlerDeviceInfoName,
    ScanHandlerReturn,
    device_info_name_from_unique_short_name,
)
from pyatv.helpers import get_unique_id
from pyatv.interface import (
    App,
    ArtworkInfo,
    Audio,
    BaseConfig,
    BaseService,
    DeviceInfo,
    FeatureInfo,
    Features,
    Metadata,
    PairingHandler,
    Playing,
    Power,
    PushUpdater,
    RemoteControl,
)
from pyatv.protocols.mrp import messages, protobuf
from pyatv.protocols.mrp.connection import AbstractMrpConnection, MrpConnection
from pyatv.protocols.mrp.pairing import MrpPairingHandler
from pyatv.protocols.mrp.player_state import PlayerState, PlayerStateManager
from pyatv.protocols.mrp.protobuf import CommandInfo_pb2
from pyatv.protocols.mrp.protobuf import ContentItemMetadata as cim
from pyatv.protocols.mrp.protobuf import PlaybackState
from pyatv.protocols.mrp.protocol import MrpProtocol
from pyatv.support.cache import Cache
from pyatv.support.device_info import lookup_model, lookup_version
from pyatv.support.http import ClientSessionManager

_LOGGER = logging.getLogger(__name__)

# Source: https://github.com/Daij-Djan/DDHidLib/blob/master/usb_hid_usages.txt
_KEY_LOOKUP = {
    # name: [usage_page, usage]
    "up": (1, 0x8C),
    "down": (1, 0x8D),
    "left": (1, 0x8B),
    "right": (1, 0x8A),
    "stop": (12, 0xB7),
    "next": (12, 0xB5),
    "previous": (12, 0xB6),
    "select": (1, 0x89),
    "menu": (1, 0x86),
    "topmenu": (12, 0x60),
    "home": (12, 0x40),
    "suspend": (1, 0x82),
    "wakeup": (1, 0x83),
    "volume_up": (12, 0xE9),
    "volume_down": (12, 0xEA),
    # 'mic': (12, 0x04),  # Siri
}  # Dict[str, Tuple[int, int]]

_FEATURES_SUPPORTED: List[FeatureName] = [
    FeatureName.Down,
    FeatureName.Home,
    FeatureName.HomeHold,
    FeatureName.Left,
    FeatureName.Menu,
    FeatureName.Right,
    FeatureName.Select,
    FeatureName.TopMenu,
    FeatureName.Up,
    FeatureName.TurnOn,
    FeatureName.TurnOff,
    FeatureName.PowerState,
]

_FEATURE_COMMAND_MAP = {
    FeatureName.Next: CommandInfo_pb2.NextTrack,
    FeatureName.Pause: CommandInfo_pb2.Pause,
    FeatureName.Play: CommandInfo_pb2.Play,
    FeatureName.PlayPause: CommandInfo_pb2.TogglePlayPause,
    FeatureName.Previous: CommandInfo_pb2.PreviousTrack,
    FeatureName.Stop: CommandInfo_pb2.Stop,
    FeatureName.SetPosition: CommandInfo_pb2.SeekToPlaybackPosition,
    FeatureName.SetRepeat: CommandInfo_pb2.ChangeRepeatMode,
    FeatureName.SetShuffle: CommandInfo_pb2.ChangeShuffleMode,
    FeatureName.Shuffle: CommandInfo_pb2.ChangeShuffleMode,
    FeatureName.Repeat: CommandInfo_pb2.ChangeRepeatMode,
    FeatureName.SkipForward: CommandInfo_pb2.SkipForward,
    FeatureName.SkipBackward: CommandInfo_pb2.SkipBackward,
}

# Features that are considered available if corresponding
_FIELD_FEATURES: Dict[FeatureName, str] = {
    FeatureName.Title: "title",
    FeatureName.Artist: "trackArtistName",
    FeatureName.Album: "albumName",
    FeatureName.Genre: "genre",
    FeatureName.TotalTime: "duration",
    FeatureName.SeriesName: "seriesName",
    FeatureName.Position: "elapsedTimeTimestamp",
    FeatureName.SeasonNumber: "seasonNumber",
    FeatureName.EpisodeNumber: "episodeNumber",
    FeatureName.ContentIdentifier: "contentIdentifier",
}

DELAY_BETWEEN_COMMANDS = 0.1

def _cocoa_to_timestamp(time):
    delta = datetime.datetime(2001, 1, 1) - datetime.datetime(1970, 1, 1)
    time_seconds = (datetime.timedelta(seconds=time) + delta).total_seconds()
    return datetime.datetime.fromtimestamp(time_seconds)

def build_playing_instance(  # pylint: disable=too-many-locals
    state: PlayerState,
) -> Playing:
    """Build a Playing instance from play state."""

    def media_type() -> MediaType:
        """Type of media is currently playing, e.g. video, music."""
        if state.metadata:
            media_type = state.metadata.mediaType
            if media_type == cim.Audio:
                return MediaType.Music
            if media_type == cim.Video:
                return MediaType.Video

        return MediaType.Unknown

    def device_state() -> DeviceState:
        """Device state, e.g. playing or paused."""
        return {
            None: DeviceState.Idle,
            PlaybackState.Playing: DeviceState.Playing,
            PlaybackState.Paused: DeviceState.Paused,
            PlaybackState.Stopped: DeviceState.Stopped,
            PlaybackState.Interrupted: DeviceState.Loading,
            PlaybackState.Seeking: DeviceState.Seeking,
        }.get(state.playback_state, DeviceState.Paused)

    def title() -> Optional[str]:
        """Title of the current media, e.g. movie or song name."""
        return state.metadata_field("title")

    def artist() -> Optional[str]:
        """Artist of the currently playing song."""
        return state.metadata_field("trackArtistName")

    def album() -> Optional[str]:
        """Album of the currently playing song."""
        return state.metadata_field("albumName")

    def genre() -> Optional[str]:
        """Genre of the currently playing song."""
        return state.metadata_field("genre")

    def total_time() -> Optional[int]:
        """Total play time in seconds."""
        duration = state.metadata_field("duration")
        if duration is None or math.isnan(duration):
            return None
        return int(duration)

    def position() -> Optional[int]:
        """Position in the playing media (seconds)."""
        elapsed_timestamp = state.metadata_field("elapsedTimeTimestamp")

        # If we don't have reference time, we can't do anything
        if not elapsed_timestamp:
            return None

        elapsed_time: int = state.metadata_field("elapsedTime") or 0
        diff = (
            datetime.datetime.now() - _cocoa_to_timestamp(elapsed_timestamp)
        ).total_seconds()

        if device_state() == DeviceState.Playing:
            return int(elapsed_time + diff)
        return int(elapsed_time)

    def shuffle() -> ShuffleState:
        """If shuffle is enabled or not."""
        info = state.command_info(CommandInfo_pb2.ChangeShuffleMode)
        if info is None:
            return ShuffleState.Off
        if info.shuffleMode == protobuf.ShuffleMode.Off:
            return ShuffleState.Off
        if info.shuffleMode == protobuf.ShuffleMode.Albums:
            return ShuffleState.Albums

        return ShuffleState.Songs

    def repeat() -> RepeatState:
        """Repeat mode."""
        info = state.command_info(CommandInfo_pb2.ChangeRepeatMode)
        if info is None:
            return RepeatState.Off
        if info.repeatMode == protobuf.RepeatMode.One:
            return RepeatState.Track
        if info.repeatMode == protobuf.RepeatMode.All:
            return RepeatState.All

        return RepeatState.Off

    def item_hash() -> str:
        """Create a unique hash for what is currently playing."""
        return state.item_identifier

    def series_name() -> str:
        """Series name."""
        return state.metadata_field("seriesName")

    def season_number() -> int:
        """Season number."""
        return state.metadata_field("seasonNumber")

    def episode_number() -> int:
        """Episode number."""
        return state.metadata_field("episodeNumber")

    def content_identifier() -> str:
        """Content identifier."""
        return state.metadata_field("contentIdentifier")

    return Playing(
        media_type=media_type(),
        device_state=device_state(),
        title=title(),
        artist=artist(),
        album=album(),
        genre=genre(),
        total_time=total_time(),
        position=position(),
        shuffle=shuffle(),
        repeat=repeat(),
        hash=item_hash(),
        series_name=series_name(),
        season_number=season_number(),
        episode_number=episode_number(),
        content_identifier=content_identifier(),
    )

async def _send_hid_key(
    protocol: MrpProtocol, key: str, action: InputAction, flush: bool = True
) -> None:
    async def _do_press(keycode: Tuple[int, int], hold: bool):
        await protocol.send(messages.send_hid_event(keycode[0], keycode[1], True))

        if hold:
            # Hardcoded hold time for one second
            await asyncio.sleep(1)

        await protocol.send(messages.send_hid_event(keycode[0], keycode[1], False))

        # Send and receive a generic message as some kind of "flush" mechanism
        if flush:
            await protocol.send_and_receive(messages.create(protobuf.GENERIC_MESSAGE))

    keycode = _KEY_LOOKUP.get(key)
    if not keycode:
        raise exceptions.NotSupportedError(f"unsupported key: {key}")

    if action == InputAction.SingleTap:
        await _do_press(keycode, False)
    elif action == InputAction.DoubleTap:
        await _do_press(keycode, False)
        await _do_press(keycode, False)
    elif action == InputAction.Hold:
        await _do_press(keycode, True)
    else:
        raise exceptions.NotSupportedError(f"unsupported input action: {action}")

# pylint: disable=too-many-public-methods
class MrpRemoteControl(RemoteControl):
    """Implementation of API for controlling an Apple TV."""

    def __init__(
        self,
        loop: asyncio.AbstractEventLoop,
        psm: PlayerStateManager,
        protocol: MrpProtocol,
    ) -> None:
        """Initialize a new MrpRemoteControl."""
        self.loop = loop
        self.psm = psm
        self.protocol = protocol

    async def _send_command(self, command, **kwargs):
        resp = await self.protocol.send_and_receive(messages.command(command, **kwargs))
        inner = resp.inner()

        if inner.sendError == protobuf.SendError.NoError:
            return

        raise exceptions.CommandError(
            f"{CommandInfo_pb2.Command.Name(command)} failed: "
            f"SendError={protobuf.SendError.Enum.Name(inner.sendError)}, "
            "HandlerReturnStatus="
            f"{protobuf.HandlerReturnStatus.Enum.Name(inner.handlerReturnStatus)}"
        )

    async def up(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key up."""
        await _send_hid_key(self.protocol, "up", action)

    async def down(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key down."""
        await _send_hid_key(self.protocol, "down", action)

    async def left(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key left."""
        await _send_hid_key(self.protocol, "left", action)

    async def right(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key right."""
        await _send_hid_key(self.protocol, "right", action)

    async def play(self) -> None:
        """Press key play."""
        await self._send_command(CommandInfo_pb2.Play)

    async def play_pause(self) -> None:
        """Toggle between play and pause."""
        # Cannot use the feature interface here since it emulates the feature state
        cmd = self.psm.playing.command_info(CommandInfo_pb2.TogglePlayPause)
        if cmd and cmd.enabled:
            await self._send_command(CommandInfo_pb2.TogglePlayPause)
        else:
            state = self.psm.playing.playback_state
            if state == PlaybackState.Playing:
                await self.pause()
            elif state == PlaybackState.Paused:
                await self.play()

    async def pause(self) -> None:
        """Press key play."""
        await self._send_command(CommandInfo_pb2.Pause)

    async def stop(self) -> None:
        """Press key stop."""
        await self._send_command(CommandInfo_pb2.Stop)

    async def next(self) -> None:
        """Press key next."""
        await self._send_command(CommandInfo_pb2.NextTrack)

    async def previous(self) -> None:
        """Press key previous."""
        await self._send_command(CommandInfo_pb2.PreviousTrack)

    async def select(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key select."""
        await _send_hid_key(self.protocol, "select", action)

    async def menu(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key menu."""
        await _send_hid_key(self.protocol, "menu", action)

    async def volume_up(self) -> None:
        """Press key volume up."""
        await _send_hid_key(self.protocol, "volume_up", InputAction.SingleTap)

    async def volume_down(self) -> None:
        """Press key volume down."""
        await _send_hid_key(self.protocol, "volume_down", InputAction.SingleTap)

    async def home(self, action: InputAction = InputAction.SingleTap) -> None:
        """Press key home."""
        await _send_hid_key(self.protocol, "home", action)

    async def home_hold(self) -> None:
        """Hold key home."""
        await _send_hid_key(self.protocol, "home", InputAction.Hold)

    async def top_menu(self) -> None:
        """Go to main menu (long press menu)."""
        await _send_hid_key(self.protocol, "topmenu", InputAction.SingleTap)

    async def suspend(self) -> None:
        """Suspend the device."""
        await _send_hid_key(self.protocol, "suspend", InputAction.SingleTap)

    async def wakeup(self) -> None:
        """Wake up the device."""
        await _send_hid_key(self.protocol, "wakeup", InputAction.SingleTap)

    async def skip_forward(self) -> None:
        """Skip forward a time interval.

        Skip interval is typically 15-30s, but is decided by the app.
        """
        await self._skip_command(CommandInfo_pb2.SkipForward)

    async def skip_backward(self) -> None:
        """Skip backwards a time interval.

        Skip interval is typically 15-30s, but is decided by the app.
        """
        await self._skip_command(CommandInfo_pb2.SkipBackward)

    async def _skip_command(self, command) -> None:
        info = self.psm.playing.command_info(command)

        # Pick the first preferred interval for simplicity
        if info and info.preferredIntervals:
            skip_interval = info.preferredIntervals[0]
        else:
            skip_interval = 15  # Default value

        await self._send_command(command, skipInterval=skip_interval)

    async def set_position(self, pos: int) -> None:
        """Seek in the current playing media."""
        await self.protocol.send_and_receive(messages.seek_to_position(pos))

    async def set_shuffle(self, shuffle_state: ShuffleState) -> None:
        """Change shuffle mode to on or off."""
        await self.protocol.send_and_receive(messages.shuffle(shuffle_state))

    async def set_repeat(self, repeat_state: RepeatState) -> None:
        """Change repeat state."""
        await self.protocol.send_and_receive(messages.repeat(repeat_state))

class MrpMetadata(Metadata):
    """Implementation of API for retrieving metadata."""

    def __init__(self, protocol, psm, identifier):
        """Initialize a new MrpPlaying."""
        self.protocol = protocol
        self.psm = psm
        self.identifier = identifier
        self.artwork_cache = Cache(limit=4)

    @property
    def device_id(self) -> Optional[str]:
        """Return a unique identifier for current device."""
        return self.identifier

    async def artwork(
        self, width: Optional[int] = 512, height: Optional[int] = None
    ) -> Optional[ArtworkInfo]:
        """Return artwork for what is currently playing (or None).

        The parameters "width" and "height" makes it possible to request artwork of a
        specific size. This is just a request, the device might impose restrictions and
        return artwork of a different size. Set both parameters to None to request
        default size. Set one of them and let the other one be None to keep original
        aspect ratio.
        """
        identifier = self.artwork_id
        if not identifier:
            _LOGGER.debug("No artwork available")
            return None

        if identifier in self.artwork_cache:
            _LOGGER.debug("Retrieved artwork %s from cache", identifier)
            return self.artwork_cache.get(identifier)

        artwork: Optional[ArtworkInfo] = None
        try:
            artwork = await self._fetch_artwork(width or 0, height or -1)
        except Exception:
            _LOGGER.warning("Artwork not present in response")
        else:
            self.artwork_cache.put(identifier, artwork)

        return artwork

    async def _fetch_artwork(self, width, height) -> Optional[ArtworkInfo]:
        playing = self.psm.playing
        resp = await self.psm.protocol.send_and_receive(
            messages.playback_queue_request(playing.location, width, height)
        )
        if not resp.HasField("type"):
            return None

        item = resp.inner().playbackQueue.contentItems[playing.location]
        return ArtworkInfo(
            bytes=item.artworkData,
            mimetype=playing.metadata.artworkMIMEType,
            width=item.artworkDataWidth,
            height=item.artworkDataHeight,
        )

    @property
    def artwork_id(self):
        """Return a unique identifier for current artwork."""
        metadata = self.psm.playing.metadata
        if metadata and metadata.artworkAvailable:
            if metadata.HasField("artworkIdentifier"):
                return metadata.artworkIdentifier
            if metadata.HasField("contentIdentifier"):
                return metadata.contentIdentifier
            return self.psm.playing.item_identifier
        return None

    async def playing(self) -> Playing:
        """Return what is currently playing."""
        return build_playing_instance(self.psm.playing)

    @property
    def app(self) -> Optional[App]:
        """Return information about running app."""
        client = self.psm.client
        if client:
            return App(client.display_name, client.bundle_identifier)
        return None

class MrpPower(Power):
    """Implementation of API for retrieving a power state from an Apple TV."""

    def __init__(
        self,
        loop: asyncio.AbstractEventLoop,
        protocol: MrpProtocol,
        remote: MrpRemoteControl,
    ) -> None:
        """Initialize a new MrpPower instance."""
        super().__init__()
        self.loop = loop
        self.protocol = protocol
        self.remote = remote
        self.device_info = None
        self._waiters: Dict[PowerState, asyncio.Event] = {}

        self.protocol.listen_to(protobuf.DEVICE_INFO_MESSAGE, self._update_power_state)
        self.protocol.listen_to(
            protobuf.DEVICE_INFO_UPDATE_MESSAGE, self._update_power_state
        )

    def _get_current_power_state(self) -> PowerState:
        latest_device_info = self.device_info or self.protocol.device_info
        return self._get_power_state(latest_device_info)

    @property
    def power_state(self) -> PowerState:
        """Return device power state."""
        currect_power_state = self._get_current_power_state()
        return currect_power_state

    async def turn_on(self, await_new_state: bool = False) -> None:
        """Turn device on."""
        await self.protocol.send(messages.wake_device())

        if await_new_state and self.power_state != PowerState.On:
            await self._waiters.setdefault(PowerState.On, asyncio.Event()).wait()

    async def turn_off(self, await_new_state: bool = False) -> None:
        """Turn device off."""
        await self.remote.home(InputAction.Hold)
        await asyncio.sleep(DELAY_BETWEEN_COMMANDS)
        await self.remote.select()

        if await_new_state and self.power_state != PowerState.Off:
            await self._waiters.setdefault(PowerState.Off, asyncio.Event()).wait()

    async def _update_power_state(self, message):
        old_state = self.power_state
        new_state = self._get_power_state(message)
        self.device_info = message

        if new_state != old_state:
            _LOGGER.debug("Power state changed from %s to %s", old_state, new_state)
            self.loop.call_soon(self.listener.powerstate_update, old_state, new_state)

        if new_state in self._waiters:
            self._waiters[new_state].set()
            del self._waiters[new_state]

    @staticmethod
    def _get_power_state(device_info_message) -> PowerState:
        logical_device_count = device_info_message.inner().logicalDeviceCount
        if logical_device_count >= 1:
            return PowerState.On
        if logical_device_count == 0:
            return PowerState.Off
        return PowerState.Unknown

class MrpPushUpdater(AbstractPushUpdater):
    """Implementation of API for handling push update from an Apple TV."""

    def __init__(
        self,
        metadata: MrpMetadata,
        psm: PlayerStateManager,
        state_dispatcher: ProtocolStateDispatcher,
    ) -> None:
        """Initialize a new MrpPushUpdater instance."""
        super().__init__(state_dispatcher)
        self.metadata = metadata
        self.psm = psm

    @property
    def active(self):
        """Return if push updater has been started."""
        return self.psm.listener == self

    def start(self, initial_delay=0):
        """Wait for push updates from device.

        Will throw NoAsyncListenerError if no listener has been set.
        """
        if self.listener is None:
            raise exceptions.NoAsyncListenerError()
        if self.active:
            return

        self.psm.listener = self
        asyncio.ensure_future(self.state_updated())

    def stop(self):
        """No longer forward updates to listener."""
        self.psm.listener = None

    async def state_updated(self):
        """State was updated for active player."""
        try:
            playstatus = await self.metadata.playing()
            self.post_update(playstatus)
        except asyncio.CancelledError:
            pass
        except Exception as ex:  # pylint: disable=broad-except
            _LOGGER.debug("Playstatus error occurred: %s", ex)
            self.loop.call_soon(self.listener.playstatus_error, self, ex)

class MrpAudio(Audio):
    """Implementation of audio functionality."""

    def __init__(
        self, protocol: MrpProtocol, state_dispatcher: ProtocolStateDispatcher
    ):
        """Initialize a new MrpAudio instance."""
        self.protocol: MrpProtocol = protocol
        self.state_dispatcher = state_dispatcher
        self._volume_controls_available: bool = False
        self._output_device_uid: Optional[str] = None
        self._volume: float = 0.0
        self._volume_event: asyncio.Event = asyncio.Event()
        self._add_listeners()

    @property
    def device_uid(self) -> Optional[str]:
        """Return device UID for current active output device."""
        if self._output_device_uid is not None:
            return self._output_device_uid
        if self.protocol.device_info is not None:
            return self.protocol.device_info.inner().deviceUID  # type: ignore
        return None

    @property
    def is_available(self):
        """Return if audio controls are available."""
        return self._volume_controls_available and self.device_uid is not None

    def _add_listeners(self):
        self.protocol.listen_to(
            protobuf.VOLUME_CONTROL_AVAILABILITY_MESSAGE,
            self._volume_control_availability,
        )
        self.protocol.listen_to(
            protobuf.VOLUME_CONTROL_CAPABILITIES_DID_CHANGE_MESSAGE,
            self._volume_control_changed,
        )
        self.protocol.listen_to(
            protobuf.VOLUME_DID_CHANGE_MESSAGE, self._volume_did_change
        )

    async def _volume_control_availability(self, message) -> None:
        self._update_volume_controls(message.inner())

    async def _volume_control_changed(self, message) -> None:
        inner = message.inner()

        self._output_device_uid = inner.outputDeviceUID
        self._update_volume_controls(inner.capabilities)

    def _update_volume_controls(
        self, availabilty_message: protobuf.VolumeControlAvailabilityMessage
    ) -> None:
        self._volume_controls_available = availabilty_message.volumeControlAvailable
        _LOGGER.debug(
            "Volume control availability changed to %s", self._volume_controls_available
        )

    async def _volume_did_change(self, message) -> None:
        inner = message.inner()

        # Make sure update is for our device (in case it changed for someone else)
        if inner.outputDeviceUID == self._output_device_uid:
            self._volume = round(inner.volume * 100.0, 1)
            _LOGGER.debug("Volume changed to %0.1f", self.volume)

            self.state_dispatcher.dispatch(UpdatedState.Volume, self._volume)

            # There are no responses to the volume_up/down commands sent to the device.
            # So when calling volume_up/down here, they will wait for the volume to
            # change to know when done. Here, a single asyncio.Event is used which
            # works as long as no more than one task is calling either function at the
            # same time. If two or more call those functions, all of them will return
            # at once (when first volume update occurs) instead of one by one. This is
            # generally fine, but can be improved if there's a need for it.
            self._volume_event.set()
            self._volume_event.clear()

    @property
    def volume(self) -> float:
        """Return current volume level."""
        return self._volume

    async def set_volume(self, level: float) -> None:
        """Change current volume level."""
        if self.device_uid is None:
            raise exceptions.ProtocolError("no output device")

        await self.protocol.send(messages.set_volume(self.device_uid, level / 100.0))

        if self._volume != level:
            await asyncio.wait_for(self._volume_event.wait(), timeout=5.0)

    async def volume_up(self) -> None:
        """Increase volume by one step."""
        if self._volume < 100.0:
            await _send_hid_key(
                self.protocol, "volume_up", InputAction.SingleTap, flush=False
            )
            await asyncio.wait_for(self._volume_event.wait(), timeout=5.0)

    async def volume_down(self) -> None:
        """Decrease volume by one step."""
        if self._volume > 0.0:
            await _send_hid_key(
                self.protocol, "volume_down", InputAction.SingleTap, flush=False
            )
            await asyncio.wait_for(self._volume_event.wait(), timeout=5.0)

class MrpFeatures(Features):
    """Implementation of API for supported feature functionality."""

    def __init__(self, config: BaseConfig, psm: PlayerStateManager, audio: MrpAudio):
        """Initialize a new MrpFeatures instance."""
        self.config = config
        self.psm = psm
        self.audio = audio

    def get_feature(  # pylint: disable=too-many-return-statements,too-many-branches
        self, feature_name: FeatureName
    ) -> FeatureInfo:
        """Return current state of a feature."""
        if feature_name in _FEATURES_SUPPORTED:
            return FeatureInfo(state=FeatureState.Available)
        if feature_name == FeatureName.Artwork:
            metadata = self.psm.playing.metadata
            if metadata and metadata.artworkAvailable:
                return FeatureInfo(state=FeatureState.Available)
            return FeatureInfo(state=FeatureState.Unavailable)

        field_name = _FIELD_FEATURES.get(feature_name)
        if field_name:
            available = self.psm.playing.metadata_field(field_name) is not None
            return FeatureInfo(
                state=FeatureState.Available if available else FeatureState.Unavailable
            )

        # Special case for PlayPause emulation. Based on the behavior in the Youtube
        # app, only the "opposite" feature to current state is available. E.g. if
        # something is playing, then pause will be available but not play. So take that
        # into consideration here.
        if feature_name == FeatureName.PlayPause:
            playback_state = self.psm.playing.playback_state
            if playback_state == PlaybackState.Playing and self.in_state(
                FeatureState.Available, FeatureName.Pause
            ):
                return FeatureInfo(state=FeatureState.Available)
            if playback_state == PlaybackState.Paused and self.in_state(
                FeatureState.Available, FeatureName.Play
            ):
                return FeatureInfo(state=FeatureState.Available)

        cmd_id = _FEATURE_COMMAND_MAP.get(feature_name)
        if cmd_id:
            cmd = self.psm.playing.command_info(cmd_id)
            if cmd and cmd.enabled:
                return FeatureInfo(state=FeatureState.Available)
            return FeatureInfo(state=FeatureState.Unavailable)

        if feature_name == FeatureName.App:
            if self.psm.client:
                return FeatureInfo(state=FeatureState.Available)
            return FeatureInfo(state=FeatureState.Unavailable)

        if feature_name in [
            FeatureName.VolumeDown,
            FeatureName.VolumeUp,
            FeatureName.Volume,
            FeatureName.SetVolume,
        ]:
            if self.audio.is_available:
                return FeatureInfo(state=FeatureState.Available)
            return FeatureInfo(state=FeatureState.Unavailable)

        return FeatureInfo(state=FeatureState.Unsupported)

def mrp_service_handler(
    mdns_service: mdns.Service, response: mdns.Response
) -> Optional[ScanHandlerReturn]:
    """Parse and return a new MRP service."""
    enabled = True

    # Disable this service if tvOS version is >= 15 as it doesn't work anymore
    build = mdns_service.properties.get("SystemBuildVersion", "")
    match = re.match(r"^(\d+)[A-Z]", build)
    if match:
        base = int(match.groups()[0])
        if base >= 19:
            _LOGGER.debug("Disabling MRP service since tvOS >= 15")
            enabled = False

    name = mdns_service.properties.get("Name", "Unknown")
    service = MutableService(
        get_unique_id(mdns_service.type, mdns_service.name, mdns_service.properties),
        Protocol.MRP,
        mdns_service.port,
        properties=mdns_service.properties,
        enabled=enabled,
    )
    return name, service

def scan() -> Mapping[str, ScanHandlerDeviceInfoName]:
    """Return handlers used for scanning."""
    return {
        "_mediaremotetv._tcp.local": (
            mrp_service_handler,
            device_info_name_from_unique_short_name,
        )
    }

def device_info(service_type: str, properties: Mapping[str, Any]) -> Dict[str, Any]:
    """Return device information from zeroconf properties."""
    devinfo: Dict[str, Any] = {}
    if "systembuildversion" in properties:
        devinfo[DeviceInfo.BUILD_NUMBER] = properties["systembuildversion"]

        version = lookup_version(properties["systembuildversion"])
        if version:
            devinfo[DeviceInfo.VERSION] = version
    if "macaddress" in properties:
        devinfo[DeviceInfo.MAC] = properties["macaddress"]

    # MRP has only been seen on Apple TV and HomePod, which both run tvOS,
    # so an educated guess is made here. It is border line OK, but will
    # do for now.
    devinfo[DeviceInfo.OPERATING_SYSTEM] = OperatingSystem.TvOS

    return devinfo

async def service_info(
    service: MutableService,
    devinfo: DeviceInfo,
    services: Mapping[Protocol, BaseService],
) -> None:
    """Update service with additional information.

    Pairing has never been enforced by MRP (maybe by design), but it is
    possible to pair if AllowPairing is YES.
    """
    service.pairing = (
        PairingRequirement.Optional
        if service.properties.get("allowpairing", "no").lower() == "yes"
        else PairingRequirement.Disabled
    )

def create_with_connection(  # pylint: disable=too-many-locals
    core: Core,
    connection: AbstractMrpConnection,
    requires_heatbeat: bool = True,
) -> SetupData:
    """Set up a new MRP service from a connection."""
    protocol = MrpProtocol(connection, SRPAuthHandler(), core.service)
    psm = PlayerStateManager(protocol)

    remote_control = MrpRemoteControl(core.loop, psm, protocol)
    metadata = MrpMetadata(protocol, psm, core.config.identifier)
    power = MrpPower(core.loop, protocol, remote_control)
    push_updater = MrpPushUpdater(metadata, psm, core.state_dispatcher)
    audio = MrpAudio(protocol, core.state_dispatcher)

    interfaces = {
        RemoteControl: remote_control,
        Metadata: metadata,
        Power: power,
        PushUpdater: push_updater,
        Features: MrpFeatures(core.config, psm, audio),
        Audio: audio,
    }

    async def _connect() -> bool:
        await protocol.start()
        if requires_heatbeat:
            protocol.enable_heartbeat()
        return True

    def _close() -> Set[asyncio.Task]:
        push_updater.stop()
        protocol.stop()
        return set()

    def _device_info() -> Dict[str, Any]:
        devinfo = device_info(list(scan().keys())[0], core.service.properties)

        # Extract build number from DEVICE_INFO_MESSAGE from device
        if protocol.device_info:
            info = protocol.device_info.inner()  # type: ignore
            devinfo[DeviceInfo.BUILD_NUMBER] = info.systemBuildVersion
            if info.modelID:
                devinfo[DeviceInfo.RAW_MODEL] = info.modelID
                devinfo[DeviceInfo.MODEL] = lookup_model(info.modelID)

        return devinfo

    # Features managed by this protocol
    features = set(
        [
            FeatureName.Artwork,
            FeatureName.VolumeDown,
            FeatureName.VolumeUp,
            FeatureName.SetVolume,
            FeatureName.Volume,
            FeatureName.App,
        ]
    )
    features.update(_FEATURES_SUPPORTED)
    features.update(_FEATURE_COMMAND_MAP.keys())
    features.update(_FIELD_FEATURES.keys())

    return SetupData(Protocol.MRP, _connect, _close, _device_info, interfaces, features)

def setup(core: Core) -> Generator[SetupData, None, None]:
    """Set up a new MRP service."""
    yield create_with_connection(
        core,
        MrpConnection(
            core.config.address, core.service.port, core.loop, atv=core.device_listener
        ),
    )

def pair(
    config: BaseConfig,
    service: BaseService,
    session_manager: ClientSessionManager,
    loop: asyncio.AbstractEventLoop,
    **kwargs
) -> PairingHandler:
    """Return pairing handler for protocol."""
    return MrpPairingHandler(config, service, session_manager, loop, **kwargs)


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::Data::Bio::RegulatoryFactor;

### NAME: EnsEMBL::Web::Data::Bio::RegulatoryFactor
### Base class - wrapper around a Bio::EnsEMBL::ExternalFeature API object

### STATUS: Under Development

### DESCRIPTION:
### This module provides additional data-handling
### capabilities on top of those provided by the API

use strict;
use warnings;
no warnings qw(uninitialized);

use base qw(EnsEMBL::Web::Data::Bio);

sub convert_to_drawing_parameters {
### Converts a set of API objects into simple parameters
### for use by drawing code and HTML components
  my $self = shift; warn $self;
  my $data = $self->data_objects;
  my $results = [];

  foreach my $reg (@$data) {
    my @stable_ids;
    my $gene_links;
    my $db_ent = $reg->get_all_DBEntries;
    foreach ( @{ $db_ent} ) {
      push @stable_ids, $_->primary_id;
      my $url = $self->hub->url({'type' => 'Gene', 'action' => 'Summary', 'g' => $stable_ids[-1] });
      $gene_links  .= qq($stable_ids[-1]);
    }

    my @extra_results = $reg->analysis->description;
    ## Sort out any links/URLs
    if ($extra_results[0] =~ /a href/i) {
      $extra_results[0] =~ s/a href/a rel="external" href/ig;
    }
    else {
      $extra_results[0] =~ s/(https?:\/\/\S+[\w\/])/$1<\/a>/ig;
    }

    push @$results, {
      'region'   => $reg->seq_region_name,
      'start'    => $reg->start,
      'end'      => $reg->end,
      'strand'   => $reg->strand,
      'length'   => $reg->end-$reg->start+1,
      'label'    => $reg->display_label,
      'gene_id'  => \@stable_ids,
      'extra'    => {
                    'gene'      => $gene_links,
                    'analysis'  => \@extra_results,
      },
    }
  }
  my $extra_columns = [
                    {'key' => 'gene',     'title' => 'Associated gene'},
                    {'key' => 'analysis', 'title' => 'Link to Tarbase', 'sort' => 'html'},
  ];
  return [$results, $extra_columns];
}

1;


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

<title>ResultListXMLBigDecimal</title>
<meta name="date" content="2017-03-06">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.github.jessemull.microflex.bigdecimalflex.io

Class ResultListXMLBigDecimal

java.lang.Object

com.github.jessemull.microflex.bigdecimalflex.io.ResultListXMLBigDecimal

All Implemented Interfaces:

java.lang.Iterable<ResultXMLBigDecimal>

public class ResultListXMLBigDecimal
extends java.lang.Object
implements java.lang.Iterable<ResultXMLBigDecimal>

This is a wrapper class used to marshal/unmarshal a list of XML encoded results.

Author:

Jesse L. Mull

Constructor Summary

Constructors

Constructor and Description

ResultListXMLBigDecimal()

ResultListXMLBigDecimal(java.util.Collection<java.util.Map<WellBigDecimal,java.math.BigDecimal>> collection)

Creates an XML result list from a collection of maps.

ResultListXMLBigDecimal(java.util.Collection<java.util.Map<WellBigDecimal,java.math.BigDecimal>> collection,
                       java.util.List<java.lang.String> labels)

Creates an XML result list from a collection of maps and a list of labels.

ResultListXMLBigDecimal(java.util.Map<WellBigDecimal,java.math.BigDecimal> map)

Creates an XML result list from a map.

ResultListXMLBigDecimal(java.util.Map<WellBigDecimal,java.math.BigDecimal> map,
                       java.lang.String label)

Creates an XML result list from a map and label.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

ResultXMLBigDecimal
get(int index)

Returns the result at the index as a well set.

java.util.List<ResultXMLBigDecimal>
getResults()

Gets the list of XML results.

java.util.Iterator<ResultXMLBigDecimal>
iterator()

Returns an iterator for result list.

void
setResults(java.util.List<ResultXMLBigDecimal> results)

Sets the list of XML results.

int
size()

Returns the size of the result list.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface java.lang.Iterable

forEach, spliterator

Constructor Detail

ResultListXMLBigDecimal

public ResultListXMLBigDecimal()

ResultListXMLBigDecimal

public ResultListXMLBigDecimal(java.util.Map<WellBigDecimal,java.math.BigDecimal> map)

Creates an XML result list from a map.

Parameters:

Map<WellBigDecimal, - BigDecimal>    the result map

ResultListXMLBigDecimal

public ResultListXMLBigDecimal(java.util.Map<WellBigDecimal,java.math.BigDecimal> map,
                               java.lang.String label)

Creates an XML result list from a map and label.

Parameters:

Map<WellBigDecimal, - BigDecimal>    the result map

String - the result label

ResultListXMLBigDecimal

public ResultListXMLBigDecimal(java.util.Collection<java.util.Map<WellBigDecimal,java.math.BigDecimal>> collection)

Creates an XML result list from a collection of maps.

Parameters:

Collection<Map<WellBigDecimal, - BigDecimal>>    collection of well objects

ResultListXMLBigDecimal

public ResultListXMLBigDecimal(java.util.Collection<java.util.Map<WellBigDecimal,java.math.BigDecimal>> collection,
                               java.util.List<java.lang.String> labels)

Creates an XML result list from a collection of maps and a list of labels.

Parameters:

Collection<Map<WellBigDecimal, - BigDecimal>>    collection of well objects

List<String> - the result labels

Method Detail

setResults

public void setResults(java.util.List<ResultXMLBigDecimal> results)

Sets the list of XML results.

Parameters:

List<ResultXMLBigDecimal> - the new list of results

getResults

public java.util.List<ResultXMLBigDecimal> getResults()

Gets the list of XML results.

Returns:

the list of results

get

public ResultXMLBigDecimal get(int index)

Returns the result at the index as a well set.

Parameters:

int - the index

Returns:

the converted result

size

public int size()

Returns the size of the result list.

Returns:

the result list size

iterator

public java.util.Iterator<ResultXMLBigDecimal> iterator()

Returns an iterator for result list.

Specified by:

iterator in interface java.lang.Iterable<ResultXMLBigDecimal>

Returns:

Iterator<ResultXMLBigDecimal>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "chipmunk.h"
#include "ChipmunkDemo.h"

static cpConstraint *motor;

#define numBalls 5
static cpBody *balls[numBalls];

static void
update(cpSpace *space)
{
	cpFloat coef = (2.0f + ChipmunkDemoKeyboard.y)/3.0f;
	cpFloat rate = ChipmunkDemoKeyboard.x*30.0f*coef;

	cpSimpleMotorSetRate(motor, rate);
	cpConstraintSetMaxForce(motor, rate ? 1000000.0f : 0.0f);

	int steps = 2;
	cpFloat dt = 1.0f/60.0f/(cpFloat)steps;

	for(int i=0; i<steps; i++){
		cpSpaceStep(space, dt);

		for(int i=0; i<numBalls; i++){
			cpBody *ball = balls[i];
			cpVect pos = cpBodyGetPos(ball);

			if(pos.x > 320.0f){
				cpBodySetVel(ball, cpvzero);
				cpBodySetPos(ball, cpv(-224.0f, 200.0f));
			}
		}
	}
}

static cpBody *
add_ball(cpSpace *space, cpVect pos)
{
	cpBody *body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero)));
	cpBodySetPos(body, pos);

	cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);

	return body;
}

static cpSpace *
init(void)
{
	ChipmunkDemoMessageString = "Use the arrow keys to control the machine.";

	cpSpace *space = cpSpaceNew();
	cpSpaceSetGravity(space, cpv(0, -600));

	cpBody *staticBody = cpSpaceGetStaticBody(space);
	cpShape *shape;

	// beveling all of the line segments slightly helps prevent things from getting stuck on cracks
	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-256,300), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-192,0), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,0), cpv(-192, -64), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,-64), cpv(-128,144), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,80), cpv(-192,176), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-192,176), cpv(-128,240), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, cpv(-128,144), cpv(192,64), 2.0f));
	cpShapeSetElasticity(shape, 0.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, NOT_GRABABLE_MASK);

	cpVect verts[] = {
		cpv(-30,-80),
		cpv(-30, 80),
		cpv( 30, 64),
		cpv( 30,-80),
	};

	cpBody *plunger = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY));
	cpBodySetPos(plunger, cpv(-160,-80));

	shape = cpSpaceAddShape(space, cpPolyShapeNew(plunger, 4, verts, cpvzero));
	cpShapeSetElasticity(shape, 1.0f);
	cpShapeSetFriction(shape, 0.5f);
	cpShapeSetLayers(shape, 1);

	// add balls to hopper
	for(int i=0; i<numBalls; i++)
		balls[i] = add_ball(space, cpv(-224 + i,80 + 64*i));

	// add small gear
	cpBody *smallGear = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 80, 0, cpvzero)));
	cpBodySetPos(smallGear, cpv(-160,-160));
	cpBodySetAngle(smallGear, -M_PI_2);

	shape = cpSpaceAddShape(space, cpCircleShapeNew(smallGear, 80.0f, cpvzero));
	cpShapeSetLayers(shape, 0);

	cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, smallGear, cpv(-160,-160), cpvzero));

	// add big gear
	cpBody *bigGear = cpSpaceAddBody(space, cpBodyNew(40.0f, cpMomentForCircle(40.0f, 160, 0, cpvzero)));
	cpBodySetPos(bigGear, cpv(80,-160));
	cpBodySetAngle(bigGear, M_PI_2);

	shape = cpSpaceAddShape(space, cpCircleShapeNew(bigGear, 160.0f, cpvzero));
	cpShapeSetLayers(shape, 0);

	cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, bigGear, cpv(80,-160), cpvzero));

	// connect the plunger to the small gear.
	cpSpaceAddConstraint(space, cpPinJointNew(smallGear, plunger, cpv(80,0), cpv(0,0)));
	// connect the gears.
	cpSpaceAddConstraint(space, cpGearJointNew(smallGear, bigGear, -M_PI_2, -2.0f));

	// feeder mechanism
	cpFloat bottom = -300.0f;
	cpFloat top = 32.0f;
	cpBody *feeder = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForSegment(1.0f, cpv(-224.0f, bottom), cpv(-224.0f, top))));
	cpBodySetPos(feeder, cpv(-224, (bottom + top)/2.0f));

	cpFloat len = top - bottom;
	cpSpaceAddShape(space, cpSegmentShapeNew(feeder, cpv(0.0f, len/2.0f), cpv(0.0f, -len/2.0f), 20.0f));

	cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, feeder, cpv(-224.0f, bottom), cpv(0.0f, -len/2.0f)));
	cpVect anchr = cpBodyWorld2Local(feeder, cpv(-224.0f, -160.0f));
	cpSpaceAddConstraint(space, cpPinJointNew(feeder, smallGear, anchr, cpv(0.0f, 80.0f)));

	// motorize the second gear
	motor = cpSpaceAddConstraint(space, cpSimpleMotorNew(staticBody, bigGear, 3.0f));

	return space;
}

static void
destroy(cpSpace *space)
{
	ChipmunkDemoFreeSpaceChildren(space);
	cpSpaceFree(space);
}

ChipmunkDemo Pump = {
	"Pump",
	init,
	update,
	ChipmunkDemoDefaultDrawImpl,
	destroy,
};


text:
package main

import (
	"encoding/json"
	"fmt"
	"path"

	"os"

	"path/filepath"

	"github.com/pkg/errors"
	raseagate "github.com/scritch007/go-ra-seagate"
)

// SyncPlugin interface
type SeagatePlugin struct {
	Login      string
	Password   string
	Path       string
	DeviceID   string
	connection *raseagate.Connection
}

func init() {
	registerPlugin(syncPluginRegistration{
		Name:      "seagate",
		NewMethod: newSeagateSyncPlugin,
	})
}

func newSeagateSyncPlugin(config string) (SyncPlugin, error) {
	var c *raseagate.Client
	var err error
	s := SeagatePlugin{}
	if len(config) == 0 {

		fmt.Println("Enter login")
		_, _ = fmt.Scanln(&s.Login)
		fmt.Println("Enter password")
		_, _ = fmt.Scanln(&s.Password)
		c, err = raseagate.NewClient(s.Login, s.Password)
		if err != nil {
			return nil, err
		}
		dList, err := c.GetDeviceList()
		if err != nil {
			return nil, err
		}
		count := 0
		for _, d := range dList {
			if d.IsAvailable() {
				fmt.Println(d.FriendlyName)
				count++
			}
		}
		if count == 0 {
			return nil, fmt.Errorf("No device available")
		}
		fmt.Println("Select device")
		var fName string
		_, _ = fmt.Scanln(&fName)
		for _, d := range dList {
			if d.FriendlyName == fName {
				s.DeviceID = d.DeviceID
				break
			}
		}
		fmt.Println("Enter path on device")
		_, _ = fmt.Scanln(&s.Path)

	} else {
		err := json.Unmarshal([]byte(config), &s)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to read config")
		}
		fmt.Printf("=>%s %s\n", s.Login, s.Password)
		c, err = raseagate.NewClient(s.Login, s.Password)
		if err != nil {
			return nil, errors.Wrap(err, "Failed to instantiate new client")
		}
	}
	if len(s.DeviceID) == 0 {
		return nil, fmt.Errorf("Unknown deviceID")
	}

	fmt.Printf("=>%v", s)
	fmt.Println("Connecting to server")
	dList, err := c.GetDeviceList()
	if err != nil {
		return nil, errors.Wrap(err, "Failed to list devices")
	}
	for _, d := range dList {
		if d.DeviceID == s.DeviceID {
			if !d.IsAvailable() {
				return nil, fmt.Errorf("Device not available")
			}
			s.connection, err = c.Connect(&d)
			if err != nil {
				return nil, errors.Wrap(err, "Failed to connect to device")
			}
			break
		}
	}
	return &s, nil
}

// Name should return the name if the plugin, this is for debug purpose only
func (s *SeagatePlugin) Name() string {
	return "seagate"
}

// BrowseFolder should only return the list of files, and not subfolders
func (s *SeagatePlugin) BrowseFolder(folder string) ([]SyncResourceInfo, error) {
	files, err := s.connection.Browse(path.Join(s.Path, folder))
	if err != nil {
		return nil, err
	}

	var res []SyncResourceInfo
	for _, f := range files {
		res = append(res, SyncResourceInfo{
			Path:   path.Join(folder, f.Name),
			Name:   f.Name,
			IsDir:  f.IsDir,
			Parent: folder,
		})
	}
	return res, nil
}

// RemoveResource is not used Yet
func (s *SeagatePlugin) RemoveResource(r SyncResourceInfo) error {
	return fmt.Errorf("Not implemented")
}

// AddResource create a new Folder or a new File
func (s *SeagatePlugin) AddResource(r *SyncResourceInfo) error {
	if r.IsDir {
		return s.connection.CreateFolder(path.Join(s.Path, r.Parent, r.Name))
	}
	f, err := os.Open(r.Path)
	if err != nil {
		return err
	}
	defer f.Close()

	err = s.connection.UploadFile(path.Join(s.Path, r.Parent, r.Name), f)
	return err
}

// HasFolder check if folder already exists
func (s *SeagatePlugin) HasFolder(folder string) bool {
	has, _ := s.connection.HasFile(path.Join(s.Path, folder))
	return has
}

// DownloadResource will download the resource
func (s *SeagatePlugin) DownloadResource(r *SyncResourceInfo) error {
	f, err := os.Create(r.Path)
	if err != nil {
		return errors.Wrap(err, "Failed to create file")
	}
	return s.connection.DownloadFile(path.Join(s.Path, r.Parent, r.Name), f)
}

// GetResourceInfo return information about the resource
func (s *SeagatePlugin) GetResourceInfo(folder string) (SyncResourceInfo, error) {
	var name, parent string
	if folder == "/" {
		name = "/"
		parent = "/"
	} else {
		name = filepath.Base(folder)
		parent = filepath.Dir(folder)
	}
	return SyncResourceInfo{Name: name, Parent: parent, Path: folder, IsDir: true}, nil
}

func (s *SeagatePlugin) SyncOnlyMedia() bool {
	return false
}


text:
import asyncio
from collections import namedtuple
import contextlib
import os
import subprocess
import tempfile

import yaml

from .async_helpers import create_subprocess_with_handle
from . import cache
from . import compat
from .compat import makedirs
from .error import PrintableError

DEFAULT_PARALLEL_FETCH_LIMIT = 10

DEBUG_PARALLEL_COUNT = 0
DEBUG_PARALLEL_MAX = 0

PluginDefinition = namedtuple(
    'PluginDefinition',
    ['type', 'sync_exe', 'reup_exe', 'fields', 'required_fields',
     'optional_fields', 'cache_fields'])

PluginContext = namedtuple(
    'PluginContext',
    ['cwd', 'plugin_cache_root', 'parallelism_semaphore', 'plugin_cache_locks',
     'tmp_root'])

@asyncio.coroutine
def plugin_fetch(plugin_context, module_type, module_fields, dest,
                 display_handle):
    env = {'PERU_SYNC_DEST': dest}
    yield from _plugin_job(plugin_context, module_type, module_fields, 'sync',
                           env, display_handle)

@asyncio.coroutine
def plugin_get_reup_fields(plugin_context, module_type, module_fields,
                           display_handle):
    with tmp_dir(plugin_context) as output_file_dir:
        output_path = os.path.join(output_file_dir, 'reup_output')
        env = {'PERU_REUP_OUTPUT': output_path}
        yield from _plugin_job(
            plugin_context, module_type, module_fields, 'reup', env,
            display_handle)
        with open(output_path) as output_file:
            fields = yaml.safe_load(output_file) or {}

    for key, value in fields.items():
        if not isinstance(key, str):
            raise PluginModuleFieldError(
                'reup field name must be a string: {}'.format(key))
        if not isinstance(value, str):
            raise PluginModuleFieldError(
                'reup field value must be a string: {}'.format(value))

    return fields

@asyncio.coroutine
def _plugin_job(plugin_context, module_type, module_fields, command, env,
                display_handle):
    # We take several locks and other context managers in here. Using an
    # ExitStack saves us from indentation hell.
    with contextlib.ExitStack() as stack:
        definition = _get_plugin_definition(module_type, module_fields,
                                            command)
        exe = _get_plugin_exe(definition, command)

        # For Windows to run scripts with the right interpreter, we need to run
        # as a shell command, rather than exec.
        shell_command_line = subprocess.list2cmdline([exe])

        complete_env = _plugin_env(
            plugin_context, definition, module_fields, command, stack)
        complete_env.update(env)

        # Use a lock to protect the plugin cache. It would be unsafe for two
        # jobs to read/write to the same plugin cache dir at the same time. The
        # lock (and the cache dir) are both keyed off the module's "cache
        # fields" as defined by plugin.yaml. For plugins that don't define
        # cacheable fields, there is no cache dir (it's set to /dev/null) and
        # the cache lock is a no-op.
        stack.enter_context((yield from _plugin_cache_lock(
            plugin_context, definition, module_fields)))

        # Use a semaphore to limit the number of jobs that can run in parallel.
        # Most plugin fetches hit the network, and for performance reasons we
        # don't want to fire off too many network requests at once. See
        # DEFAULT_PARALLEL_FETCH_LIMIT. This also lets the user control
        # parallelism with the --jobs flag. It's important that this is the
        # last lock taken before starting a job, otherwise we might waste a job
        # slot just waiting on other locks.
        stack.enter_context((yield from plugin_context.parallelism_semaphore))

        # We use this debug counter for our parallelism tests. It's important
        # that it comes after all locks have been taken (so the job it's
        # counting is actually running).
        stack.enter_context(debug_parallel_count_context())

        try:
            yield from create_subprocess_with_handle(
                shell_command_line, display_handle, cwd=plugin_context.cwd,
                env=complete_env, shell=True)
        except subprocess.CalledProcessError as e:
            raise PluginRuntimeError(
                module_type, module_fields, e.returncode, e.output)

def _get_plugin_exe(definition, command):
    if command == 'sync':
        exe = definition.sync_exe
    elif command == 'reup':
        exe = definition.reup_exe
    else:
        raise RuntimeError('Unrecognized command name: ' + repr(command))

    if not exe:
        raise PluginPermissionsError(
            "Module type '{0}' does not support {1}.",
            definition.type,
            command)
    if not os.path.exists(exe):
        raise PluginPermissionsError('Plugin exe is missing: ' + exe)
    if not os.access(exe, os.X_OK):
        raise PluginPermissionsError('Plugin exe is not executable: ' + exe)
    return exe

def _format_module_fields(module_fields):
    return {'PERU_MODULE_{}'.format(name.upper()): value for
            name, value in module_fields.items()}

def _validate_plugin_definition(definition, module_fields):
    field_names_not_strings = [name for name in definition.fields
                               if not isinstance(name, str)]
    if field_names_not_strings:
        raise PluginModuleFieldError(
            'Metadata field names must be strings: ' +
            ', '.join(repr(name) for name in field_names_not_strings))

    missing_module_fields = definition.required_fields - module_fields.keys()
    if missing_module_fields:
        raise PluginModuleFieldError(
            'Required module field missing: ' +
            ', '.join(missing_module_fields))

    unknown_module_fields = module_fields.keys() - definition.fields
    if unknown_module_fields:
        raise PluginModuleFieldError(
            'Unknown module fields: ' + ', '.join(unknown_module_fields))

def _plugin_env(plugin_context, plugin_definition, module_fields, command,
                exit_stack):
    env = os.environ.copy()

    # First, blank out all module field vars.  This prevents the calling
    # environment from leaking in when optional fields are undefined.
    blank_module_vars = {field: '' for field in plugin_definition.fields}
    env.update(_format_module_fields(blank_module_vars))
    # Then add in the fields that are actually defined.
    env.update(_format_module_fields(module_fields))

    # Disable buffering by default in Python subprocesses. Without this,
    # plugins would usually need to do something like
    #     print(..., flush=True)
    # or else all their progress output would get held up in the stdout buffer
    # until the plugin finally exited. Plugins in other languages will need to
    # be careful about this.
    env['PYTHONUNBUFFERED'] = 'true'

    # For plugins that use the same exe for sync and reup, make the command
    # name available in the environment.
    env['PERU_PLUGIN_COMMAND'] = command

    # Create a directory for plugins' temporary files.
    env['PERU_PLUGIN_TMP'] = exit_stack.enter_context(tmp_dir(plugin_context))

    # Create a persistent cache dir for saved files, like repo clones.
    env['PERU_PLUGIN_CACHE'] = _plugin_cache_path(
        plugin_context, plugin_definition, module_fields)

    return env

@asyncio.coroutine
def _noop_lock():
    return contextlib.ExitStack()  # a no-op context manager

def _plugin_cache_lock(plugin_context, definition, module_fields):
    if not definition.cache_fields:
        # This plugin is not cacheable.
        return _noop_lock()
    key = _plugin_cache_key(definition, module_fields)
    return plugin_context.plugin_cache_locks[key]

def _plugin_cache_path(plugin_context, definition, module_fields):
    if not definition.cache_fields:
        # This plugin is not cacheable.
        return os.devnull
    key = _plugin_cache_key(definition, module_fields)
    plugin_cache = os.path.join(
        plugin_context.plugin_cache_root, definition.type, key)
    makedirs(plugin_cache)
    return plugin_cache

def _plugin_cache_key(definition, module_fields):
    assert definition.cache_fields, "Can't compute key for uncacheable type."
    return cache.compute_key({
        'type': definition.type,
        'cacheable_fields': {field: module_fields.get(field, None)
                             for field in definition.cache_fields},
    })

def _get_plugin_definition(module_type, module_fields, command):
    root = _find_plugin_dir(module_type)
    metadata_path = os.path.join(root, 'plugin.yaml')
    if not os.path.isfile(metadata_path):
        raise PluginMetadataMissingError(
            'No metadata file found for plugin at path: {}'.format(root))

    # Read the metadata document.
    with open(metadata_path) as metafile:
        metadoc = yaml.safe_load(metafile) or {}
    sync_exe = os.path.join(root, metadoc.pop('sync exe'))
    reup_exe = (None if 'reup exe' not in metadoc
                else os.path.join(root, metadoc.pop('reup exe')))
    required_fields = frozenset(metadoc.pop('required fields'))
    optional_fields = frozenset(metadoc.pop('optional fields', []))
    cache_fields = frozenset(metadoc.pop('cache fields', []))
    fields = required_fields | optional_fields
    # TODO: All of these checks need to be tested.
    if metadoc:
        raise RuntimeError('Unknown metadata in {} plugin: {}'.format(
            module_type, metadoc))
    overlap = required_fields & optional_fields
    if overlap:
        raise RuntimeError('Fields in {} are both required and optional: {}'
                           .format(module_type, overlap))
    invalid = cache_fields - fields
    if invalid:
        raise RuntimeError(
            '"cache fields" must also be either required or optional: ' +
            str(invalid))

    definition = PluginDefinition(
        module_type, sync_exe, reup_exe, fields, required_fields,
        optional_fields, cache_fields)
    _validate_plugin_definition(definition, module_fields)
    return definition

def _find_plugin_dir(module_type):
    '''Find the directory containing the plugin definition for the given type.
    Do this by searching all the paths where plugins can live for a dir that
    matches the type name.'''

    for install_dir in _get_plugin_install_dirs():
        candidate = os.path.join(install_dir, module_type)
        if os.path.isdir(candidate):
            return candidate
    else:
        raise PluginCandidateError(
            'No plugin found for `{}` module in paths:\n{}'.format(
                module_type,
                '\n'.join(_get_plugin_install_dirs())))

def _get_plugin_install_dirs():
    '''Return all the places on the filesystem where we should look for plugin
    definitions. Order is significant here: user-installed plugins should be
    searched first, followed by system-installed plugins, and last of all peru
    builtins.'''
    builtins_dir = os.path.join(compat.MODULE_ROOT, 'resources', 'plugins')
    if os.name == 'nt':
        # Windows
        local_data_dir = os.path.expandvars('%LOCALAPPDATA%')
        program_files_dir = os.path.expandvars('%PROGRAMFILES%')
        return (
            os.path.join(local_data_dir, 'peru', 'plugins'),
            os.path.join(program_files_dir, 'peru', 'plugins'),
            builtins_dir,
        )
    else:
        # non-Windows
        default_config_dir = os.path.expanduser('~/.config')
        config_dir = os.environ.get('XDG_CONFIG_HOME', default_config_dir)
        return (
            os.path.join(config_dir, 'peru', 'plugins'),
            '/usr/local/lib/peru/plugins',
            '/usr/lib/peru/plugins',
            builtins_dir,
        )

def debug_assert_clean_parallel_count():
    assert DEBUG_PARALLEL_COUNT == 0, \
        "parallel count should be 0 but it's " + str(DEBUG_PARALLEL_COUNT)

@contextlib.contextmanager
def debug_parallel_count_context():
    global DEBUG_PARALLEL_COUNT, DEBUG_PARALLEL_MAX
    DEBUG_PARALLEL_COUNT += 1
    DEBUG_PARALLEL_MAX = max(DEBUG_PARALLEL_COUNT, DEBUG_PARALLEL_MAX)
    try:
        yield
    finally:
        DEBUG_PARALLEL_COUNT -= 1

def tmp_dir(context):
    return tempfile.TemporaryDirectory(dir=context.tmp_root)

class PluginCandidateError(PrintableError):
    pass

class PluginCommandCandidateError(PrintableError):
    pass

class PluginModuleFieldError(PrintableError):
    pass

class PluginMetadataMissingError(PrintableError):
    pass

class PluginPermissionsError(PrintableError):
    pass

class PluginRuntimeError(PrintableError):
    def __init__(self, type, fields, errorcode, output):
        # Don't depend on plugins using terminating newlines.
        stripped_output = output.strip('\n')
        super().__init__(stripped_output)


text:
fiddle-0022-BufferedStoreExcelExport
======

![Screenshot](screenshot.png)

### Title

Buffered Store + Grid Excel Export

### Creation Date

09-22-2015

### Description

Fiddle exploring whether a Grid exporter can be used with a buffered store.  Additionally this fiddle tests how it handles lock columns.

### Published Version Link

[sencha fiddle](https://fiddle.sencha.com/#fiddle/ua1)

### Tags

EXTJS-6, grid, panel, plugin, gridexporter, reconfigure, buffered store, column grouping, sub columns, quicktips, enablelockable, localstorageprovider, stateid

### Forked From

[fiddle-0005-LockedColumnState](../fiddle-0005-LockedColumnState)

### Forked From

[fiddle-0021-GridExcelExport](../fiddle-0021-GridExcelExport)


text:
/**
 *
 */
package com.blackducksoftware.tools.vuln_collector;

/**
 * @author akamen
 *
 */
public class VulnerabilityCollectorException extends Exception {

    public VulnerabilityCollectorException()
    {
        super();
    }

    /**
     * @param string
     * @param e
     */
    public VulnerabilityCollectorException(String msg, Exception e) {
        super(msg, e);
    }

    public VulnerabilityCollectorException(String msg)
    {
        super(msg);
    }

}


text:
define(function(require, exports, module) {
    require('vendor/zepto/zepto');
    var $ = window.Zepto;

    // Create outerHeight and outerWidth methods
    ['width', 'height'].forEach(function(dimension) {
        var offset, Dimension = dimension.replace(/./, function(m) {
            return m[0].toUpperCase()
        });
        $.fn['outer' + Dimension] = function(margin) {
            var elem = this;
            if (elem) {
                var size = elem[dimension]();
                var sides = {'width': ['left', 'right'], 'height': ['top', 'bottom']};
                sides[dimension].forEach(function(side) {
                    if (margin) size += parseInt(elem.css('margin-' + side), 10);
                });
                return size;
            } else {
                return null;
            }
        };
    });
});


text:
@interface GLDrawController ()<GLKViewDelegate> {
    GLfloat *vertexBuffer;
}

@end

@implementation GLDrawController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavBarWithTitle:@"gldemo" withLeft:[UIImage imageNamed:@"icon_back"]];
    [self glDemo];
    long a = 0;
    NSLog(@"%p", &a);
    a = 1;
    NSLog(@"%p", &a);
    a = 2;
    NSLog(@"%p", &a);
    a = 1;
    NSLog(@"%p", &a);
}

- (void)glDemo {

    GLKView *view = (GLKView *)self.view;
    view.backgroundColor = [UIColor clearColor];
    view.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
    view.delegate = self;
    [EAGLContext setCurrentContext:view.context];

    vertexBuffer = (GLfloat*)calloc(sizeof(GLfloat) * 2 * 4, 1);
    memset(vertexBuffer, 0, 2 * 4 * sizeof(GLfloat));

    vertexBuffer[0] = -1;
    vertexBuffer[1] = 0;

    vertexBuffer[2] = 0;
    vertexBuffer[3] = 0.5;

    vertexBuffer[4] = 1;
    vertexBuffer[5] = 0;

    vertexBuffer[6] = 0;
    vertexBuffer[7] = -0.5;
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    glEnable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glBlendFunc(GL_SRC_ALPHA, GL_SRC_COLOR);

    glEnableClientState(GL_VERTEX_ARRAY);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor4f(1, 0, 0, 1);

    glVertexPointer(2, GL_FLOAT, 0, vertexBuffer);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}

@end


text:
package org.mockito.internal.creation.cglib;

import org.mockito.cglib.proxy.MethodProxy;

import java.io.Serializable;
import java.lang.reflect.Field;

class CGLIBHacker {

    public void setMockitoNamingPolicy(MethodProxy methodProxy) {
        try {
            Field createInfoField = reflectOnCreateInfo(methodProxy);
            createInfoField.setAccessible(true);
            Object createInfo = createInfoField.get(methodProxy);
            Field namingPolicyField = createInfo.getClass().getDeclaredField("namingPolicy");
            namingPolicyField.setAccessible(true);
            if (namingPolicyField.get(createInfo) == null) {
                namingPolicyField.set(createInfo, MockitoNamingPolicy.INSTANCE);
            }
        } catch (Exception e) {
            throw new RuntimeException(
                            "Unable to set MockitoNamingPolicy on cglib generator which creates FastClasses", e);
        }
    }

    @SuppressWarnings("unchecked")
    private Field reflectOnCreateInfo(MethodProxy methodProxy) throws SecurityException, NoSuchFieldException {

        Class cglibMethodProxyClass = methodProxy.getClass();
        // in case methodProxy was extended by user, let's traverse the object
        // graph to find the cglib methodProxy
        // with all the fields we would like to change
        while (cglibMethodProxyClass != MethodProxy.class) {
            cglibMethodProxyClass = methodProxy.getClass().getSuperclass();
        }
        return cglibMethodProxyClass.getDeclaredField("createInfo");
    }
}


text:
FROM lekovr/consup_nodejs

ENV DOCKERFILE_VERSION  161116

# -------------------------------------------------------------------------------
# Gitbook & libs

RUN sudo apt-get install -y xvfb imagemagick  libgl1-mesa-glx libxcomposite1

# GitBook from https://www.gitbook.com/
RUN npm install gitbook-cli -g

# Calibre from https://calibre-ebook.com/
RUN wget -nv -O- https://raw.githubusercontent.com/kovidgoyal/calibre/master/setup/linux-installer.py \
  | sudo python -c "import sys; main=lambda:sys.stderr.write('Download failed\n'); exec(sys.stdin.read()); main()"

RUN gosu op gitbook fetch


text:
import {isArrayLike} from './is-array-like.js';
import {isSet} from './is-set.js';
import {isMap} from './is-map.js';
import {isIterable} from './is-iterable.js';

/**
 * Check that a predicate satisfies each elements in an array, or an
 * array-like object (such as a string, an `arguments` object, etc.).
 *
 * If the array is empty, this function will returns `true`.
 *
 * @param {array|string|object} array Array "like" object.
 * @param {function} predicate The predicate function.
 * @return {boolean} `true` if the predicate function returns `true` for each elements, `false` otherwise.
 */
function arrayEvery(array, predicate) {
  for (let i = 0, size = array.length; i < size; ++i) {
    if (!predicate.call(null, array[i], i, array)) {
      return false;
    }
  }

  return true;
}

/**
 * Check that a predicate satisfies each elements in an iterable object (an object
 * that can be iterated with the `for...of` loop such as `Set`, `Map` or objects
 * containing an `iterator` function).
 *
 * If the iterable is empty, this function will returns `true`.
 *
 * @param {object} iterable Iterable object.
 * @param {function} predicate The predicate function.
 * @return {boolean} `true` if the predicate function returns `true` for each elements, `false` otherwise.
 */
function iterableEvery(iterable, predicate) {
  let i = 0;

  for (const value of iterable) {
    if (!predicate.call(undefined, value, i, iterable)) {
      return false;
    }

    i++;
  }

  return true;
}

/**
 * Check that a predicate satisfies each elements in a `Set` or a `Map`.
 * If the map or the set is empty, this function will returns `true`.
 *
 * @param {Map|Set} mapOrSet Iterable object.
 * @param {function} predicate The predicate function.
 * @return {boolean} `true` if the predicate function returns `true` for each elements, `false` otherwise.
 */
function mapOrSetEvery(mapOrSet, predicate) {
  let hasFalse = false;

  mapOrSet.forEach(function(v, k) {
    // Be careful, `forEach` function on Safari miss the second parameter when
    // iterating over a `Set`...
    hasFalse = hasFalse || !predicate.call(undefined, v, arguments.length === 1 ? v : k, mapOrSet);
  });

  return !hasFalse;
}

/**
 * Check that a predicate satisfies each elements in an array or an iterable
 * structure.
 *
 * This function supports:
 * - Array.
 * - Array-Like objects.
 * - Map instances.
 * - Set instances.
 * - Any iterable objects.
 *
 * The predicate function will be called with three arguments:
 *  - `value` The value for the given iteration.
 *  - `key` The key of the value being iterated.
 *  - `array` The array being traversed.
 *
 * Note that the key may be different with arrays and map/set:
 * - With an array or an iterable object, the key will be the index of the value being traversed.
 * - With a map, the key will be the index value of the value being traversed.
 * - With a set, the key will be the same value being traversed (since a `Set` does not have any keys).
 *
 * See the documentation of the `forEach` functions of `Map` and `Set` structure.
 *
 * @param {Array|Map|Set} collection The collection to iterate.
 * @param {function} predicate The predicate function.
 * @return {boolean} `true` if the predicate returns a truthy value for each element
 *                   in the array, `false` otherwise.
 */
export function every(collection, predicate) {
  // First, test with an array.
  if (isArrayLike(collection)) {
    return arrayEvery(collection, predicate);
  }

  if (isSet(collection) || isMap(collection)) {
    return mapOrSetEvery(collection, predicate);
  }

  // Then, try with iterable (object with iterator function).
  if (isIterable(collection)) {
    return iterableEvery(collection, predicate);
  }

  return true;
}


text:
from __future__ import unicode_literals

from django import forms
from .models import *

class CompoundAdminForm(forms.ModelForm):
    """Form for Compound Admin"""
    class Meta:
        model = Compound
        exclude = []
        widgets = {
            'smiles': forms.Textarea(attrs={'cols': 31, 'rows': 3}),
            'canonical_method_of_action': forms.Textarea(
                attrs={'cols': 31, 'rows': 6}
            ),
            'drug_target': forms.Textarea(attrs={'cols': 31, 'rows': 4}),
        }

    def clean_drugbank_id(self):
        return self.cleaned_data['drugbank_id'] or None

    def clean_pubchem_id(self):
        return self.cleaned_data['pubchem_id'] or None

    def clean_upddi_id(self):
        return self.cleaned_data['upddi_id'] or None

class CompoundBatchAdminForm(forms.ModelForm):
    """Form for Compound Batch Admin"""
    class Meta:
        model = CompoundBatch
        exclude = []


text:
import random
import time

def system_under_testing(data):
    if data < 900:
        # Flaky bug here
        return "error"
    return data * 2

def test():
    # Send test data
    data = random.randint(1, 10000)
    output = system_under_testing(data)

    # Check that output is integer
    try:
        int(output)
    except:
        raise Exception("Data is not integer") from output

    # If we know logic of answer we can use that
    # now output should be 2 times input
    assert output == (2 * data)

if __name__ == '__main__':
    # Loop test to see how easily test can find a bug
    index = 0
    while True:
        index += 1
        print(f"Test {index}")
        time.sleep(0.1)
        test()


text:
<?php

namespace TreeHouse\IoBundle\Scrape\Event;

use Psr\Http\Message\ResponseInterface;
use TreeHouse\IoBundle\Entity\Scraper;

class ScrapeResponseEvent extends ScrapeUrlEvent
{
    /**
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @param Scraper           $scraper
     * @param string            $url
     * @param ResponseInterface $response
     */
    public function __construct(Scraper $scraper, $url, ResponseInterface $response)
    {
        parent::__construct($scraper, $url);

        $this->response = $response;
    }

    /**
     * @return ResponseInterface
     */
    public function getResponse()
    {
        return $this->response;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<project name="maven-antrun-" default="main"  >
<target name="main">
  <property location="/home/agung/Desktop/hbase-0.94.1/target/hbase-webapps" name="build.webapps"/>
  <property location="/home/agung/Desktop/hbase-0.94.1/src/main/resources/hbase-webapps" name="src.webapps"/>
  <property location="/home/agung/Desktop/hbase-0.94.1/target/generated-sources" name="generated.sources"/>
  <mkdir dir="${build.webapps}"/>
  <copy todir="${build.webapps}">
    <fileset dir="${src.webapps}">
      <exclude name="**/*.jsp"/>
      <exclude name="**/.*"/>
      <exclude name="**/*~"/>
    </fileset>
  </copy>
  <taskdef classname="org.apache.jasper.JspC" name="jspcompiler" classpathref="maven.compile.classpath"/>
  <mkdir dir="${build.webapps}/master/WEB-INF"/>
  <jspcompiler uriroot="${src.webapps}/master" package="org.apache.hadoop.hbase.generated.master" webxml="${build.webapps}/master/WEB-INF/web.xml" outputdir="${generated.sources}/java"/>
  <mkdir dir="${build.webapps}/regionserver/WEB-INF"/>
  <jspcompiler uriroot="${src.webapps}/regionserver" package="org.apache.hadoop.hbase.generated.regionserver" webxml="${build.webapps}/regionserver/WEB-INF/web.xml" outputdir="${generated.sources}/java"/>
  <exec executable="sh">
    <arg line="/home/agung/Desktop/hbase-0.94.1/src/saveVersion.sh 0.94.1 ${generated.sources}/java"/>
  </exec>
</target>
</project>


text:
<refentry id="vidioc-subdev-enum-mbus-code">
  <refmeta>
    <refentrytitle>ioctl VIDIOC_SUBDEV_ENUM_MBUS_CODE</refentrytitle>
    &manvol;
  </refmeta>

  <refnamediv>
    <refname>VIDIOC_SUBDEV_ENUM_MBUS_CODE</refname>
    <refpurpose>Enumerate media bus formats</refpurpose>
  </refnamediv>

  <refsynopsisdiv>
    <funcsynopsis>
      <funcprototype>
	<funcdef>int <function>ioctl</function></funcdef>
	<paramdef>int <parameter>fd</parameter></paramdef>
	<paramdef>int <parameter>request</parameter></paramdef>
	<paramdef>struct v4l2_subdev_mbus_code_enum *
	<parameter>argp</parameter></paramdef>
      </funcprototype>
    </funcsynopsis>
  </refsynopsisdiv>

  <refsect1>
    <title>Arguments</title>

    <variablelist>
      <varlistentry>
	<term><parameter>fd</parameter></term>
	<listitem>
	  <para>&fd;</para>
	</listitem>
      </varlistentry>
      <varlistentry>
	<term><parameter>request</parameter></term>
	<listitem>
	  <para>VIDIOC_SUBDEV_ENUM_MBUS_CODE</para>
	</listitem>
      </varlistentry>
      <varlistentry>
	<term><parameter>argp</parameter></term>
	<listitem>
	  <para></para>
	</listitem>
      </varlistentry>
    </variablelist>
  </refsect1>

  <refsect1>
    <title>Description</title>

    <note>
      <title>Experimental</title>
      <para>This is an <link linkend="experimental">experimental</link>
      interface and may change in the future.</para>
    </note>

    <para>To enumerate media bus formats available at a given sub-device pad
    applications initialize the <structfield>pad</structfield> and
    <structfield>index</structfield> fields of &v4l2-subdev-mbus-code-enum; and
    call the <constant>VIDIOC_SUBDEV_ENUM_MBUS_CODE</constant> ioctl with a
    pointer to this structure. Drivers fill the rest of the structure or return
    an &EINVAL; if either the <structfield>pad</structfield> or
    <structfield>index</structfield> are invalid. All media bus formats are
    enumerable by beginning at index zero and incrementing by one until
    <errorcode>EINVAL</errorcode> is returned.</para>

    <para>Available media bus formats may depend on the current 'try' formats
    at other pads of the sub-device, as well as on the current active links. See
    &VIDIOC-SUBDEV-G-FMT; for more information about the try formats.</para>

    <table pgwide="1" frame="none" id="v4l2-subdev-mbus-code-enum">
      <title>struct <structname>v4l2_subdev_mbus_code_enum</structname></title>
      <tgroup cols="3">
	&cs-str;
	<tbody valign="top">
	  <row>
	    <entry>__u32</entry>
	    <entry><structfield>pad</structfield></entry>
	    <entry>Pad number as reported by the media controller API.</entry>
	  </row>
	  <row>
	    <entry>__u32</entry>
	    <entry><structfield>index</structfield></entry>
	    <entry>Number of the format in the enumeration, set by the
	    application.</entry>
	  </row>
	  <row>
	    <entry>__u32</entry>
	    <entry><structfield>code</structfield></entry>
	    <entry>The media bus format code, as defined in
	    <xref linkend="v4l2-mbus-format" />.</entry>
	  </row>
	  <row>
	    <entry>__u32</entry>
	    <entry><structfield>reserved</structfield>[9]</entry>
	    <entry>Reserved for future extensions. Applications and drivers must
	    set the array to zero.</entry>
	  </row>
	</tbody>
      </tgroup>
    </table>
  </refsect1>

  <refsect1>
    &return-value;

    <variablelist>
      <varlistentry>
	<term><errorcode>EINVAL</errorcode></term>
	<listitem>
	  <para>The &v4l2-subdev-mbus-code-enum; <structfield>pad</structfield>
	  references a non-existing pad, or the <structfield>index</structfield>
	  field is out of bounds.</para>
	</listitem>
      </varlistentry>
    </variablelist>
  </refsect1>
</refentry>


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Magecrawl.Utilities
{
    public struct EffectivePoint
    {
        public Point Position;

        // On scale of .01 to 1, lower is less damage.
        public float EffectiveStrength;

        public EffectivePoint(Point p, float str)
        {
            Position = p;
            EffectiveStrength = str;
        }

        // This version is faster since we don't have to calculate targetablePoints over and over again.
        public static bool PositionInTargetablePoints(Point pointOfInterest, List<EffectivePoint> targetablePoints)
        {
            return targetablePoints.Where(t => t.Position == pointOfInterest).Count() > 0;
        }
    }
}